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": "', [ () ->\n return {\n flutter: {\n name: 'Flutter'\n measures: 4,tempo: 120, beats: 4, resoluti",
"end": 77,
"score": 0.9972497820854187,
"start": 70,
"tag": "NAME",
"value": "Flutter"
},
{
"context": " }\n }\n }\n jonny: {\n name:... | src/scripts/services/presets_service.coffee | jakealbaugh/random_commander | 31 | app.service 'Presets', [ () ->
return {
flutter: {
name: 'Flutter'
measures: 4,tempo: 120, beats: 4, resolution: 16, root: 0
clefs: {
treble: {
values: [0,0,0,0,10]
intervals: [10,0,0,10,0,6,0,10,4,0,5,0]
chords: [10,0,0,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 6
waveform: 'triangle'
volume: 6
}
bass: {
values: [10,10,10,10,0]
intervals: [10,10,0,10,0,10,0,10,10,0,10,0]
chords: [10,0,0,0,0]
octaves: [0,10,0]
silence: 0
baseoctave: 3
waveform: 'sawtooth'
volume: 10
}
}
}
jonny: {
name: 'Jonny'
measures: 4,tempo: 100, beats: 5, resolution: 16, root: 6
clefs: {
treble: {
values: [0,0,0,0,10]
intervals: [10,0,5,0,10,0,0,10,0,5,0,10]
chords: [0,10,5,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 6
waveform: 'triangle'
volume: 6
}
bass: {
values: [10,10,0,0,0]
intervals: [10,0,0,0,10,0,0,10,0,0,0,10]
chords: [10,0,0,0,0]
octaves: [0,10,0]
silence: 0
baseoctave: 5
waveform: 'square'
volume: 5
}
}
}
roulette: {
name: 'Roulette', measures: 4, tempo: 150, beats: 4, resolution: 16, root: 1
clefs: {
treble: {
values: [1,1,1,1,1]
intervals: [1,1,1,1,1,1,1,1,1,1,1,1]
chords: [1,1,1,1,1]
octaves: [1,1,1]
silence: 5
baseoctave: 6
waveform: 'triangle'
volume: 6
}
bass: {
values: [1,1,1,1,1]
intervals: [1,1,1,1,1,1,1,1,1,1,1,1]
chords: [1,1,1,1,1]
octaves: [1,1,1]
silence: 5
baseoctave: 5
waveform: 'triangle'
volume: 6
}
}
}
thumper: {
name: 'Thumper'
measures: 16, tempo: 120, beats: 4, resolution: 16, root: 7
clefs: {
treble: {
values: [5,0,10,5,0]
intervals: [10,0,0,5,0,0,0,5,0,0,5,0]
chords: [10,5,5,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 6
waveform: 'sine'
volume: 6
}
bass: {
values: [0,0,0,0,10]
intervals: [10,0,0,10,0,10,0,10,0,0,10,0]
chords: [10,0,0,0,0]
octaves: [0,10,3]
silence: 0
baseoctave: 3
waveform: 'triangle'
volume: 10
}
}
}
wander: {
name: 'Wander'
measures: 4, tempo: 150, beats: 4, resolution: 16, root: 1
clefs: {
treble: {
values: [5,5,5,5,5]
intervals: [10,5,0,5,0,5,0,5,5,0,5,0]
chords: [10,5,5,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 5
waveform: 'triangle'
volume: 6
},
bass: {
values: [10,10,10,10,0]
intervals: [10,5,0,10,0,10,0,10,5,0,10,0]
chords: [10,0,0,0,0]
octaves: [0,10,0]
silence: 0
baseoctave: 3
waveform: 'sine'
volume: 10
}
}
}
flicker: {
name: 'Flicker'
measures: 2, tempo: 160, beats: 7, resolution: 16, root: 6
clefs: {
treble: {
values: [0,0,0,0,10]
intervals: [10,0,0,10,0,6,0,10,4,0,5,0]
chords: [10,0,0,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 6
waveform: 'triangle'
volume: 6
}
bass: {
values: [0,0,10,0,0]
intervals: [10,0,0,10,0,6,0,10,4,0,5,0]
chords: [10,0,0,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 5
waveform: 'triangle'
volume: 7
}
}
}
}
] | 9654 | app.service 'Presets', [ () ->
return {
flutter: {
name: '<NAME>'
measures: 4,tempo: 120, beats: 4, resolution: 16, root: 0
clefs: {
treble: {
values: [0,0,0,0,10]
intervals: [10,0,0,10,0,6,0,10,4,0,5,0]
chords: [10,0,0,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 6
waveform: 'triangle'
volume: 6
}
bass: {
values: [10,10,10,10,0]
intervals: [10,10,0,10,0,10,0,10,10,0,10,0]
chords: [10,0,0,0,0]
octaves: [0,10,0]
silence: 0
baseoctave: 3
waveform: 'sawtooth'
volume: 10
}
}
}
jonny: {
name: '<NAME>'
measures: 4,tempo: 100, beats: 5, resolution: 16, root: 6
clefs: {
treble: {
values: [0,0,0,0,10]
intervals: [10,0,5,0,10,0,0,10,0,5,0,10]
chords: [0,10,5,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 6
waveform: 'triangle'
volume: 6
}
bass: {
values: [10,10,0,0,0]
intervals: [10,0,0,0,10,0,0,10,0,0,0,10]
chords: [10,0,0,0,0]
octaves: [0,10,0]
silence: 0
baseoctave: 5
waveform: 'square'
volume: 5
}
}
}
roulette: {
name: '<NAME>', measures: 4, tempo: 150, beats: 4, resolution: 16, root: 1
clefs: {
treble: {
values: [1,1,1,1,1]
intervals: [1,1,1,1,1,1,1,1,1,1,1,1]
chords: [1,1,1,1,1]
octaves: [1,1,1]
silence: 5
baseoctave: 6
waveform: 'triangle'
volume: 6
}
bass: {
values: [1,1,1,1,1]
intervals: [1,1,1,1,1,1,1,1,1,1,1,1]
chords: [1,1,1,1,1]
octaves: [1,1,1]
silence: 5
baseoctave: 5
waveform: 'triangle'
volume: 6
}
}
}
thumper: {
name: '<NAME>'
measures: 16, tempo: 120, beats: 4, resolution: 16, root: 7
clefs: {
treble: {
values: [5,0,10,5,0]
intervals: [10,0,0,5,0,0,0,5,0,0,5,0]
chords: [10,5,5,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 6
waveform: 'sine'
volume: 6
}
bass: {
values: [0,0,0,0,10]
intervals: [10,0,0,10,0,10,0,10,0,0,10,0]
chords: [10,0,0,0,0]
octaves: [0,10,3]
silence: 0
baseoctave: 3
waveform: 'triangle'
volume: 10
}
}
}
wander: {
name: '<NAME>'
measures: 4, tempo: 150, beats: 4, resolution: 16, root: 1
clefs: {
treble: {
values: [5,5,5,5,5]
intervals: [10,5,0,5,0,5,0,5,5,0,5,0]
chords: [10,5,5,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 5
waveform: 'triangle'
volume: 6
},
bass: {
values: [10,10,10,10,0]
intervals: [10,5,0,10,0,10,0,10,5,0,10,0]
chords: [10,0,0,0,0]
octaves: [0,10,0]
silence: 0
baseoctave: 3
waveform: 'sine'
volume: 10
}
}
}
flicker: {
name: '<NAME>'
measures: 2, tempo: 160, beats: 7, resolution: 16, root: 6
clefs: {
treble: {
values: [0,0,0,0,10]
intervals: [10,0,0,10,0,6,0,10,4,0,5,0]
chords: [10,0,0,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 6
waveform: 'triangle'
volume: 6
}
bass: {
values: [0,0,10,0,0]
intervals: [10,0,0,10,0,6,0,10,4,0,5,0]
chords: [10,0,0,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 5
waveform: 'triangle'
volume: 7
}
}
}
}
] | true | app.service 'Presets', [ () ->
return {
flutter: {
name: 'PI:NAME:<NAME>END_PI'
measures: 4,tempo: 120, beats: 4, resolution: 16, root: 0
clefs: {
treble: {
values: [0,0,0,0,10]
intervals: [10,0,0,10,0,6,0,10,4,0,5,0]
chords: [10,0,0,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 6
waveform: 'triangle'
volume: 6
}
bass: {
values: [10,10,10,10,0]
intervals: [10,10,0,10,0,10,0,10,10,0,10,0]
chords: [10,0,0,0,0]
octaves: [0,10,0]
silence: 0
baseoctave: 3
waveform: 'sawtooth'
volume: 10
}
}
}
jonny: {
name: 'PI:NAME:<NAME>END_PI'
measures: 4,tempo: 100, beats: 5, resolution: 16, root: 6
clefs: {
treble: {
values: [0,0,0,0,10]
intervals: [10,0,5,0,10,0,0,10,0,5,0,10]
chords: [0,10,5,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 6
waveform: 'triangle'
volume: 6
}
bass: {
values: [10,10,0,0,0]
intervals: [10,0,0,0,10,0,0,10,0,0,0,10]
chords: [10,0,0,0,0]
octaves: [0,10,0]
silence: 0
baseoctave: 5
waveform: 'square'
volume: 5
}
}
}
roulette: {
name: 'PI:NAME:<NAME>END_PI', measures: 4, tempo: 150, beats: 4, resolution: 16, root: 1
clefs: {
treble: {
values: [1,1,1,1,1]
intervals: [1,1,1,1,1,1,1,1,1,1,1,1]
chords: [1,1,1,1,1]
octaves: [1,1,1]
silence: 5
baseoctave: 6
waveform: 'triangle'
volume: 6
}
bass: {
values: [1,1,1,1,1]
intervals: [1,1,1,1,1,1,1,1,1,1,1,1]
chords: [1,1,1,1,1]
octaves: [1,1,1]
silence: 5
baseoctave: 5
waveform: 'triangle'
volume: 6
}
}
}
thumper: {
name: 'PI:NAME:<NAME>END_PI'
measures: 16, tempo: 120, beats: 4, resolution: 16, root: 7
clefs: {
treble: {
values: [5,0,10,5,0]
intervals: [10,0,0,5,0,0,0,5,0,0,5,0]
chords: [10,5,5,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 6
waveform: 'sine'
volume: 6
}
bass: {
values: [0,0,0,0,10]
intervals: [10,0,0,10,0,10,0,10,0,0,10,0]
chords: [10,0,0,0,0]
octaves: [0,10,3]
silence: 0
baseoctave: 3
waveform: 'triangle'
volume: 10
}
}
}
wander: {
name: 'PI:NAME:<NAME>END_PI'
measures: 4, tempo: 150, beats: 4, resolution: 16, root: 1
clefs: {
treble: {
values: [5,5,5,5,5]
intervals: [10,5,0,5,0,5,0,5,5,0,5,0]
chords: [10,5,5,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 5
waveform: 'triangle'
volume: 6
},
bass: {
values: [10,10,10,10,0]
intervals: [10,5,0,10,0,10,0,10,5,0,10,0]
chords: [10,0,0,0,0]
octaves: [0,10,0]
silence: 0
baseoctave: 3
waveform: 'sine'
volume: 10
}
}
}
flicker: {
name: 'PI:NAME:<NAME>END_PI'
measures: 2, tempo: 160, beats: 7, resolution: 16, root: 6
clefs: {
treble: {
values: [0,0,0,0,10]
intervals: [10,0,0,10,0,6,0,10,4,0,5,0]
chords: [10,0,0,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 6
waveform: 'triangle'
volume: 6
}
bass: {
values: [0,0,10,0,0]
intervals: [10,0,0,10,0,6,0,10,4,0,5,0]
chords: [10,0,0,0,0]
octaves: [5,10,5]
silence: 0
baseoctave: 5
waveform: 'triangle'
volume: 7
}
}
}
}
] |
[
{
"context": "###\n Pokemon Go(c) MITM node proxy\n by Michael Strassburger <codepoet@cpan.org>\n\n Plays with your displayed ",
"end": 61,
"score": 0.9998825788497925,
"start": 41,
"tag": "NAME",
"value": "Michael Strassburger"
},
{
"context": " Go(c) MITM node proxy\n by Michae... | example.changeLevel.coffee | BuloZB/pokemon-go-mitm-node | 393 | ###
Pokemon Go(c) MITM node proxy
by Michael Strassburger <codepoet@cpan.org>
Plays with your displayed level and XP
Be aware: this is just visible to you and won't gain you any special powers
###
PokemonGoMITM = require './lib/pokemon-go-mitm'
server = new PokemonGoMITM port: 8081
.addResponseHandler "GetInventory", (data) ->
for item in data.inventory_delta.inventory_items
if stats = item.inventory_item_data.player_stats
stats.level = 99
stats.experience = 1337
data | 126938 | ###
Pokemon Go(c) MITM node proxy
by <NAME> <<EMAIL>>
Plays with your displayed level and XP
Be aware: this is just visible to you and won't gain you any special powers
###
PokemonGoMITM = require './lib/pokemon-go-mitm'
server = new PokemonGoMITM port: 8081
.addResponseHandler "GetInventory", (data) ->
for item in data.inventory_delta.inventory_items
if stats = item.inventory_item_data.player_stats
stats.level = 99
stats.experience = 1337
data | true | ###
Pokemon Go(c) MITM node proxy
by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
Plays with your displayed level and XP
Be aware: this is just visible to you and won't gain you any special powers
###
PokemonGoMITM = require './lib/pokemon-go-mitm'
server = new PokemonGoMITM port: 8081
.addResponseHandler "GetInventory", (data) ->
for item in data.inventory_delta.inventory_items
if stats = item.inventory_item_data.player_stats
stats.level = 99
stats.experience = 1337
data |
[
{
"context": "rom User\n\nSet of bot commands\n1. create sonar user test1\n2. delete sonar user test1\n3. create sonar projec",
"end": 942,
"score": 0.9627575874328613,
"start": 937,
"tag": "USERNAME",
"value": "test1"
},
{
"context": "ds\n1. create sonar user test1\n2. delete sonar ... | scripts/sonar/scripts-hipchat/Sonar.coffee | akash1233/OnBot_Demo | 4 | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#-------------------------------------------------------------------------------
###
Coffee script used for:
1. Creation and Deletion of Project/User
2. Grant and Revoke Permissions from User
Set of bot commands
1. create sonar user test1
2. delete sonar user test1
3. create sonar project testproj
4. delete sonar project testproj
5. grant sonar user access for user test1 to project testproj
Environment variables to set:
1. SONAR_URL
2. SONAR_USER_ID
3. SONAR_PASSWORD
4. HUBOT_NAME
###
#Load Dependencies
eindex = require('./index')
request = require('request')
readjson = require ('./readjson.js');
create_project = require('./create_project.js');
delete_project = require('./delete_project.js');
create_user = require('./create_user.js');
delete_user = require('./delete_user.js');
grant_user = require('./grant_user.js');
revoke_user = require('./revoke_user.js');
list_project = require('./list_project.js');
list_user = require('./list_user.js');
generate_id = require('./mongoConnt');
#Required Environment Variables
sonar_url = process.env.SONAR_URL
sonar_user_id = process.env.SONAR_USER_ID
sonar_password = process.env.SONAR_PASSWORD
botname = process.env.HUBOT_NAME
pod_ip = process.env.MY_POD_IP
module.exports = (robot) ->
robot.respond /help/i, (msg) ->
msg.send 'create sonar project <project-id>';
msg.send 'list sonar projects';
msg.send 'list sonar users';
msg.send 'delete sonar user <user-id>';
msg.send 'create sonar user <user-id>';
msg.send 'delete sonar project <project-id>';
msg.send 'grant sonar <permission-name> <userid> <projectid>';
msg.send 'revoke sonar <permission-name> <userid> <projectid>';
msg.send 'getMetrics <projectname>'
robot.respond /create sonar project (.*)/i, (msg) ->
message = msg.match[0]
projectid = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if stdout.sonarcreateproject.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"sonarcreateproject",projectid:projectid}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Create project '+projectid+'\n approve or reject the request'
robot.messageRoom(stdout.sonarcreateproject.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.sonarcreateproject.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
create_project.create_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project created with ID : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Sonar project created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send (stderr)
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonarcreateproject', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approve"
dt='Your request is approved by '+data_http.approver+' for the creation of project';
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
projectid = request.body.projectid;
# Call from create_project file for project creation
create_project.create_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project created with ID : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'create sonar project '+ projectid;
actionmsg = "Sonar project created";
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
# Error and Exception handled
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt="Create sonar project request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to create project.';
robot.respond /list sonar projects/i, (msg) ->
projectid = msg.match[1]
# Call from list_project file to list available project
list_project.list_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout
# Send data to elastic search for logs
setTimeout (->eindex.passData stdout),1000
msg.send stdout;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
robot.respond /list sonar users/i, (msg) ->
projectid = msg.match[1]
# Call from list_user file to list available users
list_user.list_user sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout
# Send data to elastic search for logs
setTimeout (->eindex.passData stdout),1000
msg.send stdout;
# Exception and Error Handled
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
robot.respond /delete sonar user (.*)/i, (msg) ->
message = msg.match[0]
userids = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if stdout.sonardeleteuser.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"sonardeleteuser",userids:userids}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Delete User '+userids+'\n approve or reject the request'
robot.messageRoom(stdout.sonardeleteuser.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.sonardeleteuser.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
delete_user.delete_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User deleted with ID : '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
actionmsg = 'Sonar user deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData stdout),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonardeleteuser', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == "Approve"
dt='Your request is approved by '+data_http.approver+' for the deletion of user'
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
userids = request.body.userids;
# Call from delete_user file to delete user
delete_user.delete_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User deleted with ID : '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'delete sonar user '+ userids;
actionmsg = "Sonar user deleted";
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt="Delete Sonar User request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to delete user.';
robot.respond /create sonar user (.*)/i, (msg) ->
message = msg.match[0]
userids = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.sonarcreateuser.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"sonarcreateuser",userids:userids}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Create user '+userids+'\n approve or reject the request'
robot.messageRoom(stdout.sonarcreateuser.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.sonarcreateuser.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
create_user.create_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User created with ID and password: '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Sonar user created'
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonarcreateuser', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == "Approve"
dt="Create Sonar User request is approved by "+data_http.approver
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
userids = request.body.userids;
# Call from create_user file to create user
create_user.create_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User created with ID and password: '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
message = 'create sonar user '+ userids;
actionmsg = 'Sonar user created';
statusmsg = 'Success';
wallData.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt="Create Sonar User request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to create user.';
robot.respond /delete sonar project (.*)/i, (msg) ->
message = msg.match[0]
projectid = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.sonardeleteproject.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"sonardeleteproject",projectid:projectid}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Delete Project '+projectid+'\n approve or reject the request'
robot.messageRoom(stdout.sonardeleteproject.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.sonardeleteproject.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
delete_project.delete_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project deleted with id : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Sonar project deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonardeleteproject', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == "Approve"
dt="Delete Sonar Project request is approved by "+data_http.approver
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
projectid = request.body.projectid;
# Call from delete_project file for the deletion of project
delete_project.delete_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project deleted with id : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'delete sonar project '+ projectid;
actionmsg = 'Sonar project deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt="Delete Sonar Project request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to delete project.';
robot.respond /grant sonar (.*)$/i, (msg) ->
message = msg.match[0]
split_string = msg.match[1].split " ", 3
perm = split_string[0].trim()
userids = split_string[1].trim()
projid = split_string[2].trim()
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.grantsonar.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"grantsonar",projid:projid,userids:userids,perm:perm}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Grant sonar permission '+perm+"to user "+userids+" for project "+projid+'\n approve or reject the request'
robot.messageRoom(stdout.grantsonar.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.grantsonar.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
grant_user.grant_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Granted permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Permissions granted to sonar user';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/grantsonar', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == "Approve"
dt="Grant Sonar Permissions request is approved by "+data_http.approver
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
projid = request.body.projid;
userids = request.body.userids;
perm = request.body.perm;
# Call from grant_user file to grant permission to the user for particular project
grant_user.grant_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Granted permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'grant sonar '+ perm;
actionmsg = 'Permissions granted to sonar user';
statusmsg = 'Success';
wallData.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt="Grant Sonar Permissions request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to grant permissions.';
robot.respond /revoke sonar (.*)$/i, (msg) ->
message = msg.match[0]
split_string = msg.match[1].split " ", 3
perm = split_string[0].trim()
userids = split_string[1].trim()
projid = split_string[2].trim()
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.revokesonar.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"revokesonar",projid:projid,userids:userids,perm:perm}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Revoke sonar permission '+perm+"to user "+userids+" for project "+projid+'\n approve or reject the request'
robot.messageRoom(stdout.revokesonar.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.revokesonar.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
revoke_user.revoke_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Revoked permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Permissions revoked from sonar user';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/revokesonar', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == "Approve"
dt="Revoke Sonar Permissions request is approved by "+data_http.approver
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
projid = request.body.projid;
userids = request.body.userids;
perm = request.body.perm;
# Call from revoke_user file to revoke permission from the user for particular project
revoke_user.revoke_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Revoked permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'revoke sonar '+ perm;
actionmsg = 'Permissions revoked from sonar user';
statusmsg = 'Success';
wallData.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
#Rejection Handled
else
dt="Revoke Sonar Permissions request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to revoke permissions.';
robot.respond /getMetrics (.*)/i, (msg) ->
project = msg.match[1]
request.get sonar_url+'api/projects', (error, response, body) ->
if error
console.log error
dt = "Error! Please check logs."
msg.send dt
setTimeout (->eindex.passData dt),1000
else
body=JSON.parse(body)
for i in [0... body.length]
if body[i].nm == project
url = sonar_url+'api/measures/component?componentKey='+body[i].k+'&metricKeys=ncloc,sqale_index,duplicated_lines_density,coverage,bugs,code_smells,vulnerabilities'
break
if url == undefined
dt = "Project not found"
msg.send dt
setTimeout (->eindex.passData dt),1000
else
options = {
url: url,
method: 'GET',
auth: {username: sonar_user_id, password: sonar_password}
}
request.get options, (error, response, body) ->
if error
msg.send error
setTimeout (->eindex.passData error),1000
else
dt = ''
body = JSON.parse(body)
if body.errors
for i in [0... body.errors.length]
msg.send body.errors[i].msg
else
for i in [0... body.component.measures.length]
if body.component.measures[i].metric == 'bugs'
dt += '(unknown) '+body.component.measures[i].metric+": "+body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'code_smells'
dt += '(menorah) '+body.component.measures[i].metric+": "+body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'coverage'
dt += '(branch) '+body.component.measures[i].metric+": "+body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'duplicated_lines_density'
dt += '(stash) '+body.component.measures[i].metric+": "+body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'ncloc'
dt += "(continue) Lines of Code: "+body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'sqale_index'
dt += "(goldstar) Technical Debt :" +body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'vulnerabilities'
dt += '(failed) '+body.component.measures[i].metric+": "+body.component.measures[i].value+"\n"
msg.send dt
setTimeout (->eindex.passData dt),1000
| 223160 | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#-------------------------------------------------------------------------------
###
Coffee script used for:
1. Creation and Deletion of Project/User
2. Grant and Revoke Permissions from User
Set of bot commands
1. create sonar user test1
2. delete sonar user test1
3. create sonar project testproj
4. delete sonar project testproj
5. grant sonar user access for user test1 to project testproj
Environment variables to set:
1. SONAR_URL
2. SONAR_USER_ID
3. SONAR_PASSWORD
4. HUBOT_NAME
###
#Load Dependencies
eindex = require('./index')
request = require('request')
readjson = require ('./readjson.js');
create_project = require('./create_project.js');
delete_project = require('./delete_project.js');
create_user = require('./create_user.js');
delete_user = require('./delete_user.js');
grant_user = require('./grant_user.js');
revoke_user = require('./revoke_user.js');
list_project = require('./list_project.js');
list_user = require('./list_user.js');
generate_id = require('./mongoConnt');
#Required Environment Variables
sonar_url = process.env.SONAR_URL
sonar_user_id = process.env.SONAR_USER_ID
sonar_password = process.env.SONAR_PASSWORD
botname = process.env.HUBOT_NAME
pod_ip = process.env.MY_POD_IP
module.exports = (robot) ->
robot.respond /help/i, (msg) ->
msg.send 'create sonar project <project-id>';
msg.send 'list sonar projects';
msg.send 'list sonar users';
msg.send 'delete sonar user <user-id>';
msg.send 'create sonar user <user-id>';
msg.send 'delete sonar project <project-id>';
msg.send 'grant sonar <permission-name> <userid> <projectid>';
msg.send 'revoke sonar <permission-name> <userid> <projectid>';
msg.send 'getMetrics <projectname>'
robot.respond /create sonar project (.*)/i, (msg) ->
message = msg.match[0]
projectid = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if stdout.sonarcreateproject.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"sonarcreateproject",projectid:projectid}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Create project '+projectid+'\n approve or reject the request'
robot.messageRoom(stdout.sonarcreateproject.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.sonarcreateproject.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
create_project.create_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project created with ID : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Sonar project created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send (stderr)
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonarcreateproject', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approve"
dt='Your request is approved by '+data_http.approver+' for the creation of project';
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
projectid = request.body.projectid;
# Call from create_project file for project creation
create_project.create_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project created with ID : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'create sonar project '+ projectid;
actionmsg = "Sonar project created";
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
# Error and Exception handled
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt="Create sonar project request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to create project.';
robot.respond /list sonar projects/i, (msg) ->
projectid = msg.match[1]
# Call from list_project file to list available project
list_project.list_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout
# Send data to elastic search for logs
setTimeout (->eindex.passData stdout),1000
msg.send stdout;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
robot.respond /list sonar users/i, (msg) ->
projectid = msg.match[1]
# Call from list_user file to list available users
list_user.list_user sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout
# Send data to elastic search for logs
setTimeout (->eindex.passData stdout),1000
msg.send stdout;
# Exception and Error Handled
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
robot.respond /delete sonar user (.*)/i, (msg) ->
message = msg.match[0]
userids = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if stdout.sonardeleteuser.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"sonardeleteuser",userids:userids}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Delete User '+userids+'\n approve or reject the request'
robot.messageRoom(stdout.sonardeleteuser.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.sonardeleteuser.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
delete_user.delete_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User deleted with ID : '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
actionmsg = 'Sonar user deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData stdout),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonardeleteuser', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == "Approve"
dt='Your request is approved by '+data_http.approver+' for the deletion of user'
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
userids = request.body.userids;
# Call from delete_user file to delete user
delete_user.delete_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User deleted with ID : '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'delete sonar user '+ userids;
actionmsg = "Sonar user deleted";
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt="Delete Sonar User request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to delete user.';
robot.respond /create sonar user (.*)/i, (msg) ->
message = msg.match[0]
userids = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.sonarcreateuser.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"sonarcreateuser",userids:userids}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Create user '+userids+'\n approve or reject the request'
robot.messageRoom(stdout.sonarcreateuser.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.sonarcreateuser.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
create_user.create_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User created with ID and password: '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Sonar user created'
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonarcreateuser', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == "Approve"
dt="Create Sonar User request is approved by "+data_http.approver
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
userids = request.body.userids;
# Call from create_user file to create user
create_user.create_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User created with ID and password: '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
message = 'create sonar user '+ userids;
actionmsg = 'Sonar user created';
statusmsg = 'Success';
wallData.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt="Create Sonar User request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to create user.';
robot.respond /delete sonar project (.*)/i, (msg) ->
message = msg.match[0]
projectid = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.sonardeleteproject.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"sonardeleteproject",projectid:projectid}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Delete Project '+projectid+'\n approve or reject the request'
robot.messageRoom(stdout.sonardeleteproject.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.sonardeleteproject.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
delete_project.delete_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project deleted with id : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Sonar project deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonardeleteproject', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == "Approve"
dt="Delete Sonar Project request is approved by "+data_http.approver
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
projectid = request.body.projectid;
# Call from delete_project file for the deletion of project
delete_project.delete_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project deleted with id : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'delete sonar project '+ projectid;
actionmsg = 'Sonar project deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt="Delete Sonar Project request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to delete project.';
robot.respond /grant sonar (.*)$/i, (msg) ->
message = msg.match[0]
split_string = msg.match[1].split " ", 3
perm = split_string[0].trim()
userids = split_string[1].trim()
projid = split_string[2].trim()
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.grantsonar.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"grantsonar",projid:projid,userids:userids,perm:perm}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Grant sonar permission '+perm+"to user "+userids+" for project "+projid+'\n approve or reject the request'
robot.messageRoom(stdout.grantsonar.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.grantsonar.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
grant_user.grant_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Granted permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Permissions granted to sonar user';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/grantsonar', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == "Approve"
dt="Grant Sonar Permissions request is approved by "+data_http.approver
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
projid = request.body.projid;
userids = request.body.userids;
perm = request.body.perm;
# Call from grant_user file to grant permission to the user for particular project
grant_user.grant_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Granted permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'grant sonar '+ perm;
actionmsg = 'Permissions granted to sonar user';
statusmsg = 'Success';
wallData.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt="Grant Sonar Permissions request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to grant permissions.';
robot.respond /revoke sonar (.*)$/i, (msg) ->
message = msg.match[0]
split_string = msg.match[1].split " ", 3
perm = split_string[0].trim()
userids = split_string[1].trim()
projid = split_string[2].trim()
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.revokesonar.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"revokesonar",projid:projid,userids:userids,perm:perm}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Revoke sonar permission '+perm+"to user "+userids+" for project "+projid+'\n approve or reject the request'
robot.messageRoom(stdout.revokesonar.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.revokesonar.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
revoke_user.revoke_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Revoked permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Permissions revoked from sonar user';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/revokesonar', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == "Approve"
dt="Revoke Sonar Permissions request is approved by "+data_http.approver
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
projid = request.body.projid;
userids = request.body.userids;
perm = request.body.perm;
# Call from revoke_user file to revoke permission from the user for particular project
revoke_user.revoke_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Revoked permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'revoke sonar '+ perm;
actionmsg = 'Permissions revoked from sonar user';
statusmsg = 'Success';
wallData.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
#Rejection Handled
else
dt="Revoke Sonar Permissions request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to revoke permissions.';
robot.respond /getMetrics (.*)/i, (msg) ->
project = msg.match[1]
request.get sonar_url+'api/projects', (error, response, body) ->
if error
console.log error
dt = "Error! Please check logs."
msg.send dt
setTimeout (->eindex.passData dt),1000
else
body=JSON.parse(body)
for i in [0... body.length]
if body[i].nm == project
url = sonar_url+'api/measures/component?componentKey='+body[i].k+'&metricKeys=<KEY>,sqale_index,duplicated_lines_density,coverage,bugs,code_smells,vulnerabilities'
break
if url == undefined
dt = "Project not found"
msg.send dt
setTimeout (->eindex.passData dt),1000
else
options = {
url: url,
method: 'GET',
auth: {username: sonar_user_id, password: <PASSWORD>}
}
request.get options, (error, response, body) ->
if error
msg.send error
setTimeout (->eindex.passData error),1000
else
dt = ''
body = JSON.parse(body)
if body.errors
for i in [0... body.errors.length]
msg.send body.errors[i].msg
else
for i in [0... body.component.measures.length]
if body.component.measures[i].metric == 'bugs'
dt += '(unknown) '+body.component.measures[i].metric+": "+body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'code_smells'
dt += '(menorah) '+body.component.measures[i].metric+": "+body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'coverage'
dt += '(branch) '+body.component.measures[i].metric+": "+body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'duplicated_lines_density'
dt += '(stash) '+body.component.measures[i].metric+": "+body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'ncloc'
dt += "(continue) Lines of Code: "+body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'sqale_index'
dt += "(goldstar) Technical Debt :" +body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'vulnerabilities'
dt += '(failed) '+body.component.measures[i].metric+": "+body.component.measures[i].value+"\n"
msg.send dt
setTimeout (->eindex.passData dt),1000
| true | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#-------------------------------------------------------------------------------
###
Coffee script used for:
1. Creation and Deletion of Project/User
2. Grant and Revoke Permissions from User
Set of bot commands
1. create sonar user test1
2. delete sonar user test1
3. create sonar project testproj
4. delete sonar project testproj
5. grant sonar user access for user test1 to project testproj
Environment variables to set:
1. SONAR_URL
2. SONAR_USER_ID
3. SONAR_PASSWORD
4. HUBOT_NAME
###
#Load Dependencies
eindex = require('./index')
request = require('request')
readjson = require ('./readjson.js');
create_project = require('./create_project.js');
delete_project = require('./delete_project.js');
create_user = require('./create_user.js');
delete_user = require('./delete_user.js');
grant_user = require('./grant_user.js');
revoke_user = require('./revoke_user.js');
list_project = require('./list_project.js');
list_user = require('./list_user.js');
generate_id = require('./mongoConnt');
#Required Environment Variables
sonar_url = process.env.SONAR_URL
sonar_user_id = process.env.SONAR_USER_ID
sonar_password = process.env.SONAR_PASSWORD
botname = process.env.HUBOT_NAME
pod_ip = process.env.MY_POD_IP
module.exports = (robot) ->
robot.respond /help/i, (msg) ->
msg.send 'create sonar project <project-id>';
msg.send 'list sonar projects';
msg.send 'list sonar users';
msg.send 'delete sonar user <user-id>';
msg.send 'create sonar user <user-id>';
msg.send 'delete sonar project <project-id>';
msg.send 'grant sonar <permission-name> <userid> <projectid>';
msg.send 'revoke sonar <permission-name> <userid> <projectid>';
msg.send 'getMetrics <projectname>'
robot.respond /create sonar project (.*)/i, (msg) ->
message = msg.match[0]
projectid = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if stdout.sonarcreateproject.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"sonarcreateproject",projectid:projectid}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Create project '+projectid+'\n approve or reject the request'
robot.messageRoom(stdout.sonarcreateproject.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.sonarcreateproject.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
create_project.create_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project created with ID : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Sonar project created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send (stderr)
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonarcreateproject', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approve"
dt='Your request is approved by '+data_http.approver+' for the creation of project';
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
projectid = request.body.projectid;
# Call from create_project file for project creation
create_project.create_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project created with ID : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'create sonar project '+ projectid;
actionmsg = "Sonar project created";
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
# Error and Exception handled
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt="Create sonar project request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to create project.';
robot.respond /list sonar projects/i, (msg) ->
projectid = msg.match[1]
# Call from list_project file to list available project
list_project.list_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout
# Send data to elastic search for logs
setTimeout (->eindex.passData stdout),1000
msg.send stdout;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
robot.respond /list sonar users/i, (msg) ->
projectid = msg.match[1]
# Call from list_user file to list available users
list_user.list_user sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout
# Send data to elastic search for logs
setTimeout (->eindex.passData stdout),1000
msg.send stdout;
# Exception and Error Handled
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
robot.respond /delete sonar user (.*)/i, (msg) ->
message = msg.match[0]
userids = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if stdout.sonardeleteuser.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"sonardeleteuser",userids:userids}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Delete User '+userids+'\n approve or reject the request'
robot.messageRoom(stdout.sonardeleteuser.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.sonardeleteuser.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
delete_user.delete_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User deleted with ID : '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
actionmsg = 'Sonar user deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData stdout),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonardeleteuser', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == "Approve"
dt='Your request is approved by '+data_http.approver+' for the deletion of user'
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
userids = request.body.userids;
# Call from delete_user file to delete user
delete_user.delete_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User deleted with ID : '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'delete sonar user '+ userids;
actionmsg = "Sonar user deleted";
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt="Delete Sonar User request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to delete user.';
robot.respond /create sonar user (.*)/i, (msg) ->
message = msg.match[0]
userids = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.sonarcreateuser.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"sonarcreateuser",userids:userids}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Create user '+userids+'\n approve or reject the request'
robot.messageRoom(stdout.sonarcreateuser.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.sonarcreateuser.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
create_user.create_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User created with ID and password: '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Sonar user created'
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonarcreateuser', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == "Approve"
dt="Create Sonar User request is approved by "+data_http.approver
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
userids = request.body.userids;
# Call from create_user file to create user
create_user.create_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User created with ID and password: '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
message = 'create sonar user '+ userids;
actionmsg = 'Sonar user created';
statusmsg = 'Success';
wallData.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt="Create Sonar User request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to create user.';
robot.respond /delete sonar project (.*)/i, (msg) ->
message = msg.match[0]
projectid = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.sonardeleteproject.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"sonardeleteproject",projectid:projectid}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Delete Project '+projectid+'\n approve or reject the request'
robot.messageRoom(stdout.sonardeleteproject.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.sonardeleteproject.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
delete_project.delete_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project deleted with id : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Sonar project deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonardeleteproject', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == "Approve"
dt="Delete Sonar Project request is approved by "+data_http.approver
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
projectid = request.body.projectid;
# Call from delete_project file for the deletion of project
delete_project.delete_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project deleted with id : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'delete sonar project '+ projectid;
actionmsg = 'Sonar project deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt="Delete Sonar Project request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to delete project.';
robot.respond /grant sonar (.*)$/i, (msg) ->
message = msg.match[0]
split_string = msg.match[1].split " ", 3
perm = split_string[0].trim()
userids = split_string[1].trim()
projid = split_string[2].trim()
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.grantsonar.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"grantsonar",projid:projid,userids:userids,perm:perm}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Grant sonar permission '+perm+"to user "+userids+" for project "+projid+'\n approve or reject the request'
robot.messageRoom(stdout.grantsonar.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.grantsonar.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
grant_user.grant_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Granted permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Permissions granted to sonar user';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/grantsonar', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == "Approve"
dt="Grant Sonar Permissions request is approved by "+data_http.approver
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
projid = request.body.projid;
userids = request.body.userids;
perm = request.body.perm;
# Call from grant_user file to grant permission to the user for particular project
grant_user.grant_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Granted permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'grant sonar '+ perm;
actionmsg = 'Permissions granted to sonar user';
statusmsg = 'Success';
wallData.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt="Grant Sonar Permissions request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to grant permissions.';
robot.respond /revoke sonar (.*)$/i, (msg) ->
message = msg.match[0]
split_string = msg.match[1].split " ", 3
perm = split_string[0].trim()
userids = split_string[1].trim()
projid = split_string[2].trim()
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.revokesonar.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"revokesonar",projid:projid,userids:userids,perm:perm}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Revoke sonar permission '+perm+"to user "+userids+" for project "+projid+'\n approve or reject the request'
robot.messageRoom(stdout.revokesonar.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.revokesonar.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
revoke_user.revoke_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Revoked permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Permissions revoked from sonar user';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/revokesonar', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == "Approve"
dt="Revoke Sonar Permissions request is approved by "+data_http.approver
# Approved Message send to the user chat room
robot.messageRoom data_http.userid, dt;
projid = request.body.projid;
userids = request.body.userids;
perm = request.body.perm;
# Call from revoke_user file to revoke permission from the user for particular project
revoke_user.revoke_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Revoked permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'revoke sonar '+ perm;
actionmsg = 'Permissions revoked from sonar user';
statusmsg = 'Success';
wallData.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
#Rejection Handled
else
dt="Revoke Sonar Permissions request was rejected by "+data_http.approver
setTimeout (->eindex.passData dt),1000
# Rejected Message send to the user chat room
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to revoke permissions.';
robot.respond /getMetrics (.*)/i, (msg) ->
project = msg.match[1]
request.get sonar_url+'api/projects', (error, response, body) ->
if error
console.log error
dt = "Error! Please check logs."
msg.send dt
setTimeout (->eindex.passData dt),1000
else
body=JSON.parse(body)
for i in [0... body.length]
if body[i].nm == project
url = sonar_url+'api/measures/component?componentKey='+body[i].k+'&metricKeys=PI:KEY:<KEY>END_PI,sqale_index,duplicated_lines_density,coverage,bugs,code_smells,vulnerabilities'
break
if url == undefined
dt = "Project not found"
msg.send dt
setTimeout (->eindex.passData dt),1000
else
options = {
url: url,
method: 'GET',
auth: {username: sonar_user_id, password: PI:PASSWORD:<PASSWORD>END_PI}
}
request.get options, (error, response, body) ->
if error
msg.send error
setTimeout (->eindex.passData error),1000
else
dt = ''
body = JSON.parse(body)
if body.errors
for i in [0... body.errors.length]
msg.send body.errors[i].msg
else
for i in [0... body.component.measures.length]
if body.component.measures[i].metric == 'bugs'
dt += '(unknown) '+body.component.measures[i].metric+": "+body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'code_smells'
dt += '(menorah) '+body.component.measures[i].metric+": "+body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'coverage'
dt += '(branch) '+body.component.measures[i].metric+": "+body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'duplicated_lines_density'
dt += '(stash) '+body.component.measures[i].metric+": "+body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'ncloc'
dt += "(continue) Lines of Code: "+body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'sqale_index'
dt += "(goldstar) Technical Debt :" +body.component.measures[i].value+"\n"
else if body.component.measures[i].metric == 'vulnerabilities'
dt += '(failed) '+body.component.measures[i].metric+": "+body.component.measures[i].value+"\n"
msg.send dt
setTimeout (->eindex.passData dt),1000
|
[
{
"context": "### (c) 2013 Maxim Litvinov ###\n\niw = 8\nih = 8\nCOLORS = 7\nDEG = Math.PI/180\n\n",
"end": 27,
"score": 0.9997703433036804,
"start": 13,
"tag": "NAME",
"value": "Maxim Litvinov"
}
] | 7/match3.coffee | metalim/21 | 0 | ### (c) 2013 Maxim Litvinov ###
iw = 8
ih = 8
COLORS = 7
DEG = Math.PI/180
styles = [
'blue'
'magenta'
'red'
'orange'
'yellow'
'green'
'white'
]
disabled = (e)->
e.preventDefault()
trace = (e)->
#console.log e.type,e
class Game
constructor:->
@canvas = document.getElementById 'canvas'
@ctx = @canvas.getContext '2d'
@ctx.translate 0.5,0.5
@audio = {}
(@audio[name] = new Audio 'audio/'+name+'.wav') for name in ['hit','coin','fill']
@reset()
@canvas.onmousemove = (e)=>@move e
@canvas.onmousedown = (e)=>@mousedown e
@canvas.onmouseup = (e)=>@mouseup e
@canvas.onclick = trace
window.onresize = (e)=>@resize e
document.ontouchstart = disabled
document.ontouchmove = disabled
document.onmousewheel = disabled
reset:->
@playing = true
@won = false
@state = []
@state = (Math.random()*COLORS|0 for y in [0...ih] for x in [0...iw])
@resize()
@tryRemove()
resize:->
# iOS7 bug: 100% = outerHeight, not innerHeight
$('html').height window.innerHeight
window.scrollTo 0,0
w = $('div').get(0).offsetWidth
h = $('div').get(0).offsetHeight
console.log w,h
#$(document.body).prepend h
@u = Math.min(w/iw, h/ih)&~1
@canvas.width = @w = (@u*iw)|0
@canvas.height = @h = (@u*ih)|0
@offset = $(@canvas).offset()
console.log @w,@h,@u
@draw()
userActive:->
if not musicPlaying
musicPlaying = true
audio = $("audio").get(0);
if audio.duration is 0
audio.load()
audio.play()
getPos: (e)->
x: Math.floor((e.clientX - @offset.left)/@u)|0
y: ih - Math.ceil((e.clientY - @offset.top)/@u)|0
checkMoves:->
state = (c for c in col for col in @state)
#horz swap
for x in [0...iw-1]
for y in [0...ih]
@swap state,x,y,x+1,y
if @canRemove state
return true
@swap state,x,y,x+1,y
#vert swap
for x in [0...iw]
for y in [0...ih-1]
@swap state,x,y,x,y+1
if @canRemove state
return true
@swap state,x,y,x,y+1
canRemove:(state)->
# horz
for x in [0...iw-2]
for y in [0...ih]
c = state[x][y]
same = 1
for dx in [x+1...iw]
if state[dx][y] is c
same += 1
else
break
if same>=3
return true
#vert
for x in [0...iw]
for y in [0...ih-2]
c = state[x][y]
same = 1
for dy in [y+1...ih]
if state[x][dy] is c
same += 1
else
break
if same>=3
return true
false
tryRemove:->
removing = {}
# horz
for x in [0...iw-2]
for y in [0...ih]
c = @state[x][y]
same = 1
for dx in [x+1...iw]
if @state[dx][y] is c
same += 1
else
break
if same>=3
console.log x,y,'horz',same
for dx in [x...x+same]
removing[dx+'x'+y] = {x:dx,y:y}
#vert
for x in [0...iw]
for y in [0...ih-2]
c = @state[x][y]
same = 1
for dy in [y+1...ih]
if @state[x][dy] is c
same += 1
else
break
if same>=3
console.log x,y,'vert',same
for dy in [y...y+same]
removing[x+'x'+dy] = {x:x,y:dy}
removed = 0
for i of removing
c = removing[i]
console.log 'deleting',c.x,c.y
delete @state[c.x][c.y]
removed += 1
console.log removed
if removed
@audio.coin.play()
if not @removing
@removing = setTimeout =>
@removing = null
@fillNew()
,500
@draw()
removed>0
fillNew:->
for x of @state
@state[x] = (c for c in @state[x] when c?)
for x of @state
while @state[x].length<ih
@state[x].push Math.random()*COLORS|0
@audio.fill.play()
@draw()
if not @checkMoves()
@gameover()
setTimeout =>
@tryRemove()
,500
swap:(state,x1,y1,x2,y2)->
c = state[x1][y1]
state[x1][y1] = state[x2][y2]
state[x2][y2] = c
trySwap:(x1,y1,x2,y2)->
@swap @state,x1,y1,x2,y2
if not @tryRemove()
@audio.hit.play()
@swap @state,x1,y1,x2,y2
mousedown:(e)->
@userActive()
if @playing
@start = @getPos e
mouseup:(e)->
if not @playing
@reset()
return
end = @getPos e
dx = end.x-@start.x
dy = end.y-@start.y
if dx is 0 and dy is 0
return
if Math.abs(dx)>Math.abs(dy)
#horizontal
@trySwap @start.x, @start.y, @start.x + (if dx>0 then 1 else -1), @start.y
else
#vertical
@trySwap @start.x, @start.y, @start.x, @start.y + (if dy>0 then 1 else -1)
move:(e)->
if not @playing
return
p = @getPos e
if p.x in [0...iw] and p.y in [0...ih]
@selected = p
else
@selected = null
@draw()
gameover:->
@playing=false
win:->
@playing=false
@won=true
draw:->
@ctx.clearRect 0,0,@w,@h
@ctx.strokeStyle = 'grey'
@ctx.lineWidth = 1
@ctx.strokeRect 0,0,iw*@u,ih*@u
for col,x in @state
for cell,y in col when cell?
@ctx.fillStyle = styles[cell]
@ctx.beginPath()
@ctx.moveTo @u*(x+0.5),@u*(ih-y-0.95)
for i in [1...cell+3]
angle = Math.PI*2*i/(cell+3)
dx = 0.45*Math.sin angle
dy = -0.45*Math.cos angle
@ctx.lineTo @u*(x+0.5+dx),@u*(ih-y-0.5+dy)
@ctx.closePath()
if @selected? and @selected.x is x and @selected.y is y
@ctx.globalAlpha = 0.6
else
@ctx.globalAlpha = 0.8
@ctx.fill()
@ctx.globalAlpha = 1
@ctx.strokeStyle = 'gray'
@ctx.lineWidth = 1
@ctx.stroke()
if not @playing
@ctx.font = 'bold '+(@u*ih*0.1)+'px sans-serif'
@ctx.lineWidth = 2
@ctx.textAlign = 'center'
@ctx.textBaseline = 'middle'
if @won
@ctx.strokeStyle = 'yellow'
@ctx.fillStyle = 'green'
@ctx.fillText 'YOU WIN!',@w/2,@h/2
@ctx.strokeText 'YOU WIN!',@w/2,@h/2
else
@ctx.strokeStyle = 'darkred'
@ctx.fillStyle = 'red'
@ctx.fillText 'GAME OVER',@w/2,@h/2
@ctx.strokeText 'GAME OVER',@w/2,@h/2
$ ->
new Game()
| 216840 | ### (c) 2013 <NAME> ###
iw = 8
ih = 8
COLORS = 7
DEG = Math.PI/180
styles = [
'blue'
'magenta'
'red'
'orange'
'yellow'
'green'
'white'
]
disabled = (e)->
e.preventDefault()
trace = (e)->
#console.log e.type,e
class Game
constructor:->
@canvas = document.getElementById 'canvas'
@ctx = @canvas.getContext '2d'
@ctx.translate 0.5,0.5
@audio = {}
(@audio[name] = new Audio 'audio/'+name+'.wav') for name in ['hit','coin','fill']
@reset()
@canvas.onmousemove = (e)=>@move e
@canvas.onmousedown = (e)=>@mousedown e
@canvas.onmouseup = (e)=>@mouseup e
@canvas.onclick = trace
window.onresize = (e)=>@resize e
document.ontouchstart = disabled
document.ontouchmove = disabled
document.onmousewheel = disabled
reset:->
@playing = true
@won = false
@state = []
@state = (Math.random()*COLORS|0 for y in [0...ih] for x in [0...iw])
@resize()
@tryRemove()
resize:->
# iOS7 bug: 100% = outerHeight, not innerHeight
$('html').height window.innerHeight
window.scrollTo 0,0
w = $('div').get(0).offsetWidth
h = $('div').get(0).offsetHeight
console.log w,h
#$(document.body).prepend h
@u = Math.min(w/iw, h/ih)&~1
@canvas.width = @w = (@u*iw)|0
@canvas.height = @h = (@u*ih)|0
@offset = $(@canvas).offset()
console.log @w,@h,@u
@draw()
userActive:->
if not musicPlaying
musicPlaying = true
audio = $("audio").get(0);
if audio.duration is 0
audio.load()
audio.play()
getPos: (e)->
x: Math.floor((e.clientX - @offset.left)/@u)|0
y: ih - Math.ceil((e.clientY - @offset.top)/@u)|0
checkMoves:->
state = (c for c in col for col in @state)
#horz swap
for x in [0...iw-1]
for y in [0...ih]
@swap state,x,y,x+1,y
if @canRemove state
return true
@swap state,x,y,x+1,y
#vert swap
for x in [0...iw]
for y in [0...ih-1]
@swap state,x,y,x,y+1
if @canRemove state
return true
@swap state,x,y,x,y+1
canRemove:(state)->
# horz
for x in [0...iw-2]
for y in [0...ih]
c = state[x][y]
same = 1
for dx in [x+1...iw]
if state[dx][y] is c
same += 1
else
break
if same>=3
return true
#vert
for x in [0...iw]
for y in [0...ih-2]
c = state[x][y]
same = 1
for dy in [y+1...ih]
if state[x][dy] is c
same += 1
else
break
if same>=3
return true
false
tryRemove:->
removing = {}
# horz
for x in [0...iw-2]
for y in [0...ih]
c = @state[x][y]
same = 1
for dx in [x+1...iw]
if @state[dx][y] is c
same += 1
else
break
if same>=3
console.log x,y,'horz',same
for dx in [x...x+same]
removing[dx+'x'+y] = {x:dx,y:y}
#vert
for x in [0...iw]
for y in [0...ih-2]
c = @state[x][y]
same = 1
for dy in [y+1...ih]
if @state[x][dy] is c
same += 1
else
break
if same>=3
console.log x,y,'vert',same
for dy in [y...y+same]
removing[x+'x'+dy] = {x:x,y:dy}
removed = 0
for i of removing
c = removing[i]
console.log 'deleting',c.x,c.y
delete @state[c.x][c.y]
removed += 1
console.log removed
if removed
@audio.coin.play()
if not @removing
@removing = setTimeout =>
@removing = null
@fillNew()
,500
@draw()
removed>0
fillNew:->
for x of @state
@state[x] = (c for c in @state[x] when c?)
for x of @state
while @state[x].length<ih
@state[x].push Math.random()*COLORS|0
@audio.fill.play()
@draw()
if not @checkMoves()
@gameover()
setTimeout =>
@tryRemove()
,500
swap:(state,x1,y1,x2,y2)->
c = state[x1][y1]
state[x1][y1] = state[x2][y2]
state[x2][y2] = c
trySwap:(x1,y1,x2,y2)->
@swap @state,x1,y1,x2,y2
if not @tryRemove()
@audio.hit.play()
@swap @state,x1,y1,x2,y2
mousedown:(e)->
@userActive()
if @playing
@start = @getPos e
mouseup:(e)->
if not @playing
@reset()
return
end = @getPos e
dx = end.x-@start.x
dy = end.y-@start.y
if dx is 0 and dy is 0
return
if Math.abs(dx)>Math.abs(dy)
#horizontal
@trySwap @start.x, @start.y, @start.x + (if dx>0 then 1 else -1), @start.y
else
#vertical
@trySwap @start.x, @start.y, @start.x, @start.y + (if dy>0 then 1 else -1)
move:(e)->
if not @playing
return
p = @getPos e
if p.x in [0...iw] and p.y in [0...ih]
@selected = p
else
@selected = null
@draw()
gameover:->
@playing=false
win:->
@playing=false
@won=true
draw:->
@ctx.clearRect 0,0,@w,@h
@ctx.strokeStyle = 'grey'
@ctx.lineWidth = 1
@ctx.strokeRect 0,0,iw*@u,ih*@u
for col,x in @state
for cell,y in col when cell?
@ctx.fillStyle = styles[cell]
@ctx.beginPath()
@ctx.moveTo @u*(x+0.5),@u*(ih-y-0.95)
for i in [1...cell+3]
angle = Math.PI*2*i/(cell+3)
dx = 0.45*Math.sin angle
dy = -0.45*Math.cos angle
@ctx.lineTo @u*(x+0.5+dx),@u*(ih-y-0.5+dy)
@ctx.closePath()
if @selected? and @selected.x is x and @selected.y is y
@ctx.globalAlpha = 0.6
else
@ctx.globalAlpha = 0.8
@ctx.fill()
@ctx.globalAlpha = 1
@ctx.strokeStyle = 'gray'
@ctx.lineWidth = 1
@ctx.stroke()
if not @playing
@ctx.font = 'bold '+(@u*ih*0.1)+'px sans-serif'
@ctx.lineWidth = 2
@ctx.textAlign = 'center'
@ctx.textBaseline = 'middle'
if @won
@ctx.strokeStyle = 'yellow'
@ctx.fillStyle = 'green'
@ctx.fillText 'YOU WIN!',@w/2,@h/2
@ctx.strokeText 'YOU WIN!',@w/2,@h/2
else
@ctx.strokeStyle = 'darkred'
@ctx.fillStyle = 'red'
@ctx.fillText 'GAME OVER',@w/2,@h/2
@ctx.strokeText 'GAME OVER',@w/2,@h/2
$ ->
new Game()
| true | ### (c) 2013 PI:NAME:<NAME>END_PI ###
iw = 8
ih = 8
COLORS = 7
DEG = Math.PI/180
styles = [
'blue'
'magenta'
'red'
'orange'
'yellow'
'green'
'white'
]
disabled = (e)->
e.preventDefault()
trace = (e)->
#console.log e.type,e
class Game
constructor:->
@canvas = document.getElementById 'canvas'
@ctx = @canvas.getContext '2d'
@ctx.translate 0.5,0.5
@audio = {}
(@audio[name] = new Audio 'audio/'+name+'.wav') for name in ['hit','coin','fill']
@reset()
@canvas.onmousemove = (e)=>@move e
@canvas.onmousedown = (e)=>@mousedown e
@canvas.onmouseup = (e)=>@mouseup e
@canvas.onclick = trace
window.onresize = (e)=>@resize e
document.ontouchstart = disabled
document.ontouchmove = disabled
document.onmousewheel = disabled
reset:->
@playing = true
@won = false
@state = []
@state = (Math.random()*COLORS|0 for y in [0...ih] for x in [0...iw])
@resize()
@tryRemove()
resize:->
# iOS7 bug: 100% = outerHeight, not innerHeight
$('html').height window.innerHeight
window.scrollTo 0,0
w = $('div').get(0).offsetWidth
h = $('div').get(0).offsetHeight
console.log w,h
#$(document.body).prepend h
@u = Math.min(w/iw, h/ih)&~1
@canvas.width = @w = (@u*iw)|0
@canvas.height = @h = (@u*ih)|0
@offset = $(@canvas).offset()
console.log @w,@h,@u
@draw()
userActive:->
if not musicPlaying
musicPlaying = true
audio = $("audio").get(0);
if audio.duration is 0
audio.load()
audio.play()
getPos: (e)->
x: Math.floor((e.clientX - @offset.left)/@u)|0
y: ih - Math.ceil((e.clientY - @offset.top)/@u)|0
checkMoves:->
state = (c for c in col for col in @state)
#horz swap
for x in [0...iw-1]
for y in [0...ih]
@swap state,x,y,x+1,y
if @canRemove state
return true
@swap state,x,y,x+1,y
#vert swap
for x in [0...iw]
for y in [0...ih-1]
@swap state,x,y,x,y+1
if @canRemove state
return true
@swap state,x,y,x,y+1
canRemove:(state)->
# horz
for x in [0...iw-2]
for y in [0...ih]
c = state[x][y]
same = 1
for dx in [x+1...iw]
if state[dx][y] is c
same += 1
else
break
if same>=3
return true
#vert
for x in [0...iw]
for y in [0...ih-2]
c = state[x][y]
same = 1
for dy in [y+1...ih]
if state[x][dy] is c
same += 1
else
break
if same>=3
return true
false
tryRemove:->
removing = {}
# horz
for x in [0...iw-2]
for y in [0...ih]
c = @state[x][y]
same = 1
for dx in [x+1...iw]
if @state[dx][y] is c
same += 1
else
break
if same>=3
console.log x,y,'horz',same
for dx in [x...x+same]
removing[dx+'x'+y] = {x:dx,y:y}
#vert
for x in [0...iw]
for y in [0...ih-2]
c = @state[x][y]
same = 1
for dy in [y+1...ih]
if @state[x][dy] is c
same += 1
else
break
if same>=3
console.log x,y,'vert',same
for dy in [y...y+same]
removing[x+'x'+dy] = {x:x,y:dy}
removed = 0
for i of removing
c = removing[i]
console.log 'deleting',c.x,c.y
delete @state[c.x][c.y]
removed += 1
console.log removed
if removed
@audio.coin.play()
if not @removing
@removing = setTimeout =>
@removing = null
@fillNew()
,500
@draw()
removed>0
fillNew:->
for x of @state
@state[x] = (c for c in @state[x] when c?)
for x of @state
while @state[x].length<ih
@state[x].push Math.random()*COLORS|0
@audio.fill.play()
@draw()
if not @checkMoves()
@gameover()
setTimeout =>
@tryRemove()
,500
swap:(state,x1,y1,x2,y2)->
c = state[x1][y1]
state[x1][y1] = state[x2][y2]
state[x2][y2] = c
trySwap:(x1,y1,x2,y2)->
@swap @state,x1,y1,x2,y2
if not @tryRemove()
@audio.hit.play()
@swap @state,x1,y1,x2,y2
mousedown:(e)->
@userActive()
if @playing
@start = @getPos e
mouseup:(e)->
if not @playing
@reset()
return
end = @getPos e
dx = end.x-@start.x
dy = end.y-@start.y
if dx is 0 and dy is 0
return
if Math.abs(dx)>Math.abs(dy)
#horizontal
@trySwap @start.x, @start.y, @start.x + (if dx>0 then 1 else -1), @start.y
else
#vertical
@trySwap @start.x, @start.y, @start.x, @start.y + (if dy>0 then 1 else -1)
move:(e)->
if not @playing
return
p = @getPos e
if p.x in [0...iw] and p.y in [0...ih]
@selected = p
else
@selected = null
@draw()
gameover:->
@playing=false
win:->
@playing=false
@won=true
draw:->
@ctx.clearRect 0,0,@w,@h
@ctx.strokeStyle = 'grey'
@ctx.lineWidth = 1
@ctx.strokeRect 0,0,iw*@u,ih*@u
for col,x in @state
for cell,y in col when cell?
@ctx.fillStyle = styles[cell]
@ctx.beginPath()
@ctx.moveTo @u*(x+0.5),@u*(ih-y-0.95)
for i in [1...cell+3]
angle = Math.PI*2*i/(cell+3)
dx = 0.45*Math.sin angle
dy = -0.45*Math.cos angle
@ctx.lineTo @u*(x+0.5+dx),@u*(ih-y-0.5+dy)
@ctx.closePath()
if @selected? and @selected.x is x and @selected.y is y
@ctx.globalAlpha = 0.6
else
@ctx.globalAlpha = 0.8
@ctx.fill()
@ctx.globalAlpha = 1
@ctx.strokeStyle = 'gray'
@ctx.lineWidth = 1
@ctx.stroke()
if not @playing
@ctx.font = 'bold '+(@u*ih*0.1)+'px sans-serif'
@ctx.lineWidth = 2
@ctx.textAlign = 'center'
@ctx.textBaseline = 'middle'
if @won
@ctx.strokeStyle = 'yellow'
@ctx.fillStyle = 'green'
@ctx.fillText 'YOU WIN!',@w/2,@h/2
@ctx.strokeText 'YOU WIN!',@w/2,@h/2
else
@ctx.strokeStyle = 'darkred'
@ctx.fillStyle = 'red'
@ctx.fillText 'GAME OVER',@w/2,@h/2
@ctx.strokeText 'GAME OVER',@w/2,@h/2
$ ->
new Game()
|
[
{
"context": ".fillForm '#username': self.username, '#password': self.password\n else # login with a Windows Live acc",
"end": 6133,
"score": 0.9364743232727051,
"start": 6120,
"tag": "PASSWORD",
"value": "self.password"
},
{
"context": " the robot\n return if userID... | src/skypeweb.coffee | Suuperbot/hubot-skype-web | 51 | phantom = require 'phantom'
request = require 'request'
util = require 'util'
escape = require 'escape-html'
fs = require 'fs'
path = require 'path'
URL = require 'url-parse'
PageHelper = require './page_helper'
{Adapter, TextMessage, User} = require 'hubot'
class SkypeWebAdapter extends Adapter
# @param robot [Robot] the instance of hubot that uses the adapter
constructor: (@robot) ->
super @robot
@getPollUrl = -> "#{@url}/v1/users/ME/endpoints/SELF/subscriptions/0/poll"
@getSendUrl = (user) -> "#{@url}/v1/users/ME/conversations/#{user}/messages"
@sendBody = messagetype: 'RichText', contenttype: 'text', content: ''
@sendQueues = {}
@headers = false
@eventsCache = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
@respondPattern = @robot.respondPattern /.*/
# Read and validate username
@username = process.env.HUBOT_SKYPE_USERNAME
if not @username or @username.length < 2
throw new Error 'Provide a valid username in HUBOT_SKYPE_USERNAME!'
# Read and validate password
@password = process.env.HUBOT_SKYPE_PASSWORD
if not @password or @password.length < 2
throw new Error 'Provide a valid password in HUBOT_SKYPE_PASSWORD!'
# Read and validate reconnect interval
@reconnectInterval = 240
if process.env.HUBOT_SKYPE_RECONNECT
@reconnectInterval = parseInt process.env.HUBOT_SKYPE_RECONNECT
if @reconnectInterval < 20
@robot.logger.warning 'HUBOT_SKYPE_RECONNECT is the adapter ' +
'reconnect interval in minutes! (optional parameter)'
throw new Error 'Minimum reconnect interval is 20 minutes!'
# Read and validate max message length
@maxLength = 1500
if process.env.HUBOT_SKYPE_MAX_MESSAGE_LENGTH
@maxLength = parseInt process.env.HUBOT_SKYPE_MAX_MESSAGE_LENGTH
@robot.logger.info('Set max message length to ' + @maxLength)
unless 30 <= @maxLength and @maxLength <= 100000
throw new Error 'HUBOT_SKYPE_MAX_MESSAGE_LENGTH must be ' +
'between 30 and 100000'
# Starts the adapter
#
run: ->
self = @
success = ->
self.emit 'connected'
self.pollRequest()
if self.reconnectInterval
setInterval (-> self.login()), self.reconnectInterval * 60 * 1000
self.robot.logger.info "SkypeWeb adapter configured to reconnect " +
"every #{self.reconnectInterval} minutes"
error = ->
throw new Error 'SkypeWeb adapter failure in initial login!'
backup = false
try backup = JSON.parse fs.readFileSync 'hubot-skype-web.backup', 'utf8'
if backup and new Date(backup.expire) > new Date()
self.robot.logger.info 'Skype headers restored from backup.'
self.headers = backup.headers
self.url = backup.url
self.pollUrl = self.getPollUrl()
success()
setTimeout (-> self.login()), 5000
else
@login success: success, error: error
# Entry point for messages from hubot
#
send: (envelope, strings...) ->
@sendInQueue envelope.room, msg for msg in strings
# Replies back to a specific user.
#
# @note it prefixes messages only in group chats
#
reply: (envelope, strings...) ->
# Only prefix replies in group chats
if envelope.user.room.indexOf('19:') is 0
@robot.logger.debug 'reply: adding receiver prefix to all strings'
strings = strings.map (s) -> "#{envelope.user.nickname ||
envelope.user.name}: #{s}"
else
@robot.logger.debug 'reply: replying in personal ' +
'chat ' + envelope.user.room
@send envelope, strings...
# @private
# Login to Skype web client and retrieve a sample poll request.
#
# @note Uses PhantomJS to render the web page and monitor network traffic
#
# @option options [Function] success executed if the correct requests are found
# @option options [Function] error executed if the time exceeds the limit
#
login: (options = {}) ->
self = @
phantomOptions = parameters: 'web-security': false
if process.platform.indexOf('win') isnt -1
# Disable dnode with weak on Windows hosts
phantomOptions.dnodeOpts = weak: false
phantom.create ((ph) ->
ph.createPage (page) ->
# Execute fail condition if login time limit expires
errorTimer = setTimeout (->
self.robot.logger.error 'Timeout in waiting for login success!'
page.render 'login-failure.png', ->
self.robot.logger.error "Screenshot saved at: " +
process.cwd() + path.sep + 'login-failure.png'
page.close()
ph.exit 0
options?.error?()
), 50000 # after 50 secs
# Monitor outgoing requests until proper poll request appears
requestsCount = 0
success = false
page.set 'onResourceRequested', (request) ->
if request.method is 'POST'
for header in request.headers
if header.name is 'RegistrationToken'
return if requestsCount++ < 1 or success
page.close()
ph.exit 0
# Clear timer for error condition
clearTimeout errorTimer
self.robot.logger.info 'SkypeWeb adapter logged in successfully!'
self.robot.logger.debug 'Captured poll request: \n' +
util.inspect request
self.copyRequest request
success = true
options?.success?()
else
self.robot.logger.debug 'Skype during login: ' + request.url
# Use generic user-agent
page.set 'settings.userAgent',
'Mozilla (Windows NT) AppleWebKit KHTML, like Gecko) Chrome'
# Login to skype web
page.open 'https://web.skype.com', (status) ->
helper = new PageHelper page
helper.wait '#username', ->
if self.username.indexOf('@') is -1
helper.fillForm '#username': self.username, '#password': self.password
else # login with a Windows Live account
# Submit username to trigger redirect
helper.fillForm '#username': self.username
# Wait a redirect to Windows Live login page
helper.wait 'input[type="submit"]', ->
helper.fillForm 'input[type="password"]': self.password
), phantomOptions
# @private
# Stores details of the intercepted request for later use.
#
# @note Most importantly it obtains the RegistrationToken which is used
# to authenticate the requests for receiving or sending messages
#
# @param request [Request] the poll request made from skype web client
#
copyRequest: (request) ->
# Copy base URL from poll request
requestUrl = new URL request.url
@url = requestUrl.protocol + '//' + requestUrl.host
@pollUrl = @getPollUrl()
# Copy poll request headers into a map
@headers = {}
for header in request.headers
@headers[header.name] = header.value
# Clear Content-Length as we won't bother setting correct value
delete @headers['Content-Length']
@headers['Host'] = 'client-s.gateway.messenger.live.com'
@headers['Connection'] = 'keep-alive'
@headers['Accept-Encoding'] = 'gzip, deflate'
@headers['X-SkypeToken'] = @headers['RegistrationToken'].split("=")[1]
# Backup request details to disk for re-use after reboot
backup = JSON.stringify
url: @url
expire: new Date(new Date().getTime() + @reconnectInterval * 60 * 1000)
headers: @headers
self = @
fs.writeFile 'hubot-skype-web.backup', backup, (err) ->
if err
self.robot.logger.error 'IO error while storing ' +
'Skype headers to disc:' + err
else
self.robot.logger.debug 'Skype headers stored to disk successfully'
# @private
# Handles all Skype events coming from the server
#
# @param msg [EventMessage] the event object
#
onEventMessage: (msg) ->
if (msg.resourceType is 'NewMessage' and
msg.resource?.messagetype in ['Text', 'RichText'])
# Make sure we don't process same pessage more than once
# (Happens when you switch RegistrationToken-s)
return if msg.resource.id in @eventsCache
@eventsCache.shift()
@eventsCache.push msg.resource.id
userID = msg.resource.from.split('/contacts/')[1].replace '8:', ''
# Ignore messages sent by the robot
return if userID.toLowerCase() is @username.toLowerCase()
user = @robot.brain.userForId userID
user.room = msg.resource.conversationLink.split('/conversations/')[1]
# Let robot know messages in personal chats are directed at him
if user.room.indexOf('19:') isnt 0
unless user.shell? and user.shell[user.room]
# Only prefix messages that aren't already prefixed by sender
unless @respondPattern.test msg.resource.content
@robot.logger.debug 'Prefix personal message from ' + user.name
msg.resource.content = @robot.name + ': ' + msg.resource.content
# Provide the messages to the robot
@receive new TextMessage user, msg.resource.content, msg.resource.id
# @private
# Store Skype message to be send in queues
#
# @note This prevents newer messages from being received prior
# to older ones due to the async nature of the requests being made
#
# @param user [String] the recipient of the message
# @param msg [String] the contents of the message to be send
#
sendInQueue: (user, msg) ->
@sendQueues[user] ||= []
queue = @sendQueues[user]
# Split messages that can't be sent at once
if msg.length > @maxLength
@robot.logger.warning 'Message too long for sending! Splitting...'
index = msg.substring(0, @maxLength).lastIndexOf("\n")
index = @maxLength if index is -1
@sendInQueue user, msg.substring 0, index
@sendInQueue user, msg.substring index + 1
return
queue.push msg
len = queue.length
return @sendRequest user, msg if len is 1
# Optimize queue by truncating next messages
if len > 2 and queue[len-1].length + queue[len-2].length < @maxLength
queue[len-2] += "\n" + queue.pop()
# @private
# Sends POST request to Skype containing new message to given user
#
# @note it recursively calls itself until queues are empty
#
# @param user [String] the recipient of the message
# @param msg [String] the contents of the message to be send
#
sendRequest: (user, msg) ->
self = @
now = new Date().getTime()
@headers.ContextId = now
@sendBody.clientmessageid = now
@sendBody.content = escape msg
request.post(
url: @getSendUrl(user),
headers: @headers,
body: @sendBody,
gzip: true, json: true,
(error, response, body) ->
unless response.statusCode in [200, 201]
self.robot.logger.error "Send request returned status " +
"#{response.statusCode}. user='#{user}' msg='#{msg}'"
if error
self.robot.logger.error "Send request failed: " + error
self.sendQueues[user].shift()
# process remaining messages in queue
if self.sendQueues[user].length isnt 0
self.sendRequest user, self.sendQueues[user][0]
)
# @private
# Polls the server for new events.
#
# @note it recursively calls itself
#
pollRequest: ->
self = @
@headers.ContextId = new Date().getTime()
request.post(
url: @pollUrl,
headers: @headers,
gzip: true,
(error, response, body) ->
if error
self.robot.logger.error "Poll request failed: #{error}"
else
try
if body.trim()
body = JSON.parse body
if body.eventMessages
self.onEventMessage message for message in body.eventMessages
else if body.errorCode
self.robot.logger.error "Poll response error #{body.errorCode}: #{body.message}"
else if Object.keys(body).length > 0
self.robot.logger.error "Unexpected poll response body: #{util.inspect body}"
catch err
self.robot.logger.error "Parsing poll results failed: " +
"#{err} body='#{util.inspect body}'"
self.pollRequest()
)
exports.use = (robot) ->
new SkypeWebAdapter robot
| 169177 | phantom = require 'phantom'
request = require 'request'
util = require 'util'
escape = require 'escape-html'
fs = require 'fs'
path = require 'path'
URL = require 'url-parse'
PageHelper = require './page_helper'
{Adapter, TextMessage, User} = require 'hubot'
class SkypeWebAdapter extends Adapter
# @param robot [Robot] the instance of hubot that uses the adapter
constructor: (@robot) ->
super @robot
@getPollUrl = -> "#{@url}/v1/users/ME/endpoints/SELF/subscriptions/0/poll"
@getSendUrl = (user) -> "#{@url}/v1/users/ME/conversations/#{user}/messages"
@sendBody = messagetype: 'RichText', contenttype: 'text', content: ''
@sendQueues = {}
@headers = false
@eventsCache = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
@respondPattern = @robot.respondPattern /.*/
# Read and validate username
@username = process.env.HUBOT_SKYPE_USERNAME
if not @username or @username.length < 2
throw new Error 'Provide a valid username in HUBOT_SKYPE_USERNAME!'
# Read and validate password
@password = process.env.HUBOT_SKYPE_PASSWORD
if not @password or @password.length < 2
throw new Error 'Provide a valid password in HUBOT_SKYPE_PASSWORD!'
# Read and validate reconnect interval
@reconnectInterval = 240
if process.env.HUBOT_SKYPE_RECONNECT
@reconnectInterval = parseInt process.env.HUBOT_SKYPE_RECONNECT
if @reconnectInterval < 20
@robot.logger.warning 'HUBOT_SKYPE_RECONNECT is the adapter ' +
'reconnect interval in minutes! (optional parameter)'
throw new Error 'Minimum reconnect interval is 20 minutes!'
# Read and validate max message length
@maxLength = 1500
if process.env.HUBOT_SKYPE_MAX_MESSAGE_LENGTH
@maxLength = parseInt process.env.HUBOT_SKYPE_MAX_MESSAGE_LENGTH
@robot.logger.info('Set max message length to ' + @maxLength)
unless 30 <= @maxLength and @maxLength <= 100000
throw new Error 'HUBOT_SKYPE_MAX_MESSAGE_LENGTH must be ' +
'between 30 and 100000'
# Starts the adapter
#
run: ->
self = @
success = ->
self.emit 'connected'
self.pollRequest()
if self.reconnectInterval
setInterval (-> self.login()), self.reconnectInterval * 60 * 1000
self.robot.logger.info "SkypeWeb adapter configured to reconnect " +
"every #{self.reconnectInterval} minutes"
error = ->
throw new Error 'SkypeWeb adapter failure in initial login!'
backup = false
try backup = JSON.parse fs.readFileSync 'hubot-skype-web.backup', 'utf8'
if backup and new Date(backup.expire) > new Date()
self.robot.logger.info 'Skype headers restored from backup.'
self.headers = backup.headers
self.url = backup.url
self.pollUrl = self.getPollUrl()
success()
setTimeout (-> self.login()), 5000
else
@login success: success, error: error
# Entry point for messages from hubot
#
send: (envelope, strings...) ->
@sendInQueue envelope.room, msg for msg in strings
# Replies back to a specific user.
#
# @note it prefixes messages only in group chats
#
reply: (envelope, strings...) ->
# Only prefix replies in group chats
if envelope.user.room.indexOf('19:') is 0
@robot.logger.debug 'reply: adding receiver prefix to all strings'
strings = strings.map (s) -> "#{envelope.user.nickname ||
envelope.user.name}: #{s}"
else
@robot.logger.debug 'reply: replying in personal ' +
'chat ' + envelope.user.room
@send envelope, strings...
# @private
# Login to Skype web client and retrieve a sample poll request.
#
# @note Uses PhantomJS to render the web page and monitor network traffic
#
# @option options [Function] success executed if the correct requests are found
# @option options [Function] error executed if the time exceeds the limit
#
login: (options = {}) ->
self = @
phantomOptions = parameters: 'web-security': false
if process.platform.indexOf('win') isnt -1
# Disable dnode with weak on Windows hosts
phantomOptions.dnodeOpts = weak: false
phantom.create ((ph) ->
ph.createPage (page) ->
# Execute fail condition if login time limit expires
errorTimer = setTimeout (->
self.robot.logger.error 'Timeout in waiting for login success!'
page.render 'login-failure.png', ->
self.robot.logger.error "Screenshot saved at: " +
process.cwd() + path.sep + 'login-failure.png'
page.close()
ph.exit 0
options?.error?()
), 50000 # after 50 secs
# Monitor outgoing requests until proper poll request appears
requestsCount = 0
success = false
page.set 'onResourceRequested', (request) ->
if request.method is 'POST'
for header in request.headers
if header.name is 'RegistrationToken'
return if requestsCount++ < 1 or success
page.close()
ph.exit 0
# Clear timer for error condition
clearTimeout errorTimer
self.robot.logger.info 'SkypeWeb adapter logged in successfully!'
self.robot.logger.debug 'Captured poll request: \n' +
util.inspect request
self.copyRequest request
success = true
options?.success?()
else
self.robot.logger.debug 'Skype during login: ' + request.url
# Use generic user-agent
page.set 'settings.userAgent',
'Mozilla (Windows NT) AppleWebKit KHTML, like Gecko) Chrome'
# Login to skype web
page.open 'https://web.skype.com', (status) ->
helper = new PageHelper page
helper.wait '#username', ->
if self.username.indexOf('@') is -1
helper.fillForm '#username': self.username, '#password': <PASSWORD>
else # login with a Windows Live account
# Submit username to trigger redirect
helper.fillForm '#username': self.username
# Wait a redirect to Windows Live login page
helper.wait 'input[type="submit"]', ->
helper.fillForm 'input[type="password"]': self.password
), phantomOptions
# @private
# Stores details of the intercepted request for later use.
#
# @note Most importantly it obtains the RegistrationToken which is used
# to authenticate the requests for receiving or sending messages
#
# @param request [Request] the poll request made from skype web client
#
copyRequest: (request) ->
# Copy base URL from poll request
requestUrl = new URL request.url
@url = requestUrl.protocol + '//' + requestUrl.host
@pollUrl = @getPollUrl()
# Copy poll request headers into a map
@headers = {}
for header in request.headers
@headers[header.name] = header.value
# Clear Content-Length as we won't bother setting correct value
delete @headers['Content-Length']
@headers['Host'] = 'client-s.gateway.messenger.live.com'
@headers['Connection'] = 'keep-alive'
@headers['Accept-Encoding'] = 'gzip, deflate'
@headers['X-SkypeToken'] = @headers['RegistrationToken'].split("=")[1]
# Backup request details to disk for re-use after reboot
backup = JSON.stringify
url: @url
expire: new Date(new Date().getTime() + @reconnectInterval * 60 * 1000)
headers: @headers
self = @
fs.writeFile 'hubot-skype-web.backup', backup, (err) ->
if err
self.robot.logger.error 'IO error while storing ' +
'Skype headers to disc:' + err
else
self.robot.logger.debug 'Skype headers stored to disk successfully'
# @private
# Handles all Skype events coming from the server
#
# @param msg [EventMessage] the event object
#
onEventMessage: (msg) ->
if (msg.resourceType is 'NewMessage' and
msg.resource?.messagetype in ['Text', 'RichText'])
# Make sure we don't process same pessage more than once
# (Happens when you switch RegistrationToken-s)
return if msg.resource.id in @eventsCache
@eventsCache.shift()
@eventsCache.push msg.resource.id
userID = msg.resource.from.split('/contacts/')[1].replace '8:', ''
# Ignore messages sent by the robot
return if userID.toLowerCase() is @username.toLowerCase()
user = @robot.brain.userForId userID
user.room = msg.resource.conversationLink.split('/conversations/')[1]
# Let robot know messages in personal chats are directed at him
if user.room.indexOf('19:') isnt 0
unless user.shell? and user.shell[user.room]
# Only prefix messages that aren't already prefixed by sender
unless @respondPattern.test msg.resource.content
@robot.logger.debug 'Prefix personal message from ' + user.name
msg.resource.content = @robot.name + ': ' + msg.resource.content
# Provide the messages to the robot
@receive new TextMessage user, msg.resource.content, msg.resource.id
# @private
# Store Skype message to be send in queues
#
# @note This prevents newer messages from being received prior
# to older ones due to the async nature of the requests being made
#
# @param user [String] the recipient of the message
# @param msg [String] the contents of the message to be send
#
sendInQueue: (user, msg) ->
@sendQueues[user] ||= []
queue = @sendQueues[user]
# Split messages that can't be sent at once
if msg.length > @maxLength
@robot.logger.warning 'Message too long for sending! Splitting...'
index = msg.substring(0, @maxLength).lastIndexOf("\n")
index = @maxLength if index is -1
@sendInQueue user, msg.substring 0, index
@sendInQueue user, msg.substring index + 1
return
queue.push msg
len = queue.length
return @sendRequest user, msg if len is 1
# Optimize queue by truncating next messages
if len > 2 and queue[len-1].length + queue[len-2].length < @maxLength
queue[len-2] += "\n" + queue.pop()
# @private
# Sends POST request to Skype containing new message to given user
#
# @note it recursively calls itself until queues are empty
#
# @param user [String] the recipient of the message
# @param msg [String] the contents of the message to be send
#
sendRequest: (user, msg) ->
self = @
now = new Date().getTime()
@headers.ContextId = now
@sendBody.clientmessageid = now
@sendBody.content = escape msg
request.post(
url: @getSendUrl(user),
headers: @headers,
body: @sendBody,
gzip: true, json: true,
(error, response, body) ->
unless response.statusCode in [200, 201]
self.robot.logger.error "Send request returned status " +
"#{response.statusCode}. user='#{user}' msg='#{msg}'"
if error
self.robot.logger.error "Send request failed: " + error
self.sendQueues[user].shift()
# process remaining messages in queue
if self.sendQueues[user].length isnt 0
self.sendRequest user, self.sendQueues[user][0]
)
# @private
# Polls the server for new events.
#
# @note it recursively calls itself
#
pollRequest: ->
self = @
@headers.ContextId = new Date().getTime()
request.post(
url: @pollUrl,
headers: @headers,
gzip: true,
(error, response, body) ->
if error
self.robot.logger.error "Poll request failed: #{error}"
else
try
if body.trim()
body = JSON.parse body
if body.eventMessages
self.onEventMessage message for message in body.eventMessages
else if body.errorCode
self.robot.logger.error "Poll response error #{body.errorCode}: #{body.message}"
else if Object.keys(body).length > 0
self.robot.logger.error "Unexpected poll response body: #{util.inspect body}"
catch err
self.robot.logger.error "Parsing poll results failed: " +
"#{err} body='#{util.inspect body}'"
self.pollRequest()
)
exports.use = (robot) ->
new SkypeWebAdapter robot
| true | phantom = require 'phantom'
request = require 'request'
util = require 'util'
escape = require 'escape-html'
fs = require 'fs'
path = require 'path'
URL = require 'url-parse'
PageHelper = require './page_helper'
{Adapter, TextMessage, User} = require 'hubot'
class SkypeWebAdapter extends Adapter
# @param robot [Robot] the instance of hubot that uses the adapter
constructor: (@robot) ->
super @robot
@getPollUrl = -> "#{@url}/v1/users/ME/endpoints/SELF/subscriptions/0/poll"
@getSendUrl = (user) -> "#{@url}/v1/users/ME/conversations/#{user}/messages"
@sendBody = messagetype: 'RichText', contenttype: 'text', content: ''
@sendQueues = {}
@headers = false
@eventsCache = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
@respondPattern = @robot.respondPattern /.*/
# Read and validate username
@username = process.env.HUBOT_SKYPE_USERNAME
if not @username or @username.length < 2
throw new Error 'Provide a valid username in HUBOT_SKYPE_USERNAME!'
# Read and validate password
@password = process.env.HUBOT_SKYPE_PASSWORD
if not @password or @password.length < 2
throw new Error 'Provide a valid password in HUBOT_SKYPE_PASSWORD!'
# Read and validate reconnect interval
@reconnectInterval = 240
if process.env.HUBOT_SKYPE_RECONNECT
@reconnectInterval = parseInt process.env.HUBOT_SKYPE_RECONNECT
if @reconnectInterval < 20
@robot.logger.warning 'HUBOT_SKYPE_RECONNECT is the adapter ' +
'reconnect interval in minutes! (optional parameter)'
throw new Error 'Minimum reconnect interval is 20 minutes!'
# Read and validate max message length
@maxLength = 1500
if process.env.HUBOT_SKYPE_MAX_MESSAGE_LENGTH
@maxLength = parseInt process.env.HUBOT_SKYPE_MAX_MESSAGE_LENGTH
@robot.logger.info('Set max message length to ' + @maxLength)
unless 30 <= @maxLength and @maxLength <= 100000
throw new Error 'HUBOT_SKYPE_MAX_MESSAGE_LENGTH must be ' +
'between 30 and 100000'
# Starts the adapter
#
run: ->
self = @
success = ->
self.emit 'connected'
self.pollRequest()
if self.reconnectInterval
setInterval (-> self.login()), self.reconnectInterval * 60 * 1000
self.robot.logger.info "SkypeWeb adapter configured to reconnect " +
"every #{self.reconnectInterval} minutes"
error = ->
throw new Error 'SkypeWeb adapter failure in initial login!'
backup = false
try backup = JSON.parse fs.readFileSync 'hubot-skype-web.backup', 'utf8'
if backup and new Date(backup.expire) > new Date()
self.robot.logger.info 'Skype headers restored from backup.'
self.headers = backup.headers
self.url = backup.url
self.pollUrl = self.getPollUrl()
success()
setTimeout (-> self.login()), 5000
else
@login success: success, error: error
# Entry point for messages from hubot
#
send: (envelope, strings...) ->
@sendInQueue envelope.room, msg for msg in strings
# Replies back to a specific user.
#
# @note it prefixes messages only in group chats
#
reply: (envelope, strings...) ->
# Only prefix replies in group chats
if envelope.user.room.indexOf('19:') is 0
@robot.logger.debug 'reply: adding receiver prefix to all strings'
strings = strings.map (s) -> "#{envelope.user.nickname ||
envelope.user.name}: #{s}"
else
@robot.logger.debug 'reply: replying in personal ' +
'chat ' + envelope.user.room
@send envelope, strings...
# @private
# Login to Skype web client and retrieve a sample poll request.
#
# @note Uses PhantomJS to render the web page and monitor network traffic
#
# @option options [Function] success executed if the correct requests are found
# @option options [Function] error executed if the time exceeds the limit
#
login: (options = {}) ->
self = @
phantomOptions = parameters: 'web-security': false
if process.platform.indexOf('win') isnt -1
# Disable dnode with weak on Windows hosts
phantomOptions.dnodeOpts = weak: false
phantom.create ((ph) ->
ph.createPage (page) ->
# Execute fail condition if login time limit expires
errorTimer = setTimeout (->
self.robot.logger.error 'Timeout in waiting for login success!'
page.render 'login-failure.png', ->
self.robot.logger.error "Screenshot saved at: " +
process.cwd() + path.sep + 'login-failure.png'
page.close()
ph.exit 0
options?.error?()
), 50000 # after 50 secs
# Monitor outgoing requests until proper poll request appears
requestsCount = 0
success = false
page.set 'onResourceRequested', (request) ->
if request.method is 'POST'
for header in request.headers
if header.name is 'RegistrationToken'
return if requestsCount++ < 1 or success
page.close()
ph.exit 0
# Clear timer for error condition
clearTimeout errorTimer
self.robot.logger.info 'SkypeWeb adapter logged in successfully!'
self.robot.logger.debug 'Captured poll request: \n' +
util.inspect request
self.copyRequest request
success = true
options?.success?()
else
self.robot.logger.debug 'Skype during login: ' + request.url
# Use generic user-agent
page.set 'settings.userAgent',
'Mozilla (Windows NT) AppleWebKit KHTML, like Gecko) Chrome'
# Login to skype web
page.open 'https://web.skype.com', (status) ->
helper = new PageHelper page
helper.wait '#username', ->
if self.username.indexOf('@') is -1
helper.fillForm '#username': self.username, '#password': PI:PASSWORD:<PASSWORD>END_PI
else # login with a Windows Live account
# Submit username to trigger redirect
helper.fillForm '#username': self.username
# Wait a redirect to Windows Live login page
helper.wait 'input[type="submit"]', ->
helper.fillForm 'input[type="password"]': self.password
), phantomOptions
# @private
# Stores details of the intercepted request for later use.
#
# @note Most importantly it obtains the RegistrationToken which is used
# to authenticate the requests for receiving or sending messages
#
# @param request [Request] the poll request made from skype web client
#
copyRequest: (request) ->
# Copy base URL from poll request
requestUrl = new URL request.url
@url = requestUrl.protocol + '//' + requestUrl.host
@pollUrl = @getPollUrl()
# Copy poll request headers into a map
@headers = {}
for header in request.headers
@headers[header.name] = header.value
# Clear Content-Length as we won't bother setting correct value
delete @headers['Content-Length']
@headers['Host'] = 'client-s.gateway.messenger.live.com'
@headers['Connection'] = 'keep-alive'
@headers['Accept-Encoding'] = 'gzip, deflate'
@headers['X-SkypeToken'] = @headers['RegistrationToken'].split("=")[1]
# Backup request details to disk for re-use after reboot
backup = JSON.stringify
url: @url
expire: new Date(new Date().getTime() + @reconnectInterval * 60 * 1000)
headers: @headers
self = @
fs.writeFile 'hubot-skype-web.backup', backup, (err) ->
if err
self.robot.logger.error 'IO error while storing ' +
'Skype headers to disc:' + err
else
self.robot.logger.debug 'Skype headers stored to disk successfully'
# @private
# Handles all Skype events coming from the server
#
# @param msg [EventMessage] the event object
#
onEventMessage: (msg) ->
if (msg.resourceType is 'NewMessage' and
msg.resource?.messagetype in ['Text', 'RichText'])
# Make sure we don't process same pessage more than once
# (Happens when you switch RegistrationToken-s)
return if msg.resource.id in @eventsCache
@eventsCache.shift()
@eventsCache.push msg.resource.id
userID = msg.resource.from.split('/contacts/')[1].replace '8:', ''
# Ignore messages sent by the robot
return if userID.toLowerCase() is @username.toLowerCase()
user = @robot.brain.userForId userID
user.room = msg.resource.conversationLink.split('/conversations/')[1]
# Let robot know messages in personal chats are directed at him
if user.room.indexOf('19:') isnt 0
unless user.shell? and user.shell[user.room]
# Only prefix messages that aren't already prefixed by sender
unless @respondPattern.test msg.resource.content
@robot.logger.debug 'Prefix personal message from ' + user.name
msg.resource.content = @robot.name + ': ' + msg.resource.content
# Provide the messages to the robot
@receive new TextMessage user, msg.resource.content, msg.resource.id
# @private
# Store Skype message to be send in queues
#
# @note This prevents newer messages from being received prior
# to older ones due to the async nature of the requests being made
#
# @param user [String] the recipient of the message
# @param msg [String] the contents of the message to be send
#
sendInQueue: (user, msg) ->
@sendQueues[user] ||= []
queue = @sendQueues[user]
# Split messages that can't be sent at once
if msg.length > @maxLength
@robot.logger.warning 'Message too long for sending! Splitting...'
index = msg.substring(0, @maxLength).lastIndexOf("\n")
index = @maxLength if index is -1
@sendInQueue user, msg.substring 0, index
@sendInQueue user, msg.substring index + 1
return
queue.push msg
len = queue.length
return @sendRequest user, msg if len is 1
# Optimize queue by truncating next messages
if len > 2 and queue[len-1].length + queue[len-2].length < @maxLength
queue[len-2] += "\n" + queue.pop()
# @private
# Sends POST request to Skype containing new message to given user
#
# @note it recursively calls itself until queues are empty
#
# @param user [String] the recipient of the message
# @param msg [String] the contents of the message to be send
#
sendRequest: (user, msg) ->
self = @
now = new Date().getTime()
@headers.ContextId = now
@sendBody.clientmessageid = now
@sendBody.content = escape msg
request.post(
url: @getSendUrl(user),
headers: @headers,
body: @sendBody,
gzip: true, json: true,
(error, response, body) ->
unless response.statusCode in [200, 201]
self.robot.logger.error "Send request returned status " +
"#{response.statusCode}. user='#{user}' msg='#{msg}'"
if error
self.robot.logger.error "Send request failed: " + error
self.sendQueues[user].shift()
# process remaining messages in queue
if self.sendQueues[user].length isnt 0
self.sendRequest user, self.sendQueues[user][0]
)
# @private
# Polls the server for new events.
#
# @note it recursively calls itself
#
pollRequest: ->
self = @
@headers.ContextId = new Date().getTime()
request.post(
url: @pollUrl,
headers: @headers,
gzip: true,
(error, response, body) ->
if error
self.robot.logger.error "Poll request failed: #{error}"
else
try
if body.trim()
body = JSON.parse body
if body.eventMessages
self.onEventMessage message for message in body.eventMessages
else if body.errorCode
self.robot.logger.error "Poll response error #{body.errorCode}: #{body.message}"
else if Object.keys(body).length > 0
self.robot.logger.error "Unexpected poll response body: #{util.inspect body}"
catch err
self.robot.logger.error "Parsing poll results failed: " +
"#{err} body='#{util.inspect body}'"
self.pollRequest()
)
exports.use = (robot) ->
new SkypeWebAdapter robot
|
[
{
"context": "i'\n country: 'US'\n }\n ]\n name: \"Mariane Ibrahim Gallery\"\n profile: {\n bio: 'A very elaborate bio ",
"end": 295,
"score": 0.9998893737792969,
"start": 272,
"tag": "NAME",
"value": "Mariane Ibrahim Gallery"
}
] | apps/artwork/components/partner/test/fixture.coffee | xtina-starr/microgravity | 0 | { fabricate } = require 'antigravity'
module.exports =
partner = fabricate('partner',
href: "/art-gallery"
locations: [
{
city: 'New York'
country: 'US'
},
{
city: 'Miami'
country: 'US'
}
]
name: "Mariane Ibrahim Gallery"
profile: {
bio: 'A very elaborate bio about a very prestigious gallery.'
id: 'art-gallery'
}
type: "Gallery"
) | 60102 | { fabricate } = require 'antigravity'
module.exports =
partner = fabricate('partner',
href: "/art-gallery"
locations: [
{
city: 'New York'
country: 'US'
},
{
city: 'Miami'
country: 'US'
}
]
name: "<NAME>"
profile: {
bio: 'A very elaborate bio about a very prestigious gallery.'
id: 'art-gallery'
}
type: "Gallery"
) | true | { fabricate } = require 'antigravity'
module.exports =
partner = fabricate('partner',
href: "/art-gallery"
locations: [
{
city: 'New York'
country: 'US'
},
{
city: 'Miami'
country: 'US'
}
]
name: "PI:NAME:<NAME>END_PI"
profile: {
bio: 'A very elaborate bio about a very prestigious gallery.'
id: 'art-gallery'
}
type: "Gallery"
) |
[
{
"context": ".authorize({\n type: \"redirect\",\n name: \"Birds Eye\",\n success: () =>\n @status(\"signed-in",
"end": 546,
"score": 0.9398490190505981,
"start": 537,
"tag": "NAME",
"value": "Birds Eye"
},
{
"context": ".get(\"me\", {},\n (user) =>\n ... | js/user.coffee | mikemoraned/birdseye | 1 | window.birdseye ?= {}
class User
status: ko.observable("signed-out")
name: ko.observable()
organisationIds: ko.observableArray()
constructor: ->
@signedIn = ko.computed(() =>
@status() == "signed-in"
)
freshSignIn: () =>
@_clear()
@signOut()
@_signIn()
signOut: () =>
@_clear()
Trello.deauthorize()
@status("signed-out")
_clear: () =>
@name(null)
@organisationIds([])
_signIn: () =>
@status("signing-in")
Trello.authorize({
type: "redirect",
name: "Birds Eye",
success: () =>
@status("signed-in")
@_update()
,
error: @_error
})
_error: (m) =>
@signOut()
console.log("Error: #{m}")
_update: () =>
@_clear()
Trello.members.get("me", {},
(user) =>
@name(user.fullName)
@organisationIds(user.idOrganizations)
,
@_error
)
window.birdseye.User = User | 40966 | window.birdseye ?= {}
class User
status: ko.observable("signed-out")
name: ko.observable()
organisationIds: ko.observableArray()
constructor: ->
@signedIn = ko.computed(() =>
@status() == "signed-in"
)
freshSignIn: () =>
@_clear()
@signOut()
@_signIn()
signOut: () =>
@_clear()
Trello.deauthorize()
@status("signed-out")
_clear: () =>
@name(null)
@organisationIds([])
_signIn: () =>
@status("signing-in")
Trello.authorize({
type: "redirect",
name: "<NAME>",
success: () =>
@status("signed-in")
@_update()
,
error: @_error
})
_error: (m) =>
@signOut()
console.log("Error: #{m}")
_update: () =>
@_clear()
Trello.members.get("me", {},
(user) =>
@name(user.fullName)
@organisationIds(user.idOrganizations)
,
@_error
)
window.birdseye.User = User | true | window.birdseye ?= {}
class User
status: ko.observable("signed-out")
name: ko.observable()
organisationIds: ko.observableArray()
constructor: ->
@signedIn = ko.computed(() =>
@status() == "signed-in"
)
freshSignIn: () =>
@_clear()
@signOut()
@_signIn()
signOut: () =>
@_clear()
Trello.deauthorize()
@status("signed-out")
_clear: () =>
@name(null)
@organisationIds([])
_signIn: () =>
@status("signing-in")
Trello.authorize({
type: "redirect",
name: "PI:NAME:<NAME>END_PI",
success: () =>
@status("signed-in")
@_update()
,
error: @_error
})
_error: (m) =>
@signOut()
console.log("Error: #{m}")
_update: () =>
@_clear()
Trello.members.get("me", {},
(user) =>
@name(user.fullName)
@organisationIds(user.idOrganizations)
,
@_error
)
window.birdseye.User = User |
[
{
"context": "eetings'])\n\nsetup(db)\n\nschema =\n user: {'username', 'password', 'avatar'}\n announcement: {'title',",
"end": 556,
"score": 0.9893514513969421,
"start": 548,
"tag": "USERNAME",
"value": "username"
},
{
"context": "setup(db)\n\nschema =\n user: {'u... | server/db.coffee | IliaSky/sky-learning | 2 | # module.exports = require('mongojs').connect('localhost/learning', ['news', 'lectures', 'tasks', 'topics', 'users'])
utils = require('./utils')
log = utils.log
ObjectID = require('mongodb').ObjectID
fs = require('fs')
setup = require('./db-setup')
config = require('../config/db.json')
_id = (x) -> if typeof x is 'string' then ObjectID(x) else x
id = (x) -> _id: _id(x._id)
db = require('mongojs')(config.db || 'localhost/learning', ['announcements', 'lectures', 'tasks', 'topics', 'users', 'meetings'])
setup(db)
schema =
user: {'username', 'password', 'avatar'}
announcement: {'title', 'content'}
lecture: {'title', 'url', 'presentation_date'}
task: {'title', 'description', 'available_until'}
solution: {'code', 'task_id'}
post: {'content'}
# topic: {'title', 'post'}
topic: {'title', posts: ['post']}
meeting: {'id'}
validate = (object, type) ->
pattern = schema[type]
result = {}
for key, type of pattern
if type instanceof Array
# result[key] = (validate(object[key][i], type[i]) for i in pattern[key])
result[key] = [validate(object[key][0], type[0])]
else if schema.hasOwnProperty(type)
result[key] = validate(object[key], type)
else
object[key] ?= ''
result[key] = object[key].toString()
result
# validate = (object, type) ->
# result = {}
# for name of schema[type]
# object[name] ?= ''
# result[name] = object[name].toString()
# result
# these things look really bad here :(
# hash([name, (object[name] or '').toString()] for name of schema[type])
_new = (category, data, author) ->
type = category.slice(0, -1)
result = utils.extend validate(data, type), {author: author.username, created_at: new Date()}
if type is 'topic'
utils.extend result.posts[0], {author: author.username, created_at: new Date()}
result
all = (category) -> (data, cb) ->
filters =
topics: {posts: 0}
users: {password: 0}
db[category].find(data, filters[category] or {}).sort created_at: -1 , cb
one = (category) -> (data, cb) ->
data = id(data) if data._id?
db[category].findOne data, cb
those = (category) -> where: (data) -> (_, cb) ->
all(category)(data, cb)
add = (category) -> (user, data, cb) ->
if category is 'posts'
db.topics.update id(data), $push: posts: _new('posts', data, user), cb
else
db[category].insert _new(category, data, user), cb
edit = (category) -> (user, data, cb) ->
return cb('Editing posts is not allowed') if category is 'posts'
# db.topics.update {_id: data.topic_id.toString()}, $push: _new('post', data, user), cb
db[category].update id(data), $set: _new(category, data, user), cb
remove = (category) -> (user, data, cb) ->
return cb('Removing posts is not allowed') if category is 'posts'
db[category].remove id(data), cb
authenticate = (user, cb) ->
db.users.findOne utils.filter(user, ['username', 'password']), (err, data) ->
cb(data)
# return cb(user: 1, admin: 1) if data and data.admin
# return cb(user: 1) if data
# cb({})
register = (user, cb) ->
user = validate(user, 'user')
utils.extend user, author: user.username, created_at: new Date()
db.users.insert user, cb
avatar = (user, cb) ->
db.users.findOne user, (err, user) ->
if user and user.avatar
return cb.res.send(200, new Buffer(user.avatar.slice(23), "base64"), 'image/jpeg')
return fs.readFile 'client/img/NoAvatar.png', (e, img) ->
if (e)
cb.res.send(404)
else
cb.res.send(200, img, 'image/png')
changeAvatar = (user, data, cb) ->
db.users.update id(user), {$set: avatar: data.image}, cb
module.exports = {id, db, schema, validate, authenticate, register, avatar, changeAvatar,
_new, all, one, those, add, edit, remove} | 30309 | # module.exports = require('mongojs').connect('localhost/learning', ['news', 'lectures', 'tasks', 'topics', 'users'])
utils = require('./utils')
log = utils.log
ObjectID = require('mongodb').ObjectID
fs = require('fs')
setup = require('./db-setup')
config = require('../config/db.json')
_id = (x) -> if typeof x is 'string' then ObjectID(x) else x
id = (x) -> _id: _id(x._id)
db = require('mongojs')(config.db || 'localhost/learning', ['announcements', 'lectures', 'tasks', 'topics', 'users', 'meetings'])
setup(db)
schema =
user: {'username', '<PASSWORD>', 'avatar'}
announcement: {'title', 'content'}
lecture: {'title', 'url', 'presentation_date'}
task: {'title', 'description', 'available_until'}
solution: {'code', 'task_id'}
post: {'content'}
# topic: {'title', 'post'}
topic: {'title', posts: ['post']}
meeting: {'id'}
validate = (object, type) ->
pattern = schema[type]
result = {}
for key, type of pattern
if type instanceof Array
# result[key] = (validate(object[key][i], type[i]) for i in pattern[key])
result[key] = [validate(object[key][0], type[0])]
else if schema.hasOwnProperty(type)
result[key] = validate(object[key], type)
else
object[key] ?= ''
result[key] = object[key].toString()
result
# validate = (object, type) ->
# result = {}
# for name of schema[type]
# object[name] ?= ''
# result[name] = object[name].toString()
# result
# these things look really bad here :(
# hash([name, (object[name] or '').toString()] for name of schema[type])
_new = (category, data, author) ->
type = category.slice(0, -1)
result = utils.extend validate(data, type), {author: author.username, created_at: new Date()}
if type is 'topic'
utils.extend result.posts[0], {author: author.username, created_at: new Date()}
result
all = (category) -> (data, cb) ->
filters =
topics: {posts: 0}
users: {password: 0}
db[category].find(data, filters[category] or {}).sort created_at: -1 , cb
one = (category) -> (data, cb) ->
data = id(data) if data._id?
db[category].findOne data, cb
those = (category) -> where: (data) -> (_, cb) ->
all(category)(data, cb)
add = (category) -> (user, data, cb) ->
if category is 'posts'
db.topics.update id(data), $push: posts: _new('posts', data, user), cb
else
db[category].insert _new(category, data, user), cb
edit = (category) -> (user, data, cb) ->
return cb('Editing posts is not allowed') if category is 'posts'
# db.topics.update {_id: data.topic_id.toString()}, $push: _new('post', data, user), cb
db[category].update id(data), $set: _new(category, data, user), cb
remove = (category) -> (user, data, cb) ->
return cb('Removing posts is not allowed') if category is 'posts'
db[category].remove id(data), cb
authenticate = (user, cb) ->
db.users.findOne utils.filter(user, ['username', '<PASSWORD>']), (err, data) ->
cb(data)
# return cb(user: 1, admin: 1) if data and data.admin
# return cb(user: 1) if data
# cb({})
register = (user, cb) ->
user = validate(user, 'user')
utils.extend user, author: user.username, created_at: new Date()
db.users.insert user, cb
avatar = (user, cb) ->
db.users.findOne user, (err, user) ->
if user and user.avatar
return cb.res.send(200, new Buffer(user.avatar.slice(23), "base64"), 'image/jpeg')
return fs.readFile 'client/img/NoAvatar.png', (e, img) ->
if (e)
cb.res.send(404)
else
cb.res.send(200, img, 'image/png')
changeAvatar = (user, data, cb) ->
db.users.update id(user), {$set: avatar: data.image}, cb
module.exports = {id, db, schema, validate, authenticate, register, avatar, changeAvatar,
_new, all, one, those, add, edit, remove} | true | # module.exports = require('mongojs').connect('localhost/learning', ['news', 'lectures', 'tasks', 'topics', 'users'])
utils = require('./utils')
log = utils.log
ObjectID = require('mongodb').ObjectID
fs = require('fs')
setup = require('./db-setup')
config = require('../config/db.json')
_id = (x) -> if typeof x is 'string' then ObjectID(x) else x
id = (x) -> _id: _id(x._id)
db = require('mongojs')(config.db || 'localhost/learning', ['announcements', 'lectures', 'tasks', 'topics', 'users', 'meetings'])
setup(db)
schema =
user: {'username', 'PI:PASSWORD:<PASSWORD>END_PI', 'avatar'}
announcement: {'title', 'content'}
lecture: {'title', 'url', 'presentation_date'}
task: {'title', 'description', 'available_until'}
solution: {'code', 'task_id'}
post: {'content'}
# topic: {'title', 'post'}
topic: {'title', posts: ['post']}
meeting: {'id'}
validate = (object, type) ->
pattern = schema[type]
result = {}
for key, type of pattern
if type instanceof Array
# result[key] = (validate(object[key][i], type[i]) for i in pattern[key])
result[key] = [validate(object[key][0], type[0])]
else if schema.hasOwnProperty(type)
result[key] = validate(object[key], type)
else
object[key] ?= ''
result[key] = object[key].toString()
result
# validate = (object, type) ->
# result = {}
# for name of schema[type]
# object[name] ?= ''
# result[name] = object[name].toString()
# result
# these things look really bad here :(
# hash([name, (object[name] or '').toString()] for name of schema[type])
_new = (category, data, author) ->
type = category.slice(0, -1)
result = utils.extend validate(data, type), {author: author.username, created_at: new Date()}
if type is 'topic'
utils.extend result.posts[0], {author: author.username, created_at: new Date()}
result
all = (category) -> (data, cb) ->
filters =
topics: {posts: 0}
users: {password: 0}
db[category].find(data, filters[category] or {}).sort created_at: -1 , cb
one = (category) -> (data, cb) ->
data = id(data) if data._id?
db[category].findOne data, cb
those = (category) -> where: (data) -> (_, cb) ->
all(category)(data, cb)
add = (category) -> (user, data, cb) ->
if category is 'posts'
db.topics.update id(data), $push: posts: _new('posts', data, user), cb
else
db[category].insert _new(category, data, user), cb
edit = (category) -> (user, data, cb) ->
return cb('Editing posts is not allowed') if category is 'posts'
# db.topics.update {_id: data.topic_id.toString()}, $push: _new('post', data, user), cb
db[category].update id(data), $set: _new(category, data, user), cb
remove = (category) -> (user, data, cb) ->
return cb('Removing posts is not allowed') if category is 'posts'
db[category].remove id(data), cb
authenticate = (user, cb) ->
db.users.findOne utils.filter(user, ['username', 'PI:PASSWORD:<PASSWORD>END_PI']), (err, data) ->
cb(data)
# return cb(user: 1, admin: 1) if data and data.admin
# return cb(user: 1) if data
# cb({})
register = (user, cb) ->
user = validate(user, 'user')
utils.extend user, author: user.username, created_at: new Date()
db.users.insert user, cb
avatar = (user, cb) ->
db.users.findOne user, (err, user) ->
if user and user.avatar
return cb.res.send(200, new Buffer(user.avatar.slice(23), "base64"), 'image/jpeg')
return fs.readFile 'client/img/NoAvatar.png', (e, img) ->
if (e)
cb.res.send(404)
else
cb.res.send(200, img, 'image/png')
changeAvatar = (user, data, cb) ->
db.users.update id(user), {$set: avatar: data.image}, cb
module.exports = {id, db, schema, validate, authenticate, register, avatar, changeAvatar,
_new, all, one, those, add, edit, remove} |
[
{
"context": "# Based on http:#bl.ocks.org/robschmuecker/7880033 which has the following copyright\n\n# Copy",
"end": 42,
"score": 0.9996268153190613,
"start": 29,
"tag": "USERNAME",
"value": "robschmuecker"
},
{
"context": "he following copyright\n\n# Copyright (c) 2013-2016, Rob Sc... | lib/tree-view.coffee | jasongilman/proto-repl-sayid | 23 | # Based on http:#bl.ocks.org/robschmuecker/7880033 which has the following copyright
# Copyright (c) 2013-2016, Rob Schmuecker
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * The name Rob Schmuecker may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
{Range, Point} = require 'atom'
{$, $$$, ScrollView} = require 'atom-space-pen-views'
d3 = require 'd3'
# A recursive helper function for performing some setup by walking through all nodes
visit = (parent, visitFn, childrenFn)->
if !parent then return
visitFn(parent)
children = childrenFn(parent)
if children
for child in children
visit(child, visitFn, childrenFn)
PAN_SPEED = 200
# Within 20px from edges will pan when dragging.
PAN_BOUNDARY = 20
NODE_TRANSITION_DURATION = 750
# Truncates a string to the specified length if needed.
truncateToLength = (s, length)->
if s.length > length
s.substring(0, length-1) + "…"
else
s
# The maximum width of inline data on one row
MAX_INLINE_WIDTH = 60
# The string separating arguments from the return value for inline display
ARG_RETURN_SEP = " => "
# The maximum amount of space the arguments can take with summarized with return value
ARG_SUMMARY_WITH_RETURN_MAX_LENGTH = (MAX_INLINE_WIDTH - ARG_RETURN_SEP.length) * 0.75
PROTOCOL = "proto-repl-sayid:"
NAME = "Proto-REPL Sayid Call Graph"
module.exports =
class TreeView extends ScrollView
# The longest label for a node that was found.
maxLabelLength: null
# The root of the data tree
root: null
# The next id to assign to a node.
nextNodeId: 0
# The current width of the view
viewerWidth: null
#The current height of the view
viewerHeight: null
# An instance of a D3 tree layout
tree: null
# A div used to show the tool tip
tooltipDiv: null
# A timeout id used to set a timeout for delaying execution of code to get data for displaying the tooltip.
toolTipDisplayTimeout: null
# a d3 diagonal projection for use by the node paths
diagonalProjection: null
# The root svg group that holds everything. Used for zooming
svgGroup: null
# d3 zooming behavior
zoomListener: null
toolbar: null
# A map of strings to functions to call when the button is pressed.
toolBarButtonGroups: {}
atom.deserializers.add(this)
@content: ->
@div class: 'proto-repl-sayid-graph native-key-bindings', tabindex: -1
constructor: () ->
super
this
getURI: ->
"proto-repl-sayid://"
initiateView: (toolBarButtonGroups)->
@toolBarButtonGroups = toolBarButtonGroups
holderDiv = document.createElement("div")
@html $ holderDiv
d3HolderDiv = d3.select(holderDiv)
.attr("class", "sayid-holder")
# Add toolbar
@toolbar = d3HolderDiv.append("div")
.attr("class", "sayid-toolbar")
.append("div")
.attr("class", "bar")
.append("span")
.attr("class", "inline-block")
addButtonGroup = (buttons)=>
group = @toolbar.append("div").attr("class", "btn-group")
for button in buttons
btn = group.append("button")
if button.icon
if button.iconset
btn.attr("class", "btn #{button.iconset} #{button.iconset}-#{button.icon}")
.attr("alt", button.name)
else
btn.attr("class", "btn icon icon-#{button.icon}")
.attr("alt", button.name)
else
btn.attr("class", "btn")
btn.text(button.name)
btn.on("click", button.onClick)
for group in toolBarButtonGroups
addButtonGroup(group)
builtinGroup = []
builtinGroup.push(
name: "Expand",
icon: 'plus',
onClick: ()=>
if @root
@expand(@root)
@updateNode(@root)
@centerNode(@root)
)
builtinGroup.push(
name: "Collapse",
icon: "dash",
onClick: ()=>
if @root
@collapse(@root)
@updateNode(@root)
@centerNode(@root)
)
addButtonGroup builtinGroup
@graphDiv = d3HolderDiv.append("div")
.attr("class", "sayid-holder")
# size of the diagram
@viewerWidth = $(holderDiv).width()
@viewerHeight = $(holderDiv).height()
# Defines the arguments that were captured by sayid.
defArgsForNode: (id)->
window.protoRepl.executeCode "(proto-repl-sayid.core/def-args-for-node #{id})",
displayInRepl: false,
resultHandler: (result)->
if result.error
console.log result.error
atom.notifications.addError "Unable to define args for node. See Atom console for full error.", dismissable: true
# Creates an inline tree to display arguments and return values that were captured from the stack.
# Expected keys are file, line, args, return
# args is a map of argument name to edn value.
# argsSummary is a string summarization of the arguments
# returned is an edn value that was returned
inlineDataToTree: (id, {args, argsSummary, returned})->
topArgsSummary = truncateToLength(argsSummary, ARG_SUMMARY_WITH_RETURN_MAX_LENGTH)
topSummary = truncateToLength(topArgsSummary + ARG_RETURN_SEP + returned, MAX_INLINE_WIDTH)
# Create inline trees for each of the arguments.
argsInlineTrees = for argName, argValue of args
# Use Proto REPLs built in capability for this.
[summary, rest...] = window.protoRepl.ednToDisplayTree(argValue)
# Generate a new summary with the arg name.
summary = truncateToLength(argName + ": " + summary, MAX_INLINE_WIDTH)
[summary].concat(rest)
[returnedSummary, rest...] = window.protoRepl.ednToDisplayTree(returned)
returnedSummary = truncateToLength("Return: " + returnedSummary, MAX_INLINE_WIDTH)
returnedInlineTree = [returnedSummary].concat(rest)
# Defines button options to add a button that will define the arguments for a function.
defArgsButton =
button_text: "def",
button_class: "def-saved-var"
button_fn: ()=> @defArgsForNode(id)
[topSummary, {},
[truncateToLength("Args: " + argsSummary, MAX_INLINE_WIDTH), defArgsButton].concat(argsInlineTrees),
returnedInlineTree]
# Returns a promise that gets the data captured by sayid for a given node
# so it can be displayed as an inline tree.
fetchInlineData: (id)->
new Promise (resolve, reject)->
window.protoRepl.executeCode "(proto-repl-sayid.core/retrieve-node-inline-data #{id})",
displayInRepl: false,
resultHandler: (result)->
if result.error
reject(result.error)
else
resolve(window.protoRepl.parseEdn(result.value))
# Retrieves data from sayid for the node with the given id and displays an
# inline tree in the file where the function is located.
displayNodeInlineData: (id)->
@fetchInlineData(id).then((data)=>
inlineTree = @inlineDataToTree(id, data)
line = data.line - 1
range = new Range(new Point(line), new Point(line,Infinity))
textEditorPromise = atom.workspace.open(data.file, {initialLine: line, searchAllPanes: true})
textEditorPromise.then (editor)->
window.protoRepl.repl.displayInline(editor, range, inlineTree)
).catch((error)->
console.error(error)
atom.notifications.addError "Unable to retrieve node data. See Atom console for full error.", dismissable: true
)
# TODO After resize get the latest sizes for controlling zooming.
# Collapses all the nodes that are the children of the given node.
collapse: (d)->
if d.children
d._children = d.children
d._children.forEach (c)=>@collapse(c)
d.children = null
else if d._children
d._children.forEach (c)=>@collapse(c)
# Expands all the nodes that are the children of the given node.
expand: (d)->
if (d._children)
d.children = d._children
d.children.forEach (c)=>@expand(c)
d._children = null
else if d.children
d.children.forEach (c)=>@expand(c)
# Displays the sayid data in a D3 tree.
display: (treeData)->
@initiateView(@toolBarButtonGroups)
@maxLabelLength = 0
@root = null
@nextNodeId = 0
@tree = d3.layout.tree().size([@viewerHeight, @viewerWidth])
# Define the div for the tooltip
@tooltipDiv = @graphDiv.append("div")
.attr("class", "sayid-tooltip")
.style("opacity", 0);
# define a d3 diagonal projection for use by the node paths later on.
@diagonalProjection = d3.svg.diagonal().projection((d)-> [d.y, d.x])
# Fail out early but after GUI is setup if there is no data to display
if !treeData
atom.notifications.addWarning "No data was captured for display", dismissable: true
return
# Call visit function to establish maxLabelLength
visit(treeData, (d)=>
@nextNodeId++
@maxLabelLength = Math.max(d.name.length, @maxLabelLength)
, (d)-> if d.children && d.children.length > 0 then d.children else null)
# Define the zoom function for the zoomable tree
zoom = (d)=>
@svgGroup.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")")
# define the zoomListener which calls the zoom function on the "zoom" event constrained within the scaleExtents
@zoomListener = d3.behavior.zoom().scaleExtent([0.1, 3]).on("zoom", zoom)
baseSvg = @graphDiv.append("svg")
.attr("class", "sayid-overlay")
.call(@zoomListener)
# Append a group which holds all nodes and which the zoom Listener can act upon.
@svgGroup = baseSvg.append("g")
# Define the root
@root = treeData
@root.x0 = @viewerHeight / 4
@root.y0 = 0
# Layout the tree initially and center on the root node.
@updateNode(@root)
@centerNode(@root)
# Function to center node when clicked/dropped so node doesn't get lost when collapsing/moving with large amount of children.
centerNode: (source)->
scale = @zoomListener.scale()
x = -1 * source.y0
y = -1 * source.x0
x = x * scale + @viewerWidth / 4
y = y * scale + @viewerHeight / 2
d3.select('g').transition()
.duration(NODE_TRANSITION_DURATION)
.attr("transform", "translate(" + x + "," + y + ")scale(" + scale + ")")
@zoomListener.scale(scale)
@zoomListener.translate([x, y])
# Toggle children on click.
handleNodeClick: (d)->
if d3.event.defaultPrevented then return # click suppressed
if d.children
# Hide children
d._children = d.children
d.children = null
else if d._children
# Display children
d.children = d._children
d._children = null
@updateNode(d)
@centerNode(d)
# Handles a node mouse over event. Takes the node that was moused over.
handleMouseOver: (d)->
x = d3.event.layerX
y = d3.event.layerY
@toolTipDisplayTimeout = setTimeout(=>
window.protoRepl.executeCode("(proto-repl-sayid.core/node-tooltip-html #{d.id})",
displayInRepl: false
resultHandler: (result, options)=>
if result.error
console.error result.error
atom.notifications.addError "Unable to retrieve tooltip display info. See console error message", dismissable: true
else
text = result.value
text = text.substring(1, text.length-1)
text = text + " <p>Double click show full details inline</p>"
@displayToolTip(text, x, y)
)
, 200)
# Displays a tooltip with the given html at position x,y
displayToolTip: (html, x, y)->
@tooltipDiv.transition()
.duration(100)
.style("opacity", 0.9)
@tooltipDiv.html(html)
.style("left", x + "px")
.style("top", (y + 28) + "px")
# Hides a currently displayed tooltip
hideToolTip: ()->
if @toolTipDisplayTimeout
clearTimeout(@toolTipDisplayTimeout)
@toolTipDisplayTimeout = null
@tooltipDiv.transition()
.duration(500)
.style("opacity", 0)
# Main handler of D3-afication of nodes. Takes a data node and adds it to
# the displayed set of data. Can be used to update what's currently displayed
# if the current state has changed to collapse or expand a node.
updateNode: (source)->
# Compute the new height, function counts total children of root node and sets tree height accordingly.
# This prevents the layout looking squashed when new nodes are made visible or looking sparse when nodes are removed
# This makes the layout more consistent.
levelWidth = [1]
childCount = (level, n)->
if n.children && n.children.length > 0
if levelWidth.length <= level + 1 then levelWidth.push(0)
levelWidth[level + 1] += n.children.length
n.children.forEach((d)-> childCount(level + 1, d))
childCount(0, @root)
newHeight = d3.max(levelWidth) * 25 # 25 pixels per line
@tree = @tree.size([newHeight, @viewerWidth])
# Compute the new tree layout.
nodes = @tree.nodes(@root).reverse()
links = @tree.links(nodes)
# Set widths between levels based on maxLabelLength.
nodes.forEach((d)=>d.y = (d.depth * (@maxLabelLength * 10)))
# Update the nodes…
node = @svgGroup.selectAll("g.node").data(nodes, (d)=> d.id || (d.id = ++@nextNodeId))
# Enter any new nodes at the parent's previous position.
nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform",(d)->
"translate(" + source.y0 + "," + source.x0 + ")"
)
nodeEnter.append("circle")
.attr('class', 'nodeCircle')
.attr("r", 0)
.style("fill", (d)->
if d._children then "lightsteelblue" else "#fff"
)
.on('click', (d)=>@handleNodeClick(d))
nodeEnter.append("text")
.attr("x", (d)->
if d.children || d._children then -10 else 10
)
.attr("dy", ".35em")
.attr('class', 'nodeText')
.attr("text-anchor", (d)->
if d.children || d._children then "end" else "start"
)
.text((d)->d.name)
.style("fill-opacity", 0)
.on("mouseover", (d)=>@handleMouseOver(d))
.on("mouseout", (d)=>@hideToolTip(d))
.on("dblclick", (d)=>
d3.event.stopPropagation()
@displayNodeInlineData(d.id)
)
# phantom node to give us mouseover in a radius around it
nodeEnter.append("circle")
.attr('class', 'ghostCircle')
.attr("r", 30)
.attr("opacity", 0.2) # change this to zero to hide the target area
.style("fill", "red")
.attr('pointer-events', 'mouseover')
# Update the text to reflect whether node has children or not.
node.select('text')
.attr("x", (d)->
if d.children || d._children then -10 else 10
)
.attr("text-anchor", (d)->
if d.children || d._children then "end" else "start"
)
.text((d)->d.name)
# Change the circle fill depending on whether it has children and is collapsed
node.select("circle.nodeCircle")
.attr("r", 4.5)
.style("fill", (d)->
if d._children then "lightsteelblue" else "#fff"
)
# Transition nodes to their new position.
nodeUpdate = node.transition()
.duration(NODE_TRANSITION_DURATION)
.attr("transform", (d)->
"translate(" + d.y + "," + d.x + ")"
)
# Fade the text in
nodeUpdate.select("text")
.style("fill-opacity", 1)
# Transition exiting nodes to the parent's new position.
nodeExit = node.exit().transition()
.duration(NODE_TRANSITION_DURATION)
.attr("transform", (d)->
"translate(" + source.y + "," + source.x + ")"
)
.remove()
nodeExit.select("circle")
.attr("r", 0)
nodeExit.select("text")
.style("fill-opacity", 0)
# Update the links…
link = @svgGroup.selectAll("path.link")
.data(links, (d)->d.target.id)
# Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", (d)=>
o = {
x: source.x0,
y: source.y0
}
@diagonalProjection({
source: o,
target: o
})
)
# Transition links to their new position.
link.transition()
.duration(NODE_TRANSITION_DURATION)
.attr("d", @diagonalProjection)
# Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(NODE_TRANSITION_DURATION)
.attr("d", (d)=>
o = {
x: source.x,
y: source.y
}
@diagonalProjection({
source: o,
target: o
})
)
.remove()
#
# # Stash the old positions for transition.
nodes.forEach((d)->
d.x0 = d.x
d.y0 = d.y
)
getTitle: ->
NAME
| 67271 | # Based on http:#bl.ocks.org/robschmuecker/7880033 which has the following copyright
# Copyright (c) 2013-2016, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * The name <NAME> may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
{Range, Point} = require 'atom'
{$, $$$, ScrollView} = require 'atom-space-pen-views'
d3 = require 'd3'
# A recursive helper function for performing some setup by walking through all nodes
visit = (parent, visitFn, childrenFn)->
if !parent then return
visitFn(parent)
children = childrenFn(parent)
if children
for child in children
visit(child, visitFn, childrenFn)
PAN_SPEED = 200
# Within 20px from edges will pan when dragging.
PAN_BOUNDARY = 20
NODE_TRANSITION_DURATION = 750
# Truncates a string to the specified length if needed.
truncateToLength = (s, length)->
if s.length > length
s.substring(0, length-1) + "…"
else
s
# The maximum width of inline data on one row
MAX_INLINE_WIDTH = 60
# The string separating arguments from the return value for inline display
ARG_RETURN_SEP = " => "
# The maximum amount of space the arguments can take with summarized with return value
ARG_SUMMARY_WITH_RETURN_MAX_LENGTH = (MAX_INLINE_WIDTH - ARG_RETURN_SEP.length) * 0.75
PROTOCOL = "proto-repl-sayid:"
NAME = "Proto-REPL Sayid Call Graph"
module.exports =
class TreeView extends ScrollView
# The longest label for a node that was found.
maxLabelLength: null
# The root of the data tree
root: null
# The next id to assign to a node.
nextNodeId: 0
# The current width of the view
viewerWidth: null
#The current height of the view
viewerHeight: null
# An instance of a D3 tree layout
tree: null
# A div used to show the tool tip
tooltipDiv: null
# A timeout id used to set a timeout for delaying execution of code to get data for displaying the tooltip.
toolTipDisplayTimeout: null
# a d3 diagonal projection for use by the node paths
diagonalProjection: null
# The root svg group that holds everything. Used for zooming
svgGroup: null
# d3 zooming behavior
zoomListener: null
toolbar: null
# A map of strings to functions to call when the button is pressed.
toolBarButtonGroups: {}
atom.deserializers.add(this)
@content: ->
@div class: 'proto-repl-sayid-graph native-key-bindings', tabindex: -1
constructor: () ->
super
this
getURI: ->
"proto-repl-sayid://"
initiateView: (toolBarButtonGroups)->
@toolBarButtonGroups = toolBarButtonGroups
holderDiv = document.createElement("div")
@html $ holderDiv
d3HolderDiv = d3.select(holderDiv)
.attr("class", "sayid-holder")
# Add toolbar
@toolbar = d3HolderDiv.append("div")
.attr("class", "sayid-toolbar")
.append("div")
.attr("class", "bar")
.append("span")
.attr("class", "inline-block")
addButtonGroup = (buttons)=>
group = @toolbar.append("div").attr("class", "btn-group")
for button in buttons
btn = group.append("button")
if button.icon
if button.iconset
btn.attr("class", "btn #{button.iconset} #{button.iconset}-#{button.icon}")
.attr("alt", button.name)
else
btn.attr("class", "btn icon icon-#{button.icon}")
.attr("alt", button.name)
else
btn.attr("class", "btn")
btn.text(button.name)
btn.on("click", button.onClick)
for group in toolBarButtonGroups
addButtonGroup(group)
builtinGroup = []
builtinGroup.push(
name: "Expand",
icon: 'plus',
onClick: ()=>
if @root
@expand(@root)
@updateNode(@root)
@centerNode(@root)
)
builtinGroup.push(
name: "Collapse",
icon: "dash",
onClick: ()=>
if @root
@collapse(@root)
@updateNode(@root)
@centerNode(@root)
)
addButtonGroup builtinGroup
@graphDiv = d3HolderDiv.append("div")
.attr("class", "sayid-holder")
# size of the diagram
@viewerWidth = $(holderDiv).width()
@viewerHeight = $(holderDiv).height()
# Defines the arguments that were captured by sayid.
defArgsForNode: (id)->
window.protoRepl.executeCode "(proto-repl-sayid.core/def-args-for-node #{id})",
displayInRepl: false,
resultHandler: (result)->
if result.error
console.log result.error
atom.notifications.addError "Unable to define args for node. See Atom console for full error.", dismissable: true
# Creates an inline tree to display arguments and return values that were captured from the stack.
# Expected keys are file, line, args, return
# args is a map of argument name to edn value.
# argsSummary is a string summarization of the arguments
# returned is an edn value that was returned
inlineDataToTree: (id, {args, argsSummary, returned})->
topArgsSummary = truncateToLength(argsSummary, ARG_SUMMARY_WITH_RETURN_MAX_LENGTH)
topSummary = truncateToLength(topArgsSummary + ARG_RETURN_SEP + returned, MAX_INLINE_WIDTH)
# Create inline trees for each of the arguments.
argsInlineTrees = for argName, argValue of args
# Use Proto REPLs built in capability for this.
[summary, rest...] = window.protoRepl.ednToDisplayTree(argValue)
# Generate a new summary with the arg name.
summary = truncateToLength(argName + ": " + summary, MAX_INLINE_WIDTH)
[summary].concat(rest)
[returnedSummary, rest...] = window.protoRepl.ednToDisplayTree(returned)
returnedSummary = truncateToLength("Return: " + returnedSummary, MAX_INLINE_WIDTH)
returnedInlineTree = [returnedSummary].concat(rest)
# Defines button options to add a button that will define the arguments for a function.
defArgsButton =
button_text: "def",
button_class: "def-saved-var"
button_fn: ()=> @defArgsForNode(id)
[topSummary, {},
[truncateToLength("Args: " + argsSummary, MAX_INLINE_WIDTH), defArgsButton].concat(argsInlineTrees),
returnedInlineTree]
# Returns a promise that gets the data captured by sayid for a given node
# so it can be displayed as an inline tree.
fetchInlineData: (id)->
new Promise (resolve, reject)->
window.protoRepl.executeCode "(proto-repl-sayid.core/retrieve-node-inline-data #{id})",
displayInRepl: false,
resultHandler: (result)->
if result.error
reject(result.error)
else
resolve(window.protoRepl.parseEdn(result.value))
# Retrieves data from sayid for the node with the given id and displays an
# inline tree in the file where the function is located.
displayNodeInlineData: (id)->
@fetchInlineData(id).then((data)=>
inlineTree = @inlineDataToTree(id, data)
line = data.line - 1
range = new Range(new Point(line), new Point(line,Infinity))
textEditorPromise = atom.workspace.open(data.file, {initialLine: line, searchAllPanes: true})
textEditorPromise.then (editor)->
window.protoRepl.repl.displayInline(editor, range, inlineTree)
).catch((error)->
console.error(error)
atom.notifications.addError "Unable to retrieve node data. See Atom console for full error.", dismissable: true
)
# TODO After resize get the latest sizes for controlling zooming.
# Collapses all the nodes that are the children of the given node.
collapse: (d)->
if d.children
d._children = d.children
d._children.forEach (c)=>@collapse(c)
d.children = null
else if d._children
d._children.forEach (c)=>@collapse(c)
# Expands all the nodes that are the children of the given node.
expand: (d)->
if (d._children)
d.children = d._children
d.children.forEach (c)=>@expand(c)
d._children = null
else if d.children
d.children.forEach (c)=>@expand(c)
# Displays the sayid data in a D3 tree.
display: (treeData)->
@initiateView(@toolBarButtonGroups)
@maxLabelLength = 0
@root = null
@nextNodeId = 0
@tree = d3.layout.tree().size([@viewerHeight, @viewerWidth])
# Define the div for the tooltip
@tooltipDiv = @graphDiv.append("div")
.attr("class", "sayid-tooltip")
.style("opacity", 0);
# define a d3 diagonal projection for use by the node paths later on.
@diagonalProjection = d3.svg.diagonal().projection((d)-> [d.y, d.x])
# Fail out early but after GUI is setup if there is no data to display
if !treeData
atom.notifications.addWarning "No data was captured for display", dismissable: true
return
# Call visit function to establish maxLabelLength
visit(treeData, (d)=>
@nextNodeId++
@maxLabelLength = Math.max(d.name.length, @maxLabelLength)
, (d)-> if d.children && d.children.length > 0 then d.children else null)
# Define the zoom function for the zoomable tree
zoom = (d)=>
@svgGroup.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")")
# define the zoomListener which calls the zoom function on the "zoom" event constrained within the scaleExtents
@zoomListener = d3.behavior.zoom().scaleExtent([0.1, 3]).on("zoom", zoom)
baseSvg = @graphDiv.append("svg")
.attr("class", "sayid-overlay")
.call(@zoomListener)
# Append a group which holds all nodes and which the zoom Listener can act upon.
@svgGroup = baseSvg.append("g")
# Define the root
@root = treeData
@root.x0 = @viewerHeight / 4
@root.y0 = 0
# Layout the tree initially and center on the root node.
@updateNode(@root)
@centerNode(@root)
# Function to center node when clicked/dropped so node doesn't get lost when collapsing/moving with large amount of children.
centerNode: (source)->
scale = @zoomListener.scale()
x = -1 * source.y0
y = -1 * source.x0
x = x * scale + @viewerWidth / 4
y = y * scale + @viewerHeight / 2
d3.select('g').transition()
.duration(NODE_TRANSITION_DURATION)
.attr("transform", "translate(" + x + "," + y + ")scale(" + scale + ")")
@zoomListener.scale(scale)
@zoomListener.translate([x, y])
# Toggle children on click.
handleNodeClick: (d)->
if d3.event.defaultPrevented then return # click suppressed
if d.children
# Hide children
d._children = d.children
d.children = null
else if d._children
# Display children
d.children = d._children
d._children = null
@updateNode(d)
@centerNode(d)
# Handles a node mouse over event. Takes the node that was moused over.
handleMouseOver: (d)->
x = d3.event.layerX
y = d3.event.layerY
@toolTipDisplayTimeout = setTimeout(=>
window.protoRepl.executeCode("(proto-repl-sayid.core/node-tooltip-html #{d.id})",
displayInRepl: false
resultHandler: (result, options)=>
if result.error
console.error result.error
atom.notifications.addError "Unable to retrieve tooltip display info. See console error message", dismissable: true
else
text = result.value
text = text.substring(1, text.length-1)
text = text + " <p>Double click show full details inline</p>"
@displayToolTip(text, x, y)
)
, 200)
# Displays a tooltip with the given html at position x,y
displayToolTip: (html, x, y)->
@tooltipDiv.transition()
.duration(100)
.style("opacity", 0.9)
@tooltipDiv.html(html)
.style("left", x + "px")
.style("top", (y + 28) + "px")
# Hides a currently displayed tooltip
hideToolTip: ()->
if @toolTipDisplayTimeout
clearTimeout(@toolTipDisplayTimeout)
@toolTipDisplayTimeout = null
@tooltipDiv.transition()
.duration(500)
.style("opacity", 0)
# Main handler of D3-afication of nodes. Takes a data node and adds it to
# the displayed set of data. Can be used to update what's currently displayed
# if the current state has changed to collapse or expand a node.
updateNode: (source)->
# Compute the new height, function counts total children of root node and sets tree height accordingly.
# This prevents the layout looking squashed when new nodes are made visible or looking sparse when nodes are removed
# This makes the layout more consistent.
levelWidth = [1]
childCount = (level, n)->
if n.children && n.children.length > 0
if levelWidth.length <= level + 1 then levelWidth.push(0)
levelWidth[level + 1] += n.children.length
n.children.forEach((d)-> childCount(level + 1, d))
childCount(0, @root)
newHeight = d3.max(levelWidth) * 25 # 25 pixels per line
@tree = @tree.size([newHeight, @viewerWidth])
# Compute the new tree layout.
nodes = @tree.nodes(@root).reverse()
links = @tree.links(nodes)
# Set widths between levels based on maxLabelLength.
nodes.forEach((d)=>d.y = (d.depth * (@maxLabelLength * 10)))
# Update the nodes…
node = @svgGroup.selectAll("g.node").data(nodes, (d)=> d.id || (d.id = ++@nextNodeId))
# Enter any new nodes at the parent's previous position.
nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform",(d)->
"translate(" + source.y0 + "," + source.x0 + ")"
)
nodeEnter.append("circle")
.attr('class', 'nodeCircle')
.attr("r", 0)
.style("fill", (d)->
if d._children then "lightsteelblue" else "#fff"
)
.on('click', (d)=>@handleNodeClick(d))
nodeEnter.append("text")
.attr("x", (d)->
if d.children || d._children then -10 else 10
)
.attr("dy", ".35em")
.attr('class', 'nodeText')
.attr("text-anchor", (d)->
if d.children || d._children then "end" else "start"
)
.text((d)->d.name)
.style("fill-opacity", 0)
.on("mouseover", (d)=>@handleMouseOver(d))
.on("mouseout", (d)=>@hideToolTip(d))
.on("dblclick", (d)=>
d3.event.stopPropagation()
@displayNodeInlineData(d.id)
)
# phantom node to give us mouseover in a radius around it
nodeEnter.append("circle")
.attr('class', 'ghostCircle')
.attr("r", 30)
.attr("opacity", 0.2) # change this to zero to hide the target area
.style("fill", "red")
.attr('pointer-events', 'mouseover')
# Update the text to reflect whether node has children or not.
node.select('text')
.attr("x", (d)->
if d.children || d._children then -10 else 10
)
.attr("text-anchor", (d)->
if d.children || d._children then "end" else "start"
)
.text((d)->d.name)
# Change the circle fill depending on whether it has children and is collapsed
node.select("circle.nodeCircle")
.attr("r", 4.5)
.style("fill", (d)->
if d._children then "lightsteelblue" else "#fff"
)
# Transition nodes to their new position.
nodeUpdate = node.transition()
.duration(NODE_TRANSITION_DURATION)
.attr("transform", (d)->
"translate(" + d.y + "," + d.x + ")"
)
# Fade the text in
nodeUpdate.select("text")
.style("fill-opacity", 1)
# Transition exiting nodes to the parent's new position.
nodeExit = node.exit().transition()
.duration(NODE_TRANSITION_DURATION)
.attr("transform", (d)->
"translate(" + source.y + "," + source.x + ")"
)
.remove()
nodeExit.select("circle")
.attr("r", 0)
nodeExit.select("text")
.style("fill-opacity", 0)
# Update the links…
link = @svgGroup.selectAll("path.link")
.data(links, (d)->d.target.id)
# Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", (d)=>
o = {
x: source.x0,
y: source.y0
}
@diagonalProjection({
source: o,
target: o
})
)
# Transition links to their new position.
link.transition()
.duration(NODE_TRANSITION_DURATION)
.attr("d", @diagonalProjection)
# Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(NODE_TRANSITION_DURATION)
.attr("d", (d)=>
o = {
x: source.x,
y: source.y
}
@diagonalProjection({
source: o,
target: o
})
)
.remove()
#
# # Stash the old positions for transition.
nodes.forEach((d)->
d.x0 = d.x
d.y0 = d.y
)
getTitle: ->
NAME
| true | # Based on http:#bl.ocks.org/robschmuecker/7880033 which has the following copyright
# Copyright (c) 2013-2016, PI:NAME:<NAME>END_PI
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * The name PI:NAME:<NAME>END_PI may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
{Range, Point} = require 'atom'
{$, $$$, ScrollView} = require 'atom-space-pen-views'
d3 = require 'd3'
# A recursive helper function for performing some setup by walking through all nodes
visit = (parent, visitFn, childrenFn)->
if !parent then return
visitFn(parent)
children = childrenFn(parent)
if children
for child in children
visit(child, visitFn, childrenFn)
PAN_SPEED = 200
# Within 20px from edges will pan when dragging.
PAN_BOUNDARY = 20
NODE_TRANSITION_DURATION = 750
# Truncates a string to the specified length if needed.
truncateToLength = (s, length)->
if s.length > length
s.substring(0, length-1) + "…"
else
s
# The maximum width of inline data on one row
MAX_INLINE_WIDTH = 60
# The string separating arguments from the return value for inline display
ARG_RETURN_SEP = " => "
# The maximum amount of space the arguments can take with summarized with return value
ARG_SUMMARY_WITH_RETURN_MAX_LENGTH = (MAX_INLINE_WIDTH - ARG_RETURN_SEP.length) * 0.75
PROTOCOL = "proto-repl-sayid:"
NAME = "Proto-REPL Sayid Call Graph"
module.exports =
class TreeView extends ScrollView
# The longest label for a node that was found.
maxLabelLength: null
# The root of the data tree
root: null
# The next id to assign to a node.
nextNodeId: 0
# The current width of the view
viewerWidth: null
#The current height of the view
viewerHeight: null
# An instance of a D3 tree layout
tree: null
# A div used to show the tool tip
tooltipDiv: null
# A timeout id used to set a timeout for delaying execution of code to get data for displaying the tooltip.
toolTipDisplayTimeout: null
# a d3 diagonal projection for use by the node paths
diagonalProjection: null
# The root svg group that holds everything. Used for zooming
svgGroup: null
# d3 zooming behavior
zoomListener: null
toolbar: null
# A map of strings to functions to call when the button is pressed.
toolBarButtonGroups: {}
atom.deserializers.add(this)
@content: ->
@div class: 'proto-repl-sayid-graph native-key-bindings', tabindex: -1
constructor: () ->
super
this
getURI: ->
"proto-repl-sayid://"
initiateView: (toolBarButtonGroups)->
@toolBarButtonGroups = toolBarButtonGroups
holderDiv = document.createElement("div")
@html $ holderDiv
d3HolderDiv = d3.select(holderDiv)
.attr("class", "sayid-holder")
# Add toolbar
@toolbar = d3HolderDiv.append("div")
.attr("class", "sayid-toolbar")
.append("div")
.attr("class", "bar")
.append("span")
.attr("class", "inline-block")
addButtonGroup = (buttons)=>
group = @toolbar.append("div").attr("class", "btn-group")
for button in buttons
btn = group.append("button")
if button.icon
if button.iconset
btn.attr("class", "btn #{button.iconset} #{button.iconset}-#{button.icon}")
.attr("alt", button.name)
else
btn.attr("class", "btn icon icon-#{button.icon}")
.attr("alt", button.name)
else
btn.attr("class", "btn")
btn.text(button.name)
btn.on("click", button.onClick)
for group in toolBarButtonGroups
addButtonGroup(group)
builtinGroup = []
builtinGroup.push(
name: "Expand",
icon: 'plus',
onClick: ()=>
if @root
@expand(@root)
@updateNode(@root)
@centerNode(@root)
)
builtinGroup.push(
name: "Collapse",
icon: "dash",
onClick: ()=>
if @root
@collapse(@root)
@updateNode(@root)
@centerNode(@root)
)
addButtonGroup builtinGroup
@graphDiv = d3HolderDiv.append("div")
.attr("class", "sayid-holder")
# size of the diagram
@viewerWidth = $(holderDiv).width()
@viewerHeight = $(holderDiv).height()
# Defines the arguments that were captured by sayid.
defArgsForNode: (id)->
window.protoRepl.executeCode "(proto-repl-sayid.core/def-args-for-node #{id})",
displayInRepl: false,
resultHandler: (result)->
if result.error
console.log result.error
atom.notifications.addError "Unable to define args for node. See Atom console for full error.", dismissable: true
# Creates an inline tree to display arguments and return values that were captured from the stack.
# Expected keys are file, line, args, return
# args is a map of argument name to edn value.
# argsSummary is a string summarization of the arguments
# returned is an edn value that was returned
inlineDataToTree: (id, {args, argsSummary, returned})->
topArgsSummary = truncateToLength(argsSummary, ARG_SUMMARY_WITH_RETURN_MAX_LENGTH)
topSummary = truncateToLength(topArgsSummary + ARG_RETURN_SEP + returned, MAX_INLINE_WIDTH)
# Create inline trees for each of the arguments.
argsInlineTrees = for argName, argValue of args
# Use Proto REPLs built in capability for this.
[summary, rest...] = window.protoRepl.ednToDisplayTree(argValue)
# Generate a new summary with the arg name.
summary = truncateToLength(argName + ": " + summary, MAX_INLINE_WIDTH)
[summary].concat(rest)
[returnedSummary, rest...] = window.protoRepl.ednToDisplayTree(returned)
returnedSummary = truncateToLength("Return: " + returnedSummary, MAX_INLINE_WIDTH)
returnedInlineTree = [returnedSummary].concat(rest)
# Defines button options to add a button that will define the arguments for a function.
defArgsButton =
button_text: "def",
button_class: "def-saved-var"
button_fn: ()=> @defArgsForNode(id)
[topSummary, {},
[truncateToLength("Args: " + argsSummary, MAX_INLINE_WIDTH), defArgsButton].concat(argsInlineTrees),
returnedInlineTree]
# Returns a promise that gets the data captured by sayid for a given node
# so it can be displayed as an inline tree.
fetchInlineData: (id)->
new Promise (resolve, reject)->
window.protoRepl.executeCode "(proto-repl-sayid.core/retrieve-node-inline-data #{id})",
displayInRepl: false,
resultHandler: (result)->
if result.error
reject(result.error)
else
resolve(window.protoRepl.parseEdn(result.value))
# Retrieves data from sayid for the node with the given id and displays an
# inline tree in the file where the function is located.
displayNodeInlineData: (id)->
@fetchInlineData(id).then((data)=>
inlineTree = @inlineDataToTree(id, data)
line = data.line - 1
range = new Range(new Point(line), new Point(line,Infinity))
textEditorPromise = atom.workspace.open(data.file, {initialLine: line, searchAllPanes: true})
textEditorPromise.then (editor)->
window.protoRepl.repl.displayInline(editor, range, inlineTree)
).catch((error)->
console.error(error)
atom.notifications.addError "Unable to retrieve node data. See Atom console for full error.", dismissable: true
)
# TODO After resize get the latest sizes for controlling zooming.
# Collapses all the nodes that are the children of the given node.
collapse: (d)->
if d.children
d._children = d.children
d._children.forEach (c)=>@collapse(c)
d.children = null
else if d._children
d._children.forEach (c)=>@collapse(c)
# Expands all the nodes that are the children of the given node.
expand: (d)->
if (d._children)
d.children = d._children
d.children.forEach (c)=>@expand(c)
d._children = null
else if d.children
d.children.forEach (c)=>@expand(c)
# Displays the sayid data in a D3 tree.
display: (treeData)->
@initiateView(@toolBarButtonGroups)
@maxLabelLength = 0
@root = null
@nextNodeId = 0
@tree = d3.layout.tree().size([@viewerHeight, @viewerWidth])
# Define the div for the tooltip
@tooltipDiv = @graphDiv.append("div")
.attr("class", "sayid-tooltip")
.style("opacity", 0);
# define a d3 diagonal projection for use by the node paths later on.
@diagonalProjection = d3.svg.diagonal().projection((d)-> [d.y, d.x])
# Fail out early but after GUI is setup if there is no data to display
if !treeData
atom.notifications.addWarning "No data was captured for display", dismissable: true
return
# Call visit function to establish maxLabelLength
visit(treeData, (d)=>
@nextNodeId++
@maxLabelLength = Math.max(d.name.length, @maxLabelLength)
, (d)-> if d.children && d.children.length > 0 then d.children else null)
# Define the zoom function for the zoomable tree
zoom = (d)=>
@svgGroup.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")")
# define the zoomListener which calls the zoom function on the "zoom" event constrained within the scaleExtents
@zoomListener = d3.behavior.zoom().scaleExtent([0.1, 3]).on("zoom", zoom)
baseSvg = @graphDiv.append("svg")
.attr("class", "sayid-overlay")
.call(@zoomListener)
# Append a group which holds all nodes and which the zoom Listener can act upon.
@svgGroup = baseSvg.append("g")
# Define the root
@root = treeData
@root.x0 = @viewerHeight / 4
@root.y0 = 0
# Layout the tree initially and center on the root node.
@updateNode(@root)
@centerNode(@root)
# Function to center node when clicked/dropped so node doesn't get lost when collapsing/moving with large amount of children.
centerNode: (source)->
scale = @zoomListener.scale()
x = -1 * source.y0
y = -1 * source.x0
x = x * scale + @viewerWidth / 4
y = y * scale + @viewerHeight / 2
d3.select('g').transition()
.duration(NODE_TRANSITION_DURATION)
.attr("transform", "translate(" + x + "," + y + ")scale(" + scale + ")")
@zoomListener.scale(scale)
@zoomListener.translate([x, y])
# Toggle children on click.
handleNodeClick: (d)->
if d3.event.defaultPrevented then return # click suppressed
if d.children
# Hide children
d._children = d.children
d.children = null
else if d._children
# Display children
d.children = d._children
d._children = null
@updateNode(d)
@centerNode(d)
# Handles a node mouse over event. Takes the node that was moused over.
handleMouseOver: (d)->
x = d3.event.layerX
y = d3.event.layerY
@toolTipDisplayTimeout = setTimeout(=>
window.protoRepl.executeCode("(proto-repl-sayid.core/node-tooltip-html #{d.id})",
displayInRepl: false
resultHandler: (result, options)=>
if result.error
console.error result.error
atom.notifications.addError "Unable to retrieve tooltip display info. See console error message", dismissable: true
else
text = result.value
text = text.substring(1, text.length-1)
text = text + " <p>Double click show full details inline</p>"
@displayToolTip(text, x, y)
)
, 200)
# Displays a tooltip with the given html at position x,y
displayToolTip: (html, x, y)->
@tooltipDiv.transition()
.duration(100)
.style("opacity", 0.9)
@tooltipDiv.html(html)
.style("left", x + "px")
.style("top", (y + 28) + "px")
# Hides a currently displayed tooltip
hideToolTip: ()->
if @toolTipDisplayTimeout
clearTimeout(@toolTipDisplayTimeout)
@toolTipDisplayTimeout = null
@tooltipDiv.transition()
.duration(500)
.style("opacity", 0)
# Main handler of D3-afication of nodes. Takes a data node and adds it to
# the displayed set of data. Can be used to update what's currently displayed
# if the current state has changed to collapse or expand a node.
updateNode: (source)->
# Compute the new height, function counts total children of root node and sets tree height accordingly.
# This prevents the layout looking squashed when new nodes are made visible or looking sparse when nodes are removed
# This makes the layout more consistent.
levelWidth = [1]
childCount = (level, n)->
if n.children && n.children.length > 0
if levelWidth.length <= level + 1 then levelWidth.push(0)
levelWidth[level + 1] += n.children.length
n.children.forEach((d)-> childCount(level + 1, d))
childCount(0, @root)
newHeight = d3.max(levelWidth) * 25 # 25 pixels per line
@tree = @tree.size([newHeight, @viewerWidth])
# Compute the new tree layout.
nodes = @tree.nodes(@root).reverse()
links = @tree.links(nodes)
# Set widths between levels based on maxLabelLength.
nodes.forEach((d)=>d.y = (d.depth * (@maxLabelLength * 10)))
# Update the nodes…
node = @svgGroup.selectAll("g.node").data(nodes, (d)=> d.id || (d.id = ++@nextNodeId))
# Enter any new nodes at the parent's previous position.
nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform",(d)->
"translate(" + source.y0 + "," + source.x0 + ")"
)
nodeEnter.append("circle")
.attr('class', 'nodeCircle')
.attr("r", 0)
.style("fill", (d)->
if d._children then "lightsteelblue" else "#fff"
)
.on('click', (d)=>@handleNodeClick(d))
nodeEnter.append("text")
.attr("x", (d)->
if d.children || d._children then -10 else 10
)
.attr("dy", ".35em")
.attr('class', 'nodeText')
.attr("text-anchor", (d)->
if d.children || d._children then "end" else "start"
)
.text((d)->d.name)
.style("fill-opacity", 0)
.on("mouseover", (d)=>@handleMouseOver(d))
.on("mouseout", (d)=>@hideToolTip(d))
.on("dblclick", (d)=>
d3.event.stopPropagation()
@displayNodeInlineData(d.id)
)
# phantom node to give us mouseover in a radius around it
nodeEnter.append("circle")
.attr('class', 'ghostCircle')
.attr("r", 30)
.attr("opacity", 0.2) # change this to zero to hide the target area
.style("fill", "red")
.attr('pointer-events', 'mouseover')
# Update the text to reflect whether node has children or not.
node.select('text')
.attr("x", (d)->
if d.children || d._children then -10 else 10
)
.attr("text-anchor", (d)->
if d.children || d._children then "end" else "start"
)
.text((d)->d.name)
# Change the circle fill depending on whether it has children and is collapsed
node.select("circle.nodeCircle")
.attr("r", 4.5)
.style("fill", (d)->
if d._children then "lightsteelblue" else "#fff"
)
# Transition nodes to their new position.
nodeUpdate = node.transition()
.duration(NODE_TRANSITION_DURATION)
.attr("transform", (d)->
"translate(" + d.y + "," + d.x + ")"
)
# Fade the text in
nodeUpdate.select("text")
.style("fill-opacity", 1)
# Transition exiting nodes to the parent's new position.
nodeExit = node.exit().transition()
.duration(NODE_TRANSITION_DURATION)
.attr("transform", (d)->
"translate(" + source.y + "," + source.x + ")"
)
.remove()
nodeExit.select("circle")
.attr("r", 0)
nodeExit.select("text")
.style("fill-opacity", 0)
# Update the links…
link = @svgGroup.selectAll("path.link")
.data(links, (d)->d.target.id)
# Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", (d)=>
o = {
x: source.x0,
y: source.y0
}
@diagonalProjection({
source: o,
target: o
})
)
# Transition links to their new position.
link.transition()
.duration(NODE_TRANSITION_DURATION)
.attr("d", @diagonalProjection)
# Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(NODE_TRANSITION_DURATION)
.attr("d", (d)=>
o = {
x: source.x,
y: source.y
}
@diagonalProjection({
source: o,
target: o
})
)
.remove()
#
# # Stash the old positions for transition.
nodes.forEach((d)->
d.x0 = d.x
d.y0 = d.y
)
getTitle: ->
NAME
|
[
{
"context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje",
"end": 22,
"score": 0.9710984826087952,
"start": 16,
"tag": "NAME",
"value": "Konode"
}
] | src/colors.coffee | LogicalOutcomes/KoNote | 1 | # Copyright (c) Konode. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Standardized color hex definitions
# TODO: Generate these colors programatically
Imm = require 'immutable'
# Darker color spectrum for programs
ProgramColors = Imm.List [
"#cf1d1d"
"#cf1d5c"
"#cf1da7"
"#c51dcf"
"#7d1dcf"
"#3f1dcf"
"#1d4bcf"
"#1d92cf"
"#1dc0cf"
"#1dcfa3"
"#1dcf36"
"#86cf1d"
"#a3cf1d"
"#cfb41d"
"#e35c27"
"#cf691d"
]
# Brighter color spectrum for event types
EventTypeColors = Imm.List [
"#f06767"
"#f067a4"
"#f067db"
"#c467f0"
"#9167f0"
"#6777f0"
"#6794f0"
"#67b4f0"
"#67ebf0"
"#67f0cb"
"#67f06d"
"#97b45f"
"#d6d13f"
"#f0c867"
"#f0a167"
"#f08467"
]
# TODO: Metrics colors (#975)
module.exports = {
ProgramColors
EventTypeColors
} | 123963 | # Copyright (c) <NAME>. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Standardized color hex definitions
# TODO: Generate these colors programatically
Imm = require 'immutable'
# Darker color spectrum for programs
ProgramColors = Imm.List [
"#cf1d1d"
"#cf1d5c"
"#cf1da7"
"#c51dcf"
"#7d1dcf"
"#3f1dcf"
"#1d4bcf"
"#1d92cf"
"#1dc0cf"
"#1dcfa3"
"#1dcf36"
"#86cf1d"
"#a3cf1d"
"#cfb41d"
"#e35c27"
"#cf691d"
]
# Brighter color spectrum for event types
EventTypeColors = Imm.List [
"#f06767"
"#f067a4"
"#f067db"
"#c467f0"
"#9167f0"
"#6777f0"
"#6794f0"
"#67b4f0"
"#67ebf0"
"#67f0cb"
"#67f06d"
"#97b45f"
"#d6d13f"
"#f0c867"
"#f0a167"
"#f08467"
]
# TODO: Metrics colors (#975)
module.exports = {
ProgramColors
EventTypeColors
} | true | # Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Standardized color hex definitions
# TODO: Generate these colors programatically
Imm = require 'immutable'
# Darker color spectrum for programs
ProgramColors = Imm.List [
"#cf1d1d"
"#cf1d5c"
"#cf1da7"
"#c51dcf"
"#7d1dcf"
"#3f1dcf"
"#1d4bcf"
"#1d92cf"
"#1dc0cf"
"#1dcfa3"
"#1dcf36"
"#86cf1d"
"#a3cf1d"
"#cfb41d"
"#e35c27"
"#cf691d"
]
# Brighter color spectrum for event types
EventTypeColors = Imm.List [
"#f06767"
"#f067a4"
"#f067db"
"#c467f0"
"#9167f0"
"#6777f0"
"#6794f0"
"#67b4f0"
"#67ebf0"
"#67f0cb"
"#67f06d"
"#97b45f"
"#d6d13f"
"#f0c867"
"#f0a167"
"#f08467"
]
# TODO: Metrics colors (#975)
module.exports = {
ProgramColors
EventTypeColors
} |
[
{
"context": "omer'\n 'editCustomerLogin'\n ]}\n {id:2, name:\"This is the second one\", permissions:[\n 'editAdminL",
"end": 186,
"score": 0.8106033802032471,
"start": 182,
"tag": "NAME",
"value": "This"
},
{
"context": "Info'\n 'editCustomerLogin'\n ]}\n {id:3, name:\"... | resources/assets/js/admininfo/data/profiles.coffee | xavierauana/sbctemp | 0 | module.exports = [
{id:1, name:'1', permission:[
'readcustomerinfo'
'readadmininfo'
'editCustomerInfo'
'deleteCustomer'
'editCustomerLogin'
]}
{id:2, name:"This is the second one", permissions:[
'editAdminLogin'
'createNewCustomer'
'editCustomerInfo'
'editCustomerLogin'
]}
{id:3, name:"自定", permissions:[
'editDocumentType'
'uploadfile'
'editCustomerInfo'
'deleteAdmin'
'editCustomerLogin'
]}
] | 1028 | module.exports = [
{id:1, name:'1', permission:[
'readcustomerinfo'
'readadmininfo'
'editCustomerInfo'
'deleteCustomer'
'editCustomerLogin'
]}
{id:2, name:"<NAME> is the second one", permissions:[
'editAdminLogin'
'createNewCustomer'
'editCustomerInfo'
'editCustomerLogin'
]}
{id:3, name:"<NAME>定", permissions:[
'editDocumentType'
'uploadfile'
'editCustomerInfo'
'deleteAdmin'
'editCustomerLogin'
]}
] | true | module.exports = [
{id:1, name:'1', permission:[
'readcustomerinfo'
'readadmininfo'
'editCustomerInfo'
'deleteCustomer'
'editCustomerLogin'
]}
{id:2, name:"PI:NAME:<NAME>END_PI is the second one", permissions:[
'editAdminLogin'
'createNewCustomer'
'editCustomerInfo'
'editCustomerLogin'
]}
{id:3, name:"PI:NAME:<NAME>END_PI定", permissions:[
'editDocumentType'
'uploadfile'
'editCustomerInfo'
'deleteAdmin'
'editCustomerLogin'
]}
] |
[
{
"context": " ( done ) ->\n input._add [ {\n email: 'joe@example.com'\n login: 'joe'\n } ]\n \n mysq",
"end": 3023,
"score": 0.9999213814735413,
"start": 3008,
"tag": "EMAIL",
"value": "joe@example.com"
},
{
"context": "\n email: 'joe@example... | test/src/mysql.coffee | ReactiveSets/toubkal_mysql | 2 | ###
mysql.coffee
The MIT License (MIT)
Copyright (c) 2015, Reactive Sets
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.
###
# ----------------------------------------------------------------------------------------------
# rs test utils
# -------------
utils = require './tests_utils.js'
expect = utils.expect
check = utils.check
# ----------------------------------------------------------------------------------------------
# Require tested modules
# ----------------------
subclass = this.rs && this.rs.RS.subclass
rs = require 'toubkal'
require( '../../toubkal_mysql.js' )( rs )
RS = rs.RS
uuid_v4 = RS.uuid.v4
# ----------------------------------------------------------------------------------------------
# subclass test suite
# -------------------
describe 'mysql()', ->
input = null
users = null
mysql_users = null
joe = null
describe 'user table', ->
it 'should be a Pipelet', ->
input = rs.events_metadata() # add id as uuid_v4 and timestamp
users = input
.map( ( user ) -> {
id : user.id
email : user.email
login : user.login
create_time: user.create_time || user.timestamp
} )
.set []
mysql_users = users
.mysql(
'toubkal_unit_tests.user'
[
{ id: 'id', converter: 'uuid_b16' }
'email'
'login'
'create_time'
]
{
configuration:
if process.env.TRAVIS
then './test/fixtures/travis.config.json'
else null
}
)
expect( mysql_users ).to.be.a RS.Pipelet
it 'should be empty', ( done ) ->
mysql_users._fetch_all ( users ) ->
check done, () ->
expect( users ).to.be.eql []
it 'should allow to add one user', ( done ) ->
input._add [ {
email: 'joe@example.com'
login: 'joe'
} ]
mysql_users._fetch_all ( _users ) ->
check done, () ->
expect( _users.length ).to.be.eql 1
joe = _users[ 0 ]
expect( _users ).to.be.eql users._fetch_all()
it 'should allow to fetch a single user using a query', ( done ) ->
fetched = ( _users ) ->
check done, () ->
expect( _users.length ).to.be.eql 1
expect( _users ).to.be.eql users._fetch_all()
mysql_users._fetch_all fetched, [ { login: 'joe' } ]
it 'should ignore column in query not defined in schema', ( done ) ->
fetched = ( _users ) ->
check done, () ->
expect( _users.length ).to.be.eql 1
mysql_users._fetch_all fetched, [ { _login: 'joe' } ]
it 'should allow to update existing user', ( done ) ->
input._update [ [
joe
{
id : joe.id
email : 'joe@toubkal.rocks'
login : 'joe'
create_time: joe.create_time
}
] ]
mysql_users._fetch_all ( _users ) ->
check done, () ->
expect( _users.length ).to.be.eql 1
new_user = _users[ 0 ]
expect( new_user ).to.be.eql {
id : joe.id
email : 'joe@toubkal.rocks'
login : 'joe'
create_time: joe.create_time
}
joe = new_user
it 'should allow to remove previously added user', ( done ) ->
input._remove [ joe ]
mysql_users._fetch_all ( _users ) ->
check done, () ->
expect( _users.length ).to.be.eql 0
describe 'user and project table, with foreign key countraint', ->
it 'should create a project and a user', ( done ) ->
rs.Singleton( 'database', ( source, options ) ->
return source
.trace( "database in" )
.dispatch( [ { id: "users" }, { id: "projects" } ], ( source, options ) ->
if this.id == "users"
source
.flow( "users" )
.through( input )
mysql_users
.set_flow( "users" )
else
source
.flow( "projects" )
.mysql(
'toubkal_unit_tests.project'
[
{ id: 'id', converter: 'uuid_b16' }
{ id: 'creator_id', converter: 'uuid_b16' }
'name'
'create_time'
]
{
configuration:
if process.env.TRAVIS
then './test/fixtures/travis.config.json'
else null
}
)
.set_flow( "projects" )
)
)
jack = null
rs
.set( [ { name: "Great Project" } ] )
.events_metadata()
.map( ( project ) -> {
flow : "projects"
id : project.id
creator_id : project.creator_id
name : project.name
create_time: project.create_time || project.timestamp
} )
.fetch( mysql_users, ( project ) -> [ { id: project.creator_id } ] )
.map( ( fetched ) ->
operation = fetched.operation
user = fetched.values[ 0 ]
adds = []
if operation == "create"
unless user
user = jack = { flow: "users", id: uuid_v4(), email: "jack@example.com", login: "jack" }
fetched.source.creator_id = user.id
adds.push( user )
adds.push( fetched.source )
{ adds: adds }
)
.emit_operations()
.database()
rs
.once( 20 )
.fetch( rs.database() )
.map( ( fetched ) -> check done, () ->
fetched = fetched.values
expect( fetched ).to.be.eql [
{
flow : "users"
id : jack.id
email : "jack@example.com"
login : "jack"
create_time: fetched[ 0 ].create_time
}
{
flow : "projects"
id : fetched[ 1 ].id
creator_id : jack.id
name : "Great Project"
create_time: fetched[ 1 ].create_time
}
]
)
it 'should remove a project and a user', ( done ) ->
rs
.database()
.greedy()
._output
.once( 'remove', () ->
rs
.once()
.fetch( rs.database() )
.alter( ( fetched ) -> check done, () ->
expect( fetched.values ).to.be.eql []
)
)
rs
.once()
.fetch( rs.database() )
.map( ( fetched ) ->
fetched = fetched.values
{ removes: [ fetched[ 1 ], fetched[ 0 ] ] }
)
.emit_operations()
.database()
describe 'Using spatial geometry fields, WKT geometry', ->
paris = null
cities_wkt_output = null
it 'should allow to add Paris in cities_wkt', ( done ) ->
cities_wkt_output = rs
.Singleton( 'cities_wkt', ( source, options ) ->
return source
.flow( 'cities_wkt' )
.mysql(
'toubkal_unit_tests.cities'
[
{ id: 'id', converter: 'uuid_b16' }
'name'
{ id: 'geometry', converter: 'wkt' }
'create_time'
]
{
configuration:
if process.env.TRAVIS
then './test/fixtures/travis.config.json'
else null
}
)
.set_flow( 'cities_wkt' )
)
.cities_wkt()
.greedy()
._output
;
cities_wkt_output.once( "add", ( values ) -> check done, () ->
expect( values.length ).to.be 1
value = values[ 0 ]
expect( value ).to.be.eql paris
)
rs
.once()
.map( ( _ ) -> paris = {
flow: "cities_wkt"
id: uuid_v4()
name: "Paris"
geometry: "POINT( 2.349014 48.864716 )"
create_time: new Date()
} )
.cities_wkt()
;
it "should allow to fetch a city using ST_Distance_Sphere() and 'ST_GeomFromPoint', 2, 48", ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [
'ST_Distance_Sphere', [], [
'ST_GeomFromPoint', 2, 48
], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
'POINT(2.349014 48.864716)'
)
)
;
it "should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromText, 'POINT( 2 48 )', 4326", ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [
[ 'ST_Distance_Sphere', [
'ST_GeomFromText', 'POINT( 2 48 )', 4326
] ], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
'POINT(2.349014 48.864716)'
)
)
;
it "should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromText, 'POINT( 2 48 )' with default 4326 SRID", ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [
'ST_Distance_Sphere', [
'ST_GeomFromText', 'POINT( 2 48 )'
], [], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
'POINT(2.349014 48.864716)'
)
)
;
it 'should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromGeoJSON()', ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [ "$", 200000, ">=",
[ 'ST_Distance_Sphere', [
'ST_GeomFromGeoJSON', { type: "Point", coordinates: [ 2, 48 ] }
] ]
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
'POINT(2.349014 48.864716)'
)
)
;
it 'should fetch no city if distance is too small using ST_Distance_Sphere() and ST_GeomFromGeoJSON()', ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [ "$", 20000, ">=",
[ 'ST_Distance_Sphere', [
'ST_GeomFromGeoJSON', { type: "Point", coordinates: [ 2, 48 ] }
] ]
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
expect( fetched_values.length ).to.be 0
)
;
it 'should allow to remove the city of Paris', ( done ) ->
cities_wkt_output.once( "remove", ( values ) -> check done, () ->
expect( values.length ).to.be 1
expect( values[ 0 ] ).to.be.eql paris
)
rs
.once()
.map ( _ ) -> paris
.revert()
.cities_wkt()
;
describe 'Using spatial geometry fields, GeoJSON geometry', ->
paris = null
cities_geo_json_output = null
it 'should allow to add Paris in cities_geo_json', ( done ) ->
cities_geo_json_output = rs
.Singleton( 'cities_geo_json', ( source, options ) ->
return source
.flow( 'cities_geo_json' )
.mysql(
'toubkal_unit_tests.cities'
[
{ id: 'id', converter: 'uuid_b16' }
'name'
{ id: 'geometry', converter: 'geo_json' }
'create_time'
]
{
configuration:
if process.env.TRAVIS
then './test/fixtures/travis.config.json'
else null
}
)
.set_flow( 'cities_geo_json' )
)
.cities_geo_json()
.greedy()
._output
;
cities_geo_json_output.once( "add", ( values ) -> check done, () ->
expect( values.length ).to.be 1
value = values[ 0 ]
expect( value ).to.be.eql paris
)
rs
.once()
.map( ( _ ) -> paris = {
flow: "cities_geo_json"
id: uuid_v4()
name: "Paris"
geometry: { type: 'Point', coordinates: [ 2.349014, 48.864716 ] }
create_time: new Date()
} )
.cities_geo_json()
;
it "should allow to fetch a city using ST_Distance_Sphere() and 'ST_GeomFromPoint', 2, 48", ( done ) ->
rs
.once()
.fetch( rs.cities_geo_json(), () ->
[ { geometry: [
'ST_Distance_Sphere', [], [
'ST_GeomFromPoint', 2, 48
], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
{ type: 'Point', coordinates: [ 2.349014, 48.864716 ] }
)
)
;
it "should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromText, 'POINT( 2 48 )', 4326", ( done ) ->
rs
.once()
.fetch( rs.cities_geo_json(), () ->
[ { geometry: [
[ 'ST_Distance_Sphere', [
'ST_GeomFromText', 'POINT( 2 48 )', 4326
] ], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
{ type: 'Point', coordinates: [ 2.349014, 48.864716 ] }
)
)
;
it "should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromText, 'POINT( 2 48 )' with default 4326 SRID", ( done ) ->
rs
.once()
.fetch( rs.cities_geo_json(), () ->
[ { geometry: [
'ST_Distance_Sphere', [
'ST_GeomFromText', 'POINT( 2 48 )'
], [], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
{ type: 'Point', coordinates: [ 2.349014, 48.864716 ] }
)
)
;
it 'should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromGeoJSON()', ( done ) ->
rs
.once()
.fetch( rs.cities_geo_json(), () ->
[ { geometry: [ "$", 200000, ">=",
[ 'ST_Distance_Sphere', [
'ST_GeomFromGeoJSON', { type: "Point", coordinates: [ 2, 48 ] }
] ]
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
{ type: 'Point', coordinates: [ 2.349014, 48.864716 ] }
)
)
;
it 'should fetch no city if distance is too small using ST_Distance_Sphere() and ST_GeomFromGeoJSON()', ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [ "$", 20000, ">=",
[ 'ST_Distance_Sphere', [
'ST_GeomFromGeoJSON', { type: "Point", coordinates: [ 2, 48 ] }
] ]
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
expect( fetched_values.length ).to.be 0
)
;
it 'should allow to remove the city of Paris', ( done ) ->
cities_geo_json_output.once( "remove", ( values ) -> check done, () ->
expect( values.length ).to.be 1
expect( values[ 0 ] ).to.be.eql paris
)
rs
.once()
.map ( _ ) -> paris
.revert()
.cities_geo_json()
;
| 101520 | ###
mysql.coffee
The MIT License (MIT)
Copyright (c) 2015, Reactive Sets
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.
###
# ----------------------------------------------------------------------------------------------
# rs test utils
# -------------
utils = require './tests_utils.js'
expect = utils.expect
check = utils.check
# ----------------------------------------------------------------------------------------------
# Require tested modules
# ----------------------
subclass = this.rs && this.rs.RS.subclass
rs = require 'toubkal'
require( '../../toubkal_mysql.js' )( rs )
RS = rs.RS
uuid_v4 = RS.uuid.v4
# ----------------------------------------------------------------------------------------------
# subclass test suite
# -------------------
describe 'mysql()', ->
input = null
users = null
mysql_users = null
joe = null
describe 'user table', ->
it 'should be a Pipelet', ->
input = rs.events_metadata() # add id as uuid_v4 and timestamp
users = input
.map( ( user ) -> {
id : user.id
email : user.email
login : user.login
create_time: user.create_time || user.timestamp
} )
.set []
mysql_users = users
.mysql(
'toubkal_unit_tests.user'
[
{ id: 'id', converter: 'uuid_b16' }
'email'
'login'
'create_time'
]
{
configuration:
if process.env.TRAVIS
then './test/fixtures/travis.config.json'
else null
}
)
expect( mysql_users ).to.be.a RS.Pipelet
it 'should be empty', ( done ) ->
mysql_users._fetch_all ( users ) ->
check done, () ->
expect( users ).to.be.eql []
it 'should allow to add one user', ( done ) ->
input._add [ {
email: '<EMAIL>'
login: 'joe'
} ]
mysql_users._fetch_all ( _users ) ->
check done, () ->
expect( _users.length ).to.be.eql 1
joe = _users[ 0 ]
expect( _users ).to.be.eql users._fetch_all()
it 'should allow to fetch a single user using a query', ( done ) ->
fetched = ( _users ) ->
check done, () ->
expect( _users.length ).to.be.eql 1
expect( _users ).to.be.eql users._fetch_all()
mysql_users._fetch_all fetched, [ { login: 'jo<NAME>' } ]
it 'should ignore column in query not defined in schema', ( done ) ->
fetched = ( _users ) ->
check done, () ->
expect( _users.length ).to.be.eql 1
mysql_users._fetch_all fetched, [ { _login: 'jo<NAME>' } ]
it 'should allow to update existing user', ( done ) ->
input._update [ [
joe
{
id : joe.id
email : '<EMAIL>'
login : 'joe'
create_time: joe.create_time
}
] ]
mysql_users._fetch_all ( _users ) ->
check done, () ->
expect( _users.length ).to.be.eql 1
new_user = _users[ 0 ]
expect( new_user ).to.be.eql {
id : joe.id
email : '<EMAIL>'
login : 'joe'
create_time: joe.create_time
}
joe = new_user
it 'should allow to remove previously added user', ( done ) ->
input._remove [ joe ]
mysql_users._fetch_all ( _users ) ->
check done, () ->
expect( _users.length ).to.be.eql 0
describe 'user and project table, with foreign key countraint', ->
it 'should create a project and a user', ( done ) ->
rs.Singleton( 'database', ( source, options ) ->
return source
.trace( "database in" )
.dispatch( [ { id: "users" }, { id: "projects" } ], ( source, options ) ->
if this.id == "users"
source
.flow( "users" )
.through( input )
mysql_users
.set_flow( "users" )
else
source
.flow( "projects" )
.mysql(
'toubkal_unit_tests.project'
[
{ id: 'id', converter: 'uuid_b16' }
{ id: 'creator_id', converter: 'uuid_b16' }
'name'
'create_time'
]
{
configuration:
if process.env.TRAVIS
then './test/fixtures/travis.config.json'
else null
}
)
.set_flow( "projects" )
)
)
jack = null
rs
.set( [ { name: "Great Project" } ] )
.events_metadata()
.map( ( project ) -> {
flow : "projects"
id : project.id
creator_id : project.creator_id
name : project.name
create_time: project.create_time || project.timestamp
} )
.fetch( mysql_users, ( project ) -> [ { id: project.creator_id } ] )
.map( ( fetched ) ->
operation = fetched.operation
user = fetched.values[ 0 ]
adds = []
if operation == "create"
unless user
user = jack = { flow: "users", id: uuid_v4(), email: "<EMAIL>", login: "jack" }
fetched.source.creator_id = user.id
adds.push( user )
adds.push( fetched.source )
{ adds: adds }
)
.emit_operations()
.database()
rs
.once( 20 )
.fetch( rs.database() )
.map( ( fetched ) -> check done, () ->
fetched = fetched.values
expect( fetched ).to.be.eql [
{
flow : "users"
id : j<NAME>.id
email : "<EMAIL>"
login : "jack"
create_time: fetched[ 0 ].create_time
}
{
flow : "projects"
id : fetched[ 1 ].id
creator_id : <NAME>.id
name : "Great Project"
create_time: fetched[ 1 ].create_time
}
]
)
it 'should remove a project and a user', ( done ) ->
rs
.database()
.greedy()
._output
.once( 'remove', () ->
rs
.once()
.fetch( rs.database() )
.alter( ( fetched ) -> check done, () ->
expect( fetched.values ).to.be.eql []
)
)
rs
.once()
.fetch( rs.database() )
.map( ( fetched ) ->
fetched = fetched.values
{ removes: [ fetched[ 1 ], fetched[ 0 ] ] }
)
.emit_operations()
.database()
describe 'Using spatial geometry fields, WKT geometry', ->
paris = null
cities_wkt_output = null
it 'should allow to add Paris in cities_wkt', ( done ) ->
cities_wkt_output = rs
.Singleton( 'cities_wkt', ( source, options ) ->
return source
.flow( 'cities_wkt' )
.mysql(
'toubkal_unit_tests.cities'
[
{ id: 'id', converter: 'uuid_b16' }
'name'
{ id: 'geometry', converter: 'wkt' }
'create_time'
]
{
configuration:
if process.env.TRAVIS
then './test/fixtures/travis.config.json'
else null
}
)
.set_flow( 'cities_wkt' )
)
.cities_wkt()
.greedy()
._output
;
cities_wkt_output.once( "add", ( values ) -> check done, () ->
expect( values.length ).to.be 1
value = values[ 0 ]
expect( value ).to.be.eql paris
)
rs
.once()
.map( ( _ ) -> paris = {
flow: "cities_wkt"
id: uuid_v4()
name: "<NAME>"
geometry: "POINT( 2.349014 48.864716 )"
create_time: new Date()
} )
.cities_wkt()
;
it "should allow to fetch a city using ST_Distance_Sphere() and 'ST_GeomFromPoint', 2, 48", ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [
'ST_Distance_Sphere', [], [
'ST_GeomFromPoint', 2, 48
], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
'POINT(2.349014 48.864716)'
)
)
;
it "should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromText, 'POINT( 2 48 )', 4326", ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [
[ 'ST_Distance_Sphere', [
'ST_GeomFromText', 'POINT( 2 48 )', 4326
] ], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
'POINT(2.349014 48.864716)'
)
)
;
it "should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromText, 'POINT( 2 48 )' with default 4326 SRID", ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [
'ST_Distance_Sphere', [
'ST_GeomFromText', 'POINT( 2 48 )'
], [], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
'POINT(2.349014 48.864716)'
)
)
;
it 'should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromGeoJSON()', ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [ "$", 200000, ">=",
[ 'ST_Distance_Sphere', [
'ST_GeomFromGeoJSON', { type: "Point", coordinates: [ 2, 48 ] }
] ]
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
'POINT(2.349014 48.864716)'
)
)
;
it 'should fetch no city if distance is too small using ST_Distance_Sphere() and ST_GeomFromGeoJSON()', ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [ "$", 20000, ">=",
[ 'ST_Distance_Sphere', [
'ST_GeomFromGeoJSON', { type: "Point", coordinates: [ 2, 48 ] }
] ]
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
expect( fetched_values.length ).to.be 0
)
;
it 'should allow to remove the city of Paris', ( done ) ->
cities_wkt_output.once( "remove", ( values ) -> check done, () ->
expect( values.length ).to.be 1
expect( values[ 0 ] ).to.be.eql paris
)
rs
.once()
.map ( _ ) -> paris
.revert()
.cities_wkt()
;
describe 'Using spatial geometry fields, GeoJSON geometry', ->
paris = null
cities_geo_json_output = null
it 'should allow to add Paris in cities_geo_json', ( done ) ->
cities_geo_json_output = rs
.Singleton( 'cities_geo_json', ( source, options ) ->
return source
.flow( 'cities_geo_json' )
.mysql(
'toubkal_unit_tests.cities'
[
{ id: 'id', converter: 'uuid_b16' }
'name'
{ id: 'geometry', converter: 'geo_json' }
'create_time'
]
{
configuration:
if process.env.TRAVIS
then './test/fixtures/travis.config.json'
else null
}
)
.set_flow( 'cities_geo_json' )
)
.cities_geo_json()
.greedy()
._output
;
cities_geo_json_output.once( "add", ( values ) -> check done, () ->
expect( values.length ).to.be 1
value = values[ 0 ]
expect( value ).to.be.eql paris
)
rs
.once()
.map( ( _ ) -> paris = {
flow: "cities_geo_json"
id: uuid_v4()
name: "<NAME>"
geometry: { type: 'Point', coordinates: [ 2.349014, 48.864716 ] }
create_time: new Date()
} )
.cities_geo_json()
;
it "should allow to fetch a city using ST_Distance_Sphere() and 'ST_GeomFromPoint', 2, 48", ( done ) ->
rs
.once()
.fetch( rs.cities_geo_json(), () ->
[ { geometry: [
'ST_Distance_Sphere', [], [
'ST_GeomFromPoint', 2, 48
], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
{ type: 'Point', coordinates: [ 2.349014, 48.864716 ] }
)
)
;
it "should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromText, 'POINT( 2 48 )', 4326", ( done ) ->
rs
.once()
.fetch( rs.cities_geo_json(), () ->
[ { geometry: [
[ 'ST_Distance_Sphere', [
'ST_GeomFromText', 'POINT( 2 48 )', 4326
] ], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
{ type: 'Point', coordinates: [ 2.349014, 48.864716 ] }
)
)
;
it "should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromText, 'POINT( 2 48 )' with default 4326 SRID", ( done ) ->
rs
.once()
.fetch( rs.cities_geo_json(), () ->
[ { geometry: [
'ST_Distance_Sphere', [
'ST_GeomFromText', 'POINT( 2 48 )'
], [], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
{ type: 'Point', coordinates: [ 2.349014, 48.864716 ] }
)
)
;
it 'should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromGeoJSON()', ( done ) ->
rs
.once()
.fetch( rs.cities_geo_json(), () ->
[ { geometry: [ "$", 200000, ">=",
[ 'ST_Distance_Sphere', [
'ST_GeomFromGeoJSON', { type: "Point", coordinates: [ 2, 48 ] }
] ]
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
{ type: 'Point', coordinates: [ 2.349014, 48.864716 ] }
)
)
;
it 'should fetch no city if distance is too small using ST_Distance_Sphere() and ST_GeomFromGeoJSON()', ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [ "$", 20000, ">=",
[ 'ST_Distance_Sphere', [
'ST_GeomFromGeoJSON', { type: "Point", coordinates: [ 2, 48 ] }
] ]
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
expect( fetched_values.length ).to.be 0
)
;
it 'should allow to remove the city of Paris', ( done ) ->
cities_geo_json_output.once( "remove", ( values ) -> check done, () ->
expect( values.length ).to.be 1
expect( values[ 0 ] ).to.be.eql paris
)
rs
.once()
.map ( _ ) -> paris
.revert()
.cities_geo_json()
;
| true | ###
mysql.coffee
The MIT License (MIT)
Copyright (c) 2015, Reactive Sets
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.
###
# ----------------------------------------------------------------------------------------------
# rs test utils
# -------------
utils = require './tests_utils.js'
expect = utils.expect
check = utils.check
# ----------------------------------------------------------------------------------------------
# Require tested modules
# ----------------------
subclass = this.rs && this.rs.RS.subclass
rs = require 'toubkal'
require( '../../toubkal_mysql.js' )( rs )
RS = rs.RS
uuid_v4 = RS.uuid.v4
# ----------------------------------------------------------------------------------------------
# subclass test suite
# -------------------
describe 'mysql()', ->
input = null
users = null
mysql_users = null
joe = null
describe 'user table', ->
it 'should be a Pipelet', ->
input = rs.events_metadata() # add id as uuid_v4 and timestamp
users = input
.map( ( user ) -> {
id : user.id
email : user.email
login : user.login
create_time: user.create_time || user.timestamp
} )
.set []
mysql_users = users
.mysql(
'toubkal_unit_tests.user'
[
{ id: 'id', converter: 'uuid_b16' }
'email'
'login'
'create_time'
]
{
configuration:
if process.env.TRAVIS
then './test/fixtures/travis.config.json'
else null
}
)
expect( mysql_users ).to.be.a RS.Pipelet
it 'should be empty', ( done ) ->
mysql_users._fetch_all ( users ) ->
check done, () ->
expect( users ).to.be.eql []
it 'should allow to add one user', ( done ) ->
input._add [ {
email: 'PI:EMAIL:<EMAIL>END_PI'
login: 'joe'
} ]
mysql_users._fetch_all ( _users ) ->
check done, () ->
expect( _users.length ).to.be.eql 1
joe = _users[ 0 ]
expect( _users ).to.be.eql users._fetch_all()
it 'should allow to fetch a single user using a query', ( done ) ->
fetched = ( _users ) ->
check done, () ->
expect( _users.length ).to.be.eql 1
expect( _users ).to.be.eql users._fetch_all()
mysql_users._fetch_all fetched, [ { login: 'joPI:NAME:<NAME>END_PI' } ]
it 'should ignore column in query not defined in schema', ( done ) ->
fetched = ( _users ) ->
check done, () ->
expect( _users.length ).to.be.eql 1
mysql_users._fetch_all fetched, [ { _login: 'joPI:NAME:<NAME>END_PI' } ]
it 'should allow to update existing user', ( done ) ->
input._update [ [
joe
{
id : joe.id
email : 'PI:EMAIL:<EMAIL>END_PI'
login : 'joe'
create_time: joe.create_time
}
] ]
mysql_users._fetch_all ( _users ) ->
check done, () ->
expect( _users.length ).to.be.eql 1
new_user = _users[ 0 ]
expect( new_user ).to.be.eql {
id : joe.id
email : 'PI:EMAIL:<EMAIL>END_PI'
login : 'joe'
create_time: joe.create_time
}
joe = new_user
it 'should allow to remove previously added user', ( done ) ->
input._remove [ joe ]
mysql_users._fetch_all ( _users ) ->
check done, () ->
expect( _users.length ).to.be.eql 0
describe 'user and project table, with foreign key countraint', ->
it 'should create a project and a user', ( done ) ->
rs.Singleton( 'database', ( source, options ) ->
return source
.trace( "database in" )
.dispatch( [ { id: "users" }, { id: "projects" } ], ( source, options ) ->
if this.id == "users"
source
.flow( "users" )
.through( input )
mysql_users
.set_flow( "users" )
else
source
.flow( "projects" )
.mysql(
'toubkal_unit_tests.project'
[
{ id: 'id', converter: 'uuid_b16' }
{ id: 'creator_id', converter: 'uuid_b16' }
'name'
'create_time'
]
{
configuration:
if process.env.TRAVIS
then './test/fixtures/travis.config.json'
else null
}
)
.set_flow( "projects" )
)
)
jack = null
rs
.set( [ { name: "Great Project" } ] )
.events_metadata()
.map( ( project ) -> {
flow : "projects"
id : project.id
creator_id : project.creator_id
name : project.name
create_time: project.create_time || project.timestamp
} )
.fetch( mysql_users, ( project ) -> [ { id: project.creator_id } ] )
.map( ( fetched ) ->
operation = fetched.operation
user = fetched.values[ 0 ]
adds = []
if operation == "create"
unless user
user = jack = { flow: "users", id: uuid_v4(), email: "PI:EMAIL:<EMAIL>END_PI", login: "jack" }
fetched.source.creator_id = user.id
adds.push( user )
adds.push( fetched.source )
{ adds: adds }
)
.emit_operations()
.database()
rs
.once( 20 )
.fetch( rs.database() )
.map( ( fetched ) -> check done, () ->
fetched = fetched.values
expect( fetched ).to.be.eql [
{
flow : "users"
id : jPI:NAME:<NAME>END_PI.id
email : "PI:EMAIL:<EMAIL>END_PI"
login : "jack"
create_time: fetched[ 0 ].create_time
}
{
flow : "projects"
id : fetched[ 1 ].id
creator_id : PI:NAME:<NAME>END_PI.id
name : "Great Project"
create_time: fetched[ 1 ].create_time
}
]
)
it 'should remove a project and a user', ( done ) ->
rs
.database()
.greedy()
._output
.once( 'remove', () ->
rs
.once()
.fetch( rs.database() )
.alter( ( fetched ) -> check done, () ->
expect( fetched.values ).to.be.eql []
)
)
rs
.once()
.fetch( rs.database() )
.map( ( fetched ) ->
fetched = fetched.values
{ removes: [ fetched[ 1 ], fetched[ 0 ] ] }
)
.emit_operations()
.database()
describe 'Using spatial geometry fields, WKT geometry', ->
paris = null
cities_wkt_output = null
it 'should allow to add Paris in cities_wkt', ( done ) ->
cities_wkt_output = rs
.Singleton( 'cities_wkt', ( source, options ) ->
return source
.flow( 'cities_wkt' )
.mysql(
'toubkal_unit_tests.cities'
[
{ id: 'id', converter: 'uuid_b16' }
'name'
{ id: 'geometry', converter: 'wkt' }
'create_time'
]
{
configuration:
if process.env.TRAVIS
then './test/fixtures/travis.config.json'
else null
}
)
.set_flow( 'cities_wkt' )
)
.cities_wkt()
.greedy()
._output
;
cities_wkt_output.once( "add", ( values ) -> check done, () ->
expect( values.length ).to.be 1
value = values[ 0 ]
expect( value ).to.be.eql paris
)
rs
.once()
.map( ( _ ) -> paris = {
flow: "cities_wkt"
id: uuid_v4()
name: "PI:NAME:<NAME>END_PI"
geometry: "POINT( 2.349014 48.864716 )"
create_time: new Date()
} )
.cities_wkt()
;
it "should allow to fetch a city using ST_Distance_Sphere() and 'ST_GeomFromPoint', 2, 48", ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [
'ST_Distance_Sphere', [], [
'ST_GeomFromPoint', 2, 48
], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
'POINT(2.349014 48.864716)'
)
)
;
it "should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromText, 'POINT( 2 48 )', 4326", ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [
[ 'ST_Distance_Sphere', [
'ST_GeomFromText', 'POINT( 2 48 )', 4326
] ], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
'POINT(2.349014 48.864716)'
)
)
;
it "should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromText, 'POINT( 2 48 )' with default 4326 SRID", ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [
'ST_Distance_Sphere', [
'ST_GeomFromText', 'POINT( 2 48 )'
], [], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
'POINT(2.349014 48.864716)'
)
)
;
it 'should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromGeoJSON()', ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [ "$", 200000, ">=",
[ 'ST_Distance_Sphere', [
'ST_GeomFromGeoJSON', { type: "Point", coordinates: [ 2, 48 ] }
] ]
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
'POINT(2.349014 48.864716)'
)
)
;
it 'should fetch no city if distance is too small using ST_Distance_Sphere() and ST_GeomFromGeoJSON()', ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [ "$", 20000, ">=",
[ 'ST_Distance_Sphere', [
'ST_GeomFromGeoJSON', { type: "Point", coordinates: [ 2, 48 ] }
] ]
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
expect( fetched_values.length ).to.be 0
)
;
it 'should allow to remove the city of Paris', ( done ) ->
cities_wkt_output.once( "remove", ( values ) -> check done, () ->
expect( values.length ).to.be 1
expect( values[ 0 ] ).to.be.eql paris
)
rs
.once()
.map ( _ ) -> paris
.revert()
.cities_wkt()
;
describe 'Using spatial geometry fields, GeoJSON geometry', ->
paris = null
cities_geo_json_output = null
it 'should allow to add Paris in cities_geo_json', ( done ) ->
cities_geo_json_output = rs
.Singleton( 'cities_geo_json', ( source, options ) ->
return source
.flow( 'cities_geo_json' )
.mysql(
'toubkal_unit_tests.cities'
[
{ id: 'id', converter: 'uuid_b16' }
'name'
{ id: 'geometry', converter: 'geo_json' }
'create_time'
]
{
configuration:
if process.env.TRAVIS
then './test/fixtures/travis.config.json'
else null
}
)
.set_flow( 'cities_geo_json' )
)
.cities_geo_json()
.greedy()
._output
;
cities_geo_json_output.once( "add", ( values ) -> check done, () ->
expect( values.length ).to.be 1
value = values[ 0 ]
expect( value ).to.be.eql paris
)
rs
.once()
.map( ( _ ) -> paris = {
flow: "cities_geo_json"
id: uuid_v4()
name: "PI:NAME:<NAME>END_PI"
geometry: { type: 'Point', coordinates: [ 2.349014, 48.864716 ] }
create_time: new Date()
} )
.cities_geo_json()
;
it "should allow to fetch a city using ST_Distance_Sphere() and 'ST_GeomFromPoint', 2, 48", ( done ) ->
rs
.once()
.fetch( rs.cities_geo_json(), () ->
[ { geometry: [
'ST_Distance_Sphere', [], [
'ST_GeomFromPoint', 2, 48
], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
{ type: 'Point', coordinates: [ 2.349014, 48.864716 ] }
)
)
;
it "should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromText, 'POINT( 2 48 )', 4326", ( done ) ->
rs
.once()
.fetch( rs.cities_geo_json(), () ->
[ { geometry: [
[ 'ST_Distance_Sphere', [
'ST_GeomFromText', 'POINT( 2 48 )', 4326
] ], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
{ type: 'Point', coordinates: [ 2.349014, 48.864716 ] }
)
)
;
it "should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromText, 'POINT( 2 48 )' with default 4326 SRID", ( done ) ->
rs
.once()
.fetch( rs.cities_geo_json(), () ->
[ { geometry: [
'ST_Distance_Sphere', [
'ST_GeomFromText', 'POINT( 2 48 )'
], [], '<=', 200000
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
{ type: 'Point', coordinates: [ 2.349014, 48.864716 ] }
)
)
;
it 'should allow to fetch a city using ST_Distance_Sphere() and ST_GeomFromGeoJSON()', ( done ) ->
rs
.once()
.fetch( rs.cities_geo_json(), () ->
[ { geometry: [ "$", 200000, ">=",
[ 'ST_Distance_Sphere', [
'ST_GeomFromGeoJSON', { type: "Point", coordinates: [ 2, 48 ] }
] ]
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
fetched_value = fetched_values[ 0 ]
expect( fetched_values.length ).to.be 1
expect( fetched_value.geometry ).to.be.eql(
{ type: 'Point', coordinates: [ 2.349014, 48.864716 ] }
)
)
;
it 'should fetch no city if distance is too small using ST_Distance_Sphere() and ST_GeomFromGeoJSON()', ( done ) ->
rs
.once()
.fetch( rs.cities_wkt(), () ->
[ { geometry: [ "$", 20000, ">=",
[ 'ST_Distance_Sphere', [
'ST_GeomFromGeoJSON', { type: "Point", coordinates: [ 2, 48 ] }
] ]
] } ]
)
._output.once( "add", ( values ) -> check done, () ->
fetched_values = values[ 0 ].values
expect( fetched_values.length ).to.be 0
)
;
it 'should allow to remove the city of Paris', ( done ) ->
cities_geo_json_output.once( "remove", ( values ) -> check done, () ->
expect( values.length ).to.be 1
expect( values[ 0 ] ).to.be.eql paris
)
rs
.once()
.map ( _ ) -> paris
.revert()
.cities_geo_json()
;
|
[
{
"context": "w Tests for class-methods-use-this rule.\n# @author Patrick Williams\n###\n\n'use strict'\n\n#-----------------------------",
"end": 86,
"score": 0.9994756579399109,
"start": 70,
"tag": "NAME",
"value": "Patrick Williams"
}
] | src/tests/rules/class-methods-use-this.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for class-methods-use-this rule.
# @author Patrick Williams
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/class-methods-use-this'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'class-methods-use-this', rule,
valid: [
code: '''
class A
constructor: ->
'''
,
code: '''
class A
foo: -> this
'''
,
code: '''
class A
foo: -> @
'''
,
code: '''
class A
foo: => @
'''
,
code: '''
class A
foo: -> this.bar = 'bar'
'''
,
code: '''
class A
foo: -> @bar = 'bar'
'''
,
code: '''
class A
foo: -> bar @
'''
,
code: '''
class A extends B
foo: -> super.foo()
'''
,
code: '''
class A
foo: -> return @ if yes
'''
,
code: '''
class A
@foo: ->
'''
,
code: 'a: ->'
,
code: '''
class A
foo: -> => @
'''
,
code: '''
class A
foo: -> this
bar: ->
'''
options: [exceptMethods: ['bar']]
]
invalid: [
code: '''
class A
foo: ->
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: =>
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: -> ###*this*###
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: ->
a = -> this
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: ->
a = ->
b = -> this
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: -> window.this
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: -> that.this = 'this'
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: -> => undefined
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: ->
bar: ->
'''
options: [exceptMethods: ['bar']]
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: ->
hasOwnProperty: ->
'''
options: [exceptMethods: ['foo']]
errors: [
type: 'FunctionExpression'
line: 3
column: 16
messageId: 'missingThis'
data: name: 'hasOwnProperty'
]
]
| 45917 | ###*
# @fileoverview Tests for class-methods-use-this rule.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/class-methods-use-this'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'class-methods-use-this', rule,
valid: [
code: '''
class A
constructor: ->
'''
,
code: '''
class A
foo: -> this
'''
,
code: '''
class A
foo: -> @
'''
,
code: '''
class A
foo: => @
'''
,
code: '''
class A
foo: -> this.bar = 'bar'
'''
,
code: '''
class A
foo: -> @bar = 'bar'
'''
,
code: '''
class A
foo: -> bar @
'''
,
code: '''
class A extends B
foo: -> super.foo()
'''
,
code: '''
class A
foo: -> return @ if yes
'''
,
code: '''
class A
@foo: ->
'''
,
code: 'a: ->'
,
code: '''
class A
foo: -> => @
'''
,
code: '''
class A
foo: -> this
bar: ->
'''
options: [exceptMethods: ['bar']]
]
invalid: [
code: '''
class A
foo: ->
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: =>
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: -> ###*this*###
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: ->
a = -> this
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: ->
a = ->
b = -> this
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: -> window.this
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: -> that.this = 'this'
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: -> => undefined
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: ->
bar: ->
'''
options: [exceptMethods: ['bar']]
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: ->
hasOwnProperty: ->
'''
options: [exceptMethods: ['foo']]
errors: [
type: 'FunctionExpression'
line: 3
column: 16
messageId: 'missingThis'
data: name: 'hasOwnProperty'
]
]
| true | ###*
# @fileoverview Tests for class-methods-use-this rule.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/class-methods-use-this'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'class-methods-use-this', rule,
valid: [
code: '''
class A
constructor: ->
'''
,
code: '''
class A
foo: -> this
'''
,
code: '''
class A
foo: -> @
'''
,
code: '''
class A
foo: => @
'''
,
code: '''
class A
foo: -> this.bar = 'bar'
'''
,
code: '''
class A
foo: -> @bar = 'bar'
'''
,
code: '''
class A
foo: -> bar @
'''
,
code: '''
class A extends B
foo: -> super.foo()
'''
,
code: '''
class A
foo: -> return @ if yes
'''
,
code: '''
class A
@foo: ->
'''
,
code: 'a: ->'
,
code: '''
class A
foo: -> => @
'''
,
code: '''
class A
foo: -> this
bar: ->
'''
options: [exceptMethods: ['bar']]
]
invalid: [
code: '''
class A
foo: ->
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: =>
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: -> ###*this*###
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: ->
a = -> this
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: ->
a = ->
b = -> this
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: -> window.this
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: -> that.this = 'this'
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: -> => undefined
'''
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: ->
bar: ->
'''
options: [exceptMethods: ['bar']]
errors: [
type: 'FunctionExpression'
line: 2
column: 5
messageId: 'missingThis'
data: name: 'foo'
]
,
code: '''
class A
foo: ->
hasOwnProperty: ->
'''
options: [exceptMethods: ['foo']]
errors: [
type: 'FunctionExpression'
line: 3
column: 16
messageId: 'missingThis'
data: name: 'hasOwnProperty'
]
]
|
[
{
"context": " @item =\n imageUrl: '/foo.jpg',\n name: 'Foo Bar',\n href: '/foo/bar'\n detail: 'Item Deta",
"end": 301,
"score": 0.9947234392166138,
"start": 294,
"tag": "NAME",
"value": "Foo Bar"
},
{
"context": " $('.current-item__name').text().should.eql '... | src/desktop/apps/artist/test/components/current_show_auction/template.coffee | kanaabe/force | 1 | _ = require 'underscore'
jade = require 'jade'
fs = require 'fs'
benv = require 'benv'
{ resolve } = require 'path'
sinon = require 'sinon'
helpers = require '../../../view_helpers'
describe 'current auction or show', ->
before (done) ->
@item =
imageUrl: '/foo.jpg',
name: 'Foo Bar',
href: '/foo/bar'
detail: 'Item Detail'
heading: 'Current Show'
benv.setup =>
benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery')
done()
after ->
benv.teardown()
it 'with no image', (done) ->
benv.render resolve(__dirname, '../../../components/current_item/index.jade'), {
currentItem: _.extend {}, @item, imageUrl: null
viewHelpers: helpers
}, =>
$('.current-item').attr('href').should.eql '/foo/bar'
$('.current-item__image').length.should.eql 0
$('.current-item__label').text().should.eql 'Current Show'
$('.current-item__name').text().should.eql 'Foo Bar'
$('.current-item__detail').text().should.eql 'Item Detail'
done()
it 'with an image', ->
benv.render resolve(__dirname, '../../../components/current_item/index.jade'), {
currentItem: _.extend {}, @item
viewHelpers: helpers
}, =>
$('.current-item').attr('href').should.eql '/foo/bar'
$('.current-item__image').attr('src').should.eql '/foo.jpg'
$('.current-item__label').text().should.eql 'Current Show'
$('.current-item__name').text().should.eql 'Foo Bar'
$('.current-item__detail').text().should.eql 'Item Detail'
done()
| 50421 | _ = require 'underscore'
jade = require 'jade'
fs = require 'fs'
benv = require 'benv'
{ resolve } = require 'path'
sinon = require 'sinon'
helpers = require '../../../view_helpers'
describe 'current auction or show', ->
before (done) ->
@item =
imageUrl: '/foo.jpg',
name: '<NAME>',
href: '/foo/bar'
detail: 'Item Detail'
heading: 'Current Show'
benv.setup =>
benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery')
done()
after ->
benv.teardown()
it 'with no image', (done) ->
benv.render resolve(__dirname, '../../../components/current_item/index.jade'), {
currentItem: _.extend {}, @item, imageUrl: null
viewHelpers: helpers
}, =>
$('.current-item').attr('href').should.eql '/foo/bar'
$('.current-item__image').length.should.eql 0
$('.current-item__label').text().should.eql 'Current Show'
$('.current-item__name').text().should.eql '<NAME>'
$('.current-item__detail').text().should.eql 'Item Detail'
done()
it 'with an image', ->
benv.render resolve(__dirname, '../../../components/current_item/index.jade'), {
currentItem: _.extend {}, @item
viewHelpers: helpers
}, =>
$('.current-item').attr('href').should.eql '/foo/bar'
$('.current-item__image').attr('src').should.eql '/foo.jpg'
$('.current-item__label').text().should.eql 'Current Show'
$('.current-item__name').text().should.eql '<NAME>'
$('.current-item__detail').text().should.eql 'Item Detail'
done()
| true | _ = require 'underscore'
jade = require 'jade'
fs = require 'fs'
benv = require 'benv'
{ resolve } = require 'path'
sinon = require 'sinon'
helpers = require '../../../view_helpers'
describe 'current auction or show', ->
before (done) ->
@item =
imageUrl: '/foo.jpg',
name: 'PI:NAME:<NAME>END_PI',
href: '/foo/bar'
detail: 'Item Detail'
heading: 'Current Show'
benv.setup =>
benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery')
done()
after ->
benv.teardown()
it 'with no image', (done) ->
benv.render resolve(__dirname, '../../../components/current_item/index.jade'), {
currentItem: _.extend {}, @item, imageUrl: null
viewHelpers: helpers
}, =>
$('.current-item').attr('href').should.eql '/foo/bar'
$('.current-item__image').length.should.eql 0
$('.current-item__label').text().should.eql 'Current Show'
$('.current-item__name').text().should.eql 'PI:NAME:<NAME>END_PI'
$('.current-item__detail').text().should.eql 'Item Detail'
done()
it 'with an image', ->
benv.render resolve(__dirname, '../../../components/current_item/index.jade'), {
currentItem: _.extend {}, @item
viewHelpers: helpers
}, =>
$('.current-item').attr('href').should.eql '/foo/bar'
$('.current-item__image').attr('src').should.eql '/foo.jpg'
$('.current-item__label').text().should.eql 'Current Show'
$('.current-item__name').text().should.eql 'PI:NAME:<NAME>END_PI'
$('.current-item__detail').text().should.eql 'Item Detail'
done()
|
[
{
"context": "riteJSON\n 'my.host.org': \n username: 'richard'\n password: 'p@s$w0rd'\n 'my.second.ho",
"end": 348,
"score": 0.9996009469032288,
"start": 341,
"tag": "USERNAME",
"value": "richard"
},
{
"context": ": \n username: 'richard'\n passw... | test/saveFileSpec.coffee | h2non/node-authrc | 1 | fs = require 'fs'
{ expect } = require 'chai'
Authrc = require '../lib/authrc'
describe 'save/update data in file', ->
auth = null
authrcPath = "#{__dirname}/fixtures/tmp/.authrc"
writeJSON = (data) ->
fs.writeFileSync authrcPath, JSON.stringify(data, null, 4)
before ->
writeJSON
'my.host.org':
username: 'richard'
password: 'p@s$w0rd'
'my.second.host.org':
username: 'george'
password: 'p@s$w0rd'
before ->
auth = new Authrc(authrcPath)
after ->
auth.unwatch()
it 'should find the file and has data', ->
expect(auth.exists()).to.be.true
describe 'update and save data', ->
host = null
before ->
host = auth.host('http://my.host.org')
it 'should get the username', ->
expect(host.username()).to.be.equal('richard')
it 'should update the username', ->
expect(host.username('michael')).to.be.equal('michael')
it 'should get the password', ->
expect(host.password()).to.be.equal('p@s$w0rd')
it 'should update the password', ->
expect(host.password('my-n€w-pas$d0rd')).to.be.equal('my-n€w-pas$d0rd')
describe 'save changes in disk', ->
it 'should write the file with new data', (done) ->
auth.save (err) ->
expect(err).to.be.null
auth.read() # force read data from file
done()
it 'should have the new username and password values', ->
expect(host.exists()).to.be.true
expect(host.password()).to.be.equal('my-n€w-pas$d0rd')
| 53047 | fs = require 'fs'
{ expect } = require 'chai'
Authrc = require '../lib/authrc'
describe 'save/update data in file', ->
auth = null
authrcPath = "#{__dirname}/fixtures/tmp/.authrc"
writeJSON = (data) ->
fs.writeFileSync authrcPath, JSON.stringify(data, null, 4)
before ->
writeJSON
'my.host.org':
username: 'richard'
password: '<PASSWORD>'
'my.second.host.org':
username: 'george'
password: '<PASSWORD>'
before ->
auth = new Authrc(authrcPath)
after ->
auth.unwatch()
it 'should find the file and has data', ->
expect(auth.exists()).to.be.true
describe 'update and save data', ->
host = null
before ->
host = auth.host('http://my.host.org')
it 'should get the username', ->
expect(host.username()).to.be.equal('richard')
it 'should update the username', ->
expect(host.username('michael')).to.be.equal('michael')
it 'should get the password', ->
expect(host.password()).to.be.equal('<PASSWORD>')
it 'should update the password', ->
expect(host.password('<PASSWORD>-n€w-<PASSWORD>')).to.be.equal('<PASSWORD>€<PASSWORD>')
describe 'save changes in disk', ->
it 'should write the file with new data', (done) ->
auth.save (err) ->
expect(err).to.be.null
auth.read() # force read data from file
done()
it 'should have the new username and password values', ->
expect(host.exists()).to.be.true
expect(host.password()).to.be.equal('<PASSWORD>')
| true | fs = require 'fs'
{ expect } = require 'chai'
Authrc = require '../lib/authrc'
describe 'save/update data in file', ->
auth = null
authrcPath = "#{__dirname}/fixtures/tmp/.authrc"
writeJSON = (data) ->
fs.writeFileSync authrcPath, JSON.stringify(data, null, 4)
before ->
writeJSON
'my.host.org':
username: 'richard'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
'my.second.host.org':
username: 'george'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
before ->
auth = new Authrc(authrcPath)
after ->
auth.unwatch()
it 'should find the file and has data', ->
expect(auth.exists()).to.be.true
describe 'update and save data', ->
host = null
before ->
host = auth.host('http://my.host.org')
it 'should get the username', ->
expect(host.username()).to.be.equal('richard')
it 'should update the username', ->
expect(host.username('michael')).to.be.equal('michael')
it 'should get the password', ->
expect(host.password()).to.be.equal('PI:PASSWORD:<PASSWORD>END_PI')
it 'should update the password', ->
expect(host.password('PI:PASSWORD:<PASSWORD>END_PI-n€w-PI:PASSWORD:<PASSWORD>END_PI')).to.be.equal('PI:PASSWORD:<PASSWORD>END_PI€PI:PASSWORD:<PASSWORD>END_PI')
describe 'save changes in disk', ->
it 'should write the file with new data', (done) ->
auth.save (err) ->
expect(err).to.be.null
auth.read() # force read data from file
done()
it 'should have the new username and password values', ->
expect(host.exists()).to.be.true
expect(host.password()).to.be.equal('PI:PASSWORD:<PASSWORD>END_PI')
|
[
{
"context": "quire '../lib/utils'\n\n\n# state = {person: {name: 'Elin'}}\n# changes = []\n# producerOLD = undef (draft) -",
"end": 317,
"score": 0.9990808367729187,
"start": 313,
"tag": "NAME",
"value": "Elin"
}
] | examples/playground/client/src/app/lifters.coffee | Cottin/popsiql-cache | 0 | {groupBy, indexBy, map, prop} = R = require 'ramda' # auto_require: ramda
{fchange, $, $$} = RE = require 'ramda-extras' # auto_require: ramda-extras
[ːemail, ːid, ːavatar, ːname] = ['email', 'id', 'avatar', 'name'] #auto_sugar
immer = require 'immer'
{df} = require '../lib/utils'
# state = {person: {name: 'Elin'}}
# changes = []
# producerOLD = undef (draft) ->
# draft.person.age = 32
# producer = undef (draft) ->
# changeM {person: {age: 32}}, draft
# nextState = immer.produce state, producer, (patches) -> changes.push ...patches
# console.log 11111111111
# console.dir changes
module.exports =
# meʹ: ({me, url: {group}}) ->
# User1: _ {firebaseId, ːid, ːname, ːavatar, ːemail},
# memberships: _ {},
# group: _ {ːname},
# members: _ {},
# user: _ {ːavatar}
group2_debug: ({now, group, url: {groupId}}) ->
numWorkoutsMap = $ group.numWorkouts, indexBy prop('userId')
workoutsMap = $ group.workouts, groupBy prop('userId')
fchange group,
numWorkouts: undefined
members: map (m) ->
tot = numWorkoutsMap[m.userId].count
weeks = df.diff now, m.joined, 'week'
avg = (tot / weeks).toFixed 1
workouts = workoutsMap[m.userId]
return {...m, avg, tot, workouts}
| 122222 | {groupBy, indexBy, map, prop} = R = require 'ramda' # auto_require: ramda
{fchange, $, $$} = RE = require 'ramda-extras' # auto_require: ramda-extras
[ːemail, ːid, ːavatar, ːname] = ['email', 'id', 'avatar', 'name'] #auto_sugar
immer = require 'immer'
{df} = require '../lib/utils'
# state = {person: {name: '<NAME>'}}
# changes = []
# producerOLD = undef (draft) ->
# draft.person.age = 32
# producer = undef (draft) ->
# changeM {person: {age: 32}}, draft
# nextState = immer.produce state, producer, (patches) -> changes.push ...patches
# console.log 11111111111
# console.dir changes
module.exports =
# meʹ: ({me, url: {group}}) ->
# User1: _ {firebaseId, ːid, ːname, ːavatar, ːemail},
# memberships: _ {},
# group: _ {ːname},
# members: _ {},
# user: _ {ːavatar}
group2_debug: ({now, group, url: {groupId}}) ->
numWorkoutsMap = $ group.numWorkouts, indexBy prop('userId')
workoutsMap = $ group.workouts, groupBy prop('userId')
fchange group,
numWorkouts: undefined
members: map (m) ->
tot = numWorkoutsMap[m.userId].count
weeks = df.diff now, m.joined, 'week'
avg = (tot / weeks).toFixed 1
workouts = workoutsMap[m.userId]
return {...m, avg, tot, workouts}
| true | {groupBy, indexBy, map, prop} = R = require 'ramda' # auto_require: ramda
{fchange, $, $$} = RE = require 'ramda-extras' # auto_require: ramda-extras
[ːemail, ːid, ːavatar, ːname] = ['email', 'id', 'avatar', 'name'] #auto_sugar
immer = require 'immer'
{df} = require '../lib/utils'
# state = {person: {name: 'PI:NAME:<NAME>END_PI'}}
# changes = []
# producerOLD = undef (draft) ->
# draft.person.age = 32
# producer = undef (draft) ->
# changeM {person: {age: 32}}, draft
# nextState = immer.produce state, producer, (patches) -> changes.push ...patches
# console.log 11111111111
# console.dir changes
module.exports =
# meʹ: ({me, url: {group}}) ->
# User1: _ {firebaseId, ːid, ːname, ːavatar, ːemail},
# memberships: _ {},
# group: _ {ːname},
# members: _ {},
# user: _ {ːavatar}
group2_debug: ({now, group, url: {groupId}}) ->
numWorkoutsMap = $ group.numWorkouts, indexBy prop('userId')
workoutsMap = $ group.workouts, groupBy prop('userId')
fchange group,
numWorkouts: undefined
members: map (m) ->
tot = numWorkoutsMap[m.userId].count
weeks = df.diff now, m.joined, 'week'
avg = (tot / weeks).toFixed 1
workouts = workoutsMap[m.userId]
return {...m, avg, tot, workouts}
|
[
{
"context": " @myModels = [\n new MyModel({id: 1, name: \"Joseane Fogaça\", phone_number: \"96789-6991\"}),\n new MyModel",
"end": 443,
"score": 0.999845564365387,
"start": 429,
"tag": "NAME",
"value": "Joseane Fogaça"
},
{
"context": " \"96789-6991\"}),\n new MyMod... | spec/javascripts/core/components/grid.spec.coffee | houzelio/houzel | 2 | import GridCmp from 'javascripts/core/components/grid'
import PageableCollection from "backbone.paginator"
describe("Grid Component", () ->
MyModel = Backbone.Model.extend({})
MyCollection = PageableCollection.extend({
model: MyModel
url: '/test'
state:
pageSize: 2
totalRecords: 3
})
beforeEach ->
setFixtures(__html__['my-grid.html'])
@myModels = [
new MyModel({id: 1, name: "Joseane Fogaça", phone_number: "96789-6991"}),
new MyModel({id: 2, name: "Ella Fay", phone_number: "218-785-4836"}),
new MyModel({id: 3, name: "晋珊完颜", phone_number: "13840-870672"})
]
it("attachs the collection", () ->
collection = new MyCollection
myGrid = new GridCmp({columns: [], collection: collection})
expect(myGrid.getCollection()).toEqual(collection)
)
it("should set up a collection if the one ain't passed", () ->
myGrid = new GridCmp(columns: [])
expect(myGrid.getCollection()).toEqual(jasmine.any(Backbone.Collection))
)
describe("::showView", () ->
beforeEach ->
@myGrid = new GridCmp({el:'#grid', columns: []} )
@columns = [{ name: 'name', cell: 'string'}]
@myOtherGrid = new GridCmp({ el:'#grid', columns: @columns, collection: new MyCollection(@myModels)})
it("shows grid within an HTML element", () ->
@myGrid.showView()
expect($('#grid')[0]).toContainElement('table.table')
)
it("should replace the grid on Dom with the new if the el set is the same", () ->
@myGrid.showView()
expect($('#grid')[0]).not.toContainText('Joseane Fogaça')
@myOtherGrid.showView()
expect($('#grid')[0]).toContainText('Joseane Fogaça')
)
it("shows paginator automatically when 'totalRecords' is more than 'windowsSize'", () ->
@myOtherGrid.initialize(windowSize: 2)
spyOn(@myOtherGrid, 'showPaginator')
@myOtherGrid.showView()
expect(@myOtherGrid.showPaginator).toHaveBeenCalled()
)
it("should do not show paginator when 'totalRecords' is less than 'windowsSize'", () ->
spyOn(@myOtherGrid, 'showPaginator')
@myOtherGrid.showView()
expect(@myOtherGrid.showPaginator).not.toHaveBeenCalled()
)
it("should remove the thead when 'removeThead' is set to true", () ->
@myGrid.initialize(removeThead: true)
@myGrid.showView()
expect($('#grid')[0]).not.toContainHtml('<thead></thead>')
)
)
describe("normalizing", () ->
beforeEach ->
@spy = jasmine.createSpyObj('spy', ['formatter', 'click'])
@spy.formatter.and.callFake((rawData, model) ->
rawData
)
columns = [
name: 'phone_number'
formatter: @spy.formatter
thClassName: 'phone_number-render'
cell: extend:
template: _.template(
"""<a href="javascript:void(0);" data-check="true">
<span>Phone Number: <%= phone_number %> </span>
</a>"""
)
events:
'click a[data-check="true"]' : () =>
@spy.click()
]
@myGrid = new GridCmp({ el:'#grid', columns: columns, collection: new MyCollection(@myModels)})
it("supports a custom formatter function", () ->
@myGrid.showView()
expect(@spy.formatter).toHaveBeenCalled()
)
it("adds css classes to th element", () ->
@myGrid.showView()
expect($('#grid')[0]).toContainElement('th.phone_number-render')
)
describe("cell", () ->
it("renders a custom template function", () ->
@myGrid.showView()
expect($('#grid').find('a')[0]).toHaveAttr('data-check', 'true')
)
it("catches dom events triggered from the template", () ->
@myGrid.showView()
$('#grid').find('a').first().click()
expect(@spy.click).toHaveBeenCalled()
)
)
)
describe("manipulating elements", () ->
beforeEach ->
@spy = jasmine.createSpyObj('spy', ['add', 'remove', 'change'])
columns = [{ name: 'id', cell: 'string'}, {name: 'name', cell: 'string'}]
@myGrid = new GridCmp({ el:'#grid', columns: columns, collection: new MyCollection(@myModels)})
@myGrid.showView()
@myObject = new Marionette.MnObject()
describe("by adding", () ->
beforeEach ->
@myObject.listenTo(@myGrid, 'grid:add', @spy.add)
@myGrid.addElement(new MyModel({id: 4, name: "Luccas Marks"}))
it("adds the element to Dom", () ->
expect($('#grid')[0]).toContainText(4)
)
it("triggers event", () ->
expect(@spy.add).toHaveBeenCalled()
)
)
describe("by removing", () ->
beforeEach ->
@myObject.listenTo(@myGrid, 'grid:remove', @spy.remove)
@myGrid.removeElement(@myModels[2])
it("removes the element from Dom", () ->
expect($('#grid')[0]).not.toContainText(3)
)
it("triggers event", () ->
expect(@spy.remove).toHaveBeenCalled()
)
)
describe("by changing", () ->
beforeEach ->
@myObject.listenTo(@myGrid, 'grid:change', @spy.change)
@myModels[1].set('name', 'Ms. Ella Fay')
it("changes the element on Dom", () ->
expect($('#grid')[0]).toContainText('Ms. Ella Fay')
)
it("triggers event", () ->
expect(@spy.change).toHaveBeenCalled()
)
)
)
describe("::showPaginator", () ->
it("shows paginator independently of grid to have been showed", () ->
$('<div id="otherPaginator">').prependTo('body')
myGrid = new GridCmp({collection: new MyCollection(@myModels), windowSize: 2})
myGrid.showPaginator($('#otherPaginator'))
expect($('#otherPaginator')[0]).toContainElement('ul.pagination')
)
)
)
| 45716 | import GridCmp from 'javascripts/core/components/grid'
import PageableCollection from "backbone.paginator"
describe("Grid Component", () ->
MyModel = Backbone.Model.extend({})
MyCollection = PageableCollection.extend({
model: MyModel
url: '/test'
state:
pageSize: 2
totalRecords: 3
})
beforeEach ->
setFixtures(__html__['my-grid.html'])
@myModels = [
new MyModel({id: 1, name: "<NAME>", phone_number: "96789-6991"}),
new MyModel({id: 2, name: "<NAME>", phone_number: "218-785-4836"}),
new MyModel({id: 3, name: "<NAME>", phone_number: "13840-870672"})
]
it("attachs the collection", () ->
collection = new MyCollection
myGrid = new GridCmp({columns: [], collection: collection})
expect(myGrid.getCollection()).toEqual(collection)
)
it("should set up a collection if the one ain't passed", () ->
myGrid = new GridCmp(columns: [])
expect(myGrid.getCollection()).toEqual(jasmine.any(Backbone.Collection))
)
describe("::showView", () ->
beforeEach ->
@myGrid = new GridCmp({el:'#grid', columns: []} )
@columns = [{ name: 'name', cell: 'string'}]
@myOtherGrid = new GridCmp({ el:'#grid', columns: @columns, collection: new MyCollection(@myModels)})
it("shows grid within an HTML element", () ->
@myGrid.showView()
expect($('#grid')[0]).toContainElement('table.table')
)
it("should replace the grid on Dom with the new if the el set is the same", () ->
@myGrid.showView()
expect($('#grid')[0]).not.toContainText('<NAME>')
@myOtherGrid.showView()
expect($('#grid')[0]).toContainText('<NAME>')
)
it("shows paginator automatically when 'totalRecords' is more than 'windowsSize'", () ->
@myOtherGrid.initialize(windowSize: 2)
spyOn(@myOtherGrid, 'showPaginator')
@myOtherGrid.showView()
expect(@myOtherGrid.showPaginator).toHaveBeenCalled()
)
it("should do not show paginator when 'totalRecords' is less than 'windowsSize'", () ->
spyOn(@myOtherGrid, 'showPaginator')
@myOtherGrid.showView()
expect(@myOtherGrid.showPaginator).not.toHaveBeenCalled()
)
it("should remove the thead when 'removeThead' is set to true", () ->
@myGrid.initialize(removeThead: true)
@myGrid.showView()
expect($('#grid')[0]).not.toContainHtml('<thead></thead>')
)
)
describe("normalizing", () ->
beforeEach ->
@spy = jasmine.createSpyObj('spy', ['formatter', 'click'])
@spy.formatter.and.callFake((rawData, model) ->
rawData
)
columns = [
name: 'phone_number'
formatter: @spy.formatter
thClassName: 'phone_number-render'
cell: extend:
template: _.template(
"""<a href="javascript:void(0);" data-check="true">
<span>Phone Number: <%= phone_number %> </span>
</a>"""
)
events:
'click a[data-check="true"]' : () =>
@spy.click()
]
@myGrid = new GridCmp({ el:'#grid', columns: columns, collection: new MyCollection(@myModels)})
it("supports a custom formatter function", () ->
@myGrid.showView()
expect(@spy.formatter).toHaveBeenCalled()
)
it("adds css classes to th element", () ->
@myGrid.showView()
expect($('#grid')[0]).toContainElement('th.phone_number-render')
)
describe("cell", () ->
it("renders a custom template function", () ->
@myGrid.showView()
expect($('#grid').find('a')[0]).toHaveAttr('data-check', 'true')
)
it("catches dom events triggered from the template", () ->
@myGrid.showView()
$('#grid').find('a').first().click()
expect(@spy.click).toHaveBeenCalled()
)
)
)
describe("manipulating elements", () ->
beforeEach ->
@spy = jasmine.createSpyObj('spy', ['add', 'remove', 'change'])
columns = [{ name: 'id', cell: 'string'}, {name: 'name', cell: 'string'}]
@myGrid = new GridCmp({ el:'#grid', columns: columns, collection: new MyCollection(@myModels)})
@myGrid.showView()
@myObject = new Marionette.MnObject()
describe("by adding", () ->
beforeEach ->
@myObject.listenTo(@myGrid, 'grid:add', @spy.add)
@myGrid.addElement(new MyModel({id: 4, name: "<NAME>"}))
it("adds the element to Dom", () ->
expect($('#grid')[0]).toContainText(4)
)
it("triggers event", () ->
expect(@spy.add).toHaveBeenCalled()
)
)
describe("by removing", () ->
beforeEach ->
@myObject.listenTo(@myGrid, 'grid:remove', @spy.remove)
@myGrid.removeElement(@myModels[2])
it("removes the element from Dom", () ->
expect($('#grid')[0]).not.toContainText(3)
)
it("triggers event", () ->
expect(@spy.remove).toHaveBeenCalled()
)
)
describe("by changing", () ->
beforeEach ->
@myObject.listenTo(@myGrid, 'grid:change', @spy.change)
@myModels[1].set('name', '<NAME>')
it("changes the element on Dom", () ->
expect($('#grid')[0]).toContainText('<NAME>')
)
it("triggers event", () ->
expect(@spy.change).toHaveBeenCalled()
)
)
)
describe("::showPaginator", () ->
it("shows paginator independently of grid to have been showed", () ->
$('<div id="otherPaginator">').prependTo('body')
myGrid = new GridCmp({collection: new MyCollection(@myModels), windowSize: 2})
myGrid.showPaginator($('#otherPaginator'))
expect($('#otherPaginator')[0]).toContainElement('ul.pagination')
)
)
)
| true | import GridCmp from 'javascripts/core/components/grid'
import PageableCollection from "backbone.paginator"
describe("Grid Component", () ->
MyModel = Backbone.Model.extend({})
MyCollection = PageableCollection.extend({
model: MyModel
url: '/test'
state:
pageSize: 2
totalRecords: 3
})
beforeEach ->
setFixtures(__html__['my-grid.html'])
@myModels = [
new MyModel({id: 1, name: "PI:NAME:<NAME>END_PI", phone_number: "96789-6991"}),
new MyModel({id: 2, name: "PI:NAME:<NAME>END_PI", phone_number: "218-785-4836"}),
new MyModel({id: 3, name: "PI:NAME:<NAME>END_PI", phone_number: "13840-870672"})
]
it("attachs the collection", () ->
collection = new MyCollection
myGrid = new GridCmp({columns: [], collection: collection})
expect(myGrid.getCollection()).toEqual(collection)
)
it("should set up a collection if the one ain't passed", () ->
myGrid = new GridCmp(columns: [])
expect(myGrid.getCollection()).toEqual(jasmine.any(Backbone.Collection))
)
describe("::showView", () ->
beforeEach ->
@myGrid = new GridCmp({el:'#grid', columns: []} )
@columns = [{ name: 'name', cell: 'string'}]
@myOtherGrid = new GridCmp({ el:'#grid', columns: @columns, collection: new MyCollection(@myModels)})
it("shows grid within an HTML element", () ->
@myGrid.showView()
expect($('#grid')[0]).toContainElement('table.table')
)
it("should replace the grid on Dom with the new if the el set is the same", () ->
@myGrid.showView()
expect($('#grid')[0]).not.toContainText('PI:NAME:<NAME>END_PI')
@myOtherGrid.showView()
expect($('#grid')[0]).toContainText('PI:NAME:<NAME>END_PI')
)
it("shows paginator automatically when 'totalRecords' is more than 'windowsSize'", () ->
@myOtherGrid.initialize(windowSize: 2)
spyOn(@myOtherGrid, 'showPaginator')
@myOtherGrid.showView()
expect(@myOtherGrid.showPaginator).toHaveBeenCalled()
)
it("should do not show paginator when 'totalRecords' is less than 'windowsSize'", () ->
spyOn(@myOtherGrid, 'showPaginator')
@myOtherGrid.showView()
expect(@myOtherGrid.showPaginator).not.toHaveBeenCalled()
)
it("should remove the thead when 'removeThead' is set to true", () ->
@myGrid.initialize(removeThead: true)
@myGrid.showView()
expect($('#grid')[0]).not.toContainHtml('<thead></thead>')
)
)
describe("normalizing", () ->
beforeEach ->
@spy = jasmine.createSpyObj('spy', ['formatter', 'click'])
@spy.formatter.and.callFake((rawData, model) ->
rawData
)
columns = [
name: 'phone_number'
formatter: @spy.formatter
thClassName: 'phone_number-render'
cell: extend:
template: _.template(
"""<a href="javascript:void(0);" data-check="true">
<span>Phone Number: <%= phone_number %> </span>
</a>"""
)
events:
'click a[data-check="true"]' : () =>
@spy.click()
]
@myGrid = new GridCmp({ el:'#grid', columns: columns, collection: new MyCollection(@myModels)})
it("supports a custom formatter function", () ->
@myGrid.showView()
expect(@spy.formatter).toHaveBeenCalled()
)
it("adds css classes to th element", () ->
@myGrid.showView()
expect($('#grid')[0]).toContainElement('th.phone_number-render')
)
describe("cell", () ->
it("renders a custom template function", () ->
@myGrid.showView()
expect($('#grid').find('a')[0]).toHaveAttr('data-check', 'true')
)
it("catches dom events triggered from the template", () ->
@myGrid.showView()
$('#grid').find('a').first().click()
expect(@spy.click).toHaveBeenCalled()
)
)
)
describe("manipulating elements", () ->
beforeEach ->
@spy = jasmine.createSpyObj('spy', ['add', 'remove', 'change'])
columns = [{ name: 'id', cell: 'string'}, {name: 'name', cell: 'string'}]
@myGrid = new GridCmp({ el:'#grid', columns: columns, collection: new MyCollection(@myModels)})
@myGrid.showView()
@myObject = new Marionette.MnObject()
describe("by adding", () ->
beforeEach ->
@myObject.listenTo(@myGrid, 'grid:add', @spy.add)
@myGrid.addElement(new MyModel({id: 4, name: "PI:NAME:<NAME>END_PI"}))
it("adds the element to Dom", () ->
expect($('#grid')[0]).toContainText(4)
)
it("triggers event", () ->
expect(@spy.add).toHaveBeenCalled()
)
)
describe("by removing", () ->
beforeEach ->
@myObject.listenTo(@myGrid, 'grid:remove', @spy.remove)
@myGrid.removeElement(@myModels[2])
it("removes the element from Dom", () ->
expect($('#grid')[0]).not.toContainText(3)
)
it("triggers event", () ->
expect(@spy.remove).toHaveBeenCalled()
)
)
describe("by changing", () ->
beforeEach ->
@myObject.listenTo(@myGrid, 'grid:change', @spy.change)
@myModels[1].set('name', 'PI:NAME:<NAME>END_PI')
it("changes the element on Dom", () ->
expect($('#grid')[0]).toContainText('PI:NAME:<NAME>END_PI')
)
it("triggers event", () ->
expect(@spy.change).toHaveBeenCalled()
)
)
)
describe("::showPaginator", () ->
it("shows paginator independently of grid to have been showed", () ->
$('<div id="otherPaginator">').prependTo('body')
myGrid = new GridCmp({collection: new MyCollection(@myModels), windowSize: 2})
myGrid.showPaginator($('#otherPaginator'))
expect($('#otherPaginator')[0]).toContainElement('ul.pagination')
)
)
)
|
[
{
"context": "e crypto', ->\n crypto = Crypto()\n password = 'this is a password'\n data =\n foo: 1\n bar: 2\n stuff:\n ",
"end": 189,
"score": 0.9992914795875549,
"start": 171,
"tag": "PASSWORD",
"value": "this is a password"
}
] | test/crypto.coffee | yinso/keybox | 1 | Crypto = require '../src/crypto'
{ assert } = require 'chai'
describe 'crypto test', ->
crypto = null
it 'can create crypto', ->
crypto = Crypto()
password = 'this is a password'
data =
foo: 1
bar: 2
stuff:
this_is: 'top_secret_to_be_encrypted'
encrypted = null
it 'can encrypt', (done) ->
crypto.encrypt 'aes192', password, data, (err, res) ->
if err
done err
else
encrypted = res
done null
it 'can decrypt', (done) ->
crypto.decrypt password, encrypted, (err, res) ->
if err
done err
else
try
assert.deepEqual data, res
done null
catch e
done e
it 'can encrypt and decrypt', (done) ->
Crypto.encrypt 'aes256', password, data, (err, encrypted) ->
if err
done err
else
Crypto.decrypt password, encrypted, (err, decrypted) ->
if err
done err
else
try
assert.deepEqual data, decrypted
done null
catch e
done e
it 'can hash', (done) ->
Crypto.hash 'sha256', 'password:' + password, (err, hash) ->
if err
done err
else
console.log 'hash', hash
done null
| 46304 | Crypto = require '../src/crypto'
{ assert } = require 'chai'
describe 'crypto test', ->
crypto = null
it 'can create crypto', ->
crypto = Crypto()
password = '<PASSWORD>'
data =
foo: 1
bar: 2
stuff:
this_is: 'top_secret_to_be_encrypted'
encrypted = null
it 'can encrypt', (done) ->
crypto.encrypt 'aes192', password, data, (err, res) ->
if err
done err
else
encrypted = res
done null
it 'can decrypt', (done) ->
crypto.decrypt password, encrypted, (err, res) ->
if err
done err
else
try
assert.deepEqual data, res
done null
catch e
done e
it 'can encrypt and decrypt', (done) ->
Crypto.encrypt 'aes256', password, data, (err, encrypted) ->
if err
done err
else
Crypto.decrypt password, encrypted, (err, decrypted) ->
if err
done err
else
try
assert.deepEqual data, decrypted
done null
catch e
done e
it 'can hash', (done) ->
Crypto.hash 'sha256', 'password:' + password, (err, hash) ->
if err
done err
else
console.log 'hash', hash
done null
| true | Crypto = require '../src/crypto'
{ assert } = require 'chai'
describe 'crypto test', ->
crypto = null
it 'can create crypto', ->
crypto = Crypto()
password = 'PI:PASSWORD:<PASSWORD>END_PI'
data =
foo: 1
bar: 2
stuff:
this_is: 'top_secret_to_be_encrypted'
encrypted = null
it 'can encrypt', (done) ->
crypto.encrypt 'aes192', password, data, (err, res) ->
if err
done err
else
encrypted = res
done null
it 'can decrypt', (done) ->
crypto.decrypt password, encrypted, (err, res) ->
if err
done err
else
try
assert.deepEqual data, res
done null
catch e
done e
it 'can encrypt and decrypt', (done) ->
Crypto.encrypt 'aes256', password, data, (err, encrypted) ->
if err
done err
else
Crypto.decrypt password, encrypted, (err, decrypted) ->
if err
done err
else
try
assert.deepEqual data, decrypted
done null
catch e
done e
it 'can hash', (done) ->
Crypto.hash 'sha256', 'password:' + password, (err, hash) ->
if err
done err
else
console.log 'hash', hash
done null
|
[
{
"context": "### Copyright (c) 2015 Magnus Leo. All rights reserved. ###\n\nlayers = require('./la",
"end": 33,
"score": 0.9998525381088257,
"start": 23,
"tag": "NAME",
"value": "Magnus Leo"
}
] | src/modules/event.coffee | magnusleo/Leo-Engine | 1 | ### Copyright (c) 2015 Magnus Leo. All rights reserved. ###
layers = require('./layers')
util = require('./util')
event = {}
module.exports = event
event.pressedKeys = []
event._keydown = (e) ->
unless e.ctrlKey or e.metaKey
e.preventDefault()
# Prevent keydown repeat
keyIndex = event.pressedKeys.indexOf e.keyCode
if keyIndex is -1
event.pressedKeys.push e.keyCode
key = util.KEY_CODES
switch e.keyCode
when key.S
data = layers.get('ground').serialize()
localStorage.setItem('ground', data)
when key.L
data = localStorage.getItem('ground')
layers.get('ground').deserialize(data)
event.keydown e
event.keydown = (e) ->
# Override event.keydown with your keydown function
event._keyup = (e) ->
e.preventDefault()
keyIndex = event.pressedKeys.indexOf e.keyCode
if keyIndex isnt -1
event.pressedKeys.splice keyIndex, 1
event.keyup e
event.keyup = (e) ->
# Override event.keyup with your keyup function | 158117 | ### Copyright (c) 2015 <NAME>. All rights reserved. ###
layers = require('./layers')
util = require('./util')
event = {}
module.exports = event
event.pressedKeys = []
event._keydown = (e) ->
unless e.ctrlKey or e.metaKey
e.preventDefault()
# Prevent keydown repeat
keyIndex = event.pressedKeys.indexOf e.keyCode
if keyIndex is -1
event.pressedKeys.push e.keyCode
key = util.KEY_CODES
switch e.keyCode
when key.S
data = layers.get('ground').serialize()
localStorage.setItem('ground', data)
when key.L
data = localStorage.getItem('ground')
layers.get('ground').deserialize(data)
event.keydown e
event.keydown = (e) ->
# Override event.keydown with your keydown function
event._keyup = (e) ->
e.preventDefault()
keyIndex = event.pressedKeys.indexOf e.keyCode
if keyIndex isnt -1
event.pressedKeys.splice keyIndex, 1
event.keyup e
event.keyup = (e) ->
# Override event.keyup with your keyup function | true | ### Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved. ###
layers = require('./layers')
util = require('./util')
event = {}
module.exports = event
event.pressedKeys = []
event._keydown = (e) ->
unless e.ctrlKey or e.metaKey
e.preventDefault()
# Prevent keydown repeat
keyIndex = event.pressedKeys.indexOf e.keyCode
if keyIndex is -1
event.pressedKeys.push e.keyCode
key = util.KEY_CODES
switch e.keyCode
when key.S
data = layers.get('ground').serialize()
localStorage.setItem('ground', data)
when key.L
data = localStorage.getItem('ground')
layers.get('ground').deserialize(data)
event.keydown e
event.keydown = (e) ->
# Override event.keydown with your keydown function
event._keyup = (e) ->
e.preventDefault()
keyIndex = event.pressedKeys.indexOf e.keyCode
if keyIndex isnt -1
event.pressedKeys.splice keyIndex, 1
event.keyup e
event.keyup = (e) ->
# Override event.keyup with your keyup function |
[
{
"context": "tegration of a background-image uploader\n# Author: Guillaume Piot\n# Email: guillaume@cotidia.com\n# Company: Cotidia",
"end": 77,
"score": 0.9998760223388672,
"start": 63,
"tag": "NAME",
"value": "Guillaume Piot"
},
{
"context": "d-image uploader\n# Author: Guillaume ... | cotidia/cms/www/scripts/background-image.coffee | guillaumepiot/cotidia-cms | 0 | # Example integration of a background-image uploader
# Author: Guillaume Piot
# Email: guillaume@cotidia.com
# Company: Cotidia Ltd
# Licence: MIT
#
# The div holder is absolute positioned within the parent div
#
# <div class="[ article__image ] [ article-image ] [ editable ] [ parallax ]" data-name="article_image">
# <div
# data-ce-tag="bkgimg"
# class="article-image__container"
# style="background-image:url('/static/img/blog-header-placeholder.jpg')"></div>
# </div>
class ContentEdit.BackgroundImage extends ContentEdit.Element
# An editable background image element
# (e.g <div data-ce-type="bkgimg" data-url="..."></div>).
constructor: (attributes) ->
super('bkgimg', attributes)
# Read-only properties
cssTypeName: () ->
return 'background-image'
type: () ->
# Return the type of element (this should be the same as the class name)
return 'BackgroundImage'
typeName: () ->
# Return the name of the element type (e.g BackgroundImage, List item)
return 'BackgroundImage'
# Methods
html: (indent='') ->
# Return a HTML string for the node
bkgimg = "#{ indent }<div#{ @_attributesToString() }></div>"
return bkgimg
mount: () ->
# Mount the element on to the DOM
# Create the DOM element to mount
@_domElement = document.createElement('div')
# Set the classes for the backgound image element
classes = ''
if @_attributes['class']
classes += ' ' + @_attributes['class']
@_domElement.setAttribute('class', classes)
# Set the background image for the
style = if @_attributes['style'] then @_attributes['style'] else ''
@_domElement.setAttribute('style', style)
# Add the button to edit the background image
@_domButtonElement = document.createElement("button")
buttonText = document.createTextNode("Upload image");
@_domButtonElement.appendChild(buttonText)
@_domButtonElement.className = 'btn btn--small btn--change btn--upload-background-image'
@_domButtonElement.style.position = 'absolute'
super()
# Just below the toolbox level
@_domButtonElement.style.zIndex = '9998'
@_domElement.parentNode.parentNode.appendChild(@_domButtonElement)
# Get the selected element position
rect = @_domElement.getBoundingClientRect()
# @_domButtonElement.style.bottom = "16px"
@_domButtonElement.style.bottom = "16px"
@_domButtonElement.style.right = "16px"
_addDOMEventListeners: () ->
super()
@_domButtonElement.addEventListener 'click', (ev) =>
ev.preventDefault()
editor = ContentTools.EditorApp.get()
modal = new ContentTools.ModalUI(transparent=false, allowScrolling=false)
dialog = new ContentTools.ImageDialog()
# Support cancelling the dialog
dialog.addEventListener 'imageuploader.mount', (e) =>
dialog._domInput.setAttribute('accept', 'image/*,video/*');
# Support cancelling the dialog
dialog.addEventListener 'cancel', () =>
modal.hide()
dialog.hide()
# Insert the image url into the element once saved
dialog.addEventListener 'save', (ev) =>
detail = ev.detail()
imageURL = detail.imageURL
imageSize = detail.imageSize
# imageAttrs = detail.imageAttrs
if not imageAttrs
imageAttrs = {}
# imageAttrs.height = imageSize[1]
imageAttrs.src = imageURL
# imageAttrs.width = imageSize[0]
# node = document.querySelector('[data-name="page_image"]')
# element.style.backgroundImage = "url('#{imageURL}')";
# imageNode = region.descendants()[0]
style = "background-image: url('#{imageURL}')"
@attr('style', style)
modal.hide()
dialog.hide()
editor.attach(modal)
editor.attach(dialog)
modal.show()
dialog.show()
# Class properties
# Class methods
@fromDOMElement: (domElement) ->
# Convert an element (DOM) to an element of this type
attributes = @getDOMElementAttributes(domElement)
return new @(attributes)
# Register `ContentEdit.BackgroundImage` the class with associated tag names
ContentEdit.TagNames.get().register(ContentEdit.BackgroundImage, 'bkgimg')
| 36881 | # Example integration of a background-image uploader
# Author: <NAME>
# Email: <EMAIL>
# Company: Cotidia Ltd
# Licence: MIT
#
# The div holder is absolute positioned within the parent div
#
# <div class="[ article__image ] [ article-image ] [ editable ] [ parallax ]" data-name="article_image">
# <div
# data-ce-tag="bkgimg"
# class="article-image__container"
# style="background-image:url('/static/img/blog-header-placeholder.jpg')"></div>
# </div>
class ContentEdit.BackgroundImage extends ContentEdit.Element
# An editable background image element
# (e.g <div data-ce-type="bkgimg" data-url="..."></div>).
constructor: (attributes) ->
super('bkgimg', attributes)
# Read-only properties
cssTypeName: () ->
return 'background-image'
type: () ->
# Return the type of element (this should be the same as the class name)
return 'BackgroundImage'
typeName: () ->
# Return the name of the element type (e.g BackgroundImage, List item)
return 'BackgroundImage'
# Methods
html: (indent='') ->
# Return a HTML string for the node
bkgimg = "#{ indent }<div#{ @_attributesToString() }></div>"
return bkgimg
mount: () ->
# Mount the element on to the DOM
# Create the DOM element to mount
@_domElement = document.createElement('div')
# Set the classes for the backgound image element
classes = ''
if @_attributes['class']
classes += ' ' + @_attributes['class']
@_domElement.setAttribute('class', classes)
# Set the background image for the
style = if @_attributes['style'] then @_attributes['style'] else ''
@_domElement.setAttribute('style', style)
# Add the button to edit the background image
@_domButtonElement = document.createElement("button")
buttonText = document.createTextNode("Upload image");
@_domButtonElement.appendChild(buttonText)
@_domButtonElement.className = 'btn btn--small btn--change btn--upload-background-image'
@_domButtonElement.style.position = 'absolute'
super()
# Just below the toolbox level
@_domButtonElement.style.zIndex = '9998'
@_domElement.parentNode.parentNode.appendChild(@_domButtonElement)
# Get the selected element position
rect = @_domElement.getBoundingClientRect()
# @_domButtonElement.style.bottom = "16px"
@_domButtonElement.style.bottom = "16px"
@_domButtonElement.style.right = "16px"
_addDOMEventListeners: () ->
super()
@_domButtonElement.addEventListener 'click', (ev) =>
ev.preventDefault()
editor = ContentTools.EditorApp.get()
modal = new ContentTools.ModalUI(transparent=false, allowScrolling=false)
dialog = new ContentTools.ImageDialog()
# Support cancelling the dialog
dialog.addEventListener 'imageuploader.mount', (e) =>
dialog._domInput.setAttribute('accept', 'image/*,video/*');
# Support cancelling the dialog
dialog.addEventListener 'cancel', () =>
modal.hide()
dialog.hide()
# Insert the image url into the element once saved
dialog.addEventListener 'save', (ev) =>
detail = ev.detail()
imageURL = detail.imageURL
imageSize = detail.imageSize
# imageAttrs = detail.imageAttrs
if not imageAttrs
imageAttrs = {}
# imageAttrs.height = imageSize[1]
imageAttrs.src = imageURL
# imageAttrs.width = imageSize[0]
# node = document.querySelector('[data-name="page_image"]')
# element.style.backgroundImage = "url('#{imageURL}')";
# imageNode = region.descendants()[0]
style = "background-image: url('#{imageURL}')"
@attr('style', style)
modal.hide()
dialog.hide()
editor.attach(modal)
editor.attach(dialog)
modal.show()
dialog.show()
# Class properties
# Class methods
@fromDOMElement: (domElement) ->
# Convert an element (DOM) to an element of this type
attributes = @getDOMElementAttributes(domElement)
return new @(attributes)
# Register `ContentEdit.BackgroundImage` the class with associated tag names
ContentEdit.TagNames.get().register(ContentEdit.BackgroundImage, 'bkgimg')
| true | # Example integration of a background-image uploader
# Author: PI:NAME:<NAME>END_PI
# Email: PI:EMAIL:<EMAIL>END_PI
# Company: Cotidia Ltd
# Licence: MIT
#
# The div holder is absolute positioned within the parent div
#
# <div class="[ article__image ] [ article-image ] [ editable ] [ parallax ]" data-name="article_image">
# <div
# data-ce-tag="bkgimg"
# class="article-image__container"
# style="background-image:url('/static/img/blog-header-placeholder.jpg')"></div>
# </div>
class ContentEdit.BackgroundImage extends ContentEdit.Element
# An editable background image element
# (e.g <div data-ce-type="bkgimg" data-url="..."></div>).
constructor: (attributes) ->
super('bkgimg', attributes)
# Read-only properties
cssTypeName: () ->
return 'background-image'
type: () ->
# Return the type of element (this should be the same as the class name)
return 'BackgroundImage'
typeName: () ->
# Return the name of the element type (e.g BackgroundImage, List item)
return 'BackgroundImage'
# Methods
html: (indent='') ->
# Return a HTML string for the node
bkgimg = "#{ indent }<div#{ @_attributesToString() }></div>"
return bkgimg
mount: () ->
# Mount the element on to the DOM
# Create the DOM element to mount
@_domElement = document.createElement('div')
# Set the classes for the backgound image element
classes = ''
if @_attributes['class']
classes += ' ' + @_attributes['class']
@_domElement.setAttribute('class', classes)
# Set the background image for the
style = if @_attributes['style'] then @_attributes['style'] else ''
@_domElement.setAttribute('style', style)
# Add the button to edit the background image
@_domButtonElement = document.createElement("button")
buttonText = document.createTextNode("Upload image");
@_domButtonElement.appendChild(buttonText)
@_domButtonElement.className = 'btn btn--small btn--change btn--upload-background-image'
@_domButtonElement.style.position = 'absolute'
super()
# Just below the toolbox level
@_domButtonElement.style.zIndex = '9998'
@_domElement.parentNode.parentNode.appendChild(@_domButtonElement)
# Get the selected element position
rect = @_domElement.getBoundingClientRect()
# @_domButtonElement.style.bottom = "16px"
@_domButtonElement.style.bottom = "16px"
@_domButtonElement.style.right = "16px"
_addDOMEventListeners: () ->
super()
@_domButtonElement.addEventListener 'click', (ev) =>
ev.preventDefault()
editor = ContentTools.EditorApp.get()
modal = new ContentTools.ModalUI(transparent=false, allowScrolling=false)
dialog = new ContentTools.ImageDialog()
# Support cancelling the dialog
dialog.addEventListener 'imageuploader.mount', (e) =>
dialog._domInput.setAttribute('accept', 'image/*,video/*');
# Support cancelling the dialog
dialog.addEventListener 'cancel', () =>
modal.hide()
dialog.hide()
# Insert the image url into the element once saved
dialog.addEventListener 'save', (ev) =>
detail = ev.detail()
imageURL = detail.imageURL
imageSize = detail.imageSize
# imageAttrs = detail.imageAttrs
if not imageAttrs
imageAttrs = {}
# imageAttrs.height = imageSize[1]
imageAttrs.src = imageURL
# imageAttrs.width = imageSize[0]
# node = document.querySelector('[data-name="page_image"]')
# element.style.backgroundImage = "url('#{imageURL}')";
# imageNode = region.descendants()[0]
style = "background-image: url('#{imageURL}')"
@attr('style', style)
modal.hide()
dialog.hide()
editor.attach(modal)
editor.attach(dialog)
modal.show()
dialog.show()
# Class properties
# Class methods
@fromDOMElement: (domElement) ->
# Convert an element (DOM) to an element of this type
attributes = @getDOMElementAttributes(domElement)
return new @(attributes)
# Register `ContentEdit.BackgroundImage` the class with associated tag names
ContentEdit.TagNames.get().register(ContentEdit.BackgroundImage, 'bkgimg')
|
[
{
"context": "til\n\n The MIT License (MIT)\n\n Copyright (c) 2014 Yasuhiro Okuno\n\n Permission is hereby granted, free of charge, ",
"end": 88,
"score": 0.9998689889907837,
"start": 74,
"tag": "NAME",
"value": "Yasuhiro Okuno"
}
] | coffee_lib/crowdutil/subcmd/update-user.coffee | koma75/crowdutil | 1 | ###
@license
crowdutil
The MIT License (MIT)
Copyright (c) 2014 Yasuhiro Okuno
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.
###
crhelp = require '../helper/crhelper'
help = require '../helper/helper'
isOptOK = (opts) ->
rc = true
if(
help.opIsType(opts, '-f', 'string') &&
!help.isName(opts['-f'][0], false)
)
rc = false
logger.error 'first name not valid'
console.log 'E, first name not valid'
if(
help.opIsType(opts, '-l', 'string') &&
!help.isName(opts['-l'][0], false)
)
rc = false
logger.error 'last name not valid'
console.log 'E, last name not valid'
if(
help.opIsType(opts, '-d', 'string') &&
!help.isName(opts['-d'][0], true)
)
rc = false
logger.error 'disp name not valid'
console.log 'E, disp name not valid'
if(
help.opIsType(opts, '-e', 'string') &&
!help.isEmail(opts['-e'][0])
)
rc = false
logger.error 'email not valid'
console.log 'E, email not valid'
if(
!help.opIsType(opts, '-u', 'string') ||
!help.isName(opts['-u'][0], false)
)
rc = false
logger.error 'uid not given or invalid'
console.log 'E, uid not given or invalid'
if(
help.opIsType(opts, '-a', 'string') &&
!help.isName(opts['-a'][0], false)
)
rc = false
logger.error 'active state not valid'
console.log 'E, active state not valid'
return rc
exports.run = (options) ->
logger.trace 'running : update-user\n\n\n'
logger.debug options
if !isOptOK(options)
return
logger.debug 'updating user with:\n' + JSON.stringify(options,null,2)
update = {}
# get the command parameters and prepare for update
if help.opIsType(options, '-f', 'string')
update['first-name'] = options['-f'][0]
if help.opIsType(options, '-l', 'string')
update['last-name'] = options['-l'][0]
if help.opIsType(options, '-d', 'string')
update['display-name'] = options['-d'][0]
if help.opIsType(options, '-e', 'string')
update['email'] = options['-e'][0]
if help.opIsType(options, '-a', 'string')
if options['-a'][0] == 'true'
update['active'] = true
if options['-a'][0] == 'false'
update['active'] = false
uid = options['-u'][0]
# If there was no input, ignore
if Object.getOwnPropertyNames(update).length == 0
logger.info "nothing to update!"
console.log "I, nothing to update!"
return
# run update with the given user information
crowd = options['crowd']
crhelp.updateUser(crowd, uid, update, (err) ->
if err
logger.error err.message
console.log "E, Error updating #{uid}. Check the log for details."
else
logger.info " * update user #{uid}, done."
console.log "I, update user #{uid}, done."
)
| 174900 | ###
@license
crowdutil
The MIT License (MIT)
Copyright (c) 2014 <NAME>
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.
###
crhelp = require '../helper/crhelper'
help = require '../helper/helper'
isOptOK = (opts) ->
rc = true
if(
help.opIsType(opts, '-f', 'string') &&
!help.isName(opts['-f'][0], false)
)
rc = false
logger.error 'first name not valid'
console.log 'E, first name not valid'
if(
help.opIsType(opts, '-l', 'string') &&
!help.isName(opts['-l'][0], false)
)
rc = false
logger.error 'last name not valid'
console.log 'E, last name not valid'
if(
help.opIsType(opts, '-d', 'string') &&
!help.isName(opts['-d'][0], true)
)
rc = false
logger.error 'disp name not valid'
console.log 'E, disp name not valid'
if(
help.opIsType(opts, '-e', 'string') &&
!help.isEmail(opts['-e'][0])
)
rc = false
logger.error 'email not valid'
console.log 'E, email not valid'
if(
!help.opIsType(opts, '-u', 'string') ||
!help.isName(opts['-u'][0], false)
)
rc = false
logger.error 'uid not given or invalid'
console.log 'E, uid not given or invalid'
if(
help.opIsType(opts, '-a', 'string') &&
!help.isName(opts['-a'][0], false)
)
rc = false
logger.error 'active state not valid'
console.log 'E, active state not valid'
return rc
exports.run = (options) ->
logger.trace 'running : update-user\n\n\n'
logger.debug options
if !isOptOK(options)
return
logger.debug 'updating user with:\n' + JSON.stringify(options,null,2)
update = {}
# get the command parameters and prepare for update
if help.opIsType(options, '-f', 'string')
update['first-name'] = options['-f'][0]
if help.opIsType(options, '-l', 'string')
update['last-name'] = options['-l'][0]
if help.opIsType(options, '-d', 'string')
update['display-name'] = options['-d'][0]
if help.opIsType(options, '-e', 'string')
update['email'] = options['-e'][0]
if help.opIsType(options, '-a', 'string')
if options['-a'][0] == 'true'
update['active'] = true
if options['-a'][0] == 'false'
update['active'] = false
uid = options['-u'][0]
# If there was no input, ignore
if Object.getOwnPropertyNames(update).length == 0
logger.info "nothing to update!"
console.log "I, nothing to update!"
return
# run update with the given user information
crowd = options['crowd']
crhelp.updateUser(crowd, uid, update, (err) ->
if err
logger.error err.message
console.log "E, Error updating #{uid}. Check the log for details."
else
logger.info " * update user #{uid}, done."
console.log "I, update user #{uid}, done."
)
| true | ###
@license
crowdutil
The MIT License (MIT)
Copyright (c) 2014 PI:NAME:<NAME>END_PI
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.
###
crhelp = require '../helper/crhelper'
help = require '../helper/helper'
isOptOK = (opts) ->
rc = true
if(
help.opIsType(opts, '-f', 'string') &&
!help.isName(opts['-f'][0], false)
)
rc = false
logger.error 'first name not valid'
console.log 'E, first name not valid'
if(
help.opIsType(opts, '-l', 'string') &&
!help.isName(opts['-l'][0], false)
)
rc = false
logger.error 'last name not valid'
console.log 'E, last name not valid'
if(
help.opIsType(opts, '-d', 'string') &&
!help.isName(opts['-d'][0], true)
)
rc = false
logger.error 'disp name not valid'
console.log 'E, disp name not valid'
if(
help.opIsType(opts, '-e', 'string') &&
!help.isEmail(opts['-e'][0])
)
rc = false
logger.error 'email not valid'
console.log 'E, email not valid'
if(
!help.opIsType(opts, '-u', 'string') ||
!help.isName(opts['-u'][0], false)
)
rc = false
logger.error 'uid not given or invalid'
console.log 'E, uid not given or invalid'
if(
help.opIsType(opts, '-a', 'string') &&
!help.isName(opts['-a'][0], false)
)
rc = false
logger.error 'active state not valid'
console.log 'E, active state not valid'
return rc
exports.run = (options) ->
logger.trace 'running : update-user\n\n\n'
logger.debug options
if !isOptOK(options)
return
logger.debug 'updating user with:\n' + JSON.stringify(options,null,2)
update = {}
# get the command parameters and prepare for update
if help.opIsType(options, '-f', 'string')
update['first-name'] = options['-f'][0]
if help.opIsType(options, '-l', 'string')
update['last-name'] = options['-l'][0]
if help.opIsType(options, '-d', 'string')
update['display-name'] = options['-d'][0]
if help.opIsType(options, '-e', 'string')
update['email'] = options['-e'][0]
if help.opIsType(options, '-a', 'string')
if options['-a'][0] == 'true'
update['active'] = true
if options['-a'][0] == 'false'
update['active'] = false
uid = options['-u'][0]
# If there was no input, ignore
if Object.getOwnPropertyNames(update).length == 0
logger.info "nothing to update!"
console.log "I, nothing to update!"
return
# run update with the given user information
crowd = options['crowd']
crhelp.updateUser(crowd, uid, update, (err) ->
if err
logger.error err.message
console.log "E, Error updating #{uid}. Check the log for details."
else
logger.info " * update user #{uid}, done."
console.log "I, update user #{uid}, done."
)
|
[
{
"context": " hint: [\"WELCOME TO\", \"A JS13K 2018 GAME\\nBY MONSTERKODI\"]\n dots: [\n v:[0,0,1], b:0\n ",
"end": 727,
"score": 0.9500527381896973,
"start": 716,
"tag": "USERNAME",
"value": "MONSTERKODI"
},
{
"context": "'\n ,\n v:[-1,0... | Konnekt-master/coffee/lvls.coffee | sreechar/Games | 1 | ###
000 00000000 000 000 00000000 000 0000000
000 000 000 000 000 000 000
000 0000000 000 000 0000000 000 0000000
000 000 000 000 000 000
0000000 00000000 0 00000000 0000000 0000000
###
levelList = [
# 00 00 00000000 000 000 000 000
# 000 000 000 0000 000 000 000
# 000000000 0000000 000 0 000 000 000
# 000 0 000 000 000 0000 000 000
# 000 000 00000000 000 000 0000000
name: 'menu'
addUnit:0
msg: "KONNEKT"
hint: ["WELCOME TO", "A JS13K 2018 GAME\nBY MONSTERKODI"]
dots: [
v:[0,0,1], b:0
l:'TUTORIAL 1'
,
v:[0,-0.3,0.8]
l:'TUTORIAL 2'
,
v:[-0.3,-0.58,0.75]
l:'TUTORIAL 3'
,
v:[0.3,-0.58,0.75]
l:'TUTORIAL 4'
,
v:[0,-0.82,0.58]
l:'TUTORIAL 5'
,
v: [0,-1,0.01]
l: 'EASY'
,
v:[-1,0,0]
l:'CIRCLES'
,
v:[-1,0,-1]
l:'RING'
,
v:[-1,1,-1]
l:'CLOSE'
,
v:[1,1,-1]
l:'POLES'
,
v:[1,0,-1]
l:'UNFAIR'
,
v:[1,0,-0.01]
l:'FRENZY'
,
v: [0,1,0]
l: 'RANDOM'
]
lines: [
[0,1]
[1,2]
[1,3]
[3,4]
[2,4]
[4,5]
[5,6]
[6,7]
[7,8]
[8,9]
[9,10]
[10,11]
[11,12]
]
,
# 000000000 000 000 000000000 0000000 00000000 000 0000000 000 000
# 000 000 000 000 000 000 000 000 000 000 000 000 00000
# 000 000 000 000 000 000 0000000 000 000000000 000 000000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 0000000 000 0000000 000 000 000 000 000 0000000 000
name: 'TUTORIAL 1'
synt:
usr: instrument:'piano1'
bot: instrument:'piano2'
addUnit: 0
hint: ["You control the blue nodes. Your task is to fight the red nodes.\n\nNodes contain processes. The more processes, the stronger the node.", "Attack the infected red node by dragging from your blue node.\n\nEach time you attack, half of the available processes will be sent."]
dots: [
v: [-0.5,0,1]
u: 360
,
v: [0.5,0,1]
b: 270
]
,
# 000000000 000 000 000000000 0000000 00000000 000 0000000 000 00000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 000 000 000 000 000 0000000 000 000000000 000 000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 0000000 000 0000000 000 000 000 000 000 0000000 000000
name: 'TUTORIAL 2'
synt:
usr: instrument:'bell1'
bot: instrument:'bell2'
addUnit: 0
hint: ["To win, you need to deactivate all red nodes.\n\nIt is OK to leave inactive red nodes!", "This level contains 4 inactive and 2 active red nodes.\n\nDrag anywhere to rotate the sphere."]
dots: [
v: [0,0,1]
u: 90
,
v: [-0.2,0,1]
b: 11
,
v: [0.2,0,1]
b: 11
,
v: [0,0.2,1]
b: 11
,
v: [0,-0.2,1]
b: 11
,
v: [-0.1,0.1,-1]
b: 15
,
v: [0.1,0.1,-1]
b: 15
]
,
# 000000000 000 000 000000000 0000000 00000000 000 0000000 000 000000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 000 000 000 000 000 0000000 000 000000000 000 0000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 0000000 000 0000000 000 000 000 000 000 0000000 000000
name: 'TUTORIAL 3'
synt:
usr: instrument:'bell3'
bot: instrument:'bell4'
addUnit: 0
hint: ["Sending to nodes that you don't own isn't free.\n\nThe farther away the target node, the higher the cost.", "The cost factor is multiplied by the number of processes sent. The more you send, the more you loose.\n\nNotice that you need more attacks -- and loose more processes -- when defeating the far node."]
dots: [
v: [-0.9,-0.2,0.1]
u: 360
,
v: [-0.9,0.2,0.1]
u: 360
,
v: [-0.9,0,0.1]
b: 180
,
v: [0.9,0,0.1]
b: 180
]
,
name: 'TUTORIAL 4'
addUnit: 0
hint: ["Sending processes to nodes you own cost nothing.\n\nIt is efficient to occupy far away neutral nodes with few processes first and send larger groups later.", "Contrary to common believe,\nyou can't send processes between already connected nodes."]
dots: [
v: [-0.7,0.1,0.3]
u: 180
,
v: [-0.7,-0.1,0.3]
u: 12
,
v: [0.7,-0.1,0.3]
,
v: [0.7,0.1,0.3]
b: 135
]
lines: [ [0,1] ]
,
# 000000000 000 000 000000000 0000000 00000000 000 0000000 000 0000000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 000 000 000 000 000 0000000 000 000000000 000 0000000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 0000000 000 0000000 000 000 000 000 000 0000000 0000000
name: 'TUTORIAL 5'
addUnit: 3
hint: ["New processes are spawned regularily in active nodes.\n\nAlways make sure you have more active nodes than the opponent.", "You can see the number of active nodes in the top right corner.\n\nThe graph plots the relative amount of available processes."]
dots: [
v: [0,0,1]
u: 60
,
v: [-0.5,-0.5,1]
,
v: [ 0.5,-0.5,1]
,
v: [-0.5, 0.5,1]
,
v: [ 0.5, 0.5,1]
,
v: [-1, 0,1]
,
v: [ 1, 0,1]
,
v: [ 0,-1,1]
,
v: [ 0, 1,1]
,
v: [-1,-1,0]
b: 12
,
v: [ 1,-1,0]
b: 12
,
v: [-1, 1,0]
b: 12
,
v: [ 1, 1,0]
b: 12
,
v: [0,0,-1]
b: 12
]
,
# 00000000 0000000 0000000 000 000
# 000 000 000 000 000 000
# 0000000 000000000 0000000 00000
# 000 000 000 000 000
# 00000000 000 000 0000000 000
name: 'EASY'
synt:
usr: instrument:'organ1'
bot: instrument:'organ2'
addUnit: 2
hint: ["Be prepared, the red nodes are fighting back!", "You learned the basics, remove the virus from the system!"]
dots: [
v: [0,0,1]
u: 60
,
v: [-0.5,-0.5,1]
,
v: [ 0.5,-0.5,1]
,
v: [-0.5, 0.5,1]
,
v: [ 0.5, 0.5,1]
,
v: [-1, 0,1]
,
v: [ 1, 0,1]
,
v: [ 0,-1,1]
,
v: [ 0, 1,1]
,
v: [-1,-1,-1]
,
v: [ 1,-1,-1]
,
v: [-1, 1,-1]
,
v: [ 1, 1,-1]
,
v: [0,0,-1]
b: 60
]
bot:
speed: 8
i: -1
,
# 0000000 000 00000000 0000000 000 00000000 0000000
# 000 000 000 000 000 000 000 000
# 000 000 0000000 000 000 0000000 0000000
# 000 000 000 000 000 000 000 000
# 0000000 000 000 000 0000000 0000000 00000000 0000000
name: 'CIRCLES'
synt:
usr: instrument:'string'
bot: instrument:'flute'
addUnit: 4
dots: [
v: [0,0,1]
u: 60
,
c: [8,45,0,0]
,
c: [8,45,0,180]
,
c: [16,90,0,0]
,
v: [0,0,-1]
b: 60
]
bot:
speed: 7
i: -1
,
# 00000000 000 000 000 0000000
# 000 000 000 0000 000 000
# 0000000 000 000 0 000 000 0000
# 000 000 000 000 0000 000 000
# 000 000 000 000 000 0000000
name: 'RING'
synt:
usr: instrument:'bell1'
bot: instrument:'bell2'
addUnit: 4
dots: [
v: [0,0,1]
u: 60
,
c: [5,90,-30,90,30]
,
c: [5,-90,-30,90,30]
,
c: [5,70,-120,90,30]
,
c: [5,70,-60,-90,30]
,
v: [0,0,-1]
b: 60
]
bot:
speed: 5
i: -1
,
# 0000000 000 0000000 0000000 00000000
# 000 000 000 000 000 000
# 000 000 000 000 0000000 0000000
# 000 000 000 000 000 000
# 0000000 0000000 0000000 0000000 00000000
name: 'CLOSE'
addUnit: 4
dots: [
v: [-0.4,0,1]
u: 60
,
c: [11,90,-15,45,15]
,
c: [11,-90,-15,45,15]
,
v: [0.4,0,1]
b: 60
]
bot:
speed: 4
i: -1
,
# 00000000 0000000 000 00000000 0000000
# 000 000 000 000 000 000 000
# 00000000 000 000 000 0000000 0000000
# 000 000 000 000 000 000
# 000 0000000 0000000 00000000 0000000
name: 'POLES'
synt:
usr: instrument:'bell3'
bot: instrument:'bell4'
addUnit: 4
dots: [
v: [0,0,1]
u: 60
,
c: [8,20,90,0]
,
c: [8,20,-90,0]
,
c: [8,20,0,90]
,
c: [8,20,0,-90]
,
v: [0,0,-1]
b: 60
]
bot:
speed: 6
i: -1
,
# 000 000 000 000 00000000 0000000 000 00000000
# 000 000 0000 000 000 000 000 000 000 000
# 000 000 000 0 000 000000 000000000 000 0000000
# 000 000 000 0000 000 000 000 000 000 000
# 0000000 000 000 000 000 000 000 000 000
name: 'UNFAIR'
addUnit: 6
synt:
usr: instrument:'bell3'
bot: instrument:'bell4'
dots: [
v: [0,0,1]
u: 90
,
c: [4,15,180,0]
,
c: [8,30,180,0]
,
c: [16,45,180,0]
,
v: [0,0,-1]
b: 360
]
bot:
speed: 3
i: -1
,
# 00000000 00000000 00000000 000 000 0000000 000 000
# 000 000 000 000 0000 000 000 000 000
# 000000 0000000 0000000 000 0 000 000 00000
# 000 000 000 000 000 0000 000 000
# 000 000 000 00000000 000 000 0000000 000
name: 'FRENZY'
addUnit: 8
synt:
usr: instrument:'bell3'
bot: instrument:'bell4'
dots: [
v: [0,0,1]
u: 180
,
c: [4,22.5,0,0]
,
c: [4,22.5,180,0]
,
c: [4,22.5,90,0]
,
c: [4,22.5,-90,0]
,
c: [6,40,0,0]
,
c: [6,40,180,0]
,
c: [6,40,90,0]
,
c: [6,40,-90,0]
,
v: [0,0,-1]
b: 12
,
v: [1,0,0]
b: 12
,
v: [-1,0,0]
b: 12
,
v: [0,1,0]
b: 12
,
v: [0,-1,0]
b: 12
]
bot:
speed: 2
i: -1
]
levels = {}
for index in [0...levelList.length]
level = levelList[index]
level.index = index
levels[level.name] = level
| 171957 | ###
000 00000000 000 000 00000000 000 0000000
000 000 000 000 000 000 000
000 0000000 000 000 0000000 000 0000000
000 000 000 000 000 000
0000000 00000000 0 00000000 0000000 0000000
###
levelList = [
# 00 00 00000000 000 000 000 000
# 000 000 000 0000 000 000 000
# 000000000 0000000 000 0 000 000 000
# 000 0 000 000 000 0000 000 000
# 000 000 00000000 000 000 0000000
name: 'menu'
addUnit:0
msg: "KONNEKT"
hint: ["WELCOME TO", "A JS13K 2018 GAME\nBY MONSTERKODI"]
dots: [
v:[0,0,1], b:0
l:'TUTORIAL 1'
,
v:[0,-0.3,0.8]
l:'TUTORIAL 2'
,
v:[-0.3,-0.58,0.75]
l:'TUTORIAL 3'
,
v:[0.3,-0.58,0.75]
l:'TUTORIAL 4'
,
v:[0,-0.82,0.58]
l:'TUTORIAL 5'
,
v: [0,-1,0.01]
l: 'EASY'
,
v:[-1,0,0]
l:'<NAME>'
,
v:[-1,0,-1]
l:'RING'
,
v:[-1,1,-1]
l:'CLOSE'
,
v:[1,1,-1]
l:'<NAME>'
,
v:[1,0,-1]
l:'UNFAIR'
,
v:[1,0,-0.01]
l:'<NAME>'
,
v: [0,1,0]
l: 'RANDOM'
]
lines: [
[0,1]
[1,2]
[1,3]
[3,4]
[2,4]
[4,5]
[5,6]
[6,7]
[7,8]
[8,9]
[9,10]
[10,11]
[11,12]
]
,
# 000000000 000 000 000000000 0000000 00000000 000 0000000 000 000
# 000 000 000 000 000 000 000 000 000 000 000 000 00000
# 000 000 000 000 000 000 0000000 000 000000000 000 000000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 0000000 000 0000000 000 000 000 000 000 0000000 000
name: '<NAME>'
synt:
usr: instrument:'piano1'
bot: instrument:'piano2'
addUnit: 0
hint: ["You control the blue nodes. Your task is to fight the red nodes.\n\nNodes contain processes. The more processes, the stronger the node.", "Attack the infected red node by dragging from your blue node.\n\nEach time you attack, half of the available processes will be sent."]
dots: [
v: [-0.5,0,1]
u: 360
,
v: [0.5,0,1]
b: 270
]
,
# 000000000 000 000 000000000 0000000 00000000 000 0000000 000 00000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 000 000 000 000 000 0000000 000 000000000 000 000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 0000000 000 0000000 000 000 000 000 000 0000000 000000
name: 'TUTORIAL 2'
synt:
usr: instrument:'bell1'
bot: instrument:'bell2'
addUnit: 0
hint: ["To win, you need to deactivate all red nodes.\n\nIt is OK to leave inactive red nodes!", "This level contains 4 inactive and 2 active red nodes.\n\nDrag anywhere to rotate the sphere."]
dots: [
v: [0,0,1]
u: 90
,
v: [-0.2,0,1]
b: 11
,
v: [0.2,0,1]
b: 11
,
v: [0,0.2,1]
b: 11
,
v: [0,-0.2,1]
b: 11
,
v: [-0.1,0.1,-1]
b: 15
,
v: [0.1,0.1,-1]
b: 15
]
,
# 000000000 000 000 000000000 0000000 00000000 000 0000000 000 000000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 000 000 000 000 000 0000000 000 000000000 000 0000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 0000000 000 0000000 000 000 000 000 000 0000000 000000
name: 'TUTORIAL 3'
synt:
usr: instrument:'bell3'
bot: instrument:'bell4'
addUnit: 0
hint: ["Sending to nodes that you don't own isn't free.\n\nThe farther away the target node, the higher the cost.", "The cost factor is multiplied by the number of processes sent. The more you send, the more you loose.\n\nNotice that you need more attacks -- and loose more processes -- when defeating the far node."]
dots: [
v: [-0.9,-0.2,0.1]
u: 360
,
v: [-0.9,0.2,0.1]
u: 360
,
v: [-0.9,0,0.1]
b: 180
,
v: [0.9,0,0.1]
b: 180
]
,
name: 'TUTORIAL 4'
addUnit: 0
hint: ["Sending processes to nodes you own cost nothing.\n\nIt is efficient to occupy far away neutral nodes with few processes first and send larger groups later.", "Contrary to common believe,\nyou can't send processes between already connected nodes."]
dots: [
v: [-0.7,0.1,0.3]
u: 180
,
v: [-0.7,-0.1,0.3]
u: 12
,
v: [0.7,-0.1,0.3]
,
v: [0.7,0.1,0.3]
b: 135
]
lines: [ [0,1] ]
,
# 000000000 000 000 000000000 0000000 00000000 000 0000000 000 0000000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 000 000 000 000 000 0000000 000 000000000 000 0000000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 0000000 000 0000000 000 000 000 000 000 0000000 0000000
name: 'TUTORIAL 5'
addUnit: 3
hint: ["New processes are spawned regularily in active nodes.\n\nAlways make sure you have more active nodes than the opponent.", "You can see the number of active nodes in the top right corner.\n\nThe graph plots the relative amount of available processes."]
dots: [
v: [0,0,1]
u: 60
,
v: [-0.5,-0.5,1]
,
v: [ 0.5,-0.5,1]
,
v: [-0.5, 0.5,1]
,
v: [ 0.5, 0.5,1]
,
v: [-1, 0,1]
,
v: [ 1, 0,1]
,
v: [ 0,-1,1]
,
v: [ 0, 1,1]
,
v: [-1,-1,0]
b: 12
,
v: [ 1,-1,0]
b: 12
,
v: [-1, 1,0]
b: 12
,
v: [ 1, 1,0]
b: 12
,
v: [0,0,-1]
b: 12
]
,
# 00000000 0000000 0000000 000 000
# 000 000 000 000 000 000
# 0000000 000000000 0000000 00000
# 000 000 000 000 000
# 00000000 000 000 0000000 000
name: 'EASY'
synt:
usr: instrument:'organ1'
bot: instrument:'organ2'
addUnit: 2
hint: ["Be prepared, the red nodes are fighting back!", "You learned the basics, remove the virus from the system!"]
dots: [
v: [0,0,1]
u: 60
,
v: [-0.5,-0.5,1]
,
v: [ 0.5,-0.5,1]
,
v: [-0.5, 0.5,1]
,
v: [ 0.5, 0.5,1]
,
v: [-1, 0,1]
,
v: [ 1, 0,1]
,
v: [ 0,-1,1]
,
v: [ 0, 1,1]
,
v: [-1,-1,-1]
,
v: [ 1,-1,-1]
,
v: [-1, 1,-1]
,
v: [ 1, 1,-1]
,
v: [0,0,-1]
b: 60
]
bot:
speed: 8
i: -1
,
# 0000000 000 00000000 0000000 000 00000000 0000000
# 000 000 000 000 000 000 000 000
# 000 000 0000000 000 000 0000000 0000000
# 000 000 000 000 000 000 000 000
# 0000000 000 000 000 0000000 0000000 00000000 0000000
name: '<NAME>'
synt:
usr: instrument:'string'
bot: instrument:'flute'
addUnit: 4
dots: [
v: [0,0,1]
u: 60
,
c: [8,45,0,0]
,
c: [8,45,0,180]
,
c: [16,90,0,0]
,
v: [0,0,-1]
b: 60
]
bot:
speed: 7
i: -1
,
# 00000000 000 000 000 0000000
# 000 000 000 0000 000 000
# 0000000 000 000 0 000 000 0000
# 000 000 000 000 0000 000 000
# 000 000 000 000 000 0000000
name: '<NAME>'
synt:
usr: instrument:'bell1'
bot: instrument:'bell2'
addUnit: 4
dots: [
v: [0,0,1]
u: 60
,
c: [5,90,-30,90,30]
,
c: [5,-90,-30,90,30]
,
c: [5,70,-120,90,30]
,
c: [5,70,-60,-90,30]
,
v: [0,0,-1]
b: 60
]
bot:
speed: 5
i: -1
,
# 0000000 000 0000000 0000000 00000000
# 000 000 000 000 000 000
# 000 000 000 000 0000000 0000000
# 000 000 000 000 000 000
# 0000000 0000000 0000000 0000000 00000000
name: 'CLOSE'
addUnit: 4
dots: [
v: [-0.4,0,1]
u: 60
,
c: [11,90,-15,45,15]
,
c: [11,-90,-15,45,15]
,
v: [0.4,0,1]
b: 60
]
bot:
speed: 4
i: -1
,
# 00000000 0000000 000 00000000 0000000
# 000 000 000 000 000 000 000
# 00000000 000 000 000 0000000 0000000
# 000 000 000 000 000 000
# 000 0000000 0000000 00000000 0000000
name: '<NAME>'
synt:
usr: instrument:'bell3'
bot: instrument:'bell4'
addUnit: 4
dots: [
v: [0,0,1]
u: 60
,
c: [8,20,90,0]
,
c: [8,20,-90,0]
,
c: [8,20,0,90]
,
c: [8,20,0,-90]
,
v: [0,0,-1]
b: 60
]
bot:
speed: 6
i: -1
,
# 000 000 000 000 00000000 0000000 000 00000000
# 000 000 0000 000 000 000 000 000 000 000
# 000 000 000 0 000 000000 000000000 000 0000000
# 000 000 000 0000 000 000 000 000 000 000
# 0000000 000 000 000 000 000 000 000 000
name: '<NAME>'
addUnit: 6
synt:
usr: instrument:'bell3'
bot: instrument:'bell4'
dots: [
v: [0,0,1]
u: 90
,
c: [4,15,180,0]
,
c: [8,30,180,0]
,
c: [16,45,180,0]
,
v: [0,0,-1]
b: 360
]
bot:
speed: 3
i: -1
,
# 00000000 00000000 00000000 000 000 0000000 000 000
# 000 000 000 000 0000 000 000 000 000
# 000000 0000000 0000000 000 0 000 000 00000
# 000 000 000 000 000 0000 000 000
# 000 000 000 00000000 000 000 0000000 000
name: '<NAME>'
addUnit: 8
synt:
usr: instrument:'bell3'
bot: instrument:'bell4'
dots: [
v: [0,0,1]
u: 180
,
c: [4,22.5,0,0]
,
c: [4,22.5,180,0]
,
c: [4,22.5,90,0]
,
c: [4,22.5,-90,0]
,
c: [6,40,0,0]
,
c: [6,40,180,0]
,
c: [6,40,90,0]
,
c: [6,40,-90,0]
,
v: [0,0,-1]
b: 12
,
v: [1,0,0]
b: 12
,
v: [-1,0,0]
b: 12
,
v: [0,1,0]
b: 12
,
v: [0,-1,0]
b: 12
]
bot:
speed: 2
i: -1
]
levels = {}
for index in [0...levelList.length]
level = levelList[index]
level.index = index
levels[level.name] = level
| true | ###
000 00000000 000 000 00000000 000 0000000
000 000 000 000 000 000 000
000 0000000 000 000 0000000 000 0000000
000 000 000 000 000 000
0000000 00000000 0 00000000 0000000 0000000
###
levelList = [
# 00 00 00000000 000 000 000 000
# 000 000 000 0000 000 000 000
# 000000000 0000000 000 0 000 000 000
# 000 0 000 000 000 0000 000 000
# 000 000 00000000 000 000 0000000
name: 'menu'
addUnit:0
msg: "KONNEKT"
hint: ["WELCOME TO", "A JS13K 2018 GAME\nBY MONSTERKODI"]
dots: [
v:[0,0,1], b:0
l:'TUTORIAL 1'
,
v:[0,-0.3,0.8]
l:'TUTORIAL 2'
,
v:[-0.3,-0.58,0.75]
l:'TUTORIAL 3'
,
v:[0.3,-0.58,0.75]
l:'TUTORIAL 4'
,
v:[0,-0.82,0.58]
l:'TUTORIAL 5'
,
v: [0,-1,0.01]
l: 'EASY'
,
v:[-1,0,0]
l:'PI:NAME:<NAME>END_PI'
,
v:[-1,0,-1]
l:'RING'
,
v:[-1,1,-1]
l:'CLOSE'
,
v:[1,1,-1]
l:'PI:NAME:<NAME>END_PI'
,
v:[1,0,-1]
l:'UNFAIR'
,
v:[1,0,-0.01]
l:'PI:NAME:<NAME>END_PI'
,
v: [0,1,0]
l: 'RANDOM'
]
lines: [
[0,1]
[1,2]
[1,3]
[3,4]
[2,4]
[4,5]
[5,6]
[6,7]
[7,8]
[8,9]
[9,10]
[10,11]
[11,12]
]
,
# 000000000 000 000 000000000 0000000 00000000 000 0000000 000 000
# 000 000 000 000 000 000 000 000 000 000 000 000 00000
# 000 000 000 000 000 000 0000000 000 000000000 000 000000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 0000000 000 0000000 000 000 000 000 000 0000000 000
name: 'PI:NAME:<NAME>END_PI'
synt:
usr: instrument:'piano1'
bot: instrument:'piano2'
addUnit: 0
hint: ["You control the blue nodes. Your task is to fight the red nodes.\n\nNodes contain processes. The more processes, the stronger the node.", "Attack the infected red node by dragging from your blue node.\n\nEach time you attack, half of the available processes will be sent."]
dots: [
v: [-0.5,0,1]
u: 360
,
v: [0.5,0,1]
b: 270
]
,
# 000000000 000 000 000000000 0000000 00000000 000 0000000 000 00000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 000 000 000 000 000 0000000 000 000000000 000 000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 0000000 000 0000000 000 000 000 000 000 0000000 000000
name: 'TUTORIAL 2'
synt:
usr: instrument:'bell1'
bot: instrument:'bell2'
addUnit: 0
hint: ["To win, you need to deactivate all red nodes.\n\nIt is OK to leave inactive red nodes!", "This level contains 4 inactive and 2 active red nodes.\n\nDrag anywhere to rotate the sphere."]
dots: [
v: [0,0,1]
u: 90
,
v: [-0.2,0,1]
b: 11
,
v: [0.2,0,1]
b: 11
,
v: [0,0.2,1]
b: 11
,
v: [0,-0.2,1]
b: 11
,
v: [-0.1,0.1,-1]
b: 15
,
v: [0.1,0.1,-1]
b: 15
]
,
# 000000000 000 000 000000000 0000000 00000000 000 0000000 000 000000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 000 000 000 000 000 0000000 000 000000000 000 0000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 0000000 000 0000000 000 000 000 000 000 0000000 000000
name: 'TUTORIAL 3'
synt:
usr: instrument:'bell3'
bot: instrument:'bell4'
addUnit: 0
hint: ["Sending to nodes that you don't own isn't free.\n\nThe farther away the target node, the higher the cost.", "The cost factor is multiplied by the number of processes sent. The more you send, the more you loose.\n\nNotice that you need more attacks -- and loose more processes -- when defeating the far node."]
dots: [
v: [-0.9,-0.2,0.1]
u: 360
,
v: [-0.9,0.2,0.1]
u: 360
,
v: [-0.9,0,0.1]
b: 180
,
v: [0.9,0,0.1]
b: 180
]
,
name: 'TUTORIAL 4'
addUnit: 0
hint: ["Sending processes to nodes you own cost nothing.\n\nIt is efficient to occupy far away neutral nodes with few processes first and send larger groups later.", "Contrary to common believe,\nyou can't send processes between already connected nodes."]
dots: [
v: [-0.7,0.1,0.3]
u: 180
,
v: [-0.7,-0.1,0.3]
u: 12
,
v: [0.7,-0.1,0.3]
,
v: [0.7,0.1,0.3]
b: 135
]
lines: [ [0,1] ]
,
# 000000000 000 000 000000000 0000000 00000000 000 0000000 000 0000000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 000 000 000 000 000 0000000 000 000000000 000 0000000
# 000 000 000 000 000 000 000 000 000 000 000 000 000
# 000 0000000 000 0000000 000 000 000 000 000 0000000 0000000
name: 'TUTORIAL 5'
addUnit: 3
hint: ["New processes are spawned regularily in active nodes.\n\nAlways make sure you have more active nodes than the opponent.", "You can see the number of active nodes in the top right corner.\n\nThe graph plots the relative amount of available processes."]
dots: [
v: [0,0,1]
u: 60
,
v: [-0.5,-0.5,1]
,
v: [ 0.5,-0.5,1]
,
v: [-0.5, 0.5,1]
,
v: [ 0.5, 0.5,1]
,
v: [-1, 0,1]
,
v: [ 1, 0,1]
,
v: [ 0,-1,1]
,
v: [ 0, 1,1]
,
v: [-1,-1,0]
b: 12
,
v: [ 1,-1,0]
b: 12
,
v: [-1, 1,0]
b: 12
,
v: [ 1, 1,0]
b: 12
,
v: [0,0,-1]
b: 12
]
,
# 00000000 0000000 0000000 000 000
# 000 000 000 000 000 000
# 0000000 000000000 0000000 00000
# 000 000 000 000 000
# 00000000 000 000 0000000 000
name: 'EASY'
synt:
usr: instrument:'organ1'
bot: instrument:'organ2'
addUnit: 2
hint: ["Be prepared, the red nodes are fighting back!", "You learned the basics, remove the virus from the system!"]
dots: [
v: [0,0,1]
u: 60
,
v: [-0.5,-0.5,1]
,
v: [ 0.5,-0.5,1]
,
v: [-0.5, 0.5,1]
,
v: [ 0.5, 0.5,1]
,
v: [-1, 0,1]
,
v: [ 1, 0,1]
,
v: [ 0,-1,1]
,
v: [ 0, 1,1]
,
v: [-1,-1,-1]
,
v: [ 1,-1,-1]
,
v: [-1, 1,-1]
,
v: [ 1, 1,-1]
,
v: [0,0,-1]
b: 60
]
bot:
speed: 8
i: -1
,
# 0000000 000 00000000 0000000 000 00000000 0000000
# 000 000 000 000 000 000 000 000
# 000 000 0000000 000 000 0000000 0000000
# 000 000 000 000 000 000 000 000
# 0000000 000 000 000 0000000 0000000 00000000 0000000
name: 'PI:NAME:<NAME>END_PI'
synt:
usr: instrument:'string'
bot: instrument:'flute'
addUnit: 4
dots: [
v: [0,0,1]
u: 60
,
c: [8,45,0,0]
,
c: [8,45,0,180]
,
c: [16,90,0,0]
,
v: [0,0,-1]
b: 60
]
bot:
speed: 7
i: -1
,
# 00000000 000 000 000 0000000
# 000 000 000 0000 000 000
# 0000000 000 000 0 000 000 0000
# 000 000 000 000 0000 000 000
# 000 000 000 000 000 0000000
name: 'PI:NAME:<NAME>END_PI'
synt:
usr: instrument:'bell1'
bot: instrument:'bell2'
addUnit: 4
dots: [
v: [0,0,1]
u: 60
,
c: [5,90,-30,90,30]
,
c: [5,-90,-30,90,30]
,
c: [5,70,-120,90,30]
,
c: [5,70,-60,-90,30]
,
v: [0,0,-1]
b: 60
]
bot:
speed: 5
i: -1
,
# 0000000 000 0000000 0000000 00000000
# 000 000 000 000 000 000
# 000 000 000 000 0000000 0000000
# 000 000 000 000 000 000
# 0000000 0000000 0000000 0000000 00000000
name: 'CLOSE'
addUnit: 4
dots: [
v: [-0.4,0,1]
u: 60
,
c: [11,90,-15,45,15]
,
c: [11,-90,-15,45,15]
,
v: [0.4,0,1]
b: 60
]
bot:
speed: 4
i: -1
,
# 00000000 0000000 000 00000000 0000000
# 000 000 000 000 000 000 000
# 00000000 000 000 000 0000000 0000000
# 000 000 000 000 000 000
# 000 0000000 0000000 00000000 0000000
name: 'PI:NAME:<NAME>END_PI'
synt:
usr: instrument:'bell3'
bot: instrument:'bell4'
addUnit: 4
dots: [
v: [0,0,1]
u: 60
,
c: [8,20,90,0]
,
c: [8,20,-90,0]
,
c: [8,20,0,90]
,
c: [8,20,0,-90]
,
v: [0,0,-1]
b: 60
]
bot:
speed: 6
i: -1
,
# 000 000 000 000 00000000 0000000 000 00000000
# 000 000 0000 000 000 000 000 000 000 000
# 000 000 000 0 000 000000 000000000 000 0000000
# 000 000 000 0000 000 000 000 000 000 000
# 0000000 000 000 000 000 000 000 000 000
name: 'PI:NAME:<NAME>END_PI'
addUnit: 6
synt:
usr: instrument:'bell3'
bot: instrument:'bell4'
dots: [
v: [0,0,1]
u: 90
,
c: [4,15,180,0]
,
c: [8,30,180,0]
,
c: [16,45,180,0]
,
v: [0,0,-1]
b: 360
]
bot:
speed: 3
i: -1
,
# 00000000 00000000 00000000 000 000 0000000 000 000
# 000 000 000 000 0000 000 000 000 000
# 000000 0000000 0000000 000 0 000 000 00000
# 000 000 000 000 000 0000 000 000
# 000 000 000 00000000 000 000 0000000 000
name: 'PI:NAME:<NAME>END_PI'
addUnit: 8
synt:
usr: instrument:'bell3'
bot: instrument:'bell4'
dots: [
v: [0,0,1]
u: 180
,
c: [4,22.5,0,0]
,
c: [4,22.5,180,0]
,
c: [4,22.5,90,0]
,
c: [4,22.5,-90,0]
,
c: [6,40,0,0]
,
c: [6,40,180,0]
,
c: [6,40,90,0]
,
c: [6,40,-90,0]
,
v: [0,0,-1]
b: 12
,
v: [1,0,0]
b: 12
,
v: [-1,0,0]
b: 12
,
v: [0,1,0]
b: 12
,
v: [0,-1,0]
b: 12
]
bot:
speed: 2
i: -1
]
levels = {}
for index in [0...levelList.length]
level = levelList[index]
level.index = index
levels[level.name] = level
|
[
{
"context": "n = app.createModel \"UserModule\",\n email: \"admin@publish.org\"\n username: \"admin\"\n password: \"pas",
"end": 736,
"score": 0.9999209642410278,
"start": 719,
"tag": "EMAIL",
"value": "admin@publish.org"
},
{
"context": " email: \"admin@publ... | components/cms/sysmodules/user/server.coffee | dni/CCLV | 0 | auth = require "../../lib/utilities/auth"
passport = require "passport"
User = {}
module.exports.setup = (app, config)->
User = require('../../lib/model/Schema')(config)
app.get "/user", auth, (req, res)->
res.send app.user
# login
app.get '/login', (req, res)->
res.sendfile process.cwd()+'/components/cms/login.html'
app.post '/login',
passport.authenticate('local', failureRedirect: '/login'),
(req, res)->
res.redirect app.config.adminroute
app.get '/logout', (req, res)->
req.logout()
res.redirect '/login'
# create default admin user if no user exists
User.count {}, (err, count)->
if count == 0
admin = app.createModel "UserModule",
email: "admin@publish.org"
username: "admin"
password: "password"
title: "administrator"
admin.save()
console.log "admin user was created"
module.exports.localstrategy = (username, password, done) ->
User.findOne(
username: username
password: password
).exec (err, user)->
done err, user
module.exports.deserialize = (_id, done)->
User.findById _id, (err, user)->
done(err, user)
| 69547 | auth = require "../../lib/utilities/auth"
passport = require "passport"
User = {}
module.exports.setup = (app, config)->
User = require('../../lib/model/Schema')(config)
app.get "/user", auth, (req, res)->
res.send app.user
# login
app.get '/login', (req, res)->
res.sendfile process.cwd()+'/components/cms/login.html'
app.post '/login',
passport.authenticate('local', failureRedirect: '/login'),
(req, res)->
res.redirect app.config.adminroute
app.get '/logout', (req, res)->
req.logout()
res.redirect '/login'
# create default admin user if no user exists
User.count {}, (err, count)->
if count == 0
admin = app.createModel "UserModule",
email: "<EMAIL>"
username: "admin"
password: "<PASSWORD>"
title: "administrator"
admin.save()
console.log "admin user was created"
module.exports.localstrategy = (username, password, done) ->
User.findOne(
username: username
password: <PASSWORD>
).exec (err, user)->
done err, user
module.exports.deserialize = (_id, done)->
User.findById _id, (err, user)->
done(err, user)
| true | auth = require "../../lib/utilities/auth"
passport = require "passport"
User = {}
module.exports.setup = (app, config)->
User = require('../../lib/model/Schema')(config)
app.get "/user", auth, (req, res)->
res.send app.user
# login
app.get '/login', (req, res)->
res.sendfile process.cwd()+'/components/cms/login.html'
app.post '/login',
passport.authenticate('local', failureRedirect: '/login'),
(req, res)->
res.redirect app.config.adminroute
app.get '/logout', (req, res)->
req.logout()
res.redirect '/login'
# create default admin user if no user exists
User.count {}, (err, count)->
if count == 0
admin = app.createModel "UserModule",
email: "PI:EMAIL:<EMAIL>END_PI"
username: "admin"
password: "PI:PASSWORD:<PASSWORD>END_PI"
title: "administrator"
admin.save()
console.log "admin user was created"
module.exports.localstrategy = (username, password, done) ->
User.findOne(
username: username
password: PI:PASSWORD:<PASSWORD>END_PI
).exec (err, user)->
done err, user
module.exports.deserialize = (_id, done)->
User.findById _id, (err, user)->
done(err, user)
|
[
{
"context": " databasePath: @databasePath\n password: password\n lifetime: lifetime\n\n stop: (callback) ->",
"end": 538,
"score": 0.9993552565574646,
"start": 530,
"tag": "PASSWORD",
"value": "password"
}
] | lib/password_server.coffee | jacobmarshall-etc/1pass | 0 | fs = require 'fs'
path = require 'path'
net = require 'net'
child_process = require 'child_process'
class PasswordServer
constructor: (@rcDir, @databasePath) ->
@socketPath = (rcDir + '/sockets/' + databasePath).replace(/\/+/g, '/')
start: (password, lifetime, callback) ->
@stop =>
child = child_process.fork(__dirname + '/password_server_child')
child.on 'message', ->
callback(child.pid) if callback
child.send
rcDir: @rcDir
databasePath: @databasePath
password: password
lifetime: lifetime
stop: (callback) ->
buffer = []
fs.exists @socketPath, (exists) =>
return callback() if !exists
@_read (pid, pass) =>
if !pid
fs.unlink @socketPath, callback
else
@_killAndWait pid, 'SIGTERM', 2000, (result) =>
if result
callback() if callback
else
@_killAndWait pid, 'SIGKILL', 2000, =>
callback() if callback
get: (callback) ->
@_read (pid, pass) ->
callback(pass)
_makeDirs: (dir) ->
unless fs.existsSync(dir)
@_makeDirs path.dirname(dir)
fs.mkdirSync(dir)
_exec: (password, lifetime, readyCallback) ->
cleanUp = =>
fs.unlinkSync(@socketPath) if fs.existsSync(@socketPath)
process.exit()
process.on 'SIGINT' , cleanUp
process.on 'SIGTERM', cleanUp
process.on 'SIGALRM', cleanUp
server = net.createServer (socket) =>
socket.end("#{process.pid}\n#{password}")
server.on 'close', cleanUp
@_makeDirs path.dirname(@socketPath)
setTimeout (-> process.kill(process.pid, 'SIGALRM')), lifetime
server.listen @socketPath, =>
fs.chmodSync(@socketPath, 0o600)
readyCallback()
_read: (callback) ->
buffer = []
socket = new net.Socket(type: 'unix')
socket.on 'error', -> # don't throw error if connect fails
socket.on 'data', (data) -> buffer.push data
socket.on 'close', ->
[pid, pass] = buffer.join('').split(/\n/)
callback(pid or null, pass or null)
socket.connect path: @socketPath, ->
socket.end()
_killAndWait: (pid, signal, timeout, callback) ->
return if !pid
process.kill(pid, signal)
@_waitFor
timeout: timeout
condition: (done) =>
fs.exists @socketPath, (exists) -> done !exists
complete: callback
_waitFor: ({timeout, condition, complete}) ->
condition (result) =>
if result
complete true
else
if timeout <= 0
complete false
else
sleep = 100
setTimeout (=>
@_waitFor
timeout: timeout - sleep
condition: condition
complete: complete
), sleep
module.exports = PasswordServer
| 17688 | fs = require 'fs'
path = require 'path'
net = require 'net'
child_process = require 'child_process'
class PasswordServer
constructor: (@rcDir, @databasePath) ->
@socketPath = (rcDir + '/sockets/' + databasePath).replace(/\/+/g, '/')
start: (password, lifetime, callback) ->
@stop =>
child = child_process.fork(__dirname + '/password_server_child')
child.on 'message', ->
callback(child.pid) if callback
child.send
rcDir: @rcDir
databasePath: @databasePath
password: <PASSWORD>
lifetime: lifetime
stop: (callback) ->
buffer = []
fs.exists @socketPath, (exists) =>
return callback() if !exists
@_read (pid, pass) =>
if !pid
fs.unlink @socketPath, callback
else
@_killAndWait pid, 'SIGTERM', 2000, (result) =>
if result
callback() if callback
else
@_killAndWait pid, 'SIGKILL', 2000, =>
callback() if callback
get: (callback) ->
@_read (pid, pass) ->
callback(pass)
_makeDirs: (dir) ->
unless fs.existsSync(dir)
@_makeDirs path.dirname(dir)
fs.mkdirSync(dir)
_exec: (password, lifetime, readyCallback) ->
cleanUp = =>
fs.unlinkSync(@socketPath) if fs.existsSync(@socketPath)
process.exit()
process.on 'SIGINT' , cleanUp
process.on 'SIGTERM', cleanUp
process.on 'SIGALRM', cleanUp
server = net.createServer (socket) =>
socket.end("#{process.pid}\n#{password}")
server.on 'close', cleanUp
@_makeDirs path.dirname(@socketPath)
setTimeout (-> process.kill(process.pid, 'SIGALRM')), lifetime
server.listen @socketPath, =>
fs.chmodSync(@socketPath, 0o600)
readyCallback()
_read: (callback) ->
buffer = []
socket = new net.Socket(type: 'unix')
socket.on 'error', -> # don't throw error if connect fails
socket.on 'data', (data) -> buffer.push data
socket.on 'close', ->
[pid, pass] = buffer.join('').split(/\n/)
callback(pid or null, pass or null)
socket.connect path: @socketPath, ->
socket.end()
_killAndWait: (pid, signal, timeout, callback) ->
return if !pid
process.kill(pid, signal)
@_waitFor
timeout: timeout
condition: (done) =>
fs.exists @socketPath, (exists) -> done !exists
complete: callback
_waitFor: ({timeout, condition, complete}) ->
condition (result) =>
if result
complete true
else
if timeout <= 0
complete false
else
sleep = 100
setTimeout (=>
@_waitFor
timeout: timeout - sleep
condition: condition
complete: complete
), sleep
module.exports = PasswordServer
| true | fs = require 'fs'
path = require 'path'
net = require 'net'
child_process = require 'child_process'
class PasswordServer
constructor: (@rcDir, @databasePath) ->
@socketPath = (rcDir + '/sockets/' + databasePath).replace(/\/+/g, '/')
start: (password, lifetime, callback) ->
@stop =>
child = child_process.fork(__dirname + '/password_server_child')
child.on 'message', ->
callback(child.pid) if callback
child.send
rcDir: @rcDir
databasePath: @databasePath
password: PI:PASSWORD:<PASSWORD>END_PI
lifetime: lifetime
stop: (callback) ->
buffer = []
fs.exists @socketPath, (exists) =>
return callback() if !exists
@_read (pid, pass) =>
if !pid
fs.unlink @socketPath, callback
else
@_killAndWait pid, 'SIGTERM', 2000, (result) =>
if result
callback() if callback
else
@_killAndWait pid, 'SIGKILL', 2000, =>
callback() if callback
get: (callback) ->
@_read (pid, pass) ->
callback(pass)
_makeDirs: (dir) ->
unless fs.existsSync(dir)
@_makeDirs path.dirname(dir)
fs.mkdirSync(dir)
_exec: (password, lifetime, readyCallback) ->
cleanUp = =>
fs.unlinkSync(@socketPath) if fs.existsSync(@socketPath)
process.exit()
process.on 'SIGINT' , cleanUp
process.on 'SIGTERM', cleanUp
process.on 'SIGALRM', cleanUp
server = net.createServer (socket) =>
socket.end("#{process.pid}\n#{password}")
server.on 'close', cleanUp
@_makeDirs path.dirname(@socketPath)
setTimeout (-> process.kill(process.pid, 'SIGALRM')), lifetime
server.listen @socketPath, =>
fs.chmodSync(@socketPath, 0o600)
readyCallback()
_read: (callback) ->
buffer = []
socket = new net.Socket(type: 'unix')
socket.on 'error', -> # don't throw error if connect fails
socket.on 'data', (data) -> buffer.push data
socket.on 'close', ->
[pid, pass] = buffer.join('').split(/\n/)
callback(pid or null, pass or null)
socket.connect path: @socketPath, ->
socket.end()
_killAndWait: (pid, signal, timeout, callback) ->
return if !pid
process.kill(pid, signal)
@_waitFor
timeout: timeout
condition: (done) =>
fs.exists @socketPath, (exists) -> done !exists
complete: callback
_waitFor: ({timeout, condition, complete}) ->
condition (result) =>
if result
complete true
else
if timeout <= 0
complete false
else
sleep = 100
setTimeout (=>
@_waitFor
timeout: timeout - sleep
condition: condition
complete: complete
), sleep
module.exports = PasswordServer
|
[
{
"context": "ts =\n email:\n from: process.env.SMTP_FROM || 'admin@abc.com'\n opts:\n host: process.env.SMTP_HOST || '",
"end": 75,
"score": 0.9998924136161804,
"start": 62,
"tag": "EMAIL",
"value": "admin@abc.com"
}
] | backend/config/email.coffee | twhtanghk/rest.smtp | 0 | module.exports =
email:
from: process.env.SMTP_FROM || 'admin@abc.com'
opts:
host: process.env.SMTP_HOST || 'smtp.abc.com'
port: process.env.SMTP_PORT || 25
secure: false
| 56370 | module.exports =
email:
from: process.env.SMTP_FROM || '<EMAIL>'
opts:
host: process.env.SMTP_HOST || 'smtp.abc.com'
port: process.env.SMTP_PORT || 25
secure: false
| true | module.exports =
email:
from: process.env.SMTP_FROM || 'PI:EMAIL:<EMAIL>END_PI'
opts:
host: process.env.SMTP_HOST || 'smtp.abc.com'
port: process.env.SMTP_PORT || 25
secure: false
|
[
{
"context": " type: 'select'\n placement: 'right'\n name: 'dummy'\n pk: null\n callback: null\n value: -> nu",
"end": 117,
"score": 0.9549097418785095,
"start": 112,
"tag": "NAME",
"value": "dummy"
}
] | client/utils.coffee | tyrchen/teamspark | 21 | @ts = @ts || {}
ts.setEditable = (options) ->
defaults =
type: 'select'
placement: 'right'
name: 'dummy'
pk: null
callback: null
value: -> null
source: -> null
renderCallback: (e, editable) ->
showCallback: (e, editable) ->
defaults = _.extend defaults, options
defaults.node.editable(
type: defaults.type
value: defaults.value
placement: defaults.placement
name: defaults.name
pk: defaults.pk
source: defaults.source
).on('render', (e, editable) ->
defaults.renderCallback(e, editable)
)
ts.isIphone = ->
navigator.userAgent.match(/iPhone|iPod/i)?
ts.isIpad = ->
navigator.userAgent.match(/iPad/i)? | 129549 | @ts = @ts || {}
ts.setEditable = (options) ->
defaults =
type: 'select'
placement: 'right'
name: '<NAME>'
pk: null
callback: null
value: -> null
source: -> null
renderCallback: (e, editable) ->
showCallback: (e, editable) ->
defaults = _.extend defaults, options
defaults.node.editable(
type: defaults.type
value: defaults.value
placement: defaults.placement
name: defaults.name
pk: defaults.pk
source: defaults.source
).on('render', (e, editable) ->
defaults.renderCallback(e, editable)
)
ts.isIphone = ->
navigator.userAgent.match(/iPhone|iPod/i)?
ts.isIpad = ->
navigator.userAgent.match(/iPad/i)? | true | @ts = @ts || {}
ts.setEditable = (options) ->
defaults =
type: 'select'
placement: 'right'
name: 'PI:NAME:<NAME>END_PI'
pk: null
callback: null
value: -> null
source: -> null
renderCallback: (e, editable) ->
showCallback: (e, editable) ->
defaults = _.extend defaults, options
defaults.node.editable(
type: defaults.type
value: defaults.value
placement: defaults.placement
name: defaults.name
pk: defaults.pk
source: defaults.source
).on('render', (e, editable) ->
defaults.renderCallback(e, editable)
)
ts.isIphone = ->
navigator.userAgent.match(/iPhone|iPod/i)?
ts.isIpad = ->
navigator.userAgent.match(/iPad/i)? |
[
{
"context": "nished = @digger.create (x,y,solid) =>\n key = x+\",\"+y\n @maps[l][key] =\n val: if solid then ",
"end": 3271,
"score": 0.9987694025039673,
"start": 3264,
"tag": "KEY",
"value": "x+\",\"+y"
}
] | game.coffee | fazo96/aDemonsMaze | 3 | # This is A Demon's Maze main game file.
# Please look for a LICENSE.txt file in this folder for licensing information.
# Utility function. Needed!
Array::delete = (o) ->
@splice @indexOf(o), 1
Game =
w: 50
h: 50
screen_w: 80
screen_h: 25
camera_w: 80
camera_h: 23
debug: no
maps: []
monsters: []
# Called only once per session: also starts the game
init: ->
console.log "A Demon's Maze - WIP"
if ROT.isSupported() is no # Can't play.
document.getElementById("gameContainer").innerHTML = """
<h3>Oh! Your browser does not support HTML5 Canvas!</h3>
<p>Try Firefox or Chrome!</p>
"""
return
# Init
@display = new ROT.Display { width: @screen_w, height: @screen_h }
document.getElementById("gameContainer").appendChild @display.getContainer()
@newGame()
console.log "Done init"
# Resets the game
newGame: ->
@scheduler = new ROT.Scheduler.Action()
@maps = []; @monsters = []; @player = undefined
@camera = new Camera 0,0,@camera_w,@camera_h
@newLevel 1
@scheduler.next().act()
###
Cretes a new level if it's not generated yet
l: which level
moveTo: move the player to the level
###
newLevel: (l,moveTo) ->
moveTo = moveTo or yes
oldLevel = if @player then @player.z else 1
# Map
@player.z = l if @player and moveTo is yes
if @maps[l] is undefined
console.log "Generating Level: "+l
# Generate map
@generateMap l
loc = @getEmptyLoc no
if oldLevel isnt l
@map(loc.x,loc.y,l).type = "stairs"
@map(loc.x,loc.y,l).val = if oldLevel > l then "<" else ">"
console.log "Placed "+@map(loc.x,loc.y,l).val+" tile"
if @player is undefined or @player is null
@player = new Player loc.x, loc.y, l
@scheduler.add @player, yes, 0
# Stairs
loc2 = @getEmptyLoc yes
#while loc2.x is loc.x and loc2.y is loc.y
#loc2 = @getEmptyLoc yes
@map(loc2.x,loc2.y,l).type = "stairs"
@map(loc2.x,loc2.y,l).val = if oldLevel > l then ">" else "<"
else console.log "Loading Level: "+l
if @player.pos[l] isnt undefined
@player.x = @player.pos[l].x
@player.y = @player.pos[l].y
else
@player.x = loc.x; @player.y = loc.y
Game.camera.setCenter @player.x,@player.y
# Generate Monsters
if not @monsters[l]
@monsters[l] = []
times = Math.floor l * 1.5 + ROT.RNG.getUniform() * 6 - 3
if times > 15 then times = 15
console.log "Generating " + times + " monsters on floor "+l
if times > 0
for i in [1..times]
loc = @getEmptyLoc yes
@monsters[l].push new Monster(loc.x, loc.y, l)
if moveTo # Change level
console.log "Player moving to level "+l
# Stop old monsters' AI for now
if @monsters[oldLevel]
@scheduler.remove monster for monster in @monsters[oldLevel]
# Enter new monsters' AI
@scheduler.add monster, yes, 50 for monster in @monsters[l]
@draw()
# Generate the map at the given level. Overwrites existing level
generateMap: (l) ->
@map_done = no; @rooms_done = no; times = 0
@maps[l] = {}
@digger = new ROT.Map.Digger @w, @h
finished = @digger.create (x,y,solid) =>
key = x+","+y
@maps[l][key] =
val: if solid then " " else "."
seen: no
type: if solid then "wall" else "floor"
block: if solid then yes else no
fg: if solid then "#000" else "#777"
bg: if solid then "#444" else "#000"
fg_light: if solid then "#000" else "#fff"
bg_light: if solid then "#660" else "#aa0"
times++
if times is @w*@h
@map_done = yes
console.log "[Map:"+l+"] Generated structure"
console.log "[Map:"+l+"] Finalizing map..."
for i,room of @digger.getRooms()
continue unless room.getDoors
room.getDoors (x,y) =>
k = x+","+y
@maps[l][k].val = "+"
@maps[l][k].type = "door"
@maps[l][k].fg = "#3a261a"
@maps[l][k].block = yes
@maps[l][k].fg_light = "#584338"
@rooms_done = yes if i is @digger.getRooms().length - 1
console.log "[Map:"+l+"] Finished"
# Get coordinates
map : (x,y,z) -> z ?= @player.z; @maps[z][x+","+y]
drawMap : (onlySeen) ->
onlySeen = onlySeen or no; l = @player.z
for key of @maps[l]
if @maps[l][key].seen is yes or onlySeen is no
@camera.draw key.split(",")[0], key.split(",")[1],
@maps[l][key].val, @maps[l][key].fg, @maps[l][key].bg
# Draws the UI
drawUI: () ->
# Separator
s = ""; s += "_" for i in [1..@camera_w]
@display.drawText 0, @camera_h, s
# Player HP
if @player.hp > 0
@display.drawText 0, @camera_h+1, "HP "
for i in [1..10]
@display.draw 2+i,@camera_h+1, "=", "#a00", "#000"
for i in [1..Math.floor @player.hp / 10]
@display.draw 2+i,@camera_h+1, "=", "#f00", "#000"
else @display.drawText 0,@camera_h+1, "Game Over! Press Enter"
# Other
@display.drawText @screen_w-9, @camera_h+1, "Floor: "+@player.z
@display.drawText 15,@camera_h+1,"Ouch!" unless @player.hp is @player.oldHp
@player.oldHp = @player.hp
# Draws the game graphics. Call this every time a change is made
draw : ->
if not @map_done
# Map has to be finished
return
@display.clear()
# Draw player FOV and player
@player.drawMemory()
@player.drawVisible()
@camera.draw @player.x, @player.y, '@', "#fff", "#aa0"
@drawUI()
# Draw Monsters (Debug)
#for monster in @monsters[@player.z]
#@camera.draw monster.x, monster.y, 'M', "#fff", "#000"
# Is x,y in room?
inRoom : (room, x, y) ->
if room then room.x1 <= x <= room.x2 and room.y1 <= y <= room.y2 else no
isBlocked : (x,y,l,ignorePlayer) ->
l = l or @player.z; ignorePlayer = ignorePlayer or no
if not @map(x,y,l) then return yes
if @map(x,y,l).block is yes then return yes
if ignorePlayer is no
if @player.x is x and @player.y is y and @player.z is l then return yes
return no unless @monsters and @monsters[l]
for monster in @monsters[l]
return yes if monster.x is x and monster.y is y
no
# Get a location in a room where there's nothing else, at level @player.z
# away: if you want it away from the player's current position
getEmptyLoc: (away)->
away = away or yes
return unless @digger; rs = @digger.getRooms()
loop
ok = no
while ok is no
r = rs[Math.floor(ROT.RNG.getUniform() * @digger.getRooms().length - 1)]
if not @player or away is off or @inRoom(r,@player.x,@player.y) is no
if r then ok = yes
x = r.getLeft()
+ Math.floor ROT.RNG.getUniform() * (r.getRight() - r.getLeft())
y = r.getTop()
+ Math.floor ROT.RNG.getUniform() * (r.getBottom() - r.getTop())
return {x,y} unless @player and @player.x is x and @player.y is y
# Camera object: follows the player.
# Draw calls for the game world must be made to the camera
# Instance at Game.camera
Camera = (x,y,w,h) ->
@x = x; @y = y; @w = w; @h = h
@slideOffset = 10
Camera::getCenter = ->
{ x: @x + @w/2, y: @y + @h/2 }
# Convert world coords to screen
Camera::fromWorld = (x,y) ->
{ x: x-@x; y: y-@y }
# Move the camera by x, y
Camera::slide = (x,y) ->
@x += Math.floor x unless not x
@y += Math.floor y unless not y
# Moves the camera so x,y is at the center
Camera::setCenter = (x,y) ->
return unless x and y
@x = Math.floor x - @w/2; @y = Math.floor y - @h/2
# True if x,y is visible
Camera::visible = (x,y) ->
x > @x and x < @x+@w and y > @y and y < @y+@h
# Draw ch at x,y using fg color for foreground and bg color for background
Camera::draw = (x,y,ch,fg,bg) ->
Game.display.draw x-@x,y-@y,ch,fg,bg
class Entity
constructor: (@x,@y,@z,@maxhp) ->
@hp = @maxhp
@mem = {}
memory : (x,y,z) ->
act: -> console.log "unconfigured entity ai"
# Player object
# Instance at Game.player
class Player extends Entity
constructor : (x,y,z) ->
super x,y,z,100
@oldHp = @hp; @reqEnter = no
@shiftDown = no; @closeDoor = no
@move @x, @y
@pos = {}; @keyMap = {}; @sounds = []
@keyMap[38] = @keyMap[104] = 0 # up
@keyMap[33] = @keyMap[105] = 1
@keyMap[39] = @keyMap[102] = 2 # right
@keyMap[34] = @keyMap[99] = 3
@keyMap[40] = @keyMap[98] = 4 # down
@keyMap[35] = @keyMap[97] = 5
@keyMap[37] = @keyMap[100] = 6 # left
@keyMap[36] = @keyMap[103] = 7
# Workaround for problem with removing listeners when functions are bound
@_onKeyUp = @onKeyUp.bind this
@_onKeyDown = @onKeyDown.bind this
window.addEventListener "keyup", @_onKeyUp
# Callback for the turn scheduler
act : ->
if @hp <= 0
#Game.display.drawText 15,@camera_h+1,"Game Over!"
Game.draw() unless @reqEnter is yes
@reqEnter = yes
window.addEventListener "keydown", @_onKeyDown
# Callback for keyboard key released event
onKeyUp : (e) ->
if e.keyCode is 16
@shiftDown = no
# Callback for keyboard key pressed event
onKeyDown : (e) ->
finished = no
#console.log "Keycode: "+e.keyCode
# start possible actions --->
if @reqEnter is yes
if e.keyCode is 13
if @hp <= 0
Game.newGame()
finished = yes
else finished = no
return
if e.keyCode is 16 # Shift
@shiftDown = yes
else if e.keyCode is 67 # c
@closeDoor = yes
if e.keyCode is 101 or e.keyCode is 190 # dot symbol or Numpad 5: wait
finished = yes # Do nothing, pass turn
Game.scheduler.setDuration 5
if (e.keyCode is 60 or e.keyCode is 83) and Game.map(@x,@y).type is "stairs"
if Game.map(@x,@y).val is ">" and (@shiftDown or e.keyCode is 83)
# Go downstairs
@pos[@z] = { x: @x, y: @y }
Game.newLevel @z - 1
finished = yes
else if Game.map(@x,@y).val is "<" and (not @shiftDown or e.keyCode is 83)
# Go upstairs
@pos[@z] = { x: @x, y: @y }
Game.newLevel @z + 1
finished = yes
if finished is yes then Game.scheduler.setDuration 5
else if 36 <= e.keyCode <= 40 or 97 <= e.keyCode <= 105
# Direction Key
dir = ROT.DIRS[8][@keyMap[e.keyCode]]
if dir
newX = @x + dir[0]; newY = @y + dir[1]
blocked = Game.isBlocked(newX,newY,@z,no)
# Door: open or close
if Game.map(newX,newY).type is "door"
if @closeDoor is yes and blocked is no
Game.map(newX,newY).val = "+"
Game.map(newX,newY).block = yes
Game.draw(); finished = yes
else if @closeDoor is no and Game.map(newX,newY).val is "+"
Game.map(newX,newY).val = "\'"
Game.map(newX,newY).block = no
Game.draw(); finished = yes
if blocked is no and finished is no
# Move Into Open Space
@move newX, newY
Game.draw()
finished = yes
if finished is yes then Game.scheduler.setDuration 10
if e.keyCode isnt 67 then @closeDoor = no
# <--- end actions
if finished is yes # This turn is over
window.removeEventListener "keydown", @_onKeyDown
Game.scheduler.next().act()
# Move player to newX, newY in the game world
move : (newX, newY)->
#return unless newX and newY and newX isnt @x and newY isnt @y
onScreen = Game.camera.fromWorld newX, newY
if onScreen.x > Game.camera.w-Game.camera.slideOffset
Game.camera.slide 1,0
else if onScreen.x < Game.camera.slideOffset then Game.camera.slide -1,0
if onScreen.y < Game.camera.slideOffset then Game.camera.slide 0,-1
else if onScreen.y > Game.camera.h-Game.camera.slideOffset
Game.camera.slide 0,1
@x = newX; @y = newY
# Draw the known tiles of the map
drawMemory : ->
for x in [Game.camera.x .. Game.camera.x+Game.camera.w-1]
for y in [Game.camera.y .. Game.camera.y+Game.camera.h-1]
if Game.map(x,y) and Game.map(x,y).seen is true
Game.camera.draw x, y, Game.map(x,y).val,
Game.map(x,y).fg,
Game.map(x,y).bg
# Draw lighting and visible tiles, monsters and doors
drawVisible : ->
if not @fov
@fov = new ROT.FOV.PreciseShadowcasting (x,y) ->
Game.isBlocked(x,y,@z,yes) is no
# Draw heard sounds
for s in @sounds
Game.camera.draw s.x, s.y, s.val, s.light
@sounds = []
@fov.compute @x, @y, 6, (x, y, r, v) =>
return unless Game.map(x,y)
Game.map(x,y).seen = yes
Game.camera.draw x, y, Game.map(x,y).val,
Game.map(x,y).fg_light,
Game.map(x,y).bg_light
# Check for Monsters
for monster in Game.monsters[@z]
if monster.x is x and monster.y is y
Game.camera.draw x, y, monster.val,
monster.fg_light,
Game.map(x,y).bg_light
# Monster object
# There is a bidimensional array of monsters at Game.monsters
class Monster extends Entity
constructor : (x,y,z,val,fg,fg_light) ->
super x,y,z,30
@p_x = no; @p_y = no; @val = val or "M"
@fg = fg or "#fff"; @fg_light = fg_light or "#fff"
# Callback for the game turn scheduler
act : ->
# Do nothing if the player is on a different floor
return unless @z is Game.player.z
if not @fov # Create FOV instance if it doesn't exist
@fov = new ROT.FOV.PreciseShadowcasting (x,y) =>
# Callback: tells if vision passes through tile
if @x is x and @y is y
return yes
Game.isBlocked(x,y,@z,no) is no
# Compute visible tiles
@fov.compute @x, @y, 8, (x, y, r, v) =>
return unless Game.map(x,y)
if Game.player.x is x and Game.player.y is y
# Update last known player position: can see the player
@p_x = Game.player.x; @p_y = Game.player.y
if @p_x is no and @p_y is no
# Standard behaviour: no known player position
dir = ROT.DIRS[8][Math.floor(ROT.RNG.getUniform() * 7)]
@move(@x+dir[0],@y+dir[1])
Game.scheduler.setDuration 50
else # Known player position: try to approach
# Create Pathfind object
path = new ROT.Path.Dijkstra @p_x, @p_y, (x,y) =>
# TODO: Every door considered open until seen closed
if @x is x and @y is y
return yes
block = Game.isBlocked(x, y,@z,no)
!block or Game.map(x,y).val is '+'
tx = @x; ty = @y # workaround, it works and it's efficient! I hope...
path.compute tx, ty, (x,y) =>
# Compute path, then move
if Math.abs(tx-x) < 2 and Math.abs(ty-y) < 2 then @move x, y
Game.scheduler.setDuration 35
Game.scheduler.next().act()
# Act at x,y: move, or attack, or smash door (depends on what's at x,y)
move : (x,y) ->
return unless Game.map(x,y)
if Game.isBlocked(x,y,@z,yes) is yes
# Can't pass, the tile is blocked
if Game.map(x,y).type is "door" and @p_x isnt no and @p_y isnt no
# TODO: smash down the door. Not implemented yet
Game.map(x,y).val = "x"
# Door Smash!
calc = ROT.RNG.getPercentage(); lev = 75 - 2 * Game.player.z
#console.log calc+" > "+lev+" ?"
if calc > lev
Game.map(x,y).val = " "; Game.map(x,y).block = no
Game.map(x,y).type = "floor"
else if Math.abs(@x-x) < 2 and Math.abs(@y-y) < 2
# Tile is not blocked and it's near enough to move there
if x is Game.player.x and y is Game.player.y
# Hit the player!
Game.player.hp -= 5 + Math.floor(ROT.RNG.getUniform() * 20)
else
# Move there
@x = x; @y = y
if @x is @p_x and @y is @p_y
# This is player's last known position but he's not here.
# Give up on searching the player
@p_x = no; @p_y = no
Game.draw()
# Start the game
Game.init()
| 99308 | # This is A Demon's Maze main game file.
# Please look for a LICENSE.txt file in this folder for licensing information.
# Utility function. Needed!
Array::delete = (o) ->
@splice @indexOf(o), 1
Game =
w: 50
h: 50
screen_w: 80
screen_h: 25
camera_w: 80
camera_h: 23
debug: no
maps: []
monsters: []
# Called only once per session: also starts the game
init: ->
console.log "A Demon's Maze - WIP"
if ROT.isSupported() is no # Can't play.
document.getElementById("gameContainer").innerHTML = """
<h3>Oh! Your browser does not support HTML5 Canvas!</h3>
<p>Try Firefox or Chrome!</p>
"""
return
# Init
@display = new ROT.Display { width: @screen_w, height: @screen_h }
document.getElementById("gameContainer").appendChild @display.getContainer()
@newGame()
console.log "Done init"
# Resets the game
newGame: ->
@scheduler = new ROT.Scheduler.Action()
@maps = []; @monsters = []; @player = undefined
@camera = new Camera 0,0,@camera_w,@camera_h
@newLevel 1
@scheduler.next().act()
###
Cretes a new level if it's not generated yet
l: which level
moveTo: move the player to the level
###
newLevel: (l,moveTo) ->
moveTo = moveTo or yes
oldLevel = if @player then @player.z else 1
# Map
@player.z = l if @player and moveTo is yes
if @maps[l] is undefined
console.log "Generating Level: "+l
# Generate map
@generateMap l
loc = @getEmptyLoc no
if oldLevel isnt l
@map(loc.x,loc.y,l).type = "stairs"
@map(loc.x,loc.y,l).val = if oldLevel > l then "<" else ">"
console.log "Placed "+@map(loc.x,loc.y,l).val+" tile"
if @player is undefined or @player is null
@player = new Player loc.x, loc.y, l
@scheduler.add @player, yes, 0
# Stairs
loc2 = @getEmptyLoc yes
#while loc2.x is loc.x and loc2.y is loc.y
#loc2 = @getEmptyLoc yes
@map(loc2.x,loc2.y,l).type = "stairs"
@map(loc2.x,loc2.y,l).val = if oldLevel > l then ">" else "<"
else console.log "Loading Level: "+l
if @player.pos[l] isnt undefined
@player.x = @player.pos[l].x
@player.y = @player.pos[l].y
else
@player.x = loc.x; @player.y = loc.y
Game.camera.setCenter @player.x,@player.y
# Generate Monsters
if not @monsters[l]
@monsters[l] = []
times = Math.floor l * 1.5 + ROT.RNG.getUniform() * 6 - 3
if times > 15 then times = 15
console.log "Generating " + times + " monsters on floor "+l
if times > 0
for i in [1..times]
loc = @getEmptyLoc yes
@monsters[l].push new Monster(loc.x, loc.y, l)
if moveTo # Change level
console.log "Player moving to level "+l
# Stop old monsters' AI for now
if @monsters[oldLevel]
@scheduler.remove monster for monster in @monsters[oldLevel]
# Enter new monsters' AI
@scheduler.add monster, yes, 50 for monster in @monsters[l]
@draw()
# Generate the map at the given level. Overwrites existing level
generateMap: (l) ->
@map_done = no; @rooms_done = no; times = 0
@maps[l] = {}
@digger = new ROT.Map.Digger @w, @h
finished = @digger.create (x,y,solid) =>
key = <KEY>
@maps[l][key] =
val: if solid then " " else "."
seen: no
type: if solid then "wall" else "floor"
block: if solid then yes else no
fg: if solid then "#000" else "#777"
bg: if solid then "#444" else "#000"
fg_light: if solid then "#000" else "#fff"
bg_light: if solid then "#660" else "#aa0"
times++
if times is @w*@h
@map_done = yes
console.log "[Map:"+l+"] Generated structure"
console.log "[Map:"+l+"] Finalizing map..."
for i,room of @digger.getRooms()
continue unless room.getDoors
room.getDoors (x,y) =>
k = x+","+y
@maps[l][k].val = "+"
@maps[l][k].type = "door"
@maps[l][k].fg = "#3a261a"
@maps[l][k].block = yes
@maps[l][k].fg_light = "#584338"
@rooms_done = yes if i is @digger.getRooms().length - 1
console.log "[Map:"+l+"] Finished"
# Get coordinates
map : (x,y,z) -> z ?= @player.z; @maps[z][x+","+y]
drawMap : (onlySeen) ->
onlySeen = onlySeen or no; l = @player.z
for key of @maps[l]
if @maps[l][key].seen is yes or onlySeen is no
@camera.draw key.split(",")[0], key.split(",")[1],
@maps[l][key].val, @maps[l][key].fg, @maps[l][key].bg
# Draws the UI
drawUI: () ->
# Separator
s = ""; s += "_" for i in [1..@camera_w]
@display.drawText 0, @camera_h, s
# Player HP
if @player.hp > 0
@display.drawText 0, @camera_h+1, "HP "
for i in [1..10]
@display.draw 2+i,@camera_h+1, "=", "#a00", "#000"
for i in [1..Math.floor @player.hp / 10]
@display.draw 2+i,@camera_h+1, "=", "#f00", "#000"
else @display.drawText 0,@camera_h+1, "Game Over! Press Enter"
# Other
@display.drawText @screen_w-9, @camera_h+1, "Floor: "+@player.z
@display.drawText 15,@camera_h+1,"Ouch!" unless @player.hp is @player.oldHp
@player.oldHp = @player.hp
# Draws the game graphics. Call this every time a change is made
draw : ->
if not @map_done
# Map has to be finished
return
@display.clear()
# Draw player FOV and player
@player.drawMemory()
@player.drawVisible()
@camera.draw @player.x, @player.y, '@', "#fff", "#aa0"
@drawUI()
# Draw Monsters (Debug)
#for monster in @monsters[@player.z]
#@camera.draw monster.x, monster.y, 'M', "#fff", "#000"
# Is x,y in room?
inRoom : (room, x, y) ->
if room then room.x1 <= x <= room.x2 and room.y1 <= y <= room.y2 else no
isBlocked : (x,y,l,ignorePlayer) ->
l = l or @player.z; ignorePlayer = ignorePlayer or no
if not @map(x,y,l) then return yes
if @map(x,y,l).block is yes then return yes
if ignorePlayer is no
if @player.x is x and @player.y is y and @player.z is l then return yes
return no unless @monsters and @monsters[l]
for monster in @monsters[l]
return yes if monster.x is x and monster.y is y
no
# Get a location in a room where there's nothing else, at level @player.z
# away: if you want it away from the player's current position
getEmptyLoc: (away)->
away = away or yes
return unless @digger; rs = @digger.getRooms()
loop
ok = no
while ok is no
r = rs[Math.floor(ROT.RNG.getUniform() * @digger.getRooms().length - 1)]
if not @player or away is off or @inRoom(r,@player.x,@player.y) is no
if r then ok = yes
x = r.getLeft()
+ Math.floor ROT.RNG.getUniform() * (r.getRight() - r.getLeft())
y = r.getTop()
+ Math.floor ROT.RNG.getUniform() * (r.getBottom() - r.getTop())
return {x,y} unless @player and @player.x is x and @player.y is y
# Camera object: follows the player.
# Draw calls for the game world must be made to the camera
# Instance at Game.camera
Camera = (x,y,w,h) ->
@x = x; @y = y; @w = w; @h = h
@slideOffset = 10
Camera::getCenter = ->
{ x: @x + @w/2, y: @y + @h/2 }
# Convert world coords to screen
Camera::fromWorld = (x,y) ->
{ x: x-@x; y: y-@y }
# Move the camera by x, y
Camera::slide = (x,y) ->
@x += Math.floor x unless not x
@y += Math.floor y unless not y
# Moves the camera so x,y is at the center
Camera::setCenter = (x,y) ->
return unless x and y
@x = Math.floor x - @w/2; @y = Math.floor y - @h/2
# True if x,y is visible
Camera::visible = (x,y) ->
x > @x and x < @x+@w and y > @y and y < @y+@h
# Draw ch at x,y using fg color for foreground and bg color for background
Camera::draw = (x,y,ch,fg,bg) ->
Game.display.draw x-@x,y-@y,ch,fg,bg
class Entity
constructor: (@x,@y,@z,@maxhp) ->
@hp = @maxhp
@mem = {}
memory : (x,y,z) ->
act: -> console.log "unconfigured entity ai"
# Player object
# Instance at Game.player
class Player extends Entity
constructor : (x,y,z) ->
super x,y,z,100
@oldHp = @hp; @reqEnter = no
@shiftDown = no; @closeDoor = no
@move @x, @y
@pos = {}; @keyMap = {}; @sounds = []
@keyMap[38] = @keyMap[104] = 0 # up
@keyMap[33] = @keyMap[105] = 1
@keyMap[39] = @keyMap[102] = 2 # right
@keyMap[34] = @keyMap[99] = 3
@keyMap[40] = @keyMap[98] = 4 # down
@keyMap[35] = @keyMap[97] = 5
@keyMap[37] = @keyMap[100] = 6 # left
@keyMap[36] = @keyMap[103] = 7
# Workaround for problem with removing listeners when functions are bound
@_onKeyUp = @onKeyUp.bind this
@_onKeyDown = @onKeyDown.bind this
window.addEventListener "keyup", @_onKeyUp
# Callback for the turn scheduler
act : ->
if @hp <= 0
#Game.display.drawText 15,@camera_h+1,"Game Over!"
Game.draw() unless @reqEnter is yes
@reqEnter = yes
window.addEventListener "keydown", @_onKeyDown
# Callback for keyboard key released event
onKeyUp : (e) ->
if e.keyCode is 16
@shiftDown = no
# Callback for keyboard key pressed event
onKeyDown : (e) ->
finished = no
#console.log "Keycode: "+e.keyCode
# start possible actions --->
if @reqEnter is yes
if e.keyCode is 13
if @hp <= 0
Game.newGame()
finished = yes
else finished = no
return
if e.keyCode is 16 # Shift
@shiftDown = yes
else if e.keyCode is 67 # c
@closeDoor = yes
if e.keyCode is 101 or e.keyCode is 190 # dot symbol or Numpad 5: wait
finished = yes # Do nothing, pass turn
Game.scheduler.setDuration 5
if (e.keyCode is 60 or e.keyCode is 83) and Game.map(@x,@y).type is "stairs"
if Game.map(@x,@y).val is ">" and (@shiftDown or e.keyCode is 83)
# Go downstairs
@pos[@z] = { x: @x, y: @y }
Game.newLevel @z - 1
finished = yes
else if Game.map(@x,@y).val is "<" and (not @shiftDown or e.keyCode is 83)
# Go upstairs
@pos[@z] = { x: @x, y: @y }
Game.newLevel @z + 1
finished = yes
if finished is yes then Game.scheduler.setDuration 5
else if 36 <= e.keyCode <= 40 or 97 <= e.keyCode <= 105
# Direction Key
dir = ROT.DIRS[8][@keyMap[e.keyCode]]
if dir
newX = @x + dir[0]; newY = @y + dir[1]
blocked = Game.isBlocked(newX,newY,@z,no)
# Door: open or close
if Game.map(newX,newY).type is "door"
if @closeDoor is yes and blocked is no
Game.map(newX,newY).val = "+"
Game.map(newX,newY).block = yes
Game.draw(); finished = yes
else if @closeDoor is no and Game.map(newX,newY).val is "+"
Game.map(newX,newY).val = "\'"
Game.map(newX,newY).block = no
Game.draw(); finished = yes
if blocked is no and finished is no
# Move Into Open Space
@move newX, newY
Game.draw()
finished = yes
if finished is yes then Game.scheduler.setDuration 10
if e.keyCode isnt 67 then @closeDoor = no
# <--- end actions
if finished is yes # This turn is over
window.removeEventListener "keydown", @_onKeyDown
Game.scheduler.next().act()
# Move player to newX, newY in the game world
move : (newX, newY)->
#return unless newX and newY and newX isnt @x and newY isnt @y
onScreen = Game.camera.fromWorld newX, newY
if onScreen.x > Game.camera.w-Game.camera.slideOffset
Game.camera.slide 1,0
else if onScreen.x < Game.camera.slideOffset then Game.camera.slide -1,0
if onScreen.y < Game.camera.slideOffset then Game.camera.slide 0,-1
else if onScreen.y > Game.camera.h-Game.camera.slideOffset
Game.camera.slide 0,1
@x = newX; @y = newY
# Draw the known tiles of the map
drawMemory : ->
for x in [Game.camera.x .. Game.camera.x+Game.camera.w-1]
for y in [Game.camera.y .. Game.camera.y+Game.camera.h-1]
if Game.map(x,y) and Game.map(x,y).seen is true
Game.camera.draw x, y, Game.map(x,y).val,
Game.map(x,y).fg,
Game.map(x,y).bg
# Draw lighting and visible tiles, monsters and doors
drawVisible : ->
if not @fov
@fov = new ROT.FOV.PreciseShadowcasting (x,y) ->
Game.isBlocked(x,y,@z,yes) is no
# Draw heard sounds
for s in @sounds
Game.camera.draw s.x, s.y, s.val, s.light
@sounds = []
@fov.compute @x, @y, 6, (x, y, r, v) =>
return unless Game.map(x,y)
Game.map(x,y).seen = yes
Game.camera.draw x, y, Game.map(x,y).val,
Game.map(x,y).fg_light,
Game.map(x,y).bg_light
# Check for Monsters
for monster in Game.monsters[@z]
if monster.x is x and monster.y is y
Game.camera.draw x, y, monster.val,
monster.fg_light,
Game.map(x,y).bg_light
# Monster object
# There is a bidimensional array of monsters at Game.monsters
class Monster extends Entity
constructor : (x,y,z,val,fg,fg_light) ->
super x,y,z,30
@p_x = no; @p_y = no; @val = val or "M"
@fg = fg or "#fff"; @fg_light = fg_light or "#fff"
# Callback for the game turn scheduler
act : ->
# Do nothing if the player is on a different floor
return unless @z is Game.player.z
if not @fov # Create FOV instance if it doesn't exist
@fov = new ROT.FOV.PreciseShadowcasting (x,y) =>
# Callback: tells if vision passes through tile
if @x is x and @y is y
return yes
Game.isBlocked(x,y,@z,no) is no
# Compute visible tiles
@fov.compute @x, @y, 8, (x, y, r, v) =>
return unless Game.map(x,y)
if Game.player.x is x and Game.player.y is y
# Update last known player position: can see the player
@p_x = Game.player.x; @p_y = Game.player.y
if @p_x is no and @p_y is no
# Standard behaviour: no known player position
dir = ROT.DIRS[8][Math.floor(ROT.RNG.getUniform() * 7)]
@move(@x+dir[0],@y+dir[1])
Game.scheduler.setDuration 50
else # Known player position: try to approach
# Create Pathfind object
path = new ROT.Path.Dijkstra @p_x, @p_y, (x,y) =>
# TODO: Every door considered open until seen closed
if @x is x and @y is y
return yes
block = Game.isBlocked(x, y,@z,no)
!block or Game.map(x,y).val is '+'
tx = @x; ty = @y # workaround, it works and it's efficient! I hope...
path.compute tx, ty, (x,y) =>
# Compute path, then move
if Math.abs(tx-x) < 2 and Math.abs(ty-y) < 2 then @move x, y
Game.scheduler.setDuration 35
Game.scheduler.next().act()
# Act at x,y: move, or attack, or smash door (depends on what's at x,y)
move : (x,y) ->
return unless Game.map(x,y)
if Game.isBlocked(x,y,@z,yes) is yes
# Can't pass, the tile is blocked
if Game.map(x,y).type is "door" and @p_x isnt no and @p_y isnt no
# TODO: smash down the door. Not implemented yet
Game.map(x,y).val = "x"
# Door Smash!
calc = ROT.RNG.getPercentage(); lev = 75 - 2 * Game.player.z
#console.log calc+" > "+lev+" ?"
if calc > lev
Game.map(x,y).val = " "; Game.map(x,y).block = no
Game.map(x,y).type = "floor"
else if Math.abs(@x-x) < 2 and Math.abs(@y-y) < 2
# Tile is not blocked and it's near enough to move there
if x is Game.player.x and y is Game.player.y
# Hit the player!
Game.player.hp -= 5 + Math.floor(ROT.RNG.getUniform() * 20)
else
# Move there
@x = x; @y = y
if @x is @p_x and @y is @p_y
# This is player's last known position but he's not here.
# Give up on searching the player
@p_x = no; @p_y = no
Game.draw()
# Start the game
Game.init()
| true | # This is A Demon's Maze main game file.
# Please look for a LICENSE.txt file in this folder for licensing information.
# Utility function. Needed!
Array::delete = (o) ->
@splice @indexOf(o), 1
Game =
w: 50
h: 50
screen_w: 80
screen_h: 25
camera_w: 80
camera_h: 23
debug: no
maps: []
monsters: []
# Called only once per session: also starts the game
init: ->
console.log "A Demon's Maze - WIP"
if ROT.isSupported() is no # Can't play.
document.getElementById("gameContainer").innerHTML = """
<h3>Oh! Your browser does not support HTML5 Canvas!</h3>
<p>Try Firefox or Chrome!</p>
"""
return
# Init
@display = new ROT.Display { width: @screen_w, height: @screen_h }
document.getElementById("gameContainer").appendChild @display.getContainer()
@newGame()
console.log "Done init"
# Resets the game
newGame: ->
@scheduler = new ROT.Scheduler.Action()
@maps = []; @monsters = []; @player = undefined
@camera = new Camera 0,0,@camera_w,@camera_h
@newLevel 1
@scheduler.next().act()
###
Cretes a new level if it's not generated yet
l: which level
moveTo: move the player to the level
###
newLevel: (l,moveTo) ->
moveTo = moveTo or yes
oldLevel = if @player then @player.z else 1
# Map
@player.z = l if @player and moveTo is yes
if @maps[l] is undefined
console.log "Generating Level: "+l
# Generate map
@generateMap l
loc = @getEmptyLoc no
if oldLevel isnt l
@map(loc.x,loc.y,l).type = "stairs"
@map(loc.x,loc.y,l).val = if oldLevel > l then "<" else ">"
console.log "Placed "+@map(loc.x,loc.y,l).val+" tile"
if @player is undefined or @player is null
@player = new Player loc.x, loc.y, l
@scheduler.add @player, yes, 0
# Stairs
loc2 = @getEmptyLoc yes
#while loc2.x is loc.x and loc2.y is loc.y
#loc2 = @getEmptyLoc yes
@map(loc2.x,loc2.y,l).type = "stairs"
@map(loc2.x,loc2.y,l).val = if oldLevel > l then ">" else "<"
else console.log "Loading Level: "+l
if @player.pos[l] isnt undefined
@player.x = @player.pos[l].x
@player.y = @player.pos[l].y
else
@player.x = loc.x; @player.y = loc.y
Game.camera.setCenter @player.x,@player.y
# Generate Monsters
if not @monsters[l]
@monsters[l] = []
times = Math.floor l * 1.5 + ROT.RNG.getUniform() * 6 - 3
if times > 15 then times = 15
console.log "Generating " + times + " monsters on floor "+l
if times > 0
for i in [1..times]
loc = @getEmptyLoc yes
@monsters[l].push new Monster(loc.x, loc.y, l)
if moveTo # Change level
console.log "Player moving to level "+l
# Stop old monsters' AI for now
if @monsters[oldLevel]
@scheduler.remove monster for monster in @monsters[oldLevel]
# Enter new monsters' AI
@scheduler.add monster, yes, 50 for monster in @monsters[l]
@draw()
# Generate the map at the given level. Overwrites existing level
generateMap: (l) ->
@map_done = no; @rooms_done = no; times = 0
@maps[l] = {}
@digger = new ROT.Map.Digger @w, @h
finished = @digger.create (x,y,solid) =>
key = PI:KEY:<KEY>END_PI
@maps[l][key] =
val: if solid then " " else "."
seen: no
type: if solid then "wall" else "floor"
block: if solid then yes else no
fg: if solid then "#000" else "#777"
bg: if solid then "#444" else "#000"
fg_light: if solid then "#000" else "#fff"
bg_light: if solid then "#660" else "#aa0"
times++
if times is @w*@h
@map_done = yes
console.log "[Map:"+l+"] Generated structure"
console.log "[Map:"+l+"] Finalizing map..."
for i,room of @digger.getRooms()
continue unless room.getDoors
room.getDoors (x,y) =>
k = x+","+y
@maps[l][k].val = "+"
@maps[l][k].type = "door"
@maps[l][k].fg = "#3a261a"
@maps[l][k].block = yes
@maps[l][k].fg_light = "#584338"
@rooms_done = yes if i is @digger.getRooms().length - 1
console.log "[Map:"+l+"] Finished"
# Get coordinates
map : (x,y,z) -> z ?= @player.z; @maps[z][x+","+y]
drawMap : (onlySeen) ->
onlySeen = onlySeen or no; l = @player.z
for key of @maps[l]
if @maps[l][key].seen is yes or onlySeen is no
@camera.draw key.split(",")[0], key.split(",")[1],
@maps[l][key].val, @maps[l][key].fg, @maps[l][key].bg
# Draws the UI
drawUI: () ->
# Separator
s = ""; s += "_" for i in [1..@camera_w]
@display.drawText 0, @camera_h, s
# Player HP
if @player.hp > 0
@display.drawText 0, @camera_h+1, "HP "
for i in [1..10]
@display.draw 2+i,@camera_h+1, "=", "#a00", "#000"
for i in [1..Math.floor @player.hp / 10]
@display.draw 2+i,@camera_h+1, "=", "#f00", "#000"
else @display.drawText 0,@camera_h+1, "Game Over! Press Enter"
# Other
@display.drawText @screen_w-9, @camera_h+1, "Floor: "+@player.z
@display.drawText 15,@camera_h+1,"Ouch!" unless @player.hp is @player.oldHp
@player.oldHp = @player.hp
# Draws the game graphics. Call this every time a change is made
draw : ->
if not @map_done
# Map has to be finished
return
@display.clear()
# Draw player FOV and player
@player.drawMemory()
@player.drawVisible()
@camera.draw @player.x, @player.y, '@', "#fff", "#aa0"
@drawUI()
# Draw Monsters (Debug)
#for monster in @monsters[@player.z]
#@camera.draw monster.x, monster.y, 'M', "#fff", "#000"
# Is x,y in room?
inRoom : (room, x, y) ->
if room then room.x1 <= x <= room.x2 and room.y1 <= y <= room.y2 else no
isBlocked : (x,y,l,ignorePlayer) ->
l = l or @player.z; ignorePlayer = ignorePlayer or no
if not @map(x,y,l) then return yes
if @map(x,y,l).block is yes then return yes
if ignorePlayer is no
if @player.x is x and @player.y is y and @player.z is l then return yes
return no unless @monsters and @monsters[l]
for monster in @monsters[l]
return yes if monster.x is x and monster.y is y
no
# Get a location in a room where there's nothing else, at level @player.z
# away: if you want it away from the player's current position
getEmptyLoc: (away)->
away = away or yes
return unless @digger; rs = @digger.getRooms()
loop
ok = no
while ok is no
r = rs[Math.floor(ROT.RNG.getUniform() * @digger.getRooms().length - 1)]
if not @player or away is off or @inRoom(r,@player.x,@player.y) is no
if r then ok = yes
x = r.getLeft()
+ Math.floor ROT.RNG.getUniform() * (r.getRight() - r.getLeft())
y = r.getTop()
+ Math.floor ROT.RNG.getUniform() * (r.getBottom() - r.getTop())
return {x,y} unless @player and @player.x is x and @player.y is y
# Camera object: follows the player.
# Draw calls for the game world must be made to the camera
# Instance at Game.camera
Camera = (x,y,w,h) ->
@x = x; @y = y; @w = w; @h = h
@slideOffset = 10
Camera::getCenter = ->
{ x: @x + @w/2, y: @y + @h/2 }
# Convert world coords to screen
Camera::fromWorld = (x,y) ->
{ x: x-@x; y: y-@y }
# Move the camera by x, y
Camera::slide = (x,y) ->
@x += Math.floor x unless not x
@y += Math.floor y unless not y
# Moves the camera so x,y is at the center
Camera::setCenter = (x,y) ->
return unless x and y
@x = Math.floor x - @w/2; @y = Math.floor y - @h/2
# True if x,y is visible
Camera::visible = (x,y) ->
x > @x and x < @x+@w and y > @y and y < @y+@h
# Draw ch at x,y using fg color for foreground and bg color for background
Camera::draw = (x,y,ch,fg,bg) ->
Game.display.draw x-@x,y-@y,ch,fg,bg
class Entity
constructor: (@x,@y,@z,@maxhp) ->
@hp = @maxhp
@mem = {}
memory : (x,y,z) ->
act: -> console.log "unconfigured entity ai"
# Player object
# Instance at Game.player
class Player extends Entity
constructor : (x,y,z) ->
super x,y,z,100
@oldHp = @hp; @reqEnter = no
@shiftDown = no; @closeDoor = no
@move @x, @y
@pos = {}; @keyMap = {}; @sounds = []
@keyMap[38] = @keyMap[104] = 0 # up
@keyMap[33] = @keyMap[105] = 1
@keyMap[39] = @keyMap[102] = 2 # right
@keyMap[34] = @keyMap[99] = 3
@keyMap[40] = @keyMap[98] = 4 # down
@keyMap[35] = @keyMap[97] = 5
@keyMap[37] = @keyMap[100] = 6 # left
@keyMap[36] = @keyMap[103] = 7
# Workaround for problem with removing listeners when functions are bound
@_onKeyUp = @onKeyUp.bind this
@_onKeyDown = @onKeyDown.bind this
window.addEventListener "keyup", @_onKeyUp
# Callback for the turn scheduler
act : ->
if @hp <= 0
#Game.display.drawText 15,@camera_h+1,"Game Over!"
Game.draw() unless @reqEnter is yes
@reqEnter = yes
window.addEventListener "keydown", @_onKeyDown
# Callback for keyboard key released event
onKeyUp : (e) ->
if e.keyCode is 16
@shiftDown = no
# Callback for keyboard key pressed event
onKeyDown : (e) ->
finished = no
#console.log "Keycode: "+e.keyCode
# start possible actions --->
if @reqEnter is yes
if e.keyCode is 13
if @hp <= 0
Game.newGame()
finished = yes
else finished = no
return
if e.keyCode is 16 # Shift
@shiftDown = yes
else if e.keyCode is 67 # c
@closeDoor = yes
if e.keyCode is 101 or e.keyCode is 190 # dot symbol or Numpad 5: wait
finished = yes # Do nothing, pass turn
Game.scheduler.setDuration 5
if (e.keyCode is 60 or e.keyCode is 83) and Game.map(@x,@y).type is "stairs"
if Game.map(@x,@y).val is ">" and (@shiftDown or e.keyCode is 83)
# Go downstairs
@pos[@z] = { x: @x, y: @y }
Game.newLevel @z - 1
finished = yes
else if Game.map(@x,@y).val is "<" and (not @shiftDown or e.keyCode is 83)
# Go upstairs
@pos[@z] = { x: @x, y: @y }
Game.newLevel @z + 1
finished = yes
if finished is yes then Game.scheduler.setDuration 5
else if 36 <= e.keyCode <= 40 or 97 <= e.keyCode <= 105
# Direction Key
dir = ROT.DIRS[8][@keyMap[e.keyCode]]
if dir
newX = @x + dir[0]; newY = @y + dir[1]
blocked = Game.isBlocked(newX,newY,@z,no)
# Door: open or close
if Game.map(newX,newY).type is "door"
if @closeDoor is yes and blocked is no
Game.map(newX,newY).val = "+"
Game.map(newX,newY).block = yes
Game.draw(); finished = yes
else if @closeDoor is no and Game.map(newX,newY).val is "+"
Game.map(newX,newY).val = "\'"
Game.map(newX,newY).block = no
Game.draw(); finished = yes
if blocked is no and finished is no
# Move Into Open Space
@move newX, newY
Game.draw()
finished = yes
if finished is yes then Game.scheduler.setDuration 10
if e.keyCode isnt 67 then @closeDoor = no
# <--- end actions
if finished is yes # This turn is over
window.removeEventListener "keydown", @_onKeyDown
Game.scheduler.next().act()
# Move player to newX, newY in the game world
move : (newX, newY)->
#return unless newX and newY and newX isnt @x and newY isnt @y
onScreen = Game.camera.fromWorld newX, newY
if onScreen.x > Game.camera.w-Game.camera.slideOffset
Game.camera.slide 1,0
else if onScreen.x < Game.camera.slideOffset then Game.camera.slide -1,0
if onScreen.y < Game.camera.slideOffset then Game.camera.slide 0,-1
else if onScreen.y > Game.camera.h-Game.camera.slideOffset
Game.camera.slide 0,1
@x = newX; @y = newY
# Draw the known tiles of the map
drawMemory : ->
for x in [Game.camera.x .. Game.camera.x+Game.camera.w-1]
for y in [Game.camera.y .. Game.camera.y+Game.camera.h-1]
if Game.map(x,y) and Game.map(x,y).seen is true
Game.camera.draw x, y, Game.map(x,y).val,
Game.map(x,y).fg,
Game.map(x,y).bg
# Draw lighting and visible tiles, monsters and doors
drawVisible : ->
if not @fov
@fov = new ROT.FOV.PreciseShadowcasting (x,y) ->
Game.isBlocked(x,y,@z,yes) is no
# Draw heard sounds
for s in @sounds
Game.camera.draw s.x, s.y, s.val, s.light
@sounds = []
@fov.compute @x, @y, 6, (x, y, r, v) =>
return unless Game.map(x,y)
Game.map(x,y).seen = yes
Game.camera.draw x, y, Game.map(x,y).val,
Game.map(x,y).fg_light,
Game.map(x,y).bg_light
# Check for Monsters
for monster in Game.monsters[@z]
if monster.x is x and monster.y is y
Game.camera.draw x, y, monster.val,
monster.fg_light,
Game.map(x,y).bg_light
# Monster object
# There is a bidimensional array of monsters at Game.monsters
class Monster extends Entity
constructor : (x,y,z,val,fg,fg_light) ->
super x,y,z,30
@p_x = no; @p_y = no; @val = val or "M"
@fg = fg or "#fff"; @fg_light = fg_light or "#fff"
# Callback for the game turn scheduler
act : ->
# Do nothing if the player is on a different floor
return unless @z is Game.player.z
if not @fov # Create FOV instance if it doesn't exist
@fov = new ROT.FOV.PreciseShadowcasting (x,y) =>
# Callback: tells if vision passes through tile
if @x is x and @y is y
return yes
Game.isBlocked(x,y,@z,no) is no
# Compute visible tiles
@fov.compute @x, @y, 8, (x, y, r, v) =>
return unless Game.map(x,y)
if Game.player.x is x and Game.player.y is y
# Update last known player position: can see the player
@p_x = Game.player.x; @p_y = Game.player.y
if @p_x is no and @p_y is no
# Standard behaviour: no known player position
dir = ROT.DIRS[8][Math.floor(ROT.RNG.getUniform() * 7)]
@move(@x+dir[0],@y+dir[1])
Game.scheduler.setDuration 50
else # Known player position: try to approach
# Create Pathfind object
path = new ROT.Path.Dijkstra @p_x, @p_y, (x,y) =>
# TODO: Every door considered open until seen closed
if @x is x and @y is y
return yes
block = Game.isBlocked(x, y,@z,no)
!block or Game.map(x,y).val is '+'
tx = @x; ty = @y # workaround, it works and it's efficient! I hope...
path.compute tx, ty, (x,y) =>
# Compute path, then move
if Math.abs(tx-x) < 2 and Math.abs(ty-y) < 2 then @move x, y
Game.scheduler.setDuration 35
Game.scheduler.next().act()
# Act at x,y: move, or attack, or smash door (depends on what's at x,y)
move : (x,y) ->
return unless Game.map(x,y)
if Game.isBlocked(x,y,@z,yes) is yes
# Can't pass, the tile is blocked
if Game.map(x,y).type is "door" and @p_x isnt no and @p_y isnt no
# TODO: smash down the door. Not implemented yet
Game.map(x,y).val = "x"
# Door Smash!
calc = ROT.RNG.getPercentage(); lev = 75 - 2 * Game.player.z
#console.log calc+" > "+lev+" ?"
if calc > lev
Game.map(x,y).val = " "; Game.map(x,y).block = no
Game.map(x,y).type = "floor"
else if Math.abs(@x-x) < 2 and Math.abs(@y-y) < 2
# Tile is not blocked and it's near enough to move there
if x is Game.player.x and y is Game.player.y
# Hit the player!
Game.player.hp -= 5 + Math.floor(ROT.RNG.getUniform() * 20)
else
# Move there
@x = x; @y = y
if @x is @p_x and @y is @p_y
# This is player's last known position but he's not here.
# Give up on searching the player
@p_x = no; @p_y = no
Game.draw()
# Start the game
Game.init()
|
[
{
"context": "rd, we will override with email\n\t\tusernameField: 'email'\n\t\tpasswordField: 'password'\n\n\t\t# allows us to pa",
"end": 3134,
"score": 0.9899752140045166,
"start": 3129,
"tag": "USERNAME",
"value": "email"
},
{
"context": " email\n\t\tusernameField: 'email'\n\t\tpa... | src/app/scripts/passport.coffee | guloggratis/jarv-dashboard-1pagewebapp | 0 | # load all the things we need
LocalStrategy = require('passport-local').Strategy
GoogleStrategy = require('passport-google-oauth').OAuth2Strategy
bcrypt = require 'bcrypt-nodejs'
# include configs file
config = require './config.js'
# expose this function to our app using module.exports
module.exports = (passport, db) ->
# =========================================================================
# passport session setup ==================================================
# =========================================================================
# required for persistent login sessions
# passport needs ability to serialize and unserialize users out of session
# used to serialize the user for the session
passport.serializeUser (user, done) ->
# serialize info we want to have persisting across requests
serialized =
'permissions': user.permissions
done null, serialized
# used to deserialize the user
passport.deserializeUser (user, done) ->
done null, user
# =========================================================================
# GOOGLE ==================================================================
# =========================================================================
passport.use new GoogleStrategy
clientID: config.googleAuth.clientID
clientSecret: config.googleAuth.clientSecret
callbackURL: config.googleAuth.callbackURL
, (token, refreshToken, profile, done) ->
# make the code asynchronous
process.nextTick ->
# find a user whose profile ID matches the one attempting to sign up
# we are checking to see if the user trying to login already exists
users = db.collection('users')
cursor = users.findOne
google_id: profile.id
, (err, doc) ->
if doc isnt null
# a user already exists for this account
console.log 'Welcome back, Operator'
# all is well, user can proceed with the login
# return done null, user
return done null, doc
else
# the user isnt in our database, create a new user
newUser =
google_id: profile.id
google_token: token
google_name: profile.displayName
# pull the first email associate to this Google account
google_email: profile.emails[0].value
permissions: ['random']
# store the new user in the db
users.insertOne(newUser).then (r) ->
if r.insertedCount is 1
console.log "Operator #{ profile.emails[0].value } created"
return done null, newUser
else
console.log 'Something went wrong storing the newly created user'
# =========================================================================
# LOCAL SIGNUP ============================================================
# =========================================================================
# we are using named strategies since we have one for login and one for signup
# by default, if there was no name, it would just be called 'local'
passport.use 'local-signup', new LocalStrategy
# by default, local strategy uses username and password, we will override with email
usernameField: 'email'
passwordField: 'password'
# allows us to pass back the entire request to the callback
passReqToCallback: yes
, (req, email, password, done) ->
# asynchronous
process.nextTick ->
# find a user whose email is the same as the forms email
# we are checking to see if the user trying to login already exists
users = db.collection('users')
cursor = users.findOne
local_email: email
, (err, doc) ->
if doc isnt null
# an operator already exists for this
return done null, false, req.flash('signupMessage', 'Sorry kiddo, this email is already taken')
else
# this email is not in the DB yet, proceed with the signup
newUser =
local_email: email
local_password: generateHash password
permissions: ['random']
# store the new user in the db
users.insertOne(newUser).then (r) ->
if r.insertedCount is 1
console.log "Created a user for #{ email }"
return done null, newUser, req.flash('signupMessage', 'Created a user for ' + email)
else
console.log 'Something went wrong storing the newly created user'
# =========================================================================
# LOCAL LOGIN =============================================================
# =========================================================================
# we are using named strategies since we have one for login and one for signup
# by default, if there was no name, it would just be called 'local'
passport.use 'local-login', new LocalStrategy
# by default, local strategy uses username and password, we will override with email
usernameField: 'email'
passwordField: 'password'
# allows us to pass back the entire request to the callback
passReqToCallback: yes
# callback with email and password from our form
, (req, email, password, done) ->
users = db.collection('users')
cursor = users.findOne
local_email: email
, (err, doc) ->
if doc isnt null
user = doc
# user found. Validate her password
if !validPassword password, user.local_password
# create the loginMessage and save it to session as flashdata
return done null, false, req.flash('loginMessage', 'Sorry kiddo, wrong email or password')
# all is well, user can proceed with the login
return done null, user, req.flash('loginMessage', "Welcome back, #{ user.local_email }")
else
return done null, false, req.flash('loginMessage', 'Sorry kiddo, wrong email or password')
generateHash = (password) ->
return bcrypt.hashSync password
validPassword = (password, hashed_password) ->
return bcrypt.compareSync password, hashed_password | 41372 | # load all the things we need
LocalStrategy = require('passport-local').Strategy
GoogleStrategy = require('passport-google-oauth').OAuth2Strategy
bcrypt = require 'bcrypt-nodejs'
# include configs file
config = require './config.js'
# expose this function to our app using module.exports
module.exports = (passport, db) ->
# =========================================================================
# passport session setup ==================================================
# =========================================================================
# required for persistent login sessions
# passport needs ability to serialize and unserialize users out of session
# used to serialize the user for the session
passport.serializeUser (user, done) ->
# serialize info we want to have persisting across requests
serialized =
'permissions': user.permissions
done null, serialized
# used to deserialize the user
passport.deserializeUser (user, done) ->
done null, user
# =========================================================================
# GOOGLE ==================================================================
# =========================================================================
passport.use new GoogleStrategy
clientID: config.googleAuth.clientID
clientSecret: config.googleAuth.clientSecret
callbackURL: config.googleAuth.callbackURL
, (token, refreshToken, profile, done) ->
# make the code asynchronous
process.nextTick ->
# find a user whose profile ID matches the one attempting to sign up
# we are checking to see if the user trying to login already exists
users = db.collection('users')
cursor = users.findOne
google_id: profile.id
, (err, doc) ->
if doc isnt null
# a user already exists for this account
console.log 'Welcome back, Operator'
# all is well, user can proceed with the login
# return done null, user
return done null, doc
else
# the user isnt in our database, create a new user
newUser =
google_id: profile.id
google_token: token
google_name: profile.displayName
# pull the first email associate to this Google account
google_email: profile.emails[0].value
permissions: ['random']
# store the new user in the db
users.insertOne(newUser).then (r) ->
if r.insertedCount is 1
console.log "Operator #{ profile.emails[0].value } created"
return done null, newUser
else
console.log 'Something went wrong storing the newly created user'
# =========================================================================
# LOCAL SIGNUP ============================================================
# =========================================================================
# we are using named strategies since we have one for login and one for signup
# by default, if there was no name, it would just be called 'local'
passport.use 'local-signup', new LocalStrategy
# by default, local strategy uses username and password, we will override with email
usernameField: 'email'
passwordField: '<PASSWORD>'
# allows us to pass back the entire request to the callback
passReqToCallback: yes
, (req, email, password, done) ->
# asynchronous
process.nextTick ->
# find a user whose email is the same as the forms email
# we are checking to see if the user trying to login already exists
users = db.collection('users')
cursor = users.findOne
local_email: email
, (err, doc) ->
if doc isnt null
# an operator already exists for this
return done null, false, req.flash('signupMessage', 'Sorry kiddo, this email is already taken')
else
# this email is not in the DB yet, proceed with the signup
newUser =
local_email: email
local_password: <PASSWORD>
permissions: ['random']
# store the new user in the db
users.insertOne(newUser).then (r) ->
if r.insertedCount is 1
console.log "Created a user for #{ email }"
return done null, newUser, req.flash('signupMessage', 'Created a user for ' + email)
else
console.log 'Something went wrong storing the newly created user'
# =========================================================================
# LOCAL LOGIN =============================================================
# =========================================================================
# we are using named strategies since we have one for login and one for signup
# by default, if there was no name, it would just be called 'local'
passport.use 'local-login', new LocalStrategy
# by default, local strategy uses username and password, we will override with email
usernameField: 'email'
passwordField: '<PASSWORD>'
# allows us to pass back the entire request to the callback
passReqToCallback: yes
# callback with email and password from our form
, (req, email, password, done) ->
users = db.collection('users')
cursor = users.findOne
local_email: email
, (err, doc) ->
if doc isnt null
user = doc
# user found. Validate her password
if !validPassword password, user.local_password
# create the loginMessage and save it to session as flashdata
return done null, false, req.flash('loginMessage', 'Sorry kiddo, wrong email or password')
# all is well, user can proceed with the login
return done null, user, req.flash('loginMessage', "Welcome back, #{ user.local_email }")
else
return done null, false, req.flash('loginMessage', 'Sorry kiddo, wrong email or password')
generateHash = (password) ->
return bcrypt.hashSync password
validPassword = (password, hashed_password) ->
return bcrypt.compareSync password, hashed_password | true | # load all the things we need
LocalStrategy = require('passport-local').Strategy
GoogleStrategy = require('passport-google-oauth').OAuth2Strategy
bcrypt = require 'bcrypt-nodejs'
# include configs file
config = require './config.js'
# expose this function to our app using module.exports
module.exports = (passport, db) ->
# =========================================================================
# passport session setup ==================================================
# =========================================================================
# required for persistent login sessions
# passport needs ability to serialize and unserialize users out of session
# used to serialize the user for the session
passport.serializeUser (user, done) ->
# serialize info we want to have persisting across requests
serialized =
'permissions': user.permissions
done null, serialized
# used to deserialize the user
passport.deserializeUser (user, done) ->
done null, user
# =========================================================================
# GOOGLE ==================================================================
# =========================================================================
passport.use new GoogleStrategy
clientID: config.googleAuth.clientID
clientSecret: config.googleAuth.clientSecret
callbackURL: config.googleAuth.callbackURL
, (token, refreshToken, profile, done) ->
# make the code asynchronous
process.nextTick ->
# find a user whose profile ID matches the one attempting to sign up
# we are checking to see if the user trying to login already exists
users = db.collection('users')
cursor = users.findOne
google_id: profile.id
, (err, doc) ->
if doc isnt null
# a user already exists for this account
console.log 'Welcome back, Operator'
# all is well, user can proceed with the login
# return done null, user
return done null, doc
else
# the user isnt in our database, create a new user
newUser =
google_id: profile.id
google_token: token
google_name: profile.displayName
# pull the first email associate to this Google account
google_email: profile.emails[0].value
permissions: ['random']
# store the new user in the db
users.insertOne(newUser).then (r) ->
if r.insertedCount is 1
console.log "Operator #{ profile.emails[0].value } created"
return done null, newUser
else
console.log 'Something went wrong storing the newly created user'
# =========================================================================
# LOCAL SIGNUP ============================================================
# =========================================================================
# we are using named strategies since we have one for login and one for signup
# by default, if there was no name, it would just be called 'local'
passport.use 'local-signup', new LocalStrategy
# by default, local strategy uses username and password, we will override with email
usernameField: 'email'
passwordField: 'PI:PASSWORD:<PASSWORD>END_PI'
# allows us to pass back the entire request to the callback
passReqToCallback: yes
, (req, email, password, done) ->
# asynchronous
process.nextTick ->
# find a user whose email is the same as the forms email
# we are checking to see if the user trying to login already exists
users = db.collection('users')
cursor = users.findOne
local_email: email
, (err, doc) ->
if doc isnt null
# an operator already exists for this
return done null, false, req.flash('signupMessage', 'Sorry kiddo, this email is already taken')
else
# this email is not in the DB yet, proceed with the signup
newUser =
local_email: email
local_password: PI:PASSWORD:<PASSWORD>END_PI
permissions: ['random']
# store the new user in the db
users.insertOne(newUser).then (r) ->
if r.insertedCount is 1
console.log "Created a user for #{ email }"
return done null, newUser, req.flash('signupMessage', 'Created a user for ' + email)
else
console.log 'Something went wrong storing the newly created user'
# =========================================================================
# LOCAL LOGIN =============================================================
# =========================================================================
# we are using named strategies since we have one for login and one for signup
# by default, if there was no name, it would just be called 'local'
passport.use 'local-login', new LocalStrategy
# by default, local strategy uses username and password, we will override with email
usernameField: 'email'
passwordField: 'PI:PASSWORD:<PASSWORD>END_PI'
# allows us to pass back the entire request to the callback
passReqToCallback: yes
# callback with email and password from our form
, (req, email, password, done) ->
users = db.collection('users')
cursor = users.findOne
local_email: email
, (err, doc) ->
if doc isnt null
user = doc
# user found. Validate her password
if !validPassword password, user.local_password
# create the loginMessage and save it to session as flashdata
return done null, false, req.flash('loginMessage', 'Sorry kiddo, wrong email or password')
# all is well, user can proceed with the login
return done null, user, req.flash('loginMessage', "Welcome back, #{ user.local_email }")
else
return done null, false, req.flash('loginMessage', 'Sorry kiddo, wrong email or password')
generateHash = (password) ->
return bcrypt.hashSync password
validPassword = (password, hashed_password) ->
return bcrypt.compareSync password, hashed_password |
[
{
"context": " TumblRip -- Download photos from Tumblr\n# Made by Olivier ORABONA\n# Licence: MIT\n\n# NodeJS imports\nfs = require 'fs",
"end": 67,
"score": 0.9998680353164673,
"start": 52,
"tag": "NAME",
"value": "Olivier ORABONA"
}
] | src/tumblrip.coffee | thomas694/tumblrip-other | 2 | # TumblRip -- Download photos from Tumblr
# Made by Olivier ORABONA
# Licence: MIT
# NodeJS imports
fs = require 'fs'
path = require 'path'
request = require 'request'
Q = require 'q'
mkdirp = require 'mkdirp'
URL = require 'url'
bhttp = require 'bhttp'
# My own imports
{ApiError, RejectError} = require './eh'
{log, pick, findInSubArray} = require './utils'
options = require './options'
{allDone, promiseRetry} = require './promise-helpers'
# Make these functions Promise-able.
readFile = Q.nfbind fs.readFile
writeFile = Q.nfbind fs.writeFile
statFile = Q.nfbind fs.stat
###*
@name api -- communicate with remote server API
@param uri (String): the URI to make call to
@param method (String): method to call (by default it is GET)
###
api = (uri, method='GET') ->
opts =
uri: uri
method: method
promiseRetry ->
log.info "#{method} #{uri} ...\n"
Q.nfcall request, opts
.spread (response, body) ->
{statusCode} = response
log.debug "Server status code: #{statusCode}\n"
# A bit hacky but basically, if we got 4XX (and most notably 404), we skip the file.
# If this is a 5XX we retry. Otherwise we keep going.
switch statusCode / 100
when 4
log.info 'File not found, continuing...'
Q.resolve statusCode
when 5
Q.reject new ApiError "Bad status code: #{statusCode}. Retrying..."
# Strip everything before the first '{' ... '}'
if body
json = body.match /^[^\{]+(.*)\;/
if json
try
return JSON.parse json[1]
catch
return Q.reject new ApiError 'Could not parse JSON.'
else
Q.reject new ApiError 'Could not parse response body.'
else
response
###*
@name getPostsData -- get all posts data from Tumblr blog
@param blogname (String) : the blog name (we construct the URL from it)
@param this (Object) : database read from / written to
###
getPostsData = (blogname) ->
# Build url and retrieve all data
url = "http://#{blogname}.tumblr.com/api/read/json"
@title ?= null
@total ?= 0
@posts ?= []
self = @
newPosts = []
@nbNewPosts = 0
process = (start, init=false) ->
log.debug "Processing at #{start}...\n"
# We know we only want photos and the maximum item size is 50.
# These are not variables for the purpose of this tool, but could easily be
# modified to download other stuff from a Tumblr blog ! :)
api "#{url}?type=photo&num=50&start=#{start}"
.then (parsed) ->
# Get total number of posts (when first time, this value is 0).
{total} = self
# Update these global variables only once
if init
self.title = parsed.tumblelog.title
# If we have more posts on our cache than on remote site..
if parsed['posts-total'] < total
# .. We know that we might have (among probably those already downloaded)
# at most parsed['posts-total'] new pictures to download.
self.nbNewPosts = parsed['posts-total']
else
self.nbNewPosts = parsed['posts-total'] - total
# We do not set local variable 'total' which will remain set to its
# initial value. This will be used later for sub array find.
self.total = parsed['posts-total']
parsed.posts.forEach (post) ->
photoUrl = post['photo-url-1280']
timestamp = post['unix-timestamp']
# We first build a filename from concatening URL pathname. That should be
# unique enough but makes longer filenames.
outputFile = URL.parse(photoUrl).pathname.split('/').join ''
# Do not bother searching if the database (aka cache) is empty (creating db).
# Otherwise search for this URL in the cache db.
if total is 0
found = -1
else
found = findInSubArray self.posts, 1, photoUrl
# Sometimes we have a 'slug' attribute that might have a better (human readable)
# filename (everything is better than a long hex string right ?)
if !!post.slug
slugfile = "#{post.slug}#{path.extname photoUrl}"
fileslug = findInSubArray self.posts, 0, slugfile, true
# If we already have more than one occurence or if that occurence does
# not link to the same file (the long hex string one), we have a conflict.
if fileslug.length > 1 or (fileslug.length is 1 and fileslug[0] isnt found)
log.info "Already got #{fileslug.length} file(s) of that name '", slugfile, "'. Using '", outputFile, "' instead.\n"
else
outputFile = slugfile
# We build our database record as an array where
# outputFile: definitive file with name either slugfile || photoUrl
# photoUrl: the remote photo endpoint URL
# status: 'D' for 'delete', 'U' for 'update' (default action)
array = [outputFile, photoUrl, 'U']
if found is -1
log.debug 'Record not found, creating', array, '\n'
newPosts.push array
else
log.debug "Updating record #{found}", self.posts[found], 'with', array, '...\n'
self.posts[found] = array
return
if options['refresh-db'] or (self.nbNewPosts >= 50 and self.total - start >= 50)
process start + 50
else
# Make sure we have all expected new posts. This is to make sure we have
# been given proper results from Tumblr API. Since this could also be a
# consequence of cache db tampering, this check, if enforced (opt in),
# will throw an ApiError, meaning we can retry.
if options.check and self.nbNewPosts isnt newPosts.length
Q.reject new ApiError "BUG ? #{self.nbNewPosts} new posts but we got only #{newPosts.length} records!"
else
# Prepend new posts (newest first like the API)
self.posts = Array::concat.call [], newPosts, self.posts
self
process 0, true
###*
@name downloadFile -- Downloads a file but optimize by first issuing a HEAD request.
@param output (String): output file name
@param url (String): URL to download file from
@param timestamp (String): specified because of return value being spreaded. Unused here.
NOTE: We compare files not by their timestamp but by their file sizes.
###
downloadFile = (output, url, timestamp) ->
file = "#{options.dest}/#{output}"
try
stats = fs.statSync(file)
isFile = stats.isFile()
catch
isFile = false
{size} = stats if isFile
promiseRetry ->
api url, 'HEAD'
.then (response) ->
contentLength = parseInt response.headers['content-length']
if !options.force and (size is contentLength)
log.notice '! Skipping', output, 'file has the same size (', size, 'bytes).\n'
return false
log.debug 'Remote file size:', contentLength, 'local file:', size, '\n'
bhttp.get url, stream:true
.then (stream) ->
if stream
stream.on 'progress', (completed, total) ->
log.info 'Download progress', path.basename(file), ':', ((completed / total) * 100).toFixed(2), '%\r'
stream.on 'error', (error) ->
log.error 'While writing to file', error
stream.on 'response', (response) ->
{statusCode} = response
log.info 'in response', statusCode, '\n'
# A bit hacky but basically, everything not 2XX will be retried.
if statusCode / 100 isnt 2
Q.reject new ApiError 'While downloading file, wrong statusCode returned', statusCode
unless /image/.test response.headers['content-type']
Q.reject new ApiError 'Content-Type mismatch:', response.headers['content-type']
stream.on 'finish', ->
if fileSize is expectedSize
log.info "✔ #{url} (#{statusCode}) -> #{file}\n"
Q(true)
else
Q.reject new ApiError 'Connection reset. Retrying.'
stream.pipe fs.createWriteStream file
###*
@name main -- this starts here!
###
main = ->
# Parse options first
res = options.parse()
# If we have a number, we should stop right away (error code).
return res if typeof res is 'number'
{blogname, dest} = options
# Promise to...
Q.Promise (accept, reject, notify) ->
# Create destination if it does not exist.
try
isDir = fs.statSync(dest).isDirectory()
if isDir
accept dest
else
mkdirp dest, (err) ->
reject err if err
accept dest
.then (realDestination) ->
log.debug 'Using output directory:', realDestination, '\n'
options.dest = realDestination
cacheFile = "#{options.dest}/.tumblrip"
# See if we already have a cache (.tumblrip file) in our destination directory.
# If so, load it, otherwise we initialize an empty 'database'.
try
if fs.statSync(cacheFile).isFile()
readFile cacheFile
.then (data) ->
[cacheFile, JSON.parse data]
catch e
[cacheFile, {}]
.spread (cacheFile, cache) ->
# Populate cache with fresh data (insert/update)
[cacheFile, getPostsData.call cache, blogname]
.spread (cacheFile, blog) ->
{title, total, posts, nbNewPosts} = blog
log.info 'Blog title:', title, '\n'
log.info 'New posts since last update', nbNewPosts, '\n'
log.info 'Blog total posts:', total, '\n'
log.info 'Blog unique photos:', posts.length, '\n'
log.info 'Duplicates:', total-posts.length, '\n'
# We remove 'nbNewPosts' as it is going to change and not relevant to store.
delete blog.nbNewPosts
# We store the 'database' as a plain old JSON, should/can be optimized a bit probably..
outputData = JSON.stringify blog
# Write "database" to outputdir/.tumblrip
if options.cache
writeFile cacheFile, outputData
.then ->
log.info 'Cache written.\n'
[blog.posts, total, nbNewPosts]
else
[blog.posts, total, nbNewPosts]
.spread (posts, total, nbNewPosts) ->
# If we want to refresh photos we can only count those we know they exist
# in the blog. Any other file previously stored will never have a chance to
# be downloaded again!
{startAt} = options
if options['refresh-photos']
if total < startAt
throw new Error "Starting at #{startAt} is above maximum blog photos #{total}!"
else
nbNewPosts = total - startAt
# If user wants to limit the number of downloaded images, make sure it is not
# more than the maximum expected from Tumblr API.
nbNewPosts = options.limit if options.limit > 0 and options.limit < nbNewPosts
if nbNewPosts > 0
log.info "Processing #{nbNewPosts} photos on #{options.threads} threads.\n"
threaded = (start) ->
threads = posts[start...start+options.threads]
log.debug "Starting at #{start}:", threads, '\n'
# Turning the promise of an array into an array of promises
allDone threads.map (post) ->
downloadFile.apply null, post
.then -> Q.delay options.delay
.then ->
start += options.threads
# Since posts array is sorted from the newest items, we can stop when
# we reach (or go beyond) the 'nbNewPosts' value.
if start > total or start >= nbNewPosts
nbNewPosts
else
threaded start
threaded startAt
else
log.info 'No new picture. If you want to force update, add --refresh-photos [-rp].\n'
1
.then (nbNewPosts) ->
log.info "Processed #{nbNewPosts} images.\n"
process.exit nbNewPosts
, (error) ->
log.error error.message, '\n'
log.debug error, '\n'
process.exit 0
, (notice) ->
log.notice notice
exports.main = main
| 101009 | # TumblRip -- Download photos from Tumblr
# Made by <NAME>
# Licence: MIT
# NodeJS imports
fs = require 'fs'
path = require 'path'
request = require 'request'
Q = require 'q'
mkdirp = require 'mkdirp'
URL = require 'url'
bhttp = require 'bhttp'
# My own imports
{ApiError, RejectError} = require './eh'
{log, pick, findInSubArray} = require './utils'
options = require './options'
{allDone, promiseRetry} = require './promise-helpers'
# Make these functions Promise-able.
readFile = Q.nfbind fs.readFile
writeFile = Q.nfbind fs.writeFile
statFile = Q.nfbind fs.stat
###*
@name api -- communicate with remote server API
@param uri (String): the URI to make call to
@param method (String): method to call (by default it is GET)
###
api = (uri, method='GET') ->
opts =
uri: uri
method: method
promiseRetry ->
log.info "#{method} #{uri} ...\n"
Q.nfcall request, opts
.spread (response, body) ->
{statusCode} = response
log.debug "Server status code: #{statusCode}\n"
# A bit hacky but basically, if we got 4XX (and most notably 404), we skip the file.
# If this is a 5XX we retry. Otherwise we keep going.
switch statusCode / 100
when 4
log.info 'File not found, continuing...'
Q.resolve statusCode
when 5
Q.reject new ApiError "Bad status code: #{statusCode}. Retrying..."
# Strip everything before the first '{' ... '}'
if body
json = body.match /^[^\{]+(.*)\;/
if json
try
return JSON.parse json[1]
catch
return Q.reject new ApiError 'Could not parse JSON.'
else
Q.reject new ApiError 'Could not parse response body.'
else
response
###*
@name getPostsData -- get all posts data from Tumblr blog
@param blogname (String) : the blog name (we construct the URL from it)
@param this (Object) : database read from / written to
###
getPostsData = (blogname) ->
# Build url and retrieve all data
url = "http://#{blogname}.tumblr.com/api/read/json"
@title ?= null
@total ?= 0
@posts ?= []
self = @
newPosts = []
@nbNewPosts = 0
process = (start, init=false) ->
log.debug "Processing at #{start}...\n"
# We know we only want photos and the maximum item size is 50.
# These are not variables for the purpose of this tool, but could easily be
# modified to download other stuff from a Tumblr blog ! :)
api "#{url}?type=photo&num=50&start=#{start}"
.then (parsed) ->
# Get total number of posts (when first time, this value is 0).
{total} = self
# Update these global variables only once
if init
self.title = parsed.tumblelog.title
# If we have more posts on our cache than on remote site..
if parsed['posts-total'] < total
# .. We know that we might have (among probably those already downloaded)
# at most parsed['posts-total'] new pictures to download.
self.nbNewPosts = parsed['posts-total']
else
self.nbNewPosts = parsed['posts-total'] - total
# We do not set local variable 'total' which will remain set to its
# initial value. This will be used later for sub array find.
self.total = parsed['posts-total']
parsed.posts.forEach (post) ->
photoUrl = post['photo-url-1280']
timestamp = post['unix-timestamp']
# We first build a filename from concatening URL pathname. That should be
# unique enough but makes longer filenames.
outputFile = URL.parse(photoUrl).pathname.split('/').join ''
# Do not bother searching if the database (aka cache) is empty (creating db).
# Otherwise search for this URL in the cache db.
if total is 0
found = -1
else
found = findInSubArray self.posts, 1, photoUrl
# Sometimes we have a 'slug' attribute that might have a better (human readable)
# filename (everything is better than a long hex string right ?)
if !!post.slug
slugfile = "#{post.slug}#{path.extname photoUrl}"
fileslug = findInSubArray self.posts, 0, slugfile, true
# If we already have more than one occurence or if that occurence does
# not link to the same file (the long hex string one), we have a conflict.
if fileslug.length > 1 or (fileslug.length is 1 and fileslug[0] isnt found)
log.info "Already got #{fileslug.length} file(s) of that name '", slugfile, "'. Using '", outputFile, "' instead.\n"
else
outputFile = slugfile
# We build our database record as an array where
# outputFile: definitive file with name either slugfile || photoUrl
# photoUrl: the remote photo endpoint URL
# status: 'D' for 'delete', 'U' for 'update' (default action)
array = [outputFile, photoUrl, 'U']
if found is -1
log.debug 'Record not found, creating', array, '\n'
newPosts.push array
else
log.debug "Updating record #{found}", self.posts[found], 'with', array, '...\n'
self.posts[found] = array
return
if options['refresh-db'] or (self.nbNewPosts >= 50 and self.total - start >= 50)
process start + 50
else
# Make sure we have all expected new posts. This is to make sure we have
# been given proper results from Tumblr API. Since this could also be a
# consequence of cache db tampering, this check, if enforced (opt in),
# will throw an ApiError, meaning we can retry.
if options.check and self.nbNewPosts isnt newPosts.length
Q.reject new ApiError "BUG ? #{self.nbNewPosts} new posts but we got only #{newPosts.length} records!"
else
# Prepend new posts (newest first like the API)
self.posts = Array::concat.call [], newPosts, self.posts
self
process 0, true
###*
@name downloadFile -- Downloads a file but optimize by first issuing a HEAD request.
@param output (String): output file name
@param url (String): URL to download file from
@param timestamp (String): specified because of return value being spreaded. Unused here.
NOTE: We compare files not by their timestamp but by their file sizes.
###
downloadFile = (output, url, timestamp) ->
file = "#{options.dest}/#{output}"
try
stats = fs.statSync(file)
isFile = stats.isFile()
catch
isFile = false
{size} = stats if isFile
promiseRetry ->
api url, 'HEAD'
.then (response) ->
contentLength = parseInt response.headers['content-length']
if !options.force and (size is contentLength)
log.notice '! Skipping', output, 'file has the same size (', size, 'bytes).\n'
return false
log.debug 'Remote file size:', contentLength, 'local file:', size, '\n'
bhttp.get url, stream:true
.then (stream) ->
if stream
stream.on 'progress', (completed, total) ->
log.info 'Download progress', path.basename(file), ':', ((completed / total) * 100).toFixed(2), '%\r'
stream.on 'error', (error) ->
log.error 'While writing to file', error
stream.on 'response', (response) ->
{statusCode} = response
log.info 'in response', statusCode, '\n'
# A bit hacky but basically, everything not 2XX will be retried.
if statusCode / 100 isnt 2
Q.reject new ApiError 'While downloading file, wrong statusCode returned', statusCode
unless /image/.test response.headers['content-type']
Q.reject new ApiError 'Content-Type mismatch:', response.headers['content-type']
stream.on 'finish', ->
if fileSize is expectedSize
log.info "✔ #{url} (#{statusCode}) -> #{file}\n"
Q(true)
else
Q.reject new ApiError 'Connection reset. Retrying.'
stream.pipe fs.createWriteStream file
###*
@name main -- this starts here!
###
main = ->
# Parse options first
res = options.parse()
# If we have a number, we should stop right away (error code).
return res if typeof res is 'number'
{blogname, dest} = options
# Promise to...
Q.Promise (accept, reject, notify) ->
# Create destination if it does not exist.
try
isDir = fs.statSync(dest).isDirectory()
if isDir
accept dest
else
mkdirp dest, (err) ->
reject err if err
accept dest
.then (realDestination) ->
log.debug 'Using output directory:', realDestination, '\n'
options.dest = realDestination
cacheFile = "#{options.dest}/.tumblrip"
# See if we already have a cache (.tumblrip file) in our destination directory.
# If so, load it, otherwise we initialize an empty 'database'.
try
if fs.statSync(cacheFile).isFile()
readFile cacheFile
.then (data) ->
[cacheFile, JSON.parse data]
catch e
[cacheFile, {}]
.spread (cacheFile, cache) ->
# Populate cache with fresh data (insert/update)
[cacheFile, getPostsData.call cache, blogname]
.spread (cacheFile, blog) ->
{title, total, posts, nbNewPosts} = blog
log.info 'Blog title:', title, '\n'
log.info 'New posts since last update', nbNewPosts, '\n'
log.info 'Blog total posts:', total, '\n'
log.info 'Blog unique photos:', posts.length, '\n'
log.info 'Duplicates:', total-posts.length, '\n'
# We remove 'nbNewPosts' as it is going to change and not relevant to store.
delete blog.nbNewPosts
# We store the 'database' as a plain old JSON, should/can be optimized a bit probably..
outputData = JSON.stringify blog
# Write "database" to outputdir/.tumblrip
if options.cache
writeFile cacheFile, outputData
.then ->
log.info 'Cache written.\n'
[blog.posts, total, nbNewPosts]
else
[blog.posts, total, nbNewPosts]
.spread (posts, total, nbNewPosts) ->
# If we want to refresh photos we can only count those we know they exist
# in the blog. Any other file previously stored will never have a chance to
# be downloaded again!
{startAt} = options
if options['refresh-photos']
if total < startAt
throw new Error "Starting at #{startAt} is above maximum blog photos #{total}!"
else
nbNewPosts = total - startAt
# If user wants to limit the number of downloaded images, make sure it is not
# more than the maximum expected from Tumblr API.
nbNewPosts = options.limit if options.limit > 0 and options.limit < nbNewPosts
if nbNewPosts > 0
log.info "Processing #{nbNewPosts} photos on #{options.threads} threads.\n"
threaded = (start) ->
threads = posts[start...start+options.threads]
log.debug "Starting at #{start}:", threads, '\n'
# Turning the promise of an array into an array of promises
allDone threads.map (post) ->
downloadFile.apply null, post
.then -> Q.delay options.delay
.then ->
start += options.threads
# Since posts array is sorted from the newest items, we can stop when
# we reach (or go beyond) the 'nbNewPosts' value.
if start > total or start >= nbNewPosts
nbNewPosts
else
threaded start
threaded startAt
else
log.info 'No new picture. If you want to force update, add --refresh-photos [-rp].\n'
1
.then (nbNewPosts) ->
log.info "Processed #{nbNewPosts} images.\n"
process.exit nbNewPosts
, (error) ->
log.error error.message, '\n'
log.debug error, '\n'
process.exit 0
, (notice) ->
log.notice notice
exports.main = main
| true | # TumblRip -- Download photos from Tumblr
# Made by PI:NAME:<NAME>END_PI
# Licence: MIT
# NodeJS imports
fs = require 'fs'
path = require 'path'
request = require 'request'
Q = require 'q'
mkdirp = require 'mkdirp'
URL = require 'url'
bhttp = require 'bhttp'
# My own imports
{ApiError, RejectError} = require './eh'
{log, pick, findInSubArray} = require './utils'
options = require './options'
{allDone, promiseRetry} = require './promise-helpers'
# Make these functions Promise-able.
readFile = Q.nfbind fs.readFile
writeFile = Q.nfbind fs.writeFile
statFile = Q.nfbind fs.stat
###*
@name api -- communicate with remote server API
@param uri (String): the URI to make call to
@param method (String): method to call (by default it is GET)
###
api = (uri, method='GET') ->
opts =
uri: uri
method: method
promiseRetry ->
log.info "#{method} #{uri} ...\n"
Q.nfcall request, opts
.spread (response, body) ->
{statusCode} = response
log.debug "Server status code: #{statusCode}\n"
# A bit hacky but basically, if we got 4XX (and most notably 404), we skip the file.
# If this is a 5XX we retry. Otherwise we keep going.
switch statusCode / 100
when 4
log.info 'File not found, continuing...'
Q.resolve statusCode
when 5
Q.reject new ApiError "Bad status code: #{statusCode}. Retrying..."
# Strip everything before the first '{' ... '}'
if body
json = body.match /^[^\{]+(.*)\;/
if json
try
return JSON.parse json[1]
catch
return Q.reject new ApiError 'Could not parse JSON.'
else
Q.reject new ApiError 'Could not parse response body.'
else
response
###*
@name getPostsData -- get all posts data from Tumblr blog
@param blogname (String) : the blog name (we construct the URL from it)
@param this (Object) : database read from / written to
###
getPostsData = (blogname) ->
# Build url and retrieve all data
url = "http://#{blogname}.tumblr.com/api/read/json"
@title ?= null
@total ?= 0
@posts ?= []
self = @
newPosts = []
@nbNewPosts = 0
process = (start, init=false) ->
log.debug "Processing at #{start}...\n"
# We know we only want photos and the maximum item size is 50.
# These are not variables for the purpose of this tool, but could easily be
# modified to download other stuff from a Tumblr blog ! :)
api "#{url}?type=photo&num=50&start=#{start}"
.then (parsed) ->
# Get total number of posts (when first time, this value is 0).
{total} = self
# Update these global variables only once
if init
self.title = parsed.tumblelog.title
# If we have more posts on our cache than on remote site..
if parsed['posts-total'] < total
# .. We know that we might have (among probably those already downloaded)
# at most parsed['posts-total'] new pictures to download.
self.nbNewPosts = parsed['posts-total']
else
self.nbNewPosts = parsed['posts-total'] - total
# We do not set local variable 'total' which will remain set to its
# initial value. This will be used later for sub array find.
self.total = parsed['posts-total']
parsed.posts.forEach (post) ->
photoUrl = post['photo-url-1280']
timestamp = post['unix-timestamp']
# We first build a filename from concatening URL pathname. That should be
# unique enough but makes longer filenames.
outputFile = URL.parse(photoUrl).pathname.split('/').join ''
# Do not bother searching if the database (aka cache) is empty (creating db).
# Otherwise search for this URL in the cache db.
if total is 0
found = -1
else
found = findInSubArray self.posts, 1, photoUrl
# Sometimes we have a 'slug' attribute that might have a better (human readable)
# filename (everything is better than a long hex string right ?)
if !!post.slug
slugfile = "#{post.slug}#{path.extname photoUrl}"
fileslug = findInSubArray self.posts, 0, slugfile, true
# If we already have more than one occurence or if that occurence does
# not link to the same file (the long hex string one), we have a conflict.
if fileslug.length > 1 or (fileslug.length is 1 and fileslug[0] isnt found)
log.info "Already got #{fileslug.length} file(s) of that name '", slugfile, "'. Using '", outputFile, "' instead.\n"
else
outputFile = slugfile
# We build our database record as an array where
# outputFile: definitive file with name either slugfile || photoUrl
# photoUrl: the remote photo endpoint URL
# status: 'D' for 'delete', 'U' for 'update' (default action)
array = [outputFile, photoUrl, 'U']
if found is -1
log.debug 'Record not found, creating', array, '\n'
newPosts.push array
else
log.debug "Updating record #{found}", self.posts[found], 'with', array, '...\n'
self.posts[found] = array
return
if options['refresh-db'] or (self.nbNewPosts >= 50 and self.total - start >= 50)
process start + 50
else
# Make sure we have all expected new posts. This is to make sure we have
# been given proper results from Tumblr API. Since this could also be a
# consequence of cache db tampering, this check, if enforced (opt in),
# will throw an ApiError, meaning we can retry.
if options.check and self.nbNewPosts isnt newPosts.length
Q.reject new ApiError "BUG ? #{self.nbNewPosts} new posts but we got only #{newPosts.length} records!"
else
# Prepend new posts (newest first like the API)
self.posts = Array::concat.call [], newPosts, self.posts
self
process 0, true
###*
@name downloadFile -- Downloads a file but optimize by first issuing a HEAD request.
@param output (String): output file name
@param url (String): URL to download file from
@param timestamp (String): specified because of return value being spreaded. Unused here.
NOTE: We compare files not by their timestamp but by their file sizes.
###
downloadFile = (output, url, timestamp) ->
file = "#{options.dest}/#{output}"
try
stats = fs.statSync(file)
isFile = stats.isFile()
catch
isFile = false
{size} = stats if isFile
promiseRetry ->
api url, 'HEAD'
.then (response) ->
contentLength = parseInt response.headers['content-length']
if !options.force and (size is contentLength)
log.notice '! Skipping', output, 'file has the same size (', size, 'bytes).\n'
return false
log.debug 'Remote file size:', contentLength, 'local file:', size, '\n'
bhttp.get url, stream:true
.then (stream) ->
if stream
stream.on 'progress', (completed, total) ->
log.info 'Download progress', path.basename(file), ':', ((completed / total) * 100).toFixed(2), '%\r'
stream.on 'error', (error) ->
log.error 'While writing to file', error
stream.on 'response', (response) ->
{statusCode} = response
log.info 'in response', statusCode, '\n'
# A bit hacky but basically, everything not 2XX will be retried.
if statusCode / 100 isnt 2
Q.reject new ApiError 'While downloading file, wrong statusCode returned', statusCode
unless /image/.test response.headers['content-type']
Q.reject new ApiError 'Content-Type mismatch:', response.headers['content-type']
stream.on 'finish', ->
if fileSize is expectedSize
log.info "✔ #{url} (#{statusCode}) -> #{file}\n"
Q(true)
else
Q.reject new ApiError 'Connection reset. Retrying.'
stream.pipe fs.createWriteStream file
###*
@name main -- this starts here!
###
main = ->
# Parse options first
res = options.parse()
# If we have a number, we should stop right away (error code).
return res if typeof res is 'number'
{blogname, dest} = options
# Promise to...
Q.Promise (accept, reject, notify) ->
# Create destination if it does not exist.
try
isDir = fs.statSync(dest).isDirectory()
if isDir
accept dest
else
mkdirp dest, (err) ->
reject err if err
accept dest
.then (realDestination) ->
log.debug 'Using output directory:', realDestination, '\n'
options.dest = realDestination
cacheFile = "#{options.dest}/.tumblrip"
# See if we already have a cache (.tumblrip file) in our destination directory.
# If so, load it, otherwise we initialize an empty 'database'.
try
if fs.statSync(cacheFile).isFile()
readFile cacheFile
.then (data) ->
[cacheFile, JSON.parse data]
catch e
[cacheFile, {}]
.spread (cacheFile, cache) ->
# Populate cache with fresh data (insert/update)
[cacheFile, getPostsData.call cache, blogname]
.spread (cacheFile, blog) ->
{title, total, posts, nbNewPosts} = blog
log.info 'Blog title:', title, '\n'
log.info 'New posts since last update', nbNewPosts, '\n'
log.info 'Blog total posts:', total, '\n'
log.info 'Blog unique photos:', posts.length, '\n'
log.info 'Duplicates:', total-posts.length, '\n'
# We remove 'nbNewPosts' as it is going to change and not relevant to store.
delete blog.nbNewPosts
# We store the 'database' as a plain old JSON, should/can be optimized a bit probably..
outputData = JSON.stringify blog
# Write "database" to outputdir/.tumblrip
if options.cache
writeFile cacheFile, outputData
.then ->
log.info 'Cache written.\n'
[blog.posts, total, nbNewPosts]
else
[blog.posts, total, nbNewPosts]
.spread (posts, total, nbNewPosts) ->
# If we want to refresh photos we can only count those we know they exist
# in the blog. Any other file previously stored will never have a chance to
# be downloaded again!
{startAt} = options
if options['refresh-photos']
if total < startAt
throw new Error "Starting at #{startAt} is above maximum blog photos #{total}!"
else
nbNewPosts = total - startAt
# If user wants to limit the number of downloaded images, make sure it is not
# more than the maximum expected from Tumblr API.
nbNewPosts = options.limit if options.limit > 0 and options.limit < nbNewPosts
if nbNewPosts > 0
log.info "Processing #{nbNewPosts} photos on #{options.threads} threads.\n"
threaded = (start) ->
threads = posts[start...start+options.threads]
log.debug "Starting at #{start}:", threads, '\n'
# Turning the promise of an array into an array of promises
allDone threads.map (post) ->
downloadFile.apply null, post
.then -> Q.delay options.delay
.then ->
start += options.threads
# Since posts array is sorted from the newest items, we can stop when
# we reach (or go beyond) the 'nbNewPosts' value.
if start > total or start >= nbNewPosts
nbNewPosts
else
threaded start
threaded startAt
else
log.info 'No new picture. If you want to force update, add --refresh-photos [-rp].\n'
1
.then (nbNewPosts) ->
log.info "Processed #{nbNewPosts} images.\n"
process.exit nbNewPosts
, (error) ->
log.error error.message, '\n'
log.debug error, '\n'
process.exit 0
, (notice) ->
log.notice notice
exports.main = main
|
[
{
"context": "), Factory(\"Magikarp\")]\n team2: [Factory(\"Shedinja\")]\n @p1.currentHP = 2\n @battle.perf",
"end": 2628,
"score": 0.6445953845977783,
"start": 2625,
"tag": "NAME",
"value": "hed"
},
{
"context": "is,\n team1: [Factory(\"Magikarp\"), Factory(\... | test/bw/abilities.coffee | sarenji/pokebattle-sim | 5 | require '../helpers'
{Attachment, Status} = require('../../server/bw/attachment')
{Battle} = require('../../server/bw/battle')
{Pokemon} = require('../../server/bw/pokemon')
{Weather} = require('../../shared/weather')
{Item} = require('../../server/bw/data/items')
{Ability} = require '../../server/bw/data/abilities'
util = require '../../server/bw/util'
{Factory} = require '../factory'
should = require 'should'
sinon = require 'sinon'
{_} = require 'underscore'
shared = require '../shared'
describe "BW Abilities:", ->
describe "Adaptability", ->
it "makes STAB 2x instead of 1.5", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Adaptability")]
hydroPump = @battle.getMove("Hydro Pump")
hydroPump.stabModifier(@battle, @p1, @p2).should.equal(0x2000)
it "still has 1x if the pokemon does not have STAB", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Adaptability")]
tackle = @battle.getMove("Tackle")
tackle.stabModifier(@battle, @p1, @p2).should.equal(0x1000)
describe "Aftermath", ->
it "deals 25% HP damage to the killer", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Aftermath"), Factory("Magikarp")]
@p1.currentHP = 1
@battle.performMove(@p2, @battle.getMove("Tackle"))
@battle.performFaints()
(@p2.stat('hp') - @p2.currentHP).should.equal(@p2.stat('hp') >> 2)
it "does not deal damage for non-contact moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Aftermath"), Factory("Magikarp")]
@p1.currentHP = 1
@battle.performMove(@p2, @battle.getMove("Thunderbolt"))
@battle.performFaints()
@p2.currentHP.should.equal(@p2.stat('hp'))
it "does not deal damage if pokemon died of natural causes", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Aftermath"), Factory("Magikarp")]
thunderbolt = @battle.getMove("Thunderbolt")
@p1.currentHP = 2
@p1.attach(Status.Burn)
@sandbox.stub(thunderbolt, 'calculateDamage', -> 1)
@battle.performMove(@p2, thunderbolt)
@battle.endTurn()
@p2.currentHP.should.equal(@p2.stat('hp'))
it "does not crash if the Pokemon never was hit", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Aftermath"), Factory("Magikarp")]
(=> @p1.faint()).should.not.throw()
it "deals a minimum of 1 damage", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Aftermath"), Factory("Magikarp")]
team2: [Factory("Shedinja")]
@p1.currentHP = 2
@battle.performMove(@p2, @battle.getMove("Tackle"))
@battle.performFaints()
@p2.currentHP.should.equal(0)
testWeatherPreventionAbility = (name) ->
describe name, ->
it "causes the battle to think there is no weather", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
@battle.setWeather(Weather.SAND)
@battle.hasWeather(Weather.SAND).should.be.false
@battle.setWeather(Weather.SUN)
@battle.hasWeather(Weather.SUN).should.be.false
testWeatherPreventionAbility("Air Lock")
testWeatherPreventionAbility("Cloud Nine")
describe "Analytic", ->
it "multiplies attacks by 1.3 if no one is moving afterward", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Analytic")]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x14CD)
it "doesn't multiply if the user isn't the last to move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Analytic")]
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
describe "Anger Point", ->
it "maximizes Attack on critical hit", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Anger Point")]
tackle = @battle.getMove("Tackle")
@sandbox.stub(tackle, 'isCriticalHit', -> true)
@p1.stages.attack.should.equal(0)
@battle.performMove(@p2, tackle)
@p1.stages.should.containEql(attack: 6)
it "doesn't maximize attack on non-critical hits", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Anger Point")]
tackle = @battle.getMove("Tackle")
@sandbox.stub(tackle, 'isCriticalHit', -> false)
@p1.stages.attack.should.equal(0)
@battle.performMove(@p2, tackle)
@p1.stages.should.containEql(attack: 0)
describe "Anticipation", ->
it "shows a message if an opponent has a super-effective move", ->
shared.create.call this,
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Anticipation")]
team2: [Factory("Pikachu", moves: ["Thunderbolt"])]
spy = @sandbox.spy(@battle, 'cannedText')
@battle.performSwitch(@p1, 1)
spy.calledWithMatch('ANTICIPATION').should.be.true
it "shows a message if an opponent has an OHKO move", ->
shared.create.call this,
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Anticipation")]
team2: [Factory("Lapras", moves: ["Sheer Cold"])]
spy = @sandbox.spy(@battle, 'cannedText')
@battle.performSwitch(@p1, 1)
spy.calledWithMatch('ANTICIPATION').should.be.true
it "doesn't show a message otherwise", ->
shared.create.call this,
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Anticipation")]
spy = @sandbox.spy(@battle, 'cannedText')
@battle.performSwitch(@p1, 1)
spy.calledWithMatch('ANTICIPATION').should.be.false
it "displays nothing when no opponents left", ->
shared.create.call this,
team1: [Factory("Magikarp")]
team2: [Factory("Magikarp"), Factory("Magikarp")]
@p2.faint()
spy = @sandbox.spy(@battle, 'cannedText')
@p1.copyAbility(Ability.Anticipation)
spy.called.should.be.false
describe "Arena Trap", ->
it "blocks switch", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Arena Trap")]
team2: [Factory("Magikarp")]
@p2.isSwitchBlocked().should.be.true
it "blocks switch the next turn as well", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Arena Trap")]
team2: [Factory("Magikarp")]
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.true
it "doesn't block switch for Flying Pokemon", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Arena Trap")]
team2: [Factory("Gyarados")]
@p2.isSwitchBlocked().should.be.false
it "doesn't block switch for Pokemon immune to Ground by other means", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Arena Trap")]
team2: [Factory("Magikarp")]
@battle.performMove(@p2, @battle.getMove("Magnet Rise"))
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.false
describe "Bad Dreams", ->
it "deals 1/8 max HP end of turn if target is asleep", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Bad Dreams")]
team2: [Factory("Celebi")]
(@p2.stat('hp') - @p2.currentHP).should.equal(0)
@p2.attach(Status.Sleep)
@battle.endTurn()
(@p2.stat('hp') - @p2.currentHP).should.equal(@p2.stat('hp') >> 3)
it "deals no damage if target is awake", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Bad Dreams")]
team2: [Factory("Celebi")]
(@p2.stat('hp') - @p2.currentHP).should.equal(0)
@battle.endTurn()
(@p2.stat('hp') - @p2.currentHP).should.equal(0)
it "deals a minimum of 1 damage", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Bad Dreams")]
team2: [Factory("Shedinja")]
@p2.attach(Status.Sleep)
@battle.endTurn()
@p2.currentHP.should.equal(0)
testCriticalHitPreventionAbility = (name) ->
describe name, ->
it "prevents critical hits", ->
shared.create.call this,
team1: [Factory("Magikarp")]
team2: [Factory("Celebi", ability: name)]
shared.biasRNG.call(this, "next", "ch", .2)
tackle = @battle.getMove("Tackle")
@sandbox.stub(tackle, 'criticalHitLevel', -> 3)
tackle.isCriticalHit(@battle, @p1, @p2).should.be.false
testCriticalHitPreventionAbility("Battle Armor")
testCriticalHitPreventionAbility("Shell Armor")
testBoostProtectionAbility = (name, protection) ->
describe name, ->
allBoosts = [ "attack", "defense", "speed", "specialAttack",
"specialDefense", "accuracy", "evasion" ]
protection ||= allBoosts
it "protects against certain stat falls", ->
shared.create.call this, team1: [Factory("Celebi", ability: name)]
boosts = {}
boosts[stat] = -1 for stat in allBoosts
@p1.boost(boosts, @p2)
boosts[stat] = 0 for stat in protection
@p1.stages.should.eql(boosts)
it "does not protect against stat falls if the source is the user", ->
shared.create.call this, team1: [Factory("Celebi", ability: name)]
boosts = {}
boosts[stat] = -1 for stat in allBoosts
@p1.boost(boosts)
@p1.stages.should.containEql(boosts)
testBoostProtectionAbility("Big Pecks", [ "defense" ])
testBoostProtectionAbility("Clear Body")
testBoostProtectionAbility("Hyper Cutter", [ "attack" ])
testBoostProtectionAbility("Keen Eye", [ "accuracy" ])
testBoostProtectionAbility("White Smoke")
testLowHealthAbility = (name, type) ->
describe name, ->
it "increases power of #{type} moves by 1.5 at 1/3 health", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
@p1.currentHP = Math.floor(@p1.stat('hp') / 3)
move = _(@battle.MoveList).find (m) ->
m.type == type && !m.isNonDamaging()
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1800)
it "doesn't increase power if move not of #{type}", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
@p1.currentHP = Math.floor(@p1.stat('hp') / 3)
move = _(@battle.MoveList).find (m) ->
m.type != type && !m.isNonDamaging()
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "doesn't increase power if user isn't under 1/3 health", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
@p1.currentHP = Math.floor(@p1.stat('hp') / 3) + 1
move = _(@battle.MoveList).find (m) ->
m.type == type && !m.isNonDamaging()
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
testLowHealthAbility("Blaze", "Fire")
testLowHealthAbility("Torrent", "Water")
testLowHealthAbility("Overgrow", "Grass")
testLowHealthAbility("Swarm", "Bug")
testWeatherSpeedAbility = (name, weather) ->
describe name, ->
it "doubles speed when the weather becomes #{weather}", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
speed = @p1.stat('speed')
@battle.setWeather(weather)
@p1.stat('speed').should.equal(2 * speed)
it "goes back to normal when the weather becomes something else", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
speed = @p1.stat('speed')
@battle.setWeather(weather)
@battle.setWeather(Weather.NONE)
@p1.stat('speed').should.equal(speed)
it "grants immunity to damage from their respective weather", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
@p1.isWeatherDamageImmune(weather).should.be.true
testWeatherSpeedAbility("Chlorophyll", Weather.SUN)
testWeatherSpeedAbility("Swift Swim", Weather.RAIN)
testWeatherSpeedAbility("Sand Rush", Weather.SAND)
describe "Color Change", ->
it "changes the owner's type to be the move's type that just hit it", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Color Change")]
ember = @battle.getMove("Ember")
@p1.hasType(ember.type).should.be.false
@battle.performMove(@p2, ember)
@p1.hasType(ember.type).should.be.true
it "does not change the owner's type if the move is non-damaging", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Color Change")]
willOWisp = @battle.getMove("Will-O-Wisp")
@p1.hasType(willOWisp.type).should.be.false
@battle.performMove(@p2, willOWisp)
@p1.hasType(willOWisp.type).should.be.false
describe "Compoundeyes", ->
it "increases accuracy of moves by 1.3x", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Compoundeyes")]
willOWisp = @battle.getMove("Will-O-Wisp")
accuracy = willOWisp.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal Math.floor(willOWisp.accuracy * 1.3)
describe "Contrary", ->
it "reverses stat changes from all sources", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Contrary")]
leafStorm = @battle.getMove("Leaf Storm")
growl = @battle.getMove("Growl")
@battle.performMove(@p1, leafStorm)
@p1.stages.should.containEql(specialAttack: 2)
@battle.performMove(@p2, growl)
@p1.stages.should.containEql(attack: 1)
describe "Cursed Body", ->
it "has a 30% chance to disable an attacker's last move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 0)
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.true
it "does not disable the owner", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 0)
recover = @battle.getMove("Recover")
@p1.moves = [ recover ]
@p1.resetAllPP()
@p1.currentHP = 1
@battle.performMove(@p1, recover)
@p1.isMoveBlocked(recover).should.be.false
it "does not disable if attacker is behind a substitute", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 0)
tackle = @battle.getMove("Tackle")
substitute = @battle.getMove("Substitute")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, substitute)
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.false
it "does not disable if defender is behind a substitute", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 0)
tackle = @battle.getMove("Tackle")
substitute = @battle.getMove("Substitute")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p1, substitute)
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.false
it "has a 70% chance to do nothing", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", .3)
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.false
it "can work even if the defender faints", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Cursed Body"), Factory("Magikarp")]
shared.biasRNG.call(this, "next", "cursed body", 0)
@p1.currentHP = 1
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.true
it "lasts some turns", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 0)
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, tackle)
for x in [1..2]
@battle.endTurn()
@battle.beginTurn()
@p2.isMoveBlocked(tackle).should.be.true
it "cannot stack with Disable", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 1) # do not trigger
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, tackle)
@battle.performMove(@p1, @battle.getMove('Disable'))
@p2.isMoveBlocked(tackle).should.be.true
# Disable lasts 4 turns, so go to the last turn.
for x in [1..3]
@battle.endTurn()
@battle.beginTurn()
@p2.isMoveBlocked(tackle).should.be.true
shared.biasRNG.call(this, "next", "cursed body", 0)
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.true
# Disable should end.
@battle.endTurn()
@battle.beginTurn()
@p2.isMoveBlocked(tackle).should.be.false
describe "Defeatist", ->
it "halves attack and special attack if HP goes under 50%", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Defeatist")]
tackle = @battle.getMove("Tackle")
thunderbolt = @battle.getMove("Thunderbolt")
# 50%
@p1.currentHP = (@p1.stat('hp') >> 1)
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x800)
thunderbolt.modifyAttack(@battle, @p1, @p2).should.equal(0x800)
# 50% + 1
@p1.currentHP = (@p1.stat('hp') >> 1) + 1
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
thunderbolt.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
describe "Defiant", ->
it "boosts attack by 2 every time a stat is lowered", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Defiant")]
@p1.boost(defense: -1, @p2)
@p1.stages.should.containEql(attack: 2)
@p1.boost(attack: -1, defense: -2, evasion: 1, @p2)
@p1.stages.should.containEql(attack: 5)
it "does not boost attack if the stat was self-lowered", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Defiant")]
@battle.performMove(@p1, @battle.getMove("Close Combat"))
@p1.stages.should.containEql(attack: 0, defense: -1, specialDefense: -1)
describe "Download", ->
it "raises attack if foes have total defense < total sp.def", ->
shared.create.call this,
team1: [Factory("Magikarp")]
team2: [Factory("Abomasnow")]
@p1.stages.should.containEql(attack: 0)
@p1.copyAbility(Ability.Download)
@p1.stages.should.containEql(attack: 1)
it "raises special attack if foes have total sp.def <= total def", ->
shared.create.call this,
team1: [Factory("Magikarp")]
team2: [Factory("Celebi")]
@p1.stages.should.containEql(specialAttack: 0)
@p1.copyAbility(Ability.Download)
@p1.stages.should.containEql(specialAttack: 1)
it "does not raise anything if all foes have fainted", ->
shared.create.call(this)
@p2.faint()
@p1.stages.should.containEql(attack: 0, specialAttack: 0)
@p1.copyAbility(Ability.Download)
@p1.stages.should.containEql(attack: 0, specialAttack: 0)
testWeatherAbility = (name, weather) ->
describe name, ->
it "causes unending #{weather}", ->
shared.build(this, team1: [Factory("Magikarp", ability: name)])
@battle.hasWeather().should.be.false
@controller.beginBattle()
@battle.hasWeather(weather).should.be.true
@battle.weatherDuration.should.equal(-1)
testWeatherAbility("Drizzle", Weather.RAIN)
testWeatherAbility("Drought", Weather.SUN)
testWeatherAbility("Sand Stream", Weather.SAND)
testWeatherAbility("Snow Warning", Weather.HAIL)
describe "Dry Skin", ->
it "gets healed 25% HP by water moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Dry Skin")])
@p1.currentHP = 1
@battle.performMove(@p2, @battle.getMove("Hydro Pump"))
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 2))
@battle.performMove(@p2, @battle.getMove("Tackle"))
@p1.currentHP.should.be.lessThan(1 + (@p1.stat('hp') >> 2))
it "does not get healed by self-targeting water moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Dry Skin")])
@p1.currentHP = 1
@battle.performMove(@p1, @battle.getMove("Aqua Ring"))
@p1.currentHP.should.equal(1)
it "gets healed 1/8 HP end of turn in Rain", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Dry Skin")])
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1)
@battle.setWeather(Weather.RAIN)
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 3))
it "gets damaged 25% extra by fire moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Dry Skin")])
ember = @battle.getMove("Ember")
ember.modifyBasePower(@battle, @p2, @p1).should.equal(0x1400)
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p2, @p1).should.equal(0x1000)
it "gets hurt 1/8 HP end of turn in Sun", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Dry Skin")])
@battle.endTurn()
@p1.currentHP.should.equal(@p1.stat('hp'))
@battle.setWeather(Weather.SUN)
@battle.endTurn()
(@p1.stat('hp') - @p1.currentHP).should.equal(@p1.stat('hp') >> 3)
it "deals a minimum of 1 damage", ->
shared.create.call this,
team1: [Factory("Shedinja", ability: "Dry Skin")]
@battle.setWeather(Weather.SUN)
@battle.endTurn()
@p1.currentHP.should.equal(0)
it "heals a minimum of 1 hp", ->
shared.create.call this,
team1: [Factory("Magikarp", level: 1, ability: "Dry Skin")]
@p1.currentHP = 1
@battle.setWeather(Weather.RAIN)
@battle.endTurn()
@p1.currentHP.should.equal(2)
describe "Early Bird", ->
it "drops the sleep counter by 2 instead of 1", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Early Bird")])
shared.biasRNG.call(this, "randInt", 'sleep turns', 3)
@p1.attach(Status.Sleep)
@battle.performMove(@p1, @battle.getMove('Tackle'))
@p1.has(Status.Sleep).should.be.true
@battle.performMove(@p1, @battle.getMove('Tackle'))
@p1.has(Status.Sleep).should.be.false
describe "Effect Spore", ->
it "has a 30% chance to inflict poison, paralysis, or sleep on hit", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Effect Spore")])
# Sleep
shared.biasRNG.call(this, "randInt", 'effect spore', 1)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(Status.Sleep).should.be.true
# Paralysis
@p2.cureStatus()
shared.biasRNG.call(this, "randInt", 'effect spore', 2)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(Status.Paralyze).should.be.true
# Poison
@p2.cureStatus()
shared.biasRNG.call(this, "randInt", 'effect spore', 3)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(Status.Poison).should.be.true
it "has a 70% chance to do nothing", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Effect Spore")])
shared.biasRNG.call(this, "randInt", 'effect spore', 4)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.hasStatus().should.be.false
it "doesn't trigger if the hitting move is a non-contact move", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Effect Spore")])
shared.biasRNG.call(this, "randInt", 'effect spore', 1)
@battle.performMove(@p2, @battle.getMove('Thunderbolt'))
@p2.has(Status.Sleep).should.be.false
it "can work even if the defender faints", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Effect Spore"), Factory("Magikarp")]
shared.biasRNG.call(this, "randInt", 'effect spore', 1)
@p1.currentHP = 1
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(Status.Sleep).should.be.true
testFilterAbility = (name) ->
describe name, ->
it "reduces the impact of super-effective moves by 25%", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
seMove = _(@battle.MoveList).find (m) =>
!m.isNonDamaging() && util.typeEffectiveness(m.type, @p1.types) > 1
seMove.modifyDamage(@battle, @p2, @p1).should.equal(0xC00)
it "keeps non-super-effective moves as normal", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
seMove = _(@battle.MoveList).find (m) =>
!m.isNonDamaging() && util.typeEffectiveness(m.type, @p1.types) <= 1
seMove.modifyDamage(@battle, @p2, @p1).should.equal(0x1000)
testFilterAbility("Filter")
testFilterAbility("Solid Rock")
testContactStatusAbility = (name, attachment) ->
describe name, ->
it "has a 30% chance to inflict #{attachment.name} on the attacker", ->
shared.create.call this,
team1: [Factory("Magikarp", gender: "F", ability: name)]
team2: [Factory("Magikarp", gender: "M")]
shared.biasRNG.call(this, "next", 'contact status', 0)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(attachment).should.be.true
it "inflicts no status if the move used is a non-contact move", ->
shared.create.call this,
team1: [Factory("Magikarp", gender: "F", ability: name)]
team2: [Factory("Magikarp", gender: "M")]
shared.biasRNG.call(this, "next", 'contact status', 0)
@battle.performMove(@p2, @battle.getMove('Thunderbolt'))
@p2.has(attachment).should.be.false
it "inflicts no status if the hit isn't direct", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
team2: [Factory("Magikarp")]
shared.biasRNG.call(this, "next", 'contact status', 0)
@p1.attach(Attachment.Substitute)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(attachment).should.be.false
it "has a 70% chance to do nothing", ->
shared.create.call this,
team1: [Factory("Magikarp", gender: "F", ability: name)]
team2: [Factory("Magikarp", gender: "M")]
shared.biasRNG.call(this, "next", 'contact status', .3)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(attachment).should.be.false
it "can work even if the defender faints", ->
shared.create.call this,
team1: [Factory("Magikarp", gender: "F", ability: name), Factory("Magikarp")]
team2: [Factory("Magikarp", gender: "M")]
shared.biasRNG.call(this, "next", 'contact status', 0)
@p1.currentHP = 1
tackle = @battle.getMove('Tackle')
@battle.performMove(@p2, tackle)
@p2.has(attachment).should.be.true
testContactStatusAbility("Cute Charm", Attachment.Attract)
testContactStatusAbility("Flame Body", Status.Burn)
testContactStatusAbility("Poison Point", Status.Poison)
testContactStatusAbility("Static", Status.Paralyze)
testStatusBoostAbility = (name, statuses, spectra) ->
statusNames = statuses.map((s) -> s.name).join(', ')
describe name, ->
it "increases #{spectra} moves by 1.5 if has #{statusNames}", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
move = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.spectra == spectra
for status in statuses
@p1.cureStatus()
@p1.attach(status)
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1800)
it "does not increase non-#{spectra} moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
move = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.spectra != spectra
for status in statuses
@p1.cureStatus()
@p1.attach(status)
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
testStatusBoostAbility("Flare Boost", [Status.Burn], "special")
testStatusBoostAbility("Toxic Boost", [Status.Poison, Status.Toxic], "physical")
describe "Flash Fire", ->
it "makes user invulnerable to Fire-type moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Flash Fire")])
ember = @battle.getMove("Ember")
mock = @sandbox.mock(ember).expects('hit').never()
@battle.performMove(@p2, ember)
mock.verify()
it "powers up user's Fire-type moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Flash Fire")])
ember = @battle.getMove("Ember")
tackle = @battle.getMove("Tackle")
@battle.performMove(@p2, ember)
ember.modifyBasePower(@battle, @p1, @p2).should.equal(0x1800)
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "doesn't activate on Protect", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Flash Fire")])
protect = @battle.getMove("Protect")
ember = @battle.getMove("Ember")
@battle.recordMove(@id1, protect)
@battle.recordMove(@id2, ember)
@battle.continueTurn()
@p1.has(Attachment.FlashFire).should.be.false
describe "Flower Gift", ->
it "changes Cherrim's forme"
it "does not change a transformed pokemon's forme"
it "grants x1.5 attack and special defense in Sun"
it "grants x1.5 attack and special defense to allies in Sun"
describe "Forecast", ->
it "changes Castform's forme"
it "does not change a transformed pokemon's forme"
describe "Forewarn", ->
it "considers OHKO moves to have 160 BP", ->
shared.create.call(this)
Ability.Forewarn.consider(@battle.getMove("Fissure")).should.equal(160)
it "considers counter moves to have 120 BP", ->
shared.create.call(this)
{consider} = Ability.Forewarn
consider(@battle.getMove("Counter")).should.equal(120)
consider(@battle.getMove("Mirror Coat")).should.equal(120)
consider(@battle.getMove("Metal Burst")).should.equal(120)
it "considers specific variable power moves to have 80 BP", ->
shared.create.call(this)
{consider} = Ability.Forewarn
consider(@battle.getMove("Crush Grip")).should.equal(80)
consider(@battle.getMove("Dragon Rage")).should.equal(80)
consider(@battle.getMove("Endeavor")).should.equal(80)
consider(@battle.getMove("Flail")).should.equal(80)
consider(@battle.getMove("Frustration")).should.equal(80)
consider(@battle.getMove("Grass Knot")).should.equal(80)
consider(@battle.getMove("Gyro Ball")).should.equal(80)
consider(@battle.getMove("Hidden Power")).should.equal(80)
consider(@battle.getMove("Low Kick")).should.equal(80)
consider(@battle.getMove("Natural Gift")).should.equal(80)
consider(@battle.getMove("Night Shade")).should.equal(80)
consider(@battle.getMove("Psywave")).should.equal(80)
consider(@battle.getMove("Return")).should.equal(80)
consider(@battle.getMove("Reversal")).should.equal(80)
consider(@battle.getMove("Seismic Toss")).should.equal(80)
consider(@battle.getMove("SonicBoom")).should.equal(80)
consider(@battle.getMove("Trump Card")).should.equal(80)
consider(@battle.getMove("Wring Out")).should.equal(80)
it "alerts user about a foe's move with the highest base power", ->
shared.build(this, team1: [Factory("Magikarp", ability: "Forewarn")])
spy = @sandbox.spy(@battle, 'cannedText')
@controller.beginBattle()
tackle = @battle.getMove("Tackle")
spy.calledWith('FOREWARN', @p2, tackle).should.be.true
it "displays nothing when no opponents left", ->
shared.create.call this,
team1: [Factory("Magikarp")]
team2: [Factory("Magikarp"), Factory("Magikarp")]
@p2.faint()
spy = @sandbox.spy(@battle, 'cannedText')
@p1.copyAbility(Ability.Forewarn)
spy.called.should.be.false
describe "Friend Guard", ->
it "weakens attacks from allies by 25%", ->
shared.create.call this,
numActive: 2
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Friend Guard")]
earthquake = @battle.getMove("Earthquake")
earthquake.modifyDamage(@battle, @p1, @team1.at(1)).should.equal(0xC00)
it "keeps attacks by enemies at normal", ->
shared.create.call this,
numActive: 2
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Friend Guard")]
earthquake = @battle.getMove("Earthquake")
earthquake.modifyDamage(@battle, @p2, @team1.at(1)).should.equal(0x1000)
describe "Frisk", ->
it "randomly selects an opponent and displays the item", ->
shared.build this,
team1: [Factory("Magikarp", ability: "Frisk")]
team2: [Factory("Magikarp", item: "Leftovers")]
spy = @sandbox.spy(@battle, 'cannedText')
@controller.beginBattle()
spy.calledWithMatch('FRISK').should.be.true
it "displays nothing when no opponents left", ->
shared.create.call this,
team1: [Factory("Magikarp")]
team2: [Factory("Magikarp"), Factory("Magikarp")]
@p2.faint()
spy = @sandbox.spy(@battle, 'cannedText')
@p1.copyAbility(Ability.Frisk)
spy.called.should.be.false
describe "Gluttony", ->
it "makes berries activate at 50% HP", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Salac Berry", ability: "Gluttony")]
@p1.stages.should.containEql(speed: 0)
@p1.currentHP >>= 1
@p1.update()
@p1.stages.should.containEql(speed: 1)
describe "Guts", ->
it "multiplies attack by x1.5 if statused", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Guts")])
tackle = @battle.getMove("Tackle")
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
@p1.attach(Status.Burn)
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1800)
it "does not multiply attack if move is special", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Guts")])
thunderbolt = @battle.getMove("Thunderbolt")
@p1.attach(Status.Burn)
thunderbolt.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
describe "Harvest", ->
it "has a 50% chance of re-obtaining a berry it used", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Salac Berry", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 1)
@p1.useItem()
@battle.endTurn()
@p1.hasItem("Salac Berry").should.be.true
it "has a 50% chance of doing nothing", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Salac Berry", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 0)
@p1.useItem()
@battle.endTurn()
@p1.hasItem("Salac Berry").should.be.false
it "has a 100% chance to re-obtain the berry in Sun", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Salac Berry", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 0)
@p1.useItem()
@battle.setWeather(Weather.SUN)
@battle.endTurn()
@p1.hasItem("Salac Berry").should.be.true
it "does not regain a normal item", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 1)
@p1.useItem()
@battle.endTurn()
@p1.hasItem("Flying Gem").should.be.false
it "does not regain the berry if it was removed", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Salac Berry", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 1)
@p1.useItem()
@battle.endTurn()
@p1.hasItem("Salac Berry").should.be.true
@p1.removeItem()
@battle.endTurn()
@p1.hasItem("Salac Berry").should.be.false
it "uses a regained Berry immediately if the condition is right", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Sitrus Berry", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 1)
@p1.useItem()
@p1.currentHP = 1
@p1.hasItem("Sitrus Berry").should.be.false
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 2))
@p1.hasItem("Sitrus Berry").should.be.false
describe "Healer", ->
it "has a 30% chance of healing an adjacent ally's status", ->
shared.create.call this,
numActive: 3
team1: [Factory("Magikarp", ability: "Healer"), Factory("Magikarp"), Factory("Magikarp")]
shared.biasRNG.call(this, "randInt", "healer", 3)
@team1.at(0).attach(Status.Burn)
@team1.at(1).attach(Status.Burn)
@team1.at(2).attach(Status.Burn)
@battle.endTurn()
@team1.at(0).hasStatus().should.be.true
@team1.at(1).hasStatus().should.be.false
@team1.at(2).hasStatus().should.be.true
it "has a 70% chance to do nothing", ->
shared.create.call this,
numActive: 2
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Healer")]
shared.biasRNG.call(this, "randInt", "healer", 4)
@p1.attach(Status.Burn)
@battle.endTurn()
@p1.hasStatus().should.be.true
describe "Heatproof", ->
it "receives half damage from Fire-type moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Heatproof")])
ember = @battle.getMove("Ember")
ember.modifyBasePower(@battle, @p2, @p1).should.equal(0x800)
it "receives normal damage from non-Fire-type moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Heatproof")])
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p2, @p1).should.equal(0x1000)
it "receives half damage from burn", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Heatproof")])
@p1.attach(Status.Burn)
burn = @p1.get(Status.Burn)
mock = @sandbox.mock(burn).expects('endTurn').returns(@p1.currentHP >> 4)
@battle.endTurn()
mock.verify()
describe "Heavy Metal", ->
it "doubles the user's weight", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Heavy Metal")])
@p1.calculateWeight().should.equal(2 * @p1.weight)
testHugePowerAbility = (name) ->
describe name, ->
it "doubles attack when using a physical move", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
tackle = @battle.getMove("Tackle")
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x2000)
it "does not double attack when using a special move", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
testHugePowerAbility("Huge Power")
testHugePowerAbility("Pure Power")
describe "Hustle", ->
it "multiplies attack by x1.5", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Hustle")])
tackle = @battle.getMove("Tackle")
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1800)
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
it "makes physical moves have 20% less accuracy", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Hustle")])
tackle = @battle.getMove("Tackle")
accuracy = tackle.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal Math.floor(tackle.accuracy * 0.8)
thunderbolt = @battle.getMove("Thunderbolt")
accuracy = thunderbolt.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal Math.floor(thunderbolt.accuracy * 1.0)
describe "Hydration", ->
it "restores status, in Rain, at the end of the turn", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Hydration")])
@p1.attach(Status.Sleep)
@battle.setWeather(Weather.RAIN)
@battle.endTurn()
@p1.hasStatus().should.be.false
it "does not restore status if the weather is not rainy", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Hydration")])
@p1.attach(Status.Sleep)
@battle.endTurn()
@p1.hasStatus().should.be.true
describe "Ice Body", ->
it "restores 1/16 HP in Hail", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Ice Body")]
@p1.currentHP = 1
@battle.setWeather(Weather.HAIL)
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 4))
it "restores no HP in other weather", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Ice Body")]
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1)
it "grants immunity to Hail", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Ice Body")]
@p1.isWeatherDamageImmune(Weather.HAIL).should.be.true
describe "Illusion", ->
it "masquerades as the last unfainted pokemon in player's party"
it "does not masquerade if all pokemon are fainted"
it "is broken when the user takes direct damage"
describe "Imposter", ->
it "automatically transforms into the adjacent foe pokemon", ->
shared.create.call this,
numActive: 2
team1: (Factory("Magikarp") for x in [1..2])
team2: [Factory("Celebi"), Factory("Mew")]
@team1.at(1).copyAbility(Ability.Imposter)
@team1.at(1).has(Attachment.Transform).should.be.true
it "does not transform if target is behind a substitute", ->
shared.create.call(this)
@p2.attach(Attachment.Substitute, hp: 1)
@p1.copyAbility(Ability.Imposter)
@p1.has(Attachment.Transform).should.be.false
it "does not transform if target is already transformed", ->
shared.create.call(this)
@battle.performMove(@p2, @battle.getMove("Transform"))
@p2.has(Attachment.Transform).should.be.true
@p1.copyAbility(Ability.Imposter)
@p1.has(Attachment.Transform).should.be.false
it "does not transform if no one is alive", ->
shared.create.call this,
team1: [Factory("Magikarp")]
team2: [Factory("Magikarp"), Factory("Celebi")]
@p2.faint()
@p1.copyAbility(Ability.Imposter)
@p1.has(Attachment.Transform).should.be.false
testAttachmentImmuneAbility = (name, attachments, options = {}) ->
describe name, ->
it "prevents the pokemon from receiving a specific attachment", ->
shared.create.call this,
team1: [Factory("Magikarp", gender: "F", ability: name)]
team2: [Factory("Magikarp", gender: "M")]
for attachment in attachments
should.not.exist @p1.attach(attachment, source: @p2)
@p1.has(attachment).should.be.false
shouldCure = options.cure ? true
if shouldCure
it "removes the attachment if the pokemon already has it", ->
shared.create.call this,
team1: [Factory("Magikarp", gender: "F")]
team2: [Factory("Magikarp", gender: "M")]
for attachment in attachments
@p1.attach(attachment, source: @p2)
@p1.has(attachment).should.be.true
@p1.copyAbility(Ability[name.replace(/\s+/g, '')])
@p1.update()
@p1.has(attachment).should.be.false
@p1.copyAbility(null)
testAttachmentImmuneAbility("Immunity", [Status.Poison, Status.Toxic])
testAttachmentImmuneAbility("Inner Focus", [Attachment.Flinch], cure: false)
testAttachmentImmuneAbility("Insomnia", [Status.Sleep])
testAttachmentImmuneAbility("Limber", [Status.Paralyze])
testAttachmentImmuneAbility("Magma Armor", [Status.Freeze])
testAttachmentImmuneAbility("Oblivious", [Attachment.Attract])
testAttachmentImmuneAbility("Own Tempo", [Attachment.Confusion])
testAttachmentImmuneAbility("Vital Spirit", [Status.Sleep])
testAttachmentImmuneAbility("Water Veil", [Status.Burn])
describe "Intimidate", ->
it "lowers the attack of all foe pokemon", ->
shared.create.call this,
team1: [ Factory("Magikarp", ability: "Intimidate") ]
@p2.stages.should.containEql(attack: -1)
it "does not lower attack of Pokemon behind Substitute", ->
shared.create.call this,
team1: [ Factory("Magikarp") ]
@p2.attach(Attachment.Substitute, hp: (@p2.currentHP >> 2))
@p1.copyAbility(Ability.Intimidate)
@p2.stages.should.containEql(attack: 0)
it "lowers attack simultaneously on all begin-turn switch-ins", ->
shared.create.call this,
team1: (Factory("Magikarp", ability: "Intimidate") for x in [1..2])
team2: (Factory("Magikarp", ability: "Intimidate") for x in [1..2])
@p1.stages.should.containEql(attack: -1)
@p2.stages.should.containEql(attack: -1)
@p1.faint()
@p2.faint()
@battle.requestFaintedReplacements()
@controller.makeSwitch(@id1, 1)
@controller.makeSwitch(@id2, 1)
@team1.first().should.not.equal(@p1)
@team2.first().should.not.equal(@p2)
@team1.first().stages.should.containEql(attack: -1)
@team2.first().stages.should.containEql(attack: -1)
describe "Infiltrator", ->
it "ignores Reflect", ->
shared.create.call this,
team1: [ Factory("Magikarp", ability: "Infiltrator") ]
@team2.attach(Attachment.Reflect)
tackle = @battle.getMove('Tackle')
tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000)
it "ignores Light Screen", ->
shared.create.call this,
team1: [ Factory("Magikarp", ability: "Infiltrator") ]
@team2.attach(Attachment.LightScreen)
thundershock = @battle.getMove('ThunderShock')
thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x1000)
it "ignores Safeguard"
it "ignores Mist"
testContactHurtAbility = (name) ->
describe name, ->
it "damages for 1/8 HP on contact moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name), Factory("Magikarp")])
hp = @p2.stat('hp')
@battle.performMove(@p2, @battle.getMove("Tackle"))
(hp - @p2.currentHP).should.equal(hp >> 3)
it "does not damage for non-contact moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name), Factory("Magikarp")])
@battle.performMove(@p2, @battle.getMove("Thunderbolt"))
@p2.currentHP.should.equal @p2.stat('hp')
it "does not damage for non-direct hits", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name), Factory("Magikarp")])
@p1.attach(Attachment.Substitute)
@battle.performMove(@p2, @battle.getMove("Tackle"))
@p2.currentHP.should.equal @p2.stat('hp')
it "still works even if the owner faints", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name), Factory("Magikarp")])
hp = @p2.stat('hp')
@p1.currentHP = 1
@battle.performMove(@p2, @battle.getMove("Tackle"))
(hp - @p2.currentHP).should.equal(hp >> 3)
it "deals a minimum of 1 damage", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
team2: [Factory("Shedinja")]
@battle.performMove(@p2, @battle.getMove("Tackle"))
@p2.currentHP.should.equal(0)
testContactHurtAbility("Iron Barbs")
testContactHurtAbility("Rough Skin")
describe "Iron Fist", ->
it "increases base power of punching moves by approximately x1.3", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Iron Fist")])
icePunch = @battle.getMove("Ice Punch")
icePunch.modifyBasePower(@battle, @p1, @p2).should.equal(0x1333)
it "does not increase base power of non-punching moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Iron Fist")])
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
describe "Justified", ->
it "boosts attack by 1 after being hit by a Dark move", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Justified")])
@p1.stages.should.containEql(attack: 0)
@battle.performMove(@p2, @battle.getMove("Tackle"))
@p1.stages.should.containEql(attack: 0)
@battle.performMove(@p2, @battle.getMove("Crunch"))
@p1.stages.should.containEql(attack: 1)
it "doesn't boost attack if the move is non-damaging", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Justified")])
@p1.stages.should.containEql(attack: 0)
@battle.performMove(@p1, @battle.getMove("Nasty Plot"))
@p1.stages.should.containEql(attack: 0)
it "doesn't boost attack if the move hits a substitute", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Justified")])
@p1.attach(Attachment.Substitute, hp: 1)
@p1.stages.should.containEql(attack: 0)
@battle.performMove(@p2, @battle.getMove("Crunch"))
@p1.stages.should.containEql(attack: 0)
describe "Klutz", ->
it "disables user's item upon switch-in", ->
shared.create.call this,
team1: [Factory("Magikarp"), Factory("Magikarp", item: "Leftovers", ability: "Klutz")]
@battle.performSwitch(@p1, 1)
@team1.first().isItemBlocked().should.be.true
it "disables user's item in the beginning of the turn", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Leftovers", ability: "Klutz")]
@p1.isItemBlocked().should.be.true
@battle.beginTurn()
@p1.isItemBlocked().should.be.true
describe "Leaf Guard", ->
it "defends against statuses under Sun", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Leaf Guard")]
@battle.setWeather(Weather.SUN)
@p1.attach(Status.Burn)
@p1.has(Status.Burn).should.be.false
it "does not defend against statuses otherwise", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Leaf Guard")]
@p1.attach(Status.Burn)
@p1.has(Status.Burn).should.be.true
describe "Levitate", ->
it "adds a ground immunity", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Levitate")]
@p1.isImmune('Ground').should.be.true
describe "Light Metal", ->
it "halves the user's weight", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Light Metal")])
@p1.calculateWeight().should.equal(@p1.weight >> 1)
testRedirectAndBoostAbility = (name, type) ->
describe name, ->
it "should redirect attacks of #{type} to user"
it "makes user immune to #{type}", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
mock = @sandbox.mock(typedMove).expects('hit').never()
@battle.performMove(@p2, typedMove)
mock.verify()
it "boosts special attack on #{type}-type moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
@battle.performMove(@p2, typedMove)
@p1.stages.should.containEql(specialAttack: 1)
it "does not boost special attack if the user is the target", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
m.target == 'user' && m.type == type
@battle.performMove(@p1, typedMove)
@p1.stages.should.containEql(specialAttack: 0)
it "does not boost special attack on #{type}-type moves if immune", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
@sandbox.stub(@p1, 'isImmune', -> true)
@battle.performMove(@p2, typedMove)
@p1.stages.should.containEql(specialAttack: 0)
it "does nothing otherwise", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').once()
@battle.performMove(@p2, tackle)
mock.verify()
@p1.stages.should.containEql(specialAttack: 0)
testRedirectAndBoostAbility("Lightningrod", "Electric")
testRedirectAndBoostAbility("Storm Drain", "Water")
describe "Liquid Ooze", ->
it "causes drain attacks to damage the user as well", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Liquid Ooze")]
@battle.performMove(@p2, @battle.getMove("Giga Drain"))
@p2.currentHP.should.be.lessThan @p2.stat('hp')
it "causes Leech Seed to damage the user as well", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Liquid Ooze")]
@battle.performMove(@p2, @battle.getMove("Leech Seed"))
@battle.endTurn()
@p2.currentHP.should.be.lessThan @p2.stat('hp')
describe "Magic Bounce", ->
it "still has the magic coat effect next turn", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Bounce")]
@p1.has(Attachment.MagicCoat).should.be.true
@team1.has(Attachment.MagicCoat).should.be.true
@battle.endTurn()
@p1.has(Attachment.MagicCoat).should.be.true
@team1.has(Attachment.MagicCoat).should.be.true
describe "Magic Guard", ->
it "takes no damage from anything that isn't a move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@p1.attach(Status.Burn)
@p1.currentHP.should.equal(@p1.stat('hp'))
@battle.endTurn()
@p1.currentHP.should.equal(@p1.stat('hp'))
it "takes damage from moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from Struggle", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@battle.performMove(@p1, @battle.getMove('Struggle'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from Belly Drum", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@battle.performMove(@p1, @battle.getMove('Belly Drum'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from confusion", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
shared.biasRNG.call(this, 'next', 'confusion', 0)
@p1.attach(Attachment.Confusion)
@battle.performMove(@p1, @battle.getMove('Tackle'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from using Curse", ->
shared.create.call this,
team1: [Factory("Gengar", ability: "Magic Guard")]
@battle.performMove(@p1, @battle.getMove('Curse'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from Substitute", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@battle.performMove(@p1, @battle.getMove('Substitute'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from Pain Split", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@p1.currentHP = 1
@battle.performMove(@p1, @battle.getMove('Pain Split'))
@p1.currentHP.should.be.greaterThan(1)
it "takes damage from Counter", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard", moves: ["Counter"])]
@controller.makeMove(@id1, "Counter")
@controller.makeMove(@id2, "Tackle")
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "restores health from Leftovers", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard", item: "Leftovers")]
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.be.greaterThan(1)
it "receives no damage from Rocky Helmet", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1)
describe "Magnet Pull", ->
it "prevents Steel-type Pokemon from switching", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magnet Pull")]
team2: [Factory("Magnemite")]
@p2.isSwitchBlocked().should.be.true
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.true
it "doesn't prevent non-Steel-type Pokemon from switching", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magnet Pull")]
team2: [Factory("Magikarp")]
@p2.isSwitchBlocked().should.be.false
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.false
describe "Marvel Scale", ->
it "multiplies defense by 1.5 when statused", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Marvel Scale")]
defense = @p1.stat('defense')
@p1.attach(Status.Burn)
@p1.stat('defense').should.equal Math.floor(1.5 * defense)
describe "Minus", ->
it "multiplies special attack by 1.5 if on the field with Plus", ->
shared.create.call this,
numActive: 2
team1: [Factory("Magikarp"), Factory("Magikarp")]
team2: [Factory("Magikarp"), Factory("Magikarp")]
specialAttack = @p1.stat('specialAttack')
@team1.at(0).copyAbility(Ability.Minus)
@team1.at(1).copyAbility(Ability.Plus)
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.modifyAttack(@battle, @team1.at(0), @p2).should.equal(0x1800)
testAbilityCancelAbility = (name) ->
describe name, ->
it "emits a catchphrase when switching in or activating", ->
shared.create.call(this)
mock = @sandbox.mock(@battle).expects('cannedText').once()
@p1.copyAbility(Ability[name.replace(/\s+/, '')])
mock.verify()
it "cancels abilities for the duration of the user's move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
team2: [Factory("Magikarp", ability: "Levitate")]
eq = @battle.getMove("Earthquake")
mock = @sandbox.mock(eq).expects('hit').once()
@battle.performMove(@p1, eq)
mock.verify()
it "cancels modifier abilities for the duration of the user's move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
team2: [Factory("Magikarp", ability: "Thick Fat")]
ib = @battle.getMove("Ice Beam")
spy = @sandbox.spy(ib, 'modifyAttack')
spy = spy.withArgs(@battle, @p1, @p2)
@battle.performMove(@p1, ib)
spy.returnValues[0].should.equal(0x1000)
it "resets canceled abilities after the move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
team2: [Factory("Magikarp", ability: "Levitate")]
eq = @battle.getMove("Earthquake")
@p2.isAbilityBlocked().should.be.false
@battle.performMove(@p1, eq)
@p2.isAbilityBlocked().should.be.false
it "does not reset already-canceled abilities after performing move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
team2: [Factory("Magikarp", ability: "Levitate")]
@p2.blockAbility()
eq = @battle.getMove("Earthquake")
@p2.isAbilityBlocked().should.be.true
@battle.performMove(@p1, eq)
@p2.isAbilityBlocked().should.be.true
it "works when using field moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
sr = @battle.getMove("Stealth Rock")
(=> @battle.performMove(@p1, sr)).should.not.throw()
it "ignores Unaware", ->
shared.create.call this,
team1: [Factory("Haxorus", ability: name)]
team2: [Factory("Quagsire", ability: "Unaware")]
@p1.boost(attack: 2)
spy = @sandbox.spy(@p1, "editBoosts").withArgs(sinon.match(ignoreOffense: false))
@battle.performMove(@p1, @battle.getMove("Outrage"))
spy.returned(sinon.match(attack: 2)).should.be.true
testAbilityCancelAbility("Mold Breaker")
testAbilityCancelAbility("Teravolt")
testAbilityCancelAbility("Turboblaze")
describe "Moody", ->
it "at turn end, randomly raise a stat by 2 and lower another by 1", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Moody")])
shared.biasRNG.call(this, "randInt", "moody raise", 1)
shared.biasRNG.call(this, "randInt", "moody lower", 0)
@battle.endTurn()
@p1.stages.should.containEql(attack: -1, defense: 2)
it "never raises and lowers the same stat in a single turn", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Moody")])
shared.biasRNG.call(this, "randInt", "moody raise", 0)
shared.biasRNG.call(this, "randInt", "moody lower", 0)
@battle.endTurn()
@p1.stages.should.containEql(attack: 2, defense: -1)
it "does not choose individual stats at max/min", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Moody")])
shared.biasRNG.call(this, "randInt", "moody raise", 1)
shared.biasRNG.call(this, "randInt", "moody lower", 0)
@p1.boost(defense: 6)
@p1.boost(attack: -6)
@battle.endTurn()
@p1.stages.should.containEql(defense: 5, speed: 2)
it "does not try to raise a null stat", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Moody")])
shared.biasRNG.call(this, "randInt", "moody raise", 1)
shared.biasRNG.call(this, "randInt", "moody lower", 0)
@p1.boost(attack: 6, defense: 6, speed: 6, specialAttack: 6)
@p1.boost(specialDefense: 6, accuracy: 6, evasion: 6)
(=> @battle.endTurn()).should.not.throw()
testTypeImmuneAbility = (name, type, stat) ->
describe name, ->
it "makes the user immune to #{type} moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
mock = @sandbox.mock(typedMove).expects('hit').never()
@battle.performMove(@p2, typedMove)
mock.verify()
it "increases #{stat} by 1 if hit by a #{type}-type move", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
@battle.performMove(@p2, typedMove)
@p1.stages[stat].should.equal(1)
it "increases #{stat} by only 1 even if move is multi-hit", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
@sandbox.stub(typedMove, 'calculateNumberOfHits', -> 2)
@battle.performMove(@p2, typedMove)
@p1.stages[stat].should.equal(1)
it "does not increase #{stat} by 1 if the user is the target", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
typedMove = _(@battle.MoveList).find (m) ->
m.target == 'user' && m.type == type
@battle.performMove(@p1, typedMove)
@p1.stages[stat].should.equal(0)
it "does nothing otherwise", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type != type
mock = @sandbox.mock(typedMove).expects('hit').once()
@battle.performMove(@p2, typedMove)
@p1.stages[stat].should.equal(0)
mock.verify()
testTypeImmuneAbility("Motor Drive", "Electric", "speed")
testTypeImmuneAbility("Sap Sipper", "Grass", "attack")
describe "Moxie", ->
it "increases attack every time it faints another target", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Moxie")]
tackle = @battle.getMove("Tackle")
@p2.currentHP = 1
@p1.stages.should.containEql(attack: 0)
@battle.performMove(@p1, tackle)
@p1.stages.should.containEql(attack: 1)
describe "Multiscale", ->
it "takes half damage at full HP", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Multiscale")]
iceBeam = @battle.getMove("Ice Beam")
iceBeam.modifyDamage(@battle, @p2, @p1).should.equal(0x800)
it "takes normal damage at other HP", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Multiscale")]
iceBeam = @battle.getMove("Ice Beam")
@p1.currentHP -= 1
iceBeam.modifyDamage(@battle, @p2, @p1).should.equal(0x1000)
describe "Multitype", ->
it "changes Arceus forme for different plates"
describe "Mummy", ->
it "changes the attacker's ability to Mummy on contact", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Mummy")]
tackle = @battle.getMove("Tackle")
@p2.hasAbility("Mummy").should.be.false
@battle.performMove(@p2, tackle)
@p2.hasAbility("Mummy").should.be.true
it "doesn't change ability if move used isn't a contact move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Mummy")]
iceBeam = @battle.getMove("Ice Beam")
@p2.hasAbility("Mummy").should.be.false
@battle.performMove(@p2, iceBeam)
@p2.hasAbility("Mummy").should.be.false
it "doesn't change ability if attacker has Multitype", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Mummy")]
team2: [Factory("Magikarp", ability: "Multitype")]
tackle = @battle.getMove("Tackle")
@p2.hasAbility("Mummy").should.be.false
@battle.performMove(@p2, tackle)
@p2.hasAbility("Mummy").should.be.false
it "works even if the defender faints", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Mummy"), Factory("Magikarp")]
@p1.currentHP = 1
tackle = @battle.getMove("Tackle")
@p2.hasAbility("Mummy").should.be.false
@battle.performMove(@p2, tackle)
@p2.hasAbility("Mummy").should.be.true
describe "Natural Cure", ->
it "cures status upon switch out", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Natural Cure")]
@p1.attach(Status.Burn)
@p1.switchOut(@battle)
@p1.hasStatus().should.be.false
describe "No Guard", ->
it "makes every move by this Pokemon never miss", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "No Guard")]
shared.biasRNG.call(this, 'randInt', 'miss', 101)
focusBlast = @battle.getMove("Focus Blast")
focusBlast.willMiss(@battle, @p1, @p2).should.be.false
it "makes every move against this Pokemon never miss", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "No Guard")]
shared.biasRNG.call(this, 'randInt', 'miss', 101)
focusBlast = @battle.getMove("Focus Blast")
focusBlast.willMiss(@battle, @p2, @p1).should.be.false
describe "Normalize", ->
it "makes every move act as if it were Normal type", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Normalize")]
team2: [Factory("Magikarp")]
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.typeEffectiveness(@battle, @p1, @p2).should.equal(1)
it "has no effect if target is self", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Normalize")]
team2: [Factory("Magikarp")]
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.typeEffectiveness(@battle, @p1, @p1).should.equal(2)
it "has no effect on struggle", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Normalize")]
team2: [Factory("Skarmory")]
struggle = @battle.getMove("Struggle")
struggle.typeEffectiveness(@battle, @p1, @p2).should.equal(1)
describe "Overcoat", ->
it "gives an immunity to adverse weather effects", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Overcoat")]
@p1.isWeatherDamageImmune(Weather.HAIL).should.be.true
@p1.isWeatherDamageImmune(Weather.SAND).should.be.true
describe "Pickpocket", ->
it "steals the item of an opponent that makes contact", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Pickpocket")]
team2: [Factory("Magikarp", item: "Leftovers")]
tackle = @battle.getMove("Tackle")
@battle.performMove(@p2, tackle)
@p1.hasItem("Leftovers").should.be.true
@p2.hasItem("Leftovers").should.be.false
describe "Plus", ->
it "multiplies special attack by 1.5 if on the field with Minus", ->
shared.create.call this,
numActive: 2
team1: [Factory("Magikarp"), Factory("Magikarp")]
team2: [Factory("Magikarp"), Factory("Magikarp")]
specialAttack = @p1.stat('specialAttack')
@team1.at(0).copyAbility(Ability.Minus)
@team1.at(1).copyAbility(Ability.Plus)
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.modifyAttack(@battle, @team1.at(1), @p2).should.equal(0x1800)
describe "Poison Heal", ->
it "prevents normal poison damage", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Poison Heal")]
@p1.attach(Status.Poison)
@battle.endTurn()
@p1.currentHP.should.not.be.lessThan @p1.stat('hp')
@p1.cureStatus()
@p1.attach(Status.Toxic)
@battle.endTurn()
@p1.currentHP.should.not.be.lessThan @p1.stat('hp')
it "heals 1/8 HP end of turn while poisoned", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Poison Heal")]
@p1.attach(Status.Poison)
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 3))
it "heals 1/8 HP end of turn while toxiced", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Poison Heal")]
@p1.attach(Status.Toxic)
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 3))
describe "Prankster", ->
it "makes non-damaging moves have a priority (priority + 1)", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Prankster")]
spore = @battle.getMove("Spore")
tackle = @battle.getMove("Tackle")
action = {type: "move", move: spore, pokemon: @p1}
@battle.actionPriority(action).should.equal(spore.priority + 1)
action.move = tackle
@battle.actionPriority(action).should.equal(tackle.priority)
describe "Pressure", ->
it "reduces a move's PP further by 1 if targetted by foe's move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Pressure")]
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
pp = @p2.pp(tackle)
@battle.performMove(@p2, tackle)
@p2.pp(tackle).should.equal(pp - 2)
it "does not reduce a move's PP by 1 if target is self", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Pressure")]
dd = @battle.getMove("Dragon Dance")
@p1.moves = [ dd ]
@p1.resetAllPP()
pp = @p1.pp(dd)
@battle.performMove(@p1, dd)
@p1.pp(dd).should.equal(pp - 1)
describe "Quick Feet", ->
it "increases speed by x1.5 when statused", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Quick Feet")]
speed = @p1.stat('speed')
@p1.attach(Status.Sleep)
@p1.stat('speed').should.equal Math.floor(1.5 * speed)
it "negates speed drop from paralysis", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Quick Feet")]
speed = @p1.stat('speed')
@p1.attach(Status.Paralyze)
@p1.stat('speed').should.equal Math.floor(1.5 * speed)
describe "Rain Dish", ->
it "restores 1/16 HP at end of turn under Rain", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Rain Dish")]
@p1.currentHP = 1
@battle.setWeather(Weather.RAIN)
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 4))
it "does not restore HP at end of turn under non-Rain weather", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Rain Dish")]
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1)
describe "Rattled", ->
for type in ["Ghost", "Bug", "Dark"]
do (type) ->
it "raises speed by 1 when hit by a #{type} move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Rattled")]
typedMove = _(@battle.MoveList).find (m) ->
m.type == type
@p1.stages.speed.should.equal(0)
@battle.performMove(@p2, typedMove)
@p1.stages.speed.should.equal(1)
it "does not raise speed by 1 when hit by a non-damaging #{type} move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Rattled")]
typedMove = _(@battle.MoveList).find (m) ->
m.isNonDamaging() && m.type == type
@p1.stages.speed.should.equal(0)
@battle.performMove(@p2, typedMove)
@p1.stages.speed.should.equal(0)
it "does not raise speed by 1 when a #{type} move hits a substitute", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Rattled")]
typedMove = _(@battle.MoveList).find (m) ->
m.isNonDamaging() && m.type == type
@p1.attach(Attachment.Substitute, hp: 1)
@p1.stages.speed.should.equal(0)
@battle.performMove(@p2, typedMove)
@p1.stages.speed.should.equal(0)
describe "Reckless", ->
it "gives a 1.2x boost to recoil moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Reckless")]
recoilMoves = @battle.MoveList.filter (m) ->
m.recoil < 0
for move in recoilMoves
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1333)
it "boosts the kick moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Reckless")]
recoilMoves = [ @battle.getMove("Jump Kick"),
@battle.getMove("Hi Jump Kick") ]
for move in recoilMoves
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1333)
it "does not boost struggle", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Reckless")]
struggle = @battle.getMove("Struggle")
struggle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "does not boost drain moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Reckless")]
absorb = @battle.getMove("Absorb")
absorb.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
describe "Regenerator", ->
it "restores 1/3 of the user's HP upon switch out", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Regenerator")]
@p1.currentHP = 1
@p1.switchOut(@battle)
hp = Math.floor(@p1.stat('hp') / 3)
@p1.currentHP.should.equal(1 + hp)
describe "Rivalry", ->
it "reduces base power by 25% if user and target are opposite genders", ->
shared.create.call this,
team1: [Factory("Magikarp", gender: 'F', ability: "Rivalry")]
team2: [Factory("Magikarp", gender: 'M')]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0xC00)
it "increases base power by 25% if user and target are the same gender", ->
shared.create.call this,
team1: [Factory("Magikarp", gender: 'F', ability: "Rivalry")]
team2: [Factory("Magikarp", gender: 'F')]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1400)
it "has normal base power if either user or target have no gender", ->
shared.create.call this,
team1: [Factory("Magikarp", gender: 'F', ability: "Rivalry")]
team2: [Factory("Magikarp")]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
describe "Rock Head", ->
it "negates recoil", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Rock Head")]
@battle.performMove(@p1, @battle.getMove("Head Smash"))
@p1.currentHP.should.equal @p1.stat('hp')
describe "Sand Force", ->
it "increases BP of Ground-, Rock-, and Steel-type moves by 30% in sand", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sand Force")]
@battle.setWeather(Weather.SAND)
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
earthquake = @battle.getMove("Earthquake")
earthquake.modifyBasePower(@battle, @p1, @p2).should.equal(0x14CD)
rockSlide = @battle.getMove("Rock Slide")
rockSlide.modifyBasePower(@battle, @p1, @p2).should.equal(0x14CD)
meteorMash = @battle.getMove("Meteor Mash")
meteorMash.modifyBasePower(@battle, @p1, @p2).should.equal(0x14CD)
it "does not increase BP if weather is not sand", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sand Force")]
@battle.setWeather(Weather.NONE)
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
earthquake = @battle.getMove("Earthquake")
earthquake.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
rockSlide = @battle.getMove("Rock Slide")
rockSlide.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
meteorMash = @battle.getMove("Meteor Mash")
meteorMash.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "grants immunity to sandstorm", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sand Force")]
@p1.isWeatherDamageImmune(Weather.SAND).should.be.true
describe "Sand Veil", ->
it "increases evasion by 25% in Sand", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sand Veil")]
@battle.setWeather(Weather.SAND)
tackle = @battle.getMove("Tackle")
tackle.chanceToHit(@battle, @p2, @p1).should.equal(80)
it "does nothing outside of Sand", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sand Veil")]
tackle = @battle.getMove("Tackle")
tackle.chanceToHit(@battle, @p2, @p1).should.equal(100)
it "makes the user immune to Sand", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sand Veil")]
@p1.isWeatherDamageImmune(Weather.SAND).should.be.true
describe "Scrappy", ->
it "negates pokemon immunities", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Scrappy")]
team2: [Factory("Gengar")]
tackle = @battle.getMove("Tackle")
closeCombat = @battle.getMove("Close Combat")
tackle.typeEffectiveness(@battle, @p1, @p2).should.equal(1)
closeCombat.typeEffectiveness(@battle, @p1, @p2).should.equal(.5)
mock1 = @sandbox.mock(tackle).expects('hit').once()
mock2 = @sandbox.mock(closeCombat).expects('hit').once()
@battle.performMove(@p1, tackle)
@battle.performMove(@p1, closeCombat)
mock1.verify()
mock2.verify()
describe "Serene Grace", ->
it "doubles the chance of secondary effects happening", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", "secondary effect", 10)
ember = @battle.getMove("Ember")
@sandbox.stub(ember, "baseDamage", -> 1)
@battle.performMove(@p1, ember)
@p2.has(Status.Burn).should.be.false
@p1.copyAbility(Ability.SereneGrace)
@battle.performMove(@p1, ember)
@p2.has(Status.Burn).should.be.true
it "doubles the chance of secondary boosts happening", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", "secondary boost", 10)
acid = @battle.getMove("Acid")
@sandbox.stub(acid, "baseDamage", -> 1)
@battle.performMove(@p1, acid)
@p2.stages.should.containEql(specialDefense: 0)
@p1.copyAbility(Ability.SereneGrace)
@battle.performMove(@p1, acid)
@p2.stages.should.containEql(specialDefense: -1)
it "doubles the chance of flinches happening", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", "flinch", 30)
ironHead = @battle.getMove("Iron Head")
@sandbox.stub(ironHead, "baseDamage", -> 1)
@battle.performMove(@p1, ironHead)
@p2.has(Attachment.Flinch).should.be.false
@p1.copyAbility(Ability.SereneGrace)
@battle.performMove(@p1, ironHead)
@p2.has(Attachment.Flinch).should.be.true
describe "Shadow Tag", ->
it "prevents foes from switching", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Shadow Tag")]
@p2.isSwitchBlocked().should.be.true
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.true
it "does not affect foes with Shadow Tag", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Shadow Tag")]
team2: [Factory("Magikarp", ability: "Shadow Tag")]
@p2.isSwitchBlocked().should.be.false
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.false
describe "Shed Skin", ->
it "has a 30% chance of removing its status effect at end of turn", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Shed Skin")]
shared.biasRNG.call(this, "randInt", "shed skin", 3)
@p1.attach(Status.Burn)
@battle.endTurn()
@p1.has(Status.Burn).should.be.false
it "has a 70% chance of doing nothing at end of turn", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Shed Skin")]
shared.biasRNG.call(this, "randInt", "shed skin", 4)
@p1.attach(Status.Burn)
@battle.endTurn()
@p1.has(Status.Burn).should.be.true
describe "Sheer Force", ->
it "raises power of moves with secondary effects by 30%", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force")]
ember = @battle.getMove("Ember")
ember.modifyBasePower(@battle, @p1, @p2).should.equal(0x14CD)
it "does not raise power of moves without secondary effects", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force")]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "nullifies secondary effects", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
shared.biasRNG.call(this, 'next', 'secondary effect', 0) # always happens
@battle.performMove(@p1, @battle.getMove("Zap Cannon"))
@p2.has(Status.Paralyze).should.be.false
it "nullifies flinch", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
shared.biasRNG.call(this, 'next', 'flinch', 0) # always happens
@battle.performMove(@p1, @battle.getMove("Iron Head"))
@p2.has(Attachment.Flinch).should.be.false
it "nullifies secondary boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
@battle.performMove(@p1, @battle.getMove("Charge Beam"))
@p1.stages.should.containEql(specialAttack: 0)
it "does not apply to primary boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
cc = @battle.getMove("Close Combat")
cc.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
@battle.performMove(@p1, cc)
@p1.stages.should.containEql(defense: -1, specialDefense: -1)
it "receives no life orb recoil", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
@battle.performMove(@p1, @battle.getMove("Ember"))
@p1.currentHP.should.not.be.lessThan @p1.stat('hp')
it "receives life orb recoil if no secondary effect", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
@battle.performMove(@p1, @battle.getMove("Tackle"))
@p1.currentHP.should.be.lessThan @p1.stat('hp')
it "does not activate Red Card", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force"), Factory("Magikarp")]
team2: [Factory("Magikarp", item: "Red Card"), Factory("Magikarp")]
@battle.performMove(@p1, @battle.getMove("Ember"))
@p1.should.equal @team1.first()
it "activates Red Card if no secondary effect", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force"), Factory("Magikarp")]
team2: [Factory("Magikarp", item: "Red Card"), Factory("Magikarp")]
@battle.performMove(@p1, @battle.getMove("Tackle"))
@p1.should.not.equal @team1.first()
it "does not activate Eject Button", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force"), Factory("Magikarp")]
team2: [Factory("Magikarp", item: "Eject Button"), Factory("Magikarp")]
@battle.recordMove(@id2, @battle.getMove("Tackle"))
should.not.exist @battle.requests[@id2]
@battle.performMove(@p1, @battle.getMove("Ember"))
should.not.exist @battle.requests[@id2]
it "activates Eject Button if no secondary effect", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force"), Factory("Magikarp")]
team2: [Factory("Magikarp", item: "Eject Button"), Factory("Magikarp")]
@battle.recordMove(@id2, @battle.getMove("Tackle"))
should.not.exist @battle.requests[@id2]
@battle.performMove(@p1, @battle.getMove("Tackle"))
@battle.requests[@id2].should.not.be.empty
it "does not activate Jaboca Berry?"
it "does not activate Rowap Berry?"
describe "Shield Dust", ->
it "prevents secondary effects", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Shield Dust")]
shared.biasRNG.call(this, 'next', 'secondary effect', 0) # always happens
@battle.performMove(@p1, @battle.getMove("Zap Cannon"))
@p2.has(Status.Paralyze).should.be.false
it "prevents secondary flinches", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Shield Dust")]
shared.biasRNG.call(this, 'randInt', 'flinch', 0) # 100% chance
@battle.performMove(@p1, @battle.getMove("Iron Head"))
@p2.has(Attachment.Flinch).should.be.false
it "prevents secondary boosts against the target", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Shield Dust")]
@battle.performMove(@p1, @battle.getMove("Acid Spray"))
@p2.stages.should.containEql(specialDefense: 0)
it "does not prevent secondary boosts for the user", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Shield Dust")]
@battle.performMove(@p1, @battle.getMove("Flame Charge"))
@p1.stages.should.containEql(speed: 1)
describe "Simple", ->
it "doubles stat boosts, negative and positive", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Simple")])
@battle.performMove(@p1, @battle.getMove("Curse"))
@p1.stages.should.containEql(attack: 2, defense: 2, speed: -2)
describe "Slow Start", ->
it "halves attack and speed", ->
shared.create.call(this)
speed = @p1.stat('speed')
@p1.copyAbility(Ability.SlowStart)
tackle = @battle.getMove("Tackle")
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x800)
flamethrower = @battle.getMove("Flamethrower")
flamethrower.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
@p1.stat('speed').should.equal(speed >> 1)
it "returns attack and speed to normal after five turns", ->
shared.create.call(this)
tackle = @battle.getMove("Tackle")
flamethrower = @battle.getMove("Flamethrower")
speed = @p1.stat('speed')
@p1.copyAbility(Ability.SlowStart)
for x in [0...5]
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x800)
flamethrower.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
@p1.stat('speed').should.equal(speed >> 1)
@battle.endTurn()
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
flamethrower.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
@p1.stat('speed').should.equal(speed)
describe "Sniper", ->
it "multiplies damage by a further x1.5 if critting", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sniper")]
tackle = @battle.getMove("Tackle")
@p1.crit = true
tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1800)
it "has a normal 1x multiplier if not critting", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sniper")]
tackle = @battle.getMove("Tackle")
@p1.crit = false
tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000)
describe "Snow Cloak", ->
it "increases evasion by 25% in hail", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Snow Cloak")]
@battle.setWeather(Weather.HAIL)
tackle = @battle.getMove("Tackle")
tackle.chanceToHit(@battle, @p2, @p1).should.equal(80)
it "does nothing outside of hail", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Snow Cloak")]
tackle = @battle.getMove("Tackle")
tackle.chanceToHit(@battle, @p2, @p1).should.equal(100)
it "makes the user immune to hail", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Snow Cloak")]
@p1.isWeatherDamageImmune(Weather.HAIL).should.be.true
describe "Solar Power", ->
it "increases special attack by 50% in Sun", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Solar Power")]
@battle.setWeather(Weather.SUN)
tackle = @battle.getMove("Tackle")
fireBlast = @battle.getMove("Fire Blast")
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
fireBlast.modifyAttack(@battle, @p1, @p2).should.equal(0x1800)
it "owner loses 1/8 max HP per end of turn", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Solar Power")]
@battle.setWeather(Weather.SUN)
@battle.endTurn()
@p1.currentHP.should.equal(@p1.stat('hp') - (@p1.stat('hp') >> 3))
it "does nothing if the weather is not Sun", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Solar Power")]
fireBlast = @battle.getMove("Fire Blast")
fireBlast.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
@battle.endTurn()
@p1.currentHP.should.equal(@p1.stat('hp'))
it "deals a minimum of 1 damage", ->
shared.create.call this,
team1: [Factory("Shedinja", ability: "Solar Power")]
@battle.setWeather(Weather.SUN)
@battle.endTurn()
@p1.currentHP.should.equal(0)
describe "Soundproof", ->
it "makes user immune to sound moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Soundproof")]
bugBuzz = @battle.getMove('Bug Buzz')
perishSong = @battle.getMove('Perish Song')
@p1.isImmune(bugBuzz.type, move: bugBuzz).should.be.true
@p1.isImmune(perishSong.type, move: perishSong).should.be.true
describe "Speed Boost", ->
it "boosts speed at the end of every turn", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Speed Boost")]
@p1.stages.should.containEql(speed: 0)
@battle.endTurn()
@p1.stages.should.containEql(speed: 1)
@battle.endTurn()
@p1.stages.should.containEql(speed: 2)
it "boosts speed the turn after a pokemon is freshly switched in", ->
shared.create.call this,
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Speed Boost")]
@battle.performSwitch(@p1, 1)
@team1.first().stages.should.containEql(speed: 0)
@battle.endTurn()
@team1.first().stages.should.containEql(speed: 0)
@battle.endTurn()
@team1.first().stages.should.containEql(speed: 1)
@battle.endTurn()
@team1.first().stages.should.containEql(speed: 2)
it "boosts speed the turn after a pokemon is replaced", ->
shared.create.call this,
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Speed Boost")]
@p1.currentHP = 1
@controller.makeMove(@id1, "Tackle")
@controller.makeMove(@id2, "Tackle")
@controller.makeSwitch(@id1, 1)
@battle.turn.should.equal(2)
@team1.first().stages.should.containEql(speed: 0)
@battle.endTurn()
@team1.first().stages.should.containEql(speed: 1)
@battle.endTurn()
@team1.first().stages.should.containEql(speed: 2)
describe "Sticky Hold", ->
it "prevents items from being taken", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Leftovers", ability: "Sticky Hold")]
@battle.performMove(@p2, @battle.getMove("Trick"))
@p1.hasItem("Leftovers").should.be.true
@p2.hasItem().should.be.false
it "does not prevent the user from using Trick", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Leftovers", ability: "Sticky Hold")]
@battle.performMove(@p1, @battle.getMove("Trick"))
@p1.hasItem().should.be.false
@p2.hasItem("Leftovers").should.be.true
describe "Stall", ->
it "forces the user to move last no matter what", ->
shared.create.call this,
team1: [Factory("Magikarp", evs: {speed: 4}, ability: "Stall")]
team2: [Factory("Magikarp")]
splash = @battle.getMove("Splash")
@battle.recordMove(@id1, splash)
@battle.recordMove(@id2, splash)
@battle.determineTurnOrder()
pokemon = @battle.pokemonActions.map((o) -> o.pokemon)
pokemon.should.eql [ @p2, @p1 ]
it "moves before pokemon with lagging tail/full incense", ->
shared.create.call this,
team1: [Factory("Magikarp", evs: {speed: 4}, ability: "Stall")]
team2: [Factory("Magikarp", item: "Lagging Tail")]
splash = @battle.getMove("Splash")
@battle.recordMove(@id1, splash)
@battle.recordMove(@id2, splash)
@battle.determineTurnOrder()
pokemon = @battle.pokemonActions.map((o) -> o.pokemon)
pokemon.should.eql [ @p1, @p2 ]
describe "Steadfast", ->
it "raises speed if the Pokemon flinches", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Steadfast")]
tackle = @battle.getMove("Tackle")
@p1.attach(Attachment.Flinch)
@p1.beforeMove(tackle, @p1, [ @p2 ])
@p1.stages.should.containEql(speed: 1)
describe "Sturdy", ->
it "prevents the user from being OHKOed at full HP", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sturdy")]
ember = @battle.getMove('Ember')
stub = @sandbox.stub(ember, 'calculateDamage', -> 9999)
@battle.performMove(@p2, ember)
@p1.currentHP.should.equal(1)
it "lets the user be KOed if not at full HP", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sturdy")]
@p1.currentHP -= 1
ember = @battle.getMove('Ember')
stub = @sandbox.stub(ember, 'calculateDamage', -> 9999)
@battle.performMove(@p2, ember)
@p1.currentHP.should.equal(0)
describe "Suction Cups", ->
it "prevents user from being phased", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Suction Cups"), Factory("Magikarp")]
whirlwind = @battle.getMove('Whirlwind')
mock = @sandbox.mock(@team1).expects('switch').never()
@battle.performMove(@p2, whirlwind)
mock.verify()
describe "Super Luck", ->
it "adds +2 to critical hit level", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Super Luck")]
tackle = @battle.getMove("Tackle")
tackle.criticalHitLevel(@battle, @p1, @p2).should.equal(2)
describe "Synchronize", ->
it "afflicts the source of a status with the same status", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Synchronize")]
@p1.attach(Status.Paralyze, source: @p2)
@p2.has(Status.Paralyze).should.be.true
it "doesn't attempt to afflict target if target is self", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Synchronize")]
spy = @sandbox.spy(Status.Burn, 'preattach')
@p1.attach(Status.Burn, source: @p1)
spy.returned(false).should.be.true
it "activates on primary status moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Synchronize")]
@battle.performMove(@p2, @battle.getMove("Will-O-Wisp"))
@p2.has(Status.Burn).should.be.true
it "doesn't activate on Sleep", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Synchronize")]
@p1.attach(Status.Sleep, source: @p2)
@p2.has(Status.Sleep).should.be.false
it "doesn't activate on Freeze", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Synchronize")]
@p1.attach(Status.Freeze, source: @p2)
@p2.has(Status.Freeze).should.be.false
it "activates on secondary effects", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Synchronize")]
shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance
@battle.performMove(@p2, @battle.getMove("Flamethrower"))
@p2.has(Status.Burn).should.be.true
describe "Tangled Feet", ->
it "doubles evasion rate when confused", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Tangled Feet")]
tackle = @battle.getMove("Tackle")
tackle.chanceToHit(@battle, @p2, @p1).should.equal(100)
@p1.attach(Attachment.Confusion)
tackle.chanceToHit(@battle, @p2, @p1).should.equal(50)
@p1.unattach(Attachment.Confusion)
tackle.chanceToHit(@battle, @p2, @p1).should.equal(100)
describe "Technician", ->
it "increases base power of moves with BP <= 60 by x1.5", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Technician")]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1800)
it "leaves moves with BP > 60 alone", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Technician")]
iceBeam = @battle.getMove("Ice Beam")
iceBeam.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
describe "Telepathy", ->
it "cancels damaging attacks from an ally", ->
shared.create.call this,
numActive: 2
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Telepathy")]
team2: (Factory("Magikarp") for x in [1..2])
earthquake = @battle.getMove("Earthquake")
mock = @sandbox.mock(earthquake).expects('hit').exactly(2)
@battle.performMove(@p1, earthquake)
@team1.at(1).currentHP.should.equal(@team1.at(1).stat('hp'))
mock.verify()
describe "Thick Fat", ->
it "halves the base power of Fire and Ice moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Thick Fat")]
iceBeam = @battle.getMove("Ice Beam")
iceBeam.modifyAttack(@battle, @p2, @p1).should.equal(0x800)
flamethrower = @battle.getMove("Flamethrower")
flamethrower.modifyAttack(@battle, @p2, @p1).should.equal(0x800)
it "doesn't change base power of other moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Thick Fat")]
tackle = @battle.getMove("Tackle")
tackle.modifyAttack(@battle, @p2, @p1).should.equal(0x1000)
describe "Tinted Lens", ->
it "doubles damage when using a not-very-effective move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Tinted Lens")]
team2: [Factory("Magikarp")]
surf = @battle.getMove("Surf")
surf.modifyDamage(@battle, @p1, @p2).should.equal(0x2000)
it "doesn't double damage otherwise", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Tinted Lens")]
team2: [Factory("Magikarp")]
tackle = @battle.getMove("Tackle")
tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000)
describe "Trace", ->
it "copies a random foe's ability on switch-in", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Trace")]
team2: [Factory("Magikarp", ability: "Truant")]
@p1.hasAbility("Truant").should.be.true
it "does not copy certain abilities", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Trace")]
team2: [Factory("Magikarp", ability: "Forecast")]
@p1.hasAbility("Forecast").should.be.false
it "does not crash if there are no opponents", ->
shared.create.call this,
team1: [Factory("Magikarp")]
team2: [Factory("Magikarp"), Factory("Magikarp")]
@p2.faint()
(=>
@p1.copyAbility(Ability.Trace)
).should.not.throw()
it "traces another ability upon switching out and back in", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Trace"), Factory("Magikarp")]
team2: [Factory("Magikarp", ability: "Intimidate")
Factory("Magikarp", ability: "Magic Bounce")]
@p1.hasAbility("Intimidate").should.be.true
@battle.performSwitch(@p2, 1)
@battle.performSwitch(@p1, 1)
@battle.performSwitch(@team1.first(), 1)
@p1.hasAbility("Magic Bounce").should.be.true
describe "Truant", ->
it "prevents the user from attacking every other turn", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Truant")]
splash = @battle.getMove("Splash")
mock = @sandbox.mock(splash).expects('execute').once()
@battle.performMove(@p1, splash)
mock.verify()
splash.execute.restore()
mock = @sandbox.mock(splash).expects('execute').never()
@battle.performMove(@p1, splash)
mock.verify()
splash.execute.restore()
mock = @sandbox.mock(splash).expects('execute').once()
@battle.performMove(@p1, splash)
mock.verify()
splash.execute.restore()
describe "Unaware", ->
it "ignores attackers' attack and special attack boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unaware")]
@p2.boost(attack: 1, specialAttack: 2)
spy = @sandbox.spy(@p2, "editBoosts")
@battle.performMove(@p2, @battle.getMove("Tackle"))
spy.returned(sinon.match(attack: 0, specialAttack: 0)).should.be.true
it "ignores defenders' defense and special defense boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unaware")]
@p2.boost(defense: 1, specialDefense: 2)
spy = @sandbox.spy(@p2, "editBoosts")
@battle.performMove(@p1, @battle.getMove("Tackle"))
spy.returned(sinon.match(defense: 0, specialDefense: 0)).should.be.true
it "ignores attackers' accuracy boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unaware")]
@p2.boost(accuracy: 3)
spy = @sandbox.spy(@p2, "editBoosts")
@battle.getMove("Tackle").chanceToHit(@battle, @p2, @p1)
spy.returned(sinon.match(accuracy: 0)).should.be.true
it "ignores defenders' evasion boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unaware")]
@p2.boost(evasion: 3)
spy = @sandbox.spy(@p2, "editBoosts")
@battle.getMove("Tackle").chanceToHit(@battle, @p1, @p2)
spy.returned(sinon.match(evasion: 0)).should.be.true
describe "Unburden", ->
it "doubles its speed when the owner's item is removed", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Unburden")]
speed = @p1.stat('speed')
@p1.removeItem()
@p1.stat('speed').should.equal(2 * speed)
it "activates when its item is swapped for no item", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Unburden")]
speed = @p1.stat('speed')
trick = @battle.getMove("Trick")
@battle.performMove(@p2, trick)
@p1.stat('speed').should.equal(2 * speed)
it "does not activate when its item is swapped for another item", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Unburden")]
team2: [Factory("Magikarp", item: "Water Gem")]
speed = @p1.stat('speed')
trick = @battle.getMove("Trick")
@battle.performMove(@p2, trick)
@p1.stat('speed').should.equal(speed)
@p1.has(Attachment.Unburden).should.be.false
it "deactivates if it gains another item", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Unburden")]
team2: [Factory("Magikarp", item: "Water Gem")]
speed = @p1.stat('speed')
@p1.removeItem()
@p1.stat('speed').should.equal(2 * speed)
trick = @battle.getMove("Trick")
@battle.performMove(@p2, trick)
@p1.stat('speed').should.equal(speed)
@p1.has(Attachment.Unburden).should.be.false
it "deactivates if it loses this Ability", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Unburden")]
team2: [Factory("Magikarp", ability: "Run Away")]
speed = @p1.stat('speed')
@p1.removeItem()
@p1.stat('speed').should.equal(2 * speed)
rolePlay = @battle.getMove("Role Play")
@battle.performMove(@p1, rolePlay)
@p1.stat('speed').should.equal(speed)
@p1.has(Attachment.Unburden).should.be.false
describe "Unnerve", ->
it "prevents held berries from being eaten", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unnerve")]
team2: [Factory("Magikarp", item: "Salac Berry")]
@p2.currentHP = 1
@p2.update()
@p2.stages.should.containEql(speed: 0)
@battle.beginTurn()
@p2.update()
@p2.stages.should.containEql(speed: 0)
it "does not prevent regular item usage", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unnerve")]
team2: [Factory("Magikarp", item: "Leftovers")]
@p2.currentHP = 1
@battle.endTurn()
@p2.currentHP.should.be.greaterThan(1)
it "does not prevent Bug Bite, Pluck, etc. from working", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Salac Berry", ability: "Unnerve")]
@battle.performMove(@p2, @battle.getMove("Bug Bite"))
@p2.stages.should.containEql(speed: 1)
describe "Victory Star", ->
it "increases accuracy of moves by 10%", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Victory Star")]
willOWisp = @battle.getMove("Will-O-Wisp")
accuracy = willOWisp.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal Math.floor(willOWisp.accuracy * 1.1)
it "increases accuracy of ally moves by 10%"
testTypeAbsorbMove = (name, type) ->
describe name, ->
it "is immune to #{type}-type moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
m.type == type
mock = @sandbox.mock(typedMove).expects('hit').never()
@battle.performMove(@p2, typedMove)
mock.verify()
it "heals 25% HP from #{type}-type moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
m.type == type
@p1.currentHP = 1
@battle.performMove(@p2, typedMove)
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 2))
it "does not activate for the user's moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
m.target == 'user' && m.type == type
@p1.currentHP = 1
@battle.performMove(@p1, typedMove)
@p1.currentHP.should.equal(1)
testTypeAbsorbMove("Water Absorb", "Water")
testTypeAbsorbMove("Volt Absorb", "Electric")
describe "Weak Armor", ->
it "lowers defense and raises speed on physical attacks", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Weak Armor")]
tackle = @battle.getMove("Tackle")
@battle.performMove(@p2, tackle)
@p1.stages.should.containEql(defense: -1, speed: 1)
it "does nothing on any other kind of move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Weak Armor")]
willOWisp = @battle.getMove("Will-O-Wisp")
@battle.performMove(@p2, willOWisp)
@p1.stages.should.containEql(defense: 0, speed: 0)
describe "Wonder Guard", ->
it "renders the Pokemon immune to non-super-effective moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Wonder Guard")]
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').never()
@battle.performMove(@p2, tackle)
mock.verify()
it "is not immune to struggle", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Wonder Guard")]
struggle = @battle.getMove("Struggle")
mock = @sandbox.mock(struggle).expects('hit').once()
@battle.performMove(@p2, struggle)
mock.verify()
it "is not immune to non-damaging moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Wonder Guard")]
willOWisp = @battle.getMove("Will-O-Wisp")
mock = @sandbox.mock(willOWisp).expects('hit').once()
@battle.performMove(@p2, willOWisp)
mock.verify()
it "is not immune to super-effective moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Wonder Guard")]
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == 'Electric'
mock = @sandbox.mock(typedMove).expects('hit').once()
@battle.performMove(@p2, typedMove)
mock.verify()
describe "Wonder Skin", ->
it "makes non-damaging moves with over 50% accuracy have 50% accuracy", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Wonder Skin")]
trick = @battle.getMove("Trick")
accuracy = trick.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal 50
it "adjusts accuracy before any other modifiers take effect", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Compoundeyes")]
team2: [Factory("Magikarp", ability: "Wonder Skin")]
willOWisp = @battle.getMove("Will-O-Wisp")
accuracy = willOWisp.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal Math.floor(50 * 1.3)
it "does nothing to non-damaging moves that don't check accuracy", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Wonder Skin")]
meanLook = @battle.getMove("Mean Look")
accuracy = meanLook.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal 0
it "does nothing to non-damaging moves with under 50% accuracy", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Wonder Skin")]
trick = @battle.getMove("Trick")
trick.accuracy = 40
accuracy = trick.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal 40
describe "Zen Mode", ->
it "changes Darmanitan's forme when going under or above 50% HP"
| 18884 | require '../helpers'
{Attachment, Status} = require('../../server/bw/attachment')
{Battle} = require('../../server/bw/battle')
{Pokemon} = require('../../server/bw/pokemon')
{Weather} = require('../../shared/weather')
{Item} = require('../../server/bw/data/items')
{Ability} = require '../../server/bw/data/abilities'
util = require '../../server/bw/util'
{Factory} = require '../factory'
should = require 'should'
sinon = require 'sinon'
{_} = require 'underscore'
shared = require '../shared'
describe "BW Abilities:", ->
describe "Adaptability", ->
it "makes STAB 2x instead of 1.5", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Adaptability")]
hydroPump = @battle.getMove("Hydro Pump")
hydroPump.stabModifier(@battle, @p1, @p2).should.equal(0x2000)
it "still has 1x if the pokemon does not have STAB", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Adaptability")]
tackle = @battle.getMove("Tackle")
tackle.stabModifier(@battle, @p1, @p2).should.equal(0x1000)
describe "Aftermath", ->
it "deals 25% HP damage to the killer", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Aftermath"), Factory("Magikarp")]
@p1.currentHP = 1
@battle.performMove(@p2, @battle.getMove("Tackle"))
@battle.performFaints()
(@p2.stat('hp') - @p2.currentHP).should.equal(@p2.stat('hp') >> 2)
it "does not deal damage for non-contact moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Aftermath"), Factory("Magikarp")]
@p1.currentHP = 1
@battle.performMove(@p2, @battle.getMove("Thunderbolt"))
@battle.performFaints()
@p2.currentHP.should.equal(@p2.stat('hp'))
it "does not deal damage if pokemon died of natural causes", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Aftermath"), Factory("Magikarp")]
thunderbolt = @battle.getMove("Thunderbolt")
@p1.currentHP = 2
@p1.attach(Status.Burn)
@sandbox.stub(thunderbolt, 'calculateDamage', -> 1)
@battle.performMove(@p2, thunderbolt)
@battle.endTurn()
@p2.currentHP.should.equal(@p2.stat('hp'))
it "does not crash if the Pokemon never was hit", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Aftermath"), Factory("Magikarp")]
(=> @p1.faint()).should.not.throw()
it "deals a minimum of 1 damage", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Aftermath"), Factory("Magikarp")]
team2: [Factory("S<NAME>inja")]
@p1.currentHP = 2
@battle.performMove(@p2, @battle.getMove("Tackle"))
@battle.performFaints()
@p2.currentHP.should.equal(0)
testWeatherPreventionAbility = (name) ->
describe name, ->
it "causes the battle to think there is no weather", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
@battle.setWeather(Weather.SAND)
@battle.hasWeather(Weather.SAND).should.be.false
@battle.setWeather(Weather.SUN)
@battle.hasWeather(Weather.SUN).should.be.false
testWeatherPreventionAbility("Air Lock")
testWeatherPreventionAbility("Cloud Nine")
describe "Analytic", ->
it "multiplies attacks by 1.3 if no one is moving afterward", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Analytic")]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x14CD)
it "doesn't multiply if the user isn't the last to move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Analytic")]
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
describe "Anger Point", ->
it "maximizes Attack on critical hit", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Anger Point")]
tackle = @battle.getMove("Tackle")
@sandbox.stub(tackle, 'isCriticalHit', -> true)
@p1.stages.attack.should.equal(0)
@battle.performMove(@p2, tackle)
@p1.stages.should.containEql(attack: 6)
it "doesn't maximize attack on non-critical hits", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Anger Point")]
tackle = @battle.getMove("Tackle")
@sandbox.stub(tackle, 'isCriticalHit', -> false)
@p1.stages.attack.should.equal(0)
@battle.performMove(@p2, tackle)
@p1.stages.should.containEql(attack: 0)
describe "Anticipation", ->
it "shows a message if an opponent has a super-effective move", ->
shared.create.call this,
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Anticipation")]
team2: [Factory("Pikachu", moves: ["Thunderbolt"])]
spy = @sandbox.spy(@battle, 'cannedText')
@battle.performSwitch(@p1, 1)
spy.calledWithMatch('ANTICIPATION').should.be.true
it "shows a message if an opponent has an OHKO move", ->
shared.create.call this,
team1: [Factory("Magikarp"), Factory("<NAME>", ability: "Anticipation")]
team2: [Factory("<NAME>", moves: ["Sheer Cold"])]
spy = @sandbox.spy(@battle, 'cannedText')
@battle.performSwitch(@p1, 1)
spy.calledWithMatch('ANTICIPATION').should.be.true
it "doesn't show a message otherwise", ->
shared.create.call this,
team1: [Factory("Mag<NAME>"), Factory("Magikarp", ability: "Anticipation")]
spy = @sandbox.spy(@battle, 'cannedText')
@battle.performSwitch(@p1, 1)
spy.calledWithMatch('ANTICIPATION').should.be.false
it "displays nothing when no opponents left", ->
shared.create.call this,
team1: [Factory("<NAME>")]
team2: [Factory("<NAME>"), Factory("<NAME>ikarp")]
@p2.faint()
spy = @sandbox.spy(@battle, 'cannedText')
@p1.copyAbility(Ability.Anticipation)
spy.called.should.be.false
describe "Arena Trap", ->
it "blocks switch", ->
shared.create.call this,
team1: [Factory("Mag<NAME>", ability: "Arena Trap")]
team2: [Factory("<NAME>")]
@p2.isSwitchBlocked().should.be.true
it "blocks switch the next turn as well", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Arena Trap")]
team2: [Factory("<NAME>")]
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.true
it "doesn't block switch for Flying Pokemon", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Arena Trap")]
team2: [Factory("G<NAME>")]
@p2.isSwitchBlocked().should.be.false
it "doesn't block switch for Pokemon immune to Ground by other means", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Arena Trap")]
team2: [Factory("<NAME>")]
@battle.performMove(@p2, @battle.getMove("Magnet Rise"))
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.false
describe "Bad Dreams", ->
it "deals 1/8 max HP end of turn if target is asleep", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Bad Dreams")]
team2: [Factory("Celebi")]
(@p2.stat('hp') - @p2.currentHP).should.equal(0)
@p2.attach(Status.Sleep)
@battle.endTurn()
(@p2.stat('hp') - @p2.currentHP).should.equal(@p2.stat('hp') >> 3)
it "deals no damage if target is awake", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Bad Dreams")]
team2: [Factory("Celebi")]
(@p2.stat('hp') - @p2.currentHP).should.equal(0)
@battle.endTurn()
(@p2.stat('hp') - @p2.currentHP).should.equal(0)
it "deals a minimum of 1 damage", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Bad Dreams")]
team2: [Factory("<NAME>")]
@p2.attach(Status.Sleep)
@battle.endTurn()
@p2.currentHP.should.equal(0)
testCriticalHitPreventionAbility = (name) ->
describe name, ->
it "prevents critical hits", ->
shared.create.call this,
team1: [Factory("<NAME>")]
team2: [Factory("C<NAME>bi", ability: name)]
shared.biasRNG.call(this, "next", "ch", .2)
tackle = @battle.getMove("Tackle")
@sandbox.stub(tackle, 'criticalHitLevel', -> 3)
tackle.isCriticalHit(@battle, @p1, @p2).should.be.false
testCriticalHitPreventionAbility("Battle Armor")
testCriticalHitPreventionAbility("Shell Armor")
testBoostProtectionAbility = (name, protection) ->
describe name, ->
allBoosts = [ "attack", "defense", "speed", "specialAttack",
"specialDefense", "accuracy", "evasion" ]
protection ||= allBoosts
it "protects against certain stat falls", ->
shared.create.call this, team1: [Factory("Celebi", ability: name)]
boosts = {}
boosts[stat] = -1 for stat in allBoosts
@p1.boost(boosts, @p2)
boosts[stat] = 0 for stat in protection
@p1.stages.should.eql(boosts)
it "does not protect against stat falls if the source is the user", ->
shared.create.call this, team1: [Factory("Celebi", ability: name)]
boosts = {}
boosts[stat] = -1 for stat in allBoosts
@p1.boost(boosts)
@p1.stages.should.containEql(boosts)
testBoostProtectionAbility("Big Pecks", [ "defense" ])
testBoostProtectionAbility("Clear Body")
testBoostProtectionAbility("Hyper Cutter", [ "attack" ])
testBoostProtectionAbility("Keen Eye", [ "accuracy" ])
testBoostProtectionAbility("White Smoke")
testLowHealthAbility = (name, type) ->
describe name, ->
it "increases power of #{type} moves by 1.5 at 1/3 health", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
@p1.currentHP = Math.floor(@p1.stat('hp') / 3)
move = _(@battle.MoveList).find (m) ->
m.type == type && !m.isNonDamaging()
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1800)
it "doesn't increase power if move not of #{type}", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
@p1.currentHP = Math.floor(@p1.stat('hp') / 3)
move = _(@battle.MoveList).find (m) ->
m.type != type && !m.isNonDamaging()
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "doesn't increase power if user isn't under 1/3 health", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
@p1.currentHP = Math.floor(@p1.stat('hp') / 3) + 1
move = _(@battle.MoveList).find (m) ->
m.type == type && !m.isNonDamaging()
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
testLowHealthAbility("Blaze", "Fire")
testLowHealthAbility("Torrent", "Water")
testLowHealthAbility("Overgrow", "Grass")
testLowHealthAbility("Swarm", "Bug")
testWeatherSpeedAbility = (name, weather) ->
describe name, ->
it "doubles speed when the weather becomes #{weather}", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
speed = @p1.stat('speed')
@battle.setWeather(weather)
@p1.stat('speed').should.equal(2 * speed)
it "goes back to normal when the weather becomes something else", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
speed = @p1.stat('speed')
@battle.setWeather(weather)
@battle.setWeather(Weather.NONE)
@p1.stat('speed').should.equal(speed)
it "grants immunity to damage from their respective weather", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
@p1.isWeatherDamageImmune(weather).should.be.true
testWeatherSpeedAbility("Chlorophyll", Weather.SUN)
testWeatherSpeedAbility("Swift Swim", Weather.RAIN)
testWeatherSpeedAbility("Sand Rush", Weather.SAND)
describe "Color Change", ->
it "changes the owner's type to be the move's type that just hit it", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Color Change")]
ember = @battle.getMove("Ember")
@p1.hasType(ember.type).should.be.false
@battle.performMove(@p2, ember)
@p1.hasType(ember.type).should.be.true
it "does not change the owner's type if the move is non-damaging", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Color Change")]
willOWisp = @battle.getMove("Will-O-Wisp")
@p1.hasType(willOWisp.type).should.be.false
@battle.performMove(@p2, willOWisp)
@p1.hasType(willOWisp.type).should.be.false
describe "Compoundeyes", ->
it "increases accuracy of moves by 1.3x", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Compoundeyes")]
willOWisp = @battle.getMove("Will-O-Wisp")
accuracy = willOWisp.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal Math.floor(willOWisp.accuracy * 1.3)
describe "Contrary", ->
it "reverses stat changes from all sources", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Contrary")]
leafStorm = @battle.getMove("Leaf Storm")
growl = @battle.getMove("Growl")
@battle.performMove(@p1, leafStorm)
@p1.stages.should.containEql(specialAttack: 2)
@battle.performMove(@p2, growl)
@p1.stages.should.containEql(attack: 1)
describe "Cursed Body", ->
it "has a 30% chance to disable an attacker's last move", ->
shared.create.call this,
team1: [Factory("Mag<NAME>", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 0)
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.true
it "does not disable the owner", ->
shared.create.call this,
team1: [Factory("Magik<NAME>", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 0)
recover = @battle.getMove("Recover")
@p1.moves = [ recover ]
@p1.resetAllPP()
@p1.currentHP = 1
@battle.performMove(@p1, recover)
@p1.isMoveBlocked(recover).should.be.false
it "does not disable if attacker is behind a substitute", ->
shared.create.call this,
team1: [Factory("Mag<NAME>", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 0)
tackle = @battle.getMove("Tackle")
substitute = @battle.getMove("Substitute")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, substitute)
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.false
it "does not disable if defender is behind a substitute", ->
shared.create.call this,
team1: [Factory("Magik<NAME>", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 0)
tackle = @battle.getMove("Tackle")
substitute = @battle.getMove("Substitute")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p1, substitute)
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.false
it "has a 70% chance to do nothing", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", .3)
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.false
it "can work even if the defender faints", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Cursed Body"), Factory("Magikarp")]
shared.biasRNG.call(this, "next", "cursed body", 0)
@p1.currentHP = 1
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.true
it "lasts some turns", ->
shared.create.call this,
team1: [Factory("Mag<NAME>", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 0)
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, tackle)
for x in [1..2]
@battle.endTurn()
@battle.beginTurn()
@p2.isMoveBlocked(tackle).should.be.true
it "cannot stack with Disable", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 1) # do not trigger
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, tackle)
@battle.performMove(@p1, @battle.getMove('Disable'))
@p2.isMoveBlocked(tackle).should.be.true
# Disable lasts 4 turns, so go to the last turn.
for x in [1..3]
@battle.endTurn()
@battle.beginTurn()
@p2.isMoveBlocked(tackle).should.be.true
shared.biasRNG.call(this, "next", "cursed body", 0)
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.true
# Disable should end.
@battle.endTurn()
@battle.beginTurn()
@p2.isMoveBlocked(tackle).should.be.false
describe "Defeatist", ->
it "halves attack and special attack if HP goes under 50%", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Defeatist")]
tackle = @battle.getMove("Tackle")
thunderbolt = @battle.getMove("Thunderbolt")
# 50%
@p1.currentHP = (@p1.stat('hp') >> 1)
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x800)
thunderbolt.modifyAttack(@battle, @p1, @p2).should.equal(0x800)
# 50% + 1
@p1.currentHP = (@p1.stat('hp') >> 1) + 1
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
thunderbolt.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
describe "Defiant", ->
it "boosts attack by 2 every time a stat is lowered", ->
shared.create.call this,
team1: [Factory("Mag<NAME>", ability: "Defiant")]
@p1.boost(defense: -1, @p2)
@p1.stages.should.containEql(attack: 2)
@p1.boost(attack: -1, defense: -2, evasion: 1, @p2)
@p1.stages.should.containEql(attack: 5)
it "does not boost attack if the stat was self-lowered", ->
shared.create.call this,
team1: [Factory("Mag<NAME>", ability: "Defiant")]
@battle.performMove(@p1, @battle.getMove("Close Combat"))
@p1.stages.should.containEql(attack: 0, defense: -1, specialDefense: -1)
describe "Download", ->
it "raises attack if foes have total defense < total sp.def", ->
shared.create.call this,
team1: [Factory("<NAME>")]
team2: [Factory("<NAME>")]
@p1.stages.should.containEql(attack: 0)
@p1.copyAbility(Ability.Download)
@p1.stages.should.containEql(attack: 1)
it "raises special attack if foes have total sp.def <= total def", ->
shared.create.call this,
team1: [Factory("<NAME>")]
team2: [Factory("<NAME>")]
@p1.stages.should.containEql(specialAttack: 0)
@p1.copyAbility(Ability.Download)
@p1.stages.should.containEql(specialAttack: 1)
it "does not raise anything if all foes have fainted", ->
shared.create.call(this)
@p2.faint()
@p1.stages.should.containEql(attack: 0, specialAttack: 0)
@p1.copyAbility(Ability.Download)
@p1.stages.should.containEql(attack: 0, specialAttack: 0)
testWeatherAbility = (name, weather) ->
describe name, ->
it "causes unending #{weather}", ->
shared.build(this, team1: [Factory("Magikarp", ability: name)])
@battle.hasWeather().should.be.false
@controller.beginBattle()
@battle.hasWeather(weather).should.be.true
@battle.weatherDuration.should.equal(-1)
testWeatherAbility("Drizzle", Weather.RAIN)
testWeatherAbility("Drought", Weather.SUN)
testWeatherAbility("Sand Stream", Weather.SAND)
testWeatherAbility("Snow Warning", Weather.HAIL)
describe "Dry Skin", ->
it "gets healed 25% HP by water moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Dry Skin")])
@p1.currentHP = 1
@battle.performMove(@p2, @battle.getMove("Hydro Pump"))
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 2))
@battle.performMove(@p2, @battle.getMove("Tackle"))
@p1.currentHP.should.be.lessThan(1 + (@p1.stat('hp') >> 2))
it "does not get healed by self-targeting water moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Dry Skin")])
@p1.currentHP = 1
@battle.performMove(@p1, @battle.getMove("Aqua Ring"))
@p1.currentHP.should.equal(1)
it "gets healed 1/8 HP end of turn in Rain", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Dry Skin")])
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1)
@battle.setWeather(Weather.RAIN)
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 3))
it "gets damaged 25% extra by fire moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Dry Skin")])
ember = @battle.getMove("Ember")
ember.modifyBasePower(@battle, @p2, @p1).should.equal(0x1400)
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p2, @p1).should.equal(0x1000)
it "gets hurt 1/8 HP end of turn in Sun", ->
shared.create.call(this, team1: [Factory("<NAME>ikarp", ability: "Dry Skin")])
@battle.endTurn()
@p1.currentHP.should.equal(@p1.stat('hp'))
@battle.setWeather(Weather.SUN)
@battle.endTurn()
(@p1.stat('hp') - @p1.currentHP).should.equal(@p1.stat('hp') >> 3)
it "deals a minimum of 1 damage", ->
shared.create.call this,
team1: [Factory("Shedinja", ability: "Dry Skin")]
@battle.setWeather(Weather.SUN)
@battle.endTurn()
@p1.currentHP.should.equal(0)
it "heals a minimum of 1 hp", ->
shared.create.call this,
team1: [Factory("Magikarp", level: 1, ability: "Dry Skin")]
@p1.currentHP = 1
@battle.setWeather(Weather.RAIN)
@battle.endTurn()
@p1.currentHP.should.equal(2)
describe "Early Bird", ->
it "drops the sleep counter by 2 instead of 1", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Early Bird")])
shared.biasRNG.call(this, "randInt", 'sleep turns', 3)
@p1.attach(Status.Sleep)
@battle.performMove(@p1, @battle.getMove('Tackle'))
@p1.has(Status.Sleep).should.be.true
@battle.performMove(@p1, @battle.getMove('Tackle'))
@p1.has(Status.Sleep).should.be.false
describe "Effect Spore", ->
it "has a 30% chance to inflict poison, paralysis, or sleep on hit", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Effect Spore")])
# Sleep
shared.biasRNG.call(this, "randInt", 'effect spore', 1)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(Status.Sleep).should.be.true
# Paralysis
@p2.cureStatus()
shared.biasRNG.call(this, "randInt", 'effect spore', 2)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(Status.Paralyze).should.be.true
# Poison
@p2.cureStatus()
shared.biasRNG.call(this, "randInt", 'effect spore', 3)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(Status.Poison).should.be.true
it "has a 70% chance to do nothing", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Effect Spore")])
shared.biasRNG.call(this, "randInt", 'effect spore', 4)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.hasStatus().should.be.false
it "doesn't trigger if the hitting move is a non-contact move", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Effect Spore")])
shared.biasRNG.call(this, "randInt", 'effect spore', 1)
@battle.performMove(@p2, @battle.getMove('Thunderbolt'))
@p2.has(Status.Sleep).should.be.false
it "can work even if the defender faints", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Effect Spore"), Factory("Magikarp")]
shared.biasRNG.call(this, "randInt", 'effect spore', 1)
@p1.currentHP = 1
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(Status.Sleep).should.be.true
testFilterAbility = (name) ->
describe name, ->
it "reduces the impact of super-effective moves by 25%", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
seMove = _(@battle.MoveList).find (m) =>
!m.isNonDamaging() && util.typeEffectiveness(m.type, @p1.types) > 1
seMove.modifyDamage(@battle, @p2, @p1).should.equal(0xC00)
it "keeps non-super-effective moves as normal", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
seMove = _(@battle.MoveList).find (m) =>
!m.isNonDamaging() && util.typeEffectiveness(m.type, @p1.types) <= 1
seMove.modifyDamage(@battle, @p2, @p1).should.equal(0x1000)
testFilterAbility("Filter")
testFilterAbility("Solid Rock")
testContactStatusAbility = (name, attachment) ->
describe name, ->
it "has a 30% chance to inflict #{attachment.name} on the attacker", ->
shared.create.call this,
team1: [Factory("Magikarp", gender: "F", ability: name)]
team2: [Factory("Magikarp", gender: "M")]
shared.biasRNG.call(this, "next", 'contact status', 0)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(attachment).should.be.true
it "inflicts no status if the move used is a non-contact move", ->
shared.create.call this,
team1: [Factory("Mag<NAME>", gender: "F", ability: name)]
team2: [Factory("<NAME>", gender: "M")]
shared.biasRNG.call(this, "next", 'contact status', 0)
@battle.performMove(@p2, @battle.getMove('Thunderbolt'))
@p2.has(attachment).should.be.false
it "inflicts no status if the hit isn't direct", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: name)]
team2: [Factory("<NAME>")]
shared.biasRNG.call(this, "next", 'contact status', 0)
@p1.attach(Attachment.Substitute)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(attachment).should.be.false
it "has a 70% chance to do nothing", ->
shared.create.call this,
team1: [Factory("Mag<NAME>", gender: "F", ability: name)]
team2: [Factory("Magik<NAME>", gender: "M")]
shared.biasRNG.call(this, "next", 'contact status', .3)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(attachment).should.be.false
it "can work even if the defender faints", ->
shared.create.call this,
team1: [Factory("Magik<NAME>", gender: "F", ability: name), Factory("Magikarp")]
team2: [Factory("Magikarp", gender: "M")]
shared.biasRNG.call(this, "next", 'contact status', 0)
@p1.currentHP = 1
tackle = @battle.getMove('Tackle')
@battle.performMove(@p2, tackle)
@p2.has(attachment).should.be.true
testContactStatusAbility("Cute Charm", Attachment.Attract)
testContactStatusAbility("Flame Body", Status.Burn)
testContactStatusAbility("Poison Point", Status.Poison)
testContactStatusAbility("Static", Status.Paralyze)
testStatusBoostAbility = (name, statuses, spectra) ->
statusNames = statuses.map((s) -> s.name).join(', ')
describe name, ->
it "increases #{spectra} moves by 1.5 if has #{statusNames}", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
move = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.spectra == spectra
for status in statuses
@p1.cureStatus()
@p1.attach(status)
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1800)
it "does not increase non-#{spectra} moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
move = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.spectra != spectra
for status in statuses
@p1.cureStatus()
@p1.attach(status)
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
testStatusBoostAbility("Flare Boost", [Status.Burn], "special")
testStatusBoostAbility("Toxic Boost", [Status.Poison, Status.Toxic], "physical")
describe "Flash Fire", ->
it "makes user invulnerable to Fire-type moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Flash Fire")])
ember = @battle.getMove("Ember")
mock = @sandbox.mock(ember).expects('hit').never()
@battle.performMove(@p2, ember)
mock.verify()
it "powers up user's Fire-type moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Flash Fire")])
ember = @battle.getMove("Ember")
tackle = @battle.getMove("Tackle")
@battle.performMove(@p2, ember)
ember.modifyBasePower(@battle, @p1, @p2).should.equal(0x1800)
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "doesn't activate on Protect", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Flash Fire")])
protect = @battle.getMove("Protect")
ember = @battle.getMove("Ember")
@battle.recordMove(@id1, protect)
@battle.recordMove(@id2, ember)
@battle.continueTurn()
@p1.has(Attachment.FlashFire).should.be.false
describe "Flower Gift", ->
it "changes Cherrim's forme"
it "does not change a transformed pokemon's forme"
it "grants x1.5 attack and special defense in Sun"
it "grants x1.5 attack and special defense to allies in Sun"
describe "Forecast", ->
it "changes Castform's forme"
it "does not change a transformed pokemon's forme"
describe "Forewarn", ->
it "considers OHKO moves to have 160 BP", ->
shared.create.call(this)
Ability.Forewarn.consider(@battle.getMove("Fissure")).should.equal(160)
it "considers counter moves to have 120 BP", ->
shared.create.call(this)
{consider} = Ability.Forewarn
consider(@battle.getMove("Counter")).should.equal(120)
consider(@battle.getMove("Mirror Coat")).should.equal(120)
consider(@battle.getMove("Metal Burst")).should.equal(120)
it "considers specific variable power moves to have 80 BP", ->
shared.create.call(this)
{consider} = Ability.Forewarn
consider(@battle.getMove("Crush Grip")).should.equal(80)
consider(@battle.getMove("Dragon Rage")).should.equal(80)
consider(@battle.getMove("Endeavor")).should.equal(80)
consider(@battle.getMove("Flail")).should.equal(80)
consider(@battle.getMove("Frustration")).should.equal(80)
consider(@battle.getMove("Grass Knot")).should.equal(80)
consider(@battle.getMove("Gyro Ball")).should.equal(80)
consider(@battle.getMove("Hidden Power")).should.equal(80)
consider(@battle.getMove("Low Kick")).should.equal(80)
consider(@battle.getMove("Natural Gift")).should.equal(80)
consider(@battle.getMove("Night Shade")).should.equal(80)
consider(@battle.getMove("Psywave")).should.equal(80)
consider(@battle.getMove("Return")).should.equal(80)
consider(@battle.getMove("Reversal")).should.equal(80)
consider(@battle.getMove("Seismic Toss")).should.equal(80)
consider(@battle.getMove("SonicBoom")).should.equal(80)
consider(@battle.getMove("Trump Card")).should.equal(80)
consider(@battle.getMove("Wring Out")).should.equal(80)
it "alerts user about a foe's move with the highest base power", ->
shared.build(this, team1: [Factory("Magikarp", ability: "Forewarn")])
spy = @sandbox.spy(@battle, 'cannedText')
@controller.beginBattle()
tackle = @battle.getMove("Tackle")
spy.calledWith('FOREWARN', @p2, tackle).should.be.true
it "displays nothing when no opponents left", ->
shared.create.call this,
team1: [Factory("Magikarp")]
team2: [Factory("Magikarp"), Factory("Magikarp")]
@p2.faint()
spy = @sandbox.spy(@battle, 'cannedText')
@p1.copyAbility(Ability.Forewarn)
spy.called.should.be.false
describe "Friend Guard", ->
it "weakens attacks from allies by 25%", ->
shared.create.call this,
numActive: 2
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Friend Guard")]
earthquake = @battle.getMove("Earthquake")
earthquake.modifyDamage(@battle, @p1, @team1.at(1)).should.equal(0xC00)
it "keeps attacks by enemies at normal", ->
shared.create.call this,
numActive: 2
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Friend Guard")]
earthquake = @battle.getMove("Earthquake")
earthquake.modifyDamage(@battle, @p2, @team1.at(1)).should.equal(0x1000)
describe "Frisk", ->
it "randomly selects an opponent and displays the item", ->
shared.build this,
team1: [Factory("Magikarp", ability: "Frisk")]
team2: [Factory("Magikarp", item: "Leftovers")]
spy = @sandbox.spy(@battle, 'cannedText')
@controller.beginBattle()
spy.calledWithMatch('FRISK').should.be.true
it "displays nothing when no opponents left", ->
shared.create.call this,
team1: [Factory("Magikarp")]
team2: [Factory("Magikarp"), Factory("Magikarp")]
@p2.faint()
spy = @sandbox.spy(@battle, 'cannedText')
@p1.copyAbility(Ability.Frisk)
spy.called.should.be.false
describe "Gluttony", ->
it "makes berries activate at 50% HP", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Salac Berry", ability: "Gluttony")]
@p1.stages.should.containEql(speed: 0)
@p1.currentHP >>= 1
@p1.update()
@p1.stages.should.containEql(speed: 1)
describe "Guts", ->
it "multiplies attack by x1.5 if statused", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Guts")])
tackle = @battle.getMove("Tackle")
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
@p1.attach(Status.Burn)
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1800)
it "does not multiply attack if move is special", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Guts")])
thunderbolt = @battle.getMove("Thunderbolt")
@p1.attach(Status.Burn)
thunderbolt.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
describe "Harvest", ->
it "has a 50% chance of re-obtaining a berry it used", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "<NAME>ac Berry", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 1)
@p1.useItem()
@battle.endTurn()
@p1.hasItem("Salac Berry").should.be.true
it "has a 50% chance of doing nothing", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "<NAME> Berry", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 0)
@p1.useItem()
@battle.endTurn()
@p1.hasItem("Salac Berry").should.be.false
it "has a 100% chance to re-obtain the berry in Sun", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Salac Berry", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 0)
@p1.useItem()
@battle.setWeather(Weather.SUN)
@battle.endTurn()
@p1.hasItem("Salac Berry").should.be.true
it "does not regain a normal item", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 1)
@p1.useItem()
@battle.endTurn()
@p1.hasItem("Flying Gem").should.be.false
it "does not regain the berry if it was removed", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Salac Berry", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 1)
@p1.useItem()
@battle.endTurn()
@p1.hasItem("Salac Berry").should.be.true
@p1.removeItem()
@battle.endTurn()
@p1.hasItem("Salac Berry").should.be.false
it "uses a regained Berry immediately if the condition is right", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Sitrus Berry", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 1)
@p1.useItem()
@p1.currentHP = 1
@p1.hasItem("Sitrus Berry").should.be.false
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 2))
@p1.hasItem("Sitrus Berry").should.be.false
describe "Healer", ->
it "has a 30% chance of healing an adjacent ally's status", ->
shared.create.call this,
numActive: 3
team1: [Factory("Magikarp", ability: "Healer"), Factory("Magikarp"), Factory("Magikarp")]
shared.biasRNG.call(this, "randInt", "healer", 3)
@team1.at(0).attach(Status.Burn)
@team1.at(1).attach(Status.Burn)
@team1.at(2).attach(Status.Burn)
@battle.endTurn()
@team1.at(0).hasStatus().should.be.true
@team1.at(1).hasStatus().should.be.false
@team1.at(2).hasStatus().should.be.true
it "has a 70% chance to do nothing", ->
shared.create.call this,
numActive: 2
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Healer")]
shared.biasRNG.call(this, "randInt", "healer", 4)
@p1.attach(Status.Burn)
@battle.endTurn()
@p1.hasStatus().should.be.true
describe "Heatproof", ->
it "receives half damage from Fire-type moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Heatproof")])
ember = @battle.getMove("Ember")
ember.modifyBasePower(@battle, @p2, @p1).should.equal(0x800)
it "receives normal damage from non-Fire-type moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Heatproof")])
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p2, @p1).should.equal(0x1000)
it "receives half damage from burn", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Heatproof")])
@p1.attach(Status.Burn)
burn = @p1.get(Status.Burn)
mock = @sandbox.mock(burn).expects('endTurn').returns(@p1.currentHP >> 4)
@battle.endTurn()
mock.verify()
describe "Heavy Metal", ->
it "doubles the user's weight", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Heavy Metal")])
@p1.calculateWeight().should.equal(2 * @p1.weight)
testHugePowerAbility = (name) ->
describe name, ->
it "doubles attack when using a physical move", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
tackle = @battle.getMove("Tackle")
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x2000)
it "does not double attack when using a special move", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
testHugePowerAbility("Huge Power")
testHugePowerAbility("Pure Power")
describe "Hustle", ->
it "multiplies attack by x1.5", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Hustle")])
tackle = @battle.getMove("Tackle")
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1800)
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
it "makes physical moves have 20% less accuracy", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Hustle")])
tackle = @battle.getMove("Tackle")
accuracy = tackle.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal Math.floor(tackle.accuracy * 0.8)
thunderbolt = @battle.getMove("Thunderbolt")
accuracy = thunderbolt.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal Math.floor(thunderbolt.accuracy * 1.0)
describe "Hydration", ->
it "restores status, in Rain, at the end of the turn", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Hydration")])
@p1.attach(Status.Sleep)
@battle.setWeather(Weather.RAIN)
@battle.endTurn()
@p1.hasStatus().should.be.false
it "does not restore status if the weather is not rainy", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Hydration")])
@p1.attach(Status.Sleep)
@battle.endTurn()
@p1.hasStatus().should.be.true
describe "Ice Body", ->
it "restores 1/16 HP in Hail", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Ice Body")]
@p1.currentHP = 1
@battle.setWeather(Weather.HAIL)
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 4))
it "restores no HP in other weather", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Ice Body")]
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1)
it "grants immunity to Hail", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Ice Body")]
@p1.isWeatherDamageImmune(Weather.HAIL).should.be.true
describe "Illusion", ->
it "masquerades as the last unfainted pokemon in player's party"
it "does not masquerade if all pokemon are fainted"
it "is broken when the user takes direct damage"
describe "Imposter", ->
it "automatically transforms into the adjacent foe pokemon", ->
shared.create.call this,
numActive: 2
team1: (Factory("Magikarp") for x in [1..2])
team2: [Factory("Celebi"), Factory("Mew")]
@team1.at(1).copyAbility(Ability.Imposter)
@team1.at(1).has(Attachment.Transform).should.be.true
it "does not transform if target is behind a substitute", ->
shared.create.call(this)
@p2.attach(Attachment.Substitute, hp: 1)
@p1.copyAbility(Ability.Imposter)
@p1.has(Attachment.Transform).should.be.false
it "does not transform if target is already transformed", ->
shared.create.call(this)
@battle.performMove(@p2, @battle.getMove("Transform"))
@p2.has(Attachment.Transform).should.be.true
@p1.copyAbility(Ability.Imposter)
@p1.has(Attachment.Transform).should.be.false
it "does not transform if no one is alive", ->
shared.create.call this,
team1: [Factory("<NAME>")]
team2: [Factory("<NAME>"), Factory("Celebi")]
@p2.faint()
@p1.copyAbility(Ability.Imposter)
@p1.has(Attachment.Transform).should.be.false
testAttachmentImmuneAbility = (name, attachments, options = {}) ->
describe name, ->
it "prevents the pokemon from receiving a specific attachment", ->
shared.create.call this,
team1: [Factory("Magikarp", gender: "F", ability: name)]
team2: [Factory("Magikarp", gender: "M")]
for attachment in attachments
should.not.exist @p1.attach(attachment, source: @p2)
@p1.has(attachment).should.be.false
shouldCure = options.cure ? true
if shouldCure
it "removes the attachment if the pokemon already has it", ->
shared.create.call this,
team1: [Factory("Magikarp", gender: "F")]
team2: [Factory("Magikarp", gender: "M")]
for attachment in attachments
@p1.attach(attachment, source: @p2)
@p1.has(attachment).should.be.true
@p1.copyAbility(Ability[name.replace(/\s+/g, '')])
@p1.update()
@p1.has(attachment).should.be.false
@p1.copyAbility(null)
testAttachmentImmuneAbility("Immunity", [Status.Poison, Status.Toxic])
testAttachmentImmuneAbility("Inner Focus", [Attachment.Flinch], cure: false)
testAttachmentImmuneAbility("Insomnia", [Status.Sleep])
testAttachmentImmuneAbility("Limber", [Status.Paralyze])
testAttachmentImmuneAbility("Magma Armor", [Status.Freeze])
testAttachmentImmuneAbility("Oblivious", [Attachment.Attract])
testAttachmentImmuneAbility("Own Tempo", [Attachment.Confusion])
testAttachmentImmuneAbility("Vital Spirit", [Status.Sleep])
testAttachmentImmuneAbility("Water Veil", [Status.Burn])
describe "Intimidate", ->
it "lowers the attack of all foe pokemon", ->
shared.create.call this,
team1: [ Factory("Magikarp", ability: "Intimidate") ]
@p2.stages.should.containEql(attack: -1)
it "does not lower attack of Pokemon behind Substitute", ->
shared.create.call this,
team1: [ Factory("Magikarp") ]
@p2.attach(Attachment.Substitute, hp: (@p2.currentHP >> 2))
@p1.copyAbility(Ability.Intimidate)
@p2.stages.should.containEql(attack: 0)
it "lowers attack simultaneously on all begin-turn switch-ins", ->
shared.create.call this,
team1: (Factory("Magikarp", ability: "Intimidate") for x in [1..2])
team2: (Factory("Magikarp", ability: "Intimidate") for x in [1..2])
@p1.stages.should.containEql(attack: -1)
@p2.stages.should.containEql(attack: -1)
@p1.faint()
@p2.faint()
@battle.requestFaintedReplacements()
@controller.makeSwitch(@id1, 1)
@controller.makeSwitch(@id2, 1)
@team1.first().should.not.equal(@p1)
@team2.first().should.not.equal(@p2)
@team1.first().stages.should.containEql(attack: -1)
@team2.first().stages.should.containEql(attack: -1)
describe "Infiltrator", ->
it "ignores Reflect", ->
shared.create.call this,
team1: [ Factory("Magikarp", ability: "Infiltrator") ]
@team2.attach(Attachment.Reflect)
tackle = @battle.getMove('Tackle')
tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000)
it "ignores Light Screen", ->
shared.create.call this,
team1: [ Factory("Magikarp", ability: "Infiltrator") ]
@team2.attach(Attachment.LightScreen)
thundershock = @battle.getMove('ThunderShock')
thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x1000)
it "ignores Safeguard"
it "ignores Mist"
testContactHurtAbility = (name) ->
describe name, ->
it "damages for 1/8 HP on contact moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name), Factory("Magikarp")])
hp = @p2.stat('hp')
@battle.performMove(@p2, @battle.getMove("Tackle"))
(hp - @p2.currentHP).should.equal(hp >> 3)
it "does not damage for non-contact moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name), Factory("Magikarp")])
@battle.performMove(@p2, @battle.getMove("Thunderbolt"))
@p2.currentHP.should.equal @p2.stat('hp')
it "does not damage for non-direct hits", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name), Factory("Magikarp")])
@p1.attach(Attachment.Substitute)
@battle.performMove(@p2, @battle.getMove("Tackle"))
@p2.currentHP.should.equal @p2.stat('hp')
it "still works even if the owner faints", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name), Factory("Magikarp")])
hp = @p2.stat('hp')
@p1.currentHP = 1
@battle.performMove(@p2, @battle.getMove("Tackle"))
(hp - @p2.currentHP).should.equal(hp >> 3)
it "deals a minimum of 1 damage", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
team2: [Factory("Shedinja")]
@battle.performMove(@p2, @battle.getMove("Tackle"))
@p2.currentHP.should.equal(0)
testContactHurtAbility("Iron Barbs")
testContactHurtAbility("Rough Skin")
describe "Iron Fist", ->
it "increases base power of punching moves by approximately x1.3", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Iron Fist")])
icePunch = @battle.getMove("Ice Punch")
icePunch.modifyBasePower(@battle, @p1, @p2).should.equal(0x1333)
it "does not increase base power of non-punching moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Iron Fist")])
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
describe "Justified", ->
it "boosts attack by 1 after being hit by a Dark move", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Justified")])
@p1.stages.should.containEql(attack: 0)
@battle.performMove(@p2, @battle.getMove("Tackle"))
@p1.stages.should.containEql(attack: 0)
@battle.performMove(@p2, @battle.getMove("Crunch"))
@p1.stages.should.containEql(attack: 1)
it "doesn't boost attack if the move is non-damaging", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Justified")])
@p1.stages.should.containEql(attack: 0)
@battle.performMove(@p1, @battle.getMove("Nasty Plot"))
@p1.stages.should.containEql(attack: 0)
it "doesn't boost attack if the move hits a substitute", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Justified")])
@p1.attach(Attachment.Substitute, hp: 1)
@p1.stages.should.containEql(attack: 0)
@battle.performMove(@p2, @battle.getMove("Crunch"))
@p1.stages.should.containEql(attack: 0)
describe "Klutz", ->
it "disables user's item upon switch-in", ->
shared.create.call this,
team1: [Factory("Magikarp"), Factory("Magikarp", item: "Leftovers", ability: "Klutz")]
@battle.performSwitch(@p1, 1)
@team1.first().isItemBlocked().should.be.true
it "disables user's item in the beginning of the turn", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Leftovers", ability: "Klutz")]
@p1.isItemBlocked().should.be.true
@battle.beginTurn()
@p1.isItemBlocked().should.be.true
describe "Leaf Guard", ->
it "defends against statuses under Sun", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Leaf Guard")]
@battle.setWeather(Weather.SUN)
@p1.attach(Status.Burn)
@p1.has(Status.Burn).should.be.false
it "does not defend against statuses otherwise", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Leaf Guard")]
@p1.attach(Status.Burn)
@p1.has(Status.Burn).should.be.true
describe "Levitate", ->
it "adds a ground immunity", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Levitate")]
@p1.isImmune('Ground').should.be.true
describe "Light Metal", ->
it "halves the user's weight", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Light Metal")])
@p1.calculateWeight().should.equal(@p1.weight >> 1)
testRedirectAndBoostAbility = (name, type) ->
describe name, ->
it "should redirect attacks of #{type} to user"
it "makes user immune to #{type}", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
mock = @sandbox.mock(typedMove).expects('hit').never()
@battle.performMove(@p2, typedMove)
mock.verify()
it "boosts special attack on #{type}-type moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
@battle.performMove(@p2, typedMove)
@p1.stages.should.containEql(specialAttack: 1)
it "does not boost special attack if the user is the target", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
m.target == 'user' && m.type == type
@battle.performMove(@p1, typedMove)
@p1.stages.should.containEql(specialAttack: 0)
it "does not boost special attack on #{type}-type moves if immune", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
@sandbox.stub(@p1, 'isImmune', -> true)
@battle.performMove(@p2, typedMove)
@p1.stages.should.containEql(specialAttack: 0)
it "does nothing otherwise", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: name)]
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').once()
@battle.performMove(@p2, tackle)
mock.verify()
@p1.stages.should.containEql(specialAttack: 0)
testRedirectAndBoostAbility("Lightningrod", "Electric")
testRedirectAndBoostAbility("Storm Drain", "Water")
describe "Liquid Ooze", ->
it "causes drain attacks to damage the user as well", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Liquid Ooze")]
@battle.performMove(@p2, @battle.getMove("Giga Drain"))
@p2.currentHP.should.be.lessThan @p2.stat('hp')
it "causes Leech Seed to damage the user as well", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Liquid Ooze")]
@battle.performMove(@p2, @battle.getMove("Leech Seed"))
@battle.endTurn()
@p2.currentHP.should.be.lessThan @p2.stat('hp')
describe "Magic Bounce", ->
it "still has the magic coat effect next turn", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Bounce")]
@p1.has(Attachment.MagicCoat).should.be.true
@team1.has(Attachment.MagicCoat).should.be.true
@battle.endTurn()
@p1.has(Attachment.MagicCoat).should.be.true
@team1.has(Attachment.MagicCoat).should.be.true
describe "Magic Guard", ->
it "takes no damage from anything that isn't a move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@p1.attach(Status.Burn)
@p1.currentHP.should.equal(@p1.stat('hp'))
@battle.endTurn()
@p1.currentHP.should.equal(@p1.stat('hp'))
it "takes damage from moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from Struggle", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@battle.performMove(@p1, @battle.getMove('Struggle'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from Belly Drum", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@battle.performMove(@p1, @battle.getMove('Belly Drum'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from confusion", ->
shared.create.call this,
team1: [Factory("<NAME>ikarp", ability: "Magic Guard")]
shared.biasRNG.call(this, 'next', 'confusion', 0)
@p1.attach(Attachment.Confusion)
@battle.performMove(@p1, @battle.getMove('Tackle'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from using Curse", ->
shared.create.call this,
team1: [Factory("Gengar", ability: "Magic Guard")]
@battle.performMove(@p1, @battle.getMove('Curse'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from Substitute", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@battle.performMove(@p1, @battle.getMove('Substitute'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from Pain Split", ->
shared.create.call this,
team1: [Factory("<NAME>ikarp", ability: "Magic Guard")]
@p1.currentHP = 1
@battle.performMove(@p1, @battle.getMove('Pain Split'))
@p1.currentHP.should.be.greaterThan(1)
it "takes damage from Counter", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard", moves: ["Counter"])]
@controller.makeMove(@id1, "Counter")
@controller.makeMove(@id2, "Tackle")
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "restores health from Leftovers", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard", item: "Leftovers")]
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.be.greaterThan(1)
it "receives no damage from Rocky Helmet", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1)
describe "Magnet Pull", ->
it "prevents Steel-type Pokemon from switching", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magnet Pull")]
team2: [Factory("Magnemite")]
@p2.isSwitchBlocked().should.be.true
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.true
it "doesn't prevent non-Steel-type Pokemon from switching", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magnet Pull")]
team2: [Factory("Magikarp")]
@p2.isSwitchBlocked().should.be.false
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.false
describe "Marvel Scale", ->
it "multiplies defense by 1.5 when statused", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Marvel Scale")]
defense = @p1.stat('defense')
@p1.attach(Status.Burn)
@p1.stat('defense').should.equal Math.floor(1.5 * defense)
describe "Minus", ->
it "multiplies special attack by 1.5 if on the field with Plus", ->
shared.create.call this,
numActive: 2
team1: [Factory("Magikarp"), Factory("Magikarp")]
team2: [Factory("Magikarp"), Factory("Magikarp")]
specialAttack = @p1.stat('specialAttack')
@team1.at(0).copyAbility(Ability.Minus)
@team1.at(1).copyAbility(Ability.Plus)
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.modifyAttack(@battle, @team1.at(0), @p2).should.equal(0x1800)
testAbilityCancelAbility = (name) ->
describe name, ->
it "emits a catchphrase when switching in or activating", ->
shared.create.call(this)
mock = @sandbox.mock(@battle).expects('cannedText').once()
@p1.copyAbility(Ability[name.replace(/\s+/, '')])
mock.verify()
it "cancels abilities for the duration of the user's move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
team2: [Factory("Magikarp", ability: "Levitate")]
eq = @battle.getMove("Earthquake")
mock = @sandbox.mock(eq).expects('hit').once()
@battle.performMove(@p1, eq)
mock.verify()
it "cancels modifier abilities for the duration of the user's move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
team2: [Factory("Magikarp", ability: "Thick Fat")]
ib = @battle.getMove("Ice Beam")
spy = @sandbox.spy(ib, 'modifyAttack')
spy = spy.withArgs(@battle, @p1, @p2)
@battle.performMove(@p1, ib)
spy.returnValues[0].should.equal(0x1000)
it "resets canceled abilities after the move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
team2: [Factory("Magikarp", ability: "Levitate")]
eq = @battle.getMove("Earthquake")
@p2.isAbilityBlocked().should.be.false
@battle.performMove(@p1, eq)
@p2.isAbilityBlocked().should.be.false
it "does not reset already-canceled abilities after performing move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
team2: [Factory("<NAME>", ability: "Levitate")]
@p2.blockAbility()
eq = @battle.getMove("Earthquake")
@p2.isAbilityBlocked().should.be.true
@battle.performMove(@p1, eq)
@p2.isAbilityBlocked().should.be.true
it "works when using field moves", ->
shared.create.call this,
team1: [Factory("Mag<NAME>", ability: name)]
sr = @battle.getMove("Stealth Rock")
(=> @battle.performMove(@p1, sr)).should.not.throw()
it "ignores Unaware", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: name)]
team2: [Factory("<NAME>", ability: "Unaware")]
@p1.boost(attack: 2)
spy = @sandbox.spy(@p1, "editBoosts").withArgs(sinon.match(ignoreOffense: false))
@battle.performMove(@p1, @battle.getMove("Outrage"))
spy.returned(sinon.match(attack: 2)).should.be.true
testAbilityCancelAbility("Mold Breaker")
testAbilityCancelAbility("Teravolt")
testAbilityCancelAbility("Turboblaze")
describe "Moody", ->
it "at turn end, randomly raise a stat by 2 and lower another by 1", ->
shared.create.call(this, team1: [Factory("<NAME>ik<NAME>", ability: "Moody")])
shared.biasRNG.call(this, "randInt", "moody raise", 1)
shared.biasRNG.call(this, "randInt", "moody lower", 0)
@battle.endTurn()
@p1.stages.should.containEql(attack: -1, defense: 2)
it "never raises and lowers the same stat in a single turn", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Moody")])
shared.biasRNG.call(this, "randInt", "moody raise", 0)
shared.biasRNG.call(this, "randInt", "moody lower", 0)
@battle.endTurn()
@p1.stages.should.containEql(attack: 2, defense: -1)
it "does not choose individual stats at max/min", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Moody")])
shared.biasRNG.call(this, "randInt", "moody raise", 1)
shared.biasRNG.call(this, "randInt", "moody lower", 0)
@p1.boost(defense: 6)
@p1.boost(attack: -6)
@battle.endTurn()
@p1.stages.should.containEql(defense: 5, speed: 2)
it "does not try to raise a null stat", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Moody")])
shared.biasRNG.call(this, "randInt", "moody raise", 1)
shared.biasRNG.call(this, "randInt", "moody lower", 0)
@p1.boost(attack: 6, defense: 6, speed: 6, specialAttack: 6)
@p1.boost(specialDefense: 6, accuracy: 6, evasion: 6)
(=> @battle.endTurn()).should.not.throw()
testTypeImmuneAbility = (name, type, stat) ->
describe name, ->
it "makes the user immune to #{type} moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
mock = @sandbox.mock(typedMove).expects('hit').never()
@battle.performMove(@p2, typedMove)
mock.verify()
it "increases #{stat} by 1 if hit by a #{type}-type move", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
@battle.performMove(@p2, typedMove)
@p1.stages[stat].should.equal(1)
it "increases #{stat} by only 1 even if move is multi-hit", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
@sandbox.stub(typedMove, 'calculateNumberOfHits', -> 2)
@battle.performMove(@p2, typedMove)
@p1.stages[stat].should.equal(1)
it "does not increase #{stat} by 1 if the user is the target", ->
shared.create.call(this, team1: [Factory("Magik<NAME>", ability: name)])
typedMove = _(@battle.MoveList).find (m) ->
m.target == 'user' && m.type == type
@battle.performMove(@p1, typedMove)
@p1.stages[stat].should.equal(0)
it "does nothing otherwise", ->
shared.create.call(this, team1: [Factory("<NAME>", ability: name)])
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type != type
mock = @sandbox.mock(typedMove).expects('hit').once()
@battle.performMove(@p2, typedMove)
@p1.stages[stat].should.equal(0)
mock.verify()
testTypeImmuneAbility("Motor Drive", "Electric", "speed")
testTypeImmuneAbility("Sap Sipper", "Grass", "attack")
describe "Moxie", ->
it "increases attack every time it faints another target", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Moxie")]
tackle = @battle.getMove("Tackle")
@p2.currentHP = 1
@p1.stages.should.containEql(attack: 0)
@battle.performMove(@p1, tackle)
@p1.stages.should.containEql(attack: 1)
describe "Multiscale", ->
it "takes half damage at full HP", ->
shared.create.call this,
team1: [Factory("Mag<NAME>", ability: "Multiscale")]
iceBeam = @battle.getMove("Ice Beam")
iceBeam.modifyDamage(@battle, @p2, @p1).should.equal(0x800)
it "takes normal damage at other HP", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Multiscale")]
iceBeam = @battle.getMove("Ice Beam")
@p1.currentHP -= 1
iceBeam.modifyDamage(@battle, @p2, @p1).should.equal(0x1000)
describe "Multitype", ->
it "changes Arceus forme for different plates"
describe "Mummy", ->
it "changes the attacker's ability to Mummy on contact", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Mummy")]
tackle = @battle.getMove("Tackle")
@p2.hasAbility("Mummy").should.be.false
@battle.performMove(@p2, tackle)
@p2.hasAbility("Mummy").should.be.true
it "doesn't change ability if move used isn't a contact move", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Mummy")]
iceBeam = @battle.getMove("Ice Beam")
@p2.hasAbility("Mummy").should.be.false
@battle.performMove(@p2, iceBeam)
@p2.hasAbility("Mummy").should.be.false
it "doesn't change ability if attacker has Multitype", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Mummy")]
team2: [Factory("Magikarp", ability: "Multitype")]
tackle = @battle.getMove("Tackle")
@p2.hasAbility("Mummy").should.be.false
@battle.performMove(@p2, tackle)
@p2.hasAbility("Mummy").should.be.false
it "works even if the defender faints", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Mummy"), Factory("Magikarp")]
@p1.currentHP = 1
tackle = @battle.getMove("Tackle")
@p2.hasAbility("Mummy").should.be.false
@battle.performMove(@p2, tackle)
@p2.hasAbility("Mummy").should.be.true
describe "Natural Cure", ->
it "cures status upon switch out", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Natural Cure")]
@p1.attach(Status.Burn)
@p1.switchOut(@battle)
@p1.hasStatus().should.be.false
describe "No Guard", ->
it "makes every move by this Pokemon never miss", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "No Guard")]
shared.biasRNG.call(this, 'randInt', 'miss', 101)
focusBlast = @battle.getMove("Focus Blast")
focusBlast.willMiss(@battle, @p1, @p2).should.be.false
it "makes every move against this Pokemon never miss", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "No Guard")]
shared.biasRNG.call(this, 'randInt', 'miss', 101)
focusBlast = @battle.getMove("Focus Blast")
focusBlast.willMiss(@battle, @p2, @p1).should.be.false
describe "Normalize", ->
it "makes every move act as if it were Normal type", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Normalize")]
team2: [Factory("<NAME>")]
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.typeEffectiveness(@battle, @p1, @p2).should.equal(1)
it "has no effect if target is self", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Normalize")]
team2: [Factory("<NAME>")]
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.typeEffectiveness(@battle, @p1, @p1).should.equal(2)
it "has no effect on struggle", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Normalize")]
team2: [Factory("<NAME>")]
struggle = @battle.getMove("Struggle")
struggle.typeEffectiveness(@battle, @p1, @p2).should.equal(1)
describe "Overcoat", ->
it "gives an immunity to adverse weather effects", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Overcoat")]
@p1.isWeatherDamageImmune(Weather.HAIL).should.be.true
@p1.isWeatherDamageImmune(Weather.SAND).should.be.true
describe "Pickpocket", ->
it "steals the item of an opponent that makes contact", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Pickpocket")]
team2: [Factory("<NAME>", item: "<NAME>")]
tackle = @battle.getMove("Tackle")
@battle.performMove(@p2, tackle)
@p1.hasItem("Leftovers").should.be.true
@p2.hasItem("Leftovers").should.be.false
describe "Plus", ->
it "multiplies special attack by 1.5 if on the field with Minus", ->
shared.create.call this,
numActive: 2
team1: [Factory("Magikarp"), Factory("Magik<NAME>")]
team2: [Factory("Magikarp"), Factory("Magikarp")]
specialAttack = @p1.stat('specialAttack')
@team1.at(0).copyAbility(Ability.Minus)
@team1.at(1).copyAbility(Ability.Plus)
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.modifyAttack(@battle, @team1.at(1), @p2).should.equal(0x1800)
describe "Poison Heal", ->
it "prevents normal poison damage", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Poison Heal")]
@p1.attach(Status.Poison)
@battle.endTurn()
@p1.currentHP.should.not.be.lessThan @p1.stat('hp')
@p1.cureStatus()
@p1.attach(Status.Toxic)
@battle.endTurn()
@p1.currentHP.should.not.be.lessThan @p1.stat('hp')
it "heals 1/8 HP end of turn while poisoned", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Poison Heal")]
@p1.attach(Status.Poison)
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 3))
it "heals 1/8 HP end of turn while toxiced", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Poison Heal")]
@p1.attach(Status.Toxic)
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 3))
describe "Prankster", ->
it "makes non-damaging moves have a priority (priority + 1)", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Prankster")]
spore = @battle.getMove("Spore")
tackle = @battle.getMove("Tackle")
action = {type: "move", move: spore, pokemon: @p1}
@battle.actionPriority(action).should.equal(spore.priority + 1)
action.move = tackle
@battle.actionPriority(action).should.equal(tackle.priority)
describe "Pressure", ->
it "reduces a move's PP further by 1 if targetted by foe's move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Pressure")]
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
pp = @p2.pp(tackle)
@battle.performMove(@p2, tackle)
@p2.pp(tackle).should.equal(pp - 2)
it "does not reduce a move's PP by 1 if target is self", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Pressure")]
dd = @battle.getMove("Dragon Dance")
@p1.moves = [ dd ]
@p1.resetAllPP()
pp = @p1.pp(dd)
@battle.performMove(@p1, dd)
@p1.pp(dd).should.equal(pp - 1)
describe "Quick Feet", ->
it "increases speed by x1.5 when statused", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Quick Feet")]
speed = @p1.stat('speed')
@p1.attach(Status.Sleep)
@p1.stat('speed').should.equal Math.floor(1.5 * speed)
it "negates speed drop from paralysis", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Quick Feet")]
speed = @p1.stat('speed')
@p1.attach(Status.Paralyze)
@p1.stat('speed').should.equal Math.floor(1.5 * speed)
describe "Rain Dish", ->
it "restores 1/16 HP at end of turn under Rain", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Rain Dish")]
@p1.currentHP = 1
@battle.setWeather(Weather.RAIN)
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 4))
it "does not restore HP at end of turn under non-Rain weather", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Rain Dish")]
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1)
describe "Rattled", ->
for type in ["Ghost", "Bug", "Dark"]
do (type) ->
it "raises speed by 1 when hit by a #{type} move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Rattled")]
typedMove = _(@battle.MoveList).find (m) ->
m.type == type
@p1.stages.speed.should.equal(0)
@battle.performMove(@p2, typedMove)
@p1.stages.speed.should.equal(1)
it "does not raise speed by 1 when hit by a non-damaging #{type} move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Rattled")]
typedMove = _(@battle.MoveList).find (m) ->
m.isNonDamaging() && m.type == type
@p1.stages.speed.should.equal(0)
@battle.performMove(@p2, typedMove)
@p1.stages.speed.should.equal(0)
it "does not raise speed by 1 when a #{type} move hits a substitute", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Rattled")]
typedMove = _(@battle.MoveList).find (m) ->
m.isNonDamaging() && m.type == type
@p1.attach(Attachment.Substitute, hp: 1)
@p1.stages.speed.should.equal(0)
@battle.performMove(@p2, typedMove)
@p1.stages.speed.should.equal(0)
describe "Reckless", ->
it "gives a 1.2x boost to recoil moves", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Reckless")]
recoilMoves = @battle.MoveList.filter (m) ->
m.recoil < 0
for move in recoilMoves
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1333)
it "boosts the kick moves", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Reckless")]
recoilMoves = [ @battle.getMove("Jump Kick"),
@battle.getMove("Hi Jump Kick") ]
for move in recoilMoves
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1333)
it "does not boost struggle", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Reckless")]
struggle = @battle.getMove("Struggle")
struggle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "does not boost drain moves", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Reckless")]
absorb = @battle.getMove("Absorb")
absorb.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
describe "Regenerator", ->
it "restores 1/3 of the user's HP upon switch out", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Regenerator")]
@p1.currentHP = 1
@p1.switchOut(@battle)
hp = Math.floor(@p1.stat('hp') / 3)
@p1.currentHP.should.equal(1 + hp)
describe "Rivalry", ->
it "reduces base power by 25% if user and target are opposite genders", ->
shared.create.call this,
team1: [Factory("<NAME>", gender: 'F', ability: "Rivalry")]
team2: [Factory("<NAME>", gender: 'M')]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0xC00)
it "increases base power by 25% if user and target are the same gender", ->
shared.create.call this,
team1: [Factory("<NAME>", gender: 'F', ability: "Rivalry")]
team2: [Factory("<NAME>", gender: 'F')]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1400)
it "has normal base power if either user or target have no gender", ->
shared.create.call this,
team1: [Factory("<NAME>", gender: 'F', ability: "Rivalry")]
team2: [Factory("<NAME>")]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
describe "Rock Head", ->
it "negates recoil", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Rock Head")]
@battle.performMove(@p1, @battle.getMove("Head Smash"))
@p1.currentHP.should.equal @p1.stat('hp')
describe "Sand Force", ->
it "increases BP of Ground-, Rock-, and Steel-type moves by 30% in sand", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sand Force")]
@battle.setWeather(Weather.SAND)
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
earthquake = @battle.getMove("Earthquake")
earthquake.modifyBasePower(@battle, @p1, @p2).should.equal(0x14CD)
rockSlide = @battle.getMove("Rock Slide")
rockSlide.modifyBasePower(@battle, @p1, @p2).should.equal(0x14CD)
meteorMash = @battle.getMove("Meteor Mash")
meteorMash.modifyBasePower(@battle, @p1, @p2).should.equal(0x14CD)
it "does not increase BP if weather is not sand", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Sand Force")]
@battle.setWeather(Weather.NONE)
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
earthquake = @battle.getMove("Earthquake")
earthquake.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
rockSlide = @battle.getMove("Rock Slide")
rockSlide.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
meteorMash = @battle.getMove("Meteor Mash")
meteorMash.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "grants immunity to sandstorm", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Sand Force")]
@p1.isWeatherDamageImmune(Weather.SAND).should.be.true
describe "Sand Veil", ->
it "increases evasion by 25% in Sand", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sand Veil")]
@battle.setWeather(Weather.SAND)
tackle = @battle.getMove("Tackle")
tackle.chanceToHit(@battle, @p2, @p1).should.equal(80)
it "does nothing outside of Sand", ->
shared.create.call this,
team1: [Factory("<NAME>ikarp", ability: "Sand Veil")]
tackle = @battle.getMove("Tackle")
tackle.chanceToHit(@battle, @p2, @p1).should.equal(100)
it "makes the user immune to Sand", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sand Veil")]
@p1.isWeatherDamageImmune(Weather.SAND).should.be.true
describe "Scrappy", ->
it "negates pokemon immunities", ->
shared.create.call this,
team1: [Factory("<NAME>ik<NAME>", ability: "Scrappy")]
team2: [Factory("<NAME>")]
tackle = @battle.getMove("Tackle")
closeCombat = @battle.getMove("Close Combat")
tackle.typeEffectiveness(@battle, @p1, @p2).should.equal(1)
closeCombat.typeEffectiveness(@battle, @p1, @p2).should.equal(.5)
mock1 = @sandbox.mock(tackle).expects('hit').once()
mock2 = @sandbox.mock(closeCombat).expects('hit').once()
@battle.performMove(@p1, tackle)
@battle.performMove(@p1, closeCombat)
mock1.verify()
mock2.verify()
describe "Serene Grace", ->
it "doubles the chance of secondary effects happening", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", "secondary effect", 10)
ember = @battle.getMove("Ember")
@sandbox.stub(ember, "baseDamage", -> 1)
@battle.performMove(@p1, ember)
@p2.has(Status.Burn).should.be.false
@p1.copyAbility(Ability.SereneGrace)
@battle.performMove(@p1, ember)
@p2.has(Status.Burn).should.be.true
it "doubles the chance of secondary boosts happening", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", "secondary boost", 10)
acid = @battle.getMove("Acid")
@sandbox.stub(acid, "baseDamage", -> 1)
@battle.performMove(@p1, acid)
@p2.stages.should.containEql(specialDefense: 0)
@p1.copyAbility(Ability.SereneGrace)
@battle.performMove(@p1, acid)
@p2.stages.should.containEql(specialDefense: -1)
it "doubles the chance of flinches happening", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", "flinch", 30)
ironHead = @battle.getMove("Iron Head")
@sandbox.stub(ironHead, "baseDamage", -> 1)
@battle.performMove(@p1, ironHead)
@p2.has(Attachment.Flinch).should.be.false
@p1.copyAbility(Ability.SereneGrace)
@battle.performMove(@p1, ironHead)
@p2.has(Attachment.Flinch).should.be.true
describe "Shadow Tag", ->
it "prevents foes from switching", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Shadow Tag")]
@p2.isSwitchBlocked().should.be.true
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.true
it "does not affect foes with Shadow Tag", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Shadow Tag")]
team2: [Factory("Magikarp", ability: "Shadow Tag")]
@p2.isSwitchBlocked().should.be.false
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.false
describe "Shed Skin", ->
it "has a 30% chance of removing its status effect at end of turn", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Shed Skin")]
shared.biasRNG.call(this, "randInt", "shed skin", 3)
@p1.attach(Status.Burn)
@battle.endTurn()
@p1.has(Status.Burn).should.be.false
it "has a 70% chance of doing nothing at end of turn", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Shed Skin")]
shared.biasRNG.call(this, "randInt", "shed skin", 4)
@p1.attach(Status.Burn)
@battle.endTurn()
@p1.has(Status.Burn).should.be.true
describe "Sheer Force", ->
it "raises power of moves with secondary effects by 30%", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force")]
ember = @battle.getMove("Ember")
ember.modifyBasePower(@battle, @p1, @p2).should.equal(0x14CD)
it "does not raise power of moves without secondary effects", ->
shared.create.call this,
team1: [Factory("<NAME>ikarp", ability: "Sheer Force")]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "nullifies secondary effects", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
shared.biasRNG.call(this, 'next', 'secondary effect', 0) # always happens
@battle.performMove(@p1, @battle.getMove("Zap Cannon"))
@p2.has(Status.Paralyze).should.be.false
it "nullifies flinch", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
shared.biasRNG.call(this, 'next', 'flinch', 0) # always happens
@battle.performMove(@p1, @battle.getMove("Iron Head"))
@p2.has(Attachment.Flinch).should.be.false
it "nullifies secondary boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
@battle.performMove(@p1, @battle.getMove("Charge Beam"))
@p1.stages.should.containEql(specialAttack: 0)
it "does not apply to primary boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
cc = @battle.getMove("Close Combat")
cc.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
@battle.performMove(@p1, cc)
@p1.stages.should.containEql(defense: -1, specialDefense: -1)
it "receives no life orb recoil", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
@battle.performMove(@p1, @battle.getMove("Ember"))
@p1.currentHP.should.not.be.lessThan @p1.stat('hp')
it "receives life orb recoil if no secondary effect", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
@battle.performMove(@p1, @battle.getMove("Tackle"))
@p1.currentHP.should.be.lessThan @p1.stat('hp')
it "does not activate Red Card", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force"), Factory("Magikarp")]
team2: [Factory("Magikarp", item: "Red Card"), Factory("Magikarp")]
@battle.performMove(@p1, @battle.getMove("Ember"))
@p1.should.equal @team1.first()
it "activates Red Card if no secondary effect", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force"), Factory("Magikarp")]
team2: [Factory("Magikarp", item: "Red Card"), Factory("Magikarp")]
@battle.performMove(@p1, @battle.getMove("Tackle"))
@p1.should.not.equal @team1.first()
it "does not activate Eject Button", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force"), Factory("Magikarp")]
team2: [Factory("Magikarp", item: "Eject Button"), Factory("Magikarp")]
@battle.recordMove(@id2, @battle.getMove("Tackle"))
should.not.exist @battle.requests[@id2]
@battle.performMove(@p1, @battle.getMove("Ember"))
should.not.exist @battle.requests[@id2]
it "activates Eject Button if no secondary effect", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force"), Factory("Magikarp")]
team2: [Factory("Magikarp", item: "Eject Button"), Factory("Magikarp")]
@battle.recordMove(@id2, @battle.getMove("Tackle"))
should.not.exist @battle.requests[@id2]
@battle.performMove(@p1, @battle.getMove("Tackle"))
@battle.requests[@id2].should.not.be.empty
it "does not activate Jaboca Berry?"
it "does not activate Rowap Berry?"
describe "Shield Dust", ->
it "prevents secondary effects", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Shield Dust")]
shared.biasRNG.call(this, 'next', 'secondary effect', 0) # always happens
@battle.performMove(@p1, @battle.getMove("Zap Cannon"))
@p2.has(Status.Paralyze).should.be.false
it "prevents secondary flinches", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Shield Dust")]
shared.biasRNG.call(this, 'randInt', 'flinch', 0) # 100% chance
@battle.performMove(@p1, @battle.getMove("Iron Head"))
@p2.has(Attachment.Flinch).should.be.false
it "prevents secondary boosts against the target", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Shield Dust")]
@battle.performMove(@p1, @battle.getMove("Acid Spray"))
@p2.stages.should.containEql(specialDefense: 0)
it "does not prevent secondary boosts for the user", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Shield Dust")]
@battle.performMove(@p1, @battle.getMove("Flame Charge"))
@p1.stages.should.containEql(speed: 1)
describe "Simple", ->
it "doubles stat boosts, negative and positive", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Simple")])
@battle.performMove(@p1, @battle.getMove("Curse"))
@p1.stages.should.containEql(attack: 2, defense: 2, speed: -2)
describe "Slow Start", ->
it "halves attack and speed", ->
shared.create.call(this)
speed = @p1.stat('speed')
@p1.copyAbility(Ability.SlowStart)
tackle = @battle.getMove("Tackle")
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x800)
flamethrower = @battle.getMove("Flamethrower")
flamethrower.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
@p1.stat('speed').should.equal(speed >> 1)
it "returns attack and speed to normal after five turns", ->
shared.create.call(this)
tackle = @battle.getMove("Tackle")
flamethrower = @battle.getMove("Flamethrower")
speed = @p1.stat('speed')
@p1.copyAbility(Ability.SlowStart)
for x in [0...5]
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x800)
flamethrower.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
@p1.stat('speed').should.equal(speed >> 1)
@battle.endTurn()
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
flamethrower.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
@p1.stat('speed').should.equal(speed)
describe "Sniper", ->
it "multiplies damage by a further x1.5 if critting", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sniper")]
tackle = @battle.getMove("Tackle")
@p1.crit = true
tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1800)
it "has a normal 1x multiplier if not critting", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sniper")]
tackle = @battle.getMove("Tackle")
@p1.crit = false
tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000)
describe "Snow Cloak", ->
it "increases evasion by 25% in hail", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Snow Cloak")]
@battle.setWeather(Weather.HAIL)
tackle = @battle.getMove("Tackle")
tackle.chanceToHit(@battle, @p2, @p1).should.equal(80)
it "does nothing outside of hail", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Snow Cloak")]
tackle = @battle.getMove("Tackle")
tackle.chanceToHit(@battle, @p2, @p1).should.equal(100)
it "makes the user immune to hail", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Snow Cloak")]
@p1.isWeatherDamageImmune(Weather.HAIL).should.be.true
describe "Solar Power", ->
it "increases special attack by 50% in Sun", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Solar Power")]
@battle.setWeather(Weather.SUN)
tackle = @battle.getMove("Tackle")
fireBlast = @battle.getMove("Fire Blast")
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
fireBlast.modifyAttack(@battle, @p1, @p2).should.equal(0x1800)
it "owner loses 1/8 max HP per end of turn", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Solar Power")]
@battle.setWeather(Weather.SUN)
@battle.endTurn()
@p1.currentHP.should.equal(@p1.stat('hp') - (@p1.stat('hp') >> 3))
it "does nothing if the weather is not Sun", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Solar Power")]
fireBlast = @battle.getMove("Fire Blast")
fireBlast.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
@battle.endTurn()
@p1.currentHP.should.equal(@p1.stat('hp'))
it "deals a minimum of 1 damage", ->
shared.create.call this,
team1: [Factory("Shedinja", ability: "Solar Power")]
@battle.setWeather(Weather.SUN)
@battle.endTurn()
@p1.currentHP.should.equal(0)
describe "Soundproof", ->
it "makes user immune to sound moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Soundproof")]
bugBuzz = @battle.getMove('Bug Buzz')
perishSong = @battle.getMove('Perish Song')
@p1.isImmune(bugBuzz.type, move: bugBuzz).should.be.true
@p1.isImmune(perishSong.type, move: perishSong).should.be.true
describe "Speed Boost", ->
it "boosts speed at the end of every turn", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Speed Boost")]
@p1.stages.should.containEql(speed: 0)
@battle.endTurn()
@p1.stages.should.containEql(speed: 1)
@battle.endTurn()
@p1.stages.should.containEql(speed: 2)
it "boosts speed the turn after a pokemon is freshly switched in", ->
shared.create.call this,
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Speed Boost")]
@battle.performSwitch(@p1, 1)
@team1.first().stages.should.containEql(speed: 0)
@battle.endTurn()
@team1.first().stages.should.containEql(speed: 0)
@battle.endTurn()
@team1.first().stages.should.containEql(speed: 1)
@battle.endTurn()
@team1.first().stages.should.containEql(speed: 2)
it "boosts speed the turn after a pokemon is replaced", ->
shared.create.call this,
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Speed Boost")]
@p1.currentHP = 1
@controller.makeMove(@id1, "Tackle")
@controller.makeMove(@id2, "Tackle")
@controller.makeSwitch(@id1, 1)
@battle.turn.should.equal(2)
@team1.first().stages.should.containEql(speed: 0)
@battle.endTurn()
@team1.first().stages.should.containEql(speed: 1)
@battle.endTurn()
@team1.first().stages.should.containEql(speed: 2)
describe "Sticky Hold", ->
it "prevents items from being taken", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Leftovers", ability: "Sticky Hold")]
@battle.performMove(@p2, @battle.getMove("Trick"))
@p1.hasItem("Leftovers").should.be.true
@p2.hasItem().should.be.false
it "does not prevent the user from using Trick", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Leftovers", ability: "Sticky Hold")]
@battle.performMove(@p1, @battle.getMove("Trick"))
@p1.hasItem().should.be.false
@p2.hasItem("Leftovers").should.be.true
describe "Stall", ->
it "forces the user to move last no matter what", ->
shared.create.call this,
team1: [Factory("Magikarp", evs: {speed: 4}, ability: "Stall")]
team2: [Factory("Magikarp")]
splash = @battle.getMove("Splash")
@battle.recordMove(@id1, splash)
@battle.recordMove(@id2, splash)
@battle.determineTurnOrder()
pokemon = @battle.pokemonActions.map((o) -> o.pokemon)
pokemon.should.eql [ @p2, @p1 ]
it "moves before pokemon with lagging tail/full incense", ->
shared.create.call this,
team1: [Factory("Magikarp", evs: {speed: 4}, ability: "Stall")]
team2: [Factory("Magikarp", item: "Lagging Tail")]
splash = @battle.getMove("Splash")
@battle.recordMove(@id1, splash)
@battle.recordMove(@id2, splash)
@battle.determineTurnOrder()
pokemon = @battle.pokemonActions.map((o) -> o.pokemon)
pokemon.should.eql [ @p1, @p2 ]
describe "Steadfast", ->
it "raises speed if the Pokemon flinches", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Steadfast")]
tackle = @battle.getMove("Tackle")
@p1.attach(Attachment.Flinch)
@p1.beforeMove(tackle, @p1, [ @p2 ])
@p1.stages.should.containEql(speed: 1)
describe "Sturdy", ->
it "prevents the user from being OHKOed at full HP", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sturdy")]
ember = @battle.getMove('Ember')
stub = @sandbox.stub(ember, 'calculateDamage', -> 9999)
@battle.performMove(@p2, ember)
@p1.currentHP.should.equal(1)
it "lets the user be KOed if not at full HP", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sturdy")]
@p1.currentHP -= 1
ember = @battle.getMove('Ember')
stub = @sandbox.stub(ember, 'calculateDamage', -> 9999)
@battle.performMove(@p2, ember)
@p1.currentHP.should.equal(0)
describe "Suction Cups", ->
it "prevents user from being phased", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Suction Cups"), Factory("Magikarp")]
whirlwind = @battle.getMove('Whirlwind')
mock = @sandbox.mock(@team1).expects('switch').never()
@battle.performMove(@p2, whirlwind)
mock.verify()
describe "Super Luck", ->
it "adds +2 to critical hit level", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Super Luck")]
tackle = @battle.getMove("Tackle")
tackle.criticalHitLevel(@battle, @p1, @p2).should.equal(2)
describe "Synchronize", ->
it "afflicts the source of a status with the same status", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Synchronize")]
@p1.attach(Status.Paralyze, source: @p2)
@p2.has(Status.Paralyze).should.be.true
it "doesn't attempt to afflict target if target is self", ->
shared.create.call this,
team1: [Factory("Magik<NAME>", ability: "Synchronize")]
spy = @sandbox.spy(Status.Burn, 'preattach')
@p1.attach(Status.Burn, source: @p1)
spy.returned(false).should.be.true
it "activates on primary status moves", ->
shared.create.call this,
team1: [Factory("Magik<NAME>", ability: "Synchronize")]
@battle.performMove(@p2, @battle.getMove("Will-O-Wisp"))
@p2.has(Status.Burn).should.be.true
it "doesn't activate on Sleep", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Synchronize")]
@p1.attach(Status.Sleep, source: @p2)
@p2.has(Status.Sleep).should.be.false
it "doesn't activate on Freeze", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Synchronize")]
@p1.attach(Status.Freeze, source: @p2)
@p2.has(Status.Freeze).should.be.false
it "activates on secondary effects", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Synchronize")]
shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance
@battle.performMove(@p2, @battle.getMove("Flamethrower"))
@p2.has(Status.Burn).should.be.true
describe "Tangled Feet", ->
it "doubles evasion rate when confused", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Tangled Feet")]
tackle = @battle.getMove("Tackle")
tackle.chanceToHit(@battle, @p2, @p1).should.equal(100)
@p1.attach(Attachment.Confusion)
tackle.chanceToHit(@battle, @p2, @p1).should.equal(50)
@p1.unattach(Attachment.Confusion)
tackle.chanceToHit(@battle, @p2, @p1).should.equal(100)
describe "Technician", ->
it "increases base power of moves with BP <= 60 by x1.5", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Technician")]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1800)
it "leaves moves with BP > 60 alone", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Technician")]
iceBeam = @battle.getMove("Ice Beam")
iceBeam.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
describe "Telepathy", ->
it "cancels damaging attacks from an ally", ->
shared.create.call this,
numActive: 2
team1: [Factory("<NAME>"), Factory("Magikarp", ability: "Telepathy")]
team2: (Factory("<NAME>ik<NAME>") for x in [1..2])
earthquake = @battle.getMove("Earthquake")
mock = @sandbox.mock(earthquake).expects('hit').exactly(2)
@battle.performMove(@p1, earthquake)
@team1.at(1).currentHP.should.equal(@team1.at(1).stat('hp'))
mock.verify()
describe "Thick Fat", ->
it "halves the base power of Fire and Ice moves", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Thick Fat")]
iceBeam = @battle.getMove("Ice Beam")
iceBeam.modifyAttack(@battle, @p2, @p1).should.equal(0x800)
flamethrower = @battle.getMove("Flamethrower")
flamethrower.modifyAttack(@battle, @p2, @p1).should.equal(0x800)
it "doesn't change base power of other moves", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Thick Fat")]
tackle = @battle.getMove("Tackle")
tackle.modifyAttack(@battle, @p2, @p1).should.equal(0x1000)
describe "Tinted Lens", ->
it "doubles damage when using a not-very-effective move", ->
shared.create.call this,
team1: [Factory("<NAME>", ability: "Tinted Lens")]
team2: [Factory("<NAME>")]
surf = @battle.getMove("Surf")
surf.modifyDamage(@battle, @p1, @p2).should.equal(0x2000)
it "doesn't double damage otherwise", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Tinted Lens")]
team2: [Factory("Magikarp")]
tackle = @battle.getMove("Tackle")
tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000)
describe "Trace", ->
it "copies a random foe's ability on switch-in", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Trace")]
team2: [Factory("Magikarp", ability: "Truant")]
@p1.hasAbility("Truant").should.be.true
it "does not copy certain abilities", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Trace")]
team2: [Factory("Magikarp", ability: "Forecast")]
@p1.hasAbility("Forecast").should.be.false
it "does not crash if there are no opponents", ->
shared.create.call this,
team1: [Factory("Magikarp")]
team2: [Factory("Magikarp"), Factory("Magikarp")]
@p2.faint()
(=>
@p1.copyAbility(Ability.Trace)
).should.not.throw()
it "traces another ability upon switching out and back in", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Trace"), Factory("Magikarp")]
team2: [Factory("Magikarp", ability: "Intimidate")
Factory("Magikarp", ability: "Magic Bounce")]
@p1.hasAbility("Intimidate").should.be.true
@battle.performSwitch(@p2, 1)
@battle.performSwitch(@p1, 1)
@battle.performSwitch(@team1.first(), 1)
@p1.hasAbility("Magic Bounce").should.be.true
describe "Truant", ->
it "prevents the user from attacking every other turn", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Truant")]
splash = @battle.getMove("Splash")
mock = @sandbox.mock(splash).expects('execute').once()
@battle.performMove(@p1, splash)
mock.verify()
splash.execute.restore()
mock = @sandbox.mock(splash).expects('execute').never()
@battle.performMove(@p1, splash)
mock.verify()
splash.execute.restore()
mock = @sandbox.mock(splash).expects('execute').once()
@battle.performMove(@p1, splash)
mock.verify()
splash.execute.restore()
describe "Unaware", ->
it "ignores attackers' attack and special attack boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unaware")]
@p2.boost(attack: 1, specialAttack: 2)
spy = @sandbox.spy(@p2, "editBoosts")
@battle.performMove(@p2, @battle.getMove("Tackle"))
spy.returned(sinon.match(attack: 0, specialAttack: 0)).should.be.true
it "ignores defenders' defense and special defense boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unaware")]
@p2.boost(defense: 1, specialDefense: 2)
spy = @sandbox.spy(@p2, "editBoosts")
@battle.performMove(@p1, @battle.getMove("Tackle"))
spy.returned(sinon.match(defense: 0, specialDefense: 0)).should.be.true
it "ignores attackers' accuracy boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unaware")]
@p2.boost(accuracy: 3)
spy = @sandbox.spy(@p2, "editBoosts")
@battle.getMove("Tackle").chanceToHit(@battle, @p2, @p1)
spy.returned(sinon.match(accuracy: 0)).should.be.true
it "ignores defenders' evasion boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unaware")]
@p2.boost(evasion: 3)
spy = @sandbox.spy(@p2, "editBoosts")
@battle.getMove("Tackle").chanceToHit(@battle, @p1, @p2)
spy.returned(sinon.match(evasion: 0)).should.be.true
describe "Unburden", ->
it "doubles its speed when the owner's item is removed", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Unburden")]
speed = @p1.stat('speed')
@p1.removeItem()
@p1.stat('speed').should.equal(2 * speed)
it "activates when its item is swapped for no item", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Unburden")]
speed = @p1.stat('speed')
trick = @battle.getMove("Trick")
@battle.performMove(@p2, trick)
@p1.stat('speed').should.equal(2 * speed)
it "does not activate when its item is swapped for another item", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Unburden")]
team2: [Factory("Magikarp", item: "Water Gem")]
speed = @p1.stat('speed')
trick = @battle.getMove("Trick")
@battle.performMove(@p2, trick)
@p1.stat('speed').should.equal(speed)
@p1.has(Attachment.Unburden).should.be.false
it "deactivates if it gains another item", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Unburden")]
team2: [Factory("Magikarp", item: "Water Gem")]
speed = @p1.stat('speed')
@p1.removeItem()
@p1.stat('speed').should.equal(2 * speed)
trick = @battle.getMove("Trick")
@battle.performMove(@p2, trick)
@p1.stat('speed').should.equal(speed)
@p1.has(Attachment.Unburden).should.be.false
it "deactivates if it loses this Ability", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Unburden")]
team2: [Factory("Magikarp", ability: "Run Away")]
speed = @p1.stat('speed')
@p1.removeItem()
@p1.stat('speed').should.equal(2 * speed)
rolePlay = @battle.getMove("Role Play")
@battle.performMove(@p1, rolePlay)
@p1.stat('speed').should.equal(speed)
@p1.has(Attachment.Unburden).should.be.false
describe "Unnerve", ->
it "prevents held berries from being eaten", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unnerve")]
team2: [Factory("Magikarp", item: "<NAME>")]
@p2.currentHP = 1
@p2.update()
@p2.stages.should.containEql(speed: 0)
@battle.beginTurn()
@p2.update()
@p2.stages.should.containEql(speed: 0)
it "does not prevent regular item usage", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unnerve")]
team2: [Factory("Magikarp", item: "Leftovers")]
@p2.currentHP = 1
@battle.endTurn()
@p2.currentHP.should.be.greaterThan(1)
it "does not prevent Bug Bite, Pluck, etc. from working", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "<NAME>", ability: "Unnerve")]
@battle.performMove(@p2, @battle.getMove("Bug Bite"))
@p2.stages.should.containEql(speed: 1)
describe "Victory Star", ->
it "increases accuracy of moves by 10%", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Victory Star")]
willOWisp = @battle.getMove("Will-O-Wisp")
accuracy = willOWisp.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal Math.floor(willOWisp.accuracy * 1.1)
it "increases accuracy of ally moves by 10%"
testTypeAbsorbMove = (name, type) ->
describe name, ->
it "is immune to #{type}-type moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
m.type == type
mock = @sandbox.mock(typedMove).expects('hit').never()
@battle.performMove(@p2, typedMove)
mock.verify()
it "heals 25% HP from #{type}-type moves", ->
shared.create.call this,
team1: [Factory("Magik<NAME>", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
m.type == type
@p1.currentHP = 1
@battle.performMove(@p2, typedMove)
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 2))
it "does not activate for the user's moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
m.target == 'user' && m.type == type
@p1.currentHP = 1
@battle.performMove(@p1, typedMove)
@p1.currentHP.should.equal(1)
testTypeAbsorbMove("Water Absorb", "Water")
testTypeAbsorbMove("Volt Absorb", "Electric")
describe "Weak Armor", ->
it "lowers defense and raises speed on physical attacks", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Weak Armor")]
tackle = @battle.getMove("Tackle")
@battle.performMove(@p2, tackle)
@p1.stages.should.containEql(defense: -1, speed: 1)
it "does nothing on any other kind of move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Weak Armor")]
willOWisp = @battle.getMove("Will-O-Wisp")
@battle.performMove(@p2, willOWisp)
@p1.stages.should.containEql(defense: 0, speed: 0)
describe "Wonder Guard", ->
it "renders the Pokemon immune to non-super-effective moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Wonder Guard")]
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').never()
@battle.performMove(@p2, tackle)
mock.verify()
it "is not immune to struggle", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Wonder Guard")]
struggle = @battle.getMove("Struggle")
mock = @sandbox.mock(struggle).expects('hit').once()
@battle.performMove(@p2, struggle)
mock.verify()
it "is not immune to non-damaging moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Wonder Guard")]
willOWisp = @battle.getMove("Will-O-Wisp")
mock = @sandbox.mock(willOWisp).expects('hit').once()
@battle.performMove(@p2, willOWisp)
mock.verify()
it "is not immune to super-effective moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Wonder Guard")]
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == 'Electric'
mock = @sandbox.mock(typedMove).expects('hit').once()
@battle.performMove(@p2, typedMove)
mock.verify()
describe "Wonder Skin", ->
it "makes non-damaging moves with over 50% accuracy have 50% accuracy", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Wonder Skin")]
trick = @battle.getMove("Trick")
accuracy = trick.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal 50
it "adjusts accuracy before any other modifiers take effect", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Compoundeyes")]
team2: [Factory("Magikarp", ability: "Wonder Skin")]
willOWisp = @battle.getMove("Will-O-Wisp")
accuracy = willOWisp.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal Math.floor(50 * 1.3)
it "does nothing to non-damaging moves that don't check accuracy", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Wonder Skin")]
meanLook = @battle.getMove("Mean Look")
accuracy = meanLook.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal 0
it "does nothing to non-damaging moves with under 50% accuracy", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Wonder Skin")]
trick = @battle.getMove("Trick")
trick.accuracy = 40
accuracy = trick.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal 40
describe "Zen Mode", ->
it "changes Darmanitan's forme when going under or above 50% HP"
| true | require '../helpers'
{Attachment, Status} = require('../../server/bw/attachment')
{Battle} = require('../../server/bw/battle')
{Pokemon} = require('../../server/bw/pokemon')
{Weather} = require('../../shared/weather')
{Item} = require('../../server/bw/data/items')
{Ability} = require '../../server/bw/data/abilities'
util = require '../../server/bw/util'
{Factory} = require '../factory'
should = require 'should'
sinon = require 'sinon'
{_} = require 'underscore'
shared = require '../shared'
describe "BW Abilities:", ->
describe "Adaptability", ->
it "makes STAB 2x instead of 1.5", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Adaptability")]
hydroPump = @battle.getMove("Hydro Pump")
hydroPump.stabModifier(@battle, @p1, @p2).should.equal(0x2000)
it "still has 1x if the pokemon does not have STAB", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Adaptability")]
tackle = @battle.getMove("Tackle")
tackle.stabModifier(@battle, @p1, @p2).should.equal(0x1000)
describe "Aftermath", ->
it "deals 25% HP damage to the killer", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Aftermath"), Factory("Magikarp")]
@p1.currentHP = 1
@battle.performMove(@p2, @battle.getMove("Tackle"))
@battle.performFaints()
(@p2.stat('hp') - @p2.currentHP).should.equal(@p2.stat('hp') >> 2)
it "does not deal damage for non-contact moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Aftermath"), Factory("Magikarp")]
@p1.currentHP = 1
@battle.performMove(@p2, @battle.getMove("Thunderbolt"))
@battle.performFaints()
@p2.currentHP.should.equal(@p2.stat('hp'))
it "does not deal damage if pokemon died of natural causes", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Aftermath"), Factory("Magikarp")]
thunderbolt = @battle.getMove("Thunderbolt")
@p1.currentHP = 2
@p1.attach(Status.Burn)
@sandbox.stub(thunderbolt, 'calculateDamage', -> 1)
@battle.performMove(@p2, thunderbolt)
@battle.endTurn()
@p2.currentHP.should.equal(@p2.stat('hp'))
it "does not crash if the Pokemon never was hit", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Aftermath"), Factory("Magikarp")]
(=> @p1.faint()).should.not.throw()
it "deals a minimum of 1 damage", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Aftermath"), Factory("Magikarp")]
team2: [Factory("SPI:NAME:<NAME>END_PIinja")]
@p1.currentHP = 2
@battle.performMove(@p2, @battle.getMove("Tackle"))
@battle.performFaints()
@p2.currentHP.should.equal(0)
testWeatherPreventionAbility = (name) ->
describe name, ->
it "causes the battle to think there is no weather", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
@battle.setWeather(Weather.SAND)
@battle.hasWeather(Weather.SAND).should.be.false
@battle.setWeather(Weather.SUN)
@battle.hasWeather(Weather.SUN).should.be.false
testWeatherPreventionAbility("Air Lock")
testWeatherPreventionAbility("Cloud Nine")
describe "Analytic", ->
it "multiplies attacks by 1.3 if no one is moving afterward", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Analytic")]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x14CD)
it "doesn't multiply if the user isn't the last to move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Analytic")]
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
describe "Anger Point", ->
it "maximizes Attack on critical hit", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Anger Point")]
tackle = @battle.getMove("Tackle")
@sandbox.stub(tackle, 'isCriticalHit', -> true)
@p1.stages.attack.should.equal(0)
@battle.performMove(@p2, tackle)
@p1.stages.should.containEql(attack: 6)
it "doesn't maximize attack on non-critical hits", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Anger Point")]
tackle = @battle.getMove("Tackle")
@sandbox.stub(tackle, 'isCriticalHit', -> false)
@p1.stages.attack.should.equal(0)
@battle.performMove(@p2, tackle)
@p1.stages.should.containEql(attack: 0)
describe "Anticipation", ->
it "shows a message if an opponent has a super-effective move", ->
shared.create.call this,
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Anticipation")]
team2: [Factory("Pikachu", moves: ["Thunderbolt"])]
spy = @sandbox.spy(@battle, 'cannedText')
@battle.performSwitch(@p1, 1)
spy.calledWithMatch('ANTICIPATION').should.be.true
it "shows a message if an opponent has an OHKO move", ->
shared.create.call this,
team1: [Factory("Magikarp"), Factory("PI:NAME:<NAME>END_PI", ability: "Anticipation")]
team2: [Factory("PI:NAME:<NAME>END_PI", moves: ["Sheer Cold"])]
spy = @sandbox.spy(@battle, 'cannedText')
@battle.performSwitch(@p1, 1)
spy.calledWithMatch('ANTICIPATION').should.be.true
it "doesn't show a message otherwise", ->
shared.create.call this,
team1: [Factory("MagPI:NAME:<NAME>END_PI"), Factory("Magikarp", ability: "Anticipation")]
spy = @sandbox.spy(@battle, 'cannedText')
@battle.performSwitch(@p1, 1)
spy.calledWithMatch('ANTICIPATION').should.be.false
it "displays nothing when no opponents left", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI")]
team2: [Factory("PI:NAME:<NAME>END_PI"), Factory("PI:NAME:<NAME>END_PIikarp")]
@p2.faint()
spy = @sandbox.spy(@battle, 'cannedText')
@p1.copyAbility(Ability.Anticipation)
spy.called.should.be.false
describe "Arena Trap", ->
it "blocks switch", ->
shared.create.call this,
team1: [Factory("MagPI:NAME:<NAME>END_PI", ability: "Arena Trap")]
team2: [Factory("PI:NAME:<NAME>END_PI")]
@p2.isSwitchBlocked().should.be.true
it "blocks switch the next turn as well", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Arena Trap")]
team2: [Factory("PI:NAME:<NAME>END_PI")]
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.true
it "doesn't block switch for Flying Pokemon", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Arena Trap")]
team2: [Factory("GPI:NAME:<NAME>END_PI")]
@p2.isSwitchBlocked().should.be.false
it "doesn't block switch for Pokemon immune to Ground by other means", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Arena Trap")]
team2: [Factory("PI:NAME:<NAME>END_PI")]
@battle.performMove(@p2, @battle.getMove("Magnet Rise"))
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.false
describe "Bad Dreams", ->
it "deals 1/8 max HP end of turn if target is asleep", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Bad Dreams")]
team2: [Factory("Celebi")]
(@p2.stat('hp') - @p2.currentHP).should.equal(0)
@p2.attach(Status.Sleep)
@battle.endTurn()
(@p2.stat('hp') - @p2.currentHP).should.equal(@p2.stat('hp') >> 3)
it "deals no damage if target is awake", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Bad Dreams")]
team2: [Factory("Celebi")]
(@p2.stat('hp') - @p2.currentHP).should.equal(0)
@battle.endTurn()
(@p2.stat('hp') - @p2.currentHP).should.equal(0)
it "deals a minimum of 1 damage", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Bad Dreams")]
team2: [Factory("PI:NAME:<NAME>END_PI")]
@p2.attach(Status.Sleep)
@battle.endTurn()
@p2.currentHP.should.equal(0)
testCriticalHitPreventionAbility = (name) ->
describe name, ->
it "prevents critical hits", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI")]
team2: [Factory("CPI:NAME:<NAME>END_PIbi", ability: name)]
shared.biasRNG.call(this, "next", "ch", .2)
tackle = @battle.getMove("Tackle")
@sandbox.stub(tackle, 'criticalHitLevel', -> 3)
tackle.isCriticalHit(@battle, @p1, @p2).should.be.false
testCriticalHitPreventionAbility("Battle Armor")
testCriticalHitPreventionAbility("Shell Armor")
testBoostProtectionAbility = (name, protection) ->
describe name, ->
allBoosts = [ "attack", "defense", "speed", "specialAttack",
"specialDefense", "accuracy", "evasion" ]
protection ||= allBoosts
it "protects against certain stat falls", ->
shared.create.call this, team1: [Factory("Celebi", ability: name)]
boosts = {}
boosts[stat] = -1 for stat in allBoosts
@p1.boost(boosts, @p2)
boosts[stat] = 0 for stat in protection
@p1.stages.should.eql(boosts)
it "does not protect against stat falls if the source is the user", ->
shared.create.call this, team1: [Factory("Celebi", ability: name)]
boosts = {}
boosts[stat] = -1 for stat in allBoosts
@p1.boost(boosts)
@p1.stages.should.containEql(boosts)
testBoostProtectionAbility("Big Pecks", [ "defense" ])
testBoostProtectionAbility("Clear Body")
testBoostProtectionAbility("Hyper Cutter", [ "attack" ])
testBoostProtectionAbility("Keen Eye", [ "accuracy" ])
testBoostProtectionAbility("White Smoke")
testLowHealthAbility = (name, type) ->
describe name, ->
it "increases power of #{type} moves by 1.5 at 1/3 health", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
@p1.currentHP = Math.floor(@p1.stat('hp') / 3)
move = _(@battle.MoveList).find (m) ->
m.type == type && !m.isNonDamaging()
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1800)
it "doesn't increase power if move not of #{type}", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
@p1.currentHP = Math.floor(@p1.stat('hp') / 3)
move = _(@battle.MoveList).find (m) ->
m.type != type && !m.isNonDamaging()
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "doesn't increase power if user isn't under 1/3 health", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
@p1.currentHP = Math.floor(@p1.stat('hp') / 3) + 1
move = _(@battle.MoveList).find (m) ->
m.type == type && !m.isNonDamaging()
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
testLowHealthAbility("Blaze", "Fire")
testLowHealthAbility("Torrent", "Water")
testLowHealthAbility("Overgrow", "Grass")
testLowHealthAbility("Swarm", "Bug")
testWeatherSpeedAbility = (name, weather) ->
describe name, ->
it "doubles speed when the weather becomes #{weather}", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
speed = @p1.stat('speed')
@battle.setWeather(weather)
@p1.stat('speed').should.equal(2 * speed)
it "goes back to normal when the weather becomes something else", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
speed = @p1.stat('speed')
@battle.setWeather(weather)
@battle.setWeather(Weather.NONE)
@p1.stat('speed').should.equal(speed)
it "grants immunity to damage from their respective weather", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
@p1.isWeatherDamageImmune(weather).should.be.true
testWeatherSpeedAbility("Chlorophyll", Weather.SUN)
testWeatherSpeedAbility("Swift Swim", Weather.RAIN)
testWeatherSpeedAbility("Sand Rush", Weather.SAND)
describe "Color Change", ->
it "changes the owner's type to be the move's type that just hit it", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Color Change")]
ember = @battle.getMove("Ember")
@p1.hasType(ember.type).should.be.false
@battle.performMove(@p2, ember)
@p1.hasType(ember.type).should.be.true
it "does not change the owner's type if the move is non-damaging", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Color Change")]
willOWisp = @battle.getMove("Will-O-Wisp")
@p1.hasType(willOWisp.type).should.be.false
@battle.performMove(@p2, willOWisp)
@p1.hasType(willOWisp.type).should.be.false
describe "Compoundeyes", ->
it "increases accuracy of moves by 1.3x", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Compoundeyes")]
willOWisp = @battle.getMove("Will-O-Wisp")
accuracy = willOWisp.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal Math.floor(willOWisp.accuracy * 1.3)
describe "Contrary", ->
it "reverses stat changes from all sources", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Contrary")]
leafStorm = @battle.getMove("Leaf Storm")
growl = @battle.getMove("Growl")
@battle.performMove(@p1, leafStorm)
@p1.stages.should.containEql(specialAttack: 2)
@battle.performMove(@p2, growl)
@p1.stages.should.containEql(attack: 1)
describe "Cursed Body", ->
it "has a 30% chance to disable an attacker's last move", ->
shared.create.call this,
team1: [Factory("MagPI:NAME:<NAME>END_PI", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 0)
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.true
it "does not disable the owner", ->
shared.create.call this,
team1: [Factory("MagikPI:NAME:<NAME>END_PI", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 0)
recover = @battle.getMove("Recover")
@p1.moves = [ recover ]
@p1.resetAllPP()
@p1.currentHP = 1
@battle.performMove(@p1, recover)
@p1.isMoveBlocked(recover).should.be.false
it "does not disable if attacker is behind a substitute", ->
shared.create.call this,
team1: [Factory("MagPI:NAME:<NAME>END_PI", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 0)
tackle = @battle.getMove("Tackle")
substitute = @battle.getMove("Substitute")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, substitute)
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.false
it "does not disable if defender is behind a substitute", ->
shared.create.call this,
team1: [Factory("MagikPI:NAME:<NAME>END_PI", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 0)
tackle = @battle.getMove("Tackle")
substitute = @battle.getMove("Substitute")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p1, substitute)
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.false
it "has a 70% chance to do nothing", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", .3)
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.false
it "can work even if the defender faints", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Cursed Body"), Factory("Magikarp")]
shared.biasRNG.call(this, "next", "cursed body", 0)
@p1.currentHP = 1
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.true
it "lasts some turns", ->
shared.create.call this,
team1: [Factory("MagPI:NAME:<NAME>END_PI", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 0)
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, tackle)
for x in [1..2]
@battle.endTurn()
@battle.beginTurn()
@p2.isMoveBlocked(tackle).should.be.true
it "cannot stack with Disable", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Cursed Body")]
shared.biasRNG.call(this, "next", "cursed body", 1) # do not trigger
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
@battle.performMove(@p2, tackle)
@battle.performMove(@p1, @battle.getMove('Disable'))
@p2.isMoveBlocked(tackle).should.be.true
# Disable lasts 4 turns, so go to the last turn.
for x in [1..3]
@battle.endTurn()
@battle.beginTurn()
@p2.isMoveBlocked(tackle).should.be.true
shared.biasRNG.call(this, "next", "cursed body", 0)
@battle.performMove(@p2, tackle)
@p2.isMoveBlocked(tackle).should.be.true
# Disable should end.
@battle.endTurn()
@battle.beginTurn()
@p2.isMoveBlocked(tackle).should.be.false
describe "Defeatist", ->
it "halves attack and special attack if HP goes under 50%", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Defeatist")]
tackle = @battle.getMove("Tackle")
thunderbolt = @battle.getMove("Thunderbolt")
# 50%
@p1.currentHP = (@p1.stat('hp') >> 1)
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x800)
thunderbolt.modifyAttack(@battle, @p1, @p2).should.equal(0x800)
# 50% + 1
@p1.currentHP = (@p1.stat('hp') >> 1) + 1
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
thunderbolt.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
describe "Defiant", ->
it "boosts attack by 2 every time a stat is lowered", ->
shared.create.call this,
team1: [Factory("MagPI:NAME:<NAME>END_PI", ability: "Defiant")]
@p1.boost(defense: -1, @p2)
@p1.stages.should.containEql(attack: 2)
@p1.boost(attack: -1, defense: -2, evasion: 1, @p2)
@p1.stages.should.containEql(attack: 5)
it "does not boost attack if the stat was self-lowered", ->
shared.create.call this,
team1: [Factory("MagPI:NAME:<NAME>END_PI", ability: "Defiant")]
@battle.performMove(@p1, @battle.getMove("Close Combat"))
@p1.stages.should.containEql(attack: 0, defense: -1, specialDefense: -1)
describe "Download", ->
it "raises attack if foes have total defense < total sp.def", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI")]
team2: [Factory("PI:NAME:<NAME>END_PI")]
@p1.stages.should.containEql(attack: 0)
@p1.copyAbility(Ability.Download)
@p1.stages.should.containEql(attack: 1)
it "raises special attack if foes have total sp.def <= total def", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI")]
team2: [Factory("PI:NAME:<NAME>END_PI")]
@p1.stages.should.containEql(specialAttack: 0)
@p1.copyAbility(Ability.Download)
@p1.stages.should.containEql(specialAttack: 1)
it "does not raise anything if all foes have fainted", ->
shared.create.call(this)
@p2.faint()
@p1.stages.should.containEql(attack: 0, specialAttack: 0)
@p1.copyAbility(Ability.Download)
@p1.stages.should.containEql(attack: 0, specialAttack: 0)
testWeatherAbility = (name, weather) ->
describe name, ->
it "causes unending #{weather}", ->
shared.build(this, team1: [Factory("Magikarp", ability: name)])
@battle.hasWeather().should.be.false
@controller.beginBattle()
@battle.hasWeather(weather).should.be.true
@battle.weatherDuration.should.equal(-1)
testWeatherAbility("Drizzle", Weather.RAIN)
testWeatherAbility("Drought", Weather.SUN)
testWeatherAbility("Sand Stream", Weather.SAND)
testWeatherAbility("Snow Warning", Weather.HAIL)
describe "Dry Skin", ->
it "gets healed 25% HP by water moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Dry Skin")])
@p1.currentHP = 1
@battle.performMove(@p2, @battle.getMove("Hydro Pump"))
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 2))
@battle.performMove(@p2, @battle.getMove("Tackle"))
@p1.currentHP.should.be.lessThan(1 + (@p1.stat('hp') >> 2))
it "does not get healed by self-targeting water moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Dry Skin")])
@p1.currentHP = 1
@battle.performMove(@p1, @battle.getMove("Aqua Ring"))
@p1.currentHP.should.equal(1)
it "gets healed 1/8 HP end of turn in Rain", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Dry Skin")])
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1)
@battle.setWeather(Weather.RAIN)
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 3))
it "gets damaged 25% extra by fire moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Dry Skin")])
ember = @battle.getMove("Ember")
ember.modifyBasePower(@battle, @p2, @p1).should.equal(0x1400)
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p2, @p1).should.equal(0x1000)
it "gets hurt 1/8 HP end of turn in Sun", ->
shared.create.call(this, team1: [Factory("PI:NAME:<NAME>END_PIikarp", ability: "Dry Skin")])
@battle.endTurn()
@p1.currentHP.should.equal(@p1.stat('hp'))
@battle.setWeather(Weather.SUN)
@battle.endTurn()
(@p1.stat('hp') - @p1.currentHP).should.equal(@p1.stat('hp') >> 3)
it "deals a minimum of 1 damage", ->
shared.create.call this,
team1: [Factory("Shedinja", ability: "Dry Skin")]
@battle.setWeather(Weather.SUN)
@battle.endTurn()
@p1.currentHP.should.equal(0)
it "heals a minimum of 1 hp", ->
shared.create.call this,
team1: [Factory("Magikarp", level: 1, ability: "Dry Skin")]
@p1.currentHP = 1
@battle.setWeather(Weather.RAIN)
@battle.endTurn()
@p1.currentHP.should.equal(2)
describe "Early Bird", ->
it "drops the sleep counter by 2 instead of 1", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Early Bird")])
shared.biasRNG.call(this, "randInt", 'sleep turns', 3)
@p1.attach(Status.Sleep)
@battle.performMove(@p1, @battle.getMove('Tackle'))
@p1.has(Status.Sleep).should.be.true
@battle.performMove(@p1, @battle.getMove('Tackle'))
@p1.has(Status.Sleep).should.be.false
describe "Effect Spore", ->
it "has a 30% chance to inflict poison, paralysis, or sleep on hit", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Effect Spore")])
# Sleep
shared.biasRNG.call(this, "randInt", 'effect spore', 1)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(Status.Sleep).should.be.true
# Paralysis
@p2.cureStatus()
shared.biasRNG.call(this, "randInt", 'effect spore', 2)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(Status.Paralyze).should.be.true
# Poison
@p2.cureStatus()
shared.biasRNG.call(this, "randInt", 'effect spore', 3)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(Status.Poison).should.be.true
it "has a 70% chance to do nothing", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Effect Spore")])
shared.biasRNG.call(this, "randInt", 'effect spore', 4)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.hasStatus().should.be.false
it "doesn't trigger if the hitting move is a non-contact move", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Effect Spore")])
shared.biasRNG.call(this, "randInt", 'effect spore', 1)
@battle.performMove(@p2, @battle.getMove('Thunderbolt'))
@p2.has(Status.Sleep).should.be.false
it "can work even if the defender faints", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Effect Spore"), Factory("Magikarp")]
shared.biasRNG.call(this, "randInt", 'effect spore', 1)
@p1.currentHP = 1
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(Status.Sleep).should.be.true
testFilterAbility = (name) ->
describe name, ->
it "reduces the impact of super-effective moves by 25%", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
seMove = _(@battle.MoveList).find (m) =>
!m.isNonDamaging() && util.typeEffectiveness(m.type, @p1.types) > 1
seMove.modifyDamage(@battle, @p2, @p1).should.equal(0xC00)
it "keeps non-super-effective moves as normal", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
seMove = _(@battle.MoveList).find (m) =>
!m.isNonDamaging() && util.typeEffectiveness(m.type, @p1.types) <= 1
seMove.modifyDamage(@battle, @p2, @p1).should.equal(0x1000)
testFilterAbility("Filter")
testFilterAbility("Solid Rock")
testContactStatusAbility = (name, attachment) ->
describe name, ->
it "has a 30% chance to inflict #{attachment.name} on the attacker", ->
shared.create.call this,
team1: [Factory("Magikarp", gender: "F", ability: name)]
team2: [Factory("Magikarp", gender: "M")]
shared.biasRNG.call(this, "next", 'contact status', 0)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(attachment).should.be.true
it "inflicts no status if the move used is a non-contact move", ->
shared.create.call this,
team1: [Factory("MagPI:NAME:<NAME>END_PI", gender: "F", ability: name)]
team2: [Factory("PI:NAME:<NAME>END_PI", gender: "M")]
shared.biasRNG.call(this, "next", 'contact status', 0)
@battle.performMove(@p2, @battle.getMove('Thunderbolt'))
@p2.has(attachment).should.be.false
it "inflicts no status if the hit isn't direct", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: name)]
team2: [Factory("PI:NAME:<NAME>END_PI")]
shared.biasRNG.call(this, "next", 'contact status', 0)
@p1.attach(Attachment.Substitute)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(attachment).should.be.false
it "has a 70% chance to do nothing", ->
shared.create.call this,
team1: [Factory("MagPI:NAME:<NAME>END_PI", gender: "F", ability: name)]
team2: [Factory("MagikPI:NAME:<NAME>END_PI", gender: "M")]
shared.biasRNG.call(this, "next", 'contact status', .3)
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p2.has(attachment).should.be.false
it "can work even if the defender faints", ->
shared.create.call this,
team1: [Factory("MagikPI:NAME:<NAME>END_PI", gender: "F", ability: name), Factory("Magikarp")]
team2: [Factory("Magikarp", gender: "M")]
shared.biasRNG.call(this, "next", 'contact status', 0)
@p1.currentHP = 1
tackle = @battle.getMove('Tackle')
@battle.performMove(@p2, tackle)
@p2.has(attachment).should.be.true
testContactStatusAbility("Cute Charm", Attachment.Attract)
testContactStatusAbility("Flame Body", Status.Burn)
testContactStatusAbility("Poison Point", Status.Poison)
testContactStatusAbility("Static", Status.Paralyze)
testStatusBoostAbility = (name, statuses, spectra) ->
statusNames = statuses.map((s) -> s.name).join(', ')
describe name, ->
it "increases #{spectra} moves by 1.5 if has #{statusNames}", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
move = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.spectra == spectra
for status in statuses
@p1.cureStatus()
@p1.attach(status)
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1800)
it "does not increase non-#{spectra} moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
move = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.spectra != spectra
for status in statuses
@p1.cureStatus()
@p1.attach(status)
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
testStatusBoostAbility("Flare Boost", [Status.Burn], "special")
testStatusBoostAbility("Toxic Boost", [Status.Poison, Status.Toxic], "physical")
describe "Flash Fire", ->
it "makes user invulnerable to Fire-type moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Flash Fire")])
ember = @battle.getMove("Ember")
mock = @sandbox.mock(ember).expects('hit').never()
@battle.performMove(@p2, ember)
mock.verify()
it "powers up user's Fire-type moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Flash Fire")])
ember = @battle.getMove("Ember")
tackle = @battle.getMove("Tackle")
@battle.performMove(@p2, ember)
ember.modifyBasePower(@battle, @p1, @p2).should.equal(0x1800)
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "doesn't activate on Protect", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Flash Fire")])
protect = @battle.getMove("Protect")
ember = @battle.getMove("Ember")
@battle.recordMove(@id1, protect)
@battle.recordMove(@id2, ember)
@battle.continueTurn()
@p1.has(Attachment.FlashFire).should.be.false
describe "Flower Gift", ->
it "changes Cherrim's forme"
it "does not change a transformed pokemon's forme"
it "grants x1.5 attack and special defense in Sun"
it "grants x1.5 attack and special defense to allies in Sun"
describe "Forecast", ->
it "changes Castform's forme"
it "does not change a transformed pokemon's forme"
describe "Forewarn", ->
it "considers OHKO moves to have 160 BP", ->
shared.create.call(this)
Ability.Forewarn.consider(@battle.getMove("Fissure")).should.equal(160)
it "considers counter moves to have 120 BP", ->
shared.create.call(this)
{consider} = Ability.Forewarn
consider(@battle.getMove("Counter")).should.equal(120)
consider(@battle.getMove("Mirror Coat")).should.equal(120)
consider(@battle.getMove("Metal Burst")).should.equal(120)
it "considers specific variable power moves to have 80 BP", ->
shared.create.call(this)
{consider} = Ability.Forewarn
consider(@battle.getMove("Crush Grip")).should.equal(80)
consider(@battle.getMove("Dragon Rage")).should.equal(80)
consider(@battle.getMove("Endeavor")).should.equal(80)
consider(@battle.getMove("Flail")).should.equal(80)
consider(@battle.getMove("Frustration")).should.equal(80)
consider(@battle.getMove("Grass Knot")).should.equal(80)
consider(@battle.getMove("Gyro Ball")).should.equal(80)
consider(@battle.getMove("Hidden Power")).should.equal(80)
consider(@battle.getMove("Low Kick")).should.equal(80)
consider(@battle.getMove("Natural Gift")).should.equal(80)
consider(@battle.getMove("Night Shade")).should.equal(80)
consider(@battle.getMove("Psywave")).should.equal(80)
consider(@battle.getMove("Return")).should.equal(80)
consider(@battle.getMove("Reversal")).should.equal(80)
consider(@battle.getMove("Seismic Toss")).should.equal(80)
consider(@battle.getMove("SonicBoom")).should.equal(80)
consider(@battle.getMove("Trump Card")).should.equal(80)
consider(@battle.getMove("Wring Out")).should.equal(80)
it "alerts user about a foe's move with the highest base power", ->
shared.build(this, team1: [Factory("Magikarp", ability: "Forewarn")])
spy = @sandbox.spy(@battle, 'cannedText')
@controller.beginBattle()
tackle = @battle.getMove("Tackle")
spy.calledWith('FOREWARN', @p2, tackle).should.be.true
it "displays nothing when no opponents left", ->
shared.create.call this,
team1: [Factory("Magikarp")]
team2: [Factory("Magikarp"), Factory("Magikarp")]
@p2.faint()
spy = @sandbox.spy(@battle, 'cannedText')
@p1.copyAbility(Ability.Forewarn)
spy.called.should.be.false
describe "Friend Guard", ->
it "weakens attacks from allies by 25%", ->
shared.create.call this,
numActive: 2
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Friend Guard")]
earthquake = @battle.getMove("Earthquake")
earthquake.modifyDamage(@battle, @p1, @team1.at(1)).should.equal(0xC00)
it "keeps attacks by enemies at normal", ->
shared.create.call this,
numActive: 2
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Friend Guard")]
earthquake = @battle.getMove("Earthquake")
earthquake.modifyDamage(@battle, @p2, @team1.at(1)).should.equal(0x1000)
describe "Frisk", ->
it "randomly selects an opponent and displays the item", ->
shared.build this,
team1: [Factory("Magikarp", ability: "Frisk")]
team2: [Factory("Magikarp", item: "Leftovers")]
spy = @sandbox.spy(@battle, 'cannedText')
@controller.beginBattle()
spy.calledWithMatch('FRISK').should.be.true
it "displays nothing when no opponents left", ->
shared.create.call this,
team1: [Factory("Magikarp")]
team2: [Factory("Magikarp"), Factory("Magikarp")]
@p2.faint()
spy = @sandbox.spy(@battle, 'cannedText')
@p1.copyAbility(Ability.Frisk)
spy.called.should.be.false
describe "Gluttony", ->
it "makes berries activate at 50% HP", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Salac Berry", ability: "Gluttony")]
@p1.stages.should.containEql(speed: 0)
@p1.currentHP >>= 1
@p1.update()
@p1.stages.should.containEql(speed: 1)
describe "Guts", ->
it "multiplies attack by x1.5 if statused", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Guts")])
tackle = @battle.getMove("Tackle")
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
@p1.attach(Status.Burn)
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1800)
it "does not multiply attack if move is special", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Guts")])
thunderbolt = @battle.getMove("Thunderbolt")
@p1.attach(Status.Burn)
thunderbolt.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
describe "Harvest", ->
it "has a 50% chance of re-obtaining a berry it used", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "PI:NAME:<NAME>END_PIac Berry", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 1)
@p1.useItem()
@battle.endTurn()
@p1.hasItem("Salac Berry").should.be.true
it "has a 50% chance of doing nothing", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "PI:NAME:<NAME>END_PI Berry", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 0)
@p1.useItem()
@battle.endTurn()
@p1.hasItem("Salac Berry").should.be.false
it "has a 100% chance to re-obtain the berry in Sun", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Salac Berry", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 0)
@p1.useItem()
@battle.setWeather(Weather.SUN)
@battle.endTurn()
@p1.hasItem("Salac Berry").should.be.true
it "does not regain a normal item", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 1)
@p1.useItem()
@battle.endTurn()
@p1.hasItem("Flying Gem").should.be.false
it "does not regain the berry if it was removed", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Salac Berry", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 1)
@p1.useItem()
@battle.endTurn()
@p1.hasItem("Salac Berry").should.be.true
@p1.removeItem()
@battle.endTurn()
@p1.hasItem("Salac Berry").should.be.false
it "uses a regained Berry immediately if the condition is right", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Sitrus Berry", ability: "Harvest")]
shared.biasRNG.call(this, "randInt", "harvest", 1)
@p1.useItem()
@p1.currentHP = 1
@p1.hasItem("Sitrus Berry").should.be.false
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 2))
@p1.hasItem("Sitrus Berry").should.be.false
describe "Healer", ->
it "has a 30% chance of healing an adjacent ally's status", ->
shared.create.call this,
numActive: 3
team1: [Factory("Magikarp", ability: "Healer"), Factory("Magikarp"), Factory("Magikarp")]
shared.biasRNG.call(this, "randInt", "healer", 3)
@team1.at(0).attach(Status.Burn)
@team1.at(1).attach(Status.Burn)
@team1.at(2).attach(Status.Burn)
@battle.endTurn()
@team1.at(0).hasStatus().should.be.true
@team1.at(1).hasStatus().should.be.false
@team1.at(2).hasStatus().should.be.true
it "has a 70% chance to do nothing", ->
shared.create.call this,
numActive: 2
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Healer")]
shared.biasRNG.call(this, "randInt", "healer", 4)
@p1.attach(Status.Burn)
@battle.endTurn()
@p1.hasStatus().should.be.true
describe "Heatproof", ->
it "receives half damage from Fire-type moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Heatproof")])
ember = @battle.getMove("Ember")
ember.modifyBasePower(@battle, @p2, @p1).should.equal(0x800)
it "receives normal damage from non-Fire-type moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Heatproof")])
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p2, @p1).should.equal(0x1000)
it "receives half damage from burn", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Heatproof")])
@p1.attach(Status.Burn)
burn = @p1.get(Status.Burn)
mock = @sandbox.mock(burn).expects('endTurn').returns(@p1.currentHP >> 4)
@battle.endTurn()
mock.verify()
describe "Heavy Metal", ->
it "doubles the user's weight", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Heavy Metal")])
@p1.calculateWeight().should.equal(2 * @p1.weight)
testHugePowerAbility = (name) ->
describe name, ->
it "doubles attack when using a physical move", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
tackle = @battle.getMove("Tackle")
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x2000)
it "does not double attack when using a special move", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
testHugePowerAbility("Huge Power")
testHugePowerAbility("Pure Power")
describe "Hustle", ->
it "multiplies attack by x1.5", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Hustle")])
tackle = @battle.getMove("Tackle")
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1800)
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
it "makes physical moves have 20% less accuracy", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Hustle")])
tackle = @battle.getMove("Tackle")
accuracy = tackle.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal Math.floor(tackle.accuracy * 0.8)
thunderbolt = @battle.getMove("Thunderbolt")
accuracy = thunderbolt.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal Math.floor(thunderbolt.accuracy * 1.0)
describe "Hydration", ->
it "restores status, in Rain, at the end of the turn", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Hydration")])
@p1.attach(Status.Sleep)
@battle.setWeather(Weather.RAIN)
@battle.endTurn()
@p1.hasStatus().should.be.false
it "does not restore status if the weather is not rainy", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Hydration")])
@p1.attach(Status.Sleep)
@battle.endTurn()
@p1.hasStatus().should.be.true
describe "Ice Body", ->
it "restores 1/16 HP in Hail", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Ice Body")]
@p1.currentHP = 1
@battle.setWeather(Weather.HAIL)
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 4))
it "restores no HP in other weather", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Ice Body")]
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1)
it "grants immunity to Hail", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Ice Body")]
@p1.isWeatherDamageImmune(Weather.HAIL).should.be.true
describe "Illusion", ->
it "masquerades as the last unfainted pokemon in player's party"
it "does not masquerade if all pokemon are fainted"
it "is broken when the user takes direct damage"
describe "Imposter", ->
it "automatically transforms into the adjacent foe pokemon", ->
shared.create.call this,
numActive: 2
team1: (Factory("Magikarp") for x in [1..2])
team2: [Factory("Celebi"), Factory("Mew")]
@team1.at(1).copyAbility(Ability.Imposter)
@team1.at(1).has(Attachment.Transform).should.be.true
it "does not transform if target is behind a substitute", ->
shared.create.call(this)
@p2.attach(Attachment.Substitute, hp: 1)
@p1.copyAbility(Ability.Imposter)
@p1.has(Attachment.Transform).should.be.false
it "does not transform if target is already transformed", ->
shared.create.call(this)
@battle.performMove(@p2, @battle.getMove("Transform"))
@p2.has(Attachment.Transform).should.be.true
@p1.copyAbility(Ability.Imposter)
@p1.has(Attachment.Transform).should.be.false
it "does not transform if no one is alive", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI")]
team2: [Factory("PI:NAME:<NAME>END_PI"), Factory("Celebi")]
@p2.faint()
@p1.copyAbility(Ability.Imposter)
@p1.has(Attachment.Transform).should.be.false
testAttachmentImmuneAbility = (name, attachments, options = {}) ->
describe name, ->
it "prevents the pokemon from receiving a specific attachment", ->
shared.create.call this,
team1: [Factory("Magikarp", gender: "F", ability: name)]
team2: [Factory("Magikarp", gender: "M")]
for attachment in attachments
should.not.exist @p1.attach(attachment, source: @p2)
@p1.has(attachment).should.be.false
shouldCure = options.cure ? true
if shouldCure
it "removes the attachment if the pokemon already has it", ->
shared.create.call this,
team1: [Factory("Magikarp", gender: "F")]
team2: [Factory("Magikarp", gender: "M")]
for attachment in attachments
@p1.attach(attachment, source: @p2)
@p1.has(attachment).should.be.true
@p1.copyAbility(Ability[name.replace(/\s+/g, '')])
@p1.update()
@p1.has(attachment).should.be.false
@p1.copyAbility(null)
testAttachmentImmuneAbility("Immunity", [Status.Poison, Status.Toxic])
testAttachmentImmuneAbility("Inner Focus", [Attachment.Flinch], cure: false)
testAttachmentImmuneAbility("Insomnia", [Status.Sleep])
testAttachmentImmuneAbility("Limber", [Status.Paralyze])
testAttachmentImmuneAbility("Magma Armor", [Status.Freeze])
testAttachmentImmuneAbility("Oblivious", [Attachment.Attract])
testAttachmentImmuneAbility("Own Tempo", [Attachment.Confusion])
testAttachmentImmuneAbility("Vital Spirit", [Status.Sleep])
testAttachmentImmuneAbility("Water Veil", [Status.Burn])
describe "Intimidate", ->
it "lowers the attack of all foe pokemon", ->
shared.create.call this,
team1: [ Factory("Magikarp", ability: "Intimidate") ]
@p2.stages.should.containEql(attack: -1)
it "does not lower attack of Pokemon behind Substitute", ->
shared.create.call this,
team1: [ Factory("Magikarp") ]
@p2.attach(Attachment.Substitute, hp: (@p2.currentHP >> 2))
@p1.copyAbility(Ability.Intimidate)
@p2.stages.should.containEql(attack: 0)
it "lowers attack simultaneously on all begin-turn switch-ins", ->
shared.create.call this,
team1: (Factory("Magikarp", ability: "Intimidate") for x in [1..2])
team2: (Factory("Magikarp", ability: "Intimidate") for x in [1..2])
@p1.stages.should.containEql(attack: -1)
@p2.stages.should.containEql(attack: -1)
@p1.faint()
@p2.faint()
@battle.requestFaintedReplacements()
@controller.makeSwitch(@id1, 1)
@controller.makeSwitch(@id2, 1)
@team1.first().should.not.equal(@p1)
@team2.first().should.not.equal(@p2)
@team1.first().stages.should.containEql(attack: -1)
@team2.first().stages.should.containEql(attack: -1)
describe "Infiltrator", ->
it "ignores Reflect", ->
shared.create.call this,
team1: [ Factory("Magikarp", ability: "Infiltrator") ]
@team2.attach(Attachment.Reflect)
tackle = @battle.getMove('Tackle')
tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000)
it "ignores Light Screen", ->
shared.create.call this,
team1: [ Factory("Magikarp", ability: "Infiltrator") ]
@team2.attach(Attachment.LightScreen)
thundershock = @battle.getMove('ThunderShock')
thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x1000)
it "ignores Safeguard"
it "ignores Mist"
testContactHurtAbility = (name) ->
describe name, ->
it "damages for 1/8 HP on contact moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name), Factory("Magikarp")])
hp = @p2.stat('hp')
@battle.performMove(@p2, @battle.getMove("Tackle"))
(hp - @p2.currentHP).should.equal(hp >> 3)
it "does not damage for non-contact moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name), Factory("Magikarp")])
@battle.performMove(@p2, @battle.getMove("Thunderbolt"))
@p2.currentHP.should.equal @p2.stat('hp')
it "does not damage for non-direct hits", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name), Factory("Magikarp")])
@p1.attach(Attachment.Substitute)
@battle.performMove(@p2, @battle.getMove("Tackle"))
@p2.currentHP.should.equal @p2.stat('hp')
it "still works even if the owner faints", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name), Factory("Magikarp")])
hp = @p2.stat('hp')
@p1.currentHP = 1
@battle.performMove(@p2, @battle.getMove("Tackle"))
(hp - @p2.currentHP).should.equal(hp >> 3)
it "deals a minimum of 1 damage", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
team2: [Factory("Shedinja")]
@battle.performMove(@p2, @battle.getMove("Tackle"))
@p2.currentHP.should.equal(0)
testContactHurtAbility("Iron Barbs")
testContactHurtAbility("Rough Skin")
describe "Iron Fist", ->
it "increases base power of punching moves by approximately x1.3", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Iron Fist")])
icePunch = @battle.getMove("Ice Punch")
icePunch.modifyBasePower(@battle, @p1, @p2).should.equal(0x1333)
it "does not increase base power of non-punching moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Iron Fist")])
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
describe "Justified", ->
it "boosts attack by 1 after being hit by a Dark move", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Justified")])
@p1.stages.should.containEql(attack: 0)
@battle.performMove(@p2, @battle.getMove("Tackle"))
@p1.stages.should.containEql(attack: 0)
@battle.performMove(@p2, @battle.getMove("Crunch"))
@p1.stages.should.containEql(attack: 1)
it "doesn't boost attack if the move is non-damaging", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Justified")])
@p1.stages.should.containEql(attack: 0)
@battle.performMove(@p1, @battle.getMove("Nasty Plot"))
@p1.stages.should.containEql(attack: 0)
it "doesn't boost attack if the move hits a substitute", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Justified")])
@p1.attach(Attachment.Substitute, hp: 1)
@p1.stages.should.containEql(attack: 0)
@battle.performMove(@p2, @battle.getMove("Crunch"))
@p1.stages.should.containEql(attack: 0)
describe "Klutz", ->
it "disables user's item upon switch-in", ->
shared.create.call this,
team1: [Factory("Magikarp"), Factory("Magikarp", item: "Leftovers", ability: "Klutz")]
@battle.performSwitch(@p1, 1)
@team1.first().isItemBlocked().should.be.true
it "disables user's item in the beginning of the turn", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Leftovers", ability: "Klutz")]
@p1.isItemBlocked().should.be.true
@battle.beginTurn()
@p1.isItemBlocked().should.be.true
describe "Leaf Guard", ->
it "defends against statuses under Sun", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Leaf Guard")]
@battle.setWeather(Weather.SUN)
@p1.attach(Status.Burn)
@p1.has(Status.Burn).should.be.false
it "does not defend against statuses otherwise", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Leaf Guard")]
@p1.attach(Status.Burn)
@p1.has(Status.Burn).should.be.true
describe "Levitate", ->
it "adds a ground immunity", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Levitate")]
@p1.isImmune('Ground').should.be.true
describe "Light Metal", ->
it "halves the user's weight", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Light Metal")])
@p1.calculateWeight().should.equal(@p1.weight >> 1)
testRedirectAndBoostAbility = (name, type) ->
describe name, ->
it "should redirect attacks of #{type} to user"
it "makes user immune to #{type}", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
mock = @sandbox.mock(typedMove).expects('hit').never()
@battle.performMove(@p2, typedMove)
mock.verify()
it "boosts special attack on #{type}-type moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
@battle.performMove(@p2, typedMove)
@p1.stages.should.containEql(specialAttack: 1)
it "does not boost special attack if the user is the target", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
m.target == 'user' && m.type == type
@battle.performMove(@p1, typedMove)
@p1.stages.should.containEql(specialAttack: 0)
it "does not boost special attack on #{type}-type moves if immune", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
@sandbox.stub(@p1, 'isImmune', -> true)
@battle.performMove(@p2, typedMove)
@p1.stages.should.containEql(specialAttack: 0)
it "does nothing otherwise", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: name)]
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').once()
@battle.performMove(@p2, tackle)
mock.verify()
@p1.stages.should.containEql(specialAttack: 0)
testRedirectAndBoostAbility("Lightningrod", "Electric")
testRedirectAndBoostAbility("Storm Drain", "Water")
describe "Liquid Ooze", ->
it "causes drain attacks to damage the user as well", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Liquid Ooze")]
@battle.performMove(@p2, @battle.getMove("Giga Drain"))
@p2.currentHP.should.be.lessThan @p2.stat('hp')
it "causes Leech Seed to damage the user as well", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Liquid Ooze")]
@battle.performMove(@p2, @battle.getMove("Leech Seed"))
@battle.endTurn()
@p2.currentHP.should.be.lessThan @p2.stat('hp')
describe "Magic Bounce", ->
it "still has the magic coat effect next turn", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Bounce")]
@p1.has(Attachment.MagicCoat).should.be.true
@team1.has(Attachment.MagicCoat).should.be.true
@battle.endTurn()
@p1.has(Attachment.MagicCoat).should.be.true
@team1.has(Attachment.MagicCoat).should.be.true
describe "Magic Guard", ->
it "takes no damage from anything that isn't a move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@p1.attach(Status.Burn)
@p1.currentHP.should.equal(@p1.stat('hp'))
@battle.endTurn()
@p1.currentHP.should.equal(@p1.stat('hp'))
it "takes damage from moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@battle.performMove(@p2, @battle.getMove('Tackle'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from Struggle", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@battle.performMove(@p1, @battle.getMove('Struggle'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from Belly Drum", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@battle.performMove(@p1, @battle.getMove('Belly Drum'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from confusion", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PIikarp", ability: "Magic Guard")]
shared.biasRNG.call(this, 'next', 'confusion', 0)
@p1.attach(Attachment.Confusion)
@battle.performMove(@p1, @battle.getMove('Tackle'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from using Curse", ->
shared.create.call this,
team1: [Factory("Gengar", ability: "Magic Guard")]
@battle.performMove(@p1, @battle.getMove('Curse'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from Substitute", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@battle.performMove(@p1, @battle.getMove('Substitute'))
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "takes damage from Pain Split", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PIikarp", ability: "Magic Guard")]
@p1.currentHP = 1
@battle.performMove(@p1, @battle.getMove('Pain Split'))
@p1.currentHP.should.be.greaterThan(1)
it "takes damage from Counter", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard", moves: ["Counter"])]
@controller.makeMove(@id1, "Counter")
@controller.makeMove(@id2, "Tackle")
@p1.currentHP.should.be.lessThan(@p1.stat('hp'))
it "restores health from Leftovers", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard", item: "Leftovers")]
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.be.greaterThan(1)
it "receives no damage from Rocky Helmet", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magic Guard")]
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1)
describe "Magnet Pull", ->
it "prevents Steel-type Pokemon from switching", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magnet Pull")]
team2: [Factory("Magnemite")]
@p2.isSwitchBlocked().should.be.true
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.true
it "doesn't prevent non-Steel-type Pokemon from switching", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Magnet Pull")]
team2: [Factory("Magikarp")]
@p2.isSwitchBlocked().should.be.false
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.false
describe "Marvel Scale", ->
it "multiplies defense by 1.5 when statused", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Marvel Scale")]
defense = @p1.stat('defense')
@p1.attach(Status.Burn)
@p1.stat('defense').should.equal Math.floor(1.5 * defense)
describe "Minus", ->
it "multiplies special attack by 1.5 if on the field with Plus", ->
shared.create.call this,
numActive: 2
team1: [Factory("Magikarp"), Factory("Magikarp")]
team2: [Factory("Magikarp"), Factory("Magikarp")]
specialAttack = @p1.stat('specialAttack')
@team1.at(0).copyAbility(Ability.Minus)
@team1.at(1).copyAbility(Ability.Plus)
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.modifyAttack(@battle, @team1.at(0), @p2).should.equal(0x1800)
testAbilityCancelAbility = (name) ->
describe name, ->
it "emits a catchphrase when switching in or activating", ->
shared.create.call(this)
mock = @sandbox.mock(@battle).expects('cannedText').once()
@p1.copyAbility(Ability[name.replace(/\s+/, '')])
mock.verify()
it "cancels abilities for the duration of the user's move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
team2: [Factory("Magikarp", ability: "Levitate")]
eq = @battle.getMove("Earthquake")
mock = @sandbox.mock(eq).expects('hit').once()
@battle.performMove(@p1, eq)
mock.verify()
it "cancels modifier abilities for the duration of the user's move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
team2: [Factory("Magikarp", ability: "Thick Fat")]
ib = @battle.getMove("Ice Beam")
spy = @sandbox.spy(ib, 'modifyAttack')
spy = spy.withArgs(@battle, @p1, @p2)
@battle.performMove(@p1, ib)
spy.returnValues[0].should.equal(0x1000)
it "resets canceled abilities after the move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
team2: [Factory("Magikarp", ability: "Levitate")]
eq = @battle.getMove("Earthquake")
@p2.isAbilityBlocked().should.be.false
@battle.performMove(@p1, eq)
@p2.isAbilityBlocked().should.be.false
it "does not reset already-canceled abilities after performing move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
team2: [Factory("PI:NAME:<NAME>END_PI", ability: "Levitate")]
@p2.blockAbility()
eq = @battle.getMove("Earthquake")
@p2.isAbilityBlocked().should.be.true
@battle.performMove(@p1, eq)
@p2.isAbilityBlocked().should.be.true
it "works when using field moves", ->
shared.create.call this,
team1: [Factory("MagPI:NAME:<NAME>END_PI", ability: name)]
sr = @battle.getMove("Stealth Rock")
(=> @battle.performMove(@p1, sr)).should.not.throw()
it "ignores Unaware", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: name)]
team2: [Factory("PI:NAME:<NAME>END_PI", ability: "Unaware")]
@p1.boost(attack: 2)
spy = @sandbox.spy(@p1, "editBoosts").withArgs(sinon.match(ignoreOffense: false))
@battle.performMove(@p1, @battle.getMove("Outrage"))
spy.returned(sinon.match(attack: 2)).should.be.true
testAbilityCancelAbility("Mold Breaker")
testAbilityCancelAbility("Teravolt")
testAbilityCancelAbility("Turboblaze")
describe "Moody", ->
it "at turn end, randomly raise a stat by 2 and lower another by 1", ->
shared.create.call(this, team1: [Factory("PI:NAME:<NAME>END_PIikPI:NAME:<NAME>END_PI", ability: "Moody")])
shared.biasRNG.call(this, "randInt", "moody raise", 1)
shared.biasRNG.call(this, "randInt", "moody lower", 0)
@battle.endTurn()
@p1.stages.should.containEql(attack: -1, defense: 2)
it "never raises and lowers the same stat in a single turn", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Moody")])
shared.biasRNG.call(this, "randInt", "moody raise", 0)
shared.biasRNG.call(this, "randInt", "moody lower", 0)
@battle.endTurn()
@p1.stages.should.containEql(attack: 2, defense: -1)
it "does not choose individual stats at max/min", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Moody")])
shared.biasRNG.call(this, "randInt", "moody raise", 1)
shared.biasRNG.call(this, "randInt", "moody lower", 0)
@p1.boost(defense: 6)
@p1.boost(attack: -6)
@battle.endTurn()
@p1.stages.should.containEql(defense: 5, speed: 2)
it "does not try to raise a null stat", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Moody")])
shared.biasRNG.call(this, "randInt", "moody raise", 1)
shared.biasRNG.call(this, "randInt", "moody lower", 0)
@p1.boost(attack: 6, defense: 6, speed: 6, specialAttack: 6)
@p1.boost(specialDefense: 6, accuracy: 6, evasion: 6)
(=> @battle.endTurn()).should.not.throw()
testTypeImmuneAbility = (name, type, stat) ->
describe name, ->
it "makes the user immune to #{type} moves", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
mock = @sandbox.mock(typedMove).expects('hit').never()
@battle.performMove(@p2, typedMove)
mock.verify()
it "increases #{stat} by 1 if hit by a #{type}-type move", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
@battle.performMove(@p2, typedMove)
@p1.stages[stat].should.equal(1)
it "increases #{stat} by only 1 even if move is multi-hit", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: name)])
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == type
@sandbox.stub(typedMove, 'calculateNumberOfHits', -> 2)
@battle.performMove(@p2, typedMove)
@p1.stages[stat].should.equal(1)
it "does not increase #{stat} by 1 if the user is the target", ->
shared.create.call(this, team1: [Factory("MagikPI:NAME:<NAME>END_PI", ability: name)])
typedMove = _(@battle.MoveList).find (m) ->
m.target == 'user' && m.type == type
@battle.performMove(@p1, typedMove)
@p1.stages[stat].should.equal(0)
it "does nothing otherwise", ->
shared.create.call(this, team1: [Factory("PI:NAME:<NAME>END_PI", ability: name)])
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type != type
mock = @sandbox.mock(typedMove).expects('hit').once()
@battle.performMove(@p2, typedMove)
@p1.stages[stat].should.equal(0)
mock.verify()
testTypeImmuneAbility("Motor Drive", "Electric", "speed")
testTypeImmuneAbility("Sap Sipper", "Grass", "attack")
describe "Moxie", ->
it "increases attack every time it faints another target", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Moxie")]
tackle = @battle.getMove("Tackle")
@p2.currentHP = 1
@p1.stages.should.containEql(attack: 0)
@battle.performMove(@p1, tackle)
@p1.stages.should.containEql(attack: 1)
describe "Multiscale", ->
it "takes half damage at full HP", ->
shared.create.call this,
team1: [Factory("MagPI:NAME:<NAME>END_PI", ability: "Multiscale")]
iceBeam = @battle.getMove("Ice Beam")
iceBeam.modifyDamage(@battle, @p2, @p1).should.equal(0x800)
it "takes normal damage at other HP", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Multiscale")]
iceBeam = @battle.getMove("Ice Beam")
@p1.currentHP -= 1
iceBeam.modifyDamage(@battle, @p2, @p1).should.equal(0x1000)
describe "Multitype", ->
it "changes Arceus forme for different plates"
describe "Mummy", ->
it "changes the attacker's ability to Mummy on contact", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Mummy")]
tackle = @battle.getMove("Tackle")
@p2.hasAbility("Mummy").should.be.false
@battle.performMove(@p2, tackle)
@p2.hasAbility("Mummy").should.be.true
it "doesn't change ability if move used isn't a contact move", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Mummy")]
iceBeam = @battle.getMove("Ice Beam")
@p2.hasAbility("Mummy").should.be.false
@battle.performMove(@p2, iceBeam)
@p2.hasAbility("Mummy").should.be.false
it "doesn't change ability if attacker has Multitype", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Mummy")]
team2: [Factory("Magikarp", ability: "Multitype")]
tackle = @battle.getMove("Tackle")
@p2.hasAbility("Mummy").should.be.false
@battle.performMove(@p2, tackle)
@p2.hasAbility("Mummy").should.be.false
it "works even if the defender faints", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Mummy"), Factory("Magikarp")]
@p1.currentHP = 1
tackle = @battle.getMove("Tackle")
@p2.hasAbility("Mummy").should.be.false
@battle.performMove(@p2, tackle)
@p2.hasAbility("Mummy").should.be.true
describe "Natural Cure", ->
it "cures status upon switch out", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Natural Cure")]
@p1.attach(Status.Burn)
@p1.switchOut(@battle)
@p1.hasStatus().should.be.false
describe "No Guard", ->
it "makes every move by this Pokemon never miss", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "No Guard")]
shared.biasRNG.call(this, 'randInt', 'miss', 101)
focusBlast = @battle.getMove("Focus Blast")
focusBlast.willMiss(@battle, @p1, @p2).should.be.false
it "makes every move against this Pokemon never miss", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "No Guard")]
shared.biasRNG.call(this, 'randInt', 'miss', 101)
focusBlast = @battle.getMove("Focus Blast")
focusBlast.willMiss(@battle, @p2, @p1).should.be.false
describe "Normalize", ->
it "makes every move act as if it were Normal type", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Normalize")]
team2: [Factory("PI:NAME:<NAME>END_PI")]
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.typeEffectiveness(@battle, @p1, @p2).should.equal(1)
it "has no effect if target is self", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Normalize")]
team2: [Factory("PI:NAME:<NAME>END_PI")]
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.typeEffectiveness(@battle, @p1, @p1).should.equal(2)
it "has no effect on struggle", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Normalize")]
team2: [Factory("PI:NAME:<NAME>END_PI")]
struggle = @battle.getMove("Struggle")
struggle.typeEffectiveness(@battle, @p1, @p2).should.equal(1)
describe "Overcoat", ->
it "gives an immunity to adverse weather effects", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Overcoat")]
@p1.isWeatherDamageImmune(Weather.HAIL).should.be.true
@p1.isWeatherDamageImmune(Weather.SAND).should.be.true
describe "Pickpocket", ->
it "steals the item of an opponent that makes contact", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Pickpocket")]
team2: [Factory("PI:NAME:<NAME>END_PI", item: "PI:NAME:<NAME>END_PI")]
tackle = @battle.getMove("Tackle")
@battle.performMove(@p2, tackle)
@p1.hasItem("Leftovers").should.be.true
@p2.hasItem("Leftovers").should.be.false
describe "Plus", ->
it "multiplies special attack by 1.5 if on the field with Minus", ->
shared.create.call this,
numActive: 2
team1: [Factory("Magikarp"), Factory("MagikPI:NAME:<NAME>END_PI")]
team2: [Factory("Magikarp"), Factory("Magikarp")]
specialAttack = @p1.stat('specialAttack')
@team1.at(0).copyAbility(Ability.Minus)
@team1.at(1).copyAbility(Ability.Plus)
thunderbolt = @battle.getMove("Thunderbolt")
thunderbolt.modifyAttack(@battle, @team1.at(1), @p2).should.equal(0x1800)
describe "Poison Heal", ->
it "prevents normal poison damage", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Poison Heal")]
@p1.attach(Status.Poison)
@battle.endTurn()
@p1.currentHP.should.not.be.lessThan @p1.stat('hp')
@p1.cureStatus()
@p1.attach(Status.Toxic)
@battle.endTurn()
@p1.currentHP.should.not.be.lessThan @p1.stat('hp')
it "heals 1/8 HP end of turn while poisoned", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Poison Heal")]
@p1.attach(Status.Poison)
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 3))
it "heals 1/8 HP end of turn while toxiced", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Poison Heal")]
@p1.attach(Status.Toxic)
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 3))
describe "Prankster", ->
it "makes non-damaging moves have a priority (priority + 1)", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Prankster")]
spore = @battle.getMove("Spore")
tackle = @battle.getMove("Tackle")
action = {type: "move", move: spore, pokemon: @p1}
@battle.actionPriority(action).should.equal(spore.priority + 1)
action.move = tackle
@battle.actionPriority(action).should.equal(tackle.priority)
describe "Pressure", ->
it "reduces a move's PP further by 1 if targetted by foe's move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Pressure")]
tackle = @battle.getMove("Tackle")
@p2.moves = [ tackle ]
@p2.resetAllPP()
pp = @p2.pp(tackle)
@battle.performMove(@p2, tackle)
@p2.pp(tackle).should.equal(pp - 2)
it "does not reduce a move's PP by 1 if target is self", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Pressure")]
dd = @battle.getMove("Dragon Dance")
@p1.moves = [ dd ]
@p1.resetAllPP()
pp = @p1.pp(dd)
@battle.performMove(@p1, dd)
@p1.pp(dd).should.equal(pp - 1)
describe "Quick Feet", ->
it "increases speed by x1.5 when statused", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Quick Feet")]
speed = @p1.stat('speed')
@p1.attach(Status.Sleep)
@p1.stat('speed').should.equal Math.floor(1.5 * speed)
it "negates speed drop from paralysis", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Quick Feet")]
speed = @p1.stat('speed')
@p1.attach(Status.Paralyze)
@p1.stat('speed').should.equal Math.floor(1.5 * speed)
describe "Rain Dish", ->
it "restores 1/16 HP at end of turn under Rain", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Rain Dish")]
@p1.currentHP = 1
@battle.setWeather(Weather.RAIN)
@battle.endTurn()
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 4))
it "does not restore HP at end of turn under non-Rain weather", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Rain Dish")]
@p1.currentHP = 1
@battle.endTurn()
@p1.currentHP.should.equal(1)
describe "Rattled", ->
for type in ["Ghost", "Bug", "Dark"]
do (type) ->
it "raises speed by 1 when hit by a #{type} move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Rattled")]
typedMove = _(@battle.MoveList).find (m) ->
m.type == type
@p1.stages.speed.should.equal(0)
@battle.performMove(@p2, typedMove)
@p1.stages.speed.should.equal(1)
it "does not raise speed by 1 when hit by a non-damaging #{type} move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Rattled")]
typedMove = _(@battle.MoveList).find (m) ->
m.isNonDamaging() && m.type == type
@p1.stages.speed.should.equal(0)
@battle.performMove(@p2, typedMove)
@p1.stages.speed.should.equal(0)
it "does not raise speed by 1 when a #{type} move hits a substitute", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Rattled")]
typedMove = _(@battle.MoveList).find (m) ->
m.isNonDamaging() && m.type == type
@p1.attach(Attachment.Substitute, hp: 1)
@p1.stages.speed.should.equal(0)
@battle.performMove(@p2, typedMove)
@p1.stages.speed.should.equal(0)
describe "Reckless", ->
it "gives a 1.2x boost to recoil moves", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Reckless")]
recoilMoves = @battle.MoveList.filter (m) ->
m.recoil < 0
for move in recoilMoves
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1333)
it "boosts the kick moves", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Reckless")]
recoilMoves = [ @battle.getMove("Jump Kick"),
@battle.getMove("Hi Jump Kick") ]
for move in recoilMoves
move.modifyBasePower(@battle, @p1, @p2).should.equal(0x1333)
it "does not boost struggle", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Reckless")]
struggle = @battle.getMove("Struggle")
struggle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "does not boost drain moves", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Reckless")]
absorb = @battle.getMove("Absorb")
absorb.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
describe "Regenerator", ->
it "restores 1/3 of the user's HP upon switch out", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Regenerator")]
@p1.currentHP = 1
@p1.switchOut(@battle)
hp = Math.floor(@p1.stat('hp') / 3)
@p1.currentHP.should.equal(1 + hp)
describe "Rivalry", ->
it "reduces base power by 25% if user and target are opposite genders", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", gender: 'F', ability: "Rivalry")]
team2: [Factory("PI:NAME:<NAME>END_PI", gender: 'M')]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0xC00)
it "increases base power by 25% if user and target are the same gender", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", gender: 'F', ability: "Rivalry")]
team2: [Factory("PI:NAME:<NAME>END_PI", gender: 'F')]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1400)
it "has normal base power if either user or target have no gender", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", gender: 'F', ability: "Rivalry")]
team2: [Factory("PI:NAME:<NAME>END_PI")]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
describe "Rock Head", ->
it "negates recoil", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Rock Head")]
@battle.performMove(@p1, @battle.getMove("Head Smash"))
@p1.currentHP.should.equal @p1.stat('hp')
describe "Sand Force", ->
it "increases BP of Ground-, Rock-, and Steel-type moves by 30% in sand", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sand Force")]
@battle.setWeather(Weather.SAND)
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
earthquake = @battle.getMove("Earthquake")
earthquake.modifyBasePower(@battle, @p1, @p2).should.equal(0x14CD)
rockSlide = @battle.getMove("Rock Slide")
rockSlide.modifyBasePower(@battle, @p1, @p2).should.equal(0x14CD)
meteorMash = @battle.getMove("Meteor Mash")
meteorMash.modifyBasePower(@battle, @p1, @p2).should.equal(0x14CD)
it "does not increase BP if weather is not sand", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Sand Force")]
@battle.setWeather(Weather.NONE)
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
earthquake = @battle.getMove("Earthquake")
earthquake.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
rockSlide = @battle.getMove("Rock Slide")
rockSlide.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
meteorMash = @battle.getMove("Meteor Mash")
meteorMash.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "grants immunity to sandstorm", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Sand Force")]
@p1.isWeatherDamageImmune(Weather.SAND).should.be.true
describe "Sand Veil", ->
it "increases evasion by 25% in Sand", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sand Veil")]
@battle.setWeather(Weather.SAND)
tackle = @battle.getMove("Tackle")
tackle.chanceToHit(@battle, @p2, @p1).should.equal(80)
it "does nothing outside of Sand", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PIikarp", ability: "Sand Veil")]
tackle = @battle.getMove("Tackle")
tackle.chanceToHit(@battle, @p2, @p1).should.equal(100)
it "makes the user immune to Sand", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sand Veil")]
@p1.isWeatherDamageImmune(Weather.SAND).should.be.true
describe "Scrappy", ->
it "negates pokemon immunities", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PIikPI:NAME:<NAME>END_PI", ability: "Scrappy")]
team2: [Factory("PI:NAME:<NAME>END_PI")]
tackle = @battle.getMove("Tackle")
closeCombat = @battle.getMove("Close Combat")
tackle.typeEffectiveness(@battle, @p1, @p2).should.equal(1)
closeCombat.typeEffectiveness(@battle, @p1, @p2).should.equal(.5)
mock1 = @sandbox.mock(tackle).expects('hit').once()
mock2 = @sandbox.mock(closeCombat).expects('hit').once()
@battle.performMove(@p1, tackle)
@battle.performMove(@p1, closeCombat)
mock1.verify()
mock2.verify()
describe "Serene Grace", ->
it "doubles the chance of secondary effects happening", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", "secondary effect", 10)
ember = @battle.getMove("Ember")
@sandbox.stub(ember, "baseDamage", -> 1)
@battle.performMove(@p1, ember)
@p2.has(Status.Burn).should.be.false
@p1.copyAbility(Ability.SereneGrace)
@battle.performMove(@p1, ember)
@p2.has(Status.Burn).should.be.true
it "doubles the chance of secondary boosts happening", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", "secondary boost", 10)
acid = @battle.getMove("Acid")
@sandbox.stub(acid, "baseDamage", -> 1)
@battle.performMove(@p1, acid)
@p2.stages.should.containEql(specialDefense: 0)
@p1.copyAbility(Ability.SereneGrace)
@battle.performMove(@p1, acid)
@p2.stages.should.containEql(specialDefense: -1)
it "doubles the chance of flinches happening", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", "flinch", 30)
ironHead = @battle.getMove("Iron Head")
@sandbox.stub(ironHead, "baseDamage", -> 1)
@battle.performMove(@p1, ironHead)
@p2.has(Attachment.Flinch).should.be.false
@p1.copyAbility(Ability.SereneGrace)
@battle.performMove(@p1, ironHead)
@p2.has(Attachment.Flinch).should.be.true
describe "Shadow Tag", ->
it "prevents foes from switching", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Shadow Tag")]
@p2.isSwitchBlocked().should.be.true
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.true
it "does not affect foes with Shadow Tag", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Shadow Tag")]
team2: [Factory("Magikarp", ability: "Shadow Tag")]
@p2.isSwitchBlocked().should.be.false
@battle.beginTurn()
@p2.isSwitchBlocked().should.be.false
describe "Shed Skin", ->
it "has a 30% chance of removing its status effect at end of turn", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Shed Skin")]
shared.biasRNG.call(this, "randInt", "shed skin", 3)
@p1.attach(Status.Burn)
@battle.endTurn()
@p1.has(Status.Burn).should.be.false
it "has a 70% chance of doing nothing at end of turn", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Shed Skin")]
shared.biasRNG.call(this, "randInt", "shed skin", 4)
@p1.attach(Status.Burn)
@battle.endTurn()
@p1.has(Status.Burn).should.be.true
describe "Sheer Force", ->
it "raises power of moves with secondary effects by 30%", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force")]
ember = @battle.getMove("Ember")
ember.modifyBasePower(@battle, @p1, @p2).should.equal(0x14CD)
it "does not raise power of moves without secondary effects", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PIikarp", ability: "Sheer Force")]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "nullifies secondary effects", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
shared.biasRNG.call(this, 'next', 'secondary effect', 0) # always happens
@battle.performMove(@p1, @battle.getMove("Zap Cannon"))
@p2.has(Status.Paralyze).should.be.false
it "nullifies flinch", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
shared.biasRNG.call(this, 'next', 'flinch', 0) # always happens
@battle.performMove(@p1, @battle.getMove("Iron Head"))
@p2.has(Attachment.Flinch).should.be.false
it "nullifies secondary boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
@battle.performMove(@p1, @battle.getMove("Charge Beam"))
@p1.stages.should.containEql(specialAttack: 0)
it "does not apply to primary boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
cc = @battle.getMove("Close Combat")
cc.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
@battle.performMove(@p1, cc)
@p1.stages.should.containEql(defense: -1, specialDefense: -1)
it "receives no life orb recoil", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
@battle.performMove(@p1, @battle.getMove("Ember"))
@p1.currentHP.should.not.be.lessThan @p1.stat('hp')
it "receives life orb recoil if no secondary effect", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force", item: "Life Orb")]
@battle.performMove(@p1, @battle.getMove("Tackle"))
@p1.currentHP.should.be.lessThan @p1.stat('hp')
it "does not activate Red Card", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force"), Factory("Magikarp")]
team2: [Factory("Magikarp", item: "Red Card"), Factory("Magikarp")]
@battle.performMove(@p1, @battle.getMove("Ember"))
@p1.should.equal @team1.first()
it "activates Red Card if no secondary effect", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force"), Factory("Magikarp")]
team2: [Factory("Magikarp", item: "Red Card"), Factory("Magikarp")]
@battle.performMove(@p1, @battle.getMove("Tackle"))
@p1.should.not.equal @team1.first()
it "does not activate Eject Button", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force"), Factory("Magikarp")]
team2: [Factory("Magikarp", item: "Eject Button"), Factory("Magikarp")]
@battle.recordMove(@id2, @battle.getMove("Tackle"))
should.not.exist @battle.requests[@id2]
@battle.performMove(@p1, @battle.getMove("Ember"))
should.not.exist @battle.requests[@id2]
it "activates Eject Button if no secondary effect", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sheer Force"), Factory("Magikarp")]
team2: [Factory("Magikarp", item: "Eject Button"), Factory("Magikarp")]
@battle.recordMove(@id2, @battle.getMove("Tackle"))
should.not.exist @battle.requests[@id2]
@battle.performMove(@p1, @battle.getMove("Tackle"))
@battle.requests[@id2].should.not.be.empty
it "does not activate Jaboca Berry?"
it "does not activate Rowap Berry?"
describe "Shield Dust", ->
it "prevents secondary effects", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Shield Dust")]
shared.biasRNG.call(this, 'next', 'secondary effect', 0) # always happens
@battle.performMove(@p1, @battle.getMove("Zap Cannon"))
@p2.has(Status.Paralyze).should.be.false
it "prevents secondary flinches", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Shield Dust")]
shared.biasRNG.call(this, 'randInt', 'flinch', 0) # 100% chance
@battle.performMove(@p1, @battle.getMove("Iron Head"))
@p2.has(Attachment.Flinch).should.be.false
it "prevents secondary boosts against the target", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Shield Dust")]
@battle.performMove(@p1, @battle.getMove("Acid Spray"))
@p2.stages.should.containEql(specialDefense: 0)
it "does not prevent secondary boosts for the user", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Shield Dust")]
@battle.performMove(@p1, @battle.getMove("Flame Charge"))
@p1.stages.should.containEql(speed: 1)
describe "Simple", ->
it "doubles stat boosts, negative and positive", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Simple")])
@battle.performMove(@p1, @battle.getMove("Curse"))
@p1.stages.should.containEql(attack: 2, defense: 2, speed: -2)
describe "Slow Start", ->
it "halves attack and speed", ->
shared.create.call(this)
speed = @p1.stat('speed')
@p1.copyAbility(Ability.SlowStart)
tackle = @battle.getMove("Tackle")
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x800)
flamethrower = @battle.getMove("Flamethrower")
flamethrower.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
@p1.stat('speed').should.equal(speed >> 1)
it "returns attack and speed to normal after five turns", ->
shared.create.call(this)
tackle = @battle.getMove("Tackle")
flamethrower = @battle.getMove("Flamethrower")
speed = @p1.stat('speed')
@p1.copyAbility(Ability.SlowStart)
for x in [0...5]
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x800)
flamethrower.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
@p1.stat('speed').should.equal(speed >> 1)
@battle.endTurn()
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
flamethrower.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
@p1.stat('speed').should.equal(speed)
describe "Sniper", ->
it "multiplies damage by a further x1.5 if critting", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sniper")]
tackle = @battle.getMove("Tackle")
@p1.crit = true
tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1800)
it "has a normal 1x multiplier if not critting", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sniper")]
tackle = @battle.getMove("Tackle")
@p1.crit = false
tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000)
describe "Snow Cloak", ->
it "increases evasion by 25% in hail", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Snow Cloak")]
@battle.setWeather(Weather.HAIL)
tackle = @battle.getMove("Tackle")
tackle.chanceToHit(@battle, @p2, @p1).should.equal(80)
it "does nothing outside of hail", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Snow Cloak")]
tackle = @battle.getMove("Tackle")
tackle.chanceToHit(@battle, @p2, @p1).should.equal(100)
it "makes the user immune to hail", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Snow Cloak")]
@p1.isWeatherDamageImmune(Weather.HAIL).should.be.true
describe "Solar Power", ->
it "increases special attack by 50% in Sun", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Solar Power")]
@battle.setWeather(Weather.SUN)
tackle = @battle.getMove("Tackle")
fireBlast = @battle.getMove("Fire Blast")
tackle.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
fireBlast.modifyAttack(@battle, @p1, @p2).should.equal(0x1800)
it "owner loses 1/8 max HP per end of turn", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Solar Power")]
@battle.setWeather(Weather.SUN)
@battle.endTurn()
@p1.currentHP.should.equal(@p1.stat('hp') - (@p1.stat('hp') >> 3))
it "does nothing if the weather is not Sun", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Solar Power")]
fireBlast = @battle.getMove("Fire Blast")
fireBlast.modifyAttack(@battle, @p1, @p2).should.equal(0x1000)
@battle.endTurn()
@p1.currentHP.should.equal(@p1.stat('hp'))
it "deals a minimum of 1 damage", ->
shared.create.call this,
team1: [Factory("Shedinja", ability: "Solar Power")]
@battle.setWeather(Weather.SUN)
@battle.endTurn()
@p1.currentHP.should.equal(0)
describe "Soundproof", ->
it "makes user immune to sound moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Soundproof")]
bugBuzz = @battle.getMove('Bug Buzz')
perishSong = @battle.getMove('Perish Song')
@p1.isImmune(bugBuzz.type, move: bugBuzz).should.be.true
@p1.isImmune(perishSong.type, move: perishSong).should.be.true
describe "Speed Boost", ->
it "boosts speed at the end of every turn", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Speed Boost")]
@p1.stages.should.containEql(speed: 0)
@battle.endTurn()
@p1.stages.should.containEql(speed: 1)
@battle.endTurn()
@p1.stages.should.containEql(speed: 2)
it "boosts speed the turn after a pokemon is freshly switched in", ->
shared.create.call this,
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Speed Boost")]
@battle.performSwitch(@p1, 1)
@team1.first().stages.should.containEql(speed: 0)
@battle.endTurn()
@team1.first().stages.should.containEql(speed: 0)
@battle.endTurn()
@team1.first().stages.should.containEql(speed: 1)
@battle.endTurn()
@team1.first().stages.should.containEql(speed: 2)
it "boosts speed the turn after a pokemon is replaced", ->
shared.create.call this,
team1: [Factory("Magikarp"), Factory("Magikarp", ability: "Speed Boost")]
@p1.currentHP = 1
@controller.makeMove(@id1, "Tackle")
@controller.makeMove(@id2, "Tackle")
@controller.makeSwitch(@id1, 1)
@battle.turn.should.equal(2)
@team1.first().stages.should.containEql(speed: 0)
@battle.endTurn()
@team1.first().stages.should.containEql(speed: 1)
@battle.endTurn()
@team1.first().stages.should.containEql(speed: 2)
describe "Sticky Hold", ->
it "prevents items from being taken", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Leftovers", ability: "Sticky Hold")]
@battle.performMove(@p2, @battle.getMove("Trick"))
@p1.hasItem("Leftovers").should.be.true
@p2.hasItem().should.be.false
it "does not prevent the user from using Trick", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Leftovers", ability: "Sticky Hold")]
@battle.performMove(@p1, @battle.getMove("Trick"))
@p1.hasItem().should.be.false
@p2.hasItem("Leftovers").should.be.true
describe "Stall", ->
it "forces the user to move last no matter what", ->
shared.create.call this,
team1: [Factory("Magikarp", evs: {speed: 4}, ability: "Stall")]
team2: [Factory("Magikarp")]
splash = @battle.getMove("Splash")
@battle.recordMove(@id1, splash)
@battle.recordMove(@id2, splash)
@battle.determineTurnOrder()
pokemon = @battle.pokemonActions.map((o) -> o.pokemon)
pokemon.should.eql [ @p2, @p1 ]
it "moves before pokemon with lagging tail/full incense", ->
shared.create.call this,
team1: [Factory("Magikarp", evs: {speed: 4}, ability: "Stall")]
team2: [Factory("Magikarp", item: "Lagging Tail")]
splash = @battle.getMove("Splash")
@battle.recordMove(@id1, splash)
@battle.recordMove(@id2, splash)
@battle.determineTurnOrder()
pokemon = @battle.pokemonActions.map((o) -> o.pokemon)
pokemon.should.eql [ @p1, @p2 ]
describe "Steadfast", ->
it "raises speed if the Pokemon flinches", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Steadfast")]
tackle = @battle.getMove("Tackle")
@p1.attach(Attachment.Flinch)
@p1.beforeMove(tackle, @p1, [ @p2 ])
@p1.stages.should.containEql(speed: 1)
describe "Sturdy", ->
it "prevents the user from being OHKOed at full HP", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sturdy")]
ember = @battle.getMove('Ember')
stub = @sandbox.stub(ember, 'calculateDamage', -> 9999)
@battle.performMove(@p2, ember)
@p1.currentHP.should.equal(1)
it "lets the user be KOed if not at full HP", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Sturdy")]
@p1.currentHP -= 1
ember = @battle.getMove('Ember')
stub = @sandbox.stub(ember, 'calculateDamage', -> 9999)
@battle.performMove(@p2, ember)
@p1.currentHP.should.equal(0)
describe "Suction Cups", ->
it "prevents user from being phased", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Suction Cups"), Factory("Magikarp")]
whirlwind = @battle.getMove('Whirlwind')
mock = @sandbox.mock(@team1).expects('switch').never()
@battle.performMove(@p2, whirlwind)
mock.verify()
describe "Super Luck", ->
it "adds +2 to critical hit level", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Super Luck")]
tackle = @battle.getMove("Tackle")
tackle.criticalHitLevel(@battle, @p1, @p2).should.equal(2)
describe "Synchronize", ->
it "afflicts the source of a status with the same status", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Synchronize")]
@p1.attach(Status.Paralyze, source: @p2)
@p2.has(Status.Paralyze).should.be.true
it "doesn't attempt to afflict target if target is self", ->
shared.create.call this,
team1: [Factory("MagikPI:NAME:<NAME>END_PI", ability: "Synchronize")]
spy = @sandbox.spy(Status.Burn, 'preattach')
@p1.attach(Status.Burn, source: @p1)
spy.returned(false).should.be.true
it "activates on primary status moves", ->
shared.create.call this,
team1: [Factory("MagikPI:NAME:<NAME>END_PI", ability: "Synchronize")]
@battle.performMove(@p2, @battle.getMove("Will-O-Wisp"))
@p2.has(Status.Burn).should.be.true
it "doesn't activate on Sleep", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Synchronize")]
@p1.attach(Status.Sleep, source: @p2)
@p2.has(Status.Sleep).should.be.false
it "doesn't activate on Freeze", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Synchronize")]
@p1.attach(Status.Freeze, source: @p2)
@p2.has(Status.Freeze).should.be.false
it "activates on secondary effects", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Synchronize")]
shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance
@battle.performMove(@p2, @battle.getMove("Flamethrower"))
@p2.has(Status.Burn).should.be.true
describe "Tangled Feet", ->
it "doubles evasion rate when confused", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Tangled Feet")]
tackle = @battle.getMove("Tackle")
tackle.chanceToHit(@battle, @p2, @p1).should.equal(100)
@p1.attach(Attachment.Confusion)
tackle.chanceToHit(@battle, @p2, @p1).should.equal(50)
@p1.unattach(Attachment.Confusion)
tackle.chanceToHit(@battle, @p2, @p1).should.equal(100)
describe "Technician", ->
it "increases base power of moves with BP <= 60 by x1.5", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Technician")]
tackle = @battle.getMove("Tackle")
tackle.modifyBasePower(@battle, @p1, @p2).should.equal(0x1800)
it "leaves moves with BP > 60 alone", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Technician")]
iceBeam = @battle.getMove("Ice Beam")
iceBeam.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
describe "Telepathy", ->
it "cancels damaging attacks from an ally", ->
shared.create.call this,
numActive: 2
team1: [Factory("PI:NAME:<NAME>END_PI"), Factory("Magikarp", ability: "Telepathy")]
team2: (Factory("PI:NAME:<NAME>END_PIikPI:NAME:<NAME>END_PI") for x in [1..2])
earthquake = @battle.getMove("Earthquake")
mock = @sandbox.mock(earthquake).expects('hit').exactly(2)
@battle.performMove(@p1, earthquake)
@team1.at(1).currentHP.should.equal(@team1.at(1).stat('hp'))
mock.verify()
describe "Thick Fat", ->
it "halves the base power of Fire and Ice moves", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Thick Fat")]
iceBeam = @battle.getMove("Ice Beam")
iceBeam.modifyAttack(@battle, @p2, @p1).should.equal(0x800)
flamethrower = @battle.getMove("Flamethrower")
flamethrower.modifyAttack(@battle, @p2, @p1).should.equal(0x800)
it "doesn't change base power of other moves", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Thick Fat")]
tackle = @battle.getMove("Tackle")
tackle.modifyAttack(@battle, @p2, @p1).should.equal(0x1000)
describe "Tinted Lens", ->
it "doubles damage when using a not-very-effective move", ->
shared.create.call this,
team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Tinted Lens")]
team2: [Factory("PI:NAME:<NAME>END_PI")]
surf = @battle.getMove("Surf")
surf.modifyDamage(@battle, @p1, @p2).should.equal(0x2000)
it "doesn't double damage otherwise", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Tinted Lens")]
team2: [Factory("Magikarp")]
tackle = @battle.getMove("Tackle")
tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000)
describe "Trace", ->
it "copies a random foe's ability on switch-in", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Trace")]
team2: [Factory("Magikarp", ability: "Truant")]
@p1.hasAbility("Truant").should.be.true
it "does not copy certain abilities", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Trace")]
team2: [Factory("Magikarp", ability: "Forecast")]
@p1.hasAbility("Forecast").should.be.false
it "does not crash if there are no opponents", ->
shared.create.call this,
team1: [Factory("Magikarp")]
team2: [Factory("Magikarp"), Factory("Magikarp")]
@p2.faint()
(=>
@p1.copyAbility(Ability.Trace)
).should.not.throw()
it "traces another ability upon switching out and back in", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Trace"), Factory("Magikarp")]
team2: [Factory("Magikarp", ability: "Intimidate")
Factory("Magikarp", ability: "Magic Bounce")]
@p1.hasAbility("Intimidate").should.be.true
@battle.performSwitch(@p2, 1)
@battle.performSwitch(@p1, 1)
@battle.performSwitch(@team1.first(), 1)
@p1.hasAbility("Magic Bounce").should.be.true
describe "Truant", ->
it "prevents the user from attacking every other turn", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Truant")]
splash = @battle.getMove("Splash")
mock = @sandbox.mock(splash).expects('execute').once()
@battle.performMove(@p1, splash)
mock.verify()
splash.execute.restore()
mock = @sandbox.mock(splash).expects('execute').never()
@battle.performMove(@p1, splash)
mock.verify()
splash.execute.restore()
mock = @sandbox.mock(splash).expects('execute').once()
@battle.performMove(@p1, splash)
mock.verify()
splash.execute.restore()
describe "Unaware", ->
it "ignores attackers' attack and special attack boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unaware")]
@p2.boost(attack: 1, specialAttack: 2)
spy = @sandbox.spy(@p2, "editBoosts")
@battle.performMove(@p2, @battle.getMove("Tackle"))
spy.returned(sinon.match(attack: 0, specialAttack: 0)).should.be.true
it "ignores defenders' defense and special defense boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unaware")]
@p2.boost(defense: 1, specialDefense: 2)
spy = @sandbox.spy(@p2, "editBoosts")
@battle.performMove(@p1, @battle.getMove("Tackle"))
spy.returned(sinon.match(defense: 0, specialDefense: 0)).should.be.true
it "ignores attackers' accuracy boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unaware")]
@p2.boost(accuracy: 3)
spy = @sandbox.spy(@p2, "editBoosts")
@battle.getMove("Tackle").chanceToHit(@battle, @p2, @p1)
spy.returned(sinon.match(accuracy: 0)).should.be.true
it "ignores defenders' evasion boosts", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unaware")]
@p2.boost(evasion: 3)
spy = @sandbox.spy(@p2, "editBoosts")
@battle.getMove("Tackle").chanceToHit(@battle, @p1, @p2)
spy.returned(sinon.match(evasion: 0)).should.be.true
describe "Unburden", ->
it "doubles its speed when the owner's item is removed", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Unburden")]
speed = @p1.stat('speed')
@p1.removeItem()
@p1.stat('speed').should.equal(2 * speed)
it "activates when its item is swapped for no item", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Unburden")]
speed = @p1.stat('speed')
trick = @battle.getMove("Trick")
@battle.performMove(@p2, trick)
@p1.stat('speed').should.equal(2 * speed)
it "does not activate when its item is swapped for another item", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Unburden")]
team2: [Factory("Magikarp", item: "Water Gem")]
speed = @p1.stat('speed')
trick = @battle.getMove("Trick")
@battle.performMove(@p2, trick)
@p1.stat('speed').should.equal(speed)
@p1.has(Attachment.Unburden).should.be.false
it "deactivates if it gains another item", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Unburden")]
team2: [Factory("Magikarp", item: "Water Gem")]
speed = @p1.stat('speed')
@p1.removeItem()
@p1.stat('speed').should.equal(2 * speed)
trick = @battle.getMove("Trick")
@battle.performMove(@p2, trick)
@p1.stat('speed').should.equal(speed)
@p1.has(Attachment.Unburden).should.be.false
it "deactivates if it loses this Ability", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "Flying Gem", ability: "Unburden")]
team2: [Factory("Magikarp", ability: "Run Away")]
speed = @p1.stat('speed')
@p1.removeItem()
@p1.stat('speed').should.equal(2 * speed)
rolePlay = @battle.getMove("Role Play")
@battle.performMove(@p1, rolePlay)
@p1.stat('speed').should.equal(speed)
@p1.has(Attachment.Unburden).should.be.false
describe "Unnerve", ->
it "prevents held berries from being eaten", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unnerve")]
team2: [Factory("Magikarp", item: "PI:NAME:<NAME>END_PI")]
@p2.currentHP = 1
@p2.update()
@p2.stages.should.containEql(speed: 0)
@battle.beginTurn()
@p2.update()
@p2.stages.should.containEql(speed: 0)
it "does not prevent regular item usage", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Unnerve")]
team2: [Factory("Magikarp", item: "Leftovers")]
@p2.currentHP = 1
@battle.endTurn()
@p2.currentHP.should.be.greaterThan(1)
it "does not prevent Bug Bite, Pluck, etc. from working", ->
shared.create.call this,
team1: [Factory("Magikarp", item: "PI:NAME:<NAME>END_PI", ability: "Unnerve")]
@battle.performMove(@p2, @battle.getMove("Bug Bite"))
@p2.stages.should.containEql(speed: 1)
describe "Victory Star", ->
it "increases accuracy of moves by 10%", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Victory Star")]
willOWisp = @battle.getMove("Will-O-Wisp")
accuracy = willOWisp.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal Math.floor(willOWisp.accuracy * 1.1)
it "increases accuracy of ally moves by 10%"
testTypeAbsorbMove = (name, type) ->
describe name, ->
it "is immune to #{type}-type moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
m.type == type
mock = @sandbox.mock(typedMove).expects('hit').never()
@battle.performMove(@p2, typedMove)
mock.verify()
it "heals 25% HP from #{type}-type moves", ->
shared.create.call this,
team1: [Factory("MagikPI:NAME:<NAME>END_PI", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
m.type == type
@p1.currentHP = 1
@battle.performMove(@p2, typedMove)
@p1.currentHP.should.equal(1 + (@p1.stat('hp') >> 2))
it "does not activate for the user's moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: name)]
typedMove = _(@battle.MoveList).find (m) ->
m.target == 'user' && m.type == type
@p1.currentHP = 1
@battle.performMove(@p1, typedMove)
@p1.currentHP.should.equal(1)
testTypeAbsorbMove("Water Absorb", "Water")
testTypeAbsorbMove("Volt Absorb", "Electric")
describe "Weak Armor", ->
it "lowers defense and raises speed on physical attacks", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Weak Armor")]
tackle = @battle.getMove("Tackle")
@battle.performMove(@p2, tackle)
@p1.stages.should.containEql(defense: -1, speed: 1)
it "does nothing on any other kind of move", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Weak Armor")]
willOWisp = @battle.getMove("Will-O-Wisp")
@battle.performMove(@p2, willOWisp)
@p1.stages.should.containEql(defense: 0, speed: 0)
describe "Wonder Guard", ->
it "renders the Pokemon immune to non-super-effective moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Wonder Guard")]
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').never()
@battle.performMove(@p2, tackle)
mock.verify()
it "is not immune to struggle", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Wonder Guard")]
struggle = @battle.getMove("Struggle")
mock = @sandbox.mock(struggle).expects('hit').once()
@battle.performMove(@p2, struggle)
mock.verify()
it "is not immune to non-damaging moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Wonder Guard")]
willOWisp = @battle.getMove("Will-O-Wisp")
mock = @sandbox.mock(willOWisp).expects('hit').once()
@battle.performMove(@p2, willOWisp)
mock.verify()
it "is not immune to super-effective moves", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Wonder Guard")]
typedMove = _(@battle.MoveList).find (m) ->
!m.isNonDamaging() && m.type == 'Electric'
mock = @sandbox.mock(typedMove).expects('hit').once()
@battle.performMove(@p2, typedMove)
mock.verify()
describe "Wonder Skin", ->
it "makes non-damaging moves with over 50% accuracy have 50% accuracy", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Wonder Skin")]
trick = @battle.getMove("Trick")
accuracy = trick.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal 50
it "adjusts accuracy before any other modifiers take effect", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Compoundeyes")]
team2: [Factory("Magikarp", ability: "Wonder Skin")]
willOWisp = @battle.getMove("Will-O-Wisp")
accuracy = willOWisp.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal Math.floor(50 * 1.3)
it "does nothing to non-damaging moves that don't check accuracy", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Wonder Skin")]
meanLook = @battle.getMove("Mean Look")
accuracy = meanLook.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal 0
it "does nothing to non-damaging moves with under 50% accuracy", ->
shared.create.call this,
team2: [Factory("Magikarp", ability: "Wonder Skin")]
trick = @battle.getMove("Trick")
trick.accuracy = 40
accuracy = trick.chanceToHit(@battle, @p1, @p2)
accuracy.should.equal 40
describe "Zen Mode", ->
it "changes Darmanitan's forme when going under or above 50% HP"
|
[
{
"context": "et').withArgs('profile_abc').returns({firstName: \"chris\"})\n sandbox.stub(cache, 'put')\n\n afterEach ->",
"end": 423,
"score": 0.9990476369857788,
"start": 418,
"tag": "NAME",
"value": "chris"
},
{
"context": "se', ->\n profile.getProfile({_auth: {token: 'xy... | test/auth/profile-spec.coffee | theodorick/ocelot | 13 | profile = require '../../src/auth/profile'
chai = require 'chai'
cache = require 'memory-cache'
sinon = require 'sinon'
agent = require '../../src/http-agent'
config = require 'config'
chaiAsPromised = require 'chai-as-promised'
chai.use chaiAsPromised
chai.should()
sandbox = sinon.sandbox.create()
describe 'profile', ->
beforeEach ->
sandbox.stub(cache, 'get').withArgs('profile_abc').returns({firstName: "chris"})
sandbox.stub(cache, 'put')
afterEach ->
sandbox.restore()
describe 'resolves to empty', ->
it 'when user profile is false', ->
profile.getProfile({_auth: {token: 'xyz', access_token: {user_id: 'cjcoff'}}, _route: {'ent-app-id': 'myapp', 'user-profile-enabled': false}}, 'abc').should.eventually.not.exist
it 'when authentication does not contain a user id', ->
profile.getProfile({_auth: {}, _route: {'ent-app-id': 'myapp'}}, 'abc').should.eventually.not.exist
it 'when profile info does not resolve', ->
agentStub = {}
agentStub.get = sandbox.stub().returns(agentStub)
agentStub.set = sandbox.stub().withArgs('Authorization', 'Bearer def').returns(agentStub)
agentStub.then = (success, fail) -> fail()
sandbox.stub(agent, 'getAgent').returns(agentStub)
profile.getProfile({_auth: {token: 'xyz', access_token: {user_id: 'cjcoff'}}, _route: {'ent-app-id': 'myapp', 'user-profile-enabled': true}}, 'def').should.eventually.eql {}
describe 'resolves profile information', ->
it 'when user id and profile url present and profile info resolves', ->
agentStub = {}
agentStub.get = sandbox.stub().returns(agentStub)
agentStub.set = sandbox.stub().withArgs('Authorization', 'Bearer def').returns(agentStub)
agentStub.then = (func) -> func({body: {firstName: "chris"}})
sandbox.stub(agent, 'getAgent').returns(agentStub)
sandbox.stub(config, 'get').withArgs('authentication.profile-endpoint').returns("http://some-profile-service")
profile.getProfile({_auth: {token: 'xyzz', access_token: {user_id: 'cjcoff'}}, _route: {'ent-app-id': 'myapp', 'user-profile-enabled': true}}, 'def').should.eventually.eql({firstName: "chris"})
# it 'when profile is found in cache', ->
# profile.getProfile({_auth: {token: 'xyzz', access_token: {user_id: 'cjcoff'}}, _route: {'ent-app-id': 'myapp', 'user-profile-enabled': true}}, 'abc').should.eventually.eql({firstName: "chris"})
| 109342 | profile = require '../../src/auth/profile'
chai = require 'chai'
cache = require 'memory-cache'
sinon = require 'sinon'
agent = require '../../src/http-agent'
config = require 'config'
chaiAsPromised = require 'chai-as-promised'
chai.use chaiAsPromised
chai.should()
sandbox = sinon.sandbox.create()
describe 'profile', ->
beforeEach ->
sandbox.stub(cache, 'get').withArgs('profile_abc').returns({firstName: "<NAME>"})
sandbox.stub(cache, 'put')
afterEach ->
sandbox.restore()
describe 'resolves to empty', ->
it 'when user profile is false', ->
profile.getProfile({_auth: {token: '<KEY>', access_token: {user_id: '<KEY>'}}, _route: {'ent-app-id': 'myapp', 'user-profile-enabled': false}}, 'abc').should.eventually.not.exist
it 'when authentication does not contain a user id', ->
profile.getProfile({_auth: {}, _route: {'ent-app-id': 'myapp'}}, 'abc').should.eventually.not.exist
it 'when profile info does not resolve', ->
agentStub = {}
agentStub.get = sandbox.stub().returns(agentStub)
agentStub.set = sandbox.stub().withArgs('Authorization', 'Bearer def').returns(agentStub)
agentStub.then = (success, fail) -> fail()
sandbox.stub(agent, 'getAgent').returns(agentStub)
profile.getProfile({_auth: {token: '<KEY>', access_token: {user_id: '<KEY>'}}, _route: {'ent-app-id': 'myapp', 'user-profile-enabled': true}}, 'def').should.eventually.eql {}
describe 'resolves profile information', ->
it 'when user id and profile url present and profile info resolves', ->
agentStub = {}
agentStub.get = sandbox.stub().returns(agentStub)
agentStub.set = sandbox.stub().withArgs('Authorization', 'Bearer def').returns(agentStub)
agentStub.then = (func) -> func({body: {firstName: "<NAME>"}})
sandbox.stub(agent, 'getAgent').returns(agentStub)
sandbox.stub(config, 'get').withArgs('authentication.profile-endpoint').returns("http://some-profile-service")
profile.getProfile({_auth: {token: '<KEY>', access_token: {user_id: '<KEY>coff'}}, _route: {'ent-app-id': 'myapp', 'user-profile-enabled': true}}, 'def').should.eventually.eql({firstName: "<NAME>"})
# it 'when profile is found in cache', ->
# profile.getProfile({_auth: {token: '<KEY>', access_token: {user_id: '<KEY>ff'}}, _route: {'ent-app-id': 'myapp', 'user-profile-enabled': true}}, 'abc').should.eventually.eql({firstName: "<NAME>"})
| true | profile = require '../../src/auth/profile'
chai = require 'chai'
cache = require 'memory-cache'
sinon = require 'sinon'
agent = require '../../src/http-agent'
config = require 'config'
chaiAsPromised = require 'chai-as-promised'
chai.use chaiAsPromised
chai.should()
sandbox = sinon.sandbox.create()
describe 'profile', ->
beforeEach ->
sandbox.stub(cache, 'get').withArgs('profile_abc').returns({firstName: "PI:NAME:<NAME>END_PI"})
sandbox.stub(cache, 'put')
afterEach ->
sandbox.restore()
describe 'resolves to empty', ->
it 'when user profile is false', ->
profile.getProfile({_auth: {token: 'PI:KEY:<KEY>END_PI', access_token: {user_id: 'PI:KEY:<KEY>END_PI'}}, _route: {'ent-app-id': 'myapp', 'user-profile-enabled': false}}, 'abc').should.eventually.not.exist
it 'when authentication does not contain a user id', ->
profile.getProfile({_auth: {}, _route: {'ent-app-id': 'myapp'}}, 'abc').should.eventually.not.exist
it 'when profile info does not resolve', ->
agentStub = {}
agentStub.get = sandbox.stub().returns(agentStub)
agentStub.set = sandbox.stub().withArgs('Authorization', 'Bearer def').returns(agentStub)
agentStub.then = (success, fail) -> fail()
sandbox.stub(agent, 'getAgent').returns(agentStub)
profile.getProfile({_auth: {token: 'PI:KEY:<KEY>END_PI', access_token: {user_id: 'PI:KEY:<KEY>END_PI'}}, _route: {'ent-app-id': 'myapp', 'user-profile-enabled': true}}, 'def').should.eventually.eql {}
describe 'resolves profile information', ->
it 'when user id and profile url present and profile info resolves', ->
agentStub = {}
agentStub.get = sandbox.stub().returns(agentStub)
agentStub.set = sandbox.stub().withArgs('Authorization', 'Bearer def').returns(agentStub)
agentStub.then = (func) -> func({body: {firstName: "PI:NAME:<NAME>END_PI"}})
sandbox.stub(agent, 'getAgent').returns(agentStub)
sandbox.stub(config, 'get').withArgs('authentication.profile-endpoint').returns("http://some-profile-service")
profile.getProfile({_auth: {token: 'PI:KEY:<KEY>END_PI', access_token: {user_id: 'PI:KEY:<KEY>END_PIcoff'}}, _route: {'ent-app-id': 'myapp', 'user-profile-enabled': true}}, 'def').should.eventually.eql({firstName: "PI:NAME:<NAME>END_PI"})
# it 'when profile is found in cache', ->
# profile.getProfile({_auth: {token: 'PI:KEY:<KEY>END_PI', access_token: {user_id: 'PI:KEY:<KEY>END_PIff'}}, _route: {'ent-app-id': 'myapp', 'user-profile-enabled': true}}, 'abc').should.eventually.eql({firstName: "PI:NAME:<NAME>END_PI"})
|
[
{
"context": " nbits : 256\n expire_in : 10\n }]\n userid = \"Tester 1 <tester@gmail.com>\"\n await KeyManager.generate {",
"end": 758,
"score": 0.9973128437995911,
"start": 750,
"tag": "USERNAME",
"value": "Tester 1"
},
{
"context": "256\n expire_in : 10\n }]\n userid = ... | test/files/subkey_preference.iced | samkenxstream/kbpgp | 464 | kbpgp = require '../..'
C = kbpgp.const.openpgp
{unbox,box,KeyManager} = kbpgp
{ECDSA} = kbpgp.ecc
{unix_time} = kbpgp.util
exports.test_multiple_encryption_subkeys = (T,cb) ->
F = C.key_flags
primary = {
flags : F.certify_keys
nbits : 384
algo : ECDSA
}
subkeys = [{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 100
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 2000
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 5000
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 50
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 10
}]
userid = "Tester 1 <tester@gmail.com>"
await KeyManager.generate { userid, primary, subkeys }, T.esc(defer(km), cb)
await km.sign {}, T.esc(defer(), cb)
msg = "Huffy Henry hid the day, unappeasable Henry sulked."
await box { encrypt_for : km, msg }, T.esc(defer(ciphertext), cb)
# Decrypt as normal should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
km.pgp.subkeys = [ km.pgp.subkeys[2] ]
# Decrypt with only the expected subkey should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
# Decrypt without any subkeys should work
km.pgp.subkeys = []
await unbox { keyfetch : km, armored : ciphertext }, defer err
T.assert err?, "error came back with no keys"
T.assert err.toString().indexOf("No keys match the given key IDs") >= 0, "the right error msg"
cb()
exports.test_multiple_encryption_subkeys_winner_did_not_expire = (T,cb) ->
F = C.key_flags
primary = {
flags : F.certify_keys
nbits : 384
algo : ECDSA
}
subkeys = [{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 100
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 2000
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : null
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 50
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 10
}]
userid = "Tester 1 <tester@gmail.com>"
await KeyManager.generate { userid, primary, subkeys }, T.esc(defer(km), cb)
await km.sign {}, T.esc(defer(), cb)
msg = "Huffy Henry hid the day, unappeasable Henry sulked."
await box { encrypt_for : km, msg }, T.esc(defer(ciphertext), cb)
# Decrypt as normal should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
km.pgp.subkeys = [ km.pgp.subkeys[2] ]
# Decrypt with only the expected subkey should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
# Decrypt without any subkeys should work
km.pgp.subkeys = []
await unbox { keyfetch : km, armored : ciphertext }, defer err
T.assert err?, "error came back with no keys"
T.assert err.toString().indexOf("No keys match the given key IDs") >= 0, "the right error msg"
cb()
exports.test_multiple_encryption_subkeys_winner_latest = (T,cb) ->
F = C.key_flags
primary = {
flags : F.certify_keys
nbits : 384
algo : ECDSA
}
when_gen = unix_time()
expire_in = 999
when_gen_0 = when_gen - 1000
expire_in_0 = expire_in + 1000
subkeys = [{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : expire_in_0
generated : when_gen_0
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : expire_in_0
generated : when_gen_0
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : expire_in
generated : when_gen
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : expire_in_0
generated : when_gen_0
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : expire_in_0
generated : when_gen_0
}]
userid = "Tester 1 <tester@gmail.com>"
await KeyManager.generate { userid, primary, subkeys }, T.esc(defer(km), cb)
await km.sign {}, T.esc(defer(), cb)
msg = "Huffy Henry hid the day, unappeasable Henry sulked."
await box { encrypt_for : km, msg }, T.esc(defer(ciphertext), cb)
# Decrypt as normal should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
km.pgp.subkeys = [ km.pgp.subkeys[2] ]
# Decrypt with only the expected subkey should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
# Decrypt without any subkeys should work
km.pgp.subkeys = []
await unbox { keyfetch : km, armored : ciphertext }, defer err
T.assert err?, "error came back with no keys"
T.assert err.toString().indexOf("No keys match the given key IDs") >= 0, "the right error msg"
cb()
| 5455 | kbpgp = require '../..'
C = kbpgp.const.openpgp
{unbox,box,KeyManager} = kbpgp
{ECDSA} = kbpgp.ecc
{unix_time} = kbpgp.util
exports.test_multiple_encryption_subkeys = (T,cb) ->
F = C.key_flags
primary = {
flags : F.certify_keys
nbits : 384
algo : ECDSA
}
subkeys = [{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 100
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 2000
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 5000
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 50
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 10
}]
userid = "Tester 1 <<EMAIL>>"
await KeyManager.generate { userid, primary, subkeys }, T.esc(defer(km), cb)
await km.sign {}, T.esc(defer(), cb)
msg = "H<NAME> hid the day, unappeasable <NAME> sulked."
await box { encrypt_for : km, msg }, T.esc(defer(ciphertext), cb)
# Decrypt as normal should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
km.pgp.subkeys = [ km.pgp.subkeys[2] ]
# Decrypt with only the expected subkey should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
# Decrypt without any subkeys should work
km.pgp.subkeys = []
await unbox { keyfetch : km, armored : ciphertext }, defer err
T.assert err?, "error came back with no keys"
T.assert err.toString().indexOf("No keys match the given key IDs") >= 0, "the right error msg"
cb()
exports.test_multiple_encryption_subkeys_winner_did_not_expire = (T,cb) ->
F = C.key_flags
primary = {
flags : F.certify_keys
nbits : 384
algo : ECDSA
}
subkeys = [{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 100
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 2000
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : null
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 50
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 10
}]
userid = "Tester 1 <<EMAIL>>"
await KeyManager.generate { userid, primary, subkeys }, T.esc(defer(km), cb)
await km.sign {}, T.esc(defer(), cb)
msg = "H<NAME>y <NAME> hid the day, unappeasable <NAME> sulked."
await box { encrypt_for : km, msg }, T.esc(defer(ciphertext), cb)
# Decrypt as normal should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
km.pgp.subkeys = [ km.pgp.subkeys[2] ]
# Decrypt with only the expected subkey should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
# Decrypt without any subkeys should work
km.pgp.subkeys = []
await unbox { keyfetch : km, armored : ciphertext }, defer err
T.assert err?, "error came back with no keys"
T.assert err.toString().indexOf("No keys match the given key IDs") >= 0, "the right error msg"
cb()
exports.test_multiple_encryption_subkeys_winner_latest = (T,cb) ->
F = C.key_flags
primary = {
flags : F.certify_keys
nbits : 384
algo : ECDSA
}
when_gen = unix_time()
expire_in = 999
when_gen_0 = when_gen - 1000
expire_in_0 = expire_in + 1000
subkeys = [{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : expire_in_0
generated : when_gen_0
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : expire_in_0
generated : when_gen_0
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : expire_in
generated : when_gen
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : expire_in_0
generated : when_gen_0
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : expire_in_0
generated : when_gen_0
}]
userid = "Tester 1 <<EMAIL>>"
await KeyManager.generate { userid, primary, subkeys }, T.esc(defer(km), cb)
await km.sign {}, T.esc(defer(), cb)
msg = "Huffy <NAME> hid the day, unappeasable <NAME> sulked."
await box { encrypt_for : km, msg }, T.esc(defer(ciphertext), cb)
# Decrypt as normal should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
km.pgp.subkeys = [ km.pgp.subkeys[2] ]
# Decrypt with only the expected subkey should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
# Decrypt without any subkeys should work
km.pgp.subkeys = []
await unbox { keyfetch : km, armored : ciphertext }, defer err
T.assert err?, "error came back with no keys"
T.assert err.toString().indexOf("No keys match the given key IDs") >= 0, "the right error msg"
cb()
| true | kbpgp = require '../..'
C = kbpgp.const.openpgp
{unbox,box,KeyManager} = kbpgp
{ECDSA} = kbpgp.ecc
{unix_time} = kbpgp.util
exports.test_multiple_encryption_subkeys = (T,cb) ->
F = C.key_flags
primary = {
flags : F.certify_keys
nbits : 384
algo : ECDSA
}
subkeys = [{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 100
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 2000
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 5000
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 50
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 10
}]
userid = "Tester 1 <PI:EMAIL:<EMAIL>END_PI>"
await KeyManager.generate { userid, primary, subkeys }, T.esc(defer(km), cb)
await km.sign {}, T.esc(defer(), cb)
msg = "HPI:NAME:<NAME>END_PI hid the day, unappeasable PI:NAME:<NAME>END_PI sulked."
await box { encrypt_for : km, msg }, T.esc(defer(ciphertext), cb)
# Decrypt as normal should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
km.pgp.subkeys = [ km.pgp.subkeys[2] ]
# Decrypt with only the expected subkey should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
# Decrypt without any subkeys should work
km.pgp.subkeys = []
await unbox { keyfetch : km, armored : ciphertext }, defer err
T.assert err?, "error came back with no keys"
T.assert err.toString().indexOf("No keys match the given key IDs") >= 0, "the right error msg"
cb()
exports.test_multiple_encryption_subkeys_winner_did_not_expire = (T,cb) ->
F = C.key_flags
primary = {
flags : F.certify_keys
nbits : 384
algo : ECDSA
}
subkeys = [{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 100
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 2000
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : null
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 50
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : 10
}]
userid = "Tester 1 <PI:EMAIL:<EMAIL>END_PI>"
await KeyManager.generate { userid, primary, subkeys }, T.esc(defer(km), cb)
await km.sign {}, T.esc(defer(), cb)
msg = "HPI:NAME:<NAME>END_PIy PI:NAME:<NAME>END_PI hid the day, unappeasable PI:NAME:<NAME>END_PI sulked."
await box { encrypt_for : km, msg }, T.esc(defer(ciphertext), cb)
# Decrypt as normal should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
km.pgp.subkeys = [ km.pgp.subkeys[2] ]
# Decrypt with only the expected subkey should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
# Decrypt without any subkeys should work
km.pgp.subkeys = []
await unbox { keyfetch : km, armored : ciphertext }, defer err
T.assert err?, "error came back with no keys"
T.assert err.toString().indexOf("No keys match the given key IDs") >= 0, "the right error msg"
cb()
exports.test_multiple_encryption_subkeys_winner_latest = (T,cb) ->
F = C.key_flags
primary = {
flags : F.certify_keys
nbits : 384
algo : ECDSA
}
when_gen = unix_time()
expire_in = 999
when_gen_0 = when_gen - 1000
expire_in_0 = expire_in + 1000
subkeys = [{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : expire_in_0
generated : when_gen_0
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : expire_in_0
generated : when_gen_0
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : expire_in
generated : when_gen
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : expire_in_0
generated : when_gen_0
},{
flags : F.encrypt_storage | F.encrypt_comm,
nbits : 256
expire_in : expire_in_0
generated : when_gen_0
}]
userid = "Tester 1 <PI:EMAIL:<EMAIL>END_PI>"
await KeyManager.generate { userid, primary, subkeys }, T.esc(defer(km), cb)
await km.sign {}, T.esc(defer(), cb)
msg = "Huffy PI:NAME:<NAME>END_PI hid the day, unappeasable PI:NAME:<NAME>END_PI sulked."
await box { encrypt_for : km, msg }, T.esc(defer(ciphertext), cb)
# Decrypt as normal should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
km.pgp.subkeys = [ km.pgp.subkeys[2] ]
# Decrypt with only the expected subkey should work
await unbox { keyfetch : km, armored : ciphertext }, T.esc(defer(plaintext), cb)
T.equal msg, plaintext[0].data.toString('utf8'), "right plaintext back out"
# Decrypt without any subkeys should work
km.pgp.subkeys = []
await unbox { keyfetch : km, armored : ciphertext }, defer err
T.assert err?, "error came back with no keys"
T.assert err.toString().indexOf("No keys match the given key IDs") >= 0, "the right error msg"
cb()
|
[
{
"context": "ameForUser({\n\t\t\t\t\tid: window.user.id\n\t\t\t\t\temail: \"james.allen@overleaf.com\"\n\t\t\t\t\tfirst_name: \"James\"\n\t\t\t\t\tlast_name: \"Allen\"",
"end": 441,
"score": 0.9999253153800964,
"start": 417,
"tag": "EMAIL",
"value": "james.allen@overleaf.com"
},
{
"... | test/unit_frontend/coffee/ide/history/util/displayNameForUserTests.coffee | davidmehren/web-sharelatex | 0 | define ['ide/history/util/displayNameForUser'], (displayNameForUser) ->
describe "displayNameForUser", ->
beforeEach ->
window.user = { id: 42 }
it "should return 'Anonymous' with no user", ->
expect(
displayNameForUser(null)
).to.equal "Anonymous"
it "should return 'you' when the user has the same id as the window", ->
expect(
displayNameForUser({
id: window.user.id
email: "james.allen@overleaf.com"
first_name: "James"
last_name: "Allen"
})
).to.equal "you"
it "should return the first_name and last_name when present", ->
expect(
displayNameForUser({
id: window.user.id + 1
email: "james.allen@overleaf.com"
first_name: "James"
last_name: "Allen"
})
).to.equal "James Allen"
it "should return only the firstAname if no last_name", ->
expect(
displayNameForUser({
id: window.user.id + 1
email: "james.allen@overleaf.com"
first_name: "James"
last_name: ""
})
).to.equal "James"
it "should return the email username if there are no names", ->
expect(
displayNameForUser({
id: window.user.id + 1
email: "james.allen@overleaf.com"
first_name: ""
last_name: ""
})
).to.equal "james.allen"
it "should return the '?' if it has nothing", ->
expect(
displayNameForUser({
id: window.user.id + 1
email: ""
first_name: ""
last_name: ""
})
).to.equal "?"
| 202161 | define ['ide/history/util/displayNameForUser'], (displayNameForUser) ->
describe "displayNameForUser", ->
beforeEach ->
window.user = { id: 42 }
it "should return 'Anonymous' with no user", ->
expect(
displayNameForUser(null)
).to.equal "Anonymous"
it "should return 'you' when the user has the same id as the window", ->
expect(
displayNameForUser({
id: window.user.id
email: "<EMAIL>"
first_name: "<NAME>"
last_name: "<NAME>"
})
).to.equal "you"
it "should return the first_name and last_name when present", ->
expect(
displayNameForUser({
id: window.user.id + 1
email: "<EMAIL>"
first_name: "<NAME>"
last_name: "<NAME>"
})
).to.equal "<NAME>"
it "should return only the firstAname if no last_name", ->
expect(
displayNameForUser({
id: window.user.id + 1
email: "<EMAIL>"
first_name: "<NAME>"
last_name: ""
})
).to.equal "<NAME>"
it "should return the email username if there are no names", ->
expect(
displayNameForUser({
id: window.user.id + 1
email: "<EMAIL>"
first_name: ""
last_name: ""
})
).to.equal "james.allen"
it "should return the '?' if it has nothing", ->
expect(
displayNameForUser({
id: window.user.id + 1
email: ""
first_name: ""
last_name: ""
})
).to.equal "?"
| true | define ['ide/history/util/displayNameForUser'], (displayNameForUser) ->
describe "displayNameForUser", ->
beforeEach ->
window.user = { id: 42 }
it "should return 'Anonymous' with no user", ->
expect(
displayNameForUser(null)
).to.equal "Anonymous"
it "should return 'you' when the user has the same id as the window", ->
expect(
displayNameForUser({
id: window.user.id
email: "PI:EMAIL:<EMAIL>END_PI"
first_name: "PI:NAME:<NAME>END_PI"
last_name: "PI:NAME:<NAME>END_PI"
})
).to.equal "you"
it "should return the first_name and last_name when present", ->
expect(
displayNameForUser({
id: window.user.id + 1
email: "PI:EMAIL:<EMAIL>END_PI"
first_name: "PI:NAME:<NAME>END_PI"
last_name: "PI:NAME:<NAME>END_PI"
})
).to.equal "PI:NAME:<NAME>END_PI"
it "should return only the firstAname if no last_name", ->
expect(
displayNameForUser({
id: window.user.id + 1
email: "PI:EMAIL:<EMAIL>END_PI"
first_name: "PI:NAME:<NAME>END_PI"
last_name: ""
})
).to.equal "PI:NAME:<NAME>END_PI"
it "should return the email username if there are no names", ->
expect(
displayNameForUser({
id: window.user.id + 1
email: "PI:EMAIL:<EMAIL>END_PI"
first_name: ""
last_name: ""
})
).to.equal "james.allen"
it "should return the '?' if it has nothing", ->
expect(
displayNameForUser({
id: window.user.id + 1
email: ""
first_name: ""
last_name: ""
})
).to.equal "?"
|
[
{
"context": "# Mice: alert\n\n# Copyright (c) 2014 Miclle\n# Licensed under MIT (https://github.com/miclle/m",
"end": 42,
"score": 0.7694029211997986,
"start": 36,
"tag": "NAME",
"value": "Miclle"
},
{
"context": "4 Miclle\n# Licensed under MIT (https://github.com/miclle/mice/blob/m... | assets/javascripts/mice/alert.coffee | miclle/mice | 7 | # Mice: alert
# Copyright (c) 2014 Miclle
# Licensed under MIT (https://github.com/miclle/mice/blob/master/LICENSE)
'use strict';
(($) ->
# ALERT PUBLIC CLASS DEFINITION
# ===============================
class Alert
constructor: (element) ->
$(element).on('click', '[data-dismiss="alert"]', @close)
close: (e) ->
$this = $(this)
selector = $this.attr('data-target')
unless selector
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') # strip for ie7
$parent = $(selector)
e.preventDefault() if e
$parent = (if $this.hasClass('alert') then $this else $this.parent()) unless $parent.length
$parent.trigger(e = $.Event('close.alert'))
return if e.isDefaultPrevented()
$parent.removeClass('in')
removeElement = -> # detach from parent, fire event then clean up data
$parent.detach().trigger('closed.alert').remove()
if $.support.transition and $parent.hasClass('fade')
$parent.one('miceTransitionEnd', removeElement).emulateTransitionEnd(150)
else
removeElement()
# ALERT PLUGIN DEFINITION
# =========================
$.fn.alert = (option) ->
@each ->
$this = $(this)
data = $this.data('alert')
$this.data('alert', (data = new Alert(this))) unless data
data[option].call($this) if (typeof option == 'string')
$.fn.alert.Constructor = Alert
$(document).on('click.alert.data-api', '[data-dismiss="alert"]', Alert.prototype.close)
return
) jQuery | 37827 | # Mice: alert
# Copyright (c) 2014 <NAME>
# Licensed under MIT (https://github.com/miclle/mice/blob/master/LICENSE)
'use strict';
(($) ->
# ALERT PUBLIC CLASS DEFINITION
# ===============================
class Alert
constructor: (element) ->
$(element).on('click', '[data-dismiss="alert"]', @close)
close: (e) ->
$this = $(this)
selector = $this.attr('data-target')
unless selector
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') # strip for ie7
$parent = $(selector)
e.preventDefault() if e
$parent = (if $this.hasClass('alert') then $this else $this.parent()) unless $parent.length
$parent.trigger(e = $.Event('close.alert'))
return if e.isDefaultPrevented()
$parent.removeClass('in')
removeElement = -> # detach from parent, fire event then clean up data
$parent.detach().trigger('closed.alert').remove()
if $.support.transition and $parent.hasClass('fade')
$parent.one('miceTransitionEnd', removeElement).emulateTransitionEnd(150)
else
removeElement()
# ALERT PLUGIN DEFINITION
# =========================
$.fn.alert = (option) ->
@each ->
$this = $(this)
data = $this.data('alert')
$this.data('alert', (data = new Alert(this))) unless data
data[option].call($this) if (typeof option == 'string')
$.fn.alert.Constructor = Alert
$(document).on('click.alert.data-api', '[data-dismiss="alert"]', Alert.prototype.close)
return
) jQuery | true | # Mice: alert
# Copyright (c) 2014 PI:NAME:<NAME>END_PI
# Licensed under MIT (https://github.com/miclle/mice/blob/master/LICENSE)
'use strict';
(($) ->
# ALERT PUBLIC CLASS DEFINITION
# ===============================
class Alert
constructor: (element) ->
$(element).on('click', '[data-dismiss="alert"]', @close)
close: (e) ->
$this = $(this)
selector = $this.attr('data-target')
unless selector
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') # strip for ie7
$parent = $(selector)
e.preventDefault() if e
$parent = (if $this.hasClass('alert') then $this else $this.parent()) unless $parent.length
$parent.trigger(e = $.Event('close.alert'))
return if e.isDefaultPrevented()
$parent.removeClass('in')
removeElement = -> # detach from parent, fire event then clean up data
$parent.detach().trigger('closed.alert').remove()
if $.support.transition and $parent.hasClass('fade')
$parent.one('miceTransitionEnd', removeElement).emulateTransitionEnd(150)
else
removeElement()
# ALERT PLUGIN DEFINITION
# =========================
$.fn.alert = (option) ->
@each ->
$this = $(this)
data = $this.data('alert')
$this.data('alert', (data = new Alert(this))) unless data
data[option].call($this) if (typeof option == 'string')
$.fn.alert.Constructor = Alert
$(document).on('click.alert.data-api', '[data-dismiss="alert"]', Alert.prototype.close)
return
) jQuery |
[
{
"context": "alse\n\n process.nextTick =>\n @filterToken = Math.random().toString(36).substring(7)\n @_filter",
"end": 4096,
"score": 0.47242069244384766,
"start": 4092,
"tag": "KEY",
"value": "Math"
}
] | lib/filter-editor-view.coffee | JavaCS3/filter-editor-view | 0 | 'use strict'
$ = (arg) ->
return (require 'jquery') arg
module.exports =
class FilterEditorView
scheduleTimeout: null
confirmed: false
filterToken: ""
constructor: (args) ->
@_createFrameArea()
@$list = $(@list)
# Events binding
@filterEditor.getModel().getBuffer().onDidChange =>
@_schedulePopulateList()
$(@filterEditor).blur (e) =>
@cancel()
atom.commands.add @root,
'core:move-up': (event) =>
first = @$list.find('li:first')
last = @$list.find('li:last')
selectedItem = @_getSelectedItem()
if selectedItem.length is 0 # selected nothing
@_selectItem(last)
else if selectedItem is first
@_selectItem(null)
else
@_selectItem(@_getSelectedItem().prev())
event.stopPropagation()
'core:move-down': (event) =>
first = @$list.find('li:first')
last = @$list.find('li:last')
selectedItem = @_getSelectedItem()
if selectedItem.length is 0 # slected nothing
@_selectItem(first)
else if selectedItem is last
@_selectItem(null)
else
@_selectItem(@_getSelectedItem().next())
event.stopPropagation()
'core:confirm': (event) =>
@confirm()
event.stopPropagation()
'core:cancel': (event) =>
@cancel()
event.stopPropagation()
@$list.on 'mousedown', 'li', (e) =>
@_selectItem($(e.target).closest('li'))
e.preventDefault()
false
@$list.on 'mouseup', 'li', (e) =>
@confirm() if $(e.target).closest('li').hasClass('selected')
e.preventDefault()
false
_createFrameArea: ->
@root = document.createElement('div')
@root.classList.add('filter-editor-view', 'select-list', 'block')
@filterEditor = document.createElement('atom-text-editor')
@filterEditor.setAttribute('mini', true)
@root.appendChild(@filterEditor)
@list = document.createElement('ol')
@list.classList.add('list-group')
@root.appendChild(@list)
_selectItem: ($item) ->
if not ($item and $item.length)
return @$list.find('.selected').removeClass('selected')
@$list.find('.selected').removeClass('selected')
$item.addClass('selected')
@_scrollToItem($item)
_scrollToItem: ($item) ->
scrollTop = @$list.scrollTop()
desiredTop = $item.position().top + scrollTop
desiredBottom = desiredTop + $item.outerHeight()
if desiredTop < scrollTop
@$list.scrollTop(desiredTop)
else if desiredBottom > @$list.scrollTop() + @$list.height()
@$list.scrollTop(desiredBottom - @$list.height())
_getSelectedItem: ->
@$list.find('.selected')
_confirmedCallback: (str) ->
# @API
# Set confirmed callback
onConfirmed: (callback) ->
if typeof callback is 'function'
@_confirmedCallback = callback
# @API
# Confirm the input
confirm: ->
selectedItem = @_getSelectedItem()
if selectedItem.length isnt 0
@confirmed = true
@setText(selectedItem.text())
@_confirmedCallback(@getText())
# @API
# Cancel all the ongoing event
cancel: ->
@confirmed = false
clearTimeout(@scheduleTimeout)
@root.classList.remove('popover-list')
@$list.empty()
# @API
# Set the text of the filter editor
setText: (text) ->
@filterEditor.getModel().setText(text)
# @API
# Get the text of the filter editor
getText: ->
@filterEditor.getModel().getText()
_schedulePopulateList: ->
clearTimeout(@scheduleTimeout)
if @filterEditor.getModel().getText().length isnt 0
@scheduleTimeout = setTimeout (=> @_populateList()), 200
_filterCallback: (token, str, responseCallback) ->
responseCallback(token, [])
# @API
# Set filter callback
onFilter: (callback) ->
if typeof callback is 'function'
@_filterCallback = callback
_responseCallback: (token, result) =>
if token is @filterToken
@_updateResult(result)
_populateList: ->
if @confirmed
return @confirmed = false
process.nextTick =>
@filterToken = Math.random().toString(36).substring(7)
@_filterCallback(@filterToken, @getText(), @_responseCallback)
_updateResult: (result) ->
@$list.empty()
@$list.append($('<li/>').text(i)) for i in result
if result.length > 0
@root.classList.add('popover-list')
else
@root.classList.remove('popover-list')
@_selectItem(null) # select input field
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@root.remove()
# @API
# Returns the DOM element
getElement: ->
@root
| 208891 | 'use strict'
$ = (arg) ->
return (require 'jquery') arg
module.exports =
class FilterEditorView
scheduleTimeout: null
confirmed: false
filterToken: ""
constructor: (args) ->
@_createFrameArea()
@$list = $(@list)
# Events binding
@filterEditor.getModel().getBuffer().onDidChange =>
@_schedulePopulateList()
$(@filterEditor).blur (e) =>
@cancel()
atom.commands.add @root,
'core:move-up': (event) =>
first = @$list.find('li:first')
last = @$list.find('li:last')
selectedItem = @_getSelectedItem()
if selectedItem.length is 0 # selected nothing
@_selectItem(last)
else if selectedItem is first
@_selectItem(null)
else
@_selectItem(@_getSelectedItem().prev())
event.stopPropagation()
'core:move-down': (event) =>
first = @$list.find('li:first')
last = @$list.find('li:last')
selectedItem = @_getSelectedItem()
if selectedItem.length is 0 # slected nothing
@_selectItem(first)
else if selectedItem is last
@_selectItem(null)
else
@_selectItem(@_getSelectedItem().next())
event.stopPropagation()
'core:confirm': (event) =>
@confirm()
event.stopPropagation()
'core:cancel': (event) =>
@cancel()
event.stopPropagation()
@$list.on 'mousedown', 'li', (e) =>
@_selectItem($(e.target).closest('li'))
e.preventDefault()
false
@$list.on 'mouseup', 'li', (e) =>
@confirm() if $(e.target).closest('li').hasClass('selected')
e.preventDefault()
false
_createFrameArea: ->
@root = document.createElement('div')
@root.classList.add('filter-editor-view', 'select-list', 'block')
@filterEditor = document.createElement('atom-text-editor')
@filterEditor.setAttribute('mini', true)
@root.appendChild(@filterEditor)
@list = document.createElement('ol')
@list.classList.add('list-group')
@root.appendChild(@list)
_selectItem: ($item) ->
if not ($item and $item.length)
return @$list.find('.selected').removeClass('selected')
@$list.find('.selected').removeClass('selected')
$item.addClass('selected')
@_scrollToItem($item)
_scrollToItem: ($item) ->
scrollTop = @$list.scrollTop()
desiredTop = $item.position().top + scrollTop
desiredBottom = desiredTop + $item.outerHeight()
if desiredTop < scrollTop
@$list.scrollTop(desiredTop)
else if desiredBottom > @$list.scrollTop() + @$list.height()
@$list.scrollTop(desiredBottom - @$list.height())
_getSelectedItem: ->
@$list.find('.selected')
_confirmedCallback: (str) ->
# @API
# Set confirmed callback
onConfirmed: (callback) ->
if typeof callback is 'function'
@_confirmedCallback = callback
# @API
# Confirm the input
confirm: ->
selectedItem = @_getSelectedItem()
if selectedItem.length isnt 0
@confirmed = true
@setText(selectedItem.text())
@_confirmedCallback(@getText())
# @API
# Cancel all the ongoing event
cancel: ->
@confirmed = false
clearTimeout(@scheduleTimeout)
@root.classList.remove('popover-list')
@$list.empty()
# @API
# Set the text of the filter editor
setText: (text) ->
@filterEditor.getModel().setText(text)
# @API
# Get the text of the filter editor
getText: ->
@filterEditor.getModel().getText()
_schedulePopulateList: ->
clearTimeout(@scheduleTimeout)
if @filterEditor.getModel().getText().length isnt 0
@scheduleTimeout = setTimeout (=> @_populateList()), 200
_filterCallback: (token, str, responseCallback) ->
responseCallback(token, [])
# @API
# Set filter callback
onFilter: (callback) ->
if typeof callback is 'function'
@_filterCallback = callback
_responseCallback: (token, result) =>
if token is @filterToken
@_updateResult(result)
_populateList: ->
if @confirmed
return @confirmed = false
process.nextTick =>
@filterToken = <KEY>.random().toString(36).substring(7)
@_filterCallback(@filterToken, @getText(), @_responseCallback)
_updateResult: (result) ->
@$list.empty()
@$list.append($('<li/>').text(i)) for i in result
if result.length > 0
@root.classList.add('popover-list')
else
@root.classList.remove('popover-list')
@_selectItem(null) # select input field
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@root.remove()
# @API
# Returns the DOM element
getElement: ->
@root
| true | 'use strict'
$ = (arg) ->
return (require 'jquery') arg
module.exports =
class FilterEditorView
scheduleTimeout: null
confirmed: false
filterToken: ""
constructor: (args) ->
@_createFrameArea()
@$list = $(@list)
# Events binding
@filterEditor.getModel().getBuffer().onDidChange =>
@_schedulePopulateList()
$(@filterEditor).blur (e) =>
@cancel()
atom.commands.add @root,
'core:move-up': (event) =>
first = @$list.find('li:first')
last = @$list.find('li:last')
selectedItem = @_getSelectedItem()
if selectedItem.length is 0 # selected nothing
@_selectItem(last)
else if selectedItem is first
@_selectItem(null)
else
@_selectItem(@_getSelectedItem().prev())
event.stopPropagation()
'core:move-down': (event) =>
first = @$list.find('li:first')
last = @$list.find('li:last')
selectedItem = @_getSelectedItem()
if selectedItem.length is 0 # slected nothing
@_selectItem(first)
else if selectedItem is last
@_selectItem(null)
else
@_selectItem(@_getSelectedItem().next())
event.stopPropagation()
'core:confirm': (event) =>
@confirm()
event.stopPropagation()
'core:cancel': (event) =>
@cancel()
event.stopPropagation()
@$list.on 'mousedown', 'li', (e) =>
@_selectItem($(e.target).closest('li'))
e.preventDefault()
false
@$list.on 'mouseup', 'li', (e) =>
@confirm() if $(e.target).closest('li').hasClass('selected')
e.preventDefault()
false
_createFrameArea: ->
@root = document.createElement('div')
@root.classList.add('filter-editor-view', 'select-list', 'block')
@filterEditor = document.createElement('atom-text-editor')
@filterEditor.setAttribute('mini', true)
@root.appendChild(@filterEditor)
@list = document.createElement('ol')
@list.classList.add('list-group')
@root.appendChild(@list)
_selectItem: ($item) ->
if not ($item and $item.length)
return @$list.find('.selected').removeClass('selected')
@$list.find('.selected').removeClass('selected')
$item.addClass('selected')
@_scrollToItem($item)
_scrollToItem: ($item) ->
scrollTop = @$list.scrollTop()
desiredTop = $item.position().top + scrollTop
desiredBottom = desiredTop + $item.outerHeight()
if desiredTop < scrollTop
@$list.scrollTop(desiredTop)
else if desiredBottom > @$list.scrollTop() + @$list.height()
@$list.scrollTop(desiredBottom - @$list.height())
_getSelectedItem: ->
@$list.find('.selected')
_confirmedCallback: (str) ->
# @API
# Set confirmed callback
onConfirmed: (callback) ->
if typeof callback is 'function'
@_confirmedCallback = callback
# @API
# Confirm the input
confirm: ->
selectedItem = @_getSelectedItem()
if selectedItem.length isnt 0
@confirmed = true
@setText(selectedItem.text())
@_confirmedCallback(@getText())
# @API
# Cancel all the ongoing event
cancel: ->
@confirmed = false
clearTimeout(@scheduleTimeout)
@root.classList.remove('popover-list')
@$list.empty()
# @API
# Set the text of the filter editor
setText: (text) ->
@filterEditor.getModel().setText(text)
# @API
# Get the text of the filter editor
getText: ->
@filterEditor.getModel().getText()
_schedulePopulateList: ->
clearTimeout(@scheduleTimeout)
if @filterEditor.getModel().getText().length isnt 0
@scheduleTimeout = setTimeout (=> @_populateList()), 200
_filterCallback: (token, str, responseCallback) ->
responseCallback(token, [])
# @API
# Set filter callback
onFilter: (callback) ->
if typeof callback is 'function'
@_filterCallback = callback
_responseCallback: (token, result) =>
if token is @filterToken
@_updateResult(result)
_populateList: ->
if @confirmed
return @confirmed = false
process.nextTick =>
@filterToken = PI:KEY:<KEY>END_PI.random().toString(36).substring(7)
@_filterCallback(@filterToken, @getText(), @_responseCallback)
_updateResult: (result) ->
@$list.empty()
@$list.append($('<li/>').text(i)) for i in result
if result.length > 0
@root.classList.add('popover-list')
else
@root.classList.remove('popover-list')
@_selectItem(null) # select input field
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@root.remove()
# @API
# Returns the DOM element
getElement: ->
@root
|
[
{
"context": "aderValues: ['oi', 'oioi']\n headerKeys: ['6', '7']\n bodyEncoding: 'form'\n bod",
"end": 561,
"score": 0.8232784867286682,
"start": 560,
"tag": "KEY",
"value": "6"
},
{
"context": "alues: ['oi', 'oioi']\n headerKeys: ['6', '7']\n ... | test/http-formatter-spec.coffee | octoblu/nanocyte-component-http-formatter | 0 | ReturnValue = require 'nanocyte-component-return-value'
HttpFormatter = require '../src/http-formatter'
describe 'HttpFormatter', ->
beforeEach ->
@sut = new HttpFormatter
it 'should exist', ->
expect(@sut).to.be.an.instanceOf ReturnValue
describe '->onEnvelope', ->
describe 'when called with an envelope', ->
beforeEach ->
@config =
url: "http://taco.com"
bodyValues: ['test', 'test2']
method: 'GET'
queryValues: ['q1', 'q2']
headerValues: ['oi', 'oioi']
headerKeys: ['6', '7']
bodyEncoding: 'form'
bodyKeys: ['t1', 't2']
queryKeys: ['q0', 'q1']
it 'should return the message', ->
expect(@sut.onEnvelope({@config})).to.deep.equal { headers: { '6': 'oi', '7': 'oioi', 'User-Agent': 'Octoblu' }, uri: 'http://taco.com',method: 'GET',followAllRedirects: true,qs: { q0: 'q1', q1: 'q2' },form: { t1: 'test', t2: 'test2' } }
describe 'when called with only an URL for RSS feed', ->
beforeEach ->
@config =
url: "http://taco.com"
it 'should return the message', ->
expect(@sut.onEnvelope({@config})).to.deep.equal { headers: { 'User-Agent': 'Octoblu' }, uri: 'http://taco.com',method: 'GET',followAllRedirects: true,qs: {} }
| 118549 | ReturnValue = require 'nanocyte-component-return-value'
HttpFormatter = require '../src/http-formatter'
describe 'HttpFormatter', ->
beforeEach ->
@sut = new HttpFormatter
it 'should exist', ->
expect(@sut).to.be.an.instanceOf ReturnValue
describe '->onEnvelope', ->
describe 'when called with an envelope', ->
beforeEach ->
@config =
url: "http://taco.com"
bodyValues: ['test', 'test2']
method: 'GET'
queryValues: ['q1', 'q2']
headerValues: ['oi', 'oioi']
headerKeys: ['<KEY>', '<KEY>']
bodyEncoding: 'form'
bodyKeys: ['t<KEY>', 't<KEY>']
queryKeys: ['q0', 'q<KEY>']
it 'should return the message', ->
expect(@sut.onEnvelope({@config})).to.deep.equal { headers: { '6': 'oi', '7': 'oioi', 'User-Agent': 'Octoblu' }, uri: 'http://taco.com',method: 'GET',followAllRedirects: true,qs: { q0: 'q1', q1: 'q2' },form: { t1: 'test', t2: 'test2' } }
describe 'when called with only an URL for RSS feed', ->
beforeEach ->
@config =
url: "http://taco.com"
it 'should return the message', ->
expect(@sut.onEnvelope({@config})).to.deep.equal { headers: { 'User-Agent': 'Octoblu' }, uri: 'http://taco.com',method: 'GET',followAllRedirects: true,qs: {} }
| true | ReturnValue = require 'nanocyte-component-return-value'
HttpFormatter = require '../src/http-formatter'
describe 'HttpFormatter', ->
beforeEach ->
@sut = new HttpFormatter
it 'should exist', ->
expect(@sut).to.be.an.instanceOf ReturnValue
describe '->onEnvelope', ->
describe 'when called with an envelope', ->
beforeEach ->
@config =
url: "http://taco.com"
bodyValues: ['test', 'test2']
method: 'GET'
queryValues: ['q1', 'q2']
headerValues: ['oi', 'oioi']
headerKeys: ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI']
bodyEncoding: 'form'
bodyKeys: ['tPI:KEY:<KEY>END_PI', 'tPI:KEY:<KEY>END_PI']
queryKeys: ['q0', 'qPI:KEY:<KEY>END_PI']
it 'should return the message', ->
expect(@sut.onEnvelope({@config})).to.deep.equal { headers: { '6': 'oi', '7': 'oioi', 'User-Agent': 'Octoblu' }, uri: 'http://taco.com',method: 'GET',followAllRedirects: true,qs: { q0: 'q1', q1: 'q2' },form: { t1: 'test', t2: 'test2' } }
describe 'when called with only an URL for RSS feed', ->
beforeEach ->
@config =
url: "http://taco.com"
it 'should return the message', ->
expect(@sut.onEnvelope({@config})).to.deep.equal { headers: { 'User-Agent': 'Octoblu' }, uri: 'http://taco.com',method: 'GET',followAllRedirects: true,qs: {} }
|
[
{
"context": "ge, secure } = KONFIG.sessionCookie\n\n csrfToken = createId()\n # set cookie as pending cookie\n req.pendin",
"end": 333,
"score": 0.8134938478469849,
"start": 327,
"tag": "KEY",
"value": "create"
}
] | servers/lib/server/setcsrftoken.coffee | ezgikaysi/koding | 1 | KONFIG = require 'koding-config-manager'
{ v4: createId } = require 'node-uuid'
module.exports = (req, res, next) ->
unless KONFIG.environment is 'production'
res.header 'Access-Control-Allow-Origin', 'http://www.koding.com'
next() if req?.cookies?._csrf
{ maxAge, secure } = KONFIG.sessionCookie
csrfToken = createId()
# set cookie as pending cookie
req.pendingCookies or= {}
req.pendingCookies._csrf = csrfToken
expires = new Date Date.now() + 360
res.cookie '_csrf', csrfToken, { expires, secure }
next()
| 225718 | KONFIG = require 'koding-config-manager'
{ v4: createId } = require 'node-uuid'
module.exports = (req, res, next) ->
unless KONFIG.environment is 'production'
res.header 'Access-Control-Allow-Origin', 'http://www.koding.com'
next() if req?.cookies?._csrf
{ maxAge, secure } = KONFIG.sessionCookie
csrfToken = <KEY>Id()
# set cookie as pending cookie
req.pendingCookies or= {}
req.pendingCookies._csrf = csrfToken
expires = new Date Date.now() + 360
res.cookie '_csrf', csrfToken, { expires, secure }
next()
| true | KONFIG = require 'koding-config-manager'
{ v4: createId } = require 'node-uuid'
module.exports = (req, res, next) ->
unless KONFIG.environment is 'production'
res.header 'Access-Control-Allow-Origin', 'http://www.koding.com'
next() if req?.cookies?._csrf
{ maxAge, secure } = KONFIG.sessionCookie
csrfToken = PI:KEY:<KEY>END_PIId()
# set cookie as pending cookie
req.pendingCookies or= {}
req.pendingCookies._csrf = csrfToken
expires = new Date Date.now() + 360
res.cookie '_csrf', csrfToken, { expires, secure }
next()
|
[
{
"context": "argv: targv),\n key: [\n \"val1\"\n \"val2\"\n \"val3\"\n ",
"end": 1000,
"score": 0.8621773719787598,
"start": 996,
"tag": "KEY",
"value": "val1"
},
{
"context": "argv: targv),\n key: [\n ... | tests/basic_test.coffee | skoberlink/uniformer-config | 0 | uniformer = require("../lib/uniformer-config")
exports.basicTests =
setUp: (done) ->
done()
"library load test": (test) ->
test.expect 1
test.doesNotThrow require("../lib/uniformer-config")
test.done()
"argv single/multi values test": (test) ->
test.expect 2
test.deepEqual uniformer(argv: [
"-key"
"value"
]),
key: "value"
, "check single value"
test.deepEqual uniformer(argv: [
"-key"
"value1"
"value2"
]),
key: [
"value1"
"value2"
]
, "check multi value"
test.done()
"argv key test": (test) ->
targv = undefined
test.expect 6
targv = process.argv.concat([
"-key"
"val1"
"val2"
"val3"
])
test.deepEqual uniformer(argv: targv),
key: [
"val1"
"val2"
"val3"
]
, "check -key"
targv = process.argv.concat([
"--key"
"val1"
"val2"
"val3"
])
test.deepEqual uniformer(argv: targv),
key: [
"val1"
"val2"
"val3"
]
, "check --key"
targv = process.argv.concat([
"-key"
"val1"
"val2"
"val3"
"-key2"
"two1"
"two2"
"two3"
])
test.deepEqual uniformer(argv: targv),
key: [
"val1"
"val2"
"val3"
]
key2: [
"two1"
"two2"
"two3"
]
, "check multi -key"
targv = process.argv.concat([
"--key"
"val1"
"val2"
"val3"
"--key2"
"two1"
"two2"
"two3"
])
test.deepEqual uniformer(argv: targv),
key: [
"val1"
"val2"
"val3"
]
key2: [
"two1"
"two2"
"two3"
]
, "check multi --key"
targv = process.argv.concat([
"--key"
"val1"
"val2"
"val3"
"-key2"
"two1"
"two2"
"two3"
])
test.deepEqual uniformer(argv: targv),
key: [
"val1"
"val2"
"val3"
]
key2: [
"two1"
"two2"
"two3"
]
, "check mixed -(-)keys"
targv = process.argv.concat([
"-key"
"val1"
"val2"
"val3"
"--key2"
"two1"
"two2"
"two3"
])
test.deepEqual uniformer(argv: targv),
key: [
"val1"
"val2"
"val3"
]
key2: [
"two1"
"two2"
"two3"
]
, "check mixed (-)-keys"
test.done()
"argv keyscope test": (test) ->
targv = undefined
test.expect 3
targv = process.argv.concat([
"-super.key"
"val1"
"val2"
"val3"
])
test.deepEqual uniformer(argv: targv),
super:
key: [
"val1"
"val2"
"val3"
]
, "check two level keys"
targv = process.argv.concat([
"-super.big.key"
"val1"
"val2"
"val3"
])
test.deepEqual uniformer(argv: targv),
super:
big:
key: [
"val1"
"val2"
"val3"
]
, "check three level keys"
targv = process.argv.concat([
"-super.key"
"val1"
"val2"
"val3"
"--super.pie"
"pie1"
"pie2"
"-cake"
"yum"
"i like"
])
test.deepEqual uniformer(argv: targv),
cake: [
"yum"
"i like"
]
super:
key: [
"val1"
"val2"
"val3"
]
pie: [
"pie1"
"pie2"
]
, "varying levels"
test.done()
"json test": (test) ->
test.expect 1
test.deepEqual uniformer(file: "tests/test_config.json"),
super:
big:
tree: true
hill: false
cat: 12
turtle: "ahh"
, "simple json"
test.done()
"yaml test": (test) ->
test.expect 1
test.deepEqual uniformer(file: "tests/test_config.yaml"),
super:
big:
tree: true
hill: false
cat: 12
turtle: "ahh"
, "simple yaml"
test.done()
"json merge test": (test) ->
test.expect 1
test.deepEqual uniformer(
file: "tests/test_config.json"
argv: [
"-super.man"
"cool"
"--super.big.tree"
"false"
"-super.big.hill"
"true"
]
),
super:
man: "cool"
big:
tree: false
hill: true
cat: 12
turtle: "ahh"
, "simple json merge"
test.done()
"yaml merge test": (test) ->
test.expect 1
test.deepEqual uniformer(
file: "tests/test_config.yaml"
argv: [
"-super.man"
"cool"
"--super.big.tree"
"false"
"-super.big.hill"
"true"
]
),
super:
man: "cool"
big:
tree: false
hill: true
cat: 12
turtle: "ahh"
, "simple yaml merge"
test.done()
"config argument test": (test) ->
test.expect 3
test.deepEqual uniformer(argv: [
"--config"
"tests/test_config.yaml"
]),
super:
big:
tree: true
hill: false
cat: 12
turtle: "ahh"
, "simple yaml via --config"
test.deepEqual uniformer(argv: [
"-config"
"tests/test_config.yaml"
]),
super:
big:
tree: true
hill: false
cat: 12
turtle: "ahh"
, "simple yaml via -config"
test.deepEqual uniformer(argv: [
"--config"
"tests/test_config.yaml"
"--extra"
"big"
"pie"
]),
super:
big:
tree: true
hill: false
cat: 12
turtle: "ahh"
extra: [
"big"
"pie"
]
, "simple yaml via --config with extra mixin"
test.done()
"defaults test": (test) ->
test.expect 1
test.deepEqual uniformer(
defaults:
given: true
override: false
argv: [
"--override"
"true"
"--extra"
"value"
]
),
given: true
override: true
extra: "value"
test.done() | 28382 | uniformer = require("../lib/uniformer-config")
exports.basicTests =
setUp: (done) ->
done()
"library load test": (test) ->
test.expect 1
test.doesNotThrow require("../lib/uniformer-config")
test.done()
"argv single/multi values test": (test) ->
test.expect 2
test.deepEqual uniformer(argv: [
"-key"
"value"
]),
key: "value"
, "check single value"
test.deepEqual uniformer(argv: [
"-key"
"value1"
"value2"
]),
key: [
"value1"
"value2"
]
, "check multi value"
test.done()
"argv key test": (test) ->
targv = undefined
test.expect 6
targv = process.argv.concat([
"-key"
"val1"
"val2"
"val3"
])
test.deepEqual uniformer(argv: targv),
key: [
"<KEY>"
"val2"
"val3"
]
, "check -key"
targv = process.argv.concat([
"--key"
"val1"
"val2"
"val3"
])
test.deepEqual uniformer(argv: targv),
key: [
"<KEY>"
"<KEY>2"
"<KEY>3"
]
, "check --key"
targv = process.argv.concat([
"-key"
"val1"
"val2"
"val3"
"-key2"
"two1"
"two2"
"two3"
])
test.deepEqual uniformer(argv: targv),
key: [
"<KEY>"
"<KEY>2"
"<KEY>3"
]
key2: [
"<KEY>"
"<KEY>"
"<KEY>"
]
, "check multi -key"
targv = process.argv.concat([
"--key"
"val1"
"val2"
"val3"
"--key2"
"two1"
"two2"
"two3"
])
test.deepEqual uniformer(argv: targv),
key: [
"val1"
"val2"
"val3"
]
key2: [
"<KEY>"
"<KEY>"
"<KEY>"
]
, "check multi --key"
targv = process.argv.concat([
"--key"
"val1"
"val2"
"val3"
"-key2"
"two1"
"two2"
"two3"
])
test.deepEqual uniformer(argv: targv),
key: [
"<KEY>"
"val2"
"val3"
]
key2: [
"<KEY>"
"<KEY>"
"<KEY>"
]
, "check mixed -(-)keys"
targv = process.argv.concat([
"-key"
"val1"
"val2"
"val3"
"--key2"
"two1"
"two2"
"two3"
])
test.deepEqual uniformer(argv: targv),
key: [
"<KEY>"
"<KEY>"
"<KEY>"
]
key2: [
"<KEY>"
"<KEY>"
"<KEY>"
]
, "check mixed (-)-keys"
test.done()
"argv keyscope test": (test) ->
targv = undefined
test.expect 3
targv = process.argv.concat([
"-super.key"
"val1"
"val2"
"val3"
])
test.deepEqual uniformer(argv: targv),
super:
key: [
"<KEY>"
"val2"
"val3"
]
, "check two level keys"
targv = process.argv.concat([
"-super.big.key"
"val1"
"val2"
"val3"
])
test.deepEqual uniformer(argv: targv),
super:
big:
key: [
"<KEY>"
"<KEY>"
"<KEY>"
]
, "check three level keys"
targv = process.argv.concat([
"-super.key"
"val1"
"val2"
"val3"
"--super.pie"
"pie1"
"pie2"
"-cake"
"yum"
"i like"
])
test.deepEqual uniformer(argv: targv),
cake: [
"yum"
"i like"
]
super:
key: [
"val1"
"val2"
"val3"
]
pie: [
"pie1"
"pie2"
]
, "varying levels"
test.done()
"json test": (test) ->
test.expect 1
test.deepEqual uniformer(file: "tests/test_config.json"),
super:
big:
tree: true
hill: false
cat: 12
turtle: "ahh"
, "simple json"
test.done()
"yaml test": (test) ->
test.expect 1
test.deepEqual uniformer(file: "tests/test_config.yaml"),
super:
big:
tree: true
hill: false
cat: 12
turtle: "ahh"
, "simple yaml"
test.done()
"json merge test": (test) ->
test.expect 1
test.deepEqual uniformer(
file: "tests/test_config.json"
argv: [
"-super.man"
"cool"
"--super.big.tree"
"false"
"-super.big.hill"
"true"
]
),
super:
man: "cool"
big:
tree: false
hill: true
cat: 12
turtle: "ahh"
, "simple json merge"
test.done()
"yaml merge test": (test) ->
test.expect 1
test.deepEqual uniformer(
file: "tests/test_config.yaml"
argv: [
"-super.man"
"cool"
"--super.big.tree"
"false"
"-super.big.hill"
"true"
]
),
super:
man: "cool"
big:
tree: false
hill: true
cat: 12
turtle: "ahh"
, "simple yaml merge"
test.done()
"config argument test": (test) ->
test.expect 3
test.deepEqual uniformer(argv: [
"--config"
"tests/test_config.yaml"
]),
super:
big:
tree: true
hill: false
cat: 12
turtle: "ahh"
, "simple yaml via --config"
test.deepEqual uniformer(argv: [
"-config"
"tests/test_config.yaml"
]),
super:
big:
tree: true
hill: false
cat: 12
turtle: "ahh"
, "simple yaml via -config"
test.deepEqual uniformer(argv: [
"--config"
"tests/test_config.yaml"
"--extra"
"big"
"pie"
]),
super:
big:
tree: true
hill: false
cat: 12
turtle: "ahh"
extra: [
"big"
"pie"
]
, "simple yaml via --config with extra mixin"
test.done()
"defaults test": (test) ->
test.expect 1
test.deepEqual uniformer(
defaults:
given: true
override: false
argv: [
"--override"
"true"
"--extra"
"value"
]
),
given: true
override: true
extra: "value"
test.done() | true | uniformer = require("../lib/uniformer-config")
exports.basicTests =
setUp: (done) ->
done()
"library load test": (test) ->
test.expect 1
test.doesNotThrow require("../lib/uniformer-config")
test.done()
"argv single/multi values test": (test) ->
test.expect 2
test.deepEqual uniformer(argv: [
"-key"
"value"
]),
key: "value"
, "check single value"
test.deepEqual uniformer(argv: [
"-key"
"value1"
"value2"
]),
key: [
"value1"
"value2"
]
, "check multi value"
test.done()
"argv key test": (test) ->
targv = undefined
test.expect 6
targv = process.argv.concat([
"-key"
"val1"
"val2"
"val3"
])
test.deepEqual uniformer(argv: targv),
key: [
"PI:KEY:<KEY>END_PI"
"val2"
"val3"
]
, "check -key"
targv = process.argv.concat([
"--key"
"val1"
"val2"
"val3"
])
test.deepEqual uniformer(argv: targv),
key: [
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI2"
"PI:KEY:<KEY>END_PI3"
]
, "check --key"
targv = process.argv.concat([
"-key"
"val1"
"val2"
"val3"
"-key2"
"two1"
"two2"
"two3"
])
test.deepEqual uniformer(argv: targv),
key: [
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI2"
"PI:KEY:<KEY>END_PI3"
]
key2: [
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
]
, "check multi -key"
targv = process.argv.concat([
"--key"
"val1"
"val2"
"val3"
"--key2"
"two1"
"two2"
"two3"
])
test.deepEqual uniformer(argv: targv),
key: [
"val1"
"val2"
"val3"
]
key2: [
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
]
, "check multi --key"
targv = process.argv.concat([
"--key"
"val1"
"val2"
"val3"
"-key2"
"two1"
"two2"
"two3"
])
test.deepEqual uniformer(argv: targv),
key: [
"PI:KEY:<KEY>END_PI"
"val2"
"val3"
]
key2: [
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
]
, "check mixed -(-)keys"
targv = process.argv.concat([
"-key"
"val1"
"val2"
"val3"
"--key2"
"two1"
"two2"
"two3"
])
test.deepEqual uniformer(argv: targv),
key: [
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
]
key2: [
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
]
, "check mixed (-)-keys"
test.done()
"argv keyscope test": (test) ->
targv = undefined
test.expect 3
targv = process.argv.concat([
"-super.key"
"val1"
"val2"
"val3"
])
test.deepEqual uniformer(argv: targv),
super:
key: [
"PI:KEY:<KEY>END_PI"
"val2"
"val3"
]
, "check two level keys"
targv = process.argv.concat([
"-super.big.key"
"val1"
"val2"
"val3"
])
test.deepEqual uniformer(argv: targv),
super:
big:
key: [
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
]
, "check three level keys"
targv = process.argv.concat([
"-super.key"
"val1"
"val2"
"val3"
"--super.pie"
"pie1"
"pie2"
"-cake"
"yum"
"i like"
])
test.deepEqual uniformer(argv: targv),
cake: [
"yum"
"i like"
]
super:
key: [
"val1"
"val2"
"val3"
]
pie: [
"pie1"
"pie2"
]
, "varying levels"
test.done()
"json test": (test) ->
test.expect 1
test.deepEqual uniformer(file: "tests/test_config.json"),
super:
big:
tree: true
hill: false
cat: 12
turtle: "ahh"
, "simple json"
test.done()
"yaml test": (test) ->
test.expect 1
test.deepEqual uniformer(file: "tests/test_config.yaml"),
super:
big:
tree: true
hill: false
cat: 12
turtle: "ahh"
, "simple yaml"
test.done()
"json merge test": (test) ->
test.expect 1
test.deepEqual uniformer(
file: "tests/test_config.json"
argv: [
"-super.man"
"cool"
"--super.big.tree"
"false"
"-super.big.hill"
"true"
]
),
super:
man: "cool"
big:
tree: false
hill: true
cat: 12
turtle: "ahh"
, "simple json merge"
test.done()
"yaml merge test": (test) ->
test.expect 1
test.deepEqual uniformer(
file: "tests/test_config.yaml"
argv: [
"-super.man"
"cool"
"--super.big.tree"
"false"
"-super.big.hill"
"true"
]
),
super:
man: "cool"
big:
tree: false
hill: true
cat: 12
turtle: "ahh"
, "simple yaml merge"
test.done()
"config argument test": (test) ->
test.expect 3
test.deepEqual uniformer(argv: [
"--config"
"tests/test_config.yaml"
]),
super:
big:
tree: true
hill: false
cat: 12
turtle: "ahh"
, "simple yaml via --config"
test.deepEqual uniformer(argv: [
"-config"
"tests/test_config.yaml"
]),
super:
big:
tree: true
hill: false
cat: 12
turtle: "ahh"
, "simple yaml via -config"
test.deepEqual uniformer(argv: [
"--config"
"tests/test_config.yaml"
"--extra"
"big"
"pie"
]),
super:
big:
tree: true
hill: false
cat: 12
turtle: "ahh"
extra: [
"big"
"pie"
]
, "simple yaml via --config with extra mixin"
test.done()
"defaults test": (test) ->
test.expect 1
test.deepEqual uniformer(
defaults:
given: true
override: false
argv: [
"--override"
"true"
"--extra"
"value"
]
),
given: true
override: true
extra: "value"
test.done() |
[
{
"context": "g.id is 'Hero Placeholder'\n name = {knight: 'Tharin', captain: 'Anya'}[@thang.type] ? 'Hero'\n else",
"end": 4974,
"score": 0.7735147476196289,
"start": 4968,
"tag": "NAME",
"value": "Tharin"
},
{
"context": "ally know who we are then.\n name = {knight: 'T... | app/views/play/level/LevelHUDView.coffee | enricpc/codecombat | 0 | CocoView = require 'views/kinds/CocoView'
template = require 'templates/play/level/hud'
prop_template = require 'templates/play/level/hud_prop'
action_template = require 'templates/play/level/hud_action'
DialogueAnimator = require './DialogueAnimator'
module.exports = class LevelHUDView extends CocoView
id: 'thang-hud'
template: template
dialogueMode: false
subscriptions:
'surface:frame-changed': 'onFrameChanged'
'level:disable-controls': 'onDisableControls'
'level:enable-controls': 'onEnableControls'
'surface:sprite-selected': 'onSpriteSelected'
'sprite:speech-updated': 'onSpriteDialogue'
'level:sprite-clear-dialogue': 'onSpriteClearDialogue'
'level:shift-space-pressed': 'onShiftSpacePressed'
'level:escape-pressed': 'onEscapePressed'
'sprite:dialogue-sound-completed': 'onDialogueSoundCompleted'
'sprite:thang-began-talking': 'onThangBeganTalking'
'sprite:thang-finished-talking': 'onThangFinishedTalking'
'god:new-world-created': 'onNewWorld'
events:
'click': 'onClick'
afterRender: ->
super()
@$el.addClass 'no-selection'
onClick: (e) ->
Backbone.Mediator.publish 'tome:focus-editor', {} unless $(e.target).parents('.thang-props').length
onFrameChanged: (e) ->
@timeProgress = e.progress
@update()
onDisableControls: (e) ->
return if e.controls and not ('hud' in e.controls)
@disabled = true
onEnableControls: (e) ->
return if e.controls and not ('hud' in e.controls)
@disabled = false
onSpriteSelected: (e) ->
# TODO: this allows the surface and HUD selection to get out of sync if we select another unit while in dialogue mode
return if @disabled or @dialogueMode
@switchToThangElements()
@setThang e.thang, e.sprite?.thangType
onSpriteDialogue: (e) ->
return unless e.message
spriteID = e.sprite.thang.id
@setSpeaker e.sprite
@stage?.startTalking()
@setMessage(e.message, e.mood, e.responses)
window.tracker?.trackEvent 'Heard Sprite', {speaker: spriteID, message: e.message, label: e.message}, ['Google Analytics']
onDialogueSoundCompleted: ->
@stage?.stopTalking()
onSpriteClearDialogue: ->
@clearSpeaker()
onNewWorld: (e) ->
hadThang = @thang
@thang = e.world.thangMap[@thang.id] if @thang
if hadThang and not @thang
@setThang null, null
else if @thang
@createActions() # Make sure it updates its actions.
setThang: (thang, thangType) ->
unless @speaker
if not thang? and not @thang? then return
if thang? and @thang? and thang.id is @thang.id then return
@thang = thang
@thangType = thangType
@$el.toggleClass 'no-selection', not @thang?
clearTimeout @hintNextSelectionTimeout
@$el.find('.no-selection-message').hide()
if not @thang
@hintNextSelectionTimeout = _.delay((=> @$el.find('.no-selection-message').slideDown('slow')), 10000)
return
@createAvatar thangType, @thang
@createProperties()
@createActions()
@update()
@speaker = null
setSpeaker: (speakerSprite) ->
return if speakerSprite is @speakerSprite
@speakerSprite = speakerSprite
@speaker = @speakerSprite.thang.id
@createAvatar @speakerSprite.thangType, @speakerSprite.thang, @speakerSprite.options.colorConfig
@$el.removeClass 'no-selection'
@switchToDialogueElements()
clearSpeaker: ->
if not @thang
@$el.addClass 'no-selection'
@setThang @thang, @thangType
@switchToThangElements()
@speaker = null
@speakerSprite = null
@bubble = null
@update()
createAvatar: (thangType, thang, colorConfig) ->
unless thangType.isFullyLoaded()
args = arguments
unless @listeningToCreateAvatar
@listenToOnce thangType, 'sync', -> @createAvatar(args...)
@listeningToCreateAvatar = true
return
@listeningToCreateAvatar = false
options = thang.getSpriteOptions() or {}
options.async = false
options.colorConfig = colorConfig if colorConfig
wrapper = @$el.find '.thang-canvas-wrapper'
team = @thang?.team or @speakerSprite?.thang?.team
wrapper.removeClass (i, css) -> (css.match(/\bteam-\S+/g) or []).join ' '
wrapper.addClass "team-#{team}"
if thangType.get('raster')
wrapper.empty().append($('<img />').attr('src', '/file/'+thangType.get('raster')))
else
return unless stage = thangType.getPortraitStage options
newCanvas = $(stage.canvas).addClass('thang-canvas')
wrapper.empty().append(newCanvas)
stage.update()
@stage?.stopTalking()
@stage = stage
onThangBeganTalking: (e) ->
return unless @stage and @thang is e.thang
@stage?.startTalking()
onThangFinishedTalking: (e) ->
return unless @stage and @thang is e.thang
@stage?.stopTalking()
createProperties: ->
props = @$el.find('.thang-props')
props.find(':not(.thang-name)').remove()
if @thang.id is 'Hero Placeholder'
name = {knight: 'Tharin', captain: 'Anya'}[@thang.type] ? 'Hero'
else
name = if @thang.type then "#{@thang.id} - #{@thang.type}" else @thang.id
props.find('.thang-name').text name
propNames = _.without @thang.hudProperties ? [], 'action'
nColumns = Math.ceil propNames.length / 5
columns = ($('<div class="thang-props-column"></div>').appendTo(props) for i in [0 ... nColumns])
for prop, i in propNames
continue if prop is 'action'
pel = @createPropElement prop
continue unless pel?
if pel.find('.bar').is('*') and props.find('.bar').is('*')
props.find('.bar-prop').last().after pel # Keep bars together
else
columns[i % nColumns].append pel
null
createActions: ->
actions = @$el.find('.thang-actions tbody').empty()
showActions = @thang.world and not @thang.notOfThisWorld and not _.isEmpty(@thang.actions) and 'action' in (@thang.hudProperties ? [])
@$el.find('.thang-actions').toggleClass 'secret', not showActions
return unless showActions
@buildActionTimespans()
for actionName, action of @thang.actions
actions.append @createActionElement(actionName)
@lastActionTimespans[actionName] = {}
setMessage: (message, mood, responses) ->
message = marked message
# Fix old HTML icons like <i class='icon-play'></i> in the Markdown
message = message.replace /<i class='(.+?)'><\/i>/, "<i class='$1'></i>"
clearInterval(@messageInterval) if @messageInterval
@bubble = $('.dialogue-bubble', @$el)
@bubble.removeClass(@lastMood) if @lastMood
@lastMood = mood
@bubble.text('')
group = $('<div class="enter secret"></div>')
@bubble.append(group)
if responses
@lastResponses = responses
for response in responses
button = $('<button class="btn btn-small banner"></button>').text(response.text)
button.addClass response.buttonClass if response.buttonClass
group.append(button)
response.button = $('button:last', group)
else
s = $.i18n.t('play_level.hud_continue', defaultValue: 'Continue (shift+space)')
sk = $.i18n.t('play_level.skip_tutorial', defaultValue: 'skip: esc')
if not @escapePressed
group.append('<span class="hud-hint">' + sk + '</span>')
group.append($('<button class="btn btn-small banner with-dot">' + s + ' <div class="dot"></div></button>'))
@lastResponses = null
if @speaker is 'Hero Placeholder'
# Doesn't work if it fires from a script; we don't really know who we are then.
name = {knight: 'Tharin', captain: 'Anya'}[@speakerSprite?.thang?.id] ? 'Hero'
else
name = @speaker
@bubble.append($("<h3>#{name}</h3>"))
@animator = new DialogueAnimator(message, @bubble)
@messageInterval = setInterval(@addMoreMessage, 1000 / 30) # 30 FPS
addMoreMessage: =>
if @animator.done()
clearInterval(@messageInterval)
@messageInterval = null
$('.enter', @bubble).removeClass('secret').css('opacity', 0.0).delay(500).animate({opacity: 1.0}, 500, @animateEnterButton)
if @lastResponses
buttons = $('.enter button')
for response, i in @lastResponses
channel = response.channel.replace 'level-set-playing', 'level:set-playing' # Easier than migrating all those victory buttons.
f = (r) => => setTimeout((-> Backbone.Mediator.publish(channel, r.event or {})), 10)
$(buttons[i]).click(f(response))
else
$('.enter', @bubble).click(-> Backbone.Mediator.publish('script:end-current-script', {}))
return
@animator.tick()
onShiftSpacePressed: (e) ->
@shiftSpacePressed = (@shiftSpacePressed || 0) + 1
# We don't need to handle script:end-current-script--that's done--but if we do have
# custom buttons, then we need to trigger the one that should fire (the last one).
# If we decide that always having the last one fire is bad, we should make it smarter.
return unless @lastResponses?.length
r = @lastResponses[@lastResponses.length - 1]
channel = r.channel.replace 'level-set-playing', 'level:set-playing'
_.delay (-> Backbone.Mediator.publish(channel, r.event or {})), 10
onEscapePressed: (e) ->
@escapePressed = true
animateEnterButton: =>
return unless @bubble
button = $('.enter', @bubble)
dot = $('.dot', button)
dot.animate({opacity: 0.2}, 300).animate({opacity: 1.9}, 600, @animateEnterButton)
switchToDialogueElements: ->
@dialogueMode = true
$('.thang-elem', @$el).addClass('secret')
@$el.find('.thang-canvas-wrapper').removeClass('secret')
$('.dialogue-area', @$el)
.removeClass('secret')
.animate({opacity: 1.0}, 200)
$('.dialogue-bubble', @$el)
.css('opacity', 0.0)
.delay(200)
.animate({opacity: 1.0}, 200)
clearTimeout @hintNextSelectionTimeout
switchToThangElements: ->
@dialogueMode = false
$('.thang-elem', @$el).removeClass('secret')
$('.dialogue-area', @$el).addClass('secret')
update: ->
return unless @thang and not @speaker
@$el.find('.thang-props-column').toggleClass 'nonexistent', not @thang.exists
if @thang.exists
@updatePropElement(prop, @thang[prop]) for prop in @thang.hudProperties ? []
# Update action timeline
@updateActions()
createPropElement: (prop) ->
if prop in ['maxHealth']
return null # included in the bar
context =
prop: prop
hasIcon: prop in ['health', 'pos', 'target', 'collectedThangIDs', 'gold', 'bountyGold', 'visualRange', 'attackDamage', 'attackRange', 'maxSpeed', 'attackNearbyEnemyRange']
hasBar: prop in ['health']
$(prop_template(context))
updatePropElement: (prop, val) ->
pel = @$el.find '.thang-props *[name=' + prop + ']'
if prop in ['maxHealth']
return # Don't show maxes--they're built into bar labels.
if prop in ['health']
max = @thang['max' + prop.charAt(0).toUpperCase() + prop.slice(1)]
regen = @thang[prop + 'ReplenishRate']
percent = Math.round 100 * val / max
pel.find('.bar').css 'width', percent + '%'
labelText = prop + ': ' + @formatValue(prop, val) + ' / ' + @formatValue(prop, max)
if regen
labelText += ' (+' + @formatValue(prop, regen) + '/s)'
pel.find('.bar-prop-value').text(Math.round(max)) if max
else
s = @formatValue(prop, val)
labelText = "#{prop}: #{s}"
if prop is 'attackDamage'
cooldown = @thang.actions.attack.cooldown
dps = @thang.attackDamage / cooldown
labelText += " / #{cooldown.toFixed(2)}s (DPS: #{dps.toFixed(2)})"
pel.find('.prop-value').text s
pel.attr 'title', labelText
pel
formatValue: (prop, val) ->
if prop is 'target' and not val
val = @thang['targetPos']
val = null if val?.isZero()
if prop is 'rotation'
return (val * 180 / Math.PI).toFixed(0) + '˚'
if prop.search(/Range$/) isnt -1
return val + 'm'
if typeof val is 'number'
if Math.round(val) == val or prop is 'gold' then return val.toFixed(0) # int
if -10 < val < 10 then return val.toFixed(2)
if -100 < val < 100 then return val.toFixed(1)
return val.toFixed(0)
if val and typeof val is 'object'
if val.id
return val.id
else if val.x and val.y
return "x: #{val.x.toFixed(0)} y: #{val.y.toFixed(0)}"
#return "x: #{val.x.toFixed(0)} y: #{val.y.toFixed(0)}, z: #{val.z.toFixed(0)}" # Debugging: include z
else if not val?
return 'No ' + prop
return val
updateActions: ->
return unless @thang.world and not _.isEmpty @thang.actions
@buildActionTimespans() unless @timespans
for actionName, action of @thang.actions
@updateActionElement(actionName, @timespans[actionName], @thang.action is actionName)
tableContainer = @$el.find('.table-container')
arrow = tableContainer.find('.progress-arrow')
@timelineWidth ||= tableContainer.find('tr:not(.secret) .action-timeline').width()
@actionArrowWidth ||= arrow.width()
right = (1 - (@timeProgress ? 0)) * @timelineWidth
arrow.css 'right', right - @actionArrowWidth / 2
tableContainer.find('.progress-line').css 'right', right
buildActionTimespans: ->
@lastActionTimespans = {}
@timespans = {}
dt = @thang.world.dt
actionHistory = @thang.world.actionsForThang @thang.id, true
[lastFrame, lastAction] = [0, null]
for hist in actionHistory.concat {frame: @thang.world.totalFrames, name: 'END'}
[newFrame, newAction] = [hist.frame, hist.name]
continue if newAction is lastAction
if newFrame > lastFrame and lastAction
# TODO: don't push it if it didn't exist until then
(@timespans[lastAction] ?= []).push [lastFrame * dt, newFrame * dt]
[lastFrame, lastAction] = [newFrame, newAction]
createActionElement: (action) ->
$(action_template(action: action))
updateActionElement: (action, timespans, current) ->
ael = @$el.find '.thang-actions *[name=' + action + ']'
ael.toggleClass 'current-action', current
timespans ?= []
lastTimespans = @lastActionTimespans[action] ? []
if @lastActionTimespans and timespans.length is lastTimespans.length
changed = false
for timespan, i in timespans
if timespan[0] isnt lastTimespans[i][0] or timespan[1] isnt lastTimespans[i][1]
changed = true
break
return unless changed
ael.toggleClass 'secret', not timespans.length
@lastActionTimespans[action] = timespans
timeline = ael.find('.action-timeline .timeline-wrapper').empty()
lifespan = @thang.world.totalFrames / @thang.world.frameRate
scale = timeline.width() / lifespan
for [start, end] in timespans
bar = $('<div></div>').css left: start * scale, right: (lifespan - end) * scale
timeline.append bar
ael
destroy: ->
@stage?.stopTalking()
clearInterval(@messageInterval) if @messageInterval
clearTimeout @hintNextSelectionTimeout if @hintNextSelectionTimeout
super()
| 37466 | CocoView = require 'views/kinds/CocoView'
template = require 'templates/play/level/hud'
prop_template = require 'templates/play/level/hud_prop'
action_template = require 'templates/play/level/hud_action'
DialogueAnimator = require './DialogueAnimator'
module.exports = class LevelHUDView extends CocoView
id: 'thang-hud'
template: template
dialogueMode: false
subscriptions:
'surface:frame-changed': 'onFrameChanged'
'level:disable-controls': 'onDisableControls'
'level:enable-controls': 'onEnableControls'
'surface:sprite-selected': 'onSpriteSelected'
'sprite:speech-updated': 'onSpriteDialogue'
'level:sprite-clear-dialogue': 'onSpriteClearDialogue'
'level:shift-space-pressed': 'onShiftSpacePressed'
'level:escape-pressed': 'onEscapePressed'
'sprite:dialogue-sound-completed': 'onDialogueSoundCompleted'
'sprite:thang-began-talking': 'onThangBeganTalking'
'sprite:thang-finished-talking': 'onThangFinishedTalking'
'god:new-world-created': 'onNewWorld'
events:
'click': 'onClick'
afterRender: ->
super()
@$el.addClass 'no-selection'
onClick: (e) ->
Backbone.Mediator.publish 'tome:focus-editor', {} unless $(e.target).parents('.thang-props').length
onFrameChanged: (e) ->
@timeProgress = e.progress
@update()
onDisableControls: (e) ->
return if e.controls and not ('hud' in e.controls)
@disabled = true
onEnableControls: (e) ->
return if e.controls and not ('hud' in e.controls)
@disabled = false
onSpriteSelected: (e) ->
# TODO: this allows the surface and HUD selection to get out of sync if we select another unit while in dialogue mode
return if @disabled or @dialogueMode
@switchToThangElements()
@setThang e.thang, e.sprite?.thangType
onSpriteDialogue: (e) ->
return unless e.message
spriteID = e.sprite.thang.id
@setSpeaker e.sprite
@stage?.startTalking()
@setMessage(e.message, e.mood, e.responses)
window.tracker?.trackEvent 'Heard Sprite', {speaker: spriteID, message: e.message, label: e.message}, ['Google Analytics']
onDialogueSoundCompleted: ->
@stage?.stopTalking()
onSpriteClearDialogue: ->
@clearSpeaker()
onNewWorld: (e) ->
hadThang = @thang
@thang = e.world.thangMap[@thang.id] if @thang
if hadThang and not @thang
@setThang null, null
else if @thang
@createActions() # Make sure it updates its actions.
setThang: (thang, thangType) ->
unless @speaker
if not thang? and not @thang? then return
if thang? and @thang? and thang.id is @thang.id then return
@thang = thang
@thangType = thangType
@$el.toggleClass 'no-selection', not @thang?
clearTimeout @hintNextSelectionTimeout
@$el.find('.no-selection-message').hide()
if not @thang
@hintNextSelectionTimeout = _.delay((=> @$el.find('.no-selection-message').slideDown('slow')), 10000)
return
@createAvatar thangType, @thang
@createProperties()
@createActions()
@update()
@speaker = null
setSpeaker: (speakerSprite) ->
return if speakerSprite is @speakerSprite
@speakerSprite = speakerSprite
@speaker = @speakerSprite.thang.id
@createAvatar @speakerSprite.thangType, @speakerSprite.thang, @speakerSprite.options.colorConfig
@$el.removeClass 'no-selection'
@switchToDialogueElements()
clearSpeaker: ->
if not @thang
@$el.addClass 'no-selection'
@setThang @thang, @thangType
@switchToThangElements()
@speaker = null
@speakerSprite = null
@bubble = null
@update()
createAvatar: (thangType, thang, colorConfig) ->
unless thangType.isFullyLoaded()
args = arguments
unless @listeningToCreateAvatar
@listenToOnce thangType, 'sync', -> @createAvatar(args...)
@listeningToCreateAvatar = true
return
@listeningToCreateAvatar = false
options = thang.getSpriteOptions() or {}
options.async = false
options.colorConfig = colorConfig if colorConfig
wrapper = @$el.find '.thang-canvas-wrapper'
team = @thang?.team or @speakerSprite?.thang?.team
wrapper.removeClass (i, css) -> (css.match(/\bteam-\S+/g) or []).join ' '
wrapper.addClass "team-#{team}"
if thangType.get('raster')
wrapper.empty().append($('<img />').attr('src', '/file/'+thangType.get('raster')))
else
return unless stage = thangType.getPortraitStage options
newCanvas = $(stage.canvas).addClass('thang-canvas')
wrapper.empty().append(newCanvas)
stage.update()
@stage?.stopTalking()
@stage = stage
onThangBeganTalking: (e) ->
return unless @stage and @thang is e.thang
@stage?.startTalking()
onThangFinishedTalking: (e) ->
return unless @stage and @thang is e.thang
@stage?.stopTalking()
createProperties: ->
props = @$el.find('.thang-props')
props.find(':not(.thang-name)').remove()
if @thang.id is 'Hero Placeholder'
name = {knight: '<NAME>', captain: 'Anya'}[@thang.type] ? 'Hero'
else
name = if @thang.type then "#{@thang.id} - #{@thang.type}" else @thang.id
props.find('.thang-name').text name
propNames = _.without @thang.hudProperties ? [], 'action'
nColumns = Math.ceil propNames.length / 5
columns = ($('<div class="thang-props-column"></div>').appendTo(props) for i in [0 ... nColumns])
for prop, i in propNames
continue if prop is 'action'
pel = @createPropElement prop
continue unless pel?
if pel.find('.bar').is('*') and props.find('.bar').is('*')
props.find('.bar-prop').last().after pel # Keep bars together
else
columns[i % nColumns].append pel
null
createActions: ->
actions = @$el.find('.thang-actions tbody').empty()
showActions = @thang.world and not @thang.notOfThisWorld and not _.isEmpty(@thang.actions) and 'action' in (@thang.hudProperties ? [])
@$el.find('.thang-actions').toggleClass 'secret', not showActions
return unless showActions
@buildActionTimespans()
for actionName, action of @thang.actions
actions.append @createActionElement(actionName)
@lastActionTimespans[actionName] = {}
setMessage: (message, mood, responses) ->
message = marked message
# Fix old HTML icons like <i class='icon-play'></i> in the Markdown
message = message.replace /<i class='(.+?)'><\/i>/, "<i class='$1'></i>"
clearInterval(@messageInterval) if @messageInterval
@bubble = $('.dialogue-bubble', @$el)
@bubble.removeClass(@lastMood) if @lastMood
@lastMood = mood
@bubble.text('')
group = $('<div class="enter secret"></div>')
@bubble.append(group)
if responses
@lastResponses = responses
for response in responses
button = $('<button class="btn btn-small banner"></button>').text(response.text)
button.addClass response.buttonClass if response.buttonClass
group.append(button)
response.button = $('button:last', group)
else
s = $.i18n.t('play_level.hud_continue', defaultValue: 'Continue (shift+space)')
sk = $.i18n.t('play_level.skip_tutorial', defaultValue: 'skip: esc')
if not @escapePressed
group.append('<span class="hud-hint">' + sk + '</span>')
group.append($('<button class="btn btn-small banner with-dot">' + s + ' <div class="dot"></div></button>'))
@lastResponses = null
if @speaker is 'Hero Placeholder'
# Doesn't work if it fires from a script; we don't really know who we are then.
name = {knight: '<NAME>', captain: '<NAME>'}[@speakerSprite?.thang?.id] ? 'Hero'
else
name = @speaker
@bubble.append($("<h3>#{name}</h3>"))
@animator = new DialogueAnimator(message, @bubble)
@messageInterval = setInterval(@addMoreMessage, 1000 / 30) # 30 FPS
addMoreMessage: =>
if @animator.done()
clearInterval(@messageInterval)
@messageInterval = null
$('.enter', @bubble).removeClass('secret').css('opacity', 0.0).delay(500).animate({opacity: 1.0}, 500, @animateEnterButton)
if @lastResponses
buttons = $('.enter button')
for response, i in @lastResponses
channel = response.channel.replace 'level-set-playing', 'level:set-playing' # Easier than migrating all those victory buttons.
f = (r) => => setTimeout((-> Backbone.Mediator.publish(channel, r.event or {})), 10)
$(buttons[i]).click(f(response))
else
$('.enter', @bubble).click(-> Backbone.Mediator.publish('script:end-current-script', {}))
return
@animator.tick()
onShiftSpacePressed: (e) ->
@shiftSpacePressed = (@shiftSpacePressed || 0) + 1
# We don't need to handle script:end-current-script--that's done--but if we do have
# custom buttons, then we need to trigger the one that should fire (the last one).
# If we decide that always having the last one fire is bad, we should make it smarter.
return unless @lastResponses?.length
r = @lastResponses[@lastResponses.length - 1]
channel = r.channel.replace 'level-set-playing', 'level:set-playing'
_.delay (-> Backbone.Mediator.publish(channel, r.event or {})), 10
onEscapePressed: (e) ->
@escapePressed = true
animateEnterButton: =>
return unless @bubble
button = $('.enter', @bubble)
dot = $('.dot', button)
dot.animate({opacity: 0.2}, 300).animate({opacity: 1.9}, 600, @animateEnterButton)
switchToDialogueElements: ->
@dialogueMode = true
$('.thang-elem', @$el).addClass('secret')
@$el.find('.thang-canvas-wrapper').removeClass('secret')
$('.dialogue-area', @$el)
.removeClass('secret')
.animate({opacity: 1.0}, 200)
$('.dialogue-bubble', @$el)
.css('opacity', 0.0)
.delay(200)
.animate({opacity: 1.0}, 200)
clearTimeout @hintNextSelectionTimeout
switchToThangElements: ->
@dialogueMode = false
$('.thang-elem', @$el).removeClass('secret')
$('.dialogue-area', @$el).addClass('secret')
update: ->
return unless @thang and not @speaker
@$el.find('.thang-props-column').toggleClass 'nonexistent', not @thang.exists
if @thang.exists
@updatePropElement(prop, @thang[prop]) for prop in @thang.hudProperties ? []
# Update action timeline
@updateActions()
createPropElement: (prop) ->
if prop in ['maxHealth']
return null # included in the bar
context =
prop: prop
hasIcon: prop in ['health', 'pos', 'target', 'collectedThangIDs', 'gold', 'bountyGold', 'visualRange', 'attackDamage', 'attackRange', 'maxSpeed', 'attackNearbyEnemyRange']
hasBar: prop in ['health']
$(prop_template(context))
updatePropElement: (prop, val) ->
pel = @$el.find '.thang-props *[name=' + prop + ']'
if prop in ['maxHealth']
return # Don't show maxes--they're built into bar labels.
if prop in ['health']
max = @thang['max' + prop.charAt(0).toUpperCase() + prop.slice(1)]
regen = @thang[prop + 'ReplenishRate']
percent = Math.round 100 * val / max
pel.find('.bar').css 'width', percent + '%'
labelText = prop + ': ' + @formatValue(prop, val) + ' / ' + @formatValue(prop, max)
if regen
labelText += ' (+' + @formatValue(prop, regen) + '/s)'
pel.find('.bar-prop-value').text(Math.round(max)) if max
else
s = @formatValue(prop, val)
labelText = "#{prop}: #{s}"
if prop is 'attackDamage'
cooldown = @thang.actions.attack.cooldown
dps = @thang.attackDamage / cooldown
labelText += " / #{cooldown.toFixed(2)}s (DPS: #{dps.toFixed(2)})"
pel.find('.prop-value').text s
pel.attr 'title', labelText
pel
formatValue: (prop, val) ->
if prop is 'target' and not val
val = @thang['targetPos']
val = null if val?.isZero()
if prop is 'rotation'
return (val * 180 / Math.PI).toFixed(0) + '˚'
if prop.search(/Range$/) isnt -1
return val + 'm'
if typeof val is 'number'
if Math.round(val) == val or prop is 'gold' then return val.toFixed(0) # int
if -10 < val < 10 then return val.toFixed(2)
if -100 < val < 100 then return val.toFixed(1)
return val.toFixed(0)
if val and typeof val is 'object'
if val.id
return val.id
else if val.x and val.y
return "x: #{val.x.toFixed(0)} y: #{val.y.toFixed(0)}"
#return "x: #{val.x.toFixed(0)} y: #{val.y.toFixed(0)}, z: #{val.z.toFixed(0)}" # Debugging: include z
else if not val?
return 'No ' + prop
return val
updateActions: ->
return unless @thang.world and not _.isEmpty @thang.actions
@buildActionTimespans() unless @timespans
for actionName, action of @thang.actions
@updateActionElement(actionName, @timespans[actionName], @thang.action is actionName)
tableContainer = @$el.find('.table-container')
arrow = tableContainer.find('.progress-arrow')
@timelineWidth ||= tableContainer.find('tr:not(.secret) .action-timeline').width()
@actionArrowWidth ||= arrow.width()
right = (1 - (@timeProgress ? 0)) * @timelineWidth
arrow.css 'right', right - @actionArrowWidth / 2
tableContainer.find('.progress-line').css 'right', right
buildActionTimespans: ->
@lastActionTimespans = {}
@timespans = {}
dt = @thang.world.dt
actionHistory = @thang.world.actionsForThang @thang.id, true
[lastFrame, lastAction] = [0, null]
for hist in actionHistory.concat {frame: @thang.world.totalFrames, name: 'END'}
[newFrame, newAction] = [hist.frame, hist.name]
continue if newAction is lastAction
if newFrame > lastFrame and lastAction
# TODO: don't push it if it didn't exist until then
(@timespans[lastAction] ?= []).push [lastFrame * dt, newFrame * dt]
[lastFrame, lastAction] = [newFrame, newAction]
createActionElement: (action) ->
$(action_template(action: action))
updateActionElement: (action, timespans, current) ->
ael = @$el.find '.thang-actions *[name=' + action + ']'
ael.toggleClass 'current-action', current
timespans ?= []
lastTimespans = @lastActionTimespans[action] ? []
if @lastActionTimespans and timespans.length is lastTimespans.length
changed = false
for timespan, i in timespans
if timespan[0] isnt lastTimespans[i][0] or timespan[1] isnt lastTimespans[i][1]
changed = true
break
return unless changed
ael.toggleClass 'secret', not timespans.length
@lastActionTimespans[action] = timespans
timeline = ael.find('.action-timeline .timeline-wrapper').empty()
lifespan = @thang.world.totalFrames / @thang.world.frameRate
scale = timeline.width() / lifespan
for [start, end] in timespans
bar = $('<div></div>').css left: start * scale, right: (lifespan - end) * scale
timeline.append bar
ael
destroy: ->
@stage?.stopTalking()
clearInterval(@messageInterval) if @messageInterval
clearTimeout @hintNextSelectionTimeout if @hintNextSelectionTimeout
super()
| true | CocoView = require 'views/kinds/CocoView'
template = require 'templates/play/level/hud'
prop_template = require 'templates/play/level/hud_prop'
action_template = require 'templates/play/level/hud_action'
DialogueAnimator = require './DialogueAnimator'
module.exports = class LevelHUDView extends CocoView
id: 'thang-hud'
template: template
dialogueMode: false
subscriptions:
'surface:frame-changed': 'onFrameChanged'
'level:disable-controls': 'onDisableControls'
'level:enable-controls': 'onEnableControls'
'surface:sprite-selected': 'onSpriteSelected'
'sprite:speech-updated': 'onSpriteDialogue'
'level:sprite-clear-dialogue': 'onSpriteClearDialogue'
'level:shift-space-pressed': 'onShiftSpacePressed'
'level:escape-pressed': 'onEscapePressed'
'sprite:dialogue-sound-completed': 'onDialogueSoundCompleted'
'sprite:thang-began-talking': 'onThangBeganTalking'
'sprite:thang-finished-talking': 'onThangFinishedTalking'
'god:new-world-created': 'onNewWorld'
events:
'click': 'onClick'
afterRender: ->
super()
@$el.addClass 'no-selection'
onClick: (e) ->
Backbone.Mediator.publish 'tome:focus-editor', {} unless $(e.target).parents('.thang-props').length
onFrameChanged: (e) ->
@timeProgress = e.progress
@update()
onDisableControls: (e) ->
return if e.controls and not ('hud' in e.controls)
@disabled = true
onEnableControls: (e) ->
return if e.controls and not ('hud' in e.controls)
@disabled = false
onSpriteSelected: (e) ->
# TODO: this allows the surface and HUD selection to get out of sync if we select another unit while in dialogue mode
return if @disabled or @dialogueMode
@switchToThangElements()
@setThang e.thang, e.sprite?.thangType
onSpriteDialogue: (e) ->
return unless e.message
spriteID = e.sprite.thang.id
@setSpeaker e.sprite
@stage?.startTalking()
@setMessage(e.message, e.mood, e.responses)
window.tracker?.trackEvent 'Heard Sprite', {speaker: spriteID, message: e.message, label: e.message}, ['Google Analytics']
onDialogueSoundCompleted: ->
@stage?.stopTalking()
onSpriteClearDialogue: ->
@clearSpeaker()
onNewWorld: (e) ->
hadThang = @thang
@thang = e.world.thangMap[@thang.id] if @thang
if hadThang and not @thang
@setThang null, null
else if @thang
@createActions() # Make sure it updates its actions.
setThang: (thang, thangType) ->
unless @speaker
if not thang? and not @thang? then return
if thang? and @thang? and thang.id is @thang.id then return
@thang = thang
@thangType = thangType
@$el.toggleClass 'no-selection', not @thang?
clearTimeout @hintNextSelectionTimeout
@$el.find('.no-selection-message').hide()
if not @thang
@hintNextSelectionTimeout = _.delay((=> @$el.find('.no-selection-message').slideDown('slow')), 10000)
return
@createAvatar thangType, @thang
@createProperties()
@createActions()
@update()
@speaker = null
setSpeaker: (speakerSprite) ->
return if speakerSprite is @speakerSprite
@speakerSprite = speakerSprite
@speaker = @speakerSprite.thang.id
@createAvatar @speakerSprite.thangType, @speakerSprite.thang, @speakerSprite.options.colorConfig
@$el.removeClass 'no-selection'
@switchToDialogueElements()
clearSpeaker: ->
if not @thang
@$el.addClass 'no-selection'
@setThang @thang, @thangType
@switchToThangElements()
@speaker = null
@speakerSprite = null
@bubble = null
@update()
createAvatar: (thangType, thang, colorConfig) ->
unless thangType.isFullyLoaded()
args = arguments
unless @listeningToCreateAvatar
@listenToOnce thangType, 'sync', -> @createAvatar(args...)
@listeningToCreateAvatar = true
return
@listeningToCreateAvatar = false
options = thang.getSpriteOptions() or {}
options.async = false
options.colorConfig = colorConfig if colorConfig
wrapper = @$el.find '.thang-canvas-wrapper'
team = @thang?.team or @speakerSprite?.thang?.team
wrapper.removeClass (i, css) -> (css.match(/\bteam-\S+/g) or []).join ' '
wrapper.addClass "team-#{team}"
if thangType.get('raster')
wrapper.empty().append($('<img />').attr('src', '/file/'+thangType.get('raster')))
else
return unless stage = thangType.getPortraitStage options
newCanvas = $(stage.canvas).addClass('thang-canvas')
wrapper.empty().append(newCanvas)
stage.update()
@stage?.stopTalking()
@stage = stage
onThangBeganTalking: (e) ->
return unless @stage and @thang is e.thang
@stage?.startTalking()
onThangFinishedTalking: (e) ->
return unless @stage and @thang is e.thang
@stage?.stopTalking()
createProperties: ->
props = @$el.find('.thang-props')
props.find(':not(.thang-name)').remove()
if @thang.id is 'Hero Placeholder'
name = {knight: 'PI:NAME:<NAME>END_PI', captain: 'Anya'}[@thang.type] ? 'Hero'
else
name = if @thang.type then "#{@thang.id} - #{@thang.type}" else @thang.id
props.find('.thang-name').text name
propNames = _.without @thang.hudProperties ? [], 'action'
nColumns = Math.ceil propNames.length / 5
columns = ($('<div class="thang-props-column"></div>').appendTo(props) for i in [0 ... nColumns])
for prop, i in propNames
continue if prop is 'action'
pel = @createPropElement prop
continue unless pel?
if pel.find('.bar').is('*') and props.find('.bar').is('*')
props.find('.bar-prop').last().after pel # Keep bars together
else
columns[i % nColumns].append pel
null
createActions: ->
actions = @$el.find('.thang-actions tbody').empty()
showActions = @thang.world and not @thang.notOfThisWorld and not _.isEmpty(@thang.actions) and 'action' in (@thang.hudProperties ? [])
@$el.find('.thang-actions').toggleClass 'secret', not showActions
return unless showActions
@buildActionTimespans()
for actionName, action of @thang.actions
actions.append @createActionElement(actionName)
@lastActionTimespans[actionName] = {}
setMessage: (message, mood, responses) ->
message = marked message
# Fix old HTML icons like <i class='icon-play'></i> in the Markdown
message = message.replace /<i class='(.+?)'><\/i>/, "<i class='$1'></i>"
clearInterval(@messageInterval) if @messageInterval
@bubble = $('.dialogue-bubble', @$el)
@bubble.removeClass(@lastMood) if @lastMood
@lastMood = mood
@bubble.text('')
group = $('<div class="enter secret"></div>')
@bubble.append(group)
if responses
@lastResponses = responses
for response in responses
button = $('<button class="btn btn-small banner"></button>').text(response.text)
button.addClass response.buttonClass if response.buttonClass
group.append(button)
response.button = $('button:last', group)
else
s = $.i18n.t('play_level.hud_continue', defaultValue: 'Continue (shift+space)')
sk = $.i18n.t('play_level.skip_tutorial', defaultValue: 'skip: esc')
if not @escapePressed
group.append('<span class="hud-hint">' + sk + '</span>')
group.append($('<button class="btn btn-small banner with-dot">' + s + ' <div class="dot"></div></button>'))
@lastResponses = null
if @speaker is 'Hero Placeholder'
# Doesn't work if it fires from a script; we don't really know who we are then.
name = {knight: 'PI:NAME:<NAME>END_PI', captain: 'PI:NAME:<NAME>END_PI'}[@speakerSprite?.thang?.id] ? 'Hero'
else
name = @speaker
@bubble.append($("<h3>#{name}</h3>"))
@animator = new DialogueAnimator(message, @bubble)
@messageInterval = setInterval(@addMoreMessage, 1000 / 30) # 30 FPS
addMoreMessage: =>
if @animator.done()
clearInterval(@messageInterval)
@messageInterval = null
$('.enter', @bubble).removeClass('secret').css('opacity', 0.0).delay(500).animate({opacity: 1.0}, 500, @animateEnterButton)
if @lastResponses
buttons = $('.enter button')
for response, i in @lastResponses
channel = response.channel.replace 'level-set-playing', 'level:set-playing' # Easier than migrating all those victory buttons.
f = (r) => => setTimeout((-> Backbone.Mediator.publish(channel, r.event or {})), 10)
$(buttons[i]).click(f(response))
else
$('.enter', @bubble).click(-> Backbone.Mediator.publish('script:end-current-script', {}))
return
@animator.tick()
onShiftSpacePressed: (e) ->
@shiftSpacePressed = (@shiftSpacePressed || 0) + 1
# We don't need to handle script:end-current-script--that's done--but if we do have
# custom buttons, then we need to trigger the one that should fire (the last one).
# If we decide that always having the last one fire is bad, we should make it smarter.
return unless @lastResponses?.length
r = @lastResponses[@lastResponses.length - 1]
channel = r.channel.replace 'level-set-playing', 'level:set-playing'
_.delay (-> Backbone.Mediator.publish(channel, r.event or {})), 10
onEscapePressed: (e) ->
@escapePressed = true
animateEnterButton: =>
return unless @bubble
button = $('.enter', @bubble)
dot = $('.dot', button)
dot.animate({opacity: 0.2}, 300).animate({opacity: 1.9}, 600, @animateEnterButton)
switchToDialogueElements: ->
@dialogueMode = true
$('.thang-elem', @$el).addClass('secret')
@$el.find('.thang-canvas-wrapper').removeClass('secret')
$('.dialogue-area', @$el)
.removeClass('secret')
.animate({opacity: 1.0}, 200)
$('.dialogue-bubble', @$el)
.css('opacity', 0.0)
.delay(200)
.animate({opacity: 1.0}, 200)
clearTimeout @hintNextSelectionTimeout
switchToThangElements: ->
@dialogueMode = false
$('.thang-elem', @$el).removeClass('secret')
$('.dialogue-area', @$el).addClass('secret')
update: ->
return unless @thang and not @speaker
@$el.find('.thang-props-column').toggleClass 'nonexistent', not @thang.exists
if @thang.exists
@updatePropElement(prop, @thang[prop]) for prop in @thang.hudProperties ? []
# Update action timeline
@updateActions()
createPropElement: (prop) ->
if prop in ['maxHealth']
return null # included in the bar
context =
prop: prop
hasIcon: prop in ['health', 'pos', 'target', 'collectedThangIDs', 'gold', 'bountyGold', 'visualRange', 'attackDamage', 'attackRange', 'maxSpeed', 'attackNearbyEnemyRange']
hasBar: prop in ['health']
$(prop_template(context))
updatePropElement: (prop, val) ->
pel = @$el.find '.thang-props *[name=' + prop + ']'
if prop in ['maxHealth']
return # Don't show maxes--they're built into bar labels.
if prop in ['health']
max = @thang['max' + prop.charAt(0).toUpperCase() + prop.slice(1)]
regen = @thang[prop + 'ReplenishRate']
percent = Math.round 100 * val / max
pel.find('.bar').css 'width', percent + '%'
labelText = prop + ': ' + @formatValue(prop, val) + ' / ' + @formatValue(prop, max)
if regen
labelText += ' (+' + @formatValue(prop, regen) + '/s)'
pel.find('.bar-prop-value').text(Math.round(max)) if max
else
s = @formatValue(prop, val)
labelText = "#{prop}: #{s}"
if prop is 'attackDamage'
cooldown = @thang.actions.attack.cooldown
dps = @thang.attackDamage / cooldown
labelText += " / #{cooldown.toFixed(2)}s (DPS: #{dps.toFixed(2)})"
pel.find('.prop-value').text s
pel.attr 'title', labelText
pel
formatValue: (prop, val) ->
if prop is 'target' and not val
val = @thang['targetPos']
val = null if val?.isZero()
if prop is 'rotation'
return (val * 180 / Math.PI).toFixed(0) + '˚'
if prop.search(/Range$/) isnt -1
return val + 'm'
if typeof val is 'number'
if Math.round(val) == val or prop is 'gold' then return val.toFixed(0) # int
if -10 < val < 10 then return val.toFixed(2)
if -100 < val < 100 then return val.toFixed(1)
return val.toFixed(0)
if val and typeof val is 'object'
if val.id
return val.id
else if val.x and val.y
return "x: #{val.x.toFixed(0)} y: #{val.y.toFixed(0)}"
#return "x: #{val.x.toFixed(0)} y: #{val.y.toFixed(0)}, z: #{val.z.toFixed(0)}" # Debugging: include z
else if not val?
return 'No ' + prop
return val
updateActions: ->
return unless @thang.world and not _.isEmpty @thang.actions
@buildActionTimespans() unless @timespans
for actionName, action of @thang.actions
@updateActionElement(actionName, @timespans[actionName], @thang.action is actionName)
tableContainer = @$el.find('.table-container')
arrow = tableContainer.find('.progress-arrow')
@timelineWidth ||= tableContainer.find('tr:not(.secret) .action-timeline').width()
@actionArrowWidth ||= arrow.width()
right = (1 - (@timeProgress ? 0)) * @timelineWidth
arrow.css 'right', right - @actionArrowWidth / 2
tableContainer.find('.progress-line').css 'right', right
buildActionTimespans: ->
@lastActionTimespans = {}
@timespans = {}
dt = @thang.world.dt
actionHistory = @thang.world.actionsForThang @thang.id, true
[lastFrame, lastAction] = [0, null]
for hist in actionHistory.concat {frame: @thang.world.totalFrames, name: 'END'}
[newFrame, newAction] = [hist.frame, hist.name]
continue if newAction is lastAction
if newFrame > lastFrame and lastAction
# TODO: don't push it if it didn't exist until then
(@timespans[lastAction] ?= []).push [lastFrame * dt, newFrame * dt]
[lastFrame, lastAction] = [newFrame, newAction]
createActionElement: (action) ->
$(action_template(action: action))
updateActionElement: (action, timespans, current) ->
ael = @$el.find '.thang-actions *[name=' + action + ']'
ael.toggleClass 'current-action', current
timespans ?= []
lastTimespans = @lastActionTimespans[action] ? []
if @lastActionTimespans and timespans.length is lastTimespans.length
changed = false
for timespan, i in timespans
if timespan[0] isnt lastTimespans[i][0] or timespan[1] isnt lastTimespans[i][1]
changed = true
break
return unless changed
ael.toggleClass 'secret', not timespans.length
@lastActionTimespans[action] = timespans
timeline = ael.find('.action-timeline .timeline-wrapper').empty()
lifespan = @thang.world.totalFrames / @thang.world.frameRate
scale = timeline.width() / lifespan
for [start, end] in timespans
bar = $('<div></div>').css left: start * scale, right: (lifespan - end) * scale
timeline.append bar
ael
destroy: ->
@stage?.stopTalking()
clearInterval(@messageInterval) if @messageInterval
clearTimeout @hintNextSelectionTimeout if @hintNextSelectionTimeout
super()
|
[
{
"context": "###\n# @author Argi Karunia <https://github.com/hkyo89>\n# @link https://gi",
"end": 27,
"score": 0.9998750686645508,
"start": 15,
"tag": "NAME",
"value": "Argi Karunia"
},
{
"context": "###\n# @author Argi Karunia <https://github.com/hkyo89>\n# @link https://gi... | src/assets.coffee | tokopedia/nodame | 2 | ###
# @author Argi Karunia <https://github.com/hkyo89>
# @link https://github.com/tokopedia/nodame
# @license http://opensource.org/licenses/MIT
#
# @version 1.0.0
###
Path = require('./path')
# TODO: Optimize the assets variable!
# So pricey!
class Assets
start = 0
constructor: (opt) ->
@_DESKTOP = 'desktop'
@_MOBILE = 'mobile'
@_CSS = 'css'
@_JS = 'js'
@_type = @_CSS
@_module = undefined
@_appPath = opt.appPath
@_isDev = opt.isDev
@_url = opt.url
@_assets = opt.assets
@_dir = opt.dir
@_device = if nodame.config('view.adaptive') then opt.device else 'desktop'
css : (mod) -> @_get_assets(@_CSS, mod)
js : (mod) -> @_get_assets(@_JS, mod)
_get_assets: (type, mod) ->
start = new Date()
@_device = @_MOBILE unless @_device is @_DESKTOP
@_type = type
@_module = mod
assets = []
# global assets
assetsName = @_get_valid_name('global')
assets.push @_html(assetsName)
# local assets
assetsName = @_get_valid_name(@_module)
assets.push @_html(assetsName) if assetsName?
return assets.join('')
_get_valid_name: (mod) ->
type = @_type
name = @_get_name(mod).replace(/[.][a-z]+$/gi, '')
re = new RegExp(name, 'gi')
for i of @_assets[type]
for _name of @_assets[type][i]
return _name if _name.match(re)
return
_get_config_dir: ->
confDir = @_dir
if confDir.substr(0, 1) is '/'
confDir = confDir
else
confDir = Path.safe("#{@_appPath}/#{confDir}")
return confDir
_get_name: (mod) -> "#{@_device}.#{mod}.min.#{@_type}"
_html: (name) ->
data = @_assets[@_type]
_html = []
if @_isDev
for i of data
if data[i][name]?
for j of data[i][name]
filepath = data[i][name][j]
_html.push @_html_tag(@_type, filepath)
else
_html.push @_html_tag(@_type, name)
end = new Date() - start
split_filename = name.split('.')
device = split_filename[0]
module = split_filename[1]
app_name = nodame.config('logger.clients.datadog.app_name')
log.stat.histogram "#{app_name}.assets.load_time", end, [
'env:' + nodame.env()
'filename:' + name
'type:' + @_type
'device:' + device
'module:' + module
]
return _html.join('')
_html_tag: (type, filepath) ->
configDir = @_get_config_dir()
typeDir = if @_isDev then @_type else 'min'
filepath = "#{@_url}/#{typeDir}/#{filepath}"
switch type
when @_CSS
_html = "<link href=\"#{filepath}\" type=\"text/css\" rel=\"stylesheet\">"
when @_JS
_html = "<script src=\"#{filepath}\" type=\"text/javascript\"></script>"
return _html
module.exports = Assets
| 216818 | ###
# @author <NAME> <https://github.com/hkyo89>
# @link https://github.com/tokopedia/nodame
# @license http://opensource.org/licenses/MIT
#
# @version 1.0.0
###
Path = require('./path')
# TODO: Optimize the assets variable!
# So pricey!
class Assets
start = 0
constructor: (opt) ->
@_DESKTOP = 'desktop'
@_MOBILE = 'mobile'
@_CSS = 'css'
@_JS = 'js'
@_type = @_CSS
@_module = undefined
@_appPath = opt.appPath
@_isDev = opt.isDev
@_url = opt.url
@_assets = opt.assets
@_dir = opt.dir
@_device = if nodame.config('view.adaptive') then opt.device else 'desktop'
css : (mod) -> @_get_assets(@_CSS, mod)
js : (mod) -> @_get_assets(@_JS, mod)
_get_assets: (type, mod) ->
start = new Date()
@_device = @_MOBILE unless @_device is @_DESKTOP
@_type = type
@_module = mod
assets = []
# global assets
assetsName = @_get_valid_name('global')
assets.push @_html(assetsName)
# local assets
assetsName = @_get_valid_name(@_module)
assets.push @_html(assetsName) if assetsName?
return assets.join('')
_get_valid_name: (mod) ->
type = @_type
name = @_get_name(mod).replace(/[.][a-z]+$/gi, '')
re = new RegExp(name, 'gi')
for i of @_assets[type]
for _name of @_assets[type][i]
return _name if _name.match(re)
return
_get_config_dir: ->
confDir = @_dir
if confDir.substr(0, 1) is '/'
confDir = confDir
else
confDir = Path.safe("#{@_appPath}/#{confDir}")
return confDir
_get_name: (mod) -> "#{@_device}.#{mod}.min.#{@_type}"
_html: (name) ->
data = @_assets[@_type]
_html = []
if @_isDev
for i of data
if data[i][name]?
for j of data[i][name]
filepath = data[i][name][j]
_html.push @_html_tag(@_type, filepath)
else
_html.push @_html_tag(@_type, name)
end = new Date() - start
split_filename = name.split('.')
device = split_filename[0]
module = split_filename[1]
app_name = nodame.config('logger.clients.datadog.app_name')
log.stat.histogram "#{app_name}.assets.load_time", end, [
'env:' + nodame.env()
'filename:' + name
'type:' + @_type
'device:' + device
'module:' + module
]
return _html.join('')
_html_tag: (type, filepath) ->
configDir = @_get_config_dir()
typeDir = if @_isDev then @_type else 'min'
filepath = "#{@_url}/#{typeDir}/#{filepath}"
switch type
when @_CSS
_html = "<link href=\"#{filepath}\" type=\"text/css\" rel=\"stylesheet\">"
when @_JS
_html = "<script src=\"#{filepath}\" type=\"text/javascript\"></script>"
return _html
module.exports = Assets
| true | ###
# @author PI:NAME:<NAME>END_PI <https://github.com/hkyo89>
# @link https://github.com/tokopedia/nodame
# @license http://opensource.org/licenses/MIT
#
# @version 1.0.0
###
Path = require('./path')
# TODO: Optimize the assets variable!
# So pricey!
class Assets
start = 0
constructor: (opt) ->
@_DESKTOP = 'desktop'
@_MOBILE = 'mobile'
@_CSS = 'css'
@_JS = 'js'
@_type = @_CSS
@_module = undefined
@_appPath = opt.appPath
@_isDev = opt.isDev
@_url = opt.url
@_assets = opt.assets
@_dir = opt.dir
@_device = if nodame.config('view.adaptive') then opt.device else 'desktop'
css : (mod) -> @_get_assets(@_CSS, mod)
js : (mod) -> @_get_assets(@_JS, mod)
_get_assets: (type, mod) ->
start = new Date()
@_device = @_MOBILE unless @_device is @_DESKTOP
@_type = type
@_module = mod
assets = []
# global assets
assetsName = @_get_valid_name('global')
assets.push @_html(assetsName)
# local assets
assetsName = @_get_valid_name(@_module)
assets.push @_html(assetsName) if assetsName?
return assets.join('')
_get_valid_name: (mod) ->
type = @_type
name = @_get_name(mod).replace(/[.][a-z]+$/gi, '')
re = new RegExp(name, 'gi')
for i of @_assets[type]
for _name of @_assets[type][i]
return _name if _name.match(re)
return
_get_config_dir: ->
confDir = @_dir
if confDir.substr(0, 1) is '/'
confDir = confDir
else
confDir = Path.safe("#{@_appPath}/#{confDir}")
return confDir
_get_name: (mod) -> "#{@_device}.#{mod}.min.#{@_type}"
_html: (name) ->
data = @_assets[@_type]
_html = []
if @_isDev
for i of data
if data[i][name]?
for j of data[i][name]
filepath = data[i][name][j]
_html.push @_html_tag(@_type, filepath)
else
_html.push @_html_tag(@_type, name)
end = new Date() - start
split_filename = name.split('.')
device = split_filename[0]
module = split_filename[1]
app_name = nodame.config('logger.clients.datadog.app_name')
log.stat.histogram "#{app_name}.assets.load_time", end, [
'env:' + nodame.env()
'filename:' + name
'type:' + @_type
'device:' + device
'module:' + module
]
return _html.join('')
_html_tag: (type, filepath) ->
configDir = @_get_config_dir()
typeDir = if @_isDev then @_type else 'min'
filepath = "#{@_url}/#{typeDir}/#{filepath}"
switch type
when @_CSS
_html = "<link href=\"#{filepath}\" type=\"text/css\" rel=\"stylesheet\">"
when @_JS
_html = "<script src=\"#{filepath}\" type=\"text/javascript\"></script>"
return _html
module.exports = Assets
|
[
{
"context": "r}/authorized_keys\"\n keys: [\n 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCgccoXaSKaovgSkE",
"end": 520,
"score": 0.5245014429092407,
"start": 520,
"tag": "KEY",
"value": ""
},
{
"context": "uthorized_keys\"\n keys: [\n 'ssh-rsa AAAAB3NzaC1... | packages/file/test/types/ssh_authorized_keys.coffee | shivaylamba/meilisearch-gatsby-plugin-guide | 31 |
nikita = require '@nikitajs/core/lib'
{tags, config} = require '../test'
they = require('mocha-they')(config)
return unless tags.posix
describe 'file.types.ssh_authorized_keys', ->
they 'overwrite file', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
@file
target: "#{tmpdir}/authorized_keys"
content: "# Some Comment"
{$status} = await @file.types.ssh_authorized_keys
target: "#{tmpdir}/authorized_keys"
keys: [
'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCgccoXaSKaovgSkExo09Vv6PJmJEjIwrD+MQTLUQrhM6dSCQ40KNJkLATsrm3p14QGzT2G5IiIUVfl/dwXUS5kqOKRYJUBl5o1ETzxWCUzWUcaY7JmrAlQwQgBMwtwv/ClpYqjiHwGcoMOuobumXfsyz7f3CuqvrldQEfcv/f0u7t/78nVceDE4mjlMGH/bwyzH09CYHPnLW9S/Jvhw5hbyCTDDqheCZHb+Y3xecRV+fGDfH7onn/FWu9JRj0UWkzGZoCp8Lj5hZ/mAF2fqH5tbW36DkC66zi3jJNI2cwARHxH1TQ8DeDKnUjaY7J03CbB+RIaKh5KjbEquqWlTQSP Some Description'
]
$status.should.be.true()
@fs.assert
target: "#{tmpdir}/authorized_keys"
content: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCgccoXaSKaovgSkExo09Vv6PJmJEjIwrD+MQTLUQrhM6dSCQ40KNJkLATsrm3p14QGzT2G5IiIUVfl/dwXUS5kqOKRYJUBl5o1ETzxWCUzWUcaY7JmrAlQwQgBMwtwv/ClpYqjiHwGcoMOuobumXfsyz7f3CuqvrldQEfcv/f0u7t/78nVceDE4mjlMGH/bwyzH09CYHPnLW9S/Jvhw5hbyCTDDqheCZHb+Y3xecRV+fGDfH7onn/FWu9JRj0UWkzGZoCp8Lj5hZ/mAF2fqH5tbW36DkC66zi3jJNI2cwARHxH1TQ8DeDKnUjaY7J03CbB+RIaKh5KjbEquqWlTQSP Some Description\n"
they 'merge file', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
@file
target: "#{tmpdir}/authorized_keys"
content: "# Some Comment"
{$status} = await @file.types.ssh_authorized_keys
target: "#{tmpdir}/authorized_keys"
keys: [
'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCgccoXaSKaovgSkExo09Vv6PJmJEjIwrD+MQTLUQrhM6dSCQ40KNJkLATsrm3p14QGzT2G5IiIUVfl/dwXUS5kqOKRYJUBl5o1ETzxWCUzWUcaY7JmrAlQwQgBMwtwv/ClpYqjiHwGcoMOuobumXfsyz7f3CuqvrldQEfcv/f0u7t/78nVceDE4mjlMGH/bwyzH09CYHPnLW9S/Jvhw5hbyCTDDqheCZHb+Y3xecRV+fGDfH7onn/FWu9JRj0UWkzGZoCp8Lj5hZ/mAF2fqH5tbW36DkC66zi3jJNI2cwARHxH1TQ8DeDKnUjaY7J03CbB+RIaKh5KjbEquqWlTQSP Some Description'
]
merge: true
$status.should.be.true()
@fs.assert
target: "#{tmpdir}/authorized_keys"
content: """
# Some Comment
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCgccoXaSKaovgSkExo09Vv6PJmJEjIwrD+MQTLUQrhM6dSCQ40KNJkLATsrm3p14QGzT2G5IiIUVfl/dwXUS5kqOKRYJUBl5o1ETzxWCUzWUcaY7JmrAlQwQgBMwtwv/ClpYqjiHwGcoMOuobumXfsyz7f3CuqvrldQEfcv/f0u7t/78nVceDE4mjlMGH/bwyzH09CYHPnLW9S/Jvhw5hbyCTDDqheCZHb+Y3xecRV+fGDfH7onn/FWu9JRj0UWkzGZoCp8Lj5hZ/mAF2fqH5tbW36DkC66zi3jJNI2cwARHxH1TQ8DeDKnUjaY7J03CbB+RIaKh5KjbEquqWlTQSP Some Description\n
"""
| 8872 |
nikita = require '@nikitajs/core/lib'
{tags, config} = require '../test'
they = require('mocha-they')(config)
return unless tags.posix
describe 'file.types.ssh_authorized_keys', ->
they 'overwrite file', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
@file
target: "#{tmpdir}/authorized_keys"
content: "# Some Comment"
{$status} = await @file.types.ssh_authorized_keys
target: "#{tmpdir}/authorized_keys"
keys: [
'ssh<KEY>-rsa <KEY>'
]
$status.should.be.true()
@fs.assert
target: "#{tmpdir}/authorized_keys"
content: "ssh-rsa <KEY> Some Description<KEY>\n"
they 'merge file', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
@file
target: "#{tmpdir}/authorized_keys"
content: "# Some Comment"
{$status} = await @file.types.ssh_authorized_keys
target: "#{tmpdir}/authorized_keys"
keys: [
'<KEY>CbB+RIaKh5KjbEquqWlTQSP Some Description'
]
merge: true
$status.should.be.true()
@fs.assert
target: "#{tmpdir}/authorized_keys"
content: """
# Some Comment
ssh-rsa <KEY> Some Description\n
"""
| true |
nikita = require '@nikitajs/core/lib'
{tags, config} = require '../test'
they = require('mocha-they')(config)
return unless tags.posix
describe 'file.types.ssh_authorized_keys', ->
they 'overwrite file', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
@file
target: "#{tmpdir}/authorized_keys"
content: "# Some Comment"
{$status} = await @file.types.ssh_authorized_keys
target: "#{tmpdir}/authorized_keys"
keys: [
'sshPI:KEY:<KEY>END_PI-rsa PI:KEY:<KEY>END_PI'
]
$status.should.be.true()
@fs.assert
target: "#{tmpdir}/authorized_keys"
content: "ssh-rsa PI:KEY:<KEY>END_PI Some DescriptionPI:KEY:<KEY>END_PI\n"
they 'merge file', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
@file
target: "#{tmpdir}/authorized_keys"
content: "# Some Comment"
{$status} = await @file.types.ssh_authorized_keys
target: "#{tmpdir}/authorized_keys"
keys: [
'PI:KEY:<KEY>END_PICbB+RIaKh5KjbEquqWlTQSP Some Description'
]
merge: true
$status.should.be.true()
@fs.assert
target: "#{tmpdir}/authorized_keys"
content: """
# Some Comment
ssh-rsa PI:KEY:<KEY>END_PI Some Description\n
"""
|
[
{
"context": " userId = Accounts.createUser\n username: user.username,\n email: user.email,\n password:",
"end": 687,
"score": 0.9618425965309143,
"start": 674,
"tag": "USERNAME",
"value": "user.username"
},
{
"context": ",\n email: user.email,\n ... | server/entry.coffee | Vilango/accounts-entry | 0 | Meteor.startup ->
Accounts.urls.resetPassword = (token) ->
Meteor.absoluteUrl('reset-password/' + token)
AccountsEntry =
settings: {}
config: (appConfig) ->
@settings = _.extend(@settings, appConfig)
@AccountsEntry = AccountsEntry
Meteor.methods
entryValidateSignupCode: (signupCode) ->
check signupCode, Match.OneOf(String, null, undefined)
not AccountsEntry.settings.signupCode or signupCode is AccountsEntry.settings.signupCode
entryCreateUser: (user) ->
check user, Object
profile = AccountsEntry.settings.defaultProfile || {}
if user.username
userId = Accounts.createUser
username: user.username,
email: user.email,
password: user.password,
profile: _.extend(profile, user.profile)
else
userId = Accounts.createUser
email: user.email
password: user.password
profile: _.extend(profile, user.profile)
if (user.email && Accounts._options.sendVerificationEmail)
@unblock()
Accounts.sendVerificationEmail(userId, user.email)
return userId
| 147995 | Meteor.startup ->
Accounts.urls.resetPassword = (token) ->
Meteor.absoluteUrl('reset-password/' + token)
AccountsEntry =
settings: {}
config: (appConfig) ->
@settings = _.extend(@settings, appConfig)
@AccountsEntry = AccountsEntry
Meteor.methods
entryValidateSignupCode: (signupCode) ->
check signupCode, Match.OneOf(String, null, undefined)
not AccountsEntry.settings.signupCode or signupCode is AccountsEntry.settings.signupCode
entryCreateUser: (user) ->
check user, Object
profile = AccountsEntry.settings.defaultProfile || {}
if user.username
userId = Accounts.createUser
username: user.username,
email: user.email,
password: <PASSWORD>,
profile: _.extend(profile, user.profile)
else
userId = Accounts.createUser
email: user.email
password: <PASSWORD>
profile: _.extend(profile, user.profile)
if (user.email && Accounts._options.sendVerificationEmail)
@unblock()
Accounts.sendVerificationEmail(userId, user.email)
return userId
| true | Meteor.startup ->
Accounts.urls.resetPassword = (token) ->
Meteor.absoluteUrl('reset-password/' + token)
AccountsEntry =
settings: {}
config: (appConfig) ->
@settings = _.extend(@settings, appConfig)
@AccountsEntry = AccountsEntry
Meteor.methods
entryValidateSignupCode: (signupCode) ->
check signupCode, Match.OneOf(String, null, undefined)
not AccountsEntry.settings.signupCode or signupCode is AccountsEntry.settings.signupCode
entryCreateUser: (user) ->
check user, Object
profile = AccountsEntry.settings.defaultProfile || {}
if user.username
userId = Accounts.createUser
username: user.username,
email: user.email,
password: PI:PASSWORD:<PASSWORD>END_PI,
profile: _.extend(profile, user.profile)
else
userId = Accounts.createUser
email: user.email
password: PI:PASSWORD:<PASSWORD>END_PI
profile: _.extend(profile, user.profile)
if (user.email && Accounts._options.sendVerificationEmail)
@unblock()
Accounts.sendVerificationEmail(userId, user.email)
return userId
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999105334281921,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/_classes/account-edit-blocklist.coffee | osu-katakuna/osu-katakuna-web | 5 | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
class @AccountEditBlocklist
element: 'block-list__content'
jsClass: '.js-account-edit-blocklist'
constructor: ->
$(document).on 'click', @jsClass, @toggle
$.subscribe 'user:update', @updateBlockCount
updateBlockCount: =>
return unless currentUser.id?
$("#{@jsClass}-count").text osu.trans('users.blocks.blocked_count', count: currentUser.blocks?.length ? 0)
toggle: (e) =>
e.preventDefault()
$(".#{@element}").toggleClass('hidden')
label =
if $(".#{@element}").hasClass('hidden')
osu.trans 'common.buttons.show'
else
osu.trans 'common.buttons.hide'
$(@jsClass).text label
| 92379 | # 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.
class @AccountEditBlocklist
element: 'block-list__content'
jsClass: '.js-account-edit-blocklist'
constructor: ->
$(document).on 'click', @jsClass, @toggle
$.subscribe 'user:update', @updateBlockCount
updateBlockCount: =>
return unless currentUser.id?
$("#{@jsClass}-count").text osu.trans('users.blocks.blocked_count', count: currentUser.blocks?.length ? 0)
toggle: (e) =>
e.preventDefault()
$(".#{@element}").toggleClass('hidden')
label =
if $(".#{@element}").hasClass('hidden')
osu.trans 'common.buttons.show'
else
osu.trans 'common.buttons.hide'
$(@jsClass).text label
| 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.
class @AccountEditBlocklist
element: 'block-list__content'
jsClass: '.js-account-edit-blocklist'
constructor: ->
$(document).on 'click', @jsClass, @toggle
$.subscribe 'user:update', @updateBlockCount
updateBlockCount: =>
return unless currentUser.id?
$("#{@jsClass}-count").text osu.trans('users.blocks.blocked_count', count: currentUser.blocks?.length ? 0)
toggle: (e) =>
e.preventDefault()
$(".#{@element}").toggleClass('hidden')
label =
if $(".#{@element}").hasClass('hidden')
osu.trans 'common.buttons.show'
else
osu.trans 'common.buttons.hide'
$(@jsClass).text label
|
[
{
"context": "t']\nprivateProperties = ['permissions', 'email', 'firstName', 'lastName', 'gender', 'facebookID', 'music', 'v",
"end": 416,
"score": 0.9973228573799133,
"start": 407,
"tag": "NAME",
"value": "firstName"
},
{
"context": "operties = ['permissions', 'email', 'firstName', ... | server/users/user_handler.coffee | JeremyGeros/codecombat | 0 | schema = require './user_schema'
crypto = require 'crypto'
request = require 'request'
User = require './User'
Handler = require '../commons/Handler'
mongoose = require 'mongoose'
config = require '../../server_config'
errors = require '../commons/errors'
async = require 'async'
serverProperties = ['passwordHash', 'emailLower', 'nameLower', 'passwordReset']
privateProperties = ['permissions', 'email', 'firstName', 'lastName', 'gender', 'facebookID', 'music', 'volume', 'aceConfig']
UserHandler = class UserHandler extends Handler
modelClass: User
editableProperties: [
'name', 'photoURL', 'password', 'anonymous', 'wizardColor1', 'volume',
'firstName', 'lastName', 'gender', 'facebookID', 'emailSubscriptions',
'testGroupNumber', 'music', 'hourOfCode', 'hourOfCodeComplete', 'preferredLanguage',
'wizard', 'aceConfig'
]
jsonSchema: schema
constructor: ->
super(arguments...)
@editableProperties.push('permissions') unless config.isProduction
formatEntity: (req, document) ->
return null unless document?
obj = document.toObject()
delete obj[prop] for prop in serverProperties
includePrivates = req.user and (req.user?.isAdmin() or req.user?._id.equals(document._id))
delete obj[prop] for prop in privateProperties unless includePrivates
# emailHash is used by gravatar
hash = crypto.createHash('md5')
if document.get('email')
hash.update(_.trim(document.get('email')).toLowerCase())
else
hash.update(@_id+'')
obj.emailHash = hash.digest('hex')
return obj
waterfallFunctions: [
# FB access token checking
# Check the email is the same as FB reports
(req, user, callback) ->
fbID = req.query.facebookID
fbAT = req.query.facebookAccessToken
return callback(null, req, user) unless fbID and fbAT
url = "https://graph.facebook.com/me?access_token=#{fbAT}"
request(url, (error, response, body) ->
body = JSON.parse(body)
emailsMatch = req.body.email is body.email
return callback(res:'Invalid Facebook Access Token.', code:422) unless emailsMatch
callback(null, req, user)
)
# GPlus access token checking
(req, user, callback) ->
gpID = req.query.gplusID
gpAT = req.query.gplusAccessToken
return callback(null, req, user) unless gpID and gpAT
url = "https://www.googleapis.com/oauth2/v2/userinfo?access_token=#{gpAT}"
request(url, (error, response, body) ->
body = JSON.parse(body)
emailsMatch = req.body.email is body.email
return callback(res:'Invalid G+ Access Token.', code:422) unless emailsMatch
callback(null, req, user)
)
# Email setting
(req, user, callback) ->
return callback(null, req, user) unless req.body.email?
emailLower = req.body.email.toLowerCase()
return callback(null, req, user) if emailLower is user.get('emailLower')
User.findOne({emailLower:emailLower}).exec (err, otherUser) ->
return callback(res:'Database error.', code:500) if err
if (req.query.gplusID or req.query.facebookID) and otherUser
# special case, log in as that user
return req.logIn(otherUser, (err) ->
return callback(res:'Facebook user login error.', code:500) if err
return callback(null, req, otherUser)
)
r = {message:'is already used by another account', property:'email'}
return callback({res:r, code:409}) if otherUser
user.set('email', req.body.email)
callback(null, req, user)
# Name setting
(req, user, callback) ->
return callback(null, req, user) unless req.body.name
nameLower = req.body.name?.toLowerCase()
return callback(null, req, user) if nameLower is user.get('nameLower')
User.findOne({nameLower:nameLower}).exec (err, otherUser) ->
return callback(res:'Database error.', code:500) if err
r = {message:'is already used by another account', property:'name'}
return callback({res:r, code:409}) if otherUser
user.set('name', req.body.name)
callback(null, req, user)
]
getById: (req, res, id) ->
if req.user?._id.equals(id)
return @sendSuccess(res, @formatEntity(req, req.user))
super(req, res, id)
getNamesByIds: (req, res) ->
ids = req.query.ids or req.body.ids
ids = ids.split(',') if _.isString ids
ids = _.uniq ids
# TODO: Extend and repurpose this handler to return other public info about a user more flexibly,
# say by a query parameter that lists public properties to return.
returnWizard = req.query.wizard or req.body.wizard
query = if returnWizard then {name:1, wizard:1} else {name:1}
makeFunc = (id) ->
(callback) ->
User.findById(id, query).exec (err, document) ->
return done(err) if err
if document and returnWizard
callback(null, {name:document.get('name'), wizard:document.get('wizard') or {}})
else
callback(null, document?.get('name') or '')
funcs = {}
for id in ids
return errors.badInput(res, "Given an invalid id: #{id}") unless Handler.isID(id)
funcs[id] = makeFunc(id)
async.parallel funcs, (err, results) ->
return errors.serverError err if err
res.send results
res.end()
nameToID: (req, res, name) ->
User.findOne({nameLower:name.toLowerCase()}).exec (err, otherUser) ->
res.send(if otherUser then otherUser._id else JSON.stringify(''))
res.end()
post: (req, res) ->
return @sendBadInputError(res, 'No input.') if _.isEmpty(req.body)
return @sendBadInputError(res, 'Must have an anonymous user to post with.') unless req.user
return @sendBadInputError(res, 'Existing users cannot create new ones.') unless req.user.get('anonymous')
req.body._id = req.user._id if req.user.get('anonymous')
@put(req, res)
hasAccessToDocument: (req, document) ->
if req.route.method in ['put', 'post', 'patch']
return true if req.user?.isAdmin()
return req.user?._id.equals(document._id)
return true
getByRelationship: (req, res, args...) ->
return @agreeToCLA(req, res) if args[1] is 'agreeToCLA'
return @avatar(req, res, args[0]) if args[1] is 'avatar'
return @getNamesByIds(req, res) if args[1] is 'names'
return @nameToID(req, res, args[0]) if args[1] is 'nameToID'
return @sendNotFoundError(res)
agreeToCLA: (req, res) ->
return @sendUnauthorizedError(res) unless req.user
doc =
user: req.user._id+''
email: req.user.get 'email'
name: req.user.get 'name'
githubUsername: req.body.githubUsername
created: new Date()+''
collection = mongoose.connection.db.collection 'cla.submissions', (err, collection) =>
return @sendDatabaseError(res, err) if err
collection.insert doc, (err) =>
return @sendDatabaseError(res, err) if err
req.user.set('signedCLA', doc.created)
req.user.save (err) =>
return @sendDatabaseError(res, err) if err
@sendSuccess(res, {result:'success'})
avatar: (req, res, id) ->
@modelClass.findById(id).exec (err, document) ->
return @sendDatabaseError(res, err) if err
res.redirect(document?.get('photoURL') or '/images/generic-wizard-icon.png')
res.end()
module.exports = new UserHandler()
| 184500 | schema = require './user_schema'
crypto = require 'crypto'
request = require 'request'
User = require './User'
Handler = require '../commons/Handler'
mongoose = require 'mongoose'
config = require '../../server_config'
errors = require '../commons/errors'
async = require 'async'
serverProperties = ['passwordHash', 'emailLower', 'nameLower', 'passwordReset']
privateProperties = ['permissions', 'email', '<NAME>', '<NAME>', 'gender', 'facebookID', 'music', 'volume', 'aceConfig']
UserHandler = class UserHandler extends Handler
modelClass: User
editableProperties: [
'name', 'photoURL', 'password', '<PASSWORD>', 'wizardColor1', 'volume',
'<NAME>', '<NAME>', 'gender', 'facebookID', 'emailSubscriptions',
'testGroupNumber', 'music', 'hourOfCode', 'hourOfCodeComplete', 'preferredLanguage',
'wizard', 'aceConfig'
]
jsonSchema: schema
constructor: ->
super(arguments...)
@editableProperties.push('permissions') unless config.isProduction
formatEntity: (req, document) ->
return null unless document?
obj = document.toObject()
delete obj[prop] for prop in serverProperties
includePrivates = req.user and (req.user?.isAdmin() or req.user?._id.equals(document._id))
delete obj[prop] for prop in privateProperties unless includePrivates
# emailHash is used by gravatar
hash = crypto.createHash('md5')
if document.get('email')
hash.update(_.trim(document.get('email')).toLowerCase())
else
hash.update(@_id+'')
obj.emailHash = hash.digest('hex')
return obj
waterfallFunctions: [
# FB access token checking
# Check the email is the same as FB reports
(req, user, callback) ->
fbID = req.query.facebookID
fbAT = req.query.facebookAccessToken
return callback(null, req, user) unless fbID and fbAT
url = "https://graph.facebook.com/me?access_token=#{fbAT}"
request(url, (error, response, body) ->
body = JSON.parse(body)
emailsMatch = req.body.email is body.email
return callback(res:'Invalid Facebook Access Token.', code:422) unless emailsMatch
callback(null, req, user)
)
# GPlus access token checking
(req, user, callback) ->
gpID = req.query.gplusID
gpAT = req.query.gplusAccessToken
return callback(null, req, user) unless gpID and gpAT
url = "https://www.googleapis.com/oauth2/v2/userinfo?access_token=#{gpAT}"
request(url, (error, response, body) ->
body = JSON.parse(body)
emailsMatch = req.body.email is body.email
return callback(res:'Invalid G+ Access Token.', code:422) unless emailsMatch
callback(null, req, user)
)
# Email setting
(req, user, callback) ->
return callback(null, req, user) unless req.body.email?
emailLower = req.body.email.toLowerCase()
return callback(null, req, user) if emailLower is user.get('emailLower')
User.findOne({emailLower:emailLower}).exec (err, otherUser) ->
return callback(res:'Database error.', code:500) if err
if (req.query.gplusID or req.query.facebookID) and otherUser
# special case, log in as that user
return req.logIn(otherUser, (err) ->
return callback(res:'Facebook user login error.', code:500) if err
return callback(null, req, otherUser)
)
r = {message:'is already used by another account', property:'email'}
return callback({res:r, code:409}) if otherUser
user.set('email', req.body.email)
callback(null, req, user)
# Name setting
(req, user, callback) ->
return callback(null, req, user) unless req.body.name
nameLower = req.body.name?.toLowerCase()
return callback(null, req, user) if nameLower is user.get('nameLower')
User.findOne({nameLower:nameLower}).exec (err, otherUser) ->
return callback(res:'Database error.', code:500) if err
r = {message:'is already used by another account', property:'name'}
return callback({res:r, code:409}) if otherUser
user.set('name', req.body.name)
callback(null, req, user)
]
getById: (req, res, id) ->
if req.user?._id.equals(id)
return @sendSuccess(res, @formatEntity(req, req.user))
super(req, res, id)
getNamesByIds: (req, res) ->
ids = req.query.ids or req.body.ids
ids = ids.split(',') if _.isString ids
ids = _.uniq ids
# TODO: Extend and repurpose this handler to return other public info about a user more flexibly,
# say by a query parameter that lists public properties to return.
returnWizard = req.query.wizard or req.body.wizard
query = if returnWizard then {name:1, wizard:1} else {name:1}
makeFunc = (id) ->
(callback) ->
User.findById(id, query).exec (err, document) ->
return done(err) if err
if document and returnWizard
callback(null, {name:document.get('name'), wizard:document.get('wizard') or {}})
else
callback(null, document?.get('name') or '')
funcs = {}
for id in ids
return errors.badInput(res, "Given an invalid id: #{id}") unless Handler.isID(id)
funcs[id] = makeFunc(id)
async.parallel funcs, (err, results) ->
return errors.serverError err if err
res.send results
res.end()
nameToID: (req, res, name) ->
User.findOne({nameLower:name.toLowerCase()}).exec (err, otherUser) ->
res.send(if otherUser then otherUser._id else JSON.stringify(''))
res.end()
post: (req, res) ->
return @sendBadInputError(res, 'No input.') if _.isEmpty(req.body)
return @sendBadInputError(res, 'Must have an anonymous user to post with.') unless req.user
return @sendBadInputError(res, 'Existing users cannot create new ones.') unless req.user.get('anonymous')
req.body._id = req.user._id if req.user.get('anonymous')
@put(req, res)
hasAccessToDocument: (req, document) ->
if req.route.method in ['put', 'post', 'patch']
return true if req.user?.isAdmin()
return req.user?._id.equals(document._id)
return true
getByRelationship: (req, res, args...) ->
return @agreeToCLA(req, res) if args[1] is 'agreeToCLA'
return @avatar(req, res, args[0]) if args[1] is 'avatar'
return @getNamesByIds(req, res) if args[1] is 'names'
return @nameToID(req, res, args[0]) if args[1] is 'nameToID'
return @sendNotFoundError(res)
agreeToCLA: (req, res) ->
return @sendUnauthorizedError(res) unless req.user
doc =
user: req.user._id+''
email: req.user.get 'email'
name: req.user.get 'name'
githubUsername: req.body.githubUsername
created: new Date()+''
collection = mongoose.connection.db.collection 'cla.submissions', (err, collection) =>
return @sendDatabaseError(res, err) if err
collection.insert doc, (err) =>
return @sendDatabaseError(res, err) if err
req.user.set('signedCLA', doc.created)
req.user.save (err) =>
return @sendDatabaseError(res, err) if err
@sendSuccess(res, {result:'success'})
avatar: (req, res, id) ->
@modelClass.findById(id).exec (err, document) ->
return @sendDatabaseError(res, err) if err
res.redirect(document?.get('photoURL') or '/images/generic-wizard-icon.png')
res.end()
module.exports = new UserHandler()
| true | schema = require './user_schema'
crypto = require 'crypto'
request = require 'request'
User = require './User'
Handler = require '../commons/Handler'
mongoose = require 'mongoose'
config = require '../../server_config'
errors = require '../commons/errors'
async = require 'async'
serverProperties = ['passwordHash', 'emailLower', 'nameLower', 'passwordReset']
privateProperties = ['permissions', 'email', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'gender', 'facebookID', 'music', 'volume', 'aceConfig']
UserHandler = class UserHandler extends Handler
modelClass: User
editableProperties: [
'name', 'photoURL', 'password', 'PI:PASSWORD:<PASSWORD>END_PI', 'wizardColor1', 'volume',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'gender', 'facebookID', 'emailSubscriptions',
'testGroupNumber', 'music', 'hourOfCode', 'hourOfCodeComplete', 'preferredLanguage',
'wizard', 'aceConfig'
]
jsonSchema: schema
constructor: ->
super(arguments...)
@editableProperties.push('permissions') unless config.isProduction
formatEntity: (req, document) ->
return null unless document?
obj = document.toObject()
delete obj[prop] for prop in serverProperties
includePrivates = req.user and (req.user?.isAdmin() or req.user?._id.equals(document._id))
delete obj[prop] for prop in privateProperties unless includePrivates
# emailHash is used by gravatar
hash = crypto.createHash('md5')
if document.get('email')
hash.update(_.trim(document.get('email')).toLowerCase())
else
hash.update(@_id+'')
obj.emailHash = hash.digest('hex')
return obj
waterfallFunctions: [
# FB access token checking
# Check the email is the same as FB reports
(req, user, callback) ->
fbID = req.query.facebookID
fbAT = req.query.facebookAccessToken
return callback(null, req, user) unless fbID and fbAT
url = "https://graph.facebook.com/me?access_token=#{fbAT}"
request(url, (error, response, body) ->
body = JSON.parse(body)
emailsMatch = req.body.email is body.email
return callback(res:'Invalid Facebook Access Token.', code:422) unless emailsMatch
callback(null, req, user)
)
# GPlus access token checking
(req, user, callback) ->
gpID = req.query.gplusID
gpAT = req.query.gplusAccessToken
return callback(null, req, user) unless gpID and gpAT
url = "https://www.googleapis.com/oauth2/v2/userinfo?access_token=#{gpAT}"
request(url, (error, response, body) ->
body = JSON.parse(body)
emailsMatch = req.body.email is body.email
return callback(res:'Invalid G+ Access Token.', code:422) unless emailsMatch
callback(null, req, user)
)
# Email setting
(req, user, callback) ->
return callback(null, req, user) unless req.body.email?
emailLower = req.body.email.toLowerCase()
return callback(null, req, user) if emailLower is user.get('emailLower')
User.findOne({emailLower:emailLower}).exec (err, otherUser) ->
return callback(res:'Database error.', code:500) if err
if (req.query.gplusID or req.query.facebookID) and otherUser
# special case, log in as that user
return req.logIn(otherUser, (err) ->
return callback(res:'Facebook user login error.', code:500) if err
return callback(null, req, otherUser)
)
r = {message:'is already used by another account', property:'email'}
return callback({res:r, code:409}) if otherUser
user.set('email', req.body.email)
callback(null, req, user)
# Name setting
(req, user, callback) ->
return callback(null, req, user) unless req.body.name
nameLower = req.body.name?.toLowerCase()
return callback(null, req, user) if nameLower is user.get('nameLower')
User.findOne({nameLower:nameLower}).exec (err, otherUser) ->
return callback(res:'Database error.', code:500) if err
r = {message:'is already used by another account', property:'name'}
return callback({res:r, code:409}) if otherUser
user.set('name', req.body.name)
callback(null, req, user)
]
getById: (req, res, id) ->
if req.user?._id.equals(id)
return @sendSuccess(res, @formatEntity(req, req.user))
super(req, res, id)
getNamesByIds: (req, res) ->
ids = req.query.ids or req.body.ids
ids = ids.split(',') if _.isString ids
ids = _.uniq ids
# TODO: Extend and repurpose this handler to return other public info about a user more flexibly,
# say by a query parameter that lists public properties to return.
returnWizard = req.query.wizard or req.body.wizard
query = if returnWizard then {name:1, wizard:1} else {name:1}
makeFunc = (id) ->
(callback) ->
User.findById(id, query).exec (err, document) ->
return done(err) if err
if document and returnWizard
callback(null, {name:document.get('name'), wizard:document.get('wizard') or {}})
else
callback(null, document?.get('name') or '')
funcs = {}
for id in ids
return errors.badInput(res, "Given an invalid id: #{id}") unless Handler.isID(id)
funcs[id] = makeFunc(id)
async.parallel funcs, (err, results) ->
return errors.serverError err if err
res.send results
res.end()
nameToID: (req, res, name) ->
User.findOne({nameLower:name.toLowerCase()}).exec (err, otherUser) ->
res.send(if otherUser then otherUser._id else JSON.stringify(''))
res.end()
post: (req, res) ->
return @sendBadInputError(res, 'No input.') if _.isEmpty(req.body)
return @sendBadInputError(res, 'Must have an anonymous user to post with.') unless req.user
return @sendBadInputError(res, 'Existing users cannot create new ones.') unless req.user.get('anonymous')
req.body._id = req.user._id if req.user.get('anonymous')
@put(req, res)
hasAccessToDocument: (req, document) ->
if req.route.method in ['put', 'post', 'patch']
return true if req.user?.isAdmin()
return req.user?._id.equals(document._id)
return true
getByRelationship: (req, res, args...) ->
return @agreeToCLA(req, res) if args[1] is 'agreeToCLA'
return @avatar(req, res, args[0]) if args[1] is 'avatar'
return @getNamesByIds(req, res) if args[1] is 'names'
return @nameToID(req, res, args[0]) if args[1] is 'nameToID'
return @sendNotFoundError(res)
agreeToCLA: (req, res) ->
return @sendUnauthorizedError(res) unless req.user
doc =
user: req.user._id+''
email: req.user.get 'email'
name: req.user.get 'name'
githubUsername: req.body.githubUsername
created: new Date()+''
collection = mongoose.connection.db.collection 'cla.submissions', (err, collection) =>
return @sendDatabaseError(res, err) if err
collection.insert doc, (err) =>
return @sendDatabaseError(res, err) if err
req.user.set('signedCLA', doc.created)
req.user.save (err) =>
return @sendDatabaseError(res, err) if err
@sendSuccess(res, {result:'success'})
avatar: (req, res, id) ->
@modelClass.findById(id).exec (err, document) ->
return @sendDatabaseError(res, err) if err
res.redirect(document?.get('photoURL') or '/images/generic-wizard-icon.png')
res.end()
module.exports = new UserHandler()
|
[
{
"context": " can get back to doing some research.'\n pass: 'New password:'\n again: 'Again, to confirm:'\n submit: 'Su",
"end": 833,
"score": 0.9970964789390564,
"start": 821,
"tag": "PASSWORD",
"value": "New password"
},
{
"context": "vuelva a hacer algo de investigación.... | app/pages/reset-password.cjsx | Crentist/Panoptes-frontend-spanish | 1 | counterpart = require 'counterpart'
React = require 'react'
Translate = require 'react-translate-component'
auth = require 'panoptes-client/lib/auth'
alert = require '../lib/alert'
LoginDialog = require '../partials/login-dialog'
counterpart.registerTranslations 'en',
forgotten:
header: 'So, you’ve forgotten your password'
text: 'It happens to the best of us. Just enter your email address here and we’ll send you a link you can follow to reset it.'
submit: 'Submit'
emailSent: 'We’ve just sent you an email with a link to reset your password.'
error: 'There was an error reseting your password.'
reset:
success: 'You have successfully reset your password, please login to get started.'
new: 'Go ahead and enter a new password, then you can get back to doing some research.'
pass: 'New password:'
again: 'Again, to confirm:'
submit: 'Submit'
error: 'Something went wrong, please try and reset your password via email again.'
counterpart.registerTranslations 'es',
forgotten:
header: 'Así que olvidaste tu contraseña'
text: 'Nos pasa a todos. Simplemente ingrese su dirección de correo electrónico y le enviaremos un link para resetear su contraseña.'
submit: 'Enviar'
emailSent: 'El correo con el link para resetear la contraseña fue enviado.'
error: 'Hubo un error al resetear su contraseña.'
reset:
success: 'Ha reseteado su contraseña con éxito. Por favor, vuelva a ingresar.'
new: 'Ingrese una nueva contraseña y vuelva a hacer algo de investigación.'
pass: 'Nueva contraseña:'
again: 'Otra vez, para confirmar:'
submit: 'Enviar'
error: 'Algo salió mal. Por favor, intente resetear su contraseña otra vez.'
module.exports = React.createClass
displayName: 'ResetPasswordPage'
getDefaultProps: ->
query: {}
getInitialState: ->
inProgress: false
resetSuccess: false
resetError: null
emailSuccess: false
emailError: false
emailIsValid: false
componentDidMount: ->
@handleEmailChange()
handleResetSubmit: (e) ->
e.preventDefault()
@setState
inProgress: true
resetSuccess: false
resetError: null
token = @props.location.query.reset_password_token
password = @refs.password.value
confirmation = @refs.confirmation.value
auth.resetPassword {password, confirmation, token}
.then =>
@setState resetSuccess: true
alert (resolve) ->
<LoginDialog onSuccess={=>
location.hash = '/' # Sorta hacky.
resolve()
} />
return
.catch (error) =>
@setState resetError: error
.then =>
@setState inProgress: false
handleEmailChange: ->
@setState { emailIsValid: @refs.email?.checkValidity() }
handleEmailSubmit: (e) ->
e.preventDefault()
@setState
inProgress: true
emailSuccess: false
emailError: false
email = @refs.email.value
auth.requestPasswordReset {email}
.then =>
@setState emailSuccess: true
.catch =>
@setState emailError: true
.then =>
@setState inProgress: false
render: ->
<div className="centered-grid">
{if @props.location.query?.reset_password_token?
if @state.resetSuccess
<p><Translate content="reset.success" /></p>
else
<form method="POST" onSubmit={@handleResetSubmit}>
<p><Translate content="reset.new" /></p>
<p>
<Translate content="reset.pass" /><br />
<input ref="password" type="password" className="standard-input" size="20" />
</p>
<p>
<Translate content="reset.again" /><br />
<input ref="confirmation" type="password" className="standard-input" size="20" />
</p>
<p>
<button type="submit" className="standard-button" disabled={@state.resetError || @state.resetSuccess}><Translate content="reset.submit" /></button>{' '}
{if @state.inProgress
<i className="fa fa-spinner fa-spin form-help"></i>
else if @state.resetSuccess
<i className="fa fa-check-circle form-help success"></i>
else if @state.resetError?
<small className="form-help error"><Translate content="reset.error" /> {@state.resetError.toString()}</small>}
</p>
</form>
else
<form onSubmit={@handleEmailSubmit}>
<p><strong><Translate content="forgotten.header" /></strong></p>
<p><Translate content="forgotten.text" /></p>
<p>
<input ref="email" type="email" required onChange={@handleEmailChange} className="standard-input" defaultValue={@props.location.query?.email} size="50" />
</p>
<p>
<button type="submit" className="standard-button" disabled={!@state.emailIsValid}><Translate content="forgotten.submit" /></button>
{' '}
{if @state.inProgress
<i className="fa fa-spinner fa-spin form-help"></i>
else if @state.emailSuccess
<i className="fa fa-check-circle form-help success"></i>}
</p>
{if @state.emailSuccess
<p><Translate content="forgotten.emailSent" /></p>
else if @state.emailError
<small className="form-help error"><Translate content="forgotten.error" /></small>}
</form>}
</div>
| 24577 | counterpart = require 'counterpart'
React = require 'react'
Translate = require 'react-translate-component'
auth = require 'panoptes-client/lib/auth'
alert = require '../lib/alert'
LoginDialog = require '../partials/login-dialog'
counterpart.registerTranslations 'en',
forgotten:
header: 'So, you’ve forgotten your password'
text: 'It happens to the best of us. Just enter your email address here and we’ll send you a link you can follow to reset it.'
submit: 'Submit'
emailSent: 'We’ve just sent you an email with a link to reset your password.'
error: 'There was an error reseting your password.'
reset:
success: 'You have successfully reset your password, please login to get started.'
new: 'Go ahead and enter a new password, then you can get back to doing some research.'
pass: '<PASSWORD>:'
again: 'Again, to confirm:'
submit: 'Submit'
error: 'Something went wrong, please try and reset your password via email again.'
counterpart.registerTranslations 'es',
forgotten:
header: 'Así que olvidaste tu contraseña'
text: 'Nos pasa a todos. Simplemente ingrese su dirección de correo electrónico y le enviaremos un link para resetear su contraseña.'
submit: 'Enviar'
emailSent: 'El correo con el link para resetear la contraseña fue enviado.'
error: 'Hubo un error al resetear su contraseña.'
reset:
success: 'Ha reseteado su contraseña con éxito. Por favor, vuelva a ingresar.'
new: 'Ingrese una nueva contraseña y vuelva a hacer algo de investigación.'
pass: '<PASSWORD>:'
again: 'Otra vez, para confirmar:'
submit: 'Enviar'
error: 'Algo salió mal. Por favor, intente resetear su contraseña otra vez.'
module.exports = React.createClass
displayName: 'ResetPasswordPage'
getDefaultProps: ->
query: {}
getInitialState: ->
inProgress: false
resetSuccess: false
resetError: null
emailSuccess: false
emailError: false
emailIsValid: false
componentDidMount: ->
@handleEmailChange()
handleResetSubmit: (e) ->
e.preventDefault()
@setState
inProgress: true
resetSuccess: false
resetError: null
token = @props.location.query.reset_password_token
password = @refs.password.value
confirmation = @refs.confirmation.value
auth.resetPassword {password, confirmation, token}
.then =>
@setState resetSuccess: true
alert (resolve) ->
<LoginDialog onSuccess={=>
location.hash = '/' # Sorta hacky.
resolve()
} />
return
.catch (error) =>
@setState resetError: error
.then =>
@setState inProgress: false
handleEmailChange: ->
@setState { emailIsValid: @refs.email?.checkValidity() }
handleEmailSubmit: (e) ->
e.preventDefault()
@setState
inProgress: true
emailSuccess: false
emailError: false
email = @refs.email.value
auth.requestPasswordReset {email}
.then =>
@setState emailSuccess: true
.catch =>
@setState emailError: true
.then =>
@setState inProgress: false
render: ->
<div className="centered-grid">
{if @props.location.query?.reset_password_token?
if @state.resetSuccess
<p><Translate content="reset.success" /></p>
else
<form method="POST" onSubmit={@handleResetSubmit}>
<p><Translate content="reset.new" /></p>
<p>
<Translate content="reset.pass" /><br />
<input ref="password" type="<PASSWORD>" className="standard-input" size="20" />
</p>
<p>
<Translate content="reset.again" /><br />
<input ref="confirmation" type="password" className="standard-input" size="20" />
</p>
<p>
<button type="submit" className="standard-button" disabled={@state.resetError || @state.resetSuccess}><Translate content="reset.submit" /></button>{' '}
{if @state.inProgress
<i className="fa fa-spinner fa-spin form-help"></i>
else if @state.resetSuccess
<i className="fa fa-check-circle form-help success"></i>
else if @state.resetError?
<small className="form-help error"><Translate content="reset.error" /> {@state.resetError.toString()}</small>}
</p>
</form>
else
<form onSubmit={@handleEmailSubmit}>
<p><strong><Translate content="forgotten.header" /></strong></p>
<p><Translate content="forgotten.text" /></p>
<p>
<input ref="email" type="email" required onChange={@handleEmailChange} className="standard-input" defaultValue={@props.location.query?.email} size="50" />
</p>
<p>
<button type="submit" className="standard-button" disabled={!@state.emailIsValid}><Translate content="forgotten.submit" /></button>
{' '}
{if @state.inProgress
<i className="fa fa-spinner fa-spin form-help"></i>
else if @state.emailSuccess
<i className="fa fa-check-circle form-help success"></i>}
</p>
{if @state.emailSuccess
<p><Translate content="forgotten.emailSent" /></p>
else if @state.emailError
<small className="form-help error"><Translate content="forgotten.error" /></small>}
</form>}
</div>
| true | counterpart = require 'counterpart'
React = require 'react'
Translate = require 'react-translate-component'
auth = require 'panoptes-client/lib/auth'
alert = require '../lib/alert'
LoginDialog = require '../partials/login-dialog'
counterpart.registerTranslations 'en',
forgotten:
header: 'So, you’ve forgotten your password'
text: 'It happens to the best of us. Just enter your email address here and we’ll send you a link you can follow to reset it.'
submit: 'Submit'
emailSent: 'We’ve just sent you an email with a link to reset your password.'
error: 'There was an error reseting your password.'
reset:
success: 'You have successfully reset your password, please login to get started.'
new: 'Go ahead and enter a new password, then you can get back to doing some research.'
pass: 'PI:PASSWORD:<PASSWORD>END_PI:'
again: 'Again, to confirm:'
submit: 'Submit'
error: 'Something went wrong, please try and reset your password via email again.'
counterpart.registerTranslations 'es',
forgotten:
header: 'Así que olvidaste tu contraseña'
text: 'Nos pasa a todos. Simplemente ingrese su dirección de correo electrónico y le enviaremos un link para resetear su contraseña.'
submit: 'Enviar'
emailSent: 'El correo con el link para resetear la contraseña fue enviado.'
error: 'Hubo un error al resetear su contraseña.'
reset:
success: 'Ha reseteado su contraseña con éxito. Por favor, vuelva a ingresar.'
new: 'Ingrese una nueva contraseña y vuelva a hacer algo de investigación.'
pass: 'PI:PASSWORD:<PASSWORD>END_PI:'
again: 'Otra vez, para confirmar:'
submit: 'Enviar'
error: 'Algo salió mal. Por favor, intente resetear su contraseña otra vez.'
module.exports = React.createClass
displayName: 'ResetPasswordPage'
getDefaultProps: ->
query: {}
getInitialState: ->
inProgress: false
resetSuccess: false
resetError: null
emailSuccess: false
emailError: false
emailIsValid: false
componentDidMount: ->
@handleEmailChange()
handleResetSubmit: (e) ->
e.preventDefault()
@setState
inProgress: true
resetSuccess: false
resetError: null
token = @props.location.query.reset_password_token
password = @refs.password.value
confirmation = @refs.confirmation.value
auth.resetPassword {password, confirmation, token}
.then =>
@setState resetSuccess: true
alert (resolve) ->
<LoginDialog onSuccess={=>
location.hash = '/' # Sorta hacky.
resolve()
} />
return
.catch (error) =>
@setState resetError: error
.then =>
@setState inProgress: false
handleEmailChange: ->
@setState { emailIsValid: @refs.email?.checkValidity() }
handleEmailSubmit: (e) ->
e.preventDefault()
@setState
inProgress: true
emailSuccess: false
emailError: false
email = @refs.email.value
auth.requestPasswordReset {email}
.then =>
@setState emailSuccess: true
.catch =>
@setState emailError: true
.then =>
@setState inProgress: false
render: ->
<div className="centered-grid">
{if @props.location.query?.reset_password_token?
if @state.resetSuccess
<p><Translate content="reset.success" /></p>
else
<form method="POST" onSubmit={@handleResetSubmit}>
<p><Translate content="reset.new" /></p>
<p>
<Translate content="reset.pass" /><br />
<input ref="password" type="PI:PASSWORD:<PASSWORD>END_PI" className="standard-input" size="20" />
</p>
<p>
<Translate content="reset.again" /><br />
<input ref="confirmation" type="password" className="standard-input" size="20" />
</p>
<p>
<button type="submit" className="standard-button" disabled={@state.resetError || @state.resetSuccess}><Translate content="reset.submit" /></button>{' '}
{if @state.inProgress
<i className="fa fa-spinner fa-spin form-help"></i>
else if @state.resetSuccess
<i className="fa fa-check-circle form-help success"></i>
else if @state.resetError?
<small className="form-help error"><Translate content="reset.error" /> {@state.resetError.toString()}</small>}
</p>
</form>
else
<form onSubmit={@handleEmailSubmit}>
<p><strong><Translate content="forgotten.header" /></strong></p>
<p><Translate content="forgotten.text" /></p>
<p>
<input ref="email" type="email" required onChange={@handleEmailChange} className="standard-input" defaultValue={@props.location.query?.email} size="50" />
</p>
<p>
<button type="submit" className="standard-button" disabled={!@state.emailIsValid}><Translate content="forgotten.submit" /></button>
{' '}
{if @state.inProgress
<i className="fa fa-spinner fa-spin form-help"></i>
else if @state.emailSuccess
<i className="fa fa-check-circle form-help success"></i>}
</p>
{if @state.emailSuccess
<p><Translate content="forgotten.emailSent" /></p>
else if @state.emailError
<small className="form-help error"><Translate content="forgotten.error" /></small>}
</form>}
</div>
|
[
{
"context": "rver.\n populateFields: (config) ->\n password = config.password;\n passphrase = config.passphrase;\n\n if !pas",
"end": 5861,
"score": 0.9732145667076111,
"start": 5846,
"tag": "PASSWORD",
"value": "config.password"
},
{
"context": " return \"Host must be sp... | lib/dialogs/sftp-dialog.coffee | morassman/atom-commander | 43 | fs = require 'fs'
fsp = require 'fs-plus'
SSH2 = require 'ssh2'
PathUtil = require('path')
Utils = require '../utils'
SFTPFileSystem = require '../fs/ftp/sftp-filesystem'
{View, TextEditorView} = require 'atom-space-pen-views'
module.exports =
class SFTPDialog extends View
constructor: ->
super();
@ssh2 = null;
setParentDialog: (@parentDialog) ->
@content: ->
@div class: "atom-commander-ftp-dialog", =>
# @div "New SFTP Connection", {class: "heading"}
@table =>
@tbody =>
@tr =>
@td "Name", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "nameEditor", new TextEditorView(mini: true)
@tr =>
@td "URL", {class: "text-highlight", style: "width:40%"}
@td "sftp://", {outlet: "url", style: "padding-bottom: 0.5em"}
@tr =>
@td "Host", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "serverEditor", new TextEditorView(mini: true)
@tr =>
@td "Port", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "portEditor", new TextEditorView(mini: true)
@tr =>
@td "Folder", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "folderEditor", new TextEditorView(mini: true)
@tr =>
@td "Username", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "usernameEditor", new TextEditorView(mini: true)
@tr =>
@td "Password", {class: "text-highlight", style: "width:40%"}
@td =>
@div {class: "password"}, =>
@subview "passwordEditor", new TextEditorView(mini: true)
@div "Leave empty to prompt for password", {class:"encrypted"}
@tr =>
@td =>
@input {type: "radio", outlet: "loginWithPasswordCheckBox"}
@span "Login with password", {class: "text-highlight", style: "margin-left:5px"}
# @tr =>
# @td "Password", {class: "text-highlight indent", style: "width:40%"}
# @td {class: "password"}, =>
# @subview "passwordEditor", new TextEditorView(mini: true)
@tr =>
@td =>
@input {type: "radio", outlet: "loginWithPrivateKeyCheckBox"}
@span "Login with private key", {class: "text-highlight", style: "margin-left:5px"}
@tr =>
@td "Path to file", {class: "text-highlight indent", style: "width:40%"}
@td =>
@subview "privateKeyPathEditor", new TextEditorView(mini: true)
@tr =>
@td {class: "indent", style: "width:40%"}, =>
@input {type: "checkbox", outlet: "usePassphraseCheckBox"}
@span "Use passphrase", {class: "text-highlight", style: "margin-left:5px"}
@td =>
@div {class: "password"}, =>
@subview "passphraseEditor", new TextEditorView(mini: true)
@tr =>
@td =>
@input {type: "checkbox", outlet: "storeCheckBox"}
@span "Store password\\phrase", {class: "text-highlight", style: "width:40%; margin-left:5px"}
@td =>
@span "These are encrypted", {class: "encrypted"}
@div {class: "test-button-panel"}, =>
@button "Test", {class: "btn", click: "test", outlet: "testButton"}
@div {class: "bottom-button-panel"}, =>
@button "Cancel", {class: "btn", click: "cancel", outlet: "cancelButton"}
@button "OK", {class: "btn", click: "confirm", outlet: "okButton"}
@div =>
@span {class: "loading loading-spinner-tiny inline-block", outlet: "spinner"}
@span {class: "message", outlet: "message"}
initialize: ->
@nameEditor.attr("tabindex", 1);
@serverEditor.attr("tabindex", 2);
@portEditor.attr("tabindex", 3);
@folderEditor.attr("tabindex", 4);
@usernameEditor.attr("tabindex", 5);
@passwordEditor.attr("tabindex", 6);
@privateKeyPathEditor.attr("tabindex", 7);
@usePassphraseCheckBox.attr("tabindex", 8);
@passphraseEditor.attr("tabindex", 9);
@storeCheckBox.attr("tabindex", 10);
@testButton.attr("tabindex", 11);
@okButton.attr("tabindex", 12);
@cancelButton.attr("tabindex", 13);
@passwordEditor.addClass("password-editor");
@passphraseEditor.addClass("password-editor");
@spinner.hide();
@portEditor.getModel().setText("22");
@privateKeyPathEditor.getModel().setText(PathUtil.join("~", ".ssh", "id_rsa"));
@loginWithPasswordCheckBox.prop("checked", true);
@storeCheckBox.prop("checked", true);
@loginWithPasswordCheckBox.change =>
@loginWithPrivateKeyCheckBox.prop("checked", !@isLoginWithPasswordSelected());
@refreshError();
@loginWithPrivateKeyCheckBox.change =>
@loginWithPasswordCheckBox.prop("checked", !@isLoginWithPrivateKeySelected());
@refreshError();
@usePassphraseCheckBox.change =>
@refreshError();
@serverEditor.getModel().onDidChange =>
@refreshURL();
@refreshError();
@portEditor.getModel().onDidChange =>
@refreshURL();
@refreshError();
@folderEditor.getModel().onDidChange =>
@refreshURL();
@refreshError();
@usernameEditor.getModel().onDidChange =>
@refreshError();
@passwordEditor.getModel().onDidChange =>
@refreshError();
@privateKeyPathEditor.getModel().onDidChange =>
@refreshError();
atom.commands.add @element,
"core:confirm": => @confirm()
"core:cancel": => @cancel()
@refreshError();
# Populates the fields with an existing server's config. This is used
# when editing a server.
populateFields: (config) ->
password = config.password;
passphrase = config.passphrase;
if !password?
password = '';
if !passphrase?
passphrase = '';
@nameEditor.getModel().setText(config.name);
@serverEditor.getModel().setText(config.host);
@portEditor.getModel().setText(config.port + "");
@folderEditor.getModel().setText(config.folder);
@usernameEditor.getModel().setText(config.username);
@passwordEditor.getModel().setText(password);
@privateKeyPathEditor.getModel().setText(config.privateKeyPath);
@passphraseEditor.getModel().setText(passphrase);
@storeCheckBox.prop("checked", config.storePassword);
@usePassphraseCheckBox.prop("checked", config.usePassphrase);
@loginWithPasswordCheckBox.prop("checked", config.loginWithPassword);
@loginWithPrivateKeyCheckBox.prop("checked", !config.loginWithPassword);
@refreshURL();
@refreshError();
getPort: ->
port = @portEditor.getModel().getText().trim();
if port.length == 0
return 22;
port = parseInt(port);
if isNaN(port)
return null;
return port;
refreshURL: ->
server = @getServer();
port = @portEditor.getModel().getText().trim();
url = "sftp://" + server;
if (server.length > 0)
port = @getPort();
if (port != null) and (port != 22)
url += ":" + port;
url += @getFolder();
@url.text(url);
refreshError: ->
message = @getErrorMessage();
if (message == null)
@showMessage("", 0);
else
@showMessage(message, 2);
getErrorMessage: ->
server = @getServer();
if server.length == 0
return "Host must be specified."
username = @getUsername();
if username.length == 0
return "Username must be specified."
port = @getPort();
if port == null
return "Invalid port number.";
if @serverExists(server, port, username)
return "This server has already been added.";
# if @isLoginWithPasswordSelected() and @getPassword().length == 0
# return "Password not specified."
if @isLoginWithPrivateKeySelected()
if @getPrivateKeyPath(false).length == 0
return "Path to private key not specified.";
else if !@isPrivateKeyPathValid()
return "Private key file not found.";
# if @isUsePassphraseSelected() and @getPassphrase().length == 0
# return "Passphrase not specified.";
return null;
showMessage: (text, type) ->
@messageType = type;
@message.removeClass("text-error");
@message.removeClass("text-warning");
@message.removeClass("text-success");
if @messageType == 0
@message.addClass("text-success");
else if @messageType == 1
@message.addClass("text-warning");
else
@message.addClass("text-error");
@message.text(text);
serverExists: (server, port, username) ->
id = "sftp_"+server+"_"+port+"_"+username;
return @parentDialog.serverExists(id);
getName: ->
return @nameEditor.getModel().getText().trim();
getServer: ->
return @serverEditor.getModel().getText().trim();
getFolder: ->
folder = @folderEditor.getModel().getText().trim();
if (folder.length > 0)
if folder[0] != "/"
folder = "/"+folder;
else
folder = "/";
return folder;
getUsername: ->
return @usernameEditor.getModel().getText().trim();
getPassword: ->
return @passwordEditor.getModel().getText().trim();
getPrivateKeyPath: (resolve) ->
path = @privateKeyPathEditor.getModel().getText().trim();
if resolve
path = Utils.resolveHome(path);
return path;
getPassphrase: ->
return @passphraseEditor.getModel().getText().trim();
isLoginWithPasswordSelected: ->
return @loginWithPasswordCheckBox.is(":checked");
isLoginWithPrivateKeySelected: ->
return @loginWithPrivateKeyCheckBox.is(":checked");
isUsePassphraseSelected: ->
return @usePassphraseCheckBox.is(":checked");
isPrivateKeyPathValid: ->
path = @getPrivateKeyPath(true);
if path.length == 0
return false;
return fsp.isFileSync(path);
getPrivateKey: ->
if !@isPrivateKeyPathValid()
return '';
return fs.readFileSync(@getPrivateKeyPath(true), 'utf8');
isStoreCheckBoxSelected: ->
return @storeCheckBox.is(":checked");
getSFTPConfig: (testing) ->
config = {};
config.protocol = "sftp";
config.name = @getName();
config.host = @getServer();
config.port = @getPort();
config.folder = @getFolder();
config.username = @getUsername();
config.password = @getPassword();
config.passwordDecrypted = true;
config.storePassword = @isStoreCheckBoxSelected();
config.privateKeyPath = @getPrivateKeyPath(false);
config.passphrase = @getPassphrase();
config.loginWithPassword = @isLoginWithPasswordSelected();
config.usePassphrase = @isUsePassphraseSelected();
if testing
config.privateKey = @getPrivateKey();
return config;
selected: ->
@nameEditor.focus();
# attach: ->
# @panel = atom.workspace.addModalPanel(item: this.element);
# @serverEditor.focus();
# @serverEditor.getModel().scrollToCursorPosition();
close: ->
@parentDialog.close();
# panelToDestroy = @panel;
# @panel = null;
# panelToDestroy?.destroy();
# @containerView.requestFocus();
confirm: ->
if @hasError()
return;
@parentDialog.addServer(@getSFTPConfig(false));
cancel: ->
@parentDialog.close();
hasError: ->
return @messageType == 2;
test: ->
if @hasError() or (@ssh2 != null)
return;
config = @getSFTPConfig(false);
fs = new SFTPFileSystem(@parentDialog.getMain(), null, config);
fs.onError (err) =>
@parentDialog.attach();
if err.canceled
@showMessage("", 0);
else
@showMessage("Connection failed. "+err.message, 1);
fs.disconnect();
fs.onConnected () =>
@parentDialog.attach();
@showMessage("Connection successful", 0);
fs.disconnect();
fs.onDisconnected () =>
@parentDialog.attach();
fs.connect();
| 196430 | fs = require 'fs'
fsp = require 'fs-plus'
SSH2 = require 'ssh2'
PathUtil = require('path')
Utils = require '../utils'
SFTPFileSystem = require '../fs/ftp/sftp-filesystem'
{View, TextEditorView} = require 'atom-space-pen-views'
module.exports =
class SFTPDialog extends View
constructor: ->
super();
@ssh2 = null;
setParentDialog: (@parentDialog) ->
@content: ->
@div class: "atom-commander-ftp-dialog", =>
# @div "New SFTP Connection", {class: "heading"}
@table =>
@tbody =>
@tr =>
@td "Name", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "nameEditor", new TextEditorView(mini: true)
@tr =>
@td "URL", {class: "text-highlight", style: "width:40%"}
@td "sftp://", {outlet: "url", style: "padding-bottom: 0.5em"}
@tr =>
@td "Host", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "serverEditor", new TextEditorView(mini: true)
@tr =>
@td "Port", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "portEditor", new TextEditorView(mini: true)
@tr =>
@td "Folder", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "folderEditor", new TextEditorView(mini: true)
@tr =>
@td "Username", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "usernameEditor", new TextEditorView(mini: true)
@tr =>
@td "Password", {class: "text-highlight", style: "width:40%"}
@td =>
@div {class: "password"}, =>
@subview "passwordEditor", new TextEditorView(mini: true)
@div "Leave empty to prompt for password", {class:"encrypted"}
@tr =>
@td =>
@input {type: "radio", outlet: "loginWithPasswordCheckBox"}
@span "Login with password", {class: "text-highlight", style: "margin-left:5px"}
# @tr =>
# @td "Password", {class: "text-highlight indent", style: "width:40%"}
# @td {class: "password"}, =>
# @subview "passwordEditor", new TextEditorView(mini: true)
@tr =>
@td =>
@input {type: "radio", outlet: "loginWithPrivateKeyCheckBox"}
@span "Login with private key", {class: "text-highlight", style: "margin-left:5px"}
@tr =>
@td "Path to file", {class: "text-highlight indent", style: "width:40%"}
@td =>
@subview "privateKeyPathEditor", new TextEditorView(mini: true)
@tr =>
@td {class: "indent", style: "width:40%"}, =>
@input {type: "checkbox", outlet: "usePassphraseCheckBox"}
@span "Use passphrase", {class: "text-highlight", style: "margin-left:5px"}
@td =>
@div {class: "password"}, =>
@subview "passphraseEditor", new TextEditorView(mini: true)
@tr =>
@td =>
@input {type: "checkbox", outlet: "storeCheckBox"}
@span "Store password\\phrase", {class: "text-highlight", style: "width:40%; margin-left:5px"}
@td =>
@span "These are encrypted", {class: "encrypted"}
@div {class: "test-button-panel"}, =>
@button "Test", {class: "btn", click: "test", outlet: "testButton"}
@div {class: "bottom-button-panel"}, =>
@button "Cancel", {class: "btn", click: "cancel", outlet: "cancelButton"}
@button "OK", {class: "btn", click: "confirm", outlet: "okButton"}
@div =>
@span {class: "loading loading-spinner-tiny inline-block", outlet: "spinner"}
@span {class: "message", outlet: "message"}
initialize: ->
@nameEditor.attr("tabindex", 1);
@serverEditor.attr("tabindex", 2);
@portEditor.attr("tabindex", 3);
@folderEditor.attr("tabindex", 4);
@usernameEditor.attr("tabindex", 5);
@passwordEditor.attr("tabindex", 6);
@privateKeyPathEditor.attr("tabindex", 7);
@usePassphraseCheckBox.attr("tabindex", 8);
@passphraseEditor.attr("tabindex", 9);
@storeCheckBox.attr("tabindex", 10);
@testButton.attr("tabindex", 11);
@okButton.attr("tabindex", 12);
@cancelButton.attr("tabindex", 13);
@passwordEditor.addClass("password-editor");
@passphraseEditor.addClass("password-editor");
@spinner.hide();
@portEditor.getModel().setText("22");
@privateKeyPathEditor.getModel().setText(PathUtil.join("~", ".ssh", "id_rsa"));
@loginWithPasswordCheckBox.prop("checked", true);
@storeCheckBox.prop("checked", true);
@loginWithPasswordCheckBox.change =>
@loginWithPrivateKeyCheckBox.prop("checked", !@isLoginWithPasswordSelected());
@refreshError();
@loginWithPrivateKeyCheckBox.change =>
@loginWithPasswordCheckBox.prop("checked", !@isLoginWithPrivateKeySelected());
@refreshError();
@usePassphraseCheckBox.change =>
@refreshError();
@serverEditor.getModel().onDidChange =>
@refreshURL();
@refreshError();
@portEditor.getModel().onDidChange =>
@refreshURL();
@refreshError();
@folderEditor.getModel().onDidChange =>
@refreshURL();
@refreshError();
@usernameEditor.getModel().onDidChange =>
@refreshError();
@passwordEditor.getModel().onDidChange =>
@refreshError();
@privateKeyPathEditor.getModel().onDidChange =>
@refreshError();
atom.commands.add @element,
"core:confirm": => @confirm()
"core:cancel": => @cancel()
@refreshError();
# Populates the fields with an existing server's config. This is used
# when editing a server.
populateFields: (config) ->
password = <PASSWORD>;
passphrase = config.passphrase;
if !password?
password = '';
if !passphrase?
passphrase = '';
@nameEditor.getModel().setText(config.name);
@serverEditor.getModel().setText(config.host);
@portEditor.getModel().setText(config.port + "");
@folderEditor.getModel().setText(config.folder);
@usernameEditor.getModel().setText(config.username);
@passwordEditor.getModel().setText(password);
@privateKeyPathEditor.getModel().setText(config.privateKeyPath);
@passphraseEditor.getModel().setText(passphrase);
@storeCheckBox.prop("checked", config.storePassword);
@usePassphraseCheckBox.prop("checked", config.usePassphrase);
@loginWithPasswordCheckBox.prop("checked", config.loginWithPassword);
@loginWithPrivateKeyCheckBox.prop("checked", !config.loginWithPassword);
@refreshURL();
@refreshError();
getPort: ->
port = @portEditor.getModel().getText().trim();
if port.length == 0
return 22;
port = parseInt(port);
if isNaN(port)
return null;
return port;
refreshURL: ->
server = @getServer();
port = @portEditor.getModel().getText().trim();
url = "sftp://" + server;
if (server.length > 0)
port = @getPort();
if (port != null) and (port != 22)
url += ":" + port;
url += @getFolder();
@url.text(url);
refreshError: ->
message = @getErrorMessage();
if (message == null)
@showMessage("", 0);
else
@showMessage(message, 2);
getErrorMessage: ->
server = @getServer();
if server.length == 0
return "Host must be specified."
username = @getUsername();
if username.length == 0
return "Username must be specified."
port = @getPort();
if port == null
return "Invalid port number.";
if @serverExists(server, port, username)
return "This server has already been added.";
# if @isLoginWithPasswordSelected() and @getPassword().length == 0
# return "Password not specified."
if @isLoginWithPrivateKeySelected()
if @getPrivateKeyPath(false).length == 0
return "Path to private key not specified.";
else if !@isPrivateKeyPathValid()
return "Private key file not found.";
# if @isUsePassphraseSelected() and @getPassphrase().length == 0
# return "Passphrase not specified.";
return null;
showMessage: (text, type) ->
@messageType = type;
@message.removeClass("text-error");
@message.removeClass("text-warning");
@message.removeClass("text-success");
if @messageType == 0
@message.addClass("text-success");
else if @messageType == 1
@message.addClass("text-warning");
else
@message.addClass("text-error");
@message.text(text);
serverExists: (server, port, username) ->
id = "sftp_"+server+"_"+port+"_"+username;
return @parentDialog.serverExists(id);
getName: ->
return @nameEditor.getModel().getText().trim();
getServer: ->
return @serverEditor.getModel().getText().trim();
getFolder: ->
folder = @folderEditor.getModel().getText().trim();
if (folder.length > 0)
if folder[0] != "/"
folder = "/"+folder;
else
folder = "/";
return folder;
getUsername: ->
return @usernameEditor.getModel().getText().trim();
getPassword: ->
return @passwordEditor.getModel().getText().trim();
getPrivateKeyPath: (resolve) ->
path = @privateKeyPathEditor.getModel().getText().trim();
if resolve
path = Utils.resolveHome(path);
return path;
getPassphrase: ->
return @passphraseEditor.getModel().getText().trim();
isLoginWithPasswordSelected: ->
return @loginWithPasswordCheckBox.is(":checked");
isLoginWithPrivateKeySelected: ->
return @loginWithPrivateKeyCheckBox.is(":checked");
isUsePassphraseSelected: ->
return @usePassphraseCheckBox.is(":checked");
isPrivateKeyPathValid: ->
path = @getPrivateKeyPath(true);
if path.length == 0
return false;
return fsp.isFileSync(path);
getPrivateKey: ->
if !@isPrivateKeyPathValid()
return '';
return fs.readFileSync(@getPrivateKeyPath(true), 'utf8');
isStoreCheckBoxSelected: ->
return @storeCheckBox.is(":checked");
getSFTPConfig: (testing) ->
config = {};
config.protocol = "sftp";
config.name = @getName();
config.host = @getServer();
config.port = @getPort();
config.folder = @getFolder();
config.username = @getUsername();
config.password = @<PASSWORD>();
config.passwordDecrypted = true;
config.storePassword = @isStoreCheckBoxSelected();
config.privateKeyPath = @getPrivateKeyPath(false);
config.passphrase = @getPassphrase();
config.loginWithPassword = @isLoginWithPasswordSelected();
config.usePassphrase = @isUsePassphraseSelected();
if testing
config.privateKey = @getPrivateKey();
return config;
selected: ->
@nameEditor.focus();
# attach: ->
# @panel = atom.workspace.addModalPanel(item: this.element);
# @serverEditor.focus();
# @serverEditor.getModel().scrollToCursorPosition();
close: ->
@parentDialog.close();
# panelToDestroy = @panel;
# @panel = null;
# panelToDestroy?.destroy();
# @containerView.requestFocus();
confirm: ->
if @hasError()
return;
@parentDialog.addServer(@getSFTPConfig(false));
cancel: ->
@parentDialog.close();
hasError: ->
return @messageType == 2;
test: ->
if @hasError() or (@ssh2 != null)
return;
config = @getSFTPConfig(false);
fs = new SFTPFileSystem(@parentDialog.getMain(), null, config);
fs.onError (err) =>
@parentDialog.attach();
if err.canceled
@showMessage("", 0);
else
@showMessage("Connection failed. "+err.message, 1);
fs.disconnect();
fs.onConnected () =>
@parentDialog.attach();
@showMessage("Connection successful", 0);
fs.disconnect();
fs.onDisconnected () =>
@parentDialog.attach();
fs.connect();
| true | fs = require 'fs'
fsp = require 'fs-plus'
SSH2 = require 'ssh2'
PathUtil = require('path')
Utils = require '../utils'
SFTPFileSystem = require '../fs/ftp/sftp-filesystem'
{View, TextEditorView} = require 'atom-space-pen-views'
module.exports =
class SFTPDialog extends View
constructor: ->
super();
@ssh2 = null;
setParentDialog: (@parentDialog) ->
@content: ->
@div class: "atom-commander-ftp-dialog", =>
# @div "New SFTP Connection", {class: "heading"}
@table =>
@tbody =>
@tr =>
@td "Name", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "nameEditor", new TextEditorView(mini: true)
@tr =>
@td "URL", {class: "text-highlight", style: "width:40%"}
@td "sftp://", {outlet: "url", style: "padding-bottom: 0.5em"}
@tr =>
@td "Host", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "serverEditor", new TextEditorView(mini: true)
@tr =>
@td "Port", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "portEditor", new TextEditorView(mini: true)
@tr =>
@td "Folder", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "folderEditor", new TextEditorView(mini: true)
@tr =>
@td "Username", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "usernameEditor", new TextEditorView(mini: true)
@tr =>
@td "Password", {class: "text-highlight", style: "width:40%"}
@td =>
@div {class: "password"}, =>
@subview "passwordEditor", new TextEditorView(mini: true)
@div "Leave empty to prompt for password", {class:"encrypted"}
@tr =>
@td =>
@input {type: "radio", outlet: "loginWithPasswordCheckBox"}
@span "Login with password", {class: "text-highlight", style: "margin-left:5px"}
# @tr =>
# @td "Password", {class: "text-highlight indent", style: "width:40%"}
# @td {class: "password"}, =>
# @subview "passwordEditor", new TextEditorView(mini: true)
@tr =>
@td =>
@input {type: "radio", outlet: "loginWithPrivateKeyCheckBox"}
@span "Login with private key", {class: "text-highlight", style: "margin-left:5px"}
@tr =>
@td "Path to file", {class: "text-highlight indent", style: "width:40%"}
@td =>
@subview "privateKeyPathEditor", new TextEditorView(mini: true)
@tr =>
@td {class: "indent", style: "width:40%"}, =>
@input {type: "checkbox", outlet: "usePassphraseCheckBox"}
@span "Use passphrase", {class: "text-highlight", style: "margin-left:5px"}
@td =>
@div {class: "password"}, =>
@subview "passphraseEditor", new TextEditorView(mini: true)
@tr =>
@td =>
@input {type: "checkbox", outlet: "storeCheckBox"}
@span "Store password\\phrase", {class: "text-highlight", style: "width:40%; margin-left:5px"}
@td =>
@span "These are encrypted", {class: "encrypted"}
@div {class: "test-button-panel"}, =>
@button "Test", {class: "btn", click: "test", outlet: "testButton"}
@div {class: "bottom-button-panel"}, =>
@button "Cancel", {class: "btn", click: "cancel", outlet: "cancelButton"}
@button "OK", {class: "btn", click: "confirm", outlet: "okButton"}
@div =>
@span {class: "loading loading-spinner-tiny inline-block", outlet: "spinner"}
@span {class: "message", outlet: "message"}
initialize: ->
@nameEditor.attr("tabindex", 1);
@serverEditor.attr("tabindex", 2);
@portEditor.attr("tabindex", 3);
@folderEditor.attr("tabindex", 4);
@usernameEditor.attr("tabindex", 5);
@passwordEditor.attr("tabindex", 6);
@privateKeyPathEditor.attr("tabindex", 7);
@usePassphraseCheckBox.attr("tabindex", 8);
@passphraseEditor.attr("tabindex", 9);
@storeCheckBox.attr("tabindex", 10);
@testButton.attr("tabindex", 11);
@okButton.attr("tabindex", 12);
@cancelButton.attr("tabindex", 13);
@passwordEditor.addClass("password-editor");
@passphraseEditor.addClass("password-editor");
@spinner.hide();
@portEditor.getModel().setText("22");
@privateKeyPathEditor.getModel().setText(PathUtil.join("~", ".ssh", "id_rsa"));
@loginWithPasswordCheckBox.prop("checked", true);
@storeCheckBox.prop("checked", true);
@loginWithPasswordCheckBox.change =>
@loginWithPrivateKeyCheckBox.prop("checked", !@isLoginWithPasswordSelected());
@refreshError();
@loginWithPrivateKeyCheckBox.change =>
@loginWithPasswordCheckBox.prop("checked", !@isLoginWithPrivateKeySelected());
@refreshError();
@usePassphraseCheckBox.change =>
@refreshError();
@serverEditor.getModel().onDidChange =>
@refreshURL();
@refreshError();
@portEditor.getModel().onDidChange =>
@refreshURL();
@refreshError();
@folderEditor.getModel().onDidChange =>
@refreshURL();
@refreshError();
@usernameEditor.getModel().onDidChange =>
@refreshError();
@passwordEditor.getModel().onDidChange =>
@refreshError();
@privateKeyPathEditor.getModel().onDidChange =>
@refreshError();
atom.commands.add @element,
"core:confirm": => @confirm()
"core:cancel": => @cancel()
@refreshError();
# Populates the fields with an existing server's config. This is used
# when editing a server.
populateFields: (config) ->
password = PI:PASSWORD:<PASSWORD>END_PI;
passphrase = config.passphrase;
if !password?
password = '';
if !passphrase?
passphrase = '';
@nameEditor.getModel().setText(config.name);
@serverEditor.getModel().setText(config.host);
@portEditor.getModel().setText(config.port + "");
@folderEditor.getModel().setText(config.folder);
@usernameEditor.getModel().setText(config.username);
@passwordEditor.getModel().setText(password);
@privateKeyPathEditor.getModel().setText(config.privateKeyPath);
@passphraseEditor.getModel().setText(passphrase);
@storeCheckBox.prop("checked", config.storePassword);
@usePassphraseCheckBox.prop("checked", config.usePassphrase);
@loginWithPasswordCheckBox.prop("checked", config.loginWithPassword);
@loginWithPrivateKeyCheckBox.prop("checked", !config.loginWithPassword);
@refreshURL();
@refreshError();
getPort: ->
port = @portEditor.getModel().getText().trim();
if port.length == 0
return 22;
port = parseInt(port);
if isNaN(port)
return null;
return port;
refreshURL: ->
server = @getServer();
port = @portEditor.getModel().getText().trim();
url = "sftp://" + server;
if (server.length > 0)
port = @getPort();
if (port != null) and (port != 22)
url += ":" + port;
url += @getFolder();
@url.text(url);
refreshError: ->
message = @getErrorMessage();
if (message == null)
@showMessage("", 0);
else
@showMessage(message, 2);
getErrorMessage: ->
server = @getServer();
if server.length == 0
return "Host must be specified."
username = @getUsername();
if username.length == 0
return "Username must be specified."
port = @getPort();
if port == null
return "Invalid port number.";
if @serverExists(server, port, username)
return "This server has already been added.";
# if @isLoginWithPasswordSelected() and @getPassword().length == 0
# return "Password not specified."
if @isLoginWithPrivateKeySelected()
if @getPrivateKeyPath(false).length == 0
return "Path to private key not specified.";
else if !@isPrivateKeyPathValid()
return "Private key file not found.";
# if @isUsePassphraseSelected() and @getPassphrase().length == 0
# return "Passphrase not specified.";
return null;
showMessage: (text, type) ->
@messageType = type;
@message.removeClass("text-error");
@message.removeClass("text-warning");
@message.removeClass("text-success");
if @messageType == 0
@message.addClass("text-success");
else if @messageType == 1
@message.addClass("text-warning");
else
@message.addClass("text-error");
@message.text(text);
serverExists: (server, port, username) ->
id = "sftp_"+server+"_"+port+"_"+username;
return @parentDialog.serverExists(id);
getName: ->
return @nameEditor.getModel().getText().trim();
getServer: ->
return @serverEditor.getModel().getText().trim();
getFolder: ->
folder = @folderEditor.getModel().getText().trim();
if (folder.length > 0)
if folder[0] != "/"
folder = "/"+folder;
else
folder = "/";
return folder;
getUsername: ->
return @usernameEditor.getModel().getText().trim();
getPassword: ->
return @passwordEditor.getModel().getText().trim();
getPrivateKeyPath: (resolve) ->
path = @privateKeyPathEditor.getModel().getText().trim();
if resolve
path = Utils.resolveHome(path);
return path;
getPassphrase: ->
return @passphraseEditor.getModel().getText().trim();
isLoginWithPasswordSelected: ->
return @loginWithPasswordCheckBox.is(":checked");
isLoginWithPrivateKeySelected: ->
return @loginWithPrivateKeyCheckBox.is(":checked");
isUsePassphraseSelected: ->
return @usePassphraseCheckBox.is(":checked");
isPrivateKeyPathValid: ->
path = @getPrivateKeyPath(true);
if path.length == 0
return false;
return fsp.isFileSync(path);
getPrivateKey: ->
if !@isPrivateKeyPathValid()
return '';
return fs.readFileSync(@getPrivateKeyPath(true), 'utf8');
isStoreCheckBoxSelected: ->
return @storeCheckBox.is(":checked");
getSFTPConfig: (testing) ->
config = {};
config.protocol = "sftp";
config.name = @getName();
config.host = @getServer();
config.port = @getPort();
config.folder = @getFolder();
config.username = @getUsername();
config.password = @PI:PASSWORD:<PASSWORD>END_PI();
config.passwordDecrypted = true;
config.storePassword = @isStoreCheckBoxSelected();
config.privateKeyPath = @getPrivateKeyPath(false);
config.passphrase = @getPassphrase();
config.loginWithPassword = @isLoginWithPasswordSelected();
config.usePassphrase = @isUsePassphraseSelected();
if testing
config.privateKey = @getPrivateKey();
return config;
selected: ->
@nameEditor.focus();
# attach: ->
# @panel = atom.workspace.addModalPanel(item: this.element);
# @serverEditor.focus();
# @serverEditor.getModel().scrollToCursorPosition();
close: ->
@parentDialog.close();
# panelToDestroy = @panel;
# @panel = null;
# panelToDestroy?.destroy();
# @containerView.requestFocus();
confirm: ->
if @hasError()
return;
@parentDialog.addServer(@getSFTPConfig(false));
cancel: ->
@parentDialog.close();
hasError: ->
return @messageType == 2;
test: ->
if @hasError() or (@ssh2 != null)
return;
config = @getSFTPConfig(false);
fs = new SFTPFileSystem(@parentDialog.getMain(), null, config);
fs.onError (err) =>
@parentDialog.attach();
if err.canceled
@showMessage("", 0);
else
@showMessage("Connection failed. "+err.message, 1);
fs.disconnect();
fs.onConnected () =>
@parentDialog.attach();
@showMessage("Connection successful", 0);
fs.disconnect();
fs.onDisconnected () =>
@parentDialog.attach();
fs.connect();
|
[
{
"context": "###\nCopyright 2016 Balena\n\nLicensed under the Apache License, Version 2.0 (",
"end": 25,
"score": 0.973562479019165,
"start": 19,
"tag": "NAME",
"value": "Balena"
},
{
"context": "mple\n\t# balena.models.application.create({ name: 'My App', applicationType: 'essentia... | lib/models/application.coffee | xmb666/balena-sdk | 1 | ###
Copyright 2016 Balena
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.
###
url = require('url')
Promise = require('bluebird')
once = require('lodash/once')
assign = require('lodash/assign')
isArray = require('lodash/isArray')
isEmpty = require('lodash/isEmpty')
size = require('lodash/size')
errors = require('balena-errors')
{
isId,
isNoApplicationForKeyResponse,
isNotFoundResponse,
findCallback,
mergePineOptions,
treatAsMissingApplication,
LOCKED_STATUS_CODE
} = require('../util')
{ normalizeDeviceOsVersion } = require('../util/device-os-version')
{
getCurrentServiceDetailsPineOptions,
generateCurrentServiceDetails,
} = require('../util/device-service-details')
getApplicationModel = (deps, opts) ->
{ request, pine } = deps
{ apiUrl, dashboardUrl } = opts
deviceModel = once -> require('./device').default(deps, opts)
releaseModel = once -> require('./release').default(deps, opts)
{ buildDependentResource } = require('../util/dependent-resource')
tagsModel = buildDependentResource { pine }, {
resourceName: 'application_tag'
resourceKeyField: 'tag_key'
parentResourceName: 'application',
getResourceId: (nameOrSlugOrId) -> exports.get(nameOrSlugOrId, $select: 'id').get('id')
ResourceNotFoundError: errors.BalenaApplicationNotFound
}
configVarModel = buildDependentResource { pine }, {
resourceName: 'application_config_variable'
resourceKeyField: 'name'
parentResourceName: 'application',
getResourceId: (nameOrSlugOrId) -> exports.get(nameOrSlugOrId, $select: 'id').get('id')
ResourceNotFoundError: errors.BalenaApplicationNotFound
}
envVarModel = buildDependentResource { pine }, {
resourceName: 'application_environment_variable'
resourceKeyField: 'name'
parentResourceName: 'application',
getResourceId: (nameOrSlugOrId) -> exports.get(nameOrSlugOrId, $select: 'id').get('id')
ResourceNotFoundError: errors.BalenaApplicationNotFound
}
exports = {}
# Infer dashboardUrl from apiUrl if former is undefined
if not dashboardUrl?
dashboardUrl = apiUrl.replace(/api/, 'dashboard')
# Internal method for name/id disambiguation
# Note that this throws an exception for missing names, but not missing ids
getId = (nameOrSlugOrId) ->
Promise.try ->
if isId(nameOrSlugOrId)
return nameOrSlugOrId
else
exports.get(nameOrSlugOrId, $select: 'id').get('id')
exports._getId = getId
normalizeApplication = (application) ->
if isArray(application.owns__device)
application.owns__device.forEach (device) ->
normalizeDeviceOsVersion(device)
return application
###*
# @summary Get Dashboard URL for a specific application
# @function getDashboardUrl
# @memberof balena.models.application
#
# @param {Number} id - Application id
#
# @returns {String} - Dashboard URL for the specific application
# @throws Exception if the id is not a finite number
#
# @example
# balena.models.application.get('MyApp').then(function(application) {
# const dashboardApplicationUrl = balena.models.application.getDashboardUrl(application.id);
# console.log(dashboardApplicationUrl);
# });
###
exports.getDashboardUrl = (id) ->
if typeof id != 'number' || !Number.isFinite(id)
throw new Error('The id option should be a finite number')
return url.resolve(dashboardUrl, "/apps/#{id}")
###*
# @summary Get all applications
# @name getAll
# @public
# @function
# @memberof balena.models.application
#
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - applications
# @returns {Promise}
#
# @example
# balena.models.application.getAll().then(function(applications) {
# console.log(applications);
# });
#
# @example
# balena.models.application.getAll(function(error, applications) {
# if (error) throw error;
# console.log(applications);
# });
###
exports.getAll = (options = {}, callback) ->
callback = findCallback(arguments)
return pine.get
resource: 'my_application'
options:
mergePineOptions
$orderby: 'app_name asc'
, options
.map (application) ->
normalizeApplication(application)
return application
.asCallback(callback)
###*
# @summary Get applications and their devices, along with each device's
# associated services' essential details
# @name getAllWithDeviceServiceDetails
# @public
# @function
# @memberof balena.models.application
#
# @description
# This method does not map exactly to the underlying model: it runs a
# larger prebuilt query, and reformats it into an easy to use and
# understand format. If you want more control, or to see the raw model
# directly, use `application.getAll(options)` instead.
# **NOTE:** In contrast with device.getWithServiceDetails() the service details
# in the result of this method do not include the associated commit.
#
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - applications
# @returns {Promise}
#
# @example
# balena.models.application.getAllWithDeviceServiceDetails().then(function(applications) {
# console.log(applications);
# })
#
# @example
# balena.models.application.getAllWithDeviceServiceDetails(function(error, applications) {
# if (error) throw error;
# console.log(applications);
# });
###
exports.getAllWithDeviceServiceDetails = (options = {}, callback) ->
callback = findCallback(arguments)
serviceOptions = mergePineOptions
$expand: [
owns__device: getCurrentServiceDetailsPineOptions(false)
]
, options
exports.getAll(serviceOptions)
.then (apps) ->
apps.forEach (app) ->
app.owns__device = app.owns__device.map(generateCurrentServiceDetails)
return apps
.asCallback(callback)
###*
# @summary Get a single application
# @name get
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object} - application
# @returns {Promise}
#
# @example
# balena.models.application.get('MyApp').then(function(application) {
# console.log(application);
# });
#
# @example
# balena.models.application.get(123).then(function(application) {
# console.log(application);
# });
#
# @example
# balena.models.application.get('MyApp', function(error, application) {
# if (error) throw error;
# console.log(application);
# });
###
exports.get = (nameOrSlugOrId, options = {}, callback) ->
callback = findCallback(arguments)
Promise.try ->
if not nameOrSlugOrId?
throw new errors.BalenaApplicationNotFound(nameOrSlugOrId)
if isId(nameOrSlugOrId)
pine.get
resource: 'application'
id: nameOrSlugOrId
options: mergePineOptions({}, options)
.tap (application) ->
if not application?
throw new errors.BalenaApplicationNotFound(nameOrSlugOrId)
else
pine.get
resource: 'application'
options:
mergePineOptions
$filter:
$or:
app_name: nameOrSlugOrId
slug: nameOrSlugOrId.toLowerCase()
, options
.tap (applications) ->
if isEmpty(applications)
throw new errors.BalenaApplicationNotFound(nameOrSlugOrId)
if size(applications) > 1
throw new errors.BalenaAmbiguousApplication(nameOrSlugOrId)
.get(0)
.tap(normalizeApplication)
.asCallback(callback)
###*
# @summary Get a single application and its devices, along with each device's
# associated services' essential details
# @name getWithDeviceServiceDetails
# @public
# @function
# @memberof balena.models.application
#
# @description
# This method does not map exactly to the underlying model: it runs a
# larger prebuilt query, and reformats it into an easy to use and
# understand format. If you want more control, or to see the raw model
# directly, use `application.get(uuidOrId, options)` instead.
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object} - application
# @returns {Promise}
#
# @example
# balena.models.application.getWithDeviceServiceDetails('7cf02a6').then(function(device) {
# console.log(device);
# })
#
# @example
# balena.models.application.getWithDeviceServiceDetails(123).then(function(device) {
# console.log(device);
# })
#
# @example
# balena.models.application.getWithDeviceServiceDetails('7cf02a6', function(error, device) {
# if (error) throw error;
# console.log(device);
# });
###
exports.getWithDeviceServiceDetails = (nameOrSlugOrId, options = {}, callback) ->
callback = findCallback(arguments)
serviceOptions = mergePineOptions
$expand: [
owns__device: getCurrentServiceDetailsPineOptions(true)
]
, options
exports.get(nameOrSlugOrId, serviceOptions)
.then (app) ->
if app and app.owns__device
app.owns__device = app.owns__device.map(generateCurrentServiceDetails)
return app
.asCallback(callback)
###*
# @summary Get a single application using the appname and owner's username
# @name getAppByOwner
# @public
# @function
# @memberof balena.models.application
#
# @param {String} appName - application name
# @param {String} owner - The owner's username
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object} - application
# @returns {Promise}
#
# @example
# balena.models.application.getAppByOwner('MyApp', 'MyUser').then(function(application) {
# console.log(application);
# });
###
exports.getAppByOwner = (appName, owner, options = {}, callback) ->
callback = findCallback(arguments)
appName = appName.toLowerCase()
owner = owner.toLowerCase()
pine.get
resource: 'application'
options:
mergePineOptions
$filter:
slug: "#{owner}/#{appName}"
, options
.tap (applications) ->
if isEmpty(applications)
throw new errors.BalenaApplicationNotFound("#{owner}/#{appName}")
if size(applications) > 1
throw new errors.BalenaAmbiguousApplication("#{owner}/#{appName}")
.get(0)
.tap(normalizeApplication)
.asCallback(callback)
###*
# @summary Check if an application exists
# @name has
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {Boolean} - has application
# @returns {Promise}
#
# @example
# balena.models.application.has('MyApp').then(function(hasApp) {
# console.log(hasApp);
# });
#
# @example
# balena.models.application.has(123).then(function(hasApp) {
# console.log(hasApp);
# });
#
# @example
# balena.models.application.has('MyApp', function(error, hasApp) {
# if (error) throw error;
# console.log(hasApp);
# });
###
exports.has = (nameOrSlugOrId, callback) ->
exports.get(nameOrSlugOrId, $select: ['id']).return(true)
.catch errors.BalenaApplicationNotFound, ->
return false
.asCallback(callback)
###*
# @summary Check if the user has any applications
# @name hasAny
# @public
# @function
# @memberof balena.models.application
#
# @fulfil {Boolean} - has any applications
# @returns {Promise}
#
# @example
# balena.models.application.hasAny().then(function(hasAny) {
# console.log('Has any?', hasAny);
# });
#
# @example
# balena.models.application.hasAny(function(error, hasAny) {
# if (error) throw error;
# console.log('Has any?', hasAny);
# });
###
exports.hasAny = (callback) ->
exports.getAll($select: ['id']).then (applications) ->
return not isEmpty(applications)
.asCallback(callback)
###*
# @summary Create an application
# @name create
# @public
# @function
# @memberof balena.models.application
#
# @param {Object} options - application creation parameters
# @param {String} options.name - application name
# @param {String} [options.applicationType] - application type slug e.g. microservices-starter
# @param {String} options.deviceType - device type slug
# @param {(Number|String)} [options.parent] - parent application name or id
#
# @fulfil {Object} - application
# @returns {Promise}
#
# @example
# balena.models.application.create({ name: 'My App', applicationType: 'essentials', deviceType: 'raspberry-pi' }).then(function(application) {
# console.log(application);
# });
#
# @example
# balena.models.application.create({ name: 'My App', applicationType: 'microservices', deviceType: 'raspberry-pi', parent: 'ParentApp' }).then(function(application) {
# console.log(application);
# });
#
# @example
# balena.models.application.create({ name: 'My App', applicationType: 'microservices-starter', deviceType: 'raspberry-pi' }, function(error, application) {
# if (error) throw error;
# console.log(application);
# });
###
exports.create = ({ name, applicationType, deviceType, parent }, callback) ->
callback = findCallback(arguments)
applicationTypePromise = if !applicationType
Promise.resolve()
else
pine.get
resource: 'application_type'
options:
$select: [ 'id' ]
$filter:
slug: applicationType
.get(0)
.then (appType) ->
if not appType
throw new Error("Invalid application type: #{applicationType}")
appType.id
parentAppPromise = if parent
exports.get(parent, $select: [ 'id' ])
else
Promise.resolve()
deviceManifestPromise = deviceModel().getManifestBySlug(deviceType)
.tap (deviceManifest) ->
if not deviceManifest?
throw new errors.BalenaInvalidDeviceType(deviceType)
return Promise.all([
deviceManifestPromise
applicationTypePromise
parentAppPromise
])
.then ([
deviceManifest
applicationTypeId
parentApplication
]) ->
if deviceManifest.state == 'DISCONTINUED'
throw new errors.BalenaDiscontinuedDeviceType(deviceType)
extraOptions = if parentApplication
depends_on__application: parentApplication.id
else {}
if applicationTypeId
assign extraOptions,
application_type: applicationTypeId
return pine.post
resource: 'application'
body:
assign
app_name: name
device_type: deviceManifest.slug
, extraOptions
.asCallback(callback)
###*
# @summary Remove application
# @name remove
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.remove('MyApp');
#
# @example
# balena.models.application.remove(123);
#
# @example
# balena.models.application.remove('MyApp', function(error) {
# if (error) throw error;
# });
###
exports.remove = (nameOrSlugOrId, callback) ->
getId(nameOrSlugOrId).then (applicationId) ->
return pine.delete
resource: 'application'
id: applicationId
.catch(isNotFoundResponse, treatAsMissingApplication(nameOrSlugOrId))
.asCallback(callback)
###*
# @summary Restart application
# @name restart
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.restart('MyApp');
#
# @example
# balena.models.application.restart(123);
#
# @example
# balena.models.application.restart('MyApp', function(error) {
# if (error) throw error;
# });
###
exports.restart = (nameOrSlugOrId, callback) ->
getId(nameOrSlugOrId).then (applicationId) ->
return request.send
method: 'POST'
url: "/application/#{applicationId}/restart"
baseUrl: apiUrl
.return(undefined)
.catch(isNotFoundResponse, treatAsMissingApplication(nameOrSlugOrId))
.asCallback(callback)
###*
# @summary Generate an API key for a specific application
# @name generateApiKey
# @public
# @function
# @memberof balena.models.application
# @deprecated
# @description
# Generally you shouldn't use this method: if you're provisioning a recent BalenaOS
# version (2.4.0+) then generateProvisioningKey should work just as well, but
# be more secure.
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {String} - api key
# @returns {Promise}
#
# @example
# balena.models.application.generateApiKey('MyApp').then(function(apiKey) {
# console.log(apiKey);
# });
#
# @example
# balena.models.application.generateApiKey(123).then(function(apiKey) {
# console.log(apiKey);
# });
#
# @example
# balena.models.application.generateApiKey('MyApp', function(error, apiKey) {
# if (error) throw error;
# console.log(apiKey);
# });
###
exports.generateApiKey = (nameOrSlugOrId, callback) ->
# Do a full get, not just getId, because the actual api endpoint doesn't fail if the id
# doesn't exist. TODO: Can use getId once https://github.com/balena-io/balena-api/issues/110 is resolved
exports.get(nameOrSlugOrId, $select: 'id').then ({ id }) ->
return request.send
method: 'POST'
url: "/application/#{id}/generate-api-key"
baseUrl: apiUrl
.get('body')
.asCallback(callback)
###*
# @summary Generate a device provisioning key for a specific application
# @name generateProvisioningKey
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {String} - device provisioning key
# @returns {Promise}
#
# @example
# balena.models.application.generateProvisioningKey('MyApp').then(function(key) {
# console.log(key);
# });
#
# @example
# balena.models.application.generateProvisioningKey(123).then(function(key) {
# console.log(key);
# });
#
# @example
# balena.models.application.generateProvisioningKey('MyApp', function(error, key) {
# if (error) throw error;
# console.log(key);
# });
###
exports.generateProvisioningKey = (nameOrSlugOrId, callback) ->
getId(nameOrSlugOrId).then (applicationId) ->
return request.send
method: 'POST'
url: "/api-key/application/#{applicationId}/provisioning"
baseUrl: apiUrl
.catch(isNoApplicationForKeyResponse, treatAsMissingApplication(nameOrSlugOrId))
.get('body')
.asCallback(callback)
###*
# @summary Purge devices by application id
# @name purge
# @public
# @function
# @memberof balena.models.application
#
# @param {Number} appId - application id
# @returns {Promise}
#
# @example
# balena.models.application.purge(123);
#
# @example
# balena.models.application.purge(123, function(error) {
# if (error) throw error;
# });
###
exports.purge = (appId, callback) ->
return request.send
method: 'POST'
url: '/supervisor/v1/purge'
baseUrl: apiUrl
body:
appId: appId
data:
appId: "#{appId}"
.catch (err) ->
if err.statusCode == LOCKED_STATUS_CODE
throw new errors.BalenaSupervisorLockedError()
throw err
.asCallback(callback)
###*
# @summary Shutdown devices by application id
# @name shutdown
# @public
# @function
# @memberof balena.models.application
#
# @param {Number} appId - application id
# @param {Object} [options] - options
# @param {Boolean} [options.force=false] - override update lock
# @returns {Promise}
#
# @example
# balena.models.application.shutdown(123);
#
# @example
# balena.models.application.shutdown(123, function(error) {
# if (error) throw error;
# });
###
exports.shutdown = (appId, options = {}, callback) ->
return request.send
method: 'POST'
url: '/supervisor/v1/shutdown'
baseUrl: apiUrl
body:
appId: appId
data:
force: Boolean(options.force)
.catch (err) ->
if err.statusCode == LOCKED_STATUS_CODE
throw new errors.BalenaSupervisorLockedError()
throw err
.asCallback(callback)
###*
# @summary Reboot devices by application id
# @name reboot
# @public
# @function
# @memberof balena.models.application
#
# @param {Number} appId - application id
# @param {Object} [options] - options
# @param {Boolean} [options.force=false] - override update lock
# @returns {Promise}
#
# @example
# balena.models.application.reboot(123);
#
# @example
# balena.models.application.reboot(123, function(error) {
# if (error) throw error;
# });
###
exports.reboot = (appId, options = {}, callback) ->
return request.send
method: 'POST'
url: '/supervisor/v1/reboot'
baseUrl: apiUrl
body:
appId: appId
data:
force: Boolean(options.force)
.catch (err) ->
if err.statusCode == LOCKED_STATUS_CODE
throw new errors.BalenaSupervisorLockedError()
throw err
.asCallback(callback)
###*
# @summary Get whether the application is configured to receive updates whenever a new release is available
# @name willTrackNewReleases
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {Boolean} - is tracking the latest release
# @returns {Promise}
#
# @example
# balena.models.application.willTrackNewReleases('MyApp').then(function(isEnabled) {
# console.log(isEnabled);
# });
#
# @example
# balena.models.application.willTrackNewReleases(123).then(function(isEnabled) {
# console.log(isEnabled);
# });
#
# @example
# balena.models.application.willTrackNewReleases('MyApp', function(error, isEnabled) {
# console.log(isEnabled);
# });
###
exports.willTrackNewReleases = (nameOrSlugOrId, callback) ->
exports.get(nameOrSlugOrId, $select: 'should_track_latest_release')
.get('should_track_latest_release')
.asCallback(callback)
###*
# @summary Get whether the application is up to date and is tracking the latest release for updates
# @name isTrackingLatestRelease
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {Boolean} - is tracking the latest release
# @returns {Promise}
#
# @example
# balena.models.application.isTrackingLatestRelease('MyApp').then(function(isEnabled) {
# console.log(isEnabled);
# });
#
# @example
# balena.models.application.isTrackingLatestRelease(123).then(function(isEnabled) {
# console.log(isEnabled);
# });
#
# @example
# balena.models.application.isTrackingLatestRelease('MyApp', function(error, isEnabled) {
# console.log(isEnabled);
# });
###
exports.isTrackingLatestRelease = (nameOrSlugOrId, callback) ->
Promise.all([
exports.get(nameOrSlugOrId, $select: ['commit', 'should_track_latest_release'])
releaseModel().getLatestByApplication(nameOrSlugOrId, $select: 'commit')
])
.then ([application, latestRelease]) ->
return application.should_track_latest_release &&
(!latestRelease || application.commit == latestRelease.commit)
.asCallback(callback)
###*
# @summary Set a specific application to run a particular release
# @name pinToRelease
# @public
# @function
# @memberof balena.models.application
#
# @description Configures the application to run a particular release
# and not get updated when the latest release changes.
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} fullReleaseHash - the hash of a successful release (string)
# @returns {Promise}
#
# @example
# balena.models.application.pinToRelease('MyApp', 'f7caf4ff80114deeaefb7ab4447ad9c661c50847').then(function() {
# ...
# });
#
# @example
# balena.models.application.pinToRelease(123, 'f7caf4ff80114deeaefb7ab4447ad9c661c50847').then(function() {
# ...
# });
#
# @example
# balena.models.application.pinToRelease('MyApp', 'f7caf4ff80114deeaefb7ab4447ad9c661c50847', function(error) {
# if (error) throw error;
# ...
# });
###
exports.pinToRelease = (nameOrSlugOrId, fullReleaseHash, callback) ->
getId(nameOrSlugOrId)
.then (applicationId) ->
pine.patch
resource: 'application'
id: applicationId
body:
commit: fullReleaseHash
should_track_latest_release: false
.asCallback(callback)
###*
# @summary Get the hash of the current release for a specific application
# @name getTargetReleaseHash
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {String} - The release hash of the current release
# @returns {Promise}
#
# @example
# balena.models.application.getTargetReleaseHash('MyApp').then(function(release) {
# console.log(release);
# });
#
# @example
# balena.models.application.getTargetReleaseHash(123).then(function(release) {
# console.log(release);
# });
#
# @example
# balena.models.application.getTargetReleaseHash('MyApp', function(release) {
# console.log(release);
# });
###
exports.getTargetReleaseHash = (nameOrSlugOrId, callback) ->
exports.get(nameOrSlugOrId, $select: 'commit')
.get('commit')
.asCallback(callback)
###*
# @summary Configure a specific application to track the latest available release
# @name trackLatestRelease
# @public
# @function
# @memberof balena.models.application
#
# @description The application's current release will be updated with each new successfully built release.
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.trackLatestRelease('MyApp').then(function() {
# ...
# });
#
# @example
# balena.models.application.trackLatestRelease(123).then(function() {
# ...
# });
#
# @example
# balena.models.application.trackLatestRelease('MyApp', function(error) {
# if (error) throw error;
# ...
# });
###
exports.trackLatestRelease = (nameOrSlugOrId, callback) ->
releaseModel().getLatestByApplication(nameOrSlugOrId,
$select: ['commit', 'belongs_to__application']
)
.then (latestRelease) ->
if not latestRelease
return Promise.props(
applicationId: getId(nameOrSlugOrId)
commit: null
)
return {
applicationId: latestRelease.belongs_to__application.__id
commit: latestRelease.commit
}
.then ({ applicationId, commit }) ->
body =
should_track_latest_release: true
if commit
body.commit = commit
return pine.patch
resource: 'application'
id: applicationId
body: body
.asCallback(callback)
###*
# @summary Enable device urls for all devices that belong to an application
# @name enableDeviceUrls
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.enableDeviceUrls('MyApp');
#
# @example
# balena.models.application.enableDeviceUrls(123);
#
# @example
# balena.models.device.enableDeviceUrls('MyApp', function(error) {
# if (error) throw error;
# });
###
exports.enableDeviceUrls = (nameOrSlugOrId, callback) ->
exports.get(nameOrSlugOrId, $select: 'id').then ({ id }) ->
return pine.patch
resource: 'device'
body:
is_web_accessible: true
options:
$filter:
belongs_to__application: id
.asCallback(callback)
###*
# @summary Disable device urls for all devices that belong to an application
# @name disableDeviceUrls
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.disableDeviceUrls('MyApp');
#
# @example
# balena.models.application.disableDeviceUrls(123);
#
# @example
# balena.models.device.disableDeviceUrls('MyApp', function(error) {
# if (error) throw error;
# });
###
exports.disableDeviceUrls = (nameOrSlugOrId, callback) ->
exports.get(nameOrSlugOrId, $select: 'id').then ({ id }) ->
return pine.patch
resource: 'device'
body:
is_web_accessible: false
options:
$filter:
belongs_to__application: id
.asCallback(callback)
###*
# @summary Grant support access to an application until a specified time
# @name grantSupportAccess
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Number} expiryTimestamp - a timestamp in ms for when the support access will expire
# @returns {Promise}
#
# @example
# balena.models.application.grantSupportAccess('MyApp', Date.now() + 3600 * 1000);
#
# @example
# balena.models.application.grantSupportAccess(123, Date.now() + 3600 * 1000);
#
# @example
# balena.models.application.grantSupportAccess('MyApp', Date.now() + 3600 * 1000, function(error) {
# if (error) throw error;
# });
###
exports.grantSupportAccess = (nameOrSlugOrId, expiryTimestamp, callback) ->
if not expiryTimestamp? or expiryTimestamp <= Date.now()
throw new errors.BalenaInvalidParameterError('expiryTimestamp', expiryTimestamp)
getId(nameOrSlugOrId).then (applicationId) ->
return pine.patch
resource: 'application'
id: applicationId
body: is_accessible_by_support_until__date: expiryTimestamp
.catch(isNotFoundResponse, treatAsMissingApplication(nameOrSlugOrId))
.asCallback(callback)
###*
# @summary Revoke support access to an application
# @name revokeSupportAccess
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.revokeSupportAccess('MyApp');
#
# @example
# balena.models.application.revokeSupportAccess(123);
#
# @example
# balena.models.application.revokeSupportAccess('MyApp', function(error) {
# if (error) throw error;
# });
###
exports.revokeSupportAccess = (nameOrSlugOrId, callback) ->
getId(nameOrSlugOrId).then (applicationId) ->
return pine.patch
resource: 'application'
id: applicationId
body: is_accessible_by_support_until__date: null
.catch(isNotFoundResponse, treatAsMissingApplication(nameOrSlugOrId))
.asCallback(callback)
###*
# @namespace balena.models.application.tags
# @memberof balena.models.application
###
exports.tags = {
###*
# @summary Get all application tags for an application
# @name getAllByApplication
# @public
# @function
# @memberof balena.models.application.tags
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - application tags
# @returns {Promise}
#
# @example
# balena.models.application.tags.getAllByApplication('MyApp').then(function(tags) {
# console.log(tags);
# });
#
# @example
# balena.models.application.tags.getAllByApplication(999999).then(function(tags) {
# console.log(tags);
# });
#
# @example
# balena.models.application.tags.getAllByApplication('MyApp', function(error, tags) {
# if (error) throw error;
# console.log(tags)
# });
###
getAllByApplication: tagsModel.getAllByParent
###*
# @summary Get all application tags
# @name getAll
# @public
# @function
# @memberof balena.models.application.tags
#
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - application tags
# @returns {Promise}
#
# @example
# balena.models.application.tags.getAll().then(function(tags) {
# console.log(tags);
# });
#
# @example
# balena.models.application.tags.getAll(function(error, tags) {
# if (error) throw error;
# console.log(tags)
# });
###
getAll: tagsModel.getAll
###*
# @summary Set an application tag
# @name set
# @public
# @function
# @memberof balena.models.application.tags
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} tagKey - tag key
# @param {String|undefined} value - tag value
#
# @returns {Promise}
#
# @example
# balena.models.application.tags.set('7cf02a6', 'EDITOR', 'vim');
#
# @example
# balena.models.application.tags.set(123, 'EDITOR', 'vim');
#
# @example
# balena.models.application.tags.set('7cf02a6', 'EDITOR', 'vim', function(error) {
# if (error) throw error;
# });
###
set: tagsModel.set
###*
# @summary Remove an application tag
# @name remove
# @public
# @function
# @memberof balena.models.application.tags
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} tagKey - tag key
# @returns {Promise}
#
# @example
# balena.models.application.tags.remove('7cf02a6', 'EDITOR');
#
# @example
# balena.models.application.tags.remove('7cf02a6', 'EDITOR', function(error) {
# if (error) throw error;
# });
###
remove: tagsModel.remove
}
###*
# @namespace balena.models.application.configVar
# @memberof balena.models.application
###
exports.configVar = {
###*
# @summary Get all config variables for an application
# @name getAllByApplication
# @public
# @function
# @memberof balena.models.application.configVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - application config variables
# @returns {Promise}
#
# @example
# balena.models.application.configVar.getAllByApplication('MyApp').then(function(vars) {
# console.log(vars);
# });
#
# @example
# balena.models.application.configVar.getAllByApplication(999999).then(function(vars) {
# console.log(vars);
# });
#
# @example
# balena.models.application.configVar.getAllByApplication('MyApp', function(error, vars) {
# if (error) throw error;
# console.log(vars)
# });
###
getAllByApplication: configVarModel.getAllByParent
###*
# @summary Get the value of a specific config variable
# @name get
# @public
# @function
# @memberof balena.models.application.configVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - config variable name
# @fulfil {String|undefined} - the config variable value (or undefined)
# @returns {Promise}
#
# @example
# balena.models.application.configVar.get('MyApp', 'BALENA_VAR').then(function(value) {
# console.log(value);
# });
#
# @example
# balena.models.application.configVar.get(999999, 'BALENA_VAR').then(function(value) {
# console.log(value);
# });
#
# @example
# balena.models.application.configVar.get('MyApp', 'BALENA_VAR', function(error, value) {
# if (error) throw error;
# console.log(value)
# });
###
get: configVarModel.get
###*
# @summary Set the value of a specific config variable
# @name set
# @public
# @function
# @memberof balena.models.application.configVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - config variable name
# @param {String} value - config variable value
# @returns {Promise}
#
# @example
# balena.models.application.configVar.set('MyApp', 'BALENA_VAR', 'newvalue').then(function() {
# ...
# });
#
# @example
# balena.models.application.configVar.set(999999, 'BALENA_VAR', 'newvalue').then(function() {
# ...
# });
#
# @example
# balena.models.application.configVar.set('MyApp', 'BALENA_VAR', 'newvalue', function(error) {
# if (error) throw error;
# ...
# });
###
set: configVarModel.set
###*
# @summary Clear the value of a specific config variable
# @name remove
# @public
# @function
# @memberof balena.models.application.configVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - config variable name
# @returns {Promise}
#
# @example
# balena.models.application.configVar.remove('MyApp', 'BALENA_VAR').then(function() {
# ...
# });
#
# @example
# balena.models.application.configVar.remove(999999, 'BALENA_VAR').then(function() {
# ...
# });
#
# @example
# balena.models.application.configVar.remove('MyApp', 'BALENA_VAR', function(error) {
# if (error) throw error;
# ...
# });
###
remove: configVarModel.remove
}
###*
# @namespace balena.models.application.envVar
# @memberof balena.models.application
###
exports.envVar = {
###*
# @summary Get all environment variables for an application
# @name getAllByApplication
# @public
# @function
# @memberof balena.models.application.envVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - application environment variables
# @returns {Promise}
#
# @example
# balena.models.application.envVar.getAllByApplication('MyApp').then(function(vars) {
# console.log(vars);
# });
#
# @example
# balena.models.application.envVar.getAllByApplication(999999).then(function(vars) {
# console.log(vars);
# });
#
# @example
# balena.models.application.envVar.getAllByApplication('MyApp', function(error, vars) {
# if (error) throw error;
# console.log(vars)
# });
###
getAllByApplication: envVarModel.getAllByParent
###*
# @summary Get the value of a specific environment variable
# @name get
# @public
# @function
# @memberof balena.models.application.envVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - environment variable name
# @fulfil {String|undefined} - the environment variable value (or undefined)
# @returns {Promise}
#
# @example
# balena.models.application.envVar.get('MyApp', 'VAR').then(function(value) {
# console.log(value);
# });
#
# @example
# balena.models.application.envVar.get(999999, 'VAR').then(function(value) {
# console.log(value);
# });
#
# @example
# balena.models.application.envVar.get('MyApp', 'VAR', function(error, value) {
# if (error) throw error;
# console.log(value)
# });
###
get: envVarModel.get
###*
# @summary Set the value of a specific environment variable
# @name set
# @public
# @function
# @memberof balena.models.application.envVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - environment variable name
# @param {String} value - environment variable value
# @returns {Promise}
#
# @example
# balena.models.application.envVar.set('MyApp', 'VAR', 'newvalue').then(function() {
# ...
# });
#
# @example
# balena.models.application.envVar.set(999999, 'VAR', 'newvalue').then(function() {
# ...
# });
#
# @example
# balena.models.application.envVar.set('MyApp', 'VAR', 'newvalue', function(error) {
# if (error) throw error;
# ...
# });
###
set: envVarModel.set
###*
# @summary Clear the value of a specific environment variable
# @name remove
# @public
# @function
# @memberof balena.models.application.envVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - environment variable name
# @returns {Promise}
#
# @example
# balena.models.application.envVar.remove('MyApp', 'VAR').then(function() {
# ...
# });
#
# @example
# balena.models.application.envVar.remove(999999, 'VAR').then(function() {
# ...
# });
#
# @example
# balena.models.application.envVar.remove('MyApp', 'VAR', function(error) {
# if (error) throw error;
# ...
# });
###
remove: envVarModel.remove
}
return exports
module.exports =
default: getApplicationModel
| 4716 | ###
Copyright 2016 <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.
###
url = require('url')
Promise = require('bluebird')
once = require('lodash/once')
assign = require('lodash/assign')
isArray = require('lodash/isArray')
isEmpty = require('lodash/isEmpty')
size = require('lodash/size')
errors = require('balena-errors')
{
isId,
isNoApplicationForKeyResponse,
isNotFoundResponse,
findCallback,
mergePineOptions,
treatAsMissingApplication,
LOCKED_STATUS_CODE
} = require('../util')
{ normalizeDeviceOsVersion } = require('../util/device-os-version')
{
getCurrentServiceDetailsPineOptions,
generateCurrentServiceDetails,
} = require('../util/device-service-details')
getApplicationModel = (deps, opts) ->
{ request, pine } = deps
{ apiUrl, dashboardUrl } = opts
deviceModel = once -> require('./device').default(deps, opts)
releaseModel = once -> require('./release').default(deps, opts)
{ buildDependentResource } = require('../util/dependent-resource')
tagsModel = buildDependentResource { pine }, {
resourceName: 'application_tag'
resourceKeyField: 'tag_key'
parentResourceName: 'application',
getResourceId: (nameOrSlugOrId) -> exports.get(nameOrSlugOrId, $select: 'id').get('id')
ResourceNotFoundError: errors.BalenaApplicationNotFound
}
configVarModel = buildDependentResource { pine }, {
resourceName: 'application_config_variable'
resourceKeyField: 'name'
parentResourceName: 'application',
getResourceId: (nameOrSlugOrId) -> exports.get(nameOrSlugOrId, $select: 'id').get('id')
ResourceNotFoundError: errors.BalenaApplicationNotFound
}
envVarModel = buildDependentResource { pine }, {
resourceName: 'application_environment_variable'
resourceKeyField: 'name'
parentResourceName: 'application',
getResourceId: (nameOrSlugOrId) -> exports.get(nameOrSlugOrId, $select: 'id').get('id')
ResourceNotFoundError: errors.BalenaApplicationNotFound
}
exports = {}
# Infer dashboardUrl from apiUrl if former is undefined
if not dashboardUrl?
dashboardUrl = apiUrl.replace(/api/, 'dashboard')
# Internal method for name/id disambiguation
# Note that this throws an exception for missing names, but not missing ids
getId = (nameOrSlugOrId) ->
Promise.try ->
if isId(nameOrSlugOrId)
return nameOrSlugOrId
else
exports.get(nameOrSlugOrId, $select: 'id').get('id')
exports._getId = getId
normalizeApplication = (application) ->
if isArray(application.owns__device)
application.owns__device.forEach (device) ->
normalizeDeviceOsVersion(device)
return application
###*
# @summary Get Dashboard URL for a specific application
# @function getDashboardUrl
# @memberof balena.models.application
#
# @param {Number} id - Application id
#
# @returns {String} - Dashboard URL for the specific application
# @throws Exception if the id is not a finite number
#
# @example
# balena.models.application.get('MyApp').then(function(application) {
# const dashboardApplicationUrl = balena.models.application.getDashboardUrl(application.id);
# console.log(dashboardApplicationUrl);
# });
###
exports.getDashboardUrl = (id) ->
if typeof id != 'number' || !Number.isFinite(id)
throw new Error('The id option should be a finite number')
return url.resolve(dashboardUrl, "/apps/#{id}")
###*
# @summary Get all applications
# @name getAll
# @public
# @function
# @memberof balena.models.application
#
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - applications
# @returns {Promise}
#
# @example
# balena.models.application.getAll().then(function(applications) {
# console.log(applications);
# });
#
# @example
# balena.models.application.getAll(function(error, applications) {
# if (error) throw error;
# console.log(applications);
# });
###
exports.getAll = (options = {}, callback) ->
callback = findCallback(arguments)
return pine.get
resource: 'my_application'
options:
mergePineOptions
$orderby: 'app_name asc'
, options
.map (application) ->
normalizeApplication(application)
return application
.asCallback(callback)
###*
# @summary Get applications and their devices, along with each device's
# associated services' essential details
# @name getAllWithDeviceServiceDetails
# @public
# @function
# @memberof balena.models.application
#
# @description
# This method does not map exactly to the underlying model: it runs a
# larger prebuilt query, and reformats it into an easy to use and
# understand format. If you want more control, or to see the raw model
# directly, use `application.getAll(options)` instead.
# **NOTE:** In contrast with device.getWithServiceDetails() the service details
# in the result of this method do not include the associated commit.
#
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - applications
# @returns {Promise}
#
# @example
# balena.models.application.getAllWithDeviceServiceDetails().then(function(applications) {
# console.log(applications);
# })
#
# @example
# balena.models.application.getAllWithDeviceServiceDetails(function(error, applications) {
# if (error) throw error;
# console.log(applications);
# });
###
exports.getAllWithDeviceServiceDetails = (options = {}, callback) ->
callback = findCallback(arguments)
serviceOptions = mergePineOptions
$expand: [
owns__device: getCurrentServiceDetailsPineOptions(false)
]
, options
exports.getAll(serviceOptions)
.then (apps) ->
apps.forEach (app) ->
app.owns__device = app.owns__device.map(generateCurrentServiceDetails)
return apps
.asCallback(callback)
###*
# @summary Get a single application
# @name get
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object} - application
# @returns {Promise}
#
# @example
# balena.models.application.get('MyApp').then(function(application) {
# console.log(application);
# });
#
# @example
# balena.models.application.get(123).then(function(application) {
# console.log(application);
# });
#
# @example
# balena.models.application.get('MyApp', function(error, application) {
# if (error) throw error;
# console.log(application);
# });
###
exports.get = (nameOrSlugOrId, options = {}, callback) ->
callback = findCallback(arguments)
Promise.try ->
if not nameOrSlugOrId?
throw new errors.BalenaApplicationNotFound(nameOrSlugOrId)
if isId(nameOrSlugOrId)
pine.get
resource: 'application'
id: nameOrSlugOrId
options: mergePineOptions({}, options)
.tap (application) ->
if not application?
throw new errors.BalenaApplicationNotFound(nameOrSlugOrId)
else
pine.get
resource: 'application'
options:
mergePineOptions
$filter:
$or:
app_name: nameOrSlugOrId
slug: nameOrSlugOrId.toLowerCase()
, options
.tap (applications) ->
if isEmpty(applications)
throw new errors.BalenaApplicationNotFound(nameOrSlugOrId)
if size(applications) > 1
throw new errors.BalenaAmbiguousApplication(nameOrSlugOrId)
.get(0)
.tap(normalizeApplication)
.asCallback(callback)
###*
# @summary Get a single application and its devices, along with each device's
# associated services' essential details
# @name getWithDeviceServiceDetails
# @public
# @function
# @memberof balena.models.application
#
# @description
# This method does not map exactly to the underlying model: it runs a
# larger prebuilt query, and reformats it into an easy to use and
# understand format. If you want more control, or to see the raw model
# directly, use `application.get(uuidOrId, options)` instead.
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object} - application
# @returns {Promise}
#
# @example
# balena.models.application.getWithDeviceServiceDetails('7cf02a6').then(function(device) {
# console.log(device);
# })
#
# @example
# balena.models.application.getWithDeviceServiceDetails(123).then(function(device) {
# console.log(device);
# })
#
# @example
# balena.models.application.getWithDeviceServiceDetails('7cf02a6', function(error, device) {
# if (error) throw error;
# console.log(device);
# });
###
exports.getWithDeviceServiceDetails = (nameOrSlugOrId, options = {}, callback) ->
callback = findCallback(arguments)
serviceOptions = mergePineOptions
$expand: [
owns__device: getCurrentServiceDetailsPineOptions(true)
]
, options
exports.get(nameOrSlugOrId, serviceOptions)
.then (app) ->
if app and app.owns__device
app.owns__device = app.owns__device.map(generateCurrentServiceDetails)
return app
.asCallback(callback)
###*
# @summary Get a single application using the appname and owner's username
# @name getAppByOwner
# @public
# @function
# @memberof balena.models.application
#
# @param {String} appName - application name
# @param {String} owner - The owner's username
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object} - application
# @returns {Promise}
#
# @example
# balena.models.application.getAppByOwner('MyApp', 'MyUser').then(function(application) {
# console.log(application);
# });
###
exports.getAppByOwner = (appName, owner, options = {}, callback) ->
callback = findCallback(arguments)
appName = appName.toLowerCase()
owner = owner.toLowerCase()
pine.get
resource: 'application'
options:
mergePineOptions
$filter:
slug: "#{owner}/#{appName}"
, options
.tap (applications) ->
if isEmpty(applications)
throw new errors.BalenaApplicationNotFound("#{owner}/#{appName}")
if size(applications) > 1
throw new errors.BalenaAmbiguousApplication("#{owner}/#{appName}")
.get(0)
.tap(normalizeApplication)
.asCallback(callback)
###*
# @summary Check if an application exists
# @name has
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {Boolean} - has application
# @returns {Promise}
#
# @example
# balena.models.application.has('MyApp').then(function(hasApp) {
# console.log(hasApp);
# });
#
# @example
# balena.models.application.has(123).then(function(hasApp) {
# console.log(hasApp);
# });
#
# @example
# balena.models.application.has('MyApp', function(error, hasApp) {
# if (error) throw error;
# console.log(hasApp);
# });
###
exports.has = (nameOrSlugOrId, callback) ->
exports.get(nameOrSlugOrId, $select: ['id']).return(true)
.catch errors.BalenaApplicationNotFound, ->
return false
.asCallback(callback)
###*
# @summary Check if the user has any applications
# @name hasAny
# @public
# @function
# @memberof balena.models.application
#
# @fulfil {Boolean} - has any applications
# @returns {Promise}
#
# @example
# balena.models.application.hasAny().then(function(hasAny) {
# console.log('Has any?', hasAny);
# });
#
# @example
# balena.models.application.hasAny(function(error, hasAny) {
# if (error) throw error;
# console.log('Has any?', hasAny);
# });
###
exports.hasAny = (callback) ->
exports.getAll($select: ['id']).then (applications) ->
return not isEmpty(applications)
.asCallback(callback)
###*
# @summary Create an application
# @name create
# @public
# @function
# @memberof balena.models.application
#
# @param {Object} options - application creation parameters
# @param {String} options.name - application name
# @param {String} [options.applicationType] - application type slug e.g. microservices-starter
# @param {String} options.deviceType - device type slug
# @param {(Number|String)} [options.parent] - parent application name or id
#
# @fulfil {Object} - application
# @returns {Promise}
#
# @example
# balena.models.application.create({ name: '<NAME>', applicationType: 'essentials', deviceType: 'raspberry-pi' }).then(function(application) {
# console.log(application);
# });
#
# @example
# balena.models.application.create({ name: '<NAME>', applicationType: 'microservices', deviceType: 'raspberry-pi', parent: 'ParentApp' }).then(function(application) {
# console.log(application);
# });
#
# @example
# balena.models.application.create({ name: '<NAME>', applicationType: 'microservices-starter', deviceType: 'raspberry-pi' }, function(error, application) {
# if (error) throw error;
# console.log(application);
# });
###
exports.create = ({ name, applicationType, deviceType, parent }, callback) ->
callback = findCallback(arguments)
applicationTypePromise = if !applicationType
Promise.resolve()
else
pine.get
resource: 'application_type'
options:
$select: [ 'id' ]
$filter:
slug: applicationType
.get(0)
.then (appType) ->
if not appType
throw new Error("Invalid application type: #{applicationType}")
appType.id
parentAppPromise = if parent
exports.get(parent, $select: [ 'id' ])
else
Promise.resolve()
deviceManifestPromise = deviceModel().getManifestBySlug(deviceType)
.tap (deviceManifest) ->
if not deviceManifest?
throw new errors.BalenaInvalidDeviceType(deviceType)
return Promise.all([
deviceManifestPromise
applicationTypePromise
parentAppPromise
])
.then ([
deviceManifest
applicationTypeId
parentApplication
]) ->
if deviceManifest.state == 'DISCONTINUED'
throw new errors.BalenaDiscontinuedDeviceType(deviceType)
extraOptions = if parentApplication
depends_on__application: parentApplication.id
else {}
if applicationTypeId
assign extraOptions,
application_type: applicationTypeId
return pine.post
resource: 'application'
body:
assign
app_name: name
device_type: deviceManifest.slug
, extraOptions
.asCallback(callback)
###*
# @summary Remove application
# @name remove
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.remove('MyApp');
#
# @example
# balena.models.application.remove(123);
#
# @example
# balena.models.application.remove('MyApp', function(error) {
# if (error) throw error;
# });
###
exports.remove = (nameOrSlugOrId, callback) ->
getId(nameOrSlugOrId).then (applicationId) ->
return pine.delete
resource: 'application'
id: applicationId
.catch(isNotFoundResponse, treatAsMissingApplication(nameOrSlugOrId))
.asCallback(callback)
###*
# @summary Restart application
# @name restart
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.restart('MyApp');
#
# @example
# balena.models.application.restart(123);
#
# @example
# balena.models.application.restart('MyApp', function(error) {
# if (error) throw error;
# });
###
exports.restart = (nameOrSlugOrId, callback) ->
getId(nameOrSlugOrId).then (applicationId) ->
return request.send
method: 'POST'
url: "/application/#{applicationId}/restart"
baseUrl: apiUrl
.return(undefined)
.catch(isNotFoundResponse, treatAsMissingApplication(nameOrSlugOrId))
.asCallback(callback)
###*
# @summary Generate an API key for a specific application
# @name generateApiKey
# @public
# @function
# @memberof balena.models.application
# @deprecated
# @description
# Generally you shouldn't use this method: if you're provisioning a recent BalenaOS
# version (2.4.0+) then generateProvisioningKey should work just as well, but
# be more secure.
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {String} - api key
# @returns {Promise}
#
# @example
# balena.models.application.generateApiKey('MyApp').then(function(apiKey) {
# console.log(apiKey);
# });
#
# @example
# balena.models.application.generateApiKey(123).then(function(apiKey) {
# console.log(apiKey);
# });
#
# @example
# balena.models.application.generateApiKey('MyApp', function(error, apiKey) {
# if (error) throw error;
# console.log(apiKey);
# });
###
exports.generateApiKey = (nameOrSlugOrId, callback) ->
# Do a full get, not just getId, because the actual api endpoint doesn't fail if the id
# doesn't exist. TODO: Can use getId once https://github.com/balena-io/balena-api/issues/110 is resolved
exports.get(nameOrSlugOrId, $select: 'id').then ({ id }) ->
return request.send
method: 'POST'
url: "/application/#{id}/generate-api-key"
baseUrl: apiUrl
.get('body')
.asCallback(callback)
###*
# @summary Generate a device provisioning key for a specific application
# @name generateProvisioningKey
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {String} - device provisioning key
# @returns {Promise}
#
# @example
# balena.models.application.generateProvisioningKey('MyApp').then(function(key) {
# console.log(key);
# });
#
# @example
# balena.models.application.generateProvisioningKey(123).then(function(key) {
# console.log(key);
# });
#
# @example
# balena.models.application.generateProvisioningKey('MyApp', function(error, key) {
# if (error) throw error;
# console.log(key);
# });
###
exports.generateProvisioningKey = (nameOrSlugOrId, callback) ->
getId(nameOrSlugOrId).then (applicationId) ->
return request.send
method: 'POST'
url: "/api-key/application/#{applicationId}/provisioning"
baseUrl: apiUrl
.catch(isNoApplicationForKeyResponse, treatAsMissingApplication(nameOrSlugOrId))
.get('body')
.asCallback(callback)
###*
# @summary Purge devices by application id
# @name purge
# @public
# @function
# @memberof balena.models.application
#
# @param {Number} appId - application id
# @returns {Promise}
#
# @example
# balena.models.application.purge(123);
#
# @example
# balena.models.application.purge(123, function(error) {
# if (error) throw error;
# });
###
exports.purge = (appId, callback) ->
return request.send
method: 'POST'
url: '/supervisor/v1/purge'
baseUrl: apiUrl
body:
appId: appId
data:
appId: "#{appId}"
.catch (err) ->
if err.statusCode == LOCKED_STATUS_CODE
throw new errors.BalenaSupervisorLockedError()
throw err
.asCallback(callback)
###*
# @summary Shutdown devices by application id
# @name shutdown
# @public
# @function
# @memberof balena.models.application
#
# @param {Number} appId - application id
# @param {Object} [options] - options
# @param {Boolean} [options.force=false] - override update lock
# @returns {Promise}
#
# @example
# balena.models.application.shutdown(123);
#
# @example
# balena.models.application.shutdown(123, function(error) {
# if (error) throw error;
# });
###
exports.shutdown = (appId, options = {}, callback) ->
return request.send
method: 'POST'
url: '/supervisor/v1/shutdown'
baseUrl: apiUrl
body:
appId: appId
data:
force: Boolean(options.force)
.catch (err) ->
if err.statusCode == LOCKED_STATUS_CODE
throw new errors.BalenaSupervisorLockedError()
throw err
.asCallback(callback)
###*
# @summary Reboot devices by application id
# @name reboot
# @public
# @function
# @memberof balena.models.application
#
# @param {Number} appId - application id
# @param {Object} [options] - options
# @param {Boolean} [options.force=false] - override update lock
# @returns {Promise}
#
# @example
# balena.models.application.reboot(123);
#
# @example
# balena.models.application.reboot(123, function(error) {
# if (error) throw error;
# });
###
exports.reboot = (appId, options = {}, callback) ->
return request.send
method: 'POST'
url: '/supervisor/v1/reboot'
baseUrl: apiUrl
body:
appId: appId
data:
force: Boolean(options.force)
.catch (err) ->
if err.statusCode == LOCKED_STATUS_CODE
throw new errors.BalenaSupervisorLockedError()
throw err
.asCallback(callback)
###*
# @summary Get whether the application is configured to receive updates whenever a new release is available
# @name willTrackNewReleases
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {Boolean} - is tracking the latest release
# @returns {Promise}
#
# @example
# balena.models.application.willTrackNewReleases('MyApp').then(function(isEnabled) {
# console.log(isEnabled);
# });
#
# @example
# balena.models.application.willTrackNewReleases(123).then(function(isEnabled) {
# console.log(isEnabled);
# });
#
# @example
# balena.models.application.willTrackNewReleases('MyApp', function(error, isEnabled) {
# console.log(isEnabled);
# });
###
exports.willTrackNewReleases = (nameOrSlugOrId, callback) ->
exports.get(nameOrSlugOrId, $select: 'should_track_latest_release')
.get('should_track_latest_release')
.asCallback(callback)
###*
# @summary Get whether the application is up to date and is tracking the latest release for updates
# @name isTrackingLatestRelease
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {Boolean} - is tracking the latest release
# @returns {Promise}
#
# @example
# balena.models.application.isTrackingLatestRelease('MyApp').then(function(isEnabled) {
# console.log(isEnabled);
# });
#
# @example
# balena.models.application.isTrackingLatestRelease(123).then(function(isEnabled) {
# console.log(isEnabled);
# });
#
# @example
# balena.models.application.isTrackingLatestRelease('MyApp', function(error, isEnabled) {
# console.log(isEnabled);
# });
###
exports.isTrackingLatestRelease = (nameOrSlugOrId, callback) ->
Promise.all([
exports.get(nameOrSlugOrId, $select: ['commit', 'should_track_latest_release'])
releaseModel().getLatestByApplication(nameOrSlugOrId, $select: 'commit')
])
.then ([application, latestRelease]) ->
return application.should_track_latest_release &&
(!latestRelease || application.commit == latestRelease.commit)
.asCallback(callback)
###*
# @summary Set a specific application to run a particular release
# @name pinToRelease
# @public
# @function
# @memberof balena.models.application
#
# @description Configures the application to run a particular release
# and not get updated when the latest release changes.
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} fullReleaseHash - the hash of a successful release (string)
# @returns {Promise}
#
# @example
# balena.models.application.pinToRelease('MyApp', 'f7caf4ff80114deeaefb7ab4447ad9c661c50847').then(function() {
# ...
# });
#
# @example
# balena.models.application.pinToRelease(123, 'f7caf4ff80114deeaefb7ab4447ad9c661c50847').then(function() {
# ...
# });
#
# @example
# balena.models.application.pinToRelease('MyApp', 'f7caf4ff80114deeaefb7ab4447ad9c661c50847', function(error) {
# if (error) throw error;
# ...
# });
###
exports.pinToRelease = (nameOrSlugOrId, fullReleaseHash, callback) ->
getId(nameOrSlugOrId)
.then (applicationId) ->
pine.patch
resource: 'application'
id: applicationId
body:
commit: fullReleaseHash
should_track_latest_release: false
.asCallback(callback)
###*
# @summary Get the hash of the current release for a specific application
# @name getTargetReleaseHash
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {String} - The release hash of the current release
# @returns {Promise}
#
# @example
# balena.models.application.getTargetReleaseHash('MyApp').then(function(release) {
# console.log(release);
# });
#
# @example
# balena.models.application.getTargetReleaseHash(123).then(function(release) {
# console.log(release);
# });
#
# @example
# balena.models.application.getTargetReleaseHash('MyApp', function(release) {
# console.log(release);
# });
###
exports.getTargetReleaseHash = (nameOrSlugOrId, callback) ->
exports.get(nameOrSlugOrId, $select: 'commit')
.get('commit')
.asCallback(callback)
###*
# @summary Configure a specific application to track the latest available release
# @name trackLatestRelease
# @public
# @function
# @memberof balena.models.application
#
# @description The application's current release will be updated with each new successfully built release.
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.trackLatestRelease('MyApp').then(function() {
# ...
# });
#
# @example
# balena.models.application.trackLatestRelease(123).then(function() {
# ...
# });
#
# @example
# balena.models.application.trackLatestRelease('MyApp', function(error) {
# if (error) throw error;
# ...
# });
###
exports.trackLatestRelease = (nameOrSlugOrId, callback) ->
releaseModel().getLatestByApplication(nameOrSlugOrId,
$select: ['commit', 'belongs_to__application']
)
.then (latestRelease) ->
if not latestRelease
return Promise.props(
applicationId: getId(nameOrSlugOrId)
commit: null
)
return {
applicationId: latestRelease.belongs_to__application.__id
commit: latestRelease.commit
}
.then ({ applicationId, commit }) ->
body =
should_track_latest_release: true
if commit
body.commit = commit
return pine.patch
resource: 'application'
id: applicationId
body: body
.asCallback(callback)
###*
# @summary Enable device urls for all devices that belong to an application
# @name enableDeviceUrls
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.enableDeviceUrls('MyApp');
#
# @example
# balena.models.application.enableDeviceUrls(123);
#
# @example
# balena.models.device.enableDeviceUrls('MyApp', function(error) {
# if (error) throw error;
# });
###
exports.enableDeviceUrls = (nameOrSlugOrId, callback) ->
exports.get(nameOrSlugOrId, $select: 'id').then ({ id }) ->
return pine.patch
resource: 'device'
body:
is_web_accessible: true
options:
$filter:
belongs_to__application: id
.asCallback(callback)
###*
# @summary Disable device urls for all devices that belong to an application
# @name disableDeviceUrls
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.disableDeviceUrls('MyApp');
#
# @example
# balena.models.application.disableDeviceUrls(123);
#
# @example
# balena.models.device.disableDeviceUrls('MyApp', function(error) {
# if (error) throw error;
# });
###
exports.disableDeviceUrls = (nameOrSlugOrId, callback) ->
exports.get(nameOrSlugOrId, $select: 'id').then ({ id }) ->
return pine.patch
resource: 'device'
body:
is_web_accessible: false
options:
$filter:
belongs_to__application: id
.asCallback(callback)
###*
# @summary Grant support access to an application until a specified time
# @name grantSupportAccess
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Number} expiryTimestamp - a timestamp in ms for when the support access will expire
# @returns {Promise}
#
# @example
# balena.models.application.grantSupportAccess('MyApp', Date.now() + 3600 * 1000);
#
# @example
# balena.models.application.grantSupportAccess(123, Date.now() + 3600 * 1000);
#
# @example
# balena.models.application.grantSupportAccess('MyApp', Date.now() + 3600 * 1000, function(error) {
# if (error) throw error;
# });
###
exports.grantSupportAccess = (nameOrSlugOrId, expiryTimestamp, callback) ->
if not expiryTimestamp? or expiryTimestamp <= Date.now()
throw new errors.BalenaInvalidParameterError('expiryTimestamp', expiryTimestamp)
getId(nameOrSlugOrId).then (applicationId) ->
return pine.patch
resource: 'application'
id: applicationId
body: is_accessible_by_support_until__date: expiryTimestamp
.catch(isNotFoundResponse, treatAsMissingApplication(nameOrSlugOrId))
.asCallback(callback)
###*
# @summary Revoke support access to an application
# @name revokeSupportAccess
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.revokeSupportAccess('MyApp');
#
# @example
# balena.models.application.revokeSupportAccess(123);
#
# @example
# balena.models.application.revokeSupportAccess('MyApp', function(error) {
# if (error) throw error;
# });
###
exports.revokeSupportAccess = (nameOrSlugOrId, callback) ->
getId(nameOrSlugOrId).then (applicationId) ->
return pine.patch
resource: 'application'
id: applicationId
body: is_accessible_by_support_until__date: null
.catch(isNotFoundResponse, treatAsMissingApplication(nameOrSlugOrId))
.asCallback(callback)
###*
# @namespace balena.models.application.tags
# @memberof balena.models.application
###
exports.tags = {
###*
# @summary Get all application tags for an application
# @name getAllByApplication
# @public
# @function
# @memberof balena.models.application.tags
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - application tags
# @returns {Promise}
#
# @example
# balena.models.application.tags.getAllByApplication('MyApp').then(function(tags) {
# console.log(tags);
# });
#
# @example
# balena.models.application.tags.getAllByApplication(999999).then(function(tags) {
# console.log(tags);
# });
#
# @example
# balena.models.application.tags.getAllByApplication('MyApp', function(error, tags) {
# if (error) throw error;
# console.log(tags)
# });
###
getAllByApplication: tagsModel.getAllByParent
###*
# @summary Get all application tags
# @name getAll
# @public
# @function
# @memberof balena.models.application.tags
#
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - application tags
# @returns {Promise}
#
# @example
# balena.models.application.tags.getAll().then(function(tags) {
# console.log(tags);
# });
#
# @example
# balena.models.application.tags.getAll(function(error, tags) {
# if (error) throw error;
# console.log(tags)
# });
###
getAll: tagsModel.getAll
###*
# @summary Set an application tag
# @name set
# @public
# @function
# @memberof balena.models.application.tags
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} tagKey - tag key
# @param {String|undefined} value - tag value
#
# @returns {Promise}
#
# @example
# balena.models.application.tags.set('7cf02a6', 'EDITOR', 'vim');
#
# @example
# balena.models.application.tags.set(123, 'EDITOR', 'vim');
#
# @example
# balena.models.application.tags.set('7cf02a6', 'EDITOR', 'vim', function(error) {
# if (error) throw error;
# });
###
set: tagsModel.set
###*
# @summary Remove an application tag
# @name remove
# @public
# @function
# @memberof balena.models.application.tags
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} tagKey - tag key
# @returns {Promise}
#
# @example
# balena.models.application.tags.remove('7cf02a6', 'EDITOR');
#
# @example
# balena.models.application.tags.remove('7cf02a6', 'EDITOR', function(error) {
# if (error) throw error;
# });
###
remove: tagsModel.remove
}
###*
# @namespace balena.models.application.configVar
# @memberof balena.models.application
###
exports.configVar = {
###*
# @summary Get all config variables for an application
# @name getAllByApplication
# @public
# @function
# @memberof balena.models.application.configVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - application config variables
# @returns {Promise}
#
# @example
# balena.models.application.configVar.getAllByApplication('MyApp').then(function(vars) {
# console.log(vars);
# });
#
# @example
# balena.models.application.configVar.getAllByApplication(999999).then(function(vars) {
# console.log(vars);
# });
#
# @example
# balena.models.application.configVar.getAllByApplication('MyApp', function(error, vars) {
# if (error) throw error;
# console.log(vars)
# });
###
getAllByApplication: configVarModel.getAllByParent
###*
# @summary Get the value of a specific config variable
# @name get
# @public
# @function
# @memberof balena.models.application.configVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - config variable name
# @fulfil {String|undefined} - the config variable value (or undefined)
# @returns {Promise}
#
# @example
# balena.models.application.configVar.get('MyApp', 'BALENA_VAR').then(function(value) {
# console.log(value);
# });
#
# @example
# balena.models.application.configVar.get(999999, 'BALENA_VAR').then(function(value) {
# console.log(value);
# });
#
# @example
# balena.models.application.configVar.get('MyApp', 'BALENA_VAR', function(error, value) {
# if (error) throw error;
# console.log(value)
# });
###
get: configVarModel.get
###*
# @summary Set the value of a specific config variable
# @name set
# @public
# @function
# @memberof balena.models.application.configVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - config variable name
# @param {String} value - config variable value
# @returns {Promise}
#
# @example
# balena.models.application.configVar.set('MyApp', 'BALENA_VAR', 'newvalue').then(function() {
# ...
# });
#
# @example
# balena.models.application.configVar.set(999999, 'BALENA_VAR', 'newvalue').then(function() {
# ...
# });
#
# @example
# balena.models.application.configVar.set('MyApp', 'BALENA_VAR', 'newvalue', function(error) {
# if (error) throw error;
# ...
# });
###
set: configVarModel.set
###*
# @summary Clear the value of a specific config variable
# @name remove
# @public
# @function
# @memberof balena.models.application.configVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - config variable name
# @returns {Promise}
#
# @example
# balena.models.application.configVar.remove('MyApp', 'BALENA_VAR').then(function() {
# ...
# });
#
# @example
# balena.models.application.configVar.remove(999999, 'BALENA_VAR').then(function() {
# ...
# });
#
# @example
# balena.models.application.configVar.remove('MyApp', 'BALENA_VAR', function(error) {
# if (error) throw error;
# ...
# });
###
remove: configVarModel.remove
}
###*
# @namespace balena.models.application.envVar
# @memberof balena.models.application
###
exports.envVar = {
###*
# @summary Get all environment variables for an application
# @name getAllByApplication
# @public
# @function
# @memberof balena.models.application.envVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - application environment variables
# @returns {Promise}
#
# @example
# balena.models.application.envVar.getAllByApplication('MyApp').then(function(vars) {
# console.log(vars);
# });
#
# @example
# balena.models.application.envVar.getAllByApplication(999999).then(function(vars) {
# console.log(vars);
# });
#
# @example
# balena.models.application.envVar.getAllByApplication('MyApp', function(error, vars) {
# if (error) throw error;
# console.log(vars)
# });
###
getAllByApplication: envVarModel.getAllByParent
###*
# @summary Get the value of a specific environment variable
# @name get
# @public
# @function
# @memberof balena.models.application.envVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - environment variable name
# @fulfil {String|undefined} - the environment variable value (or undefined)
# @returns {Promise}
#
# @example
# balena.models.application.envVar.get('MyApp', 'VAR').then(function(value) {
# console.log(value);
# });
#
# @example
# balena.models.application.envVar.get(999999, 'VAR').then(function(value) {
# console.log(value);
# });
#
# @example
# balena.models.application.envVar.get('MyApp', 'VAR', function(error, value) {
# if (error) throw error;
# console.log(value)
# });
###
get: envVarModel.get
###*
# @summary Set the value of a specific environment variable
# @name set
# @public
# @function
# @memberof balena.models.application.envVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - environment variable name
# @param {String} value - environment variable value
# @returns {Promise}
#
# @example
# balena.models.application.envVar.set('MyApp', 'VAR', 'newvalue').then(function() {
# ...
# });
#
# @example
# balena.models.application.envVar.set(999999, 'VAR', 'newvalue').then(function() {
# ...
# });
#
# @example
# balena.models.application.envVar.set('MyApp', 'VAR', 'newvalue', function(error) {
# if (error) throw error;
# ...
# });
###
set: envVarModel.set
###*
# @summary Clear the value of a specific environment variable
# @name remove
# @public
# @function
# @memberof balena.models.application.envVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - environment variable name
# @returns {Promise}
#
# @example
# balena.models.application.envVar.remove('MyApp', 'VAR').then(function() {
# ...
# });
#
# @example
# balena.models.application.envVar.remove(999999, 'VAR').then(function() {
# ...
# });
#
# @example
# balena.models.application.envVar.remove('MyApp', 'VAR', function(error) {
# if (error) throw error;
# ...
# });
###
remove: envVarModel.remove
}
return exports
module.exports =
default: getApplicationModel
| true | ###
Copyright 2016 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.
###
url = require('url')
Promise = require('bluebird')
once = require('lodash/once')
assign = require('lodash/assign')
isArray = require('lodash/isArray')
isEmpty = require('lodash/isEmpty')
size = require('lodash/size')
errors = require('balena-errors')
{
isId,
isNoApplicationForKeyResponse,
isNotFoundResponse,
findCallback,
mergePineOptions,
treatAsMissingApplication,
LOCKED_STATUS_CODE
} = require('../util')
{ normalizeDeviceOsVersion } = require('../util/device-os-version')
{
getCurrentServiceDetailsPineOptions,
generateCurrentServiceDetails,
} = require('../util/device-service-details')
getApplicationModel = (deps, opts) ->
{ request, pine } = deps
{ apiUrl, dashboardUrl } = opts
deviceModel = once -> require('./device').default(deps, opts)
releaseModel = once -> require('./release').default(deps, opts)
{ buildDependentResource } = require('../util/dependent-resource')
tagsModel = buildDependentResource { pine }, {
resourceName: 'application_tag'
resourceKeyField: 'tag_key'
parentResourceName: 'application',
getResourceId: (nameOrSlugOrId) -> exports.get(nameOrSlugOrId, $select: 'id').get('id')
ResourceNotFoundError: errors.BalenaApplicationNotFound
}
configVarModel = buildDependentResource { pine }, {
resourceName: 'application_config_variable'
resourceKeyField: 'name'
parentResourceName: 'application',
getResourceId: (nameOrSlugOrId) -> exports.get(nameOrSlugOrId, $select: 'id').get('id')
ResourceNotFoundError: errors.BalenaApplicationNotFound
}
envVarModel = buildDependentResource { pine }, {
resourceName: 'application_environment_variable'
resourceKeyField: 'name'
parentResourceName: 'application',
getResourceId: (nameOrSlugOrId) -> exports.get(nameOrSlugOrId, $select: 'id').get('id')
ResourceNotFoundError: errors.BalenaApplicationNotFound
}
exports = {}
# Infer dashboardUrl from apiUrl if former is undefined
if not dashboardUrl?
dashboardUrl = apiUrl.replace(/api/, 'dashboard')
# Internal method for name/id disambiguation
# Note that this throws an exception for missing names, but not missing ids
getId = (nameOrSlugOrId) ->
Promise.try ->
if isId(nameOrSlugOrId)
return nameOrSlugOrId
else
exports.get(nameOrSlugOrId, $select: 'id').get('id')
exports._getId = getId
normalizeApplication = (application) ->
if isArray(application.owns__device)
application.owns__device.forEach (device) ->
normalizeDeviceOsVersion(device)
return application
###*
# @summary Get Dashboard URL for a specific application
# @function getDashboardUrl
# @memberof balena.models.application
#
# @param {Number} id - Application id
#
# @returns {String} - Dashboard URL for the specific application
# @throws Exception if the id is not a finite number
#
# @example
# balena.models.application.get('MyApp').then(function(application) {
# const dashboardApplicationUrl = balena.models.application.getDashboardUrl(application.id);
# console.log(dashboardApplicationUrl);
# });
###
exports.getDashboardUrl = (id) ->
if typeof id != 'number' || !Number.isFinite(id)
throw new Error('The id option should be a finite number')
return url.resolve(dashboardUrl, "/apps/#{id}")
###*
# @summary Get all applications
# @name getAll
# @public
# @function
# @memberof balena.models.application
#
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - applications
# @returns {Promise}
#
# @example
# balena.models.application.getAll().then(function(applications) {
# console.log(applications);
# });
#
# @example
# balena.models.application.getAll(function(error, applications) {
# if (error) throw error;
# console.log(applications);
# });
###
exports.getAll = (options = {}, callback) ->
callback = findCallback(arguments)
return pine.get
resource: 'my_application'
options:
mergePineOptions
$orderby: 'app_name asc'
, options
.map (application) ->
normalizeApplication(application)
return application
.asCallback(callback)
###*
# @summary Get applications and their devices, along with each device's
# associated services' essential details
# @name getAllWithDeviceServiceDetails
# @public
# @function
# @memberof balena.models.application
#
# @description
# This method does not map exactly to the underlying model: it runs a
# larger prebuilt query, and reformats it into an easy to use and
# understand format. If you want more control, or to see the raw model
# directly, use `application.getAll(options)` instead.
# **NOTE:** In contrast with device.getWithServiceDetails() the service details
# in the result of this method do not include the associated commit.
#
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - applications
# @returns {Promise}
#
# @example
# balena.models.application.getAllWithDeviceServiceDetails().then(function(applications) {
# console.log(applications);
# })
#
# @example
# balena.models.application.getAllWithDeviceServiceDetails(function(error, applications) {
# if (error) throw error;
# console.log(applications);
# });
###
exports.getAllWithDeviceServiceDetails = (options = {}, callback) ->
callback = findCallback(arguments)
serviceOptions = mergePineOptions
$expand: [
owns__device: getCurrentServiceDetailsPineOptions(false)
]
, options
exports.getAll(serviceOptions)
.then (apps) ->
apps.forEach (app) ->
app.owns__device = app.owns__device.map(generateCurrentServiceDetails)
return apps
.asCallback(callback)
###*
# @summary Get a single application
# @name get
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object} - application
# @returns {Promise}
#
# @example
# balena.models.application.get('MyApp').then(function(application) {
# console.log(application);
# });
#
# @example
# balena.models.application.get(123).then(function(application) {
# console.log(application);
# });
#
# @example
# balena.models.application.get('MyApp', function(error, application) {
# if (error) throw error;
# console.log(application);
# });
###
exports.get = (nameOrSlugOrId, options = {}, callback) ->
callback = findCallback(arguments)
Promise.try ->
if not nameOrSlugOrId?
throw new errors.BalenaApplicationNotFound(nameOrSlugOrId)
if isId(nameOrSlugOrId)
pine.get
resource: 'application'
id: nameOrSlugOrId
options: mergePineOptions({}, options)
.tap (application) ->
if not application?
throw new errors.BalenaApplicationNotFound(nameOrSlugOrId)
else
pine.get
resource: 'application'
options:
mergePineOptions
$filter:
$or:
app_name: nameOrSlugOrId
slug: nameOrSlugOrId.toLowerCase()
, options
.tap (applications) ->
if isEmpty(applications)
throw new errors.BalenaApplicationNotFound(nameOrSlugOrId)
if size(applications) > 1
throw new errors.BalenaAmbiguousApplication(nameOrSlugOrId)
.get(0)
.tap(normalizeApplication)
.asCallback(callback)
###*
# @summary Get a single application and its devices, along with each device's
# associated services' essential details
# @name getWithDeviceServiceDetails
# @public
# @function
# @memberof balena.models.application
#
# @description
# This method does not map exactly to the underlying model: it runs a
# larger prebuilt query, and reformats it into an easy to use and
# understand format. If you want more control, or to see the raw model
# directly, use `application.get(uuidOrId, options)` instead.
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object} - application
# @returns {Promise}
#
# @example
# balena.models.application.getWithDeviceServiceDetails('7cf02a6').then(function(device) {
# console.log(device);
# })
#
# @example
# balena.models.application.getWithDeviceServiceDetails(123).then(function(device) {
# console.log(device);
# })
#
# @example
# balena.models.application.getWithDeviceServiceDetails('7cf02a6', function(error, device) {
# if (error) throw error;
# console.log(device);
# });
###
exports.getWithDeviceServiceDetails = (nameOrSlugOrId, options = {}, callback) ->
callback = findCallback(arguments)
serviceOptions = mergePineOptions
$expand: [
owns__device: getCurrentServiceDetailsPineOptions(true)
]
, options
exports.get(nameOrSlugOrId, serviceOptions)
.then (app) ->
if app and app.owns__device
app.owns__device = app.owns__device.map(generateCurrentServiceDetails)
return app
.asCallback(callback)
###*
# @summary Get a single application using the appname and owner's username
# @name getAppByOwner
# @public
# @function
# @memberof balena.models.application
#
# @param {String} appName - application name
# @param {String} owner - The owner's username
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object} - application
# @returns {Promise}
#
# @example
# balena.models.application.getAppByOwner('MyApp', 'MyUser').then(function(application) {
# console.log(application);
# });
###
exports.getAppByOwner = (appName, owner, options = {}, callback) ->
callback = findCallback(arguments)
appName = appName.toLowerCase()
owner = owner.toLowerCase()
pine.get
resource: 'application'
options:
mergePineOptions
$filter:
slug: "#{owner}/#{appName}"
, options
.tap (applications) ->
if isEmpty(applications)
throw new errors.BalenaApplicationNotFound("#{owner}/#{appName}")
if size(applications) > 1
throw new errors.BalenaAmbiguousApplication("#{owner}/#{appName}")
.get(0)
.tap(normalizeApplication)
.asCallback(callback)
###*
# @summary Check if an application exists
# @name has
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {Boolean} - has application
# @returns {Promise}
#
# @example
# balena.models.application.has('MyApp').then(function(hasApp) {
# console.log(hasApp);
# });
#
# @example
# balena.models.application.has(123).then(function(hasApp) {
# console.log(hasApp);
# });
#
# @example
# balena.models.application.has('MyApp', function(error, hasApp) {
# if (error) throw error;
# console.log(hasApp);
# });
###
exports.has = (nameOrSlugOrId, callback) ->
exports.get(nameOrSlugOrId, $select: ['id']).return(true)
.catch errors.BalenaApplicationNotFound, ->
return false
.asCallback(callback)
###*
# @summary Check if the user has any applications
# @name hasAny
# @public
# @function
# @memberof balena.models.application
#
# @fulfil {Boolean} - has any applications
# @returns {Promise}
#
# @example
# balena.models.application.hasAny().then(function(hasAny) {
# console.log('Has any?', hasAny);
# });
#
# @example
# balena.models.application.hasAny(function(error, hasAny) {
# if (error) throw error;
# console.log('Has any?', hasAny);
# });
###
exports.hasAny = (callback) ->
exports.getAll($select: ['id']).then (applications) ->
return not isEmpty(applications)
.asCallback(callback)
###*
# @summary Create an application
# @name create
# @public
# @function
# @memberof balena.models.application
#
# @param {Object} options - application creation parameters
# @param {String} options.name - application name
# @param {String} [options.applicationType] - application type slug e.g. microservices-starter
# @param {String} options.deviceType - device type slug
# @param {(Number|String)} [options.parent] - parent application name or id
#
# @fulfil {Object} - application
# @returns {Promise}
#
# @example
# balena.models.application.create({ name: 'PI:NAME:<NAME>END_PI', applicationType: 'essentials', deviceType: 'raspberry-pi' }).then(function(application) {
# console.log(application);
# });
#
# @example
# balena.models.application.create({ name: 'PI:NAME:<NAME>END_PI', applicationType: 'microservices', deviceType: 'raspberry-pi', parent: 'ParentApp' }).then(function(application) {
# console.log(application);
# });
#
# @example
# balena.models.application.create({ name: 'PI:NAME:<NAME>END_PI', applicationType: 'microservices-starter', deviceType: 'raspberry-pi' }, function(error, application) {
# if (error) throw error;
# console.log(application);
# });
###
exports.create = ({ name, applicationType, deviceType, parent }, callback) ->
callback = findCallback(arguments)
applicationTypePromise = if !applicationType
Promise.resolve()
else
pine.get
resource: 'application_type'
options:
$select: [ 'id' ]
$filter:
slug: applicationType
.get(0)
.then (appType) ->
if not appType
throw new Error("Invalid application type: #{applicationType}")
appType.id
parentAppPromise = if parent
exports.get(parent, $select: [ 'id' ])
else
Promise.resolve()
deviceManifestPromise = deviceModel().getManifestBySlug(deviceType)
.tap (deviceManifest) ->
if not deviceManifest?
throw new errors.BalenaInvalidDeviceType(deviceType)
return Promise.all([
deviceManifestPromise
applicationTypePromise
parentAppPromise
])
.then ([
deviceManifest
applicationTypeId
parentApplication
]) ->
if deviceManifest.state == 'DISCONTINUED'
throw new errors.BalenaDiscontinuedDeviceType(deviceType)
extraOptions = if parentApplication
depends_on__application: parentApplication.id
else {}
if applicationTypeId
assign extraOptions,
application_type: applicationTypeId
return pine.post
resource: 'application'
body:
assign
app_name: name
device_type: deviceManifest.slug
, extraOptions
.asCallback(callback)
###*
# @summary Remove application
# @name remove
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.remove('MyApp');
#
# @example
# balena.models.application.remove(123);
#
# @example
# balena.models.application.remove('MyApp', function(error) {
# if (error) throw error;
# });
###
exports.remove = (nameOrSlugOrId, callback) ->
getId(nameOrSlugOrId).then (applicationId) ->
return pine.delete
resource: 'application'
id: applicationId
.catch(isNotFoundResponse, treatAsMissingApplication(nameOrSlugOrId))
.asCallback(callback)
###*
# @summary Restart application
# @name restart
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.restart('MyApp');
#
# @example
# balena.models.application.restart(123);
#
# @example
# balena.models.application.restart('MyApp', function(error) {
# if (error) throw error;
# });
###
exports.restart = (nameOrSlugOrId, callback) ->
getId(nameOrSlugOrId).then (applicationId) ->
return request.send
method: 'POST'
url: "/application/#{applicationId}/restart"
baseUrl: apiUrl
.return(undefined)
.catch(isNotFoundResponse, treatAsMissingApplication(nameOrSlugOrId))
.asCallback(callback)
###*
# @summary Generate an API key for a specific application
# @name generateApiKey
# @public
# @function
# @memberof balena.models.application
# @deprecated
# @description
# Generally you shouldn't use this method: if you're provisioning a recent BalenaOS
# version (2.4.0+) then generateProvisioningKey should work just as well, but
# be more secure.
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {String} - api key
# @returns {Promise}
#
# @example
# balena.models.application.generateApiKey('MyApp').then(function(apiKey) {
# console.log(apiKey);
# });
#
# @example
# balena.models.application.generateApiKey(123).then(function(apiKey) {
# console.log(apiKey);
# });
#
# @example
# balena.models.application.generateApiKey('MyApp', function(error, apiKey) {
# if (error) throw error;
# console.log(apiKey);
# });
###
exports.generateApiKey = (nameOrSlugOrId, callback) ->
# Do a full get, not just getId, because the actual api endpoint doesn't fail if the id
# doesn't exist. TODO: Can use getId once https://github.com/balena-io/balena-api/issues/110 is resolved
exports.get(nameOrSlugOrId, $select: 'id').then ({ id }) ->
return request.send
method: 'POST'
url: "/application/#{id}/generate-api-key"
baseUrl: apiUrl
.get('body')
.asCallback(callback)
###*
# @summary Generate a device provisioning key for a specific application
# @name generateProvisioningKey
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {String} - device provisioning key
# @returns {Promise}
#
# @example
# balena.models.application.generateProvisioningKey('MyApp').then(function(key) {
# console.log(key);
# });
#
# @example
# balena.models.application.generateProvisioningKey(123).then(function(key) {
# console.log(key);
# });
#
# @example
# balena.models.application.generateProvisioningKey('MyApp', function(error, key) {
# if (error) throw error;
# console.log(key);
# });
###
exports.generateProvisioningKey = (nameOrSlugOrId, callback) ->
getId(nameOrSlugOrId).then (applicationId) ->
return request.send
method: 'POST'
url: "/api-key/application/#{applicationId}/provisioning"
baseUrl: apiUrl
.catch(isNoApplicationForKeyResponse, treatAsMissingApplication(nameOrSlugOrId))
.get('body')
.asCallback(callback)
###*
# @summary Purge devices by application id
# @name purge
# @public
# @function
# @memberof balena.models.application
#
# @param {Number} appId - application id
# @returns {Promise}
#
# @example
# balena.models.application.purge(123);
#
# @example
# balena.models.application.purge(123, function(error) {
# if (error) throw error;
# });
###
exports.purge = (appId, callback) ->
return request.send
method: 'POST'
url: '/supervisor/v1/purge'
baseUrl: apiUrl
body:
appId: appId
data:
appId: "#{appId}"
.catch (err) ->
if err.statusCode == LOCKED_STATUS_CODE
throw new errors.BalenaSupervisorLockedError()
throw err
.asCallback(callback)
###*
# @summary Shutdown devices by application id
# @name shutdown
# @public
# @function
# @memberof balena.models.application
#
# @param {Number} appId - application id
# @param {Object} [options] - options
# @param {Boolean} [options.force=false] - override update lock
# @returns {Promise}
#
# @example
# balena.models.application.shutdown(123);
#
# @example
# balena.models.application.shutdown(123, function(error) {
# if (error) throw error;
# });
###
exports.shutdown = (appId, options = {}, callback) ->
return request.send
method: 'POST'
url: '/supervisor/v1/shutdown'
baseUrl: apiUrl
body:
appId: appId
data:
force: Boolean(options.force)
.catch (err) ->
if err.statusCode == LOCKED_STATUS_CODE
throw new errors.BalenaSupervisorLockedError()
throw err
.asCallback(callback)
###*
# @summary Reboot devices by application id
# @name reboot
# @public
# @function
# @memberof balena.models.application
#
# @param {Number} appId - application id
# @param {Object} [options] - options
# @param {Boolean} [options.force=false] - override update lock
# @returns {Promise}
#
# @example
# balena.models.application.reboot(123);
#
# @example
# balena.models.application.reboot(123, function(error) {
# if (error) throw error;
# });
###
exports.reboot = (appId, options = {}, callback) ->
return request.send
method: 'POST'
url: '/supervisor/v1/reboot'
baseUrl: apiUrl
body:
appId: appId
data:
force: Boolean(options.force)
.catch (err) ->
if err.statusCode == LOCKED_STATUS_CODE
throw new errors.BalenaSupervisorLockedError()
throw err
.asCallback(callback)
###*
# @summary Get whether the application is configured to receive updates whenever a new release is available
# @name willTrackNewReleases
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {Boolean} - is tracking the latest release
# @returns {Promise}
#
# @example
# balena.models.application.willTrackNewReleases('MyApp').then(function(isEnabled) {
# console.log(isEnabled);
# });
#
# @example
# balena.models.application.willTrackNewReleases(123).then(function(isEnabled) {
# console.log(isEnabled);
# });
#
# @example
# balena.models.application.willTrackNewReleases('MyApp', function(error, isEnabled) {
# console.log(isEnabled);
# });
###
exports.willTrackNewReleases = (nameOrSlugOrId, callback) ->
exports.get(nameOrSlugOrId, $select: 'should_track_latest_release')
.get('should_track_latest_release')
.asCallback(callback)
###*
# @summary Get whether the application is up to date and is tracking the latest release for updates
# @name isTrackingLatestRelease
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {Boolean} - is tracking the latest release
# @returns {Promise}
#
# @example
# balena.models.application.isTrackingLatestRelease('MyApp').then(function(isEnabled) {
# console.log(isEnabled);
# });
#
# @example
# balena.models.application.isTrackingLatestRelease(123).then(function(isEnabled) {
# console.log(isEnabled);
# });
#
# @example
# balena.models.application.isTrackingLatestRelease('MyApp', function(error, isEnabled) {
# console.log(isEnabled);
# });
###
exports.isTrackingLatestRelease = (nameOrSlugOrId, callback) ->
Promise.all([
exports.get(nameOrSlugOrId, $select: ['commit', 'should_track_latest_release'])
releaseModel().getLatestByApplication(nameOrSlugOrId, $select: 'commit')
])
.then ([application, latestRelease]) ->
return application.should_track_latest_release &&
(!latestRelease || application.commit == latestRelease.commit)
.asCallback(callback)
###*
# @summary Set a specific application to run a particular release
# @name pinToRelease
# @public
# @function
# @memberof balena.models.application
#
# @description Configures the application to run a particular release
# and not get updated when the latest release changes.
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} fullReleaseHash - the hash of a successful release (string)
# @returns {Promise}
#
# @example
# balena.models.application.pinToRelease('MyApp', 'f7caf4ff80114deeaefb7ab4447ad9c661c50847').then(function() {
# ...
# });
#
# @example
# balena.models.application.pinToRelease(123, 'f7caf4ff80114deeaefb7ab4447ad9c661c50847').then(function() {
# ...
# });
#
# @example
# balena.models.application.pinToRelease('MyApp', 'f7caf4ff80114deeaefb7ab4447ad9c661c50847', function(error) {
# if (error) throw error;
# ...
# });
###
exports.pinToRelease = (nameOrSlugOrId, fullReleaseHash, callback) ->
getId(nameOrSlugOrId)
.then (applicationId) ->
pine.patch
resource: 'application'
id: applicationId
body:
commit: fullReleaseHash
should_track_latest_release: false
.asCallback(callback)
###*
# @summary Get the hash of the current release for a specific application
# @name getTargetReleaseHash
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @fulfil {String} - The release hash of the current release
# @returns {Promise}
#
# @example
# balena.models.application.getTargetReleaseHash('MyApp').then(function(release) {
# console.log(release);
# });
#
# @example
# balena.models.application.getTargetReleaseHash(123).then(function(release) {
# console.log(release);
# });
#
# @example
# balena.models.application.getTargetReleaseHash('MyApp', function(release) {
# console.log(release);
# });
###
exports.getTargetReleaseHash = (nameOrSlugOrId, callback) ->
exports.get(nameOrSlugOrId, $select: 'commit')
.get('commit')
.asCallback(callback)
###*
# @summary Configure a specific application to track the latest available release
# @name trackLatestRelease
# @public
# @function
# @memberof balena.models.application
#
# @description The application's current release will be updated with each new successfully built release.
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.trackLatestRelease('MyApp').then(function() {
# ...
# });
#
# @example
# balena.models.application.trackLatestRelease(123).then(function() {
# ...
# });
#
# @example
# balena.models.application.trackLatestRelease('MyApp', function(error) {
# if (error) throw error;
# ...
# });
###
exports.trackLatestRelease = (nameOrSlugOrId, callback) ->
releaseModel().getLatestByApplication(nameOrSlugOrId,
$select: ['commit', 'belongs_to__application']
)
.then (latestRelease) ->
if not latestRelease
return Promise.props(
applicationId: getId(nameOrSlugOrId)
commit: null
)
return {
applicationId: latestRelease.belongs_to__application.__id
commit: latestRelease.commit
}
.then ({ applicationId, commit }) ->
body =
should_track_latest_release: true
if commit
body.commit = commit
return pine.patch
resource: 'application'
id: applicationId
body: body
.asCallback(callback)
###*
# @summary Enable device urls for all devices that belong to an application
# @name enableDeviceUrls
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.enableDeviceUrls('MyApp');
#
# @example
# balena.models.application.enableDeviceUrls(123);
#
# @example
# balena.models.device.enableDeviceUrls('MyApp', function(error) {
# if (error) throw error;
# });
###
exports.enableDeviceUrls = (nameOrSlugOrId, callback) ->
exports.get(nameOrSlugOrId, $select: 'id').then ({ id }) ->
return pine.patch
resource: 'device'
body:
is_web_accessible: true
options:
$filter:
belongs_to__application: id
.asCallback(callback)
###*
# @summary Disable device urls for all devices that belong to an application
# @name disableDeviceUrls
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.disableDeviceUrls('MyApp');
#
# @example
# balena.models.application.disableDeviceUrls(123);
#
# @example
# balena.models.device.disableDeviceUrls('MyApp', function(error) {
# if (error) throw error;
# });
###
exports.disableDeviceUrls = (nameOrSlugOrId, callback) ->
exports.get(nameOrSlugOrId, $select: 'id').then ({ id }) ->
return pine.patch
resource: 'device'
body:
is_web_accessible: false
options:
$filter:
belongs_to__application: id
.asCallback(callback)
###*
# @summary Grant support access to an application until a specified time
# @name grantSupportAccess
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Number} expiryTimestamp - a timestamp in ms for when the support access will expire
# @returns {Promise}
#
# @example
# balena.models.application.grantSupportAccess('MyApp', Date.now() + 3600 * 1000);
#
# @example
# balena.models.application.grantSupportAccess(123, Date.now() + 3600 * 1000);
#
# @example
# balena.models.application.grantSupportAccess('MyApp', Date.now() + 3600 * 1000, function(error) {
# if (error) throw error;
# });
###
exports.grantSupportAccess = (nameOrSlugOrId, expiryTimestamp, callback) ->
if not expiryTimestamp? or expiryTimestamp <= Date.now()
throw new errors.BalenaInvalidParameterError('expiryTimestamp', expiryTimestamp)
getId(nameOrSlugOrId).then (applicationId) ->
return pine.patch
resource: 'application'
id: applicationId
body: is_accessible_by_support_until__date: expiryTimestamp
.catch(isNotFoundResponse, treatAsMissingApplication(nameOrSlugOrId))
.asCallback(callback)
###*
# @summary Revoke support access to an application
# @name revokeSupportAccess
# @public
# @function
# @memberof balena.models.application
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @returns {Promise}
#
# @example
# balena.models.application.revokeSupportAccess('MyApp');
#
# @example
# balena.models.application.revokeSupportAccess(123);
#
# @example
# balena.models.application.revokeSupportAccess('MyApp', function(error) {
# if (error) throw error;
# });
###
exports.revokeSupportAccess = (nameOrSlugOrId, callback) ->
getId(nameOrSlugOrId).then (applicationId) ->
return pine.patch
resource: 'application'
id: applicationId
body: is_accessible_by_support_until__date: null
.catch(isNotFoundResponse, treatAsMissingApplication(nameOrSlugOrId))
.asCallback(callback)
###*
# @namespace balena.models.application.tags
# @memberof balena.models.application
###
exports.tags = {
###*
# @summary Get all application tags for an application
# @name getAllByApplication
# @public
# @function
# @memberof balena.models.application.tags
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - application tags
# @returns {Promise}
#
# @example
# balena.models.application.tags.getAllByApplication('MyApp').then(function(tags) {
# console.log(tags);
# });
#
# @example
# balena.models.application.tags.getAllByApplication(999999).then(function(tags) {
# console.log(tags);
# });
#
# @example
# balena.models.application.tags.getAllByApplication('MyApp', function(error, tags) {
# if (error) throw error;
# console.log(tags)
# });
###
getAllByApplication: tagsModel.getAllByParent
###*
# @summary Get all application tags
# @name getAll
# @public
# @function
# @memberof balena.models.application.tags
#
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - application tags
# @returns {Promise}
#
# @example
# balena.models.application.tags.getAll().then(function(tags) {
# console.log(tags);
# });
#
# @example
# balena.models.application.tags.getAll(function(error, tags) {
# if (error) throw error;
# console.log(tags)
# });
###
getAll: tagsModel.getAll
###*
# @summary Set an application tag
# @name set
# @public
# @function
# @memberof balena.models.application.tags
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} tagKey - tag key
# @param {String|undefined} value - tag value
#
# @returns {Promise}
#
# @example
# balena.models.application.tags.set('7cf02a6', 'EDITOR', 'vim');
#
# @example
# balena.models.application.tags.set(123, 'EDITOR', 'vim');
#
# @example
# balena.models.application.tags.set('7cf02a6', 'EDITOR', 'vim', function(error) {
# if (error) throw error;
# });
###
set: tagsModel.set
###*
# @summary Remove an application tag
# @name remove
# @public
# @function
# @memberof balena.models.application.tags
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} tagKey - tag key
# @returns {Promise}
#
# @example
# balena.models.application.tags.remove('7cf02a6', 'EDITOR');
#
# @example
# balena.models.application.tags.remove('7cf02a6', 'EDITOR', function(error) {
# if (error) throw error;
# });
###
remove: tagsModel.remove
}
###*
# @namespace balena.models.application.configVar
# @memberof balena.models.application
###
exports.configVar = {
###*
# @summary Get all config variables for an application
# @name getAllByApplication
# @public
# @function
# @memberof balena.models.application.configVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - application config variables
# @returns {Promise}
#
# @example
# balena.models.application.configVar.getAllByApplication('MyApp').then(function(vars) {
# console.log(vars);
# });
#
# @example
# balena.models.application.configVar.getAllByApplication(999999).then(function(vars) {
# console.log(vars);
# });
#
# @example
# balena.models.application.configVar.getAllByApplication('MyApp', function(error, vars) {
# if (error) throw error;
# console.log(vars)
# });
###
getAllByApplication: configVarModel.getAllByParent
###*
# @summary Get the value of a specific config variable
# @name get
# @public
# @function
# @memberof balena.models.application.configVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - config variable name
# @fulfil {String|undefined} - the config variable value (or undefined)
# @returns {Promise}
#
# @example
# balena.models.application.configVar.get('MyApp', 'BALENA_VAR').then(function(value) {
# console.log(value);
# });
#
# @example
# balena.models.application.configVar.get(999999, 'BALENA_VAR').then(function(value) {
# console.log(value);
# });
#
# @example
# balena.models.application.configVar.get('MyApp', 'BALENA_VAR', function(error, value) {
# if (error) throw error;
# console.log(value)
# });
###
get: configVarModel.get
###*
# @summary Set the value of a specific config variable
# @name set
# @public
# @function
# @memberof balena.models.application.configVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - config variable name
# @param {String} value - config variable value
# @returns {Promise}
#
# @example
# balena.models.application.configVar.set('MyApp', 'BALENA_VAR', 'newvalue').then(function() {
# ...
# });
#
# @example
# balena.models.application.configVar.set(999999, 'BALENA_VAR', 'newvalue').then(function() {
# ...
# });
#
# @example
# balena.models.application.configVar.set('MyApp', 'BALENA_VAR', 'newvalue', function(error) {
# if (error) throw error;
# ...
# });
###
set: configVarModel.set
###*
# @summary Clear the value of a specific config variable
# @name remove
# @public
# @function
# @memberof balena.models.application.configVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - config variable name
# @returns {Promise}
#
# @example
# balena.models.application.configVar.remove('MyApp', 'BALENA_VAR').then(function() {
# ...
# });
#
# @example
# balena.models.application.configVar.remove(999999, 'BALENA_VAR').then(function() {
# ...
# });
#
# @example
# balena.models.application.configVar.remove('MyApp', 'BALENA_VAR', function(error) {
# if (error) throw error;
# ...
# });
###
remove: configVarModel.remove
}
###*
# @namespace balena.models.application.envVar
# @memberof balena.models.application
###
exports.envVar = {
###*
# @summary Get all environment variables for an application
# @name getAllByApplication
# @public
# @function
# @memberof balena.models.application.envVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {Object} [options={}] - extra pine options to use
# @fulfil {Object[]} - application environment variables
# @returns {Promise}
#
# @example
# balena.models.application.envVar.getAllByApplication('MyApp').then(function(vars) {
# console.log(vars);
# });
#
# @example
# balena.models.application.envVar.getAllByApplication(999999).then(function(vars) {
# console.log(vars);
# });
#
# @example
# balena.models.application.envVar.getAllByApplication('MyApp', function(error, vars) {
# if (error) throw error;
# console.log(vars)
# });
###
getAllByApplication: envVarModel.getAllByParent
###*
# @summary Get the value of a specific environment variable
# @name get
# @public
# @function
# @memberof balena.models.application.envVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - environment variable name
# @fulfil {String|undefined} - the environment variable value (or undefined)
# @returns {Promise}
#
# @example
# balena.models.application.envVar.get('MyApp', 'VAR').then(function(value) {
# console.log(value);
# });
#
# @example
# balena.models.application.envVar.get(999999, 'VAR').then(function(value) {
# console.log(value);
# });
#
# @example
# balena.models.application.envVar.get('MyApp', 'VAR', function(error, value) {
# if (error) throw error;
# console.log(value)
# });
###
get: envVarModel.get
###*
# @summary Set the value of a specific environment variable
# @name set
# @public
# @function
# @memberof balena.models.application.envVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - environment variable name
# @param {String} value - environment variable value
# @returns {Promise}
#
# @example
# balena.models.application.envVar.set('MyApp', 'VAR', 'newvalue').then(function() {
# ...
# });
#
# @example
# balena.models.application.envVar.set(999999, 'VAR', 'newvalue').then(function() {
# ...
# });
#
# @example
# balena.models.application.envVar.set('MyApp', 'VAR', 'newvalue', function(error) {
# if (error) throw error;
# ...
# });
###
set: envVarModel.set
###*
# @summary Clear the value of a specific environment variable
# @name remove
# @public
# @function
# @memberof balena.models.application.envVar
#
# @param {String|Number} nameOrSlugOrId - application name (string), slug (string) or id (number)
# @param {String} key - environment variable name
# @returns {Promise}
#
# @example
# balena.models.application.envVar.remove('MyApp', 'VAR').then(function() {
# ...
# });
#
# @example
# balena.models.application.envVar.remove(999999, 'VAR').then(function() {
# ...
# });
#
# @example
# balena.models.application.envVar.remove('MyApp', 'VAR', function(error) {
# if (error) throw error;
# ...
# });
###
remove: envVarModel.remove
}
return exports
module.exports =
default: getApplicationModel
|
[
{
"context": "*************************\n#\n# Application\n# -> HUB GIZ\n#\n# *************************************\n\n",
"end": 66,
"score": 0.7964599132537842,
"start": 65,
"tag": "NAME",
"value": "H"
}
] | app/assets/javascripts/admin.js.coffee | qsitconsultoria/hub | 0 | # *************************************
#
# Application
# -> HUB GIZ
#
# *************************************
# -------------------------------------
# vendor
# -------------------------------------
#= require medium-editor
#= require pickadate/lib/picker
#= require pickadate/lib/picker.date
#= require pickadate/lib/translations/pt_BR
#= require jqueryui/ui/core
#= require jqueryui/ui/widget
#= require jqueryui/ui/mouse
#= require jqueryui/ui/sortable
#= require refile
#= require select2/select2
#= require select2/select2_locale_pt-BR
# -------------------------------------
# components
# -------------------------------------
#= require components/select_navigation
#= require components/editor
#= require components/behavior
#= require components/date_time_picker
#= require components/video_input
#= require components/_slug
#= require components/sortable
#= require components/_color_check_bg
#= require components/_slidebar_options
#= require components/file_uploader
# -------------------------------------
# custom files
# -------------------------------------
#= require admin/new_manager_form
# -------------------------------------
# Components Setup
# -------------------------------------
$ ->
# $('[data-component="SelectNavigation"]').each (index, element) ->
# new SelectNavigation($(element))
# $('[data-component="Editor"]').each (index, element) ->
# new Editor($(element))
# $('[data-component="DateTimePicker"]').each (index, element) ->
# new DateTimePicker($(element))
$('[data-sortable-container="item"]').on 'sortable:update', (event, index) ->
index = '0' + index if index < 9
$(event.target).find('.panel-title').text(index)
# -------------------------------------
# Inbox
# -------------------------------------
$ ->
$.behavior('autosize').autosize()
# Fastclick
FastClick.attach document.body
$ ->
$(".js-multiple-select").removeClass('form__input')
$(".js-multiple-select").select2()
$("#s2id_autogen1").attr('placeholder', 'Adicione um Tema...')
$('#s2id_autogen2').attr('placeholder', 'Adicione um Curso...')
| 189516 | # *************************************
#
# Application
# -> <NAME>UB GIZ
#
# *************************************
# -------------------------------------
# vendor
# -------------------------------------
#= require medium-editor
#= require pickadate/lib/picker
#= require pickadate/lib/picker.date
#= require pickadate/lib/translations/pt_BR
#= require jqueryui/ui/core
#= require jqueryui/ui/widget
#= require jqueryui/ui/mouse
#= require jqueryui/ui/sortable
#= require refile
#= require select2/select2
#= require select2/select2_locale_pt-BR
# -------------------------------------
# components
# -------------------------------------
#= require components/select_navigation
#= require components/editor
#= require components/behavior
#= require components/date_time_picker
#= require components/video_input
#= require components/_slug
#= require components/sortable
#= require components/_color_check_bg
#= require components/_slidebar_options
#= require components/file_uploader
# -------------------------------------
# custom files
# -------------------------------------
#= require admin/new_manager_form
# -------------------------------------
# Components Setup
# -------------------------------------
$ ->
# $('[data-component="SelectNavigation"]').each (index, element) ->
# new SelectNavigation($(element))
# $('[data-component="Editor"]').each (index, element) ->
# new Editor($(element))
# $('[data-component="DateTimePicker"]').each (index, element) ->
# new DateTimePicker($(element))
$('[data-sortable-container="item"]').on 'sortable:update', (event, index) ->
index = '0' + index if index < 9
$(event.target).find('.panel-title').text(index)
# -------------------------------------
# Inbox
# -------------------------------------
$ ->
$.behavior('autosize').autosize()
# Fastclick
FastClick.attach document.body
$ ->
$(".js-multiple-select").removeClass('form__input')
$(".js-multiple-select").select2()
$("#s2id_autogen1").attr('placeholder', 'Adicione um Tema...')
$('#s2id_autogen2').attr('placeholder', 'Adicione um Curso...')
| true | # *************************************
#
# Application
# -> PI:NAME:<NAME>END_PIUB GIZ
#
# *************************************
# -------------------------------------
# vendor
# -------------------------------------
#= require medium-editor
#= require pickadate/lib/picker
#= require pickadate/lib/picker.date
#= require pickadate/lib/translations/pt_BR
#= require jqueryui/ui/core
#= require jqueryui/ui/widget
#= require jqueryui/ui/mouse
#= require jqueryui/ui/sortable
#= require refile
#= require select2/select2
#= require select2/select2_locale_pt-BR
# -------------------------------------
# components
# -------------------------------------
#= require components/select_navigation
#= require components/editor
#= require components/behavior
#= require components/date_time_picker
#= require components/video_input
#= require components/_slug
#= require components/sortable
#= require components/_color_check_bg
#= require components/_slidebar_options
#= require components/file_uploader
# -------------------------------------
# custom files
# -------------------------------------
#= require admin/new_manager_form
# -------------------------------------
# Components Setup
# -------------------------------------
$ ->
# $('[data-component="SelectNavigation"]').each (index, element) ->
# new SelectNavigation($(element))
# $('[data-component="Editor"]').each (index, element) ->
# new Editor($(element))
# $('[data-component="DateTimePicker"]').each (index, element) ->
# new DateTimePicker($(element))
$('[data-sortable-container="item"]').on 'sortable:update', (event, index) ->
index = '0' + index if index < 9
$(event.target).find('.panel-title').text(index)
# -------------------------------------
# Inbox
# -------------------------------------
$ ->
$.behavior('autosize').autosize()
# Fastclick
FastClick.attach document.body
$ ->
$(".js-multiple-select").removeClass('form__input')
$(".js-multiple-select").select2()
$("#s2id_autogen1").attr('placeholder', 'Adicione um Tema...')
$('#s2id_autogen2').attr('placeholder', 'Adicione um Curso...')
|
[
{
"context": "tions = state: 'st4t3'\n res = access_token: 't0k3n'\n error = {}\n\n before ->\n sinon.",
"end": 3606,
"score": 0.9954054951667786,
"start": 3601,
"tag": "PASSWORD",
"value": "t0k3n"
}
] | test/unit/strategies/OAuth2.coffee | 1242035/connect | 331 | # Test dependencies
nock = require 'nock'
chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
# Assertions
chai.use sinonChai
chai.should()
# Code under test
Strategy = require('passport-strategy')
OAuth2Strategy = require '../../../protocols/OAuth2'
describe 'OAuth2 Strategy', ->
{err, res, credentials} = {}
provider =
id: 'id'
name: 'Name'
protocol: 'OAuth 2.0'
url: 'https://domain.tld'
redirect_uri: 'https://local.tld/callback'
scope: ['a', 'b']
separator: ' '
endpoints:
authorize:
url: 'https://domain.tld/authorize'
method: 'POST'
token:
url: 'https://domain.tld/token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://domain.tld/userinfo'
method: 'GET'
auth: 'bearer_token'
mapping:
name: 'name'
config =
client_id: 'id',
client_secret: 'secret'
scope: ['c']
verify = (req, res, profile) ->
strategy = new OAuth2Strategy provider, config, verify
describe 'instance', ->
it 'should inherit from Strategy', ->
expect(strategy).to.be.instanceof Strategy
describe 'constructor', ->
it 'should set provider', ->
strategy.provider.should.equal provider
it 'should set endpoints', ->
strategy.endpoints.should.equal provider.endpoints
it 'should set client', ->
strategy.client.should.equal config
it 'should set name', ->
strategy.name.should.equal provider.id
it 'should set verify', ->
strategy.verify.should.equal verify
describe 'authenticate', ->
describe 'with new authorization request', ->
req = query: { query: {} }
options = state: 'st4t3'
before ->
sinon.stub(strategy, 'authorizationRequest')
strategy.authenticate req, options
after ->
strategy.authorizationRequest.restore()
it 'should initialize the authorization flow', ->
strategy.authorizationRequest.should.have.been.calledWith req, options
describe 'with access denied response', ->
req = query: { error: 'access_denied', error_description: 'nope' }
options = state: 'st4t3'
before ->
strategy.fail = sinon.spy()
strategy.authenticate req, options
it 'should fail to authenticate', ->
strategy.fail.should.have.been.calledWith 'Access denied', 403
describe 'with authorization error response', ->
req = query: { error: 'invalid', error_description: 'Invalid' }
options = state: 'st4t3'
before ->
strategy.error = sinon.spy()
strategy.authenticate req, options
it 'should fail to authenticate', ->
strategy.error.should.have.been.calledWith sinon.match({
name: 'ProviderAuthError'
})
describe 'with authorization code grant error response', ->
req = query: { code: 'c0d3' }
options = state: 'st4t3'
error = {}
before ->
sinon.stub(strategy, 'authorizationCodeGrant').callsArgWith(1, error)
strategy.error = sinon.spy()
strategy.authenticate req, options
after ->
strategy.authorizationCodeGrant.restore()
it 'should fail to authenticate', ->
strategy.error.should.have.been.calledWith error
describe 'with userinfo error response', ->
req = query: { code: 'c0d3' }
options = state: 'st4t3'
res = access_token: 't0k3n'
error = {}
before ->
sinon.stub(strategy, 'authorizationCodeGrant').callsArgWith(1, null, res)
sinon.stub(strategy, 'userInfo').callsArgWith(1, {})
strategy.error = sinon.spy()
strategy.authenticate req, options
it 'should fail to authenticate', ->
strategy.error.should.have.been.calledWith error
describe 'with verification error', ->
describe 'with verify providing a null user', ->
describe 'with successful authorization', ->
describe 'base64credentials', ->
before ->
credentials = strategy.base64credentials()
it 'should include the client_id', ->
Buffer.from(credentials, 'base64')
.toString().should.contain config.client_id
it 'should include the client_secret', ->
Buffer.from(credentials, 'base64')
.toString().should.contain config.client_secret
it 'should include the separator', ->
Buffer.from(credentials, 'base64')
.toString().should.contain ':'
describe 'authorizationRequest', ->
describe 'with valid configuration', ->
req = query: { query: {} }
options = state: 'st4t3'
beforeEach ->
strategy.redirect = sinon.spy()
strategy.authorizationRequest(req, options)
it 'should redirect', ->
url = provider.endpoints.authorize.url
strategy.redirect.should.have.been.calledWith sinon.match(url)
it 'should include response_type', ->
strategy.redirect.should.have.been.calledWith sinon.match(
'response_type=code'
)
it 'should include client_id', ->
strategy.redirect.should.have.been.calledWith sinon.match(
'client_id=' + config.client_id
)
it 'should include redirect_uri', ->
strategy.redirect.should.have.been.calledWith sinon.match(
'redirect_uri=' + encodeURIComponent(provider.redirect_uri)
)
it 'should include scope', ->
strategy.redirect.should.have.been.calledWith sinon.match(
'scope=a%20b%20c'
)
it 'should include state', ->
strategy.redirect.should.have.been.calledWith sinon.match(
'state=' + options.state
)
| 145823 | # Test dependencies
nock = require 'nock'
chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
# Assertions
chai.use sinonChai
chai.should()
# Code under test
Strategy = require('passport-strategy')
OAuth2Strategy = require '../../../protocols/OAuth2'
describe 'OAuth2 Strategy', ->
{err, res, credentials} = {}
provider =
id: 'id'
name: 'Name'
protocol: 'OAuth 2.0'
url: 'https://domain.tld'
redirect_uri: 'https://local.tld/callback'
scope: ['a', 'b']
separator: ' '
endpoints:
authorize:
url: 'https://domain.tld/authorize'
method: 'POST'
token:
url: 'https://domain.tld/token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://domain.tld/userinfo'
method: 'GET'
auth: 'bearer_token'
mapping:
name: 'name'
config =
client_id: 'id',
client_secret: 'secret'
scope: ['c']
verify = (req, res, profile) ->
strategy = new OAuth2Strategy provider, config, verify
describe 'instance', ->
it 'should inherit from Strategy', ->
expect(strategy).to.be.instanceof Strategy
describe 'constructor', ->
it 'should set provider', ->
strategy.provider.should.equal provider
it 'should set endpoints', ->
strategy.endpoints.should.equal provider.endpoints
it 'should set client', ->
strategy.client.should.equal config
it 'should set name', ->
strategy.name.should.equal provider.id
it 'should set verify', ->
strategy.verify.should.equal verify
describe 'authenticate', ->
describe 'with new authorization request', ->
req = query: { query: {} }
options = state: 'st4t3'
before ->
sinon.stub(strategy, 'authorizationRequest')
strategy.authenticate req, options
after ->
strategy.authorizationRequest.restore()
it 'should initialize the authorization flow', ->
strategy.authorizationRequest.should.have.been.calledWith req, options
describe 'with access denied response', ->
req = query: { error: 'access_denied', error_description: 'nope' }
options = state: 'st4t3'
before ->
strategy.fail = sinon.spy()
strategy.authenticate req, options
it 'should fail to authenticate', ->
strategy.fail.should.have.been.calledWith 'Access denied', 403
describe 'with authorization error response', ->
req = query: { error: 'invalid', error_description: 'Invalid' }
options = state: 'st4t3'
before ->
strategy.error = sinon.spy()
strategy.authenticate req, options
it 'should fail to authenticate', ->
strategy.error.should.have.been.calledWith sinon.match({
name: 'ProviderAuthError'
})
describe 'with authorization code grant error response', ->
req = query: { code: 'c0d3' }
options = state: 'st4t3'
error = {}
before ->
sinon.stub(strategy, 'authorizationCodeGrant').callsArgWith(1, error)
strategy.error = sinon.spy()
strategy.authenticate req, options
after ->
strategy.authorizationCodeGrant.restore()
it 'should fail to authenticate', ->
strategy.error.should.have.been.calledWith error
describe 'with userinfo error response', ->
req = query: { code: 'c0d3' }
options = state: 'st4t3'
res = access_token: '<PASSWORD>'
error = {}
before ->
sinon.stub(strategy, 'authorizationCodeGrant').callsArgWith(1, null, res)
sinon.stub(strategy, 'userInfo').callsArgWith(1, {})
strategy.error = sinon.spy()
strategy.authenticate req, options
it 'should fail to authenticate', ->
strategy.error.should.have.been.calledWith error
describe 'with verification error', ->
describe 'with verify providing a null user', ->
describe 'with successful authorization', ->
describe 'base64credentials', ->
before ->
credentials = strategy.base64credentials()
it 'should include the client_id', ->
Buffer.from(credentials, 'base64')
.toString().should.contain config.client_id
it 'should include the client_secret', ->
Buffer.from(credentials, 'base64')
.toString().should.contain config.client_secret
it 'should include the separator', ->
Buffer.from(credentials, 'base64')
.toString().should.contain ':'
describe 'authorizationRequest', ->
describe 'with valid configuration', ->
req = query: { query: {} }
options = state: 'st4t3'
beforeEach ->
strategy.redirect = sinon.spy()
strategy.authorizationRequest(req, options)
it 'should redirect', ->
url = provider.endpoints.authorize.url
strategy.redirect.should.have.been.calledWith sinon.match(url)
it 'should include response_type', ->
strategy.redirect.should.have.been.calledWith sinon.match(
'response_type=code'
)
it 'should include client_id', ->
strategy.redirect.should.have.been.calledWith sinon.match(
'client_id=' + config.client_id
)
it 'should include redirect_uri', ->
strategy.redirect.should.have.been.calledWith sinon.match(
'redirect_uri=' + encodeURIComponent(provider.redirect_uri)
)
it 'should include scope', ->
strategy.redirect.should.have.been.calledWith sinon.match(
'scope=a%20b%20c'
)
it 'should include state', ->
strategy.redirect.should.have.been.calledWith sinon.match(
'state=' + options.state
)
| true | # Test dependencies
nock = require 'nock'
chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
# Assertions
chai.use sinonChai
chai.should()
# Code under test
Strategy = require('passport-strategy')
OAuth2Strategy = require '../../../protocols/OAuth2'
describe 'OAuth2 Strategy', ->
{err, res, credentials} = {}
provider =
id: 'id'
name: 'Name'
protocol: 'OAuth 2.0'
url: 'https://domain.tld'
redirect_uri: 'https://local.tld/callback'
scope: ['a', 'b']
separator: ' '
endpoints:
authorize:
url: 'https://domain.tld/authorize'
method: 'POST'
token:
url: 'https://domain.tld/token'
method: 'POST'
auth: 'client_secret_basic'
user:
url: 'https://domain.tld/userinfo'
method: 'GET'
auth: 'bearer_token'
mapping:
name: 'name'
config =
client_id: 'id',
client_secret: 'secret'
scope: ['c']
verify = (req, res, profile) ->
strategy = new OAuth2Strategy provider, config, verify
describe 'instance', ->
it 'should inherit from Strategy', ->
expect(strategy).to.be.instanceof Strategy
describe 'constructor', ->
it 'should set provider', ->
strategy.provider.should.equal provider
it 'should set endpoints', ->
strategy.endpoints.should.equal provider.endpoints
it 'should set client', ->
strategy.client.should.equal config
it 'should set name', ->
strategy.name.should.equal provider.id
it 'should set verify', ->
strategy.verify.should.equal verify
describe 'authenticate', ->
describe 'with new authorization request', ->
req = query: { query: {} }
options = state: 'st4t3'
before ->
sinon.stub(strategy, 'authorizationRequest')
strategy.authenticate req, options
after ->
strategy.authorizationRequest.restore()
it 'should initialize the authorization flow', ->
strategy.authorizationRequest.should.have.been.calledWith req, options
describe 'with access denied response', ->
req = query: { error: 'access_denied', error_description: 'nope' }
options = state: 'st4t3'
before ->
strategy.fail = sinon.spy()
strategy.authenticate req, options
it 'should fail to authenticate', ->
strategy.fail.should.have.been.calledWith 'Access denied', 403
describe 'with authorization error response', ->
req = query: { error: 'invalid', error_description: 'Invalid' }
options = state: 'st4t3'
before ->
strategy.error = sinon.spy()
strategy.authenticate req, options
it 'should fail to authenticate', ->
strategy.error.should.have.been.calledWith sinon.match({
name: 'ProviderAuthError'
})
describe 'with authorization code grant error response', ->
req = query: { code: 'c0d3' }
options = state: 'st4t3'
error = {}
before ->
sinon.stub(strategy, 'authorizationCodeGrant').callsArgWith(1, error)
strategy.error = sinon.spy()
strategy.authenticate req, options
after ->
strategy.authorizationCodeGrant.restore()
it 'should fail to authenticate', ->
strategy.error.should.have.been.calledWith error
describe 'with userinfo error response', ->
req = query: { code: 'c0d3' }
options = state: 'st4t3'
res = access_token: 'PI:PASSWORD:<PASSWORD>END_PI'
error = {}
before ->
sinon.stub(strategy, 'authorizationCodeGrant').callsArgWith(1, null, res)
sinon.stub(strategy, 'userInfo').callsArgWith(1, {})
strategy.error = sinon.spy()
strategy.authenticate req, options
it 'should fail to authenticate', ->
strategy.error.should.have.been.calledWith error
describe 'with verification error', ->
describe 'with verify providing a null user', ->
describe 'with successful authorization', ->
describe 'base64credentials', ->
before ->
credentials = strategy.base64credentials()
it 'should include the client_id', ->
Buffer.from(credentials, 'base64')
.toString().should.contain config.client_id
it 'should include the client_secret', ->
Buffer.from(credentials, 'base64')
.toString().should.contain config.client_secret
it 'should include the separator', ->
Buffer.from(credentials, 'base64')
.toString().should.contain ':'
describe 'authorizationRequest', ->
describe 'with valid configuration', ->
req = query: { query: {} }
options = state: 'st4t3'
beforeEach ->
strategy.redirect = sinon.spy()
strategy.authorizationRequest(req, options)
it 'should redirect', ->
url = provider.endpoints.authorize.url
strategy.redirect.should.have.been.calledWith sinon.match(url)
it 'should include response_type', ->
strategy.redirect.should.have.been.calledWith sinon.match(
'response_type=code'
)
it 'should include client_id', ->
strategy.redirect.should.have.been.calledWith sinon.match(
'client_id=' + config.client_id
)
it 'should include redirect_uri', ->
strategy.redirect.should.have.been.calledWith sinon.match(
'redirect_uri=' + encodeURIComponent(provider.redirect_uri)
)
it 'should include scope', ->
strategy.redirect.should.have.been.calledWith sinon.match(
'scope=a%20b%20c'
)
it 'should include state', ->
strategy.redirect.should.have.been.calledWith sinon.match(
'state=' + options.state
)
|
[
{
"context": "-m '[bot] build and deploy'\"\nrun \"git push --force git@heroku.com:#{HEROKU_APP}.git HEAD:master\"\n",
"end": 528,
"score": 0.9997607469558716,
"start": 514,
"tag": "EMAIL",
"value": "git@heroku.com"
}
] | bin/deploy.coffee | canopyui/canopy | 1 | #!/usr/bin/env coffee
require 'shelljs/global'
HEROKU_APP = process.env.HEROKU_APP ? throw new Error("Please set environment variable HEROKU_APP")
run = (cmd, options = {}) ->
continue_on_failure = options.continue_on_failure ? false
echo "==> #{cmd}"
code = (exec cmd).code
if code isnt 0
echo 'COMMAND FAILED'
exit(code) unless continue_on_failure
code
run "npm run build"
run "git add --force --no-ignore-removal public/"
run "git commit -m '[bot] build and deploy'"
run "git push --force git@heroku.com:#{HEROKU_APP}.git HEAD:master"
| 100579 | #!/usr/bin/env coffee
require 'shelljs/global'
HEROKU_APP = process.env.HEROKU_APP ? throw new Error("Please set environment variable HEROKU_APP")
run = (cmd, options = {}) ->
continue_on_failure = options.continue_on_failure ? false
echo "==> #{cmd}"
code = (exec cmd).code
if code isnt 0
echo 'COMMAND FAILED'
exit(code) unless continue_on_failure
code
run "npm run build"
run "git add --force --no-ignore-removal public/"
run "git commit -m '[bot] build and deploy'"
run "git push --force <EMAIL>:#{HEROKU_APP}.git HEAD:master"
| true | #!/usr/bin/env coffee
require 'shelljs/global'
HEROKU_APP = process.env.HEROKU_APP ? throw new Error("Please set environment variable HEROKU_APP")
run = (cmd, options = {}) ->
continue_on_failure = options.continue_on_failure ? false
echo "==> #{cmd}"
code = (exec cmd).code
if code isnt 0
echo 'COMMAND FAILED'
exit(code) unless continue_on_failure
code
run "npm run build"
run "git add --force --no-ignore-removal public/"
run "git commit -m '[bot] build and deploy'"
run "git push --force PI:EMAIL:<EMAIL>END_PI:#{HEROKU_APP}.git HEAD:master"
|
[
{
"context": "\n }],\n \"cat2\": [{\n \"title\": \"test2\",\n \"active\": true,\n \"dataToggl",
"end": 1046,
"score": 0.5440605282783508,
"start": 1042,
"tag": "NAME",
"value": "test"
}
] | spec/sidebar-spec.coffee | Cantik-Music-Player/sidebar | 0 | Sidebar = require '../lib/sidebar'
sinon = require 'sinon'
assert = require 'assert'
describe "Sidebar", ->
beforeEach ->
Sidebar.prototype.show = sinon.spy()
@sidebar = new Sidebar('pluginManager', 'element')
@sidebar.activate = ->
it "Initialized", ->
assert.deepEqual(@sidebar.links, {})
it "Add link", ->
@sidebar.addLink('test1', 'cat1', 'func4', true)
@sidebar.addLink('test2', 'cat2', 'func3', true)
@sidebar.addLink('test3', 'cat1', 'func2', false)
@sidebar.addLink('test4', 'cat2', 'func1', false, false)
delete @sidebar.links['cat1'][0]['onClick']
delete @sidebar.links['cat1'][1]['onClick']
delete @sidebar.links['cat2'][0]['onClick']
delete @sidebar.links['cat2'][1]['onClick']
assert.deepEqual(@sidebar.links, {
"cat1": [{
"title": "test1",
"active": true,
"dataToggle": true
},
{
"title": "test3",
"active": false,
"dataToggle": true
}],
"cat2": [{
"title": "test2",
"active": true,
"dataToggle": true
},
{
"title": "test4",
"active": false,
"dataToggle": false
}],
})
| 2117 | Sidebar = require '../lib/sidebar'
sinon = require 'sinon'
assert = require 'assert'
describe "Sidebar", ->
beforeEach ->
Sidebar.prototype.show = sinon.spy()
@sidebar = new Sidebar('pluginManager', 'element')
@sidebar.activate = ->
it "Initialized", ->
assert.deepEqual(@sidebar.links, {})
it "Add link", ->
@sidebar.addLink('test1', 'cat1', 'func4', true)
@sidebar.addLink('test2', 'cat2', 'func3', true)
@sidebar.addLink('test3', 'cat1', 'func2', false)
@sidebar.addLink('test4', 'cat2', 'func1', false, false)
delete @sidebar.links['cat1'][0]['onClick']
delete @sidebar.links['cat1'][1]['onClick']
delete @sidebar.links['cat2'][0]['onClick']
delete @sidebar.links['cat2'][1]['onClick']
assert.deepEqual(@sidebar.links, {
"cat1": [{
"title": "test1",
"active": true,
"dataToggle": true
},
{
"title": "test3",
"active": false,
"dataToggle": true
}],
"cat2": [{
"title": "<NAME>2",
"active": true,
"dataToggle": true
},
{
"title": "test4",
"active": false,
"dataToggle": false
}],
})
| true | Sidebar = require '../lib/sidebar'
sinon = require 'sinon'
assert = require 'assert'
describe "Sidebar", ->
beforeEach ->
Sidebar.prototype.show = sinon.spy()
@sidebar = new Sidebar('pluginManager', 'element')
@sidebar.activate = ->
it "Initialized", ->
assert.deepEqual(@sidebar.links, {})
it "Add link", ->
@sidebar.addLink('test1', 'cat1', 'func4', true)
@sidebar.addLink('test2', 'cat2', 'func3', true)
@sidebar.addLink('test3', 'cat1', 'func2', false)
@sidebar.addLink('test4', 'cat2', 'func1', false, false)
delete @sidebar.links['cat1'][0]['onClick']
delete @sidebar.links['cat1'][1]['onClick']
delete @sidebar.links['cat2'][0]['onClick']
delete @sidebar.links['cat2'][1]['onClick']
assert.deepEqual(@sidebar.links, {
"cat1": [{
"title": "test1",
"active": true,
"dataToggle": true
},
{
"title": "test3",
"active": false,
"dataToggle": true
}],
"cat2": [{
"title": "PI:NAME:<NAME>END_PI2",
"active": true,
"dataToggle": true
},
{
"title": "test4",
"active": false,
"dataToggle": false
}],
})
|
[
{
"context": "ions = toImmutable [\n generateDummyAccount 1, 'nick', '', ''\n generateDummyAccount 2, 'john', 'Joh",
"end": 425,
"score": 0.927107572555542,
"start": 421,
"tag": "USERNAME",
"value": "nick"
},
{
"context": "nt 1, 'nick', '', ''\n generateDummyAccount 2, 'john... | client/activity/lib/components/chatinputwidget/test/mentiondropbox.coffee | ezgikaysi/koding | 1 | kd = require 'kd'
React = require 'kd-react'
expect = require 'expect'
toImmutable = require 'app/util/toImmutable'
MentionDropbox = require '../mentiondropbox'
helpers = require './helpers'
generateDummyAccount = require 'app/util/generateDummyAccount'
describe 'MentionDropbox', ->
userMentions = toImmutable [
generateDummyAccount 1, 'nick', '', ''
generateDummyAccount 2, 'john', 'John', 'Johnson'
]
channelMentions = toImmutable [
{
names : [ 'channel', 'all', 'team', 'group' ]
description : 'notify everyone in the channel'
}
{
names : [ 'admins' ]
}
]
afterEach -> helpers.clearDropboxes()
describe '::render', ->
it 'renders invisible dropbox if user and channel items are empty', ->
dropbox = helpers.renderDropbox {}, MentionDropbox
expect(dropbox.props.visible).toBe no
it 'renders dropbox with user and channel items in one list', ->
props = { userMentions, channelMentions }
dropbox = helpers.renderDropbox props, MentionDropbox
content = dropbox.getContentElement()
userItems = content.querySelectorAll '.UserMentionItem'
expect(userItems.length).toEqual props.userMentions.size
channelItems = content.querySelectorAll '.ChannelMentionItem'
expect(channelItems.length).toEqual props.channelMentions.size
it 'renders user items correctly', ->
props = { userMentions }
dropbox = helpers.renderDropbox props, MentionDropbox
content = dropbox.getContentElement()
userItems = content.querySelectorAll '.UserMentionItem'
expect(userItems.length).toEqual props.userMentions.size
for item, i in userItems
dataItem = props.userMentions.get i
avatar = item.querySelector 'img'
expect(avatar).toExist()
nickname = item.querySelector '.UserMentionItem-nickname'
expect(nickname).toExist()
expect(nickname.textContent).toEqual dataItem.getIn [ 'profile', 'nickname' ]
fullName = item.querySelector '.UserMentionItem-fullName'
firstName = dataItem.getIn [ 'profile', 'firstName' ]
lastName = dataItem.getIn [ 'profile', 'lastName' ]
if firstName and lastName
expect(fullName).toExist()
expect(fullName.textContent).toEqual "#{firstName} #{lastName}"
else
expect(fullName).toNotExist()
it 'renders channel items correctly', ->
props = { channelMentions }
dropbox = helpers.renderDropbox props, MentionDropbox
content = dropbox.getContentElement()
channelItems = content.querySelectorAll '.ChannelMentionItem'
expect(channelItems.length).toEqual props.channelMentions.size
for item, i in channelItems
dataItem = props.channelMentions.get i
names = dataItem.get('names').toJS()
mentionList = item.querySelector '.ChannelMentionItem-mentionList'
expect(mentionList).toExist()
for name in names
expect(mentionList.textContent).toInclude "@#{name}"
description = item.querySelector '.ChannelMentionItem-description'
text = dataItem.get 'description'
if text
expect(description).toExist()
expect(description.textContent).toInclude text
else
expect(description).toNotExist()
it 'renders dropbox with selected item', ->
props = { userMentions, channelMentions, selectedIndex : 1 }
helpers.dropboxSelectedItemTest props, MentionDropbox
describe '::onItemSelected', ->
it 'should be called when dropbox item is hovered', ->
props = { userMentions, channelMentions, selectedIndex : 1 }
helpers.dropboxSelectedItemCallbackTest props, MentionDropbox
describe '::onItemConfirmed', ->
it 'should be called when dropbox item is clicked', ->
props = { userMentions, channelMentions, selectedIndex : 2 }
helpers.dropboxConfirmedItemCallbackTest props, MentionDropbox
| 28868 | kd = require 'kd'
React = require 'kd-react'
expect = require 'expect'
toImmutable = require 'app/util/toImmutable'
MentionDropbox = require '../mentiondropbox'
helpers = require './helpers'
generateDummyAccount = require 'app/util/generateDummyAccount'
describe 'MentionDropbox', ->
userMentions = toImmutable [
generateDummyAccount 1, 'nick', '', ''
generateDummyAccount 2, 'john', '<NAME>', '<NAME>'
]
channelMentions = toImmutable [
{
names : [ 'channel', 'all', 'team', 'group' ]
description : 'notify everyone in the channel'
}
{
names : [ 'admins' ]
}
]
afterEach -> helpers.clearDropboxes()
describe '::render', ->
it 'renders invisible dropbox if user and channel items are empty', ->
dropbox = helpers.renderDropbox {}, MentionDropbox
expect(dropbox.props.visible).toBe no
it 'renders dropbox with user and channel items in one list', ->
props = { userMentions, channelMentions }
dropbox = helpers.renderDropbox props, MentionDropbox
content = dropbox.getContentElement()
userItems = content.querySelectorAll '.UserMentionItem'
expect(userItems.length).toEqual props.userMentions.size
channelItems = content.querySelectorAll '.ChannelMentionItem'
expect(channelItems.length).toEqual props.channelMentions.size
it 'renders user items correctly', ->
props = { userMentions }
dropbox = helpers.renderDropbox props, MentionDropbox
content = dropbox.getContentElement()
userItems = content.querySelectorAll '.UserMentionItem'
expect(userItems.length).toEqual props.userMentions.size
for item, i in userItems
dataItem = props.userMentions.get i
avatar = item.querySelector 'img'
expect(avatar).toExist()
nickname = item.querySelector '.UserMentionItem-nickname'
expect(nickname).toExist()
expect(nickname.textContent).toEqual dataItem.getIn [ 'profile', 'nickname' ]
fullName = item.querySelector '.UserMentionItem-fullName'
firstName = dataItem.getIn [ 'profile', 'firstName' ]
lastName = dataItem.getIn [ 'profile', 'lastName' ]
if firstName and lastName
expect(fullName).toExist()
expect(fullName.textContent).toEqual "#{firstName} #{lastName}"
else
expect(fullName).toNotExist()
it 'renders channel items correctly', ->
props = { channelMentions }
dropbox = helpers.renderDropbox props, MentionDropbox
content = dropbox.getContentElement()
channelItems = content.querySelectorAll '.ChannelMentionItem'
expect(channelItems.length).toEqual props.channelMentions.size
for item, i in channelItems
dataItem = props.channelMentions.get i
names = dataItem.get('names').toJS()
mentionList = item.querySelector '.ChannelMentionItem-mentionList'
expect(mentionList).toExist()
for name in names
expect(mentionList.textContent).toInclude "@#{name}"
description = item.querySelector '.ChannelMentionItem-description'
text = dataItem.get 'description'
if text
expect(description).toExist()
expect(description.textContent).toInclude text
else
expect(description).toNotExist()
it 'renders dropbox with selected item', ->
props = { userMentions, channelMentions, selectedIndex : 1 }
helpers.dropboxSelectedItemTest props, MentionDropbox
describe '::onItemSelected', ->
it 'should be called when dropbox item is hovered', ->
props = { userMentions, channelMentions, selectedIndex : 1 }
helpers.dropboxSelectedItemCallbackTest props, MentionDropbox
describe '::onItemConfirmed', ->
it 'should be called when dropbox item is clicked', ->
props = { userMentions, channelMentions, selectedIndex : 2 }
helpers.dropboxConfirmedItemCallbackTest props, MentionDropbox
| true | kd = require 'kd'
React = require 'kd-react'
expect = require 'expect'
toImmutable = require 'app/util/toImmutable'
MentionDropbox = require '../mentiondropbox'
helpers = require './helpers'
generateDummyAccount = require 'app/util/generateDummyAccount'
describe 'MentionDropbox', ->
userMentions = toImmutable [
generateDummyAccount 1, 'nick', '', ''
generateDummyAccount 2, 'john', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'
]
channelMentions = toImmutable [
{
names : [ 'channel', 'all', 'team', 'group' ]
description : 'notify everyone in the channel'
}
{
names : [ 'admins' ]
}
]
afterEach -> helpers.clearDropboxes()
describe '::render', ->
it 'renders invisible dropbox if user and channel items are empty', ->
dropbox = helpers.renderDropbox {}, MentionDropbox
expect(dropbox.props.visible).toBe no
it 'renders dropbox with user and channel items in one list', ->
props = { userMentions, channelMentions }
dropbox = helpers.renderDropbox props, MentionDropbox
content = dropbox.getContentElement()
userItems = content.querySelectorAll '.UserMentionItem'
expect(userItems.length).toEqual props.userMentions.size
channelItems = content.querySelectorAll '.ChannelMentionItem'
expect(channelItems.length).toEqual props.channelMentions.size
it 'renders user items correctly', ->
props = { userMentions }
dropbox = helpers.renderDropbox props, MentionDropbox
content = dropbox.getContentElement()
userItems = content.querySelectorAll '.UserMentionItem'
expect(userItems.length).toEqual props.userMentions.size
for item, i in userItems
dataItem = props.userMentions.get i
avatar = item.querySelector 'img'
expect(avatar).toExist()
nickname = item.querySelector '.UserMentionItem-nickname'
expect(nickname).toExist()
expect(nickname.textContent).toEqual dataItem.getIn [ 'profile', 'nickname' ]
fullName = item.querySelector '.UserMentionItem-fullName'
firstName = dataItem.getIn [ 'profile', 'firstName' ]
lastName = dataItem.getIn [ 'profile', 'lastName' ]
if firstName and lastName
expect(fullName).toExist()
expect(fullName.textContent).toEqual "#{firstName} #{lastName}"
else
expect(fullName).toNotExist()
it 'renders channel items correctly', ->
props = { channelMentions }
dropbox = helpers.renderDropbox props, MentionDropbox
content = dropbox.getContentElement()
channelItems = content.querySelectorAll '.ChannelMentionItem'
expect(channelItems.length).toEqual props.channelMentions.size
for item, i in channelItems
dataItem = props.channelMentions.get i
names = dataItem.get('names').toJS()
mentionList = item.querySelector '.ChannelMentionItem-mentionList'
expect(mentionList).toExist()
for name in names
expect(mentionList.textContent).toInclude "@#{name}"
description = item.querySelector '.ChannelMentionItem-description'
text = dataItem.get 'description'
if text
expect(description).toExist()
expect(description.textContent).toInclude text
else
expect(description).toNotExist()
it 'renders dropbox with selected item', ->
props = { userMentions, channelMentions, selectedIndex : 1 }
helpers.dropboxSelectedItemTest props, MentionDropbox
describe '::onItemSelected', ->
it 'should be called when dropbox item is hovered', ->
props = { userMentions, channelMentions, selectedIndex : 1 }
helpers.dropboxSelectedItemCallbackTest props, MentionDropbox
describe '::onItemConfirmed', ->
it 'should be called when dropbox item is clicked', ->
props = { userMentions, channelMentions, selectedIndex : 2 }
helpers.dropboxConfirmedItemCallbackTest props, MentionDropbox
|
[
{
"context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @",
"end": 33,
"score": 0.9998882412910461,
"start": 17,
"tag": "NAME",
"value": "Abdelhakim RAFIK"
},
{
"context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhaki... | src/app/models/_associations.coffee | AbdelhakimRafik/Project | 1 | ###
* @author Abdelhakim RAFIK
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 Abdelhakim RAFIK
* @date June 2021
###
###
Tables associations definition
###
module.exports = (Models) ->
# User - Articles assocations
Models.User.hasMany Models.Article
Models.Article.belongsTo Models.User
# Article - Comment
Models.Article.hasMany Models.Comment
Models.Comment.belongsTo Models.Article
# User - Comment
Models.User.hasMany Models.Comment
Models.Comment.belongsTo Models.User
# Article - Tag
Models.Article.belongsToMany Models.Tag, through: 'article-targs'
Models.Tag.belongsToMany Models.Article, through: 'article-tags' | 40512 | ###
* @author <NAME>
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 <NAME>
* @date June 2021
###
###
Tables associations definition
###
module.exports = (Models) ->
# User - Articles assocations
Models.User.hasMany Models.Article
Models.Article.belongsTo Models.User
# Article - Comment
Models.Article.hasMany Models.Comment
Models.Comment.belongsTo Models.Article
# User - Comment
Models.User.hasMany Models.Comment
Models.Comment.belongsTo Models.User
# Article - Tag
Models.Article.belongsToMany Models.Tag, through: 'article-targs'
Models.Tag.belongsToMany Models.Article, through: 'article-tags' | true | ###
* @author PI:NAME:<NAME>END_PI
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 PI:NAME:<NAME>END_PI
* @date June 2021
###
###
Tables associations definition
###
module.exports = (Models) ->
# User - Articles assocations
Models.User.hasMany Models.Article
Models.Article.belongsTo Models.User
# Article - Comment
Models.Article.hasMany Models.Comment
Models.Comment.belongsTo Models.Article
# User - Comment
Models.User.hasMany Models.Comment
Models.Comment.belongsTo Models.User
# Article - Tag
Models.Article.belongsToMany Models.Tag, through: 'article-targs'
Models.Tag.belongsToMany Models.Article, through: 'article-tags' |
[
{
"context": "_PAGE_SIZE\n 'reverse': false\n 'memberKey': 'member'\n 'rankKey': 'rank'\n 'scoreKey': 'score'\n ",
"end": 394,
"score": 0.9472173452377319,
"start": 388,
"tag": "KEY",
"value": "member"
},
{
"context": ": false\n 'memberKey': 'member'\n 'rankKey': '... | src/leaderboard.coffee | KeKs0r/leaderboard-coffeescript | 22 | redis = require 'redis'
class Leaderboard
###
# Default page size: 25
###
@DEFAULT_PAGE_SIZE = 25
###
# Default options when creating a leaderboard. Page size is 25 and reverse
# is set to false, meaning various methods will return results in
# highest-to-lowest order.
###
DEFAULT_OPTIONS =
'pageSize': @DEFAULT_PAGE_SIZE
'reverse': false
'memberKey': 'member'
'rankKey': 'rank'
'scoreKey': 'score'
'memberDataKey': 'member_data'
'memberDataNamespace': 'member_data'
###
# Default Redis host: localhost
###
@DEFAULT_REDIS_HOST = 'localhost'
###
# Default Redis post: 6379
###
@DEFAULT_REDIS_PORT = 6379
###
# Default Redis options when creating a connection to Redis. The
# +DEFAULT_REDIS_HOST+ and +DEFAULT_REDIS_PORT+ will be passed.
###
DEFAULT_REDIS_OPTIONS =
'host': @DEFAULT_REDIS_HOST
'port': @DEFAULT_REDIS_PORT
###
# Create a new instance of a leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param options [Hash] Options for the leaderboard such as +'pageSize'+.
# @param redisOptions [Hash] Options for configuring Redis.
###
constructor: (@leaderboardName, options = DEFAULT_OPTIONS, redisOptions = DEFAULT_REDIS_OPTIONS) ->
@reverse = options['reverse']
@pageSize = options['pageSize']
if @pageSize == null || @pageSize < 1
@pageSize = Leaderboard.DEFAULT_PAGE_SIZE
@memberKeyOption = options['memberKey'] || 'member'
@rankKeyOption = options['rankKey'] || 'rank'
@scoreKeyOption = options['scoreKey'] || 'score'
@memberDataKeyOption = options['memberDataKey'] || 'member_data'
@memberDataNamespace = options['memberDataNamespace'] || 'member_data'
@redisConnection = redisOptions['redis_connection']
if @redisConnection?
delete redisOptions['redis_connection']
@redisConnection = redis.createClient(redisOptions['port'], redisOptions['host']) unless @redisConnection?
###
# Disconnect the Redis connection.
###
disconnect: ->
@redisConnection.quit((err, reply) -> )
###
# Delete the current leaderboard.
#
# @param callback Optional callback for result of call.
###
deleteLeaderboard: (callback) ->
this.deleteLeaderboardNamed(@leaderboardName, callback)
###
# Delete the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param callback Optional callback for result of call.
###
deleteLeaderboardNamed: (leaderboardName, callback) ->
transaction = @redisConnection.multi()
transaction.del(leaderboardName)
transaction.del(this.memberDataKey(leaderboardName))
transaction.exec((err, reply) ->
callback(reply) if callback)
###
# Rank a member in the leaderboard.
#
# @param member [String] Member name.
# @param score [float] Member score.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
rankMember: (member, score, memberData = null, callback) ->
this.rankMemberIn(@leaderboardName, member, score, memberData, callback)
###
# Rank a member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param score [float] Member score.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
rankMemberIn: (leaderboardName, member, score, memberData = null, callback) ->
transaction = @redisConnection.multi()
transaction.zadd(leaderboardName, score, member)
transaction.hset(this.memberDataKey(leaderboardName), member, memberData) if memberData?
transaction.exec((err, reply) ->
callback(reply) if callback)
###
# Rank a member across multiple leaderboards.
#
# @param leaderboards [Array] Leaderboard names.
# @param member [String] Member name.
# @param score [float] Member score.
# @param member_data [String] Optional member data.
###
rankMemberAcross: (leaderboardNames, member, score, memberData = null, callback) ->
transaction = @redisConnection.multi()
for leaderboardName in leaderboardNames
transaction.zadd(leaderboardName, score, member)
transaction.hset(this.memberDataKey(leaderboardName), member, memberData) if memberData?
transaction.exec((err, reply) ->
callback(reply) if callback)
###
# Rank a member in the leaderboard based on execution of the +rankConditional+.
#
# The +rankConditional+ is passed the following parameters:
# member: Member name.
# currentScore: Current score for the member in the leaderboard.
# score: Member score.
# memberData: Optional member data.
# options: Leaderboard options, e.g. 'reverse': Value of reverse option
#
# @param rankConditional [Function] Function which must return +true+ or +false+ that controls whether or not the member is ranked in the leaderboard.
# @param member [String] Member name.
# @param score [float] Member score.
# @param currentScore [float] Current score.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
rankMemberIf: (rankConditional, member, score, currentScore, memberData = null, callback) ->
this.rankMemberIfIn(@leaderboardName, rankConditional, member, score, currentScore, memberData, callback)
###
# Rank a member in the named leaderboard based on execution of the +rankConditional+.
#
# The +rankConditional+ is passed the following parameters:
# member: Member name.
# currentScore: Current score for the member in the leaderboard.
# score: Member score.
# memberData: Optional member data.
# options: Leaderboard options, e.g. 'reverse': Value of reverse option
#
# @param leaderboardName [String] Name of the leaderboard.
# @param rankConditional [Function] Function which must return +true+ or +false+ that controls whether or not the member is ranked in the leaderboard.
# @param member [String] Member name.
# @param score [float] Member score.
# @param currentScore [float] Current score.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
rankMemberIfIn: (leaderboardName, rankConditional, member, score, currentScore, memberData = null, callback) ->
if rankConditional(member, currentScore, score, memberData, {'reverse': @reverse})
this.rankMemberIn(leaderboardName, member, score, memberData, callback)
else
callback(0) if callback
###
# Rank an array of members in the leaderboard.
#
# @param membersAndScores [Array] Variable list of members and scores.
# @param callback Optional callback for result of call.
###
rankMembers: (membersAndScores, callback) ->
this.rankMembersIn(@leaderboardName, membersAndScores, callback)
###
# Rank an array of members in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param membersAndScores [Array] Variable list of members and scores
# @param callback Optional callback for result of call.
###
rankMembersIn: (leaderboardName, membersAndScores, callback) ->
transaction = @redisConnection.multi()
for index in [0...membersAndScores.length] by 2
slice = membersAndScores[index...index + 2]
transaction.zadd(leaderboardName, slice[1], slice[0])
transaction.exec((err, reply) ->
callback(reply) if callback)
###
# Retrieve the optional member data for a given member in the leaderboard.
#
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return String of optional member data.
###
memberDataFor: (member, callback) ->
this.memberDataForIn(@leaderboardName, member, callback)
###
# Retrieve the optional member data for a given member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return String of optional member data.
###
memberDataForIn: (leaderboardName, member, callback) ->
@redisConnection.hget(this.memberDataKey(leaderboardName), member, (err, reply) ->
callback(reply))
###
# Update the optional member data for a given member in the leaderboard.
#
# @param member [String] Member name.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
updateMemberData: (member, memberData, callback) ->
this.updateMemberDataFor(@leaderboardName, member, memberData, callback)
###
# Update the optional member data for a given member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
updateMemberDataFor: (leaderboardName, member, memberData, callback) ->
@redisConnection.hset(this.memberDataKey(leaderboardName), member, memberData, (err, reply) ->
callback(reply) if callback)
###
# Remove the optional member data for a given member in the leaderboard.
#
# @param member [String] Member name.
# @param callback Optional callback for result of call.
###
removeMemberData: (member, callback) ->
this.remberMemberDataFor(@leaderboardName, member, callback)
###
# Remove the optional member data for a given member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Optional callback for result of call.
###
remberMemberDataFor: (leaderboardName, member, callback) ->
@redisConnection.hdel(this.memberDataKey(leaderboardName), member, (err, reply) ->
callback(reply) if callback)
###
# Remove a member from the leaderboard.
#
# @param member [String] Member name.
# @param callback Optional callback for result of call.
###
removeMember: (member, callback) ->
this.removeMemberFrom(@leaderboardName, member, callback)
###
# Remove a member from the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Optional callback for result of call.
###
removeMemberFrom: (leaderboardName, member, callback) ->
transaction = @redisConnection.multi()
transaction.zrem(leaderboardName, member)
transaction.hdel(this.memberDataKey(leaderboardName), member)
transaction.exec((err, reply) ->
callback(reply) if callback)
###
# Retrieve the total number of members in the leaderboard.
#
# @return total number of members in the leaderboard.
# @param callback Callback for result of call.
###
totalMembers: (callback) ->
this.totalMembersIn(@leaderboardName, callback)
###
# Retrieve the total number of members in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param callback Callback for result of call.
#
# @return the total number of members in the named leaderboard.
###
totalMembersIn: (leaderboardName, callback) ->
@redisConnection.zcard(leaderboardName, (err, reply) ->
callback(reply))
###
# Retrieve the total number of pages in the leaderboard.
#
# @param pageSize [int, nil] Page size to be used when calculating the total number of pages.
# @param callback Callback for result of call.
#
# @return the total number of pages in the leaderboard.
###
totalPages: (pageSize = null, callback) ->
this.totalPagesIn(@leaderboardName, pageSize, callback)
###
# Retrieve the total number of pages in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param pageSize [int, nil] Page size to be used when calculating the total number of pages.
# @param callback Callback for result of call.
#
# @return the total number of pages in the named leaderboard.
###
totalPagesIn: (leaderboardName, pageSize = null, callback) ->
unless pageSize?
pageSize = @pageSize
@redisConnection.zcard(leaderboardName, (err, reply) ->
callback(Math.ceil(reply / pageSize)))
###
# Retrieve the total members in a given score range from the leaderboard.
#
# @param minScore [float] Minimum score.
# @param maxScore [float] Maximum score.
# @param callback Callback for result of call.
#
# @return the total members in a given score range from the leaderboard.
###
totalMembersInScoreRange: (minScore, maxScore, callback) ->
this.totalMembersInScoreRangeIn(@leaderboardName, minScore, maxScore, callback)
###
# Retrieve the total members in a given score range from the named leaderboard.
#
# @param leaderboard_name Name of the leaderboard.
# @param minScore [float] Minimum score.
# @param maxScore [float] Maximum score.
# @param callback Callback for result of call.
#
# @return the total members in a given score range from the named leaderboard.
###
totalMembersInScoreRangeIn: (leaderboardName, minScore, maxScore, callback) ->
@redisConnection.zcount(leaderboardName, minScore, maxScore, (err, reply) ->
callback(reply))
###
# Change the score for a member in the leaderboard by a score delta which can be positive or negative.
#
# @param member [String] Member name.
# @param delta [float] Score change.
# @param callback Optional callback for result of call.
###
changeScoreFor: (member, delta, callback) ->
this.changeScoreForMemberIn(@leaderboardName, member, delta, callback)
###
# Change the score for a member in the named leaderboard by a delta which can be positive or negative.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param delta [float] Score change.
# @param callback Optional callback for result of call.
###
changeScoreForMemberIn: (leaderboardName, member, delta, callback) ->
@redisConnection.zincrby(leaderboardName, delta, member, (err, reply) ->
callback(reply) if callback)
###
# Retrieve the rank for a member in the leaderboard.
#
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the rank for a member in the leaderboard.
###
rankFor: (member, callback) ->
this.rankForIn(@leaderboardName, member, callback)
###
# Retrieve the rank for a member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the rank for a member in the leaderboard.
###
rankForIn: (leaderboardName, member, callback) ->
process_response = (err, reply) ->
if reply?
callback(reply + 1)
else
callback()
if @reverse
@redisConnection.zrank(leaderboardName, member, process_response)
else
@redisConnection.zrevrank(leaderboardName, member, process_response)
###
# Retrieve the score for a member in the leaderboard.
#
# @param member Member name.
# @param callback Callback for result of call.
#
# @return the score for a member in the leaderboard or +nil+ if the member is not in the leaderboard.
###
scoreFor: (member, callback) ->
this.scoreForIn(@leaderboardName, member, callback)
###
# Retrieve the score for a member in the named leaderboard.
#
# @param leaderboardName Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the score for a member in the leaderboard or +nil+ if the member is not in the leaderboard.
###
scoreForIn: (leaderboardName, member, callback) ->
@redisConnection.zscore(leaderboardName, member, (err, reply) ->
if reply?
callback(parseFloat(reply))
else
callback(null))
###
# Check to see if a member exists in the leaderboard.
#
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return +true+ if the member exists in the leaderboard, +false+ otherwise.
###
checkMember: (member, callback) ->
this.checkMemberIn(@leaderboardName, member, callback)
###
# Check to see if a member exists in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return +true+ if the member exists in the named leaderboard, +false+ otherwise.
###
checkMemberIn: (leaderboardName, member, callback) ->
@redisConnection.zscore(leaderboardName, member, (err, reply) ->
callback(reply?))
###
# Retrieve the score and rank for a member in the leaderboard.
#
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the score and rank for a member in the leaderboard as a Hash.
###
scoreAndRankFor: (member, callback) ->
this.scoreAndRankForIn(@leaderboardName, member, callback)
###
# Retrieve the score and rank for a member in the named leaderboard.
#
# @param leaderboardName [String]Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the score and rank for a member in the named leaderboard as a Hash.
###
scoreAndRankForIn: (leaderboardName, member, callback) ->
transaction = @redisConnection.multi()
transaction.zscore(leaderboardName, member)
if @reverse
transaction.zrank(leaderboardName, member)
else
transaction.zrevrank(leaderboardName, member)
transaction.exec((err, replies) =>
if replies
scoreAndRankData = {}
if replies[0]?
scoreAndRankData[@scoreKeyOption] = parseFloat(replies[0])
else
scoreAndRankData[@scoreKeyOption] = null
if replies[1]?
scoreAndRankData[@rankKeyOption] = replies[1] + 1
else
scoreAndRankData[@rankKeyOption] = null
scoreAndRankData[@memberKeyOption] = member
callback(scoreAndRankData))
###
# Remove members from the leaderboard in a given score range.
#
# @param minScore [float] Minimum score.
# @param maxScore [float] Maximum score.
# @param callback Optional callback for result of call.
###
removeMembersInScoreRange: (minScore, maxScore, callback) ->
this.removeMembersInScoreRangeIn(@leaderboardName, minScore, maxScore, callback)
###
# Remove members from the named leaderboard in a given score range.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param minScore [float] Minimum score.
# @param maxScore [float] Maximum score.
# @param callback Optional callback for result of call.
###
removeMembersInScoreRangeIn: (leaderboardName, minScore, maxScore, callback) ->
@redisConnection.zremrangebyscore(leaderboardName, minScore, maxScore, (err, reply) ->
callback(reply) if callback)
###
# Remove members from the leaderboard outside a given rank.
#
# @param rank [int] The rank (inclusive) which we should keep.
# @param callback Optional callback for result of call.
# @return the total number of members removed.
###
removeMembersOutsideRank: (rank, callback) ->
this.removeMembersOutsideRankIn(@leaderboardName, rank, callback)
###
# Remove members from the leaderboard outside a given rank.
#
# @param leaderboard_name [String] Name of the leaderboard.
# @param rank [int] The rank (inclusive) which we should keep.
# @param callback Optional callback for result of call.
# @return the total number of members removed.
###
removeMembersOutsideRankIn: (leaderboardName, rank, callback) ->
if @reverse
@redisConnection.zremrangebyrank(leaderboardName, rank, -1, (err, reply) ->
callback(reply) if callback)
else
@redisConnection.zremrangebyrank(leaderboardName, 0, -(rank) - 1, (err, reply) ->
callback(reply) if callback)
###
# Retrieve the percentile for a member in the leaderboard.
#
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the percentile for a member in the leaderboard. Return +nil+ for a non-existent member.
###
percentileFor: (member, callback) ->
this.percentileForIn(@leaderboardName, member, callback)
###
# Retrieve the percentile for a member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the percentile for a member in the named leaderboard.
###
percentileForIn: (leaderboardName, member, callback) ->
this.checkMemberIn(leaderboardName, member, (reply) =>
if reply
transaction = @redisConnection.multi()
transaction.zcard(leaderboardName)
transaction.zrevrank(leaderboardName, member)
transaction.exec((err, replies) ->
if replies
percentile = Math.ceil(parseFloat((parseFloat(replies[0] - replies[1] - 1)) / parseFloat(replies[0]) * 100))
if @reverse
callback(100 - percentile)
else
callback(percentile)
)
else
callback()
)
###
# Calculate the score for a given percentile value in the leaderboard.
#
# @param percentile [float] Percentile value (0.0 to 100.0 inclusive)
# @param callback Callback for result of call.
#
# @return the calculated score for the requested percentile value. Return +nil+ for an invalid (outside 0-100) percentile or a leaderboard with no members.
###
scoreForPercentile: (percentile, callback) ->
this.scoreForPercentileIn(@leaderboardName, percentile, callback)
###
# Calculate the score for a given percentile value in the leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param percentile [float] Percentile value (0.0 to 100.0 inclusive)
# @param callback Callback for result of call.
#
# @return the calculated score for the requested percentile value. Return +nil+ for an invalid (outside 0-100) percentile or a leaderboard with no members.
###
scoreForPercentileIn: (leaderboardName, percentile, callback) ->
unless 0 <= percentile <= 100
return callback()
if @reverse
percentile = 100 - percentile
this.totalMembersIn(leaderboardName, (reply) =>
totalMembers = reply
if totalMembers == 0
return callback()
else
index = (totalMembers - 1) * (percentile / 100)
zrange_args = [leaderboardName, Math.floor(index), Math.ceil(index), 'WITHSCORES']
@redisConnection.zrange(zrange_args, (err, reply) ->
# Response format: ["Alice", "123", "Bob", "456"] (i.e. flat list, not member/score tuples)
lowScore = parseFloat(reply[1])
if index == Math.floor(index)
callback(lowScore)
else
interpolateFraction = index - Math.floor(index)
hiScore = parseFloat(reply[3])
callback(lowScore + interpolateFraction * (hiScore - lowScore))
)
)
###
# Determine the page where a member falls in the leaderboard.
#
# @param member [String] Member name.
# @param pageSize [int] Page size to be used in determining page location.
# @param callback Callback for result of call.
#
# @return the page where a member falls in the leaderboard.
###
pageFor: (member, pageSize = @DEFAULT_PAGE_SIZE, callback) ->
this.pageForIn(@leaderboardName, member, pageSize, callback)
###
# Determine the page where a member falls in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param pageSize [int] Page size to be used in determining page location.
# @param callback Callback for result of call.
#
# @return the page where a member falls in the leaderboard.
###
pageForIn: (leaderboardName, member, pageSize = @DEFAULT_PAGE_SIZE, callback) ->
transaction = @redisConnection.multi()
if @reverse
transaction.zrank(leaderboardName, member)
else
transaction.zrevrank(leaderboardName, member)
transaction.exec((err, replies) ->
rankForMember = replies[0]
if rankForMember?
rankForMember += 1
else
rankForMember = 0
callback(Math.ceil(rankForMember / pageSize))
)
###
# Expire the current leaderboard in a set number of seconds. Do not use this with
# leaderboards that utilize member data as there is no facility to cascade the
# expiration out to the keys for the member data.
#
# @param seconds [int] Number of seconds after which the leaderboard will be expired.
# @param callback Optional callback for result of call.
###
expireLeaderboard: (seconds, callback) ->
this.expireLeaderboardFor(@leaderboardName, seconds, callback)
###
# Expire the given leaderboard in a set number of seconds. Do not use this with
# leaderboards that utilize member data as there is no facility to cascade the
# expiration out to the keys for the member data.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param seconds [int] Number of seconds after which the leaderboard will be expired.
# @param callback Optional callback for result of call.
###
expireLeaderboardFor: (leaderboardName, seconds, callback) ->
transaction = @redisConnection.multi()
transaction.expire(leaderboardName, seconds)
transaction.expire(this.memberDataKey(leaderboardName), seconds)
transaction.exec((err, replies) ->
callback(replies) if callback)
###
# Expire the current leaderboard at a specific UNIX timestamp. Do not use this with
# leaderboards that utilize member data as there is no facility to cascade the
# expiration out to the keys for the member data.
#
# @param timestamp [int] UNIX timestamp at which the leaderboard will be expired.
# @param callback Optional callback for result of call.
###
expireLeaderboardAt: (timestamp, callback) ->
this.expireLeaderboardAtFor(@leaderboardName, timestamp, callback)
###
# Expire the given leaderboard at a specific UNIX timestamp. Do not use this with
# leaderboards that utilize member data as there is no facility to cascade the
# expiration out to the keys for the member data.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param timestamp [int] UNIX timestamp at which the leaderboard will be expired.
# @param callback Optional callback for result of call.
###
expireLeaderboardAtFor: (leaderboardName, timestamp, callback) ->
transaction = @redisConnection.multi()
transaction.expireat(leaderboardName, timestamp)
transaction.expireat(this.memberDataKey(leaderboardName), timestamp)
transaction.exec((err, replies) ->
callback(replies) if callback)
###
# Retrieve a page of leaders from the leaderboard for a given list of members.
#
# @param members [Array] Member names.
# @param options [Hash] Options to be used when retrieving the page from the leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the leaderboard for a given list of members.
###
rankedInList: (members, options = {}, callback) ->
this.rankedInListIn(@leaderboardName, members, options, callback)
###
# Retrieve a page of leaders from the named leaderboard for a given list of members.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param members [Array] Member names.
# @param options [Hash] Options to be used when retrieving the page from the named leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the named leaderboard for a given list of members.
###
rankedInListIn: (leaderboardName, members, options = {}, callback) ->
if not members? or members.length == 0
return callback([])
ranksForMembers = []
transaction = @redisConnection.multi()
unless options['membersOnly']
for member in members
if @reverse
transaction.zrank(leaderboardName, member)
else
transaction.zrevrank(leaderboardName, member)
transaction.zscore(leaderboardName, member)
transaction.exec((err, replies) =>
for member, index in members
do (member) =>
data = {}
data[@memberKeyOption] = member
unless options['membersOnly']
data[@rankKeyOption] = replies[index * 2] + 1
if replies[index * 2 + 1]
data[@scoreKeyOption] = parseFloat(replies[index * 2 + 1])
else
data[@scoreKeyOption] = null
data[@rankKeyOption] = null
# Retrieve optional member data based on options['withMemberData']
if options['withMemberData']
this.memberDataForIn leaderboardName, member, (memberdata) =>
data[@memberDataKeyOption] = memberdata
ranksForMembers.push(data)
# Sort if options['sortBy']
if ranksForMembers.length == members.length
switch options['sortBy']
when 'rank'
ranksForMembers.sort((a, b) ->
a.rank > b.rank)
when 'score'
ranksForMembers.sort((a, b) ->
a.score > b.score)
callback(ranksForMembers)
else
ranksForMembers.push(data)
# Sort if options['sortBy']
if ranksForMembers.length == members.length
switch options['sortBy']
when 'rank'
ranksForMembers.sort((a, b) ->
a.rank > b.rank)
when 'score'
ranksForMembers.sort((a, b) ->
a.score > b.score)
callback(ranksForMembers)
)
###
# Retrieve a page of leaders from the leaderboard.
#
# @param currentPage [int] Page to retrieve from the leaderboard.
# @param options [Hash] Options to be used when retrieving the page from the leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the leaderboard.
###
leaders: (currentPage, options = {}, callback) ->
this.leadersIn(@leaderboardName, currentPage, options, callback)
###
# Retrieve a page of leaders from the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param currentPage [int] Page to retrieve from the named leaderboard.
# @param options [Hash] Options to be used when retrieving the page from the named leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the named leaderboard.
###
leadersIn: (leaderboardName, currentPage, options = {}, callback) ->
currentPage = 1 if currentPage < 1
pageSize = options['pageSize'] || @pageSize
this.totalPages(pageSize, (totalPages) =>
if currentPage > totalPages
currentPage = totalPages
indexForRedis = currentPage - 1
startingOffset = (indexForRedis * pageSize)
endingOffset = (startingOffset + pageSize) - 1
if @reverse
@redisConnection.zrange(leaderboardName, startingOffset, endingOffset, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
@redisConnection.zrevrange(leaderboardName, startingOffset, endingOffset, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
)
###
# Retrieve all leaders from the leaderboard.
#
# @param options [Hash] Options to be used when retrieving the leaders from the leaderboard.
# @param callback Callback for result of call.
#
# @return the leaders from the leaderboard.
###
allLeaders: (options = {}, callback) ->
this.allLeadersFrom(@leaderboardName, options, callback)
###
# Retrieves all leaders from the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param options [Hash] Options to be used when retrieving the leaders from the named leaderboard.
# @param callback Callback for result of call.
#
# @return the named leaderboard.
###
allLeadersFrom: (leaderboardName, options = {}, callback) ->
if @reverse
@redisConnection.zrange(leaderboardName, 0, -1, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
@redisConnection.zrevrange(leaderboardName, 0, -1, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
###
# Retrieve members from the leaderboard within a given score range.
#
# @param minimumScore [float] Minimum score (inclusive).
# @param maximumScore [float] Maximum score (inclusive).
# @param options [Hash] Options to be used when retrieving the data from the leaderboard.
# @param callback Callback for result of call.
#
# @return members from the leaderboard that fall within the given score range.
###
membersFromScoreRange: (minimumScore, maximumScore, options = {}, callback) ->
this.membersFromScoreRangeIn(@leaderboardName, minimumScore, maximumScore, options, callback)
###
# Retrieve members from the named leaderboard within a given score range.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param minimumScore [float] Minimum score (inclusive).
# @param maximumScore [float] Maximum score (inclusive).
# @param options [Hash] Options to be used when retrieving the data from the leaderboard.
# @param callback Callback for result of call.
#
# @return members from the leaderboard that fall within the given score range.
###
membersFromScoreRangeIn: (leaderboardName, minimumScore, maximumScore, options = {}, callback) ->
if @reverse
@redisConnection.zrangebyscore(leaderboardName, minimumScore, maximumScore, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
@redisConnection.zrevrangebyscore(leaderboardName, maximumScore, minimumScore, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
###
# Retrieve members from the leaderboard within a given rank range.
#
# @param startingRank [int] Starting rank (inclusive).
# @param endingRank [int] Ending rank (inclusive).
# @param options [Hash] Options to be used when retrieving the data from the leaderboard.
# @param callback Callback for result of call.
#
# @return members from the leaderboard that fall within the given rank range.
###
membersFromRankRange: (startingRank, endingRank, options = {}, callback) ->
this.membersFromRankRangeIn(@leaderboardName, startingRank, endingRank, options, callback)
###
# Retrieve members from the named leaderboard within a given rank range.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param startingRank [int] Starting rank (inclusive).
# @param endingRank [int] Ending rank (inclusive).
# @param options [Hash] Options to be used when retrieving the data from the leaderboard.
# @param callback Callback for result of call.
#
# @return members from the leaderboard that fall within the given rank range.
###
membersFromRankRangeIn: (leaderboardName, startingRank, endingRank, options, callback) ->
startingRank -= 1
if startingRank < 0
startingRank = 0
endingRank -= 1
if endingRank < 0
endingRank = 0
if @reverse
@redisConnection.zrange(leaderboardName, startingRank, endingRank, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
@redisConnection.zrevrange(leaderboardName, startingRank, endingRank, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
###
# Retrieve a member at the specified index from the leaderboard.
#
# @param position [int] Position in leaderboard.
# @param options [Hash] Options to be used when retrieving the member from the leaderboard.
# @param callback Callback for result of call.
#
# @return a member from the leaderboard.
###
memberAt: (position, options = {}, callback) ->
this.memberAtIn(@leaderboardName, position, options, callback)
###
# Retrieve a member at the specified index from the leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param position [int] Position in named leaderboard.
# @param options [Hash] Options to be used when retrieving the member from the named leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the named leaderboard.
###
memberAtIn: (leaderboardName, position, options = {}, callback) ->
this.membersFromRankRangeIn(leaderboardName, position, position, options, callback)
###
# Retrieve a page of leaders from the leaderboard around a given member.
#
# @param member [String] Member name.
# @param options [Hash] Options to be used when retrieving the page from the leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the leaderboard around a given member.
###
aroundMe: (member, options = {}, callback) ->
this.aroundMeIn(@leaderboardName, member, options, callback)
###
# Retrieve a page of leaders from the named leaderboard around a given member.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param options [Hash] Options to be used when retrieving the page from the named leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the named leaderboard around a given member. Returns an empty array for a non-existent member.
###
aroundMeIn: (leaderboardName, member, options = {}, callback) ->
pageSize = options['pageSize'] || @pageSize
if @reverse
@redisConnection.zrank(leaderboardName, member, (err, reply) =>
if reply?
startingOffset = parseInt(Math.ceil(reply - (pageSize / 2)))
startingOffset = 0 if startingOffset < 0
endingOffset = (startingOffset + pageSize) - 1
@redisConnection.zrange(leaderboardName, startingOffset, endingOffset, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
callback([])
[]
)
else
@redisConnection.zrevrank(leaderboardName, member, (err, reply) =>
if reply?
startingOffset = parseInt(Math.ceil(reply - (pageSize / 2)))
startingOffset = 0 if startingOffset < 0
endingOffset = (startingOffset + pageSize) - 1
@redisConnection.zrevrange(leaderboardName, startingOffset, endingOffset, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
callback([])
[]
)
###
# Merge leaderboards given by keys with this leaderboard into a named destination leaderboard.
#
# @param destination [String] Destination leaderboard name.
# @param keys [Array] Leaderboards to be merged with the current leaderboard.
# @param options [Hash] Options for merging the leaderboards.
# @param callback Callback for result of call.
###
mergeLeaderboards: (destination, keys, options = {'aggregate': 'sum'}, callback) ->
len = keys.length + 1
keys.unshift(@leaderboardName)
keys.unshift(len)
keys.unshift(destination)
keys.push("AGGREGATE")
keys.push(options['aggregate'])
@redisConnection.zunionstore(keys, (err, reply) ->
callback(reply) if callback)
###
# Intersect leaderboards given by keys with this leaderboard into a named destination leaderboard.
#
# @param destination [String] Destination leaderboard name.
# @param keys [Array] Leaderboards to be merged with the current leaderboard.
# @param options [Hash] Options for intersecting the leaderboards.
# @param callback Callback for result of call.
###
intersectLeaderboards: (destination, keys, options = {'aggregate': 'sum'}, callback) ->
len = keys.length + 1
keys.unshift(@leaderboardName)
keys.unshift(len)
keys.unshift(destination)
keys.push("AGGREGATE")
keys.push(options['aggregate'])
@redisConnection.zinterstore(keys, (err, reply) ->
callback(reply) if callback)
###
# Key for retrieving optional member data.
#
# @param leaderboardName [String] Name of the leaderboard.
#
# @return a key in the form of +leaderboardName:member_data+
###
memberDataKey: (leaderboardName) ->
"#{leaderboardName}:#{@memberDataNamespace}"
module.exports = Leaderboard
| 91084 | redis = require 'redis'
class Leaderboard
###
# Default page size: 25
###
@DEFAULT_PAGE_SIZE = 25
###
# Default options when creating a leaderboard. Page size is 25 and reverse
# is set to false, meaning various methods will return results in
# highest-to-lowest order.
###
DEFAULT_OPTIONS =
'pageSize': @DEFAULT_PAGE_SIZE
'reverse': false
'memberKey': '<KEY>'
'rankKey': '<KEY>'
'scoreKey': '<KEY>'
'memberDataKey': '<KEY>'
'memberDataNamespace': 'member_data'
###
# Default Redis host: localhost
###
@DEFAULT_REDIS_HOST = 'localhost'
###
# Default Redis post: 6379
###
@DEFAULT_REDIS_PORT = 6379
###
# Default Redis options when creating a connection to Redis. The
# +DEFAULT_REDIS_HOST+ and +DEFAULT_REDIS_PORT+ will be passed.
###
DEFAULT_REDIS_OPTIONS =
'host': @DEFAULT_REDIS_HOST
'port': @DEFAULT_REDIS_PORT
###
# Create a new instance of a leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param options [Hash] Options for the leaderboard such as +'pageSize'+.
# @param redisOptions [Hash] Options for configuring Redis.
###
constructor: (@leaderboardName, options = DEFAULT_OPTIONS, redisOptions = DEFAULT_REDIS_OPTIONS) ->
@reverse = options['reverse']
@pageSize = options['pageSize']
if @pageSize == null || @pageSize < 1
@pageSize = Leaderboard.DEFAULT_PAGE_SIZE
@memberKeyOption = options['memberKey'] || '<KEY>'
@rankKeyOption = options['rankKey'] || '<KEY>'
@scoreKeyOption = options['scoreKey'] || '<KEY>'
@memberDataKeyOption = options['memberDataKey'] || '<KEY>'
@memberDataNamespace = options['memberDataNamespace'] || 'member_data'
@redisConnection = redisOptions['redis_connection']
if @redisConnection?
delete redisOptions['redis_connection']
@redisConnection = redis.createClient(redisOptions['port'], redisOptions['host']) unless @redisConnection?
###
# Disconnect the Redis connection.
###
disconnect: ->
@redisConnection.quit((err, reply) -> )
###
# Delete the current leaderboard.
#
# @param callback Optional callback for result of call.
###
deleteLeaderboard: (callback) ->
this.deleteLeaderboardNamed(@leaderboardName, callback)
###
# Delete the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param callback Optional callback for result of call.
###
deleteLeaderboardNamed: (leaderboardName, callback) ->
transaction = @redisConnection.multi()
transaction.del(leaderboardName)
transaction.del(this.memberDataKey(leaderboardName))
transaction.exec((err, reply) ->
callback(reply) if callback)
###
# Rank a member in the leaderboard.
#
# @param member [String] Member name.
# @param score [float] Member score.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
rankMember: (member, score, memberData = null, callback) ->
this.rankMemberIn(@leaderboardName, member, score, memberData, callback)
###
# Rank a member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param score [float] Member score.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
rankMemberIn: (leaderboardName, member, score, memberData = null, callback) ->
transaction = @redisConnection.multi()
transaction.zadd(leaderboardName, score, member)
transaction.hset(this.memberDataKey(leaderboardName), member, memberData) if memberData?
transaction.exec((err, reply) ->
callback(reply) if callback)
###
# Rank a member across multiple leaderboards.
#
# @param leaderboards [Array] Leaderboard names.
# @param member [String] Member name.
# @param score [float] Member score.
# @param member_data [String] Optional member data.
###
rankMemberAcross: (leaderboardNames, member, score, memberData = null, callback) ->
transaction = @redisConnection.multi()
for leaderboardName in leaderboardNames
transaction.zadd(leaderboardName, score, member)
transaction.hset(this.memberDataKey(leaderboardName), member, memberData) if memberData?
transaction.exec((err, reply) ->
callback(reply) if callback)
###
# Rank a member in the leaderboard based on execution of the +rankConditional+.
#
# The +rankConditional+ is passed the following parameters:
# member: Member name.
# currentScore: Current score for the member in the leaderboard.
# score: Member score.
# memberData: Optional member data.
# options: Leaderboard options, e.g. 'reverse': Value of reverse option
#
# @param rankConditional [Function] Function which must return +true+ or +false+ that controls whether or not the member is ranked in the leaderboard.
# @param member [String] Member name.
# @param score [float] Member score.
# @param currentScore [float] Current score.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
rankMemberIf: (rankConditional, member, score, currentScore, memberData = null, callback) ->
this.rankMemberIfIn(@leaderboardName, rankConditional, member, score, currentScore, memberData, callback)
###
# Rank a member in the named leaderboard based on execution of the +rankConditional+.
#
# The +rankConditional+ is passed the following parameters:
# member: Member name.
# currentScore: Current score for the member in the leaderboard.
# score: Member score.
# memberData: Optional member data.
# options: Leaderboard options, e.g. 'reverse': Value of reverse option
#
# @param leaderboardName [String] Name of the leaderboard.
# @param rankConditional [Function] Function which must return +true+ or +false+ that controls whether or not the member is ranked in the leaderboard.
# @param member [String] Member name.
# @param score [float] Member score.
# @param currentScore [float] Current score.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
rankMemberIfIn: (leaderboardName, rankConditional, member, score, currentScore, memberData = null, callback) ->
if rankConditional(member, currentScore, score, memberData, {'reverse': @reverse})
this.rankMemberIn(leaderboardName, member, score, memberData, callback)
else
callback(0) if callback
###
# Rank an array of members in the leaderboard.
#
# @param membersAndScores [Array] Variable list of members and scores.
# @param callback Optional callback for result of call.
###
rankMembers: (membersAndScores, callback) ->
this.rankMembersIn(@leaderboardName, membersAndScores, callback)
###
# Rank an array of members in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param membersAndScores [Array] Variable list of members and scores
# @param callback Optional callback for result of call.
###
rankMembersIn: (leaderboardName, membersAndScores, callback) ->
transaction = @redisConnection.multi()
for index in [0...membersAndScores.length] by 2
slice = membersAndScores[index...index + 2]
transaction.zadd(leaderboardName, slice[1], slice[0])
transaction.exec((err, reply) ->
callback(reply) if callback)
###
# Retrieve the optional member data for a given member in the leaderboard.
#
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return String of optional member data.
###
memberDataFor: (member, callback) ->
this.memberDataForIn(@leaderboardName, member, callback)
###
# Retrieve the optional member data for a given member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return String of optional member data.
###
memberDataForIn: (leaderboardName, member, callback) ->
@redisConnection.hget(this.memberDataKey(leaderboardName), member, (err, reply) ->
callback(reply))
###
# Update the optional member data for a given member in the leaderboard.
#
# @param member [String] Member name.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
updateMemberData: (member, memberData, callback) ->
this.updateMemberDataFor(@leaderboardName, member, memberData, callback)
###
# Update the optional member data for a given member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
updateMemberDataFor: (leaderboardName, member, memberData, callback) ->
@redisConnection.hset(this.memberDataKey(leaderboardName), member, memberData, (err, reply) ->
callback(reply) if callback)
###
# Remove the optional member data for a given member in the leaderboard.
#
# @param member [String] Member name.
# @param callback Optional callback for result of call.
###
removeMemberData: (member, callback) ->
this.remberMemberDataFor(@leaderboardName, member, callback)
###
# Remove the optional member data for a given member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Optional callback for result of call.
###
remberMemberDataFor: (leaderboardName, member, callback) ->
@redisConnection.hdel(this.memberDataKey(leaderboardName), member, (err, reply) ->
callback(reply) if callback)
###
# Remove a member from the leaderboard.
#
# @param member [String] Member name.
# @param callback Optional callback for result of call.
###
removeMember: (member, callback) ->
this.removeMemberFrom(@leaderboardName, member, callback)
###
# Remove a member from the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Optional callback for result of call.
###
removeMemberFrom: (leaderboardName, member, callback) ->
transaction = @redisConnection.multi()
transaction.zrem(leaderboardName, member)
transaction.hdel(this.memberDataKey(leaderboardName), member)
transaction.exec((err, reply) ->
callback(reply) if callback)
###
# Retrieve the total number of members in the leaderboard.
#
# @return total number of members in the leaderboard.
# @param callback Callback for result of call.
###
totalMembers: (callback) ->
this.totalMembersIn(@leaderboardName, callback)
###
# Retrieve the total number of members in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param callback Callback for result of call.
#
# @return the total number of members in the named leaderboard.
###
totalMembersIn: (leaderboardName, callback) ->
@redisConnection.zcard(leaderboardName, (err, reply) ->
callback(reply))
###
# Retrieve the total number of pages in the leaderboard.
#
# @param pageSize [int, nil] Page size to be used when calculating the total number of pages.
# @param callback Callback for result of call.
#
# @return the total number of pages in the leaderboard.
###
totalPages: (pageSize = null, callback) ->
this.totalPagesIn(@leaderboardName, pageSize, callback)
###
# Retrieve the total number of pages in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param pageSize [int, nil] Page size to be used when calculating the total number of pages.
# @param callback Callback for result of call.
#
# @return the total number of pages in the named leaderboard.
###
totalPagesIn: (leaderboardName, pageSize = null, callback) ->
unless pageSize?
pageSize = @pageSize
@redisConnection.zcard(leaderboardName, (err, reply) ->
callback(Math.ceil(reply / pageSize)))
###
# Retrieve the total members in a given score range from the leaderboard.
#
# @param minScore [float] Minimum score.
# @param maxScore [float] Maximum score.
# @param callback Callback for result of call.
#
# @return the total members in a given score range from the leaderboard.
###
totalMembersInScoreRange: (minScore, maxScore, callback) ->
this.totalMembersInScoreRangeIn(@leaderboardName, minScore, maxScore, callback)
###
# Retrieve the total members in a given score range from the named leaderboard.
#
# @param leaderboard_name Name of the leaderboard.
# @param minScore [float] Minimum score.
# @param maxScore [float] Maximum score.
# @param callback Callback for result of call.
#
# @return the total members in a given score range from the named leaderboard.
###
totalMembersInScoreRangeIn: (leaderboardName, minScore, maxScore, callback) ->
@redisConnection.zcount(leaderboardName, minScore, maxScore, (err, reply) ->
callback(reply))
###
# Change the score for a member in the leaderboard by a score delta which can be positive or negative.
#
# @param member [String] Member name.
# @param delta [float] Score change.
# @param callback Optional callback for result of call.
###
changeScoreFor: (member, delta, callback) ->
this.changeScoreForMemberIn(@leaderboardName, member, delta, callback)
###
# Change the score for a member in the named leaderboard by a delta which can be positive or negative.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param delta [float] Score change.
# @param callback Optional callback for result of call.
###
changeScoreForMemberIn: (leaderboardName, member, delta, callback) ->
@redisConnection.zincrby(leaderboardName, delta, member, (err, reply) ->
callback(reply) if callback)
###
# Retrieve the rank for a member in the leaderboard.
#
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the rank for a member in the leaderboard.
###
rankFor: (member, callback) ->
this.rankForIn(@leaderboardName, member, callback)
###
# Retrieve the rank for a member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the rank for a member in the leaderboard.
###
rankForIn: (leaderboardName, member, callback) ->
process_response = (err, reply) ->
if reply?
callback(reply + 1)
else
callback()
if @reverse
@redisConnection.zrank(leaderboardName, member, process_response)
else
@redisConnection.zrevrank(leaderboardName, member, process_response)
###
# Retrieve the score for a member in the leaderboard.
#
# @param member Member name.
# @param callback Callback for result of call.
#
# @return the score for a member in the leaderboard or +nil+ if the member is not in the leaderboard.
###
scoreFor: (member, callback) ->
this.scoreForIn(@leaderboardName, member, callback)
###
# Retrieve the score for a member in the named leaderboard.
#
# @param leaderboardName Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the score for a member in the leaderboard or +nil+ if the member is not in the leaderboard.
###
scoreForIn: (leaderboardName, member, callback) ->
@redisConnection.zscore(leaderboardName, member, (err, reply) ->
if reply?
callback(parseFloat(reply))
else
callback(null))
###
# Check to see if a member exists in the leaderboard.
#
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return +true+ if the member exists in the leaderboard, +false+ otherwise.
###
checkMember: (member, callback) ->
this.checkMemberIn(@leaderboardName, member, callback)
###
# Check to see if a member exists in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return +true+ if the member exists in the named leaderboard, +false+ otherwise.
###
checkMemberIn: (leaderboardName, member, callback) ->
@redisConnection.zscore(leaderboardName, member, (err, reply) ->
callback(reply?))
###
# Retrieve the score and rank for a member in the leaderboard.
#
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the score and rank for a member in the leaderboard as a Hash.
###
scoreAndRankFor: (member, callback) ->
this.scoreAndRankForIn(@leaderboardName, member, callback)
###
# Retrieve the score and rank for a member in the named leaderboard.
#
# @param leaderboardName [String]Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the score and rank for a member in the named leaderboard as a Hash.
###
scoreAndRankForIn: (leaderboardName, member, callback) ->
transaction = @redisConnection.multi()
transaction.zscore(leaderboardName, member)
if @reverse
transaction.zrank(leaderboardName, member)
else
transaction.zrevrank(leaderboardName, member)
transaction.exec((err, replies) =>
if replies
scoreAndRankData = {}
if replies[0]?
scoreAndRankData[@scoreKeyOption] = parseFloat(replies[0])
else
scoreAndRankData[@scoreKeyOption] = null
if replies[1]?
scoreAndRankData[@rankKeyOption] = replies[1] + 1
else
scoreAndRankData[@rankKeyOption] = null
scoreAndRankData[@memberKeyOption] = member
callback(scoreAndRankData))
###
# Remove members from the leaderboard in a given score range.
#
# @param minScore [float] Minimum score.
# @param maxScore [float] Maximum score.
# @param callback Optional callback for result of call.
###
removeMembersInScoreRange: (minScore, maxScore, callback) ->
this.removeMembersInScoreRangeIn(@leaderboardName, minScore, maxScore, callback)
###
# Remove members from the named leaderboard in a given score range.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param minScore [float] Minimum score.
# @param maxScore [float] Maximum score.
# @param callback Optional callback for result of call.
###
removeMembersInScoreRangeIn: (leaderboardName, minScore, maxScore, callback) ->
@redisConnection.zremrangebyscore(leaderboardName, minScore, maxScore, (err, reply) ->
callback(reply) if callback)
###
# Remove members from the leaderboard outside a given rank.
#
# @param rank [int] The rank (inclusive) which we should keep.
# @param callback Optional callback for result of call.
# @return the total number of members removed.
###
removeMembersOutsideRank: (rank, callback) ->
this.removeMembersOutsideRankIn(@leaderboardName, rank, callback)
###
# Remove members from the leaderboard outside a given rank.
#
# @param leaderboard_name [String] Name of the leaderboard.
# @param rank [int] The rank (inclusive) which we should keep.
# @param callback Optional callback for result of call.
# @return the total number of members removed.
###
removeMembersOutsideRankIn: (leaderboardName, rank, callback) ->
if @reverse
@redisConnection.zremrangebyrank(leaderboardName, rank, -1, (err, reply) ->
callback(reply) if callback)
else
@redisConnection.zremrangebyrank(leaderboardName, 0, -(rank) - 1, (err, reply) ->
callback(reply) if callback)
###
# Retrieve the percentile for a member in the leaderboard.
#
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the percentile for a member in the leaderboard. Return +nil+ for a non-existent member.
###
percentileFor: (member, callback) ->
this.percentileForIn(@leaderboardName, member, callback)
###
# Retrieve the percentile for a member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the percentile for a member in the named leaderboard.
###
percentileForIn: (leaderboardName, member, callback) ->
this.checkMemberIn(leaderboardName, member, (reply) =>
if reply
transaction = @redisConnection.multi()
transaction.zcard(leaderboardName)
transaction.zrevrank(leaderboardName, member)
transaction.exec((err, replies) ->
if replies
percentile = Math.ceil(parseFloat((parseFloat(replies[0] - replies[1] - 1)) / parseFloat(replies[0]) * 100))
if @reverse
callback(100 - percentile)
else
callback(percentile)
)
else
callback()
)
###
# Calculate the score for a given percentile value in the leaderboard.
#
# @param percentile [float] Percentile value (0.0 to 100.0 inclusive)
# @param callback Callback for result of call.
#
# @return the calculated score for the requested percentile value. Return +nil+ for an invalid (outside 0-100) percentile or a leaderboard with no members.
###
scoreForPercentile: (percentile, callback) ->
this.scoreForPercentileIn(@leaderboardName, percentile, callback)
###
# Calculate the score for a given percentile value in the leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param percentile [float] Percentile value (0.0 to 100.0 inclusive)
# @param callback Callback for result of call.
#
# @return the calculated score for the requested percentile value. Return +nil+ for an invalid (outside 0-100) percentile or a leaderboard with no members.
###
scoreForPercentileIn: (leaderboardName, percentile, callback) ->
unless 0 <= percentile <= 100
return callback()
if @reverse
percentile = 100 - percentile
this.totalMembersIn(leaderboardName, (reply) =>
totalMembers = reply
if totalMembers == 0
return callback()
else
index = (totalMembers - 1) * (percentile / 100)
zrange_args = [leaderboardName, Math.floor(index), Math.ceil(index), 'WITHSCORES']
@redisConnection.zrange(zrange_args, (err, reply) ->
# Response format: ["<NAME>", "123", "<NAME>", "456"] (i.e. flat list, not member/score tuples)
lowScore = parseFloat(reply[1])
if index == Math.floor(index)
callback(lowScore)
else
interpolateFraction = index - Math.floor(index)
hiScore = parseFloat(reply[3])
callback(lowScore + interpolateFraction * (hiScore - lowScore))
)
)
###
# Determine the page where a member falls in the leaderboard.
#
# @param member [String] Member name.
# @param pageSize [int] Page size to be used in determining page location.
# @param callback Callback for result of call.
#
# @return the page where a member falls in the leaderboard.
###
pageFor: (member, pageSize = @DEFAULT_PAGE_SIZE, callback) ->
this.pageForIn(@leaderboardName, member, pageSize, callback)
###
# Determine the page where a member falls in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param pageSize [int] Page size to be used in determining page location.
# @param callback Callback for result of call.
#
# @return the page where a member falls in the leaderboard.
###
pageForIn: (leaderboardName, member, pageSize = @DEFAULT_PAGE_SIZE, callback) ->
transaction = @redisConnection.multi()
if @reverse
transaction.zrank(leaderboardName, member)
else
transaction.zrevrank(leaderboardName, member)
transaction.exec((err, replies) ->
rankForMember = replies[0]
if rankForMember?
rankForMember += 1
else
rankForMember = 0
callback(Math.ceil(rankForMember / pageSize))
)
###
# Expire the current leaderboard in a set number of seconds. Do not use this with
# leaderboards that utilize member data as there is no facility to cascade the
# expiration out to the keys for the member data.
#
# @param seconds [int] Number of seconds after which the leaderboard will be expired.
# @param callback Optional callback for result of call.
###
expireLeaderboard: (seconds, callback) ->
this.expireLeaderboardFor(@leaderboardName, seconds, callback)
###
# Expire the given leaderboard in a set number of seconds. Do not use this with
# leaderboards that utilize member data as there is no facility to cascade the
# expiration out to the keys for the member data.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param seconds [int] Number of seconds after which the leaderboard will be expired.
# @param callback Optional callback for result of call.
###
expireLeaderboardFor: (leaderboardName, seconds, callback) ->
transaction = @redisConnection.multi()
transaction.expire(leaderboardName, seconds)
transaction.expire(this.memberDataKey(leaderboardName), seconds)
transaction.exec((err, replies) ->
callback(replies) if callback)
###
# Expire the current leaderboard at a specific UNIX timestamp. Do not use this with
# leaderboards that utilize member data as there is no facility to cascade the
# expiration out to the keys for the member data.
#
# @param timestamp [int] UNIX timestamp at which the leaderboard will be expired.
# @param callback Optional callback for result of call.
###
expireLeaderboardAt: (timestamp, callback) ->
this.expireLeaderboardAtFor(@leaderboardName, timestamp, callback)
###
# Expire the given leaderboard at a specific UNIX timestamp. Do not use this with
# leaderboards that utilize member data as there is no facility to cascade the
# expiration out to the keys for the member data.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param timestamp [int] UNIX timestamp at which the leaderboard will be expired.
# @param callback Optional callback for result of call.
###
expireLeaderboardAtFor: (leaderboardName, timestamp, callback) ->
transaction = @redisConnection.multi()
transaction.expireat(leaderboardName, timestamp)
transaction.expireat(this.memberDataKey(leaderboardName), timestamp)
transaction.exec((err, replies) ->
callback(replies) if callback)
###
# Retrieve a page of leaders from the leaderboard for a given list of members.
#
# @param members [Array] Member names.
# @param options [Hash] Options to be used when retrieving the page from the leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the leaderboard for a given list of members.
###
rankedInList: (members, options = {}, callback) ->
this.rankedInListIn(@leaderboardName, members, options, callback)
###
# Retrieve a page of leaders from the named leaderboard for a given list of members.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param members [Array] Member names.
# @param options [Hash] Options to be used when retrieving the page from the named leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the named leaderboard for a given list of members.
###
rankedInListIn: (leaderboardName, members, options = {}, callback) ->
if not members? or members.length == 0
return callback([])
ranksForMembers = []
transaction = @redisConnection.multi()
unless options['membersOnly']
for member in members
if @reverse
transaction.zrank(leaderboardName, member)
else
transaction.zrevrank(leaderboardName, member)
transaction.zscore(leaderboardName, member)
transaction.exec((err, replies) =>
for member, index in members
do (member) =>
data = {}
data[@memberKeyOption] = member
unless options['membersOnly']
data[@rankKeyOption] = replies[index * 2] + 1
if replies[index * 2 + 1]
data[@scoreKeyOption] = parseFloat(replies[index * 2 + 1])
else
data[@scoreKeyOption] = null
data[@rankKeyOption] = null
# Retrieve optional member data based on options['withMemberData']
if options['withMemberData']
this.memberDataForIn leaderboardName, member, (memberdata) =>
data[@memberDataKeyOption] = memberdata
ranksForMembers.push(data)
# Sort if options['sortBy']
if ranksForMembers.length == members.length
switch options['sortBy']
when 'rank'
ranksForMembers.sort((a, b) ->
a.rank > b.rank)
when 'score'
ranksForMembers.sort((a, b) ->
a.score > b.score)
callback(ranksForMembers)
else
ranksForMembers.push(data)
# Sort if options['sortBy']
if ranksForMembers.length == members.length
switch options['sortBy']
when 'rank'
ranksForMembers.sort((a, b) ->
a.rank > b.rank)
when 'score'
ranksForMembers.sort((a, b) ->
a.score > b.score)
callback(ranksForMembers)
)
###
# Retrieve a page of leaders from the leaderboard.
#
# @param currentPage [int] Page to retrieve from the leaderboard.
# @param options [Hash] Options to be used when retrieving the page from the leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the leaderboard.
###
leaders: (currentPage, options = {}, callback) ->
this.leadersIn(@leaderboardName, currentPage, options, callback)
###
# Retrieve a page of leaders from the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param currentPage [int] Page to retrieve from the named leaderboard.
# @param options [Hash] Options to be used when retrieving the page from the named leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the named leaderboard.
###
leadersIn: (leaderboardName, currentPage, options = {}, callback) ->
currentPage = 1 if currentPage < 1
pageSize = options['pageSize'] || @pageSize
this.totalPages(pageSize, (totalPages) =>
if currentPage > totalPages
currentPage = totalPages
indexForRedis = currentPage - 1
startingOffset = (indexForRedis * pageSize)
endingOffset = (startingOffset + pageSize) - 1
if @reverse
@redisConnection.zrange(leaderboardName, startingOffset, endingOffset, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
@redisConnection.zrevrange(leaderboardName, startingOffset, endingOffset, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
)
###
# Retrieve all leaders from the leaderboard.
#
# @param options [Hash] Options to be used when retrieving the leaders from the leaderboard.
# @param callback Callback for result of call.
#
# @return the leaders from the leaderboard.
###
allLeaders: (options = {}, callback) ->
this.allLeadersFrom(@leaderboardName, options, callback)
###
# Retrieves all leaders from the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param options [Hash] Options to be used when retrieving the leaders from the named leaderboard.
# @param callback Callback for result of call.
#
# @return the named leaderboard.
###
allLeadersFrom: (leaderboardName, options = {}, callback) ->
if @reverse
@redisConnection.zrange(leaderboardName, 0, -1, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
@redisConnection.zrevrange(leaderboardName, 0, -1, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
###
# Retrieve members from the leaderboard within a given score range.
#
# @param minimumScore [float] Minimum score (inclusive).
# @param maximumScore [float] Maximum score (inclusive).
# @param options [Hash] Options to be used when retrieving the data from the leaderboard.
# @param callback Callback for result of call.
#
# @return members from the leaderboard that fall within the given score range.
###
membersFromScoreRange: (minimumScore, maximumScore, options = {}, callback) ->
this.membersFromScoreRangeIn(@leaderboardName, minimumScore, maximumScore, options, callback)
###
# Retrieve members from the named leaderboard within a given score range.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param minimumScore [float] Minimum score (inclusive).
# @param maximumScore [float] Maximum score (inclusive).
# @param options [Hash] Options to be used when retrieving the data from the leaderboard.
# @param callback Callback for result of call.
#
# @return members from the leaderboard that fall within the given score range.
###
membersFromScoreRangeIn: (leaderboardName, minimumScore, maximumScore, options = {}, callback) ->
if @reverse
@redisConnection.zrangebyscore(leaderboardName, minimumScore, maximumScore, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
@redisConnection.zrevrangebyscore(leaderboardName, maximumScore, minimumScore, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
###
# Retrieve members from the leaderboard within a given rank range.
#
# @param startingRank [int] Starting rank (inclusive).
# @param endingRank [int] Ending rank (inclusive).
# @param options [Hash] Options to be used when retrieving the data from the leaderboard.
# @param callback Callback for result of call.
#
# @return members from the leaderboard that fall within the given rank range.
###
membersFromRankRange: (startingRank, endingRank, options = {}, callback) ->
this.membersFromRankRangeIn(@leaderboardName, startingRank, endingRank, options, callback)
###
# Retrieve members from the named leaderboard within a given rank range.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param startingRank [int] Starting rank (inclusive).
# @param endingRank [int] Ending rank (inclusive).
# @param options [Hash] Options to be used when retrieving the data from the leaderboard.
# @param callback Callback for result of call.
#
# @return members from the leaderboard that fall within the given rank range.
###
membersFromRankRangeIn: (leaderboardName, startingRank, endingRank, options, callback) ->
startingRank -= 1
if startingRank < 0
startingRank = 0
endingRank -= 1
if endingRank < 0
endingRank = 0
if @reverse
@redisConnection.zrange(leaderboardName, startingRank, endingRank, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
@redisConnection.zrevrange(leaderboardName, startingRank, endingRank, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
###
# Retrieve a member at the specified index from the leaderboard.
#
# @param position [int] Position in leaderboard.
# @param options [Hash] Options to be used when retrieving the member from the leaderboard.
# @param callback Callback for result of call.
#
# @return a member from the leaderboard.
###
memberAt: (position, options = {}, callback) ->
this.memberAtIn(@leaderboardName, position, options, callback)
###
# Retrieve a member at the specified index from the leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param position [int] Position in named leaderboard.
# @param options [Hash] Options to be used when retrieving the member from the named leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the named leaderboard.
###
memberAtIn: (leaderboardName, position, options = {}, callback) ->
this.membersFromRankRangeIn(leaderboardName, position, position, options, callback)
###
# Retrieve a page of leaders from the leaderboard around a given member.
#
# @param member [String] Member name.
# @param options [Hash] Options to be used when retrieving the page from the leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the leaderboard around a given member.
###
aroundMe: (member, options = {}, callback) ->
this.aroundMeIn(@leaderboardName, member, options, callback)
###
# Retrieve a page of leaders from the named leaderboard around a given member.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param options [Hash] Options to be used when retrieving the page from the named leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the named leaderboard around a given member. Returns an empty array for a non-existent member.
###
aroundMeIn: (leaderboardName, member, options = {}, callback) ->
pageSize = options['pageSize'] || @pageSize
if @reverse
@redisConnection.zrank(leaderboardName, member, (err, reply) =>
if reply?
startingOffset = parseInt(Math.ceil(reply - (pageSize / 2)))
startingOffset = 0 if startingOffset < 0
endingOffset = (startingOffset + pageSize) - 1
@redisConnection.zrange(leaderboardName, startingOffset, endingOffset, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
callback([])
[]
)
else
@redisConnection.zrevrank(leaderboardName, member, (err, reply) =>
if reply?
startingOffset = parseInt(Math.ceil(reply - (pageSize / 2)))
startingOffset = 0 if startingOffset < 0
endingOffset = (startingOffset + pageSize) - 1
@redisConnection.zrevrange(leaderboardName, startingOffset, endingOffset, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
callback([])
[]
)
###
# Merge leaderboards given by keys with this leaderboard into a named destination leaderboard.
#
# @param destination [String] Destination leaderboard name.
# @param keys [Array] Leaderboards to be merged with the current leaderboard.
# @param options [Hash] Options for merging the leaderboards.
# @param callback Callback for result of call.
###
mergeLeaderboards: (destination, keys, options = {'aggregate': 'sum'}, callback) ->
len = keys.length + 1
keys.unshift(@leaderboardName)
keys.unshift(len)
keys.unshift(destination)
keys.push("AGGREGATE")
keys.push(options['aggregate'])
@redisConnection.zunionstore(keys, (err, reply) ->
callback(reply) if callback)
###
# Intersect leaderboards given by keys with this leaderboard into a named destination leaderboard.
#
# @param destination [String] Destination leaderboard name.
# @param keys [Array] Leaderboards to be merged with the current leaderboard.
# @param options [Hash] Options for intersecting the leaderboards.
# @param callback Callback for result of call.
###
intersectLeaderboards: (destination, keys, options = {'aggregate': 'sum'}, callback) ->
len = keys.length + 1
keys.unshift(@leaderboardName)
keys.unshift(len)
keys.unshift(destination)
keys.push("AGGREGATE")
keys.push(options['aggregate'])
@redisConnection.zinterstore(keys, (err, reply) ->
callback(reply) if callback)
###
# Key for retrieving optional member data.
#
# @param leaderboardName [String] Name of the leaderboard.
#
# @return a key in the form of +leaderboardName:member_data+
###
memberDataKey: (leaderboardName) ->
"#{leaderboardName}:#{@memberDataNamespace}"
module.exports = Leaderboard
| true | redis = require 'redis'
class Leaderboard
###
# Default page size: 25
###
@DEFAULT_PAGE_SIZE = 25
###
# Default options when creating a leaderboard. Page size is 25 and reverse
# is set to false, meaning various methods will return results in
# highest-to-lowest order.
###
DEFAULT_OPTIONS =
'pageSize': @DEFAULT_PAGE_SIZE
'reverse': false
'memberKey': 'PI:KEY:<KEY>END_PI'
'rankKey': 'PI:KEY:<KEY>END_PI'
'scoreKey': 'PI:KEY:<KEY>END_PI'
'memberDataKey': 'PI:KEY:<KEY>END_PI'
'memberDataNamespace': 'member_data'
###
# Default Redis host: localhost
###
@DEFAULT_REDIS_HOST = 'localhost'
###
# Default Redis post: 6379
###
@DEFAULT_REDIS_PORT = 6379
###
# Default Redis options when creating a connection to Redis. The
# +DEFAULT_REDIS_HOST+ and +DEFAULT_REDIS_PORT+ will be passed.
###
DEFAULT_REDIS_OPTIONS =
'host': @DEFAULT_REDIS_HOST
'port': @DEFAULT_REDIS_PORT
###
# Create a new instance of a leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param options [Hash] Options for the leaderboard such as +'pageSize'+.
# @param redisOptions [Hash] Options for configuring Redis.
###
constructor: (@leaderboardName, options = DEFAULT_OPTIONS, redisOptions = DEFAULT_REDIS_OPTIONS) ->
@reverse = options['reverse']
@pageSize = options['pageSize']
if @pageSize == null || @pageSize < 1
@pageSize = Leaderboard.DEFAULT_PAGE_SIZE
@memberKeyOption = options['memberKey'] || 'PI:KEY:<KEY>END_PI'
@rankKeyOption = options['rankKey'] || 'PI:KEY:<KEY>END_PI'
@scoreKeyOption = options['scoreKey'] || 'PI:KEY:<KEY>END_PI'
@memberDataKeyOption = options['memberDataKey'] || 'PI:KEY:<KEY>END_PI'
@memberDataNamespace = options['memberDataNamespace'] || 'member_data'
@redisConnection = redisOptions['redis_connection']
if @redisConnection?
delete redisOptions['redis_connection']
@redisConnection = redis.createClient(redisOptions['port'], redisOptions['host']) unless @redisConnection?
###
# Disconnect the Redis connection.
###
disconnect: ->
@redisConnection.quit((err, reply) -> )
###
# Delete the current leaderboard.
#
# @param callback Optional callback for result of call.
###
deleteLeaderboard: (callback) ->
this.deleteLeaderboardNamed(@leaderboardName, callback)
###
# Delete the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param callback Optional callback for result of call.
###
deleteLeaderboardNamed: (leaderboardName, callback) ->
transaction = @redisConnection.multi()
transaction.del(leaderboardName)
transaction.del(this.memberDataKey(leaderboardName))
transaction.exec((err, reply) ->
callback(reply) if callback)
###
# Rank a member in the leaderboard.
#
# @param member [String] Member name.
# @param score [float] Member score.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
rankMember: (member, score, memberData = null, callback) ->
this.rankMemberIn(@leaderboardName, member, score, memberData, callback)
###
# Rank a member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param score [float] Member score.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
rankMemberIn: (leaderboardName, member, score, memberData = null, callback) ->
transaction = @redisConnection.multi()
transaction.zadd(leaderboardName, score, member)
transaction.hset(this.memberDataKey(leaderboardName), member, memberData) if memberData?
transaction.exec((err, reply) ->
callback(reply) if callback)
###
# Rank a member across multiple leaderboards.
#
# @param leaderboards [Array] Leaderboard names.
# @param member [String] Member name.
# @param score [float] Member score.
# @param member_data [String] Optional member data.
###
rankMemberAcross: (leaderboardNames, member, score, memberData = null, callback) ->
transaction = @redisConnection.multi()
for leaderboardName in leaderboardNames
transaction.zadd(leaderboardName, score, member)
transaction.hset(this.memberDataKey(leaderboardName), member, memberData) if memberData?
transaction.exec((err, reply) ->
callback(reply) if callback)
###
# Rank a member in the leaderboard based on execution of the +rankConditional+.
#
# The +rankConditional+ is passed the following parameters:
# member: Member name.
# currentScore: Current score for the member in the leaderboard.
# score: Member score.
# memberData: Optional member data.
# options: Leaderboard options, e.g. 'reverse': Value of reverse option
#
# @param rankConditional [Function] Function which must return +true+ or +false+ that controls whether or not the member is ranked in the leaderboard.
# @param member [String] Member name.
# @param score [float] Member score.
# @param currentScore [float] Current score.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
rankMemberIf: (rankConditional, member, score, currentScore, memberData = null, callback) ->
this.rankMemberIfIn(@leaderboardName, rankConditional, member, score, currentScore, memberData, callback)
###
# Rank a member in the named leaderboard based on execution of the +rankConditional+.
#
# The +rankConditional+ is passed the following parameters:
# member: Member name.
# currentScore: Current score for the member in the leaderboard.
# score: Member score.
# memberData: Optional member data.
# options: Leaderboard options, e.g. 'reverse': Value of reverse option
#
# @param leaderboardName [String] Name of the leaderboard.
# @param rankConditional [Function] Function which must return +true+ or +false+ that controls whether or not the member is ranked in the leaderboard.
# @param member [String] Member name.
# @param score [float] Member score.
# @param currentScore [float] Current score.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
rankMemberIfIn: (leaderboardName, rankConditional, member, score, currentScore, memberData = null, callback) ->
if rankConditional(member, currentScore, score, memberData, {'reverse': @reverse})
this.rankMemberIn(leaderboardName, member, score, memberData, callback)
else
callback(0) if callback
###
# Rank an array of members in the leaderboard.
#
# @param membersAndScores [Array] Variable list of members and scores.
# @param callback Optional callback for result of call.
###
rankMembers: (membersAndScores, callback) ->
this.rankMembersIn(@leaderboardName, membersAndScores, callback)
###
# Rank an array of members in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param membersAndScores [Array] Variable list of members and scores
# @param callback Optional callback for result of call.
###
rankMembersIn: (leaderboardName, membersAndScores, callback) ->
transaction = @redisConnection.multi()
for index in [0...membersAndScores.length] by 2
slice = membersAndScores[index...index + 2]
transaction.zadd(leaderboardName, slice[1], slice[0])
transaction.exec((err, reply) ->
callback(reply) if callback)
###
# Retrieve the optional member data for a given member in the leaderboard.
#
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return String of optional member data.
###
memberDataFor: (member, callback) ->
this.memberDataForIn(@leaderboardName, member, callback)
###
# Retrieve the optional member data for a given member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return String of optional member data.
###
memberDataForIn: (leaderboardName, member, callback) ->
@redisConnection.hget(this.memberDataKey(leaderboardName), member, (err, reply) ->
callback(reply))
###
# Update the optional member data for a given member in the leaderboard.
#
# @param member [String] Member name.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
updateMemberData: (member, memberData, callback) ->
this.updateMemberDataFor(@leaderboardName, member, memberData, callback)
###
# Update the optional member data for a given member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param memberData [String] Optional member data.
# @param callback Optional callback for result of call.
###
updateMemberDataFor: (leaderboardName, member, memberData, callback) ->
@redisConnection.hset(this.memberDataKey(leaderboardName), member, memberData, (err, reply) ->
callback(reply) if callback)
###
# Remove the optional member data for a given member in the leaderboard.
#
# @param member [String] Member name.
# @param callback Optional callback for result of call.
###
removeMemberData: (member, callback) ->
this.remberMemberDataFor(@leaderboardName, member, callback)
###
# Remove the optional member data for a given member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Optional callback for result of call.
###
remberMemberDataFor: (leaderboardName, member, callback) ->
@redisConnection.hdel(this.memberDataKey(leaderboardName), member, (err, reply) ->
callback(reply) if callback)
###
# Remove a member from the leaderboard.
#
# @param member [String] Member name.
# @param callback Optional callback for result of call.
###
removeMember: (member, callback) ->
this.removeMemberFrom(@leaderboardName, member, callback)
###
# Remove a member from the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Optional callback for result of call.
###
removeMemberFrom: (leaderboardName, member, callback) ->
transaction = @redisConnection.multi()
transaction.zrem(leaderboardName, member)
transaction.hdel(this.memberDataKey(leaderboardName), member)
transaction.exec((err, reply) ->
callback(reply) if callback)
###
# Retrieve the total number of members in the leaderboard.
#
# @return total number of members in the leaderboard.
# @param callback Callback for result of call.
###
totalMembers: (callback) ->
this.totalMembersIn(@leaderboardName, callback)
###
# Retrieve the total number of members in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param callback Callback for result of call.
#
# @return the total number of members in the named leaderboard.
###
totalMembersIn: (leaderboardName, callback) ->
@redisConnection.zcard(leaderboardName, (err, reply) ->
callback(reply))
###
# Retrieve the total number of pages in the leaderboard.
#
# @param pageSize [int, nil] Page size to be used when calculating the total number of pages.
# @param callback Callback for result of call.
#
# @return the total number of pages in the leaderboard.
###
totalPages: (pageSize = null, callback) ->
this.totalPagesIn(@leaderboardName, pageSize, callback)
###
# Retrieve the total number of pages in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param pageSize [int, nil] Page size to be used when calculating the total number of pages.
# @param callback Callback for result of call.
#
# @return the total number of pages in the named leaderboard.
###
totalPagesIn: (leaderboardName, pageSize = null, callback) ->
unless pageSize?
pageSize = @pageSize
@redisConnection.zcard(leaderboardName, (err, reply) ->
callback(Math.ceil(reply / pageSize)))
###
# Retrieve the total members in a given score range from the leaderboard.
#
# @param minScore [float] Minimum score.
# @param maxScore [float] Maximum score.
# @param callback Callback for result of call.
#
# @return the total members in a given score range from the leaderboard.
###
totalMembersInScoreRange: (minScore, maxScore, callback) ->
this.totalMembersInScoreRangeIn(@leaderboardName, minScore, maxScore, callback)
###
# Retrieve the total members in a given score range from the named leaderboard.
#
# @param leaderboard_name Name of the leaderboard.
# @param minScore [float] Minimum score.
# @param maxScore [float] Maximum score.
# @param callback Callback for result of call.
#
# @return the total members in a given score range from the named leaderboard.
###
totalMembersInScoreRangeIn: (leaderboardName, minScore, maxScore, callback) ->
@redisConnection.zcount(leaderboardName, minScore, maxScore, (err, reply) ->
callback(reply))
###
# Change the score for a member in the leaderboard by a score delta which can be positive or negative.
#
# @param member [String] Member name.
# @param delta [float] Score change.
# @param callback Optional callback for result of call.
###
changeScoreFor: (member, delta, callback) ->
this.changeScoreForMemberIn(@leaderboardName, member, delta, callback)
###
# Change the score for a member in the named leaderboard by a delta which can be positive or negative.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param delta [float] Score change.
# @param callback Optional callback for result of call.
###
changeScoreForMemberIn: (leaderboardName, member, delta, callback) ->
@redisConnection.zincrby(leaderboardName, delta, member, (err, reply) ->
callback(reply) if callback)
###
# Retrieve the rank for a member in the leaderboard.
#
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the rank for a member in the leaderboard.
###
rankFor: (member, callback) ->
this.rankForIn(@leaderboardName, member, callback)
###
# Retrieve the rank for a member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the rank for a member in the leaderboard.
###
rankForIn: (leaderboardName, member, callback) ->
process_response = (err, reply) ->
if reply?
callback(reply + 1)
else
callback()
if @reverse
@redisConnection.zrank(leaderboardName, member, process_response)
else
@redisConnection.zrevrank(leaderboardName, member, process_response)
###
# Retrieve the score for a member in the leaderboard.
#
# @param member Member name.
# @param callback Callback for result of call.
#
# @return the score for a member in the leaderboard or +nil+ if the member is not in the leaderboard.
###
scoreFor: (member, callback) ->
this.scoreForIn(@leaderboardName, member, callback)
###
# Retrieve the score for a member in the named leaderboard.
#
# @param leaderboardName Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the score for a member in the leaderboard or +nil+ if the member is not in the leaderboard.
###
scoreForIn: (leaderboardName, member, callback) ->
@redisConnection.zscore(leaderboardName, member, (err, reply) ->
if reply?
callback(parseFloat(reply))
else
callback(null))
###
# Check to see if a member exists in the leaderboard.
#
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return +true+ if the member exists in the leaderboard, +false+ otherwise.
###
checkMember: (member, callback) ->
this.checkMemberIn(@leaderboardName, member, callback)
###
# Check to see if a member exists in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return +true+ if the member exists in the named leaderboard, +false+ otherwise.
###
checkMemberIn: (leaderboardName, member, callback) ->
@redisConnection.zscore(leaderboardName, member, (err, reply) ->
callback(reply?))
###
# Retrieve the score and rank for a member in the leaderboard.
#
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the score and rank for a member in the leaderboard as a Hash.
###
scoreAndRankFor: (member, callback) ->
this.scoreAndRankForIn(@leaderboardName, member, callback)
###
# Retrieve the score and rank for a member in the named leaderboard.
#
# @param leaderboardName [String]Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the score and rank for a member in the named leaderboard as a Hash.
###
scoreAndRankForIn: (leaderboardName, member, callback) ->
transaction = @redisConnection.multi()
transaction.zscore(leaderboardName, member)
if @reverse
transaction.zrank(leaderboardName, member)
else
transaction.zrevrank(leaderboardName, member)
transaction.exec((err, replies) =>
if replies
scoreAndRankData = {}
if replies[0]?
scoreAndRankData[@scoreKeyOption] = parseFloat(replies[0])
else
scoreAndRankData[@scoreKeyOption] = null
if replies[1]?
scoreAndRankData[@rankKeyOption] = replies[1] + 1
else
scoreAndRankData[@rankKeyOption] = null
scoreAndRankData[@memberKeyOption] = member
callback(scoreAndRankData))
###
# Remove members from the leaderboard in a given score range.
#
# @param minScore [float] Minimum score.
# @param maxScore [float] Maximum score.
# @param callback Optional callback for result of call.
###
removeMembersInScoreRange: (minScore, maxScore, callback) ->
this.removeMembersInScoreRangeIn(@leaderboardName, minScore, maxScore, callback)
###
# Remove members from the named leaderboard in a given score range.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param minScore [float] Minimum score.
# @param maxScore [float] Maximum score.
# @param callback Optional callback for result of call.
###
removeMembersInScoreRangeIn: (leaderboardName, minScore, maxScore, callback) ->
@redisConnection.zremrangebyscore(leaderboardName, minScore, maxScore, (err, reply) ->
callback(reply) if callback)
###
# Remove members from the leaderboard outside a given rank.
#
# @param rank [int] The rank (inclusive) which we should keep.
# @param callback Optional callback for result of call.
# @return the total number of members removed.
###
removeMembersOutsideRank: (rank, callback) ->
this.removeMembersOutsideRankIn(@leaderboardName, rank, callback)
###
# Remove members from the leaderboard outside a given rank.
#
# @param leaderboard_name [String] Name of the leaderboard.
# @param rank [int] The rank (inclusive) which we should keep.
# @param callback Optional callback for result of call.
# @return the total number of members removed.
###
removeMembersOutsideRankIn: (leaderboardName, rank, callback) ->
if @reverse
@redisConnection.zremrangebyrank(leaderboardName, rank, -1, (err, reply) ->
callback(reply) if callback)
else
@redisConnection.zremrangebyrank(leaderboardName, 0, -(rank) - 1, (err, reply) ->
callback(reply) if callback)
###
# Retrieve the percentile for a member in the leaderboard.
#
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the percentile for a member in the leaderboard. Return +nil+ for a non-existent member.
###
percentileFor: (member, callback) ->
this.percentileForIn(@leaderboardName, member, callback)
###
# Retrieve the percentile for a member in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param callback Callback for result of call.
#
# @return the percentile for a member in the named leaderboard.
###
percentileForIn: (leaderboardName, member, callback) ->
this.checkMemberIn(leaderboardName, member, (reply) =>
if reply
transaction = @redisConnection.multi()
transaction.zcard(leaderboardName)
transaction.zrevrank(leaderboardName, member)
transaction.exec((err, replies) ->
if replies
percentile = Math.ceil(parseFloat((parseFloat(replies[0] - replies[1] - 1)) / parseFloat(replies[0]) * 100))
if @reverse
callback(100 - percentile)
else
callback(percentile)
)
else
callback()
)
###
# Calculate the score for a given percentile value in the leaderboard.
#
# @param percentile [float] Percentile value (0.0 to 100.0 inclusive)
# @param callback Callback for result of call.
#
# @return the calculated score for the requested percentile value. Return +nil+ for an invalid (outside 0-100) percentile or a leaderboard with no members.
###
scoreForPercentile: (percentile, callback) ->
this.scoreForPercentileIn(@leaderboardName, percentile, callback)
###
# Calculate the score for a given percentile value in the leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param percentile [float] Percentile value (0.0 to 100.0 inclusive)
# @param callback Callback for result of call.
#
# @return the calculated score for the requested percentile value. Return +nil+ for an invalid (outside 0-100) percentile or a leaderboard with no members.
###
scoreForPercentileIn: (leaderboardName, percentile, callback) ->
unless 0 <= percentile <= 100
return callback()
if @reverse
percentile = 100 - percentile
this.totalMembersIn(leaderboardName, (reply) =>
totalMembers = reply
if totalMembers == 0
return callback()
else
index = (totalMembers - 1) * (percentile / 100)
zrange_args = [leaderboardName, Math.floor(index), Math.ceil(index), 'WITHSCORES']
@redisConnection.zrange(zrange_args, (err, reply) ->
# Response format: ["PI:NAME:<NAME>END_PI", "123", "PI:NAME:<NAME>END_PI", "456"] (i.e. flat list, not member/score tuples)
lowScore = parseFloat(reply[1])
if index == Math.floor(index)
callback(lowScore)
else
interpolateFraction = index - Math.floor(index)
hiScore = parseFloat(reply[3])
callback(lowScore + interpolateFraction * (hiScore - lowScore))
)
)
###
# Determine the page where a member falls in the leaderboard.
#
# @param member [String] Member name.
# @param pageSize [int] Page size to be used in determining page location.
# @param callback Callback for result of call.
#
# @return the page where a member falls in the leaderboard.
###
pageFor: (member, pageSize = @DEFAULT_PAGE_SIZE, callback) ->
this.pageForIn(@leaderboardName, member, pageSize, callback)
###
# Determine the page where a member falls in the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param pageSize [int] Page size to be used in determining page location.
# @param callback Callback for result of call.
#
# @return the page where a member falls in the leaderboard.
###
pageForIn: (leaderboardName, member, pageSize = @DEFAULT_PAGE_SIZE, callback) ->
transaction = @redisConnection.multi()
if @reverse
transaction.zrank(leaderboardName, member)
else
transaction.zrevrank(leaderboardName, member)
transaction.exec((err, replies) ->
rankForMember = replies[0]
if rankForMember?
rankForMember += 1
else
rankForMember = 0
callback(Math.ceil(rankForMember / pageSize))
)
###
# Expire the current leaderboard in a set number of seconds. Do not use this with
# leaderboards that utilize member data as there is no facility to cascade the
# expiration out to the keys for the member data.
#
# @param seconds [int] Number of seconds after which the leaderboard will be expired.
# @param callback Optional callback for result of call.
###
expireLeaderboard: (seconds, callback) ->
this.expireLeaderboardFor(@leaderboardName, seconds, callback)
###
# Expire the given leaderboard in a set number of seconds. Do not use this with
# leaderboards that utilize member data as there is no facility to cascade the
# expiration out to the keys for the member data.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param seconds [int] Number of seconds after which the leaderboard will be expired.
# @param callback Optional callback for result of call.
###
expireLeaderboardFor: (leaderboardName, seconds, callback) ->
transaction = @redisConnection.multi()
transaction.expire(leaderboardName, seconds)
transaction.expire(this.memberDataKey(leaderboardName), seconds)
transaction.exec((err, replies) ->
callback(replies) if callback)
###
# Expire the current leaderboard at a specific UNIX timestamp. Do not use this with
# leaderboards that utilize member data as there is no facility to cascade the
# expiration out to the keys for the member data.
#
# @param timestamp [int] UNIX timestamp at which the leaderboard will be expired.
# @param callback Optional callback for result of call.
###
expireLeaderboardAt: (timestamp, callback) ->
this.expireLeaderboardAtFor(@leaderboardName, timestamp, callback)
###
# Expire the given leaderboard at a specific UNIX timestamp. Do not use this with
# leaderboards that utilize member data as there is no facility to cascade the
# expiration out to the keys for the member data.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param timestamp [int] UNIX timestamp at which the leaderboard will be expired.
# @param callback Optional callback for result of call.
###
expireLeaderboardAtFor: (leaderboardName, timestamp, callback) ->
transaction = @redisConnection.multi()
transaction.expireat(leaderboardName, timestamp)
transaction.expireat(this.memberDataKey(leaderboardName), timestamp)
transaction.exec((err, replies) ->
callback(replies) if callback)
###
# Retrieve a page of leaders from the leaderboard for a given list of members.
#
# @param members [Array] Member names.
# @param options [Hash] Options to be used when retrieving the page from the leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the leaderboard for a given list of members.
###
rankedInList: (members, options = {}, callback) ->
this.rankedInListIn(@leaderboardName, members, options, callback)
###
# Retrieve a page of leaders from the named leaderboard for a given list of members.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param members [Array] Member names.
# @param options [Hash] Options to be used when retrieving the page from the named leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the named leaderboard for a given list of members.
###
rankedInListIn: (leaderboardName, members, options = {}, callback) ->
if not members? or members.length == 0
return callback([])
ranksForMembers = []
transaction = @redisConnection.multi()
unless options['membersOnly']
for member in members
if @reverse
transaction.zrank(leaderboardName, member)
else
transaction.zrevrank(leaderboardName, member)
transaction.zscore(leaderboardName, member)
transaction.exec((err, replies) =>
for member, index in members
do (member) =>
data = {}
data[@memberKeyOption] = member
unless options['membersOnly']
data[@rankKeyOption] = replies[index * 2] + 1
if replies[index * 2 + 1]
data[@scoreKeyOption] = parseFloat(replies[index * 2 + 1])
else
data[@scoreKeyOption] = null
data[@rankKeyOption] = null
# Retrieve optional member data based on options['withMemberData']
if options['withMemberData']
this.memberDataForIn leaderboardName, member, (memberdata) =>
data[@memberDataKeyOption] = memberdata
ranksForMembers.push(data)
# Sort if options['sortBy']
if ranksForMembers.length == members.length
switch options['sortBy']
when 'rank'
ranksForMembers.sort((a, b) ->
a.rank > b.rank)
when 'score'
ranksForMembers.sort((a, b) ->
a.score > b.score)
callback(ranksForMembers)
else
ranksForMembers.push(data)
# Sort if options['sortBy']
if ranksForMembers.length == members.length
switch options['sortBy']
when 'rank'
ranksForMembers.sort((a, b) ->
a.rank > b.rank)
when 'score'
ranksForMembers.sort((a, b) ->
a.score > b.score)
callback(ranksForMembers)
)
###
# Retrieve a page of leaders from the leaderboard.
#
# @param currentPage [int] Page to retrieve from the leaderboard.
# @param options [Hash] Options to be used when retrieving the page from the leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the leaderboard.
###
leaders: (currentPage, options = {}, callback) ->
this.leadersIn(@leaderboardName, currentPage, options, callback)
###
# Retrieve a page of leaders from the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param currentPage [int] Page to retrieve from the named leaderboard.
# @param options [Hash] Options to be used when retrieving the page from the named leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the named leaderboard.
###
leadersIn: (leaderboardName, currentPage, options = {}, callback) ->
currentPage = 1 if currentPage < 1
pageSize = options['pageSize'] || @pageSize
this.totalPages(pageSize, (totalPages) =>
if currentPage > totalPages
currentPage = totalPages
indexForRedis = currentPage - 1
startingOffset = (indexForRedis * pageSize)
endingOffset = (startingOffset + pageSize) - 1
if @reverse
@redisConnection.zrange(leaderboardName, startingOffset, endingOffset, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
@redisConnection.zrevrange(leaderboardName, startingOffset, endingOffset, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
)
###
# Retrieve all leaders from the leaderboard.
#
# @param options [Hash] Options to be used when retrieving the leaders from the leaderboard.
# @param callback Callback for result of call.
#
# @return the leaders from the leaderboard.
###
allLeaders: (options = {}, callback) ->
this.allLeadersFrom(@leaderboardName, options, callback)
###
# Retrieves all leaders from the named leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param options [Hash] Options to be used when retrieving the leaders from the named leaderboard.
# @param callback Callback for result of call.
#
# @return the named leaderboard.
###
allLeadersFrom: (leaderboardName, options = {}, callback) ->
if @reverse
@redisConnection.zrange(leaderboardName, 0, -1, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
@redisConnection.zrevrange(leaderboardName, 0, -1, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
###
# Retrieve members from the leaderboard within a given score range.
#
# @param minimumScore [float] Minimum score (inclusive).
# @param maximumScore [float] Maximum score (inclusive).
# @param options [Hash] Options to be used when retrieving the data from the leaderboard.
# @param callback Callback for result of call.
#
# @return members from the leaderboard that fall within the given score range.
###
membersFromScoreRange: (minimumScore, maximumScore, options = {}, callback) ->
this.membersFromScoreRangeIn(@leaderboardName, minimumScore, maximumScore, options, callback)
###
# Retrieve members from the named leaderboard within a given score range.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param minimumScore [float] Minimum score (inclusive).
# @param maximumScore [float] Maximum score (inclusive).
# @param options [Hash] Options to be used when retrieving the data from the leaderboard.
# @param callback Callback for result of call.
#
# @return members from the leaderboard that fall within the given score range.
###
membersFromScoreRangeIn: (leaderboardName, minimumScore, maximumScore, options = {}, callback) ->
if @reverse
@redisConnection.zrangebyscore(leaderboardName, minimumScore, maximumScore, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
@redisConnection.zrevrangebyscore(leaderboardName, maximumScore, minimumScore, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
###
# Retrieve members from the leaderboard within a given rank range.
#
# @param startingRank [int] Starting rank (inclusive).
# @param endingRank [int] Ending rank (inclusive).
# @param options [Hash] Options to be used when retrieving the data from the leaderboard.
# @param callback Callback for result of call.
#
# @return members from the leaderboard that fall within the given rank range.
###
membersFromRankRange: (startingRank, endingRank, options = {}, callback) ->
this.membersFromRankRangeIn(@leaderboardName, startingRank, endingRank, options, callback)
###
# Retrieve members from the named leaderboard within a given rank range.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param startingRank [int] Starting rank (inclusive).
# @param endingRank [int] Ending rank (inclusive).
# @param options [Hash] Options to be used when retrieving the data from the leaderboard.
# @param callback Callback for result of call.
#
# @return members from the leaderboard that fall within the given rank range.
###
membersFromRankRangeIn: (leaderboardName, startingRank, endingRank, options, callback) ->
startingRank -= 1
if startingRank < 0
startingRank = 0
endingRank -= 1
if endingRank < 0
endingRank = 0
if @reverse
@redisConnection.zrange(leaderboardName, startingRank, endingRank, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
@redisConnection.zrevrange(leaderboardName, startingRank, endingRank, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
###
# Retrieve a member at the specified index from the leaderboard.
#
# @param position [int] Position in leaderboard.
# @param options [Hash] Options to be used when retrieving the member from the leaderboard.
# @param callback Callback for result of call.
#
# @return a member from the leaderboard.
###
memberAt: (position, options = {}, callback) ->
this.memberAtIn(@leaderboardName, position, options, callback)
###
# Retrieve a member at the specified index from the leaderboard.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param position [int] Position in named leaderboard.
# @param options [Hash] Options to be used when retrieving the member from the named leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the named leaderboard.
###
memberAtIn: (leaderboardName, position, options = {}, callback) ->
this.membersFromRankRangeIn(leaderboardName, position, position, options, callback)
###
# Retrieve a page of leaders from the leaderboard around a given member.
#
# @param member [String] Member name.
# @param options [Hash] Options to be used when retrieving the page from the leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the leaderboard around a given member.
###
aroundMe: (member, options = {}, callback) ->
this.aroundMeIn(@leaderboardName, member, options, callback)
###
# Retrieve a page of leaders from the named leaderboard around a given member.
#
# @param leaderboardName [String] Name of the leaderboard.
# @param member [String] Member name.
# @param options [Hash] Options to be used when retrieving the page from the named leaderboard.
# @param callback Callback for result of call.
#
# @return a page of leaders from the named leaderboard around a given member. Returns an empty array for a non-existent member.
###
aroundMeIn: (leaderboardName, member, options = {}, callback) ->
pageSize = options['pageSize'] || @pageSize
if @reverse
@redisConnection.zrank(leaderboardName, member, (err, reply) =>
if reply?
startingOffset = parseInt(Math.ceil(reply - (pageSize / 2)))
startingOffset = 0 if startingOffset < 0
endingOffset = (startingOffset + pageSize) - 1
@redisConnection.zrange(leaderboardName, startingOffset, endingOffset, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
callback([])
[]
)
else
@redisConnection.zrevrank(leaderboardName, member, (err, reply) =>
if reply?
startingOffset = parseInt(Math.ceil(reply - (pageSize / 2)))
startingOffset = 0 if startingOffset < 0
endingOffset = (startingOffset + pageSize) - 1
@redisConnection.zrevrange(leaderboardName, startingOffset, endingOffset, (err, reply) =>
this.rankedInListIn(leaderboardName, reply, options, callback))
else
callback([])
[]
)
###
# Merge leaderboards given by keys with this leaderboard into a named destination leaderboard.
#
# @param destination [String] Destination leaderboard name.
# @param keys [Array] Leaderboards to be merged with the current leaderboard.
# @param options [Hash] Options for merging the leaderboards.
# @param callback Callback for result of call.
###
mergeLeaderboards: (destination, keys, options = {'aggregate': 'sum'}, callback) ->
len = keys.length + 1
keys.unshift(@leaderboardName)
keys.unshift(len)
keys.unshift(destination)
keys.push("AGGREGATE")
keys.push(options['aggregate'])
@redisConnection.zunionstore(keys, (err, reply) ->
callback(reply) if callback)
###
# Intersect leaderboards given by keys with this leaderboard into a named destination leaderboard.
#
# @param destination [String] Destination leaderboard name.
# @param keys [Array] Leaderboards to be merged with the current leaderboard.
# @param options [Hash] Options for intersecting the leaderboards.
# @param callback Callback for result of call.
###
intersectLeaderboards: (destination, keys, options = {'aggregate': 'sum'}, callback) ->
len = keys.length + 1
keys.unshift(@leaderboardName)
keys.unshift(len)
keys.unshift(destination)
keys.push("AGGREGATE")
keys.push(options['aggregate'])
@redisConnection.zinterstore(keys, (err, reply) ->
callback(reply) if callback)
###
# Key for retrieving optional member data.
#
# @param leaderboardName [String] Name of the leaderboard.
#
# @return a key in the form of +leaderboardName:member_data+
###
memberDataKey: (leaderboardName) ->
"#{leaderboardName}:#{@memberDataNamespace}"
module.exports = Leaderboard
|
[
{
"context": " getType: -> 'group'\n @stubs.user =\n name: 'name'\n real_name: 'real_name'\n id: 'U123'\n pr",
"end": 1032,
"score": 0.6846247911453247,
"start": 1028,
"tag": "NAME",
"value": "name"
},
{
"context": "\n @stubs.user =\n name: 'name'\n real_name: '... | test/stubs.coffee | fabchia/hubot | 0 | # Setup stubs used by the other tests
SlackBot = require '../src/bot'
SlackFormatter = require '../src/formatter'
SlackClient = require '../src/client'
{EventEmitter} = require 'events'
# Use Hubot's brain in our stubs
{Brain, Robot} = require 'hubot'
_ = require 'lodash'
# Stub a few interfaces to grease the skids for tests. These are intentionally
# as minimal as possible and only provide enough to make the tests possible.
# Stubs are recreated before each test.
beforeEach ->
@stubs = {}
@stubs.send = (room, msg, opts) =>
@stubs._room = room
@stubs._opts = opts
if /^[UD@][\d\w]+/.test(room)
@stubs._dmmsg = msg
else
@stubs._msg = msg
msg
@stubs.channel =
name: 'general'
id: 'C123'
sendMessage: (msg) -> msg
getType: -> 'channel'
@stubs.DM =
name: 'User'
id: 'D1232'
sendMessage: (msg) -> msg
getType: -> 'dm'
@stubs.group =
name: 'Group'
id: 'G12324'
sendMessage: (msg) -> msg
getType: -> 'group'
@stubs.user =
name: 'name'
real_name: 'real_name'
id: 'U123'
profile:
email: 'email@example.com'
misc: 'misc'
@stubs.bot =
name: 'testbot'
id: 'B123'
@stubs.userperiod =
name: 'name.lname'
id: 'U124'
profile:
email: 'name.lname@example.com'
@stubs.userhyphen =
name: 'name-lname'
id: 'U125'
profile:
email: 'name-lname@example.com'
@stubs.usernoprofile =
name: 'name'
real_name: 'real_name'
id: 'U126'
misc: 'misc'
@stubs.usernoemail =
name: 'name'
real_name: 'real_name'
id: 'U126'
profile:
foo: 'bar'
misc: 'misc'
@stubs.self =
name: 'self'
id: 'U456'
bot_id: 'B456'
profile:
email: 'self@example.com'
@stubs.self_bot =
name: 'self'
id: 'B456'
profile:
email: 'self@example.com'
@stubs.org_user_not_in_workspace =
name: 'name'
id: 'W123'
profile:
email: 'org_not_in_workspace@example.com'
@stubs.team =
name: 'Example Team'
# Slack client
@stubs.client =
dataStore:
getUserById: (id) =>
for user in @stubs.client.dataStore.users
return user if user.id is id
getBotById: (id) =>
for bot in @stubs.client.dataStore.bots
return bot if bot.id is id
getUserByName: (name) =>
for user in @stubs.client.dataStore.users
return user if user.name is name
getChannelById: (id) =>
@stubs.channel if @stubs.channel.id == id
getChannelGroupOrDMById: (id) =>
@stubs.channel if @stubs.channel.id == id
getChannelGroupOrDMByName: (name) =>
return @stubs.channel if @stubs.channel.name == name
for dm in @stubs.client.dataStore.dms
return dm if dm.name is name
users: [@stubs.user, @stubs.self, @stubs.userperiod, @stubs.userhyphen]
bots: [@stubs.bot]
dms: [
name: 'user2'
id: 'D5432'
]
@stubs.rtm =
login: =>
@stubs._connected = true
start: =>
@stubs._connected = true
on: (name, callback) =>
console.log("#####")
console.log(name)
console.log(callback)
callback(name)
removeListener: (name) =>
sendMessage: (msg, room) =>
@stubs.send room, msg
dataStore:
getUserById: (id) =>
switch id
when @stubs.user.id then @stubs.user
when @stubs.bot.id then @stubs.bot
when @stubs.self.id then @stubs.self
when @stubs.self_bot.id then @stubs.self_bot
else undefined
getChannelByName: (name) =>
switch name
when 'known_room' then {id: 'C00000004'}
else undefined
getChannelGroupOrDMById: (id) =>
switch id
when @stubs.channel.id then @stubs.channel
when @stubs.DM.id then @stubs.DM
@stubs.chatMock =
postMessage: (msg, room, opts) =>
@stubs.send(msg, room, opts)
@stubs.channelsMock =
setTopic: (id, topic) =>
@stubs._topic = topic
@stubs.responseUsersList =
ok: true
members: [@stubs.user, @stubs.userperiod]
@stubs.wrongResponseUsersList =
ok: false
# Hubot.Robot instance
@stubs.robot = do ->
robot = new EventEmitter
# noop the logging
robot.logger =
logs: {}
log: (type, message) ->
@logs[type] ?= []
@logs[type].push(message)
info: (message) ->
@log('info', message)
debug: (message) ->
@log('debug', message)
error: (message) ->
@log('error', message)
# record all received messages
robot.received = []
robot.receive = (msg) ->
@received.push msg
# attach a real Brain to the robot
robot.brain = new Brain robot
robot.name = 'bot'
robot.listeners = []
robot.listen = Robot.prototype.listen.bind(robot)
robot.react = Robot.prototype.react.bind(robot)
robot
@stubs.callback = do ->
return "done"
@stubs.receiveMock =
receive: (message, user) =>
@stubs._received = message
# Generate a new slack instance for each test.
@slackbot = new SlackBot @stubs.robot, token: 'xoxb-faketoken'
_.merge @slackbot.client, @stubs.client
_.merge @slackbot.client.rtm, @stubs.rtm
_.merge @slackbot.client.web.chat, @stubs.chatMock
_.merge @slackbot.client.web.channels, @stubs.channelsMock
_.merge @slackbot, @stubs.receiveMock
@slackbot.self = @stubs.self
@formatter = new SlackFormatter @stubs.client.dataStore
@client = new SlackClient {token: 'xoxb-faketoken'}, @stubs.robot
_.merge @client.rtm, @stubs.rtm
_.merge @client.web.chat, @stubs.chatMock
_.merge @client.web.channels, @stubs.channelsMock
| 221763 | # Setup stubs used by the other tests
SlackBot = require '../src/bot'
SlackFormatter = require '../src/formatter'
SlackClient = require '../src/client'
{EventEmitter} = require 'events'
# Use Hubot's brain in our stubs
{Brain, Robot} = require 'hubot'
_ = require 'lodash'
# Stub a few interfaces to grease the skids for tests. These are intentionally
# as minimal as possible and only provide enough to make the tests possible.
# Stubs are recreated before each test.
beforeEach ->
@stubs = {}
@stubs.send = (room, msg, opts) =>
@stubs._room = room
@stubs._opts = opts
if /^[UD@][\d\w]+/.test(room)
@stubs._dmmsg = msg
else
@stubs._msg = msg
msg
@stubs.channel =
name: 'general'
id: 'C123'
sendMessage: (msg) -> msg
getType: -> 'channel'
@stubs.DM =
name: 'User'
id: 'D1232'
sendMessage: (msg) -> msg
getType: -> 'dm'
@stubs.group =
name: 'Group'
id: 'G12324'
sendMessage: (msg) -> msg
getType: -> 'group'
@stubs.user =
name: '<NAME>'
real_name: '<NAME>'
id: 'U123'
profile:
email: '<EMAIL>'
misc: 'misc'
@stubs.bot =
name: 'testbot'
id: 'B123'
@stubs.userperiod =
name: 'name.lname'
id: 'U124'
profile:
email: '<EMAIL>'
@stubs.userhyphen =
name: 'name-lname'
id: 'U125'
profile:
email: '<EMAIL>'
@stubs.usernoprofile =
name: '<NAME>'
real_name: '<NAME>_<NAME>'
id: 'U126'
misc: 'misc'
@stubs.usernoemail =
name: 'name'
real_name: 'real_name'
id: 'U126'
profile:
foo: 'bar'
misc: 'misc'
@stubs.self =
name: 'self'
id: 'U456'
bot_id: 'B456'
profile:
email: '<EMAIL>'
@stubs.self_bot =
name: 'self'
id: 'B456'
profile:
email: '<EMAIL>'
@stubs.org_user_not_in_workspace =
name: 'name'
id: 'W123'
profile:
email: '<EMAIL>'
@stubs.team =
name: 'Example Team'
# Slack client
@stubs.client =
dataStore:
getUserById: (id) =>
for user in @stubs.client.dataStore.users
return user if user.id is id
getBotById: (id) =>
for bot in @stubs.client.dataStore.bots
return bot if bot.id is id
getUserByName: (name) =>
for user in @stubs.client.dataStore.users
return user if user.name is name
getChannelById: (id) =>
@stubs.channel if @stubs.channel.id == id
getChannelGroupOrDMById: (id) =>
@stubs.channel if @stubs.channel.id == id
getChannelGroupOrDMByName: (name) =>
return @stubs.channel if @stubs.channel.name == name
for dm in @stubs.client.dataStore.dms
return dm if dm.name is name
users: [@stubs.user, @stubs.self, @stubs.userperiod, @stubs.userhyphen]
bots: [@stubs.bot]
dms: [
name: 'user2'
id: 'D5432'
]
@stubs.rtm =
login: =>
@stubs._connected = true
start: =>
@stubs._connected = true
on: (name, callback) =>
console.log("#####")
console.log(name)
console.log(callback)
callback(name)
removeListener: (name) =>
sendMessage: (msg, room) =>
@stubs.send room, msg
dataStore:
getUserById: (id) =>
switch id
when @stubs.user.id then @stubs.user
when @stubs.bot.id then @stubs.bot
when @stubs.self.id then @stubs.self
when @stubs.self_bot.id then @stubs.self_bot
else undefined
getChannelByName: (name) =>
switch name
when 'known_room' then {id: 'C00000004'}
else undefined
getChannelGroupOrDMById: (id) =>
switch id
when @stubs.channel.id then @stubs.channel
when @stubs.DM.id then @stubs.DM
@stubs.chatMock =
postMessage: (msg, room, opts) =>
@stubs.send(msg, room, opts)
@stubs.channelsMock =
setTopic: (id, topic) =>
@stubs._topic = topic
@stubs.responseUsersList =
ok: true
members: [@stubs.user, @stubs.userperiod]
@stubs.wrongResponseUsersList =
ok: false
# Hubot.Robot instance
@stubs.robot = do ->
robot = new EventEmitter
# noop the logging
robot.logger =
logs: {}
log: (type, message) ->
@logs[type] ?= []
@logs[type].push(message)
info: (message) ->
@log('info', message)
debug: (message) ->
@log('debug', message)
error: (message) ->
@log('error', message)
# record all received messages
robot.received = []
robot.receive = (msg) ->
@received.push msg
# attach a real Brain to the robot
robot.brain = new Brain robot
robot.name = 'bot'
robot.listeners = []
robot.listen = Robot.prototype.listen.bind(robot)
robot.react = Robot.prototype.react.bind(robot)
robot
@stubs.callback = do ->
return "done"
@stubs.receiveMock =
receive: (message, user) =>
@stubs._received = message
# Generate a new slack instance for each test.
@slackbot = new SlackBot @stubs.robot, token: '<PASSWORD>'
_.merge @slackbot.client, @stubs.client
_.merge @slackbot.client.rtm, @stubs.rtm
_.merge @slackbot.client.web.chat, @stubs.chatMock
_.merge @slackbot.client.web.channels, @stubs.channelsMock
_.merge @slackbot, @stubs.receiveMock
@slackbot.self = @stubs.self
@formatter = new SlackFormatter @stubs.client.dataStore
@client = new SlackClient {token: '<PASSWORD>'}, @stubs.robot
_.merge @client.rtm, @stubs.rtm
_.merge @client.web.chat, @stubs.chatMock
_.merge @client.web.channels, @stubs.channelsMock
| true | # Setup stubs used by the other tests
SlackBot = require '../src/bot'
SlackFormatter = require '../src/formatter'
SlackClient = require '../src/client'
{EventEmitter} = require 'events'
# Use Hubot's brain in our stubs
{Brain, Robot} = require 'hubot'
_ = require 'lodash'
# Stub a few interfaces to grease the skids for tests. These are intentionally
# as minimal as possible and only provide enough to make the tests possible.
# Stubs are recreated before each test.
beforeEach ->
@stubs = {}
@stubs.send = (room, msg, opts) =>
@stubs._room = room
@stubs._opts = opts
if /^[UD@][\d\w]+/.test(room)
@stubs._dmmsg = msg
else
@stubs._msg = msg
msg
@stubs.channel =
name: 'general'
id: 'C123'
sendMessage: (msg) -> msg
getType: -> 'channel'
@stubs.DM =
name: 'User'
id: 'D1232'
sendMessage: (msg) -> msg
getType: -> 'dm'
@stubs.group =
name: 'Group'
id: 'G12324'
sendMessage: (msg) -> msg
getType: -> 'group'
@stubs.user =
name: 'PI:NAME:<NAME>END_PI'
real_name: 'PI:NAME:<NAME>END_PI'
id: 'U123'
profile:
email: 'PI:EMAIL:<EMAIL>END_PI'
misc: 'misc'
@stubs.bot =
name: 'testbot'
id: 'B123'
@stubs.userperiod =
name: 'name.lname'
id: 'U124'
profile:
email: 'PI:EMAIL:<EMAIL>END_PI'
@stubs.userhyphen =
name: 'name-lname'
id: 'U125'
profile:
email: 'PI:EMAIL:<EMAIL>END_PI'
@stubs.usernoprofile =
name: 'PI:NAME:<NAME>END_PI'
real_name: 'PI:NAME:<NAME>END_PI_PI:NAME:<NAME>END_PI'
id: 'U126'
misc: 'misc'
@stubs.usernoemail =
name: 'name'
real_name: 'real_name'
id: 'U126'
profile:
foo: 'bar'
misc: 'misc'
@stubs.self =
name: 'self'
id: 'U456'
bot_id: 'B456'
profile:
email: 'PI:EMAIL:<EMAIL>END_PI'
@stubs.self_bot =
name: 'self'
id: 'B456'
profile:
email: 'PI:EMAIL:<EMAIL>END_PI'
@stubs.org_user_not_in_workspace =
name: 'name'
id: 'W123'
profile:
email: 'PI:EMAIL:<EMAIL>END_PI'
@stubs.team =
name: 'Example Team'
# Slack client
@stubs.client =
dataStore:
getUserById: (id) =>
for user in @stubs.client.dataStore.users
return user if user.id is id
getBotById: (id) =>
for bot in @stubs.client.dataStore.bots
return bot if bot.id is id
getUserByName: (name) =>
for user in @stubs.client.dataStore.users
return user if user.name is name
getChannelById: (id) =>
@stubs.channel if @stubs.channel.id == id
getChannelGroupOrDMById: (id) =>
@stubs.channel if @stubs.channel.id == id
getChannelGroupOrDMByName: (name) =>
return @stubs.channel if @stubs.channel.name == name
for dm in @stubs.client.dataStore.dms
return dm if dm.name is name
users: [@stubs.user, @stubs.self, @stubs.userperiod, @stubs.userhyphen]
bots: [@stubs.bot]
dms: [
name: 'user2'
id: 'D5432'
]
@stubs.rtm =
login: =>
@stubs._connected = true
start: =>
@stubs._connected = true
on: (name, callback) =>
console.log("#####")
console.log(name)
console.log(callback)
callback(name)
removeListener: (name) =>
sendMessage: (msg, room) =>
@stubs.send room, msg
dataStore:
getUserById: (id) =>
switch id
when @stubs.user.id then @stubs.user
when @stubs.bot.id then @stubs.bot
when @stubs.self.id then @stubs.self
when @stubs.self_bot.id then @stubs.self_bot
else undefined
getChannelByName: (name) =>
switch name
when 'known_room' then {id: 'C00000004'}
else undefined
getChannelGroupOrDMById: (id) =>
switch id
when @stubs.channel.id then @stubs.channel
when @stubs.DM.id then @stubs.DM
@stubs.chatMock =
postMessage: (msg, room, opts) =>
@stubs.send(msg, room, opts)
@stubs.channelsMock =
setTopic: (id, topic) =>
@stubs._topic = topic
@stubs.responseUsersList =
ok: true
members: [@stubs.user, @stubs.userperiod]
@stubs.wrongResponseUsersList =
ok: false
# Hubot.Robot instance
@stubs.robot = do ->
robot = new EventEmitter
# noop the logging
robot.logger =
logs: {}
log: (type, message) ->
@logs[type] ?= []
@logs[type].push(message)
info: (message) ->
@log('info', message)
debug: (message) ->
@log('debug', message)
error: (message) ->
@log('error', message)
# record all received messages
robot.received = []
robot.receive = (msg) ->
@received.push msg
# attach a real Brain to the robot
robot.brain = new Brain robot
robot.name = 'bot'
robot.listeners = []
robot.listen = Robot.prototype.listen.bind(robot)
robot.react = Robot.prototype.react.bind(robot)
robot
@stubs.callback = do ->
return "done"
@stubs.receiveMock =
receive: (message, user) =>
@stubs._received = message
# Generate a new slack instance for each test.
@slackbot = new SlackBot @stubs.robot, token: 'PI:PASSWORD:<PASSWORD>END_PI'
_.merge @slackbot.client, @stubs.client
_.merge @slackbot.client.rtm, @stubs.rtm
_.merge @slackbot.client.web.chat, @stubs.chatMock
_.merge @slackbot.client.web.channels, @stubs.channelsMock
_.merge @slackbot, @stubs.receiveMock
@slackbot.self = @stubs.self
@formatter = new SlackFormatter @stubs.client.dataStore
@client = new SlackClient {token: 'PI:PASSWORD:<PASSWORD>END_PI'}, @stubs.robot
_.merge @client.rtm, @stubs.rtm
_.merge @client.web.chat, @stubs.chatMock
_.merge @client.web.channels, @stubs.channelsMock
|
[
{
"context": "xample {\"data\":{\"phone_number\":null,\"name_first\":\"Aha\",\"address_street1\":\"2800 San Jacinto Street\",\"liv",
"end": 4087,
"score": 0.9997574090957642,
"start": 4084,
"tag": "NAME",
"value": "Aha"
},
{
"context": "_code\":\"US\",\"address_city\":\"Houston\",\"n... | app/scripts/services/authentication.coffee | nerdfiles/utxo_us | 0 | "use strict"
###*
@ngdoc service
@name utxoPmc.authentication
@description
# authentication
Service in the utxoPmc.
###
angular.module("utxoPmc").factory "authentication", ($timeout, $q, $http, $window, person, crypto, localStorageService, $location) ->
###*
Authentication Service Interface.
###
__interface__ = {}
__interface__.loadSession = ->
#
# *
# *
#
def = $q.defer()
sec_phone = localStorageService.get("hook")
try
_sec_phone = crypto.decrypt(sec_phone, person.session.user.token)
catch e
$location.path "/"
exploded_sec_phone = _sec_phone.toString(CryptoJS.enc.Utf8)
if person.session.user and exploded_sec_phone
_formObject = phone_number: null
_formObject.phone_number = exploded_sec_phone
#var payload = $.param(_formObject);
person.get(
mode: "byId"
handle: _formObject.phone_number
).then (personData) ->
personData = (if personData? then personData else {})
stored_order = (if (person.current and person.current.order) then person.current.order else null)
if (personData and person.current and not person.current.order?) or person.current.order.paid is "true"
person.current = personData
_orders = _.toArray(personData.orders)
_orders.sort (a, b) ->
b.timestamp - a.timestamp
person.current.order = _.last(_orders)
person.current.order = stored_order if stored_order
def.resolve person.current
else
def.resolve person.current
return
#
# *$http.post(
# * environment.rest.orders.latest,
# * payload
# *).success(function (responseData) {
# * console.dir(responseData);
# *}).error(function (errorData) {
# * console.dir(errorData);
# *});
#
else
def.reject false
def.promise
uiCleanupStyles = {}
portSpec = (if $window.location.port isnt "" then (":" + $window.location.port) else "")
hostname = $window.location.hostname + portSpec
uiCleanupStyles.property_clean = (type, obj) ->
###*
Property Clean
@inner
###
switch type
when "sanitize"
_.forEach obj, (_property) ->
p = _property.replace(/-/g, "")
console.log p
p
obj
__interface__.scrapeUrl = $window.location.protocol + "//" + hostname + "/scraper/"
__interface__.validate_identity = (formObject) ->
###*
Create Person
@extends http://schema.org/Person
@extends http://docs.blockscore.com/v4.0/python/#people
@extends https://www.dandb.com/advanced-search/#people (CommonREST)
@extends http://schema.org/Organziation
@extends http://docs.blockscore.com/v4.0/python/#companies
@extends https://www.dandb.com/advanced-search/#companies (CommonREST)
###
baseUrl = environment.rest.person.create
def = $q.defer()
uri_base = "/"
formObject["has_pos"] = null
formObject["duns"] = null
formObject["isic_v4"] = null
formObject["naics"] = null
formObject["tax_id"] = null
formObject["vat_id"] = null
formObject["email"] = null
formObject["affiliation"] = null
formObject["telephone"] = null
formObject["uri"] = uri_base
formObject["sales_opportunity"] = null
formObject["latest_fin_sales"] = null
formObject["industry"] = null
formObject["primary_industry"] = null
formObject["num_of_employees"] = 1
formObject["seeks"] = null
formObject["net_worth"] = null
formObject["owns"] = null
formObject["makes_offer"] = null
formObject["member_off"] = null
formObject["knows"] = null
formObject["global_location_number"] = null
formObject["fax_number"] = null
formObject["under_name"] = null
formObject["reviewed_by"] = null
formObject["broker"] = null
formObject["alumni_of"] = null
payload = $.param(formObject)
# @example {"data":{"phone_number":null,"name_first":"Aha","address_street1":"2800 San Jacinto Street","livemode":false,"updated_at":1441627226,"question_sets":[],"document_value":"5734","birth_day":27,"id":"55ed7c5a3735380003000158","note":null,"address_subdivision":"Texas","name_middle":"","details":{"ofac":"no_match","address_risk":"low","pep":"no_match","date_of_birth":"not_found","identification":"no_match","address":"no_match"},"birth_month":3,"birth_year":1985,"status":"invalid","address_street2":"","object":"person","document_type":"ssn","ip_address":"","address_country_code":"US","address_city":"Houston","name_last":"Hah","created_at":1441627226,"address_postal_code":"77004"}}
$http.post(baseUrl, payload).success((responseData) ->
def.resolve responseData
return
).error (errorData) ->
def.reject errorData
return
def.promise
__interface__.score_question_set = (formObject) ->
###*
Score Validation Question Set
###
baseUrl = environment.rest.questionSet.validate
def = $q.defer()
payload = $.param(formObject)
$http.post(baseUrl + "/" + formObject.id, payload).success((responseData) ->
def.resolve responseData
return
).error (errorData) ->
def.reject errorData
return
def.promise
__interface__.create_validate_questions = (formObject) ->
###*
Create Validation Questions Set
###
baseUrl = environment.rest.questionSet.create
def = $q.defer()
payload = $.param(person_id: formObject.person_id)
$http.post(baseUrl, payload).success((responseData) ->
def.resolve responseData
return
).error (errorData) ->
def.reject errorData
return
def.promise
__interface__.validate_phone_number = (formObject) ->
###*
Validate Phone Number
###
baseUrl = environment.rest.authenticationSms.create
def = $q.defer()
_formObject = uiCleanupStyles.property_clean("sanitize", formObject)
payload = $.param(_formObject)
$http.post(baseUrl, payload).success((responseData) ->
def.resolve responseData
return
).error (errorData) ->
def.reject errorData
return
def.promise
###*
Export Authentication Service Interface.
###
__interface__
| 212302 | "use strict"
###*
@ngdoc service
@name utxoPmc.authentication
@description
# authentication
Service in the utxoPmc.
###
angular.module("utxoPmc").factory "authentication", ($timeout, $q, $http, $window, person, crypto, localStorageService, $location) ->
###*
Authentication Service Interface.
###
__interface__ = {}
__interface__.loadSession = ->
#
# *
# *
#
def = $q.defer()
sec_phone = localStorageService.get("hook")
try
_sec_phone = crypto.decrypt(sec_phone, person.session.user.token)
catch e
$location.path "/"
exploded_sec_phone = _sec_phone.toString(CryptoJS.enc.Utf8)
if person.session.user and exploded_sec_phone
_formObject = phone_number: null
_formObject.phone_number = exploded_sec_phone
#var payload = $.param(_formObject);
person.get(
mode: "byId"
handle: _formObject.phone_number
).then (personData) ->
personData = (if personData? then personData else {})
stored_order = (if (person.current and person.current.order) then person.current.order else null)
if (personData and person.current and not person.current.order?) or person.current.order.paid is "true"
person.current = personData
_orders = _.toArray(personData.orders)
_orders.sort (a, b) ->
b.timestamp - a.timestamp
person.current.order = _.last(_orders)
person.current.order = stored_order if stored_order
def.resolve person.current
else
def.resolve person.current
return
#
# *$http.post(
# * environment.rest.orders.latest,
# * payload
# *).success(function (responseData) {
# * console.dir(responseData);
# *}).error(function (errorData) {
# * console.dir(errorData);
# *});
#
else
def.reject false
def.promise
uiCleanupStyles = {}
portSpec = (if $window.location.port isnt "" then (":" + $window.location.port) else "")
hostname = $window.location.hostname + portSpec
uiCleanupStyles.property_clean = (type, obj) ->
###*
Property Clean
@inner
###
switch type
when "sanitize"
_.forEach obj, (_property) ->
p = _property.replace(/-/g, "")
console.log p
p
obj
__interface__.scrapeUrl = $window.location.protocol + "//" + hostname + "/scraper/"
__interface__.validate_identity = (formObject) ->
###*
Create Person
@extends http://schema.org/Person
@extends http://docs.blockscore.com/v4.0/python/#people
@extends https://www.dandb.com/advanced-search/#people (CommonREST)
@extends http://schema.org/Organziation
@extends http://docs.blockscore.com/v4.0/python/#companies
@extends https://www.dandb.com/advanced-search/#companies (CommonREST)
###
baseUrl = environment.rest.person.create
def = $q.defer()
uri_base = "/"
formObject["has_pos"] = null
formObject["duns"] = null
formObject["isic_v4"] = null
formObject["naics"] = null
formObject["tax_id"] = null
formObject["vat_id"] = null
formObject["email"] = null
formObject["affiliation"] = null
formObject["telephone"] = null
formObject["uri"] = uri_base
formObject["sales_opportunity"] = null
formObject["latest_fin_sales"] = null
formObject["industry"] = null
formObject["primary_industry"] = null
formObject["num_of_employees"] = 1
formObject["seeks"] = null
formObject["net_worth"] = null
formObject["owns"] = null
formObject["makes_offer"] = null
formObject["member_off"] = null
formObject["knows"] = null
formObject["global_location_number"] = null
formObject["fax_number"] = null
formObject["under_name"] = null
formObject["reviewed_by"] = null
formObject["broker"] = null
formObject["alumni_of"] = null
payload = $.param(formObject)
# @example {"data":{"phone_number":null,"name_first":"<NAME>","address_street1":"2800 San Jacinto Street","livemode":false,"updated_at":1441627226,"question_sets":[],"document_value":"5734","birth_day":27,"id":"55ed7c5a3735380003000158","note":null,"address_subdivision":"Texas","name_middle":"","details":{"ofac":"no_match","address_risk":"low","pep":"no_match","date_of_birth":"not_found","identification":"no_match","address":"no_match"},"birth_month":3,"birth_year":1985,"status":"invalid","address_street2":"","object":"person","document_type":"ssn","ip_address":"","address_country_code":"US","address_city":"Houston","name_last":"<NAME>","created_at":1441627226,"address_postal_code":"77004"}}
$http.post(baseUrl, payload).success((responseData) ->
def.resolve responseData
return
).error (errorData) ->
def.reject errorData
return
def.promise
__interface__.score_question_set = (formObject) ->
###*
Score Validation Question Set
###
baseUrl = environment.rest.questionSet.validate
def = $q.defer()
payload = $.param(formObject)
$http.post(baseUrl + "/" + formObject.id, payload).success((responseData) ->
def.resolve responseData
return
).error (errorData) ->
def.reject errorData
return
def.promise
__interface__.create_validate_questions = (formObject) ->
###*
Create Validation Questions Set
###
baseUrl = environment.rest.questionSet.create
def = $q.defer()
payload = $.param(person_id: formObject.person_id)
$http.post(baseUrl, payload).success((responseData) ->
def.resolve responseData
return
).error (errorData) ->
def.reject errorData
return
def.promise
__interface__.validate_phone_number = (formObject) ->
###*
Validate Phone Number
###
baseUrl = environment.rest.authenticationSms.create
def = $q.defer()
_formObject = uiCleanupStyles.property_clean("sanitize", formObject)
payload = $.param(_formObject)
$http.post(baseUrl, payload).success((responseData) ->
def.resolve responseData
return
).error (errorData) ->
def.reject errorData
return
def.promise
###*
Export Authentication Service Interface.
###
__interface__
| true | "use strict"
###*
@ngdoc service
@name utxoPmc.authentication
@description
# authentication
Service in the utxoPmc.
###
angular.module("utxoPmc").factory "authentication", ($timeout, $q, $http, $window, person, crypto, localStorageService, $location) ->
###*
Authentication Service Interface.
###
__interface__ = {}
__interface__.loadSession = ->
#
# *
# *
#
def = $q.defer()
sec_phone = localStorageService.get("hook")
try
_sec_phone = crypto.decrypt(sec_phone, person.session.user.token)
catch e
$location.path "/"
exploded_sec_phone = _sec_phone.toString(CryptoJS.enc.Utf8)
if person.session.user and exploded_sec_phone
_formObject = phone_number: null
_formObject.phone_number = exploded_sec_phone
#var payload = $.param(_formObject);
person.get(
mode: "byId"
handle: _formObject.phone_number
).then (personData) ->
personData = (if personData? then personData else {})
stored_order = (if (person.current and person.current.order) then person.current.order else null)
if (personData and person.current and not person.current.order?) or person.current.order.paid is "true"
person.current = personData
_orders = _.toArray(personData.orders)
_orders.sort (a, b) ->
b.timestamp - a.timestamp
person.current.order = _.last(_orders)
person.current.order = stored_order if stored_order
def.resolve person.current
else
def.resolve person.current
return
#
# *$http.post(
# * environment.rest.orders.latest,
# * payload
# *).success(function (responseData) {
# * console.dir(responseData);
# *}).error(function (errorData) {
# * console.dir(errorData);
# *});
#
else
def.reject false
def.promise
uiCleanupStyles = {}
portSpec = (if $window.location.port isnt "" then (":" + $window.location.port) else "")
hostname = $window.location.hostname + portSpec
uiCleanupStyles.property_clean = (type, obj) ->
###*
Property Clean
@inner
###
switch type
when "sanitize"
_.forEach obj, (_property) ->
p = _property.replace(/-/g, "")
console.log p
p
obj
__interface__.scrapeUrl = $window.location.protocol + "//" + hostname + "/scraper/"
__interface__.validate_identity = (formObject) ->
###*
Create Person
@extends http://schema.org/Person
@extends http://docs.blockscore.com/v4.0/python/#people
@extends https://www.dandb.com/advanced-search/#people (CommonREST)
@extends http://schema.org/Organziation
@extends http://docs.blockscore.com/v4.0/python/#companies
@extends https://www.dandb.com/advanced-search/#companies (CommonREST)
###
baseUrl = environment.rest.person.create
def = $q.defer()
uri_base = "/"
formObject["has_pos"] = null
formObject["duns"] = null
formObject["isic_v4"] = null
formObject["naics"] = null
formObject["tax_id"] = null
formObject["vat_id"] = null
formObject["email"] = null
formObject["affiliation"] = null
formObject["telephone"] = null
formObject["uri"] = uri_base
formObject["sales_opportunity"] = null
formObject["latest_fin_sales"] = null
formObject["industry"] = null
formObject["primary_industry"] = null
formObject["num_of_employees"] = 1
formObject["seeks"] = null
formObject["net_worth"] = null
formObject["owns"] = null
formObject["makes_offer"] = null
formObject["member_off"] = null
formObject["knows"] = null
formObject["global_location_number"] = null
formObject["fax_number"] = null
formObject["under_name"] = null
formObject["reviewed_by"] = null
formObject["broker"] = null
formObject["alumni_of"] = null
payload = $.param(formObject)
# @example {"data":{"phone_number":null,"name_first":"PI:NAME:<NAME>END_PI","address_street1":"2800 San Jacinto Street","livemode":false,"updated_at":1441627226,"question_sets":[],"document_value":"5734","birth_day":27,"id":"55ed7c5a3735380003000158","note":null,"address_subdivision":"Texas","name_middle":"","details":{"ofac":"no_match","address_risk":"low","pep":"no_match","date_of_birth":"not_found","identification":"no_match","address":"no_match"},"birth_month":3,"birth_year":1985,"status":"invalid","address_street2":"","object":"person","document_type":"ssn","ip_address":"","address_country_code":"US","address_city":"Houston","name_last":"PI:NAME:<NAME>END_PI","created_at":1441627226,"address_postal_code":"77004"}}
$http.post(baseUrl, payload).success((responseData) ->
def.resolve responseData
return
).error (errorData) ->
def.reject errorData
return
def.promise
__interface__.score_question_set = (formObject) ->
###*
Score Validation Question Set
###
baseUrl = environment.rest.questionSet.validate
def = $q.defer()
payload = $.param(formObject)
$http.post(baseUrl + "/" + formObject.id, payload).success((responseData) ->
def.resolve responseData
return
).error (errorData) ->
def.reject errorData
return
def.promise
__interface__.create_validate_questions = (formObject) ->
###*
Create Validation Questions Set
###
baseUrl = environment.rest.questionSet.create
def = $q.defer()
payload = $.param(person_id: formObject.person_id)
$http.post(baseUrl, payload).success((responseData) ->
def.resolve responseData
return
).error (errorData) ->
def.reject errorData
return
def.promise
__interface__.validate_phone_number = (formObject) ->
###*
Validate Phone Number
###
baseUrl = environment.rest.authenticationSms.create
def = $q.defer()
_formObject = uiCleanupStyles.property_clean("sanitize", formObject)
payload = $.param(_formObject)
$http.post(baseUrl, payload).success((responseData) ->
def.resolve responseData
return
).error (errorData) ->
def.reject errorData
return
def.promise
###*
Export Authentication Service Interface.
###
__interface__
|
[
{
"context": ".equal(c1)\n\n\t\t\tcontext = new Framer.Context(name:\"Test\")\n\n\t\t\tcontext.reset()\n\t\t\tcontext.reset()\n\t\t\tconte",
"end": 355,
"score": 0.8585156798362732,
"start": 351,
"tag": "NAME",
"value": "Test"
},
{
"context": "vents\", ->\n\n\t\t\tcontext = new Frame... | test/tests/ContextTest.coffee | HydAu/FramerJS | 0 | assert = require "assert"
describe "Context", ->
describe "Reset", ->
it "should never append more than a single child on reset", (done) ->
c1 = document.querySelectorAll(".framerContext").length
# There's one default context:
document.querySelectorAll(".framerContext").length.should.equal(c1)
context = new Framer.Context(name:"Test")
context.reset()
context.reset()
context.reset()
Framer.Loop.once "render", ->
document.querySelectorAll(".framerContext").length.should.equal(c1+1)
done()
# Todo: event cleanup
# Todo: parent layer on context cleanup
describe "Freezing", ->
it "should remove events", ->
context = new Framer.Context(name:"Test")
layer = null
handler = ->
context.run ->
layer = new Layer
layer.on(Events.Click, handler)
# We should have a click listener
layer.listeners(Events.Click).should.eql([handler])
context.freeze()
layer.listeners(Events.Click).should.eql([])
it "should restore events", ->
context = new Framer.Context(name:"Test")
layer = null
handler = ->
context.run ->
layer = new Layer
layer.on(Events.Click, handler)
context.freeze()
context.resume()
# Now it should have been restored
layer.listeners(Events.Click).should.eql([handler])
it "should freeze and restore multiple events on multiple layers", ->
context = new Framer.Context(name:"Test")
layerA = layerB = null
handlerA = ->
handlerB = ->
handlerC = ->
handlerD = ->
context.run ->
layerA = new Layer
layerA.on(Events.Click, handlerA)
layerA.on(Events.Click, handlerB)
layerB = new Layer
layerB.on(Events.Scroll, handlerC)
layerB.on(Events.Scroll, handlerD)
# We should have a click listener
layerA.listeners(Events.Click).should.eql([handlerA, handlerB])
layerB.listeners(Events.Scroll).should.eql([handlerC, handlerD])
context.freeze()
layerA.listeners(Events.Click).should.eql([])
layerB.listeners(Events.Click).should.eql([])
context.resume()
layerA.listeners(Events.Click).should.eql([handlerA, handlerB])
layerB.listeners(Events.Scroll).should.eql([handlerC, handlerD])
it "should freeze and restore multiple events a layer", ->
context = new Framer.Context(name:"Test")
layerA = null
handlerA = ->
handlerB = ->
handlerC = ->
handlerD = ->
context.run ->
layerA = new Layer
layerA.on(Events.Click, handlerA)
layerA.on(Events.Click, handlerB)
layerA.on(Events.Scroll, handlerC)
layerA.on(Events.Scroll, handlerD)
# We should have a click listener
layerA.listeners(Events.Click).should.eql([handlerA, handlerB])
layerA.listeners(Events.Scroll).should.eql([handlerC, handlerD])
context.freeze()
layerA.listeners(Events.Click).should.eql([])
context.resume()
layerA.listeners(Events.Click).should.eql([handlerA, handlerB])
layerA.listeners(Events.Scroll).should.eql([handlerC, handlerD])
it "should stop animations", ->
context = new Framer.Context(name:"Test")
layer = null
animation = null
handler = ->
context.run ->
layer = new Layer
animation = layer.animate
properties:
x: 100
# We should have a click listener
context.animations.should.eql [animation]
context.freeze()
context.animations.should.eql []
it "should stop timers", ->
context = new Framer.Context(name:"Test")
layer = null
timer = null
handler = ->
context.run ->
layer = new Layer
timer = Utils.delay(1, handler)
# We should have a click listener
context.timers.should.eql [timer]
context.freeze()
context.timers.should.eql []
describe "Layers", ->
it "should add and remove layers", ->
context = new Framer.Context(name:"Test")
context.run ->
layerA = new Layer
layerB = new Layer
layerC = new Layer
layerD = new Layer
context.layers.should.eql [layerA, layerB, layerC, layerD]
_.invokeMap(context.layers, "destroy")
context.layers.should.eql []
it "should list root layers", ->
context = new Framer.Context(name:"Test")
context.run ->
layerA = new Layer
layerB = new Layer parent:layerA
context.rootLayers.should.eql [layerA]
layerB.parent = null
context.rootLayers.should.eql [layerA, layerB]
it "should get layers by id", ->
context = new Framer.Context(name:"Test")
context.run ->
layerA = new Layer
context.layerForId(layerA.id).should.equal layerA
it "should get layers by element", ->
context = new Framer.Context(name:"Test")
context.run ->
layerA = new Layer
context.layerForElement(layerA._element).should.equal layerA
describe "Events", ->
it "should emit reset", (callback) ->
context = new Framer.Context(name:"Test")
context.on "reset", -> callback()
context.reset()
it "should emit layer create", (callback) ->
context = new Framer.Context(name:"Test")
context.on "layer:create", ->
context.getLayers().length.should.equal 1
callback()
context.run ->
layer = new Layer
it "should emit layer destroy", (callback) ->
context = new Framer.Context(name:"Test")
context.on "layer:create", ->
context.getLayers().length.should.equal 1
context.on "layer:destroy", ->
context.getLayers().length.should.equal 0
callback()
context.run ->
layer = new Layer
layer.destroy()
it "should keep layer id count per context", ->
context = new Framer.Context(name:"Test")
context.run ->
layer = new Layer
layer.id.should.equal 1
layer = new Layer
layer.id.should.equal 2
context.reset()
context.run ->
layer = new Layer
layer.id.should.equal 1
layer = new Layer
layer.id.should.equal 2
describe "Styling", ->
it "should set backgroundColor", ->
context = new Framer.Context(name:"Test")
context.backgroundColor = "red"
color = new Color "red"
colorString = color.toString()
context._element.style["backgroundColor"].should.equal colorString
it "should have a default perspective of 0", ->
context = new Framer.Context(name:"Test")
context._element.style["webkitPerspective"].should.equal "0"
it "should allow the perspective to be changed", ->
context = new Framer.Context(name:"Test")
context.perspective = 800
context._element.style["webkitPerspective"].should.equal "800"
| 21845 | assert = require "assert"
describe "Context", ->
describe "Reset", ->
it "should never append more than a single child on reset", (done) ->
c1 = document.querySelectorAll(".framerContext").length
# There's one default context:
document.querySelectorAll(".framerContext").length.should.equal(c1)
context = new Framer.Context(name:"<NAME>")
context.reset()
context.reset()
context.reset()
Framer.Loop.once "render", ->
document.querySelectorAll(".framerContext").length.should.equal(c1+1)
done()
# Todo: event cleanup
# Todo: parent layer on context cleanup
describe "Freezing", ->
it "should remove events", ->
context = new Framer.Context(name:"<NAME>")
layer = null
handler = ->
context.run ->
layer = new Layer
layer.on(Events.Click, handler)
# We should have a click listener
layer.listeners(Events.Click).should.eql([handler])
context.freeze()
layer.listeners(Events.Click).should.eql([])
it "should restore events", ->
context = new Framer.Context(name:"<NAME>")
layer = null
handler = ->
context.run ->
layer = new Layer
layer.on(Events.Click, handler)
context.freeze()
context.resume()
# Now it should have been restored
layer.listeners(Events.Click).should.eql([handler])
it "should freeze and restore multiple events on multiple layers", ->
context = new Framer.Context(name:"<NAME>")
layerA = layerB = null
handlerA = ->
handlerB = ->
handlerC = ->
handlerD = ->
context.run ->
layerA = new Layer
layerA.on(Events.Click, handlerA)
layerA.on(Events.Click, handlerB)
layerB = new Layer
layerB.on(Events.Scroll, handlerC)
layerB.on(Events.Scroll, handlerD)
# We should have a click listener
layerA.listeners(Events.Click).should.eql([handlerA, handlerB])
layerB.listeners(Events.Scroll).should.eql([handlerC, handlerD])
context.freeze()
layerA.listeners(Events.Click).should.eql([])
layerB.listeners(Events.Click).should.eql([])
context.resume()
layerA.listeners(Events.Click).should.eql([handlerA, handlerB])
layerB.listeners(Events.Scroll).should.eql([handlerC, handlerD])
it "should freeze and restore multiple events a layer", ->
context = new Framer.Context(name:"<NAME>")
layerA = null
handlerA = ->
handlerB = ->
handlerC = ->
handlerD = ->
context.run ->
layerA = new Layer
layerA.on(Events.Click, handlerA)
layerA.on(Events.Click, handlerB)
layerA.on(Events.Scroll, handlerC)
layerA.on(Events.Scroll, handlerD)
# We should have a click listener
layerA.listeners(Events.Click).should.eql([handlerA, handlerB])
layerA.listeners(Events.Scroll).should.eql([handlerC, handlerD])
context.freeze()
layerA.listeners(Events.Click).should.eql([])
context.resume()
layerA.listeners(Events.Click).should.eql([handlerA, handlerB])
layerA.listeners(Events.Scroll).should.eql([handlerC, handlerD])
it "should stop animations", ->
context = new Framer.Context(name:"<NAME>")
layer = null
animation = null
handler = ->
context.run ->
layer = new Layer
animation = layer.animate
properties:
x: 100
# We should have a click listener
context.animations.should.eql [animation]
context.freeze()
context.animations.should.eql []
it "should stop timers", ->
context = new Framer.Context(name:"<NAME>")
layer = null
timer = null
handler = ->
context.run ->
layer = new Layer
timer = Utils.delay(1, handler)
# We should have a click listener
context.timers.should.eql [timer]
context.freeze()
context.timers.should.eql []
describe "Layers", ->
it "should add and remove layers", ->
context = new Framer.Context(name:"Test")
context.run ->
layerA = new Layer
layerB = new Layer
layerC = new Layer
layerD = new Layer
context.layers.should.eql [layerA, layerB, layerC, layerD]
_.invokeMap(context.layers, "destroy")
context.layers.should.eql []
it "should list root layers", ->
context = new Framer.Context(name:"Test")
context.run ->
layerA = new Layer
layerB = new Layer parent:layerA
context.rootLayers.should.eql [layerA]
layerB.parent = null
context.rootLayers.should.eql [layerA, layerB]
it "should get layers by id", ->
context = new Framer.Context(name:"Test")
context.run ->
layerA = new Layer
context.layerForId(layerA.id).should.equal layerA
it "should get layers by element", ->
context = new Framer.Context(name:"Test")
context.run ->
layerA = new Layer
context.layerForElement(layerA._element).should.equal layerA
describe "Events", ->
it "should emit reset", (callback) ->
context = new Framer.Context(name:"<NAME>")
context.on "reset", -> callback()
context.reset()
it "should emit layer create", (callback) ->
context = new Framer.Context(name:"Test")
context.on "layer:create", ->
context.getLayers().length.should.equal 1
callback()
context.run ->
layer = new Layer
it "should emit layer destroy", (callback) ->
context = new Framer.Context(name:"<NAME>")
context.on "layer:create", ->
context.getLayers().length.should.equal 1
context.on "layer:destroy", ->
context.getLayers().length.should.equal 0
callback()
context.run ->
layer = new Layer
layer.destroy()
it "should keep layer id count per context", ->
context = new Framer.Context(name:"<NAME>")
context.run ->
layer = new Layer
layer.id.should.equal 1
layer = new Layer
layer.id.should.equal 2
context.reset()
context.run ->
layer = new Layer
layer.id.should.equal 1
layer = new Layer
layer.id.should.equal 2
describe "Styling", ->
it "should set backgroundColor", ->
context = new Framer.Context(name:"<NAME>")
context.backgroundColor = "red"
color = new Color "red"
colorString = color.toString()
context._element.style["backgroundColor"].should.equal colorString
it "should have a default perspective of 0", ->
context = new Framer.Context(name:"<NAME>")
context._element.style["webkitPerspective"].should.equal "0"
it "should allow the perspective to be changed", ->
context = new Framer.Context(name:"<NAME>")
context.perspective = 800
context._element.style["webkitPerspective"].should.equal "800"
| true | assert = require "assert"
describe "Context", ->
describe "Reset", ->
it "should never append more than a single child on reset", (done) ->
c1 = document.querySelectorAll(".framerContext").length
# There's one default context:
document.querySelectorAll(".framerContext").length.should.equal(c1)
context = new Framer.Context(name:"PI:NAME:<NAME>END_PI")
context.reset()
context.reset()
context.reset()
Framer.Loop.once "render", ->
document.querySelectorAll(".framerContext").length.should.equal(c1+1)
done()
# Todo: event cleanup
# Todo: parent layer on context cleanup
describe "Freezing", ->
it "should remove events", ->
context = new Framer.Context(name:"PI:NAME:<NAME>END_PI")
layer = null
handler = ->
context.run ->
layer = new Layer
layer.on(Events.Click, handler)
# We should have a click listener
layer.listeners(Events.Click).should.eql([handler])
context.freeze()
layer.listeners(Events.Click).should.eql([])
it "should restore events", ->
context = new Framer.Context(name:"PI:NAME:<NAME>END_PI")
layer = null
handler = ->
context.run ->
layer = new Layer
layer.on(Events.Click, handler)
context.freeze()
context.resume()
# Now it should have been restored
layer.listeners(Events.Click).should.eql([handler])
it "should freeze and restore multiple events on multiple layers", ->
context = new Framer.Context(name:"PI:NAME:<NAME>END_PI")
layerA = layerB = null
handlerA = ->
handlerB = ->
handlerC = ->
handlerD = ->
context.run ->
layerA = new Layer
layerA.on(Events.Click, handlerA)
layerA.on(Events.Click, handlerB)
layerB = new Layer
layerB.on(Events.Scroll, handlerC)
layerB.on(Events.Scroll, handlerD)
# We should have a click listener
layerA.listeners(Events.Click).should.eql([handlerA, handlerB])
layerB.listeners(Events.Scroll).should.eql([handlerC, handlerD])
context.freeze()
layerA.listeners(Events.Click).should.eql([])
layerB.listeners(Events.Click).should.eql([])
context.resume()
layerA.listeners(Events.Click).should.eql([handlerA, handlerB])
layerB.listeners(Events.Scroll).should.eql([handlerC, handlerD])
it "should freeze and restore multiple events a layer", ->
context = new Framer.Context(name:"PI:NAME:<NAME>END_PI")
layerA = null
handlerA = ->
handlerB = ->
handlerC = ->
handlerD = ->
context.run ->
layerA = new Layer
layerA.on(Events.Click, handlerA)
layerA.on(Events.Click, handlerB)
layerA.on(Events.Scroll, handlerC)
layerA.on(Events.Scroll, handlerD)
# We should have a click listener
layerA.listeners(Events.Click).should.eql([handlerA, handlerB])
layerA.listeners(Events.Scroll).should.eql([handlerC, handlerD])
context.freeze()
layerA.listeners(Events.Click).should.eql([])
context.resume()
layerA.listeners(Events.Click).should.eql([handlerA, handlerB])
layerA.listeners(Events.Scroll).should.eql([handlerC, handlerD])
it "should stop animations", ->
context = new Framer.Context(name:"PI:NAME:<NAME>END_PI")
layer = null
animation = null
handler = ->
context.run ->
layer = new Layer
animation = layer.animate
properties:
x: 100
# We should have a click listener
context.animations.should.eql [animation]
context.freeze()
context.animations.should.eql []
it "should stop timers", ->
context = new Framer.Context(name:"PI:NAME:<NAME>END_PI")
layer = null
timer = null
handler = ->
context.run ->
layer = new Layer
timer = Utils.delay(1, handler)
# We should have a click listener
context.timers.should.eql [timer]
context.freeze()
context.timers.should.eql []
describe "Layers", ->
it "should add and remove layers", ->
context = new Framer.Context(name:"Test")
context.run ->
layerA = new Layer
layerB = new Layer
layerC = new Layer
layerD = new Layer
context.layers.should.eql [layerA, layerB, layerC, layerD]
_.invokeMap(context.layers, "destroy")
context.layers.should.eql []
it "should list root layers", ->
context = new Framer.Context(name:"Test")
context.run ->
layerA = new Layer
layerB = new Layer parent:layerA
context.rootLayers.should.eql [layerA]
layerB.parent = null
context.rootLayers.should.eql [layerA, layerB]
it "should get layers by id", ->
context = new Framer.Context(name:"Test")
context.run ->
layerA = new Layer
context.layerForId(layerA.id).should.equal layerA
it "should get layers by element", ->
context = new Framer.Context(name:"Test")
context.run ->
layerA = new Layer
context.layerForElement(layerA._element).should.equal layerA
describe "Events", ->
it "should emit reset", (callback) ->
context = new Framer.Context(name:"PI:NAME:<NAME>END_PI")
context.on "reset", -> callback()
context.reset()
it "should emit layer create", (callback) ->
context = new Framer.Context(name:"Test")
context.on "layer:create", ->
context.getLayers().length.should.equal 1
callback()
context.run ->
layer = new Layer
it "should emit layer destroy", (callback) ->
context = new Framer.Context(name:"PI:NAME:<NAME>END_PI")
context.on "layer:create", ->
context.getLayers().length.should.equal 1
context.on "layer:destroy", ->
context.getLayers().length.should.equal 0
callback()
context.run ->
layer = new Layer
layer.destroy()
it "should keep layer id count per context", ->
context = new Framer.Context(name:"PI:NAME:<NAME>END_PI")
context.run ->
layer = new Layer
layer.id.should.equal 1
layer = new Layer
layer.id.should.equal 2
context.reset()
context.run ->
layer = new Layer
layer.id.should.equal 1
layer = new Layer
layer.id.should.equal 2
describe "Styling", ->
it "should set backgroundColor", ->
context = new Framer.Context(name:"PI:NAME:<NAME>END_PI")
context.backgroundColor = "red"
color = new Color "red"
colorString = color.toString()
context._element.style["backgroundColor"].should.equal colorString
it "should have a default perspective of 0", ->
context = new Framer.Context(name:"PI:NAME:<NAME>END_PI")
context._element.style["webkitPerspective"].should.equal "0"
it "should allow the perspective to be changed", ->
context = new Framer.Context(name:"PI:NAME:<NAME>END_PI")
context.perspective = 800
context._element.style["webkitPerspective"].should.equal "800"
|
[
{
"context": "t_filters.join(\",\")\n\ninitSidebarTab = ->\n key = \"dashboard_sidebar_filter\"\n\n # store selection in cookie\n $('.dash-sideba",
"end": 760,
"score": 0.979351818561554,
"start": 736,
"tag": "KEY",
"value": "dashboard_sidebar_filter"
}
] | app/assets/javascripts/dashboard.js.coffee | lbt/gitlabhq | 1 | window.dashboardPage = ->
Pager.init 20, true
initSidebarTab()
$(".event_filter_link").bind "click", (event) ->
event.preventDefault()
toggleFilter $(this)
reloadActivities()
reloadActivities = ->
$(".content_list").html ''
Pager.init 20, true
toggleFilter = (sender) ->
sender.parent().toggleClass "inactive"
event_filters = $.cookie("event_filter")
filter = sender.attr("id").split("_")[0]
if event_filters
event_filters = event_filters.split(",")
else
event_filters = new Array()
index = event_filters.indexOf(filter)
if index is -1
event_filters.push filter
else
event_filters.splice index, 1
$.cookie "event_filter", event_filters.join(",")
initSidebarTab = ->
key = "dashboard_sidebar_filter"
# store selection in cookie
$('.dash-sidebar-tabs a').on 'click', (e) ->
$.cookie(key, $(e.target).attr('id'))
# show tab from cookie
sidebar_filter = $.cookie(key)
$("#" + sidebar_filter).tab('show') if sidebar_filter
| 18741 | window.dashboardPage = ->
Pager.init 20, true
initSidebarTab()
$(".event_filter_link").bind "click", (event) ->
event.preventDefault()
toggleFilter $(this)
reloadActivities()
reloadActivities = ->
$(".content_list").html ''
Pager.init 20, true
toggleFilter = (sender) ->
sender.parent().toggleClass "inactive"
event_filters = $.cookie("event_filter")
filter = sender.attr("id").split("_")[0]
if event_filters
event_filters = event_filters.split(",")
else
event_filters = new Array()
index = event_filters.indexOf(filter)
if index is -1
event_filters.push filter
else
event_filters.splice index, 1
$.cookie "event_filter", event_filters.join(",")
initSidebarTab = ->
key = "<KEY>"
# store selection in cookie
$('.dash-sidebar-tabs a').on 'click', (e) ->
$.cookie(key, $(e.target).attr('id'))
# show tab from cookie
sidebar_filter = $.cookie(key)
$("#" + sidebar_filter).tab('show') if sidebar_filter
| true | window.dashboardPage = ->
Pager.init 20, true
initSidebarTab()
$(".event_filter_link").bind "click", (event) ->
event.preventDefault()
toggleFilter $(this)
reloadActivities()
reloadActivities = ->
$(".content_list").html ''
Pager.init 20, true
toggleFilter = (sender) ->
sender.parent().toggleClass "inactive"
event_filters = $.cookie("event_filter")
filter = sender.attr("id").split("_")[0]
if event_filters
event_filters = event_filters.split(",")
else
event_filters = new Array()
index = event_filters.indexOf(filter)
if index is -1
event_filters.push filter
else
event_filters.splice index, 1
$.cookie "event_filter", event_filters.join(",")
initSidebarTab = ->
key = "PI:KEY:<KEY>END_PI"
# store selection in cookie
$('.dash-sidebar-tabs a').on 'click', (e) ->
$.cookie(key, $(e.target).attr('id'))
# show tab from cookie
sidebar_filter = $.cookie(key)
$("#" + sidebar_filter).tab('show') if sidebar_filter
|
[
{
"context": " Ember.belongsTo('Travis.Repo', key: 'repository_id')\n commit: Ember.belongsTo('Travis.Commit', key:",
"end": 653,
"score": 0.7613850831985474,
"start": 651,
"tag": "KEY",
"value": "id"
},
{
"context": "uild: Ember.belongsTo('Travis.Build', key: 'build_id')\n\n is... | assets/scripts/app/models/request.coffee | Acidburn0zzz/travis-web | 0 | require 'travis/model'
@Travis.Request = Travis.Model.extend
id: Ember.attr('string')
created_at: Ember.attr('string')
event_type: Ember.attr('string')
result: Ember.attr('string')
message: Ember.attr('string')
headCommit: Ember.attr('string')
baseCommit: Ember.attr('string')
branchName: Ember.attr('string', key: 'branch')
tagName: Ember.attr('string', key: 'tag')
pullRequest: Ember.attr('boolean')
pullRequestTitle: Ember.attr('string')
pullRequestNumber: Ember.attr(Number)
repo: Ember.belongsTo('Travis.Repo', key: 'repository_id')
commit: Ember.belongsTo('Travis.Commit', key: 'commit_id')
build: Ember.belongsTo('Travis.Build', key: 'build_id')
isAccepted: (->
# For some reason some of the requests have a null result beside the fact that
# the build was created. We need to look into it, but for now we can just assume
# that if build was created, the request was accepted
@get('result') == 'accepted' || @get('build')
).property('result')
isPullRequest: (->
@get('event_type') == 'pull_request'
).property('event_type')
| 41450 | require 'travis/model'
@Travis.Request = Travis.Model.extend
id: Ember.attr('string')
created_at: Ember.attr('string')
event_type: Ember.attr('string')
result: Ember.attr('string')
message: Ember.attr('string')
headCommit: Ember.attr('string')
baseCommit: Ember.attr('string')
branchName: Ember.attr('string', key: 'branch')
tagName: Ember.attr('string', key: 'tag')
pullRequest: Ember.attr('boolean')
pullRequestTitle: Ember.attr('string')
pullRequestNumber: Ember.attr(Number)
repo: Ember.belongsTo('Travis.Repo', key: 'repository_<KEY>')
commit: Ember.belongsTo('Travis.Commit', key: 'commit_id')
build: Ember.belongsTo('Travis.Build', key: 'build_<KEY>')
isAccepted: (->
# For some reason some of the requests have a null result beside the fact that
# the build was created. We need to look into it, but for now we can just assume
# that if build was created, the request was accepted
@get('result') == 'accepted' || @get('build')
).property('result')
isPullRequest: (->
@get('event_type') == 'pull_request'
).property('event_type')
| true | require 'travis/model'
@Travis.Request = Travis.Model.extend
id: Ember.attr('string')
created_at: Ember.attr('string')
event_type: Ember.attr('string')
result: Ember.attr('string')
message: Ember.attr('string')
headCommit: Ember.attr('string')
baseCommit: Ember.attr('string')
branchName: Ember.attr('string', key: 'branch')
tagName: Ember.attr('string', key: 'tag')
pullRequest: Ember.attr('boolean')
pullRequestTitle: Ember.attr('string')
pullRequestNumber: Ember.attr(Number)
repo: Ember.belongsTo('Travis.Repo', key: 'repository_PI:KEY:<KEY>END_PI')
commit: Ember.belongsTo('Travis.Commit', key: 'commit_id')
build: Ember.belongsTo('Travis.Build', key: 'build_PI:KEY:<KEY>END_PI')
isAccepted: (->
# For some reason some of the requests have a null result beside the fact that
# the build was created. We need to look into it, but for now we can just assume
# that if build was created, the request was accepted
@get('result') == 'accepted' || @get('build')
).property('result')
isPullRequest: (->
@get('event_type') == 'pull_request'
).property('event_type')
|
[
{
"context": " spread operators and their expressions.\n# @author Kai Cataldo\n###\n\n'use strict'\n\n#-----------------------------",
"end": 115,
"score": 0.9998527765274048,
"start": 104,
"tag": "NAME",
"value": "Kai Cataldo"
}
] | src/rules/rest-spread-spacing.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Enforce spacing between rest and spread operators and their expressions.
# @author Kai Cataldo
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description:
'enforce spacing between rest and spread operators and their expressions'
category: 'ECMAScript 6'
recommended: no
url: 'https://eslint.org/docs/rules/rest-spread-spacing'
fixable: 'whitespace'
schema: [enum: ['always', 'never']]
create: (context) ->
sourceCode = context.getSourceCode()
alwaysSpace = context.options[0] is 'always'
#--------------------------------------------------------------------------
# Helpers
#--------------------------------------------------------------------------
###*
# Checks whitespace between rest/spread operators and their expressions
# @param {ASTNode} node - The node to check
# @returns {void}
###
checkWhiteSpace = (node) ->
{postfix} = node
if postfix
operator = sourceCode.getLastToken node
prevToken = sourceCode.getTokenBefore operator
hasWhitespace = sourceCode.isSpaceBetweenTokens prevToken, operator
else
operator = sourceCode.getFirstToken node
nextToken = sourceCode.getTokenAfter operator
hasWhitespace = sourceCode.isSpaceBetweenTokens operator, nextToken
switch node.type
when 'SpreadElement'
type = 'spread'
if node.parent.type is 'ObjectExpression' then type += ' property'
when 'RestElement'
type = 'rest'
if node.parent.type is 'ObjectPattern' then type += ' property'
when 'ExperimentalSpreadProperty'
type = 'spread property'
when 'ExperimentalRestProperty'
type = 'rest property'
else
return
if alwaysSpace and not hasWhitespace
context.report {
node
loc:
line: operator.loc.end.line
column: operator.loc.end.column
message: "Expected whitespace #{
if postfix then 'before' else 'after'
} {{type}} operator."
data: {
type
}
fix: (fixer) ->
fixer.replaceTextRange(
if postfix
[prevToken.range[1], operator.range[0]]
else
[operator.range[1], nextToken.range[0]]
,
' '
)
}
else if not alwaysSpace and hasWhitespace
context.report {
node
loc:
line: operator.loc.end.line
column: operator.loc.end.column
message: "Unexpected whitespace #{
if postfix then 'before' else 'after'
} {{type}} operator."
data: {
type
}
fix: (fixer) ->
fixer.removeRange(
if postfix
[prevToken.range[1], operator.range[0]]
else
[operator.range[1], nextToken.range[0]]
)
}
#--------------------------------------------------------------------------
# Public
#--------------------------------------------------------------------------
SpreadElement: checkWhiteSpace
RestElement: checkWhiteSpace
ExperimentalSpreadProperty: checkWhiteSpace
ExperimentalRestProperty: checkWhiteSpace
| 215841 | ###*
# @fileoverview Enforce spacing between rest and spread operators and their expressions.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description:
'enforce spacing between rest and spread operators and their expressions'
category: 'ECMAScript 6'
recommended: no
url: 'https://eslint.org/docs/rules/rest-spread-spacing'
fixable: 'whitespace'
schema: [enum: ['always', 'never']]
create: (context) ->
sourceCode = context.getSourceCode()
alwaysSpace = context.options[0] is 'always'
#--------------------------------------------------------------------------
# Helpers
#--------------------------------------------------------------------------
###*
# Checks whitespace between rest/spread operators and their expressions
# @param {ASTNode} node - The node to check
# @returns {void}
###
checkWhiteSpace = (node) ->
{postfix} = node
if postfix
operator = sourceCode.getLastToken node
prevToken = sourceCode.getTokenBefore operator
hasWhitespace = sourceCode.isSpaceBetweenTokens prevToken, operator
else
operator = sourceCode.getFirstToken node
nextToken = sourceCode.getTokenAfter operator
hasWhitespace = sourceCode.isSpaceBetweenTokens operator, nextToken
switch node.type
when 'SpreadElement'
type = 'spread'
if node.parent.type is 'ObjectExpression' then type += ' property'
when 'RestElement'
type = 'rest'
if node.parent.type is 'ObjectPattern' then type += ' property'
when 'ExperimentalSpreadProperty'
type = 'spread property'
when 'ExperimentalRestProperty'
type = 'rest property'
else
return
if alwaysSpace and not hasWhitespace
context.report {
node
loc:
line: operator.loc.end.line
column: operator.loc.end.column
message: "Expected whitespace #{
if postfix then 'before' else 'after'
} {{type}} operator."
data: {
type
}
fix: (fixer) ->
fixer.replaceTextRange(
if postfix
[prevToken.range[1], operator.range[0]]
else
[operator.range[1], nextToken.range[0]]
,
' '
)
}
else if not alwaysSpace and hasWhitespace
context.report {
node
loc:
line: operator.loc.end.line
column: operator.loc.end.column
message: "Unexpected whitespace #{
if postfix then 'before' else 'after'
} {{type}} operator."
data: {
type
}
fix: (fixer) ->
fixer.removeRange(
if postfix
[prevToken.range[1], operator.range[0]]
else
[operator.range[1], nextToken.range[0]]
)
}
#--------------------------------------------------------------------------
# Public
#--------------------------------------------------------------------------
SpreadElement: checkWhiteSpace
RestElement: checkWhiteSpace
ExperimentalSpreadProperty: checkWhiteSpace
ExperimentalRestProperty: checkWhiteSpace
| true | ###*
# @fileoverview Enforce spacing between rest and spread operators and their expressions.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description:
'enforce spacing between rest and spread operators and their expressions'
category: 'ECMAScript 6'
recommended: no
url: 'https://eslint.org/docs/rules/rest-spread-spacing'
fixable: 'whitespace'
schema: [enum: ['always', 'never']]
create: (context) ->
sourceCode = context.getSourceCode()
alwaysSpace = context.options[0] is 'always'
#--------------------------------------------------------------------------
# Helpers
#--------------------------------------------------------------------------
###*
# Checks whitespace between rest/spread operators and their expressions
# @param {ASTNode} node - The node to check
# @returns {void}
###
checkWhiteSpace = (node) ->
{postfix} = node
if postfix
operator = sourceCode.getLastToken node
prevToken = sourceCode.getTokenBefore operator
hasWhitespace = sourceCode.isSpaceBetweenTokens prevToken, operator
else
operator = sourceCode.getFirstToken node
nextToken = sourceCode.getTokenAfter operator
hasWhitespace = sourceCode.isSpaceBetweenTokens operator, nextToken
switch node.type
when 'SpreadElement'
type = 'spread'
if node.parent.type is 'ObjectExpression' then type += ' property'
when 'RestElement'
type = 'rest'
if node.parent.type is 'ObjectPattern' then type += ' property'
when 'ExperimentalSpreadProperty'
type = 'spread property'
when 'ExperimentalRestProperty'
type = 'rest property'
else
return
if alwaysSpace and not hasWhitespace
context.report {
node
loc:
line: operator.loc.end.line
column: operator.loc.end.column
message: "Expected whitespace #{
if postfix then 'before' else 'after'
} {{type}} operator."
data: {
type
}
fix: (fixer) ->
fixer.replaceTextRange(
if postfix
[prevToken.range[1], operator.range[0]]
else
[operator.range[1], nextToken.range[0]]
,
' '
)
}
else if not alwaysSpace and hasWhitespace
context.report {
node
loc:
line: operator.loc.end.line
column: operator.loc.end.column
message: "Unexpected whitespace #{
if postfix then 'before' else 'after'
} {{type}} operator."
data: {
type
}
fix: (fixer) ->
fixer.removeRange(
if postfix
[prevToken.range[1], operator.range[0]]
else
[operator.range[1], nextToken.range[0]]
)
}
#--------------------------------------------------------------------------
# Public
#--------------------------------------------------------------------------
SpreadElement: checkWhiteSpace
RestElement: checkWhiteSpace
ExperimentalSpreadProperty: checkWhiteSpace
ExperimentalRestProperty: checkWhiteSpace
|
[
{
"context": "ipt.\n So make your changes in the .coffee file.\n Thatcher Peskens\n _\n ,_(')<\n \\___)\n###\n\ndo @myTe",
"end": 139,
"score": 0.9998021721839905,
"start": 123,
"tag": "NAME",
"value": "Thatcher Peskens"
},
{
"context": "\n {\n \"Authori... | whisk_tutorial/static/js/terminal.coffee | apache/openwhisk-tutorial | 2 | ###
Please note the javascript is being fully generated from coffeescript.
So make your changes in the .coffee file.
Thatcher Peskens
_
,_(')<
\___)
###
do @myTerminal = ->
# Which terminal emulator version are we
EMULATOR_VERSION = "0.1.3"
@basesettings = {
prompt: 'you@tutorial:~$ ',
greetings: """
Welcome to the interactive OpenWhisk CLI tutorial
"""
}
###
Callback definitions. These can be overridden by functions anywhere else
###
@preventDefaultCallback = false
@immediateCallback = (command) ->
console.debug("immediate callback from #{command}")
return
@finishedCallback = (command) ->
console.debug("finished callback from #{command}")
return
@intermediateResults = (string) ->
console.debug("sent #{string}")
return
###
Base interpreter
###
@interpreter = (input, term) ->
inputs = input.split(" ")
command = inputs[0]
if command is 'hi'
term.echo 'hi there! What is your name??'
term.push (command, term) ->
term.echo command + ' is a pretty name'
else if command is 'shell'
term.push (command, term) ->
if command is 'cd'
bash(term, inputs)
, {prompt: '> $ '}
else if command is 'r'
location.reload('forceGet')
else if command is '#'
term.echo 'which question?'
else if command is 'test'
term.echo 'I have to keep testing myself.'
else if command is 'cd'
bash(term, inputs)
else if command is "wsk"
wsk(term, inputs)
else if command is "help"
term.echo help
else if command is "ls"
term.echo "This is an emulator, not a shell. Try following the instructions."
else if command is "pull"
term.echo '[[b;#fff;]some text]'
wait(term, 5000, true)
alert term.get_output()
return
## finally
else if command
term.echo "#{inputs[0]}: command not found"
immediateCallback(inputs)
### =======================================
Common utils
======================================= ###
String.prototype.beginsWith = (string) ->
###
Check if 'this' string starts with the inputstring.
###
return(this.indexOf(string) is 0)
Array.prototype.containsAllOfThese = (inputArr) ->
###
This function compares all of the elements in the inputArr
and checks them one by one if they exist in 'this'. When it
finds an element to not exist, it returns false.
###
me = this
valid = false
if inputArr
valid = inputArr.every( (value) ->
if me.indexOf(value) == -1
return false
else
return true
)
return valid
Array.prototype.containsAllOfTheseParts = (inputArr) ->
###
This function is like containsAllofThese, but also matches partial strings.
###
me = this
if inputArr
valid = inputArr.every( (value) ->
for item in me
if item.match(value)
return true
return false
)
return valid
parseInput = (inputs) ->
command = inputs[1]
switches = []
switchArg = false
switchArgs = []
imagename = ""
commands = []
j = 0
# parse args
for input in inputs
if input.startsWith('-') and imagename == ""
switches.push(input)
if switches.length > 0
if not ['-i', '-t', '-d'].containsAllOfThese([input])
switchArg = true
else if switchArg == true
# reset switchArg
switchArg = false
switchArgs.push(input)
else if j > 1 and imagename == ""
# match wrong names
imagename = input
else if imagename != ""
commands.push (input)
else
# nothing?
j++
parsed_input = {
'switches': switches.sortBy(),
'switchArgs': switchArgs,
'imageName': imagename,
'commands': commands,
}
return parsed_input
util_slow_lines = (term, paragraph, keyword, finishedCallback) ->
if keyword
lines = paragraph(keyword).split("\n")
else
lines = paragraph.split("\n")
term.pause()
i = 0
# function calls itself after timeout is done, until
# all lines are finished
foo = (lines) ->
self.setTimeout ( ->
if lines[i]
term.echo (lines[i])
i++
foo(lines)
else
term.resume()
finishedCallback()
), 1000
foo(lines)
wait = (term, time, dots) ->
term.echo "starting to wait"
interval_id = self.setInterval ( -> dots ? term.insert '.'), 500
self.setTimeout ( ->
self.clearInterval(interval_id)
output = term.get_command()
term.echo output
term.echo "done "
), time
###
Bash program
###
bash = (term, inputs) ->
echo = term.echo
insert = term.insert
if not inputs[1]
console.log("none")
else
argument = inputs[1]
if argument.beginsWith('..')
echo "-bash: cd: #{argument}: Permission denied"
else
echo "-bash: cd: #{argument}: No such file or directory"
#---------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------
# WSK I N T E R P R E T E R --------------------------------------------------------
#---------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------
cat = (term, inputs) ->
echo = term.echo
if inputs[1] is "hello.js"
echo wsk_cat_helloWorld
return
wsk = (term, inputs) ->
echo = term.echo
insert = term.insert
callback = () -> @finishedCallback(inputs)
command = inputs[1]
# no command
if not inputs[1]
console.debug "no args"
echo wsk_no_args
else if inputs[1] is "--help" or inputs[1] is "-h"
echo wsk_help
else if inputs[1] is "action"
if inputs[2] is "create"
if inputs[3] is "hello"
if inputs[4] is "hello.js"
echo wsk_create_action_hello
if inputs[3] is "sequenceOfActions"
if inputs[4] is "--sequence"
if inputs[5] is "/whisk.system/util/cat,/whisk.system/util/sort"
intermediateResults(0)
echo wsk_create_action_sequence
else
echo wsk_unrecognized_arguments
if inputs[3] is "helloPython"
if inputs[4] is "hello.py"
echo wsk_create_action_python
else if inputs[2] is "list"
echo wsk_list_action_hello
else if inputs[2] is "invoke"
if inputs[3] is "hello"
echo wsk_action_invoke_hello
else if inputs[3] is "--blocking"
if inputs[4] is "hello"
echo wsk_action_invoke_blocking_hello
else
echo wsk_no_args
else if inputs[1] is "trigger"
if inputs[2] is "create"
if inputs[3] is "myTrigger"
intermediateResults(0)
echo wsk_trigger_created
if inputs[2] is "delete"
if inputs[3] is "myTrigger"
intermediateResults(0)
echo wsk_trigger_deleted
else if inputs[1] is "rule"
if inputs[2] is "create"
if inputs[3] is "myRule"
if inputs[4] is "myTrigger"
if inputs[5] is "hello"
intermediateResults(0)
echo wsk_rule_created
else if inputs[1] is "package"
if inputs[2] is "create"
if inputs[3] is "myPackage"
intermediateResults(0)
echo wsk_package_created
else if inputs[1] is "activation"
if inputs[2] is "result"
if inputs[3] is "6bf1f670ee614a7eb5af3c9fde813043"
echo wsk_activation_result
else if inputs[2] is "list"
echo wsk_activation_list
else if inputs[1] is "-v"
if inputs[2] is "action"
if inputs[3] is "create"
if inputs[4] is "hello"
if inputs[5] is "hello.js"
echo wsk_create_action_hello_v
else if inputs[1] is "images"
echo currentCloudImages
return
wsk_help = \
"""
Usage:
wsk [command]
Available Commands:
action work with actions
activation work with activations
package work with packages
rule work with rules
trigger work with triggers
sdk work with the sdk
property work with whisk properties
namespace work with namespaces
list list available namespaces
Flags:
--apihost HOST whisk API HOST
--apiversion VERSION whisk API VERSION
-u, --auth KEY authorization KEY
-d, --debug debug level output
-h, --help help for wsk
-i, --insecure bypass certificate checking
-v, --verbose verbose output
Use "wsk [command] --help" for more information about a command.
"""
wsk_invalid_choice = \
"""
usage: wsk [-h] [-v] [--apihost hostname] [--apiversion version]
{action,activation,namespace,package,rule,trigger,sdk,property,list}
...
wsk: error: argument cmd: invalid choice: (choose from 'action', 'activation', 'namespace', 'package', 'rule', 'trigger', 'sdk', 'property', 'list')
"""
wsk_trigger_created = \
"""
ok: created trigger myTrigger
"""
wsk_trigger_deleted = \
"""
ok deleted myTrigger
"""
wsk_rule_created = \
"""
ok: created rule myRule
"""
wsk_package_created = \
"""
ok: create package myPackage
"""
wsk_cat_helloWorld = \
"""
function main(params) {
return {payload: 'Hello world'};
}
"""
wsk_create_action_hello = \
"""
ok: created action hello
"""
wsk_create_action_python = \
"""
ok: created action helloPython
"""
wsk_create_action_hello_v = \
"""
{'apihost': 'openwhisk.ng.bluemix.net', 'namespace': 'jstart', 'clibuild': '2016-03-03T09:55:47-06:00', 'apiversion': 'v1'}
========
REQUEST:
PUT https://openwhisk.ng.bluemix.net/api/v1/namespaces/jstart/actions/hello
Headers sent:
{
"Authorization": "Basic
UyLWJJkYu65JKhu7YjM0ZDcwODhlNzBiOmlFS3RWMHl0UWdIT1SxUGNrMUFJRHUzSF2VlFSV53hDUnZlVXhyMGJpbTBGeH827=",
"Content-Type": "application/json"
}
Body sent:
{"exec": {"kind": "nodejs", "code": "function main(params) {\n return {payload: 'Hello, ' + params.name + ' from ' + params.place};\n}\n\n"}}
--------
RESPONSE:
Got response with code 200
Body received:
{
"name": "hello",
"publish": false,
"annotations": [],
"version": "0.0.1",
"exec": {
"kind": "nodejs",
"code": "function main(params) {\n return {payload: 'Hello, ' + params.name + ' from ' + params.place};\n}\n\n"
},
"parameters": [],
"limits": {
"timeout": 60000,
"memory": 256
},
"namespace": "jstart"
}
========
ok: created action hello
"""
wsk_list_action_hello = \
"""
actions
hello private
"""
wsk_action_invoke_hello = \
"""
ok: invoked hello with id 6bf1f670ee614a7eb5af3c9fde813043
"""
wsk_action_invoke_blocking_hello = \
"""
ok: invoked hello with id 44794bd6aab74415b4e42a308d880e5b
response:
{
"result": {
"payload": "Hello world"
},
"status": "success",
"success": true
}
"""
wsk_activation_result = \
"""
{
"payload" : "Hello world"
}
"""
wsk_activation_list = \
"""
activations
44794bd6aab74415b4e42a308d880e5b hello
6bf1f670ee614a7eb5af3c9fde813043 hello
"""
wsk_no_args = \
"""
Usage:
wsk [command]
Available Commands:
action work with actions
activation work with activations
package work with packages
rule work with rules
trigger work with triggers
sdk work with the sdk
property work with whisk properties
namespace work with namespaces
list list available namespaces
Flags:
--apihost HOST whisk API HOST
--apiversion VERSION whisk API VERSION
-u, --auth KEY authorization KEY
-d, --debug debug level output
-h, --help help for wsk
-i, --insecure bypass certificate checking
-v, --verbose verbose output
Use "wsk [command] --help" for more information about a command.
"""
wsk_create_action_sequence = \
"""
ok: created action sequenceOfActions
"""
wsk_unrecognized_arguments = \
"""
Usage:
wsk [command]
Available Commands:
action work with actions
activation work with activations
package work with packages
rule work with rules
trigger work with triggers
sdk work with the sdk
property work with whisk properties
namespace work with namespaces
list list available namespaces
Flags:
--apihost HOST whisk API HOST
--apiversion VERSION whisk API VERSION
-u, --auth KEY authorization KEY
-d, --debug debug level output
-h, --help help for wsk
-i, --insecure bypass certificate checking
-v, --verbose verbose output
Use "wsk [command] --help" for more information about a command.
"""
wsk_package_get = \
"""
package /whisk.system/util
action /whisk.system/util/cat: Concatenate array of strings, and split lines into an array
action /whisk.system/util/head: Filter first K array elements and discard rest
action /whisk.system/util/date: Get current date and time
action /whisk.system/util/sort: Sort array
"""
return this | 209032 | ###
Please note the javascript is being fully generated from coffeescript.
So make your changes in the .coffee file.
<NAME>
_
,_(')<
\___)
###
do @myTerminal = ->
# Which terminal emulator version are we
EMULATOR_VERSION = "0.1.3"
@basesettings = {
prompt: 'you@tutorial:~$ ',
greetings: """
Welcome to the interactive OpenWhisk CLI tutorial
"""
}
###
Callback definitions. These can be overridden by functions anywhere else
###
@preventDefaultCallback = false
@immediateCallback = (command) ->
console.debug("immediate callback from #{command}")
return
@finishedCallback = (command) ->
console.debug("finished callback from #{command}")
return
@intermediateResults = (string) ->
console.debug("sent #{string}")
return
###
Base interpreter
###
@interpreter = (input, term) ->
inputs = input.split(" ")
command = inputs[0]
if command is 'hi'
term.echo 'hi there! What is your name??'
term.push (command, term) ->
term.echo command + ' is a pretty name'
else if command is 'shell'
term.push (command, term) ->
if command is 'cd'
bash(term, inputs)
, {prompt: '> $ '}
else if command is 'r'
location.reload('forceGet')
else if command is '#'
term.echo 'which question?'
else if command is 'test'
term.echo 'I have to keep testing myself.'
else if command is 'cd'
bash(term, inputs)
else if command is "wsk"
wsk(term, inputs)
else if command is "help"
term.echo help
else if command is "ls"
term.echo "This is an emulator, not a shell. Try following the instructions."
else if command is "pull"
term.echo '[[b;#fff;]some text]'
wait(term, 5000, true)
alert term.get_output()
return
## finally
else if command
term.echo "#{inputs[0]}: command not found"
immediateCallback(inputs)
### =======================================
Common utils
======================================= ###
String.prototype.beginsWith = (string) ->
###
Check if 'this' string starts with the inputstring.
###
return(this.indexOf(string) is 0)
Array.prototype.containsAllOfThese = (inputArr) ->
###
This function compares all of the elements in the inputArr
and checks them one by one if they exist in 'this'. When it
finds an element to not exist, it returns false.
###
me = this
valid = false
if inputArr
valid = inputArr.every( (value) ->
if me.indexOf(value) == -1
return false
else
return true
)
return valid
Array.prototype.containsAllOfTheseParts = (inputArr) ->
###
This function is like containsAllofThese, but also matches partial strings.
###
me = this
if inputArr
valid = inputArr.every( (value) ->
for item in me
if item.match(value)
return true
return false
)
return valid
parseInput = (inputs) ->
command = inputs[1]
switches = []
switchArg = false
switchArgs = []
imagename = ""
commands = []
j = 0
# parse args
for input in inputs
if input.startsWith('-') and imagename == ""
switches.push(input)
if switches.length > 0
if not ['-i', '-t', '-d'].containsAllOfThese([input])
switchArg = true
else if switchArg == true
# reset switchArg
switchArg = false
switchArgs.push(input)
else if j > 1 and imagename == ""
# match wrong names
imagename = input
else if imagename != ""
commands.push (input)
else
# nothing?
j++
parsed_input = {
'switches': switches.sortBy(),
'switchArgs': switchArgs,
'imageName': imagename,
'commands': commands,
}
return parsed_input
util_slow_lines = (term, paragraph, keyword, finishedCallback) ->
if keyword
lines = paragraph(keyword).split("\n")
else
lines = paragraph.split("\n")
term.pause()
i = 0
# function calls itself after timeout is done, until
# all lines are finished
foo = (lines) ->
self.setTimeout ( ->
if lines[i]
term.echo (lines[i])
i++
foo(lines)
else
term.resume()
finishedCallback()
), 1000
foo(lines)
wait = (term, time, dots) ->
term.echo "starting to wait"
interval_id = self.setInterval ( -> dots ? term.insert '.'), 500
self.setTimeout ( ->
self.clearInterval(interval_id)
output = term.get_command()
term.echo output
term.echo "done "
), time
###
Bash program
###
bash = (term, inputs) ->
echo = term.echo
insert = term.insert
if not inputs[1]
console.log("none")
else
argument = inputs[1]
if argument.beginsWith('..')
echo "-bash: cd: #{argument}: Permission denied"
else
echo "-bash: cd: #{argument}: No such file or directory"
#---------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------
# WSK I N T E R P R E T E R --------------------------------------------------------
#---------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------
cat = (term, inputs) ->
echo = term.echo
if inputs[1] is "hello.js"
echo wsk_cat_helloWorld
return
wsk = (term, inputs) ->
echo = term.echo
insert = term.insert
callback = () -> @finishedCallback(inputs)
command = inputs[1]
# no command
if not inputs[1]
console.debug "no args"
echo wsk_no_args
else if inputs[1] is "--help" or inputs[1] is "-h"
echo wsk_help
else if inputs[1] is "action"
if inputs[2] is "create"
if inputs[3] is "hello"
if inputs[4] is "hello.js"
echo wsk_create_action_hello
if inputs[3] is "sequenceOfActions"
if inputs[4] is "--sequence"
if inputs[5] is "/whisk.system/util/cat,/whisk.system/util/sort"
intermediateResults(0)
echo wsk_create_action_sequence
else
echo wsk_unrecognized_arguments
if inputs[3] is "helloPython"
if inputs[4] is "hello.py"
echo wsk_create_action_python
else if inputs[2] is "list"
echo wsk_list_action_hello
else if inputs[2] is "invoke"
if inputs[3] is "hello"
echo wsk_action_invoke_hello
else if inputs[3] is "--blocking"
if inputs[4] is "hello"
echo wsk_action_invoke_blocking_hello
else
echo wsk_no_args
else if inputs[1] is "trigger"
if inputs[2] is "create"
if inputs[3] is "myTrigger"
intermediateResults(0)
echo wsk_trigger_created
if inputs[2] is "delete"
if inputs[3] is "myTrigger"
intermediateResults(0)
echo wsk_trigger_deleted
else if inputs[1] is "rule"
if inputs[2] is "create"
if inputs[3] is "myRule"
if inputs[4] is "myTrigger"
if inputs[5] is "hello"
intermediateResults(0)
echo wsk_rule_created
else if inputs[1] is "package"
if inputs[2] is "create"
if inputs[3] is "myPackage"
intermediateResults(0)
echo wsk_package_created
else if inputs[1] is "activation"
if inputs[2] is "result"
if inputs[3] is "6bf1f670ee614a7eb5af3c9fde813043"
echo wsk_activation_result
else if inputs[2] is "list"
echo wsk_activation_list
else if inputs[1] is "-v"
if inputs[2] is "action"
if inputs[3] is "create"
if inputs[4] is "hello"
if inputs[5] is "hello.js"
echo wsk_create_action_hello_v
else if inputs[1] is "images"
echo currentCloudImages
return
wsk_help = \
"""
Usage:
wsk [command]
Available Commands:
action work with actions
activation work with activations
package work with packages
rule work with rules
trigger work with triggers
sdk work with the sdk
property work with whisk properties
namespace work with namespaces
list list available namespaces
Flags:
--apihost HOST whisk API HOST
--apiversion VERSION whisk API VERSION
-u, --auth KEY authorization KEY
-d, --debug debug level output
-h, --help help for wsk
-i, --insecure bypass certificate checking
-v, --verbose verbose output
Use "wsk [command] --help" for more information about a command.
"""
wsk_invalid_choice = \
"""
usage: wsk [-h] [-v] [--apihost hostname] [--apiversion version]
{action,activation,namespace,package,rule,trigger,sdk,property,list}
...
wsk: error: argument cmd: invalid choice: (choose from 'action', 'activation', 'namespace', 'package', 'rule', 'trigger', 'sdk', 'property', 'list')
"""
wsk_trigger_created = \
"""
ok: created trigger myTrigger
"""
wsk_trigger_deleted = \
"""
ok deleted myTrigger
"""
wsk_rule_created = \
"""
ok: created rule myRule
"""
wsk_package_created = \
"""
ok: create package myPackage
"""
wsk_cat_helloWorld = \
"""
function main(params) {
return {payload: 'Hello world'};
}
"""
wsk_create_action_hello = \
"""
ok: created action hello
"""
wsk_create_action_python = \
"""
ok: created action helloPython
"""
wsk_create_action_hello_v = \
"""
{'apihost': 'openwhisk.ng.bluemix.net', 'namespace': 'jstart', 'clibuild': '2016-03-03T09:55:47-06:00', 'apiversion': 'v1'}
========
REQUEST:
PUT https://openwhisk.ng.bluemix.net/api/v1/namespaces/jstart/actions/hello
Headers sent:
{
"Authorization": "Basic
U<KEY>
"Content-Type": "application/json"
}
Body sent:
{"exec": {"kind": "nodejs", "code": "function main(params) {\n return {payload: 'Hello, ' + params.name + ' from ' + params.place};\n}\n\n"}}
--------
RESPONSE:
Got response with code 200
Body received:
{
"name": "<NAME>",
"publish": false,
"annotations": [],
"version": "0.0.1",
"exec": {
"kind": "nodejs",
"code": "function main(params) {\n return {payload: 'Hello, ' + params.name + ' from ' + params.place};\n}\n\n"
},
"parameters": [],
"limits": {
"timeout": 60000,
"memory": 256
},
"namespace": "jstart"
}
========
ok: created action hello
"""
wsk_list_action_hello = \
"""
actions
hello private
"""
wsk_action_invoke_hello = \
"""
ok: invoked hello with id 6bf1f670ee614a7eb5af3c9fde813043
"""
wsk_action_invoke_blocking_hello = \
"""
ok: invoked hello with id 44794bd6aab74415b4e42a308d880e5b
response:
{
"result": {
"payload": "Hello world"
},
"status": "success",
"success": true
}
"""
wsk_activation_result = \
"""
{
"payload" : "Hello world"
}
"""
wsk_activation_list = \
"""
activations
44794bd6aab74415b4e42a308d880e5b hello
6bf1f670ee614a7eb5af3c9fde813043 hello
"""
wsk_no_args = \
"""
Usage:
wsk [command]
Available Commands:
action work with actions
activation work with activations
package work with packages
rule work with rules
trigger work with triggers
sdk work with the sdk
property work with whisk properties
namespace work with namespaces
list list available namespaces
Flags:
--apihost HOST whisk API HOST
--apiversion VERSION whisk API VERSION
-u, --auth KEY authorization KEY
-d, --debug debug level output
-h, --help help for wsk
-i, --insecure bypass certificate checking
-v, --verbose verbose output
Use "wsk [command] --help" for more information about a command.
"""
wsk_create_action_sequence = \
"""
ok: created action sequenceOfActions
"""
wsk_unrecognized_arguments = \
"""
Usage:
wsk [command]
Available Commands:
action work with actions
activation work with activations
package work with packages
rule work with rules
trigger work with triggers
sdk work with the sdk
property work with whisk properties
namespace work with namespaces
list list available namespaces
Flags:
--apihost HOST whisk API HOST
--apiversion VERSION whisk API VERSION
-u, --auth KEY authorization KEY
-d, --debug debug level output
-h, --help help for wsk
-i, --insecure bypass certificate checking
-v, --verbose verbose output
Use "wsk [command] --help" for more information about a command.
"""
wsk_package_get = \
"""
package /whisk.system/util
action /whisk.system/util/cat: Concatenate array of strings, and split lines into an array
action /whisk.system/util/head: Filter first K array elements and discard rest
action /whisk.system/util/date: Get current date and time
action /whisk.system/util/sort: Sort array
"""
return this | true | ###
Please note the javascript is being fully generated from coffeescript.
So make your changes in the .coffee file.
PI:NAME:<NAME>END_PI
_
,_(')<
\___)
###
do @myTerminal = ->
# Which terminal emulator version are we
EMULATOR_VERSION = "0.1.3"
@basesettings = {
prompt: 'you@tutorial:~$ ',
greetings: """
Welcome to the interactive OpenWhisk CLI tutorial
"""
}
###
Callback definitions. These can be overridden by functions anywhere else
###
@preventDefaultCallback = false
@immediateCallback = (command) ->
console.debug("immediate callback from #{command}")
return
@finishedCallback = (command) ->
console.debug("finished callback from #{command}")
return
@intermediateResults = (string) ->
console.debug("sent #{string}")
return
###
Base interpreter
###
@interpreter = (input, term) ->
inputs = input.split(" ")
command = inputs[0]
if command is 'hi'
term.echo 'hi there! What is your name??'
term.push (command, term) ->
term.echo command + ' is a pretty name'
else if command is 'shell'
term.push (command, term) ->
if command is 'cd'
bash(term, inputs)
, {prompt: '> $ '}
else if command is 'r'
location.reload('forceGet')
else if command is '#'
term.echo 'which question?'
else if command is 'test'
term.echo 'I have to keep testing myself.'
else if command is 'cd'
bash(term, inputs)
else if command is "wsk"
wsk(term, inputs)
else if command is "help"
term.echo help
else if command is "ls"
term.echo "This is an emulator, not a shell. Try following the instructions."
else if command is "pull"
term.echo '[[b;#fff;]some text]'
wait(term, 5000, true)
alert term.get_output()
return
## finally
else if command
term.echo "#{inputs[0]}: command not found"
immediateCallback(inputs)
### =======================================
Common utils
======================================= ###
String.prototype.beginsWith = (string) ->
###
Check if 'this' string starts with the inputstring.
###
return(this.indexOf(string) is 0)
Array.prototype.containsAllOfThese = (inputArr) ->
###
This function compares all of the elements in the inputArr
and checks them one by one if they exist in 'this'. When it
finds an element to not exist, it returns false.
###
me = this
valid = false
if inputArr
valid = inputArr.every( (value) ->
if me.indexOf(value) == -1
return false
else
return true
)
return valid
Array.prototype.containsAllOfTheseParts = (inputArr) ->
###
This function is like containsAllofThese, but also matches partial strings.
###
me = this
if inputArr
valid = inputArr.every( (value) ->
for item in me
if item.match(value)
return true
return false
)
return valid
parseInput = (inputs) ->
command = inputs[1]
switches = []
switchArg = false
switchArgs = []
imagename = ""
commands = []
j = 0
# parse args
for input in inputs
if input.startsWith('-') and imagename == ""
switches.push(input)
if switches.length > 0
if not ['-i', '-t', '-d'].containsAllOfThese([input])
switchArg = true
else if switchArg == true
# reset switchArg
switchArg = false
switchArgs.push(input)
else if j > 1 and imagename == ""
# match wrong names
imagename = input
else if imagename != ""
commands.push (input)
else
# nothing?
j++
parsed_input = {
'switches': switches.sortBy(),
'switchArgs': switchArgs,
'imageName': imagename,
'commands': commands,
}
return parsed_input
util_slow_lines = (term, paragraph, keyword, finishedCallback) ->
if keyword
lines = paragraph(keyword).split("\n")
else
lines = paragraph.split("\n")
term.pause()
i = 0
# function calls itself after timeout is done, until
# all lines are finished
foo = (lines) ->
self.setTimeout ( ->
if lines[i]
term.echo (lines[i])
i++
foo(lines)
else
term.resume()
finishedCallback()
), 1000
foo(lines)
wait = (term, time, dots) ->
term.echo "starting to wait"
interval_id = self.setInterval ( -> dots ? term.insert '.'), 500
self.setTimeout ( ->
self.clearInterval(interval_id)
output = term.get_command()
term.echo output
term.echo "done "
), time
###
Bash program
###
bash = (term, inputs) ->
echo = term.echo
insert = term.insert
if not inputs[1]
console.log("none")
else
argument = inputs[1]
if argument.beginsWith('..')
echo "-bash: cd: #{argument}: Permission denied"
else
echo "-bash: cd: #{argument}: No such file or directory"
#---------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------
# WSK I N T E R P R E T E R --------------------------------------------------------
#---------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------
cat = (term, inputs) ->
echo = term.echo
if inputs[1] is "hello.js"
echo wsk_cat_helloWorld
return
wsk = (term, inputs) ->
echo = term.echo
insert = term.insert
callback = () -> @finishedCallback(inputs)
command = inputs[1]
# no command
if not inputs[1]
console.debug "no args"
echo wsk_no_args
else if inputs[1] is "--help" or inputs[1] is "-h"
echo wsk_help
else if inputs[1] is "action"
if inputs[2] is "create"
if inputs[3] is "hello"
if inputs[4] is "hello.js"
echo wsk_create_action_hello
if inputs[3] is "sequenceOfActions"
if inputs[4] is "--sequence"
if inputs[5] is "/whisk.system/util/cat,/whisk.system/util/sort"
intermediateResults(0)
echo wsk_create_action_sequence
else
echo wsk_unrecognized_arguments
if inputs[3] is "helloPython"
if inputs[4] is "hello.py"
echo wsk_create_action_python
else if inputs[2] is "list"
echo wsk_list_action_hello
else if inputs[2] is "invoke"
if inputs[3] is "hello"
echo wsk_action_invoke_hello
else if inputs[3] is "--blocking"
if inputs[4] is "hello"
echo wsk_action_invoke_blocking_hello
else
echo wsk_no_args
else if inputs[1] is "trigger"
if inputs[2] is "create"
if inputs[3] is "myTrigger"
intermediateResults(0)
echo wsk_trigger_created
if inputs[2] is "delete"
if inputs[3] is "myTrigger"
intermediateResults(0)
echo wsk_trigger_deleted
else if inputs[1] is "rule"
if inputs[2] is "create"
if inputs[3] is "myRule"
if inputs[4] is "myTrigger"
if inputs[5] is "hello"
intermediateResults(0)
echo wsk_rule_created
else if inputs[1] is "package"
if inputs[2] is "create"
if inputs[3] is "myPackage"
intermediateResults(0)
echo wsk_package_created
else if inputs[1] is "activation"
if inputs[2] is "result"
if inputs[3] is "6bf1f670ee614a7eb5af3c9fde813043"
echo wsk_activation_result
else if inputs[2] is "list"
echo wsk_activation_list
else if inputs[1] is "-v"
if inputs[2] is "action"
if inputs[3] is "create"
if inputs[4] is "hello"
if inputs[5] is "hello.js"
echo wsk_create_action_hello_v
else if inputs[1] is "images"
echo currentCloudImages
return
wsk_help = \
"""
Usage:
wsk [command]
Available Commands:
action work with actions
activation work with activations
package work with packages
rule work with rules
trigger work with triggers
sdk work with the sdk
property work with whisk properties
namespace work with namespaces
list list available namespaces
Flags:
--apihost HOST whisk API HOST
--apiversion VERSION whisk API VERSION
-u, --auth KEY authorization KEY
-d, --debug debug level output
-h, --help help for wsk
-i, --insecure bypass certificate checking
-v, --verbose verbose output
Use "wsk [command] --help" for more information about a command.
"""
wsk_invalid_choice = \
"""
usage: wsk [-h] [-v] [--apihost hostname] [--apiversion version]
{action,activation,namespace,package,rule,trigger,sdk,property,list}
...
wsk: error: argument cmd: invalid choice: (choose from 'action', 'activation', 'namespace', 'package', 'rule', 'trigger', 'sdk', 'property', 'list')
"""
wsk_trigger_created = \
"""
ok: created trigger myTrigger
"""
wsk_trigger_deleted = \
"""
ok deleted myTrigger
"""
wsk_rule_created = \
"""
ok: created rule myRule
"""
wsk_package_created = \
"""
ok: create package myPackage
"""
wsk_cat_helloWorld = \
"""
function main(params) {
return {payload: 'Hello world'};
}
"""
wsk_create_action_hello = \
"""
ok: created action hello
"""
wsk_create_action_python = \
"""
ok: created action helloPython
"""
wsk_create_action_hello_v = \
"""
{'apihost': 'openwhisk.ng.bluemix.net', 'namespace': 'jstart', 'clibuild': '2016-03-03T09:55:47-06:00', 'apiversion': 'v1'}
========
REQUEST:
PUT https://openwhisk.ng.bluemix.net/api/v1/namespaces/jstart/actions/hello
Headers sent:
{
"Authorization": "Basic
UPI:KEY:<KEY>END_PI
"Content-Type": "application/json"
}
Body sent:
{"exec": {"kind": "nodejs", "code": "function main(params) {\n return {payload: 'Hello, ' + params.name + ' from ' + params.place};\n}\n\n"}}
--------
RESPONSE:
Got response with code 200
Body received:
{
"name": "PI:NAME:<NAME>END_PI",
"publish": false,
"annotations": [],
"version": "0.0.1",
"exec": {
"kind": "nodejs",
"code": "function main(params) {\n return {payload: 'Hello, ' + params.name + ' from ' + params.place};\n}\n\n"
},
"parameters": [],
"limits": {
"timeout": 60000,
"memory": 256
},
"namespace": "jstart"
}
========
ok: created action hello
"""
wsk_list_action_hello = \
"""
actions
hello private
"""
wsk_action_invoke_hello = \
"""
ok: invoked hello with id 6bf1f670ee614a7eb5af3c9fde813043
"""
wsk_action_invoke_blocking_hello = \
"""
ok: invoked hello with id 44794bd6aab74415b4e42a308d880e5b
response:
{
"result": {
"payload": "Hello world"
},
"status": "success",
"success": true
}
"""
wsk_activation_result = \
"""
{
"payload" : "Hello world"
}
"""
wsk_activation_list = \
"""
activations
44794bd6aab74415b4e42a308d880e5b hello
6bf1f670ee614a7eb5af3c9fde813043 hello
"""
wsk_no_args = \
"""
Usage:
wsk [command]
Available Commands:
action work with actions
activation work with activations
package work with packages
rule work with rules
trigger work with triggers
sdk work with the sdk
property work with whisk properties
namespace work with namespaces
list list available namespaces
Flags:
--apihost HOST whisk API HOST
--apiversion VERSION whisk API VERSION
-u, --auth KEY authorization KEY
-d, --debug debug level output
-h, --help help for wsk
-i, --insecure bypass certificate checking
-v, --verbose verbose output
Use "wsk [command] --help" for more information about a command.
"""
wsk_create_action_sequence = \
"""
ok: created action sequenceOfActions
"""
wsk_unrecognized_arguments = \
"""
Usage:
wsk [command]
Available Commands:
action work with actions
activation work with activations
package work with packages
rule work with rules
trigger work with triggers
sdk work with the sdk
property work with whisk properties
namespace work with namespaces
list list available namespaces
Flags:
--apihost HOST whisk API HOST
--apiversion VERSION whisk API VERSION
-u, --auth KEY authorization KEY
-d, --debug debug level output
-h, --help help for wsk
-i, --insecure bypass certificate checking
-v, --verbose verbose output
Use "wsk [command] --help" for more information about a command.
"""
wsk_package_get = \
"""
package /whisk.system/util
action /whisk.system/util/cat: Concatenate array of strings, and split lines into an array
action /whisk.system/util/head: Filter first K array elements and discard rest
action /whisk.system/util/date: Get current date and time
action /whisk.system/util/sort: Sort array
"""
return this |
[
{
"context": "# @link http://podstats.org/\n# @author Dennis Morhardt <info@dennismorhardt.de>\n# @copyright Copyright",
"end": 93,
"score": 0.9998766779899597,
"start": 78,
"tag": "NAME",
"value": "Dennis Morhardt"
},
{
"context": "p://podstats.org/\n# @author Den... | Application/Assets/javascripts/components/download-timeline.coffee | gglnx/podstats | 0 | ##
# @package Podstats
# @link http://podstats.org/
# @author Dennis Morhardt <info@dennismorhardt.de>
# @copyright Copyright 2014, Dennis Morhardt
# @license BSD-3-Clause, http://opensource.org/licenses/BSD-3-Clause
##
# Download timeline
define ['jquery', 'moment', 'Raphael', 'morris'], ($, moment, Raphael) -> $ ()->
$('[data-type="download-timeline"]').each (index, el)->
# Setup moment
moment.lang 'de'
# 1. Get data from API
$.ajax
url: $(el).data 'source'
dataType: 'json'
# 2. Generate graph
.done (response)->
# Check if response is ok and we got data
if response.ok == false or response.data? == false
return
# Remove loading class
$(el).removeClass 'graph-loading'
# No data? Show message
if response.data.length == 0
$(el).addClass 'no-data'
$(el).parent().addClass 'no-data'
$(el).append 'Keine Daten für diesen Zeitraum vorhanden.'
return
# Init morris
new Morris.Area
element: $(el).attr 'id'
data: response.data
gridTextFamily: '"PT Sans", Helmet, Freesans, sans-serif'
xkey: 'date'
fillOpacity: 0.4
resize: true
xLabels: $(el).data 'xlabel'
hideHover: true
hoverCallback: (index, options, content)->
row = options.data[index]
'<div class="morris-hover-row-label">' + moment(row.date).format('DD.MM.YYYY') + '</div><div class="morris-hover-point" style="color: #0b62a4">Downloads: ' + row.downloads + '</div>'
xLabelFormat: (date)->
moment(date).format $(el).data 'xlabel-format'
ykeys: ['downloads']
labels: ['Downloads']
lineColors: ['#5C97BF']
| 192367 | ##
# @package Podstats
# @link http://podstats.org/
# @author <NAME> <<EMAIL>>
# @copyright Copyright 2014, <NAME>
# @license BSD-3-Clause, http://opensource.org/licenses/BSD-3-Clause
##
# Download timeline
define ['jquery', 'moment', 'Raphael', 'morris'], ($, moment, Raphael) -> $ ()->
$('[data-type="download-timeline"]').each (index, el)->
# Setup moment
moment.lang 'de'
# 1. Get data from API
$.ajax
url: $(el).data 'source'
dataType: 'json'
# 2. Generate graph
.done (response)->
# Check if response is ok and we got data
if response.ok == false or response.data? == false
return
# Remove loading class
$(el).removeClass 'graph-loading'
# No data? Show message
if response.data.length == 0
$(el).addClass 'no-data'
$(el).parent().addClass 'no-data'
$(el).append 'Keine Daten für diesen Zeitraum vorhanden.'
return
# Init morris
new Morris.Area
element: $(el).attr 'id'
data: response.data
gridTextFamily: '"PT Sans", Helmet, Freesans, sans-serif'
xkey: 'date'
fillOpacity: 0.4
resize: true
xLabels: $(el).data 'xlabel'
hideHover: true
hoverCallback: (index, options, content)->
row = options.data[index]
'<div class="morris-hover-row-label">' + moment(row.date).format('DD.MM.YYYY') + '</div><div class="morris-hover-point" style="color: #0b62a4">Downloads: ' + row.downloads + '</div>'
xLabelFormat: (date)->
moment(date).format $(el).data 'xlabel-format'
ykeys: ['<KEY>']
labels: ['Downloads']
lineColors: ['#5C97BF']
| true | ##
# @package Podstats
# @link http://podstats.org/
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# @copyright Copyright 2014, PI:NAME:<NAME>END_PI
# @license BSD-3-Clause, http://opensource.org/licenses/BSD-3-Clause
##
# Download timeline
define ['jquery', 'moment', 'Raphael', 'morris'], ($, moment, Raphael) -> $ ()->
$('[data-type="download-timeline"]').each (index, el)->
# Setup moment
moment.lang 'de'
# 1. Get data from API
$.ajax
url: $(el).data 'source'
dataType: 'json'
# 2. Generate graph
.done (response)->
# Check if response is ok and we got data
if response.ok == false or response.data? == false
return
# Remove loading class
$(el).removeClass 'graph-loading'
# No data? Show message
if response.data.length == 0
$(el).addClass 'no-data'
$(el).parent().addClass 'no-data'
$(el).append 'Keine Daten für diesen Zeitraum vorhanden.'
return
# Init morris
new Morris.Area
element: $(el).attr 'id'
data: response.data
gridTextFamily: '"PT Sans", Helmet, Freesans, sans-serif'
xkey: 'date'
fillOpacity: 0.4
resize: true
xLabels: $(el).data 'xlabel'
hideHover: true
hoverCallback: (index, options, content)->
row = options.data[index]
'<div class="morris-hover-row-label">' + moment(row.date).format('DD.MM.YYYY') + '</div><div class="morris-hover-point" style="color: #0b62a4">Downloads: ' + row.downloads + '</div>'
xLabelFormat: (date)->
moment(date).format $(el).data 'xlabel-format'
ykeys: ['PI:KEY:<KEY>END_PI']
labels: ['Downloads']
lineColors: ['#5C97BF']
|
[
{
"context": "###\n Author: ec.huyinghuan@gmail.com\n Date: 2015.07.07\n Describe:\n gitlab与项目相关关系的",
"end": 37,
"score": 0.9999063611030579,
"start": 14,
"tag": "EMAIL",
"value": "ec.huyinghuan@gmail.com"
}
] | src/js/gitlab/gitlab-controller.coffee | Kiteam/kiteam-angular | 0 | ###
Author: ec.huyinghuan@gmail.com
Date: 2015.07.07
Describe:
gitlab与项目相关关系的增删改
###
"use strict"
define [
'../ng-module'
'../utils'
], (_module, _utils) ->
_module.controllerModule.
controller('gitlabController',
['$rootScope', '$scope', '$stateParams', 'API', 'NOTIFY'
($rootScope, $scope, $stateParams, API, NOTIFY)->
projectAPI = API.project($stateParams.project_id)
getData = (name)->
projectAPI[name]().retrieve()
#删除一条gitlab关联记录
doDelGitMap = (id)->
projectAPI.gitlab(id).delete().then((result)->
NOTIFY.success("删除成功!")
$scope.$broadcast("component:gitlab:reload")
)
#fork 一个gitlab仓库
forkGit = (git_id)->
projectAPI.gitlab(git_id).fork().retrieve().then(->
NOTIFY.success("fork成功!")
$scope.$broadcast("component:gitlab:reload")
)
#给项目添加关联一个已存在的gitlab地址
addGitToProject = (gitlab_url)->
projectAPI.gitlab().update({gitlab_url: gitlab_url}).then(->
NOTIFY.success("添加成功!")
$scope.$broadcast("component:gitlab:reload")
$scope.$broadcast("component:gitlab_add_form:reset")
)
#创建一个新gitlab仓库并关联到项目
createGitForProject = (gitlab_name)->
projectAPI.gitlab().create({gitlab_name: gitlab_name}).then(->
NOTIFY.success("创建项目成功")
$scope.$broadcast("component:gitlab:reload")
$scope.$broadcast("component:gitlab_create_form:reset")
)
doAction = (name, value)->
switch name
when "fork"
forkGit value
when "del"
doDelGitMap value
when "add"
addGitToProject value
when "create"
createGitForProject value
$scope.bean = {
getData: getData
doAction: doAction
}
]) | 205760 | ###
Author: <EMAIL>
Date: 2015.07.07
Describe:
gitlab与项目相关关系的增删改
###
"use strict"
define [
'../ng-module'
'../utils'
], (_module, _utils) ->
_module.controllerModule.
controller('gitlabController',
['$rootScope', '$scope', '$stateParams', 'API', 'NOTIFY'
($rootScope, $scope, $stateParams, API, NOTIFY)->
projectAPI = API.project($stateParams.project_id)
getData = (name)->
projectAPI[name]().retrieve()
#删除一条gitlab关联记录
doDelGitMap = (id)->
projectAPI.gitlab(id).delete().then((result)->
NOTIFY.success("删除成功!")
$scope.$broadcast("component:gitlab:reload")
)
#fork 一个gitlab仓库
forkGit = (git_id)->
projectAPI.gitlab(git_id).fork().retrieve().then(->
NOTIFY.success("fork成功!")
$scope.$broadcast("component:gitlab:reload")
)
#给项目添加关联一个已存在的gitlab地址
addGitToProject = (gitlab_url)->
projectAPI.gitlab().update({gitlab_url: gitlab_url}).then(->
NOTIFY.success("添加成功!")
$scope.$broadcast("component:gitlab:reload")
$scope.$broadcast("component:gitlab_add_form:reset")
)
#创建一个新gitlab仓库并关联到项目
createGitForProject = (gitlab_name)->
projectAPI.gitlab().create({gitlab_name: gitlab_name}).then(->
NOTIFY.success("创建项目成功")
$scope.$broadcast("component:gitlab:reload")
$scope.$broadcast("component:gitlab_create_form:reset")
)
doAction = (name, value)->
switch name
when "fork"
forkGit value
when "del"
doDelGitMap value
when "add"
addGitToProject value
when "create"
createGitForProject value
$scope.bean = {
getData: getData
doAction: doAction
}
]) | true | ###
Author: PI:EMAIL:<EMAIL>END_PI
Date: 2015.07.07
Describe:
gitlab与项目相关关系的增删改
###
"use strict"
define [
'../ng-module'
'../utils'
], (_module, _utils) ->
_module.controllerModule.
controller('gitlabController',
['$rootScope', '$scope', '$stateParams', 'API', 'NOTIFY'
($rootScope, $scope, $stateParams, API, NOTIFY)->
projectAPI = API.project($stateParams.project_id)
getData = (name)->
projectAPI[name]().retrieve()
#删除一条gitlab关联记录
doDelGitMap = (id)->
projectAPI.gitlab(id).delete().then((result)->
NOTIFY.success("删除成功!")
$scope.$broadcast("component:gitlab:reload")
)
#fork 一个gitlab仓库
forkGit = (git_id)->
projectAPI.gitlab(git_id).fork().retrieve().then(->
NOTIFY.success("fork成功!")
$scope.$broadcast("component:gitlab:reload")
)
#给项目添加关联一个已存在的gitlab地址
addGitToProject = (gitlab_url)->
projectAPI.gitlab().update({gitlab_url: gitlab_url}).then(->
NOTIFY.success("添加成功!")
$scope.$broadcast("component:gitlab:reload")
$scope.$broadcast("component:gitlab_add_form:reset")
)
#创建一个新gitlab仓库并关联到项目
createGitForProject = (gitlab_name)->
projectAPI.gitlab().create({gitlab_name: gitlab_name}).then(->
NOTIFY.success("创建项目成功")
$scope.$broadcast("component:gitlab:reload")
$scope.$broadcast("component:gitlab_create_form:reset")
)
doAction = (name, value)->
switch name
when "fork"
forkGit value
when "del"
doDelGitMap value
when "add"
addGitToProject value
when "create"
createGitForProject value
$scope.bean = {
getData: getData
doAction: doAction
}
]) |
[
{
"context": "t(\"paananen\")\n userName = Bacon.constant(\"mr.bacon\")\n Bacon.combineTemplate({ userName: user",
"end": 28082,
"score": 0.9995568990707397,
"start": 28074,
"tag": "USERNAME",
"value": "mr.bacon"
},
{
"context": "tName, lastName: lastName }})\n [... | spec/BaconSpec.coffee | hden/testling-ci-playground | 0 | Bacon = (require "../src/Bacon").Bacon
Mocks = (require "./Mock")
mock = Mocks.mock
mockFunction = Mocks.mockFunction
EventEmitter = require("events").EventEmitter
th = require("./SpecHelper")
t = th.t
expectStreamEvents = th.expectStreamEvents
expectPropertyEvents = th.expectPropertyEvents
verifyCleanup = th.verifyCleanup
error = th.error
soon = th.soon
series = th.series
repeat = th.repeat
toValues = th.toValues
describe "Bacon.later", ->
it "should send single event and end", ->
expectStreamEvents(
-> Bacon.later(t(1), "lol")
["lol"])
describe "Bacon.sequentially", ->
it "should send given events and end", ->
expectStreamEvents(
-> Bacon.sequentially(t(1), ["lol", "wut"])
["lol", "wut"])
it "include error events", ->
expectStreamEvents(
-> Bacon.sequentially(t(1), [error(), "lol"])
[error(), "lol"])
describe "Bacon.interval", ->
it "repeats single element indefinitely", ->
expectStreamEvents(
-> Bacon.interval(t(1), "x").take(3)
["x", "x", "x"])
describe "Bacon.fromCallback", ->
it "makes an EventStream from function that takes a callback", ->
expectStreamEvents(
->
src = (callback) -> callback("lol")
stream = Bacon.fromCallback(src)
["lol"])
it "supports partial application", ->
expectStreamEvents(
->
src = (param, callback) -> callback(param)
stream = Bacon.fromCallback(src, "lol")
["lol"])
describe "Bacon.fromEventTarget", ->
it "should create EventStream from DOM object", ->
emitter = new EventEmitter()
emitter.on "newListener", ->
runs ->
emitter.emit "click", "x"
element = toEventTarget emitter
expectStreamEvents(
-> Bacon.fromEventTarget(element, "click").take(1)
["x"]
)
it "should create EventStream from EventEmitter", ->
emitter = new EventEmitter()
emitter.on "newListener", ->
runs ->
emitter.emit "data", "x"
expectStreamEvents(
-> Bacon.fromEventTarget(emitter, "data").take(1)
["x"]
)
it "should allow a custom map function for EventStream from EventEmitter", ->
emitter = new EventEmitter()
emitter.on "newListener", ->
runs ->
emitter.emit "data", "x", "y"
expectStreamEvents(
-> Bacon.fromEventTarget(emitter, "data", (x, y) => [x, y]).take(1)
[["x", "y"]]
)
it "should clean up event listeners from EventEmitter", ->
emitter = new EventEmitter()
Bacon.fromEventTarget(emitter, "data").take(1).subscribe ->
emitter.emit "data", "x"
expect(emitter.listeners("data").length).toEqual(0)
it "should clean up event listeners from DOM object", ->
emitter = new EventEmitter()
element = toEventTarget emitter
dispose = Bacon.fromEventTarget(element, "click").subscribe ->
dispose()
expect(emitter.listeners("click").length).toEqual(0)
describe "Observable.log", ->
it "does not crash", ->
Bacon.constant(1).log
describe "Observable.slidingWindow", ->
it "slides the window for EventStreams", ->
expectPropertyEvents(
-> series(1, [1,2,3]).slidingWindow(2)
[[], [1], [1,2], [2,3]])
it "slides the window for Properties", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty().slidingWindow(2)
[[], [1], [1,2], [2,3]])
describe "EventStream.filter", ->
it "should filter values", ->
expectStreamEvents(
-> series(1, [1, 2, error(), 3]).filter(lessThan(3))
[1, 2, error()])
it "extracts field values", ->
expectStreamEvents(
-> series(1, [{good:true, value:"yes"}, {good:false, value:"no"}]).filter(".good").map(".value")
["yes"])
it "can filter by Property value", ->
expectStreamEvents(
->
src = series(1, [1,1,2,3,4,4,8,7])
odd = src.map((x) -> x % 2).toProperty()
src.filter(odd)
[1,1,3,7])
describe "EventStream.map", ->
it "should map with given function", ->
expectStreamEvents(
-> series(1, [1, 2, 3]).map(times, 2)
[2, 4, 6])
it "also accepts a constant value", ->
expectStreamEvents(
-> series(1, [1, 2, 3,]).map("lol")
["lol", "lol", "lol"])
it "extracts property from value object", ->
o = { lol : "wut" }
expectStreamEvents(
-> repeat(1, [o]).take(3).map(".lol")
["wut", "wut", "wut"])
it "extracts a nested property too", ->
o = { lol : { wut : "wat" } }
expectStreamEvents(
-> Bacon.once(o).map(".lol.wut")
["wat"])
it "in case of a function property, calls the function with no args", ->
expectStreamEvents(
-> Bacon.once([1,2,3]).map(".length")
[3])
it "allows arguments for methods", ->
thing = { square: (x) -> x * x }
expectStreamEvents(
-> Bacon.once(thing).map(".square", 2)
[4])
it "works with method call on given object, with partial application", ->
multiplier = { multiply: (x, y) -> x * y }
expectStreamEvents(
-> series(1, [1,2,3]).map(multiplier, "multiply", 2)
[2,4,6])
it "can map to a Property value", ->
expectStreamEvents(
-> series(1, [1,2,3]).map(Bacon.constant(2))
[2,2,2])
describe "EventStream.mapError", ->
it "should map error events with given function", ->
expectStreamEvents(
-> repeat(1, [1, error("OOPS")]).mapError(id).take(2)
[1, "OOPS"])
it "also accepts a constant value", ->
expectStreamEvents(
-> repeat(1, [1, error()]).mapError("ERR").take(2)
[1, "ERR"])
describe "EventStream.doAction", ->
it "calls function before sending value to listeners", ->
called = []
bus = new Bacon.Bus()
s = bus.doAction((x) -> called.push(x))
s.onValue(->)
s.onValue(->)
bus.push(1)
expect(called).toEqual([1])
it "does not alter the stream", ->
expectStreamEvents(
-> series(1, [1, 2]).doAction(->)
[1, 2])
describe "EventStream.mapEnd", ->
it "produces an extra element on stream end", ->
expectStreamEvents(
-> series(1, ["1", error()]).mapEnd("the end")
["1", error(), "the end"])
it "accepts either a function or a constant value", ->
expectStreamEvents(
-> series(1, ["1", error()]).mapEnd(-> "the end")
["1", error(), "the end"])
it "works with undefined value as well", ->
expectStreamEvents(
-> series(1, ["1", error()]).mapEnd()
["1", error(), undefined])
describe "EventStream.takeWhile", ->
it "should take while predicate is true", ->
expectStreamEvents(
-> repeat(1, [1, error("wat"), 2, 3]).takeWhile(lessThan(3))
[1, error("wat"), 2])
describe "EventStream.skip", ->
it "should skip first N items", ->
expectStreamEvents(
-> series(1, [1, error(), 2, error(), 3]).skip(1)
[error(), 2, error(), 3])
describe "EventStream.skipDuplicates", ->
it "drops duplicates", ->
expectStreamEvents(
-> series(1, [1, 2, error(), 2, 3, 1]).skipDuplicates()
[1, 2, error(), 3, 1])
it "allows undefined as initial value", ->
expectStreamEvents(
-> series(1, [undefined, undefined, 1, 2]).skipDuplicates()
[undefined, 1, 2])
it "works with custom isEqual function", ->
a = {x: 1}; b = {x: 2}; c = {x: 2}; d = {x: 3}; e = {x: 1}
isEqual = (a, b) -> a?.x == b?.x
expectStreamEvents(
-> series(1, [a, b, error(), c, d, e]).skipDuplicates(isEqual)
[a, b, error(), d, e])
describe "EventStream.flatMap", ->
it "should spawn new stream for each value and collect results into a single stream", ->
expectStreamEvents(
-> series(1, [1, 2]).flatMap (value) ->
Bacon.sequentially(t(2), [value, error(), value])
[1, 2, error(), error(), 1, 2])
it "should pass source errors through to the result", ->
expectStreamEvents(
-> series(1, [error(), 1]).flatMap (value) ->
Bacon.later(t(1), value)
[error(), 1])
it "should work with a spawned stream responding synchronously", ->
expectStreamEvents(
-> series(1, [1, 2]).flatMap (value) ->
Bacon.never().concat(Bacon.once(value))
[1, 2])
it "should work with a source stream responding synchronously", ->
expectStreamEvents(
-> Bacon.once(1).flatMap (value) ->
Bacon.once(value)
[1])
it "Works also when f returns a Property instead of an EventStream", ->
expectStreamEvents(
-> series(1, [1,2]).flatMap(Bacon.constant)
[1,2])
describe "Property.flatMap", ->
it "should spawn new stream for all events including Init", ->
expectStreamEvents(
->
once = (x) -> Bacon.once(x)
series(1, [1, 2]).toProperty(0).flatMap(once)
[0, 1, 2])
it "Works also when f returns a Property instead of an EventStream", ->
expectStreamEvents(
-> series(1, [1,2]).toProperty().flatMap(Bacon.constant)
[1,2])
expectPropertyEvents(
-> series(1, [1,2]).toProperty().flatMap(Bacon.constant).toProperty()
[1,2])
describe "EventStream.flatMapLatest", ->
it "spawns new streams but collects values from the latest spawned stream only", ->
expectStreamEvents(
-> series(3, [1, 2]).flatMapLatest (value) ->
Bacon.sequentially(t(2), [value, error(), value])
[1, 2, error(), 2])
describe "Property.flatMapLatest", ->
it "spawns new streams but collects values from the latest spawned stream only", ->
expectStreamEvents(
-> series(3, [1, 2]).toProperty(0).flatMapLatest (value) ->
Bacon.sequentially(t(2), [value, value])
[0, 1, 2, 2])
describe "EventStream.merge", ->
it "merges two streams and ends when both are exhausted", ->
expectStreamEvents(
->
left = series(1, [1, error(), 2, 3])
right = series(1, [4, 5, 6]).delay(t(4))
left.merge(right)
[1, error(), 2, 3, 4, 5, 6])
it "respects subscriber return value", ->
expectStreamEvents(
->
left = repeat(2, [1, 3]).take(3)
right = repeat(3, [2]).take(3)
left.merge(right).takeWhile(lessThan(2))
[1])
describe "EventStream.delay", ->
it "delays all events (except errors) by given delay in milliseconds", ->
expectStreamEvents(
->
left = series(2, [1, 2, 3])
right = series(1, [error(), 4, 5, 6]).delay(t(6))
left.merge(right)
[error(), 1, 2, 3, 4, 5, 6])
describe "EventStream.throttle", ->
it "throttles input by given delay, passing-through errors", ->
expectStreamEvents(
-> series(2, [1, error(), 2]).throttle(t(7))
[error(), 2])
it "waits for a quiet period before outputing anything", ->
expectStreamTimings(
-> series(2, [1, 2, 3, 4]).throttle(t(3))
[[11, 4]])
describe "EventStream.throttle2(delay)", ->
it "outputs at steady intervals, without waiting for quite period", ->
expectStreamTimings(
-> series(2, [1, 2, 3]).throttle2(t(3))
[[5, 2], [8, 3]])
describe "EventStream.bufferWithTime", ->
it "returns events in bursts, passing through errors", ->
expectStreamEvents(
-> series(2, [error(), 1, 2, 3, 4, 5, 6, 7]).bufferWithTime(t(7))
[error(), [1, 2, 3, 4], [5, 6, 7]])
it "keeps constant output rate even when input is sporadical", ->
th.expectStreamTimings(
-> th.atGivenTimes([[0, "a"], [3, "b"], [5, "c"]]).bufferWithTime(t(2))
[[2, ["a"]], [4, ["b"]], [6, ["c"]]]
)
it "works with empty stream", ->
expectStreamEvents(
-> Bacon.never().bufferWithTime(t(1))
[])
it "allows custom defer-function", ->
fast = (f) -> setTimeout(f, 0)
th.expectStreamTimings(
-> th.atGivenTimes([[0, "a"], [2, "b"]]).bufferWithTime(fast)
[[0, ["a"]], [2, ["b"]]])
it "works with synchronous defer-function", ->
sync = (f) -> f()
th.expectStreamTimings(
-> th.atGivenTimes([[0, "a"], [2, "b"]]).bufferWithTime(sync)
[[0, ["a"]], [2, ["b"]]])
describe "EventStream.bufferWithCount", ->
it "returns events in chunks of fixed size, passing through errors", ->
expectStreamEvents(
-> series(1, [1, 2, 3, error(), 4, 5]).bufferWithCount(2)
[[1, 2], error(), [3, 4], [5]])
describe "EventStream.takeUntil", ->
it "takes elements from source until an event appears in the other stream", ->
expectStreamEvents(
->
src = repeat(3, [1, 2, 3])
stopper = repeat(7, ["stop!"])
src.takeUntil(stopper)
[1, 2])
it "works on self-derived stopper", ->
expectStreamEvents(
->
src = repeat(3, [3, 2, 1])
stopper = src.filter(lessThan(3))
src.takeUntil(stopper)
[3])
it "includes source errors, ignores stopper errors", ->
expectStreamEvents(
->
src = repeat(2, [1, error(), 2, 3])
stopper = repeat(7, ["stop!"]).merge(repeat(1, [error()]))
src.takeUntil(stopper)
[1, error(), 2])
describe "EventStream.awaiting(other)", ->
it "indicates whether s1 has produced output after s2 (or only the former has output so far)", ->
expectPropertyEvents(
-> series(2, [1, 1]).awaiting(series(3, [2]))
[false, true, false, true])
describe "EventStream.endOnError", ->
it "terminates on error", ->
expectStreamEvents(
-> repeat(1, [1, 2, error(), 3]).endOnError()
[1, 2, error()])
describe "Bacon.constant", ->
it "creates a constant property", ->
expectPropertyEvents(
-> Bacon.constant("lol")
["lol"])
it "ignores unsubscribe", ->
Bacon.constant("lol").onValue(=>)()
it "provides same value to all listeners", ->
c = Bacon.constant("lol")
expectPropertyEvents((-> c), ["lol"])
f = mockFunction()
c.onValue(f)
f.verify("lol")
it "provides same value to all listeners, when mapped (bug fix)", ->
c = Bacon.constant("lol").map(id)
f = mockFunction()
c.onValue(f)
f.verify("lol")
c.onValue(f)
f.verify("lol")
describe "Bacon.never", ->
it "should send just end", ->
expectStreamEvents(
-> Bacon.never()
[])
describe "Bacon.once", ->
it "should send single event and end", ->
expectStreamEvents(
-> Bacon.once("pow")
["pow"])
describe "EventStream.concat", ->
it "provides values from streams in given order and ends when both are exhausted", ->
expectStreamEvents(
->
left = series(2, [1, error(), 2, 3])
right = series(1, [4, 5, 6])
left.concat(right)
[1, error(), 2, 3, 4, 5, 6])
it "respects subscriber return value when providing events from left stream", ->
expectStreamEvents(
->
left = repeat(3, [1, 3]).take(3)
right = repeat(2, [1]).take(3)
left.concat(right).takeWhile(lessThan(2))
[1])
it "respects subscriber return value when providing events from right stream", ->
expectStreamEvents(
->
left = series(3, [1, 2])
right = series(2, [2, 4, 6])
left.concat(right).takeWhile(lessThan(4))
[1, 2, 2])
it "works with Bacon.never()", ->
expectStreamEvents(
-> Bacon.never().concat(Bacon.never())
[])
it "works with Bacon.once()", ->
expectStreamEvents(
-> Bacon.once(2).concat(Bacon.once(1))
[2, 1])
it "works with Bacon.once() and Bacon.never()", ->
expectStreamEvents(
-> Bacon.once(1).concat(Bacon.never())
[1])
it "works with Bacon.never() and Bacon.once()", ->
expectStreamEvents(
-> Bacon.never().concat(Bacon.once(1))
[1])
describe "EventStream.startWith", ->
it "provides seed value, then the rest", ->
expectStreamEvents(
->
left = series(1, [1, 2, 3])
left.startWith('pow')
['pow', 1, 2, 3])
describe "Property", ->
it "delivers current value and changes to subscribers", ->
expectPropertyEvents(
->
s = new Bacon.Bus()
p = s.toProperty("a")
soon ->
s.push "b"
s.end()
p
["a", "b"])
it "passes through also Errors", ->
expectPropertyEvents(
-> series(1, [1, error(), 2]).toProperty()
[1, error(), 2])
it "supports null as value", ->
expectPropertyEvents(
-> series(1, [null, 1, null]).toProperty(null)
[null, null, 1, null])
it "does not get messed-up by a transient subscriber (bug fix)", ->
expectPropertyEvents(
->
prop = series(1, [1,2,3]).toProperty(0)
prop.subscribe (event) =>
Bacon.noMore
prop
[0, 1, 2, 3])
describe "Property.toEventStream", ->
it "creates a stream that starts with current property value", ->
expectStreamEvents(
-> series(1, [1, 2]).toProperty(0).toEventStream()
[0, 1, 2])
describe "Property.map", ->
it "maps property values", ->
expectPropertyEvents(
->
s = new Bacon.Bus()
p = s.toProperty(1).map(times, 2)
soon ->
s.push 2
s.error()
s.end()
p
[2, 4, error()])
describe "Property.filter", ->
it "should filter values", ->
expectPropertyEvents(
-> series(1, [1, error(), 2, 3]).toProperty().filter(lessThan(3))
[1, error(), 2])
it "preserves old current value if the updated value is non-matching", ->
s = new Bacon.Bus()
p = s.toProperty().filter(lessThan(2))
p.onValue(=>) # to ensure that property is actualy updated
s.push(1)
s.push(2)
values = []
p.onValue((v) => values.push(v))
expect(values).toEqual([1])
describe "Property.take(1)", ->
it "takes the Initial event", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty(0).take(1)
[0])
it "takes the first Next event, if no Initial value", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty().take(1)
[1])
it "works for constants", ->
expectPropertyEvents(
-> Bacon.constant(1)
[1])
describe "Bacon.once().take(1)", ->
it "works", ->
expectStreamEvents(
-> Bacon.once(1).take(1)
[1])
describe "Property.takeUntil", ->
it "takes elements from source until an event appears in the other stream", ->
expectPropertyEvents(
-> series(2, [1,2,3]).toProperty().takeUntil(Bacon.later(t(3)))
[1])
it "works with errors", ->
expectPropertyEvents(
->
src = repeat(2, [1, error(), 3])
stopper = repeat(5, ["stop!"])
src.toProperty(0).takeUntil(stopper)
[0, 1, error()])
describe "Property.delay", ->
it "delivers initial value and changes", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty(0).delay(t(1))
[0,1,2,3])
it "delays changes", ->
expectStreamEvents(
-> series(2, [1,2,3]).toProperty()
.delay(t(2)).changes().takeUntil(Bacon.later(t(5)))
[1])
it "does not delay initial value", ->
expectPropertyEvents(
-> series(3, [1]).toProperty(0).delay(1).takeUntil(Bacon.later(t(2)))
[0])
describe "Property.throttle", ->
it "delivers initial value and changes", ->
expectPropertyEvents(
-> series(2, [1,2,3]).toProperty(0).throttle(t(1))
[0,1,2,3])
it "throttles changes, but not initial value", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty(0).throttle(t(4))
[0,3])
it "works without initial value", ->
expectPropertyEvents(
-> series(2, [1,2,3]).toProperty().throttle(t(4))
[3])
describe "Property.throttle2", ->
it "throttles changes, but not initial value", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty(0).throttle2(t(4))
[0,3])
describe "Property.endOnError", ->
it "terminates on Error", ->
expectPropertyEvents(
-> series(2, [1, error(), 2]).toProperty().endOnError()
[1, error()])
describe "Property.skipDuplicates", ->
it "drops duplicates", ->
expectPropertyEvents(
-> series(1, [1, 2, error(), 2, 3, 1]).toProperty(0).skipDuplicates()
[0, 1, 2, error(), 3, 1])
describe "Property.changes", ->
it "sends property change events", ->
expectStreamEvents(
->
s = new Bacon.Bus()
p = s.toProperty("a").changes()
soon ->
s.push "b"
s.error()
s.end()
p
["b", error()])
describe "Property.combine", ->
it "combines latest values of two properties, with given combinator function, passing through errors", ->
expectPropertyEvents(
->
left = series(2, [1, error(), 2, 3]).toProperty()
right = series(2, [4, error(), 5, 6]).delay(t(1)).toProperty()
left.combine(right, add)
[5, error(), error(), 6, 7, 8, 9])
it "also accepts a field name instead of combinator function", ->
expectPropertyEvents(
->
left = series(1, [[1]]).toProperty()
right = series(2, [[2]]).toProperty()
left.combine(right, ".concat")
[[1, 2]])
it "combines with null values", ->
expectPropertyEvents(
->
left = series(1, [null]).toProperty()
right = series(1, [null]).toProperty()
left.combine(right, (l, r)-> [l, r])
[[null, null]])
it "unsubscribes when initial value callback returns Bacon.noMore", ->
calls = 0
bus = new Bacon.Bus()
other = Bacon.constant(["rolfcopter"])
bus.toProperty(["lollerskates"]).combine(other, ".concat").subscribe (e) ->
if !e.isInitial()
calls += 1
Bacon.noMore
bus.push(["fail whale"])
expect(calls).toBe 0
describe "Bacon.combineAsArray", ->
it "combines properties and latest values of streams, into a Property having arrays as values", ->
expectPropertyEvents(
->
stream = series(1, ["a", "b"])
Bacon.combineAsArray([Bacon.constant(1), Bacon.constant(2), stream])
[[1, 2, "a"], [1, 2, "b"]])
it "Works with streams provided as a list of arguments as well as with a single array arg", ->
expectPropertyEvents(
->
stream = series(1, ["a", "b"])
Bacon.combineAsArray(Bacon.constant(1), Bacon.constant(2), stream)
[[1, 2, "a"], [1, 2, "b"]])
it "works with single stream", ->
expectPropertyEvents(
->
Bacon.combineAsArray([Bacon.constant(1)])
[[1]])
it "works with arrays as values, with first array being empty (bug fix)", ->
expectPropertyEvents(
->
Bacon.combineAsArray([Bacon.constant([]), Bacon.constant([1])])
([[[], [1]]]))
it "works with arrays as values, with first array being non-empty (bug fix)", ->
expectPropertyEvents(
->
Bacon.combineAsArray([Bacon.constant([1]), Bacon.constant([2])])
([[[1], [2]]]))
it "works with empty array", ->
expectPropertyEvents(
-> Bacon.combineAsArray([])
[[]])
describe "Bacon.combineWith", ->
it "combines properties by applying the combinator function to values", ->
expectPropertyEvents(
->
stream = series(1, [[1]])
Bacon.combineWith([stream, Bacon.constant([2]), Bacon.constant([3])], ".concat")
[[1, 2, 3]])
describe "Boolean logic", ->
it "combines Properties with and()", ->
expectPropertyEvents(
-> Bacon.constant(true).and(Bacon.constant(false))
[false])
it "combines Properties with or()", ->
expectPropertyEvents(
-> Bacon.constant(true).or(Bacon.constant(false))
[true])
it "inverts property with not()", ->
expectPropertyEvents(
-> Bacon.constant(true).not()
[false])
describe "Bacon.mergeAll", ->
it ("merges all given streams"), ->
expectStreamEvents(
->
Bacon.mergeAll([
series(3, [1, 2])
series(3, [3, 4]).delay(t(1))
series(3, [5, 6]).delay(t(2))])
[1, 3, 5, 2, 4, 6])
describe "Property.sampledBy", ->
it "samples property at events, resulting to EventStream", ->
expectStreamEvents(
->
prop = series(2, [1, 2]).toProperty()
stream = repeat(3, ["troll"]).take(4)
prop.sampledBy(stream)
[1, 2, 2, 2])
it "includes errors from both Property and EventStream", ->
expectStreamEvents(
->
prop = series(2, [error(), 2]).toProperty()
stream = series(3, [error(), "troll"])
prop.sampledBy(stream)
[error(), error(), 2])
it "ends when sampling stream ends", ->
expectStreamEvents(
->
prop = repeat(2, [1, 2]).toProperty()
stream = repeat(2, [""]).delay(t(1)).take(4)
prop.sampledBy(stream)
[1, 2, 1, 2])
it "accepts optional combinator function f(Vp, Vs)", ->
expectStreamEvents(
->
prop = series(2, ["a", "b"]).toProperty()
stream = series(2, ["1", "2", "1", "2"]).delay(t(1))
prop.sampledBy(stream, add)
["a1", "b2", "b1", "b2"])
it "allows method name instead of function too", ->
expectStreamEvents(
->
Bacon.constant([1]).sampledBy(Bacon.once([2]), ".concat")
[[1, 2]])
it "works with same origin", ->
expectStreamEvents(
->
src = series(2, [1, 2])
src.toProperty().sampledBy(src)
[1, 2])
expectStreamEvents(
->
src = series(2, [1, 2])
src.toProperty().sampledBy(src.map(times, 2))
[1, 2])
describe "Property.sample", ->
it "samples property by given interval", ->
expectStreamEvents(
->
prop = series(2, [1, 2]).toProperty()
prop.sample(t(3)).take(4)
[1, 2, 2, 2])
it "includes all errors", ->
expectStreamEvents(
->
prop = series(2, [1, error(), 2]).toProperty()
prop.sample(t(5)).take(2)
[error(), 1, 2])
describe "EventStream.scan", ->
it "accumulates values with given seed and accumulator function, passing through errors", ->
expectPropertyEvents(
-> series(1, [1, 2, error(), 3]).scan(0, add)
[0, 1, 3, error(), 6])
it "also works with method name", ->
expectPropertyEvents(
-> series(1, [[1], [2]]).scan([], ".concat")
[[], [1], [1, 2]])
it "yields the seed value immediately", ->
outputs = []
bus = new Bacon.Bus()
bus.scan(0, -> 1).onValue((value) -> outputs.push(value))
expect(outputs).toEqual([0])
it "yields null seed value", ->
expectPropertyEvents(
-> series(1, [1]).scan(null, ->1)
[null, 1])
describe "Property.scan", ->
it "with Init value, starts with f(seed, init)", ->
expectPropertyEvents(
-> series(1, [2,3]).toProperty(1).scan(0, add)
[1, 3, 6])
it "without Init value, starts with seed", ->
expectPropertyEvents(
-> series(1, [2,3]).toProperty().scan(0, add)
[0, 2, 5])
it "treats null seed value like any other value", ->
expectPropertyEvents(
-> series(1, [1]).toProperty().scan(null, add)
[null, 1])
expectPropertyEvents(
-> series(1, [2]).toProperty(1).scan(null, add)
[1, 3])
describe "EventStream.diff", ->
it "apply diff function to previous and current values, passing through errors", ->
expectPropertyEvents(
-> series(1, [1, 2, error(), 3]).diff(0, add)
[1, 3, error(), 5])
it "also works with method name", ->
expectPropertyEvents(
-> series(1, [[1], [2]]).diff([0], ".concat")
[[0, 1], [1, 2]])
it "does not yields the start value immediately", ->
outputs = []
bus = new Bacon.Bus()
bus.diff(0, -> 1).onValue((value) -> outputs.push(value))
expect(outputs).toEqual([])
describe "Property.diff", ->
it "with Init value, starts with f(start, init)", ->
expectPropertyEvents(
-> series(1, [2,3]).toProperty(1).diff(0, add)
[1, 3, 5])
it "without Init value, waits for the first value", ->
expectPropertyEvents(
-> series(1, [2,3]).toProperty().diff(0, add)
[2, 5])
it "treats null start value like any other value", ->
expectPropertyEvents(
-> series(1, [1]).toProperty().diff(null, add)
[1])
expectPropertyEvents(
-> series(1, [2]).toProperty(1).diff(null, add)
[1, 3])
describe "combineTemplate", ->
it "combines streams according to a template object", ->
expectPropertyEvents(
->
firstName = Bacon.constant("juha")
lastName = Bacon.constant("paananen")
userName = Bacon.constant("mr.bacon")
Bacon.combineTemplate({ userName: userName, password: "*****", fullName: { firstName: firstName, lastName: lastName }})
[{ userName: "mr.bacon", password: "*****", fullName: { firstName: "juha", lastName: "paananen" } }])
it "works with a single-stream template", ->
expectPropertyEvents(
->
bacon = Bacon.constant("bacon")
Bacon.combineTemplate({ favoriteFood: bacon })
[{ favoriteFood: "bacon" }])
it "works when dynamic part is not the last part (bug fix)", ->
expectPropertyEvents(
->
username = Bacon.constant("raimohanska")
password = Bacon.constant("easy")
Bacon.combineTemplate({url: "/user/login",
data: { username: username, password: password }, type: "post"})
[url: "/user/login", data: {username: "raimohanska", password: "easy"}, type: "post"])
it "works with arrays as data (bug fix)", ->
expectPropertyEvents(
-> Bacon.combineTemplate( { x : Bacon.constant([]), y : Bacon.constant([[]]), z : Bacon.constant(["z"])})
[{ x : [], y : [[]], z : ["z"]}])
it "supports empty object", ->
expectPropertyEvents(
-> Bacon.combineTemplate({})
[{}])
it "supports arrays", ->
value = {key: [{ x: 1 }, { x: 2 }]}
Bacon.combineTemplate(value).onValue (x) ->
expect(x).toEqual(value)
expect(x.key instanceof Array).toEqual(true) # seems that the former passes even if x is not an array
value = [{ x: 1 }, { x: 2 }]
Bacon.combineTemplate(value).onValue (x) ->
expect(x).toEqual(value)
expect(x instanceof Array).toEqual(true)
value = {key: [{ x: 1 }, { x: 2 }], key2: {}}
Bacon.combineTemplate(value).onValue (x) ->
expect(x).toEqual(value)
expect(x.key instanceof Array).toEqual(true)
value = {key: [{ x: 1 }, { x: Bacon.constant(2) }]}
Bacon.combineTemplate(value).onValue (x) ->
expect(x).toEqual({key: [{ x: 1 }, { x: 2 }]})
expect(x.key instanceof Array).toEqual(true) # seems that the former passes even if x is not an array
describe "Property.decode", ->
it "switches between source Properties based on property value", ->
expectPropertyEvents(
->
a = Bacon.constant("a")
b = Bacon.constant("b")
c = Bacon.constant("c")
series(1, [1,2,3]).toProperty().decode({1: a, 2: b, 3: c})
["a", "b", "c"])
describe "Observable.onValues", ->
it "splits value array to callback arguments", ->
f = mockFunction()
Bacon.constant([1,2,3]).onValues(f)
f.verify(1,2,3)
describe "Observable.subscribe and onValue", ->
it "returns a dispose() for unsubscribing", ->
s = new Bacon.Bus()
values = []
dispose = s.onValue (value) -> values.push value
s.push "lol"
dispose()
s.push "wut"
expect(values).toEqual(["lol"])
describe "Observable.onEnd", ->
it "is called on stream end", ->
s = new Bacon.Bus()
ended = false
s.onEnd(-> ended = true)
s.push("LOL")
expect(ended).toEqual(false)
s.end()
expect(ended).toEqual(true)
describe "Field value extraction", ->
it "extracts field value", ->
expectStreamEvents(
-> Bacon.once({lol:"wut"}).map(".lol")
["wut"])
it "extracts nested field value", ->
expectStreamEvents(
-> Bacon.once({lol:{wut: "wat"}}).map(".lol.wut")
["wat"])
it "if field value is method, it does a method call", ->
context = null
result = null
object = {
method: ->
context = this
"result"
}
Bacon.once(object).map(".method").onValue((x) -> result = x)
expect(result).toEqual("result")
expect(context).toEqual(object)
testSideEffects = (wrapper, method) ->
->
it "(f) calls function with property value", ->
f = mockFunction()
wrapper("kaboom")[method](f)
f.verify("kaboom")
it "(f, param) calls function, partially applied with param", ->
f = mockFunction()
wrapper("kaboom")[method](f, "pow")
f.verify("pow", "kaboom")
it "('.method') calls event value object method", ->
value = mock("get")
value.when().get().thenReturn("pow")
wrapper(value)[method](".get")
value.verify().get()
it "('.method', param) calls event value object method with param", ->
value = mock("get")
value.when().get("value").thenReturn("pow")
wrapper(value)[method](".get", "value")
value.verify().get("value")
it "(object, method) calls object method with property value", ->
target = mock("pow")
wrapper("kaboom")[method](target, "pow")
target.verify().pow("kaboom")
it "(object, method, param) partially applies object method with param", ->
target = mock("pow")
wrapper("kaboom")[method](target, "pow", "smack")
target.verify().pow("smack", "kaboom")
it "(object, method, param1, param2) partially applies with 2 args", ->
target = mock("pow")
wrapper("kaboom")[method](target, "pow", "smack", "whack")
target.verify().pow("smack", "whack", "kaboom")
describe "Property.onValue", testSideEffects(Bacon.constant, "onValue")
describe "Property.assign", testSideEffects(Bacon.constant, "assign")
describe "EventStream.onValue", testSideEffects(Bacon.once, "onValue")
describe "Property.assign", ->
it "calls given objects given method with property values", ->
target = mock("pow")
Bacon.constant("kaboom").assign(target, "pow")
target.verify().pow("kaboom")
it "allows partial application of method (i.e. adding fixed args)", ->
target = mock("pow")
Bacon.constant("kaboom").assign(target, "pow", "smack")
target.verify().pow("smack", "kaboom")
it "allows partial application of method with 2 args (i.e. adding fixed args)", ->
target = mock("pow")
Bacon.constant("kaboom").assign(target, "pow", "smack", "whack")
target.verify().pow("smack", "whack", "kaboom")
describe "Bacon.Bus", ->
it "merges plugged-in streams", ->
bus = new Bacon.Bus()
values = []
dispose = bus.onValue (value) -> values.push value
push = new Bacon.Bus()
bus.plug(push)
push.push("lol")
expect(values).toEqual(["lol"])
dispose()
verifyCleanup()
it "works with looped streams", ->
expectStreamEvents(
->
bus = new Bacon.Bus()
bus.plug(Bacon.later(t(2), "lol"))
bus.plug(bus.filter((value) => "lol" == value).map(=> "wut"))
Bacon.later(t(4)).onValue(=> bus.end())
bus
["lol", "wut"])
it "dispose works with looped streams", ->
bus = new Bacon.Bus()
bus.plug(Bacon.later(t(2), "lol"))
bus.plug(bus.filter((value) => "lol" == value).map(=> "wut"))
dispose = bus.onValue(=>)
dispose()
it "Removes input from input list on End event", ->
subscribed = 0
bus = new Bacon.Bus()
input = new Bacon.Bus()
# override subscribe to increase the subscribed-count
inputSubscribe = input.subscribe
input.subscribe = (sink) ->
subscribed++
inputSubscribe(sink)
bus.plug(input)
dispose = bus.onValue(=>)
input.end()
dispose()
bus.onValue(=>) # this latter subscription should not go to the ended source anymore
expect(subscribed).toEqual(1)
it "unsubscribes inputs on end() call", ->
bus = new Bacon.Bus()
input = new Bacon.Bus()
events = []
bus.plug(input)
bus.subscribe((e) => events.push(e))
input.push("a")
bus.end()
input.push("b")
expect(toValues(events)).toEqual(["a", "<end>"])
it "handles cold single-event streams correctly (bug fix)", ->
values = []
bus = new Bacon.Bus()
bus.plug(Bacon.once("x"))
bus.plug(Bacon.once("y"))
bus.onValue((x) -> values.push(x))
expect(values).toEqual(["x", "y"])
it "handles end() calls even when there are no subscribers", ->
bus = new Bacon.Bus()
bus.end()
it "delivers pushed events and errors", ->
expectStreamEvents(
->
s = new Bacon.Bus()
s.push "pullMe"
soon ->
s.push "pushMe"
s.error()
s.end()
s
["pushMe", error()])
it "does not deliver pushed events after end() call", ->
called = false
bus = new Bacon.Bus()
bus.onValue(-> called = true)
bus.end()
bus.push("LOL")
expect(called).toEqual(false)
it "does not plug after end() call", ->
plugged = false
bus = new Bacon.Bus()
bus.end()
bus.plug(new Bacon.EventStream((sink) -> plugged = true; (->)))
bus.onValue(->)
expect(plugged).toEqual(false)
it "returns unplug function from plug", ->
values = []
bus = new Bacon.Bus()
src = new Bacon.Bus()
unplug = bus.plug(src)
bus.onValue((x) -> values.push(x))
src.push("x")
unplug()
src.push("y")
expect(values).toEqual(["x"])
describe "EventStream", ->
it "works with functions as values (bug fix)", ->
expectStreamEvents(
-> Bacon.once(-> "hello").map((f) -> f())
["hello"])
expectStreamEvents(
-> Bacon.once(-> "hello").flatMap(Bacon.once).map((f) -> f())
["hello"])
expectPropertyEvents(
-> Bacon.constant(-> "hello").map((f) -> f())
["hello"])
expectStreamEvents(
-> Bacon.constant(-> "hello").flatMap(Bacon.once).map((f) -> f())
["hello"])
lessThan = (limit) ->
(x) -> x < limit
times = (x, y) -> x * y
add = (x, y) -> x + y
id = (x) -> x
# Wrap EventEmitter as EventTarget
toEventTarget = (emitter) ->
addEventListener: (event, handler) -> emitter.addListener(event, handler)
removeEventListener: (event, handler) -> emitter.removeListener(event, handler)
| 91667 | Bacon = (require "../src/Bacon").Bacon
Mocks = (require "./Mock")
mock = Mocks.mock
mockFunction = Mocks.mockFunction
EventEmitter = require("events").EventEmitter
th = require("./SpecHelper")
t = th.t
expectStreamEvents = th.expectStreamEvents
expectPropertyEvents = th.expectPropertyEvents
verifyCleanup = th.verifyCleanup
error = th.error
soon = th.soon
series = th.series
repeat = th.repeat
toValues = th.toValues
describe "Bacon.later", ->
it "should send single event and end", ->
expectStreamEvents(
-> Bacon.later(t(1), "lol")
["lol"])
describe "Bacon.sequentially", ->
it "should send given events and end", ->
expectStreamEvents(
-> Bacon.sequentially(t(1), ["lol", "wut"])
["lol", "wut"])
it "include error events", ->
expectStreamEvents(
-> Bacon.sequentially(t(1), [error(), "lol"])
[error(), "lol"])
describe "Bacon.interval", ->
it "repeats single element indefinitely", ->
expectStreamEvents(
-> Bacon.interval(t(1), "x").take(3)
["x", "x", "x"])
describe "Bacon.fromCallback", ->
it "makes an EventStream from function that takes a callback", ->
expectStreamEvents(
->
src = (callback) -> callback("lol")
stream = Bacon.fromCallback(src)
["lol"])
it "supports partial application", ->
expectStreamEvents(
->
src = (param, callback) -> callback(param)
stream = Bacon.fromCallback(src, "lol")
["lol"])
describe "Bacon.fromEventTarget", ->
it "should create EventStream from DOM object", ->
emitter = new EventEmitter()
emitter.on "newListener", ->
runs ->
emitter.emit "click", "x"
element = toEventTarget emitter
expectStreamEvents(
-> Bacon.fromEventTarget(element, "click").take(1)
["x"]
)
it "should create EventStream from EventEmitter", ->
emitter = new EventEmitter()
emitter.on "newListener", ->
runs ->
emitter.emit "data", "x"
expectStreamEvents(
-> Bacon.fromEventTarget(emitter, "data").take(1)
["x"]
)
it "should allow a custom map function for EventStream from EventEmitter", ->
emitter = new EventEmitter()
emitter.on "newListener", ->
runs ->
emitter.emit "data", "x", "y"
expectStreamEvents(
-> Bacon.fromEventTarget(emitter, "data", (x, y) => [x, y]).take(1)
[["x", "y"]]
)
it "should clean up event listeners from EventEmitter", ->
emitter = new EventEmitter()
Bacon.fromEventTarget(emitter, "data").take(1).subscribe ->
emitter.emit "data", "x"
expect(emitter.listeners("data").length).toEqual(0)
it "should clean up event listeners from DOM object", ->
emitter = new EventEmitter()
element = toEventTarget emitter
dispose = Bacon.fromEventTarget(element, "click").subscribe ->
dispose()
expect(emitter.listeners("click").length).toEqual(0)
describe "Observable.log", ->
it "does not crash", ->
Bacon.constant(1).log
describe "Observable.slidingWindow", ->
it "slides the window for EventStreams", ->
expectPropertyEvents(
-> series(1, [1,2,3]).slidingWindow(2)
[[], [1], [1,2], [2,3]])
it "slides the window for Properties", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty().slidingWindow(2)
[[], [1], [1,2], [2,3]])
describe "EventStream.filter", ->
it "should filter values", ->
expectStreamEvents(
-> series(1, [1, 2, error(), 3]).filter(lessThan(3))
[1, 2, error()])
it "extracts field values", ->
expectStreamEvents(
-> series(1, [{good:true, value:"yes"}, {good:false, value:"no"}]).filter(".good").map(".value")
["yes"])
it "can filter by Property value", ->
expectStreamEvents(
->
src = series(1, [1,1,2,3,4,4,8,7])
odd = src.map((x) -> x % 2).toProperty()
src.filter(odd)
[1,1,3,7])
describe "EventStream.map", ->
it "should map with given function", ->
expectStreamEvents(
-> series(1, [1, 2, 3]).map(times, 2)
[2, 4, 6])
it "also accepts a constant value", ->
expectStreamEvents(
-> series(1, [1, 2, 3,]).map("lol")
["lol", "lol", "lol"])
it "extracts property from value object", ->
o = { lol : "wut" }
expectStreamEvents(
-> repeat(1, [o]).take(3).map(".lol")
["wut", "wut", "wut"])
it "extracts a nested property too", ->
o = { lol : { wut : "wat" } }
expectStreamEvents(
-> Bacon.once(o).map(".lol.wut")
["wat"])
it "in case of a function property, calls the function with no args", ->
expectStreamEvents(
-> Bacon.once([1,2,3]).map(".length")
[3])
it "allows arguments for methods", ->
thing = { square: (x) -> x * x }
expectStreamEvents(
-> Bacon.once(thing).map(".square", 2)
[4])
it "works with method call on given object, with partial application", ->
multiplier = { multiply: (x, y) -> x * y }
expectStreamEvents(
-> series(1, [1,2,3]).map(multiplier, "multiply", 2)
[2,4,6])
it "can map to a Property value", ->
expectStreamEvents(
-> series(1, [1,2,3]).map(Bacon.constant(2))
[2,2,2])
describe "EventStream.mapError", ->
it "should map error events with given function", ->
expectStreamEvents(
-> repeat(1, [1, error("OOPS")]).mapError(id).take(2)
[1, "OOPS"])
it "also accepts a constant value", ->
expectStreamEvents(
-> repeat(1, [1, error()]).mapError("ERR").take(2)
[1, "ERR"])
describe "EventStream.doAction", ->
it "calls function before sending value to listeners", ->
called = []
bus = new Bacon.Bus()
s = bus.doAction((x) -> called.push(x))
s.onValue(->)
s.onValue(->)
bus.push(1)
expect(called).toEqual([1])
it "does not alter the stream", ->
expectStreamEvents(
-> series(1, [1, 2]).doAction(->)
[1, 2])
describe "EventStream.mapEnd", ->
it "produces an extra element on stream end", ->
expectStreamEvents(
-> series(1, ["1", error()]).mapEnd("the end")
["1", error(), "the end"])
it "accepts either a function or a constant value", ->
expectStreamEvents(
-> series(1, ["1", error()]).mapEnd(-> "the end")
["1", error(), "the end"])
it "works with undefined value as well", ->
expectStreamEvents(
-> series(1, ["1", error()]).mapEnd()
["1", error(), undefined])
describe "EventStream.takeWhile", ->
it "should take while predicate is true", ->
expectStreamEvents(
-> repeat(1, [1, error("wat"), 2, 3]).takeWhile(lessThan(3))
[1, error("wat"), 2])
describe "EventStream.skip", ->
it "should skip first N items", ->
expectStreamEvents(
-> series(1, [1, error(), 2, error(), 3]).skip(1)
[error(), 2, error(), 3])
describe "EventStream.skipDuplicates", ->
it "drops duplicates", ->
expectStreamEvents(
-> series(1, [1, 2, error(), 2, 3, 1]).skipDuplicates()
[1, 2, error(), 3, 1])
it "allows undefined as initial value", ->
expectStreamEvents(
-> series(1, [undefined, undefined, 1, 2]).skipDuplicates()
[undefined, 1, 2])
it "works with custom isEqual function", ->
a = {x: 1}; b = {x: 2}; c = {x: 2}; d = {x: 3}; e = {x: 1}
isEqual = (a, b) -> a?.x == b?.x
expectStreamEvents(
-> series(1, [a, b, error(), c, d, e]).skipDuplicates(isEqual)
[a, b, error(), d, e])
describe "EventStream.flatMap", ->
it "should spawn new stream for each value and collect results into a single stream", ->
expectStreamEvents(
-> series(1, [1, 2]).flatMap (value) ->
Bacon.sequentially(t(2), [value, error(), value])
[1, 2, error(), error(), 1, 2])
it "should pass source errors through to the result", ->
expectStreamEvents(
-> series(1, [error(), 1]).flatMap (value) ->
Bacon.later(t(1), value)
[error(), 1])
it "should work with a spawned stream responding synchronously", ->
expectStreamEvents(
-> series(1, [1, 2]).flatMap (value) ->
Bacon.never().concat(Bacon.once(value))
[1, 2])
it "should work with a source stream responding synchronously", ->
expectStreamEvents(
-> Bacon.once(1).flatMap (value) ->
Bacon.once(value)
[1])
it "Works also when f returns a Property instead of an EventStream", ->
expectStreamEvents(
-> series(1, [1,2]).flatMap(Bacon.constant)
[1,2])
describe "Property.flatMap", ->
it "should spawn new stream for all events including Init", ->
expectStreamEvents(
->
once = (x) -> Bacon.once(x)
series(1, [1, 2]).toProperty(0).flatMap(once)
[0, 1, 2])
it "Works also when f returns a Property instead of an EventStream", ->
expectStreamEvents(
-> series(1, [1,2]).toProperty().flatMap(Bacon.constant)
[1,2])
expectPropertyEvents(
-> series(1, [1,2]).toProperty().flatMap(Bacon.constant).toProperty()
[1,2])
describe "EventStream.flatMapLatest", ->
it "spawns new streams but collects values from the latest spawned stream only", ->
expectStreamEvents(
-> series(3, [1, 2]).flatMapLatest (value) ->
Bacon.sequentially(t(2), [value, error(), value])
[1, 2, error(), 2])
describe "Property.flatMapLatest", ->
it "spawns new streams but collects values from the latest spawned stream only", ->
expectStreamEvents(
-> series(3, [1, 2]).toProperty(0).flatMapLatest (value) ->
Bacon.sequentially(t(2), [value, value])
[0, 1, 2, 2])
describe "EventStream.merge", ->
it "merges two streams and ends when both are exhausted", ->
expectStreamEvents(
->
left = series(1, [1, error(), 2, 3])
right = series(1, [4, 5, 6]).delay(t(4))
left.merge(right)
[1, error(), 2, 3, 4, 5, 6])
it "respects subscriber return value", ->
expectStreamEvents(
->
left = repeat(2, [1, 3]).take(3)
right = repeat(3, [2]).take(3)
left.merge(right).takeWhile(lessThan(2))
[1])
describe "EventStream.delay", ->
it "delays all events (except errors) by given delay in milliseconds", ->
expectStreamEvents(
->
left = series(2, [1, 2, 3])
right = series(1, [error(), 4, 5, 6]).delay(t(6))
left.merge(right)
[error(), 1, 2, 3, 4, 5, 6])
describe "EventStream.throttle", ->
it "throttles input by given delay, passing-through errors", ->
expectStreamEvents(
-> series(2, [1, error(), 2]).throttle(t(7))
[error(), 2])
it "waits for a quiet period before outputing anything", ->
expectStreamTimings(
-> series(2, [1, 2, 3, 4]).throttle(t(3))
[[11, 4]])
describe "EventStream.throttle2(delay)", ->
it "outputs at steady intervals, without waiting for quite period", ->
expectStreamTimings(
-> series(2, [1, 2, 3]).throttle2(t(3))
[[5, 2], [8, 3]])
describe "EventStream.bufferWithTime", ->
it "returns events in bursts, passing through errors", ->
expectStreamEvents(
-> series(2, [error(), 1, 2, 3, 4, 5, 6, 7]).bufferWithTime(t(7))
[error(), [1, 2, 3, 4], [5, 6, 7]])
it "keeps constant output rate even when input is sporadical", ->
th.expectStreamTimings(
-> th.atGivenTimes([[0, "a"], [3, "b"], [5, "c"]]).bufferWithTime(t(2))
[[2, ["a"]], [4, ["b"]], [6, ["c"]]]
)
it "works with empty stream", ->
expectStreamEvents(
-> Bacon.never().bufferWithTime(t(1))
[])
it "allows custom defer-function", ->
fast = (f) -> setTimeout(f, 0)
th.expectStreamTimings(
-> th.atGivenTimes([[0, "a"], [2, "b"]]).bufferWithTime(fast)
[[0, ["a"]], [2, ["b"]]])
it "works with synchronous defer-function", ->
sync = (f) -> f()
th.expectStreamTimings(
-> th.atGivenTimes([[0, "a"], [2, "b"]]).bufferWithTime(sync)
[[0, ["a"]], [2, ["b"]]])
describe "EventStream.bufferWithCount", ->
it "returns events in chunks of fixed size, passing through errors", ->
expectStreamEvents(
-> series(1, [1, 2, 3, error(), 4, 5]).bufferWithCount(2)
[[1, 2], error(), [3, 4], [5]])
describe "EventStream.takeUntil", ->
it "takes elements from source until an event appears in the other stream", ->
expectStreamEvents(
->
src = repeat(3, [1, 2, 3])
stopper = repeat(7, ["stop!"])
src.takeUntil(stopper)
[1, 2])
it "works on self-derived stopper", ->
expectStreamEvents(
->
src = repeat(3, [3, 2, 1])
stopper = src.filter(lessThan(3))
src.takeUntil(stopper)
[3])
it "includes source errors, ignores stopper errors", ->
expectStreamEvents(
->
src = repeat(2, [1, error(), 2, 3])
stopper = repeat(7, ["stop!"]).merge(repeat(1, [error()]))
src.takeUntil(stopper)
[1, error(), 2])
describe "EventStream.awaiting(other)", ->
it "indicates whether s1 has produced output after s2 (or only the former has output so far)", ->
expectPropertyEvents(
-> series(2, [1, 1]).awaiting(series(3, [2]))
[false, true, false, true])
describe "EventStream.endOnError", ->
it "terminates on error", ->
expectStreamEvents(
-> repeat(1, [1, 2, error(), 3]).endOnError()
[1, 2, error()])
describe "Bacon.constant", ->
it "creates a constant property", ->
expectPropertyEvents(
-> Bacon.constant("lol")
["lol"])
it "ignores unsubscribe", ->
Bacon.constant("lol").onValue(=>)()
it "provides same value to all listeners", ->
c = Bacon.constant("lol")
expectPropertyEvents((-> c), ["lol"])
f = mockFunction()
c.onValue(f)
f.verify("lol")
it "provides same value to all listeners, when mapped (bug fix)", ->
c = Bacon.constant("lol").map(id)
f = mockFunction()
c.onValue(f)
f.verify("lol")
c.onValue(f)
f.verify("lol")
describe "Bacon.never", ->
it "should send just end", ->
expectStreamEvents(
-> Bacon.never()
[])
describe "Bacon.once", ->
it "should send single event and end", ->
expectStreamEvents(
-> Bacon.once("pow")
["pow"])
describe "EventStream.concat", ->
it "provides values from streams in given order and ends when both are exhausted", ->
expectStreamEvents(
->
left = series(2, [1, error(), 2, 3])
right = series(1, [4, 5, 6])
left.concat(right)
[1, error(), 2, 3, 4, 5, 6])
it "respects subscriber return value when providing events from left stream", ->
expectStreamEvents(
->
left = repeat(3, [1, 3]).take(3)
right = repeat(2, [1]).take(3)
left.concat(right).takeWhile(lessThan(2))
[1])
it "respects subscriber return value when providing events from right stream", ->
expectStreamEvents(
->
left = series(3, [1, 2])
right = series(2, [2, 4, 6])
left.concat(right).takeWhile(lessThan(4))
[1, 2, 2])
it "works with Bacon.never()", ->
expectStreamEvents(
-> Bacon.never().concat(Bacon.never())
[])
it "works with Bacon.once()", ->
expectStreamEvents(
-> Bacon.once(2).concat(Bacon.once(1))
[2, 1])
it "works with Bacon.once() and Bacon.never()", ->
expectStreamEvents(
-> Bacon.once(1).concat(Bacon.never())
[1])
it "works with Bacon.never() and Bacon.once()", ->
expectStreamEvents(
-> Bacon.never().concat(Bacon.once(1))
[1])
describe "EventStream.startWith", ->
it "provides seed value, then the rest", ->
expectStreamEvents(
->
left = series(1, [1, 2, 3])
left.startWith('pow')
['pow', 1, 2, 3])
describe "Property", ->
it "delivers current value and changes to subscribers", ->
expectPropertyEvents(
->
s = new Bacon.Bus()
p = s.toProperty("a")
soon ->
s.push "b"
s.end()
p
["a", "b"])
it "passes through also Errors", ->
expectPropertyEvents(
-> series(1, [1, error(), 2]).toProperty()
[1, error(), 2])
it "supports null as value", ->
expectPropertyEvents(
-> series(1, [null, 1, null]).toProperty(null)
[null, null, 1, null])
it "does not get messed-up by a transient subscriber (bug fix)", ->
expectPropertyEvents(
->
prop = series(1, [1,2,3]).toProperty(0)
prop.subscribe (event) =>
Bacon.noMore
prop
[0, 1, 2, 3])
describe "Property.toEventStream", ->
it "creates a stream that starts with current property value", ->
expectStreamEvents(
-> series(1, [1, 2]).toProperty(0).toEventStream()
[0, 1, 2])
describe "Property.map", ->
it "maps property values", ->
expectPropertyEvents(
->
s = new Bacon.Bus()
p = s.toProperty(1).map(times, 2)
soon ->
s.push 2
s.error()
s.end()
p
[2, 4, error()])
describe "Property.filter", ->
it "should filter values", ->
expectPropertyEvents(
-> series(1, [1, error(), 2, 3]).toProperty().filter(lessThan(3))
[1, error(), 2])
it "preserves old current value if the updated value is non-matching", ->
s = new Bacon.Bus()
p = s.toProperty().filter(lessThan(2))
p.onValue(=>) # to ensure that property is actualy updated
s.push(1)
s.push(2)
values = []
p.onValue((v) => values.push(v))
expect(values).toEqual([1])
describe "Property.take(1)", ->
it "takes the Initial event", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty(0).take(1)
[0])
it "takes the first Next event, if no Initial value", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty().take(1)
[1])
it "works for constants", ->
expectPropertyEvents(
-> Bacon.constant(1)
[1])
describe "Bacon.once().take(1)", ->
it "works", ->
expectStreamEvents(
-> Bacon.once(1).take(1)
[1])
describe "Property.takeUntil", ->
it "takes elements from source until an event appears in the other stream", ->
expectPropertyEvents(
-> series(2, [1,2,3]).toProperty().takeUntil(Bacon.later(t(3)))
[1])
it "works with errors", ->
expectPropertyEvents(
->
src = repeat(2, [1, error(), 3])
stopper = repeat(5, ["stop!"])
src.toProperty(0).takeUntil(stopper)
[0, 1, error()])
describe "Property.delay", ->
it "delivers initial value and changes", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty(0).delay(t(1))
[0,1,2,3])
it "delays changes", ->
expectStreamEvents(
-> series(2, [1,2,3]).toProperty()
.delay(t(2)).changes().takeUntil(Bacon.later(t(5)))
[1])
it "does not delay initial value", ->
expectPropertyEvents(
-> series(3, [1]).toProperty(0).delay(1).takeUntil(Bacon.later(t(2)))
[0])
describe "Property.throttle", ->
it "delivers initial value and changes", ->
expectPropertyEvents(
-> series(2, [1,2,3]).toProperty(0).throttle(t(1))
[0,1,2,3])
it "throttles changes, but not initial value", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty(0).throttle(t(4))
[0,3])
it "works without initial value", ->
expectPropertyEvents(
-> series(2, [1,2,3]).toProperty().throttle(t(4))
[3])
describe "Property.throttle2", ->
it "throttles changes, but not initial value", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty(0).throttle2(t(4))
[0,3])
describe "Property.endOnError", ->
it "terminates on Error", ->
expectPropertyEvents(
-> series(2, [1, error(), 2]).toProperty().endOnError()
[1, error()])
describe "Property.skipDuplicates", ->
it "drops duplicates", ->
expectPropertyEvents(
-> series(1, [1, 2, error(), 2, 3, 1]).toProperty(0).skipDuplicates()
[0, 1, 2, error(), 3, 1])
describe "Property.changes", ->
it "sends property change events", ->
expectStreamEvents(
->
s = new Bacon.Bus()
p = s.toProperty("a").changes()
soon ->
s.push "b"
s.error()
s.end()
p
["b", error()])
describe "Property.combine", ->
it "combines latest values of two properties, with given combinator function, passing through errors", ->
expectPropertyEvents(
->
left = series(2, [1, error(), 2, 3]).toProperty()
right = series(2, [4, error(), 5, 6]).delay(t(1)).toProperty()
left.combine(right, add)
[5, error(), error(), 6, 7, 8, 9])
it "also accepts a field name instead of combinator function", ->
expectPropertyEvents(
->
left = series(1, [[1]]).toProperty()
right = series(2, [[2]]).toProperty()
left.combine(right, ".concat")
[[1, 2]])
it "combines with null values", ->
expectPropertyEvents(
->
left = series(1, [null]).toProperty()
right = series(1, [null]).toProperty()
left.combine(right, (l, r)-> [l, r])
[[null, null]])
it "unsubscribes when initial value callback returns Bacon.noMore", ->
calls = 0
bus = new Bacon.Bus()
other = Bacon.constant(["rolfcopter"])
bus.toProperty(["lollerskates"]).combine(other, ".concat").subscribe (e) ->
if !e.isInitial()
calls += 1
Bacon.noMore
bus.push(["fail whale"])
expect(calls).toBe 0
describe "Bacon.combineAsArray", ->
it "combines properties and latest values of streams, into a Property having arrays as values", ->
expectPropertyEvents(
->
stream = series(1, ["a", "b"])
Bacon.combineAsArray([Bacon.constant(1), Bacon.constant(2), stream])
[[1, 2, "a"], [1, 2, "b"]])
it "Works with streams provided as a list of arguments as well as with a single array arg", ->
expectPropertyEvents(
->
stream = series(1, ["a", "b"])
Bacon.combineAsArray(Bacon.constant(1), Bacon.constant(2), stream)
[[1, 2, "a"], [1, 2, "b"]])
it "works with single stream", ->
expectPropertyEvents(
->
Bacon.combineAsArray([Bacon.constant(1)])
[[1]])
it "works with arrays as values, with first array being empty (bug fix)", ->
expectPropertyEvents(
->
Bacon.combineAsArray([Bacon.constant([]), Bacon.constant([1])])
([[[], [1]]]))
it "works with arrays as values, with first array being non-empty (bug fix)", ->
expectPropertyEvents(
->
Bacon.combineAsArray([Bacon.constant([1]), Bacon.constant([2])])
([[[1], [2]]]))
it "works with empty array", ->
expectPropertyEvents(
-> Bacon.combineAsArray([])
[[]])
describe "Bacon.combineWith", ->
it "combines properties by applying the combinator function to values", ->
expectPropertyEvents(
->
stream = series(1, [[1]])
Bacon.combineWith([stream, Bacon.constant([2]), Bacon.constant([3])], ".concat")
[[1, 2, 3]])
describe "Boolean logic", ->
it "combines Properties with and()", ->
expectPropertyEvents(
-> Bacon.constant(true).and(Bacon.constant(false))
[false])
it "combines Properties with or()", ->
expectPropertyEvents(
-> Bacon.constant(true).or(Bacon.constant(false))
[true])
it "inverts property with not()", ->
expectPropertyEvents(
-> Bacon.constant(true).not()
[false])
describe "Bacon.mergeAll", ->
it ("merges all given streams"), ->
expectStreamEvents(
->
Bacon.mergeAll([
series(3, [1, 2])
series(3, [3, 4]).delay(t(1))
series(3, [5, 6]).delay(t(2))])
[1, 3, 5, 2, 4, 6])
describe "Property.sampledBy", ->
it "samples property at events, resulting to EventStream", ->
expectStreamEvents(
->
prop = series(2, [1, 2]).toProperty()
stream = repeat(3, ["troll"]).take(4)
prop.sampledBy(stream)
[1, 2, 2, 2])
it "includes errors from both Property and EventStream", ->
expectStreamEvents(
->
prop = series(2, [error(), 2]).toProperty()
stream = series(3, [error(), "troll"])
prop.sampledBy(stream)
[error(), error(), 2])
it "ends when sampling stream ends", ->
expectStreamEvents(
->
prop = repeat(2, [1, 2]).toProperty()
stream = repeat(2, [""]).delay(t(1)).take(4)
prop.sampledBy(stream)
[1, 2, 1, 2])
it "accepts optional combinator function f(Vp, Vs)", ->
expectStreamEvents(
->
prop = series(2, ["a", "b"]).toProperty()
stream = series(2, ["1", "2", "1", "2"]).delay(t(1))
prop.sampledBy(stream, add)
["a1", "b2", "b1", "b2"])
it "allows method name instead of function too", ->
expectStreamEvents(
->
Bacon.constant([1]).sampledBy(Bacon.once([2]), ".concat")
[[1, 2]])
it "works with same origin", ->
expectStreamEvents(
->
src = series(2, [1, 2])
src.toProperty().sampledBy(src)
[1, 2])
expectStreamEvents(
->
src = series(2, [1, 2])
src.toProperty().sampledBy(src.map(times, 2))
[1, 2])
describe "Property.sample", ->
it "samples property by given interval", ->
expectStreamEvents(
->
prop = series(2, [1, 2]).toProperty()
prop.sample(t(3)).take(4)
[1, 2, 2, 2])
it "includes all errors", ->
expectStreamEvents(
->
prop = series(2, [1, error(), 2]).toProperty()
prop.sample(t(5)).take(2)
[error(), 1, 2])
describe "EventStream.scan", ->
it "accumulates values with given seed and accumulator function, passing through errors", ->
expectPropertyEvents(
-> series(1, [1, 2, error(), 3]).scan(0, add)
[0, 1, 3, error(), 6])
it "also works with method name", ->
expectPropertyEvents(
-> series(1, [[1], [2]]).scan([], ".concat")
[[], [1], [1, 2]])
it "yields the seed value immediately", ->
outputs = []
bus = new Bacon.Bus()
bus.scan(0, -> 1).onValue((value) -> outputs.push(value))
expect(outputs).toEqual([0])
it "yields null seed value", ->
expectPropertyEvents(
-> series(1, [1]).scan(null, ->1)
[null, 1])
describe "Property.scan", ->
it "with Init value, starts with f(seed, init)", ->
expectPropertyEvents(
-> series(1, [2,3]).toProperty(1).scan(0, add)
[1, 3, 6])
it "without Init value, starts with seed", ->
expectPropertyEvents(
-> series(1, [2,3]).toProperty().scan(0, add)
[0, 2, 5])
it "treats null seed value like any other value", ->
expectPropertyEvents(
-> series(1, [1]).toProperty().scan(null, add)
[null, 1])
expectPropertyEvents(
-> series(1, [2]).toProperty(1).scan(null, add)
[1, 3])
describe "EventStream.diff", ->
it "apply diff function to previous and current values, passing through errors", ->
expectPropertyEvents(
-> series(1, [1, 2, error(), 3]).diff(0, add)
[1, 3, error(), 5])
it "also works with method name", ->
expectPropertyEvents(
-> series(1, [[1], [2]]).diff([0], ".concat")
[[0, 1], [1, 2]])
it "does not yields the start value immediately", ->
outputs = []
bus = new Bacon.Bus()
bus.diff(0, -> 1).onValue((value) -> outputs.push(value))
expect(outputs).toEqual([])
describe "Property.diff", ->
it "with Init value, starts with f(start, init)", ->
expectPropertyEvents(
-> series(1, [2,3]).toProperty(1).diff(0, add)
[1, 3, 5])
it "without Init value, waits for the first value", ->
expectPropertyEvents(
-> series(1, [2,3]).toProperty().diff(0, add)
[2, 5])
it "treats null start value like any other value", ->
expectPropertyEvents(
-> series(1, [1]).toProperty().diff(null, add)
[1])
expectPropertyEvents(
-> series(1, [2]).toProperty(1).diff(null, add)
[1, 3])
describe "combineTemplate", ->
it "combines streams according to a template object", ->
expectPropertyEvents(
->
firstName = Bacon.constant("juha")
lastName = Bacon.constant("paananen")
userName = Bacon.constant("mr.bacon")
Bacon.combineTemplate({ userName: userName, password: "*****", fullName: { firstName: firstName, lastName: lastName }})
[{ userName: "mr.bacon", password: "<PASSWORD>*****", fullName: { firstName: "juha", lastName: "paananen" } }])
it "works with a single-stream template", ->
expectPropertyEvents(
->
bacon = Bacon.constant("bacon")
Bacon.combineTemplate({ favoriteFood: bacon })
[{ favoriteFood: "bacon" }])
it "works when dynamic part is not the last part (bug fix)", ->
expectPropertyEvents(
->
username = Bacon.constant("raimohanska")
password = Bacon.constant("easy")
Bacon.combineTemplate({url: "/user/login",
data: { username: username, password: <PASSWORD> }, type: "post"})
[url: "/user/login", data: {username: "raimohanska", password: "<PASSWORD>"}, type: "post"])
it "works with arrays as data (bug fix)", ->
expectPropertyEvents(
-> Bacon.combineTemplate( { x : Bacon.constant([]), y : Bacon.constant([[]]), z : Bacon.constant(["z"])})
[{ x : [], y : [[]], z : ["z"]}])
it "supports empty object", ->
expectPropertyEvents(
-> Bacon.combineTemplate({})
[{}])
it "supports arrays", ->
value = {key: [{ x: 1 }, { x: 2 }]}
Bacon.combineTemplate(value).onValue (x) ->
expect(x).toEqual(value)
expect(x.key instanceof Array).toEqual(true) # seems that the former passes even if x is not an array
value = [{ x: 1 }, { x: 2 }]
Bacon.combineTemplate(value).onValue (x) ->
expect(x).toEqual(value)
expect(x instanceof Array).toEqual(true)
value = {key: [{ x: 1 }, { x: 2 }], key2: {}}
Bacon.combineTemplate(value).onValue (x) ->
expect(x).toEqual(value)
expect(x.key instanceof Array).toEqual(true)
value = {key: [{ x: 1 }, { x: Bacon.constant(2) }]}
Bacon.combineTemplate(value).onValue (x) ->
expect(x).toEqual({key: [{ x: 1 }, { x: 2 }]})
expect(x.key instanceof Array).toEqual(true) # seems that the former passes even if x is not an array
describe "Property.decode", ->
it "switches between source Properties based on property value", ->
expectPropertyEvents(
->
a = Bacon.constant("a")
b = Bacon.constant("b")
c = Bacon.constant("c")
series(1, [1,2,3]).toProperty().decode({1: a, 2: b, 3: c})
["a", "b", "c"])
describe "Observable.onValues", ->
it "splits value array to callback arguments", ->
f = mockFunction()
Bacon.constant([1,2,3]).onValues(f)
f.verify(1,2,3)
describe "Observable.subscribe and onValue", ->
it "returns a dispose() for unsubscribing", ->
s = new Bacon.Bus()
values = []
dispose = s.onValue (value) -> values.push value
s.push "lol"
dispose()
s.push "wut"
expect(values).toEqual(["lol"])
describe "Observable.onEnd", ->
it "is called on stream end", ->
s = new Bacon.Bus()
ended = false
s.onEnd(-> ended = true)
s.push("LOL")
expect(ended).toEqual(false)
s.end()
expect(ended).toEqual(true)
describe "Field value extraction", ->
it "extracts field value", ->
expectStreamEvents(
-> Bacon.once({lol:"wut"}).map(".lol")
["wut"])
it "extracts nested field value", ->
expectStreamEvents(
-> Bacon.once({lol:{wut: "wat"}}).map(".lol.wut")
["wat"])
it "if field value is method, it does a method call", ->
context = null
result = null
object = {
method: ->
context = this
"result"
}
Bacon.once(object).map(".method").onValue((x) -> result = x)
expect(result).toEqual("result")
expect(context).toEqual(object)
testSideEffects = (wrapper, method) ->
->
it "(f) calls function with property value", ->
f = mockFunction()
wrapper("kaboom")[method](f)
f.verify("kaboom")
it "(f, param) calls function, partially applied with param", ->
f = mockFunction()
wrapper("kaboom")[method](f, "pow")
f.verify("pow", "kaboom")
it "('.method') calls event value object method", ->
value = mock("get")
value.when().get().thenReturn("pow")
wrapper(value)[method](".get")
value.verify().get()
it "('.method', param) calls event value object method with param", ->
value = mock("get")
value.when().get("value").thenReturn("pow")
wrapper(value)[method](".get", "value")
value.verify().get("value")
it "(object, method) calls object method with property value", ->
target = mock("pow")
wrapper("kaboom")[method](target, "pow")
target.verify().pow("kaboom")
it "(object, method, param) partially applies object method with param", ->
target = mock("pow")
wrapper("kaboom")[method](target, "pow", "smack")
target.verify().pow("smack", "kaboom")
it "(object, method, param1, param2) partially applies with 2 args", ->
target = mock("pow")
wrapper("kaboom")[method](target, "pow", "smack", "whack")
target.verify().pow("smack", "whack", "kaboom")
describe "Property.onValue", testSideEffects(Bacon.constant, "onValue")
describe "Property.assign", testSideEffects(Bacon.constant, "assign")
describe "EventStream.onValue", testSideEffects(Bacon.once, "onValue")
describe "Property.assign", ->
it "calls given objects given method with property values", ->
target = mock("pow")
Bacon.constant("kaboom").assign(target, "pow")
target.verify().pow("kaboom")
it "allows partial application of method (i.e. adding fixed args)", ->
target = mock("pow")
Bacon.constant("kaboom").assign(target, "pow", "smack")
target.verify().pow("smack", "kaboom")
it "allows partial application of method with 2 args (i.e. adding fixed args)", ->
target = mock("pow")
Bacon.constant("kaboom").assign(target, "pow", "smack", "whack")
target.verify().pow("smack", "whack", "kaboom")
describe "Bacon.Bus", ->
it "merges plugged-in streams", ->
bus = new Bacon.Bus()
values = []
dispose = bus.onValue (value) -> values.push value
push = new Bacon.Bus()
bus.plug(push)
push.push("lol")
expect(values).toEqual(["lol"])
dispose()
verifyCleanup()
it "works with looped streams", ->
expectStreamEvents(
->
bus = new Bacon.Bus()
bus.plug(Bacon.later(t(2), "lol"))
bus.plug(bus.filter((value) => "lol" == value).map(=> "wut"))
Bacon.later(t(4)).onValue(=> bus.end())
bus
["lol", "wut"])
it "dispose works with looped streams", ->
bus = new Bacon.Bus()
bus.plug(Bacon.later(t(2), "lol"))
bus.plug(bus.filter((value) => "lol" == value).map(=> "wut"))
dispose = bus.onValue(=>)
dispose()
it "Removes input from input list on End event", ->
subscribed = 0
bus = new Bacon.Bus()
input = new Bacon.Bus()
# override subscribe to increase the subscribed-count
inputSubscribe = input.subscribe
input.subscribe = (sink) ->
subscribed++
inputSubscribe(sink)
bus.plug(input)
dispose = bus.onValue(=>)
input.end()
dispose()
bus.onValue(=>) # this latter subscription should not go to the ended source anymore
expect(subscribed).toEqual(1)
it "unsubscribes inputs on end() call", ->
bus = new Bacon.Bus()
input = new Bacon.Bus()
events = []
bus.plug(input)
bus.subscribe((e) => events.push(e))
input.push("a")
bus.end()
input.push("b")
expect(toValues(events)).toEqual(["a", "<end>"])
it "handles cold single-event streams correctly (bug fix)", ->
values = []
bus = new Bacon.Bus()
bus.plug(Bacon.once("x"))
bus.plug(Bacon.once("y"))
bus.onValue((x) -> values.push(x))
expect(values).toEqual(["x", "y"])
it "handles end() calls even when there are no subscribers", ->
bus = new Bacon.Bus()
bus.end()
it "delivers pushed events and errors", ->
expectStreamEvents(
->
s = new Bacon.Bus()
s.push "pullMe"
soon ->
s.push "pushMe"
s.error()
s.end()
s
["pushMe", error()])
it "does not deliver pushed events after end() call", ->
called = false
bus = new Bacon.Bus()
bus.onValue(-> called = true)
bus.end()
bus.push("LOL")
expect(called).toEqual(false)
it "does not plug after end() call", ->
plugged = false
bus = new Bacon.Bus()
bus.end()
bus.plug(new Bacon.EventStream((sink) -> plugged = true; (->)))
bus.onValue(->)
expect(plugged).toEqual(false)
it "returns unplug function from plug", ->
values = []
bus = new Bacon.Bus()
src = new Bacon.Bus()
unplug = bus.plug(src)
bus.onValue((x) -> values.push(x))
src.push("x")
unplug()
src.push("y")
expect(values).toEqual(["x"])
describe "EventStream", ->
it "works with functions as values (bug fix)", ->
expectStreamEvents(
-> Bacon.once(-> "hello").map((f) -> f())
["hello"])
expectStreamEvents(
-> Bacon.once(-> "hello").flatMap(Bacon.once).map((f) -> f())
["hello"])
expectPropertyEvents(
-> Bacon.constant(-> "hello").map((f) -> f())
["hello"])
expectStreamEvents(
-> Bacon.constant(-> "hello").flatMap(Bacon.once).map((f) -> f())
["hello"])
lessThan = (limit) ->
(x) -> x < limit
times = (x, y) -> x * y
add = (x, y) -> x + y
id = (x) -> x
# Wrap EventEmitter as EventTarget
toEventTarget = (emitter) ->
addEventListener: (event, handler) -> emitter.addListener(event, handler)
removeEventListener: (event, handler) -> emitter.removeListener(event, handler)
| true | Bacon = (require "../src/Bacon").Bacon
Mocks = (require "./Mock")
mock = Mocks.mock
mockFunction = Mocks.mockFunction
EventEmitter = require("events").EventEmitter
th = require("./SpecHelper")
t = th.t
expectStreamEvents = th.expectStreamEvents
expectPropertyEvents = th.expectPropertyEvents
verifyCleanup = th.verifyCleanup
error = th.error
soon = th.soon
series = th.series
repeat = th.repeat
toValues = th.toValues
describe "Bacon.later", ->
it "should send single event and end", ->
expectStreamEvents(
-> Bacon.later(t(1), "lol")
["lol"])
describe "Bacon.sequentially", ->
it "should send given events and end", ->
expectStreamEvents(
-> Bacon.sequentially(t(1), ["lol", "wut"])
["lol", "wut"])
it "include error events", ->
expectStreamEvents(
-> Bacon.sequentially(t(1), [error(), "lol"])
[error(), "lol"])
describe "Bacon.interval", ->
it "repeats single element indefinitely", ->
expectStreamEvents(
-> Bacon.interval(t(1), "x").take(3)
["x", "x", "x"])
describe "Bacon.fromCallback", ->
it "makes an EventStream from function that takes a callback", ->
expectStreamEvents(
->
src = (callback) -> callback("lol")
stream = Bacon.fromCallback(src)
["lol"])
it "supports partial application", ->
expectStreamEvents(
->
src = (param, callback) -> callback(param)
stream = Bacon.fromCallback(src, "lol")
["lol"])
describe "Bacon.fromEventTarget", ->
it "should create EventStream from DOM object", ->
emitter = new EventEmitter()
emitter.on "newListener", ->
runs ->
emitter.emit "click", "x"
element = toEventTarget emitter
expectStreamEvents(
-> Bacon.fromEventTarget(element, "click").take(1)
["x"]
)
it "should create EventStream from EventEmitter", ->
emitter = new EventEmitter()
emitter.on "newListener", ->
runs ->
emitter.emit "data", "x"
expectStreamEvents(
-> Bacon.fromEventTarget(emitter, "data").take(1)
["x"]
)
it "should allow a custom map function for EventStream from EventEmitter", ->
emitter = new EventEmitter()
emitter.on "newListener", ->
runs ->
emitter.emit "data", "x", "y"
expectStreamEvents(
-> Bacon.fromEventTarget(emitter, "data", (x, y) => [x, y]).take(1)
[["x", "y"]]
)
it "should clean up event listeners from EventEmitter", ->
emitter = new EventEmitter()
Bacon.fromEventTarget(emitter, "data").take(1).subscribe ->
emitter.emit "data", "x"
expect(emitter.listeners("data").length).toEqual(0)
it "should clean up event listeners from DOM object", ->
emitter = new EventEmitter()
element = toEventTarget emitter
dispose = Bacon.fromEventTarget(element, "click").subscribe ->
dispose()
expect(emitter.listeners("click").length).toEqual(0)
describe "Observable.log", ->
it "does not crash", ->
Bacon.constant(1).log
describe "Observable.slidingWindow", ->
it "slides the window for EventStreams", ->
expectPropertyEvents(
-> series(1, [1,2,3]).slidingWindow(2)
[[], [1], [1,2], [2,3]])
it "slides the window for Properties", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty().slidingWindow(2)
[[], [1], [1,2], [2,3]])
describe "EventStream.filter", ->
it "should filter values", ->
expectStreamEvents(
-> series(1, [1, 2, error(), 3]).filter(lessThan(3))
[1, 2, error()])
it "extracts field values", ->
expectStreamEvents(
-> series(1, [{good:true, value:"yes"}, {good:false, value:"no"}]).filter(".good").map(".value")
["yes"])
it "can filter by Property value", ->
expectStreamEvents(
->
src = series(1, [1,1,2,3,4,4,8,7])
odd = src.map((x) -> x % 2).toProperty()
src.filter(odd)
[1,1,3,7])
describe "EventStream.map", ->
it "should map with given function", ->
expectStreamEvents(
-> series(1, [1, 2, 3]).map(times, 2)
[2, 4, 6])
it "also accepts a constant value", ->
expectStreamEvents(
-> series(1, [1, 2, 3,]).map("lol")
["lol", "lol", "lol"])
it "extracts property from value object", ->
o = { lol : "wut" }
expectStreamEvents(
-> repeat(1, [o]).take(3).map(".lol")
["wut", "wut", "wut"])
it "extracts a nested property too", ->
o = { lol : { wut : "wat" } }
expectStreamEvents(
-> Bacon.once(o).map(".lol.wut")
["wat"])
it "in case of a function property, calls the function with no args", ->
expectStreamEvents(
-> Bacon.once([1,2,3]).map(".length")
[3])
it "allows arguments for methods", ->
thing = { square: (x) -> x * x }
expectStreamEvents(
-> Bacon.once(thing).map(".square", 2)
[4])
it "works with method call on given object, with partial application", ->
multiplier = { multiply: (x, y) -> x * y }
expectStreamEvents(
-> series(1, [1,2,3]).map(multiplier, "multiply", 2)
[2,4,6])
it "can map to a Property value", ->
expectStreamEvents(
-> series(1, [1,2,3]).map(Bacon.constant(2))
[2,2,2])
describe "EventStream.mapError", ->
it "should map error events with given function", ->
expectStreamEvents(
-> repeat(1, [1, error("OOPS")]).mapError(id).take(2)
[1, "OOPS"])
it "also accepts a constant value", ->
expectStreamEvents(
-> repeat(1, [1, error()]).mapError("ERR").take(2)
[1, "ERR"])
describe "EventStream.doAction", ->
it "calls function before sending value to listeners", ->
called = []
bus = new Bacon.Bus()
s = bus.doAction((x) -> called.push(x))
s.onValue(->)
s.onValue(->)
bus.push(1)
expect(called).toEqual([1])
it "does not alter the stream", ->
expectStreamEvents(
-> series(1, [1, 2]).doAction(->)
[1, 2])
describe "EventStream.mapEnd", ->
it "produces an extra element on stream end", ->
expectStreamEvents(
-> series(1, ["1", error()]).mapEnd("the end")
["1", error(), "the end"])
it "accepts either a function or a constant value", ->
expectStreamEvents(
-> series(1, ["1", error()]).mapEnd(-> "the end")
["1", error(), "the end"])
it "works with undefined value as well", ->
expectStreamEvents(
-> series(1, ["1", error()]).mapEnd()
["1", error(), undefined])
describe "EventStream.takeWhile", ->
it "should take while predicate is true", ->
expectStreamEvents(
-> repeat(1, [1, error("wat"), 2, 3]).takeWhile(lessThan(3))
[1, error("wat"), 2])
describe "EventStream.skip", ->
it "should skip first N items", ->
expectStreamEvents(
-> series(1, [1, error(), 2, error(), 3]).skip(1)
[error(), 2, error(), 3])
describe "EventStream.skipDuplicates", ->
it "drops duplicates", ->
expectStreamEvents(
-> series(1, [1, 2, error(), 2, 3, 1]).skipDuplicates()
[1, 2, error(), 3, 1])
it "allows undefined as initial value", ->
expectStreamEvents(
-> series(1, [undefined, undefined, 1, 2]).skipDuplicates()
[undefined, 1, 2])
it "works with custom isEqual function", ->
a = {x: 1}; b = {x: 2}; c = {x: 2}; d = {x: 3}; e = {x: 1}
isEqual = (a, b) -> a?.x == b?.x
expectStreamEvents(
-> series(1, [a, b, error(), c, d, e]).skipDuplicates(isEqual)
[a, b, error(), d, e])
describe "EventStream.flatMap", ->
it "should spawn new stream for each value and collect results into a single stream", ->
expectStreamEvents(
-> series(1, [1, 2]).flatMap (value) ->
Bacon.sequentially(t(2), [value, error(), value])
[1, 2, error(), error(), 1, 2])
it "should pass source errors through to the result", ->
expectStreamEvents(
-> series(1, [error(), 1]).flatMap (value) ->
Bacon.later(t(1), value)
[error(), 1])
it "should work with a spawned stream responding synchronously", ->
expectStreamEvents(
-> series(1, [1, 2]).flatMap (value) ->
Bacon.never().concat(Bacon.once(value))
[1, 2])
it "should work with a source stream responding synchronously", ->
expectStreamEvents(
-> Bacon.once(1).flatMap (value) ->
Bacon.once(value)
[1])
it "Works also when f returns a Property instead of an EventStream", ->
expectStreamEvents(
-> series(1, [1,2]).flatMap(Bacon.constant)
[1,2])
describe "Property.flatMap", ->
it "should spawn new stream for all events including Init", ->
expectStreamEvents(
->
once = (x) -> Bacon.once(x)
series(1, [1, 2]).toProperty(0).flatMap(once)
[0, 1, 2])
it "Works also when f returns a Property instead of an EventStream", ->
expectStreamEvents(
-> series(1, [1,2]).toProperty().flatMap(Bacon.constant)
[1,2])
expectPropertyEvents(
-> series(1, [1,2]).toProperty().flatMap(Bacon.constant).toProperty()
[1,2])
describe "EventStream.flatMapLatest", ->
it "spawns new streams but collects values from the latest spawned stream only", ->
expectStreamEvents(
-> series(3, [1, 2]).flatMapLatest (value) ->
Bacon.sequentially(t(2), [value, error(), value])
[1, 2, error(), 2])
describe "Property.flatMapLatest", ->
it "spawns new streams but collects values from the latest spawned stream only", ->
expectStreamEvents(
-> series(3, [1, 2]).toProperty(0).flatMapLatest (value) ->
Bacon.sequentially(t(2), [value, value])
[0, 1, 2, 2])
describe "EventStream.merge", ->
it "merges two streams and ends when both are exhausted", ->
expectStreamEvents(
->
left = series(1, [1, error(), 2, 3])
right = series(1, [4, 5, 6]).delay(t(4))
left.merge(right)
[1, error(), 2, 3, 4, 5, 6])
it "respects subscriber return value", ->
expectStreamEvents(
->
left = repeat(2, [1, 3]).take(3)
right = repeat(3, [2]).take(3)
left.merge(right).takeWhile(lessThan(2))
[1])
describe "EventStream.delay", ->
it "delays all events (except errors) by given delay in milliseconds", ->
expectStreamEvents(
->
left = series(2, [1, 2, 3])
right = series(1, [error(), 4, 5, 6]).delay(t(6))
left.merge(right)
[error(), 1, 2, 3, 4, 5, 6])
describe "EventStream.throttle", ->
it "throttles input by given delay, passing-through errors", ->
expectStreamEvents(
-> series(2, [1, error(), 2]).throttle(t(7))
[error(), 2])
it "waits for a quiet period before outputing anything", ->
expectStreamTimings(
-> series(2, [1, 2, 3, 4]).throttle(t(3))
[[11, 4]])
describe "EventStream.throttle2(delay)", ->
it "outputs at steady intervals, without waiting for quite period", ->
expectStreamTimings(
-> series(2, [1, 2, 3]).throttle2(t(3))
[[5, 2], [8, 3]])
describe "EventStream.bufferWithTime", ->
it "returns events in bursts, passing through errors", ->
expectStreamEvents(
-> series(2, [error(), 1, 2, 3, 4, 5, 6, 7]).bufferWithTime(t(7))
[error(), [1, 2, 3, 4], [5, 6, 7]])
it "keeps constant output rate even when input is sporadical", ->
th.expectStreamTimings(
-> th.atGivenTimes([[0, "a"], [3, "b"], [5, "c"]]).bufferWithTime(t(2))
[[2, ["a"]], [4, ["b"]], [6, ["c"]]]
)
it "works with empty stream", ->
expectStreamEvents(
-> Bacon.never().bufferWithTime(t(1))
[])
it "allows custom defer-function", ->
fast = (f) -> setTimeout(f, 0)
th.expectStreamTimings(
-> th.atGivenTimes([[0, "a"], [2, "b"]]).bufferWithTime(fast)
[[0, ["a"]], [2, ["b"]]])
it "works with synchronous defer-function", ->
sync = (f) -> f()
th.expectStreamTimings(
-> th.atGivenTimes([[0, "a"], [2, "b"]]).bufferWithTime(sync)
[[0, ["a"]], [2, ["b"]]])
describe "EventStream.bufferWithCount", ->
it "returns events in chunks of fixed size, passing through errors", ->
expectStreamEvents(
-> series(1, [1, 2, 3, error(), 4, 5]).bufferWithCount(2)
[[1, 2], error(), [3, 4], [5]])
describe "EventStream.takeUntil", ->
it "takes elements from source until an event appears in the other stream", ->
expectStreamEvents(
->
src = repeat(3, [1, 2, 3])
stopper = repeat(7, ["stop!"])
src.takeUntil(stopper)
[1, 2])
it "works on self-derived stopper", ->
expectStreamEvents(
->
src = repeat(3, [3, 2, 1])
stopper = src.filter(lessThan(3))
src.takeUntil(stopper)
[3])
it "includes source errors, ignores stopper errors", ->
expectStreamEvents(
->
src = repeat(2, [1, error(), 2, 3])
stopper = repeat(7, ["stop!"]).merge(repeat(1, [error()]))
src.takeUntil(stopper)
[1, error(), 2])
describe "EventStream.awaiting(other)", ->
it "indicates whether s1 has produced output after s2 (or only the former has output so far)", ->
expectPropertyEvents(
-> series(2, [1, 1]).awaiting(series(3, [2]))
[false, true, false, true])
describe "EventStream.endOnError", ->
it "terminates on error", ->
expectStreamEvents(
-> repeat(1, [1, 2, error(), 3]).endOnError()
[1, 2, error()])
describe "Bacon.constant", ->
it "creates a constant property", ->
expectPropertyEvents(
-> Bacon.constant("lol")
["lol"])
it "ignores unsubscribe", ->
Bacon.constant("lol").onValue(=>)()
it "provides same value to all listeners", ->
c = Bacon.constant("lol")
expectPropertyEvents((-> c), ["lol"])
f = mockFunction()
c.onValue(f)
f.verify("lol")
it "provides same value to all listeners, when mapped (bug fix)", ->
c = Bacon.constant("lol").map(id)
f = mockFunction()
c.onValue(f)
f.verify("lol")
c.onValue(f)
f.verify("lol")
describe "Bacon.never", ->
it "should send just end", ->
expectStreamEvents(
-> Bacon.never()
[])
describe "Bacon.once", ->
it "should send single event and end", ->
expectStreamEvents(
-> Bacon.once("pow")
["pow"])
describe "EventStream.concat", ->
it "provides values from streams in given order and ends when both are exhausted", ->
expectStreamEvents(
->
left = series(2, [1, error(), 2, 3])
right = series(1, [4, 5, 6])
left.concat(right)
[1, error(), 2, 3, 4, 5, 6])
it "respects subscriber return value when providing events from left stream", ->
expectStreamEvents(
->
left = repeat(3, [1, 3]).take(3)
right = repeat(2, [1]).take(3)
left.concat(right).takeWhile(lessThan(2))
[1])
it "respects subscriber return value when providing events from right stream", ->
expectStreamEvents(
->
left = series(3, [1, 2])
right = series(2, [2, 4, 6])
left.concat(right).takeWhile(lessThan(4))
[1, 2, 2])
it "works with Bacon.never()", ->
expectStreamEvents(
-> Bacon.never().concat(Bacon.never())
[])
it "works with Bacon.once()", ->
expectStreamEvents(
-> Bacon.once(2).concat(Bacon.once(1))
[2, 1])
it "works with Bacon.once() and Bacon.never()", ->
expectStreamEvents(
-> Bacon.once(1).concat(Bacon.never())
[1])
it "works with Bacon.never() and Bacon.once()", ->
expectStreamEvents(
-> Bacon.never().concat(Bacon.once(1))
[1])
describe "EventStream.startWith", ->
it "provides seed value, then the rest", ->
expectStreamEvents(
->
left = series(1, [1, 2, 3])
left.startWith('pow')
['pow', 1, 2, 3])
describe "Property", ->
it "delivers current value and changes to subscribers", ->
expectPropertyEvents(
->
s = new Bacon.Bus()
p = s.toProperty("a")
soon ->
s.push "b"
s.end()
p
["a", "b"])
it "passes through also Errors", ->
expectPropertyEvents(
-> series(1, [1, error(), 2]).toProperty()
[1, error(), 2])
it "supports null as value", ->
expectPropertyEvents(
-> series(1, [null, 1, null]).toProperty(null)
[null, null, 1, null])
it "does not get messed-up by a transient subscriber (bug fix)", ->
expectPropertyEvents(
->
prop = series(1, [1,2,3]).toProperty(0)
prop.subscribe (event) =>
Bacon.noMore
prop
[0, 1, 2, 3])
describe "Property.toEventStream", ->
it "creates a stream that starts with current property value", ->
expectStreamEvents(
-> series(1, [1, 2]).toProperty(0).toEventStream()
[0, 1, 2])
describe "Property.map", ->
it "maps property values", ->
expectPropertyEvents(
->
s = new Bacon.Bus()
p = s.toProperty(1).map(times, 2)
soon ->
s.push 2
s.error()
s.end()
p
[2, 4, error()])
describe "Property.filter", ->
it "should filter values", ->
expectPropertyEvents(
-> series(1, [1, error(), 2, 3]).toProperty().filter(lessThan(3))
[1, error(), 2])
it "preserves old current value if the updated value is non-matching", ->
s = new Bacon.Bus()
p = s.toProperty().filter(lessThan(2))
p.onValue(=>) # to ensure that property is actualy updated
s.push(1)
s.push(2)
values = []
p.onValue((v) => values.push(v))
expect(values).toEqual([1])
describe "Property.take(1)", ->
it "takes the Initial event", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty(0).take(1)
[0])
it "takes the first Next event, if no Initial value", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty().take(1)
[1])
it "works for constants", ->
expectPropertyEvents(
-> Bacon.constant(1)
[1])
describe "Bacon.once().take(1)", ->
it "works", ->
expectStreamEvents(
-> Bacon.once(1).take(1)
[1])
describe "Property.takeUntil", ->
it "takes elements from source until an event appears in the other stream", ->
expectPropertyEvents(
-> series(2, [1,2,3]).toProperty().takeUntil(Bacon.later(t(3)))
[1])
it "works with errors", ->
expectPropertyEvents(
->
src = repeat(2, [1, error(), 3])
stopper = repeat(5, ["stop!"])
src.toProperty(0).takeUntil(stopper)
[0, 1, error()])
describe "Property.delay", ->
it "delivers initial value and changes", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty(0).delay(t(1))
[0,1,2,3])
it "delays changes", ->
expectStreamEvents(
-> series(2, [1,2,3]).toProperty()
.delay(t(2)).changes().takeUntil(Bacon.later(t(5)))
[1])
it "does not delay initial value", ->
expectPropertyEvents(
-> series(3, [1]).toProperty(0).delay(1).takeUntil(Bacon.later(t(2)))
[0])
describe "Property.throttle", ->
it "delivers initial value and changes", ->
expectPropertyEvents(
-> series(2, [1,2,3]).toProperty(0).throttle(t(1))
[0,1,2,3])
it "throttles changes, but not initial value", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty(0).throttle(t(4))
[0,3])
it "works without initial value", ->
expectPropertyEvents(
-> series(2, [1,2,3]).toProperty().throttle(t(4))
[3])
describe "Property.throttle2", ->
it "throttles changes, but not initial value", ->
expectPropertyEvents(
-> series(1, [1,2,3]).toProperty(0).throttle2(t(4))
[0,3])
describe "Property.endOnError", ->
it "terminates on Error", ->
expectPropertyEvents(
-> series(2, [1, error(), 2]).toProperty().endOnError()
[1, error()])
describe "Property.skipDuplicates", ->
it "drops duplicates", ->
expectPropertyEvents(
-> series(1, [1, 2, error(), 2, 3, 1]).toProperty(0).skipDuplicates()
[0, 1, 2, error(), 3, 1])
describe "Property.changes", ->
it "sends property change events", ->
expectStreamEvents(
->
s = new Bacon.Bus()
p = s.toProperty("a").changes()
soon ->
s.push "b"
s.error()
s.end()
p
["b", error()])
describe "Property.combine", ->
it "combines latest values of two properties, with given combinator function, passing through errors", ->
expectPropertyEvents(
->
left = series(2, [1, error(), 2, 3]).toProperty()
right = series(2, [4, error(), 5, 6]).delay(t(1)).toProperty()
left.combine(right, add)
[5, error(), error(), 6, 7, 8, 9])
it "also accepts a field name instead of combinator function", ->
expectPropertyEvents(
->
left = series(1, [[1]]).toProperty()
right = series(2, [[2]]).toProperty()
left.combine(right, ".concat")
[[1, 2]])
it "combines with null values", ->
expectPropertyEvents(
->
left = series(1, [null]).toProperty()
right = series(1, [null]).toProperty()
left.combine(right, (l, r)-> [l, r])
[[null, null]])
it "unsubscribes when initial value callback returns Bacon.noMore", ->
calls = 0
bus = new Bacon.Bus()
other = Bacon.constant(["rolfcopter"])
bus.toProperty(["lollerskates"]).combine(other, ".concat").subscribe (e) ->
if !e.isInitial()
calls += 1
Bacon.noMore
bus.push(["fail whale"])
expect(calls).toBe 0
describe "Bacon.combineAsArray", ->
it "combines properties and latest values of streams, into a Property having arrays as values", ->
expectPropertyEvents(
->
stream = series(1, ["a", "b"])
Bacon.combineAsArray([Bacon.constant(1), Bacon.constant(2), stream])
[[1, 2, "a"], [1, 2, "b"]])
it "Works with streams provided as a list of arguments as well as with a single array arg", ->
expectPropertyEvents(
->
stream = series(1, ["a", "b"])
Bacon.combineAsArray(Bacon.constant(1), Bacon.constant(2), stream)
[[1, 2, "a"], [1, 2, "b"]])
it "works with single stream", ->
expectPropertyEvents(
->
Bacon.combineAsArray([Bacon.constant(1)])
[[1]])
it "works with arrays as values, with first array being empty (bug fix)", ->
expectPropertyEvents(
->
Bacon.combineAsArray([Bacon.constant([]), Bacon.constant([1])])
([[[], [1]]]))
it "works with arrays as values, with first array being non-empty (bug fix)", ->
expectPropertyEvents(
->
Bacon.combineAsArray([Bacon.constant([1]), Bacon.constant([2])])
([[[1], [2]]]))
it "works with empty array", ->
expectPropertyEvents(
-> Bacon.combineAsArray([])
[[]])
describe "Bacon.combineWith", ->
it "combines properties by applying the combinator function to values", ->
expectPropertyEvents(
->
stream = series(1, [[1]])
Bacon.combineWith([stream, Bacon.constant([2]), Bacon.constant([3])], ".concat")
[[1, 2, 3]])
describe "Boolean logic", ->
it "combines Properties with and()", ->
expectPropertyEvents(
-> Bacon.constant(true).and(Bacon.constant(false))
[false])
it "combines Properties with or()", ->
expectPropertyEvents(
-> Bacon.constant(true).or(Bacon.constant(false))
[true])
it "inverts property with not()", ->
expectPropertyEvents(
-> Bacon.constant(true).not()
[false])
describe "Bacon.mergeAll", ->
it ("merges all given streams"), ->
expectStreamEvents(
->
Bacon.mergeAll([
series(3, [1, 2])
series(3, [3, 4]).delay(t(1))
series(3, [5, 6]).delay(t(2))])
[1, 3, 5, 2, 4, 6])
describe "Property.sampledBy", ->
it "samples property at events, resulting to EventStream", ->
expectStreamEvents(
->
prop = series(2, [1, 2]).toProperty()
stream = repeat(3, ["troll"]).take(4)
prop.sampledBy(stream)
[1, 2, 2, 2])
it "includes errors from both Property and EventStream", ->
expectStreamEvents(
->
prop = series(2, [error(), 2]).toProperty()
stream = series(3, [error(), "troll"])
prop.sampledBy(stream)
[error(), error(), 2])
it "ends when sampling stream ends", ->
expectStreamEvents(
->
prop = repeat(2, [1, 2]).toProperty()
stream = repeat(2, [""]).delay(t(1)).take(4)
prop.sampledBy(stream)
[1, 2, 1, 2])
it "accepts optional combinator function f(Vp, Vs)", ->
expectStreamEvents(
->
prop = series(2, ["a", "b"]).toProperty()
stream = series(2, ["1", "2", "1", "2"]).delay(t(1))
prop.sampledBy(stream, add)
["a1", "b2", "b1", "b2"])
it "allows method name instead of function too", ->
expectStreamEvents(
->
Bacon.constant([1]).sampledBy(Bacon.once([2]), ".concat")
[[1, 2]])
it "works with same origin", ->
expectStreamEvents(
->
src = series(2, [1, 2])
src.toProperty().sampledBy(src)
[1, 2])
expectStreamEvents(
->
src = series(2, [1, 2])
src.toProperty().sampledBy(src.map(times, 2))
[1, 2])
describe "Property.sample", ->
it "samples property by given interval", ->
expectStreamEvents(
->
prop = series(2, [1, 2]).toProperty()
prop.sample(t(3)).take(4)
[1, 2, 2, 2])
it "includes all errors", ->
expectStreamEvents(
->
prop = series(2, [1, error(), 2]).toProperty()
prop.sample(t(5)).take(2)
[error(), 1, 2])
describe "EventStream.scan", ->
it "accumulates values with given seed and accumulator function, passing through errors", ->
expectPropertyEvents(
-> series(1, [1, 2, error(), 3]).scan(0, add)
[0, 1, 3, error(), 6])
it "also works with method name", ->
expectPropertyEvents(
-> series(1, [[1], [2]]).scan([], ".concat")
[[], [1], [1, 2]])
it "yields the seed value immediately", ->
outputs = []
bus = new Bacon.Bus()
bus.scan(0, -> 1).onValue((value) -> outputs.push(value))
expect(outputs).toEqual([0])
it "yields null seed value", ->
expectPropertyEvents(
-> series(1, [1]).scan(null, ->1)
[null, 1])
describe "Property.scan", ->
it "with Init value, starts with f(seed, init)", ->
expectPropertyEvents(
-> series(1, [2,3]).toProperty(1).scan(0, add)
[1, 3, 6])
it "without Init value, starts with seed", ->
expectPropertyEvents(
-> series(1, [2,3]).toProperty().scan(0, add)
[0, 2, 5])
it "treats null seed value like any other value", ->
expectPropertyEvents(
-> series(1, [1]).toProperty().scan(null, add)
[null, 1])
expectPropertyEvents(
-> series(1, [2]).toProperty(1).scan(null, add)
[1, 3])
describe "EventStream.diff", ->
it "apply diff function to previous and current values, passing through errors", ->
expectPropertyEvents(
-> series(1, [1, 2, error(), 3]).diff(0, add)
[1, 3, error(), 5])
it "also works with method name", ->
expectPropertyEvents(
-> series(1, [[1], [2]]).diff([0], ".concat")
[[0, 1], [1, 2]])
it "does not yields the start value immediately", ->
outputs = []
bus = new Bacon.Bus()
bus.diff(0, -> 1).onValue((value) -> outputs.push(value))
expect(outputs).toEqual([])
describe "Property.diff", ->
it "with Init value, starts with f(start, init)", ->
expectPropertyEvents(
-> series(1, [2,3]).toProperty(1).diff(0, add)
[1, 3, 5])
it "without Init value, waits for the first value", ->
expectPropertyEvents(
-> series(1, [2,3]).toProperty().diff(0, add)
[2, 5])
it "treats null start value like any other value", ->
expectPropertyEvents(
-> series(1, [1]).toProperty().diff(null, add)
[1])
expectPropertyEvents(
-> series(1, [2]).toProperty(1).diff(null, add)
[1, 3])
describe "combineTemplate", ->
it "combines streams according to a template object", ->
expectPropertyEvents(
->
firstName = Bacon.constant("juha")
lastName = Bacon.constant("paananen")
userName = Bacon.constant("mr.bacon")
Bacon.combineTemplate({ userName: userName, password: "*****", fullName: { firstName: firstName, lastName: lastName }})
[{ userName: "mr.bacon", password: "PI:PASSWORD:<PASSWORD>END_PI*****", fullName: { firstName: "juha", lastName: "paananen" } }])
it "works with a single-stream template", ->
expectPropertyEvents(
->
bacon = Bacon.constant("bacon")
Bacon.combineTemplate({ favoriteFood: bacon })
[{ favoriteFood: "bacon" }])
it "works when dynamic part is not the last part (bug fix)", ->
expectPropertyEvents(
->
username = Bacon.constant("raimohanska")
password = Bacon.constant("easy")
Bacon.combineTemplate({url: "/user/login",
data: { username: username, password: PI:PASSWORD:<PASSWORD>END_PI }, type: "post"})
[url: "/user/login", data: {username: "raimohanska", password: "PI:PASSWORD:<PASSWORD>END_PI"}, type: "post"])
it "works with arrays as data (bug fix)", ->
expectPropertyEvents(
-> Bacon.combineTemplate( { x : Bacon.constant([]), y : Bacon.constant([[]]), z : Bacon.constant(["z"])})
[{ x : [], y : [[]], z : ["z"]}])
it "supports empty object", ->
expectPropertyEvents(
-> Bacon.combineTemplate({})
[{}])
it "supports arrays", ->
value = {key: [{ x: 1 }, { x: 2 }]}
Bacon.combineTemplate(value).onValue (x) ->
expect(x).toEqual(value)
expect(x.key instanceof Array).toEqual(true) # seems that the former passes even if x is not an array
value = [{ x: 1 }, { x: 2 }]
Bacon.combineTemplate(value).onValue (x) ->
expect(x).toEqual(value)
expect(x instanceof Array).toEqual(true)
value = {key: [{ x: 1 }, { x: 2 }], key2: {}}
Bacon.combineTemplate(value).onValue (x) ->
expect(x).toEqual(value)
expect(x.key instanceof Array).toEqual(true)
value = {key: [{ x: 1 }, { x: Bacon.constant(2) }]}
Bacon.combineTemplate(value).onValue (x) ->
expect(x).toEqual({key: [{ x: 1 }, { x: 2 }]})
expect(x.key instanceof Array).toEqual(true) # seems that the former passes even if x is not an array
describe "Property.decode", ->
it "switches between source Properties based on property value", ->
expectPropertyEvents(
->
a = Bacon.constant("a")
b = Bacon.constant("b")
c = Bacon.constant("c")
series(1, [1,2,3]).toProperty().decode({1: a, 2: b, 3: c})
["a", "b", "c"])
describe "Observable.onValues", ->
it "splits value array to callback arguments", ->
f = mockFunction()
Bacon.constant([1,2,3]).onValues(f)
f.verify(1,2,3)
describe "Observable.subscribe and onValue", ->
it "returns a dispose() for unsubscribing", ->
s = new Bacon.Bus()
values = []
dispose = s.onValue (value) -> values.push value
s.push "lol"
dispose()
s.push "wut"
expect(values).toEqual(["lol"])
describe "Observable.onEnd", ->
it "is called on stream end", ->
s = new Bacon.Bus()
ended = false
s.onEnd(-> ended = true)
s.push("LOL")
expect(ended).toEqual(false)
s.end()
expect(ended).toEqual(true)
describe "Field value extraction", ->
it "extracts field value", ->
expectStreamEvents(
-> Bacon.once({lol:"wut"}).map(".lol")
["wut"])
it "extracts nested field value", ->
expectStreamEvents(
-> Bacon.once({lol:{wut: "wat"}}).map(".lol.wut")
["wat"])
it "if field value is method, it does a method call", ->
context = null
result = null
object = {
method: ->
context = this
"result"
}
Bacon.once(object).map(".method").onValue((x) -> result = x)
expect(result).toEqual("result")
expect(context).toEqual(object)
testSideEffects = (wrapper, method) ->
->
it "(f) calls function with property value", ->
f = mockFunction()
wrapper("kaboom")[method](f)
f.verify("kaboom")
it "(f, param) calls function, partially applied with param", ->
f = mockFunction()
wrapper("kaboom")[method](f, "pow")
f.verify("pow", "kaboom")
it "('.method') calls event value object method", ->
value = mock("get")
value.when().get().thenReturn("pow")
wrapper(value)[method](".get")
value.verify().get()
it "('.method', param) calls event value object method with param", ->
value = mock("get")
value.when().get("value").thenReturn("pow")
wrapper(value)[method](".get", "value")
value.verify().get("value")
it "(object, method) calls object method with property value", ->
target = mock("pow")
wrapper("kaboom")[method](target, "pow")
target.verify().pow("kaboom")
it "(object, method, param) partially applies object method with param", ->
target = mock("pow")
wrapper("kaboom")[method](target, "pow", "smack")
target.verify().pow("smack", "kaboom")
it "(object, method, param1, param2) partially applies with 2 args", ->
target = mock("pow")
wrapper("kaboom")[method](target, "pow", "smack", "whack")
target.verify().pow("smack", "whack", "kaboom")
describe "Property.onValue", testSideEffects(Bacon.constant, "onValue")
describe "Property.assign", testSideEffects(Bacon.constant, "assign")
describe "EventStream.onValue", testSideEffects(Bacon.once, "onValue")
describe "Property.assign", ->
it "calls given objects given method with property values", ->
target = mock("pow")
Bacon.constant("kaboom").assign(target, "pow")
target.verify().pow("kaboom")
it "allows partial application of method (i.e. adding fixed args)", ->
target = mock("pow")
Bacon.constant("kaboom").assign(target, "pow", "smack")
target.verify().pow("smack", "kaboom")
it "allows partial application of method with 2 args (i.e. adding fixed args)", ->
target = mock("pow")
Bacon.constant("kaboom").assign(target, "pow", "smack", "whack")
target.verify().pow("smack", "whack", "kaboom")
describe "Bacon.Bus", ->
it "merges plugged-in streams", ->
bus = new Bacon.Bus()
values = []
dispose = bus.onValue (value) -> values.push value
push = new Bacon.Bus()
bus.plug(push)
push.push("lol")
expect(values).toEqual(["lol"])
dispose()
verifyCleanup()
it "works with looped streams", ->
expectStreamEvents(
->
bus = new Bacon.Bus()
bus.plug(Bacon.later(t(2), "lol"))
bus.plug(bus.filter((value) => "lol" == value).map(=> "wut"))
Bacon.later(t(4)).onValue(=> bus.end())
bus
["lol", "wut"])
it "dispose works with looped streams", ->
bus = new Bacon.Bus()
bus.plug(Bacon.later(t(2), "lol"))
bus.plug(bus.filter((value) => "lol" == value).map(=> "wut"))
dispose = bus.onValue(=>)
dispose()
it "Removes input from input list on End event", ->
subscribed = 0
bus = new Bacon.Bus()
input = new Bacon.Bus()
# override subscribe to increase the subscribed-count
inputSubscribe = input.subscribe
input.subscribe = (sink) ->
subscribed++
inputSubscribe(sink)
bus.plug(input)
dispose = bus.onValue(=>)
input.end()
dispose()
bus.onValue(=>) # this latter subscription should not go to the ended source anymore
expect(subscribed).toEqual(1)
it "unsubscribes inputs on end() call", ->
bus = new Bacon.Bus()
input = new Bacon.Bus()
events = []
bus.plug(input)
bus.subscribe((e) => events.push(e))
input.push("a")
bus.end()
input.push("b")
expect(toValues(events)).toEqual(["a", "<end>"])
it "handles cold single-event streams correctly (bug fix)", ->
values = []
bus = new Bacon.Bus()
bus.plug(Bacon.once("x"))
bus.plug(Bacon.once("y"))
bus.onValue((x) -> values.push(x))
expect(values).toEqual(["x", "y"])
it "handles end() calls even when there are no subscribers", ->
bus = new Bacon.Bus()
bus.end()
it "delivers pushed events and errors", ->
expectStreamEvents(
->
s = new Bacon.Bus()
s.push "pullMe"
soon ->
s.push "pushMe"
s.error()
s.end()
s
["pushMe", error()])
it "does not deliver pushed events after end() call", ->
called = false
bus = new Bacon.Bus()
bus.onValue(-> called = true)
bus.end()
bus.push("LOL")
expect(called).toEqual(false)
it "does not plug after end() call", ->
plugged = false
bus = new Bacon.Bus()
bus.end()
bus.plug(new Bacon.EventStream((sink) -> plugged = true; (->)))
bus.onValue(->)
expect(plugged).toEqual(false)
it "returns unplug function from plug", ->
values = []
bus = new Bacon.Bus()
src = new Bacon.Bus()
unplug = bus.plug(src)
bus.onValue((x) -> values.push(x))
src.push("x")
unplug()
src.push("y")
expect(values).toEqual(["x"])
describe "EventStream", ->
it "works with functions as values (bug fix)", ->
expectStreamEvents(
-> Bacon.once(-> "hello").map((f) -> f())
["hello"])
expectStreamEvents(
-> Bacon.once(-> "hello").flatMap(Bacon.once).map((f) -> f())
["hello"])
expectPropertyEvents(
-> Bacon.constant(-> "hello").map((f) -> f())
["hello"])
expectStreamEvents(
-> Bacon.constant(-> "hello").flatMap(Bacon.once).map((f) -> f())
["hello"])
lessThan = (limit) ->
(x) -> x < limit
times = (x, y) -> x * y
add = (x, y) -> x + y
id = (x) -> x
# Wrap EventEmitter as EventTarget
toEventTarget = (emitter) ->
addEventListener: (event, handler) -> emitter.addListener(event, handler)
removeEventListener: (event, handler) -> emitter.removeListener(event, handler)
|
[
{
"context": "x, y)\n @tag = \"lock_#{tag}\"\n @key = \"key_#{tag}\"\n\n @addAnimation('locked', sprites.getTextu",
"end": 194,
"score": 0.9517753720283508,
"start": 189,
"tag": "KEY",
"value": "#{tag"
}
] | src/lock.coffee | icebreaker/deermas | 1 | class Lock extends Fz2D.Entity
constructor: (sprites, tag=null, x=0, y=0) ->
if tag?
super(sprites.getTexture("lock_#{tag}"), x, y)
@tag = "lock_#{tag}"
@key = "key_#{tag}"
@addAnimation('locked', sprites.getTexture("lock_#{tag}"))
@addAnimation('unlocked', sprites.getTexture("lock_#{tag}_unlocked"))
else
super(sprites.getTexture('lock'), x, y)
@tag = 'lock'
@key = 'key'
@addAnimation('locked', sprites.getTexture('lock'))
@addAnimation('unlocked', sprites.getTexture('lock_unlocked'))
@play('locked')
onunlock: (entity) ->
# nop
unlock: (entity) ->
if @is('locked') and entity.use(@key)
@play('unlocked')
@onunlock(entity)
true
else
false
| 9614 | class Lock extends Fz2D.Entity
constructor: (sprites, tag=null, x=0, y=0) ->
if tag?
super(sprites.getTexture("lock_#{tag}"), x, y)
@tag = "lock_#{tag}"
@key = "key_<KEY>}"
@addAnimation('locked', sprites.getTexture("lock_#{tag}"))
@addAnimation('unlocked', sprites.getTexture("lock_#{tag}_unlocked"))
else
super(sprites.getTexture('lock'), x, y)
@tag = 'lock'
@key = 'key'
@addAnimation('locked', sprites.getTexture('lock'))
@addAnimation('unlocked', sprites.getTexture('lock_unlocked'))
@play('locked')
onunlock: (entity) ->
# nop
unlock: (entity) ->
if @is('locked') and entity.use(@key)
@play('unlocked')
@onunlock(entity)
true
else
false
| true | class Lock extends Fz2D.Entity
constructor: (sprites, tag=null, x=0, y=0) ->
if tag?
super(sprites.getTexture("lock_#{tag}"), x, y)
@tag = "lock_#{tag}"
@key = "key_PI:KEY:<KEY>END_PI}"
@addAnimation('locked', sprites.getTexture("lock_#{tag}"))
@addAnimation('unlocked', sprites.getTexture("lock_#{tag}_unlocked"))
else
super(sprites.getTexture('lock'), x, y)
@tag = 'lock'
@key = 'key'
@addAnimation('locked', sprites.getTexture('lock'))
@addAnimation('unlocked', sprites.getTexture('lock_unlocked'))
@play('locked')
onunlock: (entity) ->
# nop
unlock: (entity) ->
if @is('locked') and entity.use(@key)
@play('unlocked')
@onunlock(entity)
true
else
false
|
[
{
"context": "class Person\n constructor: (@name, @preferences) ->\n @mate = null\n @best_mate",
"end": 34,
"score": 0.7417832612991333,
"start": 28,
"tag": "USERNAME",
"value": "(@name"
},
{
"context": "\n\n preferred_mate_name: =>\n @preferences[@best_mate_rank]\n\n rej... | Task/Stable-marriage-problem/CoffeeScript/stable-marriage-problem.coffee | LaudateCorpus1/RosettaCodeData | 1 | class Person
constructor: (@name, @preferences) ->
@mate = null
@best_mate_rank = 0
@rank = {}
for preference, i in @preferences
@rank[preference] = i
preferred_mate_name: =>
@preferences[@best_mate_rank]
reject: =>
@best_mate_rank += 1
set_mate: (mate) =>
@mate = mate
offer_mate: (free_mate, reject_mate_cb) =>
if @mate
if @covets(free_mate)
console.log "#{free_mate.name} steals #{@name} from #{@mate.name}"
reject_mate_cb @mate
free_mate.set_mate @
@set_mate free_mate
else
console.log "#{free_mate.name} cannot steal #{@name} from #{@mate.name}"
reject_mate_cb free_mate
else
console.log "#{free_mate.name} gets #{@name} first"
free_mate.set_mate @
@set_mate free_mate
happiness: =>
@rank[@mate.name]
covets: (other_mate) =>
@rank[other_mate.name] <= @rank[@mate.name]
persons_by_name = (persons) ->
hsh = {}
for person in persons
hsh[person.name] = person
hsh
mate_off = (guys, gals) ->
free_pursuers = (guy for guy in guys)
guys_by_name = persons_by_name guys
gals_by_name = persons_by_name gals
while free_pursuers.length > 0
free_pursuer = free_pursuers.shift()
gal_name = free_pursuer.preferred_mate_name()
gal = gals_by_name[gal_name]
reject_mate_cb = (guy) ->
guy.reject()
free_pursuers.push guy
gal.offer_mate free_pursuer, reject_mate_cb
report_on_mates = (guys) ->
console.log "\n----Marriage Report"
for guy, i in guys
throw Error("illegal marriage") if guy.mate.mate isnt guy
console.log guy.name, guy.mate.name, \
"(his choice #{guy.happiness()}, her choice #{guy.mate.happiness()} )"
report_potential_adulteries = (guys) ->
for guy1, i in guys
gal1 = guy1.mate
for j in [0...i]
guy2 = guys[j]
gal2 = guy2.mate
if guy1.covets(gal2) and gal2.covets(guy1)
console.log "#{guy1.name} and #{gal2.name} would stray"
if guy2.covets(gal1) and gal1.covets(guy2)
console.log "#{guy2.name} and #{gal1.name} would stray"
perturb = (guys) ->
# mess up marriages by swapping two couples...this is mainly to drive
# out that report_potential_adulteries will actually work
guy0 = guys[0]
guy1 = guys[1]
gal0 = guy0.mate
gal1 = guy1.mate
console.log "\nPerturbing with #{guy0.name}, #{gal0.name}, #{guy1.name}, #{gal1.name}"
guy0.set_mate gal1
guy1.set_mate gal0
gal1.set_mate guy0
gal0.set_mate guy1
Population = ->
guy_preferences =
abe: ['abi', 'eve', 'cath', 'ivy', 'jan', 'dee', 'fay', 'bea', 'hope', 'gay']
bob: ['cath', 'hope', 'abi', 'dee', 'eve', 'fay', 'bea', 'jan', 'ivy', 'gay']
col: ['hope', 'eve', 'abi', 'dee', 'bea', 'fay', 'ivy', 'gay', 'cath', 'jan']
dan: ['ivy', 'fay', 'dee', 'gay', 'hope', 'eve', 'jan', 'bea', 'cath', 'abi']
ed: ['jan', 'dee', 'bea', 'cath', 'fay', 'eve', 'abi', 'ivy', 'hope', 'gay']
fred: ['bea', 'abi', 'dee', 'gay', 'eve', 'ivy', 'cath', 'jan', 'hope', 'fay']
gav: ['gay', 'eve', 'ivy', 'bea', 'cath', 'abi', 'dee', 'hope', 'jan', 'fay']
hal: ['abi', 'eve', 'hope', 'fay', 'ivy', 'cath', 'jan', 'bea', 'gay', 'dee']
ian: ['hope', 'cath', 'dee', 'gay', 'bea', 'abi', 'fay', 'ivy', 'jan', 'eve']
jon: ['abi', 'fay', 'jan', 'gay', 'eve', 'bea', 'dee', 'cath', 'ivy', 'hope']
gal_preferences =
abi: ['bob', 'fred', 'jon', 'gav', 'ian', 'abe', 'dan', 'ed', 'col', 'hal']
bea: ['bob', 'abe', 'col', 'fred', 'gav', 'dan', 'ian', 'ed', 'jon', 'hal']
cath: ['fred', 'bob', 'ed', 'gav', 'hal', 'col', 'ian', 'abe', 'dan', 'jon']
dee: ['fred', 'jon', 'col', 'abe', 'ian', 'hal', 'gav', 'dan', 'bob', 'ed']
eve: ['jon', 'hal', 'fred', 'dan', 'abe', 'gav', 'col', 'ed', 'ian', 'bob']
fay: ['bob', 'abe', 'ed', 'ian', 'jon', 'dan', 'fred', 'gav', 'col', 'hal']
gay: ['jon', 'gav', 'hal', 'fred', 'bob', 'abe', 'col', 'ed', 'dan', 'ian']
hope: ['gav', 'jon', 'bob', 'abe', 'ian', 'dan', 'hal', 'ed', 'col', 'fred']
ivy: ['ian', 'col', 'hal', 'gav', 'fred', 'bob', 'abe', 'ed', 'jon', 'dan']
jan: ['ed', 'hal', 'gav', 'abe', 'bob', 'jon', 'col', 'ian', 'fred', 'dan']
guys = (new Person(name, preferences) for name, preferences of guy_preferences)
gals = (new Person(name, preferences) for name, preferences of gal_preferences)
[guys, gals]
do ->
[guys, gals] = Population()
mate_off guys, gals
report_on_mates guys
report_potential_adulteries guys
perturb guys
report_on_mates guys
report_potential_adulteries guys
| 152018 | class Person
constructor: (@name, @preferences) ->
@mate = null
@best_mate_rank = 0
@rank = {}
for preference, i in @preferences
@rank[preference] = i
preferred_mate_name: =>
@preferences[@best_mate_rank]
reject: =>
@best_mate_rank += 1
set_mate: (mate) =>
@mate = mate
offer_mate: (free_mate, reject_mate_cb) =>
if @mate
if @covets(free_mate)
console.log "#{free_mate.name} steals #{@name} from #{@mate.name}"
reject_mate_cb @mate
free_mate.set_mate @
@set_mate free_mate
else
console.log "#{free_mate.name} cannot steal #{@name} from #{@mate.name}"
reject_mate_cb free_mate
else
console.log "#{free_mate.name} gets #{@name} first"
free_mate.set_mate @
@set_mate free_mate
happiness: =>
@rank[@mate.name]
covets: (other_mate) =>
@rank[other_mate.name] <= @rank[@mate.name]
persons_by_name = (persons) ->
hsh = {}
for person in persons
hsh[person.name] = person
hsh
mate_off = (guys, gals) ->
free_pursuers = (guy for guy in guys)
guys_by_name = persons_by_name guys
gals_by_name = persons_by_name gals
while free_pursuers.length > 0
free_pursuer = free_pursuers.shift()
gal_name = free_pursuer.preferred_mate_name()
gal = gals_by_name[gal_name]
reject_mate_cb = (guy) ->
guy.reject()
free_pursuers.push guy
gal.offer_mate free_pursuer, reject_mate_cb
report_on_mates = (guys) ->
console.log "\n----Marriage Report"
for guy, i in guys
throw Error("illegal marriage") if guy.mate.mate isnt guy
console.log guy.name, guy.mate.name, \
"(his choice #{guy.happiness()}, her choice #{guy.mate.happiness()} )"
report_potential_adulteries = (guys) ->
for guy1, i in guys
gal1 = guy1.mate
for j in [0...i]
guy2 = guys[j]
gal2 = guy2.mate
if guy1.covets(gal2) and gal2.covets(guy1)
console.log "#{guy1.name} and #{gal2.name} would stray"
if guy2.covets(gal1) and gal1.covets(guy2)
console.log "#{guy2.name} and #{gal1.name} would stray"
perturb = (guys) ->
# mess up marriages by swapping two couples...this is mainly to drive
# out that report_potential_adulteries will actually work
guy0 = guys[0]
guy1 = guys[1]
gal0 = guy0.mate
gal1 = guy1.mate
console.log "\nPerturbing with #{guy0.name}, #{gal0.name}, #{guy1.name}, #{gal1.name}"
guy0.set_mate gal1
guy1.set_mate gal0
gal1.set_mate guy0
gal0.set_mate guy1
Population = ->
guy_preferences =
abe: ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', 'fay', 'bea', '<NAME>', '<NAME>']
bob: ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', 'fay', 'bea', 'jan', 'ivy', 'gay']
col: ['<NAME>', '<NAME>', '<NAME>', '<NAME>', 'bea', 'fay', 'ivy', 'gay', '<NAME>', 'jan']
dan: ['ivy', 'fay', 'dee', 'gay', 'hope', 'eve', 'jan', 'bea', 'cath', 'abi']
ed: ['jan', 'dee', 'bea', 'cath', 'fay', 'eve', 'abi', 'ivy', 'hope', 'gay']
fred: ['bea', 'abi', 'dee', 'gay', 'eve', 'ivy', 'cath', 'jan', 'hope', 'fay']
gav: ['gay', 'eve', 'ivy', 'bea', 'cath', 'abi', 'dee', 'hope', 'jan', 'fay']
hal: ['abi', 'eve', 'hope', 'fay', 'ivy', 'cath', 'jan', 'bea', 'gay', 'dee']
ian: ['hope', 'cath', 'dee', 'gay', 'bea', 'abi', 'fay', 'ivy', 'jan', 'eve']
jon: ['abi', 'fay', 'jan', 'gay', 'eve', 'bea', 'dee', 'cath', 'ivy', 'hope']
gal_preferences =
abi: ['<NAME>', '<NAME>', '<NAME>', '<NAME>', 'ian', 'abe', 'dan', '<NAME>', '<NAME>', 'hal']
bea: ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', 'dan', 'ian', '<NAME>', '<NAME>', '<NAME>']
cath: ['<NAME>', '<NAME>', '<NAME>', '<NAME>av', 'hal', 'col', 'ian', 'abe', '<NAME>', '<NAME>']
dee: ['<NAME>', '<NAME>', '<NAME>', 'abe', 'ian', 'hal', '<NAME>av', '<NAME>', '<NAME>', '<NAME>']
eve: ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', 'gav', 'col', 'ed', 'ian', '<NAME>']
fay: ['<NAME>', '<NAME>', 'ed', 'ian', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', 'hal']
gay: ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>']
hope: ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>']
ivy: ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>']
jan: ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>']
guys = (new Person(name, preferences) for name, preferences of guy_preferences)
gals = (new Person(name, preferences) for name, preferences of gal_preferences)
[guys, gals]
do ->
[guys, gals] = Population()
mate_off guys, gals
report_on_mates guys
report_potential_adulteries guys
perturb guys
report_on_mates guys
report_potential_adulteries guys
| true | class Person
constructor: (@name, @preferences) ->
@mate = null
@best_mate_rank = 0
@rank = {}
for preference, i in @preferences
@rank[preference] = i
preferred_mate_name: =>
@preferences[@best_mate_rank]
reject: =>
@best_mate_rank += 1
set_mate: (mate) =>
@mate = mate
offer_mate: (free_mate, reject_mate_cb) =>
if @mate
if @covets(free_mate)
console.log "#{free_mate.name} steals #{@name} from #{@mate.name}"
reject_mate_cb @mate
free_mate.set_mate @
@set_mate free_mate
else
console.log "#{free_mate.name} cannot steal #{@name} from #{@mate.name}"
reject_mate_cb free_mate
else
console.log "#{free_mate.name} gets #{@name} first"
free_mate.set_mate @
@set_mate free_mate
happiness: =>
@rank[@mate.name]
covets: (other_mate) =>
@rank[other_mate.name] <= @rank[@mate.name]
persons_by_name = (persons) ->
hsh = {}
for person in persons
hsh[person.name] = person
hsh
mate_off = (guys, gals) ->
free_pursuers = (guy for guy in guys)
guys_by_name = persons_by_name guys
gals_by_name = persons_by_name gals
while free_pursuers.length > 0
free_pursuer = free_pursuers.shift()
gal_name = free_pursuer.preferred_mate_name()
gal = gals_by_name[gal_name]
reject_mate_cb = (guy) ->
guy.reject()
free_pursuers.push guy
gal.offer_mate free_pursuer, reject_mate_cb
report_on_mates = (guys) ->
console.log "\n----Marriage Report"
for guy, i in guys
throw Error("illegal marriage") if guy.mate.mate isnt guy
console.log guy.name, guy.mate.name, \
"(his choice #{guy.happiness()}, her choice #{guy.mate.happiness()} )"
report_potential_adulteries = (guys) ->
for guy1, i in guys
gal1 = guy1.mate
for j in [0...i]
guy2 = guys[j]
gal2 = guy2.mate
if guy1.covets(gal2) and gal2.covets(guy1)
console.log "#{guy1.name} and #{gal2.name} would stray"
if guy2.covets(gal1) and gal1.covets(guy2)
console.log "#{guy2.name} and #{gal1.name} would stray"
perturb = (guys) ->
# mess up marriages by swapping two couples...this is mainly to drive
# out that report_potential_adulteries will actually work
guy0 = guys[0]
guy1 = guys[1]
gal0 = guy0.mate
gal1 = guy1.mate
console.log "\nPerturbing with #{guy0.name}, #{gal0.name}, #{guy1.name}, #{gal1.name}"
guy0.set_mate gal1
guy1.set_mate gal0
gal1.set_mate guy0
gal0.set_mate guy1
Population = ->
guy_preferences =
abe: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'fay', 'bea', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
bob: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'fay', 'bea', 'jan', 'ivy', 'gay']
col: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'bea', 'fay', 'ivy', 'gay', 'PI:NAME:<NAME>END_PI', 'jan']
dan: ['ivy', 'fay', 'dee', 'gay', 'hope', 'eve', 'jan', 'bea', 'cath', 'abi']
ed: ['jan', 'dee', 'bea', 'cath', 'fay', 'eve', 'abi', 'ivy', 'hope', 'gay']
fred: ['bea', 'abi', 'dee', 'gay', 'eve', 'ivy', 'cath', 'jan', 'hope', 'fay']
gav: ['gay', 'eve', 'ivy', 'bea', 'cath', 'abi', 'dee', 'hope', 'jan', 'fay']
hal: ['abi', 'eve', 'hope', 'fay', 'ivy', 'cath', 'jan', 'bea', 'gay', 'dee']
ian: ['hope', 'cath', 'dee', 'gay', 'bea', 'abi', 'fay', 'ivy', 'jan', 'eve']
jon: ['abi', 'fay', 'jan', 'gay', 'eve', 'bea', 'dee', 'cath', 'ivy', 'hope']
gal_preferences =
abi: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'ian', 'abe', 'dan', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'hal']
bea: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'dan', 'ian', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
cath: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PIav', 'hal', 'col', 'ian', 'abe', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
dee: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'abe', 'ian', 'hal', 'PI:NAME:<NAME>END_PIav', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
eve: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'gav', 'col', 'ed', 'ian', 'PI:NAME:<NAME>END_PI']
fay: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'ed', 'ian', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'hal']
gay: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
hope: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
ivy: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
jan: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
guys = (new Person(name, preferences) for name, preferences of guy_preferences)
gals = (new Person(name, preferences) for name, preferences of gal_preferences)
[guys, gals]
do ->
[guys, gals] = Population()
mate_off guys, gals
report_on_mates guys
report_potential_adulteries guys
perturb guys
report_on_mates guys
report_potential_adulteries guys
|
[
{
"context": "io.com\n\nCopyright 2016 Chai Biotechnologies Inc. <info@chaibio.com>\n\nLicensed under the Apache License, Version 2.0 ",
"end": 194,
"score": 0.9999219179153442,
"start": 178,
"tag": "EMAIL",
"value": "info@chaibio.com"
}
] | frontend/javascripts/app/controllers/standard_curve_chart_ctrl.js.coffee | MakerButt/chaipcr | 1 | ###
Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments.
For more information visit http://www.chaibio.com
Copyright 2016 Chai Biotechnologies Inc. <info@chaibio.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
window.ChaiBioTech.ngApp.controller 'StandardCurveChartCtrl', [
'$scope'
'$stateParams'
'Experiment'
'StandardCurveChartHelper'
'expName'
'$interval'
'Device'
'$timeout'
'$rootScope'
'focus'
($scope, $stateParams, Experiment, helper, expName, $interval, Device, $timeout, $rootScope, focus ) ->
Device.isDualChannel().then (is_dual_channel) ->
$scope.is_dual_channel = is_dual_channel
$scope.chartConfig = helper.chartConfig()
$scope.chartConfig.channels = if is_dual_channel then 2 else 1
# $scope.chartConfig.axes.x.max = 1
$scope.standardcurve_data = helper.paddData($scope.is_dual_channel)
$scope.well_data = []
$scope.line_data = {target_line: []}
$scope.COLORS = helper.SAMPLE_TARGET_COLORS
$scope.WELL_COLORS = helper.COLORS
AMPLI_DATA_CACHE = null
retryInterval = null
$scope.baseline_subtraction = true
$scope.color_by = 'well'
$scope.retrying = false
$scope.retry = 0
$scope.fetching = false
$scope.channel_1 = true
$scope.channel_2 = if is_dual_channel then true else false
$scope.standardcurve_zoom = 0
$scope.showOptions = true
$scope.isError = false
$scope.samples = []
$scope.types = []
$scope.targets = []
$scope.targetsSet = []
$scope.targetsSetHided = []
$scope.omittedIndexes = []
$scope.well_targets = []
$scope.label_effic = ''
$scope.label_r2 = ''
$scope.label_slope = ''
$scope.label_yint = ''
$scope.index_target = 0
$scope.index_channel = -1
$scope.label_sample = null
$scope.label_target = "No Selection"
$scope.label_well = "No Selection"
$scope.label_channel = ""
$scope.label_plot = null
$scope.has_init = false
$scope.re_init_chart_data = false
$scope.init_sample_color = '#ccc'
$scope.line_bgcolor_target = {
'background-color':'#666666'
}
$scope.plot_bgcolor_target = {
'background-color':'#666666'
}
last_well_number = 0
last_target_channel = 0
last_target_assigned = 0
$scope.registerOutsideHover = false;
unhighlight_event = ''
if !$scope.registerOutsideHover
$scope.registerOutsideHover = angular.element(window).on 'mousemove', (e)->
if !angular.element(e.target).parents('.well-switch').length and !angular.element(e.target).parents('.well-item-row').length
if unhighlight_event
$rootScope.$broadcast unhighlight_event, {}
unhighlight_event = ''
last_well_number = 0
last_target_channel = 0
last_target_assigned = 0
$scope.$apply()
$scope.toggleOmitIndex = (well_item) ->
return if $scope.re_init_chart_data
omit_index = well_item.well_num.toString() + '_' + well_item.channel.toString()
if $scope.omittedIndexes.indexOf(omit_index) != -1
$scope.omittedIndexes.splice $scope.omittedIndexes.indexOf(omit_index), 1
else
$scope.omittedIndexes.push omit_index
well_item.omit = if well_item.omit then 0 else 1
omitTargetLink = []
omitTargetLink. push
well_num: well_item.well_num,
omit: well_item.omit
Experiment.linkTarget($stateParams.id, well_item.target_id, { wells: omitTargetLink }).then (data) ->
reInitChartData()
getWellDataIndex = (well_num, channel) ->
return well_num.toString() + '_' + channel
reInitChartData = ->
$scope.chartConfig.line_series = []
$scope.chartConfig.series = []
$scope.retrying = false
$scope.retry = 0
$scope.fetching = false
$scope.hasData = false
$scope.error = null
$scope.has_init = false
$scope.re_init_chart_data = true
$scope.well_targets = []
Experiment.getWellLayout($stateParams.id).then (resp) ->
for i in [0...resp.data.length]
$scope.samples[i] = if resp.data[i].samples then resp.data[i].samples[0] else null
if $scope.samples[i]
for j in [0...$scope.expSamples.length]
if $scope.samples[i].id == $scope.expSamples[j].id
$scope.samples[i].color = $scope.COLORS[j % $scope.COLORS.length]
break
else
$scope.samples[i].color = $scope.init_sample_color
if $scope.is_dual_channel
$scope.well_targets[2*i] = if resp.data[i].targets && resp.data[i].targets[0] then resp.data[i].targets[0] else null
$scope.well_targets[2*i+1] = if resp.data[i].targets && resp.data[i].targets[1] then resp.data[i].targets[1] else null
if $scope.well_targets[2*i]
$scope.well_targets[2*i].color = if $scope.well_targets[2*i] then $scope.lookupTargets[$scope.well_targets[2*i].id] else 'transparent'
if $scope.well_targets[2*i+1]
$scope.well_targets[2*i+1].color = if $scope.well_targets[2*i+1] then $scope.lookupTargets[$scope.well_targets[2*i+1].id] else 'transparent'
else
$scope.well_targets[i] = if resp.data[i].targets && resp.data[i].targets[0] then resp.data[i].targets[0] else null
if $scope.well_targets[i]
$scope.well_targets[i].color = if $scope.well_targets[i] then $scope.lookupTargets[$scope.well_targets[i].id] else 'transparent'
fetchFluorescenceData()
$scope.updateTargetsSet = ->
# $scope.targetsSet = []
for i in [0...$scope.targets.length]
if $scope.targets[i]?.id
target = _.filter $scope.targetsSet, (target) ->
target.id is $scope.targets[i].id
if !target.length
$scope.targetsSet.push($scope.targets[i])
for i in [$scope.targetsSet.length-1..0] by -1
if $scope.targetsSet[i]?.id
target = _.filter $scope.targets, (item) ->
item.id is $scope.targetsSet[i].id
if !target.length
$scope.targetsSet.splice(i, 1)
$scope.$watchCollection 'targetsSetHided', ->
updateSeries() if $scope.hasData
$scope.$on 'event:switch-chart-well', (e, data, oldData) ->
if !data.active
$scope.onUnselectLine()
channel_count = if $scope.is_dual_channel then 2 else 1
wellScrollTop = (data.index * channel_count + channel_count) * 36 - document.querySelector('.table-container').offsetHeight
angular.element(document.querySelector('.table-container')).animate { scrollTop: wellScrollTop }, 'fast'
Experiment.get(id: $stateParams.id).then (data) ->
maxCycle = helper.getMaxExperimentCycle(data.experiment)
# $scope.chartConfig.axes.x.max = 1
$scope.experiment = data.experiment
$scope.$on 'status:data:updated', (e, data, oldData) ->
return if !data
return if !data.experiment_controller
$scope.statusData = data
$scope.state = data.experiment_controller.machine.state
$scope.thermal_state = data.experiment_controller.machine.thermal_state
$scope.oldState = oldData?.experiment_controller?.machine?.state || 'NONE'
$scope.isCurrentExp = parseInt(data.experiment_controller.experiment?.id) is parseInt($stateParams.id)
if $scope.isCurrentExp is true
$scope.enterState = $scope.isCurrentExp
retry = ->
$scope.retrying = true
$scope.retry = 5
retryInterval = $interval ->
$scope.retry = $scope.retry - 1
if $scope.retry is 0
$interval.cancel(retryInterval)
$scope.retrying = false
$scope.error = null
fetchFluorescenceData()
, 1000
fetchFluorescenceData = ->
gofetch = true
gofetch = false if $scope.fetching
gofetch = false if $scope.$parent.chart isnt 'standard-curve'
gofetch = false if $scope.retrying
if gofetch
$scope.has_init = true
$scope.fetching = true
Experiment
.getStandardCurveData($stateParams.id)
.then (resp) ->
$scope.fetching = false
$scope.error = null
if (resp.status is 200 and !resp.data.partial)
$scope.hasData = true
$scope.standardcurve_data = helper.paddData($scope.is_dual_channel)
if (resp.status is 200 and resp.data?.partial and $scope.enterState)
$scope.hasData = false
if resp.status is 200 and !resp.data.partial
$rootScope.$broadcast 'complete'
if $scope.hasData and (resp.data.steps?[0].amplification_data and resp.data.steps?[0].amplification_data?.length > 1)
# $scope.chartConfig.axes.x.min = 0
data = resp.data.steps[0]
$scope.well_data = helper.normalizeSummaryData(data.summary_data, data.targets, $scope.well_targets)
$scope.targets = helper.normalizeWellTargetData($scope.well_data, $scope.targets, $scope.is_dual_channel)
data.summary_data = helper.initialSummaryData(data.summary_data, data.targets)
$scope.omittedIndexes = []
for well, i in $scope.well_data by 1
if well.omit
$scope.omittedIndexes.push(getWellDataIndex(well.well_num, well.channel))
if !$scope.re_init_chart_data
for i in [0..$scope.targets.length - 1] by 1
$scope.targetsSetHided[$scope.targets[i]?.id] = true if $scope.targetsSetHided[$scope.targets[i]?.id] is undefined
AMPLI_DATA_CACHE = angular.copy data
$scope.standardcurve_data = helper.neutralizeChartData(data.summary_data, data.targets, $scope.targets, $scope.is_dual_channel)
$scope.line_data = helper.neutralizeLineData(data.targets)
minQt = if $scope.well_data[0] then $scope.well_data[0].quantity else 0
maxQt = 0
minCq = if $scope.well_data[0] then $scope.well_data[0].cq else 0
maxCq = 0
for well_item in $scope.well_data by 1
if well_item.quantity <= minQt and well_item.quantity then minQt = well_item.quantity
if well_item.quantity >= maxQt and well_item.quantity then maxQt = well_item.quantity
if well_item.cq <= minCq and well_item.cq then minCq = well_item.cq
if well_item.cq >= maxCq and well_item.cq then maxCq = well_item.cq
maxQt = Math.log10(maxQt)
minQt = Math.log10(minQt)
gapX = maxQt - minQt
gapY = maxCq - minCq
$scope.chartConfig.axes.x.min = if Math.floor(minQt) is minQt then minQt - 1 else Math.floor(minQt)
$scope.chartConfig.axes.x.max = if Math.ceil(maxQt) is maxQt then maxQt + 1 else Math.ceil(maxQt)
$scope.chartConfig.axes.y.min = minCq
$scope.chartConfig.axes.y.max = maxCq
$scope.updateTargetsSet()
updateButtonCts()
updateSeries()
if !(($scope.experiment?.completion_status && $scope.experiment?.completed_at) or $scope.enterState)
$scope.retrying = true
if ((resp.data?.partial is true) or (resp.status is 202)) and !$scope.retrying
retry()
else
$scope.re_init_chart_data = false
.catch (resp) ->
if resp.status is 500
$scope.error = resp.statusText || 'Unknown error'
$scope.fetching = false
return if $scope.retrying
retry()
else
retry()
updateButtonCts = ->
for well_i in [0..15] by 1
channel_1_well = _.find $scope.well_data, (item) ->
item.well_num is well_i+1 and item.channel is 1
channel_2_well = _.find $scope.well_data, (item) ->
item.well_num is well_i+1 and item.channel is 2
$scope.wellButtons["well_#{well_i}"].well_type = []
$scope.wellButtons["well_#{well_i}"].well_type.push(if channel_1_well then channel_1_well.well_type else '')
$scope.wellButtons["well_#{well_i}"].well_type.push(if channel_2_well then channel_2_well.well_type else '')
cts = _.filter AMPLI_DATA_CACHE.summary_data, (ct) ->
ct[1] is well_i+1
$scope.wellButtons["well_#{well_i}"].ct = []
for ct_i in [0..cts.length - 1] by 1
$scope.wellButtons["well_#{well_i}"].ct.push(cts[ct_i][3])
return
updateSeries = (buttons) ->
buttons = buttons || $scope.wellButtons || {}
$scope.chartConfig.series = []
nonGreySeries = []
channel_count = if $scope.is_dual_channel then 2 else 1
channel_end = if $scope.channel_1 && $scope.channel_2 then 2 else if $scope.channel_1 && !$scope.channel_2 then 1 else if !$scope.channel_1 && $scope.channel_2 then 2
channel_start = if $scope.channel_1 && $scope.channel_2 then 1 else if $scope.channel_1 && !$scope.channel_2 then 1 else if !$scope.channel_1 && $scope.channel_2 then 2
$scope.chartConfig.line_series = []
for i in [0..$scope.line_data['target_line'].length - 1] by 1
well_color = '#c5c5c5'
if $scope.targetsSetHided[$scope.line_data['target_line'][i].id]
if $scope.color_by is 'target'
target = _.filter $scope.targets, (target) ->
target && target.id is $scope.line_data['target_line'][i].id
if target.length
well_color = target[0].color
else
well_color = 'transparent'
$scope.line_data['target_line'][i].color = well_color
for ch_i in [channel_start..channel_end] by 1
for i in [0..15] by 1
if $scope.omittedIndexes.indexOf(getWellDataIndex(i + 1, ch_i)) == -1
# alert(i)
if buttons["well_#{i}"]?.selected and $scope.targets[i * channel_count + (ch_i - 1)] and $scope.targets[i * channel_count + (ch_i - 1)].id and $scope.targetsSetHided[$scope.targets[i * channel_count + (ch_i - 1)].id]
if $scope.color_by is 'well'
well_color = buttons["well_#{i}"].color
else if $scope.color_by is 'target'
well_color = if $scope.targets[(ch_i - 1)+i*channel_count] then $scope.targets[(ch_i - 1)+i*channel_count].color else 'transparent'
else if $scope.color_by is 'sample'
well_color = if $scope.samples[i] then $scope.samples[i].color else $scope.init_sample_color
if ($scope.is_dual_channel and !$scope.targets[i*channel_count].id and !$scope.targets[i*channel_count+1].id) or (!$scope.is_dual_channel and !$scope.targets[i].id)
well_color = 'transparent'
else if ch_i is 1
well_color = '#00AEEF'
else
well_color = '#8FC742'
continue if $scope.standardcurve_data["well_#{i}_#{ch_i}"][0] is undefined or Math.abs($scope.standardcurve_data["well_#{i}_#{ch_i}"][0]['log_quantity']) is Number.POSITIVE_INFINITY
if $scope.color_by is 'sample'
if well_color is $scope.init_sample_color
$scope.chartConfig.series.push
dataset: "well_#{i}_#{ch_i}"
x: 'log_quantity'
y: "cq"
color: well_color
cq: $scope.wellButtons["well_#{i}"]?.ct
well: i
channel: ch_i
well_type: $scope.targets[i * channel_count + (ch_i - 1)].well_type
target_id: $scope.targets[i * channel_count + (ch_i - 1)].id
else
nonGreySeries.push
dataset: "well_#{i}_#{ch_i}"
x: 'log_quantity'
y: "cq"
color: well_color
cq: $scope.wellButtons["well_#{i}"]?.ct
well: i
channel: ch_i
well_type: $scope.targets[i * channel_count + (ch_i - 1)].well_type
target_id: $scope.targets[i * channel_count + (ch_i - 1)].id
else
$scope.chartConfig.series.push
dataset: "well_#{i}_#{ch_i}"
x: 'log_quantity'
y: "cq"
color: well_color
cq: $scope.wellButtons["well_#{i}"]?.ct
well: i
channel: ch_i
well_type: $scope.targets[i * channel_count + (ch_i - 1)].well_type
target_id: $scope.targets[i * channel_count + (ch_i - 1)].id
else
$scope.onUnselectPlot()
if $scope.color_by is 'sample'
for i in [0..nonGreySeries.length - 1] by 1
$scope.chartConfig.series.push(nonGreySeries[i])
getWellDataIndex = (well_num, channel) ->
for i in [0..$scope.well_data.length - 1] by 1
if $scope.well_data[i].well_num is well_num and $scope.well_data[i].channel is channel
return i
return -1
$scope.onUpdateProperties = (line_config) ->
$scope.label_effic = line_config.efficiency
$scope.label_r2 = line_config.r2
$scope.label_slope = line_config.slope
$scope.label_yint = line_config.offset
target = _.filter $scope.targets, (target) ->
target && target.id is line_config.id
if target.length
$scope.label_well = target[0].name
$scope.label_channel = target[0].channel
$scope.line_bgcolor_target = { 'background-color':'black' }
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = false
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = false
$scope.onHighlightPlots = (configs, well_index) ->
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = false
$scope.well_data[well_i].highlight = false
for well_i in [0..$scope.well_data.length - 1]
omit_index = $scope.well_data[well_i].well_num.toString() + '_' + $scope.well_data[well_i].channel.toString()
for config, i in configs by 1
if ($scope.well_data[well_i].well_num - 1 == config.config.well and $scope.well_data[well_i].channel == config.config.channel) and ($scope.omittedIndexes.indexOf(omit_index) == -1)
$scope.well_data[well_i].highlight = true
dual_value = if $scope.is_dual_channel then 2 else 1
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = (i == well_index)
if configs[0]
config = configs[0].config
wellScrollTop = (config.well * dual_value + config.channel - 1 + dual_value) * 36 - document.querySelector('.detail-mode-table tbody').offsetHeight
angular.element('.detail-mode-table tbody').animate { scrollTop: wellScrollTop }, 'fast'
return
$scope.onUnHighlightPlots = () ->
$scope.onUnselectPlot()
return
$scope.onHoverPlot = (plot_config, well_index) ->
$scope.onUnselectPlot()
$scope.label_plot = plot_config
if $scope.label_plot
if $scope.label_plot.well < 8
$scope.label_plot.well_label = 'A' + ($scope.label_plot.well + 1)
else
$scope.label_plot.well_label = 'B' + ($scope.label_plot.well - 7)
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = false
$scope.well_data[well_i].highlight = false
omit_index = $scope.well_data[well_i].well_num.toString() + '_' + $scope.well_data[well_i].channel.toString()
if ($scope.well_data[well_i].well_num - 1 == plot_config.well and $scope.well_data[well_i].channel == plot_config.channel) and ($scope.omittedIndexes.indexOf(omit_index) == -1)
$scope.well_data[well_i].highlight = true
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = (i == plot_config.well)
else
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = false
$scope.well_data[well_i].highlight = false
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = false
$scope.onHoverRow = (event, well_item, index) ->
is_active_plot = false
for well_i in [0..$scope.well_data.length - 1]
if $scope.well_data[well_i].active
is_active_plot = true
break
if is_active_plot or (last_well_number == well_item.well_num and last_target_channel == well_item.channel)
return
last_well_number = well_item.well_num
last_target_channel = well_item.channel
omit_index = well_item.well_num.toString() + '_' + well_item.channel.toString()
if !$scope.has_init or (($scope.wellButtons['well_' + (well_item.well_num - 1)].selected) and ($scope.omittedIndexes.indexOf(omit_index) == -1) and ($scope.targetsSetHided[$scope.targets[index].id]))
if !well_item.active
$rootScope.$broadcast 'event:std-highlight-row', { well_datas: [{well: well_item.well_num, channel: well_item.channel}], well_index: well_item.well_num - 1 }
unhighlight_event = 'event:std-unhighlight-row'
$scope.onZoom = (transform, w, h, scale_extent) ->
$scope.std_scroll = {
value: Math.abs(transform.x/(w*transform.k - w))
width: w/(w*transform.k)
}
$scope.standardcurve_zoom = (transform.k - 1)/ (scale_extent)
$scope.zoomIn = ->
$scope.standardcurve_zoom = Math.min($scope.standardcurve_zoom * 2 || 0.001 * 2, 1)
$scope.zoomOut = ->
$scope.standardcurve_zoom = Math.max($scope.standardcurve_zoom * 0.5, 0.001)
$scope.onSelectWell = (well_item, index) ->
config = {}
config.config = {}
config.config.well = well_item.well_num - 1
config.config.channel = well_item.channel
dual_value = if $scope.is_dual_channel then 2 else 1
omit_index = well_item.well_num.toString() + '_' + well_item.channel.toString()
if $scope.wellButtons['well_' + (well_item.well_num - 1)].selected and $scope.omittedIndexes.indexOf(omit_index) == -1 and $scope.targetsSetHided[$scope.targets[index].id]
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = ($scope.well_data[well_i].well_num - 1 == config.config.well and $scope.well_data[well_i].channel == config.config.channel)
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = (i == config.config.well)
if(i == config.config.well)
$scope.index_target = i % 8
if (i < 8)
$scope.index_channel = 1
else
$scope.index_channel = 2
$scope.label_channel = config.config.channel
if i < $scope.targets.length
if $scope.targets[i]!=null
$scope.label_target = $scope.targets[config.config.well * dual_value + config.config.channel - 1]
else
$scope.label_target = ""
else
$scope.label_target = ""
if i < $scope.targets.length
if $scope.samples[i]!=null
$scope.label_sample = $scope.samples[i].name if $scope.samples[i]
else
$scope.label_sample = null
else
$scope.label_sample = null
# $scope.label_slope =
# $scope.label_yint =
wells = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8']
if $scope.label_target.name
$scope.line_bgcolor_target = { 'background-color':'black' }
else
$scope.line_bgcolor_target = { 'background-color':'#666' }
$scope.onSelectRow = (well_item, index) ->
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].highlight = false
omit_index = well_item.well_num.toString() + '_' + well_item.channel.toString()
if !$scope.has_init or (($scope.wellButtons['well_' + (well_item.well_num - 1)].selected) and ($scope.omittedIndexes.indexOf(omit_index) == -1) and ($scope.targetsSetHided[$scope.targets[index].id]))
if !well_item.active
$rootScope.$broadcast 'event:standard-select-row', {well: well_item.well_num, channel: well_item.channel, well_type: well_item.well_type}
else
$rootScope.$broadcast 'event:standard-unselect-row', {well: well_item.well_num, channel: well_item.channel, well_type: well_item.well_type }
$scope.onUnselectPlot()
$scope.onSelectPlot = (config) ->
$scope.plot_bgcolor_target = { 'background-color':'black' }
$scope.line_bgcolor_target = { 'background-color':'#666666' }
$scope.label_plot = config
if $scope.label_plot
if $scope.label_plot.well < 8
$scope.label_plot.well_label = 'A' + ($scope.label_plot.well + 1)
else
$scope.label_plot.well_label = 'B' + ($scope.label_plot.well - 7)
# $scope.line_bgcolor_target = { 'background-color':config.config.color }
dual_value = if $scope.is_dual_channel then 2 else 1
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = ($scope.well_data[well_i].well_num - 1 == config.well and $scope.well_data[well_i].channel == config.channel)
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = (i == config.well)
wellScrollTop = (config.well * dual_value + config.channel - 1 + dual_value) * 36 - document.querySelector('.table-container').offsetHeight
angular.element(document.querySelector('.table-container')).animate { scrollTop: wellScrollTop }, 'fast'
$scope.onUnselectLine = ->
$scope.label_well = "No Selection"
$scope.label_channel = ""
$scope.label_effic = ''
$scope.label_r2 = ''
$scope.label_slope = ''
$scope.label_yint = ''
$scope.line_bgcolor_target = {'background-color':'#666666'}
$scope.onUnselectPlot = ->
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i]?.active = false
$scope.well_data[well_i]?.highlight = false
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"]?.active = false
$scope.plot_bgcolor_target = {'background-color':'#666666'}
$scope.label_plot = null
$scope.$watchCollection 'wellButtons', ->
if $scope.hasData
$scope.onUnselectLine()
$scope.onUnselectPlot()
updateSeries()
$scope.$watch ->
$scope.$parent.chart
, (chart) ->
if chart is 'standard-curve'
$scope.expTargets = []
$scope.lookupTargets = []
Experiment.getTargets($stateParams.id).then (resp_target) ->
for i in [0...resp_target.data.length]
$scope.expTargets[i] = resp_target.data[i].target
$scope.lookupTargets[resp_target.data[i].target.id] = $scope.COLORS[i % $scope.COLORS.length]
$scope.expSamples = []
Experiment.getSamples($stateParams.id).then (response) ->
for i in [0...response.data.length]
$scope.expSamples[i] = response.data[i].sample
$scope.well_targets = []
Experiment.getWellLayout($stateParams.id).then (resp) ->
for i in [0...resp.data.length]
$scope.samples[i] = if resp.data[i].samples then resp.data[i].samples[0] else null
if $scope.samples[i]
for j in [0...$scope.expSamples.length]
if $scope.samples[i].id == $scope.expSamples[j].id
$scope.samples[i].color = $scope.COLORS[j % $scope.COLORS.length]
break
else
$scope.samples[i].color = $scope.init_sample_color
if $scope.is_dual_channel
$scope.well_targets[2*i] = if resp.data[i].targets && resp.data[i].targets[0] then resp.data[i].targets[0] else null
$scope.well_targets[2*i+1] = if resp.data[i].targets && resp.data[i].targets[1] then resp.data[i].targets[1] else null
if $scope.well_targets[2*i]
$scope.well_targets[2*i].color = if $scope.well_targets[2*i] then $scope.lookupTargets[$scope.well_targets[2*i].id] else 'transparent'
if $scope.well_targets[2*i+1]
$scope.well_targets[2*i+1].color = if $scope.well_targets[2*i+1] then $scope.lookupTargets[$scope.well_targets[2*i+1].id] else 'transparent'
else
$scope.well_targets[i] = if resp.data[i].targets && resp.data[i].targets[0] then resp.data[i].targets[0] else null
if $scope.well_targets[i]
$scope.well_targets[i].color = if $scope.well_targets[i] then $scope.lookupTargets[$scope.well_targets[i].id] else 'transparent'
$scope.well_data = helper.blankWellData($scope.is_dual_channel, $scope.well_targets)
$scope.targets = helper.blankWellTargetData($scope.well_data)
for i in [0..$scope.targets.length - 1] by 1
$scope.targetsSetHided[$scope.targets[i]?.id] = true if $scope.targetsSetHided[$scope.targets[i]?.id] is undefined
$scope.omittedIndexes = []
for well, i in $scope.well_data by 1
if well.omit
$scope.omittedIndexes.push(getWellDataIndex(well.well_num, well.channel))
$scope.updateTargetsSet()
updateSeries()
fetchFluorescenceData()
$timeout ->
$rootScope.$broadcast 'event:start-resize-aspect-ratio'
$scope.showStandardChart = true
, 1000
else
$scope.showAmpliChart = false
$scope.showStandardChart = false
$scope.$on '$destroy', ->
$interval.cancel(retryInterval) if retryInterval
# store well buttons
wellSelections = {}
for well_i in [0..15] by 1
wellSelections["well_#{well_i}"] = $scope.wellButtons["well_#{well_i}"].selected
$.jStorage.set('selectedWells', wellSelections)
$.jStorage.set('selectedExpId', $stateParams.id)
$scope.showPlotTypeList = ->
document.getElementById("plotTypeList").classList.toggle("show")
$scope.showColorByList = ->
document.getElementById("colorByList_standard").classList.toggle("show")
$scope.targetClick = (index) ->
$scope.targetsSetHided[index] = !$scope.targetsSetHided[index]
updateSeries()
# $scope.targetGridTop = ->
# document.getElementById("curve-plot").clientHeight + 30
$scope.targetGridTop = ->
Math.max(document.getElementById("curve-plot").clientHeight + 30, 412 + 30)
]
| 121777 | ###
Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments.
For more information visit http://www.chaibio.com
Copyright 2016 Chai Biotechnologies Inc. <<EMAIL>>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
window.ChaiBioTech.ngApp.controller 'StandardCurveChartCtrl', [
'$scope'
'$stateParams'
'Experiment'
'StandardCurveChartHelper'
'expName'
'$interval'
'Device'
'$timeout'
'$rootScope'
'focus'
($scope, $stateParams, Experiment, helper, expName, $interval, Device, $timeout, $rootScope, focus ) ->
Device.isDualChannel().then (is_dual_channel) ->
$scope.is_dual_channel = is_dual_channel
$scope.chartConfig = helper.chartConfig()
$scope.chartConfig.channels = if is_dual_channel then 2 else 1
# $scope.chartConfig.axes.x.max = 1
$scope.standardcurve_data = helper.paddData($scope.is_dual_channel)
$scope.well_data = []
$scope.line_data = {target_line: []}
$scope.COLORS = helper.SAMPLE_TARGET_COLORS
$scope.WELL_COLORS = helper.COLORS
AMPLI_DATA_CACHE = null
retryInterval = null
$scope.baseline_subtraction = true
$scope.color_by = 'well'
$scope.retrying = false
$scope.retry = 0
$scope.fetching = false
$scope.channel_1 = true
$scope.channel_2 = if is_dual_channel then true else false
$scope.standardcurve_zoom = 0
$scope.showOptions = true
$scope.isError = false
$scope.samples = []
$scope.types = []
$scope.targets = []
$scope.targetsSet = []
$scope.targetsSetHided = []
$scope.omittedIndexes = []
$scope.well_targets = []
$scope.label_effic = ''
$scope.label_r2 = ''
$scope.label_slope = ''
$scope.label_yint = ''
$scope.index_target = 0
$scope.index_channel = -1
$scope.label_sample = null
$scope.label_target = "No Selection"
$scope.label_well = "No Selection"
$scope.label_channel = ""
$scope.label_plot = null
$scope.has_init = false
$scope.re_init_chart_data = false
$scope.init_sample_color = '#ccc'
$scope.line_bgcolor_target = {
'background-color':'#666666'
}
$scope.plot_bgcolor_target = {
'background-color':'#666666'
}
last_well_number = 0
last_target_channel = 0
last_target_assigned = 0
$scope.registerOutsideHover = false;
unhighlight_event = ''
if !$scope.registerOutsideHover
$scope.registerOutsideHover = angular.element(window).on 'mousemove', (e)->
if !angular.element(e.target).parents('.well-switch').length and !angular.element(e.target).parents('.well-item-row').length
if unhighlight_event
$rootScope.$broadcast unhighlight_event, {}
unhighlight_event = ''
last_well_number = 0
last_target_channel = 0
last_target_assigned = 0
$scope.$apply()
$scope.toggleOmitIndex = (well_item) ->
return if $scope.re_init_chart_data
omit_index = well_item.well_num.toString() + '_' + well_item.channel.toString()
if $scope.omittedIndexes.indexOf(omit_index) != -1
$scope.omittedIndexes.splice $scope.omittedIndexes.indexOf(omit_index), 1
else
$scope.omittedIndexes.push omit_index
well_item.omit = if well_item.omit then 0 else 1
omitTargetLink = []
omitTargetLink. push
well_num: well_item.well_num,
omit: well_item.omit
Experiment.linkTarget($stateParams.id, well_item.target_id, { wells: omitTargetLink }).then (data) ->
reInitChartData()
getWellDataIndex = (well_num, channel) ->
return well_num.toString() + '_' + channel
reInitChartData = ->
$scope.chartConfig.line_series = []
$scope.chartConfig.series = []
$scope.retrying = false
$scope.retry = 0
$scope.fetching = false
$scope.hasData = false
$scope.error = null
$scope.has_init = false
$scope.re_init_chart_data = true
$scope.well_targets = []
Experiment.getWellLayout($stateParams.id).then (resp) ->
for i in [0...resp.data.length]
$scope.samples[i] = if resp.data[i].samples then resp.data[i].samples[0] else null
if $scope.samples[i]
for j in [0...$scope.expSamples.length]
if $scope.samples[i].id == $scope.expSamples[j].id
$scope.samples[i].color = $scope.COLORS[j % $scope.COLORS.length]
break
else
$scope.samples[i].color = $scope.init_sample_color
if $scope.is_dual_channel
$scope.well_targets[2*i] = if resp.data[i].targets && resp.data[i].targets[0] then resp.data[i].targets[0] else null
$scope.well_targets[2*i+1] = if resp.data[i].targets && resp.data[i].targets[1] then resp.data[i].targets[1] else null
if $scope.well_targets[2*i]
$scope.well_targets[2*i].color = if $scope.well_targets[2*i] then $scope.lookupTargets[$scope.well_targets[2*i].id] else 'transparent'
if $scope.well_targets[2*i+1]
$scope.well_targets[2*i+1].color = if $scope.well_targets[2*i+1] then $scope.lookupTargets[$scope.well_targets[2*i+1].id] else 'transparent'
else
$scope.well_targets[i] = if resp.data[i].targets && resp.data[i].targets[0] then resp.data[i].targets[0] else null
if $scope.well_targets[i]
$scope.well_targets[i].color = if $scope.well_targets[i] then $scope.lookupTargets[$scope.well_targets[i].id] else 'transparent'
fetchFluorescenceData()
$scope.updateTargetsSet = ->
# $scope.targetsSet = []
for i in [0...$scope.targets.length]
if $scope.targets[i]?.id
target = _.filter $scope.targetsSet, (target) ->
target.id is $scope.targets[i].id
if !target.length
$scope.targetsSet.push($scope.targets[i])
for i in [$scope.targetsSet.length-1..0] by -1
if $scope.targetsSet[i]?.id
target = _.filter $scope.targets, (item) ->
item.id is $scope.targetsSet[i].id
if !target.length
$scope.targetsSet.splice(i, 1)
$scope.$watchCollection 'targetsSetHided', ->
updateSeries() if $scope.hasData
$scope.$on 'event:switch-chart-well', (e, data, oldData) ->
if !data.active
$scope.onUnselectLine()
channel_count = if $scope.is_dual_channel then 2 else 1
wellScrollTop = (data.index * channel_count + channel_count) * 36 - document.querySelector('.table-container').offsetHeight
angular.element(document.querySelector('.table-container')).animate { scrollTop: wellScrollTop }, 'fast'
Experiment.get(id: $stateParams.id).then (data) ->
maxCycle = helper.getMaxExperimentCycle(data.experiment)
# $scope.chartConfig.axes.x.max = 1
$scope.experiment = data.experiment
$scope.$on 'status:data:updated', (e, data, oldData) ->
return if !data
return if !data.experiment_controller
$scope.statusData = data
$scope.state = data.experiment_controller.machine.state
$scope.thermal_state = data.experiment_controller.machine.thermal_state
$scope.oldState = oldData?.experiment_controller?.machine?.state || 'NONE'
$scope.isCurrentExp = parseInt(data.experiment_controller.experiment?.id) is parseInt($stateParams.id)
if $scope.isCurrentExp is true
$scope.enterState = $scope.isCurrentExp
retry = ->
$scope.retrying = true
$scope.retry = 5
retryInterval = $interval ->
$scope.retry = $scope.retry - 1
if $scope.retry is 0
$interval.cancel(retryInterval)
$scope.retrying = false
$scope.error = null
fetchFluorescenceData()
, 1000
fetchFluorescenceData = ->
gofetch = true
gofetch = false if $scope.fetching
gofetch = false if $scope.$parent.chart isnt 'standard-curve'
gofetch = false if $scope.retrying
if gofetch
$scope.has_init = true
$scope.fetching = true
Experiment
.getStandardCurveData($stateParams.id)
.then (resp) ->
$scope.fetching = false
$scope.error = null
if (resp.status is 200 and !resp.data.partial)
$scope.hasData = true
$scope.standardcurve_data = helper.paddData($scope.is_dual_channel)
if (resp.status is 200 and resp.data?.partial and $scope.enterState)
$scope.hasData = false
if resp.status is 200 and !resp.data.partial
$rootScope.$broadcast 'complete'
if $scope.hasData and (resp.data.steps?[0].amplification_data and resp.data.steps?[0].amplification_data?.length > 1)
# $scope.chartConfig.axes.x.min = 0
data = resp.data.steps[0]
$scope.well_data = helper.normalizeSummaryData(data.summary_data, data.targets, $scope.well_targets)
$scope.targets = helper.normalizeWellTargetData($scope.well_data, $scope.targets, $scope.is_dual_channel)
data.summary_data = helper.initialSummaryData(data.summary_data, data.targets)
$scope.omittedIndexes = []
for well, i in $scope.well_data by 1
if well.omit
$scope.omittedIndexes.push(getWellDataIndex(well.well_num, well.channel))
if !$scope.re_init_chart_data
for i in [0..$scope.targets.length - 1] by 1
$scope.targetsSetHided[$scope.targets[i]?.id] = true if $scope.targetsSetHided[$scope.targets[i]?.id] is undefined
AMPLI_DATA_CACHE = angular.copy data
$scope.standardcurve_data = helper.neutralizeChartData(data.summary_data, data.targets, $scope.targets, $scope.is_dual_channel)
$scope.line_data = helper.neutralizeLineData(data.targets)
minQt = if $scope.well_data[0] then $scope.well_data[0].quantity else 0
maxQt = 0
minCq = if $scope.well_data[0] then $scope.well_data[0].cq else 0
maxCq = 0
for well_item in $scope.well_data by 1
if well_item.quantity <= minQt and well_item.quantity then minQt = well_item.quantity
if well_item.quantity >= maxQt and well_item.quantity then maxQt = well_item.quantity
if well_item.cq <= minCq and well_item.cq then minCq = well_item.cq
if well_item.cq >= maxCq and well_item.cq then maxCq = well_item.cq
maxQt = Math.log10(maxQt)
minQt = Math.log10(minQt)
gapX = maxQt - minQt
gapY = maxCq - minCq
$scope.chartConfig.axes.x.min = if Math.floor(minQt) is minQt then minQt - 1 else Math.floor(minQt)
$scope.chartConfig.axes.x.max = if Math.ceil(maxQt) is maxQt then maxQt + 1 else Math.ceil(maxQt)
$scope.chartConfig.axes.y.min = minCq
$scope.chartConfig.axes.y.max = maxCq
$scope.updateTargetsSet()
updateButtonCts()
updateSeries()
if !(($scope.experiment?.completion_status && $scope.experiment?.completed_at) or $scope.enterState)
$scope.retrying = true
if ((resp.data?.partial is true) or (resp.status is 202)) and !$scope.retrying
retry()
else
$scope.re_init_chart_data = false
.catch (resp) ->
if resp.status is 500
$scope.error = resp.statusText || 'Unknown error'
$scope.fetching = false
return if $scope.retrying
retry()
else
retry()
updateButtonCts = ->
for well_i in [0..15] by 1
channel_1_well = _.find $scope.well_data, (item) ->
item.well_num is well_i+1 and item.channel is 1
channel_2_well = _.find $scope.well_data, (item) ->
item.well_num is well_i+1 and item.channel is 2
$scope.wellButtons["well_#{well_i}"].well_type = []
$scope.wellButtons["well_#{well_i}"].well_type.push(if channel_1_well then channel_1_well.well_type else '')
$scope.wellButtons["well_#{well_i}"].well_type.push(if channel_2_well then channel_2_well.well_type else '')
cts = _.filter AMPLI_DATA_CACHE.summary_data, (ct) ->
ct[1] is well_i+1
$scope.wellButtons["well_#{well_i}"].ct = []
for ct_i in [0..cts.length - 1] by 1
$scope.wellButtons["well_#{well_i}"].ct.push(cts[ct_i][3])
return
updateSeries = (buttons) ->
buttons = buttons || $scope.wellButtons || {}
$scope.chartConfig.series = []
nonGreySeries = []
channel_count = if $scope.is_dual_channel then 2 else 1
channel_end = if $scope.channel_1 && $scope.channel_2 then 2 else if $scope.channel_1 && !$scope.channel_2 then 1 else if !$scope.channel_1 && $scope.channel_2 then 2
channel_start = if $scope.channel_1 && $scope.channel_2 then 1 else if $scope.channel_1 && !$scope.channel_2 then 1 else if !$scope.channel_1 && $scope.channel_2 then 2
$scope.chartConfig.line_series = []
for i in [0..$scope.line_data['target_line'].length - 1] by 1
well_color = '#c5c5c5'
if $scope.targetsSetHided[$scope.line_data['target_line'][i].id]
if $scope.color_by is 'target'
target = _.filter $scope.targets, (target) ->
target && target.id is $scope.line_data['target_line'][i].id
if target.length
well_color = target[0].color
else
well_color = 'transparent'
$scope.line_data['target_line'][i].color = well_color
for ch_i in [channel_start..channel_end] by 1
for i in [0..15] by 1
if $scope.omittedIndexes.indexOf(getWellDataIndex(i + 1, ch_i)) == -1
# alert(i)
if buttons["well_#{i}"]?.selected and $scope.targets[i * channel_count + (ch_i - 1)] and $scope.targets[i * channel_count + (ch_i - 1)].id and $scope.targetsSetHided[$scope.targets[i * channel_count + (ch_i - 1)].id]
if $scope.color_by is 'well'
well_color = buttons["well_#{i}"].color
else if $scope.color_by is 'target'
well_color = if $scope.targets[(ch_i - 1)+i*channel_count] then $scope.targets[(ch_i - 1)+i*channel_count].color else 'transparent'
else if $scope.color_by is 'sample'
well_color = if $scope.samples[i] then $scope.samples[i].color else $scope.init_sample_color
if ($scope.is_dual_channel and !$scope.targets[i*channel_count].id and !$scope.targets[i*channel_count+1].id) or (!$scope.is_dual_channel and !$scope.targets[i].id)
well_color = 'transparent'
else if ch_i is 1
well_color = '#00AEEF'
else
well_color = '#8FC742'
continue if $scope.standardcurve_data["well_#{i}_#{ch_i}"][0] is undefined or Math.abs($scope.standardcurve_data["well_#{i}_#{ch_i}"][0]['log_quantity']) is Number.POSITIVE_INFINITY
if $scope.color_by is 'sample'
if well_color is $scope.init_sample_color
$scope.chartConfig.series.push
dataset: "well_#{i}_#{ch_i}"
x: 'log_quantity'
y: "cq"
color: well_color
cq: $scope.wellButtons["well_#{i}"]?.ct
well: i
channel: ch_i
well_type: $scope.targets[i * channel_count + (ch_i - 1)].well_type
target_id: $scope.targets[i * channel_count + (ch_i - 1)].id
else
nonGreySeries.push
dataset: "well_#{i}_#{ch_i}"
x: 'log_quantity'
y: "cq"
color: well_color
cq: $scope.wellButtons["well_#{i}"]?.ct
well: i
channel: ch_i
well_type: $scope.targets[i * channel_count + (ch_i - 1)].well_type
target_id: $scope.targets[i * channel_count + (ch_i - 1)].id
else
$scope.chartConfig.series.push
dataset: "well_#{i}_#{ch_i}"
x: 'log_quantity'
y: "cq"
color: well_color
cq: $scope.wellButtons["well_#{i}"]?.ct
well: i
channel: ch_i
well_type: $scope.targets[i * channel_count + (ch_i - 1)].well_type
target_id: $scope.targets[i * channel_count + (ch_i - 1)].id
else
$scope.onUnselectPlot()
if $scope.color_by is 'sample'
for i in [0..nonGreySeries.length - 1] by 1
$scope.chartConfig.series.push(nonGreySeries[i])
getWellDataIndex = (well_num, channel) ->
for i in [0..$scope.well_data.length - 1] by 1
if $scope.well_data[i].well_num is well_num and $scope.well_data[i].channel is channel
return i
return -1
$scope.onUpdateProperties = (line_config) ->
$scope.label_effic = line_config.efficiency
$scope.label_r2 = line_config.r2
$scope.label_slope = line_config.slope
$scope.label_yint = line_config.offset
target = _.filter $scope.targets, (target) ->
target && target.id is line_config.id
if target.length
$scope.label_well = target[0].name
$scope.label_channel = target[0].channel
$scope.line_bgcolor_target = { 'background-color':'black' }
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = false
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = false
$scope.onHighlightPlots = (configs, well_index) ->
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = false
$scope.well_data[well_i].highlight = false
for well_i in [0..$scope.well_data.length - 1]
omit_index = $scope.well_data[well_i].well_num.toString() + '_' + $scope.well_data[well_i].channel.toString()
for config, i in configs by 1
if ($scope.well_data[well_i].well_num - 1 == config.config.well and $scope.well_data[well_i].channel == config.config.channel) and ($scope.omittedIndexes.indexOf(omit_index) == -1)
$scope.well_data[well_i].highlight = true
dual_value = if $scope.is_dual_channel then 2 else 1
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = (i == well_index)
if configs[0]
config = configs[0].config
wellScrollTop = (config.well * dual_value + config.channel - 1 + dual_value) * 36 - document.querySelector('.detail-mode-table tbody').offsetHeight
angular.element('.detail-mode-table tbody').animate { scrollTop: wellScrollTop }, 'fast'
return
$scope.onUnHighlightPlots = () ->
$scope.onUnselectPlot()
return
$scope.onHoverPlot = (plot_config, well_index) ->
$scope.onUnselectPlot()
$scope.label_plot = plot_config
if $scope.label_plot
if $scope.label_plot.well < 8
$scope.label_plot.well_label = 'A' + ($scope.label_plot.well + 1)
else
$scope.label_plot.well_label = 'B' + ($scope.label_plot.well - 7)
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = false
$scope.well_data[well_i].highlight = false
omit_index = $scope.well_data[well_i].well_num.toString() + '_' + $scope.well_data[well_i].channel.toString()
if ($scope.well_data[well_i].well_num - 1 == plot_config.well and $scope.well_data[well_i].channel == plot_config.channel) and ($scope.omittedIndexes.indexOf(omit_index) == -1)
$scope.well_data[well_i].highlight = true
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = (i == plot_config.well)
else
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = false
$scope.well_data[well_i].highlight = false
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = false
$scope.onHoverRow = (event, well_item, index) ->
is_active_plot = false
for well_i in [0..$scope.well_data.length - 1]
if $scope.well_data[well_i].active
is_active_plot = true
break
if is_active_plot or (last_well_number == well_item.well_num and last_target_channel == well_item.channel)
return
last_well_number = well_item.well_num
last_target_channel = well_item.channel
omit_index = well_item.well_num.toString() + '_' + well_item.channel.toString()
if !$scope.has_init or (($scope.wellButtons['well_' + (well_item.well_num - 1)].selected) and ($scope.omittedIndexes.indexOf(omit_index) == -1) and ($scope.targetsSetHided[$scope.targets[index].id]))
if !well_item.active
$rootScope.$broadcast 'event:std-highlight-row', { well_datas: [{well: well_item.well_num, channel: well_item.channel}], well_index: well_item.well_num - 1 }
unhighlight_event = 'event:std-unhighlight-row'
$scope.onZoom = (transform, w, h, scale_extent) ->
$scope.std_scroll = {
value: Math.abs(transform.x/(w*transform.k - w))
width: w/(w*transform.k)
}
$scope.standardcurve_zoom = (transform.k - 1)/ (scale_extent)
$scope.zoomIn = ->
$scope.standardcurve_zoom = Math.min($scope.standardcurve_zoom * 2 || 0.001 * 2, 1)
$scope.zoomOut = ->
$scope.standardcurve_zoom = Math.max($scope.standardcurve_zoom * 0.5, 0.001)
$scope.onSelectWell = (well_item, index) ->
config = {}
config.config = {}
config.config.well = well_item.well_num - 1
config.config.channel = well_item.channel
dual_value = if $scope.is_dual_channel then 2 else 1
omit_index = well_item.well_num.toString() + '_' + well_item.channel.toString()
if $scope.wellButtons['well_' + (well_item.well_num - 1)].selected and $scope.omittedIndexes.indexOf(omit_index) == -1 and $scope.targetsSetHided[$scope.targets[index].id]
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = ($scope.well_data[well_i].well_num - 1 == config.config.well and $scope.well_data[well_i].channel == config.config.channel)
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = (i == config.config.well)
if(i == config.config.well)
$scope.index_target = i % 8
if (i < 8)
$scope.index_channel = 1
else
$scope.index_channel = 2
$scope.label_channel = config.config.channel
if i < $scope.targets.length
if $scope.targets[i]!=null
$scope.label_target = $scope.targets[config.config.well * dual_value + config.config.channel - 1]
else
$scope.label_target = ""
else
$scope.label_target = ""
if i < $scope.targets.length
if $scope.samples[i]!=null
$scope.label_sample = $scope.samples[i].name if $scope.samples[i]
else
$scope.label_sample = null
else
$scope.label_sample = null
# $scope.label_slope =
# $scope.label_yint =
wells = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8']
if $scope.label_target.name
$scope.line_bgcolor_target = { 'background-color':'black' }
else
$scope.line_bgcolor_target = { 'background-color':'#666' }
$scope.onSelectRow = (well_item, index) ->
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].highlight = false
omit_index = well_item.well_num.toString() + '_' + well_item.channel.toString()
if !$scope.has_init or (($scope.wellButtons['well_' + (well_item.well_num - 1)].selected) and ($scope.omittedIndexes.indexOf(omit_index) == -1) and ($scope.targetsSetHided[$scope.targets[index].id]))
if !well_item.active
$rootScope.$broadcast 'event:standard-select-row', {well: well_item.well_num, channel: well_item.channel, well_type: well_item.well_type}
else
$rootScope.$broadcast 'event:standard-unselect-row', {well: well_item.well_num, channel: well_item.channel, well_type: well_item.well_type }
$scope.onUnselectPlot()
$scope.onSelectPlot = (config) ->
$scope.plot_bgcolor_target = { 'background-color':'black' }
$scope.line_bgcolor_target = { 'background-color':'#666666' }
$scope.label_plot = config
if $scope.label_plot
if $scope.label_plot.well < 8
$scope.label_plot.well_label = 'A' + ($scope.label_plot.well + 1)
else
$scope.label_plot.well_label = 'B' + ($scope.label_plot.well - 7)
# $scope.line_bgcolor_target = { 'background-color':config.config.color }
dual_value = if $scope.is_dual_channel then 2 else 1
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = ($scope.well_data[well_i].well_num - 1 == config.well and $scope.well_data[well_i].channel == config.channel)
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = (i == config.well)
wellScrollTop = (config.well * dual_value + config.channel - 1 + dual_value) * 36 - document.querySelector('.table-container').offsetHeight
angular.element(document.querySelector('.table-container')).animate { scrollTop: wellScrollTop }, 'fast'
$scope.onUnselectLine = ->
$scope.label_well = "No Selection"
$scope.label_channel = ""
$scope.label_effic = ''
$scope.label_r2 = ''
$scope.label_slope = ''
$scope.label_yint = ''
$scope.line_bgcolor_target = {'background-color':'#666666'}
$scope.onUnselectPlot = ->
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i]?.active = false
$scope.well_data[well_i]?.highlight = false
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"]?.active = false
$scope.plot_bgcolor_target = {'background-color':'#666666'}
$scope.label_plot = null
$scope.$watchCollection 'wellButtons', ->
if $scope.hasData
$scope.onUnselectLine()
$scope.onUnselectPlot()
updateSeries()
$scope.$watch ->
$scope.$parent.chart
, (chart) ->
if chart is 'standard-curve'
$scope.expTargets = []
$scope.lookupTargets = []
Experiment.getTargets($stateParams.id).then (resp_target) ->
for i in [0...resp_target.data.length]
$scope.expTargets[i] = resp_target.data[i].target
$scope.lookupTargets[resp_target.data[i].target.id] = $scope.COLORS[i % $scope.COLORS.length]
$scope.expSamples = []
Experiment.getSamples($stateParams.id).then (response) ->
for i in [0...response.data.length]
$scope.expSamples[i] = response.data[i].sample
$scope.well_targets = []
Experiment.getWellLayout($stateParams.id).then (resp) ->
for i in [0...resp.data.length]
$scope.samples[i] = if resp.data[i].samples then resp.data[i].samples[0] else null
if $scope.samples[i]
for j in [0...$scope.expSamples.length]
if $scope.samples[i].id == $scope.expSamples[j].id
$scope.samples[i].color = $scope.COLORS[j % $scope.COLORS.length]
break
else
$scope.samples[i].color = $scope.init_sample_color
if $scope.is_dual_channel
$scope.well_targets[2*i] = if resp.data[i].targets && resp.data[i].targets[0] then resp.data[i].targets[0] else null
$scope.well_targets[2*i+1] = if resp.data[i].targets && resp.data[i].targets[1] then resp.data[i].targets[1] else null
if $scope.well_targets[2*i]
$scope.well_targets[2*i].color = if $scope.well_targets[2*i] then $scope.lookupTargets[$scope.well_targets[2*i].id] else 'transparent'
if $scope.well_targets[2*i+1]
$scope.well_targets[2*i+1].color = if $scope.well_targets[2*i+1] then $scope.lookupTargets[$scope.well_targets[2*i+1].id] else 'transparent'
else
$scope.well_targets[i] = if resp.data[i].targets && resp.data[i].targets[0] then resp.data[i].targets[0] else null
if $scope.well_targets[i]
$scope.well_targets[i].color = if $scope.well_targets[i] then $scope.lookupTargets[$scope.well_targets[i].id] else 'transparent'
$scope.well_data = helper.blankWellData($scope.is_dual_channel, $scope.well_targets)
$scope.targets = helper.blankWellTargetData($scope.well_data)
for i in [0..$scope.targets.length - 1] by 1
$scope.targetsSetHided[$scope.targets[i]?.id] = true if $scope.targetsSetHided[$scope.targets[i]?.id] is undefined
$scope.omittedIndexes = []
for well, i in $scope.well_data by 1
if well.omit
$scope.omittedIndexes.push(getWellDataIndex(well.well_num, well.channel))
$scope.updateTargetsSet()
updateSeries()
fetchFluorescenceData()
$timeout ->
$rootScope.$broadcast 'event:start-resize-aspect-ratio'
$scope.showStandardChart = true
, 1000
else
$scope.showAmpliChart = false
$scope.showStandardChart = false
$scope.$on '$destroy', ->
$interval.cancel(retryInterval) if retryInterval
# store well buttons
wellSelections = {}
for well_i in [0..15] by 1
wellSelections["well_#{well_i}"] = $scope.wellButtons["well_#{well_i}"].selected
$.jStorage.set('selectedWells', wellSelections)
$.jStorage.set('selectedExpId', $stateParams.id)
$scope.showPlotTypeList = ->
document.getElementById("plotTypeList").classList.toggle("show")
$scope.showColorByList = ->
document.getElementById("colorByList_standard").classList.toggle("show")
$scope.targetClick = (index) ->
$scope.targetsSetHided[index] = !$scope.targetsSetHided[index]
updateSeries()
# $scope.targetGridTop = ->
# document.getElementById("curve-plot").clientHeight + 30
$scope.targetGridTop = ->
Math.max(document.getElementById("curve-plot").clientHeight + 30, 412 + 30)
]
| true | ###
Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments.
For more information visit http://www.chaibio.com
Copyright 2016 Chai Biotechnologies Inc. <PI:EMAIL:<EMAIL>END_PI>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
window.ChaiBioTech.ngApp.controller 'StandardCurveChartCtrl', [
'$scope'
'$stateParams'
'Experiment'
'StandardCurveChartHelper'
'expName'
'$interval'
'Device'
'$timeout'
'$rootScope'
'focus'
($scope, $stateParams, Experiment, helper, expName, $interval, Device, $timeout, $rootScope, focus ) ->
Device.isDualChannel().then (is_dual_channel) ->
$scope.is_dual_channel = is_dual_channel
$scope.chartConfig = helper.chartConfig()
$scope.chartConfig.channels = if is_dual_channel then 2 else 1
# $scope.chartConfig.axes.x.max = 1
$scope.standardcurve_data = helper.paddData($scope.is_dual_channel)
$scope.well_data = []
$scope.line_data = {target_line: []}
$scope.COLORS = helper.SAMPLE_TARGET_COLORS
$scope.WELL_COLORS = helper.COLORS
AMPLI_DATA_CACHE = null
retryInterval = null
$scope.baseline_subtraction = true
$scope.color_by = 'well'
$scope.retrying = false
$scope.retry = 0
$scope.fetching = false
$scope.channel_1 = true
$scope.channel_2 = if is_dual_channel then true else false
$scope.standardcurve_zoom = 0
$scope.showOptions = true
$scope.isError = false
$scope.samples = []
$scope.types = []
$scope.targets = []
$scope.targetsSet = []
$scope.targetsSetHided = []
$scope.omittedIndexes = []
$scope.well_targets = []
$scope.label_effic = ''
$scope.label_r2 = ''
$scope.label_slope = ''
$scope.label_yint = ''
$scope.index_target = 0
$scope.index_channel = -1
$scope.label_sample = null
$scope.label_target = "No Selection"
$scope.label_well = "No Selection"
$scope.label_channel = ""
$scope.label_plot = null
$scope.has_init = false
$scope.re_init_chart_data = false
$scope.init_sample_color = '#ccc'
$scope.line_bgcolor_target = {
'background-color':'#666666'
}
$scope.plot_bgcolor_target = {
'background-color':'#666666'
}
last_well_number = 0
last_target_channel = 0
last_target_assigned = 0
$scope.registerOutsideHover = false;
unhighlight_event = ''
if !$scope.registerOutsideHover
$scope.registerOutsideHover = angular.element(window).on 'mousemove', (e)->
if !angular.element(e.target).parents('.well-switch').length and !angular.element(e.target).parents('.well-item-row').length
if unhighlight_event
$rootScope.$broadcast unhighlight_event, {}
unhighlight_event = ''
last_well_number = 0
last_target_channel = 0
last_target_assigned = 0
$scope.$apply()
$scope.toggleOmitIndex = (well_item) ->
return if $scope.re_init_chart_data
omit_index = well_item.well_num.toString() + '_' + well_item.channel.toString()
if $scope.omittedIndexes.indexOf(omit_index) != -1
$scope.omittedIndexes.splice $scope.omittedIndexes.indexOf(omit_index), 1
else
$scope.omittedIndexes.push omit_index
well_item.omit = if well_item.omit then 0 else 1
omitTargetLink = []
omitTargetLink. push
well_num: well_item.well_num,
omit: well_item.omit
Experiment.linkTarget($stateParams.id, well_item.target_id, { wells: omitTargetLink }).then (data) ->
reInitChartData()
getWellDataIndex = (well_num, channel) ->
return well_num.toString() + '_' + channel
reInitChartData = ->
$scope.chartConfig.line_series = []
$scope.chartConfig.series = []
$scope.retrying = false
$scope.retry = 0
$scope.fetching = false
$scope.hasData = false
$scope.error = null
$scope.has_init = false
$scope.re_init_chart_data = true
$scope.well_targets = []
Experiment.getWellLayout($stateParams.id).then (resp) ->
for i in [0...resp.data.length]
$scope.samples[i] = if resp.data[i].samples then resp.data[i].samples[0] else null
if $scope.samples[i]
for j in [0...$scope.expSamples.length]
if $scope.samples[i].id == $scope.expSamples[j].id
$scope.samples[i].color = $scope.COLORS[j % $scope.COLORS.length]
break
else
$scope.samples[i].color = $scope.init_sample_color
if $scope.is_dual_channel
$scope.well_targets[2*i] = if resp.data[i].targets && resp.data[i].targets[0] then resp.data[i].targets[0] else null
$scope.well_targets[2*i+1] = if resp.data[i].targets && resp.data[i].targets[1] then resp.data[i].targets[1] else null
if $scope.well_targets[2*i]
$scope.well_targets[2*i].color = if $scope.well_targets[2*i] then $scope.lookupTargets[$scope.well_targets[2*i].id] else 'transparent'
if $scope.well_targets[2*i+1]
$scope.well_targets[2*i+1].color = if $scope.well_targets[2*i+1] then $scope.lookupTargets[$scope.well_targets[2*i+1].id] else 'transparent'
else
$scope.well_targets[i] = if resp.data[i].targets && resp.data[i].targets[0] then resp.data[i].targets[0] else null
if $scope.well_targets[i]
$scope.well_targets[i].color = if $scope.well_targets[i] then $scope.lookupTargets[$scope.well_targets[i].id] else 'transparent'
fetchFluorescenceData()
$scope.updateTargetsSet = ->
# $scope.targetsSet = []
for i in [0...$scope.targets.length]
if $scope.targets[i]?.id
target = _.filter $scope.targetsSet, (target) ->
target.id is $scope.targets[i].id
if !target.length
$scope.targetsSet.push($scope.targets[i])
for i in [$scope.targetsSet.length-1..0] by -1
if $scope.targetsSet[i]?.id
target = _.filter $scope.targets, (item) ->
item.id is $scope.targetsSet[i].id
if !target.length
$scope.targetsSet.splice(i, 1)
$scope.$watchCollection 'targetsSetHided', ->
updateSeries() if $scope.hasData
$scope.$on 'event:switch-chart-well', (e, data, oldData) ->
if !data.active
$scope.onUnselectLine()
channel_count = if $scope.is_dual_channel then 2 else 1
wellScrollTop = (data.index * channel_count + channel_count) * 36 - document.querySelector('.table-container').offsetHeight
angular.element(document.querySelector('.table-container')).animate { scrollTop: wellScrollTop }, 'fast'
Experiment.get(id: $stateParams.id).then (data) ->
maxCycle = helper.getMaxExperimentCycle(data.experiment)
# $scope.chartConfig.axes.x.max = 1
$scope.experiment = data.experiment
$scope.$on 'status:data:updated', (e, data, oldData) ->
return if !data
return if !data.experiment_controller
$scope.statusData = data
$scope.state = data.experiment_controller.machine.state
$scope.thermal_state = data.experiment_controller.machine.thermal_state
$scope.oldState = oldData?.experiment_controller?.machine?.state || 'NONE'
$scope.isCurrentExp = parseInt(data.experiment_controller.experiment?.id) is parseInt($stateParams.id)
if $scope.isCurrentExp is true
$scope.enterState = $scope.isCurrentExp
retry = ->
$scope.retrying = true
$scope.retry = 5
retryInterval = $interval ->
$scope.retry = $scope.retry - 1
if $scope.retry is 0
$interval.cancel(retryInterval)
$scope.retrying = false
$scope.error = null
fetchFluorescenceData()
, 1000
fetchFluorescenceData = ->
gofetch = true
gofetch = false if $scope.fetching
gofetch = false if $scope.$parent.chart isnt 'standard-curve'
gofetch = false if $scope.retrying
if gofetch
$scope.has_init = true
$scope.fetching = true
Experiment
.getStandardCurveData($stateParams.id)
.then (resp) ->
$scope.fetching = false
$scope.error = null
if (resp.status is 200 and !resp.data.partial)
$scope.hasData = true
$scope.standardcurve_data = helper.paddData($scope.is_dual_channel)
if (resp.status is 200 and resp.data?.partial and $scope.enterState)
$scope.hasData = false
if resp.status is 200 and !resp.data.partial
$rootScope.$broadcast 'complete'
if $scope.hasData and (resp.data.steps?[0].amplification_data and resp.data.steps?[0].amplification_data?.length > 1)
# $scope.chartConfig.axes.x.min = 0
data = resp.data.steps[0]
$scope.well_data = helper.normalizeSummaryData(data.summary_data, data.targets, $scope.well_targets)
$scope.targets = helper.normalizeWellTargetData($scope.well_data, $scope.targets, $scope.is_dual_channel)
data.summary_data = helper.initialSummaryData(data.summary_data, data.targets)
$scope.omittedIndexes = []
for well, i in $scope.well_data by 1
if well.omit
$scope.omittedIndexes.push(getWellDataIndex(well.well_num, well.channel))
if !$scope.re_init_chart_data
for i in [0..$scope.targets.length - 1] by 1
$scope.targetsSetHided[$scope.targets[i]?.id] = true if $scope.targetsSetHided[$scope.targets[i]?.id] is undefined
AMPLI_DATA_CACHE = angular.copy data
$scope.standardcurve_data = helper.neutralizeChartData(data.summary_data, data.targets, $scope.targets, $scope.is_dual_channel)
$scope.line_data = helper.neutralizeLineData(data.targets)
minQt = if $scope.well_data[0] then $scope.well_data[0].quantity else 0
maxQt = 0
minCq = if $scope.well_data[0] then $scope.well_data[0].cq else 0
maxCq = 0
for well_item in $scope.well_data by 1
if well_item.quantity <= minQt and well_item.quantity then minQt = well_item.quantity
if well_item.quantity >= maxQt and well_item.quantity then maxQt = well_item.quantity
if well_item.cq <= minCq and well_item.cq then minCq = well_item.cq
if well_item.cq >= maxCq and well_item.cq then maxCq = well_item.cq
maxQt = Math.log10(maxQt)
minQt = Math.log10(minQt)
gapX = maxQt - minQt
gapY = maxCq - minCq
$scope.chartConfig.axes.x.min = if Math.floor(minQt) is minQt then minQt - 1 else Math.floor(minQt)
$scope.chartConfig.axes.x.max = if Math.ceil(maxQt) is maxQt then maxQt + 1 else Math.ceil(maxQt)
$scope.chartConfig.axes.y.min = minCq
$scope.chartConfig.axes.y.max = maxCq
$scope.updateTargetsSet()
updateButtonCts()
updateSeries()
if !(($scope.experiment?.completion_status && $scope.experiment?.completed_at) or $scope.enterState)
$scope.retrying = true
if ((resp.data?.partial is true) or (resp.status is 202)) and !$scope.retrying
retry()
else
$scope.re_init_chart_data = false
.catch (resp) ->
if resp.status is 500
$scope.error = resp.statusText || 'Unknown error'
$scope.fetching = false
return if $scope.retrying
retry()
else
retry()
updateButtonCts = ->
for well_i in [0..15] by 1
channel_1_well = _.find $scope.well_data, (item) ->
item.well_num is well_i+1 and item.channel is 1
channel_2_well = _.find $scope.well_data, (item) ->
item.well_num is well_i+1 and item.channel is 2
$scope.wellButtons["well_#{well_i}"].well_type = []
$scope.wellButtons["well_#{well_i}"].well_type.push(if channel_1_well then channel_1_well.well_type else '')
$scope.wellButtons["well_#{well_i}"].well_type.push(if channel_2_well then channel_2_well.well_type else '')
cts = _.filter AMPLI_DATA_CACHE.summary_data, (ct) ->
ct[1] is well_i+1
$scope.wellButtons["well_#{well_i}"].ct = []
for ct_i in [0..cts.length - 1] by 1
$scope.wellButtons["well_#{well_i}"].ct.push(cts[ct_i][3])
return
updateSeries = (buttons) ->
buttons = buttons || $scope.wellButtons || {}
$scope.chartConfig.series = []
nonGreySeries = []
channel_count = if $scope.is_dual_channel then 2 else 1
channel_end = if $scope.channel_1 && $scope.channel_2 then 2 else if $scope.channel_1 && !$scope.channel_2 then 1 else if !$scope.channel_1 && $scope.channel_2 then 2
channel_start = if $scope.channel_1 && $scope.channel_2 then 1 else if $scope.channel_1 && !$scope.channel_2 then 1 else if !$scope.channel_1 && $scope.channel_2 then 2
$scope.chartConfig.line_series = []
for i in [0..$scope.line_data['target_line'].length - 1] by 1
well_color = '#c5c5c5'
if $scope.targetsSetHided[$scope.line_data['target_line'][i].id]
if $scope.color_by is 'target'
target = _.filter $scope.targets, (target) ->
target && target.id is $scope.line_data['target_line'][i].id
if target.length
well_color = target[0].color
else
well_color = 'transparent'
$scope.line_data['target_line'][i].color = well_color
for ch_i in [channel_start..channel_end] by 1
for i in [0..15] by 1
if $scope.omittedIndexes.indexOf(getWellDataIndex(i + 1, ch_i)) == -1
# alert(i)
if buttons["well_#{i}"]?.selected and $scope.targets[i * channel_count + (ch_i - 1)] and $scope.targets[i * channel_count + (ch_i - 1)].id and $scope.targetsSetHided[$scope.targets[i * channel_count + (ch_i - 1)].id]
if $scope.color_by is 'well'
well_color = buttons["well_#{i}"].color
else if $scope.color_by is 'target'
well_color = if $scope.targets[(ch_i - 1)+i*channel_count] then $scope.targets[(ch_i - 1)+i*channel_count].color else 'transparent'
else if $scope.color_by is 'sample'
well_color = if $scope.samples[i] then $scope.samples[i].color else $scope.init_sample_color
if ($scope.is_dual_channel and !$scope.targets[i*channel_count].id and !$scope.targets[i*channel_count+1].id) or (!$scope.is_dual_channel and !$scope.targets[i].id)
well_color = 'transparent'
else if ch_i is 1
well_color = '#00AEEF'
else
well_color = '#8FC742'
continue if $scope.standardcurve_data["well_#{i}_#{ch_i}"][0] is undefined or Math.abs($scope.standardcurve_data["well_#{i}_#{ch_i}"][0]['log_quantity']) is Number.POSITIVE_INFINITY
if $scope.color_by is 'sample'
if well_color is $scope.init_sample_color
$scope.chartConfig.series.push
dataset: "well_#{i}_#{ch_i}"
x: 'log_quantity'
y: "cq"
color: well_color
cq: $scope.wellButtons["well_#{i}"]?.ct
well: i
channel: ch_i
well_type: $scope.targets[i * channel_count + (ch_i - 1)].well_type
target_id: $scope.targets[i * channel_count + (ch_i - 1)].id
else
nonGreySeries.push
dataset: "well_#{i}_#{ch_i}"
x: 'log_quantity'
y: "cq"
color: well_color
cq: $scope.wellButtons["well_#{i}"]?.ct
well: i
channel: ch_i
well_type: $scope.targets[i * channel_count + (ch_i - 1)].well_type
target_id: $scope.targets[i * channel_count + (ch_i - 1)].id
else
$scope.chartConfig.series.push
dataset: "well_#{i}_#{ch_i}"
x: 'log_quantity'
y: "cq"
color: well_color
cq: $scope.wellButtons["well_#{i}"]?.ct
well: i
channel: ch_i
well_type: $scope.targets[i * channel_count + (ch_i - 1)].well_type
target_id: $scope.targets[i * channel_count + (ch_i - 1)].id
else
$scope.onUnselectPlot()
if $scope.color_by is 'sample'
for i in [0..nonGreySeries.length - 1] by 1
$scope.chartConfig.series.push(nonGreySeries[i])
getWellDataIndex = (well_num, channel) ->
for i in [0..$scope.well_data.length - 1] by 1
if $scope.well_data[i].well_num is well_num and $scope.well_data[i].channel is channel
return i
return -1
$scope.onUpdateProperties = (line_config) ->
$scope.label_effic = line_config.efficiency
$scope.label_r2 = line_config.r2
$scope.label_slope = line_config.slope
$scope.label_yint = line_config.offset
target = _.filter $scope.targets, (target) ->
target && target.id is line_config.id
if target.length
$scope.label_well = target[0].name
$scope.label_channel = target[0].channel
$scope.line_bgcolor_target = { 'background-color':'black' }
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = false
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = false
$scope.onHighlightPlots = (configs, well_index) ->
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = false
$scope.well_data[well_i].highlight = false
for well_i in [0..$scope.well_data.length - 1]
omit_index = $scope.well_data[well_i].well_num.toString() + '_' + $scope.well_data[well_i].channel.toString()
for config, i in configs by 1
if ($scope.well_data[well_i].well_num - 1 == config.config.well and $scope.well_data[well_i].channel == config.config.channel) and ($scope.omittedIndexes.indexOf(omit_index) == -1)
$scope.well_data[well_i].highlight = true
dual_value = if $scope.is_dual_channel then 2 else 1
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = (i == well_index)
if configs[0]
config = configs[0].config
wellScrollTop = (config.well * dual_value + config.channel - 1 + dual_value) * 36 - document.querySelector('.detail-mode-table tbody').offsetHeight
angular.element('.detail-mode-table tbody').animate { scrollTop: wellScrollTop }, 'fast'
return
$scope.onUnHighlightPlots = () ->
$scope.onUnselectPlot()
return
$scope.onHoverPlot = (plot_config, well_index) ->
$scope.onUnselectPlot()
$scope.label_plot = plot_config
if $scope.label_plot
if $scope.label_plot.well < 8
$scope.label_plot.well_label = 'A' + ($scope.label_plot.well + 1)
else
$scope.label_plot.well_label = 'B' + ($scope.label_plot.well - 7)
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = false
$scope.well_data[well_i].highlight = false
omit_index = $scope.well_data[well_i].well_num.toString() + '_' + $scope.well_data[well_i].channel.toString()
if ($scope.well_data[well_i].well_num - 1 == plot_config.well and $scope.well_data[well_i].channel == plot_config.channel) and ($scope.omittedIndexes.indexOf(omit_index) == -1)
$scope.well_data[well_i].highlight = true
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = (i == plot_config.well)
else
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = false
$scope.well_data[well_i].highlight = false
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = false
$scope.onHoverRow = (event, well_item, index) ->
is_active_plot = false
for well_i in [0..$scope.well_data.length - 1]
if $scope.well_data[well_i].active
is_active_plot = true
break
if is_active_plot or (last_well_number == well_item.well_num and last_target_channel == well_item.channel)
return
last_well_number = well_item.well_num
last_target_channel = well_item.channel
omit_index = well_item.well_num.toString() + '_' + well_item.channel.toString()
if !$scope.has_init or (($scope.wellButtons['well_' + (well_item.well_num - 1)].selected) and ($scope.omittedIndexes.indexOf(omit_index) == -1) and ($scope.targetsSetHided[$scope.targets[index].id]))
if !well_item.active
$rootScope.$broadcast 'event:std-highlight-row', { well_datas: [{well: well_item.well_num, channel: well_item.channel}], well_index: well_item.well_num - 1 }
unhighlight_event = 'event:std-unhighlight-row'
$scope.onZoom = (transform, w, h, scale_extent) ->
$scope.std_scroll = {
value: Math.abs(transform.x/(w*transform.k - w))
width: w/(w*transform.k)
}
$scope.standardcurve_zoom = (transform.k - 1)/ (scale_extent)
$scope.zoomIn = ->
$scope.standardcurve_zoom = Math.min($scope.standardcurve_zoom * 2 || 0.001 * 2, 1)
$scope.zoomOut = ->
$scope.standardcurve_zoom = Math.max($scope.standardcurve_zoom * 0.5, 0.001)
$scope.onSelectWell = (well_item, index) ->
config = {}
config.config = {}
config.config.well = well_item.well_num - 1
config.config.channel = well_item.channel
dual_value = if $scope.is_dual_channel then 2 else 1
omit_index = well_item.well_num.toString() + '_' + well_item.channel.toString()
if $scope.wellButtons['well_' + (well_item.well_num - 1)].selected and $scope.omittedIndexes.indexOf(omit_index) == -1 and $scope.targetsSetHided[$scope.targets[index].id]
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = ($scope.well_data[well_i].well_num - 1 == config.config.well and $scope.well_data[well_i].channel == config.config.channel)
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = (i == config.config.well)
if(i == config.config.well)
$scope.index_target = i % 8
if (i < 8)
$scope.index_channel = 1
else
$scope.index_channel = 2
$scope.label_channel = config.config.channel
if i < $scope.targets.length
if $scope.targets[i]!=null
$scope.label_target = $scope.targets[config.config.well * dual_value + config.config.channel - 1]
else
$scope.label_target = ""
else
$scope.label_target = ""
if i < $scope.targets.length
if $scope.samples[i]!=null
$scope.label_sample = $scope.samples[i].name if $scope.samples[i]
else
$scope.label_sample = null
else
$scope.label_sample = null
# $scope.label_slope =
# $scope.label_yint =
wells = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8']
if $scope.label_target.name
$scope.line_bgcolor_target = { 'background-color':'black' }
else
$scope.line_bgcolor_target = { 'background-color':'#666' }
$scope.onSelectRow = (well_item, index) ->
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].highlight = false
omit_index = well_item.well_num.toString() + '_' + well_item.channel.toString()
if !$scope.has_init or (($scope.wellButtons['well_' + (well_item.well_num - 1)].selected) and ($scope.omittedIndexes.indexOf(omit_index) == -1) and ($scope.targetsSetHided[$scope.targets[index].id]))
if !well_item.active
$rootScope.$broadcast 'event:standard-select-row', {well: well_item.well_num, channel: well_item.channel, well_type: well_item.well_type}
else
$rootScope.$broadcast 'event:standard-unselect-row', {well: well_item.well_num, channel: well_item.channel, well_type: well_item.well_type }
$scope.onUnselectPlot()
$scope.onSelectPlot = (config) ->
$scope.plot_bgcolor_target = { 'background-color':'black' }
$scope.line_bgcolor_target = { 'background-color':'#666666' }
$scope.label_plot = config
if $scope.label_plot
if $scope.label_plot.well < 8
$scope.label_plot.well_label = 'A' + ($scope.label_plot.well + 1)
else
$scope.label_plot.well_label = 'B' + ($scope.label_plot.well - 7)
# $scope.line_bgcolor_target = { 'background-color':config.config.color }
dual_value = if $scope.is_dual_channel then 2 else 1
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i].active = ($scope.well_data[well_i].well_num - 1 == config.well and $scope.well_data[well_i].channel == config.channel)
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"].active = (i == config.well)
wellScrollTop = (config.well * dual_value + config.channel - 1 + dual_value) * 36 - document.querySelector('.table-container').offsetHeight
angular.element(document.querySelector('.table-container')).animate { scrollTop: wellScrollTop }, 'fast'
$scope.onUnselectLine = ->
$scope.label_well = "No Selection"
$scope.label_channel = ""
$scope.label_effic = ''
$scope.label_r2 = ''
$scope.label_slope = ''
$scope.label_yint = ''
$scope.line_bgcolor_target = {'background-color':'#666666'}
$scope.onUnselectPlot = ->
for well_i in [0..$scope.well_data.length - 1]
$scope.well_data[well_i]?.active = false
$scope.well_data[well_i]?.highlight = false
for i in [0..15] by 1
$scope.wellButtons["well_#{i}"]?.active = false
$scope.plot_bgcolor_target = {'background-color':'#666666'}
$scope.label_plot = null
$scope.$watchCollection 'wellButtons', ->
if $scope.hasData
$scope.onUnselectLine()
$scope.onUnselectPlot()
updateSeries()
$scope.$watch ->
$scope.$parent.chart
, (chart) ->
if chart is 'standard-curve'
$scope.expTargets = []
$scope.lookupTargets = []
Experiment.getTargets($stateParams.id).then (resp_target) ->
for i in [0...resp_target.data.length]
$scope.expTargets[i] = resp_target.data[i].target
$scope.lookupTargets[resp_target.data[i].target.id] = $scope.COLORS[i % $scope.COLORS.length]
$scope.expSamples = []
Experiment.getSamples($stateParams.id).then (response) ->
for i in [0...response.data.length]
$scope.expSamples[i] = response.data[i].sample
$scope.well_targets = []
Experiment.getWellLayout($stateParams.id).then (resp) ->
for i in [0...resp.data.length]
$scope.samples[i] = if resp.data[i].samples then resp.data[i].samples[0] else null
if $scope.samples[i]
for j in [0...$scope.expSamples.length]
if $scope.samples[i].id == $scope.expSamples[j].id
$scope.samples[i].color = $scope.COLORS[j % $scope.COLORS.length]
break
else
$scope.samples[i].color = $scope.init_sample_color
if $scope.is_dual_channel
$scope.well_targets[2*i] = if resp.data[i].targets && resp.data[i].targets[0] then resp.data[i].targets[0] else null
$scope.well_targets[2*i+1] = if resp.data[i].targets && resp.data[i].targets[1] then resp.data[i].targets[1] else null
if $scope.well_targets[2*i]
$scope.well_targets[2*i].color = if $scope.well_targets[2*i] then $scope.lookupTargets[$scope.well_targets[2*i].id] else 'transparent'
if $scope.well_targets[2*i+1]
$scope.well_targets[2*i+1].color = if $scope.well_targets[2*i+1] then $scope.lookupTargets[$scope.well_targets[2*i+1].id] else 'transparent'
else
$scope.well_targets[i] = if resp.data[i].targets && resp.data[i].targets[0] then resp.data[i].targets[0] else null
if $scope.well_targets[i]
$scope.well_targets[i].color = if $scope.well_targets[i] then $scope.lookupTargets[$scope.well_targets[i].id] else 'transparent'
$scope.well_data = helper.blankWellData($scope.is_dual_channel, $scope.well_targets)
$scope.targets = helper.blankWellTargetData($scope.well_data)
for i in [0..$scope.targets.length - 1] by 1
$scope.targetsSetHided[$scope.targets[i]?.id] = true if $scope.targetsSetHided[$scope.targets[i]?.id] is undefined
$scope.omittedIndexes = []
for well, i in $scope.well_data by 1
if well.omit
$scope.omittedIndexes.push(getWellDataIndex(well.well_num, well.channel))
$scope.updateTargetsSet()
updateSeries()
fetchFluorescenceData()
$timeout ->
$rootScope.$broadcast 'event:start-resize-aspect-ratio'
$scope.showStandardChart = true
, 1000
else
$scope.showAmpliChart = false
$scope.showStandardChart = false
$scope.$on '$destroy', ->
$interval.cancel(retryInterval) if retryInterval
# store well buttons
wellSelections = {}
for well_i in [0..15] by 1
wellSelections["well_#{well_i}"] = $scope.wellButtons["well_#{well_i}"].selected
$.jStorage.set('selectedWells', wellSelections)
$.jStorage.set('selectedExpId', $stateParams.id)
$scope.showPlotTypeList = ->
document.getElementById("plotTypeList").classList.toggle("show")
$scope.showColorByList = ->
document.getElementById("colorByList_standard").classList.toggle("show")
$scope.targetClick = (index) ->
$scope.targetsSetHided[index] = !$scope.targetsSetHided[index]
updateSeries()
# $scope.targetGridTop = ->
# document.getElementById("curve-plot").clientHeight + 30
$scope.targetGridTop = ->
Math.max(document.getElementById("curve-plot").clientHeight + 30, 412 + 30)
]
|
[
{
"context": "ashPassword\n password : password\n salt : new Buffer",
"end": 1836,
"score": 0.9986457228660583,
"start": 1828,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "t) ->\n hashPassword({pa... | src/api/authentication_strategies.coffee | bladepan/cloudbrowser | 0 | Crypto = require('crypto')
Async = require('async')
User = require('../server/user')
{getParentMountPoint, hashPassword} = require('./utils')
cloudbrowserError = require('../shared/cloudbrowser_error')
utils = require('../shared/utils')
###*
@class LocalStrategy
@param {BrowserServer} bserver
@param {cloudbrowser} cbCtx
###
class LocalStrategy
constructor : (app, bserver, cbCtx) ->
###*
Logs a user into the application.
@method login
@param options
@param {String} options.emailID
@param {String} options.password
@param {booleanCallback} options.callback
@instance
@memberof LocalStrategy
###
@login = (options) ->
{emailID, password, callback} = options
if typeof callback isnt "function" then return
if typeof password isnt "string"
return callback?(cloudbrowserError("PARAM_INVALID", "- password"))
if typeof emailID isnt "string" or
not utils.isEmail(emailID)
return callback?(cloudbrowserError("PARAM_INVALID", "- emailID"))
user = new User(emailID)
mountPoint = app.mountPoint
sessionManager = bserver.server.sessionManager
appUrl = app.getAppUrl()
dbKey = null
redirectto = null
result = null
Async.waterfall [
(next) ->
app.findUser(user, next)
(userRec, next) ->
if userRec and userRec.key and userRec.salt and userRec.status isnt 'unverified'
dbKey = userRec.key
hashPassword
password : password
salt : new Buffer(userRec.salt, 'hex')
, next
# Bypassing the waterfall
else callback(null, null)
(res, next) ->
result = res
bserver.getFirstSession(next)
], (err, session) ->
if err then return callback(err)
if result?.key.toString('hex') is dbKey
# This is the what actually marks the user as logged in
sessionManager.addAppUserID(session, mountPoint, user)
else callback(null, false)
# When an unauthenticated request for a specific browser
# arrives, the url for that browser is stored in the
# session (session.redirectto) of the requesting user.
# Then, the user is redirected to the authentication
# browser, where the user logs in using the current
# function. Finally the user is redirected to the
# originally requested browser stored in the session.
redirectto = sessionManager.findPropOnSession(session,
'redirectto')
sessionManager.setPropOnSession(session, 'redirectto', null)
if redirectto then bserver.redirect(redirectto)
else bserver.redirect(appUrl)
bserver.once 'NoClients', () ->
app.closeBrowser(bserver)
return
###*
Registers a user with the application and sends a confirmation email to the user's registered email ID.
The email ID is not activated until it has been confirmed by the user.
@method signup
@param options
@param {String} options.emailID
@param {String} options.password
@param {booleanCallback} options.callback
@instance
@memberof LocalStrategy
###
@signup = (options) ->
{emailID, password, callback} = options
if typeof password isnt "string"
return callback(cloudbrowserError("PARAM_INVALID", "- password"))
if typeof emailID isnt "string"
return callback(cloudbrowserError("PARAM_INVALID", "- emailID"))
{util} = cbCtx
user = new User(emailID)
appUrl = app.getAppUrl()
token = null
# Generating a random token to ensure the validity of user confirmation.
Async.waterfall [
(next) ->
Crypto.randomBytes(32, next)
(tkn, next) ->
# Sending the confirmation email
token = tkn.toString('hex')
subject = "Activate your cloudbrowser account"
confirmationMsg = "Please click on the link below to verify " +
"your email address.<br><p><a href='#{appUrl}/activate/" +
"#{token}'>Activate your account</a></p><p>If you have " +
"received this message in error and did not sign up for a " +
"cloudbrowser account, click <a href='#{appUrl}/deactivate/" +
"#{token}'>not my account</a></p>"
util.sendEmail
to : user.getEmail()
subject : subject
html : confirmationMsg
callback : next
(next) ->
hashPassword({password : password}, next)
(result, next) ->
# Hashing the user supplied password using pbkdf2
# and storing it with the status of 'unverified' to
# indicate that the email ID has not been activated
# and any login request from this account must not be
# allowed to pass unless verified by clicking on the
# email link sent above.
user.key = result.key.toString('hex')
user.salt = result.salt.toString('hex')
user.token = token
user.status = 'unverified'
app.addNewUser(user, (err) -> next(err))
], callback
return
###*
@class GoogleStrategy
@param {BrowserServer} bserver
###
class GoogleStrategy
constructor : (app, bserver) ->
###*
Log in through a google ID
@method login
@instance
@memberof GoogleStrategy
###
@login = () ->
bserver._redirectToGoogleAuth(app.mountPoint)
return
module.exports =
LocalStrategy : LocalStrategy
GoogleStrategy : GoogleStrategy
| 117563 | Crypto = require('crypto')
Async = require('async')
User = require('../server/user')
{getParentMountPoint, hashPassword} = require('./utils')
cloudbrowserError = require('../shared/cloudbrowser_error')
utils = require('../shared/utils')
###*
@class LocalStrategy
@param {BrowserServer} bserver
@param {cloudbrowser} cbCtx
###
class LocalStrategy
constructor : (app, bserver, cbCtx) ->
###*
Logs a user into the application.
@method login
@param options
@param {String} options.emailID
@param {String} options.password
@param {booleanCallback} options.callback
@instance
@memberof LocalStrategy
###
@login = (options) ->
{emailID, password, callback} = options
if typeof callback isnt "function" then return
if typeof password isnt "string"
return callback?(cloudbrowserError("PARAM_INVALID", "- password"))
if typeof emailID isnt "string" or
not utils.isEmail(emailID)
return callback?(cloudbrowserError("PARAM_INVALID", "- emailID"))
user = new User(emailID)
mountPoint = app.mountPoint
sessionManager = bserver.server.sessionManager
appUrl = app.getAppUrl()
dbKey = null
redirectto = null
result = null
Async.waterfall [
(next) ->
app.findUser(user, next)
(userRec, next) ->
if userRec and userRec.key and userRec.salt and userRec.status isnt 'unverified'
dbKey = userRec.key
hashPassword
password : <PASSWORD>
salt : new Buffer(userRec.salt, 'hex')
, next
# Bypassing the waterfall
else callback(null, null)
(res, next) ->
result = res
bserver.getFirstSession(next)
], (err, session) ->
if err then return callback(err)
if result?.key.toString('hex') is dbKey
# This is the what actually marks the user as logged in
sessionManager.addAppUserID(session, mountPoint, user)
else callback(null, false)
# When an unauthenticated request for a specific browser
# arrives, the url for that browser is stored in the
# session (session.redirectto) of the requesting user.
# Then, the user is redirected to the authentication
# browser, where the user logs in using the current
# function. Finally the user is redirected to the
# originally requested browser stored in the session.
redirectto = sessionManager.findPropOnSession(session,
'redirectto')
sessionManager.setPropOnSession(session, 'redirectto', null)
if redirectto then bserver.redirect(redirectto)
else bserver.redirect(appUrl)
bserver.once 'NoClients', () ->
app.closeBrowser(bserver)
return
###*
Registers a user with the application and sends a confirmation email to the user's registered email ID.
The email ID is not activated until it has been confirmed by the user.
@method signup
@param options
@param {String} options.emailID
@param {String} options.password
@param {booleanCallback} options.callback
@instance
@memberof LocalStrategy
###
@signup = (options) ->
{emailID, password, callback} = options
if typeof password isnt "string"
return callback(cloudbrowserError("PARAM_INVALID", "- password"))
if typeof emailID isnt "string"
return callback(cloudbrowserError("PARAM_INVALID", "- emailID"))
{util} = cbCtx
user = new User(emailID)
appUrl = app.getAppUrl()
token = null
# Generating a random token to ensure the validity of user confirmation.
Async.waterfall [
(next) ->
Crypto.randomBytes(32, next)
(tkn, next) ->
# Sending the confirmation email
token = tkn.toString('hex')
subject = "Activate your cloudbrowser account"
confirmationMsg = "Please click on the link below to verify " +
"your email address.<br><p><a href='#{appUrl}/activate/" +
"#{token}'>Activate your account</a></p><p>If you have " +
"received this message in error and did not sign up for a " +
"cloudbrowser account, click <a href='#{appUrl}/deactivate/" +
"#{token}'>not my account</a></p>"
util.sendEmail
to : user.getEmail()
subject : subject
html : confirmationMsg
callback : next
(next) ->
hashPassword({password : <PASSWORD>}, next)
(result, next) ->
# Hashing the user supplied password using pbkdf2
# and storing it with the status of 'unverified' to
# indicate that the email ID has not been activated
# and any login request from this account must not be
# allowed to pass unless verified by clicking on the
# email link sent above.
user.key = result.key.toString('hex')
user.salt = result.salt.toString('hex')
user.token = token
user.status = 'unverified'
app.addNewUser(user, (err) -> next(err))
], callback
return
###*
@class GoogleStrategy
@param {BrowserServer} bserver
###
class GoogleStrategy
constructor : (app, bserver) ->
###*
Log in through a google ID
@method login
@instance
@memberof GoogleStrategy
###
@login = () ->
bserver._redirectToGoogleAuth(app.mountPoint)
return
module.exports =
LocalStrategy : LocalStrategy
GoogleStrategy : GoogleStrategy
| true | Crypto = require('crypto')
Async = require('async')
User = require('../server/user')
{getParentMountPoint, hashPassword} = require('./utils')
cloudbrowserError = require('../shared/cloudbrowser_error')
utils = require('../shared/utils')
###*
@class LocalStrategy
@param {BrowserServer} bserver
@param {cloudbrowser} cbCtx
###
class LocalStrategy
constructor : (app, bserver, cbCtx) ->
###*
Logs a user into the application.
@method login
@param options
@param {String} options.emailID
@param {String} options.password
@param {booleanCallback} options.callback
@instance
@memberof LocalStrategy
###
@login = (options) ->
{emailID, password, callback} = options
if typeof callback isnt "function" then return
if typeof password isnt "string"
return callback?(cloudbrowserError("PARAM_INVALID", "- password"))
if typeof emailID isnt "string" or
not utils.isEmail(emailID)
return callback?(cloudbrowserError("PARAM_INVALID", "- emailID"))
user = new User(emailID)
mountPoint = app.mountPoint
sessionManager = bserver.server.sessionManager
appUrl = app.getAppUrl()
dbKey = null
redirectto = null
result = null
Async.waterfall [
(next) ->
app.findUser(user, next)
(userRec, next) ->
if userRec and userRec.key and userRec.salt and userRec.status isnt 'unverified'
dbKey = userRec.key
hashPassword
password : PI:PASSWORD:<PASSWORD>END_PI
salt : new Buffer(userRec.salt, 'hex')
, next
# Bypassing the waterfall
else callback(null, null)
(res, next) ->
result = res
bserver.getFirstSession(next)
], (err, session) ->
if err then return callback(err)
if result?.key.toString('hex') is dbKey
# This is the what actually marks the user as logged in
sessionManager.addAppUserID(session, mountPoint, user)
else callback(null, false)
# When an unauthenticated request for a specific browser
# arrives, the url for that browser is stored in the
# session (session.redirectto) of the requesting user.
# Then, the user is redirected to the authentication
# browser, where the user logs in using the current
# function. Finally the user is redirected to the
# originally requested browser stored in the session.
redirectto = sessionManager.findPropOnSession(session,
'redirectto')
sessionManager.setPropOnSession(session, 'redirectto', null)
if redirectto then bserver.redirect(redirectto)
else bserver.redirect(appUrl)
bserver.once 'NoClients', () ->
app.closeBrowser(bserver)
return
###*
Registers a user with the application and sends a confirmation email to the user's registered email ID.
The email ID is not activated until it has been confirmed by the user.
@method signup
@param options
@param {String} options.emailID
@param {String} options.password
@param {booleanCallback} options.callback
@instance
@memberof LocalStrategy
###
@signup = (options) ->
{emailID, password, callback} = options
if typeof password isnt "string"
return callback(cloudbrowserError("PARAM_INVALID", "- password"))
if typeof emailID isnt "string"
return callback(cloudbrowserError("PARAM_INVALID", "- emailID"))
{util} = cbCtx
user = new User(emailID)
appUrl = app.getAppUrl()
token = null
# Generating a random token to ensure the validity of user confirmation.
Async.waterfall [
(next) ->
Crypto.randomBytes(32, next)
(tkn, next) ->
# Sending the confirmation email
token = tkn.toString('hex')
subject = "Activate your cloudbrowser account"
confirmationMsg = "Please click on the link below to verify " +
"your email address.<br><p><a href='#{appUrl}/activate/" +
"#{token}'>Activate your account</a></p><p>If you have " +
"received this message in error and did not sign up for a " +
"cloudbrowser account, click <a href='#{appUrl}/deactivate/" +
"#{token}'>not my account</a></p>"
util.sendEmail
to : user.getEmail()
subject : subject
html : confirmationMsg
callback : next
(next) ->
hashPassword({password : PI:PASSWORD:<PASSWORD>END_PI}, next)
(result, next) ->
# Hashing the user supplied password using pbkdf2
# and storing it with the status of 'unverified' to
# indicate that the email ID has not been activated
# and any login request from this account must not be
# allowed to pass unless verified by clicking on the
# email link sent above.
user.key = result.key.toString('hex')
user.salt = result.salt.toString('hex')
user.token = token
user.status = 'unverified'
app.addNewUser(user, (err) -> next(err))
], callback
return
###*
@class GoogleStrategy
@param {BrowserServer} bserver
###
class GoogleStrategy
constructor : (app, bserver) ->
###*
Log in through a google ID
@method login
@instance
@memberof GoogleStrategy
###
@login = () ->
bserver._redirectToGoogleAuth(app.mountPoint)
return
module.exports =
LocalStrategy : LocalStrategy
GoogleStrategy : GoogleStrategy
|
[
{
"context": "er for Zen Photon Garden.\n#\n# Copyright (c) 2013 Micah Elizabeth Scott <micah@scanlime.org>\n#\n# Permission is hereby g",
"end": 481,
"score": 0.9998833537101746,
"start": 460,
"tag": "NAME",
"value": "Micah Elizabeth Scott"
},
{
"context": ".\n#\n# Copyright (... | example /hqz/cluster-start.coffee | amane312/photon_generator | 0 | #!/usr/bin/env coffee
#
# Cluster startup script. Experimental!
#
# AWS configuration comes from the environment:
#
# AWS_ACCESS_KEY_ID
# AWS_SECRET_ACCESS_KEY
# AWS_REGION
# HQZ_BUCKET
#
# Required Node modules:
#
# npm install aws-sdk coffee-script async
#
######################################################################
#
# This file is part of HQZ, the batch renderer for Zen Photon Garden.
#
# Copyright (c) 2013 Micah Elizabeth Scott <micah@scanlime.org>
#
# 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.
#
# Tweakables
kRoleName = 'hqz-node'
kSpotPrice = "0.10" # Maximum price per instance-hour
kImageId = "ami-2efa9d47" # Ubuntu 12.04 LTS, x64, us-east-1
kInstanceType = "c1.xlarge" # High-CPU instance
# Number of instances that will stay around to wait for the queue to fully empty.
# The rest of them will start exiting when they're less than 50% utilized.
kMaxStickyInstances = 1
kBucketName = process.env.HQZ_BUCKET
kInstanceTags = [ {
Key: "com.zenphoton.hqz"
Value: "node"
} ]
######################################################################
AWS = require 'aws-sdk'
async = require 'async'
util = require 'util'
iam = new AWS.IAM().client
ec2 = new AWS.EC2().client
log = (msg) -> console.log "[#{ (new Date).toJSON() }] #{msg}"
if process.argv.length != 3
console.log "usage: cluster-start <number of instances>"
process.exit 1
numInstances = process.argv[2] | 0
process.exit 0 if numInstances <= 0
numStickyInstances = Math.min numInstances, kMaxStickyInstances
numBurstInstances = Math.max 0, numInstances - numStickyInstances
script = (minCPU) ->
# Set up queue-runner and run it in a loop until it
# gracefully powers off due to having less than 'minCPU'
# core utilization.
"""
#!/bin/sh
apt-get update
apt-get install -y nodejs npm make gcc g++ git
npm install -g coffee-script aws-sdk async async-cache
ln -s /usr/bin/nodejs /usr/bin/node
export NODE_PATH=/usr/local/lib/node_modules
export AWS_REGION=#{ AWS.config.region }
export HQZ_MIN_CPU=#{ minCPU }
git clone https://github.com/scanlime/zenphoton.git
cd zenphoton/hqz
make
until ./queue-runner.coffee; do true; done
poweroff
"""
requestInstances = (minCPU, num, cb) ->
return cb null, {} if num <= 0
ec2.requestSpotInstances
SpotPrice: kSpotPrice
InstanceCount: num
Type: "one-time"
LaunchSpecification:
ImageId: kImageId
InstanceType: kInstanceType
IamInstanceProfile:
Name: "#{kRoleName}-instance"
UserData:
Buffer(script(minCPU)).toString('base64')
# Tag each spot request
(error, data) ->
return cb error if error
requests = ( spot.SpotInstanceRequestId for spot in data.SpotInstanceRequests )
log ' ' + JSON.stringify requests
ec2.createTags
Resources: requests
Tags: kInstanceTags
cb
assumeRolePolicy =
Version: "2012-10-17"
Statement: [
Effect: "Allow"
Principal:
Service: [ "ec2.amazonaws.com" ]
Action: [ "sts:AssumeRole" ]
]
policyDocument =
Statement: [
{
Action: [ "s3:*" ]
Effect: "Allow"
Resource: [ "arn:aws:s3:::#{kBucketName}/*" ]
}, {
Action: [
"sqs:ChangeMessageVisibility"
"sqs:CreateQueue"
"sqs:DeleteMessage"
"sqs:ReceiveMessage"
"sqs:SendMessage"
]
Effect: "Allow"
Resource: [ "*" ]
}
]
async.waterfall [
# Create a security role for our new instances, if it doesn't already exist
(cb) ->
log "Setting up security role with S3 bucket #{kBucketName}"
iam.createRole
RoleName: kRoleName
AssumeRolePolicyDocument: JSON.stringify assumeRolePolicy
(error, data) ->
return cb null, {} if error and error.code == 'EntityAlreadyExists'
cb error, data
(data, cb) ->
log "Setting up role policy"
iam.putRolePolicy
RoleName: kRoleName
PolicyName: "#{kRoleName}-policy"
PolicyDocument: JSON.stringify policyDocument
cb
(data, cb) ->
log "Creating instance profile"
iam.createInstanceProfile
InstanceProfileName: "#{kRoleName}-instance"
(error, data) ->
return cb null, {} if error and error.code == 'EntityAlreadyExists'
cb error, data
(data, cb) ->
log "Adding role to instance profile"
iam.addRoleToInstanceProfile
InstanceProfileName: "#{kRoleName}-instance"
RoleName: kRoleName
(error, data) ->
return cb null, {} if error and error.code == 'LimitExceeded'
cb error, data
(data, cb) ->
log "Requesting sticky spot instances"
requestInstances 0.001, numStickyInstances, cb
(data, cb) ->
log "Requesting burst spot instances"
requestInstances 0.5, numBurstInstances, cb
], (error, data) ->
return log util.inspect error if error
log "Cluster starting up!"
| 67964 | #!/usr/bin/env coffee
#
# Cluster startup script. Experimental!
#
# AWS configuration comes from the environment:
#
# AWS_ACCESS_KEY_ID
# AWS_SECRET_ACCESS_KEY
# AWS_REGION
# HQZ_BUCKET
#
# Required Node modules:
#
# npm install aws-sdk coffee-script async
#
######################################################################
#
# This file is part of HQZ, the batch renderer for Zen Photon Garden.
#
# Copyright (c) 2013 <NAME> <<EMAIL>>
#
# 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.
#
# Tweakables
kRoleName = 'hqz-node'
kSpotPrice = "0.10" # Maximum price per instance-hour
kImageId = "ami-2efa9d47" # Ubuntu 12.04 LTS, x64, us-east-1
kInstanceType = "c1.xlarge" # High-CPU instance
# Number of instances that will stay around to wait for the queue to fully empty.
# The rest of them will start exiting when they're less than 50% utilized.
kMaxStickyInstances = 1
kBucketName = process.env.HQZ_BUCKET
kInstanceTags = [ {
Key: "com.zenphoton.hqz"
Value: "node"
} ]
######################################################################
AWS = require 'aws-sdk'
async = require 'async'
util = require 'util'
iam = new AWS.IAM().client
ec2 = new AWS.EC2().client
log = (msg) -> console.log "[#{ (new Date).toJSON() }] #{msg}"
if process.argv.length != 3
console.log "usage: cluster-start <number of instances>"
process.exit 1
numInstances = process.argv[2] | 0
process.exit 0 if numInstances <= 0
numStickyInstances = Math.min numInstances, kMaxStickyInstances
numBurstInstances = Math.max 0, numInstances - numStickyInstances
script = (minCPU) ->
# Set up queue-runner and run it in a loop until it
# gracefully powers off due to having less than 'minCPU'
# core utilization.
"""
#!/bin/sh
apt-get update
apt-get install -y nodejs npm make gcc g++ git
npm install -g coffee-script aws-sdk async async-cache
ln -s /usr/bin/nodejs /usr/bin/node
export NODE_PATH=/usr/local/lib/node_modules
export AWS_REGION=#{ AWS.config.region }
export HQZ_MIN_CPU=#{ minCPU }
git clone https://github.com/scanlime/zenphoton.git
cd zenphoton/hqz
make
until ./queue-runner.coffee; do true; done
poweroff
"""
requestInstances = (minCPU, num, cb) ->
return cb null, {} if num <= 0
ec2.requestSpotInstances
SpotPrice: kSpotPrice
InstanceCount: num
Type: "one-time"
LaunchSpecification:
ImageId: kImageId
InstanceType: kInstanceType
IamInstanceProfile:
Name: "#{kRoleName}-instance"
UserData:
Buffer(script(minCPU)).toString('base64')
# Tag each spot request
(error, data) ->
return cb error if error
requests = ( spot.SpotInstanceRequestId for spot in data.SpotInstanceRequests )
log ' ' + JSON.stringify requests
ec2.createTags
Resources: requests
Tags: kInstanceTags
cb
assumeRolePolicy =
Version: "2012-10-17"
Statement: [
Effect: "Allow"
Principal:
Service: [ "ec2.amazonaws.com" ]
Action: [ "sts:AssumeRole" ]
]
policyDocument =
Statement: [
{
Action: [ "s3:*" ]
Effect: "Allow"
Resource: [ "arn:aws:s3:::#{kBucketName}/*" ]
}, {
Action: [
"sqs:ChangeMessageVisibility"
"sqs:CreateQueue"
"sqs:DeleteMessage"
"sqs:ReceiveMessage"
"sqs:SendMessage"
]
Effect: "Allow"
Resource: [ "*" ]
}
]
async.waterfall [
# Create a security role for our new instances, if it doesn't already exist
(cb) ->
log "Setting up security role with S3 bucket #{kBucketName}"
iam.createRole
RoleName: kRoleName
AssumeRolePolicyDocument: JSON.stringify assumeRolePolicy
(error, data) ->
return cb null, {} if error and error.code == 'EntityAlreadyExists'
cb error, data
(data, cb) ->
log "Setting up role policy"
iam.putRolePolicy
RoleName: kRoleName
PolicyName: "#{kRoleName}-policy"
PolicyDocument: JSON.stringify policyDocument
cb
(data, cb) ->
log "Creating instance profile"
iam.createInstanceProfile
InstanceProfileName: "#{kRoleName}-instance"
(error, data) ->
return cb null, {} if error and error.code == 'EntityAlreadyExists'
cb error, data
(data, cb) ->
log "Adding role to instance profile"
iam.addRoleToInstanceProfile
InstanceProfileName: "#{kRoleName}-instance"
RoleName: kRoleName
(error, data) ->
return cb null, {} if error and error.code == 'LimitExceeded'
cb error, data
(data, cb) ->
log "Requesting sticky spot instances"
requestInstances 0.001, numStickyInstances, cb
(data, cb) ->
log "Requesting burst spot instances"
requestInstances 0.5, numBurstInstances, cb
], (error, data) ->
return log util.inspect error if error
log "Cluster starting up!"
| true | #!/usr/bin/env coffee
#
# Cluster startup script. Experimental!
#
# AWS configuration comes from the environment:
#
# AWS_ACCESS_KEY_ID
# AWS_SECRET_ACCESS_KEY
# AWS_REGION
# HQZ_BUCKET
#
# Required Node modules:
#
# npm install aws-sdk coffee-script async
#
######################################################################
#
# This file is part of HQZ, the batch renderer for Zen Photon Garden.
#
# Copyright (c) 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
# 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.
#
# Tweakables
kRoleName = 'hqz-node'
kSpotPrice = "0.10" # Maximum price per instance-hour
kImageId = "ami-2efa9d47" # Ubuntu 12.04 LTS, x64, us-east-1
kInstanceType = "c1.xlarge" # High-CPU instance
# Number of instances that will stay around to wait for the queue to fully empty.
# The rest of them will start exiting when they're less than 50% utilized.
kMaxStickyInstances = 1
kBucketName = process.env.HQZ_BUCKET
kInstanceTags = [ {
Key: "com.zenphoton.hqz"
Value: "node"
} ]
######################################################################
AWS = require 'aws-sdk'
async = require 'async'
util = require 'util'
iam = new AWS.IAM().client
ec2 = new AWS.EC2().client
log = (msg) -> console.log "[#{ (new Date).toJSON() }] #{msg}"
if process.argv.length != 3
console.log "usage: cluster-start <number of instances>"
process.exit 1
numInstances = process.argv[2] | 0
process.exit 0 if numInstances <= 0
numStickyInstances = Math.min numInstances, kMaxStickyInstances
numBurstInstances = Math.max 0, numInstances - numStickyInstances
script = (minCPU) ->
# Set up queue-runner and run it in a loop until it
# gracefully powers off due to having less than 'minCPU'
# core utilization.
"""
#!/bin/sh
apt-get update
apt-get install -y nodejs npm make gcc g++ git
npm install -g coffee-script aws-sdk async async-cache
ln -s /usr/bin/nodejs /usr/bin/node
export NODE_PATH=/usr/local/lib/node_modules
export AWS_REGION=#{ AWS.config.region }
export HQZ_MIN_CPU=#{ minCPU }
git clone https://github.com/scanlime/zenphoton.git
cd zenphoton/hqz
make
until ./queue-runner.coffee; do true; done
poweroff
"""
requestInstances = (minCPU, num, cb) ->
return cb null, {} if num <= 0
ec2.requestSpotInstances
SpotPrice: kSpotPrice
InstanceCount: num
Type: "one-time"
LaunchSpecification:
ImageId: kImageId
InstanceType: kInstanceType
IamInstanceProfile:
Name: "#{kRoleName}-instance"
UserData:
Buffer(script(minCPU)).toString('base64')
# Tag each spot request
(error, data) ->
return cb error if error
requests = ( spot.SpotInstanceRequestId for spot in data.SpotInstanceRequests )
log ' ' + JSON.stringify requests
ec2.createTags
Resources: requests
Tags: kInstanceTags
cb
assumeRolePolicy =
Version: "2012-10-17"
Statement: [
Effect: "Allow"
Principal:
Service: [ "ec2.amazonaws.com" ]
Action: [ "sts:AssumeRole" ]
]
policyDocument =
Statement: [
{
Action: [ "s3:*" ]
Effect: "Allow"
Resource: [ "arn:aws:s3:::#{kBucketName}/*" ]
}, {
Action: [
"sqs:ChangeMessageVisibility"
"sqs:CreateQueue"
"sqs:DeleteMessage"
"sqs:ReceiveMessage"
"sqs:SendMessage"
]
Effect: "Allow"
Resource: [ "*" ]
}
]
async.waterfall [
# Create a security role for our new instances, if it doesn't already exist
(cb) ->
log "Setting up security role with S3 bucket #{kBucketName}"
iam.createRole
RoleName: kRoleName
AssumeRolePolicyDocument: JSON.stringify assumeRolePolicy
(error, data) ->
return cb null, {} if error and error.code == 'EntityAlreadyExists'
cb error, data
(data, cb) ->
log "Setting up role policy"
iam.putRolePolicy
RoleName: kRoleName
PolicyName: "#{kRoleName}-policy"
PolicyDocument: JSON.stringify policyDocument
cb
(data, cb) ->
log "Creating instance profile"
iam.createInstanceProfile
InstanceProfileName: "#{kRoleName}-instance"
(error, data) ->
return cb null, {} if error and error.code == 'EntityAlreadyExists'
cb error, data
(data, cb) ->
log "Adding role to instance profile"
iam.addRoleToInstanceProfile
InstanceProfileName: "#{kRoleName}-instance"
RoleName: kRoleName
(error, data) ->
return cb null, {} if error and error.code == 'LimitExceeded'
cb error, data
(data, cb) ->
log "Requesting sticky spot instances"
requestInstances 0.001, numStickyInstances, cb
(data, cb) ->
log "Requesting burst spot instances"
requestInstances 0.5, numBurstInstances, cb
], (error, data) ->
return log util.inspect error if error
log "Cluster starting up!"
|
[
{
"context": "###\ncontext.coffee\nCopyright (C) 2014 ender xu <xuender@gmail.com>\n\nDistributed under terms of t",
"end": 46,
"score": 0.9996089339256287,
"start": 38,
"tag": "NAME",
"value": "ender xu"
},
{
"context": "###\ncontext.coffee\nCopyright (C) 2014 ender xu <xuender@gmai... | src/mate/context.coffee | roceys/cm | 248 | ###
context.coffee
Copyright (C) 2014 ender xu <xuender@gmail.com>
Distributed under terms of the MIT license.
###
s_x = 0
s_y = 0
if 's_b' not of window
window.s_b = true
document.addEventListener('dragstart', (e)->
s_x = e.screenX
s_y = e.screenY
, false)
document.addEventListener('dragover', (e)->
if e.toElement.tagName == 'INPUT' or e.toElement.tagName == 'TEXTAREA'
return true
if e.preventDefault
e.preventDefault()
false
, false)
document.addEventListener('drop', (e)->
if e.toElement.tagName == 'INPUT' or e.toElement.tagName == 'TEXTAREA'
return true
if e.preventDefault
e.preventDefault()
x = 1
if e.screenX < s_x
x = -1
y = 1
if e.screenY < s_y
y = -1
data = e.dataTransfer.getData('URL')
msg = 'url'
if !data
data = e.dataTransfer.getData('Text')
msg = 'txt'
if data
chrome.runtime.sendMessage('phlfmkfpmphogkomddckmggcfpmfchpn',
cmd: msg
values: data
x: x
y: y
)
false
, true)
| 159444 | ###
context.coffee
Copyright (C) 2014 <NAME> <<EMAIL>>
Distributed under terms of the MIT license.
###
s_x = 0
s_y = 0
if 's_b' not of window
window.s_b = true
document.addEventListener('dragstart', (e)->
s_x = e.screenX
s_y = e.screenY
, false)
document.addEventListener('dragover', (e)->
if e.toElement.tagName == 'INPUT' or e.toElement.tagName == 'TEXTAREA'
return true
if e.preventDefault
e.preventDefault()
false
, false)
document.addEventListener('drop', (e)->
if e.toElement.tagName == 'INPUT' or e.toElement.tagName == 'TEXTAREA'
return true
if e.preventDefault
e.preventDefault()
x = 1
if e.screenX < s_x
x = -1
y = 1
if e.screenY < s_y
y = -1
data = e.dataTransfer.getData('URL')
msg = 'url'
if !data
data = e.dataTransfer.getData('Text')
msg = 'txt'
if data
chrome.runtime.sendMessage('phlfmkfpmphogkomddckmggcfpmfchpn',
cmd: msg
values: data
x: x
y: y
)
false
, true)
| true | ###
context.coffee
Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
Distributed under terms of the MIT license.
###
s_x = 0
s_y = 0
if 's_b' not of window
window.s_b = true
document.addEventListener('dragstart', (e)->
s_x = e.screenX
s_y = e.screenY
, false)
document.addEventListener('dragover', (e)->
if e.toElement.tagName == 'INPUT' or e.toElement.tagName == 'TEXTAREA'
return true
if e.preventDefault
e.preventDefault()
false
, false)
document.addEventListener('drop', (e)->
if e.toElement.tagName == 'INPUT' or e.toElement.tagName == 'TEXTAREA'
return true
if e.preventDefault
e.preventDefault()
x = 1
if e.screenX < s_x
x = -1
y = 1
if e.screenY < s_y
y = -1
data = e.dataTransfer.getData('URL')
msg = 'url'
if !data
data = e.dataTransfer.getData('Text')
msg = 'txt'
if data
chrome.runtime.sendMessage('phlfmkfpmphogkomddckmggcfpmfchpn',
cmd: msg
values: data
x: x
y: y
)
false
, true)
|
[
{
"context": "ckbone.$ = $\n\nwindow.gon = {\n user: {\n name: \"Luccas Marks\"\n email: \"luccas@houzel.com\"\n admin: false\n",
"end": 202,
"score": 0.9998835325241089,
"start": 190,
"tag": "NAME",
"value": "Luccas Marks"
},
{
"context": " {\n user: {\n name: \"Luccas... | spec/javascripts/spec_helper.coffee | houzelio/houzel | 2 | import defaultLocale from "../../config/locales/javascript/en.yml"
import { t } from 'javascripts/core/helpers/i18n'
import 'bootstrap'
Backbone.$ = $
window.gon = {
user: {
name: "Luccas Marks"
email: "luccas@houzel.com"
admin: false
}
locale: "en"
}
phrases = defaultLocale.json['en'].javascripts
t().load(phrases: phrases)
requireAll = (requireContext) ->
requireContext.keys().forEach(requireContext)
requireAll(require.context('./', true, /^((?!spec_helper).)*\.coffee?$/))
| 30550 | import defaultLocale from "../../config/locales/javascript/en.yml"
import { t } from 'javascripts/core/helpers/i18n'
import 'bootstrap'
Backbone.$ = $
window.gon = {
user: {
name: "<NAME>"
email: "<EMAIL>"
admin: false
}
locale: "en"
}
phrases = defaultLocale.json['en'].javascripts
t().load(phrases: phrases)
requireAll = (requireContext) ->
requireContext.keys().forEach(requireContext)
requireAll(require.context('./', true, /^((?!spec_helper).)*\.coffee?$/))
| true | import defaultLocale from "../../config/locales/javascript/en.yml"
import { t } from 'javascripts/core/helpers/i18n'
import 'bootstrap'
Backbone.$ = $
window.gon = {
user: {
name: "PI:NAME:<NAME>END_PI"
email: "PI:EMAIL:<EMAIL>END_PI"
admin: false
}
locale: "en"
}
phrases = defaultLocale.json['en'].javascripts
t().load(phrases: phrases)
requireAll = (requireContext) ->
requireContext.keys().forEach(requireContext)
requireAll(require.context('./', true, /^((?!spec_helper).)*\.coffee?$/))
|
[
{
"context": "t.Injector.resolve('planStore').model,\n id: 'ABC123',\n name: 'Q1',\n theme: ' \\n'\n\n @the",
"end": 1930,
"score": 0.7103622555732727,
"start": 1924,
"tag": "KEY",
"value": "ABC123"
},
{
"context": "t.Injector.resolve('planStore').model,\n id:... | test/spec/roadmapplanningboard/ThemeHeaderSpec.coffee | RallyHackathon/app-catalog | 1 | Ext = window.Ext4 || window.Ext
Ext.require [
'Rally.test.apps.roadmapplanningboard.helper.TestDependencyHelper'
'Rally.apps.roadmapplanningboard.ThemeHeader'
'Rally.apps.roadmapplanningboard.PlanningBoard'
]
describe 'Rally.apps.roadmapplanningboard.ThemeHeader', ->
helpers
createCardboard: (config) ->
@cardboard = Ext.create 'Rally.apps.roadmapplanningboard.PlanningBoard',
roadmapId: '413617ecef8623df1391fabc'
_retrieveLowestLevelPI: (callback) -> callback.call(@, Rally.test.mock.ModelObjectMother.getRecord('typedefinition', {values: { TypePath : 'PortfolioItem/Feature' }}))
renderTo: 'testDiv'
@waitForComponentReady @cardboard
beforeEach ->
@ajax.whenQuerying('PortfolioItem/Feature').respondWith([])
Rally.test.apps.roadmapplanningboard.helper.TestDependencyHelper.loadDependencies()
afterEach ->
@cardboard?.destroy()
Deft.Injector.reset()
@themeHeader?.destroy()
it 'displays theme from planModel', ->
planRecord = Ext.create Deft.Injector.resolve('planStore').model,
id: 'ABC123',
name: 'Q1',
theme: 'Take over the world!'
@themeHeader = Ext.create 'Rally.apps.roadmapplanningboard.ThemeHeader',
record: planRecord
@themeHeader.render Ext.getBody()
expect(@themeHeader.el.dom.innerHTML.indexOf(planRecord.get('theme'))).not.toBe -1
it 'displays "Add Theme" when model theme is blank', ->
planRecord = Ext.create Deft.Injector.resolve('planStore').model,
id: 'ABC123',
name: 'Q1',
theme: undefined
@themeHeader = Ext.create 'Rally.apps.roadmapplanningboard.ThemeHeader',
record: planRecord
@themeHeader.render Ext.getBody()
expect(@themeHeader.el.dom.innerHTML.indexOf('Add theme')).not.toBe -1
it 'displays "Add Theme" when model theme is whitespace', ->
planRecord = Ext.create Deft.Injector.resolve('planStore').model,
id: 'ABC123',
name: 'Q1',
theme: ' \n'
@themeHeader = Ext.create 'Rally.apps.roadmapplanningboard.ThemeHeader',
record: planRecord
@themeHeader.render Ext.getBody()
expect(@themeHeader.el.dom.innerHTML.indexOf('Add theme')).not.toBe -1
it 'should trim whitespace from theme', ->
planRecord = Ext.create Deft.Injector.resolve('planStore').model,
id: 'ABC123',
name: 'Q1',
theme: 'My Theme \n'
@themeHeader = Ext.create 'Rally.apps.roadmapplanningboard.ThemeHeader',
record: planRecord
@themeHeader.render Ext.getBody()
expect(@themeHeader.el.dom.innerHTML.indexOf('My Theme')).not.toBe -1
expect(@themeHeader.el.dom.innerHTML.indexOf('My Theme ')).toBe -1
it 'should find containing cardboard with getCardboardComponent', ->
@createCardboard().then =>
themeHeader = @cardboard.getColumns()[1].getColumnHeader().query('roadmapthemeheader')[0]
expect(themeHeader.getCardboardComponent()).toBe(@cardboard)
it 'should fire headersizechanged when edit mode textarea resizes based on content', ->
@createCardboard().then =>
# Allows us to verify whether headersizechanged was fired
resizeStub = sinon.stub()
@cardboard.on 'headersizechanged', resizeStub
themeHeader = @cardboard.getColumns()[1].getColumnHeader().query('roadmapthemeheader')[0]
themeHeader.themeContainer.goToEditMode()
resizeStub.reset()
textField = themeHeader.themeContainer.down('textareafield')
textField.setValue('Updated theme\nWith enough more\nlines that we are sure it will\nresize itself\nand tell the header to resize\nfor multi-line content')
expect(resizeStub).toHaveBeenCalledOnce()
resizeStub.reset()
textField.setValue('One line\nAnd another')
expect(resizeStub).toHaveBeenCalledOnce()
it 'should save the theme when the theme is changed', ->
@createCardboard().then =>
themeHeader = @cardboard.getColumns()[1].getColumnHeader().down('roadmapthemeheader').down('rallydetailfieldcontainer')
record = themeHeader.record
@saveStub = @stub record, 'save'
themeHeader.goToEditMode()
themeHeader.editor.setValue 'My Theme'
themeHeader.editor.blur()
themeHeader.goToViewMode()
expect(@saveStub).toHaveBeenCalledOnce()
expect(record.get('theme')).toBe 'My Theme'
it 'should fire headersizechanged when editor mode switches back to view mode', ->
@createCardboard().then =>
# TODO - srly, wtf?
themeHeader = @cardboard.getColumns()[1].getColumnHeader().query('roadmapthemeheader')[0]
themeHeader.themeContainer.goToEditMode()
textField = themeHeader.themeContainer.down('textareafield')
textField.setValue 'Updated theme'
# Allows us to verify whether headersizechanged was fired
resizeStub = sinon.stub()
@cardboard.on 'headersizechanged', resizeStub
# fieldContainer's refresh uses a defer - use afterDraw stub to push our checks and cleanup past the defer
afterDrawStub = sinon.stub()
themeHeader.themeContainer.afterDraw = afterDrawStub
textField.blur()
@once(
condition: ->
afterDrawStub.called
).then =>
# In IE8, resizeStub may have been called 1 or 2 times (timing-dependent), so just verify it was called
expect(resizeStub.called).toBeTruthy()
it 'should not fire headersizechanged until editor has been deleted', ->
@createCardboard().then =>
themeHeader = @cardboard.getColumns()[1].getColumnHeader().query('roadmapthemeheader')[0]
themeHeader.themeContainer.goToEditMode()
textField = themeHeader.themeContainer.down('textareafield')
textField.setValue 'Updated theme'
# Sorry! -- expectation lexically ordered before action so that we can verify precise timing of setEditMode() and headersizechanged
@cardboard.on 'headersizechanged', ->
expect(themeHeader.themeContainer.getEditMode()).toBeFalsy()
# fieldContainer's refresh uses a defer - use afterDraw stub to push our checks and cleanup past the defer
afterDrawStub = sinon.stub()
themeHeader.themeContainer.afterDraw = afterDrawStub
textField.blur()
@once(
condition: ->
afterDrawStub.called
).then =>
@cardboard.destroy()
| 54692 | Ext = window.Ext4 || window.Ext
Ext.require [
'Rally.test.apps.roadmapplanningboard.helper.TestDependencyHelper'
'Rally.apps.roadmapplanningboard.ThemeHeader'
'Rally.apps.roadmapplanningboard.PlanningBoard'
]
describe 'Rally.apps.roadmapplanningboard.ThemeHeader', ->
helpers
createCardboard: (config) ->
@cardboard = Ext.create 'Rally.apps.roadmapplanningboard.PlanningBoard',
roadmapId: '413617ecef8623df1391fabc'
_retrieveLowestLevelPI: (callback) -> callback.call(@, Rally.test.mock.ModelObjectMother.getRecord('typedefinition', {values: { TypePath : 'PortfolioItem/Feature' }}))
renderTo: 'testDiv'
@waitForComponentReady @cardboard
beforeEach ->
@ajax.whenQuerying('PortfolioItem/Feature').respondWith([])
Rally.test.apps.roadmapplanningboard.helper.TestDependencyHelper.loadDependencies()
afterEach ->
@cardboard?.destroy()
Deft.Injector.reset()
@themeHeader?.destroy()
it 'displays theme from planModel', ->
planRecord = Ext.create Deft.Injector.resolve('planStore').model,
id: 'ABC123',
name: 'Q1',
theme: 'Take over the world!'
@themeHeader = Ext.create 'Rally.apps.roadmapplanningboard.ThemeHeader',
record: planRecord
@themeHeader.render Ext.getBody()
expect(@themeHeader.el.dom.innerHTML.indexOf(planRecord.get('theme'))).not.toBe -1
it 'displays "Add Theme" when model theme is blank', ->
planRecord = Ext.create Deft.Injector.resolve('planStore').model,
id: 'ABC123',
name: 'Q1',
theme: undefined
@themeHeader = Ext.create 'Rally.apps.roadmapplanningboard.ThemeHeader',
record: planRecord
@themeHeader.render Ext.getBody()
expect(@themeHeader.el.dom.innerHTML.indexOf('Add theme')).not.toBe -1
it 'displays "Add Theme" when model theme is whitespace', ->
planRecord = Ext.create Deft.Injector.resolve('planStore').model,
id: '<KEY>',
name: 'Q1',
theme: ' \n'
@themeHeader = Ext.create 'Rally.apps.roadmapplanningboard.ThemeHeader',
record: planRecord
@themeHeader.render Ext.getBody()
expect(@themeHeader.el.dom.innerHTML.indexOf('Add theme')).not.toBe -1
it 'should trim whitespace from theme', ->
planRecord = Ext.create Deft.Injector.resolve('planStore').model,
id: '<KEY>',
name: 'Q1',
theme: 'My Theme \n'
@themeHeader = Ext.create 'Rally.apps.roadmapplanningboard.ThemeHeader',
record: planRecord
@themeHeader.render Ext.getBody()
expect(@themeHeader.el.dom.innerHTML.indexOf('My Theme')).not.toBe -1
expect(@themeHeader.el.dom.innerHTML.indexOf('My Theme ')).toBe -1
it 'should find containing cardboard with getCardboardComponent', ->
@createCardboard().then =>
themeHeader = @cardboard.getColumns()[1].getColumnHeader().query('roadmapthemeheader')[0]
expect(themeHeader.getCardboardComponent()).toBe(@cardboard)
it 'should fire headersizechanged when edit mode textarea resizes based on content', ->
@createCardboard().then =>
# Allows us to verify whether headersizechanged was fired
resizeStub = sinon.stub()
@cardboard.on 'headersizechanged', resizeStub
themeHeader = @cardboard.getColumns()[1].getColumnHeader().query('roadmapthemeheader')[0]
themeHeader.themeContainer.goToEditMode()
resizeStub.reset()
textField = themeHeader.themeContainer.down('textareafield')
textField.setValue('Updated theme\nWith enough more\nlines that we are sure it will\nresize itself\nand tell the header to resize\nfor multi-line content')
expect(resizeStub).toHaveBeenCalledOnce()
resizeStub.reset()
textField.setValue('One line\nAnd another')
expect(resizeStub).toHaveBeenCalledOnce()
it 'should save the theme when the theme is changed', ->
@createCardboard().then =>
themeHeader = @cardboard.getColumns()[1].getColumnHeader().down('roadmapthemeheader').down('rallydetailfieldcontainer')
record = themeHeader.record
@saveStub = @stub record, 'save'
themeHeader.goToEditMode()
themeHeader.editor.setValue 'My Theme'
themeHeader.editor.blur()
themeHeader.goToViewMode()
expect(@saveStub).toHaveBeenCalledOnce()
expect(record.get('theme')).toBe 'My Theme'
it 'should fire headersizechanged when editor mode switches back to view mode', ->
@createCardboard().then =>
# TODO - srly, wtf?
themeHeader = @cardboard.getColumns()[1].getColumnHeader().query('roadmapthemeheader')[0]
themeHeader.themeContainer.goToEditMode()
textField = themeHeader.themeContainer.down('textareafield')
textField.setValue 'Updated theme'
# Allows us to verify whether headersizechanged was fired
resizeStub = sinon.stub()
@cardboard.on 'headersizechanged', resizeStub
# fieldContainer's refresh uses a defer - use afterDraw stub to push our checks and cleanup past the defer
afterDrawStub = sinon.stub()
themeHeader.themeContainer.afterDraw = afterDrawStub
textField.blur()
@once(
condition: ->
afterDrawStub.called
).then =>
# In IE8, resizeStub may have been called 1 or 2 times (timing-dependent), so just verify it was called
expect(resizeStub.called).toBeTruthy()
it 'should not fire headersizechanged until editor has been deleted', ->
@createCardboard().then =>
themeHeader = @cardboard.getColumns()[1].getColumnHeader().query('roadmapthemeheader')[0]
themeHeader.themeContainer.goToEditMode()
textField = themeHeader.themeContainer.down('textareafield')
textField.setValue 'Updated theme'
# Sorry! -- expectation lexically ordered before action so that we can verify precise timing of setEditMode() and headersizechanged
@cardboard.on 'headersizechanged', ->
expect(themeHeader.themeContainer.getEditMode()).toBeFalsy()
# fieldContainer's refresh uses a defer - use afterDraw stub to push our checks and cleanup past the defer
afterDrawStub = sinon.stub()
themeHeader.themeContainer.afterDraw = afterDrawStub
textField.blur()
@once(
condition: ->
afterDrawStub.called
).then =>
@cardboard.destroy()
| true | Ext = window.Ext4 || window.Ext
Ext.require [
'Rally.test.apps.roadmapplanningboard.helper.TestDependencyHelper'
'Rally.apps.roadmapplanningboard.ThemeHeader'
'Rally.apps.roadmapplanningboard.PlanningBoard'
]
describe 'Rally.apps.roadmapplanningboard.ThemeHeader', ->
helpers
createCardboard: (config) ->
@cardboard = Ext.create 'Rally.apps.roadmapplanningboard.PlanningBoard',
roadmapId: '413617ecef8623df1391fabc'
_retrieveLowestLevelPI: (callback) -> callback.call(@, Rally.test.mock.ModelObjectMother.getRecord('typedefinition', {values: { TypePath : 'PortfolioItem/Feature' }}))
renderTo: 'testDiv'
@waitForComponentReady @cardboard
beforeEach ->
@ajax.whenQuerying('PortfolioItem/Feature').respondWith([])
Rally.test.apps.roadmapplanningboard.helper.TestDependencyHelper.loadDependencies()
afterEach ->
@cardboard?.destroy()
Deft.Injector.reset()
@themeHeader?.destroy()
it 'displays theme from planModel', ->
planRecord = Ext.create Deft.Injector.resolve('planStore').model,
id: 'ABC123',
name: 'Q1',
theme: 'Take over the world!'
@themeHeader = Ext.create 'Rally.apps.roadmapplanningboard.ThemeHeader',
record: planRecord
@themeHeader.render Ext.getBody()
expect(@themeHeader.el.dom.innerHTML.indexOf(planRecord.get('theme'))).not.toBe -1
it 'displays "Add Theme" when model theme is blank', ->
planRecord = Ext.create Deft.Injector.resolve('planStore').model,
id: 'ABC123',
name: 'Q1',
theme: undefined
@themeHeader = Ext.create 'Rally.apps.roadmapplanningboard.ThemeHeader',
record: planRecord
@themeHeader.render Ext.getBody()
expect(@themeHeader.el.dom.innerHTML.indexOf('Add theme')).not.toBe -1
it 'displays "Add Theme" when model theme is whitespace', ->
planRecord = Ext.create Deft.Injector.resolve('planStore').model,
id: 'PI:KEY:<KEY>END_PI',
name: 'Q1',
theme: ' \n'
@themeHeader = Ext.create 'Rally.apps.roadmapplanningboard.ThemeHeader',
record: planRecord
@themeHeader.render Ext.getBody()
expect(@themeHeader.el.dom.innerHTML.indexOf('Add theme')).not.toBe -1
it 'should trim whitespace from theme', ->
planRecord = Ext.create Deft.Injector.resolve('planStore').model,
id: 'PI:KEY:<KEY>END_PI',
name: 'Q1',
theme: 'My Theme \n'
@themeHeader = Ext.create 'Rally.apps.roadmapplanningboard.ThemeHeader',
record: planRecord
@themeHeader.render Ext.getBody()
expect(@themeHeader.el.dom.innerHTML.indexOf('My Theme')).not.toBe -1
expect(@themeHeader.el.dom.innerHTML.indexOf('My Theme ')).toBe -1
it 'should find containing cardboard with getCardboardComponent', ->
@createCardboard().then =>
themeHeader = @cardboard.getColumns()[1].getColumnHeader().query('roadmapthemeheader')[0]
expect(themeHeader.getCardboardComponent()).toBe(@cardboard)
it 'should fire headersizechanged when edit mode textarea resizes based on content', ->
@createCardboard().then =>
# Allows us to verify whether headersizechanged was fired
resizeStub = sinon.stub()
@cardboard.on 'headersizechanged', resizeStub
themeHeader = @cardboard.getColumns()[1].getColumnHeader().query('roadmapthemeheader')[0]
themeHeader.themeContainer.goToEditMode()
resizeStub.reset()
textField = themeHeader.themeContainer.down('textareafield')
textField.setValue('Updated theme\nWith enough more\nlines that we are sure it will\nresize itself\nand tell the header to resize\nfor multi-line content')
expect(resizeStub).toHaveBeenCalledOnce()
resizeStub.reset()
textField.setValue('One line\nAnd another')
expect(resizeStub).toHaveBeenCalledOnce()
it 'should save the theme when the theme is changed', ->
@createCardboard().then =>
themeHeader = @cardboard.getColumns()[1].getColumnHeader().down('roadmapthemeheader').down('rallydetailfieldcontainer')
record = themeHeader.record
@saveStub = @stub record, 'save'
themeHeader.goToEditMode()
themeHeader.editor.setValue 'My Theme'
themeHeader.editor.blur()
themeHeader.goToViewMode()
expect(@saveStub).toHaveBeenCalledOnce()
expect(record.get('theme')).toBe 'My Theme'
it 'should fire headersizechanged when editor mode switches back to view mode', ->
@createCardboard().then =>
# TODO - srly, wtf?
themeHeader = @cardboard.getColumns()[1].getColumnHeader().query('roadmapthemeheader')[0]
themeHeader.themeContainer.goToEditMode()
textField = themeHeader.themeContainer.down('textareafield')
textField.setValue 'Updated theme'
# Allows us to verify whether headersizechanged was fired
resizeStub = sinon.stub()
@cardboard.on 'headersizechanged', resizeStub
# fieldContainer's refresh uses a defer - use afterDraw stub to push our checks and cleanup past the defer
afterDrawStub = sinon.stub()
themeHeader.themeContainer.afterDraw = afterDrawStub
textField.blur()
@once(
condition: ->
afterDrawStub.called
).then =>
# In IE8, resizeStub may have been called 1 or 2 times (timing-dependent), so just verify it was called
expect(resizeStub.called).toBeTruthy()
it 'should not fire headersizechanged until editor has been deleted', ->
@createCardboard().then =>
themeHeader = @cardboard.getColumns()[1].getColumnHeader().query('roadmapthemeheader')[0]
themeHeader.themeContainer.goToEditMode()
textField = themeHeader.themeContainer.down('textareafield')
textField.setValue 'Updated theme'
# Sorry! -- expectation lexically ordered before action so that we can verify precise timing of setEditMode() and headersizechanged
@cardboard.on 'headersizechanged', ->
expect(themeHeader.themeContainer.getEditMode()).toBeFalsy()
# fieldContainer's refresh uses a defer - use afterDraw stub to push our checks and cleanup past the defer
afterDrawStub = sinon.stub()
themeHeader.themeContainer.afterDraw = afterDrawStub
textField.blur()
@once(
condition: ->
afterDrawStub.called
).then =>
@cardboard.destroy()
|
[
{
"context": "son: {start: {c: 3,r: 0}, end: {c: 4,r: 0}, name:\"Zuchini\", color:\"#008045\"}\n subscriber: recorder",
"end": 1199,
"score": 0.9833941459655762,
"start": 1192,
"tag": "NAME",
"value": "Zuchini"
},
{
"context": ".add {start: {c: 2,r: 0}, end: {c: 2,r: 0}, nam... | test/unit/plants-test.coffee | TheSoftwareGreenhouse/ourSquareFeet | 1 | vows = require 'vows'
assert = require 'assert'
recorderMock = require('../mockjQuery.coffee').recorderMock
PlantsModule = require '../../server/public/javascript/plants.coffee'
PlantModule = require '../../server/public/javascript/plant.coffee'
assert.hasBeenCalled = (actual) ->
assert.isNotZero actual.__calls.length, "#{actual.name} was not called"
assert.wasCalledWith = (actual, arguments) ->
matches = (call for call in actual.__calls when (call.arguments[0] is arguments[0] and call.arguments[1] is arguments[1]))
assert.isNotZero matches.length, "#{actual.name} was not called with #{arguments}"
compareArguments = (arguments, predicates) ->
for argument in arguments
for predicate in predicates
{argument, predicate}
assert.wasCalledWithArguments = (actual, predicates) ->
matches = (call for call in actual.__calls when (compareArguments(call.arguments, predicates)))
assert.isNotZero matches.length, "#{actual} was not called with argumenst that matched"
vows.describe('Plants').addBatch({
'when a new Plants collection is created': {
topic: () ->
topic = {
mocks: {
plantJson: {start: {c: 3,r: 0}, end: {c: 4,r: 0}, name:"Zuchini", color:"#008045"}
subscriber: recorderMock "callOnAdd", "callOnDelete", "callOnPlantChanged"
}
sut: new PlantsModule.Plants()
}
topic.mocks.plant = new PlantModule.Plant(topic.mocks.plantJson)
topic
'then the collection has an add method': (topic) ->
assert.isFunction topic.sut.add
'then the collection has a existsAtCoord method': (topic) ->
assert.isFunction topic.sut.existsAtCoord
'then the collection has a remove method': (topic) ->
assert.isFunction topic.sut.remove
'then the collection has an updatePlantName method': (topic) ->
assert.isFunction topic.sut.updatePlantName
'then the collection has an onPlantChanged method': (topic) ->
assert.isFunction topic.sut.onPlantChanged
'and a plant is added': {
topic: (topic) ->
topic.sut = new PlantsModule.Plants()
topic.sut.subscribe "new", topic.mocks.subscriber.callOnAdd
topic.sut.add topic.mocks.plantJson
topic
'then the plant should exists at both start and end': (topic) ->
assert.isTrue topic.sut.existsAtCoord({c:3, r:0})
assert.isTrue topic.sut.existsAtCoord({c:4, r:0})
'then the plants collection raised the new event': (topic) ->
assert.hasBeenCalled topic.mocks.subscriber.callOnAdd
"and the plant's name is updated": {
topic: (topic) ->
topic.sut.add topic.mocks.plantJson
topic.sut.onPlantChanged topic.mocks.subscriber.callOnPlantChanged
topic.sut.updatePlantName topic.mocks.plant, "Milkwood"
topic
'then the plant still exists': (topic) ->
assert.isTrue topic.sut.existsAtCoord({c:3, r:0})
'then the plants collection raises the Plant Changed event': (topic) ->
assert.hasBeenCalled topic.mocks.subscriber.callOnPlantChanged
'then the plant raised has the correct name': (topic) ->
assert.equal topic.mocks.subscriber.callOnPlantChanged.__calls[0].arguments[0].name, "Milkwood"
}
}
}
}).addBatch({
'when the Plants collection is populated': {
topic: () ->
topic = {
mocks: {
subscriber: recorderMock "callOnDelete"
}
sut: new PlantsModule.Plants()
}
topic.sut.add {start: {c: 0,r: 0}, end: {c: 0,r: 0}, name:"Corn", color:"#008045"}
topic.sut.add {start: {c: 1,r: 0}, end: {c: 1,r: 0}, name:"Peas", color:"#008045"}
topic.sut.add {start: {c: 2,r: 0}, end: {c: 2,r: 0}, name:"Bananas", color:"#008045"}
topic
'and the plant is removed': {
topic: (topic) ->
topic.sut.subscribe "deleted", topic.mocks.subscriber.callOnDelete
topic.sut.remove {c:0, r:0}
topic
'then the plant should not exist at the start or end': (topic) ->
assert.isFalse topic.sut.existsAtCoord({c:0, r:0})
'then the plants collection raises a deleted event': (topic) ->
assert.hasBeenCalled topic.mocks.subscriber.callOnDelete
'then the correct plant is deleted': (topic) ->
assert.equal topic.mocks.subscriber.callOnDelete.__calls[0].arguments[0].name, "Corn"
#assert.wasCalledWith topic.mocks.subscriber.callOnDelete, [topic.mocks.plant]
}
}
}).export module
| 181001 | vows = require 'vows'
assert = require 'assert'
recorderMock = require('../mockjQuery.coffee').recorderMock
PlantsModule = require '../../server/public/javascript/plants.coffee'
PlantModule = require '../../server/public/javascript/plant.coffee'
assert.hasBeenCalled = (actual) ->
assert.isNotZero actual.__calls.length, "#{actual.name} was not called"
assert.wasCalledWith = (actual, arguments) ->
matches = (call for call in actual.__calls when (call.arguments[0] is arguments[0] and call.arguments[1] is arguments[1]))
assert.isNotZero matches.length, "#{actual.name} was not called with #{arguments}"
compareArguments = (arguments, predicates) ->
for argument in arguments
for predicate in predicates
{argument, predicate}
assert.wasCalledWithArguments = (actual, predicates) ->
matches = (call for call in actual.__calls when (compareArguments(call.arguments, predicates)))
assert.isNotZero matches.length, "#{actual} was not called with argumenst that matched"
vows.describe('Plants').addBatch({
'when a new Plants collection is created': {
topic: () ->
topic = {
mocks: {
plantJson: {start: {c: 3,r: 0}, end: {c: 4,r: 0}, name:"<NAME>", color:"#008045"}
subscriber: recorderMock "callOnAdd", "callOnDelete", "callOnPlantChanged"
}
sut: new PlantsModule.Plants()
}
topic.mocks.plant = new PlantModule.Plant(topic.mocks.plantJson)
topic
'then the collection has an add method': (topic) ->
assert.isFunction topic.sut.add
'then the collection has a existsAtCoord method': (topic) ->
assert.isFunction topic.sut.existsAtCoord
'then the collection has a remove method': (topic) ->
assert.isFunction topic.sut.remove
'then the collection has an updatePlantName method': (topic) ->
assert.isFunction topic.sut.updatePlantName
'then the collection has an onPlantChanged method': (topic) ->
assert.isFunction topic.sut.onPlantChanged
'and a plant is added': {
topic: (topic) ->
topic.sut = new PlantsModule.Plants()
topic.sut.subscribe "new", topic.mocks.subscriber.callOnAdd
topic.sut.add topic.mocks.plantJson
topic
'then the plant should exists at both start and end': (topic) ->
assert.isTrue topic.sut.existsAtCoord({c:3, r:0})
assert.isTrue topic.sut.existsAtCoord({c:4, r:0})
'then the plants collection raised the new event': (topic) ->
assert.hasBeenCalled topic.mocks.subscriber.callOnAdd
"and the plant's name is updated": {
topic: (topic) ->
topic.sut.add topic.mocks.plantJson
topic.sut.onPlantChanged topic.mocks.subscriber.callOnPlantChanged
topic.sut.updatePlantName topic.mocks.plant, "Milkwood"
topic
'then the plant still exists': (topic) ->
assert.isTrue topic.sut.existsAtCoord({c:3, r:0})
'then the plants collection raises the Plant Changed event': (topic) ->
assert.hasBeenCalled topic.mocks.subscriber.callOnPlantChanged
'then the plant raised has the correct name': (topic) ->
assert.equal topic.mocks.subscriber.callOnPlantChanged.__calls[0].arguments[0].name, "Milkwood"
}
}
}
}).addBatch({
'when the Plants collection is populated': {
topic: () ->
topic = {
mocks: {
subscriber: recorderMock "callOnDelete"
}
sut: new PlantsModule.Plants()
}
topic.sut.add {start: {c: 0,r: 0}, end: {c: 0,r: 0}, name:"Corn", color:"#008045"}
topic.sut.add {start: {c: 1,r: 0}, end: {c: 1,r: 0}, name:"Peas", color:"#008045"}
topic.sut.add {start: {c: 2,r: 0}, end: {c: 2,r: 0}, name:"<NAME>", color:"#008045"}
topic
'and the plant is removed': {
topic: (topic) ->
topic.sut.subscribe "deleted", topic.mocks.subscriber.callOnDelete
topic.sut.remove {c:0, r:0}
topic
'then the plant should not exist at the start or end': (topic) ->
assert.isFalse topic.sut.existsAtCoord({c:0, r:0})
'then the plants collection raises a deleted event': (topic) ->
assert.hasBeenCalled topic.mocks.subscriber.callOnDelete
'then the correct plant is deleted': (topic) ->
assert.equal topic.mocks.subscriber.callOnDelete.__calls[0].arguments[0].name, "Corn"
#assert.wasCalledWith topic.mocks.subscriber.callOnDelete, [topic.mocks.plant]
}
}
}).export module
| true | vows = require 'vows'
assert = require 'assert'
recorderMock = require('../mockjQuery.coffee').recorderMock
PlantsModule = require '../../server/public/javascript/plants.coffee'
PlantModule = require '../../server/public/javascript/plant.coffee'
assert.hasBeenCalled = (actual) ->
assert.isNotZero actual.__calls.length, "#{actual.name} was not called"
assert.wasCalledWith = (actual, arguments) ->
matches = (call for call in actual.__calls when (call.arguments[0] is arguments[0] and call.arguments[1] is arguments[1]))
assert.isNotZero matches.length, "#{actual.name} was not called with #{arguments}"
compareArguments = (arguments, predicates) ->
for argument in arguments
for predicate in predicates
{argument, predicate}
assert.wasCalledWithArguments = (actual, predicates) ->
matches = (call for call in actual.__calls when (compareArguments(call.arguments, predicates)))
assert.isNotZero matches.length, "#{actual} was not called with argumenst that matched"
vows.describe('Plants').addBatch({
'when a new Plants collection is created': {
topic: () ->
topic = {
mocks: {
plantJson: {start: {c: 3,r: 0}, end: {c: 4,r: 0}, name:"PI:NAME:<NAME>END_PI", color:"#008045"}
subscriber: recorderMock "callOnAdd", "callOnDelete", "callOnPlantChanged"
}
sut: new PlantsModule.Plants()
}
topic.mocks.plant = new PlantModule.Plant(topic.mocks.plantJson)
topic
'then the collection has an add method': (topic) ->
assert.isFunction topic.sut.add
'then the collection has a existsAtCoord method': (topic) ->
assert.isFunction topic.sut.existsAtCoord
'then the collection has a remove method': (topic) ->
assert.isFunction topic.sut.remove
'then the collection has an updatePlantName method': (topic) ->
assert.isFunction topic.sut.updatePlantName
'then the collection has an onPlantChanged method': (topic) ->
assert.isFunction topic.sut.onPlantChanged
'and a plant is added': {
topic: (topic) ->
topic.sut = new PlantsModule.Plants()
topic.sut.subscribe "new", topic.mocks.subscriber.callOnAdd
topic.sut.add topic.mocks.plantJson
topic
'then the plant should exists at both start and end': (topic) ->
assert.isTrue topic.sut.existsAtCoord({c:3, r:0})
assert.isTrue topic.sut.existsAtCoord({c:4, r:0})
'then the plants collection raised the new event': (topic) ->
assert.hasBeenCalled topic.mocks.subscriber.callOnAdd
"and the plant's name is updated": {
topic: (topic) ->
topic.sut.add topic.mocks.plantJson
topic.sut.onPlantChanged topic.mocks.subscriber.callOnPlantChanged
topic.sut.updatePlantName topic.mocks.plant, "Milkwood"
topic
'then the plant still exists': (topic) ->
assert.isTrue topic.sut.existsAtCoord({c:3, r:0})
'then the plants collection raises the Plant Changed event': (topic) ->
assert.hasBeenCalled topic.mocks.subscriber.callOnPlantChanged
'then the plant raised has the correct name': (topic) ->
assert.equal topic.mocks.subscriber.callOnPlantChanged.__calls[0].arguments[0].name, "Milkwood"
}
}
}
}).addBatch({
'when the Plants collection is populated': {
topic: () ->
topic = {
mocks: {
subscriber: recorderMock "callOnDelete"
}
sut: new PlantsModule.Plants()
}
topic.sut.add {start: {c: 0,r: 0}, end: {c: 0,r: 0}, name:"Corn", color:"#008045"}
topic.sut.add {start: {c: 1,r: 0}, end: {c: 1,r: 0}, name:"Peas", color:"#008045"}
topic.sut.add {start: {c: 2,r: 0}, end: {c: 2,r: 0}, name:"PI:NAME:<NAME>END_PI", color:"#008045"}
topic
'and the plant is removed': {
topic: (topic) ->
topic.sut.subscribe "deleted", topic.mocks.subscriber.callOnDelete
topic.sut.remove {c:0, r:0}
topic
'then the plant should not exist at the start or end': (topic) ->
assert.isFalse topic.sut.existsAtCoord({c:0, r:0})
'then the plants collection raises a deleted event': (topic) ->
assert.hasBeenCalled topic.mocks.subscriber.callOnDelete
'then the correct plant is deleted': (topic) ->
assert.equal topic.mocks.subscriber.callOnDelete.__calls[0].arguments[0].name, "Corn"
#assert.wasCalledWith topic.mocks.subscriber.callOnDelete, [topic.mocks.plant]
}
}
}).export module
|
[
{
"context": " - proteus api commands\n#\n# Notes:\n#\n# Author:\n# gfjohnson\n\npapi = require 'bcprotapi'\n\nmoduledesc = 'Proteu",
"end": 439,
"score": 0.9997132420539856,
"start": 430,
"tag": "USERNAME",
"value": "gfjohnson"
},
{
"context": "'papi'\n\nconfig =\n host: 'localho... | src/proteusdns.coffee | gsfjohnson/hubot-proteusdns | 0 | # coffeelint: disable=max_line_length
#
# Description:
# Interact with Proteus API.
#
# Dependencies:
# proteusdns
#
# Configuration:
# HUBOT_BCPROTAPI_HOST [required] - url (e.g. proteus.example.com)
# HUBOT_BCPROTAPI_USER [required] - api user
# HUBOT_BCPROTAPI_PASS [required] - api pass
# HUBOT_BCPROTAPI_SSL [optional] - use ssl
#
# Commands:
# hubot papi help - proteus api commands
#
# Notes:
#
# Author:
# gfjohnson
papi = require 'bcprotapi'
moduledesc = 'ProteusAPI'
modulename = 'papi'
config =
host: 'localhost'
username: 'example'
password: 'example'
ssl: false
keepalives: true
interation: 0
config.ssl = true if process.env.HUBOT_BCPROTAPI_SSL
config.host = process.env.HUBOT_BCPROTAPI_HOST if process.env.HUBOT_BCPROTAPI_HOST
config.username = process.env.HUBOT_BCPROTAPI_USER if process.env.HUBOT_BCPROTAPI_USER
config.password = process.env.HUBOT_BCPROTAPI_PASS if process.env.HUBOT_BCPROTAPI_PASS
unless config.username == "example"
papi.connect config
searchByObjectTypes = (robot, msg, args) ->
# robot.logger.info "searchByObjectTypes: sending request for #{keyword}"
papi.searchByObjectTypes args, (err, res) ->
if err
if config.iteration < 1 and err is 'Error: env:Server: Not logged in'
msgout = "#{moduledesc}: connection timeout, attempting reconnect"
robot.logger.info "#{msgout} [#{msg.envelope.user.name}]"
robot.send {room: msg.envelope.user.name}, msgout
papi.connect config, (err, res) ->
config.iteration += 1
return searchByObjectTypes robot, msg, args
return
msgout = "#{moduledesc}: error"
robot.logger.info "#{msgout} (#{err}) [#{msg.envelope.user.name}]"
return robot.send {room: msg.envelope.user.name}, "#{msgout}, check hubot log for details"
config.iteration = 0
if res is null
msgout = "#{moduledesc}: no searchByObjectTypes results for `#{JSON.stringify(args)}`"
robot.logger.info "#{msgout} [#{msg.envelope.user.name}]"
return msg.reply msgout
r = []
for o in res
switch o.type
when 'HostRecord' then r.push "#{o.absoluteName} - #{o.addresses}"
when 'AliasRecord' then r.push "#{o.name} - #{o.properties}"
when 'IP4Network' then r.push "#{o.CIDR} - #{o.name}"
when 'IP4Address' then r.push "#{o.address} - #{o.state} - #{o.macAddress}"
when 'MACAddress' then r.push "#{o.properties}"
when 'NAPTRRecord' then r.push "#{o.properties}"
out = r.join "\n"
msgout = "#{moduledesc}: `#{res.length} results` ```#{out}```"
robot.logger.info "#{msgout} [#{msg.envelope.user.name}]"
return msg.reply msgout
module.exports = (robot) ->
robot.respond /papi help$/, (msg) ->
cmds = []
arr = [
"#{modulename} search <keyword> - search database"
"#{modulename} IP4Address <keyword> - search IP4Address objects only"
"#{modulename} IP4Network <keyword> - search IP4Network objects only"
"#{modulename} HostRecord <keyword> - search HostRecord objects only"
]
for str in arr
cmd = str.split " - "
cmds.push "`#{cmd[0]}` - #{cmd[1]}"
robot.send {room: msg.message?.user?.name}, cmds.join "\n"
robot.respond /papi s(?:earch)? (.+)$/i, (msg) ->
keyword = msg.match[1]
robot.logger.info "#{moduledesc}: keyword search: #{keyword} [#{msg.envelope.user.name}]"
args =
keyword: keyword
return searchByObjectTypes robot, msg, args
robot.respond /papi IP4A(?:ddress)? (.+)$/i, (msg) ->
keyword = msg.match[1]
type = 'IP4Address'
robot.logger.info "#{moduledesc}: keyword search for #{type}: #{keyword} [#{msg.envelope.user.name}]"
args =
keyword: keyword
types: type
return searchByObjectTypes robot, msg, args
robot.respond /papi IP4N(?:etwork)? (.+)$/i, (msg) ->
keyword = msg.match[1]
type = 'IP4Network'
robot.logger.info "#{moduledesc}: keyword search for #{type}: #{keyword} [#{msg.envelope.user.name}]"
args =
keyword: keyword
types: type
return searchByObjectTypes robot, msg, args
robot.respond /papi Host(?:Record)? (.+)$/i, (msg) ->
keyword = msg.match[1]
type = 'HostRecord'
robot.logger.info "#{moduledesc}: keyword search for #{type}: #{keyword} [#{msg.envelope.user.name}]"
args =
keyword: keyword
types: type
return searchByObjectTypes robot, msg, args
| 43856 | # coffeelint: disable=max_line_length
#
# Description:
# Interact with Proteus API.
#
# Dependencies:
# proteusdns
#
# Configuration:
# HUBOT_BCPROTAPI_HOST [required] - url (e.g. proteus.example.com)
# HUBOT_BCPROTAPI_USER [required] - api user
# HUBOT_BCPROTAPI_PASS [required] - api pass
# HUBOT_BCPROTAPI_SSL [optional] - use ssl
#
# Commands:
# hubot papi help - proteus api commands
#
# Notes:
#
# Author:
# gfjohnson
papi = require 'bcprotapi'
moduledesc = 'ProteusAPI'
modulename = 'papi'
config =
host: 'localhost'
username: 'example'
password: '<PASSWORD>'
ssl: false
keepalives: true
interation: 0
config.ssl = true if process.env.HUBOT_BCPROTAPI_SSL
config.host = process.env.HUBOT_BCPROTAPI_HOST if process.env.HUBOT_BCPROTAPI_HOST
config.username = process.env.HUBOT_BCPROTAPI_USER if process.env.HUBOT_BCPROTAPI_USER
config.password = process.env.HUBOT_BCPROTAPI_PASS if process.env.HUBOT_BCPROTAPI_PASS
unless config.username == "example"
papi.connect config
searchByObjectTypes = (robot, msg, args) ->
# robot.logger.info "searchByObjectTypes: sending request for #{keyword}"
papi.searchByObjectTypes args, (err, res) ->
if err
if config.iteration < 1 and err is 'Error: env:Server: Not logged in'
msgout = "#{moduledesc}: connection timeout, attempting reconnect"
robot.logger.info "#{msgout} [#{msg.envelope.user.name}]"
robot.send {room: msg.envelope.user.name}, msgout
papi.connect config, (err, res) ->
config.iteration += 1
return searchByObjectTypes robot, msg, args
return
msgout = "#{moduledesc}: error"
robot.logger.info "#{msgout} (#{err}) [#{msg.envelope.user.name}]"
return robot.send {room: msg.envelope.user.name}, "#{msgout}, check hubot log for details"
config.iteration = 0
if res is null
msgout = "#{moduledesc}: no searchByObjectTypes results for `#{JSON.stringify(args)}`"
robot.logger.info "#{msgout} [#{msg.envelope.user.name}]"
return msg.reply msgout
r = []
for o in res
switch o.type
when 'HostRecord' then r.push "#{o.absoluteName} - #{o.addresses}"
when 'AliasRecord' then r.push "#{o.name} - #{o.properties}"
when 'IP4Network' then r.push "#{o.CIDR} - #{o.name}"
when 'IP4Address' then r.push "#{o.address} - #{o.state} - #{o.macAddress}"
when 'MACAddress' then r.push "#{o.properties}"
when 'NAPTRRecord' then r.push "#{o.properties}"
out = r.join "\n"
msgout = "#{moduledesc}: `#{res.length} results` ```#{out}```"
robot.logger.info "#{msgout} [#{msg.envelope.user.name}]"
return msg.reply msgout
module.exports = (robot) ->
robot.respond /papi help$/, (msg) ->
cmds = []
arr = [
"#{modulename} search <keyword> - search database"
"#{modulename} IP4Address <keyword> - search IP4Address objects only"
"#{modulename} IP4Network <keyword> - search IP4Network objects only"
"#{modulename} HostRecord <keyword> - search HostRecord objects only"
]
for str in arr
cmd = str.split " - "
cmds.push "`#{cmd[0]}` - #{cmd[1]}"
robot.send {room: msg.message?.user?.name}, cmds.join "\n"
robot.respond /papi s(?:earch)? (.+)$/i, (msg) ->
keyword = msg.match[1]
robot.logger.info "#{moduledesc}: keyword search: #{keyword} [#{msg.envelope.user.name}]"
args =
keyword: keyword
return searchByObjectTypes robot, msg, args
robot.respond /papi IP4A(?:ddress)? (.+)$/i, (msg) ->
keyword = msg.match[1]
type = 'IP4Address'
robot.logger.info "#{moduledesc}: keyword search for #{type}: #{keyword} [#{msg.envelope.user.name}]"
args =
keyword: keyword
types: type
return searchByObjectTypes robot, msg, args
robot.respond /papi IP4N(?:etwork)? (.+)$/i, (msg) ->
keyword = msg.match[1]
type = 'IP4Network'
robot.logger.info "#{moduledesc}: keyword search for #{type}: #{keyword} [#{msg.envelope.user.name}]"
args =
keyword: keyword
types: type
return searchByObjectTypes robot, msg, args
robot.respond /papi Host(?:Record)? (.+)$/i, (msg) ->
keyword = msg.match[1]
type = 'HostRecord'
robot.logger.info "#{moduledesc}: keyword search for #{type}: #{keyword} [#{msg.envelope.user.name}]"
args =
keyword: keyword
types: type
return searchByObjectTypes robot, msg, args
| true | # coffeelint: disable=max_line_length
#
# Description:
# Interact with Proteus API.
#
# Dependencies:
# proteusdns
#
# Configuration:
# HUBOT_BCPROTAPI_HOST [required] - url (e.g. proteus.example.com)
# HUBOT_BCPROTAPI_USER [required] - api user
# HUBOT_BCPROTAPI_PASS [required] - api pass
# HUBOT_BCPROTAPI_SSL [optional] - use ssl
#
# Commands:
# hubot papi help - proteus api commands
#
# Notes:
#
# Author:
# gfjohnson
papi = require 'bcprotapi'
moduledesc = 'ProteusAPI'
modulename = 'papi'
config =
host: 'localhost'
username: 'example'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
ssl: false
keepalives: true
interation: 0
config.ssl = true if process.env.HUBOT_BCPROTAPI_SSL
config.host = process.env.HUBOT_BCPROTAPI_HOST if process.env.HUBOT_BCPROTAPI_HOST
config.username = process.env.HUBOT_BCPROTAPI_USER if process.env.HUBOT_BCPROTAPI_USER
config.password = process.env.HUBOT_BCPROTAPI_PASS if process.env.HUBOT_BCPROTAPI_PASS
unless config.username == "example"
papi.connect config
searchByObjectTypes = (robot, msg, args) ->
# robot.logger.info "searchByObjectTypes: sending request for #{keyword}"
papi.searchByObjectTypes args, (err, res) ->
if err
if config.iteration < 1 and err is 'Error: env:Server: Not logged in'
msgout = "#{moduledesc}: connection timeout, attempting reconnect"
robot.logger.info "#{msgout} [#{msg.envelope.user.name}]"
robot.send {room: msg.envelope.user.name}, msgout
papi.connect config, (err, res) ->
config.iteration += 1
return searchByObjectTypes robot, msg, args
return
msgout = "#{moduledesc}: error"
robot.logger.info "#{msgout} (#{err}) [#{msg.envelope.user.name}]"
return robot.send {room: msg.envelope.user.name}, "#{msgout}, check hubot log for details"
config.iteration = 0
if res is null
msgout = "#{moduledesc}: no searchByObjectTypes results for `#{JSON.stringify(args)}`"
robot.logger.info "#{msgout} [#{msg.envelope.user.name}]"
return msg.reply msgout
r = []
for o in res
switch o.type
when 'HostRecord' then r.push "#{o.absoluteName} - #{o.addresses}"
when 'AliasRecord' then r.push "#{o.name} - #{o.properties}"
when 'IP4Network' then r.push "#{o.CIDR} - #{o.name}"
when 'IP4Address' then r.push "#{o.address} - #{o.state} - #{o.macAddress}"
when 'MACAddress' then r.push "#{o.properties}"
when 'NAPTRRecord' then r.push "#{o.properties}"
out = r.join "\n"
msgout = "#{moduledesc}: `#{res.length} results` ```#{out}```"
robot.logger.info "#{msgout} [#{msg.envelope.user.name}]"
return msg.reply msgout
module.exports = (robot) ->
robot.respond /papi help$/, (msg) ->
cmds = []
arr = [
"#{modulename} search <keyword> - search database"
"#{modulename} IP4Address <keyword> - search IP4Address objects only"
"#{modulename} IP4Network <keyword> - search IP4Network objects only"
"#{modulename} HostRecord <keyword> - search HostRecord objects only"
]
for str in arr
cmd = str.split " - "
cmds.push "`#{cmd[0]}` - #{cmd[1]}"
robot.send {room: msg.message?.user?.name}, cmds.join "\n"
robot.respond /papi s(?:earch)? (.+)$/i, (msg) ->
keyword = msg.match[1]
robot.logger.info "#{moduledesc}: keyword search: #{keyword} [#{msg.envelope.user.name}]"
args =
keyword: keyword
return searchByObjectTypes robot, msg, args
robot.respond /papi IP4A(?:ddress)? (.+)$/i, (msg) ->
keyword = msg.match[1]
type = 'IP4Address'
robot.logger.info "#{moduledesc}: keyword search for #{type}: #{keyword} [#{msg.envelope.user.name}]"
args =
keyword: keyword
types: type
return searchByObjectTypes robot, msg, args
robot.respond /papi IP4N(?:etwork)? (.+)$/i, (msg) ->
keyword = msg.match[1]
type = 'IP4Network'
robot.logger.info "#{moduledesc}: keyword search for #{type}: #{keyword} [#{msg.envelope.user.name}]"
args =
keyword: keyword
types: type
return searchByObjectTypes robot, msg, args
robot.respond /papi Host(?:Record)? (.+)$/i, (msg) ->
keyword = msg.match[1]
type = 'HostRecord'
robot.logger.info "#{moduledesc}: keyword search for #{type}: #{keyword} [#{msg.envelope.user.name}]"
args =
keyword: keyword
types: type
return searchByObjectTypes robot, msg, args
|
[
{
"context": " removeFromCache: (path, args, obj) ->\n key = @key path, args\n @procs[key] = @procs[key].filter (",
"end": 478,
"score": 0.7809809446334839,
"start": 475,
"tag": "KEY",
"value": "key"
}
] | lib/connection/process/cycler.coffee | jessebett/atom-julia-client | 0 | {isEqual} = require 'underscore-plus'
basic = require './basic'
basic2 = require './basic2'
IPC = require '../ipc'
module.exports =
provider: ->
switch atom.config.get 'julia-client.consoleOptions.consoleStyle'
when 'REPL-based' then basic2
when 'Legacy' then basic
cacheLength: 1
procs: {}
key: (path, args) -> [path, args...].join ' '
cache: (path, args) -> @procs[@key(path, args)] ?= []
removeFromCache: (path, args, obj) ->
key = @key path, args
@procs[key] = @procs[key].filter (x) -> x != obj
toCache: (path, args, proc) ->
proc.cached = true
@cache(path, args).push proc
fromCache: (path, args) ->
ps = @cache path, args
p = ps.shift()
return unless p?
p.cached = false
p.init.then =>
@start path, args
p.proc
start: (path, args) ->
@provider().lock (release) =>
if @cache(path, args).length < @cacheLength
@provider().get_(path, args).then (proc) =>
obj = {path, args, proc: proc}
@monitor proc
@warmup obj
@toCache path, args, obj
proc.socket
.then => @start path, args
.catch (e) => @removeFromCache path, args, obj
release proc.socket
else
release()
return
flush: (events, out, err) ->
for {type, data} in events
(if type == 'stdout' then out else err) data
monitor: (proc) ->
proc.events = []
proc.wasCached = true
proc.onStdout (data) -> proc.events?.push {type: 'stdout', data}
proc.onStderr (data) -> proc.events?.push {type: 'stderr', data}
proc.flush = (out, err) =>
@flush proc.events, out, err
delete proc.events
boot: (ipc) -> ipc.rpc 'ping'
console: (ipc) -> ipc.rpc 'evalrepl', {code: 'Void()'}
completions: (ipc) -> ipc.rpc 'cacheCompletions', 'Main'
warmup: (obj) ->
obj.init = Promise.resolve()
obj.proc.socket
.then (sock) =>
return unless obj.cached
ipc = new IPC sock
[@boot, @console, @completions].forEach (f) ->
obj.init = obj.init.then ->
if obj.cached then f ipc
obj.init = obj.init
.catch (err) -> console.warn 'julia warmup error:', err
.then -> ipc.unreadStream()
return
.catch ->
get: (path, args) ->
if (proc = @fromCache path, args) then p = proc
else p = @provider().get path, args
@start path, args
p
reset: ->
for key, ps of @procs
for p in ps
p.proc.kill()
| 104866 | {isEqual} = require 'underscore-plus'
basic = require './basic'
basic2 = require './basic2'
IPC = require '../ipc'
module.exports =
provider: ->
switch atom.config.get 'julia-client.consoleOptions.consoleStyle'
when 'REPL-based' then basic2
when 'Legacy' then basic
cacheLength: 1
procs: {}
key: (path, args) -> [path, args...].join ' '
cache: (path, args) -> @procs[@key(path, args)] ?= []
removeFromCache: (path, args, obj) ->
key = @<KEY> path, args
@procs[key] = @procs[key].filter (x) -> x != obj
toCache: (path, args, proc) ->
proc.cached = true
@cache(path, args).push proc
fromCache: (path, args) ->
ps = @cache path, args
p = ps.shift()
return unless p?
p.cached = false
p.init.then =>
@start path, args
p.proc
start: (path, args) ->
@provider().lock (release) =>
if @cache(path, args).length < @cacheLength
@provider().get_(path, args).then (proc) =>
obj = {path, args, proc: proc}
@monitor proc
@warmup obj
@toCache path, args, obj
proc.socket
.then => @start path, args
.catch (e) => @removeFromCache path, args, obj
release proc.socket
else
release()
return
flush: (events, out, err) ->
for {type, data} in events
(if type == 'stdout' then out else err) data
monitor: (proc) ->
proc.events = []
proc.wasCached = true
proc.onStdout (data) -> proc.events?.push {type: 'stdout', data}
proc.onStderr (data) -> proc.events?.push {type: 'stderr', data}
proc.flush = (out, err) =>
@flush proc.events, out, err
delete proc.events
boot: (ipc) -> ipc.rpc 'ping'
console: (ipc) -> ipc.rpc 'evalrepl', {code: 'Void()'}
completions: (ipc) -> ipc.rpc 'cacheCompletions', 'Main'
warmup: (obj) ->
obj.init = Promise.resolve()
obj.proc.socket
.then (sock) =>
return unless obj.cached
ipc = new IPC sock
[@boot, @console, @completions].forEach (f) ->
obj.init = obj.init.then ->
if obj.cached then f ipc
obj.init = obj.init
.catch (err) -> console.warn 'julia warmup error:', err
.then -> ipc.unreadStream()
return
.catch ->
get: (path, args) ->
if (proc = @fromCache path, args) then p = proc
else p = @provider().get path, args
@start path, args
p
reset: ->
for key, ps of @procs
for p in ps
p.proc.kill()
| true | {isEqual} = require 'underscore-plus'
basic = require './basic'
basic2 = require './basic2'
IPC = require '../ipc'
module.exports =
provider: ->
switch atom.config.get 'julia-client.consoleOptions.consoleStyle'
when 'REPL-based' then basic2
when 'Legacy' then basic
cacheLength: 1
procs: {}
key: (path, args) -> [path, args...].join ' '
cache: (path, args) -> @procs[@key(path, args)] ?= []
removeFromCache: (path, args, obj) ->
key = @PI:KEY:<KEY>END_PI path, args
@procs[key] = @procs[key].filter (x) -> x != obj
toCache: (path, args, proc) ->
proc.cached = true
@cache(path, args).push proc
fromCache: (path, args) ->
ps = @cache path, args
p = ps.shift()
return unless p?
p.cached = false
p.init.then =>
@start path, args
p.proc
start: (path, args) ->
@provider().lock (release) =>
if @cache(path, args).length < @cacheLength
@provider().get_(path, args).then (proc) =>
obj = {path, args, proc: proc}
@monitor proc
@warmup obj
@toCache path, args, obj
proc.socket
.then => @start path, args
.catch (e) => @removeFromCache path, args, obj
release proc.socket
else
release()
return
flush: (events, out, err) ->
for {type, data} in events
(if type == 'stdout' then out else err) data
monitor: (proc) ->
proc.events = []
proc.wasCached = true
proc.onStdout (data) -> proc.events?.push {type: 'stdout', data}
proc.onStderr (data) -> proc.events?.push {type: 'stderr', data}
proc.flush = (out, err) =>
@flush proc.events, out, err
delete proc.events
boot: (ipc) -> ipc.rpc 'ping'
console: (ipc) -> ipc.rpc 'evalrepl', {code: 'Void()'}
completions: (ipc) -> ipc.rpc 'cacheCompletions', 'Main'
warmup: (obj) ->
obj.init = Promise.resolve()
obj.proc.socket
.then (sock) =>
return unless obj.cached
ipc = new IPC sock
[@boot, @console, @completions].forEach (f) ->
obj.init = obj.init.then ->
if obj.cached then f ipc
obj.init = obj.init
.catch (err) -> console.warn 'julia warmup error:', err
.then -> ipc.unreadStream()
return
.catch ->
get: (path, args) ->
if (proc = @fromCache path, args) then p = proc
else p = @provider().get path, args
@start path, args
p
reset: ->
for key, ps of @procs
for p in ps
p.proc.kill()
|
[
{
"context": "# DataProjector.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Main class ",
"end": 31,
"score": 0.9560483694076538,
"start": 25,
"tag": "NAME",
"value": "Tomasz"
},
{
"context": "# DataProjector.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# M... | src/DataProjector.coffee | SachithDassanayaka/sachithdassanayaka.github.io | 0 | # DataProjector.coffee
# Tomasz (Tomek) Zemla
# tomek@datacratic.com
# Main class of the data visualization application.
Subject = require('./Subject.coffee')
Observer = require('./Observer.coffee')
Utility = require('./Utility.coffee')
Palette = require('./Palette.coffee')
Storage = require('./Storage.coffee')
Toolbar = require('./Toolbar.coffee')
Menu = require('./Menu.coffee')
Info = require('./Info.coffee')
Projector = require('./Projector.coffee')
class DataProjector extends Observer
# M E M B E R S
# main modules
storage : null # read/write
toolbar : null # main application menu
menu : null # main data menu - left side panel
info : null # information console - right side panel
projector : null # WebGL visualization canvas
palette : null # stores both fixed UI colors and autogenerated ones for visualization
colors : null # Array<THREE.Color> generated color values for visualization
# C O N S T R U C T O R
# Create data projector and display/visualize given data file.
constructor : ->
# data read/write access
@storage = new Storage()
@storage.attach(@)
@storage.requestData()
# user interface - panels
@toolbar = new Toolbar('#toolbar')
@toolbar.attach(@)
@menu = new Menu('#menu')
@menu.attach(@)
@info = new Info('#info')
@info.attach(@)
# user interface - visualization
@projector = new Projector()
@projector.attach(@)
# throw new Error()
# E V E N T H A N D L E R S
# Derived from Observer, update is fired whenever event notifications from subjects come in.
update: (subject, type, data) ->
if subject instanceof Storage then @onStorageEvent(type, data)
if subject instanceof Toolbar then @onToolbarEvent(type, data)
if subject instanceof Menu then @onMenuEvent(type, data)
if subject instanceof Projector then @onProjectorEvent(type, data)
# Handle storage events.
onStorageEvent : (type, data) ->
switch type
when Storage.EVENT_DATA_READY
@info.display "Processed #{@storage.getPoints()} points."
@info.display "Found #{@storage.getClusters()} clusters."
@initialize() # get going!
when Storage.EVENT_SCREENSHOT_OK
@info.display "Screenshot #{@storage.getSaved()} saved."
# Handle toolbar events.
onToolbarEvent : (type, data) ->
switch type
when Toolbar.EVENT_MENU
state = @menu.toggle()
@toolbar.setMenuButtonSelected(state)
when Toolbar.EVENT_INFO
state = @info.toggle()
@toolbar.setInfoButtonSelected(state)
when Toolbar.EVENT_PERSPECTIVE
@projector.setMode(Projector.VIEW.PERSPECTIVE)
@toolbar.setCameraButtonSelected(true, false, false)
when Toolbar.EVENT_ORTHOGRAPHIC
@projector.setMode(Projector.VIEW.ORTHOGRAPHIC)
@toolbar.setCameraButtonSelected(false, true, false)
when Toolbar.EVENT_DUAL
@projector.setMode(Projector.VIEW.DUAL)
@toolbar.setCameraButtonSelected(false, false, true)
when Toolbar.EVENT_RESET
@projector.resetCamera(true)
@toolbar.blinkResetButton()
when Toolbar.EVENT_CLEAR
@info.clear()
@toolbar.blinkClearButton()
when Toolbar.EVENT_BOX
state = @projector.toggleBox()
@toolbar.setBoxButtonSelected(state)
when Toolbar.EVENT_VIEWPORT
state = @projector.toggleViewport()
@toolbar.setViewportButtonSelected(state)
when Toolbar.EVENT_SELECT
state = @projector.toggleSelector()
@toolbar.setSelectButtonSelected(state)
when Toolbar.EVENT_VIEW_TOP
@projector.changeView(Utility.DIRECTION.TOP)
@toolbar.setViewButtonSelected(true, false, false)
when Toolbar.EVENT_VIEW_FRONT
@projector.changeView(Utility.DIRECTION.FRONT)
@toolbar.setViewButtonSelected(false, true, false)
when Toolbar.EVENT_VIEW_SIDE
@projector.changeView(Utility.DIRECTION.SIDE)
@toolbar.setViewButtonSelected(false, false, true)
when Toolbar.EVENT_SPIN_LEFT
@projector.setSpin(Projector.SPIN.LEFT)
@toolbar.setSpinButtonSelected(true, false, false)
when Toolbar.EVENT_SPIN_STOP
@projector.setSpin(Projector.SPIN.NONE)
@toolbar.setSpinButtonSelected(false, true, false)
when Toolbar.EVENT_SPIN_RIGHT
@projector.setSpin(Projector.SPIN.RIGHT)
@toolbar.setSpinButtonSelected(false, false, true)
when Toolbar.EVENT_ANIMATE
state = @projector.toggleAnimation()
@toolbar.setAnimateButtonSelected(state)
when Toolbar.EVENT_PRINT
@storage.saveImage(@projector.getImage())
@toolbar.blinkPrintButton()
# Handle menu events.
onMenuEvent : (type, data) ->
switch type
when Menu.EVENT_TOGGLE_ALL_ON
@projector.setAllClustersVisible(true)
when Menu.EVENT_TOGGLE_ALL_OFF
@projector.setAllClustersVisible(false)
when Menu.EVENT_TOGGLE_ID
@projector.toggleClusterVisibility(data.id)
when Menu.EVENT_CLUSTER_ID
@projector.toggleClusterSelection(data.id)
# Handle projector events.
onProjectorEvent : (type, data) ->
console.log "DataProjector.onProjectorEvent " + type + " : " + data
switch type
when Projector.EVENT_DATA_LOADED
console.log "DataProjector.onProjectorEvent " + type
when Projector.EVENT_POINTS_SELECTED
@info.display "Selected #{data.points} points."
when Projector.EVENT_CLUSTER_SELECTED
if data.id > -1
@info.display("Cluster #{data.id} selected")
else
@info.display("No cluster selected")
# M E T H O D S
# Initialize the application with the loaded data.
initialize : ->
# autogenerate palette for the visualization and menus
@palette = new Palette(@storage.getClusters())
@colors = @palette.getColors()
# dynamically build menu for all clusters
@menu.create(@storage.getClusters(), @palette.getColors())
@projector.setColors(@colors) # use generated palette
@projector.load(@storage) # load data for visualization
@onToolbarEvent(Toolbar.EVENT_SPIN_RIGHT)
dataProjector = new DataProjector() # run!
| 203303 | # DataProjector.coffee
# <NAME> (<NAME>
# <EMAIL>
# Main class of the data visualization application.
Subject = require('./Subject.coffee')
Observer = require('./Observer.coffee')
Utility = require('./Utility.coffee')
Palette = require('./Palette.coffee')
Storage = require('./Storage.coffee')
Toolbar = require('./Toolbar.coffee')
Menu = require('./Menu.coffee')
Info = require('./Info.coffee')
Projector = require('./Projector.coffee')
class DataProjector extends Observer
# M E M B E R S
# main modules
storage : null # read/write
toolbar : null # main application menu
menu : null # main data menu - left side panel
info : null # information console - right side panel
projector : null # WebGL visualization canvas
palette : null # stores both fixed UI colors and autogenerated ones for visualization
colors : null # Array<THREE.Color> generated color values for visualization
# C O N S T R U C T O R
# Create data projector and display/visualize given data file.
constructor : ->
# data read/write access
@storage = new Storage()
@storage.attach(@)
@storage.requestData()
# user interface - panels
@toolbar = new Toolbar('#toolbar')
@toolbar.attach(@)
@menu = new Menu('#menu')
@menu.attach(@)
@info = new Info('#info')
@info.attach(@)
# user interface - visualization
@projector = new Projector()
@projector.attach(@)
# throw new Error()
# E V E N T H A N D L E R S
# Derived from Observer, update is fired whenever event notifications from subjects come in.
update: (subject, type, data) ->
if subject instanceof Storage then @onStorageEvent(type, data)
if subject instanceof Toolbar then @onToolbarEvent(type, data)
if subject instanceof Menu then @onMenuEvent(type, data)
if subject instanceof Projector then @onProjectorEvent(type, data)
# Handle storage events.
onStorageEvent : (type, data) ->
switch type
when Storage.EVENT_DATA_READY
@info.display "Processed #{@storage.getPoints()} points."
@info.display "Found #{@storage.getClusters()} clusters."
@initialize() # get going!
when Storage.EVENT_SCREENSHOT_OK
@info.display "Screenshot #{@storage.getSaved()} saved."
# Handle toolbar events.
onToolbarEvent : (type, data) ->
switch type
when Toolbar.EVENT_MENU
state = @menu.toggle()
@toolbar.setMenuButtonSelected(state)
when Toolbar.EVENT_INFO
state = @info.toggle()
@toolbar.setInfoButtonSelected(state)
when Toolbar.EVENT_PERSPECTIVE
@projector.setMode(Projector.VIEW.PERSPECTIVE)
@toolbar.setCameraButtonSelected(true, false, false)
when Toolbar.EVENT_ORTHOGRAPHIC
@projector.setMode(Projector.VIEW.ORTHOGRAPHIC)
@toolbar.setCameraButtonSelected(false, true, false)
when Toolbar.EVENT_DUAL
@projector.setMode(Projector.VIEW.DUAL)
@toolbar.setCameraButtonSelected(false, false, true)
when Toolbar.EVENT_RESET
@projector.resetCamera(true)
@toolbar.blinkResetButton()
when Toolbar.EVENT_CLEAR
@info.clear()
@toolbar.blinkClearButton()
when Toolbar.EVENT_BOX
state = @projector.toggleBox()
@toolbar.setBoxButtonSelected(state)
when Toolbar.EVENT_VIEWPORT
state = @projector.toggleViewport()
@toolbar.setViewportButtonSelected(state)
when Toolbar.EVENT_SELECT
state = @projector.toggleSelector()
@toolbar.setSelectButtonSelected(state)
when Toolbar.EVENT_VIEW_TOP
@projector.changeView(Utility.DIRECTION.TOP)
@toolbar.setViewButtonSelected(true, false, false)
when Toolbar.EVENT_VIEW_FRONT
@projector.changeView(Utility.DIRECTION.FRONT)
@toolbar.setViewButtonSelected(false, true, false)
when Toolbar.EVENT_VIEW_SIDE
@projector.changeView(Utility.DIRECTION.SIDE)
@toolbar.setViewButtonSelected(false, false, true)
when Toolbar.EVENT_SPIN_LEFT
@projector.setSpin(Projector.SPIN.LEFT)
@toolbar.setSpinButtonSelected(true, false, false)
when Toolbar.EVENT_SPIN_STOP
@projector.setSpin(Projector.SPIN.NONE)
@toolbar.setSpinButtonSelected(false, true, false)
when Toolbar.EVENT_SPIN_RIGHT
@projector.setSpin(Projector.SPIN.RIGHT)
@toolbar.setSpinButtonSelected(false, false, true)
when Toolbar.EVENT_ANIMATE
state = @projector.toggleAnimation()
@toolbar.setAnimateButtonSelected(state)
when Toolbar.EVENT_PRINT
@storage.saveImage(@projector.getImage())
@toolbar.blinkPrintButton()
# Handle menu events.
onMenuEvent : (type, data) ->
switch type
when Menu.EVENT_TOGGLE_ALL_ON
@projector.setAllClustersVisible(true)
when Menu.EVENT_TOGGLE_ALL_OFF
@projector.setAllClustersVisible(false)
when Menu.EVENT_TOGGLE_ID
@projector.toggleClusterVisibility(data.id)
when Menu.EVENT_CLUSTER_ID
@projector.toggleClusterSelection(data.id)
# Handle projector events.
onProjectorEvent : (type, data) ->
console.log "DataProjector.onProjectorEvent " + type + " : " + data
switch type
when Projector.EVENT_DATA_LOADED
console.log "DataProjector.onProjectorEvent " + type
when Projector.EVENT_POINTS_SELECTED
@info.display "Selected #{data.points} points."
when Projector.EVENT_CLUSTER_SELECTED
if data.id > -1
@info.display("Cluster #{data.id} selected")
else
@info.display("No cluster selected")
# M E T H O D S
# Initialize the application with the loaded data.
initialize : ->
# autogenerate palette for the visualization and menus
@palette = new Palette(@storage.getClusters())
@colors = @palette.getColors()
# dynamically build menu for all clusters
@menu.create(@storage.getClusters(), @palette.getColors())
@projector.setColors(@colors) # use generated palette
@projector.load(@storage) # load data for visualization
@onToolbarEvent(Toolbar.EVENT_SPIN_RIGHT)
dataProjector = new DataProjector() # run!
| true | # DataProjector.coffee
# PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI
# PI:EMAIL:<EMAIL>END_PI
# Main class of the data visualization application.
Subject = require('./Subject.coffee')
Observer = require('./Observer.coffee')
Utility = require('./Utility.coffee')
Palette = require('./Palette.coffee')
Storage = require('./Storage.coffee')
Toolbar = require('./Toolbar.coffee')
Menu = require('./Menu.coffee')
Info = require('./Info.coffee')
Projector = require('./Projector.coffee')
class DataProjector extends Observer
# M E M B E R S
# main modules
storage : null # read/write
toolbar : null # main application menu
menu : null # main data menu - left side panel
info : null # information console - right side panel
projector : null # WebGL visualization canvas
palette : null # stores both fixed UI colors and autogenerated ones for visualization
colors : null # Array<THREE.Color> generated color values for visualization
# C O N S T R U C T O R
# Create data projector and display/visualize given data file.
constructor : ->
# data read/write access
@storage = new Storage()
@storage.attach(@)
@storage.requestData()
# user interface - panels
@toolbar = new Toolbar('#toolbar')
@toolbar.attach(@)
@menu = new Menu('#menu')
@menu.attach(@)
@info = new Info('#info')
@info.attach(@)
# user interface - visualization
@projector = new Projector()
@projector.attach(@)
# throw new Error()
# E V E N T H A N D L E R S
# Derived from Observer, update is fired whenever event notifications from subjects come in.
update: (subject, type, data) ->
if subject instanceof Storage then @onStorageEvent(type, data)
if subject instanceof Toolbar then @onToolbarEvent(type, data)
if subject instanceof Menu then @onMenuEvent(type, data)
if subject instanceof Projector then @onProjectorEvent(type, data)
# Handle storage events.
onStorageEvent : (type, data) ->
switch type
when Storage.EVENT_DATA_READY
@info.display "Processed #{@storage.getPoints()} points."
@info.display "Found #{@storage.getClusters()} clusters."
@initialize() # get going!
when Storage.EVENT_SCREENSHOT_OK
@info.display "Screenshot #{@storage.getSaved()} saved."
# Handle toolbar events.
onToolbarEvent : (type, data) ->
switch type
when Toolbar.EVENT_MENU
state = @menu.toggle()
@toolbar.setMenuButtonSelected(state)
when Toolbar.EVENT_INFO
state = @info.toggle()
@toolbar.setInfoButtonSelected(state)
when Toolbar.EVENT_PERSPECTIVE
@projector.setMode(Projector.VIEW.PERSPECTIVE)
@toolbar.setCameraButtonSelected(true, false, false)
when Toolbar.EVENT_ORTHOGRAPHIC
@projector.setMode(Projector.VIEW.ORTHOGRAPHIC)
@toolbar.setCameraButtonSelected(false, true, false)
when Toolbar.EVENT_DUAL
@projector.setMode(Projector.VIEW.DUAL)
@toolbar.setCameraButtonSelected(false, false, true)
when Toolbar.EVENT_RESET
@projector.resetCamera(true)
@toolbar.blinkResetButton()
when Toolbar.EVENT_CLEAR
@info.clear()
@toolbar.blinkClearButton()
when Toolbar.EVENT_BOX
state = @projector.toggleBox()
@toolbar.setBoxButtonSelected(state)
when Toolbar.EVENT_VIEWPORT
state = @projector.toggleViewport()
@toolbar.setViewportButtonSelected(state)
when Toolbar.EVENT_SELECT
state = @projector.toggleSelector()
@toolbar.setSelectButtonSelected(state)
when Toolbar.EVENT_VIEW_TOP
@projector.changeView(Utility.DIRECTION.TOP)
@toolbar.setViewButtonSelected(true, false, false)
when Toolbar.EVENT_VIEW_FRONT
@projector.changeView(Utility.DIRECTION.FRONT)
@toolbar.setViewButtonSelected(false, true, false)
when Toolbar.EVENT_VIEW_SIDE
@projector.changeView(Utility.DIRECTION.SIDE)
@toolbar.setViewButtonSelected(false, false, true)
when Toolbar.EVENT_SPIN_LEFT
@projector.setSpin(Projector.SPIN.LEFT)
@toolbar.setSpinButtonSelected(true, false, false)
when Toolbar.EVENT_SPIN_STOP
@projector.setSpin(Projector.SPIN.NONE)
@toolbar.setSpinButtonSelected(false, true, false)
when Toolbar.EVENT_SPIN_RIGHT
@projector.setSpin(Projector.SPIN.RIGHT)
@toolbar.setSpinButtonSelected(false, false, true)
when Toolbar.EVENT_ANIMATE
state = @projector.toggleAnimation()
@toolbar.setAnimateButtonSelected(state)
when Toolbar.EVENT_PRINT
@storage.saveImage(@projector.getImage())
@toolbar.blinkPrintButton()
# Handle menu events.
onMenuEvent : (type, data) ->
switch type
when Menu.EVENT_TOGGLE_ALL_ON
@projector.setAllClustersVisible(true)
when Menu.EVENT_TOGGLE_ALL_OFF
@projector.setAllClustersVisible(false)
when Menu.EVENT_TOGGLE_ID
@projector.toggleClusterVisibility(data.id)
when Menu.EVENT_CLUSTER_ID
@projector.toggleClusterSelection(data.id)
# Handle projector events.
onProjectorEvent : (type, data) ->
console.log "DataProjector.onProjectorEvent " + type + " : " + data
switch type
when Projector.EVENT_DATA_LOADED
console.log "DataProjector.onProjectorEvent " + type
when Projector.EVENT_POINTS_SELECTED
@info.display "Selected #{data.points} points."
when Projector.EVENT_CLUSTER_SELECTED
if data.id > -1
@info.display("Cluster #{data.id} selected")
else
@info.display("No cluster selected")
# M E T H O D S
# Initialize the application with the loaded data.
initialize : ->
# autogenerate palette for the visualization and menus
@palette = new Palette(@storage.getClusters())
@colors = @palette.getColors()
# dynamically build menu for all clusters
@menu.create(@storage.getClusters(), @palette.getColors())
@projector.setColors(@colors) # use generated palette
@projector.load(@storage) # load data for visualization
@onToolbarEvent(Toolbar.EVENT_SPIN_RIGHT)
dataProjector = new DataProjector() # run!
|
[
{
"context": "'use strict'\n\nconsole.log('%cBINGO!!!\\nlyfuture@gmail.com', 'color:Orange');\n\ndefaultRules = 'from_url,to_u",
"end": 57,
"score": 0.9391108751296997,
"start": 38,
"tag": "EMAIL",
"value": "nlyfuture@gmail.com"
}
] | app.safariextension/scripts/options.coffee | lanceli/redirector | 26 | 'use strict'
console.log('%cBINGO!!!\nlyfuture@gmail.com', 'color:Orange');
defaultRules = 'from_url,to_url\nfrom_url,to_url,disabled_rule\nblock_url\nblock_url,,disabled_rule'
document.addEventListener 'DOMContentLoaded', () ->
$rules = document.getElementById('rules')
$rules.focus()
$rules.innerText = localStorage.getItem('rules_text') || defaultRules
$rules.onkeyup = (e) ->
rules = []
this.innerText.split('\n').forEach (v, i) ->
if v.trim() isnt ''
rules.push(v.split(','))
return
localStorage.setItem('rules_json', JSON.stringify(rules))
localStorage.setItem('rules_text', this.innerText)
if safari
safari.self.tab.dispatchMessage('saveRules', {
json: JSON.stringify(rules),
text: this.innerText
})
return
return
| 147676 | 'use strict'
console.log('%cBINGO!!!\<EMAIL>', 'color:Orange');
defaultRules = 'from_url,to_url\nfrom_url,to_url,disabled_rule\nblock_url\nblock_url,,disabled_rule'
document.addEventListener 'DOMContentLoaded', () ->
$rules = document.getElementById('rules')
$rules.focus()
$rules.innerText = localStorage.getItem('rules_text') || defaultRules
$rules.onkeyup = (e) ->
rules = []
this.innerText.split('\n').forEach (v, i) ->
if v.trim() isnt ''
rules.push(v.split(','))
return
localStorage.setItem('rules_json', JSON.stringify(rules))
localStorage.setItem('rules_text', this.innerText)
if safari
safari.self.tab.dispatchMessage('saveRules', {
json: JSON.stringify(rules),
text: this.innerText
})
return
return
| true | 'use strict'
console.log('%cBINGO!!!\PI:EMAIL:<EMAIL>END_PI', 'color:Orange');
defaultRules = 'from_url,to_url\nfrom_url,to_url,disabled_rule\nblock_url\nblock_url,,disabled_rule'
document.addEventListener 'DOMContentLoaded', () ->
$rules = document.getElementById('rules')
$rules.focus()
$rules.innerText = localStorage.getItem('rules_text') || defaultRules
$rules.onkeyup = (e) ->
rules = []
this.innerText.split('\n').forEach (v, i) ->
if v.trim() isnt ''
rules.push(v.split(','))
return
localStorage.setItem('rules_json', JSON.stringify(rules))
localStorage.setItem('rules_text', this.innerText)
if safari
safari.self.tab.dispatchMessage('saveRules', {
json: JSON.stringify(rules),
text: this.innerText
})
return
return
|
[
{
"context": "e approaching the greatest of mysteries.\n - Carl Sagan, Cosmos 1980\n '''\n\n contentView = new D",
"end": 1273,
"score": 0.9998501539230347,
"start": 1263,
"tag": "NAME",
"value": "Carl Sagan"
}
] | coffee/test/shells/doc.shell.spec.coffee | athenalabs/acorn-player | 11 | goog.provide 'acorn.specs.shells.DocShell'
goog.require 'acorn.shells.DocShell'
goog.require 'acorn.util.test'
describe 'acorn.shells.DocShell', ->
text = athena.lib.util.test
TextShell = acorn.shells.TextShell
DocShell = acorn.shells.DocShell
it 'should be part of acorn.shells', ->
expect(DocShell).toBeDefined()
acorn.util.test.describeShellModule DocShell, ->
options =
model: new DocShell.Model
shellid: 'acorn.DocShell'
describe 'DocShell.MediaView', ->
test.describeSubview
View: DocShell.MediaView
Subview: athena.lib.DocView
subviewAttr: 'docView'
viewOptions: options
it 'its views should look good', ->
# setup DOM
acorn.util.appendCss()
$player = $('<div>').addClass('acorn-player').appendTo('body')
model = new DocShell.Model
shellid: 'acorn.DocShell'
text: '''
# Cosmos
> The Cosmos is *all* that is or ever was or ever will be.
> Our feeblest contemplations of the Cosmos stir us —
> there is a tingling in the spine, a catch in the voice,
> a faint sensation as if a distant memory,
> of falling from a height.
> We know we are approaching the greatest of mysteries.
- Carl Sagan, Cosmos 1980
'''
contentView = new DocShell.MediaView model: model
contentView.$el.width 600
contentView.render()
$player.append contentView.el
remixView = new DocShell.RemixView model: model
remixView.$el.width 600
remixView.render()
$player.append remixView.el
| 176863 | goog.provide 'acorn.specs.shells.DocShell'
goog.require 'acorn.shells.DocShell'
goog.require 'acorn.util.test'
describe 'acorn.shells.DocShell', ->
text = athena.lib.util.test
TextShell = acorn.shells.TextShell
DocShell = acorn.shells.DocShell
it 'should be part of acorn.shells', ->
expect(DocShell).toBeDefined()
acorn.util.test.describeShellModule DocShell, ->
options =
model: new DocShell.Model
shellid: 'acorn.DocShell'
describe 'DocShell.MediaView', ->
test.describeSubview
View: DocShell.MediaView
Subview: athena.lib.DocView
subviewAttr: 'docView'
viewOptions: options
it 'its views should look good', ->
# setup DOM
acorn.util.appendCss()
$player = $('<div>').addClass('acorn-player').appendTo('body')
model = new DocShell.Model
shellid: 'acorn.DocShell'
text: '''
# Cosmos
> The Cosmos is *all* that is or ever was or ever will be.
> Our feeblest contemplations of the Cosmos stir us —
> there is a tingling in the spine, a catch in the voice,
> a faint sensation as if a distant memory,
> of falling from a height.
> We know we are approaching the greatest of mysteries.
- <NAME>, Cosmos 1980
'''
contentView = new DocShell.MediaView model: model
contentView.$el.width 600
contentView.render()
$player.append contentView.el
remixView = new DocShell.RemixView model: model
remixView.$el.width 600
remixView.render()
$player.append remixView.el
| true | goog.provide 'acorn.specs.shells.DocShell'
goog.require 'acorn.shells.DocShell'
goog.require 'acorn.util.test'
describe 'acorn.shells.DocShell', ->
text = athena.lib.util.test
TextShell = acorn.shells.TextShell
DocShell = acorn.shells.DocShell
it 'should be part of acorn.shells', ->
expect(DocShell).toBeDefined()
acorn.util.test.describeShellModule DocShell, ->
options =
model: new DocShell.Model
shellid: 'acorn.DocShell'
describe 'DocShell.MediaView', ->
test.describeSubview
View: DocShell.MediaView
Subview: athena.lib.DocView
subviewAttr: 'docView'
viewOptions: options
it 'its views should look good', ->
# setup DOM
acorn.util.appendCss()
$player = $('<div>').addClass('acorn-player').appendTo('body')
model = new DocShell.Model
shellid: 'acorn.DocShell'
text: '''
# Cosmos
> The Cosmos is *all* that is or ever was or ever will be.
> Our feeblest contemplations of the Cosmos stir us —
> there is a tingling in the spine, a catch in the voice,
> a faint sensation as if a distant memory,
> of falling from a height.
> We know we are approaching the greatest of mysteries.
- PI:NAME:<NAME>END_PI, Cosmos 1980
'''
contentView = new DocShell.MediaView model: model
contentView.$el.width 600
contentView.render()
$player.append contentView.el
remixView = new DocShell.RemixView model: model
remixView.$el.width 600
remixView.render()
$player.append remixView.el
|
[
{
"context": "ual = require 'deep-equal'\nquery = require '@gasolwu/refract-query'\nrenderExample = require './example",
"end": 289,
"score": 0.5689322352409363,
"start": 287,
"tag": "USERNAME",
"value": "wu"
},
{
"context": "styles` directory for available options.\n key = \"css-#{... | src/main.coffee | Gasol/aglio-theme-olio | 1 | crypto = require 'crypto'
fs = require 'fs'
hljs = require 'highlight.js'
pug = require 'pug'
less = require 'less'
markdownIt = require 'markdown-it'
moment = require 'moment'
path = require 'path'
querystring = require 'querystring'
equal = require 'deep-equal'
query = require '@gasolwu/refract-query'
renderExample = require './example'
renderSchema = require './schema'
# The root directory of this project
ROOT = path.dirname __dirname
cache = {}
# Utility for benchmarking
benchmark =
start: (message) -> if process.env.BENCHMARK then console.time message
end: (message) -> if process.env.BENCHMARK then console.timeEnd message
# Extend an error's message. Returns the modified error.
errMsg = (message, err) ->
err.message = "#{message}: #{err.message}"
return err
# Generate a SHA1 hash
sha1 = (value) ->
crypto.createHash('sha1').update(value.toString()).digest('hex')
# A function to create ID-safe slugs. If `unique` is passed, then
# unique slugs are returned for the same input. The cache is just
# a plain object where the keys are the sluggified name.
slug = (cache={}, value='', unique=false) ->
sluggified = value.toLowerCase()
.replace(/[ \t\n\\<>"'=:/]/g, '-')
.replace(/-+/g, '-')
.replace(/^-/, '')
if unique
while cache[sluggified]
# Already exists, so let's try to make it unique.
if sluggified.match /\d+$/
sluggified = sluggified.replace /\d+$/, (value) ->
parseInt(value) + 1
else
sluggified = sluggified + '-1'
cache[sluggified] = true
return sluggified
# A function to highlight snippets of code. lang is optional and
# if given, is used to set the code language. If lang is no-highlight
# then no highlighting is performed.
highlight = (code, lang, subset) ->
benchmark.start "highlight #{lang}"
response = switch lang
when 'no-highlight' then code
when undefined, null, ''
hljs.highlightAuto(code, subset).value
else hljs.highlight(lang, code).value
benchmark.end "highlight #{lang}"
return response.trim()
getCached = (key, compiledPath, sources, load, done) ->
# Disable the template/css caching?
if process.env.NOCACHE then return done null
# Already loaded? Just return it!
if cache[key] then return done null, cache[key]
# Next, try to check if the compiled path exists and is newer than all of
# the sources. If so, load the compiled path into the in-memory cache.
try
if fs.existsSync compiledPath
compiledStats = fs.statSync compiledPath
for source in sources
sourceStats = fs.statSync source
if sourceStats.mtime > compiledStats.mtime
# There is a newer source file, so we ignore the compiled
# version on disk. It'll be regenerated later.
return done null
try
load compiledPath, (err, item) ->
if err then return done(errMsg 'Error loading cached resource', err)
cache[key] = item
done null, cache[key]
catch loadErr
return done(errMsg 'Error loading cached resource', loadErr)
else
done null
catch err
done err
getCss = (variables, styles, verbose, done) ->
# Get the CSS for the given variables and style. This method caches
# its output, so subsequent calls will be extremely fast but will
# not reload potentially changed data from disk.
# The CSS is generated via a dummy LESS file with imports to the
# default variables, any custom override variables, and the given
# layout style. Both variables and style support special values,
# for example `flatly` might load `styles/variables-flatly.less`.
# See the `styles` directory for available options.
key = "css-#{variables}-#{styles}"
if cache[key] then return done null, cache[key]
# Not cached in memory, but maybe it's already compiled on disk?
compiledPath = path.join ROOT, 'cache',
"#{sha1 key}.css"
defaultVariablePath = path.join ROOT, 'styles', 'variables-default.less'
sources = [defaultVariablePath]
if not Array.isArray(variables) then variables = [variables]
if not Array.isArray(styles) then styles = [styles]
variablePaths = [defaultVariablePath]
for item in variables
if item isnt 'default'
customPath = path.join ROOT, 'styles', "variables-#{item}.less"
if not fs.existsSync customPath
customPath = item
if not fs.existsSync customPath
return done new Error "#{customPath} does not exist!"
variablePaths.push customPath
sources.push customPath
stylePaths = []
for item in styles
customPath = path.join ROOT, 'styles', "layout-#{item}.less"
if not fs.existsSync customPath
customPath = item
if not fs.existsSync customPath
return done new Error "#{customPath} does not exist!"
stylePaths.push customPath
sources.push customPath
load = (filename, loadDone) ->
fs.readFile filename, 'utf-8', loadDone
if verbose
console.log "Using variables #{variablePaths}"
console.log "Using styles #{stylePaths}"
console.log "Checking cache #{compiledPath}"
getCached key, compiledPath, sources, load, (err, css) ->
if err then return done err
if css
if verbose then console.log 'Cached version loaded'
return done null, css
# Not cached, so let's create the file.
if verbose
console.log 'Not cached or out of date. Generating CSS...'
tmp = ''
for customPath in variablePaths
tmp += "@import \"#{customPath}\";\n"
for customPath in stylePaths
tmp += "@import \"#{customPath}\";\n"
benchmark.start 'less-compile'
less.render tmp, compress: true, (err, result) ->
if err then return done(errMsg 'Error processing LESS -> CSS', err)
try
css = result.css
fs.writeFileSync compiledPath, css, 'utf-8'
catch writeErr
return done(errMsg 'Error writing cached CSS to file', writeErr)
benchmark.end 'less-compile'
cache[key] = css
done null, cache[key]
compileTemplate = (filename, options) ->
compiled = """
var pug = require('pug');
#{pug.compileFileClient filename, options}
module.exports = compiledFunc;
"""
getTemplate = (name, verbose, done) ->
# Check if this is a built-in template name
builtin = path.join(ROOT, 'templates', "#{name}.pug")
if not fs.existsSync(name) and fs.existsSync(builtin)
name = builtin
# Get the template function for the given path. This will load and
# compile the template if necessary, and cache it for future use.
key = "template-#{name}"
# Check if it is cached in memory. If not, then we'll check the disk.
if cache[key] then return done null, cache[key]
# Check if it is compiled on disk and not older than the template file.
# If not present or outdated, then we'll need to compile it.
compiledPath = path.join ROOT, 'cache', "#{sha1 key}.js"
load = (filename, loadDone) ->
try
loaded = require(filename)
catch loadErr
return loadDone(errMsg 'Unable to load template', loadErr)
loadDone null, require(filename)
if verbose
console.log "Using template #{name}"
console.log "Checking cache #{compiledPath}"
getCached key, compiledPath, [name], load, (err, template) ->
if err then return done err
if template
if verbose then console.log 'Cached version loaded'
return done null, template
if verbose
console.log 'Not cached or out of date. Generating template JS...'
# We need to compile the template, then cache it. This is interesting
# because we are compiling to a client-side template, then adding some
# module-specific code to make it work here. This allows us to save time
# in the future by just loading the generated javascript function.
benchmark.start 'pug-compile'
compileOptions =
filename: name
name: 'compiledFunc'
self: true
compileDebug: false
try
compiled = compileTemplate name, compileOptions
catch compileErr
return done(errMsg 'Error compiling template', compileErr)
if compiled.indexOf('self.') is -1
# Not using self, so we probably need to recompile into compatibility
# mode. This is slower, but keeps things working with Pug files
# designed for Aglio 1.x.
compileOptions.self = false
try
compiled = compileTemplate name, compileOptions
catch compileErr
return done(errMsg 'Error compiling template', compileErr)
try
fs.writeFileSync compiledPath, compiled, 'utf-8'
catch writeErr
return done(errMsg 'Error writing cached template file', writeErr)
benchmark.end 'pug-compile'
cache[key] = require(compiledPath)
done null, cache[key]
modifyUriTemplate = (templateUri, parameters, colorize) ->
# Modify a URI template to only include the parameter names from
# the given parameters. For example:
# URI template: /pages/{id}{?verbose}
# Parameters contains a single `id` parameter
# Output: /pages/{id}
parameterValidator = (b) ->
# Compare the names, removing the special `*` operator
parameterNames.indexOf(
querystring.unescape b.replace(/^\*|\*$/, '')) isnt -1
parameterNames = (param.name for param in parameters)
parameterBlocks = []
lastIndex = index = 0
while (index = templateUri.indexOf("{", index)) isnt -1
parameterBlocks.push templateUri.substring(lastIndex, index)
block = {}
closeIndex = templateUri.indexOf("}", index)
block.querySet = templateUri.indexOf("{?", index) is index
block.formSet = templateUri.indexOf("{&", index) is index
block.reservedSet = templateUri.indexOf("{+", index) is index
lastIndex = closeIndex + 1
index++
index++ if block.querySet or block.formSet or block.reservedSet
parameterSet = templateUri.substring(index, closeIndex)
block.parameters = parameterSet.split(",").filter(parameterValidator)
parameterBlocks.push block if block.parameters.length
parameterBlocks.push templateUri.substring(lastIndex, templateUri.length)
parameterBlocks.reduce((uri, v) ->
if typeof v is "string"
uri.push v
else
segment = if not colorize then ["{"] else []
segment.push "?" if v.querySet
segment.push "&" if v.formSet
segment.push "+" if v.reservedSet and not colorize
segment.push v.parameters.map((name) ->
if not colorize then name else
# TODO: handle errors here?
name = name.replace(/^\*|\*$/, '')
param = parameters[parameterNames.indexOf(querystring.unescape name)]
if v.querySet or v.formSet
"<span class=\"hljs-attribute\">#{name}=</span>" +
"<span class=\"hljs-literal\">#{param.example || ''}</span>"
else
"<span class=\"hljs-attribute\" title=\"#{name}\">#{
param.example || name}</span>"
).join(if colorize then '&' else ',')
if not colorize
segment.push "}"
uri.push segment.join("")
uri
, []).join('').replace(/\/+/g, '/')
getTitle = (parseResult) ->
[category, ...] = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'api'
}
]
}
}
}
return category?.meta.title?.content or ''
getDataStructures = (parseResult) ->
results = query parseResult, {
element: 'dataStructure',
content: {
meta: {
id: {
element: 'string'
}
}
}
}
return new -> @[result.content.meta.id.content] = result \
for result in results; @
getApiDescription = (parseResult) ->
[category, ...] = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'api'
}
]
}
},
}
if category?.content.length > 0
content = category.content[0]
return content.content if content.element == 'copy'
return ''
getHost = (parseResult) ->
[category, ...] = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'api'
}
]
}
}
}
[member, ...] = query category?.attributes?.metadata or [], {
element: 'member'
content: {
key: {
content: 'HOST'
}
}
}
return member?.content.value.content or ''
getResourceGroups = (parseResult, slugCache, md) ->
results = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'resourceGroup'
}
]
}
}
}
return (getResourceGroup result, slugCache, md for result in results)
getResourceGroup = (resourceGroupElement, slugCache, md) ->
slugify = slug.bind slug, slugCache
title = resourceGroupElement.meta.title.content
title_slug = slugify title, true
if resourceGroupElement.content.length > 0 and
resourceGroupElement.content[0].element == 'copy'
description = md.render resourceGroupElement.content[0].content
resourceGroup = {
name: title
elementId: title_slug
elementLink: "##{title_slug}"
descriptionHtml: description or ''
resources: []
}
if description
resourceGroup.navItems = slugCache._nav
slugCache._nav = []
resourceElements = query resourceGroupElement, {element: 'resource'}
resourceGroup.resources = getResources resourceElements, slugCache,
resourceGroup.elementId
return resourceGroup
getResourceDescription = (resourceElement) ->
if resourceElement.content[0]?.element == 'copy'
return resourceElement.content[0].content
return ''
getResources = (resourceElements, slugCache, parentId) ->
return (getResource resourceElement, slugCache, parentId \
for resourceElement in resourceElements)
getResource = (resourceElement, slugCache, parentId) ->
slugify = slug.bind slug, slugCache
title = resourceElement.meta.title.content
title_slug = slugify "#{parentId}-#{title}", true
description = getResourceDescription resourceElement
resource = {
name: title
elementId: title_slug
elementLink: "##{title_slug}"
description: description
actions: []
uriTemplate: resourceElement.attributes?.href.content || ""
}
resource.actions = getActions resourceElement, slugCache,
"#{parentId}-#{title}-#{resource.name}"
return resource
getHeaders = (headersElement) ->
return ({
name: element.content.key.content
value: element.content.value.content
} for element in headersElement or [])
getRequest = (requestElement) ->
hasRequest = requestElement.meta?.title or \
requestElement.content.length > 0
name = requestElement.meta?.title.content
method = requestElement.attributes.method.content
[copy] = query requestElement, {element: 'copy'}
[schema] = query requestElement, {
element: 'asset',
meta: {
classes: {
content: [
{
content: 'messageBodySchema'
}
]
}
}
}
[body] = query requestElement, {
element: 'asset',
meta: {
classes: {
content: [
{
content: 'messageBody'
}
]
}
}
}
headers = getHeaders requestElement.attributes.headers?.content
return {
name: name or ''
description: copy?.content or ''
schema: schema?.content or ''
body: body?.content or ''
headers: headers
content: []
method: method
hasContent: copy?.content? or \
headers.length > 0 or \
body?.content? or \
schema?.content?
}
getResponse = (responseElement) ->
name = responseElement.attributes.statusCode.content
[schema] = query responseElement, {
element: 'asset',
meta: {
classes: {
content: [
{
content: 'messageBodySchema'
}
]
}
}
}
[body] = query responseElement, {
element: 'asset',
meta: {
classes: {
content: [
{
content: 'messageBody'
}
]
}
}
}
[copy] = query responseElement, {element: 'copy'}
headers = getHeaders responseElement.attributes.headers?.content
return {
name: name or ''
description: copy?.content or ''
headers: headers
body: body?.content or ''
schema: schema?.content or ''
content: []
hasContent: copy?.content? or \
headers.length > 0 or \
body?.content? or \
schema?.content?
}
isEmptyMessage = (message) ->
return message.name? and
message.headers.length == 0 and
message.description? and
message.body? and
message.schema? and
message.content.length == 0
getExamples = (actionElement) ->
example = {
name: ''
description: ''
requests: []
responses: []
}
examples = [example]
for httpTransaction in query actionElement, {element: 'httpTransaction'}
for requestElement in query httpTransaction, {element: 'httpRequest'}
request = getRequest requestElement
method = request.method
for responseElement in query httpTransaction, {element: 'httpResponse'}
response = getResponse responseElement
[..., prevRequest] = example?.requests or []
[..., prevResponse] = example?.responses or []
sameRequest = equal prevRequest, request
sameResponse = equal prevResponse, response
if sameRequest
if not sameResponse
example.responses.push response
else
if prevRequest
example = {
name: ''
description: ''
requests: []
responses: []
}
examples.push example
if not isEmptyMessage request
example.requests.push request
if not sameResponse
example.responses.push response
return examples
getRequestMethod = (actionElement) ->
for requestElement in query actionElement, {element: 'httpRequest'}
method = requestElement.attributes.method.content
return method if method
return ''
getActions = (resourceElement, slugCache, parentId) ->
slugify = slug.bind slug, slugCache
actions = []
for actionElement in query resourceElement, {element: 'transition'}
title = actionElement.meta.title.content
method = getRequestMethod actionElement
examples = getExamples actionElement
for example in examples
hasRequest = example.requests.length > 0
break if hasRequest
[..., copy] = query actionElement, {element: 'copy'}
id = slugify "#{parentId}-#{method}",
true
action = {
name: title
description: copy?.content
elementId: id
elementLink: "##{id}"
method: method
methodLower: method.toLowerCase()
hasRequest: hasRequest? or false
examples: examples
}
action.parameters = getParameters actionElement, resourceElement
href = actionElement.attributes?.href or resourceElement.attributes.href \
or {}
uriTemplate = href.content or ''
action.uriTemplate = modifyUriTemplate uriTemplate, action.parameters
action.attributes =
urlTemplate: action.uriTemplate
action.colorizedUriTemplate = modifyUriTemplate uriTemplate,
action.parameters,
true
actions.push action
return actions
getParameters = (actionElement, resourceElement) ->
parameters = []
resourceParams = resourceElement.attributes?.hrefVariables?.content or []
actionParams = actionElement.attributes?.hrefVariables?.content or []
hrefVariables = resourceParams.concat actionParams
for hrefVariable in hrefVariables
requiredElement = query hrefVariable.attributes.typeAttributes, {
content: 'required'
}
valueElement = hrefVariable.content.value
switch valueElement.element
when 'enum'
values = ({value: enumValue.content} for enumValue in \
valueElement.attributes.enumerations.content)
example = valueElement.content.content
else
values = []
example = valueElement.content
parameter = {
name: hrefVariable.content.key.content
description: hrefVariable.meta.description?.content or ''
type: hrefVariable.meta.title?.content
required: requiredElement.length > 0
example: example
values: values
}
parameters.push parameter
return parameters
getMetadata = (parseResult) ->
[category, ...] = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'api'
}
]
}
}
}
return ({
name: meta.content.key.content
value: meta.content.value.content
} for meta in category?.attributes?.metadata?.content or [])
getDefaultResourceGroup = (parseResult, slugCache) ->
[result] = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'api'
}
]
}
},
content: [
{
element: 'resource'
}
]
}
resourceElements = (query result, {element: 'resource'} if result) or []
resources = getResources resourceElements, slugCache, ''
if resources.length > 0
return {
name: ''
elementId: ''
elementLink: ''
descriptionHtml: ''
resources: resources
}
else
return null
decorate = (api, md, slugCache, verbose) ->
# Decorate an API Blueprint AST with various pieces of information that
# will be useful for the theme. Anything that would significantly
# complicate the Pug template should probably live here instead!
# Use the slug caching mechanism
slugify = slug.bind slug, slugCache
# Find data structures. This is a temporary workaround until Drafter is
# updated to support JSON Schema again.
# TODO: Remove me when Drafter is released.
api.name = getTitle api
api.metadata = getMetadata api
dataStructures = getDataStructures api
if verbose
console.log "Known data structures: #{Object.keys(dataStructures)}"
api.descriptionHtml = md.render getApiDescription api
if api.descriptionHtml
api.navItems = slugCache._nav
slugCache._nav = []
api.host = getHost api
api.resourceGroups = getResourceGroups api, slugCache, md
defaultResourceGroup = getDefaultResourceGroup api, slugCache
api.resourceGroups.unshift defaultResourceGroup if defaultResourceGroup
# Get the theme's configuration, used by Aglio to present available
# options and confirm that the input blueprint is a supported
# version.
exports.getConfig = ->
formats: ['1A']
options: [
{name: 'variables',
description: 'Color scheme name or path to custom variables',
default: 'default'},
{name: 'condense-nav', description: 'Condense navigation links',
boolean: true, default: true},
{name: 'full-width', description: 'Use full window width',
boolean: true, default: false},
{name: 'template', description: 'Template name or path to custom template',
default: 'default'},
{name: 'style',
description: 'Layout style name or path to custom stylesheet'},
{name: 'emoji', description: 'Enable support for emoticons',
boolean: true, default: true}
]
# Render the blueprint with the given options using Pug and LESS
exports.render = (input, options, done) ->
if not done?
done = options
options = {}
# Disable the template/css caching?
if process.env.NOCACHE then cache = {}
# This is purely for backward-compatibility
if options.condenseNav then options.themeCondenseNav = options.condenseNav
if options.fullWidth then options.themeFullWidth = options.fullWidth
# Setup defaults
options.themeVariables ?= 'default'
options.themeStyle ?= 'default'
options.themeTemplate ?= 'default'
options.themeCondenseNav ?= true
options.themeFullWidth ?= false
# Transform built-in layout names to paths
if options.themeTemplate is 'default'
options.themeTemplate = path.join ROOT, 'templates', 'index.pug'
# Setup markdown with code highlighting and smartypants. This also enables
# automatically inserting permalinks for headers.
slugCache =
_nav: []
md = markdownIt(
html: true
linkify: true
typographer: true
highlight: highlight
).use(require('markdown-it-anchor'),
slugify: (value) ->
output = "header-#{slug(slugCache, value, true)}"
slugCache._nav.push [value, "##{output}"]
return output
permalink: true
permalinkClass: 'permalink'
).use(require('markdown-it-checkbox')
).use(require('markdown-it-container'), 'note'
).use(require('markdown-it-container'), 'warning')
if options.themeEmoji then md.use require('markdown-it-emoji')
# Enable code highlighting for unfenced code blocks
md.renderer.rules.code_block = md.renderer.rules.fence
benchmark.start 'decorate'
decorate input, md, slugCache, options.verbose
benchmark.end 'decorate'
benchmark.start 'css-total'
{themeVariables, themeStyle, verbose} = options
getCss themeVariables, themeStyle, verbose, (err, css) ->
if err then return done(errMsg 'Could not get CSS', err)
benchmark.end 'css-total'
locals =
api: input
condenseNav: options.themeCondenseNav
css: css
fullWidth: options.themeFullWidth
date: moment
hash: (value) ->
crypto.createHash('md5').update(value.toString()).digest('hex')
highlight: highlight
markdown: (content) -> md.render content
slug: slug.bind(slug, slugCache)
urldec: (value) -> querystring.unescape(value)
for key, value of options.locals or {}
locals[key] = value
benchmark.start 'get-template'
getTemplate options.themeTemplate, verbose, (getTemplateErr, renderer) ->
if getTemplateErr
return done(errMsg 'Could not get template', getTemplateErr)
benchmark.end 'get-template'
benchmark.start 'call-template'
try html = renderer locals
catch err
return done(errMsg 'Error calling template during rendering', err)
benchmark.end 'call-template'
done null, html
| 53978 | crypto = require 'crypto'
fs = require 'fs'
hljs = require 'highlight.js'
pug = require 'pug'
less = require 'less'
markdownIt = require 'markdown-it'
moment = require 'moment'
path = require 'path'
querystring = require 'querystring'
equal = require 'deep-equal'
query = require '@gasolwu/refract-query'
renderExample = require './example'
renderSchema = require './schema'
# The root directory of this project
ROOT = path.dirname __dirname
cache = {}
# Utility for benchmarking
benchmark =
start: (message) -> if process.env.BENCHMARK then console.time message
end: (message) -> if process.env.BENCHMARK then console.timeEnd message
# Extend an error's message. Returns the modified error.
errMsg = (message, err) ->
err.message = "#{message}: #{err.message}"
return err
# Generate a SHA1 hash
sha1 = (value) ->
crypto.createHash('sha1').update(value.toString()).digest('hex')
# A function to create ID-safe slugs. If `unique` is passed, then
# unique slugs are returned for the same input. The cache is just
# a plain object where the keys are the sluggified name.
slug = (cache={}, value='', unique=false) ->
sluggified = value.toLowerCase()
.replace(/[ \t\n\\<>"'=:/]/g, '-')
.replace(/-+/g, '-')
.replace(/^-/, '')
if unique
while cache[sluggified]
# Already exists, so let's try to make it unique.
if sluggified.match /\d+$/
sluggified = sluggified.replace /\d+$/, (value) ->
parseInt(value) + 1
else
sluggified = sluggified + '-1'
cache[sluggified] = true
return sluggified
# A function to highlight snippets of code. lang is optional and
# if given, is used to set the code language. If lang is no-highlight
# then no highlighting is performed.
highlight = (code, lang, subset) ->
benchmark.start "highlight #{lang}"
response = switch lang
when 'no-highlight' then code
when undefined, null, ''
hljs.highlightAuto(code, subset).value
else hljs.highlight(lang, code).value
benchmark.end "highlight #{lang}"
return response.trim()
getCached = (key, compiledPath, sources, load, done) ->
# Disable the template/css caching?
if process.env.NOCACHE then return done null
# Already loaded? Just return it!
if cache[key] then return done null, cache[key]
# Next, try to check if the compiled path exists and is newer than all of
# the sources. If so, load the compiled path into the in-memory cache.
try
if fs.existsSync compiledPath
compiledStats = fs.statSync compiledPath
for source in sources
sourceStats = fs.statSync source
if sourceStats.mtime > compiledStats.mtime
# There is a newer source file, so we ignore the compiled
# version on disk. It'll be regenerated later.
return done null
try
load compiledPath, (err, item) ->
if err then return done(errMsg 'Error loading cached resource', err)
cache[key] = item
done null, cache[key]
catch loadErr
return done(errMsg 'Error loading cached resource', loadErr)
else
done null
catch err
done err
getCss = (variables, styles, verbose, done) ->
# Get the CSS for the given variables and style. This method caches
# its output, so subsequent calls will be extremely fast but will
# not reload potentially changed data from disk.
# The CSS is generated via a dummy LESS file with imports to the
# default variables, any custom override variables, and the given
# layout style. Both variables and style support special values,
# for example `flatly` might load `styles/variables-flatly.less`.
# See the `styles` directory for available options.
key = "<KEY>styles<KEY>}"
if cache[key] then return done null, cache[key]
# Not cached in memory, but maybe it's already compiled on disk?
compiledPath = path.join ROOT, 'cache',
"#{sha1 key}.css"
defaultVariablePath = path.join ROOT, 'styles', 'variables-default.less'
sources = [defaultVariablePath]
if not Array.isArray(variables) then variables = [variables]
if not Array.isArray(styles) then styles = [styles]
variablePaths = [defaultVariablePath]
for item in variables
if item isnt 'default'
customPath = path.join ROOT, 'styles', "variables-#{item}.less"
if not fs.existsSync customPath
customPath = item
if not fs.existsSync customPath
return done new Error "#{customPath} does not exist!"
variablePaths.push customPath
sources.push customPath
stylePaths = []
for item in styles
customPath = path.join ROOT, 'styles', "layout-#{item}.less"
if not fs.existsSync customPath
customPath = item
if not fs.existsSync customPath
return done new Error "#{customPath} does not exist!"
stylePaths.push customPath
sources.push customPath
load = (filename, loadDone) ->
fs.readFile filename, 'utf-8', loadDone
if verbose
console.log "Using variables #{variablePaths}"
console.log "Using styles #{stylePaths}"
console.log "Checking cache #{compiledPath}"
getCached key, compiledPath, sources, load, (err, css) ->
if err then return done err
if css
if verbose then console.log 'Cached version loaded'
return done null, css
# Not cached, so let's create the file.
if verbose
console.log 'Not cached or out of date. Generating CSS...'
tmp = ''
for customPath in variablePaths
tmp += "@import \"#{customPath}\";\n"
for customPath in stylePaths
tmp += "@import \"#{customPath}\";\n"
benchmark.start 'less-compile'
less.render tmp, compress: true, (err, result) ->
if err then return done(errMsg 'Error processing LESS -> CSS', err)
try
css = result.css
fs.writeFileSync compiledPath, css, 'utf-8'
catch writeErr
return done(errMsg 'Error writing cached CSS to file', writeErr)
benchmark.end 'less-compile'
cache[key] = css
done null, cache[key]
compileTemplate = (filename, options) ->
compiled = """
var pug = require('pug');
#{pug.compileFileClient filename, options}
module.exports = compiledFunc;
"""
getTemplate = (name, verbose, done) ->
# Check if this is a built-in template name
builtin = path.join(ROOT, 'templates', "#{name}.pug")
if not fs.existsSync(name) and fs.existsSync(builtin)
name = builtin
# Get the template function for the given path. This will load and
# compile the template if necessary, and cache it for future use.
key = "<KEY>
# Check if it is cached in memory. If not, then we'll check the disk.
if cache[key] then return done null, cache[key]
# Check if it is compiled on disk and not older than the template file.
# If not present or outdated, then we'll need to compile it.
compiledPath = path.join ROOT, 'cache', "#{sha1 key}.js"
load = (filename, loadDone) ->
try
loaded = require(filename)
catch loadErr
return loadDone(errMsg 'Unable to load template', loadErr)
loadDone null, require(filename)
if verbose
console.log "Using template #{name}"
console.log "Checking cache #{compiledPath}"
getCached key, compiledPath, [name], load, (err, template) ->
if err then return done err
if template
if verbose then console.log 'Cached version loaded'
return done null, template
if verbose
console.log 'Not cached or out of date. Generating template JS...'
# We need to compile the template, then cache it. This is interesting
# because we are compiling to a client-side template, then adding some
# module-specific code to make it work here. This allows us to save time
# in the future by just loading the generated javascript function.
benchmark.start 'pug-compile'
compileOptions =
filename: name
name: 'compiledFunc'
self: true
compileDebug: false
try
compiled = compileTemplate name, compileOptions
catch compileErr
return done(errMsg 'Error compiling template', compileErr)
if compiled.indexOf('self.') is -1
# Not using self, so we probably need to recompile into compatibility
# mode. This is slower, but keeps things working with Pug files
# designed for Aglio 1.x.
compileOptions.self = false
try
compiled = compileTemplate name, compileOptions
catch compileErr
return done(errMsg 'Error compiling template', compileErr)
try
fs.writeFileSync compiledPath, compiled, 'utf-8'
catch writeErr
return done(errMsg 'Error writing cached template file', writeErr)
benchmark.end 'pug-compile'
cache[key] = require(compiledPath)
done null, cache[key]
modifyUriTemplate = (templateUri, parameters, colorize) ->
# Modify a URI template to only include the parameter names from
# the given parameters. For example:
# URI template: /pages/{id}{?verbose}
# Parameters contains a single `id` parameter
# Output: /pages/{id}
parameterValidator = (b) ->
# Compare the names, removing the special `*` operator
parameterNames.indexOf(
querystring.unescape b.replace(/^\*|\*$/, '')) isnt -1
parameterNames = (param.name for param in parameters)
parameterBlocks = []
lastIndex = index = 0
while (index = templateUri.indexOf("{", index)) isnt -1
parameterBlocks.push templateUri.substring(lastIndex, index)
block = {}
closeIndex = templateUri.indexOf("}", index)
block.querySet = templateUri.indexOf("{?", index) is index
block.formSet = templateUri.indexOf("{&", index) is index
block.reservedSet = templateUri.indexOf("{+", index) is index
lastIndex = closeIndex + 1
index++
index++ if block.querySet or block.formSet or block.reservedSet
parameterSet = templateUri.substring(index, closeIndex)
block.parameters = parameterSet.split(",").filter(parameterValidator)
parameterBlocks.push block if block.parameters.length
parameterBlocks.push templateUri.substring(lastIndex, templateUri.length)
parameterBlocks.reduce((uri, v) ->
if typeof v is "string"
uri.push v
else
segment = if not colorize then ["{"] else []
segment.push "?" if v.querySet
segment.push "&" if v.formSet
segment.push "+" if v.reservedSet and not colorize
segment.push v.parameters.map((name) ->
if not colorize then name else
# TODO: handle errors here?
name = name.replace(/^\*|\*$/, '')
param = parameters[parameterNames.indexOf(querystring.unescape name)]
if v.querySet or v.formSet
"<span class=\"hljs-attribute\">#{name}=</span>" +
"<span class=\"hljs-literal\">#{param.example || ''}</span>"
else
"<span class=\"hljs-attribute\" title=\"#{name}\">#{
param.example || name}</span>"
).join(if colorize then '&' else ',')
if not colorize
segment.push "}"
uri.push segment.join("")
uri
, []).join('').replace(/\/+/g, '/')
getTitle = (parseResult) ->
[category, ...] = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'api'
}
]
}
}
}
return category?.meta.title?.content or ''
getDataStructures = (parseResult) ->
results = query parseResult, {
element: 'dataStructure',
content: {
meta: {
id: {
element: 'string'
}
}
}
}
return new -> @[result.content.meta.id.content] = result \
for result in results; @
getApiDescription = (parseResult) ->
[category, ...] = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'api'
}
]
}
},
}
if category?.content.length > 0
content = category.content[0]
return content.content if content.element == 'copy'
return ''
getHost = (parseResult) ->
[category, ...] = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'api'
}
]
}
}
}
[member, ...] = query category?.attributes?.metadata or [], {
element: 'member'
content: {
key: {
content: '<KEY>'
}
}
}
return member?.content.value.content or ''
getResourceGroups = (parseResult, slugCache, md) ->
results = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'resourceGroup'
}
]
}
}
}
return (getResourceGroup result, slugCache, md for result in results)
getResourceGroup = (resourceGroupElement, slugCache, md) ->
slugify = slug.bind slug, slugCache
title = resourceGroupElement.meta.title.content
title_slug = slugify title, true
if resourceGroupElement.content.length > 0 and
resourceGroupElement.content[0].element == 'copy'
description = md.render resourceGroupElement.content[0].content
resourceGroup = {
name: title
elementId: title_slug
elementLink: "##{title_slug}"
descriptionHtml: description or ''
resources: []
}
if description
resourceGroup.navItems = slugCache._nav
slugCache._nav = []
resourceElements = query resourceGroupElement, {element: 'resource'}
resourceGroup.resources = getResources resourceElements, slugCache,
resourceGroup.elementId
return resourceGroup
getResourceDescription = (resourceElement) ->
if resourceElement.content[0]?.element == 'copy'
return resourceElement.content[0].content
return ''
getResources = (resourceElements, slugCache, parentId) ->
return (getResource resourceElement, slugCache, parentId \
for resourceElement in resourceElements)
getResource = (resourceElement, slugCache, parentId) ->
slugify = slug.bind slug, slugCache
title = resourceElement.meta.title.content
title_slug = slugify "#{parentId}-#{title}", true
description = getResourceDescription resourceElement
resource = {
name: title
elementId: title_slug
elementLink: "##{title_slug}"
description: description
actions: []
uriTemplate: resourceElement.attributes?.href.content || ""
}
resource.actions = getActions resourceElement, slugCache,
"#{parentId}-#{title}-#{resource.name}"
return resource
getHeaders = (headersElement) ->
return ({
name: element.content.key.content
value: element.content.value.content
} for element in headersElement or [])
getRequest = (requestElement) ->
hasRequest = requestElement.meta?.title or \
requestElement.content.length > 0
name = requestElement.meta?.title.content
method = requestElement.attributes.method.content
[copy] = query requestElement, {element: 'copy'}
[schema] = query requestElement, {
element: 'asset',
meta: {
classes: {
content: [
{
content: 'messageBodySchema'
}
]
}
}
}
[body] = query requestElement, {
element: 'asset',
meta: {
classes: {
content: [
{
content: 'messageBody'
}
]
}
}
}
headers = getHeaders requestElement.attributes.headers?.content
return {
name: name or ''
description: copy?.content or ''
schema: schema?.content or ''
body: body?.content or ''
headers: headers
content: []
method: method
hasContent: copy?.content? or \
headers.length > 0 or \
body?.content? or \
schema?.content?
}
getResponse = (responseElement) ->
name = responseElement.attributes.statusCode.content
[schema] = query responseElement, {
element: 'asset',
meta: {
classes: {
content: [
{
content: 'messageBodySchema'
}
]
}
}
}
[body] = query responseElement, {
element: 'asset',
meta: {
classes: {
content: [
{
content: 'messageBody'
}
]
}
}
}
[copy] = query responseElement, {element: 'copy'}
headers = getHeaders responseElement.attributes.headers?.content
return {
name: name or ''
description: copy?.content or ''
headers: headers
body: body?.content or ''
schema: schema?.content or ''
content: []
hasContent: copy?.content? or \
headers.length > 0 or \
body?.content? or \
schema?.content?
}
isEmptyMessage = (message) ->
return message.name? and
message.headers.length == 0 and
message.description? and
message.body? and
message.schema? and
message.content.length == 0
getExamples = (actionElement) ->
example = {
name: ''
description: ''
requests: []
responses: []
}
examples = [example]
for httpTransaction in query actionElement, {element: 'httpTransaction'}
for requestElement in query httpTransaction, {element: 'httpRequest'}
request = getRequest requestElement
method = request.method
for responseElement in query httpTransaction, {element: 'httpResponse'}
response = getResponse responseElement
[..., prevRequest] = example?.requests or []
[..., prevResponse] = example?.responses or []
sameRequest = equal prevRequest, request
sameResponse = equal prevResponse, response
if sameRequest
if not sameResponse
example.responses.push response
else
if prevRequest
example = {
name: ''
description: ''
requests: []
responses: []
}
examples.push example
if not isEmptyMessage request
example.requests.push request
if not sameResponse
example.responses.push response
return examples
getRequestMethod = (actionElement) ->
for requestElement in query actionElement, {element: 'httpRequest'}
method = requestElement.attributes.method.content
return method if method
return ''
getActions = (resourceElement, slugCache, parentId) ->
slugify = slug.bind slug, slugCache
actions = []
for actionElement in query resourceElement, {element: 'transition'}
title = actionElement.meta.title.content
method = getRequestMethod actionElement
examples = getExamples actionElement
for example in examples
hasRequest = example.requests.length > 0
break if hasRequest
[..., copy] = query actionElement, {element: 'copy'}
id = slugify "#{parentId}-#{method}",
true
action = {
name: title
description: copy?.content
elementId: id
elementLink: "##{id}"
method: method
methodLower: method.toLowerCase()
hasRequest: hasRequest? or false
examples: examples
}
action.parameters = getParameters actionElement, resourceElement
href = actionElement.attributes?.href or resourceElement.attributes.href \
or {}
uriTemplate = href.content or ''
action.uriTemplate = modifyUriTemplate uriTemplate, action.parameters
action.attributes =
urlTemplate: action.uriTemplate
action.colorizedUriTemplate = modifyUriTemplate uriTemplate,
action.parameters,
true
actions.push action
return actions
getParameters = (actionElement, resourceElement) ->
parameters = []
resourceParams = resourceElement.attributes?.hrefVariables?.content or []
actionParams = actionElement.attributes?.hrefVariables?.content or []
hrefVariables = resourceParams.concat actionParams
for hrefVariable in hrefVariables
requiredElement = query hrefVariable.attributes.typeAttributes, {
content: 'required'
}
valueElement = hrefVariable.content.value
switch valueElement.element
when 'enum'
values = ({value: enumValue.content} for enumValue in \
valueElement.attributes.enumerations.content)
example = valueElement.content.content
else
values = []
example = valueElement.content
parameter = {
name: hrefVariable.content.key.content
description: hrefVariable.meta.description?.content or ''
type: hrefVariable.meta.title?.content
required: requiredElement.length > 0
example: example
values: values
}
parameters.push parameter
return parameters
getMetadata = (parseResult) ->
[category, ...] = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'api'
}
]
}
}
}
return ({
name: meta.content.key.content
value: meta.content.value.content
} for meta in category?.attributes?.metadata?.content or [])
getDefaultResourceGroup = (parseResult, slugCache) ->
[result] = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'api'
}
]
}
},
content: [
{
element: 'resource'
}
]
}
resourceElements = (query result, {element: 'resource'} if result) or []
resources = getResources resourceElements, slugCache, ''
if resources.length > 0
return {
name: ''
elementId: ''
elementLink: ''
descriptionHtml: ''
resources: resources
}
else
return null
decorate = (api, md, slugCache, verbose) ->
# Decorate an API Blueprint AST with various pieces of information that
# will be useful for the theme. Anything that would significantly
# complicate the Pug template should probably live here instead!
# Use the slug caching mechanism
slugify = slug.bind slug, slugCache
# Find data structures. This is a temporary workaround until Drafter is
# updated to support JSON Schema again.
# TODO: Remove me when Drafter is released.
api.name = getTitle api
api.metadata = getMetadata api
dataStructures = getDataStructures api
if verbose
console.log "Known data structures: #{Object.keys(dataStructures)}"
api.descriptionHtml = md.render getApiDescription api
if api.descriptionHtml
api.navItems = slugCache._nav
slugCache._nav = []
api.host = getHost api
api.resourceGroups = getResourceGroups api, slugCache, md
defaultResourceGroup = getDefaultResourceGroup api, slugCache
api.resourceGroups.unshift defaultResourceGroup if defaultResourceGroup
# Get the theme's configuration, used by Aglio to present available
# options and confirm that the input blueprint is a supported
# version.
exports.getConfig = ->
formats: ['1A']
options: [
{name: 'variables',
description: 'Color scheme name or path to custom variables',
default: 'default'},
{name: 'condense-nav', description: 'Condense navigation links',
boolean: true, default: true},
{name: 'full-width', description: 'Use full window width',
boolean: true, default: false},
{name: 'template', description: 'Template name or path to custom template',
default: 'default'},
{name: 'style',
description: 'Layout style name or path to custom stylesheet'},
{name: 'emoji', description: 'Enable support for emoticons',
boolean: true, default: true}
]
# Render the blueprint with the given options using Pug and LESS
exports.render = (input, options, done) ->
if not done?
done = options
options = {}
# Disable the template/css caching?
if process.env.NOCACHE then cache = {}
# This is purely for backward-compatibility
if options.condenseNav then options.themeCondenseNav = options.condenseNav
if options.fullWidth then options.themeFullWidth = options.fullWidth
# Setup defaults
options.themeVariables ?= 'default'
options.themeStyle ?= 'default'
options.themeTemplate ?= 'default'
options.themeCondenseNav ?= true
options.themeFullWidth ?= false
# Transform built-in layout names to paths
if options.themeTemplate is 'default'
options.themeTemplate = path.join ROOT, 'templates', 'index.pug'
# Setup markdown with code highlighting and smartypants. This also enables
# automatically inserting permalinks for headers.
slugCache =
_nav: []
md = markdownIt(
html: true
linkify: true
typographer: true
highlight: highlight
).use(require('markdown-it-anchor'),
slugify: (value) ->
output = "header-#{slug(slugCache, value, true)}"
slugCache._nav.push [value, "##{output}"]
return output
permalink: true
permalinkClass: 'permalink'
).use(require('markdown-it-checkbox')
).use(require('markdown-it-container'), 'note'
).use(require('markdown-it-container'), 'warning')
if options.themeEmoji then md.use require('markdown-it-emoji')
# Enable code highlighting for unfenced code blocks
md.renderer.rules.code_block = md.renderer.rules.fence
benchmark.start 'decorate'
decorate input, md, slugCache, options.verbose
benchmark.end 'decorate'
benchmark.start 'css-total'
{themeVariables, themeStyle, verbose} = options
getCss themeVariables, themeStyle, verbose, (err, css) ->
if err then return done(errMsg 'Could not get CSS', err)
benchmark.end 'css-total'
locals =
api: input
condenseNav: options.themeCondenseNav
css: css
fullWidth: options.themeFullWidth
date: moment
hash: (value) ->
crypto.createHash('md5').update(value.toString()).digest('hex')
highlight: highlight
markdown: (content) -> md.render content
slug: slug.bind(slug, slugCache)
urldec: (value) -> querystring.unescape(value)
for key, value of options.locals or {}
locals[key] = value
benchmark.start 'get-template'
getTemplate options.themeTemplate, verbose, (getTemplateErr, renderer) ->
if getTemplateErr
return done(errMsg 'Could not get template', getTemplateErr)
benchmark.end 'get-template'
benchmark.start 'call-template'
try html = renderer locals
catch err
return done(errMsg 'Error calling template during rendering', err)
benchmark.end 'call-template'
done null, html
| true | crypto = require 'crypto'
fs = require 'fs'
hljs = require 'highlight.js'
pug = require 'pug'
less = require 'less'
markdownIt = require 'markdown-it'
moment = require 'moment'
path = require 'path'
querystring = require 'querystring'
equal = require 'deep-equal'
query = require '@gasolwu/refract-query'
renderExample = require './example'
renderSchema = require './schema'
# The root directory of this project
ROOT = path.dirname __dirname
cache = {}
# Utility for benchmarking
benchmark =
start: (message) -> if process.env.BENCHMARK then console.time message
end: (message) -> if process.env.BENCHMARK then console.timeEnd message
# Extend an error's message. Returns the modified error.
errMsg = (message, err) ->
err.message = "#{message}: #{err.message}"
return err
# Generate a SHA1 hash
sha1 = (value) ->
crypto.createHash('sha1').update(value.toString()).digest('hex')
# A function to create ID-safe slugs. If `unique` is passed, then
# unique slugs are returned for the same input. The cache is just
# a plain object where the keys are the sluggified name.
slug = (cache={}, value='', unique=false) ->
sluggified = value.toLowerCase()
.replace(/[ \t\n\\<>"'=:/]/g, '-')
.replace(/-+/g, '-')
.replace(/^-/, '')
if unique
while cache[sluggified]
# Already exists, so let's try to make it unique.
if sluggified.match /\d+$/
sluggified = sluggified.replace /\d+$/, (value) ->
parseInt(value) + 1
else
sluggified = sluggified + '-1'
cache[sluggified] = true
return sluggified
# A function to highlight snippets of code. lang is optional and
# if given, is used to set the code language. If lang is no-highlight
# then no highlighting is performed.
highlight = (code, lang, subset) ->
benchmark.start "highlight #{lang}"
response = switch lang
when 'no-highlight' then code
when undefined, null, ''
hljs.highlightAuto(code, subset).value
else hljs.highlight(lang, code).value
benchmark.end "highlight #{lang}"
return response.trim()
getCached = (key, compiledPath, sources, load, done) ->
# Disable the template/css caching?
if process.env.NOCACHE then return done null
# Already loaded? Just return it!
if cache[key] then return done null, cache[key]
# Next, try to check if the compiled path exists and is newer than all of
# the sources. If so, load the compiled path into the in-memory cache.
try
if fs.existsSync compiledPath
compiledStats = fs.statSync compiledPath
for source in sources
sourceStats = fs.statSync source
if sourceStats.mtime > compiledStats.mtime
# There is a newer source file, so we ignore the compiled
# version on disk. It'll be regenerated later.
return done null
try
load compiledPath, (err, item) ->
if err then return done(errMsg 'Error loading cached resource', err)
cache[key] = item
done null, cache[key]
catch loadErr
return done(errMsg 'Error loading cached resource', loadErr)
else
done null
catch err
done err
getCss = (variables, styles, verbose, done) ->
# Get the CSS for the given variables and style. This method caches
# its output, so subsequent calls will be extremely fast but will
# not reload potentially changed data from disk.
# The CSS is generated via a dummy LESS file with imports to the
# default variables, any custom override variables, and the given
# layout style. Both variables and style support special values,
# for example `flatly` might load `styles/variables-flatly.less`.
# See the `styles` directory for available options.
key = "PI:KEY:<KEY>END_PIstylesPI:KEY:<KEY>END_PI}"
if cache[key] then return done null, cache[key]
# Not cached in memory, but maybe it's already compiled on disk?
compiledPath = path.join ROOT, 'cache',
"#{sha1 key}.css"
defaultVariablePath = path.join ROOT, 'styles', 'variables-default.less'
sources = [defaultVariablePath]
if not Array.isArray(variables) then variables = [variables]
if not Array.isArray(styles) then styles = [styles]
variablePaths = [defaultVariablePath]
for item in variables
if item isnt 'default'
customPath = path.join ROOT, 'styles', "variables-#{item}.less"
if not fs.existsSync customPath
customPath = item
if not fs.existsSync customPath
return done new Error "#{customPath} does not exist!"
variablePaths.push customPath
sources.push customPath
stylePaths = []
for item in styles
customPath = path.join ROOT, 'styles', "layout-#{item}.less"
if not fs.existsSync customPath
customPath = item
if not fs.existsSync customPath
return done new Error "#{customPath} does not exist!"
stylePaths.push customPath
sources.push customPath
load = (filename, loadDone) ->
fs.readFile filename, 'utf-8', loadDone
if verbose
console.log "Using variables #{variablePaths}"
console.log "Using styles #{stylePaths}"
console.log "Checking cache #{compiledPath}"
getCached key, compiledPath, sources, load, (err, css) ->
if err then return done err
if css
if verbose then console.log 'Cached version loaded'
return done null, css
# Not cached, so let's create the file.
if verbose
console.log 'Not cached or out of date. Generating CSS...'
tmp = ''
for customPath in variablePaths
tmp += "@import \"#{customPath}\";\n"
for customPath in stylePaths
tmp += "@import \"#{customPath}\";\n"
benchmark.start 'less-compile'
less.render tmp, compress: true, (err, result) ->
if err then return done(errMsg 'Error processing LESS -> CSS', err)
try
css = result.css
fs.writeFileSync compiledPath, css, 'utf-8'
catch writeErr
return done(errMsg 'Error writing cached CSS to file', writeErr)
benchmark.end 'less-compile'
cache[key] = css
done null, cache[key]
compileTemplate = (filename, options) ->
compiled = """
var pug = require('pug');
#{pug.compileFileClient filename, options}
module.exports = compiledFunc;
"""
getTemplate = (name, verbose, done) ->
# Check if this is a built-in template name
builtin = path.join(ROOT, 'templates', "#{name}.pug")
if not fs.existsSync(name) and fs.existsSync(builtin)
name = builtin
# Get the template function for the given path. This will load and
# compile the template if necessary, and cache it for future use.
key = "PI:KEY:<KEY>END_PI
# Check if it is cached in memory. If not, then we'll check the disk.
if cache[key] then return done null, cache[key]
# Check if it is compiled on disk and not older than the template file.
# If not present or outdated, then we'll need to compile it.
compiledPath = path.join ROOT, 'cache', "#{sha1 key}.js"
load = (filename, loadDone) ->
try
loaded = require(filename)
catch loadErr
return loadDone(errMsg 'Unable to load template', loadErr)
loadDone null, require(filename)
if verbose
console.log "Using template #{name}"
console.log "Checking cache #{compiledPath}"
getCached key, compiledPath, [name], load, (err, template) ->
if err then return done err
if template
if verbose then console.log 'Cached version loaded'
return done null, template
if verbose
console.log 'Not cached or out of date. Generating template JS...'
# We need to compile the template, then cache it. This is interesting
# because we are compiling to a client-side template, then adding some
# module-specific code to make it work here. This allows us to save time
# in the future by just loading the generated javascript function.
benchmark.start 'pug-compile'
compileOptions =
filename: name
name: 'compiledFunc'
self: true
compileDebug: false
try
compiled = compileTemplate name, compileOptions
catch compileErr
return done(errMsg 'Error compiling template', compileErr)
if compiled.indexOf('self.') is -1
# Not using self, so we probably need to recompile into compatibility
# mode. This is slower, but keeps things working with Pug files
# designed for Aglio 1.x.
compileOptions.self = false
try
compiled = compileTemplate name, compileOptions
catch compileErr
return done(errMsg 'Error compiling template', compileErr)
try
fs.writeFileSync compiledPath, compiled, 'utf-8'
catch writeErr
return done(errMsg 'Error writing cached template file', writeErr)
benchmark.end 'pug-compile'
cache[key] = require(compiledPath)
done null, cache[key]
modifyUriTemplate = (templateUri, parameters, colorize) ->
# Modify a URI template to only include the parameter names from
# the given parameters. For example:
# URI template: /pages/{id}{?verbose}
# Parameters contains a single `id` parameter
# Output: /pages/{id}
parameterValidator = (b) ->
# Compare the names, removing the special `*` operator
parameterNames.indexOf(
querystring.unescape b.replace(/^\*|\*$/, '')) isnt -1
parameterNames = (param.name for param in parameters)
parameterBlocks = []
lastIndex = index = 0
while (index = templateUri.indexOf("{", index)) isnt -1
parameterBlocks.push templateUri.substring(lastIndex, index)
block = {}
closeIndex = templateUri.indexOf("}", index)
block.querySet = templateUri.indexOf("{?", index) is index
block.formSet = templateUri.indexOf("{&", index) is index
block.reservedSet = templateUri.indexOf("{+", index) is index
lastIndex = closeIndex + 1
index++
index++ if block.querySet or block.formSet or block.reservedSet
parameterSet = templateUri.substring(index, closeIndex)
block.parameters = parameterSet.split(",").filter(parameterValidator)
parameterBlocks.push block if block.parameters.length
parameterBlocks.push templateUri.substring(lastIndex, templateUri.length)
parameterBlocks.reduce((uri, v) ->
if typeof v is "string"
uri.push v
else
segment = if not colorize then ["{"] else []
segment.push "?" if v.querySet
segment.push "&" if v.formSet
segment.push "+" if v.reservedSet and not colorize
segment.push v.parameters.map((name) ->
if not colorize then name else
# TODO: handle errors here?
name = name.replace(/^\*|\*$/, '')
param = parameters[parameterNames.indexOf(querystring.unescape name)]
if v.querySet or v.formSet
"<span class=\"hljs-attribute\">#{name}=</span>" +
"<span class=\"hljs-literal\">#{param.example || ''}</span>"
else
"<span class=\"hljs-attribute\" title=\"#{name}\">#{
param.example || name}</span>"
).join(if colorize then '&' else ',')
if not colorize
segment.push "}"
uri.push segment.join("")
uri
, []).join('').replace(/\/+/g, '/')
getTitle = (parseResult) ->
[category, ...] = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'api'
}
]
}
}
}
return category?.meta.title?.content or ''
getDataStructures = (parseResult) ->
results = query parseResult, {
element: 'dataStructure',
content: {
meta: {
id: {
element: 'string'
}
}
}
}
return new -> @[result.content.meta.id.content] = result \
for result in results; @
getApiDescription = (parseResult) ->
[category, ...] = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'api'
}
]
}
},
}
if category?.content.length > 0
content = category.content[0]
return content.content if content.element == 'copy'
return ''
getHost = (parseResult) ->
[category, ...] = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'api'
}
]
}
}
}
[member, ...] = query category?.attributes?.metadata or [], {
element: 'member'
content: {
key: {
content: 'PI:KEY:<KEY>END_PI'
}
}
}
return member?.content.value.content or ''
getResourceGroups = (parseResult, slugCache, md) ->
results = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'resourceGroup'
}
]
}
}
}
return (getResourceGroup result, slugCache, md for result in results)
getResourceGroup = (resourceGroupElement, slugCache, md) ->
slugify = slug.bind slug, slugCache
title = resourceGroupElement.meta.title.content
title_slug = slugify title, true
if resourceGroupElement.content.length > 0 and
resourceGroupElement.content[0].element == 'copy'
description = md.render resourceGroupElement.content[0].content
resourceGroup = {
name: title
elementId: title_slug
elementLink: "##{title_slug}"
descriptionHtml: description or ''
resources: []
}
if description
resourceGroup.navItems = slugCache._nav
slugCache._nav = []
resourceElements = query resourceGroupElement, {element: 'resource'}
resourceGroup.resources = getResources resourceElements, slugCache,
resourceGroup.elementId
return resourceGroup
getResourceDescription = (resourceElement) ->
if resourceElement.content[0]?.element == 'copy'
return resourceElement.content[0].content
return ''
getResources = (resourceElements, slugCache, parentId) ->
return (getResource resourceElement, slugCache, parentId \
for resourceElement in resourceElements)
getResource = (resourceElement, slugCache, parentId) ->
slugify = slug.bind slug, slugCache
title = resourceElement.meta.title.content
title_slug = slugify "#{parentId}-#{title}", true
description = getResourceDescription resourceElement
resource = {
name: title
elementId: title_slug
elementLink: "##{title_slug}"
description: description
actions: []
uriTemplate: resourceElement.attributes?.href.content || ""
}
resource.actions = getActions resourceElement, slugCache,
"#{parentId}-#{title}-#{resource.name}"
return resource
getHeaders = (headersElement) ->
return ({
name: element.content.key.content
value: element.content.value.content
} for element in headersElement or [])
getRequest = (requestElement) ->
hasRequest = requestElement.meta?.title or \
requestElement.content.length > 0
name = requestElement.meta?.title.content
method = requestElement.attributes.method.content
[copy] = query requestElement, {element: 'copy'}
[schema] = query requestElement, {
element: 'asset',
meta: {
classes: {
content: [
{
content: 'messageBodySchema'
}
]
}
}
}
[body] = query requestElement, {
element: 'asset',
meta: {
classes: {
content: [
{
content: 'messageBody'
}
]
}
}
}
headers = getHeaders requestElement.attributes.headers?.content
return {
name: name or ''
description: copy?.content or ''
schema: schema?.content or ''
body: body?.content or ''
headers: headers
content: []
method: method
hasContent: copy?.content? or \
headers.length > 0 or \
body?.content? or \
schema?.content?
}
getResponse = (responseElement) ->
name = responseElement.attributes.statusCode.content
[schema] = query responseElement, {
element: 'asset',
meta: {
classes: {
content: [
{
content: 'messageBodySchema'
}
]
}
}
}
[body] = query responseElement, {
element: 'asset',
meta: {
classes: {
content: [
{
content: 'messageBody'
}
]
}
}
}
[copy] = query responseElement, {element: 'copy'}
headers = getHeaders responseElement.attributes.headers?.content
return {
name: name or ''
description: copy?.content or ''
headers: headers
body: body?.content or ''
schema: schema?.content or ''
content: []
hasContent: copy?.content? or \
headers.length > 0 or \
body?.content? or \
schema?.content?
}
isEmptyMessage = (message) ->
return message.name? and
message.headers.length == 0 and
message.description? and
message.body? and
message.schema? and
message.content.length == 0
getExamples = (actionElement) ->
example = {
name: ''
description: ''
requests: []
responses: []
}
examples = [example]
for httpTransaction in query actionElement, {element: 'httpTransaction'}
for requestElement in query httpTransaction, {element: 'httpRequest'}
request = getRequest requestElement
method = request.method
for responseElement in query httpTransaction, {element: 'httpResponse'}
response = getResponse responseElement
[..., prevRequest] = example?.requests or []
[..., prevResponse] = example?.responses or []
sameRequest = equal prevRequest, request
sameResponse = equal prevResponse, response
if sameRequest
if not sameResponse
example.responses.push response
else
if prevRequest
example = {
name: ''
description: ''
requests: []
responses: []
}
examples.push example
if not isEmptyMessage request
example.requests.push request
if not sameResponse
example.responses.push response
return examples
getRequestMethod = (actionElement) ->
for requestElement in query actionElement, {element: 'httpRequest'}
method = requestElement.attributes.method.content
return method if method
return ''
getActions = (resourceElement, slugCache, parentId) ->
slugify = slug.bind slug, slugCache
actions = []
for actionElement in query resourceElement, {element: 'transition'}
title = actionElement.meta.title.content
method = getRequestMethod actionElement
examples = getExamples actionElement
for example in examples
hasRequest = example.requests.length > 0
break if hasRequest
[..., copy] = query actionElement, {element: 'copy'}
id = slugify "#{parentId}-#{method}",
true
action = {
name: title
description: copy?.content
elementId: id
elementLink: "##{id}"
method: method
methodLower: method.toLowerCase()
hasRequest: hasRequest? or false
examples: examples
}
action.parameters = getParameters actionElement, resourceElement
href = actionElement.attributes?.href or resourceElement.attributes.href \
or {}
uriTemplate = href.content or ''
action.uriTemplate = modifyUriTemplate uriTemplate, action.parameters
action.attributes =
urlTemplate: action.uriTemplate
action.colorizedUriTemplate = modifyUriTemplate uriTemplate,
action.parameters,
true
actions.push action
return actions
getParameters = (actionElement, resourceElement) ->
parameters = []
resourceParams = resourceElement.attributes?.hrefVariables?.content or []
actionParams = actionElement.attributes?.hrefVariables?.content or []
hrefVariables = resourceParams.concat actionParams
for hrefVariable in hrefVariables
requiredElement = query hrefVariable.attributes.typeAttributes, {
content: 'required'
}
valueElement = hrefVariable.content.value
switch valueElement.element
when 'enum'
values = ({value: enumValue.content} for enumValue in \
valueElement.attributes.enumerations.content)
example = valueElement.content.content
else
values = []
example = valueElement.content
parameter = {
name: hrefVariable.content.key.content
description: hrefVariable.meta.description?.content or ''
type: hrefVariable.meta.title?.content
required: requiredElement.length > 0
example: example
values: values
}
parameters.push parameter
return parameters
getMetadata = (parseResult) ->
[category, ...] = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'api'
}
]
}
}
}
return ({
name: meta.content.key.content
value: meta.content.value.content
} for meta in category?.attributes?.metadata?.content or [])
getDefaultResourceGroup = (parseResult, slugCache) ->
[result] = query parseResult, {
element: 'category',
meta: {
classes: {
content: [
{
content: 'api'
}
]
}
},
content: [
{
element: 'resource'
}
]
}
resourceElements = (query result, {element: 'resource'} if result) or []
resources = getResources resourceElements, slugCache, ''
if resources.length > 0
return {
name: ''
elementId: ''
elementLink: ''
descriptionHtml: ''
resources: resources
}
else
return null
decorate = (api, md, slugCache, verbose) ->
# Decorate an API Blueprint AST with various pieces of information that
# will be useful for the theme. Anything that would significantly
# complicate the Pug template should probably live here instead!
# Use the slug caching mechanism
slugify = slug.bind slug, slugCache
# Find data structures. This is a temporary workaround until Drafter is
# updated to support JSON Schema again.
# TODO: Remove me when Drafter is released.
api.name = getTitle api
api.metadata = getMetadata api
dataStructures = getDataStructures api
if verbose
console.log "Known data structures: #{Object.keys(dataStructures)}"
api.descriptionHtml = md.render getApiDescription api
if api.descriptionHtml
api.navItems = slugCache._nav
slugCache._nav = []
api.host = getHost api
api.resourceGroups = getResourceGroups api, slugCache, md
defaultResourceGroup = getDefaultResourceGroup api, slugCache
api.resourceGroups.unshift defaultResourceGroup if defaultResourceGroup
# Get the theme's configuration, used by Aglio to present available
# options and confirm that the input blueprint is a supported
# version.
exports.getConfig = ->
formats: ['1A']
options: [
{name: 'variables',
description: 'Color scheme name or path to custom variables',
default: 'default'},
{name: 'condense-nav', description: 'Condense navigation links',
boolean: true, default: true},
{name: 'full-width', description: 'Use full window width',
boolean: true, default: false},
{name: 'template', description: 'Template name or path to custom template',
default: 'default'},
{name: 'style',
description: 'Layout style name or path to custom stylesheet'},
{name: 'emoji', description: 'Enable support for emoticons',
boolean: true, default: true}
]
# Render the blueprint with the given options using Pug and LESS
exports.render = (input, options, done) ->
if not done?
done = options
options = {}
# Disable the template/css caching?
if process.env.NOCACHE then cache = {}
# This is purely for backward-compatibility
if options.condenseNav then options.themeCondenseNav = options.condenseNav
if options.fullWidth then options.themeFullWidth = options.fullWidth
# Setup defaults
options.themeVariables ?= 'default'
options.themeStyle ?= 'default'
options.themeTemplate ?= 'default'
options.themeCondenseNav ?= true
options.themeFullWidth ?= false
# Transform built-in layout names to paths
if options.themeTemplate is 'default'
options.themeTemplate = path.join ROOT, 'templates', 'index.pug'
# Setup markdown with code highlighting and smartypants. This also enables
# automatically inserting permalinks for headers.
slugCache =
_nav: []
md = markdownIt(
html: true
linkify: true
typographer: true
highlight: highlight
).use(require('markdown-it-anchor'),
slugify: (value) ->
output = "header-#{slug(slugCache, value, true)}"
slugCache._nav.push [value, "##{output}"]
return output
permalink: true
permalinkClass: 'permalink'
).use(require('markdown-it-checkbox')
).use(require('markdown-it-container'), 'note'
).use(require('markdown-it-container'), 'warning')
if options.themeEmoji then md.use require('markdown-it-emoji')
# Enable code highlighting for unfenced code blocks
md.renderer.rules.code_block = md.renderer.rules.fence
benchmark.start 'decorate'
decorate input, md, slugCache, options.verbose
benchmark.end 'decorate'
benchmark.start 'css-total'
{themeVariables, themeStyle, verbose} = options
getCss themeVariables, themeStyle, verbose, (err, css) ->
if err then return done(errMsg 'Could not get CSS', err)
benchmark.end 'css-total'
locals =
api: input
condenseNav: options.themeCondenseNav
css: css
fullWidth: options.themeFullWidth
date: moment
hash: (value) ->
crypto.createHash('md5').update(value.toString()).digest('hex')
highlight: highlight
markdown: (content) -> md.render content
slug: slug.bind(slug, slugCache)
urldec: (value) -> querystring.unescape(value)
for key, value of options.locals or {}
locals[key] = value
benchmark.start 'get-template'
getTemplate options.themeTemplate, verbose, (getTemplateErr, renderer) ->
if getTemplateErr
return done(errMsg 'Could not get template', getTemplateErr)
benchmark.end 'get-template'
benchmark.start 'call-template'
try html = renderer locals
catch err
return done(errMsg 'Error calling template during rendering', err)
benchmark.end 'call-template'
done null, html
|
[
{
"context": "r_dir', ()->\n account = 'the-account'\n token = 'the-token'\n login1 = 'the-login'\n login2 = 'second:login'",
"end": 248,
"score": 0.99396151304245,
"start": 239,
"tag": "PASSWORD",
"value": "the-token"
},
{
"context": "= 'the-account'\n token = 'the-token'\n lo... | test/directory_test.coffee | conjurinc/api-node | 2 | assert = require('assert')
gently = new (require('gently'))
g = require('../lib/global')
conjur_dir = require('../lib/conjur/directory')
{makeEvents} = require('./helpers')
describe 'conjur_dir', ()->
account = 'the-account'
token = 'the-token'
login1 = 'the-login'
login2 = 'second:login'
logins = [ login1, login2 ]
id1 = 1001
id2 = 1002
ids = [ id1, id2 ]
connection = conjur_dir.connect('http://example.com', token)
describe_number = (numberType, path) ->
describe "##{numberType}", ->
stubGet = (result, statusCode)->
gently.expect g.rest, 'get', (url)->
assert.equal url, g.format(
"http://example.com/#{path}/#{numberType}?id[]=%s&id[]=%s",
encodeURIComponent(login1), encodeURIComponent(login2))
makeEvents (arg, callback)->
if arg == 'complete'
callback(result, { statusCode: statusCode })
else
throw new Error 'unexpected arg : ' + arg
describe 'with status code 404', ()->
it 'returns false', (done)->
stubGet null, 404
connection[numberType] logins, (err, result)->
assert err
assert !result
done()
describe 'with status code 200', ()->
it 'returns the ids', (done)->
stubGet ids, 200
connection[numberType] logins, (err, result)->
assert !err
assert.deepEqual ids, result
done()
describe_number 'uidnumbers', 'users'
describe_number 'gidnumbers', 'groups'
| 201592 | assert = require('assert')
gently = new (require('gently'))
g = require('../lib/global')
conjur_dir = require('../lib/conjur/directory')
{makeEvents} = require('./helpers')
describe 'conjur_dir', ()->
account = 'the-account'
token = '<PASSWORD>'
login1 = 'the-login'
login2 = 'second:<PASSWORD>'
logins = [ login1, login2 ]
id1 = 1001
id2 = 1002
ids = [ id1, id2 ]
connection = conjur_dir.connect('http://example.com', token)
describe_number = (numberType, path) ->
describe "##{numberType}", ->
stubGet = (result, statusCode)->
gently.expect g.rest, 'get', (url)->
assert.equal url, g.format(
"http://example.com/#{path}/#{numberType}?id[]=%s&id[]=%s",
encodeURIComponent(login1), encodeURIComponent(login2))
makeEvents (arg, callback)->
if arg == 'complete'
callback(result, { statusCode: statusCode })
else
throw new Error 'unexpected arg : ' + arg
describe 'with status code 404', ()->
it 'returns false', (done)->
stubGet null, 404
connection[numberType] logins, (err, result)->
assert err
assert !result
done()
describe 'with status code 200', ()->
it 'returns the ids', (done)->
stubGet ids, 200
connection[numberType] logins, (err, result)->
assert !err
assert.deepEqual ids, result
done()
describe_number 'uidnumbers', 'users'
describe_number 'gidnumbers', 'groups'
| true | assert = require('assert')
gently = new (require('gently'))
g = require('../lib/global')
conjur_dir = require('../lib/conjur/directory')
{makeEvents} = require('./helpers')
describe 'conjur_dir', ()->
account = 'the-account'
token = 'PI:PASSWORD:<PASSWORD>END_PI'
login1 = 'the-login'
login2 = 'second:PI:PASSWORD:<PASSWORD>END_PI'
logins = [ login1, login2 ]
id1 = 1001
id2 = 1002
ids = [ id1, id2 ]
connection = conjur_dir.connect('http://example.com', token)
describe_number = (numberType, path) ->
describe "##{numberType}", ->
stubGet = (result, statusCode)->
gently.expect g.rest, 'get', (url)->
assert.equal url, g.format(
"http://example.com/#{path}/#{numberType}?id[]=%s&id[]=%s",
encodeURIComponent(login1), encodeURIComponent(login2))
makeEvents (arg, callback)->
if arg == 'complete'
callback(result, { statusCode: statusCode })
else
throw new Error 'unexpected arg : ' + arg
describe 'with status code 404', ()->
it 'returns false', (done)->
stubGet null, 404
connection[numberType] logins, (err, result)->
assert err
assert !result
done()
describe 'with status code 200', ()->
it 'returns the ids', (done)->
stubGet ids, 200
connection[numberType] logins, (err, result)->
assert !err
assert.deepEqual ids, result
done()
describe_number 'uidnumbers', 'users'
describe_number 'gidnumbers', 'groups'
|
[
{
"context": "###\nCopyright 2016 Balena\n\nLicensed under the Apache License, Version 2.0 (",
"end": 25,
"score": 0.9983971118927002,
"start": 19,
"tag": "NAME",
"value": "Balena"
},
{
"context": " following documentation:\n#\n#\t\thttps://github.com/flatiron/revalidator\n###\nmodul... | lib/schema.coffee | balena-io-modules/resin-device-config | 2 | ###
Copyright 2016 Balena
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.
###
_ = require('lodash')
###*
# @summary config.json validation schema
# @name schema
# @type {Object}
#
# @description
# This is a `revalidator` schema. Refer to the following documentation:
#
# https://github.com/flatiron/revalidator
###
module.exports =
properties:
# Included for backwards compatibility - it does not exist in modern config files
applicationName:
description: 'application name'
type: 'string'
required: false
allowEmpty: false
applicationId:
description: 'application id'
type: 'number'
minimum: 0
required: true
deviceType:
description: 'device type'
type: 'string'
required: true
allowEmpty: false
# Included for backwards compatibility - it does not exist in modern config files
userId:
description: 'user id'
type: 'number'
minimum: 0
required: false
# Included for backwards compatibility - it does not exist in modern config files
username:
description: 'username'
type: 'string'
required: false
allowEmpty: false
files:
description: 'files'
type: 'object'
required: false
properties:
'network/settings':
description: 'network settings'
type: 'string'
required: true
allowEmpty: false
'network/network.config':
description: 'network config'
type: 'string'
required: true
allowEmpty: false
appUpdatePollInterval:
description: 'app update poll interval'
type: 'number'
minimum: 0
required: true
listenPort:
description: 'listen port'
type: 'number'
minimum: 0
required: true
# Included for backwards compatibility - it does not exist in modern config files
vpnPort:
description: 'vpn port'
type: 'number'
minimum: 0
required: false
conform: _.negate(_.isNaN)
messages:
conform: 'is NaN'
apiEndpoint:
description: 'api endpoint'
type: 'string'
required: true
allowEmpty: false
format: 'url'
deltaEndpoint:
description: 'delta endpoint'
type: 'string'
required: false
allowEmpty: false
format: 'url'
# Included for backwards compatibility - it does not exist in modern config files
vpnEndpoint:
description: 'vpn endpoint'
type: 'string'
required: false
allowEmpty: false
format: 'host-name'
registryEndpoint:
description: 'registry endpoint'
type: 'string'
required: true
allowEmpty: false
format: 'host-name'
# Included for backwards compatibility - it does not exist in modern config files
pubnubSubscribeKey:
description: 'pubnub subscribe key'
type: 'string'
required: false
allowEmpty: true
# Included for backwards compatibility - it does not exist in modern config files
pubnubPublishKey:
description: 'pubnub publish key'
type: 'string'
required: false
allowEmpty: true
# Included for backwards compatibility - it does not exist in modern config files
mixpanelToken:
description: 'mixpanel token'
type: 'string'
required: false
allowEmpty: false
balenaRootCA:
description: 'balena root CA'
type: 'string'
required: false
allowEmpty: false
# An api key is required, but it can be either apiKey or deviceApiKey (not both)
apiKey:
description: 'api key'
type: 'string'
required: false
allowEmpty: false
# The device api key is only useful if coupled with a uuid
deviceApiKey:
description: 'device api key'
type: 'string'
required: false
allowEmpty: false
registered_at:
description: 'registered at'
type: 'number'
minimum: 0
format: 'utc-millisec'
deviceId:
description: 'device id'
type: 'number'
minimum: 0
uuid:
description: 'uuid'
type: 'string'
allowEmpty: false
pattern: /^[0-9a-f]{32,62}$/
wifiSsid:
description: 'wifi ssid'
type: 'string'
allowEmpty: true
wifiKey:
description: 'wifi key'
type: 'string'
allowEmpty: true
connectivity:
description: 'network management software'
type: 'string'
allowEmpty: false
enum: ['NetworkManager', 'connman']
default: 'connman'
network:
description: 'network configurations'
type: 'array'
required: false
items:
type: 'object'
properties:
wifiSsid:
description: 'wifi ssid'
type: 'string'
allowEmpty: true
wifiKey:
description: 'wifi key'
type: 'string'
allowEmpty: true
configuration:
description: 'configuration'
type: 'string'
allowEmpty: true
| 81690 | ###
Copyright 2016 <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.
###
_ = require('lodash')
###*
# @summary config.json validation schema
# @name schema
# @type {Object}
#
# @description
# This is a `revalidator` schema. Refer to the following documentation:
#
# https://github.com/flatiron/revalidator
###
module.exports =
properties:
# Included for backwards compatibility - it does not exist in modern config files
applicationName:
description: 'application name'
type: 'string'
required: false
allowEmpty: false
applicationId:
description: 'application id'
type: 'number'
minimum: 0
required: true
deviceType:
description: 'device type'
type: 'string'
required: true
allowEmpty: false
# Included for backwards compatibility - it does not exist in modern config files
userId:
description: 'user id'
type: 'number'
minimum: 0
required: false
# Included for backwards compatibility - it does not exist in modern config files
username:
description: 'username'
type: 'string'
required: false
allowEmpty: false
files:
description: 'files'
type: 'object'
required: false
properties:
'network/settings':
description: 'network settings'
type: 'string'
required: true
allowEmpty: false
'network/network.config':
description: 'network config'
type: 'string'
required: true
allowEmpty: false
appUpdatePollInterval:
description: 'app update poll interval'
type: 'number'
minimum: 0
required: true
listenPort:
description: 'listen port'
type: 'number'
minimum: 0
required: true
# Included for backwards compatibility - it does not exist in modern config files
vpnPort:
description: 'vpn port'
type: 'number'
minimum: 0
required: false
conform: _.negate(_.isNaN)
messages:
conform: 'is NaN'
apiEndpoint:
description: 'api endpoint'
type: 'string'
required: true
allowEmpty: false
format: 'url'
deltaEndpoint:
description: 'delta endpoint'
type: 'string'
required: false
allowEmpty: false
format: 'url'
# Included for backwards compatibility - it does not exist in modern config files
vpnEndpoint:
description: 'vpn endpoint'
type: 'string'
required: false
allowEmpty: false
format: 'host-name'
registryEndpoint:
description: 'registry endpoint'
type: 'string'
required: true
allowEmpty: false
format: 'host-name'
# Included for backwards compatibility - it does not exist in modern config files
pubnubSubscribeKey:
description: 'pubnub subscribe key'
type: 'string'
required: false
allowEmpty: true
# Included for backwards compatibility - it does not exist in modern config files
pubnubPublishKey:
description: 'pubnub publish key'
type: 'string'
required: false
allowEmpty: true
# Included for backwards compatibility - it does not exist in modern config files
mixpanelToken:
description: 'mixpanel token'
type: 'string'
required: false
allowEmpty: false
balenaRootCA:
description: 'balena root CA'
type: 'string'
required: false
allowEmpty: false
# An api key is required, but it can be either apiKey or deviceApiKey (not both)
apiKey:
description: 'api key'
type: 'string'
required: false
allowEmpty: false
# The device api key is only useful if coupled with a uuid
deviceApiKey:
description: 'device api key'
type: 'string'
required: false
allowEmpty: false
registered_at:
description: 'registered at'
type: 'number'
minimum: 0
format: 'utc-millisec'
deviceId:
description: 'device id'
type: 'number'
minimum: 0
uuid:
description: 'uuid'
type: 'string'
allowEmpty: false
pattern: /^[0-9a-f]{32,62}$/
wifiSsid:
description: 'wifi ssid'
type: 'string'
allowEmpty: true
wifiKey:
description: 'wifi key'
type: 'string'
allowEmpty: true
connectivity:
description: 'network management software'
type: 'string'
allowEmpty: false
enum: ['NetworkManager', 'connman']
default: 'connman'
network:
description: 'network configurations'
type: 'array'
required: false
items:
type: 'object'
properties:
wifiSsid:
description: 'wifi ssid'
type: 'string'
allowEmpty: true
wifiKey:
description: 'wifi key'
type: 'string'
allowEmpty: true
configuration:
description: 'configuration'
type: 'string'
allowEmpty: true
| true | ###
Copyright 2016 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.
###
_ = require('lodash')
###*
# @summary config.json validation schema
# @name schema
# @type {Object}
#
# @description
# This is a `revalidator` schema. Refer to the following documentation:
#
# https://github.com/flatiron/revalidator
###
module.exports =
properties:
# Included for backwards compatibility - it does not exist in modern config files
applicationName:
description: 'application name'
type: 'string'
required: false
allowEmpty: false
applicationId:
description: 'application id'
type: 'number'
minimum: 0
required: true
deviceType:
description: 'device type'
type: 'string'
required: true
allowEmpty: false
# Included for backwards compatibility - it does not exist in modern config files
userId:
description: 'user id'
type: 'number'
minimum: 0
required: false
# Included for backwards compatibility - it does not exist in modern config files
username:
description: 'username'
type: 'string'
required: false
allowEmpty: false
files:
description: 'files'
type: 'object'
required: false
properties:
'network/settings':
description: 'network settings'
type: 'string'
required: true
allowEmpty: false
'network/network.config':
description: 'network config'
type: 'string'
required: true
allowEmpty: false
appUpdatePollInterval:
description: 'app update poll interval'
type: 'number'
minimum: 0
required: true
listenPort:
description: 'listen port'
type: 'number'
minimum: 0
required: true
# Included for backwards compatibility - it does not exist in modern config files
vpnPort:
description: 'vpn port'
type: 'number'
minimum: 0
required: false
conform: _.negate(_.isNaN)
messages:
conform: 'is NaN'
apiEndpoint:
description: 'api endpoint'
type: 'string'
required: true
allowEmpty: false
format: 'url'
deltaEndpoint:
description: 'delta endpoint'
type: 'string'
required: false
allowEmpty: false
format: 'url'
# Included for backwards compatibility - it does not exist in modern config files
vpnEndpoint:
description: 'vpn endpoint'
type: 'string'
required: false
allowEmpty: false
format: 'host-name'
registryEndpoint:
description: 'registry endpoint'
type: 'string'
required: true
allowEmpty: false
format: 'host-name'
# Included for backwards compatibility - it does not exist in modern config files
pubnubSubscribeKey:
description: 'pubnub subscribe key'
type: 'string'
required: false
allowEmpty: true
# Included for backwards compatibility - it does not exist in modern config files
pubnubPublishKey:
description: 'pubnub publish key'
type: 'string'
required: false
allowEmpty: true
# Included for backwards compatibility - it does not exist in modern config files
mixpanelToken:
description: 'mixpanel token'
type: 'string'
required: false
allowEmpty: false
balenaRootCA:
description: 'balena root CA'
type: 'string'
required: false
allowEmpty: false
# An api key is required, but it can be either apiKey or deviceApiKey (not both)
apiKey:
description: 'api key'
type: 'string'
required: false
allowEmpty: false
# The device api key is only useful if coupled with a uuid
deviceApiKey:
description: 'device api key'
type: 'string'
required: false
allowEmpty: false
registered_at:
description: 'registered at'
type: 'number'
minimum: 0
format: 'utc-millisec'
deviceId:
description: 'device id'
type: 'number'
minimum: 0
uuid:
description: 'uuid'
type: 'string'
allowEmpty: false
pattern: /^[0-9a-f]{32,62}$/
wifiSsid:
description: 'wifi ssid'
type: 'string'
allowEmpty: true
wifiKey:
description: 'wifi key'
type: 'string'
allowEmpty: true
connectivity:
description: 'network management software'
type: 'string'
allowEmpty: false
enum: ['NetworkManager', 'connman']
default: 'connman'
network:
description: 'network configurations'
type: 'array'
required: false
items:
type: 'object'
properties:
wifiSsid:
description: 'wifi ssid'
type: 'string'
allowEmpty: true
wifiKey:
description: 'wifi key'
type: 'string'
allowEmpty: true
configuration:
description: 'configuration'
type: 'string'
allowEmpty: true
|
[
{
"context": "ces to all of its direct customers. Please contact Joong W Park (323) 735-9665 for further information.\n \"\"\"\n\n",
"end": 2236,
"score": 0.9998643398284912,
"start": 2224,
"tag": "NAME",
"value": "Joong W Park"
}
] | tests/features/step_definitions/documents_steps.coffee | ecohealthalliance/eidr-connect | 1 | do ->
'use strict'
module.exports = ->
DOCUMENT_LINK = 'http://www.promedmail.org/post/5018201'
DOCUMENT_TEXT = """
US Deer Antler Ex and Imp, of Los Angeles, CA is recalling a variety of herbal teas prepared on [its] premises between 1 March and 30 April 2017 in cooperation with an inspection made by the California Department of Public Health. The aforementioned herbal teas, especially those with low-acidity held at room temperature, were not produced according to approved guideline, making them susceptible to contamination by _Clostridium botulinum_.
Below are the product descriptions:
Products / Packaging / Cases
Herbal Tea Variety Batches prepared on the premises between 1 Mar 2017 and 30 Apr 2017 / 120 mL per pouch / 40 pouches per case
The herbal teas were distributed to individual customers and acupuncturists in California, Florida, Illinois, Maryland, North Carolina, Texas, and Virginia.
Symptoms of _Clostridium botulinum_ typically begin with blurred or double vision followed by trouble speaking, swallowing; and progression to muscle weakness starting in the upper body, moving downward. Botulism can lead to life-threatening paralysis of breathing muscles requiring support with a breathing machine (ventilator) and intensive care. http://www.cdph.ca.gov/HealthInfo/discond/Pages/Botulism.aspx
People experiencing these symptoms who have recently consumed these herbal teas should seek immediate medical attention.
In its ongoing cooperation with the California Department of Public Health, US Deer Antler Ex and Imp, Inc has immediately segregated its entire inventory of herbal tea varieties, and is notifying consumers and customers not to consume potentially-contaminated product.
Furthermore, US Deer Antler Ex and Imp Inc is voluntarily recalling all varieties of general herbal teas prepared on site in the period of 1 March to 30 April 2017 to ensure consumer safety. Consumers in possession of these products are to stop consumption and return unconsumed product to their original place of purchase.
US Deer Antler Ex and Imp, Inc will be sending recall notices to all of its direct customers. Please contact Joong W Park (323) 735-9665 for further information.
"""
@When /^I select the "([^"]*)" feed$/, (feedName) ->
if feedName is 'User Added'
@client.waitForVisible('.curator-inbox--feed-selector')
@client
.element('.curator-inbox--feed-selector')
.selectByValue('userAdded')
@When /^I add a new test document with "([^"]*)"$/, (sourceType) ->
@client.clickWhenVisible('.add-document')
@client.waitForVisible('#add-source')
if sourceType is 'link'
@client.setValue('#article', DOCUMENT_LINK)
else
@client.clickWhenVisible('[href="#text"]')
@client.waitForVisible('#content')
@client.setValue('#content', DOCUMENT_TEXT)
@client.setValue('#title', 'Test Document')
@client.clickIfVisible('.add-publish-date .btn')
# The publishTime element might be in an invalid state that
# prevents setValue from working if this pause is not used.
@client.pause(10000)
@client.setValue('#publishTime', '12:00 PM')
@client.pause(5000)
@client.click('.save-source')
@Then /^I select the first user added document$/, ->
@client.clickWhenVisible('.curator-inbox-source-list table:first-of-type tbody tr:first-of-type')
@Then /^I should see the content of the document$/, ->
@client.waitForExist('.selectable-content')
@Then /^I should see accepted or rejected incidents$/, ->
@client.waitForExist('.incident-list li')
@When /^I delete the user added document$/, ->
@client.clickWhenVisible('.delete-document')
@When /^I edit the existing document$/, ->
@client.clickWhenVisible('.edit-source')
| 47713 | do ->
'use strict'
module.exports = ->
DOCUMENT_LINK = 'http://www.promedmail.org/post/5018201'
DOCUMENT_TEXT = """
US Deer Antler Ex and Imp, of Los Angeles, CA is recalling a variety of herbal teas prepared on [its] premises between 1 March and 30 April 2017 in cooperation with an inspection made by the California Department of Public Health. The aforementioned herbal teas, especially those with low-acidity held at room temperature, were not produced according to approved guideline, making them susceptible to contamination by _Clostridium botulinum_.
Below are the product descriptions:
Products / Packaging / Cases
Herbal Tea Variety Batches prepared on the premises between 1 Mar 2017 and 30 Apr 2017 / 120 mL per pouch / 40 pouches per case
The herbal teas were distributed to individual customers and acupuncturists in California, Florida, Illinois, Maryland, North Carolina, Texas, and Virginia.
Symptoms of _Clostridium botulinum_ typically begin with blurred or double vision followed by trouble speaking, swallowing; and progression to muscle weakness starting in the upper body, moving downward. Botulism can lead to life-threatening paralysis of breathing muscles requiring support with a breathing machine (ventilator) and intensive care. http://www.cdph.ca.gov/HealthInfo/discond/Pages/Botulism.aspx
People experiencing these symptoms who have recently consumed these herbal teas should seek immediate medical attention.
In its ongoing cooperation with the California Department of Public Health, US Deer Antler Ex and Imp, Inc has immediately segregated its entire inventory of herbal tea varieties, and is notifying consumers and customers not to consume potentially-contaminated product.
Furthermore, US Deer Antler Ex and Imp Inc is voluntarily recalling all varieties of general herbal teas prepared on site in the period of 1 March to 30 April 2017 to ensure consumer safety. Consumers in possession of these products are to stop consumption and return unconsumed product to their original place of purchase.
US Deer Antler Ex and Imp, Inc will be sending recall notices to all of its direct customers. Please contact <NAME> (323) 735-9665 for further information.
"""
@When /^I select the "([^"]*)" feed$/, (feedName) ->
if feedName is 'User Added'
@client.waitForVisible('.curator-inbox--feed-selector')
@client
.element('.curator-inbox--feed-selector')
.selectByValue('userAdded')
@When /^I add a new test document with "([^"]*)"$/, (sourceType) ->
@client.clickWhenVisible('.add-document')
@client.waitForVisible('#add-source')
if sourceType is 'link'
@client.setValue('#article', DOCUMENT_LINK)
else
@client.clickWhenVisible('[href="#text"]')
@client.waitForVisible('#content')
@client.setValue('#content', DOCUMENT_TEXT)
@client.setValue('#title', 'Test Document')
@client.clickIfVisible('.add-publish-date .btn')
# The publishTime element might be in an invalid state that
# prevents setValue from working if this pause is not used.
@client.pause(10000)
@client.setValue('#publishTime', '12:00 PM')
@client.pause(5000)
@client.click('.save-source')
@Then /^I select the first user added document$/, ->
@client.clickWhenVisible('.curator-inbox-source-list table:first-of-type tbody tr:first-of-type')
@Then /^I should see the content of the document$/, ->
@client.waitForExist('.selectable-content')
@Then /^I should see accepted or rejected incidents$/, ->
@client.waitForExist('.incident-list li')
@When /^I delete the user added document$/, ->
@client.clickWhenVisible('.delete-document')
@When /^I edit the existing document$/, ->
@client.clickWhenVisible('.edit-source')
| true | do ->
'use strict'
module.exports = ->
DOCUMENT_LINK = 'http://www.promedmail.org/post/5018201'
DOCUMENT_TEXT = """
US Deer Antler Ex and Imp, of Los Angeles, CA is recalling a variety of herbal teas prepared on [its] premises between 1 March and 30 April 2017 in cooperation with an inspection made by the California Department of Public Health. The aforementioned herbal teas, especially those with low-acidity held at room temperature, were not produced according to approved guideline, making them susceptible to contamination by _Clostridium botulinum_.
Below are the product descriptions:
Products / Packaging / Cases
Herbal Tea Variety Batches prepared on the premises between 1 Mar 2017 and 30 Apr 2017 / 120 mL per pouch / 40 pouches per case
The herbal teas were distributed to individual customers and acupuncturists in California, Florida, Illinois, Maryland, North Carolina, Texas, and Virginia.
Symptoms of _Clostridium botulinum_ typically begin with blurred or double vision followed by trouble speaking, swallowing; and progression to muscle weakness starting in the upper body, moving downward. Botulism can lead to life-threatening paralysis of breathing muscles requiring support with a breathing machine (ventilator) and intensive care. http://www.cdph.ca.gov/HealthInfo/discond/Pages/Botulism.aspx
People experiencing these symptoms who have recently consumed these herbal teas should seek immediate medical attention.
In its ongoing cooperation with the California Department of Public Health, US Deer Antler Ex and Imp, Inc has immediately segregated its entire inventory of herbal tea varieties, and is notifying consumers and customers not to consume potentially-contaminated product.
Furthermore, US Deer Antler Ex and Imp Inc is voluntarily recalling all varieties of general herbal teas prepared on site in the period of 1 March to 30 April 2017 to ensure consumer safety. Consumers in possession of these products are to stop consumption and return unconsumed product to their original place of purchase.
US Deer Antler Ex and Imp, Inc will be sending recall notices to all of its direct customers. Please contact PI:NAME:<NAME>END_PI (323) 735-9665 for further information.
"""
@When /^I select the "([^"]*)" feed$/, (feedName) ->
if feedName is 'User Added'
@client.waitForVisible('.curator-inbox--feed-selector')
@client
.element('.curator-inbox--feed-selector')
.selectByValue('userAdded')
@When /^I add a new test document with "([^"]*)"$/, (sourceType) ->
@client.clickWhenVisible('.add-document')
@client.waitForVisible('#add-source')
if sourceType is 'link'
@client.setValue('#article', DOCUMENT_LINK)
else
@client.clickWhenVisible('[href="#text"]')
@client.waitForVisible('#content')
@client.setValue('#content', DOCUMENT_TEXT)
@client.setValue('#title', 'Test Document')
@client.clickIfVisible('.add-publish-date .btn')
# The publishTime element might be in an invalid state that
# prevents setValue from working if this pause is not used.
@client.pause(10000)
@client.setValue('#publishTime', '12:00 PM')
@client.pause(5000)
@client.click('.save-source')
@Then /^I select the first user added document$/, ->
@client.clickWhenVisible('.curator-inbox-source-list table:first-of-type tbody tr:first-of-type')
@Then /^I should see the content of the document$/, ->
@client.waitForExist('.selectable-content')
@Then /^I should see accepted or rejected incidents$/, ->
@client.waitForExist('.incident-list li')
@When /^I delete the user added document$/, ->
@client.clickWhenVisible('.delete-document')
@When /^I edit the existing document$/, ->
@client.clickWhenVisible('.edit-source')
|
[
{
"context": " @user1 = @server.findOrCreateUser(id: 1, name: \"Star Fox\", @spark1)\n @user2 = @server.findOrCreateUser(",
"end": 830,
"score": 0.9575255513191223,
"start": 822,
"tag": "NAME",
"value": "Star Fox"
},
{
"context": " @user2 = @server.findOrCreateUser(id: 2, name: ... | test/server/commands_spec.coffee | sarenji/pokebattle-sim | 5 | require('../helpers')
should = require('should')
async = require 'async'
primus = require('primus')
commands = require('../../server/commands')
alts = require('../../server/alts')
auth = require('../../server/auth')
{User} = require('../../server/user')
{BattleServer} = require('../../server/server')
{Room} = require('../../server/rooms')
ratings = require('../../server/ratings')
{Factory} = require '../factory'
redis = require('../../server/redis')
generateTeam = ->
[ Factory("Magikarp")
Factory("Gyarados")
Factory('Hitmonchan')
Factory("Celebi")
Factory("Blissey")
Factory("Alakazam") ]
describe "Commands", ->
beforeEach ->
@server = new BattleServer()
@room = new Room()
@spark1 = @stubSpark()
@spark2 = @stubSpark()
@user1 = @server.findOrCreateUser(id: 1, name: "Star Fox", @spark1)
@user2 = @server.findOrCreateUser(id: 2, name: "Slippy", @spark2)
@aardvark = @server.findOrCreateUser(id: 3, name: 'aardvark', @stubSpark())
@bologna = @server.findOrCreateUser(id: 3, name: 'bologna', @stubSpark())
@offlineName = "husk"
@room.add(@spark1)
@room.add(@spark2)
@emptyRoom = new Room()
@server.rooms.push(@room)
@server.join(@spark1)
@server.join(@spark2)
describe "#executeCommand", ->
describe "an invalid command", ->
it "returns an error to the user", ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand(@server, @user1, @room, "an invalid command")
mock1.verify()
mock2.verify()
describe "rating", ->
user1Rating = 9001
user2Rating = 101
beforeEach (done) ->
ratings.setRating @user1.name, user1Rating, =>
ratings.setRating(@user2.name, user2Rating, done)
it "returns the user's rating to the user without arguments", (done) ->
spy = @sandbox.spy(@user1, 'announce')
commands.executeCommand @server, @user1, @room, "rating", =>
spy.callCount.should.equal(1)
spy.firstCall.args[2].should.containEql(@user1.name)
spy.firstCall.args[2].should.containEql(user1Rating)
done()
it "returns someone's rating to the user as an argument", (done) ->
spy = @sandbox.spy(@user1, 'announce')
commands.executeCommand @server, @user1, @room, "rating", @user2.name, =>
spy.callCount.should.equal(1)
spy.callCount.should.equal(1)
spy.firstCall.args[2].should.containEql(@user2.name)
spy.firstCall.args[2].should.containEql(user2Rating)
done()
describe "voice", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "voice", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "voices a user if owner", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "voice", @user2.name, =>
@user2.should.have.property("authority")
@user2.authority.should.equal(auth.levels.DRIVER)
done()
it "does not crash if user isn't on yet", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "voice", @offlineName, =>
auth.getAuth @offlineName, (err, result) ->
result.should.equal(auth.levels.DRIVER)
done()
describe "mod", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "mod", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "mods a user if owner", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "mod", @user2.name, =>
@user2.should.have.property("authority")
@user2.authority.should.equal(auth.levels.MOD)
done()
it "does not crash if user isn't on yet", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "mod", @offlineName, =>
auth.getAuth @offlineName, (err, result) ->
result.should.equal(auth.levels.MOD)
done()
describe "admin", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "admin", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "admins a user if owner", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "admin", @user2.name, =>
@user2.should.have.property("authority")
@user2.authority.should.equal(auth.levels.ADMIN)
done()
it "does not crash if user isn't on yet", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "admin", @offlineName, =>
auth.getAuth @offlineName, (err, result) ->
result.should.equal(auth.levels.ADMIN)
done()
describe "deauth", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "deauth", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "deauthes a user if owner", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "deauth", @user2.name, =>
@user2.should.have.property("authority")
@user2.authority.should.equal(auth.levels.USER)
done()
it "does not crash if user isn't on yet", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "deauth", @offlineName, =>
auth.getAuth @offlineName, (err, result) ->
result.should.equal(auth.levels.USER)
done()
describe "ban", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@spark2).expects('end').never()
commands.executeCommand @server, @user1, @room, "ban", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "bans a user if mod", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').never()
mock2 = @sandbox.mock(@spark2).expects('end').once()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @user2.name, =>
mock1.verify()
mock2.verify()
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(60 * 60)
done()
it "bans a user even if user isn't on yet", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @offlineName, =>
mock1.verify()
auth.getBanTTL @offlineName, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(60 * 60)
done()
it "bans a user for a specified amount of time", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @user2.name, "23h", =>
mock.verify()
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(23 * 60 * 60)
done()
it "defaults to an hour if banning for zero minutes", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @user2.name, "0", =>
mock.verify()
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(60 * 60)
done()
it "cannot ban over one day if mod", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @user2.name, "1y", =>
mock.verify()
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(1 * 24 * 60 * 60)
done()
describe "unban", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "unban", @user2.name, =>
mock1.verify()
mock2.verify()
done()
it "unbans a user if mod", (done) ->
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @user2.name, =>
commands.executeCommand @server, @user1, @room, "unban", @user2.name, =>
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(-2)
done()
it "returns an error if user is not banned", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "unban", @user2.name, =>
mock1.verify()
mock2.verify()
done()
it "unbans a user even if user isn't on yet", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @offlineName, =>
commands.executeCommand @server, @user1, @room, "unban", @offlineName, =>
mock.verify()
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(-2)
done()
describe "mute", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "mute", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "mutes a user if mod", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @user2.name, =>
mock.verify()
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(10 * 60)
done()
it "mutes a user even if user isn't on yet", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @offlineName, =>
mock.verify()
auth.getMuteTTL @offlineName, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(10 * 60)
done()
it "mutes a user for a specified amount of time", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @user2.name, "23h", =>
mock.verify()
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(23 * 60 * 60)
done()
it "defaults to 10 if muting for zero minutes", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @user2.name, "0", =>
mock.verify()
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(10 * 60)
done()
it "cannot mute over two days if mod", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @user2.name, "1y", =>
mock.verify()
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(2 * 24 * 60 * 60)
done()
describe "unmute", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "unmute", @user2.name, =>
mock1.verify()
mock2.verify()
done()
it "unmutes a user if mod", (done) ->
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @user2.name, =>
commands.executeCommand @server, @user1, @room, "unmute", @user2.name, =>
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(-2)
done()
it "returns an error if user is not muted", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "unmute", @user2.name, =>
mock1.verify()
mock2.verify()
done()
it "unmutes a user even if user isn't on yet", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @offlineName, =>
commands.executeCommand @server, @user1, @room, "unmute", @offlineName, =>
mock1.verify()
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(-2)
done()
describe "battles", ->
it "returns an error if no user is passed", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "battles", ->
mock1.verify()
mock2.verify()
done()
it "returns all battles that user is in if user is passed", (done) ->
@server.queuePlayer(@user1.name, generateTeam()).should.be.empty
@server.queuePlayer(@user2.name, generateTeam()).should.be.empty
@server.queuePlayer(@aardvark.name, generateTeam()).should.be.empty
@server.queuePlayer(@bologna.name, generateTeam()).should.be.empty
@server.beginBattles (err, battleIds) =>
if err then throw err
battleIds.length.should.equal(2)
spy = @sandbox.spy(@user1, 'announce')
commands.executeCommand @server, @user1, @room, "battles", @user2.name, =>
spy.callCount.should.equal(1)
spy.firstCall.args[2].should.containEql(@user2.name)
spy.firstCall.args[2].should.containEql(battleIds[0])
spy.firstCall.args[2].should.not.containEql(@user1.name)
spy.firstCall.args[2].should.not.containEql(battleIds[1])
done()
it "does not containEql alts in the battle list", (done) ->
@server.queuePlayer(@user1.name, [ Factory("Magikarp") ])
@server.queuePlayer(@user2.name, [ Factory("Magikarp") ], "Im an Alt")
@server.beginBattles (err, battleIds) =>
if err then throw err
spy = @sandbox.spy(@user1, 'announce')
commands.executeCommand @server, @user1, @room, "battles", @user2.name, =>
if err then throw err
spy.callCount.should.equal(1)
spy.firstCall.args[2].should.containEql(@user2.name)
done()
describe "topic", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
commands.executeCommand @server, @user1, @room, "topic", "test topic", ->
mock1.verify()
done()
it "updates the channel topic", (done) ->
topicName = "a test"
@user1.authority = auth.levels.ADMIN
mock = @sandbox.mock(@room).expects("setTopic").withArgs(topicName).once()
commands.executeCommand @server, @user1, @room, "topic", topicName, ->
mock.verify()
done()
describe "wall", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
commands.executeCommand @server, @user1, @room, "wall", "hi", ->
mock1.verify()
done()
it "messages all rooms and all battles", (done) ->
mock = @sandbox.mock(@room).expects('announce').once()
spy1 = @sandbox.spy(@spark1, 'send')
spy2 = @sandbox.spy(@spark2, 'send')
@server.queuePlayer(@user1.name, generateTeam()).should.be.empty
@server.queuePlayer(@user2.name, generateTeam()).should.be.empty
@server.beginBattles (err, battleIds) =>
if err then throw err
@user1.authority = auth.levels.ADMIN
commands.executeCommand @server, @user1, @room, "wall", "derper", =>
mock.verify()
spy1.calledWithMatch("announce", battleIds[0], 'warning', "derper").should.be.true
spy2.calledWithMatch("announce", battleIds[0], 'warning', "derper").should.be.true
done()
describe "lockdown", ->
it "returns an error if insufficient authority", (done) ->
mock = @sandbox.mock(@user1).expects('error').once()
commands.executeCommand @server, @user1, @room, "lockdown", ->
mock.verify()
done()
it "stops battles from occuring", (done) ->
mock = @sandbox.mock(@server).expects('lockdown').once()
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "lockdown", ->
mock.verify()
done()
it "can start them again", (done) ->
mock = @sandbox.mock(@server).expects('unlockdown').once()
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "lockdown", "off", ->
mock.verify()
done()
describe "whois", ->
beforeEach (done) ->
async.parallel([
alts.createAlt.bind(alts, @user1.name, 'alt1')
alts.createAlt.bind(alts, @user1.name, 'alt2')
], done)
it "returns an error if insufficient authority", (done) ->
mock = @sandbox.mock(@user1).expects('error').once()
commands.executeCommand @server, @user1, @room, "whois", @user1.name, =>
mock.verify()
done()
it "returns a list of alts and the main account", (done) ->
@user1.authority = auth.levels.MOD
spy = @sandbox.spy(@user1, 'announce')
commands.executeCommand @server, @user1, @room, "whois", @user1.name, =>
spy.callCount.should.equal(1)
spy.firstCall.args[2].should.containEql(@user1.name)
spy.firstCall.args[2].should.containEql("alt1")
spy.firstCall.args[2].should.containEql("alt2")
done()
| 22921 | require('../helpers')
should = require('should')
async = require 'async'
primus = require('primus')
commands = require('../../server/commands')
alts = require('../../server/alts')
auth = require('../../server/auth')
{User} = require('../../server/user')
{BattleServer} = require('../../server/server')
{Room} = require('../../server/rooms')
ratings = require('../../server/ratings')
{Factory} = require '../factory'
redis = require('../../server/redis')
generateTeam = ->
[ Factory("Magikarp")
Factory("Gyarados")
Factory('Hitmonchan')
Factory("Celebi")
Factory("Blissey")
Factory("Alakazam") ]
describe "Commands", ->
beforeEach ->
@server = new BattleServer()
@room = new Room()
@spark1 = @stubSpark()
@spark2 = @stubSpark()
@user1 = @server.findOrCreateUser(id: 1, name: "<NAME>", @spark1)
@user2 = @server.findOrCreateUser(id: 2, name: "<NAME>", @spark2)
@aardvark = @server.findOrCreateUser(id: 3, name: '<NAME>', @stubSpark())
@bologna = @server.findOrCreateUser(id: 3, name: '<NAME>', @stubSpark())
@offlineName = "hus<NAME>"
@room.add(@spark1)
@room.add(@spark2)
@emptyRoom = new Room()
@server.rooms.push(@room)
@server.join(@spark1)
@server.join(@spark2)
describe "#executeCommand", ->
describe "an invalid command", ->
it "returns an error to the user", ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand(@server, @user1, @room, "an invalid command")
mock1.verify()
mock2.verify()
describe "rating", ->
user1Rating = 9001
user2Rating = 101
beforeEach (done) ->
ratings.setRating @user1.name, user1Rating, =>
ratings.setRating(@user2.name, user2Rating, done)
it "returns the user's rating to the user without arguments", (done) ->
spy = @sandbox.spy(@user1, 'announce')
commands.executeCommand @server, @user1, @room, "rating", =>
spy.callCount.should.equal(1)
spy.firstCall.args[2].should.containEql(@user1.name)
spy.firstCall.args[2].should.containEql(user1Rating)
done()
it "returns someone's rating to the user as an argument", (done) ->
spy = @sandbox.spy(@user1, 'announce')
commands.executeCommand @server, @user1, @room, "rating", @user2.name, =>
spy.callCount.should.equal(1)
spy.callCount.should.equal(1)
spy.firstCall.args[2].should.containEql(@user2.name)
spy.firstCall.args[2].should.containEql(user2Rating)
done()
describe "voice", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "voice", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "voices a user if owner", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "voice", @user2.name, =>
@user2.should.have.property("authority")
@user2.authority.should.equal(auth.levels.DRIVER)
done()
it "does not crash if user isn't on yet", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "voice", @offlineName, =>
auth.getAuth @offlineName, (err, result) ->
result.should.equal(auth.levels.DRIVER)
done()
describe "mod", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "mod", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "mods a user if owner", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "mod", @user2.name, =>
@user2.should.have.property("authority")
@user2.authority.should.equal(auth.levels.MOD)
done()
it "does not crash if user isn't on yet", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "mod", @offlineName, =>
auth.getAuth @offlineName, (err, result) ->
result.should.equal(auth.levels.MOD)
done()
describe "admin", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "admin", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "admins a user if owner", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "admin", @user2.name, =>
@user2.should.have.property("authority")
@user2.authority.should.equal(auth.levels.ADMIN)
done()
it "does not crash if user isn't on yet", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "admin", @offlineName, =>
auth.getAuth @offlineName, (err, result) ->
result.should.equal(auth.levels.ADMIN)
done()
describe "deauth", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "deauth", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "deauthes a user if owner", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "deauth", @user2.name, =>
@user2.should.have.property("authority")
@user2.authority.should.equal(auth.levels.USER)
done()
it "does not crash if user isn't on yet", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "deauth", @offlineName, =>
auth.getAuth @offlineName, (err, result) ->
result.should.equal(auth.levels.USER)
done()
describe "ban", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@spark2).expects('end').never()
commands.executeCommand @server, @user1, @room, "ban", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "bans a user if mod", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').never()
mock2 = @sandbox.mock(@spark2).expects('end').once()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @user2.name, =>
mock1.verify()
mock2.verify()
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(60 * 60)
done()
it "bans a user even if user isn't on yet", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @offlineName, =>
mock1.verify()
auth.getBanTTL @offlineName, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(60 * 60)
done()
it "bans a user for a specified amount of time", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @user2.name, "23h", =>
mock.verify()
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(23 * 60 * 60)
done()
it "defaults to an hour if banning for zero minutes", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @user2.name, "0", =>
mock.verify()
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(60 * 60)
done()
it "cannot ban over one day if mod", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @user2.name, "1y", =>
mock.verify()
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(1 * 24 * 60 * 60)
done()
describe "unban", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "unban", @user2.name, =>
mock1.verify()
mock2.verify()
done()
it "unbans a user if mod", (done) ->
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @user2.name, =>
commands.executeCommand @server, @user1, @room, "unban", @user2.name, =>
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(-2)
done()
it "returns an error if user is not banned", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "unban", @user2.name, =>
mock1.verify()
mock2.verify()
done()
it "unbans a user even if user isn't on yet", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @offlineName, =>
commands.executeCommand @server, @user1, @room, "unban", @offlineName, =>
mock.verify()
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(-2)
done()
describe "mute", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "mute", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "mutes a user if mod", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @user2.name, =>
mock.verify()
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(10 * 60)
done()
it "mutes a user even if user isn't on yet", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @offlineName, =>
mock.verify()
auth.getMuteTTL @offlineName, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(10 * 60)
done()
it "mutes a user for a specified amount of time", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @user2.name, "23h", =>
mock.verify()
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(23 * 60 * 60)
done()
it "defaults to 10 if muting for zero minutes", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @user2.name, "0", =>
mock.verify()
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(10 * 60)
done()
it "cannot mute over two days if mod", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @user2.name, "1y", =>
mock.verify()
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(2 * 24 * 60 * 60)
done()
describe "unmute", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "unmute", @user2.name, =>
mock1.verify()
mock2.verify()
done()
it "unmutes a user if mod", (done) ->
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @user2.name, =>
commands.executeCommand @server, @user1, @room, "unmute", @user2.name, =>
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(-2)
done()
it "returns an error if user is not muted", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "unmute", @user2.name, =>
mock1.verify()
mock2.verify()
done()
it "unmutes a user even if user isn't on yet", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @offlineName, =>
commands.executeCommand @server, @user1, @room, "unmute", @offlineName, =>
mock1.verify()
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(-2)
done()
describe "battles", ->
it "returns an error if no user is passed", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "battles", ->
mock1.verify()
mock2.verify()
done()
it "returns all battles that user is in if user is passed", (done) ->
@server.queuePlayer(@user1.name, generateTeam()).should.be.empty
@server.queuePlayer(@user2.name, generateTeam()).should.be.empty
@server.queuePlayer(@aardvark.name, generateTeam()).should.be.empty
@server.queuePlayer(@bologna.name, generateTeam()).should.be.empty
@server.beginBattles (err, battleIds) =>
if err then throw err
battleIds.length.should.equal(2)
spy = @sandbox.spy(@user1, 'announce')
commands.executeCommand @server, @user1, @room, "battles", @user2.name, =>
spy.callCount.should.equal(1)
spy.firstCall.args[2].should.containEql(@user2.name)
spy.firstCall.args[2].should.containEql(battleIds[0])
spy.firstCall.args[2].should.not.containEql(@user1.name)
spy.firstCall.args[2].should.not.containEql(battleIds[1])
done()
it "does not containEql alts in the battle list", (done) ->
@server.queuePlayer(@user1.name, [ Factory("Magikarp") ])
@server.queuePlayer(@user2.name, [ Factory("Magikarp") ], "Im an Alt")
@server.beginBattles (err, battleIds) =>
if err then throw err
spy = @sandbox.spy(@user1, 'announce')
commands.executeCommand @server, @user1, @room, "battles", @user2.name, =>
if err then throw err
spy.callCount.should.equal(1)
spy.firstCall.args[2].should.containEql(@user2.name)
done()
describe "topic", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
commands.executeCommand @server, @user1, @room, "topic", "test topic", ->
mock1.verify()
done()
it "updates the channel topic", (done) ->
topicName = "a test"
@user1.authority = auth.levels.ADMIN
mock = @sandbox.mock(@room).expects("setTopic").withArgs(topicName).once()
commands.executeCommand @server, @user1, @room, "topic", topicName, ->
mock.verify()
done()
describe "wall", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
commands.executeCommand @server, @user1, @room, "wall", "hi", ->
mock1.verify()
done()
it "messages all rooms and all battles", (done) ->
mock = @sandbox.mock(@room).expects('announce').once()
spy1 = @sandbox.spy(@spark1, 'send')
spy2 = @sandbox.spy(@spark2, 'send')
@server.queuePlayer(@user1.name, generateTeam()).should.be.empty
@server.queuePlayer(@user2.name, generateTeam()).should.be.empty
@server.beginBattles (err, battleIds) =>
if err then throw err
@user1.authority = auth.levels.ADMIN
commands.executeCommand @server, @user1, @room, "wall", "derper", =>
mock.verify()
spy1.calledWithMatch("announce", battleIds[0], 'warning', "derper").should.be.true
spy2.calledWithMatch("announce", battleIds[0], 'warning', "derper").should.be.true
done()
describe "lockdown", ->
it "returns an error if insufficient authority", (done) ->
mock = @sandbox.mock(@user1).expects('error').once()
commands.executeCommand @server, @user1, @room, "lockdown", ->
mock.verify()
done()
it "stops battles from occuring", (done) ->
mock = @sandbox.mock(@server).expects('lockdown').once()
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "lockdown", ->
mock.verify()
done()
it "can start them again", (done) ->
mock = @sandbox.mock(@server).expects('unlockdown').once()
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "lockdown", "off", ->
mock.verify()
done()
describe "whois", ->
beforeEach (done) ->
async.parallel([
alts.createAlt.bind(alts, @user1.name, 'alt1')
alts.createAlt.bind(alts, @user1.name, 'alt2')
], done)
it "returns an error if insufficient authority", (done) ->
mock = @sandbox.mock(@user1).expects('error').once()
commands.executeCommand @server, @user1, @room, "whois", @user1.name, =>
mock.verify()
done()
it "returns a list of alts and the main account", (done) ->
@user1.authority = auth.levels.MOD
spy = @sandbox.spy(@user1, 'announce')
commands.executeCommand @server, @user1, @room, "whois", @user1.name, =>
spy.callCount.should.equal(1)
spy.firstCall.args[2].should.containEql(@user1.name)
spy.firstCall.args[2].should.containEql("alt1")
spy.firstCall.args[2].should.containEql("alt2")
done()
| true | require('../helpers')
should = require('should')
async = require 'async'
primus = require('primus')
commands = require('../../server/commands')
alts = require('../../server/alts')
auth = require('../../server/auth')
{User} = require('../../server/user')
{BattleServer} = require('../../server/server')
{Room} = require('../../server/rooms')
ratings = require('../../server/ratings')
{Factory} = require '../factory'
redis = require('../../server/redis')
generateTeam = ->
[ Factory("Magikarp")
Factory("Gyarados")
Factory('Hitmonchan')
Factory("Celebi")
Factory("Blissey")
Factory("Alakazam") ]
describe "Commands", ->
beforeEach ->
@server = new BattleServer()
@room = new Room()
@spark1 = @stubSpark()
@spark2 = @stubSpark()
@user1 = @server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @spark1)
@user2 = @server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @spark2)
@aardvark = @server.findOrCreateUser(id: 3, name: 'PI:NAME:<NAME>END_PI', @stubSpark())
@bologna = @server.findOrCreateUser(id: 3, name: 'PI:NAME:<NAME>END_PI', @stubSpark())
@offlineName = "husPI:NAME:<NAME>END_PI"
@room.add(@spark1)
@room.add(@spark2)
@emptyRoom = new Room()
@server.rooms.push(@room)
@server.join(@spark1)
@server.join(@spark2)
describe "#executeCommand", ->
describe "an invalid command", ->
it "returns an error to the user", ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand(@server, @user1, @room, "an invalid command")
mock1.verify()
mock2.verify()
describe "rating", ->
user1Rating = 9001
user2Rating = 101
beforeEach (done) ->
ratings.setRating @user1.name, user1Rating, =>
ratings.setRating(@user2.name, user2Rating, done)
it "returns the user's rating to the user without arguments", (done) ->
spy = @sandbox.spy(@user1, 'announce')
commands.executeCommand @server, @user1, @room, "rating", =>
spy.callCount.should.equal(1)
spy.firstCall.args[2].should.containEql(@user1.name)
spy.firstCall.args[2].should.containEql(user1Rating)
done()
it "returns someone's rating to the user as an argument", (done) ->
spy = @sandbox.spy(@user1, 'announce')
commands.executeCommand @server, @user1, @room, "rating", @user2.name, =>
spy.callCount.should.equal(1)
spy.callCount.should.equal(1)
spy.firstCall.args[2].should.containEql(@user2.name)
spy.firstCall.args[2].should.containEql(user2Rating)
done()
describe "voice", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "voice", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "voices a user if owner", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "voice", @user2.name, =>
@user2.should.have.property("authority")
@user2.authority.should.equal(auth.levels.DRIVER)
done()
it "does not crash if user isn't on yet", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "voice", @offlineName, =>
auth.getAuth @offlineName, (err, result) ->
result.should.equal(auth.levels.DRIVER)
done()
describe "mod", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "mod", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "mods a user if owner", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "mod", @user2.name, =>
@user2.should.have.property("authority")
@user2.authority.should.equal(auth.levels.MOD)
done()
it "does not crash if user isn't on yet", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "mod", @offlineName, =>
auth.getAuth @offlineName, (err, result) ->
result.should.equal(auth.levels.MOD)
done()
describe "admin", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "admin", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "admins a user if owner", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "admin", @user2.name, =>
@user2.should.have.property("authority")
@user2.authority.should.equal(auth.levels.ADMIN)
done()
it "does not crash if user isn't on yet", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "admin", @offlineName, =>
auth.getAuth @offlineName, (err, result) ->
result.should.equal(auth.levels.ADMIN)
done()
describe "deauth", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "deauth", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "deauthes a user if owner", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "deauth", @user2.name, =>
@user2.should.have.property("authority")
@user2.authority.should.equal(auth.levels.USER)
done()
it "does not crash if user isn't on yet", (done) ->
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "deauth", @offlineName, =>
auth.getAuth @offlineName, (err, result) ->
result.should.equal(auth.levels.USER)
done()
describe "ban", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@spark2).expects('end').never()
commands.executeCommand @server, @user1, @room, "ban", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "bans a user if mod", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').never()
mock2 = @sandbox.mock(@spark2).expects('end').once()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @user2.name, =>
mock1.verify()
mock2.verify()
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(60 * 60)
done()
it "bans a user even if user isn't on yet", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @offlineName, =>
mock1.verify()
auth.getBanTTL @offlineName, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(60 * 60)
done()
it "bans a user for a specified amount of time", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @user2.name, "23h", =>
mock.verify()
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(23 * 60 * 60)
done()
it "defaults to an hour if banning for zero minutes", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @user2.name, "0", =>
mock.verify()
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(60 * 60)
done()
it "cannot ban over one day if mod", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @user2.name, "1y", =>
mock.verify()
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(1 * 24 * 60 * 60)
done()
describe "unban", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "unban", @user2.name, =>
mock1.verify()
mock2.verify()
done()
it "unbans a user if mod", (done) ->
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @user2.name, =>
commands.executeCommand @server, @user1, @room, "unban", @user2.name, =>
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(-2)
done()
it "returns an error if user is not banned", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "unban", @user2.name, =>
mock1.verify()
mock2.verify()
done()
it "unbans a user even if user isn't on yet", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "ban", @offlineName, =>
commands.executeCommand @server, @user1, @room, "unban", @offlineName, =>
mock.verify()
auth.getBanTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(-2)
done()
describe "mute", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "mute", @user2.name, ->
mock1.verify()
mock2.verify()
done()
it "mutes a user if mod", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @user2.name, =>
mock.verify()
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(10 * 60)
done()
it "mutes a user even if user isn't on yet", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @offlineName, =>
mock.verify()
auth.getMuteTTL @offlineName, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(10 * 60)
done()
it "mutes a user for a specified amount of time", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @user2.name, "23h", =>
mock.verify()
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(23 * 60 * 60)
done()
it "defaults to 10 if muting for zero minutes", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @user2.name, "0", =>
mock.verify()
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(10 * 60)
done()
it "cannot mute over two days if mod", (done) ->
mock = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @user2.name, "1y", =>
mock.verify()
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(2 * 24 * 60 * 60)
done()
describe "unmute", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "unmute", @user2.name, =>
mock1.verify()
mock2.verify()
done()
it "unmutes a user if mod", (done) ->
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @user2.name, =>
commands.executeCommand @server, @user1, @room, "unmute", @user2.name, =>
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(-2)
done()
it "returns an error if user is not muted", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "unmute", @user2.name, =>
mock1.verify()
mock2.verify()
done()
it "unmutes a user even if user isn't on yet", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').never()
@user1.authority = auth.levels.MOD
commands.executeCommand @server, @user1, @room, "mute", @offlineName, =>
commands.executeCommand @server, @user1, @room, "unmute", @offlineName, =>
mock1.verify()
auth.getMuteTTL @user2.name, (err, ttl) ->
should.exist(ttl)
ttl.should.equal(-2)
done()
describe "battles", ->
it "returns an error if no user is passed", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
mock2 = @sandbox.mock(@user2).expects('error').never()
commands.executeCommand @server, @user1, @room, "battles", ->
mock1.verify()
mock2.verify()
done()
it "returns all battles that user is in if user is passed", (done) ->
@server.queuePlayer(@user1.name, generateTeam()).should.be.empty
@server.queuePlayer(@user2.name, generateTeam()).should.be.empty
@server.queuePlayer(@aardvark.name, generateTeam()).should.be.empty
@server.queuePlayer(@bologna.name, generateTeam()).should.be.empty
@server.beginBattles (err, battleIds) =>
if err then throw err
battleIds.length.should.equal(2)
spy = @sandbox.spy(@user1, 'announce')
commands.executeCommand @server, @user1, @room, "battles", @user2.name, =>
spy.callCount.should.equal(1)
spy.firstCall.args[2].should.containEql(@user2.name)
spy.firstCall.args[2].should.containEql(battleIds[0])
spy.firstCall.args[2].should.not.containEql(@user1.name)
spy.firstCall.args[2].should.not.containEql(battleIds[1])
done()
it "does not containEql alts in the battle list", (done) ->
@server.queuePlayer(@user1.name, [ Factory("Magikarp") ])
@server.queuePlayer(@user2.name, [ Factory("Magikarp") ], "Im an Alt")
@server.beginBattles (err, battleIds) =>
if err then throw err
spy = @sandbox.spy(@user1, 'announce')
commands.executeCommand @server, @user1, @room, "battles", @user2.name, =>
if err then throw err
spy.callCount.should.equal(1)
spy.firstCall.args[2].should.containEql(@user2.name)
done()
describe "topic", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
commands.executeCommand @server, @user1, @room, "topic", "test topic", ->
mock1.verify()
done()
it "updates the channel topic", (done) ->
topicName = "a test"
@user1.authority = auth.levels.ADMIN
mock = @sandbox.mock(@room).expects("setTopic").withArgs(topicName).once()
commands.executeCommand @server, @user1, @room, "topic", topicName, ->
mock.verify()
done()
describe "wall", ->
it "returns an error if insufficient authority", (done) ->
mock1 = @sandbox.mock(@user1).expects('error').once()
commands.executeCommand @server, @user1, @room, "wall", "hi", ->
mock1.verify()
done()
it "messages all rooms and all battles", (done) ->
mock = @sandbox.mock(@room).expects('announce').once()
spy1 = @sandbox.spy(@spark1, 'send')
spy2 = @sandbox.spy(@spark2, 'send')
@server.queuePlayer(@user1.name, generateTeam()).should.be.empty
@server.queuePlayer(@user2.name, generateTeam()).should.be.empty
@server.beginBattles (err, battleIds) =>
if err then throw err
@user1.authority = auth.levels.ADMIN
commands.executeCommand @server, @user1, @room, "wall", "derper", =>
mock.verify()
spy1.calledWithMatch("announce", battleIds[0], 'warning', "derper").should.be.true
spy2.calledWithMatch("announce", battleIds[0], 'warning', "derper").should.be.true
done()
describe "lockdown", ->
it "returns an error if insufficient authority", (done) ->
mock = @sandbox.mock(@user1).expects('error').once()
commands.executeCommand @server, @user1, @room, "lockdown", ->
mock.verify()
done()
it "stops battles from occuring", (done) ->
mock = @sandbox.mock(@server).expects('lockdown').once()
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "lockdown", ->
mock.verify()
done()
it "can start them again", (done) ->
mock = @sandbox.mock(@server).expects('unlockdown').once()
@user1.authority = auth.levels.OWNER
commands.executeCommand @server, @user1, @room, "lockdown", "off", ->
mock.verify()
done()
describe "whois", ->
beforeEach (done) ->
async.parallel([
alts.createAlt.bind(alts, @user1.name, 'alt1')
alts.createAlt.bind(alts, @user1.name, 'alt2')
], done)
it "returns an error if insufficient authority", (done) ->
mock = @sandbox.mock(@user1).expects('error').once()
commands.executeCommand @server, @user1, @room, "whois", @user1.name, =>
mock.verify()
done()
it "returns a list of alts and the main account", (done) ->
@user1.authority = auth.levels.MOD
spy = @sandbox.spy(@user1, 'announce')
commands.executeCommand @server, @user1, @room, "whois", @user1.name, =>
spy.callCount.should.equal(1)
spy.firstCall.args[2].should.containEql(@user1.name)
spy.firstCall.args[2].should.containEql("alt1")
spy.firstCall.args[2].should.containEql("alt2")
done()
|
[
{
"context": "ersonality makes you Lawful-aligned.\n *\n * @name Lawful\n * @prerequisite Play for one week\n * @effect +",
"end": 118,
"score": 0.7785242795944214,
"start": 112,
"tag": "NAME",
"value": "Lawful"
}
] | src/character/personalities/Lawful.coffee | sadbear-/IdleLands | 3 |
Personality = require "../base/Personality"
`/**
* This personality makes you Lawful-aligned.
*
* @name Lawful
* @prerequisite Play for one week
* @effect +10 alignment
* @category Personalities
* @package Player
*/`
class Lawful extends Personality
constructor: ->
alignment: -> 10
@canUse = (player) ->
hoursPlayed = (Math.abs player.registrationDate.getTime()-Date.now()) / 36e5
hoursPlayed >= (7 * 24)
@desc = "Play for 1 week"
module.exports = exports = Lawful
| 133704 |
Personality = require "../base/Personality"
`/**
* This personality makes you Lawful-aligned.
*
* @name <NAME>
* @prerequisite Play for one week
* @effect +10 alignment
* @category Personalities
* @package Player
*/`
class Lawful extends Personality
constructor: ->
alignment: -> 10
@canUse = (player) ->
hoursPlayed = (Math.abs player.registrationDate.getTime()-Date.now()) / 36e5
hoursPlayed >= (7 * 24)
@desc = "Play for 1 week"
module.exports = exports = Lawful
| true |
Personality = require "../base/Personality"
`/**
* This personality makes you Lawful-aligned.
*
* @name PI:NAME:<NAME>END_PI
* @prerequisite Play for one week
* @effect +10 alignment
* @category Personalities
* @package Player
*/`
class Lawful extends Personality
constructor: ->
alignment: -> 10
@canUse = (player) ->
hoursPlayed = (Math.abs player.registrationDate.getTime()-Date.now()) / 36e5
hoursPlayed >= (7 * 24)
@desc = "Play for 1 week"
module.exports = exports = Lawful
|
[
{
"context": "esults.at(0).get(\"Author\").get(\"Name\")).to.equal(\"Administrator\")\r\n\r\n query.exec()\r\n\r\n it 'can support de",
"end": 9181,
"score": 0.7827478647232056,
"start": 9168,
"tag": "NAME",
"value": "Administrator"
}
] | tests/JsonQuery.Tests.coffee | versionone/V1.Backbone | 1 | V1 = require('../V1.Backbone')
JsonRetriever = V1.Backbone.JsonRetriever
expect = require('chai').expect
Backbone = require('backbone')
recorded = require('./recorded')
spy = require('sinon').spy
deferred = require('JQDeferred')
inputCollection = null
describe 'V1.Backbone.JsonRetriever', ->
describe 'creating the object', ->
it 'throws an error when a url is not provided', ->
createWithoutUrl = -> new JsonRetriever()
expect(createWithoutUrl).to.throw(/url required/)
it 'does not throw an error when a url is provided', ->
createWithoutUrl = -> new JsonRetriever(url:"/VersionOne.Web/query.legacy.v1")
expect(createWithoutUrl).not.to.throw(/url required/)
describe 'given a collection with a queryMucker function on the collection\'s prototype', ->
beforeEach () ->
@queryMuckerSpy = spy()
inputCollection = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
inputCollection.prototype.queryMucker = @queryMuckerSpy
@url = "/VersionOne.Web/query.legacy.v1"
@fetcherSpy = spy () ->
deferred()
describe 'when executing the query', ->
beforeEach () ->
@sut = new JsonRetriever(url: @url, fetch: @fetcherSpy, defer: deferred)
@sut.for(inputCollection)
@sut.exec()
it 'should call the collection\'s prototype queryMucker function', ->
expect(@queryMuckerSpy.called).to.be.true
describe 'given a collection with a queryMucker function on the collection\'s instance', ->
beforeEach () ->
@queryMuckerSpy = spy()
inputCollection = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
queryMucker: @queryMuckerSpy
@url = "/VersionOne.Web/query.legacy.v1"
@fetcherSpy = spy () ->
deferred()
describe 'when executing the query', ->
beforeEach () ->
@sut = new JsonRetriever(url: @url, fetch: @fetcherSpy, defer: deferred)
@sut.for(inputCollection)
@sut.exec()
it 'should call the collection\'s instance queryMucker function', ->
expect(@queryMuckerSpy.called).to.be.true
describe 'executing a query', ->
it 'should not make a request if nothing has been asked for', ->
actualUrl = "/VersionOne.Web/query.legacy.v1"
fetcher = spy()
query = new JsonRetriever(url:actualUrl, fetch: fetcher)
query.exec()
expect(fetcher.called).to.be.false
it 'should make a request to the correct url', ->
collection = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
actualUrl = "/VersionOne.Web/query.legacy.v1"
fetcher = spy (url) ->
expect(url).to.equal(actualUrl)
deferred()
query = new JsonRetriever(url:actualUrl, fetch: fetcher, defer: deferred)
query.for(collection)
query.exec()
expect(fetcher.called).to.be.true
describe 'converting a backbone model to a query', ->
expectedQuery = (expected) ->
(url, data) ->
expect(data).to.equal(expected)
deferred()
describe 'basic schema', ->
it 'can generate very simple query', ->
Members = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: ["Name"]
ajax = expectedQuery '{"from":"Member","select":["Name"]}'
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Members)
query.exec()
it 'can query with an alias', ->
alias = V1.Backbone.alias
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ alias("Author.Name").as("Speaker") ]
ajax = expectedQuery '{"from":"Expression","select":["Author.Name"]}'
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Expressions)
query.exec()
it 'can generate a query with multiple attributes', ->
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: ["Author.Name", "Content"]
ajax = expectedQuery '{"from":"Expression","select":["Author.Name","Content"]}'
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Expressions)
query.exec()
it 'can generate a query with a relation', ->
relation = V1.Backbone.relation
Author = V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: ["Name"]
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ relation("Author").of(Author) ]
ajax = expectedQuery "{\"from\":\"Expression\",\"select\":[{\"from\":\"Author as Member\",\"select\":[\"Name\"]}]}"
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Expressions)
query.exec()
it 'can generate a query with a mutlirelation', ->
relation = V1.Backbone.relation
Replies = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: ["Content"]
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ relation("ExpressionsInConversation").of(Replies) ]
ajax = expectedQuery "{\"from\":\"Expression\",\"select\":[{\"from\":\"ExpressionsInConversation as Expression\",\"select\":[\"Content\"]}]}"
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Expressions)
query.exec()
describe "filtering relations", ->
it 'should be able to filter relations using "filter" clauses', ->
relation = V1.Backbone.relation
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
Members = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: [
relation("ParticipatesInConversations")
.of(Expressions)
.as("BigGroups")
.addFilter("ConversationParticipants.@Count>='2'")
]
ajax = expectedQuery '{"from":"Member","select":[{"from":"ParticipatesInConversations as Expression","filter":["ConversationParticipants.@Count>=\'2\'"]}]}'
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Members)
query.exec()
describe "getting results", ->
it 'can get results for a simple query', ->
Members = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: ["Name"]
query = new JsonRetriever(url:"url", fetch: recorded, defer: deferred)
query.for(Members).done (results) ->
expect(results.length).to.equal(5)
expect(results.at(0).get("Name")).to.equal("Administrator")
query.exec()
it 'can get results with an alias', ->
Members = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: [V1.Backbone.alias("Name").as("Who")]
query = new JsonRetriever(url:"url", fetch: recorded, defer: deferred)
query.for(Members).done (results) ->
expect(results.length).to.equal(5)
expect(results.at(0).get("Who")).to.equal("Administrator")
query.exec()
it 'can get hydrate results for a relation', ->
Member = V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: ["Name"]
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ V1.Backbone.relation("Author").of(Member) ]
query = new JsonRetriever(url:"url", fetch: recorded, defer: deferred)
query.for(Expressions).done (results) ->
expect(results.length).to.equal(41)
expect(results.at(0).get("Author").get("Name")).to.equal("Administrator")
query.exec()
it 'can support deep aliasing', ->
Member = V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: [ V1.Backbone.alias("Name").as("WhoDat") ]
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ V1.Backbone.relation("Author").of(Member) ]
query = new JsonRetriever(url:"url", fetch: recorded, defer: deferred)
query.for(Expressions).done (results) ->
expect(results.length).to.equal(41)
expect(results.at(0).get("Author").get("WhoDat")).to.equal("Administrator")
query.exec()
it 'can support deep relations', ->
Member = V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: [ V1.Backbone.alias("Name").as("WhoDat") ]
Reply = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ V1.Backbone.relation("Author").of(Member) ]
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ V1.Backbone.relation("ExpressionsInConversation").of(Reply).as("Replies") ]
query = new JsonRetriever(url:"url", fetch: recorded, defer: deferred)
query.for(Expressions).done (expressions) ->
expect(expressions.length).to.equal(41)
expect(expressions.at(1).get("Replies")).to.be.an.instanceof(V1.Backbone.Collection)
expect(expressions.at(1).get("Replies").at(0).get("Author").get("WhoDat")).to.equal("Administrator")
query.exec()
| 31145 | V1 = require('../V1.Backbone')
JsonRetriever = V1.Backbone.JsonRetriever
expect = require('chai').expect
Backbone = require('backbone')
recorded = require('./recorded')
spy = require('sinon').spy
deferred = require('JQDeferred')
inputCollection = null
describe 'V1.Backbone.JsonRetriever', ->
describe 'creating the object', ->
it 'throws an error when a url is not provided', ->
createWithoutUrl = -> new JsonRetriever()
expect(createWithoutUrl).to.throw(/url required/)
it 'does not throw an error when a url is provided', ->
createWithoutUrl = -> new JsonRetriever(url:"/VersionOne.Web/query.legacy.v1")
expect(createWithoutUrl).not.to.throw(/url required/)
describe 'given a collection with a queryMucker function on the collection\'s prototype', ->
beforeEach () ->
@queryMuckerSpy = spy()
inputCollection = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
inputCollection.prototype.queryMucker = @queryMuckerSpy
@url = "/VersionOne.Web/query.legacy.v1"
@fetcherSpy = spy () ->
deferred()
describe 'when executing the query', ->
beforeEach () ->
@sut = new JsonRetriever(url: @url, fetch: @fetcherSpy, defer: deferred)
@sut.for(inputCollection)
@sut.exec()
it 'should call the collection\'s prototype queryMucker function', ->
expect(@queryMuckerSpy.called).to.be.true
describe 'given a collection with a queryMucker function on the collection\'s instance', ->
beforeEach () ->
@queryMuckerSpy = spy()
inputCollection = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
queryMucker: @queryMuckerSpy
@url = "/VersionOne.Web/query.legacy.v1"
@fetcherSpy = spy () ->
deferred()
describe 'when executing the query', ->
beforeEach () ->
@sut = new JsonRetriever(url: @url, fetch: @fetcherSpy, defer: deferred)
@sut.for(inputCollection)
@sut.exec()
it 'should call the collection\'s instance queryMucker function', ->
expect(@queryMuckerSpy.called).to.be.true
describe 'executing a query', ->
it 'should not make a request if nothing has been asked for', ->
actualUrl = "/VersionOne.Web/query.legacy.v1"
fetcher = spy()
query = new JsonRetriever(url:actualUrl, fetch: fetcher)
query.exec()
expect(fetcher.called).to.be.false
it 'should make a request to the correct url', ->
collection = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
actualUrl = "/VersionOne.Web/query.legacy.v1"
fetcher = spy (url) ->
expect(url).to.equal(actualUrl)
deferred()
query = new JsonRetriever(url:actualUrl, fetch: fetcher, defer: deferred)
query.for(collection)
query.exec()
expect(fetcher.called).to.be.true
describe 'converting a backbone model to a query', ->
expectedQuery = (expected) ->
(url, data) ->
expect(data).to.equal(expected)
deferred()
describe 'basic schema', ->
it 'can generate very simple query', ->
Members = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: ["Name"]
ajax = expectedQuery '{"from":"Member","select":["Name"]}'
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Members)
query.exec()
it 'can query with an alias', ->
alias = V1.Backbone.alias
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ alias("Author.Name").as("Speaker") ]
ajax = expectedQuery '{"from":"Expression","select":["Author.Name"]}'
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Expressions)
query.exec()
it 'can generate a query with multiple attributes', ->
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: ["Author.Name", "Content"]
ajax = expectedQuery '{"from":"Expression","select":["Author.Name","Content"]}'
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Expressions)
query.exec()
it 'can generate a query with a relation', ->
relation = V1.Backbone.relation
Author = V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: ["Name"]
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ relation("Author").of(Author) ]
ajax = expectedQuery "{\"from\":\"Expression\",\"select\":[{\"from\":\"Author as Member\",\"select\":[\"Name\"]}]}"
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Expressions)
query.exec()
it 'can generate a query with a mutlirelation', ->
relation = V1.Backbone.relation
Replies = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: ["Content"]
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ relation("ExpressionsInConversation").of(Replies) ]
ajax = expectedQuery "{\"from\":\"Expression\",\"select\":[{\"from\":\"ExpressionsInConversation as Expression\",\"select\":[\"Content\"]}]}"
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Expressions)
query.exec()
describe "filtering relations", ->
it 'should be able to filter relations using "filter" clauses', ->
relation = V1.Backbone.relation
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
Members = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: [
relation("ParticipatesInConversations")
.of(Expressions)
.as("BigGroups")
.addFilter("ConversationParticipants.@Count>='2'")
]
ajax = expectedQuery '{"from":"Member","select":[{"from":"ParticipatesInConversations as Expression","filter":["ConversationParticipants.@Count>=\'2\'"]}]}'
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Members)
query.exec()
describe "getting results", ->
it 'can get results for a simple query', ->
Members = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: ["Name"]
query = new JsonRetriever(url:"url", fetch: recorded, defer: deferred)
query.for(Members).done (results) ->
expect(results.length).to.equal(5)
expect(results.at(0).get("Name")).to.equal("Administrator")
query.exec()
it 'can get results with an alias', ->
Members = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: [V1.Backbone.alias("Name").as("Who")]
query = new JsonRetriever(url:"url", fetch: recorded, defer: deferred)
query.for(Members).done (results) ->
expect(results.length).to.equal(5)
expect(results.at(0).get("Who")).to.equal("Administrator")
query.exec()
it 'can get hydrate results for a relation', ->
Member = V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: ["Name"]
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ V1.Backbone.relation("Author").of(Member) ]
query = new JsonRetriever(url:"url", fetch: recorded, defer: deferred)
query.for(Expressions).done (results) ->
expect(results.length).to.equal(41)
expect(results.at(0).get("Author").get("Name")).to.equal("<NAME>")
query.exec()
it 'can support deep aliasing', ->
Member = V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: [ V1.Backbone.alias("Name").as("WhoDat") ]
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ V1.Backbone.relation("Author").of(Member) ]
query = new JsonRetriever(url:"url", fetch: recorded, defer: deferred)
query.for(Expressions).done (results) ->
expect(results.length).to.equal(41)
expect(results.at(0).get("Author").get("WhoDat")).to.equal("Administrator")
query.exec()
it 'can support deep relations', ->
Member = V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: [ V1.Backbone.alias("Name").as("WhoDat") ]
Reply = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ V1.Backbone.relation("Author").of(Member) ]
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ V1.Backbone.relation("ExpressionsInConversation").of(Reply).as("Replies") ]
query = new JsonRetriever(url:"url", fetch: recorded, defer: deferred)
query.for(Expressions).done (expressions) ->
expect(expressions.length).to.equal(41)
expect(expressions.at(1).get("Replies")).to.be.an.instanceof(V1.Backbone.Collection)
expect(expressions.at(1).get("Replies").at(0).get("Author").get("WhoDat")).to.equal("Administrator")
query.exec()
| true | V1 = require('../V1.Backbone')
JsonRetriever = V1.Backbone.JsonRetriever
expect = require('chai').expect
Backbone = require('backbone')
recorded = require('./recorded')
spy = require('sinon').spy
deferred = require('JQDeferred')
inputCollection = null
describe 'V1.Backbone.JsonRetriever', ->
describe 'creating the object', ->
it 'throws an error when a url is not provided', ->
createWithoutUrl = -> new JsonRetriever()
expect(createWithoutUrl).to.throw(/url required/)
it 'does not throw an error when a url is provided', ->
createWithoutUrl = -> new JsonRetriever(url:"/VersionOne.Web/query.legacy.v1")
expect(createWithoutUrl).not.to.throw(/url required/)
describe 'given a collection with a queryMucker function on the collection\'s prototype', ->
beforeEach () ->
@queryMuckerSpy = spy()
inputCollection = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
inputCollection.prototype.queryMucker = @queryMuckerSpy
@url = "/VersionOne.Web/query.legacy.v1"
@fetcherSpy = spy () ->
deferred()
describe 'when executing the query', ->
beforeEach () ->
@sut = new JsonRetriever(url: @url, fetch: @fetcherSpy, defer: deferred)
@sut.for(inputCollection)
@sut.exec()
it 'should call the collection\'s prototype queryMucker function', ->
expect(@queryMuckerSpy.called).to.be.true
describe 'given a collection with a queryMucker function on the collection\'s instance', ->
beforeEach () ->
@queryMuckerSpy = spy()
inputCollection = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
queryMucker: @queryMuckerSpy
@url = "/VersionOne.Web/query.legacy.v1"
@fetcherSpy = spy () ->
deferred()
describe 'when executing the query', ->
beforeEach () ->
@sut = new JsonRetriever(url: @url, fetch: @fetcherSpy, defer: deferred)
@sut.for(inputCollection)
@sut.exec()
it 'should call the collection\'s instance queryMucker function', ->
expect(@queryMuckerSpy.called).to.be.true
describe 'executing a query', ->
it 'should not make a request if nothing has been asked for', ->
actualUrl = "/VersionOne.Web/query.legacy.v1"
fetcher = spy()
query = new JsonRetriever(url:actualUrl, fetch: fetcher)
query.exec()
expect(fetcher.called).to.be.false
it 'should make a request to the correct url', ->
collection = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
actualUrl = "/VersionOne.Web/query.legacy.v1"
fetcher = spy (url) ->
expect(url).to.equal(actualUrl)
deferred()
query = new JsonRetriever(url:actualUrl, fetch: fetcher, defer: deferred)
query.for(collection)
query.exec()
expect(fetcher.called).to.be.true
describe 'converting a backbone model to a query', ->
expectedQuery = (expected) ->
(url, data) ->
expect(data).to.equal(expected)
deferred()
describe 'basic schema', ->
it 'can generate very simple query', ->
Members = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: ["Name"]
ajax = expectedQuery '{"from":"Member","select":["Name"]}'
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Members)
query.exec()
it 'can query with an alias', ->
alias = V1.Backbone.alias
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ alias("Author.Name").as("Speaker") ]
ajax = expectedQuery '{"from":"Expression","select":["Author.Name"]}'
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Expressions)
query.exec()
it 'can generate a query with multiple attributes', ->
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: ["Author.Name", "Content"]
ajax = expectedQuery '{"from":"Expression","select":["Author.Name","Content"]}'
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Expressions)
query.exec()
it 'can generate a query with a relation', ->
relation = V1.Backbone.relation
Author = V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: ["Name"]
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ relation("Author").of(Author) ]
ajax = expectedQuery "{\"from\":\"Expression\",\"select\":[{\"from\":\"Author as Member\",\"select\":[\"Name\"]}]}"
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Expressions)
query.exec()
it 'can generate a query with a mutlirelation', ->
relation = V1.Backbone.relation
Replies = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: ["Content"]
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ relation("ExpressionsInConversation").of(Replies) ]
ajax = expectedQuery "{\"from\":\"Expression\",\"select\":[{\"from\":\"ExpressionsInConversation as Expression\",\"select\":[\"Content\"]}]}"
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Expressions)
query.exec()
describe "filtering relations", ->
it 'should be able to filter relations using "filter" clauses', ->
relation = V1.Backbone.relation
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
Members = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: [
relation("ParticipatesInConversations")
.of(Expressions)
.as("BigGroups")
.addFilter("ConversationParticipants.@Count>='2'")
]
ajax = expectedQuery '{"from":"Member","select":[{"from":"ParticipatesInConversations as Expression","filter":["ConversationParticipants.@Count>=\'2\'"]}]}'
query = new JsonRetriever(url:"url", fetch: ajax, defer: deferred)
query.for(Members)
query.exec()
describe "getting results", ->
it 'can get results for a simple query', ->
Members = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: ["Name"]
query = new JsonRetriever(url:"url", fetch: recorded, defer: deferred)
query.for(Members).done (results) ->
expect(results.length).to.equal(5)
expect(results.at(0).get("Name")).to.equal("Administrator")
query.exec()
it 'can get results with an alias', ->
Members = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: [V1.Backbone.alias("Name").as("Who")]
query = new JsonRetriever(url:"url", fetch: recorded, defer: deferred)
query.for(Members).done (results) ->
expect(results.length).to.equal(5)
expect(results.at(0).get("Who")).to.equal("Administrator")
query.exec()
it 'can get hydrate results for a relation', ->
Member = V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: ["Name"]
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ V1.Backbone.relation("Author").of(Member) ]
query = new JsonRetriever(url:"url", fetch: recorded, defer: deferred)
query.for(Expressions).done (results) ->
expect(results.length).to.equal(41)
expect(results.at(0).get("Author").get("Name")).to.equal("PI:NAME:<NAME>END_PI")
query.exec()
it 'can support deep aliasing', ->
Member = V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: [ V1.Backbone.alias("Name").as("WhoDat") ]
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ V1.Backbone.relation("Author").of(Member) ]
query = new JsonRetriever(url:"url", fetch: recorded, defer: deferred)
query.for(Expressions).done (results) ->
expect(results.length).to.equal(41)
expect(results.at(0).get("Author").get("WhoDat")).to.equal("Administrator")
query.exec()
it 'can support deep relations', ->
Member = V1.Backbone.Model.extend
queryOptions:
assetType: "Member"
schema: [ V1.Backbone.alias("Name").as("WhoDat") ]
Reply = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ V1.Backbone.relation("Author").of(Member) ]
Expressions = V1.Backbone.Collection.extend
model: V1.Backbone.Model.extend
queryOptions:
assetType: "Expression"
schema: [ V1.Backbone.relation("ExpressionsInConversation").of(Reply).as("Replies") ]
query = new JsonRetriever(url:"url", fetch: recorded, defer: deferred)
query.for(Expressions).done (expressions) ->
expect(expressions.length).to.equal(41)
expect(expressions.at(1).get("Replies")).to.be.an.instanceof(V1.Backbone.Collection)
expect(expressions.at(1).get("Replies").at(0).get("Author").get("WhoDat")).to.equal("Administrator")
query.exec()
|
[
{
"context": "a-f0-9]{24}$/i)\n required: true\n altKeys: ['shipId', 'platformId']\n },\n orgUrl: {\n validation: ",
"end": 1080,
"score": 0.9969333410263062,
"start": 1074,
"tag": "KEY",
"value": "shipId"
},
{
"context": "}$/i)\n required: true\n altKeys: ['shipId',... | src/client/script-tag-config.coffee | fossabot/hull-js | 25 | _ = require '../utils/lodash'
logger = require '../utils/logger'
dasherize = (str)->
str.replace /[A-Z]/, (c) -> "-" + c.toLowerCase()
origin = window.location.origin || window.location.protocol + "//" + window.location.hostname
if window.location.port
origin += ':' + window.location.port
httpsRegex = /^https:|^\/\//
valid =
regex: (reg)-> (val, key)->
check = reg.test(val)
if !check
logger.error("[Hull.init] invalid format for '#{key}'. Value '#{val}' should match #{reg.toString()}")
check
https: (val, key)->
check = httpsRegex.test(val)
return true if check
logger.warn("[Hull.init] #{key} should be loaded via https. Current value is ", val)
true
transform =
url: (url, key)->
if url && url.length > 0
a = document.createElement('a')
a.href = url
a.href
bool: (str, key)->
switch str
when 'true', true then true
when 'false', false then false
else undefined
initParams = {
appId: {
validation: valid.regex(/^[a-f0-9]{24}$/i)
required: true
altKeys: ['shipId', 'platformId']
},
orgUrl: {
validation: valid.https
required: true
},
jsUrl: {
transform: transform.url
validation: valid.https
altKeys: ['src']
},
callbackUrl: {
transform: transform.url
validation: valid.regex(new RegExp("^" + origin + "/"))
},
debug : { default: false, transform: transform.bool },
verbose : { default: false, transform: transform.bool },
embed : { default: true, transform: transform.bool },
autoStart : { default: true, transform: transform.bool },
accessToken : { default: null },
customerId : { default: null },
anonymousId : { default: null },
sessionId : { default: null },
ravenDsn : { default: null }
}
getAttribute = (el, k)->
el.getAttribute("data-" + dasherize(k)) || el.getAttribute("data-" + k) || el.getAttribute(dasherize(k)) || el.getAttribute(k)
getParamValue = (el, param, key)->
keys = [key].concat(param.altKeys || [])
transform = param.transform || (o)-> o
value = _.reduce(keys, (ret, k)->
if ret == null
value = transform(getAttribute(el, k), key)
valid = value? && (!param.validation || param.validation(value, k, el))
ret = value if valid
ret
, null)
if value? then value else param.default
module.exports = ->
hull_js_sdk = document.getElementById('hull-js-sdk') || document.querySelector('[org-url][platform-id][data-org-url][data-platform-id]')
return unless hull_js_sdk
# Map known config values to Hull init
out = _.reduce initParams, (config, param, key)->
return unless config
value = getParamValue(hull_js_sdk, param, key)
if value?
config[key] = value
else if param.required
config = false
config
, {}
if out
logger.error("[Hull.init] jsUrl NEEDS be loaded via https if orgUrl is https ") if httpsRegex.test(out.orgUrl) and not httpsRegex.test(out.jsUrl)
out
| 145063 | _ = require '../utils/lodash'
logger = require '../utils/logger'
dasherize = (str)->
str.replace /[A-Z]/, (c) -> "-" + c.toLowerCase()
origin = window.location.origin || window.location.protocol + "//" + window.location.hostname
if window.location.port
origin += ':' + window.location.port
httpsRegex = /^https:|^\/\//
valid =
regex: (reg)-> (val, key)->
check = reg.test(val)
if !check
logger.error("[Hull.init] invalid format for '#{key}'. Value '#{val}' should match #{reg.toString()}")
check
https: (val, key)->
check = httpsRegex.test(val)
return true if check
logger.warn("[Hull.init] #{key} should be loaded via https. Current value is ", val)
true
transform =
url: (url, key)->
if url && url.length > 0
a = document.createElement('a')
a.href = url
a.href
bool: (str, key)->
switch str
when 'true', true then true
when 'false', false then false
else undefined
initParams = {
appId: {
validation: valid.regex(/^[a-f0-9]{24}$/i)
required: true
altKeys: ['<KEY>', '<KEY>']
},
orgUrl: {
validation: valid.https
required: true
},
jsUrl: {
transform: transform.url
validation: valid.https
altKeys: ['src']
},
callbackUrl: {
transform: transform.url
validation: valid.regex(new RegExp("^" + origin + "/"))
},
debug : { default: false, transform: transform.bool },
verbose : { default: false, transform: transform.bool },
embed : { default: true, transform: transform.bool },
autoStart : { default: true, transform: transform.bool },
accessToken : { default: null },
customerId : { default: null },
anonymousId : { default: null },
sessionId : { default: null },
ravenDsn : { default: null }
}
getAttribute = (el, k)->
el.getAttribute("data-" + dasherize(k)) || el.getAttribute("data-" + k) || el.getAttribute(dasherize(k)) || el.getAttribute(k)
getParamValue = (el, param, key)->
keys = [key].concat(param.altKeys || [])
transform = param.transform || (o)-> o
value = _.reduce(keys, (ret, k)->
if ret == null
value = transform(getAttribute(el, k), key)
valid = value? && (!param.validation || param.validation(value, k, el))
ret = value if valid
ret
, null)
if value? then value else param.default
module.exports = ->
hull_js_sdk = document.getElementById('hull-js-sdk') || document.querySelector('[org-url][platform-id][data-org-url][data-platform-id]')
return unless hull_js_sdk
# Map known config values to Hull init
out = _.reduce initParams, (config, param, key)->
return unless config
value = getParamValue(hull_js_sdk, param, key)
if value?
config[key] = value
else if param.required
config = false
config
, {}
if out
logger.error("[Hull.init] jsUrl NEEDS be loaded via https if orgUrl is https ") if httpsRegex.test(out.orgUrl) and not httpsRegex.test(out.jsUrl)
out
| true | _ = require '../utils/lodash'
logger = require '../utils/logger'
dasherize = (str)->
str.replace /[A-Z]/, (c) -> "-" + c.toLowerCase()
origin = window.location.origin || window.location.protocol + "//" + window.location.hostname
if window.location.port
origin += ':' + window.location.port
httpsRegex = /^https:|^\/\//
valid =
regex: (reg)-> (val, key)->
check = reg.test(val)
if !check
logger.error("[Hull.init] invalid format for '#{key}'. Value '#{val}' should match #{reg.toString()}")
check
https: (val, key)->
check = httpsRegex.test(val)
return true if check
logger.warn("[Hull.init] #{key} should be loaded via https. Current value is ", val)
true
transform =
url: (url, key)->
if url && url.length > 0
a = document.createElement('a')
a.href = url
a.href
bool: (str, key)->
switch str
when 'true', true then true
when 'false', false then false
else undefined
initParams = {
appId: {
validation: valid.regex(/^[a-f0-9]{24}$/i)
required: true
altKeys: ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI']
},
orgUrl: {
validation: valid.https
required: true
},
jsUrl: {
transform: transform.url
validation: valid.https
altKeys: ['src']
},
callbackUrl: {
transform: transform.url
validation: valid.regex(new RegExp("^" + origin + "/"))
},
debug : { default: false, transform: transform.bool },
verbose : { default: false, transform: transform.bool },
embed : { default: true, transform: transform.bool },
autoStart : { default: true, transform: transform.bool },
accessToken : { default: null },
customerId : { default: null },
anonymousId : { default: null },
sessionId : { default: null },
ravenDsn : { default: null }
}
getAttribute = (el, k)->
el.getAttribute("data-" + dasherize(k)) || el.getAttribute("data-" + k) || el.getAttribute(dasherize(k)) || el.getAttribute(k)
getParamValue = (el, param, key)->
keys = [key].concat(param.altKeys || [])
transform = param.transform || (o)-> o
value = _.reduce(keys, (ret, k)->
if ret == null
value = transform(getAttribute(el, k), key)
valid = value? && (!param.validation || param.validation(value, k, el))
ret = value if valid
ret
, null)
if value? then value else param.default
module.exports = ->
hull_js_sdk = document.getElementById('hull-js-sdk') || document.querySelector('[org-url][platform-id][data-org-url][data-platform-id]')
return unless hull_js_sdk
# Map known config values to Hull init
out = _.reduce initParams, (config, param, key)->
return unless config
value = getParamValue(hull_js_sdk, param, key)
if value?
config[key] = value
else if param.required
config = false
config
, {}
if out
logger.error("[Hull.init] jsUrl NEEDS be loaded via https if orgUrl is https ") if httpsRegex.test(out.orgUrl) and not httpsRegex.test(out.jsUrl)
out
|
[
{
"context": " $modalInstance.close {\n username: this.username\n password: this.password\n }\n $scop",
"end": 5467,
"score": 0.5811622738838196,
"start": 5459,
"tag": "USERNAME",
"value": "username"
},
{
"context": "\n username: this.username\n ... | src/coffee/controllers/mainCtrl.coffee | Chanshi712/RedmineTimeTracker | 73 | timeTracker.controller 'MainCtrl', ($rootScope, $scope, $timeout, $location, $anchorScroll, $window, $q, $modal, Ticket, Project, Account, State, DataAdapter, Message, Platform, Resource, Option, Log, Analytics, RedmineLoader) ->
# represents 5 minuts [msec]
MINUTE_5 = 5 * 60 * 1000
# List for toast Message.
$rootScope.messages = []
# Global state
$scope.state = State
# Root font size
$scope.options = Option.getOptions()
###
Initialize.
###
init = () ->
deferred = $q.defer()
deferred.promise
.then(_setLoginLister)
.then(_initializeGoogleAnalytics)
.then(_initializeDataFromChrome)
.then(_initializeDataFromRedmine)
.then(_initializeEvents)
.then(_startDataSync)
deferred.resolve()
###
initialize events.
###
_initializeEvents = () ->
Log.debug "[4] initializeEvents start"
DataAdapter.addEventListener DataAdapter.ACCOUNT_ADDED, RedmineLoader.fetchAllData
DataAdapter.addEventListener DataAdapter.ACCOUNT_UPDATED, RedmineLoader.fetchAllData
DataAdapter.addEventListener DataAdapter.SELECTED_PROJECT_CHANGED, _syncSelectedProject
DataAdapter.addEventListener DataAdapter.PROJECTS_CHANGED, () ->
Project.syncLocal(DataAdapter.getProjects())
DataAdapter.addEventListener DataAdapter.TICKETS_CHANGED, () ->
Ticket.syncLocal(DataAdapter.tickets)
Option.onChanged('reportUsage', (val) -> Analytics.setPermission(val))
Option.onChanged('hideNonTicketProject', _toggleProjectHidden)
Log.debug "[4] initializeEvents success"
###
count project's issues count on all accounts.
###
_toggleProjectHidden = (enableHide) ->
if enableHide
promises = for a in Account.getAccounts()
RedmineLoader.fetchTicketsCount(a)()
else
DataAdapter.updateProjects()
###
request a setup of redmine account to user.
###
_requestAddAccount = () ->
$timeout () ->
State.isAddingAccount = true
State.isCollapseSetting = false
, 500
$timeout () ->
$location.hash('accounts')
$anchorScroll()
, 1000
$timeout () ->
Message.toast(Resource.string("msgRequestAddAccount_0"), 5000)
, 1500
$timeout () ->
Message.toast(Resource.string("msgRequestAddAccount_1"), 5000)
, 2500
###
initialize GoogleAnalytics.
###
_initializeGoogleAnalytics = () ->
Log.debug "[1] initializeGoogleAnalytics start"
Analytics.init {
serviceName: "RedmineTimeTracker"
analyticsCode: "UA-32234486-7"
}
Analytics.sendView(Platform.getPlatform())
Log.debug "[1] initializeGoogleAnalytics success"
###
initialize Data from chrome storage.
###
_initializeDataFromChrome = () ->
Log.debug "[2] initializeDataFromChrome start"
Option.loadOptions()
.then(_initializeAccount)
.then(_initializeProject)
.then(_initializeTicket)
.then(() ->
Log.debug "[2] initializeDataFromChrome success."
, () ->
Log.warn "[2] initializeDataFromChrome failed")
###
Initialize account from chrome storage.
###
_initializeAccount = () ->
Account.load().then (accounts) ->
if accounts and not accounts.isEmpty()
DataAdapter.addAccounts(accounts)
else
_requestAddAccount()
###
Initialize project from chrome storage.
###
_initializeProject = () ->
Project.load()
.then((projects) ->
DataAdapter.addProjects(projects)
# restore last selected project.
Platform.load(Platform.SELECTED_PROJECT))
.then((selected) ->
if not selected? then return
projects = DataAdapter.getProjects(selected.url)
project = projects.find (p) -> p.equals(selected)
DataAdapter.selectedProject = project)
###
Initialize issues status.
###
_initializeTicket = () ->
Ticket.load()
.then((res) -> DataAdapter.toggleIsTicketShow(res.tickets))
###
initialize Data from Redmine.
###
_initializeDataFromRedmine = () ->
Log.debug "[3] initializeDataFromRedmine start "
accounts = DataAdapter.getAccount()
$q.all(RedmineLoader.fetchAllData(accounts))
.finally(-> Log.debug "[3] initializeDataFromRedmine success")
###*
Start data synchronization.
###
_startDataSync = () ->
window.setInterval(() ->
Ticket.sync(DataAdapter.tickets)
Project.sync(DataAdapter.getProjects())
, MINUTE_5)
###*
Sync a selected project to chrome storage.
###
_syncSelectedProject = () ->
selected = DataAdapter.selectedProject
obj = {
url: selected.url
id: selected.id
type: selected.type
}
Platform.save(Platform.SELECTED_PROJECT, obj)
###*
Set proxy login event lister.
###
_setLoginLister = () ->
return if 'electron' isnt Platform.getPlatform()
isShowingModal = false
Platform.setLoginLister (callback) ->
return if isShowingModal
isShowingModal = true
modal = $modal.open {
templateUrl: Platform.getPath('/views/proxyLogin.html')
controller: loginCtrl
}
modal.result.then (auth) ->
isShowingModal = false
callback(auth)
, () ->
isShowingModal = false
callback(null) # canceled
###*
Controller for input login infomation dialog.
###
loginCtrl = ($scope, $modalInstance, Resource) ->
$scope.R = Resource
$scope.ok = () ->
$modalInstance.close {
username: this.username
password: this.password
}
$scope.cancel = () ->
$modalInstance.dismiss 'canceled.'
loginCtrl.$inject = ['$scope', '$modalInstance', 'Resource']
###
Start Initialize.
###
init()
| 11958 | timeTracker.controller 'MainCtrl', ($rootScope, $scope, $timeout, $location, $anchorScroll, $window, $q, $modal, Ticket, Project, Account, State, DataAdapter, Message, Platform, Resource, Option, Log, Analytics, RedmineLoader) ->
# represents 5 minuts [msec]
MINUTE_5 = 5 * 60 * 1000
# List for toast Message.
$rootScope.messages = []
# Global state
$scope.state = State
# Root font size
$scope.options = Option.getOptions()
###
Initialize.
###
init = () ->
deferred = $q.defer()
deferred.promise
.then(_setLoginLister)
.then(_initializeGoogleAnalytics)
.then(_initializeDataFromChrome)
.then(_initializeDataFromRedmine)
.then(_initializeEvents)
.then(_startDataSync)
deferred.resolve()
###
initialize events.
###
_initializeEvents = () ->
Log.debug "[4] initializeEvents start"
DataAdapter.addEventListener DataAdapter.ACCOUNT_ADDED, RedmineLoader.fetchAllData
DataAdapter.addEventListener DataAdapter.ACCOUNT_UPDATED, RedmineLoader.fetchAllData
DataAdapter.addEventListener DataAdapter.SELECTED_PROJECT_CHANGED, _syncSelectedProject
DataAdapter.addEventListener DataAdapter.PROJECTS_CHANGED, () ->
Project.syncLocal(DataAdapter.getProjects())
DataAdapter.addEventListener DataAdapter.TICKETS_CHANGED, () ->
Ticket.syncLocal(DataAdapter.tickets)
Option.onChanged('reportUsage', (val) -> Analytics.setPermission(val))
Option.onChanged('hideNonTicketProject', _toggleProjectHidden)
Log.debug "[4] initializeEvents success"
###
count project's issues count on all accounts.
###
_toggleProjectHidden = (enableHide) ->
if enableHide
promises = for a in Account.getAccounts()
RedmineLoader.fetchTicketsCount(a)()
else
DataAdapter.updateProjects()
###
request a setup of redmine account to user.
###
_requestAddAccount = () ->
$timeout () ->
State.isAddingAccount = true
State.isCollapseSetting = false
, 500
$timeout () ->
$location.hash('accounts')
$anchorScroll()
, 1000
$timeout () ->
Message.toast(Resource.string("msgRequestAddAccount_0"), 5000)
, 1500
$timeout () ->
Message.toast(Resource.string("msgRequestAddAccount_1"), 5000)
, 2500
###
initialize GoogleAnalytics.
###
_initializeGoogleAnalytics = () ->
Log.debug "[1] initializeGoogleAnalytics start"
Analytics.init {
serviceName: "RedmineTimeTracker"
analyticsCode: "UA-32234486-7"
}
Analytics.sendView(Platform.getPlatform())
Log.debug "[1] initializeGoogleAnalytics success"
###
initialize Data from chrome storage.
###
_initializeDataFromChrome = () ->
Log.debug "[2] initializeDataFromChrome start"
Option.loadOptions()
.then(_initializeAccount)
.then(_initializeProject)
.then(_initializeTicket)
.then(() ->
Log.debug "[2] initializeDataFromChrome success."
, () ->
Log.warn "[2] initializeDataFromChrome failed")
###
Initialize account from chrome storage.
###
_initializeAccount = () ->
Account.load().then (accounts) ->
if accounts and not accounts.isEmpty()
DataAdapter.addAccounts(accounts)
else
_requestAddAccount()
###
Initialize project from chrome storage.
###
_initializeProject = () ->
Project.load()
.then((projects) ->
DataAdapter.addProjects(projects)
# restore last selected project.
Platform.load(Platform.SELECTED_PROJECT))
.then((selected) ->
if not selected? then return
projects = DataAdapter.getProjects(selected.url)
project = projects.find (p) -> p.equals(selected)
DataAdapter.selectedProject = project)
###
Initialize issues status.
###
_initializeTicket = () ->
Ticket.load()
.then((res) -> DataAdapter.toggleIsTicketShow(res.tickets))
###
initialize Data from Redmine.
###
_initializeDataFromRedmine = () ->
Log.debug "[3] initializeDataFromRedmine start "
accounts = DataAdapter.getAccount()
$q.all(RedmineLoader.fetchAllData(accounts))
.finally(-> Log.debug "[3] initializeDataFromRedmine success")
###*
Start data synchronization.
###
_startDataSync = () ->
window.setInterval(() ->
Ticket.sync(DataAdapter.tickets)
Project.sync(DataAdapter.getProjects())
, MINUTE_5)
###*
Sync a selected project to chrome storage.
###
_syncSelectedProject = () ->
selected = DataAdapter.selectedProject
obj = {
url: selected.url
id: selected.id
type: selected.type
}
Platform.save(Platform.SELECTED_PROJECT, obj)
###*
Set proxy login event lister.
###
_setLoginLister = () ->
return if 'electron' isnt Platform.getPlatform()
isShowingModal = false
Platform.setLoginLister (callback) ->
return if isShowingModal
isShowingModal = true
modal = $modal.open {
templateUrl: Platform.getPath('/views/proxyLogin.html')
controller: loginCtrl
}
modal.result.then (auth) ->
isShowingModal = false
callback(auth)
, () ->
isShowingModal = false
callback(null) # canceled
###*
Controller for input login infomation dialog.
###
loginCtrl = ($scope, $modalInstance, Resource) ->
$scope.R = Resource
$scope.ok = () ->
$modalInstance.close {
username: this.username
password: <PASSWORD>
}
$scope.cancel = () ->
$modalInstance.dismiss 'canceled.'
loginCtrl.$inject = ['$scope', '$modalInstance', 'Resource']
###
Start Initialize.
###
init()
| true | timeTracker.controller 'MainCtrl', ($rootScope, $scope, $timeout, $location, $anchorScroll, $window, $q, $modal, Ticket, Project, Account, State, DataAdapter, Message, Platform, Resource, Option, Log, Analytics, RedmineLoader) ->
# represents 5 minuts [msec]
MINUTE_5 = 5 * 60 * 1000
# List for toast Message.
$rootScope.messages = []
# Global state
$scope.state = State
# Root font size
$scope.options = Option.getOptions()
###
Initialize.
###
init = () ->
deferred = $q.defer()
deferred.promise
.then(_setLoginLister)
.then(_initializeGoogleAnalytics)
.then(_initializeDataFromChrome)
.then(_initializeDataFromRedmine)
.then(_initializeEvents)
.then(_startDataSync)
deferred.resolve()
###
initialize events.
###
_initializeEvents = () ->
Log.debug "[4] initializeEvents start"
DataAdapter.addEventListener DataAdapter.ACCOUNT_ADDED, RedmineLoader.fetchAllData
DataAdapter.addEventListener DataAdapter.ACCOUNT_UPDATED, RedmineLoader.fetchAllData
DataAdapter.addEventListener DataAdapter.SELECTED_PROJECT_CHANGED, _syncSelectedProject
DataAdapter.addEventListener DataAdapter.PROJECTS_CHANGED, () ->
Project.syncLocal(DataAdapter.getProjects())
DataAdapter.addEventListener DataAdapter.TICKETS_CHANGED, () ->
Ticket.syncLocal(DataAdapter.tickets)
Option.onChanged('reportUsage', (val) -> Analytics.setPermission(val))
Option.onChanged('hideNonTicketProject', _toggleProjectHidden)
Log.debug "[4] initializeEvents success"
###
count project's issues count on all accounts.
###
_toggleProjectHidden = (enableHide) ->
if enableHide
promises = for a in Account.getAccounts()
RedmineLoader.fetchTicketsCount(a)()
else
DataAdapter.updateProjects()
###
request a setup of redmine account to user.
###
_requestAddAccount = () ->
$timeout () ->
State.isAddingAccount = true
State.isCollapseSetting = false
, 500
$timeout () ->
$location.hash('accounts')
$anchorScroll()
, 1000
$timeout () ->
Message.toast(Resource.string("msgRequestAddAccount_0"), 5000)
, 1500
$timeout () ->
Message.toast(Resource.string("msgRequestAddAccount_1"), 5000)
, 2500
###
initialize GoogleAnalytics.
###
_initializeGoogleAnalytics = () ->
Log.debug "[1] initializeGoogleAnalytics start"
Analytics.init {
serviceName: "RedmineTimeTracker"
analyticsCode: "UA-32234486-7"
}
Analytics.sendView(Platform.getPlatform())
Log.debug "[1] initializeGoogleAnalytics success"
###
initialize Data from chrome storage.
###
_initializeDataFromChrome = () ->
Log.debug "[2] initializeDataFromChrome start"
Option.loadOptions()
.then(_initializeAccount)
.then(_initializeProject)
.then(_initializeTicket)
.then(() ->
Log.debug "[2] initializeDataFromChrome success."
, () ->
Log.warn "[2] initializeDataFromChrome failed")
###
Initialize account from chrome storage.
###
_initializeAccount = () ->
Account.load().then (accounts) ->
if accounts and not accounts.isEmpty()
DataAdapter.addAccounts(accounts)
else
_requestAddAccount()
###
Initialize project from chrome storage.
###
_initializeProject = () ->
Project.load()
.then((projects) ->
DataAdapter.addProjects(projects)
# restore last selected project.
Platform.load(Platform.SELECTED_PROJECT))
.then((selected) ->
if not selected? then return
projects = DataAdapter.getProjects(selected.url)
project = projects.find (p) -> p.equals(selected)
DataAdapter.selectedProject = project)
###
Initialize issues status.
###
_initializeTicket = () ->
Ticket.load()
.then((res) -> DataAdapter.toggleIsTicketShow(res.tickets))
###
initialize Data from Redmine.
###
_initializeDataFromRedmine = () ->
Log.debug "[3] initializeDataFromRedmine start "
accounts = DataAdapter.getAccount()
$q.all(RedmineLoader.fetchAllData(accounts))
.finally(-> Log.debug "[3] initializeDataFromRedmine success")
###*
Start data synchronization.
###
_startDataSync = () ->
window.setInterval(() ->
Ticket.sync(DataAdapter.tickets)
Project.sync(DataAdapter.getProjects())
, MINUTE_5)
###*
Sync a selected project to chrome storage.
###
_syncSelectedProject = () ->
selected = DataAdapter.selectedProject
obj = {
url: selected.url
id: selected.id
type: selected.type
}
Platform.save(Platform.SELECTED_PROJECT, obj)
###*
Set proxy login event lister.
###
_setLoginLister = () ->
return if 'electron' isnt Platform.getPlatform()
isShowingModal = false
Platform.setLoginLister (callback) ->
return if isShowingModal
isShowingModal = true
modal = $modal.open {
templateUrl: Platform.getPath('/views/proxyLogin.html')
controller: loginCtrl
}
modal.result.then (auth) ->
isShowingModal = false
callback(auth)
, () ->
isShowingModal = false
callback(null) # canceled
###*
Controller for input login infomation dialog.
###
loginCtrl = ($scope, $modalInstance, Resource) ->
$scope.R = Resource
$scope.ok = () ->
$modalInstance.close {
username: this.username
password: PI:PASSWORD:<PASSWORD>END_PI
}
$scope.cancel = () ->
$modalInstance.dismiss 'canceled.'
loginCtrl.$inject = ['$scope', '$modalInstance', 'Resource']
###
Start Initialize.
###
init()
|
[
{
"context": "t([catIndex, catGenreIndex])\n keys = Set(['genre','cat','dude'])\n \n index = ObjectSt",
"end": 9898,
"score": 0.7870301008224487,
"start": 9893,
"tag": "KEY",
"value": "genre"
},
{
"context": "dex, catGenreIndex])\n keys = Set(['genre','cat... | spec/search/object_store_spec.coffee | dcrosby42/metroid-clone | 5 | # Finder = require '../../src/javascript/search/immutable_object_finder'
Immutable = require 'immutable'
{Map,Set,List} = Immutable
ExpectHelpers = require '../helpers/expect_helpers'
expectIs = ExpectHelpers.expectIs
ObjectStore = require '../../src/javascript/search/object_store'
util = require 'util'
chai = require('chai')
expect = chai.expect
assert = chai.assert
imm = Immutable.fromJS
immset = (xs...) -> Set(xs)
padThai = imm dishId: 'i1', dish: 'Pad Thai', base: 'noodles'
houseSpecial = imm dishId: 'i2', dish: 'Curry fried rice', base: 'rice'
curryPadThai = imm dishId: 'i3', dish: 'Basil Cury', base: 'rice'
pcn = imm dishId: 'i4', dish: 'Peanut Curry Noodle', base: 'noodles'
dishList = imm [ padThai, houseSpecial, curryPadThai, pcn ]
books = imm [
{ bookId: 'b1', cat: 'fiction', genre: 'scifi', title: 'Foundation' }
{ bookId: 'b2', cat: 'nonfiction', genre: 'selfhelp', title: 'Crucial Conversations' }
{ bookId: 'b3', cat: 'fiction', genre: 'fantasy', title: 'The Wheel of Time' }
{ bookId: 'b4', cat: 'fiction', genre: 'scifi', title: 'Time Enough for Love' }
]
mappedBooks = ObjectStore.mappedBy(books,'bookId')
book1 = mappedBooks.get('b1')
book4 = mappedBooks.get('b4')
describe "ObjectStore", ->
describe "data transformation fns", ->
describe "mappedBy", ->
it "converts a list of objects into a map, keyed by the indicated key", ->
m = ObjectStore.mappedBy(dishList, 'dishId')
expectIs m, imm(
i1: padThai
i2: houseSpecial
i3: curryPadThai
i4: pcn
)
it "returns empty map for empty list", ->
m = ObjectStore.mappedBy(imm([]), 'wat')
expectIs m, imm({})
describe "indexObjects", ->
it "given objects and a prop names, group the objects' identKeys by the given prop name", ->
idx = ObjectStore.indexObjects(dishList.values(), List(['base']), 'dishId')
expectIs idx, imm(
rice: immset('i2','i3')
noodles: immset('i1','i4')
)
it "given objects and a list of n prop names, return an n-ary keyed map of key-paths to their identifier keys", ->
idx = ObjectStore.indexObjects(books.values(), List(['cat','genre']), 'bookId')
expectIs idx, imm(
fiction:
scifi: immset('b1','b4')
fantasy: immset('b3')
nonfiction:
selfhelp: immset('b2')
)
describe "store manipulation fns", ->
store = null
beforeEach ->
store = ObjectStore.create('bookId')
describe "addObject() and getObject()", ->
it "can store and retrieve objects according to the dataKey", ->
store = ObjectStore.addObject(store, books.get(0))
expectIs ObjectStore.getObject(store, 'b1'), books.get(0)
it "returns null when requested object isn't there", ->
expect(ObjectStore.getObject(store, 'NOOO')).to.be.null
expect(ObjectStore.getObject(store, '')).to.be.null
expect(ObjectStore.getObject(store, null)).to.be.null
describe "addIndex(), getIndexedObjectIds() and getIndexedObjects()", ->
it "can add multiple objects and index them and retrieve by indexed search", ->
store = ObjectStore.addIndex(store, imm(['genre']))
store = ObjectStore.addObjects(store, books)
scifiBookIds = ObjectStore.getIndexedObjectIds(store, imm(['genre']), imm(['scifi']))
expectIs scifiBookIds, immset('b1', 'b4')
store = ObjectStore.addIndex(store, imm(['cat','genre']))
helps = ObjectStore.getIndexedObjectIds(store, imm(['cat','genre']), imm(['nonfiction','selfhelp']))
expectIs helps, immset('b2')
store = ObjectStore.addObject(store, imm { bookId: 'b05', cat: 'nonfiction', genre: 'selfhelp', title: '7 Habits of Highly Effective People' })
helps = ObjectStore.getIndexedObjectIds(store, imm(['cat','genre']), imm(['nonfiction','selfhelp']))
expectIs helps, immset('b2','b05')
it "can retrieve actual objects", ->
store = ObjectStore.addIndex(store, imm(['genre']))
store = ObjectStore.addObjects(store, books)
scifiBooks = ObjectStore.getIndexedObjects(store, imm(['genre']), imm(['scifi']))
expectIs scifiBooks, immset(book1, book4)
it "returns empty Set when requested index isn't there", ->
res = ObjectStore.getIndexedObjectIds(store, imm(['something','wicked']), imm(['this way','comes']))
expectIs res, immset()
res = ObjectStore.getIndexedObjectIds(store, imm([]), imm(['this way','comes']))
expectIs res, immset()
res = ObjectStore.getIndexedObjectIds(store, null, imm(['this way','comes']))
expectIs res, immset()
res = ObjectStore.getIndexedObjects(store, null, imm(['this way','comes']))
expectIs res, immset()
describe "removeObject()", ->
it "removes objects from the store", ->
# store = ObjectStore.addIndex(store, imm(['genre']))
store = ObjectStore.addObjects(store, books)
b1 = books.get(0)
b2 = books.get(1)
expectIs ObjectStore.getObject(store, 'b1'), b1
expectIs ObjectStore.getObject(store, 'b2'), b2
store = ObjectStore.removeObject(store, b1)
expect(ObjectStore.getObject(store, 'b1')).to.be.null
# b2 should still be there:
expectIs ObjectStore.getObject(store, 'b2'), b2
store = ObjectStore.removeObject(store, b2)
expect(ObjectStore.getObject(store, 'b2')).to.be.null
it "removes objects from their indices", ->
store = ObjectStore.addIndex(store, List(['genre']))
store = ObjectStore.addObjects(store, books)
b1 = books.get(0)
b4 = books.get(3)
scifiBookIds = ObjectStore.getIndexedObjectIds(store, List(['genre']), List(['scifi']))
expectIs scifiBookIds, Set(['b1', 'b4'])
store = ObjectStore.removeObject(store, b1)
scifiBookIds = ObjectStore.getIndexedObjectIds(store, List(['genre']), List(['scifi']))
expectIs scifiBookIds, Set(['b4'])
store = ObjectStore.removeObject(store, b4)
scifiBookIds = ObjectStore.getIndexedObjectIds(store, List(['genre']), List(['scifi']))
expectIs scifiBookIds, Set()
expectIs store.getIn(['indexedData',List(['genre'])]).keySeq().toSet(), Set(['selfhelp','fantasy'])
it "removes objects from their multi-key indices", ->
store = ObjectStore.addIndex(store, List(['cat','genre']))
# console.log store.get('indexedData')
store = ObjectStore.addObjects(store, books)
# console.log store.get('indexedData')
b1 = books.get(0)
b2 = books.get(1)
b3 = books.get(2)
b4 = books.get(3)
#
selfHelpIds = ObjectStore.getIndexedObjectIds(store, List(['cat','genre']), List(['nonfiction','selfhelp']))
expectIs selfHelpIds, Set(['b2'])
store = ObjectStore.removeObject(store, b2)
# See the id is gone from the cache:
selfHelpIds = ObjectStore.getIndexedObjectIds(store, List(['cat','genre']), List(['nonfiction','selfhelp']))
expectIs selfHelpIds, Set()
# See the nonfiction index path was cleaned out:
expectIs store.getIn(['indexedData',List(['cat','genre'])]).keySeq().toSet(), Set(['fiction'])
# console.log store.get('indexedData')
store = ObjectStore.removeObject(store, b1)
# console.log store.get('indexedData')
store = ObjectStore.removeObject(store, b4)
# console.log store.get('indexedData')
store = ObjectStore.removeObject(store, b3)
# console.log store.get('indexedData')
expectIs store.getIn(['indexedData',List(['cat','genre'])]).keySeq().toSet(), Set()
describe "hasIndex()", ->
it 'tells you if an index is present or not', ->
index1 = imm(['genre'])
index2 = imm(['cat','genre'])
expect(ObjectStore.hasIndex(store, index1)).to.equal(false)
store = ObjectStore.addIndex(store, index1)
expect(ObjectStore.hasIndex(store, index1)).to.equal(true)
expect(ObjectStore.hasIndex(store, index2)).to.equal(false)
store = ObjectStore.addIndex(store, index2)
expect(ObjectStore.hasIndex(store, index2)).to.equal(true)
expect(ObjectStore.hasIndex(store, index1)).to.equal(true)
expect(ObjectStore.hasIndex(store, [])).to.equal(false)
expect(ObjectStore.hasIndex(store, null)).to.equal(false)
describe "addIndices() and getIndices()", ->
it "returns a sequence of index definers", ->
index1 = imm(['genre'])
index2 = imm(['cat','genre'])
store = ObjectStore.addIndices(store, imm([
['genre']
['cat','genre']
]))
indices = ObjectStore.getIndices(store)
expectIs indices.toList(), imm([ ['genre'], ['cat','genre'] ])
it "returns empty List when no indexes are present", ->
indices = ObjectStore.getIndices(store)
expectIs indices.toList(), imm([])
describe "create with indices", ->
it "adds all indices on creation", ->
index1 = imm(['genre'])
index2 = imm(['cat','genre'])
store = ObjectStore.create('bookId', List([index1,index2]))
# store = ObjectStore.addIndices(store, imm([index1,index2]))
indices = ObjectStore.getIndices(store)
expectIs indices.toList(), imm([ ['genre'], ['cat','genre'] ])
it "returns empty List when no indexes are present", ->
indices = ObjectStore.getIndices(store)
expectIs indices.toList(), imm([])
describe "selectMatchingIndex()", ->
it "given a set of keys, decide which index (keyset) is the best (biggest) match", ->
catIndex = imm(['cat'])
catGenreIndex = imm(['cat','genre'])
indices = List([catIndex, catGenreIndex])
keys = Set(['genre','cat','dude'])
index = ObjectStore.selectMatchingIndex(indices, keys)
expectIs index, catGenreIndex
keys2 = keys.delete('genre')
index2 = ObjectStore.selectMatchingIndex(indices,keys2)
expectIs index2, catIndex
keys3 = keys2.delete('cat')
index3 = ObjectStore.selectMatchingIndex(indices,keys3)
expect(index3).to.be.null
describe "bestIndexForKeys()", ->
catIndex = imm(['cat'])
catGenreIndex = imm(['cat','genre'])
beforeEach ->
store = ObjectStore.addIndex(store, imm(['other']))
store = ObjectStore.addIndex(store, catIndex)
store = ObjectStore.addIndex(store, catGenreIndex)
it "finds which indices in a store may be used for the given match configuration", ->
match = imm
genre: 'scifi'
cat: 'fiction'
dude: "dave"
keys = match.keySeq().toSet()
index = ObjectStore.bestIndexForKeys(store,keys)
expectIs index, catGenreIndex
keys2 = match.delete('genre').keySeq().toSet()
index2 = ObjectStore.bestIndexForKeys(store,keys2)
expectIs index2, catIndex
keys3 = match.delete('genre').delete('cat').keySeq().toSet()
index3 = ObjectStore.bestIndexForKeys(store,keys3)
expect(index3).to.be.null
# describe "ObjectStore.Wrapper", ->
# wrapper = null
# beforeEach ->
# wrapper = ObjectStore.createWrapper('bookId')
#
# it "can store and retrieve objects according to the dataKey", ->
# wrapper.add(books.get(0))
# expectIs wrapper.get('b1'), books.get(0)
#
# it "can add multiple objects and index them and retrieve by indexed search", ->
# wrapper.addIndex(imm(['genre']))
# wrapper.addAll(books)
# scifiBookIds = wrapper.getIndexedObjectIds(imm(['genre']), imm(['scifi']))
# expectIs scifiBookIds, immset('b1', 'b4')
#
# scifiBooks = wrapper.getIndexedObjects(imm(['genre']), imm(['scifi']))
# expectIs scifiBooks, immset(book1, book4)
#
# wrapper.addIndex(imm(['cat','genre']))
# helps = wrapper.getIndexedObjectIds(imm(['cat','genre']), imm(['nonfiction','selfhelp']))
# expectIs helps, immset('b2')
#
# store = wrapper.add(imm { bookId: 'b05', cat: 'nonfiction', genre: 'selfhelp', title: '7 Habits of Highly Effective People' })
# helps = wrapper.getIndexedObjectIds(imm(['cat','genre']), imm(['nonfiction','selfhelp']))
# expectIs helps, immset('b2','b05')
#
# expectIs wrapper.getIndices(), imm([['genre'],['cat','genre']])
#
# it "can indicate presence of an index", ->
# expect(wrapper.hasIndex(imm(['genre']))).to.equal(false)
# wrapper.addIndex(imm(['genre']))
# expect(wrapper.hasIndex(imm(['genre']))).to.equal(true)
# [
# {
# as: 'bullet'
# match:
# type: 'bullet'
# }
# {
# as: 'hit_box'
# match:
# type: 'hit_box'
# eid: ['bullet','eid']
# }
# {
# as: 'animation'
# match:
# type: 'animation'
# eid: {matching: ['bullet','eid']}
# }
# ]
| 36595 | # Finder = require '../../src/javascript/search/immutable_object_finder'
Immutable = require 'immutable'
{Map,Set,List} = Immutable
ExpectHelpers = require '../helpers/expect_helpers'
expectIs = ExpectHelpers.expectIs
ObjectStore = require '../../src/javascript/search/object_store'
util = require 'util'
chai = require('chai')
expect = chai.expect
assert = chai.assert
imm = Immutable.fromJS
immset = (xs...) -> Set(xs)
padThai = imm dishId: 'i1', dish: 'Pad Thai', base: 'noodles'
houseSpecial = imm dishId: 'i2', dish: 'Curry fried rice', base: 'rice'
curryPadThai = imm dishId: 'i3', dish: 'Basil Cury', base: 'rice'
pcn = imm dishId: 'i4', dish: 'Peanut Curry Noodle', base: 'noodles'
dishList = imm [ padThai, houseSpecial, curryPadThai, pcn ]
books = imm [
{ bookId: 'b1', cat: 'fiction', genre: 'scifi', title: 'Foundation' }
{ bookId: 'b2', cat: 'nonfiction', genre: 'selfhelp', title: 'Crucial Conversations' }
{ bookId: 'b3', cat: 'fiction', genre: 'fantasy', title: 'The Wheel of Time' }
{ bookId: 'b4', cat: 'fiction', genre: 'scifi', title: 'Time Enough for Love' }
]
mappedBooks = ObjectStore.mappedBy(books,'bookId')
book1 = mappedBooks.get('b1')
book4 = mappedBooks.get('b4')
describe "ObjectStore", ->
describe "data transformation fns", ->
describe "mappedBy", ->
it "converts a list of objects into a map, keyed by the indicated key", ->
m = ObjectStore.mappedBy(dishList, 'dishId')
expectIs m, imm(
i1: padThai
i2: houseSpecial
i3: curryPadThai
i4: pcn
)
it "returns empty map for empty list", ->
m = ObjectStore.mappedBy(imm([]), 'wat')
expectIs m, imm({})
describe "indexObjects", ->
it "given objects and a prop names, group the objects' identKeys by the given prop name", ->
idx = ObjectStore.indexObjects(dishList.values(), List(['base']), 'dishId')
expectIs idx, imm(
rice: immset('i2','i3')
noodles: immset('i1','i4')
)
it "given objects and a list of n prop names, return an n-ary keyed map of key-paths to their identifier keys", ->
idx = ObjectStore.indexObjects(books.values(), List(['cat','genre']), 'bookId')
expectIs idx, imm(
fiction:
scifi: immset('b1','b4')
fantasy: immset('b3')
nonfiction:
selfhelp: immset('b2')
)
describe "store manipulation fns", ->
store = null
beforeEach ->
store = ObjectStore.create('bookId')
describe "addObject() and getObject()", ->
it "can store and retrieve objects according to the dataKey", ->
store = ObjectStore.addObject(store, books.get(0))
expectIs ObjectStore.getObject(store, 'b1'), books.get(0)
it "returns null when requested object isn't there", ->
expect(ObjectStore.getObject(store, 'NOOO')).to.be.null
expect(ObjectStore.getObject(store, '')).to.be.null
expect(ObjectStore.getObject(store, null)).to.be.null
describe "addIndex(), getIndexedObjectIds() and getIndexedObjects()", ->
it "can add multiple objects and index them and retrieve by indexed search", ->
store = ObjectStore.addIndex(store, imm(['genre']))
store = ObjectStore.addObjects(store, books)
scifiBookIds = ObjectStore.getIndexedObjectIds(store, imm(['genre']), imm(['scifi']))
expectIs scifiBookIds, immset('b1', 'b4')
store = ObjectStore.addIndex(store, imm(['cat','genre']))
helps = ObjectStore.getIndexedObjectIds(store, imm(['cat','genre']), imm(['nonfiction','selfhelp']))
expectIs helps, immset('b2')
store = ObjectStore.addObject(store, imm { bookId: 'b05', cat: 'nonfiction', genre: 'selfhelp', title: '7 Habits of Highly Effective People' })
helps = ObjectStore.getIndexedObjectIds(store, imm(['cat','genre']), imm(['nonfiction','selfhelp']))
expectIs helps, immset('b2','b05')
it "can retrieve actual objects", ->
store = ObjectStore.addIndex(store, imm(['genre']))
store = ObjectStore.addObjects(store, books)
scifiBooks = ObjectStore.getIndexedObjects(store, imm(['genre']), imm(['scifi']))
expectIs scifiBooks, immset(book1, book4)
it "returns empty Set when requested index isn't there", ->
res = ObjectStore.getIndexedObjectIds(store, imm(['something','wicked']), imm(['this way','comes']))
expectIs res, immset()
res = ObjectStore.getIndexedObjectIds(store, imm([]), imm(['this way','comes']))
expectIs res, immset()
res = ObjectStore.getIndexedObjectIds(store, null, imm(['this way','comes']))
expectIs res, immset()
res = ObjectStore.getIndexedObjects(store, null, imm(['this way','comes']))
expectIs res, immset()
describe "removeObject()", ->
it "removes objects from the store", ->
# store = ObjectStore.addIndex(store, imm(['genre']))
store = ObjectStore.addObjects(store, books)
b1 = books.get(0)
b2 = books.get(1)
expectIs ObjectStore.getObject(store, 'b1'), b1
expectIs ObjectStore.getObject(store, 'b2'), b2
store = ObjectStore.removeObject(store, b1)
expect(ObjectStore.getObject(store, 'b1')).to.be.null
# b2 should still be there:
expectIs ObjectStore.getObject(store, 'b2'), b2
store = ObjectStore.removeObject(store, b2)
expect(ObjectStore.getObject(store, 'b2')).to.be.null
it "removes objects from their indices", ->
store = ObjectStore.addIndex(store, List(['genre']))
store = ObjectStore.addObjects(store, books)
b1 = books.get(0)
b4 = books.get(3)
scifiBookIds = ObjectStore.getIndexedObjectIds(store, List(['genre']), List(['scifi']))
expectIs scifiBookIds, Set(['b1', 'b4'])
store = ObjectStore.removeObject(store, b1)
scifiBookIds = ObjectStore.getIndexedObjectIds(store, List(['genre']), List(['scifi']))
expectIs scifiBookIds, Set(['b4'])
store = ObjectStore.removeObject(store, b4)
scifiBookIds = ObjectStore.getIndexedObjectIds(store, List(['genre']), List(['scifi']))
expectIs scifiBookIds, Set()
expectIs store.getIn(['indexedData',List(['genre'])]).keySeq().toSet(), Set(['selfhelp','fantasy'])
it "removes objects from their multi-key indices", ->
store = ObjectStore.addIndex(store, List(['cat','genre']))
# console.log store.get('indexedData')
store = ObjectStore.addObjects(store, books)
# console.log store.get('indexedData')
b1 = books.get(0)
b2 = books.get(1)
b3 = books.get(2)
b4 = books.get(3)
#
selfHelpIds = ObjectStore.getIndexedObjectIds(store, List(['cat','genre']), List(['nonfiction','selfhelp']))
expectIs selfHelpIds, Set(['b2'])
store = ObjectStore.removeObject(store, b2)
# See the id is gone from the cache:
selfHelpIds = ObjectStore.getIndexedObjectIds(store, List(['cat','genre']), List(['nonfiction','selfhelp']))
expectIs selfHelpIds, Set()
# See the nonfiction index path was cleaned out:
expectIs store.getIn(['indexedData',List(['cat','genre'])]).keySeq().toSet(), Set(['fiction'])
# console.log store.get('indexedData')
store = ObjectStore.removeObject(store, b1)
# console.log store.get('indexedData')
store = ObjectStore.removeObject(store, b4)
# console.log store.get('indexedData')
store = ObjectStore.removeObject(store, b3)
# console.log store.get('indexedData')
expectIs store.getIn(['indexedData',List(['cat','genre'])]).keySeq().toSet(), Set()
describe "hasIndex()", ->
it 'tells you if an index is present or not', ->
index1 = imm(['genre'])
index2 = imm(['cat','genre'])
expect(ObjectStore.hasIndex(store, index1)).to.equal(false)
store = ObjectStore.addIndex(store, index1)
expect(ObjectStore.hasIndex(store, index1)).to.equal(true)
expect(ObjectStore.hasIndex(store, index2)).to.equal(false)
store = ObjectStore.addIndex(store, index2)
expect(ObjectStore.hasIndex(store, index2)).to.equal(true)
expect(ObjectStore.hasIndex(store, index1)).to.equal(true)
expect(ObjectStore.hasIndex(store, [])).to.equal(false)
expect(ObjectStore.hasIndex(store, null)).to.equal(false)
describe "addIndices() and getIndices()", ->
it "returns a sequence of index definers", ->
index1 = imm(['genre'])
index2 = imm(['cat','genre'])
store = ObjectStore.addIndices(store, imm([
['genre']
['cat','genre']
]))
indices = ObjectStore.getIndices(store)
expectIs indices.toList(), imm([ ['genre'], ['cat','genre'] ])
it "returns empty List when no indexes are present", ->
indices = ObjectStore.getIndices(store)
expectIs indices.toList(), imm([])
describe "create with indices", ->
it "adds all indices on creation", ->
index1 = imm(['genre'])
index2 = imm(['cat','genre'])
store = ObjectStore.create('bookId', List([index1,index2]))
# store = ObjectStore.addIndices(store, imm([index1,index2]))
indices = ObjectStore.getIndices(store)
expectIs indices.toList(), imm([ ['genre'], ['cat','genre'] ])
it "returns empty List when no indexes are present", ->
indices = ObjectStore.getIndices(store)
expectIs indices.toList(), imm([])
describe "selectMatchingIndex()", ->
it "given a set of keys, decide which index (keyset) is the best (biggest) match", ->
catIndex = imm(['cat'])
catGenreIndex = imm(['cat','genre'])
indices = List([catIndex, catGenreIndex])
keys = Set(['<KEY>','<KEY>','<KEY>'])
index = ObjectStore.selectMatchingIndex(indices, keys)
expectIs index, catGenreIndex
keys2 = keys.delete('genre')
index2 = ObjectStore.selectMatchingIndex(indices,keys2)
expectIs index2, catIndex
keys3 = keys2.delete('cat')
index3 = ObjectStore.selectMatchingIndex(indices,keys3)
expect(index3).to.be.null
describe "bestIndexForKeys()", ->
catIndex = imm(['cat'])
catGenreIndex = imm(['cat','genre'])
beforeEach ->
store = ObjectStore.addIndex(store, imm(['other']))
store = ObjectStore.addIndex(store, catIndex)
store = ObjectStore.addIndex(store, catGenreIndex)
it "finds which indices in a store may be used for the given match configuration", ->
match = imm
genre: 'scifi'
cat: 'fiction'
dude: "<NAME>"
keys = match.key<KEY>()
index = ObjectStore.bestIndexForKeys(store,keys)
expectIs index, catGenreIndex
keys2 = match.delete('genre').<KEY>()
index2 = ObjectStore.bestIndexForKeys(store,keys2)
expectIs index2, catIndex
keys3 = match.delete('genre').delete('cat').<KEY>()
index3 = ObjectStore.bestIndexForKeys(store,keys3)
expect(index3).to.be.null
# describe "ObjectStore.Wrapper", ->
# wrapper = null
# beforeEach ->
# wrapper = ObjectStore.createWrapper('bookId')
#
# it "can store and retrieve objects according to the dataKey", ->
# wrapper.add(books.get(0))
# expectIs wrapper.get('b1'), books.get(0)
#
# it "can add multiple objects and index them and retrieve by indexed search", ->
# wrapper.addIndex(imm(['genre']))
# wrapper.addAll(books)
# scifiBookIds = wrapper.getIndexedObjectIds(imm(['genre']), imm(['scifi']))
# expectIs scifiBookIds, immset('b1', 'b4')
#
# scifiBooks = wrapper.getIndexedObjects(imm(['genre']), imm(['scifi']))
# expectIs scifiBooks, immset(book1, book4)
#
# wrapper.addIndex(imm(['cat','genre']))
# helps = wrapper.getIndexedObjectIds(imm(['cat','genre']), imm(['nonfiction','selfhelp']))
# expectIs helps, immset('b2')
#
# store = wrapper.add(imm { bookId: 'b05', cat: 'nonfiction', genre: 'selfhelp', title: '7 Habits of Highly Effective People' })
# helps = wrapper.getIndexedObjectIds(imm(['cat','genre']), imm(['nonfiction','selfhelp']))
# expectIs helps, immset('b2','b05')
#
# expectIs wrapper.getIndices(), imm([['genre'],['cat','genre']])
#
# it "can indicate presence of an index", ->
# expect(wrapper.hasIndex(imm(['genre']))).to.equal(false)
# wrapper.addIndex(imm(['genre']))
# expect(wrapper.hasIndex(imm(['genre']))).to.equal(true)
# [
# {
# as: 'bullet'
# match:
# type: 'bullet'
# }
# {
# as: 'hit_box'
# match:
# type: 'hit_box'
# eid: ['bullet','eid']
# }
# {
# as: 'animation'
# match:
# type: 'animation'
# eid: {matching: ['bullet','eid']}
# }
# ]
| true | # Finder = require '../../src/javascript/search/immutable_object_finder'
Immutable = require 'immutable'
{Map,Set,List} = Immutable
ExpectHelpers = require '../helpers/expect_helpers'
expectIs = ExpectHelpers.expectIs
ObjectStore = require '../../src/javascript/search/object_store'
util = require 'util'
chai = require('chai')
expect = chai.expect
assert = chai.assert
imm = Immutable.fromJS
immset = (xs...) -> Set(xs)
padThai = imm dishId: 'i1', dish: 'Pad Thai', base: 'noodles'
houseSpecial = imm dishId: 'i2', dish: 'Curry fried rice', base: 'rice'
curryPadThai = imm dishId: 'i3', dish: 'Basil Cury', base: 'rice'
pcn = imm dishId: 'i4', dish: 'Peanut Curry Noodle', base: 'noodles'
dishList = imm [ padThai, houseSpecial, curryPadThai, pcn ]
books = imm [
{ bookId: 'b1', cat: 'fiction', genre: 'scifi', title: 'Foundation' }
{ bookId: 'b2', cat: 'nonfiction', genre: 'selfhelp', title: 'Crucial Conversations' }
{ bookId: 'b3', cat: 'fiction', genre: 'fantasy', title: 'The Wheel of Time' }
{ bookId: 'b4', cat: 'fiction', genre: 'scifi', title: 'Time Enough for Love' }
]
mappedBooks = ObjectStore.mappedBy(books,'bookId')
book1 = mappedBooks.get('b1')
book4 = mappedBooks.get('b4')
describe "ObjectStore", ->
describe "data transformation fns", ->
describe "mappedBy", ->
it "converts a list of objects into a map, keyed by the indicated key", ->
m = ObjectStore.mappedBy(dishList, 'dishId')
expectIs m, imm(
i1: padThai
i2: houseSpecial
i3: curryPadThai
i4: pcn
)
it "returns empty map for empty list", ->
m = ObjectStore.mappedBy(imm([]), 'wat')
expectIs m, imm({})
describe "indexObjects", ->
it "given objects and a prop names, group the objects' identKeys by the given prop name", ->
idx = ObjectStore.indexObjects(dishList.values(), List(['base']), 'dishId')
expectIs idx, imm(
rice: immset('i2','i3')
noodles: immset('i1','i4')
)
it "given objects and a list of n prop names, return an n-ary keyed map of key-paths to their identifier keys", ->
idx = ObjectStore.indexObjects(books.values(), List(['cat','genre']), 'bookId')
expectIs idx, imm(
fiction:
scifi: immset('b1','b4')
fantasy: immset('b3')
nonfiction:
selfhelp: immset('b2')
)
describe "store manipulation fns", ->
store = null
beforeEach ->
store = ObjectStore.create('bookId')
describe "addObject() and getObject()", ->
it "can store and retrieve objects according to the dataKey", ->
store = ObjectStore.addObject(store, books.get(0))
expectIs ObjectStore.getObject(store, 'b1'), books.get(0)
it "returns null when requested object isn't there", ->
expect(ObjectStore.getObject(store, 'NOOO')).to.be.null
expect(ObjectStore.getObject(store, '')).to.be.null
expect(ObjectStore.getObject(store, null)).to.be.null
describe "addIndex(), getIndexedObjectIds() and getIndexedObjects()", ->
it "can add multiple objects and index them and retrieve by indexed search", ->
store = ObjectStore.addIndex(store, imm(['genre']))
store = ObjectStore.addObjects(store, books)
scifiBookIds = ObjectStore.getIndexedObjectIds(store, imm(['genre']), imm(['scifi']))
expectIs scifiBookIds, immset('b1', 'b4')
store = ObjectStore.addIndex(store, imm(['cat','genre']))
helps = ObjectStore.getIndexedObjectIds(store, imm(['cat','genre']), imm(['nonfiction','selfhelp']))
expectIs helps, immset('b2')
store = ObjectStore.addObject(store, imm { bookId: 'b05', cat: 'nonfiction', genre: 'selfhelp', title: '7 Habits of Highly Effective People' })
helps = ObjectStore.getIndexedObjectIds(store, imm(['cat','genre']), imm(['nonfiction','selfhelp']))
expectIs helps, immset('b2','b05')
it "can retrieve actual objects", ->
store = ObjectStore.addIndex(store, imm(['genre']))
store = ObjectStore.addObjects(store, books)
scifiBooks = ObjectStore.getIndexedObjects(store, imm(['genre']), imm(['scifi']))
expectIs scifiBooks, immset(book1, book4)
it "returns empty Set when requested index isn't there", ->
res = ObjectStore.getIndexedObjectIds(store, imm(['something','wicked']), imm(['this way','comes']))
expectIs res, immset()
res = ObjectStore.getIndexedObjectIds(store, imm([]), imm(['this way','comes']))
expectIs res, immset()
res = ObjectStore.getIndexedObjectIds(store, null, imm(['this way','comes']))
expectIs res, immset()
res = ObjectStore.getIndexedObjects(store, null, imm(['this way','comes']))
expectIs res, immset()
describe "removeObject()", ->
it "removes objects from the store", ->
# store = ObjectStore.addIndex(store, imm(['genre']))
store = ObjectStore.addObjects(store, books)
b1 = books.get(0)
b2 = books.get(1)
expectIs ObjectStore.getObject(store, 'b1'), b1
expectIs ObjectStore.getObject(store, 'b2'), b2
store = ObjectStore.removeObject(store, b1)
expect(ObjectStore.getObject(store, 'b1')).to.be.null
# b2 should still be there:
expectIs ObjectStore.getObject(store, 'b2'), b2
store = ObjectStore.removeObject(store, b2)
expect(ObjectStore.getObject(store, 'b2')).to.be.null
it "removes objects from their indices", ->
store = ObjectStore.addIndex(store, List(['genre']))
store = ObjectStore.addObjects(store, books)
b1 = books.get(0)
b4 = books.get(3)
scifiBookIds = ObjectStore.getIndexedObjectIds(store, List(['genre']), List(['scifi']))
expectIs scifiBookIds, Set(['b1', 'b4'])
store = ObjectStore.removeObject(store, b1)
scifiBookIds = ObjectStore.getIndexedObjectIds(store, List(['genre']), List(['scifi']))
expectIs scifiBookIds, Set(['b4'])
store = ObjectStore.removeObject(store, b4)
scifiBookIds = ObjectStore.getIndexedObjectIds(store, List(['genre']), List(['scifi']))
expectIs scifiBookIds, Set()
expectIs store.getIn(['indexedData',List(['genre'])]).keySeq().toSet(), Set(['selfhelp','fantasy'])
it "removes objects from their multi-key indices", ->
store = ObjectStore.addIndex(store, List(['cat','genre']))
# console.log store.get('indexedData')
store = ObjectStore.addObjects(store, books)
# console.log store.get('indexedData')
b1 = books.get(0)
b2 = books.get(1)
b3 = books.get(2)
b4 = books.get(3)
#
selfHelpIds = ObjectStore.getIndexedObjectIds(store, List(['cat','genre']), List(['nonfiction','selfhelp']))
expectIs selfHelpIds, Set(['b2'])
store = ObjectStore.removeObject(store, b2)
# See the id is gone from the cache:
selfHelpIds = ObjectStore.getIndexedObjectIds(store, List(['cat','genre']), List(['nonfiction','selfhelp']))
expectIs selfHelpIds, Set()
# See the nonfiction index path was cleaned out:
expectIs store.getIn(['indexedData',List(['cat','genre'])]).keySeq().toSet(), Set(['fiction'])
# console.log store.get('indexedData')
store = ObjectStore.removeObject(store, b1)
# console.log store.get('indexedData')
store = ObjectStore.removeObject(store, b4)
# console.log store.get('indexedData')
store = ObjectStore.removeObject(store, b3)
# console.log store.get('indexedData')
expectIs store.getIn(['indexedData',List(['cat','genre'])]).keySeq().toSet(), Set()
describe "hasIndex()", ->
it 'tells you if an index is present or not', ->
index1 = imm(['genre'])
index2 = imm(['cat','genre'])
expect(ObjectStore.hasIndex(store, index1)).to.equal(false)
store = ObjectStore.addIndex(store, index1)
expect(ObjectStore.hasIndex(store, index1)).to.equal(true)
expect(ObjectStore.hasIndex(store, index2)).to.equal(false)
store = ObjectStore.addIndex(store, index2)
expect(ObjectStore.hasIndex(store, index2)).to.equal(true)
expect(ObjectStore.hasIndex(store, index1)).to.equal(true)
expect(ObjectStore.hasIndex(store, [])).to.equal(false)
expect(ObjectStore.hasIndex(store, null)).to.equal(false)
describe "addIndices() and getIndices()", ->
it "returns a sequence of index definers", ->
index1 = imm(['genre'])
index2 = imm(['cat','genre'])
store = ObjectStore.addIndices(store, imm([
['genre']
['cat','genre']
]))
indices = ObjectStore.getIndices(store)
expectIs indices.toList(), imm([ ['genre'], ['cat','genre'] ])
it "returns empty List when no indexes are present", ->
indices = ObjectStore.getIndices(store)
expectIs indices.toList(), imm([])
describe "create with indices", ->
it "adds all indices on creation", ->
index1 = imm(['genre'])
index2 = imm(['cat','genre'])
store = ObjectStore.create('bookId', List([index1,index2]))
# store = ObjectStore.addIndices(store, imm([index1,index2]))
indices = ObjectStore.getIndices(store)
expectIs indices.toList(), imm([ ['genre'], ['cat','genre'] ])
it "returns empty List when no indexes are present", ->
indices = ObjectStore.getIndices(store)
expectIs indices.toList(), imm([])
describe "selectMatchingIndex()", ->
it "given a set of keys, decide which index (keyset) is the best (biggest) match", ->
catIndex = imm(['cat'])
catGenreIndex = imm(['cat','genre'])
indices = List([catIndex, catGenreIndex])
keys = Set(['PI:KEY:<KEY>END_PI','PI:KEY:<KEY>END_PI','PI:KEY:<KEY>END_PI'])
index = ObjectStore.selectMatchingIndex(indices, keys)
expectIs index, catGenreIndex
keys2 = keys.delete('genre')
index2 = ObjectStore.selectMatchingIndex(indices,keys2)
expectIs index2, catIndex
keys3 = keys2.delete('cat')
index3 = ObjectStore.selectMatchingIndex(indices,keys3)
expect(index3).to.be.null
describe "bestIndexForKeys()", ->
catIndex = imm(['cat'])
catGenreIndex = imm(['cat','genre'])
beforeEach ->
store = ObjectStore.addIndex(store, imm(['other']))
store = ObjectStore.addIndex(store, catIndex)
store = ObjectStore.addIndex(store, catGenreIndex)
it "finds which indices in a store may be used for the given match configuration", ->
match = imm
genre: 'scifi'
cat: 'fiction'
dude: "PI:NAME:<NAME>END_PI"
keys = match.keyPI:KEY:<KEY>END_PI()
index = ObjectStore.bestIndexForKeys(store,keys)
expectIs index, catGenreIndex
keys2 = match.delete('genre').PI:KEY:<KEY>END_PI()
index2 = ObjectStore.bestIndexForKeys(store,keys2)
expectIs index2, catIndex
keys3 = match.delete('genre').delete('cat').PI:KEY:<KEY>END_PI()
index3 = ObjectStore.bestIndexForKeys(store,keys3)
expect(index3).to.be.null
# describe "ObjectStore.Wrapper", ->
# wrapper = null
# beforeEach ->
# wrapper = ObjectStore.createWrapper('bookId')
#
# it "can store and retrieve objects according to the dataKey", ->
# wrapper.add(books.get(0))
# expectIs wrapper.get('b1'), books.get(0)
#
# it "can add multiple objects and index them and retrieve by indexed search", ->
# wrapper.addIndex(imm(['genre']))
# wrapper.addAll(books)
# scifiBookIds = wrapper.getIndexedObjectIds(imm(['genre']), imm(['scifi']))
# expectIs scifiBookIds, immset('b1', 'b4')
#
# scifiBooks = wrapper.getIndexedObjects(imm(['genre']), imm(['scifi']))
# expectIs scifiBooks, immset(book1, book4)
#
# wrapper.addIndex(imm(['cat','genre']))
# helps = wrapper.getIndexedObjectIds(imm(['cat','genre']), imm(['nonfiction','selfhelp']))
# expectIs helps, immset('b2')
#
# store = wrapper.add(imm { bookId: 'b05', cat: 'nonfiction', genre: 'selfhelp', title: '7 Habits of Highly Effective People' })
# helps = wrapper.getIndexedObjectIds(imm(['cat','genre']), imm(['nonfiction','selfhelp']))
# expectIs helps, immset('b2','b05')
#
# expectIs wrapper.getIndices(), imm([['genre'],['cat','genre']])
#
# it "can indicate presence of an index", ->
# expect(wrapper.hasIndex(imm(['genre']))).to.equal(false)
# wrapper.addIndex(imm(['genre']))
# expect(wrapper.hasIndex(imm(['genre']))).to.equal(true)
# [
# {
# as: 'bullet'
# match:
# type: 'bullet'
# }
# {
# as: 'hit_box'
# match:
# type: 'hit_box'
# eid: ['bullet','eid']
# }
# {
# as: 'animation'
# match:
# type: 'animation'
# eid: {matching: ['bullet','eid']}
# }
# ]
|
[
{
"context": "e 2\"\n description: \"View Issue 2\"\n}, {\n text: \"Lol wut\"\n icon: \"😂\"\n group: \"Issue 2\"\n description: \"D",
"end": 636,
"score": 0.6799201965332031,
"start": 630,
"tag": "NAME",
"value": "ol wut"
},
{
"context": "10\"\n description: \"Culvert Livin'\"... | system/achievement.coffee | STRd6/zine | 12 | Achievement = require "../lib/achievement"
{Observable} = UI = require "ui"
{emptyElement} = require "../util"
# TODO: Track unlocks, save/restore achievements
# TODO: Only display once
# TODO: View achievement progress grouped by area
achievementData = [{
text: "Issue 1"
icon: "📰"
group: "Issue 1"
description: "View Issue 1"
}, {
text: "Cover-2-cover"
icon: "📗"
group: "Issue 1"
description: "Read the entire issue"
}, {
text: "No rush"
icon: "⏳"
group: "Issue 1"
description: "Patience is a virtue"
}, {
text: "Issue 2"
icon: "📰"
group: "Issue 2"
description: "View Issue 2"
}, {
text: "Lol wut"
icon: "😂"
group: "Issue 2"
description: "Did you know Windows Vista had a magazine?"
}, {
text: "Cover-2-cover 2: 2 cover 2 furious"
icon: "📗"
group: "Issue 2"
description: "Read the entire issue"
}, {
text: "Feeling the frog"
icon: "🐸"
group: "Issue 2"
description: "Visit frogfeels.com"
}, {
text: "The dungeon is in our heart"
icon: "😭"
group: "Issue 2"
description: "Played dungeon of sadness"
}, {
text: "Issue 3"
icon: "📰"
group: "Issue 3"
description: "View Issue 3"
}, {
text: "Cover-2-cover 3: Tokyo Drift"
icon: "📗"
group: "Issue 3"
description: "Read the entire issue"
}, {
text: "Blue light special"
icon: "🈹"
group: "Issue 3"
description: "Read 'Blue Light Special'"
}, {
text: "Issue 4"
icon: "📰"
group: "Issue 4"
description: "View Issue 4"
}, {
text: "Cover-2-cover 4: Fast & Furious"
icon: "📗"
group: "Issue 4"
description: "Read the entire issue"
}, {
text: "Izzy"
icon: "🈹"
group: "Issue 4"
description: "Read 'Izzy'"
}, {
text: "Residue"
icon: "🈹"
group: "Issue 4"
description: "Read 'Residue'"
}, {
text: "Issue 5"
icon: "📰"
group: "Issue 5"
description: "View Issue 5"
}, {
text: "Issue 6"
icon: "🐝"
group: "Issue 6"
description: "View Issue 6"
}, {
text: "Bee afraid"
icon: "🐝"
group: "Issue 6"
description: "Learn the truth about 'Bee Movie'"
}, {
text: "Tree story"
icon: "🐝"
group: "Issue 6"
description: "Read Tree"
}, {
text: "Issue 10"
icon: "🎃"
group: "Issue 10"
description: "Special Halloween Editon"
}, {
text: "Hard Rain"
icon: "☔"
group: "Issue 10"
description: "Culvert Livin'"
}, {
text: "3spoopy5me"
icon: "😨"
group: "Issue 10"
description: "Don't spoop your pants!"
}, {
text: "Not a real JT song"
icon: "👻"
group: "Issue 10"
description: "Maybe he hired a ghost writer"
}, {
text: "Issue 11"
icon: "💃"
group: "Issue 11"
description: "You can dab if you wanna"
}, {
text: "Late stage capitalism"
icon: "💰"
group: "Issue 11"
description: "What if this is only the beginning?"
}, {
text: "Value Investing"
icon: "📈"
group: "Issue 11"
description: "Value investing has proven to be a successful investment strategy."
}, {
text: "Getting Hairy"
icon: "👣"
group: "Issue 12"
description: "Individuals claim to have seen Bigfoot."
}, {
text: "Volume 2: Episode 1"
icon: "📰"
group: "V2E01"
description: "New year, same old you"
}, {
text: "As fortold in the Dead Sea Scrolls"
icon: "📜"
group: "V2E01"
description: "Beyond revelations"
}, {
text: "Inner or outer space?"
icon: "🐬"
group: "V2E01"
description: "Out of this world"
}, { # Apps
text: "Notepad.exe"
icon: "📝"
group: "App"
description: "Launch a text editor"
}, {
text: "Pump up the jam"
icon: "🎶"
group: "App"
description: "Launch audio application"
}, {
text: "Microsoft Access 97"
icon: "🔞"
group: "App"
description: "Launch a spreadsheet application"
}, {
text: "Look at that"
icon: "🖼️"
group: "App"
description: "Open the image viewer"
}, {
text: "Pixel perfect"
icon: "◼️️"
group: "App"
description: "Open the pixel editor"
}, {
text: "Check yo' self"
icon: "😉"
group: "App"
description: "Check your achievement status"
}, {
text: "Oh no, my files!"
icon: "💼"
group: "App"
description: "Opened 'My Briefcase'"
}, { # OS
text: "Save a file"
icon: "💾"
group: "OS"
description: "Write to the file system"
}, {
text: "Load a file"
icon: "💽"
group: "OS"
description: "Read from the file system"
}, {
text: "Execute code"
icon: "🖥️"
group: "OS"
description: "Some people like to live dangerously"
}, {
text: "Dismiss modal"
icon: "💃"
group: "OS"
description: "Dismiss a modal without even reading it"
}, {
text: "I AM ERROR"
icon: "🐛"
group: "OS"
description: "Encountered a JavaScript error"
}, {
text: "Shut Down"
icon: "🔌"
group: "OS"
description: "ZineOS cannot be stopped"
}, { # Social
text: "Do you 'like' like me?"
icon: "💕"
group: "Social"
description: "Have fine taste"
}, {
text: "A little bird told me"
icon: "🐦"
group: "Social"
description: "Social media marketing 101"
}, {
text: "We value your input"
icon: "📩"
group: "Social"
description: "View feedback form"
}, { # Chateau
text: "Enter the Chateau"
icon: "🏡"
group: "Chateau"
description: "Enter the Chateau"
}, {
text: "Puttin' on the Ritz"
icon: "🐭"
group: "Chateau"
description: "Upload custom avatar"
}, {
text: "Paint the town red"
icon: "🌆"
group: "Chateau"
description: "Upload a custom background"
}, {
text: "Poutine on the Ritz"
icon: "🍘"
group: "Chateau"
description: "Put poutine on a Ritz cracker"
}, {
text: "It's in the cloud"
icon: "☁️️"
group: "Chateau"
description: "Upload a file"
}, {
text: "Rawr"
icon: "🐉"
group: "Contrasaurus"
description: "Played Contrasaurus"
}]
restore = ->
storedCheevos = []
try
storedCheevos = JSON.parse localStorage.cheevos
storedAchieved = {}
storedCheevos.forEach ({achieved, text}) ->
storedAchieved[text] = achieved
achievementData.forEach (cheevo) ->
{text} = cheevo
if storedAchieved[text]
cheevo.achieved = true
persist = ->
localStorage.cheevos = JSON.stringify(achievementData)
AchievementProgressPresenter = require "../presenters/achievement-group-progress"
groupBy = (xs, key) ->
xs.reduce (rv, x) ->
(rv[x[key]] ?= []).push(x)
rv
, {}
module.exports = (I, self) ->
restore()
Object.assign self,
Achievement:
groupData: Observable {}
unlock: (name) ->
opts = achievementData.find ({text}) ->
text is name
if opts and !opts.achieved
opts.achieved = true
persist()
updateStatus()
Achievement.display opts
progressView: ->
content = document.createElement "content"
Observable ->
data = self.Achievement.groupData()
elements = Object.keys(data).map (group) ->
AchievementProgressPresenter
name: group
achievements: data[group]
emptyElement content
elements.forEach (element) ->
content.appendChild(element)
return content
updateStatus = ->
self.Achievement.groupData groupBy(achievementData, "group")
updateStatus()
return self
| 184226 | Achievement = require "../lib/achievement"
{Observable} = UI = require "ui"
{emptyElement} = require "../util"
# TODO: Track unlocks, save/restore achievements
# TODO: Only display once
# TODO: View achievement progress grouped by area
achievementData = [{
text: "Issue 1"
icon: "📰"
group: "Issue 1"
description: "View Issue 1"
}, {
text: "Cover-2-cover"
icon: "📗"
group: "Issue 1"
description: "Read the entire issue"
}, {
text: "No rush"
icon: "⏳"
group: "Issue 1"
description: "Patience is a virtue"
}, {
text: "Issue 2"
icon: "📰"
group: "Issue 2"
description: "View Issue 2"
}, {
text: "L<NAME>"
icon: "😂"
group: "Issue 2"
description: "Did you know Windows Vista had a magazine?"
}, {
text: "Cover-2-cover 2: 2 cover 2 furious"
icon: "📗"
group: "Issue 2"
description: "Read the entire issue"
}, {
text: "Feeling the frog"
icon: "🐸"
group: "Issue 2"
description: "Visit frogfeels.com"
}, {
text: "The dungeon is in our heart"
icon: "😭"
group: "Issue 2"
description: "Played dungeon of sadness"
}, {
text: "Issue 3"
icon: "📰"
group: "Issue 3"
description: "View Issue 3"
}, {
text: "Cover-2-cover 3: Tokyo Drift"
icon: "📗"
group: "Issue 3"
description: "Read the entire issue"
}, {
text: "Blue light special"
icon: "🈹"
group: "Issue 3"
description: "Read 'Blue Light Special'"
}, {
text: "Issue 4"
icon: "📰"
group: "Issue 4"
description: "View Issue 4"
}, {
text: "Cover-2-cover 4: Fast & Furious"
icon: "📗"
group: "Issue 4"
description: "Read the entire issue"
}, {
text: "Izzy"
icon: "🈹"
group: "Issue 4"
description: "Read 'Izzy'"
}, {
text: "Residue"
icon: "🈹"
group: "Issue 4"
description: "Read 'Residue'"
}, {
text: "Issue 5"
icon: "📰"
group: "Issue 5"
description: "View Issue 5"
}, {
text: "Issue 6"
icon: "🐝"
group: "Issue 6"
description: "View Issue 6"
}, {
text: "Bee afraid"
icon: "🐝"
group: "Issue 6"
description: "Learn the truth about 'Bee Movie'"
}, {
text: "Tree story"
icon: "🐝"
group: "Issue 6"
description: "Read Tree"
}, {
text: "Issue 10"
icon: "🎃"
group: "Issue 10"
description: "Special Halloween Editon"
}, {
text: "Hard Rain"
icon: "☔"
group: "Issue 10"
description: "Culvert Livin'"
}, {
text: "3spoopy5me"
icon: "😨"
group: "Issue 10"
description: "Don't spoop your pants!"
}, {
text: "Not a real JT song"
icon: "👻"
group: "Issue 10"
description: "Maybe he hired a ghost writer"
}, {
text: "Issue 11"
icon: "💃"
group: "Issue 11"
description: "You can dab if you wanna"
}, {
text: "Late stage capitalism"
icon: "💰"
group: "Issue 11"
description: "What if this is only the beginning?"
}, {
text: "Value Investing"
icon: "📈"
group: "Issue 11"
description: "Value investing has proven to be a successful investment strategy."
}, {
text: "Getting Hairy"
icon: "👣"
group: "Issue 12"
description: "Individuals claim to have seen Bigfoot."
}, {
text: "Volume 2: Episode 1"
icon: "📰"
group: "V2E01"
description: "New year, same old you"
}, {
text: "As fortold in the Dead Sea Scrolls"
icon: "📜"
group: "V2E01"
description: "Beyond revelations"
}, {
text: "Inner or outer space?"
icon: "🐬"
group: "V2E01"
description: "Out of this world"
}, { # Apps
text: "Notepad.exe"
icon: "📝"
group: "App"
description: "Launch a text editor"
}, {
text: "Pump up the jam"
icon: "🎶"
group: "App"
description: "Launch audio application"
}, {
text: "Microsoft Access 97"
icon: "🔞"
group: "App"
description: "Launch a spreadsheet application"
}, {
text: "Look at that"
icon: "🖼️"
group: "App"
description: "Open the image viewer"
}, {
text: "Pixel perfect"
icon: "◼️️"
group: "App"
description: "Open the pixel editor"
}, {
text: "Check yo' self"
icon: "😉"
group: "App"
description: "Check your achievement status"
}, {
text: "Oh no, my files!"
icon: "💼"
group: "App"
description: "Opened 'My Briefcase'"
}, { # OS
text: "Save a file"
icon: "💾"
group: "OS"
description: "Write to the file system"
}, {
text: "Load a file"
icon: "💽"
group: "OS"
description: "Read from the file system"
}, {
text: "Execute code"
icon: "🖥️"
group: "OS"
description: "Some people like to live dangerously"
}, {
text: "Dismiss modal"
icon: "💃"
group: "OS"
description: "Dismiss a modal without even reading it"
}, {
text: "I AM ERROR"
icon: "🐛"
group: "OS"
description: "Encountered a JavaScript error"
}, {
text: "Shut Down"
icon: "🔌"
group: "OS"
description: "ZineOS cannot be stopped"
}, { # Social
text: "Do you 'like' like me?"
icon: "💕"
group: "Social"
description: "Have fine taste"
}, {
text: "A little bird told me"
icon: "🐦"
group: "Social"
description: "Social media marketing 101"
}, {
text: "We value your input"
icon: "📩"
group: "Social"
description: "View feedback form"
}, { # Chateau
text: "Enter the Chateau"
icon: "🏡"
group: "Chateau"
description: "Enter the Chateau"
}, {
text: "Puttin' on the Ritz"
icon: "🐭"
group: "Chateau"
description: "Upload custom avatar"
}, {
text: "Paint the town red"
icon: "🌆"
group: "Chateau"
description: "Upload a custom background"
}, {
text: "Poutine on the Ritz"
icon: "🍘"
group: "Chateau"
description: "Put poutine on a Ritz cracker"
}, {
text: "It's in the cloud"
icon: "☁️️"
group: "Chateau"
description: "Upload a file"
}, {
text: "<NAME>r"
icon: "🐉"
group: "Contrasaurus"
description: "Played Contrasaurus"
}]
restore = ->
storedCheevos = []
try
storedCheevos = JSON.parse localStorage.cheevos
storedAchieved = {}
storedCheevos.forEach ({achieved, text}) ->
storedAchieved[text] = achieved
achievementData.forEach (cheevo) ->
{text} = cheevo
if storedAchieved[text]
cheevo.achieved = true
persist = ->
localStorage.cheevos = JSON.stringify(achievementData)
AchievementProgressPresenter = require "../presenters/achievement-group-progress"
groupBy = (xs, key) ->
xs.reduce (rv, x) ->
(rv[x[key]] ?= []).push(x)
rv
, {}
module.exports = (I, self) ->
restore()
Object.assign self,
Achievement:
groupData: Observable {}
unlock: (name) ->
opts = achievementData.find ({text}) ->
text is name
if opts and !opts.achieved
opts.achieved = true
persist()
updateStatus()
Achievement.display opts
progressView: ->
content = document.createElement "content"
Observable ->
data = self.Achievement.groupData()
elements = Object.keys(data).map (group) ->
AchievementProgressPresenter
name: group
achievements: data[group]
emptyElement content
elements.forEach (element) ->
content.appendChild(element)
return content
updateStatus = ->
self.Achievement.groupData groupBy(achievementData, "group")
updateStatus()
return self
| true | Achievement = require "../lib/achievement"
{Observable} = UI = require "ui"
{emptyElement} = require "../util"
# TODO: Track unlocks, save/restore achievements
# TODO: Only display once
# TODO: View achievement progress grouped by area
achievementData = [{
text: "Issue 1"
icon: "📰"
group: "Issue 1"
description: "View Issue 1"
}, {
text: "Cover-2-cover"
icon: "📗"
group: "Issue 1"
description: "Read the entire issue"
}, {
text: "No rush"
icon: "⏳"
group: "Issue 1"
description: "Patience is a virtue"
}, {
text: "Issue 2"
icon: "📰"
group: "Issue 2"
description: "View Issue 2"
}, {
text: "LPI:NAME:<NAME>END_PI"
icon: "😂"
group: "Issue 2"
description: "Did you know Windows Vista had a magazine?"
}, {
text: "Cover-2-cover 2: 2 cover 2 furious"
icon: "📗"
group: "Issue 2"
description: "Read the entire issue"
}, {
text: "Feeling the frog"
icon: "🐸"
group: "Issue 2"
description: "Visit frogfeels.com"
}, {
text: "The dungeon is in our heart"
icon: "😭"
group: "Issue 2"
description: "Played dungeon of sadness"
}, {
text: "Issue 3"
icon: "📰"
group: "Issue 3"
description: "View Issue 3"
}, {
text: "Cover-2-cover 3: Tokyo Drift"
icon: "📗"
group: "Issue 3"
description: "Read the entire issue"
}, {
text: "Blue light special"
icon: "🈹"
group: "Issue 3"
description: "Read 'Blue Light Special'"
}, {
text: "Issue 4"
icon: "📰"
group: "Issue 4"
description: "View Issue 4"
}, {
text: "Cover-2-cover 4: Fast & Furious"
icon: "📗"
group: "Issue 4"
description: "Read the entire issue"
}, {
text: "Izzy"
icon: "🈹"
group: "Issue 4"
description: "Read 'Izzy'"
}, {
text: "Residue"
icon: "🈹"
group: "Issue 4"
description: "Read 'Residue'"
}, {
text: "Issue 5"
icon: "📰"
group: "Issue 5"
description: "View Issue 5"
}, {
text: "Issue 6"
icon: "🐝"
group: "Issue 6"
description: "View Issue 6"
}, {
text: "Bee afraid"
icon: "🐝"
group: "Issue 6"
description: "Learn the truth about 'Bee Movie'"
}, {
text: "Tree story"
icon: "🐝"
group: "Issue 6"
description: "Read Tree"
}, {
text: "Issue 10"
icon: "🎃"
group: "Issue 10"
description: "Special Halloween Editon"
}, {
text: "Hard Rain"
icon: "☔"
group: "Issue 10"
description: "Culvert Livin'"
}, {
text: "3spoopy5me"
icon: "😨"
group: "Issue 10"
description: "Don't spoop your pants!"
}, {
text: "Not a real JT song"
icon: "👻"
group: "Issue 10"
description: "Maybe he hired a ghost writer"
}, {
text: "Issue 11"
icon: "💃"
group: "Issue 11"
description: "You can dab if you wanna"
}, {
text: "Late stage capitalism"
icon: "💰"
group: "Issue 11"
description: "What if this is only the beginning?"
}, {
text: "Value Investing"
icon: "📈"
group: "Issue 11"
description: "Value investing has proven to be a successful investment strategy."
}, {
text: "Getting Hairy"
icon: "👣"
group: "Issue 12"
description: "Individuals claim to have seen Bigfoot."
}, {
text: "Volume 2: Episode 1"
icon: "📰"
group: "V2E01"
description: "New year, same old you"
}, {
text: "As fortold in the Dead Sea Scrolls"
icon: "📜"
group: "V2E01"
description: "Beyond revelations"
}, {
text: "Inner or outer space?"
icon: "🐬"
group: "V2E01"
description: "Out of this world"
}, { # Apps
text: "Notepad.exe"
icon: "📝"
group: "App"
description: "Launch a text editor"
}, {
text: "Pump up the jam"
icon: "🎶"
group: "App"
description: "Launch audio application"
}, {
text: "Microsoft Access 97"
icon: "🔞"
group: "App"
description: "Launch a spreadsheet application"
}, {
text: "Look at that"
icon: "🖼️"
group: "App"
description: "Open the image viewer"
}, {
text: "Pixel perfect"
icon: "◼️️"
group: "App"
description: "Open the pixel editor"
}, {
text: "Check yo' self"
icon: "😉"
group: "App"
description: "Check your achievement status"
}, {
text: "Oh no, my files!"
icon: "💼"
group: "App"
description: "Opened 'My Briefcase'"
}, { # OS
text: "Save a file"
icon: "💾"
group: "OS"
description: "Write to the file system"
}, {
text: "Load a file"
icon: "💽"
group: "OS"
description: "Read from the file system"
}, {
text: "Execute code"
icon: "🖥️"
group: "OS"
description: "Some people like to live dangerously"
}, {
text: "Dismiss modal"
icon: "💃"
group: "OS"
description: "Dismiss a modal without even reading it"
}, {
text: "I AM ERROR"
icon: "🐛"
group: "OS"
description: "Encountered a JavaScript error"
}, {
text: "Shut Down"
icon: "🔌"
group: "OS"
description: "ZineOS cannot be stopped"
}, { # Social
text: "Do you 'like' like me?"
icon: "💕"
group: "Social"
description: "Have fine taste"
}, {
text: "A little bird told me"
icon: "🐦"
group: "Social"
description: "Social media marketing 101"
}, {
text: "We value your input"
icon: "📩"
group: "Social"
description: "View feedback form"
}, { # Chateau
text: "Enter the Chateau"
icon: "🏡"
group: "Chateau"
description: "Enter the Chateau"
}, {
text: "Puttin' on the Ritz"
icon: "🐭"
group: "Chateau"
description: "Upload custom avatar"
}, {
text: "Paint the town red"
icon: "🌆"
group: "Chateau"
description: "Upload a custom background"
}, {
text: "Poutine on the Ritz"
icon: "🍘"
group: "Chateau"
description: "Put poutine on a Ritz cracker"
}, {
text: "It's in the cloud"
icon: "☁️️"
group: "Chateau"
description: "Upload a file"
}, {
text: "PI:NAME:<NAME>END_PIr"
icon: "🐉"
group: "Contrasaurus"
description: "Played Contrasaurus"
}]
restore = ->
storedCheevos = []
try
storedCheevos = JSON.parse localStorage.cheevos
storedAchieved = {}
storedCheevos.forEach ({achieved, text}) ->
storedAchieved[text] = achieved
achievementData.forEach (cheevo) ->
{text} = cheevo
if storedAchieved[text]
cheevo.achieved = true
persist = ->
localStorage.cheevos = JSON.stringify(achievementData)
AchievementProgressPresenter = require "../presenters/achievement-group-progress"
groupBy = (xs, key) ->
xs.reduce (rv, x) ->
(rv[x[key]] ?= []).push(x)
rv
, {}
module.exports = (I, self) ->
restore()
Object.assign self,
Achievement:
groupData: Observable {}
unlock: (name) ->
opts = achievementData.find ({text}) ->
text is name
if opts and !opts.achieved
opts.achieved = true
persist()
updateStatus()
Achievement.display opts
progressView: ->
content = document.createElement "content"
Observable ->
data = self.Achievement.groupData()
elements = Object.keys(data).map (group) ->
AchievementProgressPresenter
name: group
achievements: data[group]
emptyElement content
elements.forEach (element) ->
content.appendChild(element)
return content
updateStatus = ->
self.Achievement.groupData groupBy(achievementData, "group")
updateStatus()
return self
|
[
{
"context": "verview Tests for no-restricted-globals.\n# @author Benoît Zugmeyer\n###\n\n'use strict'\n\n#-----------------------------",
"end": 79,
"score": 0.9998325109481812,
"start": 64,
"tag": "NAME",
"value": "Benoît Zugmeyer"
}
] | src/tests/rules/no-restricted-globals.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for no-restricted-globals.
# @author Benoît Zugmeyer
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-restricted-globals'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-restricted-globals', rule,
valid: [
'foo'
,
code: 'foo'
options: ['bar']
,
code: 'foo = 1'
options: ['foo']
,
code: 'event'
options: ['bar']
env: browser: yes
,
code: "import foo from 'bar'"
options: ['foo']
parserOptions: ecmaVersion: 6, sourceType: 'module'
,
code: 'foo = ->'
options: ['foo']
,
code: 'foo.bar'
options: ['bar']
,
code: 'foo'
options: [name: 'bar', message: 'Use baz instead.']
]
invalid: [
code: 'foo'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: '-> foo'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: '-> foo'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
globals: foo: no
,
code: 'event'
options: ['foo', 'event']
errors: [message: "Unexpected use of 'event'.", type: 'Identifier']
env: browser: yes
,
code: 'foo'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
globals: foo: no
,
code: 'foo()'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: 'foo.bar()'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: 'foo'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: '-> foo'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: '-> foo'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
globals: foo: no
,
code: 'event'
options: ['foo', {name: 'event'}]
errors: [message: "Unexpected use of 'event'.", type: 'Identifier']
env: browser: yes
,
code: 'foo'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
globals: foo: no
,
code: 'foo()'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: 'foo.bar()'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: 'foo'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
,
code: '-> foo'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
,
code: '-> foo'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
globals: foo: no
,
code: 'event'
options: ['foo', {name: 'event', message: 'Use local event parameter.'}]
errors: [
message: "Unexpected use of 'event'. Use local event parameter."
type: 'Identifier'
]
env: browser: yes
,
code: 'foo'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
globals: foo: no
,
code: 'foo()'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
,
code: 'foo.bar()'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
,
code: "foo = (obj) => hasOwnProperty(obj, 'name')"
options: ['hasOwnProperty']
errors: [message: "Unexpected use of 'hasOwnProperty'.", type: 'Identifier']
]
| 170651 | ###*
# @fileoverview Tests for no-restricted-globals.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-restricted-globals'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-restricted-globals', rule,
valid: [
'foo'
,
code: 'foo'
options: ['bar']
,
code: 'foo = 1'
options: ['foo']
,
code: 'event'
options: ['bar']
env: browser: yes
,
code: "import foo from 'bar'"
options: ['foo']
parserOptions: ecmaVersion: 6, sourceType: 'module'
,
code: 'foo = ->'
options: ['foo']
,
code: 'foo.bar'
options: ['bar']
,
code: 'foo'
options: [name: 'bar', message: 'Use baz instead.']
]
invalid: [
code: 'foo'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: '-> foo'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: '-> foo'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
globals: foo: no
,
code: 'event'
options: ['foo', 'event']
errors: [message: "Unexpected use of 'event'.", type: 'Identifier']
env: browser: yes
,
code: 'foo'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
globals: foo: no
,
code: 'foo()'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: 'foo.bar()'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: 'foo'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: '-> foo'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: '-> foo'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
globals: foo: no
,
code: 'event'
options: ['foo', {name: 'event'}]
errors: [message: "Unexpected use of 'event'.", type: 'Identifier']
env: browser: yes
,
code: 'foo'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
globals: foo: no
,
code: 'foo()'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: 'foo.bar()'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: 'foo'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
,
code: '-> foo'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
,
code: '-> foo'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
globals: foo: no
,
code: 'event'
options: ['foo', {name: 'event', message: 'Use local event parameter.'}]
errors: [
message: "Unexpected use of 'event'. Use local event parameter."
type: 'Identifier'
]
env: browser: yes
,
code: 'foo'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
globals: foo: no
,
code: 'foo()'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
,
code: 'foo.bar()'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
,
code: "foo = (obj) => hasOwnProperty(obj, 'name')"
options: ['hasOwnProperty']
errors: [message: "Unexpected use of 'hasOwnProperty'.", type: 'Identifier']
]
| true | ###*
# @fileoverview Tests for no-restricted-globals.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-restricted-globals'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-restricted-globals', rule,
valid: [
'foo'
,
code: 'foo'
options: ['bar']
,
code: 'foo = 1'
options: ['foo']
,
code: 'event'
options: ['bar']
env: browser: yes
,
code: "import foo from 'bar'"
options: ['foo']
parserOptions: ecmaVersion: 6, sourceType: 'module'
,
code: 'foo = ->'
options: ['foo']
,
code: 'foo.bar'
options: ['bar']
,
code: 'foo'
options: [name: 'bar', message: 'Use baz instead.']
]
invalid: [
code: 'foo'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: '-> foo'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: '-> foo'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
globals: foo: no
,
code: 'event'
options: ['foo', 'event']
errors: [message: "Unexpected use of 'event'.", type: 'Identifier']
env: browser: yes
,
code: 'foo'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
globals: foo: no
,
code: 'foo()'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: 'foo.bar()'
options: ['foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: 'foo'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: '-> foo'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: '-> foo'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
globals: foo: no
,
code: 'event'
options: ['foo', {name: 'event'}]
errors: [message: "Unexpected use of 'event'.", type: 'Identifier']
env: browser: yes
,
code: 'foo'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
globals: foo: no
,
code: 'foo()'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: 'foo.bar()'
options: [name: 'foo']
errors: [message: "Unexpected use of 'foo'.", type: 'Identifier']
,
code: 'foo'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
,
code: '-> foo'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
,
code: '-> foo'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
globals: foo: no
,
code: 'event'
options: ['foo', {name: 'event', message: 'Use local event parameter.'}]
errors: [
message: "Unexpected use of 'event'. Use local event parameter."
type: 'Identifier'
]
env: browser: yes
,
code: 'foo'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
globals: foo: no
,
code: 'foo()'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
,
code: 'foo.bar()'
options: [name: 'foo', message: 'Use bar instead.']
errors: [
message: "Unexpected use of 'foo'. Use bar instead.", type: 'Identifier'
]
,
code: "foo = (obj) => hasOwnProperty(obj, 'name')"
options: ['hasOwnProperty']
errors: [message: "Unexpected use of 'hasOwnProperty'.", type: 'Identifier']
]
|
[
{
"context": "oveCount = 0\n\ndevicetokens.forEach (dt) ->\n key = \"#{dt.user}#{dt.type}#{dt.clientId}\"\n if dtMap[key] ",
"end": 144,
"score": 0.7496496438980103,
"start": 141,
"tag": "KEY",
"value": "\"#{"
},
{
"context": "0\n\ndevicetokens.forEach (dt) ->\n key = \"#{dt.user}... | talk-api2x/mshells/cleanup-repeat-client-id.coffee | ikingye/talk-os | 3,084 | devicetokens = db.devicetokens.find().sort({updatedAt: -1})
dtMap = {}
tokenMap = {}
removeCount = 0
devicetokens.forEach (dt) ->
key = "#{dt.user}#{dt.type}#{dt.clientId}"
if dtMap[key] or tokenMap[dt.token] or not dt.clientId
print "Remove", JSON.stringify(dt)
removeCount += 1
db.devicetokens.remove({_id: dt._id})
else
# Log key index
dtMap[key] = dt._id
tokenMap[dt.token] = dt._id
print "Removed count", removeCount
| 96847 | devicetokens = db.devicetokens.find().sort({updatedAt: -1})
dtMap = {}
tokenMap = {}
removeCount = 0
devicetokens.forEach (dt) ->
key = <KEY>dt.user}<KEY>dt.type}<KEY>dt.clientId<KEY>}"
if dtMap[key] or tokenMap[dt.token] or not dt.clientId
print "Remove", JSON.stringify(dt)
removeCount += 1
db.devicetokens.remove({_id: dt._id})
else
# Log key index
dtMap[key] = dt._id
tokenMap[dt.token] = dt._id
print "Removed count", removeCount
| true | devicetokens = db.devicetokens.find().sort({updatedAt: -1})
dtMap = {}
tokenMap = {}
removeCount = 0
devicetokens.forEach (dt) ->
key = PI:KEY:<KEY>END_PIdt.user}PI:KEY:<KEY>END_PIdt.type}PI:KEY:<KEY>END_PIdt.clientIdPI:KEY:<KEY>END_PI}"
if dtMap[key] or tokenMap[dt.token] or not dt.clientId
print "Remove", JSON.stringify(dt)
removeCount += 1
db.devicetokens.remove({_id: dt._id})
else
# Log key index
dtMap[key] = dt._id
tokenMap[dt.token] = dt._id
print "Removed count", removeCount
|
[
{
"context": "k: {}\n clientId: \"12345\"\n accessToken: \"abcdefg\"\n callbackUrl: \"http://localhost/callback.ht",
"end": 707,
"score": 0.9958217144012451,
"start": 700,
"tag": "KEY",
"value": "abcdefg"
},
{
"context": "d is provided\", ->\n readmill.book = auth... | test/spec/readmill.coffee | aron/annotator.readmill.js | 0 | describe "Readmill", ->
jQuery = Annotator.$
Readmill = Annotator.Readmill
readmill = null
beforeEach ->
sinon.stub(Readmill.Store.prototype, "get").returns(null)
readmill = new Readmill $("<div />"),
book: {}
clientId: "12345"
callbackUrl: "http://localhost/callback.html"
afterEach ->
Readmill.Store.prototype.get.restore()
it "should be an instance of Annotator.Plugin", ->
expect(readmill).to.be.an.instanceof Annotator.Plugin
it "should call @connected() with the access token if provided", ->
sinon.stub(Readmill.prototype, "connected")
target = new Readmill $("<div />"),
book: {}
clientId: "12345"
accessToken: "abcdefg"
callbackUrl: "http://localhost/callback.html"
expect(target.connected).was.called()
expect(target.connected).was.calledWith("abcdefg")
Readmill.prototype.connected.restore()
it "should call @connected() with the access token if in localStorage", ->
sinon.stub(Readmill.prototype, "connected")
Readmill.Store.prototype.get.returns("abcdefg")
target = new Readmill $("<div />"),
book: {}
clientId: "12345"
callbackUrl: "http://localhost/callback.html"
expect(target.connected).was.called()
expect(target.connected).was.calledWith("abcdefg")
Readmill.prototype.connected.restore()
it "should raise an Error if any required parameters are missing", ->
target = ->
target = new Readmill $("<div />"),
clientId: "12345"
callbackUrl: "http://localhost/callback.html"
expect(target).to.throw(Error)
it "should wrap all methods with 'Error' in the name with a 401 handler", ->
target = sinon.stub(Readmill.prototype, "_createUnauthorizedHandler")
new Readmill $("<div />"),
book: {}
clientId: "12345"
callbackUrl: "http://localhost/callback.html"
methods = 0
methods++ for key, value of Readmill.prototype when key.indexOf("Error") > -1
expect(target.callCount).to.equal(methods)
target.restore()
it "should have a default options.getPage() function", ->
expected = window.location.href.split("?").shift()
expect(readmill.options.getPage()).to.equal(expected)
describe "#pluginInit()", ->
beforeEach ->
sinon.stub(jQuery.fn, "append")
sinon.stub(readmill, "lookupBook")
sinon.stub(readmill, "lookupReading")
afterEach ->
jQuery.fn.append.restore()
it "should append the @view.element to the document body", ->
readmill.pluginInit()
expect(jQuery.fn.append).was.called()
expect(jQuery.fn.append).was.calledWith(readmill.view.element)
it "should call @lookupBook()", ->
readmill.pluginInit()
expect(readmill.lookupBook).was.called()
it "should call @lookupReading() if authorised", ->
sinon.stub(readmill.client, "isAuthorized").returns(true)
readmill.lookupReading.returns(done: sinon.stub())
readmill.pluginInit()
expect(readmill.lookupReading).was.called()
it "should updated the view when the reading is loaded", ->
target = sinon.stub()
sinon.stub(readmill.client, "isAuthorized").returns(true)
sinon.stub(readmill.view, "reading")
readmill.lookupReading.returns(done: target)
readmill.pluginInit()
expect(target).was.called()
target.args[0][0]()
expect(readmill.view.reading).was.called()
it "should register view event listeners", ->
target = sinon.stub(readmill.view, "on")
readmill.pluginInit()
expect(readmill.view.on).was.calledWith("reading", readmill.lookupReading)
expect(readmill.view.on).was.calledWith("connect", readmill.connect)
expect(readmill.view.on).was.calledWith("disconnect", readmill.disconnect)
describe "#lookupBook()", ->
promise = null
beforeEach ->
readmill.book = {id: 1}
promise = sinon.createPromiseStub()
sinon.stub(readmill.client, "getBook").returns promise
sinon.stub(readmill.client, "matchBook").returns promise
it "should call @client.getBook() if an book.id is provided", ->
readmill.lookupBook()
expect(readmill.client.getBook).was.called()
expect(readmill.client.getBook).was.calledWith(1)
it "should call @client.matchBook() if no book.id is provided", ->
readmill.book = author: "Graham Greene", title: "Brighton Rock"
readmill.lookupBook()
expect(readmill.client.matchBook).was.called()
expect(readmill.client.matchBook).was.calledWith(readmill.book)
it "should return a jQuery.Deferred() promise", ->
expect(readmill.lookupBook()).to.equal(promise)
it "should register @_onBookSuccess and @_onBookError callbacks", ->
readmill.lookupBook()
expect(promise.then).was.called()
expect(promise.then).was.calledWith(readmill._onBookSuccess, readmill._onBookError)
it "should return the book.promise if it already exists", ->
readmill.book.promise = promise
expect(readmill.lookupBook()).to.equal(promise)
describe "#lookupReading()", ->
bookPromise = null
readingPromise = null
beforeEach ->
bookPromise = sinon.createPromiseStub()
readingPromise = sinon.createPromiseStub()
sinon.stub(readmill, "lookupBook").returns bookPromise
sinon.stub(readmill.client, "createReadingForBook").returns readingPromise
it "should call @lookupBook()", ->
readmill.lookupReading()
expect(readmill.lookupBook).was.called()
it "should call @client.createReadingForBook()", ->
readmill.lookupReading()
bookPromise.done.args[0][0]()
expect(readmill.client.createReadingForBook).was.called()
it "should register the @_onCreateReadingSuccess and @_onCreateReadingError callbacks", ->
readmill.lookupReading()
bookPromise.done.args[0][0]()
expect(readingPromise.then).was.called()
expect(readingPromise.then).was.calledWith(readmill._onCreateReadingSuccess, readmill._onCreateReadingError)
describe "#endReading()", ->
it "should remove the reading property from @book"
it "should tell Readmill the book is finished"
it "should remove all annotations from the page"
describe "#updatePrivacy()", ->
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
sinon.stub(readmill.client, "updateReading").returns(promise)
it "should update the privacy depending on the view state", ->
readmill.book.reading = {uri: "http://"}
sinon.stub(readmill.view, "isPrivate").returns(true)
readmill.updatePrivacy()
expect(readmill.view.isPrivate).was.called()
expect(readmill.client.updateReading).was.called()
expect(readmill.client.updateReading).was.calledWith("http://", private: true)
it "should register an error handler", ->
readmill.book.reading = {uri: "http://"}
sinon.stub(readmill.view, "isPrivate").returns(true)
readmill.updatePrivacy()
expect(promise.fail).was.called()
expect(promise.fail).was.calledWith(readmill._onUpdatePrivacyError)
it "should do nothing if there is no reading", ->
readmill.updatePrivacy()
expect(readmill.client.updateReading).was.notCalled()
describe "#connect()", ->
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
sinon.stub(readmill.auth, "connect").returns(promise)
it "should call @auth.connect()", ->
readmill.connect()
expect(readmill.auth.connect).was.called()
it "should register the @_onConnectSuccess and @_onConnectError callbacks", ->
readmill.connect()
expect(promise.then).was.called()
expect(promise.then).was.calledWith(readmill._onConnectSuccess, readmill._onConnectError)
describe "#connected()", ->
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
sinon.stub(readmill.store, "set")
sinon.stub(readmill.client, "me").returns(promise)
sinon.stub(readmill.client, "authorize")
sinon.stub(Annotator, "showNotification")
afterEach ->
Annotator.showNotification.restore()
it "should authorise the @client", ->
readmill.connected("123456")
expect(readmill.client.authorize).was.called()
it "should request the users details from Readmill", ->
readmill.connected("123456")
expect(readmill.client.me).was.called()
it "should register the @_onMeSuccess and @_onMeError callbacks", ->
readmill.connected("123456")
expect(promise.then).was.called()
expect(promise.then).was.calledWith(readmill._onMeSuccess, readmill._onMeError)
it "should save the access token in the @store", ->
readmill.connected("123456")
expect(readmill.store.set).was.called()
expect(readmill.store.set).was.calledWith("access-token", "123456")
it "should save the access token in the @store with an expires time", ->
readmill.connected("123456", expires: 3000)
expect(readmill.store.set).was.called()
expect(readmill.store.set).was.calledWith("access-token", "123456", 3000)
it "should display a success notification", ->
readmill.connected("123456")
expect(Annotator.showNotification).was.called()
expect(Annotator.showNotification).was.calledWith("Successfully connected to Readmill")
it "should not display a success notification if options.silent is true", ->
readmill.connected("123456", silent: true)
expect(Annotator.showNotification).was.notCalled()
describe "#disconnect()", ->
beforeEach ->
sinon.stub(readmill.store, "remove")
sinon.stub(readmill.client, "deauthorize")
sinon.stub(readmill.element, "find").returns
each: sinon.spy()
it "should deauthorise the @client", ->
readmill.disconnect()
expect(readmill.client.deauthorize).was.called()
it "should remove the api token from local storage", ->
readmill.disconnect()
expect(readmill.store.remove).was.called()
expect(readmill.store.remove).was.calledWith("access-token")
it "should remove highlights from the dom", ->
readmill.disconnect()
expect(readmill.element.find).was.called()
expect(readmill.element.find).was.calledWith(".annotator-hl")
it "should not remove the annotations if options.removeAnnotations is false", ->
target = sinon.stub(readmill, "removeAnnotations")
readmill.disconnect(removeAnnotations: false)
expect(target).was.notCalled()
describe "#error()", ->
it "should display an error notifiaction", ->
target = sinon.stub Annotator, "showNotification"
readmill.error("message")
expect(target).was.called()
expect(target).was.calledWith("message")
target.restore()
describe "#removeAnnotations()", ->
it "should remove all annotations from the page"
describe "#_createUnauthorizedHandler()", ->
it "should return a new handler function", ->
target = readmill._createUnauthorizedHandler(->)
expect(target).to.be.a("function")
describe "handler()", ->
it "should handle an unauthorised response", ->
target = sinon.stub(readmill, "unauthorized")
callback = readmill._createUnauthorizedHandler(target)
callback(status: 401)
expect(target).was.called()
it "should call the parent callback if response is authorised", ->
target = sinon.stub()
callback = readmill._createUnauthorizedHandler(target)
callback(status: 200)
expect(target).was.called()
expect(target).was.calledWith(status: 200)
describe "#_onConnectSuccess()", ->
it "should call @connected() with the access token and additonal params", ->
target = sinon.stub readmill, "connected"
params = access_token: "123456", expires: 3000
readmill._onConnectSuccess(params)
expect(target).was.called()
expect(target).was.calledWith("123456", params)
describe "#_onConnectError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onConnectError("test-error")
expect(target).was.called()
expect(target).was.calledWith("test-error")
describe "#_onMeSuccess()", ->
beforeEach ->
sinon.stub readmill, "lookupReading"
it "should assign the @user data", ->
user = {}
readmill._onMeSuccess(user)
expect(readmill.user).to.equal(user)
describe "#_onMeError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onMeError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to fetch user info from Readmill")
describe "#_onBookSuccess()", ->
it "should extend @book with the response data", ->
target = sinon.stub jQuery, "extend"
book = id: 1
readmill._onBookSuccess(book)
expect(target).was.called()
expect(target).was.calledWith(readmill.book, book)
target.restore()
describe "#_onBookError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onBookError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to fetch book info from Readmill")
describe "#_onCreateReadingSuccess()", ->
body = null
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
sinon.stub(readmill.client, "request").returns(promise)
body = location: "http://api.readmill.com/reading/1"
it "should request the reading resource if location is present", ->
readmill._onCreateReadingSuccess(body)
expect(readmill.client.request).was.called()
expect(readmill.client.request.args[0][0]).to.eql(url: "http://api.readmill.com/reading/1")
it "should register the @_onGetReadingSuccess() and @_onGetReadingError() callbacks", ->
readmill._onCreateReadingSuccess(body)
expect(promise.then).was.called()
expect(promise.then).was.calledWith(readmill._onGetReadingSuccess, readmill._onGetReadingError)
it "should call @_onGetReadingError() if the location cannot be parsed", ->
sinon.stub(readmill, "_onGetReadingError")
readmill._onCreateReadingSuccess({})
expect(readmill._onGetReadingError).was.called()
describe "#_onCreateReadingError()", ->
it "should call @_onCreateReadingSuccess() if status is 409", ->
body = {}
target = sinon.stub readmill, "_onCreateReadingSuccess"
response = status: 409, responseText: '{"location": "http://"}'
sinon.stub(JSON, "parse").returns(body)
sinon.stub(readmill, "error")
readmill._onCreateReadingError(response)
expect(target).was.called()
expect(target).was.calledWith(body, "success", response)
JSON.parse.restore()
it "should call @error() with the error message if status is not 409", ->
target = sinon.stub readmill, "error"
readmill._onCreateReadingError(status: 422)
expect(target).was.called()
expect(target).was.calledWith("Unable to create a reading for this book")
describe "#_onGetReadingSuccess()", ->
reading = null
promise = null
beforeEach ->
reading = highlights: "http://api.readmill.com/reading/1/highlights"
promise = sinon.createPromiseStub()
sinon.stub(readmill.view, "updateBook")
sinon.stub(readmill.client, "getHighlights").returns(promise)
it "should assign the reading to @book.reading", ->
readmill._onGetReadingSuccess(reading)
expect(readmill.book.reading).to.equal(reading)
it "should update the view with the reading", ->
readmill._onGetReadingSuccess(reading)
expect(readmill.view.updateBook).was.called()
it "should request the highlights for the reading", ->
readmill._onGetReadingSuccess(reading)
expect(readmill.client.getHighlights).was.called()
expect(readmill.client.getHighlights).was.calledWith(reading.highlights)
it "should register the @_onGetHighlightsSuccess() and @_onGetHighlightsError() callbacks", ->
readmill._onGetReadingSuccess(reading)
expect(promise.then).was.called()
expect(promise.then).was.calledWith(readmill._onGetHighlightsSuccess, readmill._onGetHighlightsError)
describe "#_onGetReadingError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onGetReadingError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to create a reading for this book")
describe "#_onGetHighlightsSuccess()", ->
highlights = null
promises = null
whenPromise = null
beforeEach ->
highlights = [{}, {}, {}]
promises = [
sinon.createPromiseStub()
sinon.createPromiseStub()
sinon.createPromiseStub()
]
cloned = promises.slice()
promises[1].state.returns("rejected")
sinon.stub Readmill.utils, "annotationFromHighlight", ->
cloned.shift()
whenPromise = sinon.createPromiseStub()
sinon.stub(jQuery, "when").returns(whenPromise)
afterEach ->
jQuery.when.restore()
Readmill.utils.annotationFromHighlight.restore()
it "should parse the highlights", ->
readmill._onGetHighlightsSuccess(highlights)
target = Readmill.utils.annotationFromHighlight
expect(target).was.called()
expect(target.callCount).to.equal(3)
it "should filter out rejected annotations", ->
readmill._onGetHighlightsSuccess(highlights)
target = jQuery.when
expect(target).was.called()
expect(target.args[0].length).to.equal(2)
expect(target).was.calledWith(promises[0], promises[2])
it "should load the annotations into the annotator", ->
readmill.annotator = loadAnnotations: sinon.spy()
annotations = [{}, {}, {}]
readmill._onGetHighlightsSuccess(highlights)
whenPromise.done.args[0][0].apply(null, annotations)
expect(readmill.annotator.loadAnnotations).was.called()
expect(readmill.annotator.loadAnnotations).was.calledWith(annotations)
describe "#_onGetHighlightsError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onGetHighlightsError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to fetch highlights for reading")
describe "#_onCreateHighlight()", ->
promise = null
annotation = null
response = null
highlight = null
beforeEach ->
promise = sinon.createPromiseStub()
annotation = text: "this is an annotation comment"
response = location: "http://api.readmill.com/highlight/1"
highlight =
id: "1"
uri: "http://api.readmill.com/highlight/1"
comments: "http://api.readmill.com/highlight/1/comments"
sinon.stub(readmill, "_onAnnotationUpdated")
sinon.stub(readmill.client, "request").returns(promise)
it "should request the newly created highlight", ->
readmill._onCreateHighlight(annotation, response)
expect(readmill.client.request).was.called()
expect(readmill.client.request).was.calledWith(url: response.location)
it "should store the id, commentsUrl and highlightUrl on the annotation", ->
readmill._onCreateHighlight(annotation, response)
promise.done.args[0][0](highlight)
expect(annotation).to.have.property("id", annotation.id)
expect(annotation).to.have.property("highlightUrl", annotation.uri)
expect(annotation).to.have.property("commentsUrl", annotation.comments)
it "should create the comment on the highlight", ->
readmill._onCreateHighlight(annotation, response)
promise.done.args[0][0](highlight)
expect(readmill._onAnnotationUpdated).was.called()
expect(readmill._onAnnotationUpdated).was.calledWith(annotation)
describe "#_onAnnotationCreated()", ->
promise = null
proxied = null
annotation = {}
beforeEach ->
promise = sinon.createPromiseStub()
proxied = sinon.spy()
readmill.book =
id: "32"
url: "http://"
reading: {highlights: "http://"}
sinon.stub(readmill, "lookupBook").returns(sinon.createPromiseStub())
sinon.stub(readmill.client, "isAuthorized").returns(true)
sinon.stub(readmill.client, "createHighlight").returns(promise)
sinon.stub(jQuery, "proxy").returns(proxied)
afterEach ->
jQuery.proxy.restore()
it "should create a callback function with the annotation as the first arg", ->
readmill._onAnnotationCreated(annotation)
expect(jQuery.proxy).was.called()
expect(jQuery.proxy).was.calledWith(readmill, "_onCreateHighlight", annotation)
it "should try and create a new annotation", ->
readmill._onAnnotationCreated(annotation)
target = readmill.client.createHighlight
expect(target).was.called()
expect(target).was.calledWith(readmill.book.reading.highlights)
it "should register success and error handlers", ->
readmill._onAnnotationCreated(annotation)
expect(promise.done).was.called()
expect(promise.done).was.calledWith(proxied)
expect(promise.fail).was.called()
expect(promise.fail).was.calledWith(readmill._onAnnotationCreatedError)
it "should push the annotation into the @unsaved array if unauthed or no book", ->
readmill.book = {}
readmill._onAnnotationCreated(annotation)
expect(readmill.unsaved).to.eql([annotation])
it "should notify the user that the plugin is not authorised", ->
readmill.client.isAuthorized.returns(false)
target = sinon.stub readmill, "unauthorized"
readmill._onAnnotationCreated(annotation)
expect(target).was.called()
it "should look up the book and retry if no book", ->
readmill.book = {}
target = readmill.lookupBook
readmill._onAnnotationCreated(annotation)
expect(target).was.called()
describe "#_onAnnotationCreatedError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onAnnotationCreatedError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to save annotation to Readmill")
describe "#_onAnnotationUpdated()", ->
annotation = null
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
annotation =
text: "Annotation Comment"
sinon.stub(readmill.client, "createComment").returns(promise)
sinon.stub(readmill.client, "updateComment").returns(promise)
it "should update the comment if annotation.commentUrl is present", ->
target = readmill.client.updateComment
annotation.commentUrl = "http://api.readmill.com/comments/1"
readmill._onAnnotationUpdated(annotation)
expect(target).was.called()
expect(target).was.calledWith("http://api.readmill.com/comments/1")
it "should create the comment if annotation.commentUrl is not present", ->
target = readmill.client.createComment
annotation.commentsUrl = "http://api.readmill.com/comments/"
readmill._onAnnotationUpdated(annotation)
expect(target).was.called()
expect(target).was.calledWith("http://api.readmill.com/comments/")
it "should regsiter a success hander if annotation is created", ->
target = readmill.client.createComment
annotation.commentsUrl = "http://api.readmill.com/comments/"
readmill._onAnnotationUpdated(annotation)
expect(promise.done).was.called()
it "should register an error handler", ->
target = readmill.client.createComment
annotation.commentsUrl = "http://api.readmill.com/comments/"
readmill._onAnnotationUpdated(annotation)
expect(promise.fail).was.called()
expect(promise.fail).was.calledWith(readmill._onAnnotationUpdatedError)
describe "#_onAnnotationUpdatedError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onAnnotationUpdatedError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to update annotation in Readmill")
describe "#_onAnnotationDeleted()", ->
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
sinon.stub(readmill.client, "deleteHighlight").returns(promise)
it "should delete the highlight if annotation.highlightUrl is present", ->
readmill._onAnnotationDeleted(highlightUrl: "http://")
expect(readmill.client.deleteHighlight).was.called()
expect(readmill.client.deleteHighlight).was.calledWith("http://")
it "should register an error callback", ->
readmill._onAnnotationDeleted(highlightUrl: "http://")
expect(promise.fail).was.called()
expect(promise.fail).was.calledWith(readmill._onAnnotationDeletedError)
it "should do nothing if annotation.highlightUrl is not present", ->
readmill._onAnnotationDeleted({})
expect(readmill.client.deleteHighlight).was.notCalled()
describe "#_onAnnotationDeletedError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onAnnotationDeletedError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to delete annotation on Readmill")
| 25391 | describe "Readmill", ->
jQuery = Annotator.$
Readmill = Annotator.Readmill
readmill = null
beforeEach ->
sinon.stub(Readmill.Store.prototype, "get").returns(null)
readmill = new Readmill $("<div />"),
book: {}
clientId: "12345"
callbackUrl: "http://localhost/callback.html"
afterEach ->
Readmill.Store.prototype.get.restore()
it "should be an instance of Annotator.Plugin", ->
expect(readmill).to.be.an.instanceof Annotator.Plugin
it "should call @connected() with the access token if provided", ->
sinon.stub(Readmill.prototype, "connected")
target = new Readmill $("<div />"),
book: {}
clientId: "12345"
accessToken: "<KEY>"
callbackUrl: "http://localhost/callback.html"
expect(target.connected).was.called()
expect(target.connected).was.calledWith("abcdefg")
Readmill.prototype.connected.restore()
it "should call @connected() with the access token if in localStorage", ->
sinon.stub(Readmill.prototype, "connected")
Readmill.Store.prototype.get.returns("abcdefg")
target = new Readmill $("<div />"),
book: {}
clientId: "12345"
callbackUrl: "http://localhost/callback.html"
expect(target.connected).was.called()
expect(target.connected).was.calledWith("abcdefg")
Readmill.prototype.connected.restore()
it "should raise an Error if any required parameters are missing", ->
target = ->
target = new Readmill $("<div />"),
clientId: "12345"
callbackUrl: "http://localhost/callback.html"
expect(target).to.throw(Error)
it "should wrap all methods with 'Error' in the name with a 401 handler", ->
target = sinon.stub(Readmill.prototype, "_createUnauthorizedHandler")
new Readmill $("<div />"),
book: {}
clientId: "12345"
callbackUrl: "http://localhost/callback.html"
methods = 0
methods++ for key, value of Readmill.prototype when key.indexOf("Error") > -1
expect(target.callCount).to.equal(methods)
target.restore()
it "should have a default options.getPage() function", ->
expected = window.location.href.split("?").shift()
expect(readmill.options.getPage()).to.equal(expected)
describe "#pluginInit()", ->
beforeEach ->
sinon.stub(jQuery.fn, "append")
sinon.stub(readmill, "lookupBook")
sinon.stub(readmill, "lookupReading")
afterEach ->
jQuery.fn.append.restore()
it "should append the @view.element to the document body", ->
readmill.pluginInit()
expect(jQuery.fn.append).was.called()
expect(jQuery.fn.append).was.calledWith(readmill.view.element)
it "should call @lookupBook()", ->
readmill.pluginInit()
expect(readmill.lookupBook).was.called()
it "should call @lookupReading() if authorised", ->
sinon.stub(readmill.client, "isAuthorized").returns(true)
readmill.lookupReading.returns(done: sinon.stub())
readmill.pluginInit()
expect(readmill.lookupReading).was.called()
it "should updated the view when the reading is loaded", ->
target = sinon.stub()
sinon.stub(readmill.client, "isAuthorized").returns(true)
sinon.stub(readmill.view, "reading")
readmill.lookupReading.returns(done: target)
readmill.pluginInit()
expect(target).was.called()
target.args[0][0]()
expect(readmill.view.reading).was.called()
it "should register view event listeners", ->
target = sinon.stub(readmill.view, "on")
readmill.pluginInit()
expect(readmill.view.on).was.calledWith("reading", readmill.lookupReading)
expect(readmill.view.on).was.calledWith("connect", readmill.connect)
expect(readmill.view.on).was.calledWith("disconnect", readmill.disconnect)
describe "#lookupBook()", ->
promise = null
beforeEach ->
readmill.book = {id: 1}
promise = sinon.createPromiseStub()
sinon.stub(readmill.client, "getBook").returns promise
sinon.stub(readmill.client, "matchBook").returns promise
it "should call @client.getBook() if an book.id is provided", ->
readmill.lookupBook()
expect(readmill.client.getBook).was.called()
expect(readmill.client.getBook).was.calledWith(1)
it "should call @client.matchBook() if no book.id is provided", ->
readmill.book = author: "<NAME>", title: "Brighton Rock"
readmill.lookupBook()
expect(readmill.client.matchBook).was.called()
expect(readmill.client.matchBook).was.calledWith(readmill.book)
it "should return a jQuery.Deferred() promise", ->
expect(readmill.lookupBook()).to.equal(promise)
it "should register @_onBookSuccess and @_onBookError callbacks", ->
readmill.lookupBook()
expect(promise.then).was.called()
expect(promise.then).was.calledWith(readmill._onBookSuccess, readmill._onBookError)
it "should return the book.promise if it already exists", ->
readmill.book.promise = promise
expect(readmill.lookupBook()).to.equal(promise)
describe "#lookupReading()", ->
bookPromise = null
readingPromise = null
beforeEach ->
bookPromise = sinon.createPromiseStub()
readingPromise = sinon.createPromiseStub()
sinon.stub(readmill, "lookupBook").returns bookPromise
sinon.stub(readmill.client, "createReadingForBook").returns readingPromise
it "should call @lookupBook()", ->
readmill.lookupReading()
expect(readmill.lookupBook).was.called()
it "should call @client.createReadingForBook()", ->
readmill.lookupReading()
bookPromise.done.args[0][0]()
expect(readmill.client.createReadingForBook).was.called()
it "should register the @_onCreateReadingSuccess and @_onCreateReadingError callbacks", ->
readmill.lookupReading()
bookPromise.done.args[0][0]()
expect(readingPromise.then).was.called()
expect(readingPromise.then).was.calledWith(readmill._onCreateReadingSuccess, readmill._onCreateReadingError)
describe "#endReading()", ->
it "should remove the reading property from @book"
it "should tell Readmill the book is finished"
it "should remove all annotations from the page"
describe "#updatePrivacy()", ->
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
sinon.stub(readmill.client, "updateReading").returns(promise)
it "should update the privacy depending on the view state", ->
readmill.book.reading = {uri: "http://"}
sinon.stub(readmill.view, "isPrivate").returns(true)
readmill.updatePrivacy()
expect(readmill.view.isPrivate).was.called()
expect(readmill.client.updateReading).was.called()
expect(readmill.client.updateReading).was.calledWith("http://", private: true)
it "should register an error handler", ->
readmill.book.reading = {uri: "http://"}
sinon.stub(readmill.view, "isPrivate").returns(true)
readmill.updatePrivacy()
expect(promise.fail).was.called()
expect(promise.fail).was.calledWith(readmill._onUpdatePrivacyError)
it "should do nothing if there is no reading", ->
readmill.updatePrivacy()
expect(readmill.client.updateReading).was.notCalled()
describe "#connect()", ->
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
sinon.stub(readmill.auth, "connect").returns(promise)
it "should call @auth.connect()", ->
readmill.connect()
expect(readmill.auth.connect).was.called()
it "should register the @_onConnectSuccess and @_onConnectError callbacks", ->
readmill.connect()
expect(promise.then).was.called()
expect(promise.then).was.calledWith(readmill._onConnectSuccess, readmill._onConnectError)
describe "#connected()", ->
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
sinon.stub(readmill.store, "set")
sinon.stub(readmill.client, "me").returns(promise)
sinon.stub(readmill.client, "authorize")
sinon.stub(Annotator, "showNotification")
afterEach ->
Annotator.showNotification.restore()
it "should authorise the @client", ->
readmill.connected("123456")
expect(readmill.client.authorize).was.called()
it "should request the users details from Readmill", ->
readmill.connected("123456")
expect(readmill.client.me).was.called()
it "should register the @_onMeSuccess and @_onMeError callbacks", ->
readmill.connected("123456")
expect(promise.then).was.called()
expect(promise.then).was.calledWith(readmill._onMeSuccess, readmill._onMeError)
it "should save the access token in the @store", ->
readmill.connected("123456")
expect(readmill.store.set).was.called()
expect(readmill.store.set).was.calledWith("access-token", "<PASSWORD>")
it "should save the access token in the @store with an expires time", ->
readmill.connected("123456", expires: 3000)
expect(readmill.store.set).was.called()
expect(readmill.store.set).was.calledWith("access-token", "<PASSWORD>", 3000)
it "should display a success notification", ->
readmill.connected("123456")
expect(Annotator.showNotification).was.called()
expect(Annotator.showNotification).was.calledWith("Successfully connected to Readmill")
it "should not display a success notification if options.silent is true", ->
readmill.connected("123456", silent: true)
expect(Annotator.showNotification).was.notCalled()
describe "#disconnect()", ->
beforeEach ->
sinon.stub(readmill.store, "remove")
sinon.stub(readmill.client, "deauthorize")
sinon.stub(readmill.element, "find").returns
each: sinon.spy()
it "should deauthorise the @client", ->
readmill.disconnect()
expect(readmill.client.deauthorize).was.called()
it "should remove the api token from local storage", ->
readmill.disconnect()
expect(readmill.store.remove).was.called()
expect(readmill.store.remove).was.calledWith("access-token")
it "should remove highlights from the dom", ->
readmill.disconnect()
expect(readmill.element.find).was.called()
expect(readmill.element.find).was.calledWith(".annotator-hl")
it "should not remove the annotations if options.removeAnnotations is false", ->
target = sinon.stub(readmill, "removeAnnotations")
readmill.disconnect(removeAnnotations: false)
expect(target).was.notCalled()
describe "#error()", ->
it "should display an error notifiaction", ->
target = sinon.stub Annotator, "showNotification"
readmill.error("message")
expect(target).was.called()
expect(target).was.calledWith("message")
target.restore()
describe "#removeAnnotations()", ->
it "should remove all annotations from the page"
describe "#_createUnauthorizedHandler()", ->
it "should return a new handler function", ->
target = readmill._createUnauthorizedHandler(->)
expect(target).to.be.a("function")
describe "handler()", ->
it "should handle an unauthorised response", ->
target = sinon.stub(readmill, "unauthorized")
callback = readmill._createUnauthorizedHandler(target)
callback(status: 401)
expect(target).was.called()
it "should call the parent callback if response is authorised", ->
target = sinon.stub()
callback = readmill._createUnauthorizedHandler(target)
callback(status: 200)
expect(target).was.called()
expect(target).was.calledWith(status: 200)
describe "#_onConnectSuccess()", ->
it "should call @connected() with the access token and additonal params", ->
target = sinon.stub readmill, "connected"
params = access_token: "<KEY> <PASSWORD>", expires: 3000
readmill._onConnectSuccess(params)
expect(target).was.called()
expect(target).was.calledWith("123456", params)
describe "#_onConnectError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onConnectError("test-error")
expect(target).was.called()
expect(target).was.calledWith("test-error")
describe "#_onMeSuccess()", ->
beforeEach ->
sinon.stub readmill, "lookupReading"
it "should assign the @user data", ->
user = {}
readmill._onMeSuccess(user)
expect(readmill.user).to.equal(user)
describe "#_onMeError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onMeError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to fetch user info from Readmill")
describe "#_onBookSuccess()", ->
it "should extend @book with the response data", ->
target = sinon.stub jQuery, "extend"
book = id: 1
readmill._onBookSuccess(book)
expect(target).was.called()
expect(target).was.calledWith(readmill.book, book)
target.restore()
describe "#_onBookError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onBookError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to fetch book info from Readmill")
describe "#_onCreateReadingSuccess()", ->
body = null
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
sinon.stub(readmill.client, "request").returns(promise)
body = location: "http://api.readmill.com/reading/1"
it "should request the reading resource if location is present", ->
readmill._onCreateReadingSuccess(body)
expect(readmill.client.request).was.called()
expect(readmill.client.request.args[0][0]).to.eql(url: "http://api.readmill.com/reading/1")
it "should register the @_onGetReadingSuccess() and @_onGetReadingError() callbacks", ->
readmill._onCreateReadingSuccess(body)
expect(promise.then).was.called()
expect(promise.then).was.calledWith(readmill._onGetReadingSuccess, readmill._onGetReadingError)
it "should call @_onGetReadingError() if the location cannot be parsed", ->
sinon.stub(readmill, "_onGetReadingError")
readmill._onCreateReadingSuccess({})
expect(readmill._onGetReadingError).was.called()
describe "#_onCreateReadingError()", ->
it "should call @_onCreateReadingSuccess() if status is 409", ->
body = {}
target = sinon.stub readmill, "_onCreateReadingSuccess"
response = status: 409, responseText: '{"location": "http://"}'
sinon.stub(JSON, "parse").returns(body)
sinon.stub(readmill, "error")
readmill._onCreateReadingError(response)
expect(target).was.called()
expect(target).was.calledWith(body, "success", response)
JSON.parse.restore()
it "should call @error() with the error message if status is not 409", ->
target = sinon.stub readmill, "error"
readmill._onCreateReadingError(status: 422)
expect(target).was.called()
expect(target).was.calledWith("Unable to create a reading for this book")
describe "#_onGetReadingSuccess()", ->
reading = null
promise = null
beforeEach ->
reading = highlights: "http://api.readmill.com/reading/1/highlights"
promise = sinon.createPromiseStub()
sinon.stub(readmill.view, "updateBook")
sinon.stub(readmill.client, "getHighlights").returns(promise)
it "should assign the reading to @book.reading", ->
readmill._onGetReadingSuccess(reading)
expect(readmill.book.reading).to.equal(reading)
it "should update the view with the reading", ->
readmill._onGetReadingSuccess(reading)
expect(readmill.view.updateBook).was.called()
it "should request the highlights for the reading", ->
readmill._onGetReadingSuccess(reading)
expect(readmill.client.getHighlights).was.called()
expect(readmill.client.getHighlights).was.calledWith(reading.highlights)
it "should register the @_onGetHighlightsSuccess() and @_onGetHighlightsError() callbacks", ->
readmill._onGetReadingSuccess(reading)
expect(promise.then).was.called()
expect(promise.then).was.calledWith(readmill._onGetHighlightsSuccess, readmill._onGetHighlightsError)
describe "#_onGetReadingError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onGetReadingError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to create a reading for this book")
describe "#_onGetHighlightsSuccess()", ->
highlights = null
promises = null
whenPromise = null
beforeEach ->
highlights = [{}, {}, {}]
promises = [
sinon.createPromiseStub()
sinon.createPromiseStub()
sinon.createPromiseStub()
]
cloned = promises.slice()
promises[1].state.returns("rejected")
sinon.stub Readmill.utils, "annotationFromHighlight", ->
cloned.shift()
whenPromise = sinon.createPromiseStub()
sinon.stub(jQuery, "when").returns(whenPromise)
afterEach ->
jQuery.when.restore()
Readmill.utils.annotationFromHighlight.restore()
it "should parse the highlights", ->
readmill._onGetHighlightsSuccess(highlights)
target = Readmill.utils.annotationFromHighlight
expect(target).was.called()
expect(target.callCount).to.equal(3)
it "should filter out rejected annotations", ->
readmill._onGetHighlightsSuccess(highlights)
target = jQuery.when
expect(target).was.called()
expect(target.args[0].length).to.equal(2)
expect(target).was.calledWith(promises[0], promises[2])
it "should load the annotations into the annotator", ->
readmill.annotator = loadAnnotations: sinon.spy()
annotations = [{}, {}, {}]
readmill._onGetHighlightsSuccess(highlights)
whenPromise.done.args[0][0].apply(null, annotations)
expect(readmill.annotator.loadAnnotations).was.called()
expect(readmill.annotator.loadAnnotations).was.calledWith(annotations)
describe "#_onGetHighlightsError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onGetHighlightsError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to fetch highlights for reading")
describe "#_onCreateHighlight()", ->
promise = null
annotation = null
response = null
highlight = null
beforeEach ->
promise = sinon.createPromiseStub()
annotation = text: "this is an annotation comment"
response = location: "http://api.readmill.com/highlight/1"
highlight =
id: "1"
uri: "http://api.readmill.com/highlight/1"
comments: "http://api.readmill.com/highlight/1/comments"
sinon.stub(readmill, "_onAnnotationUpdated")
sinon.stub(readmill.client, "request").returns(promise)
it "should request the newly created highlight", ->
readmill._onCreateHighlight(annotation, response)
expect(readmill.client.request).was.called()
expect(readmill.client.request).was.calledWith(url: response.location)
it "should store the id, commentsUrl and highlightUrl on the annotation", ->
readmill._onCreateHighlight(annotation, response)
promise.done.args[0][0](highlight)
expect(annotation).to.have.property("id", annotation.id)
expect(annotation).to.have.property("highlightUrl", annotation.uri)
expect(annotation).to.have.property("commentsUrl", annotation.comments)
it "should create the comment on the highlight", ->
readmill._onCreateHighlight(annotation, response)
promise.done.args[0][0](highlight)
expect(readmill._onAnnotationUpdated).was.called()
expect(readmill._onAnnotationUpdated).was.calledWith(annotation)
describe "#_onAnnotationCreated()", ->
promise = null
proxied = null
annotation = {}
beforeEach ->
promise = sinon.createPromiseStub()
proxied = sinon.spy()
readmill.book =
id: "32"
url: "http://"
reading: {highlights: "http://"}
sinon.stub(readmill, "lookupBook").returns(sinon.createPromiseStub())
sinon.stub(readmill.client, "isAuthorized").returns(true)
sinon.stub(readmill.client, "createHighlight").returns(promise)
sinon.stub(jQuery, "proxy").returns(proxied)
afterEach ->
jQuery.proxy.restore()
it "should create a callback function with the annotation as the first arg", ->
readmill._onAnnotationCreated(annotation)
expect(jQuery.proxy).was.called()
expect(jQuery.proxy).was.calledWith(readmill, "_onCreateHighlight", annotation)
it "should try and create a new annotation", ->
readmill._onAnnotationCreated(annotation)
target = readmill.client.createHighlight
expect(target).was.called()
expect(target).was.calledWith(readmill.book.reading.highlights)
it "should register success and error handlers", ->
readmill._onAnnotationCreated(annotation)
expect(promise.done).was.called()
expect(promise.done).was.calledWith(proxied)
expect(promise.fail).was.called()
expect(promise.fail).was.calledWith(readmill._onAnnotationCreatedError)
it "should push the annotation into the @unsaved array if unauthed or no book", ->
readmill.book = {}
readmill._onAnnotationCreated(annotation)
expect(readmill.unsaved).to.eql([annotation])
it "should notify the user that the plugin is not authorised", ->
readmill.client.isAuthorized.returns(false)
target = sinon.stub readmill, "unauthorized"
readmill._onAnnotationCreated(annotation)
expect(target).was.called()
it "should look up the book and retry if no book", ->
readmill.book = {}
target = readmill.lookupBook
readmill._onAnnotationCreated(annotation)
expect(target).was.called()
describe "#_onAnnotationCreatedError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onAnnotationCreatedError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to save annotation to Readmill")
describe "#_onAnnotationUpdated()", ->
annotation = null
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
annotation =
text: "Annotation Comment"
sinon.stub(readmill.client, "createComment").returns(promise)
sinon.stub(readmill.client, "updateComment").returns(promise)
it "should update the comment if annotation.commentUrl is present", ->
target = readmill.client.updateComment
annotation.commentUrl = "http://api.readmill.com/comments/1"
readmill._onAnnotationUpdated(annotation)
expect(target).was.called()
expect(target).was.calledWith("http://api.readmill.com/comments/1")
it "should create the comment if annotation.commentUrl is not present", ->
target = readmill.client.createComment
annotation.commentsUrl = "http://api.readmill.com/comments/"
readmill._onAnnotationUpdated(annotation)
expect(target).was.called()
expect(target).was.calledWith("http://api.readmill.com/comments/")
it "should regsiter a success hander if annotation is created", ->
target = readmill.client.createComment
annotation.commentsUrl = "http://api.readmill.com/comments/"
readmill._onAnnotationUpdated(annotation)
expect(promise.done).was.called()
it "should register an error handler", ->
target = readmill.client.createComment
annotation.commentsUrl = "http://api.readmill.com/comments/"
readmill._onAnnotationUpdated(annotation)
expect(promise.fail).was.called()
expect(promise.fail).was.calledWith(readmill._onAnnotationUpdatedError)
describe "#_onAnnotationUpdatedError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onAnnotationUpdatedError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to update annotation in Readmill")
describe "#_onAnnotationDeleted()", ->
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
sinon.stub(readmill.client, "deleteHighlight").returns(promise)
it "should delete the highlight if annotation.highlightUrl is present", ->
readmill._onAnnotationDeleted(highlightUrl: "http://")
expect(readmill.client.deleteHighlight).was.called()
expect(readmill.client.deleteHighlight).was.calledWith("http://")
it "should register an error callback", ->
readmill._onAnnotationDeleted(highlightUrl: "http://")
expect(promise.fail).was.called()
expect(promise.fail).was.calledWith(readmill._onAnnotationDeletedError)
it "should do nothing if annotation.highlightUrl is not present", ->
readmill._onAnnotationDeleted({})
expect(readmill.client.deleteHighlight).was.notCalled()
describe "#_onAnnotationDeletedError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onAnnotationDeletedError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to delete annotation on Readmill")
| true | describe "Readmill", ->
jQuery = Annotator.$
Readmill = Annotator.Readmill
readmill = null
beforeEach ->
sinon.stub(Readmill.Store.prototype, "get").returns(null)
readmill = new Readmill $("<div />"),
book: {}
clientId: "12345"
callbackUrl: "http://localhost/callback.html"
afterEach ->
Readmill.Store.prototype.get.restore()
it "should be an instance of Annotator.Plugin", ->
expect(readmill).to.be.an.instanceof Annotator.Plugin
it "should call @connected() with the access token if provided", ->
sinon.stub(Readmill.prototype, "connected")
target = new Readmill $("<div />"),
book: {}
clientId: "12345"
accessToken: "PI:KEY:<KEY>END_PI"
callbackUrl: "http://localhost/callback.html"
expect(target.connected).was.called()
expect(target.connected).was.calledWith("abcdefg")
Readmill.prototype.connected.restore()
it "should call @connected() with the access token if in localStorage", ->
sinon.stub(Readmill.prototype, "connected")
Readmill.Store.prototype.get.returns("abcdefg")
target = new Readmill $("<div />"),
book: {}
clientId: "12345"
callbackUrl: "http://localhost/callback.html"
expect(target.connected).was.called()
expect(target.connected).was.calledWith("abcdefg")
Readmill.prototype.connected.restore()
it "should raise an Error if any required parameters are missing", ->
target = ->
target = new Readmill $("<div />"),
clientId: "12345"
callbackUrl: "http://localhost/callback.html"
expect(target).to.throw(Error)
it "should wrap all methods with 'Error' in the name with a 401 handler", ->
target = sinon.stub(Readmill.prototype, "_createUnauthorizedHandler")
new Readmill $("<div />"),
book: {}
clientId: "12345"
callbackUrl: "http://localhost/callback.html"
methods = 0
methods++ for key, value of Readmill.prototype when key.indexOf("Error") > -1
expect(target.callCount).to.equal(methods)
target.restore()
it "should have a default options.getPage() function", ->
expected = window.location.href.split("?").shift()
expect(readmill.options.getPage()).to.equal(expected)
describe "#pluginInit()", ->
beforeEach ->
sinon.stub(jQuery.fn, "append")
sinon.stub(readmill, "lookupBook")
sinon.stub(readmill, "lookupReading")
afterEach ->
jQuery.fn.append.restore()
it "should append the @view.element to the document body", ->
readmill.pluginInit()
expect(jQuery.fn.append).was.called()
expect(jQuery.fn.append).was.calledWith(readmill.view.element)
it "should call @lookupBook()", ->
readmill.pluginInit()
expect(readmill.lookupBook).was.called()
it "should call @lookupReading() if authorised", ->
sinon.stub(readmill.client, "isAuthorized").returns(true)
readmill.lookupReading.returns(done: sinon.stub())
readmill.pluginInit()
expect(readmill.lookupReading).was.called()
it "should updated the view when the reading is loaded", ->
target = sinon.stub()
sinon.stub(readmill.client, "isAuthorized").returns(true)
sinon.stub(readmill.view, "reading")
readmill.lookupReading.returns(done: target)
readmill.pluginInit()
expect(target).was.called()
target.args[0][0]()
expect(readmill.view.reading).was.called()
it "should register view event listeners", ->
target = sinon.stub(readmill.view, "on")
readmill.pluginInit()
expect(readmill.view.on).was.calledWith("reading", readmill.lookupReading)
expect(readmill.view.on).was.calledWith("connect", readmill.connect)
expect(readmill.view.on).was.calledWith("disconnect", readmill.disconnect)
describe "#lookupBook()", ->
promise = null
beforeEach ->
readmill.book = {id: 1}
promise = sinon.createPromiseStub()
sinon.stub(readmill.client, "getBook").returns promise
sinon.stub(readmill.client, "matchBook").returns promise
it "should call @client.getBook() if an book.id is provided", ->
readmill.lookupBook()
expect(readmill.client.getBook).was.called()
expect(readmill.client.getBook).was.calledWith(1)
it "should call @client.matchBook() if no book.id is provided", ->
readmill.book = author: "PI:NAME:<NAME>END_PI", title: "Brighton Rock"
readmill.lookupBook()
expect(readmill.client.matchBook).was.called()
expect(readmill.client.matchBook).was.calledWith(readmill.book)
it "should return a jQuery.Deferred() promise", ->
expect(readmill.lookupBook()).to.equal(promise)
it "should register @_onBookSuccess and @_onBookError callbacks", ->
readmill.lookupBook()
expect(promise.then).was.called()
expect(promise.then).was.calledWith(readmill._onBookSuccess, readmill._onBookError)
it "should return the book.promise if it already exists", ->
readmill.book.promise = promise
expect(readmill.lookupBook()).to.equal(promise)
describe "#lookupReading()", ->
bookPromise = null
readingPromise = null
beforeEach ->
bookPromise = sinon.createPromiseStub()
readingPromise = sinon.createPromiseStub()
sinon.stub(readmill, "lookupBook").returns bookPromise
sinon.stub(readmill.client, "createReadingForBook").returns readingPromise
it "should call @lookupBook()", ->
readmill.lookupReading()
expect(readmill.lookupBook).was.called()
it "should call @client.createReadingForBook()", ->
readmill.lookupReading()
bookPromise.done.args[0][0]()
expect(readmill.client.createReadingForBook).was.called()
it "should register the @_onCreateReadingSuccess and @_onCreateReadingError callbacks", ->
readmill.lookupReading()
bookPromise.done.args[0][0]()
expect(readingPromise.then).was.called()
expect(readingPromise.then).was.calledWith(readmill._onCreateReadingSuccess, readmill._onCreateReadingError)
describe "#endReading()", ->
it "should remove the reading property from @book"
it "should tell Readmill the book is finished"
it "should remove all annotations from the page"
describe "#updatePrivacy()", ->
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
sinon.stub(readmill.client, "updateReading").returns(promise)
it "should update the privacy depending on the view state", ->
readmill.book.reading = {uri: "http://"}
sinon.stub(readmill.view, "isPrivate").returns(true)
readmill.updatePrivacy()
expect(readmill.view.isPrivate).was.called()
expect(readmill.client.updateReading).was.called()
expect(readmill.client.updateReading).was.calledWith("http://", private: true)
it "should register an error handler", ->
readmill.book.reading = {uri: "http://"}
sinon.stub(readmill.view, "isPrivate").returns(true)
readmill.updatePrivacy()
expect(promise.fail).was.called()
expect(promise.fail).was.calledWith(readmill._onUpdatePrivacyError)
it "should do nothing if there is no reading", ->
readmill.updatePrivacy()
expect(readmill.client.updateReading).was.notCalled()
describe "#connect()", ->
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
sinon.stub(readmill.auth, "connect").returns(promise)
it "should call @auth.connect()", ->
readmill.connect()
expect(readmill.auth.connect).was.called()
it "should register the @_onConnectSuccess and @_onConnectError callbacks", ->
readmill.connect()
expect(promise.then).was.called()
expect(promise.then).was.calledWith(readmill._onConnectSuccess, readmill._onConnectError)
describe "#connected()", ->
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
sinon.stub(readmill.store, "set")
sinon.stub(readmill.client, "me").returns(promise)
sinon.stub(readmill.client, "authorize")
sinon.stub(Annotator, "showNotification")
afterEach ->
Annotator.showNotification.restore()
it "should authorise the @client", ->
readmill.connected("123456")
expect(readmill.client.authorize).was.called()
it "should request the users details from Readmill", ->
readmill.connected("123456")
expect(readmill.client.me).was.called()
it "should register the @_onMeSuccess and @_onMeError callbacks", ->
readmill.connected("123456")
expect(promise.then).was.called()
expect(promise.then).was.calledWith(readmill._onMeSuccess, readmill._onMeError)
it "should save the access token in the @store", ->
readmill.connected("123456")
expect(readmill.store.set).was.called()
expect(readmill.store.set).was.calledWith("access-token", "PI:PASSWORD:<PASSWORD>END_PI")
it "should save the access token in the @store with an expires time", ->
readmill.connected("123456", expires: 3000)
expect(readmill.store.set).was.called()
expect(readmill.store.set).was.calledWith("access-token", "PI:PASSWORD:<PASSWORD>END_PI", 3000)
it "should display a success notification", ->
readmill.connected("123456")
expect(Annotator.showNotification).was.called()
expect(Annotator.showNotification).was.calledWith("Successfully connected to Readmill")
it "should not display a success notification if options.silent is true", ->
readmill.connected("123456", silent: true)
expect(Annotator.showNotification).was.notCalled()
describe "#disconnect()", ->
beforeEach ->
sinon.stub(readmill.store, "remove")
sinon.stub(readmill.client, "deauthorize")
sinon.stub(readmill.element, "find").returns
each: sinon.spy()
it "should deauthorise the @client", ->
readmill.disconnect()
expect(readmill.client.deauthorize).was.called()
it "should remove the api token from local storage", ->
readmill.disconnect()
expect(readmill.store.remove).was.called()
expect(readmill.store.remove).was.calledWith("access-token")
it "should remove highlights from the dom", ->
readmill.disconnect()
expect(readmill.element.find).was.called()
expect(readmill.element.find).was.calledWith(".annotator-hl")
it "should not remove the annotations if options.removeAnnotations is false", ->
target = sinon.stub(readmill, "removeAnnotations")
readmill.disconnect(removeAnnotations: false)
expect(target).was.notCalled()
describe "#error()", ->
it "should display an error notifiaction", ->
target = sinon.stub Annotator, "showNotification"
readmill.error("message")
expect(target).was.called()
expect(target).was.calledWith("message")
target.restore()
describe "#removeAnnotations()", ->
it "should remove all annotations from the page"
describe "#_createUnauthorizedHandler()", ->
it "should return a new handler function", ->
target = readmill._createUnauthorizedHandler(->)
expect(target).to.be.a("function")
describe "handler()", ->
it "should handle an unauthorised response", ->
target = sinon.stub(readmill, "unauthorized")
callback = readmill._createUnauthorizedHandler(target)
callback(status: 401)
expect(target).was.called()
it "should call the parent callback if response is authorised", ->
target = sinon.stub()
callback = readmill._createUnauthorizedHandler(target)
callback(status: 200)
expect(target).was.called()
expect(target).was.calledWith(status: 200)
describe "#_onConnectSuccess()", ->
it "should call @connected() with the access token and additonal params", ->
target = sinon.stub readmill, "connected"
params = access_token: "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI", expires: 3000
readmill._onConnectSuccess(params)
expect(target).was.called()
expect(target).was.calledWith("123456", params)
describe "#_onConnectError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onConnectError("test-error")
expect(target).was.called()
expect(target).was.calledWith("test-error")
describe "#_onMeSuccess()", ->
beforeEach ->
sinon.stub readmill, "lookupReading"
it "should assign the @user data", ->
user = {}
readmill._onMeSuccess(user)
expect(readmill.user).to.equal(user)
describe "#_onMeError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onMeError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to fetch user info from Readmill")
describe "#_onBookSuccess()", ->
it "should extend @book with the response data", ->
target = sinon.stub jQuery, "extend"
book = id: 1
readmill._onBookSuccess(book)
expect(target).was.called()
expect(target).was.calledWith(readmill.book, book)
target.restore()
describe "#_onBookError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onBookError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to fetch book info from Readmill")
describe "#_onCreateReadingSuccess()", ->
body = null
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
sinon.stub(readmill.client, "request").returns(promise)
body = location: "http://api.readmill.com/reading/1"
it "should request the reading resource if location is present", ->
readmill._onCreateReadingSuccess(body)
expect(readmill.client.request).was.called()
expect(readmill.client.request.args[0][0]).to.eql(url: "http://api.readmill.com/reading/1")
it "should register the @_onGetReadingSuccess() and @_onGetReadingError() callbacks", ->
readmill._onCreateReadingSuccess(body)
expect(promise.then).was.called()
expect(promise.then).was.calledWith(readmill._onGetReadingSuccess, readmill._onGetReadingError)
it "should call @_onGetReadingError() if the location cannot be parsed", ->
sinon.stub(readmill, "_onGetReadingError")
readmill._onCreateReadingSuccess({})
expect(readmill._onGetReadingError).was.called()
describe "#_onCreateReadingError()", ->
it "should call @_onCreateReadingSuccess() if status is 409", ->
body = {}
target = sinon.stub readmill, "_onCreateReadingSuccess"
response = status: 409, responseText: '{"location": "http://"}'
sinon.stub(JSON, "parse").returns(body)
sinon.stub(readmill, "error")
readmill._onCreateReadingError(response)
expect(target).was.called()
expect(target).was.calledWith(body, "success", response)
JSON.parse.restore()
it "should call @error() with the error message if status is not 409", ->
target = sinon.stub readmill, "error"
readmill._onCreateReadingError(status: 422)
expect(target).was.called()
expect(target).was.calledWith("Unable to create a reading for this book")
describe "#_onGetReadingSuccess()", ->
reading = null
promise = null
beforeEach ->
reading = highlights: "http://api.readmill.com/reading/1/highlights"
promise = sinon.createPromiseStub()
sinon.stub(readmill.view, "updateBook")
sinon.stub(readmill.client, "getHighlights").returns(promise)
it "should assign the reading to @book.reading", ->
readmill._onGetReadingSuccess(reading)
expect(readmill.book.reading).to.equal(reading)
it "should update the view with the reading", ->
readmill._onGetReadingSuccess(reading)
expect(readmill.view.updateBook).was.called()
it "should request the highlights for the reading", ->
readmill._onGetReadingSuccess(reading)
expect(readmill.client.getHighlights).was.called()
expect(readmill.client.getHighlights).was.calledWith(reading.highlights)
it "should register the @_onGetHighlightsSuccess() and @_onGetHighlightsError() callbacks", ->
readmill._onGetReadingSuccess(reading)
expect(promise.then).was.called()
expect(promise.then).was.calledWith(readmill._onGetHighlightsSuccess, readmill._onGetHighlightsError)
describe "#_onGetReadingError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onGetReadingError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to create a reading for this book")
describe "#_onGetHighlightsSuccess()", ->
highlights = null
promises = null
whenPromise = null
beforeEach ->
highlights = [{}, {}, {}]
promises = [
sinon.createPromiseStub()
sinon.createPromiseStub()
sinon.createPromiseStub()
]
cloned = promises.slice()
promises[1].state.returns("rejected")
sinon.stub Readmill.utils, "annotationFromHighlight", ->
cloned.shift()
whenPromise = sinon.createPromiseStub()
sinon.stub(jQuery, "when").returns(whenPromise)
afterEach ->
jQuery.when.restore()
Readmill.utils.annotationFromHighlight.restore()
it "should parse the highlights", ->
readmill._onGetHighlightsSuccess(highlights)
target = Readmill.utils.annotationFromHighlight
expect(target).was.called()
expect(target.callCount).to.equal(3)
it "should filter out rejected annotations", ->
readmill._onGetHighlightsSuccess(highlights)
target = jQuery.when
expect(target).was.called()
expect(target.args[0].length).to.equal(2)
expect(target).was.calledWith(promises[0], promises[2])
it "should load the annotations into the annotator", ->
readmill.annotator = loadAnnotations: sinon.spy()
annotations = [{}, {}, {}]
readmill._onGetHighlightsSuccess(highlights)
whenPromise.done.args[0][0].apply(null, annotations)
expect(readmill.annotator.loadAnnotations).was.called()
expect(readmill.annotator.loadAnnotations).was.calledWith(annotations)
describe "#_onGetHighlightsError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onGetHighlightsError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to fetch highlights for reading")
describe "#_onCreateHighlight()", ->
promise = null
annotation = null
response = null
highlight = null
beforeEach ->
promise = sinon.createPromiseStub()
annotation = text: "this is an annotation comment"
response = location: "http://api.readmill.com/highlight/1"
highlight =
id: "1"
uri: "http://api.readmill.com/highlight/1"
comments: "http://api.readmill.com/highlight/1/comments"
sinon.stub(readmill, "_onAnnotationUpdated")
sinon.stub(readmill.client, "request").returns(promise)
it "should request the newly created highlight", ->
readmill._onCreateHighlight(annotation, response)
expect(readmill.client.request).was.called()
expect(readmill.client.request).was.calledWith(url: response.location)
it "should store the id, commentsUrl and highlightUrl on the annotation", ->
readmill._onCreateHighlight(annotation, response)
promise.done.args[0][0](highlight)
expect(annotation).to.have.property("id", annotation.id)
expect(annotation).to.have.property("highlightUrl", annotation.uri)
expect(annotation).to.have.property("commentsUrl", annotation.comments)
it "should create the comment on the highlight", ->
readmill._onCreateHighlight(annotation, response)
promise.done.args[0][0](highlight)
expect(readmill._onAnnotationUpdated).was.called()
expect(readmill._onAnnotationUpdated).was.calledWith(annotation)
describe "#_onAnnotationCreated()", ->
promise = null
proxied = null
annotation = {}
beforeEach ->
promise = sinon.createPromiseStub()
proxied = sinon.spy()
readmill.book =
id: "32"
url: "http://"
reading: {highlights: "http://"}
sinon.stub(readmill, "lookupBook").returns(sinon.createPromiseStub())
sinon.stub(readmill.client, "isAuthorized").returns(true)
sinon.stub(readmill.client, "createHighlight").returns(promise)
sinon.stub(jQuery, "proxy").returns(proxied)
afterEach ->
jQuery.proxy.restore()
it "should create a callback function with the annotation as the first arg", ->
readmill._onAnnotationCreated(annotation)
expect(jQuery.proxy).was.called()
expect(jQuery.proxy).was.calledWith(readmill, "_onCreateHighlight", annotation)
it "should try and create a new annotation", ->
readmill._onAnnotationCreated(annotation)
target = readmill.client.createHighlight
expect(target).was.called()
expect(target).was.calledWith(readmill.book.reading.highlights)
it "should register success and error handlers", ->
readmill._onAnnotationCreated(annotation)
expect(promise.done).was.called()
expect(promise.done).was.calledWith(proxied)
expect(promise.fail).was.called()
expect(promise.fail).was.calledWith(readmill._onAnnotationCreatedError)
it "should push the annotation into the @unsaved array if unauthed or no book", ->
readmill.book = {}
readmill._onAnnotationCreated(annotation)
expect(readmill.unsaved).to.eql([annotation])
it "should notify the user that the plugin is not authorised", ->
readmill.client.isAuthorized.returns(false)
target = sinon.stub readmill, "unauthorized"
readmill._onAnnotationCreated(annotation)
expect(target).was.called()
it "should look up the book and retry if no book", ->
readmill.book = {}
target = readmill.lookupBook
readmill._onAnnotationCreated(annotation)
expect(target).was.called()
describe "#_onAnnotationCreatedError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onAnnotationCreatedError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to save annotation to Readmill")
describe "#_onAnnotationUpdated()", ->
annotation = null
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
annotation =
text: "Annotation Comment"
sinon.stub(readmill.client, "createComment").returns(promise)
sinon.stub(readmill.client, "updateComment").returns(promise)
it "should update the comment if annotation.commentUrl is present", ->
target = readmill.client.updateComment
annotation.commentUrl = "http://api.readmill.com/comments/1"
readmill._onAnnotationUpdated(annotation)
expect(target).was.called()
expect(target).was.calledWith("http://api.readmill.com/comments/1")
it "should create the comment if annotation.commentUrl is not present", ->
target = readmill.client.createComment
annotation.commentsUrl = "http://api.readmill.com/comments/"
readmill._onAnnotationUpdated(annotation)
expect(target).was.called()
expect(target).was.calledWith("http://api.readmill.com/comments/")
it "should regsiter a success hander if annotation is created", ->
target = readmill.client.createComment
annotation.commentsUrl = "http://api.readmill.com/comments/"
readmill._onAnnotationUpdated(annotation)
expect(promise.done).was.called()
it "should register an error handler", ->
target = readmill.client.createComment
annotation.commentsUrl = "http://api.readmill.com/comments/"
readmill._onAnnotationUpdated(annotation)
expect(promise.fail).was.called()
expect(promise.fail).was.calledWith(readmill._onAnnotationUpdatedError)
describe "#_onAnnotationUpdatedError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onAnnotationUpdatedError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to update annotation in Readmill")
describe "#_onAnnotationDeleted()", ->
promise = null
beforeEach ->
promise = sinon.createPromiseStub()
sinon.stub(readmill.client, "deleteHighlight").returns(promise)
it "should delete the highlight if annotation.highlightUrl is present", ->
readmill._onAnnotationDeleted(highlightUrl: "http://")
expect(readmill.client.deleteHighlight).was.called()
expect(readmill.client.deleteHighlight).was.calledWith("http://")
it "should register an error callback", ->
readmill._onAnnotationDeleted(highlightUrl: "http://")
expect(promise.fail).was.called()
expect(promise.fail).was.calledWith(readmill._onAnnotationDeletedError)
it "should do nothing if annotation.highlightUrl is not present", ->
readmill._onAnnotationDeleted({})
expect(readmill.client.deleteHighlight).was.notCalled()
describe "#_onAnnotationDeletedError()", ->
it "should call @error() with the error message", ->
target = sinon.stub readmill, "error"
readmill._onAnnotationDeletedError(status: 400)
expect(target).was.called()
expect(target).was.calledWith("Unable to delete annotation on Readmill")
|
[
{
"context": ".setPageTitle('nav.my_account')\n\n user.password = ''\n user.password_confirmation = ''\n\n $scope.editi",
"end": 169,
"score": 0.9638828635215759,
"start": 169,
"tag": "PASSWORD",
"value": ""
},
{
"context": " user.password = ''\n user.password_confirmation = ''\n... | app/assets/javascripts/sprangular/controllers/account.coffee | rposborne/sprangular | 0 | Sprangular.controller 'AccountCtrl', (
$scope,
$location,
$routeParams,
Status,
Account,
user
) ->
Status.setPageTitle('nav.my_account')
user.password = ''
user.password_confirmation = ''
$scope.editing = false
$scope.user = user
$scope.edit = ->
$scope.editing = true
$scope.stopEdit = ->
$scope.editing = false
$scope.save = ->
user.errors = {}
Account.save(user)
.then (content) ->
$scope.editing = false
$location.path('/') if !Account.isLogged
, (errors) ->
user.errors = errors
| 35991 | Sprangular.controller 'AccountCtrl', (
$scope,
$location,
$routeParams,
Status,
Account,
user
) ->
Status.setPageTitle('nav.my_account')
user.password =<PASSWORD> ''
user.password_confirmation =<PASSWORD> ''
$scope.editing = false
$scope.user = user
$scope.edit = ->
$scope.editing = true
$scope.stopEdit = ->
$scope.editing = false
$scope.save = ->
user.errors = {}
Account.save(user)
.then (content) ->
$scope.editing = false
$location.path('/') if !Account.isLogged
, (errors) ->
user.errors = errors
| true | Sprangular.controller 'AccountCtrl', (
$scope,
$location,
$routeParams,
Status,
Account,
user
) ->
Status.setPageTitle('nav.my_account')
user.password =PI:PASSWORD:<PASSWORD>END_PI ''
user.password_confirmation =PI:PASSWORD:<PASSWORD>END_PI ''
$scope.editing = false
$scope.user = user
$scope.edit = ->
$scope.editing = true
$scope.stopEdit = ->
$scope.editing = false
$scope.save = ->
user.errors = {}
Account.save(user)
.then (content) ->
$scope.editing = false
$location.path('/') if !Account.isLogged
, (errors) ->
user.errors = errors
|
[
{
"context": "---------------------------------\n# Copyright 2014 Patrick Mueller\n#\n# Licensed under the Apache License, Version 2.",
"end": 704,
"score": 0.9998435974121094,
"start": 689,
"tag": "NAME",
"value": "Patrick Mueller"
}
] | www-src/ang/views/body.coffee | pmuellr/gh-miner | 1 | # Licensed under the Apache License. See footer for details.
AngTangle.controller body = ($scope, Logger, data) ->
domReady = false
$ ->
domReady = true
$scope.isDev = $("html").hasClass "dev"
$scope.messages = Logger.getMessages()
$scope.pkg = data.package
subTitle = ""
$scope.getSubtitle = ->
return "" if subTitle is ""
return ": #{subTitle}"
$scope.setSubtitle = (s) ->
subTitle = s
$scope.$on "$routeChangeSuccess", (next, current) ->
$(".navbar-collapse").collapse("hide") if domReady
#-------------------------------------------------------------------------------
# Copyright 2014 Patrick Mueller
#
# 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.
#-------------------------------------------------------------------------------
| 90340 | # Licensed under the Apache License. See footer for details.
AngTangle.controller body = ($scope, Logger, data) ->
domReady = false
$ ->
domReady = true
$scope.isDev = $("html").hasClass "dev"
$scope.messages = Logger.getMessages()
$scope.pkg = data.package
subTitle = ""
$scope.getSubtitle = ->
return "" if subTitle is ""
return ": #{subTitle}"
$scope.setSubtitle = (s) ->
subTitle = s
$scope.$on "$routeChangeSuccess", (next, current) ->
$(".navbar-collapse").collapse("hide") if domReady
#-------------------------------------------------------------------------------
# Copyright 2014 <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.
AngTangle.controller body = ($scope, Logger, data) ->
domReady = false
$ ->
domReady = true
$scope.isDev = $("html").hasClass "dev"
$scope.messages = Logger.getMessages()
$scope.pkg = data.package
subTitle = ""
$scope.getSubtitle = ->
return "" if subTitle is ""
return ": #{subTitle}"
$scope.setSubtitle = (s) ->
subTitle = s
$scope.$on "$routeChangeSuccess", (next, current) ->
$(".navbar-collapse").collapse("hide") if domReady
#-------------------------------------------------------------------------------
# Copyright 2014 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": "rs (dot) noreply (dot) github (dot) com\n# @Author: Ben Mz\n\n# Licensed under the Apache License, Version 2.0",
"end": 101,
"score": 0.9997890591621399,
"start": 95,
"tag": "NAME",
"value": "Ben Mz"
}
] | livetoken.coffee | x62en/livetoken-npm | 0 | # Copyright [2016]
# @Email: x62en (at) users (dot) noreply (dot) github (dot) com
# @Author: Ben Mz
# 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.
request = require 'request'
module.exports = class Livetoken
# Define the apikey used by the server
constructor: (@apikey) ->
# Execute status request
status: ({callback}) ->
unless callback
callback = @_default_callback
@_interact
action: 'status'
params: { 'Client_ID': @apikey }
callback: callback
# Execute token request
request: ({phone, email, callback}) ->
params = { 'Client_ID': @apikey }
if phone
params.Phone = phone
if email
params.Email = phone
unless callback
callback = @_default_callback
@_interact
action: 'request'
params: params
callback: callback
_default_callback: (raw) ->
console.log JSON.stringify raw
# Do the actual request to server (private call)
_interact: ({action, params, callback}) ->
request
method: 'POST'
json: true
form: params
uri: "https://livetoken.io/#{action}"
(error, response, body) =>
# Define answer object
if not error and response.statusCode is 200
callback body
else
callback {State: false, Msg: "Uknown server error: #{response.statusCode}"}
| 170899 | # Copyright [2016]
# @Email: x62en (at) users (dot) noreply (dot) github (dot) com
# @Author: <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.
request = require 'request'
module.exports = class Livetoken
# Define the apikey used by the server
constructor: (@apikey) ->
# Execute status request
status: ({callback}) ->
unless callback
callback = @_default_callback
@_interact
action: 'status'
params: { 'Client_ID': @apikey }
callback: callback
# Execute token request
request: ({phone, email, callback}) ->
params = { 'Client_ID': @apikey }
if phone
params.Phone = phone
if email
params.Email = phone
unless callback
callback = @_default_callback
@_interact
action: 'request'
params: params
callback: callback
_default_callback: (raw) ->
console.log JSON.stringify raw
# Do the actual request to server (private call)
_interact: ({action, params, callback}) ->
request
method: 'POST'
json: true
form: params
uri: "https://livetoken.io/#{action}"
(error, response, body) =>
# Define answer object
if not error and response.statusCode is 200
callback body
else
callback {State: false, Msg: "Uknown server error: #{response.statusCode}"}
| true | # Copyright [2016]
# @Email: x62en (at) users (dot) noreply (dot) github (dot) com
# @Author: 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.
request = require 'request'
module.exports = class Livetoken
# Define the apikey used by the server
constructor: (@apikey) ->
# Execute status request
status: ({callback}) ->
unless callback
callback = @_default_callback
@_interact
action: 'status'
params: { 'Client_ID': @apikey }
callback: callback
# Execute token request
request: ({phone, email, callback}) ->
params = { 'Client_ID': @apikey }
if phone
params.Phone = phone
if email
params.Email = phone
unless callback
callback = @_default_callback
@_interact
action: 'request'
params: params
callback: callback
_default_callback: (raw) ->
console.log JSON.stringify raw
# Do the actual request to server (private call)
_interact: ({action, params, callback}) ->
request
method: 'POST'
json: true
form: params
uri: "https://livetoken.io/#{action}"
(error, response, body) =>
# Define answer object
if not error and response.statusCode is 200
callback body
else
callback {State: false, Msg: "Uknown server error: #{response.statusCode}"}
|
[
{
"context": "s', (next) ->\n parse \"\"\"\n name,last name\n Boudreau,Jonathan\n \"\"\", raw: true, columns: ['FIELD_1', ",
"end": 791,
"score": 0.9366697072982788,
"start": 783,
"tag": "NAME",
"value": "Boudreau"
},
{
"context": " ->\n parse \"\"\"\n name,last nam... | test/api.raw.coffee | hei-pa/node-csv-parse | 1 |
parse = require '../src'
describe 'api raw', ->
it 'includes escape chars', (next) ->
str = """
"hello""world",LOL
"""
parse str, raw: true, escape: '"', (err, data) ->
data[0].raw.should.eql str unless err
data[0].row.should.eql [ 'hello"world', 'LOL' ] unless err
next err
it 'includes line breaks', (next) ->
parse """
hello
my
friend
""", raw: true, escape: '"', (err, data) ->
data[1].raw.should.match /\n$/ unless err
next err
it 'has the inner line breaks', (next) ->
str = """
foo,"b
a
r"
"""
parse str, raw: true, escape: '"', (err, data) ->
data[0].raw.should.eql str unless err
next err
it 'preserve columns', (next) ->
parse """
name,last name
Boudreau,Jonathan
""", raw: true, columns: ['FIELD_1', false], (err, data) ->
data[0].raw.should.eql 'name,last name\n' unless err
data[0].row.should.eql FIELD_1: 'name' unless err
next err
| 118262 |
parse = require '../src'
describe 'api raw', ->
it 'includes escape chars', (next) ->
str = """
"hello""world",LOL
"""
parse str, raw: true, escape: '"', (err, data) ->
data[0].raw.should.eql str unless err
data[0].row.should.eql [ 'hello"world', 'LOL' ] unless err
next err
it 'includes line breaks', (next) ->
parse """
hello
my
friend
""", raw: true, escape: '"', (err, data) ->
data[1].raw.should.match /\n$/ unless err
next err
it 'has the inner line breaks', (next) ->
str = """
foo,"b
a
r"
"""
parse str, raw: true, escape: '"', (err, data) ->
data[0].raw.should.eql str unless err
next err
it 'preserve columns', (next) ->
parse """
name,last name
<NAME>,<NAME>
""", raw: true, columns: ['FIELD_1', false], (err, data) ->
data[0].raw.should.eql 'name,last name\n' unless err
data[0].row.should.eql FIELD_1: 'name' unless err
next err
| true |
parse = require '../src'
describe 'api raw', ->
it 'includes escape chars', (next) ->
str = """
"hello""world",LOL
"""
parse str, raw: true, escape: '"', (err, data) ->
data[0].raw.should.eql str unless err
data[0].row.should.eql [ 'hello"world', 'LOL' ] unless err
next err
it 'includes line breaks', (next) ->
parse """
hello
my
friend
""", raw: true, escape: '"', (err, data) ->
data[1].raw.should.match /\n$/ unless err
next err
it 'has the inner line breaks', (next) ->
str = """
foo,"b
a
r"
"""
parse str, raw: true, escape: '"', (err, data) ->
data[0].raw.should.eql str unless err
next err
it 'preserve columns', (next) ->
parse """
name,last name
PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI
""", raw: true, columns: ['FIELD_1', false], (err, data) ->
data[0].raw.should.eql 'name,last name\n' unless err
data[0].row.should.eql FIELD_1: 'name' unless err
next err
|
[
{
"context": "ount = new DotLedger.Models.Account(id: 1, name: 'Some Account'))->\n view = new DotLedger.Views.Statements.Fo",
"end": 178,
"score": 0.7129579782485962,
"start": 166,
"tag": "NAME",
"value": "Some Account"
}
] | spec/javascripts/dot_ledger/views/statements/form_spec.js.coffee | timobleeker/dotledger | 0 | describe "DotLedger.Views.Statements.Form", ->
createView = (statement = new DotLedger.Models.Statement(),
account = new DotLedger.Models.Account(id: 1, name: 'Some Account'))->
view = new DotLedger.Views.Statements.Form
model: statement
account: account
view
it "should be defined", ->
expect(DotLedger.Views.Statements.Form).toBeDefined()
it "should use the correct template", ->
expect(DotLedger.Views.Statements.Form).toUseTemplate('statements/form')
it "can be rendered", ->
view = createView()
expect(view.render).not.toThrow()
it "renders the form fields", ->
view = createView().render()
expect(view.$el).toContainElement('input[name=file]')
it "renders the heading", ->
view = createView().render()
expect(view.$el).toHaveText(/Import Statement/)
it "renders the account name", ->
view = createView().render()
expect(view.$el).toHaveText(/Some Account/)
it "renders the cancel link for existing account", ->
view = createView().render()
expect(view.$el).toContainElement('a[href="/accounts/1"]')
| 25339 | describe "DotLedger.Views.Statements.Form", ->
createView = (statement = new DotLedger.Models.Statement(),
account = new DotLedger.Models.Account(id: 1, name: '<NAME>'))->
view = new DotLedger.Views.Statements.Form
model: statement
account: account
view
it "should be defined", ->
expect(DotLedger.Views.Statements.Form).toBeDefined()
it "should use the correct template", ->
expect(DotLedger.Views.Statements.Form).toUseTemplate('statements/form')
it "can be rendered", ->
view = createView()
expect(view.render).not.toThrow()
it "renders the form fields", ->
view = createView().render()
expect(view.$el).toContainElement('input[name=file]')
it "renders the heading", ->
view = createView().render()
expect(view.$el).toHaveText(/Import Statement/)
it "renders the account name", ->
view = createView().render()
expect(view.$el).toHaveText(/Some Account/)
it "renders the cancel link for existing account", ->
view = createView().render()
expect(view.$el).toContainElement('a[href="/accounts/1"]')
| true | describe "DotLedger.Views.Statements.Form", ->
createView = (statement = new DotLedger.Models.Statement(),
account = new DotLedger.Models.Account(id: 1, name: 'PI:NAME:<NAME>END_PI'))->
view = new DotLedger.Views.Statements.Form
model: statement
account: account
view
it "should be defined", ->
expect(DotLedger.Views.Statements.Form).toBeDefined()
it "should use the correct template", ->
expect(DotLedger.Views.Statements.Form).toUseTemplate('statements/form')
it "can be rendered", ->
view = createView()
expect(view.render).not.toThrow()
it "renders the form fields", ->
view = createView().render()
expect(view.$el).toContainElement('input[name=file]')
it "renders the heading", ->
view = createView().render()
expect(view.$el).toHaveText(/Import Statement/)
it "renders the account name", ->
view = createView().render()
expect(view.$el).toHaveText(/Some Account/)
it "renders the cancel link for existing account", ->
view = createView().render()
expect(view.$el).toContainElement('a[href="/accounts/1"]')
|
[
{
"context": "# Reavetard Wifi Module Tests - Author: Robbie Saunders\n# Test Linux interface configuration commands fro",
"end": 55,
"score": 0.9998611211776733,
"start": 40,
"tag": "NAME",
"value": "Robbie Saunders"
}
] | test/wifi.coffee | eibbors/reavetard | 1 | # Reavetard Wifi Module Tests - Author: Robbie Saunders
# Test Linux interface configuration commands from wifi.coffee
# Change these to match your interface names before running
DEV1 = 'wlan1'
DEV2 = 'wlan2'
DEV3 = 'eth1'
# Import wifi command `namespaces`
{airmon, iwconfig, ifconfig} = require '../src/wifi'
# airmon-ng
# -------------------------
airmon.getInterfaces (ifaces) ->
console.log 'airmon-ng compatible interfaces:\n', ifaces
airmon.getPhysicalInterfaces (phyfaces) ->
console.log 'again, by physical interface:\n', phyfaces
airmon.start "#{DEV2}", (res, output) ->
if res.enabledOn
console.log "monitor mode enabled on #{res.enabledOn}"
setTimeout((=> airmon.stop(res.enabledOn, console.log)) , 3000)
if res.processes
console.log "processes that may cause problems:", res.processes
console.log "other interfaces:", res.interfaces
# iwconfig
# -------------------------
iwconfig.run '', (err, ifaces) ->
console.log 'iwconfig returned the following interface data:\n', ifaces
iwconfig.checkWifiSetup "#{DEV1}", (err, ifaces) ->
console.log "iwconfig + select #{DEV1} data:\n", ifaces
iwconfig.checkWifiSetup 'poop', (err, ifaces) ->
console.log 'iwconfig + bogus iface:\n', err, ifaces
# ifconfig + macchanger
# -------------------------
ifconfig.all (err, ifaces) ->
console.log 'ifconfig returned following interfaces:\n', ifaces
ifconfig.down "#{DEV1}", (err, success) ->
console.log "ifconfig took #{DEV1} down? #{success or err}" | 99319 | # Reavetard Wifi Module Tests - Author: <NAME>
# Test Linux interface configuration commands from wifi.coffee
# Change these to match your interface names before running
DEV1 = 'wlan1'
DEV2 = 'wlan2'
DEV3 = 'eth1'
# Import wifi command `namespaces`
{airmon, iwconfig, ifconfig} = require '../src/wifi'
# airmon-ng
# -------------------------
airmon.getInterfaces (ifaces) ->
console.log 'airmon-ng compatible interfaces:\n', ifaces
airmon.getPhysicalInterfaces (phyfaces) ->
console.log 'again, by physical interface:\n', phyfaces
airmon.start "#{DEV2}", (res, output) ->
if res.enabledOn
console.log "monitor mode enabled on #{res.enabledOn}"
setTimeout((=> airmon.stop(res.enabledOn, console.log)) , 3000)
if res.processes
console.log "processes that may cause problems:", res.processes
console.log "other interfaces:", res.interfaces
# iwconfig
# -------------------------
iwconfig.run '', (err, ifaces) ->
console.log 'iwconfig returned the following interface data:\n', ifaces
iwconfig.checkWifiSetup "#{DEV1}", (err, ifaces) ->
console.log "iwconfig + select #{DEV1} data:\n", ifaces
iwconfig.checkWifiSetup 'poop', (err, ifaces) ->
console.log 'iwconfig + bogus iface:\n', err, ifaces
# ifconfig + macchanger
# -------------------------
ifconfig.all (err, ifaces) ->
console.log 'ifconfig returned following interfaces:\n', ifaces
ifconfig.down "#{DEV1}", (err, success) ->
console.log "ifconfig took #{DEV1} down? #{success or err}" | true | # Reavetard Wifi Module Tests - Author: PI:NAME:<NAME>END_PI
# Test Linux interface configuration commands from wifi.coffee
# Change these to match your interface names before running
DEV1 = 'wlan1'
DEV2 = 'wlan2'
DEV3 = 'eth1'
# Import wifi command `namespaces`
{airmon, iwconfig, ifconfig} = require '../src/wifi'
# airmon-ng
# -------------------------
airmon.getInterfaces (ifaces) ->
console.log 'airmon-ng compatible interfaces:\n', ifaces
airmon.getPhysicalInterfaces (phyfaces) ->
console.log 'again, by physical interface:\n', phyfaces
airmon.start "#{DEV2}", (res, output) ->
if res.enabledOn
console.log "monitor mode enabled on #{res.enabledOn}"
setTimeout((=> airmon.stop(res.enabledOn, console.log)) , 3000)
if res.processes
console.log "processes that may cause problems:", res.processes
console.log "other interfaces:", res.interfaces
# iwconfig
# -------------------------
iwconfig.run '', (err, ifaces) ->
console.log 'iwconfig returned the following interface data:\n', ifaces
iwconfig.checkWifiSetup "#{DEV1}", (err, ifaces) ->
console.log "iwconfig + select #{DEV1} data:\n", ifaces
iwconfig.checkWifiSetup 'poop', (err, ifaces) ->
console.log 'iwconfig + bogus iface:\n', err, ifaces
# ifconfig + macchanger
# -------------------------
ifconfig.all (err, ifaces) ->
console.log 'ifconfig returned following interfaces:\n', ifaces
ifconfig.down "#{DEV1}", (err, success) ->
console.log "ifconfig took #{DEV1} down? #{success or err}" |
[
{
"context": "# \n# grunt-include-bootstrap\n# https://github.com/davewasmer/grunt-include-bootstrap\n# \n# Copyright (c) 2013 D",
"end": 60,
"score": 0.9997206330299377,
"start": 50,
"tag": "USERNAME",
"value": "davewasmer"
},
{
"context": "er/grunt-include-bootstrap\n# \n# Copyrigh... | tasks/include_bootstrap.coffee | gruntjs-updater/grunt-include-bootstrap | 0 | #
# grunt-include-bootstrap
# https://github.com/davewasmer/grunt-include-bootstrap
#
# Copyright (c) 2013 Dave Wasmer
# Licensed under the MIT license.
#
path = require 'path'
module.exports = (grunt) ->
grunt.task.loadNpmTasks('grunt-contrib-less')
grunt.registerMultiTask 'include_bootstrap', 'Include the base Bootstrap in your LESS, overriden by any of your local styles or variables', ->
options = grunt.util._.extend {}, @options(), @files
options.paths or= []
options.paths.push path.resolve(path.join('node_modules','grunt-include-bootstrap','less'))
@files.forEach (f) ->
options.paths.push path.resolve path.dirname f.src
grunt.config.set 'less',
include_bootstrap:
options: options
files: @files
grunt.task.run 'less:include_bootstrap' | 63064 | #
# grunt-include-bootstrap
# https://github.com/davewasmer/grunt-include-bootstrap
#
# Copyright (c) 2013 <NAME>
# Licensed under the MIT license.
#
path = require 'path'
module.exports = (grunt) ->
grunt.task.loadNpmTasks('grunt-contrib-less')
grunt.registerMultiTask 'include_bootstrap', 'Include the base Bootstrap in your LESS, overriden by any of your local styles or variables', ->
options = grunt.util._.extend {}, @options(), @files
options.paths or= []
options.paths.push path.resolve(path.join('node_modules','grunt-include-bootstrap','less'))
@files.forEach (f) ->
options.paths.push path.resolve path.dirname f.src
grunt.config.set 'less',
include_bootstrap:
options: options
files: @files
grunt.task.run 'less:include_bootstrap' | true | #
# grunt-include-bootstrap
# https://github.com/davewasmer/grunt-include-bootstrap
#
# Copyright (c) 2013 PI:NAME:<NAME>END_PI
# Licensed under the MIT license.
#
path = require 'path'
module.exports = (grunt) ->
grunt.task.loadNpmTasks('grunt-contrib-less')
grunt.registerMultiTask 'include_bootstrap', 'Include the base Bootstrap in your LESS, overriden by any of your local styles or variables', ->
options = grunt.util._.extend {}, @options(), @files
options.paths or= []
options.paths.push path.resolve(path.join('node_modules','grunt-include-bootstrap','less'))
@files.forEach (f) ->
options.paths.push path.resolve path.dirname f.src
grunt.config.set 'less',
include_bootstrap:
options: options
files: @files
grunt.task.run 'less:include_bootstrap' |
[
{
"context": "d = this.inputs.profile_id;\n this.user.password = this.inputs.password;\n ",
"end": 207,
"score": 0.9662841558456421,
"start": 187,
"tag": "PASSWORD",
"value": "this.inputs.password"
}
] | resources/assets/js/admininfo/methods/updateUser.coffee | xavierauana/sbctemp | 0 | module.exports = ->
console.log('Put to server and update user');
this.user.loginName = this.inputs.loginName;
this.user.profile_id = this.inputs.profile_id;
this.user.password = this.inputs.password;
| 153578 | module.exports = ->
console.log('Put to server and update user');
this.user.loginName = this.inputs.loginName;
this.user.profile_id = this.inputs.profile_id;
this.user.password = <PASSWORD>;
| true | module.exports = ->
console.log('Put to server and update user');
this.user.loginName = this.inputs.loginName;
this.user.profile_id = this.inputs.profile_id;
this.user.password = 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.