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": " hubot XXX [<args>] - DESCRIPTION\n#\n# Author:\n# bouzuya <m@bouzuya.net>\n#\nmodule.exports = (robot) ->\n r", "end": 179, "score": 0.9997251629829407, "start": 172, "tag": "USERNAME", "value": "bouzuya" }, { "context": "X [<args>] - DESCRIPTION\n#\n# Author:\n# bouzuya <m@bouzuya.net>\n#\nmodule.exports = (robot) ->\n rot13 = (keyword", "end": 194, "score": 0.9999300241470337, "start": 181, "tag": "EMAIL", "value": "m@bouzuya.net" } ]
src/scripts/rot13.coffee
bouzuya/hubot-rot13
1
# Description # A Hubot script that DESCRIPTION # # Dependencies: # None # # Configuration: # None # # Commands: # hubot XXX [<args>] - DESCRIPTION # # Author: # bouzuya <m@bouzuya.net> # module.exports = (robot) -> rot13 = (keyword) -> original = 'abcdefghijklmnopqrstuvwxyz' keyword .split '' .map (c) -> index = original.indexOf(c) if index >= 0 then original.charAt((index + 13) % 26) else c .join '' robot.respond /rot13\s+(.+)$/i, (res) -> keyword = res.match[1] converted = rot13(keyword) res.send converted
73217
# Description # A Hubot script that DESCRIPTION # # Dependencies: # None # # Configuration: # None # # Commands: # hubot XXX [<args>] - DESCRIPTION # # Author: # bouzuya <<EMAIL>> # module.exports = (robot) -> rot13 = (keyword) -> original = 'abcdefghijklmnopqrstuvwxyz' keyword .split '' .map (c) -> index = original.indexOf(c) if index >= 0 then original.charAt((index + 13) % 26) else c .join '' robot.respond /rot13\s+(.+)$/i, (res) -> keyword = res.match[1] converted = rot13(keyword) res.send converted
true
# Description # A Hubot script that DESCRIPTION # # Dependencies: # None # # Configuration: # None # # Commands: # hubot XXX [<args>] - DESCRIPTION # # Author: # bouzuya <PI:EMAIL:<EMAIL>END_PI> # module.exports = (robot) -> rot13 = (keyword) -> original = 'abcdefghijklmnopqrstuvwxyz' keyword .split '' .map (c) -> index = original.indexOf(c) if index >= 0 then original.charAt((index + 13) % 26) else c .join '' robot.respond /rot13\s+(.+)$/i, (res) -> keyword = res.match[1] converted = rot13(keyword) res.send converted
[ { "context": " secretLock = (\"00\": bytes);\n secretKey = (\"00\": bytes) ];\n \n const states_INVALID : nat =", "end": 18050, "score": 0.9604810476303101, "start": 18049, "tag": "KEY", "value": "0" }, { "context": "ecretLock = secretLock_;\n secretKey = (\"00\": bytes) (* args: 0 *) ];\n test_self.swaps", "end": 19464, "score": 0.9413830637931824, "start": 19463, "tag": "KEY", "value": "0" } ]
test/translate_ligo_online_examples.coffee
madfish-solutions/sol2ligo
66
config = require "../src/config" { translate_ligo_make_test : make_test } = require("./util") describe "translate ligo online examples", ()-> @timeout 10000 # NOTE some duplication with other tests # ################################################################################################### it "int arithmetic", ()-> text_i = """ pragma solidity ^0.5.11; contract Arith { int public value; function arith() public returns (int ret_val) { int a = 0; int b = 0; int c = 0; c = -c; c = a + b; c = a - b; c = a * b; c = a / b; return c; } } """#" text_o = """ type arith_args is record callbackAddress : address; end; type state is record value : int; end; type router_enum is | Arith of arith_args; function arith (const #{config.reserved}__unit : unit) : (int) is block { const ret_val : int = 0; const a : int = 0; const b : int = 0; const c : int = 0; c := -(c); c := (a + b); c := (a - b); c := (a * b); c := (a / b); } with (c); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Arith(match_action) -> block { const tmp : (int) = arith(unit); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(int))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "uint arithmetic", ()-> text_i = """ pragma solidity ^0.5.11; contract Arith { uint public value; function arith() public returns (uint ret_val) { uint a = 0; uint b = 0; uint c = 0; c = a + b; c = a * b; c = a / b; c = a | b; c = a & b; c = a ^ b; return c; } } """#" text_o = """ type arith_args is record callbackAddress : address; end; type state is record value : nat; end; type router_enum is | Arith of arith_args; function arith (const #{config.reserved}__unit : unit) : (nat) is block { const ret_val : nat = 0n; const a : nat = 0n; const b : nat = 0n; const c : nat = 0n; c := (a + b); c := (a * b); c := (a / b); c := Bitwise.or(a, b); c := Bitwise.and(a, b); c := Bitwise.xor(a, b); } with (c); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Arith(match_action) -> block { const tmp : (nat) = arith(unit); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(nat))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "if", ()-> text_i = """ pragma solidity ^0.5.11; contract Ifer { uint public value; function ifer() public returns (uint) { uint x = 6; if (x == 5) { x += 1; } else { x += 10; } return x; } } """#" text_o = """ type ifer_args is record callbackAddress : address; end; type state is record value : nat; end; type router_enum is | Ifer of ifer_args; function ifer (const #{config.reserved}__unit : unit) : (nat) is block { const x : nat = 6n; if (x = 5n) then block { x := (x + 1n); } else block { x := (x + 10n); }; } with (x); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Ifer(match_action) -> block { const tmp : (nat) = ifer(unit); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(nat))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "for", ()-> text_i = """ pragma solidity ^0.5.11; contract Forer { uint public value; function forer() public returns (uint ret_val) { uint y = 0; for (uint i=0; i<5; i+=1) { y += 1; } return y; } } """#" text_o = """ type forer_args is record callbackAddress : address; end; type state is record value : nat; end; type router_enum is | Forer of forer_args; function forer (const #{config.reserved}__unit : unit) : (nat) is block { const ret_val : nat = 0n; const y : nat = 0n; const i : nat = 0n; while (i < 5n) block { y := (y + 1n); i := (i + 1n); }; } with (y); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Forer(match_action) -> block { const tmp : (nat) = forer(unit); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(nat))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "while", ()-> text_i = """ pragma solidity ^0.5.11; contract Whiler { uint public value; function whiler() public returns (uint ret_val) { uint y = 0; while (y != 2) { y += 1; } return y; } } """#" text_o = """ type whiler_args is record callbackAddress : address; end; type state is record value : nat; end; type router_enum is | Whiler of whiler_args; function whiler (const #{config.reserved}__unit : unit) : (nat) is block { const ret_val : nat = 0n; const y : nat = 0n; while (y =/= 2n) block { y := (y + 1n); }; } with (y); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Whiler(match_action) -> block { const tmp : (nat) = whiler(unit); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(nat))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "fn call", ()-> text_i = """ pragma solidity ^0.5.11; contract Fn_call { int public value; function fn1(int a) public returns (int ret_val) { value += 1; return a; } function fn2() public returns (int ret_val) { fn1(1); int res = 1; return res; } } """#" text_o = """ type fn1_args is record a : int; callbackAddress : address; end; type fn2_args is record callbackAddress : address; end; type state is record value : int; end; type router_enum is | Fn1 of fn1_args | Fn2 of fn2_args; function fn1 (const contract_storage : state; const a : int) : (state * int) is block { const ret_val : int = 0; contract_storage.value := (contract_storage.value + 1); } with (contract_storage, a); function fn2 (const contract_storage : state) : (state * int) is block { const ret_val : int = 0; const tmp_0 : (state * int) = fn1(contract_storage, 1); contract_storage := tmp_0.0; const res : int = 1; } with (contract_storage, res); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Fn1(match_action) -> block { const tmp : (state * int) = fn1(contract_storage, match_action.a); var opList : list(operation) := list transaction((tmp.0), 0mutez, (get_contract(match_action.callbackAddress) : contract(state))) end; } with ((opList, tmp.0)) | Fn2(match_action) -> block { const tmp : (state * int) = fn2(contract_storage); var opList : list(operation) := list transaction((tmp.0), 0mutez, (get_contract(match_action.callbackAddress) : contract(state))) end; } with ((opList, tmp.0)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "simplecoin", ()-> text_i = """ pragma solidity ^0.5.11; contract Coin { address minter; mapping (address => uint) balances; constructor() public { minter = msg.sender; } function mint(address owner, uint amount) public { if (msg.sender == minter) { balances[owner] += amount; } } function send(address receiver, uint amount) public { if (balances[msg.sender] >= amount) { balances[msg.sender] -= amount; balances[receiver] += amount; } } function queryBalance(address addr) public view returns (uint balance) { return balances[addr]; } } """#" text_o = """ type constructor_args is unit; type mint_args is record owner : address; #{config.reserved}__amount : nat; end; type send_args is record receiver : address; #{config.reserved}__amount : nat; end; type queryBalance_args is record addr : address; callbackAddress : address; end; type state is record minter : address; balances : map(address, nat); end; type router_enum is | Constructor of constructor_args | Mint of mint_args | Send of send_args | QueryBalance of queryBalance_args; function constructor (const contract_storage : state) : (state) is block { contract_storage.minter := Tezos.sender; } with (contract_storage); function mint (const contract_storage : state; const owner : address; const #{config.reserved}__amount : nat) : (state) is block { if (Tezos.sender = contract_storage.minter) then block { contract_storage.balances[owner] := ((case contract_storage.balances[owner] of | None -> 0n | Some(x) -> x end) + #{config.reserved}__amount); } else block { skip }; } with (contract_storage); function send (const contract_storage : state; const receiver : address; const #{config.reserved}__amount : nat) : (state) is block { if ((case contract_storage.balances[Tezos.sender] of | None -> 0n | Some(x) -> x end) >= #{config.reserved}__amount) then block { contract_storage.balances[Tezos.sender] := abs((case contract_storage.balances[Tezos.sender] of | None -> 0n | Some(x) -> x end) - #{config.reserved}__amount); contract_storage.balances[receiver] := ((case contract_storage.balances[receiver] of | None -> 0n | Some(x) -> x end) + #{config.reserved}__amount); } else block { skip }; } with (contract_storage); function queryBalance (const contract_storage : state; const addr : address) : (nat) is block { const #{config.reserved}__balance : nat = 0n; } with ((case contract_storage.balances[addr] of | None -> 0n | Some(x) -> x end)); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Constructor(match_action) -> ((nil: list(operation)), constructor(contract_storage)) | Mint(match_action) -> ((nil: list(operation)), mint(contract_storage, match_action.owner, match_action.#{config.reserved}__amount)) | Send(match_action) -> ((nil: list(operation)), send(contract_storage, match_action.receiver, match_action.#{config.reserved}__amount)) | QueryBalance(match_action) -> block { const tmp : (nat) = queryBalance(contract_storage, match_action.addr); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(nat))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "AtomicSwap", ()-> text_i = """ pragma solidity ^0.4.18; contract AtomicSwapEther { struct Swap { uint256 timelock; uint256 value; address ethTrader; address withdrawTrader; bytes32 secretLock; bytes secretKey; } enum States { INVALID, OPEN, CLOSED, EXPIRED } mapping (bytes32 => Swap) private swaps; mapping (bytes32 => States) private swapStates; event Open(bytes32 _swapID, address _withdrawTrader,bytes32 _secretLock); event Expire(bytes32 _swapID); event Close(bytes32 _swapID, bytes _secretKey); modifier onlyInvalidSwaps(bytes32 _swapID) { require (swapStates[_swapID] == States.INVALID); _; } modifier onlyOpenSwaps(bytes32 _swapID) { require (swapStates[_swapID] == States.OPEN); _; } modifier onlyClosedSwaps(bytes32 _swapID) { require (swapStates[_swapID] == States.CLOSED); _; } modifier onlyExpirableSwaps(bytes32 _swapID) { require (now >= swaps[_swapID].timelock); _; } modifier onlyWithSecretKey(bytes32 _swapID, bytes _secretKey) { // TODO: Require _secretKey length to conform to the spec require (swaps[_swapID].secretLock == sha256(_secretKey)); _; } function open(bytes32 _swapID, address _withdrawTrader, bytes32 _secretLock, uint256 _timelock) public onlyInvalidSwaps(_swapID) payable { // Store the details of the swap. Swap memory swap = Swap({ timelock: _timelock, value: msg.value, ethTrader: msg.sender, withdrawTrader: _withdrawTrader, secretLock: _secretLock, secretKey: new bytes(0) }); swaps[_swapID] = swap; swapStates[_swapID] = States.OPEN; // Trigger open event. Open(_swapID, _withdrawTrader, _secretLock); } function close(bytes32 _swapID, bytes _secretKey) public onlyOpenSwaps(_swapID) onlyWithSecretKey(_swapID, _secretKey) { // Close the swap. Swap memory swap = swaps[_swapID]; swaps[_swapID].secretKey = _secretKey; swapStates[_swapID] = States.CLOSED; // Transfer the ETH funds from this contract to the withdrawing trader. swap.withdrawTrader.transfer(swap.value); // Trigger close event. Close(_swapID, _secretKey); } function expire(bytes32 _swapID) public onlyOpenSwaps(_swapID) onlyExpirableSwaps(_swapID) { // Expire the swap. Swap memory swap = swaps[_swapID]; swapStates[_swapID] = States.EXPIRED; // Transfer the ETH value from this contract back to the ETH trader. swap.ethTrader.transfer(swap.value); // Trigger expire event. Expire(_swapID); } function check(bytes32 _swapID) public view returns (uint256 timelock, uint256 value, address withdrawTrader, bytes32 secretLock) { Swap memory swap = swaps[_swapID]; return (swap.timelock, swap.value, swap.withdrawTrader, swap.secretLock); } function checkSecretKey(bytes32 _swapID) public view onlyClosedSwaps(_swapID) returns (bytes secretKey) { Swap memory swap = swaps[_swapID]; return swap.secretKey; } } """#" text_o = """ type atomicSwapEther_Swap is record timelock : nat; value : nat; ethTrader : address; withdrawTrader : address; secretLock : bytes; secretKey : bytes; end; type open_args is record swapID_ : bytes; withdrawTrader_ : address; secretLock_ : bytes; timelock_ : nat; end; type close_args is record swapID_ : bytes; secretKey_ : bytes; end; type expire_args is record swapID_ : bytes; end; type check_args is record swapID_ : bytes; callbackAddress : address; end; type checkSecretKey_args is record swapID_ : bytes; callbackAddress : address; end; type state is record swaps : map(bytes, atomicSwapEther_Swap); swapStates : map(bytes, nat); end; const burn_address : address = ("tz1ZZZZZZZZZZZZZZZZZZZZZZZZZZZZNkiRg" : address); const atomicSwapEther_Swap_default : atomicSwapEther_Swap = record [ timelock = 0n; value = 0n; ethTrader = burn_address; withdrawTrader = burn_address; secretLock = ("00": bytes); secretKey = ("00": bytes) ]; const states_INVALID : nat = 0n; const states_OPEN : nat = 1n; const states_CLOSED : nat = 2n; const states_EXPIRED : nat = 3n; type router_enum is | Open of open_args | Close of close_args | Expire of expire_args | Check of check_args | CheckSecretKey of checkSecretKey_args; (* EventDefinition Open(swapID_ : bytes; withdrawTrader_ : address; secretLock_ : bytes) *) (* EventDefinition Expire(swapID_ : bytes) *) (* EventDefinition Close(swapID_ : bytes; secretKey_ : bytes) *) (* enum States converted into list of nats *) (* modifier onlyInvalidSwaps inlined *) (* modifier onlyOpenSwaps inlined *) (* modifier onlyClosedSwaps inlined *) (* modifier onlyExpirableSwaps inlined *) (* modifier onlyWithSecretKey inlined *) function open (const test_self : state; const swapID_ : bytes; const withdrawTrader_ : address; const secretLock_ : bytes; const timelock_ : nat) : (state) is block { assert(((case test_self.swapStates[swapID_] of | None -> 0n | Some(x) -> x end) = states_INVALID)); const swap : atomicSwapEther_Swap = record [ timelock = timelock_; value = (amount / 1mutez); ethTrader = Tezos.sender; withdrawTrader = withdrawTrader_; secretLock = secretLock_; secretKey = ("00": bytes) (* args: 0 *) ]; test_self.swaps[swapID_] := swap; test_self.swapStates[swapID_] := states_OPEN; (* EmitStatement Open(_swapID, _withdrawTrader, _secretLock) *) } with (test_self); function close (const opList : list(operation); const test_self : state; const swapID_ : bytes; const secretKey_ : bytes) : (list(operation) * state) is block { assert(((case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end).secretLock = sha_256(secretKey_))); assert(((case test_self.swapStates[swapID_] of | None -> 0n | Some(x) -> x end) = states_OPEN)); const swap : atomicSwapEther_Swap = (case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end); test_self.swaps[swapID_].secretKey := secretKey_; test_self.swapStates[swapID_] := states_CLOSED; const op0 : operation = transaction((unit), (swap.value * 1mutez), (get_contract(swap.withdrawTrader) : contract(unit))); (* EmitStatement Close(_swapID, _secretKey) *) } with (list [op0], test_self); function expire (const opList : list(operation); const test_self : state; const swapID_ : bytes) : (list(operation) * state) is block { assert((abs(now - ("1970-01-01T00:00:00Z" : timestamp)) >= (case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end).timelock)); assert(((case test_self.swapStates[swapID_] of | None -> 0n | Some(x) -> x end) = states_OPEN)); const swap : atomicSwapEther_Swap = (case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end); test_self.swapStates[swapID_] := states_EXPIRED; const op0 : operation = transaction((unit), (swap.value * 1mutez), (get_contract(swap.ethTrader) : contract(unit))); (* EmitStatement Expire(_swapID) *) } with (list [op0], test_self); function check (const test_self : state; const swapID_ : bytes) : ((nat * nat * address * bytes)) is block { const timelock : nat = 0n; const value : nat = 0n; const withdrawTrader : address = burn_address; const secretLock : bytes = ("00": bytes); const swap : atomicSwapEther_Swap = (case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end); } with ((swap.timelock, swap.value, swap.withdrawTrader, swap.secretLock)); function checkSecretKey (const test_self : state; const swapID_ : bytes) : (bytes) is block { assert(((case test_self.swapStates[swapID_] of | None -> 0n | Some(x) -> x end) = states_CLOSED)); const secretKey : bytes = ("00": bytes); const swap : atomicSwapEther_Swap = (case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end); } with (swap.secretKey); function main (const action : router_enum; const test_self : state) : (list(operation) * state) is (case action of | Open(match_action) -> ((nil: list(operation)), open(test_self, match_action.swapID_, match_action.withdrawTrader_, match_action.secretLock_, match_action.timelock_)) | Close(match_action) -> close((nil: list(operation)), test_self, match_action.swapID_, match_action.secretKey_) | Expire(match_action) -> expire((nil: list(operation)), test_self, match_action.swapID_) | Check(match_action) -> block { const tmp : ((nat * nat * address * bytes)) = check(test_self, match_action.swapID_); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract((nat * nat * address * bytes)))) end; } with ((opList, test_self)) | CheckSecretKey(match_action) -> block { const tmp : (bytes) = checkSecretKey(test_self, match_action.swapID_); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(bytes))) end; } with ((opList, test_self)) end); """#" make_test text_i, text_o, router: true # ################################################################################################### it "Dice", ()-> text_i = """ pragma solidity ^0.4.24; // * dice2.win - fair games that pay Ether. Version 5. // // * Ethereum smart contract, deployed at 0xD1CEeeeee83F8bCF3BEDad437202b6154E9F5405. // // * Uses hybrid commit-reveal + block hash random number generation that is immune // to tampering by players, house and miners. Apart from being fully transparent, // this also allows arbitrarily high bets. // // * Refer to https://dice2.win/whitepaper.pdf for detailed description and proofs. contract Dice2Win { /// *** Constants section // Each bet is deducted 1% in favour of the house, but no less than some minimum. // The lower bound is dictated by gas costs of the settleBet transaction, providing // headroom for up to 10 Gwei prices. uint256 constant HOUSE_EDGE_PERCENT = 1; uint256 constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0003 ether; // Bets lower than this amount do not participate in jackpot rolls (and are // not deducted JACKPOT_FEE). uint256 constant MIN_JACKPOT_BET = 0.1 ether; // Chance to win jackpot (currently 0.1%) and fee deducted into jackpot fund. uint256 constant JACKPOT_MODULO = 1000; uint256 constant JACKPOT_FEE = 0.001 ether; // There is minimum and maximum bets. uint256 constant MIN_BET = 0.01 ether; uint256 constant MAX_AMOUNT = 300000 ether; // Modulo is a number of equiprobable outcomes in a game: // - 2 for coin flip // - 6 for dice // - 6*6 = 36 for double dice // - 100 for etheroll // - 37 for roulette // etc. // It's called so because 256-bit entropy is treated like a huge integer and // the remainder of its division by modulo is considered bet outcome. uint256 constant MAX_MODULO = 100; // For modulos below this threshold rolls are checked against a bit mask, // thus allowing betting on any combination of outcomes. For example, given // modulo 6 for dice, 101000 mask (base-2, big endian) means betting on // 4 and 6; for games with modulos higher than threshold (Etheroll), a simple // limit is used, allowing betting on any outcome in [0, N) range. // // The specific value is dictated by the fact that 256-bit intermediate // multiplication result allows implementing population count efficiently // for numbers that are up to 42 bits, and 40 is the highest multiple of // eight below 42. uint256 constant MAX_MASK_MODULO = 40; // This is a check on bet mask overflow. uint256 constant MAX_BET_MASK = 2**MAX_MASK_MODULO; // EVM BLOCKHASH opcode can query no further than 256 blocks into the // past. Given that settleBet uses block hash of placeBet as one of // complementary entropy sources, we cannot process bets older than this // threshold. On rare occasions dice2.win croupier may fail to invoke // settleBet in this timespan due to technical issues or extreme Ethereum // congestion; such bets can be refunded via invoking refundBet. uint256 constant BET_EXPIRATION_BLOCKS = 250; // Some deliberately invalid address to initialize the secret signer with. // Forces maintainers to invoke setSecretSigner before processing any bets. address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // Standard contract ownership transfer. address public owner; address private nextOwner; // Adjustable max bet profit. Used to cap bets against dynamic odds. uint256 public maxProfit; // The address corresponding to a private key used to sign placeBet commits. address public secretSigner; // Accumulated jackpot fund. uint128 public jackpotSize; // Funds that are locked in potentially winning bets. Prevents contract from // committing to bets it cannot pay out. uint128 public lockedInBets; // A structure representing a single bet. struct Bet { // Wager amount in wei. uint256 amount; // Modulo of a game. uint8 modulo; // Number of winning outcomes, used to compute winning payment (* modulo/rollUnder), // and used instead of mask for games with modulo > MAX_MASK_MODULO. uint8 rollUnder; // Block number of placeBet tx. uint40 placeBlockNumber; // Bit mask representing winning bet outcomes (see MAX_MASK_MODULO comment). uint40 mask; // Address of a gambler, used to pay out winning bets. address gambler; } // Mapping from commits to all currently active & processed bets. mapping(uint256 => Bet) bets; // Croupier account. address public croupier; // Events that are issued to make statistic recovery easier. event FailedPayment(address indexed beneficiary, uint256 amount); event Payment(address indexed beneficiary, uint256 amount); event JackpotPayment(address indexed beneficiary, uint256 amount); // This event is emitted in placeBet to record commit in the logs. event Commit(uint256 commit); // Constructor. Deliberately does not take any parameters. constructor() public { owner = msg.sender; secretSigner = DUMMY_ADDRESS; croupier = DUMMY_ADDRESS; } // Standard modifier on methods invokable only by contract owner. modifier onlyOwner { require(msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } // Standard modifier on methods invokable only by contract owner. modifier onlyCroupier { require( msg.sender == croupier, "OnlyCroupier methods called by non-croupier." ); _; } // Standard contract ownership transfer implementation, function approveNextOwner(address _nextOwner) external onlyOwner { require(_nextOwner != owner, "Cannot approve current owner."); nextOwner = _nextOwner; } function acceptNextOwner() external { require( msg.sender == nextOwner, "Can only accept preapproved new owner." ); owner = nextOwner; } // Fallback function deliberately left empty. It's primary use case // is to top up the bank roll. function() public payable {} // See comment for "secretSigner" variable. function setSecretSigner(address newSecretSigner) external onlyOwner { secretSigner = newSecretSigner; } // Change the croupier address. function setCroupier(address newCroupier) external onlyOwner { croupier = newCroupier; } // Change max bet reward. Setting this to zero effectively disables betting. function setMaxProfit(uint256 _maxProfit) public onlyOwner { require(_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number."); maxProfit = _maxProfit; } // This function is used to bump up the jackpot fund. Cannot be used to lower it. function increaseJackpot(uint256 increaseAmount) external onlyOwner { require( increaseAmount <= address(this).balance, "Increase amount larger than balance." ); require( jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds." ); jackpotSize += uint128(increaseAmount); } // Funds withdrawal to cover costs of dice2.win operation. function withdrawFunds(address beneficiary, uint256 withdrawAmount) external onlyOwner { require( withdrawAmount <= address(this).balance, "Increase amount larger than balance." ); require( jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds." ); sendFunds(beneficiary, withdrawAmount, withdrawAmount); } // Contract may be destroyed only when there are no ongoing bets, // either settled or refunded. All funds are transferred to contract owner. function kill() external onlyOwner { require( lockedInBets == 0, "All bets should be processed (settled or refunded) before test_self-destruct." ); selfdestruct(owner); } /// *** Betting logic // Bet states: // amount == 0 && gambler == 0 - 'clean' (can place a bet) // amount != 0 && gambler != 0 - 'active' (can be settled or refunded) // amount == 0 && gambler != 0 - 'processed' (can clean storage) // // NOTE: Storage cleaning is not implemented in this contract version; it will be added // with the next upgrade to prevent polluting Ethereum state with expired bets. // Bet placing transaction - issued by the player. // betMask - bet outcomes bit mask for modulo <= MAX_MASK_MODULO, // [0, betMask) for larger modulos. // modulo - game modulo. // commitLastBlock - number of the maximum block where "commit" is still considered valid. // commit - Keccak256 hash of some secret "reveal" random number, to be supplied // by the dice2.win croupier bot in the settleBet transaction. Supplying // "commit" ensures that "reveal" cannot be changed behind the scenes // after placeBet have been mined. // r, s - components of ECDSA signature of (commitLastBlock, commit). v is // guaranteed to always equal 27. // // Commit, being essentially random 256-bit number, is used as a unique bet identifier in // the 'bets' mapping. // // Commits are signed with a block limit to ensure that they are used at most once - otherwise // it would be possible for a miner to place a bet with a known commit/reveal pair and tamper // with the blockhash. Croupier guarantees that commitLastBlock will always be not greater than // placeBet block number plus BET_EXPIRATION_BLOCKS. See whitepaper for details. function placeBet( uint256 betMask, uint256 modulo, uint256 commitLastBlock, uint256 commit, bytes32 r, bytes32 s ) external payable { // Check that the bet is in 'clean' state. Bet storage bet = bets[commit]; require(bet.gambler == address(0), "Bet should be in a 'clean' _state."); // Validate input data ranges. uint256 amount = msg.value; require( modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range." ); require( amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range." ); require( betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range." ); // Check that commit is valid - it has not expired and its signature is valid. require(block.number <= commitLastBlock, "Commit has expired."); bytes32 signatureHash = keccak256( abi.encodePacked(uint40(commitLastBlock), commit) ); require( secretSigner == ecrecover(signatureHash, 27, r, s), "ECDSA signature is not valid." ); uint256 rollUnder; uint256 mask; if (modulo <= MAX_MASK_MODULO) { // Small modulo games specify bet outcomes via bit mask. // rollUnder is a number of 1 bits in this mask (population count). // This magic looking formula is an efficient way to compute population // count on EVM for numbers below 2**40. For detailed proof consult // the dice2.win whitepaper. rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO; mask = betMask; } else { // Larger modulos specify the right edge of half-open interval of // winning bet outcomes. require( betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo." ); rollUnder = betMask; } // Winning amount and jackpot increase. uint256 possibleWinAmount; uint256 jackpotFee; (possibleWinAmount, jackpotFee) = getDiceWinAmount( amount, modulo, rollUnder ); // Enforce max profit limit. require( possibleWinAmount <= amount + maxProfit, "maxProfit limit violation." ); // Lock funds. lockedInBets += uint128(possibleWinAmount); jackpotSize += uint128(jackpotFee); // Check whether contract has enough funds to process this bet. require( jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet." ); // Record commit in logs. emit Commit(commit); // Store bet parameters on blockchain. bet.amount = amount; bet.modulo = uint8(modulo); bet.rollUnder = uint8(rollUnder); bet.placeBlockNumber = uint40(block.number); bet.mask = uint40(mask); bet.gambler = msg.sender; } // This is the method used to settle 99% of bets. To process a bet with a specific // "commit", settleBet should supply a "reveal" number that would Keccak256-hash to // "commit". "blockHash" is the block hash of placeBet block as seen by croupier; it // is additionally asserted to prevent changing the bet outcomes on Ethereum reorgs. function settleBet(uint256 reveal, bytes32 blockHash) external onlyCroupier { uint256 commit = uint256(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; uint256 placeBlockNumber = bet.placeBlockNumber; // Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS). require( block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before." ); require( block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM." ); require(blockhash(placeBlockNumber) == blockHash); // Settle bet using reveal and blockHash as entropy sources. settleBetCommon(bet, reveal, blockHash); } // This method is used to settle a bet that was mined into an uncle block. At this // point the player was shown some bet outcome, but the blockhash at placeBet height // is different because of Ethereum chain reorg. We supply a full merkle proof of the // placeBet transaction receipt to provide untamperable evidence that uncle block hash // indeed was present on-chain at some point. function settleBetUncleMerkleProof( uint256 reveal, uint40 canonicalBlockNumber ) external onlyCroupier { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint256 commit = uint256(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; // Check that canonical block hash can still be verified. require( block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM." ); // Verify placeBet receipt. requireCorrectReceipt(4 + 32 + 32 + 4); // Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them. bytes32 canonicalHash; bytes32 uncleHash; (canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32); require(blockhash(canonicalBlockNumber) == canonicalHash); // Settle bet using reveal and uncleHash as entropy sources. settleBetCommon(bet, reveal, uncleHash); } // Common settlement code for settleBet & settleBetUncleMerkleProof. function settleBetCommon( Bet storage bet, uint256 reveal, bytes32 entropyBlockHash ) private { // Fetch bet parameters into local variables (to save gas). uint256 amount = bet.amount; uint256 modulo = bet.modulo; uint256 rollUnder = bet.rollUnder; address gambler = bet.gambler; // Check that bet is in 'active' state. require(amount != 0, "Bet should be in an 'active' _state"); // Move bet into 'processed' state already. bet.amount = 0; // The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners // are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256 // preimage is intractable), and house is unable to alter the "reveal" after // placeBet have been mined (as Keccak256 collision finding is also intractable). bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash)); // Do a roll by taking a modulo of entropy. Compute winning amount. uint256 dice = uint256(entropy) % modulo; uint256 diceWinAmount; uint256 _jackpotFee; (diceWinAmount, _jackpotFee) = getDiceWinAmount( amount, modulo, rollUnder ); uint256 diceWin = 0; uint256 jackpotWin = 0; // Determine dice outcome. if (modulo <= MAX_MASK_MODULO) { // For small modulo games, check the outcome against a bit mask. if ((2**dice) & bet.mask != 0) { diceWin = diceWinAmount; } } else { // For larger modulos, check inclusion into half-open interval. if (dice < rollUnder) { diceWin = diceWinAmount; } } // Unlock the bet amount, regardless of the outcome. lockedInBets -= uint128(diceWinAmount); // Roll for a jackpot (if eligible). if (amount >= MIN_JACKPOT_BET) { // The second modulo, statistically independent from the "main" dice roll. // Effectively you are playing two games at once! uint256 jackpotRng = (uint256(entropy) / modulo) % JACKPOT_MODULO; // Bingo! if (jackpotRng == 0) { jackpotWin = jackpotSize; jackpotSize = 0; } } // Log jackpot win. if (jackpotWin > 0) { emit JackpotPayment(gambler, jackpotWin); } // Send the funds to gambler. sendFunds( gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin ); } // Refund transaction - return the bet amount of a roll that was not processed in a // due timeframe. Processing such blocks is not possible due to EVM limitations (see // BET_EXPIRATION_BLOCKS comment above for details). In case you ever find yourself // in a situation like this, just contact the dice2.win support, however nothing // precludes you from invoking this method yourself. function refundBet(uint256 commit) external { // Check that bet is in 'active' state. Bet storage bet = bets[commit]; uint256 amount = bet.amount; require(amount != 0, "Bet should be in an 'active' _state"); // Check that bet has already expired. require( block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM." ); // Move bet into 'processed' state, release funds. bet.amount = 0; uint256 diceWinAmount; uint256 jackpotFee; (diceWinAmount, jackpotFee) = getDiceWinAmount( amount, bet.modulo, bet.rollUnder ); lockedInBets -= uint128(diceWinAmount); jackpotSize -= uint128(jackpotFee); // Send the refund. sendFunds(bet.gambler, amount, amount); } // Get the expected win amount after house edge is subtracted. function getDiceWinAmount(uint256 amount, uint256 modulo, uint256 rollUnder) private pure returns (uint256 winAmount, uint256 jackpotFee) { require( 0 < rollUnder && rollUnder <= modulo, "Win probability out of range." ); jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0; uint256 houseEdge = (amount * HOUSE_EDGE_PERCENT) / 100; if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) { houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT; } require( houseEdge + jackpotFee <= amount, "Bet doesn't even cover house edge." ); winAmount = ((amount - houseEdge - jackpotFee) * modulo) / rollUnder; } // Helper routine to process the payment. function sendFunds( address beneficiary, uint256 amount, uint256 successLogAmount ) private { if (beneficiary.send(amount)) { emit Payment(beneficiary, successLogAmount); } else { emit FailedPayment(beneficiary, amount); } } // This are some constants making O(1) population count in placeBet possible. // See whitepaper for intuition and proofs behind it. uint256 constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001; uint256 constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041; uint256 constant POPCNT_MODULO = 0x3F; // *** Merkle proofs. // This helpers are used to verify cryptographic proofs of placeBet inclusion into // uncle blocks. They are used to prevent bet outcome changing on Ethereum reorgs without // compromising the security of the smart contract. Proof data is appended to the input data // in a simple prefix length format and does not adhere to the ABI. // Invariants checked: // - receipt trie entry contains a (1) successful transaction (2) directed at this smart // contract (3) containing commit as a payload. // - receipt trie entry is a part of a valid merkle proof of a block header // - the block header is a part of uncle list of some block on canonical chain // The implementation is optimized for gas cost and relies on the specifics of Ethereum internal data structures. // Read the whitepaper for details. // Helper to verify a full merkle proof starting from some seedHash (usually commit). "offset" is the location of the proof // beginning in the calldata. function verifyMerkleProof(uint256 seedHash, uint256 offset) private pure returns (bytes32 blockHash, bytes32 uncleHash) { // (Safe) assumption - nobody will write into RAM during this method invocation. uint256 scratchBuf1; assembly { scratchBuf1 := mload(0x40) } uint256 uncleHeaderLength; uint256 blobLength; uint256 shift; uint256 hashSlot; // Verify merkle proofs up to uncle block header. Calldata layout is: // - 2 byte big-endian slice length // - 2 byte big-endian offset to the beginning of previous slice hash within the current slice (should be zeroed) // - followed by the current slice verbatim for (; ; offset += blobLength) { assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) } if (blobLength == 0) { // Zero slice length marks the end of uncle proof. break; } assembly { shift := and(calldataload(sub(offset, 28)), 0xffff) } require(shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly { hashSlot := calldataload(add(offset, shift)) } require(hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) seedHash := sha3(scratchBuf1, blobLength) uncleHeaderLength := blobLength } } // At this moment the uncle hash is known. uncleHash = bytes32(seedHash); // Construct the uncle list of a canonical block. uint256 scratchBuf2 = scratchBuf1 + uncleHeaderLength; uint256 unclesLength; assembly { unclesLength := and(calldataload(sub(offset, 28)), 0xffff) } uint256 unclesShift; assembly { unclesShift := and(calldataload(sub(offset, 26)), 0xffff) } require( unclesShift + uncleHeaderLength <= unclesLength, "Shift bounds check." ); offset += 6; assembly { calldatacopy(scratchBuf2, offset, unclesLength) } memcpy(scratchBuf2 + unclesShift, scratchBuf1, uncleHeaderLength); assembly { seedHash := sha3(scratchBuf2, unclesLength) } offset += unclesLength; // Verify the canonical block header using the computed sha3Uncles. assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) shift := and(calldataload(sub(offset, 28)), 0xffff) } require(shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly { hashSlot := calldataload(add(offset, shift)) } require(hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) // At this moment the canonical block hash is known. blockHash := sha3(scratchBuf1, blobLength) } } // Helper to check the placeBet receipt. "offset" is the location of the proof beginning in the calldata. // RLP layout: [triePath, str([status, cumGasUsed, bloomFilter, [[address, [topics], data]])] function requireCorrectReceipt(uint256 offset) private view { uint256 leafHeaderByte; assembly { leafHeaderByte := byte(0, calldataload(offset)) } require(leafHeaderByte >= 0xf7, "Receipt leaf longer than 55 bytes."); offset += leafHeaderByte - 0xf6; uint256 pathHeaderByte; assembly { pathHeaderByte := byte(0, calldataload(offset)) } if (pathHeaderByte <= 0x7f) { offset += 1; } else { require( pathHeaderByte >= 0x80 && pathHeaderByte <= 0xb7, "Path is an RLP string." ); offset += pathHeaderByte - 0x7f; } uint256 receiptStringHeaderByte; assembly { receiptStringHeaderByte := byte(0, calldataload(offset)) } require( receiptStringHeaderByte == 0xb9, "Receipt string is always at least 256 bytes long, but less than 64k." ); offset += 3; uint256 receiptHeaderByte; assembly { receiptHeaderByte := byte(0, calldataload(offset)) } require( receiptHeaderByte == 0xf9, "Receipt is always at least 256 bytes long, but less than 64k." ); offset += 3; uint256 statusByte; assembly { statusByte := byte(0, calldataload(offset)) } require(statusByte == 0x1, "Status should be success."); offset += 1; uint256 cumGasHeaderByte; assembly { cumGasHeaderByte := byte(0, calldataload(offset)) } if (cumGasHeaderByte <= 0x7f) { offset += 1; } else { require( cumGasHeaderByte >= 0x80 && cumGasHeaderByte <= 0xb7, "Cumulative gas is an RLP string." ); offset += cumGasHeaderByte - 0x7f; } uint256 bloomHeaderByte; assembly { bloomHeaderByte := byte(0, calldataload(offset)) } require( bloomHeaderByte == 0xb9, "Bloom filter is always 256 bytes long." ); offset += 256 + 3; uint256 logsListHeaderByte; assembly { logsListHeaderByte := byte(0, calldataload(offset)) } require( logsListHeaderByte == 0xf8, "Logs list is less than 256 bytes long." ); offset += 2; uint256 logEntryHeaderByte; assembly { logEntryHeaderByte := byte(0, calldataload(offset)) } require( logEntryHeaderByte == 0xf8, "Log entry is less than 256 bytes long." ); offset += 2; uint256 addressHeaderByte; assembly { addressHeaderByte := byte(0, calldataload(offset)) } require(addressHeaderByte == 0x94, "Address is 20 bytes long."); uint256 logAddress; assembly { logAddress := and( calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff ) } require(logAddress == uint256(address(this))); } // Memory copy. function memcpy(uint256 dest, uint256 src, uint256 len) private pure { // Full 32 byte words for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Remaining bytes uint256 mask = 256**(32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } """#" text_o = """ type dice2Win_Bet is record #{config.reserved}__amount : nat; modulo : nat; rollUnder : nat; placeBlockNumber : nat; mask : nat; gambler : address; end; type constructor_args is unit; type approveNextOwner_args is record nextOwner_ : address; end; type acceptNextOwner_args is unit; type fallback_args is unit; type setSecretSigner_args is record newSecretSigner : address; end; type setCroupier_args is record newCroupier : address; end; type setMaxProfit_args is record maxProfit_ : nat; end; type increaseJackpot_args is record increaseAmount : nat; end; type withdrawFunds_args is record beneficiary : address; withdrawAmount : nat; end; type kill_args is unit; type placeBet_args is record betMask : nat; modulo : nat; commitLastBlock : nat; commit : nat; r : bytes; s : bytes; end; type settleBet_args is record reveal : nat; blockHash : bytes; end; type settleBetUncleMerkleProof_args is record reveal : nat; canonicalBlockNumber : nat; end; type refundBet_args is record commit : nat; end; type state is record owner : address; nextOwner : address; maxProfit : nat; secretSigner : address; jackpotSize : nat; lockedInBets : nat; bets : map(nat, dice2Win_Bet); croupier : address; end; function pow (const base : nat; const exp : nat) : nat is block { var b : nat := base; var e : nat := exp; var r : nat := 1n; while e > 0n block { if e mod 2n = 1n then { r := r * b; } else skip; b := b * b; e := e / 2n; } } with r; const burn_address : address = ("tz1ZZZZZZZZZZZZZZZZZZZZZZZZZZZZNkiRg" : address); const dice2Win_Bet_default : dice2Win_Bet = record [ #{config.reserved}__amount = 0n; modulo = 0n; rollUnder = 0n; placeBlockNumber = 0n; mask = 0n; gambler = burn_address ]; type router_enum is | Constructor of constructor_args | ApproveNextOwner of approveNextOwner_args | AcceptNextOwner of acceptNextOwner_args | Fallback of fallback_args | SetSecretSigner of setSecretSigner_args | SetCroupier of setCroupier_args | SetMaxProfit of setMaxProfit_args | IncreaseJackpot of increaseJackpot_args | WithdrawFunds of withdrawFunds_args | Kill of kill_args | PlaceBet of placeBet_args | SettleBet of settleBet_args | SettleBetUncleMerkleProof of settleBetUncleMerkleProof_args | RefundBet of refundBet_args; const hOUSE_EDGE_PERCENT : nat = 1n const hOUSE_EDGE_MINIMUM_AMOUNT : nat = (0.0003n * 1000000n) const mIN_JACKPOT_BET : nat = (0.1n * 1000000n) const jACKPOT_MODULO : nat = 1000n const jACKPOT_FEE : nat = (0.001n * 1000000n) const mIN_BET : nat = (0.01n * 1000000n) const mAX_AMOUNT : nat = (300000n * 1000000n) const mAX_MODULO : nat = 100n const mAX_MASK_MODULO : nat = 40n const mAX_BET_MASK : nat = pow(2n, mAX_MASK_MODULO) const bET_EXPIRATION_BLOCKS : nat = 250n const dUMMY_ADDRESS : address = ("PLEASE_REPLACE_ETH_ADDRESS_0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE_WITH_A_TEZOS_ADDRESS" : address) (* EventDefinition FailedPayment(beneficiary : address; #{config.reserved}__amount : nat) *) (* EventDefinition Payment(beneficiary : address; #{config.reserved}__amount : nat) *) (* EventDefinition JackpotPayment(beneficiary : address; #{config.reserved}__amount : nat) *) (* EventDefinition Commit(commit : nat) *) const pOPCNT_MULT : nat = 0x0000000000002000000000100000000008000000000400000000020000000001n const pOPCNT_MASK : nat = 0x0001041041041041041041041041041041041041041041041041041041041041n const pOPCNT_MODULO : nat = 0x3Fn function constructor (const test_self : state) : (state) is block { test_self.owner := Tezos.sender; test_self.secretSigner := dUMMY_ADDRESS; test_self.croupier := dUMMY_ADDRESS; } with (test_self); (* modifier onlyOwner inlined *) (* modifier onlyCroupier inlined *) function approveNextOwner (const test_self : state; const nextOwner_ : address) : (state) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); assert((nextOwner_ =/= test_self.owner)) (* "Cannot approve current owner." *); test_self.nextOwner := nextOwner_; } with (test_self); function acceptNextOwner (const test_self : state) : (state) is block { assert((Tezos.sender = test_self.nextOwner)) (* "Can only accept preapproved new owner." *); test_self.owner := test_self.nextOwner; } with (test_self); function fallback (const #{config.reserved}__unit : unit) : (unit) is block { skip } with (unit); function setSecretSigner (const test_self : state; const newSecretSigner : address) : (state) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); test_self.secretSigner := newSecretSigner; } with (test_self); function setCroupier (const test_self : state; const newCroupier : address) : (state) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); test_self.croupier := newCroupier; } with (test_self); function setMaxProfit (const test_self : state; const maxProfit_ : nat) : (state) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); assert((maxProfit_ < mAX_AMOUNT)) (* "maxProfit should be a sane number." *); test_self.maxProfit := maxProfit_; } with (test_self); function increaseJackpot (const test_self : state; const increaseAmount : nat) : (state) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); assert((increaseAmount <= self_address.#{config.reserved}__balance)) (* "Increase amount larger than balance." *); assert((((test_self.jackpotSize + test_self.lockedInBets) + increaseAmount) <= self_address.#{config.reserved}__balance)) (* "Not enough funds." *); test_self.jackpotSize := (test_self.jackpotSize + increaseAmount); } with (test_self); function sendFunds (const opList : list(operation); const test_self : state; const beneficiary : address; const #{config.reserved}__amount : nat; const successLogAmount : nat) : (list(operation)) is block { if (const op0 : operation = transaction((unit), (#{config.reserved}__amount * 1mutez), (get_contract(beneficiary) : contract(unit)))) then block { (* EmitStatement Payment(beneficiary, successLogAmount) *) } else block { (* EmitStatement FailedPayment(beneficiary, amount) *) }; } with (list [op0]); function withdrawFunds (const opList : list(operation); const test_self : state; const beneficiary : address; const withdrawAmount : nat) : (list(operation)) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); assert((withdrawAmount <= self_address.#{config.reserved}__balance)) (* "Increase amount larger than balance." *); assert((((test_self.jackpotSize + test_self.lockedInBets) + withdrawAmount) <= self_address.#{config.reserved}__balance)) (* "Not enough funds." *); opList := sendFunds((test_self : address), beneficiary, withdrawAmount, withdrawAmount); } with (opList); function kill (const test_self : state) : (unit) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); assert((test_self.lockedInBets = 0n)) (* "All bets should be processed (settled or refunded) before test_self-destruct." *); selfdestruct(test_self.owner) (* unsupported *); } with (unit); function getDiceWinAmount (const test_self : state; const #{config.reserved}__amount : nat; const modulo : nat; const rollUnder : nat) : ((nat * nat)) is block { const winAmount : nat = 0n; const jackpotFee : nat = 0n; assert(((0n < rollUnder) and (rollUnder <= modulo))) (* "Win probability out of range." *); jackpotFee := (case (#{config.reserved}__amount >= mIN_JACKPOT_BET) of | True -> jACKPOT_FEE | False -> 0n end); const houseEdge : nat = ((#{config.reserved}__amount * hOUSE_EDGE_PERCENT) / 100n); if (houseEdge < hOUSE_EDGE_MINIMUM_AMOUNT) then block { houseEdge := hOUSE_EDGE_MINIMUM_AMOUNT; } else block { skip }; assert(((houseEdge + jackpotFee) <= #{config.reserved}__amount)) (* "Bet doesn't even cover house edge." *); winAmount := ((abs(abs(#{config.reserved}__amount - houseEdge) - jackpotFee) * modulo) / rollUnder); } with ((winAmount, jackpotFee)); function placeBet (const test_self : state; const betMask : nat; const modulo : nat; const commitLastBlock : nat; const commit : nat; const r : bytes; const s : bytes) : (state) is block { const bet : dice2Win_Bet = (case test_self.bets[commit] of | None -> dice2Win_Bet_default | Some(x) -> x end); assert((bet.gambler = burn_address)) (* "Bet should be in a 'clean' _state." *); const #{config.reserved}__amount : nat = (amount / 1mutez); assert(((modulo > 1n) and (modulo <= mAX_MODULO))) (* "Modulo should be within range." *); assert(((#{config.reserved}__amount >= mIN_BET) and (#{config.reserved}__amount <= mAX_AMOUNT))) (* "Amount should be within range." *); assert(((betMask > 0n) and (betMask < mAX_BET_MASK))) (* "Mask should be within range." *); assert((0n <= commitLastBlock)) (* "Commit has expired." *); const signatureHash : bytes = sha_256((commitLastBlock, commit)); assert((test_self.secretSigner = ecrecover(signatureHash, 27n, r, s))) (* "ECDSA signature is not valid." *); const rollUnder : nat = 0n; const mask : nat = 0n; if (modulo <= mAX_MASK_MODULO) then block { rollUnder := (Bitwise.and((betMask * pOPCNT_MULT), pOPCNT_MASK) mod pOPCNT_MODULO); mask := betMask; } else block { assert(((betMask > 0n) and (betMask <= modulo))) (* "High modulo range, betMask larger than modulo." *); rollUnder := betMask; }; const possibleWinAmount : nat = 0n; const jackpotFee : nat = 0n; (possibleWinAmount, jackpotFee) := getDiceWinAmount(test_self, #{config.reserved}__amount, modulo, rollUnder); assert((possibleWinAmount <= (#{config.reserved}__amount + test_self.maxProfit))) (* "maxProfit limit violation." *); test_self.lockedInBets := (test_self.lockedInBets + possibleWinAmount); test_self.jackpotSize := (test_self.jackpotSize + jackpotFee); assert(((test_self.jackpotSize + test_self.lockedInBets) <= self_address.#{config.reserved}__balance)) (* "Cannot afford to lose this bet." *); (* EmitStatement Commit(commit) *) bet.#{config.reserved}__amount := #{config.reserved}__amount; bet.modulo := modulo; bet.rollUnder := rollUnder; bet.placeBlockNumber := 0n; bet.mask := mask; bet.gambler := Tezos.sender; } with (test_self); function settleBetCommon (const opList : list(operation); const test_self : state; const bet : dice2Win_Bet; const reveal : nat; const entropyBlockHash : bytes) : (list(operation) * state) is block { const #{config.reserved}__amount : nat = bet.#{config.reserved}__amount; const modulo : nat = bet.modulo; const rollUnder : nat = bet.rollUnder; const gambler : address = bet.gambler; assert((#{config.reserved}__amount =/= 0n)) (* "Bet should be in an 'active' _state" *); bet.#{config.reserved}__amount := 0n; const entropy : bytes = sha_256((reveal, entropyBlockHash)); const dice : nat = (abs(entropy) mod modulo); const diceWinAmount : nat = 0n; const jackpotFee_ : nat = 0n; (diceWinAmount, jackpotFee_) := getDiceWinAmount(test_self, #{config.reserved}__amount, modulo, rollUnder); const diceWin : nat = 0n; const jackpotWin : nat = 0n; if (modulo <= mAX_MASK_MODULO) then block { if (Bitwise.and(pow(2n, dice), bet.mask) =/= 0n) then block { diceWin := diceWinAmount; } else block { skip }; } else block { if (dice < rollUnder) then block { diceWin := diceWinAmount; } else block { skip }; }; test_self.lockedInBets := abs(test_self.lockedInBets - diceWinAmount); if (#{config.reserved}__amount >= mIN_JACKPOT_BET) then block { const jackpotRng : nat = ((abs(entropy) / modulo) mod jACKPOT_MODULO); if (jackpotRng = 0n) then block { jackpotWin := test_self.jackpotSize; test_self.jackpotSize := 0n; } else block { skip }; } else block { skip }; if (jackpotWin > 0n) then block { (* EmitStatement JackpotPayment(gambler, jackpotWin) *) } else block { skip }; opList := sendFunds((test_self : address), gambler, (case ((diceWin + jackpotWin) = 0n) of | True -> 1n | False -> (diceWin + jackpotWin) end), diceWin); } with (opList, test_self); function settleBet (const opList : list(operation); const test_self : state; const reveal : nat; const blockHash : bytes) : (list(operation) * state) is block { assert((Tezos.sender = test_self.croupier)) (* "OnlyCroupier methods called by non-croupier." *); const commit : nat = abs(sha_256((reveal))); const bet : dice2Win_Bet = (case test_self.bets[commit] of | None -> dice2Win_Bet_default | Some(x) -> x end); const placeBlockNumber : nat = bet.placeBlockNumber; assert((0n > placeBlockNumber)) (* "settleBet in the same block as placeBet, or before." *); assert((0n <= (placeBlockNumber + bET_EXPIRATION_BLOCKS))) (* "Blockhash can't be queried by EVM." *); assert((("00" : bytes) (* Should be blockhash of placeBlockNumber *) = blockHash)); const tmp_0 : (list(operation) * state) = settleBetCommon(test_self, bet, reveal, blockHash); opList := tmp_0.0; test_self := tmp_0.1; } with (opList, test_self); function memcpy (const dest : nat; const src : nat; const len : nat) : (unit) is block { while (len >= 32n) block { failwith("Unsupported InlineAssembly"); (* InlineAssembly { mstore(dest, mload(src)) } *) dest := (dest + 32n); src := (src + 32n); len := abs(len - 32n); }; const mask : nat = abs(pow(256n, abs(32n - len)) - 1n); failwith("Unsupported InlineAssembly"); (* InlineAssembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } *) } with (unit); function verifyMerkleProof (const seedHash : nat; const offset : nat) : ((bytes * bytes)) is block { const blockHash : bytes = ("00": bytes); const uncleHash : bytes = ("00": bytes); const scratchBuf1 : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { scratchBuf1 := mload(0x40) } *) const uncleHeaderLength : nat = 0n; const blobLength : nat = 0n; const shift : nat = 0n; const hashSlot : nat = 0n; while (True) block { failwith("Unsupported InlineAssembly"); (* InlineAssembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) } *) if (blobLength = 0n) then block { (* `break` statement is not supported in LIGO *); } else block { skip }; failwith("Unsupported InlineAssembly"); (* InlineAssembly { shift := and(calldataload(sub(offset, 28)), 0xffff) } *) assert(((shift + 32n) <= blobLength)) (* "Shift bounds check." *); offset := (offset + 4n); failwith("Unsupported InlineAssembly"); (* InlineAssembly { hashSlot := calldataload(add(offset, shift)) } *) assert((hashSlot = 0n)) (* "Non-empty hash slot." *); failwith("Unsupported InlineAssembly"); (* InlineAssembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) seedHash := keccak256(scratchBuf1, blobLength) uncleHeaderLength := blobLength } *) offset := (offset + blobLength); }; uncleHash := (seedHash : bytes); const scratchBuf2 : nat = (scratchBuf1 + uncleHeaderLength); const unclesLength : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { unclesLength := and(calldataload(sub(offset, 28)), 0xffff) } *) const unclesShift : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { unclesShift := and(calldataload(sub(offset, 26)), 0xffff) } *) assert(((unclesShift + uncleHeaderLength) <= unclesLength)) (* "Shift bounds check." *); offset := (offset + 6n); failwith("Unsupported InlineAssembly"); (* InlineAssembly { calldatacopy(scratchBuf2, offset, unclesLength) } *) memcpy((scratchBuf2 + unclesShift), scratchBuf1, uncleHeaderLength); failwith("Unsupported InlineAssembly"); (* InlineAssembly { seedHash := keccak256(scratchBuf2, unclesLength) } *) offset := (offset + unclesLength); failwith("Unsupported InlineAssembly"); (* InlineAssembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) shift := and(calldataload(sub(offset, 28)), 0xffff) } *) assert(((shift + 32n) <= blobLength)) (* "Shift bounds check." *); offset := (offset + 4n); failwith("Unsupported InlineAssembly"); (* InlineAssembly { hashSlot := calldataload(add(offset, shift)) } *) assert((hashSlot = 0n)) (* "Non-empty hash slot." *); failwith("Unsupported InlineAssembly"); (* InlineAssembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) blockHash := keccak256(scratchBuf1, blobLength) } *) } with ((blockHash, uncleHash)); function requireCorrectReceipt (const offset : nat) : (unit) is block { const leafHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { leafHeaderByte := byte(0, calldataload(offset)) } *) assert((leafHeaderByte >= 0xf7n)) (* "Receipt leaf longer than 55 bytes." *); offset := (offset + abs(leafHeaderByte - 0xf6n)); const pathHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { pathHeaderByte := byte(0, calldataload(offset)) } *) if (pathHeaderByte <= 0x7fn) then block { offset := (offset + 1n); } else block { assert(((pathHeaderByte >= 0x80n) and (pathHeaderByte <= 0xb7n))) (* "Path is an RLP string." *); offset := (offset + abs(pathHeaderByte - 0x7fn)); }; const receiptStringHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { receiptStringHeaderByte := byte(0, calldataload(offset)) } *) assert((receiptStringHeaderByte = 0xb9n)) (* "Receipt string is always at least 256 bytes long, but less than 64k." *); offset := (offset + 3n); const receiptHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { receiptHeaderByte := byte(0, calldataload(offset)) } *) assert((receiptHeaderByte = 0xf9n)) (* "Receipt is always at least 256 bytes long, but less than 64k." *); offset := (offset + 3n); const statusByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { statusByte := byte(0, calldataload(offset)) } *) assert((statusByte = 0x1n)) (* "Status should be success." *); offset := (offset + 1n); const cumGasHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { cumGasHeaderByte := byte(0, calldataload(offset)) } *) if (cumGasHeaderByte <= 0x7fn) then block { offset := (offset + 1n); } else block { assert(((cumGasHeaderByte >= 0x80n) and (cumGasHeaderByte <= 0xb7n))) (* "Cumulative gas is an RLP string." *); offset := (offset + abs(cumGasHeaderByte - 0x7fn)); }; const bloomHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { bloomHeaderByte := byte(0, calldataload(offset)) } *) assert((bloomHeaderByte = 0xb9n)) (* "Bloom filter is always 256 bytes long." *); offset := (offset + (256 + 3)); const logsListHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { logsListHeaderByte := byte(0, calldataload(offset)) } *) assert((logsListHeaderByte = 0xf8n)) (* "Logs list is less than 256 bytes long." *); offset := (offset + 2n); const logEntryHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { logEntryHeaderByte := byte(0, calldataload(offset)) } *) assert((logEntryHeaderByte = 0xf8n)) (* "Log entry is less than 256 bytes long." *); offset := (offset + 2n); const addressHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { addressHeaderByte := byte(0, calldataload(offset)) } *) assert((addressHeaderByte = 0x94n)) (* "Address is 20 bytes long." *); const logAddress : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { logAddress := and(calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff) } *) assert((logAddress = abs(self_address))); } with (unit); function settleBetUncleMerkleProof (const opList : list(operation); const test_self : state; const reveal : nat; const canonicalBlockNumber : nat) : (list(operation) * state) is block { assert((Tezos.sender = test_self.croupier)) (* "OnlyCroupier methods called by non-croupier." *); const commit : nat = abs(sha_256((reveal))); const bet : dice2Win_Bet = (case test_self.bets[commit] of | None -> dice2Win_Bet_default | Some(x) -> x end); assert((0n <= (canonicalBlockNumber + bET_EXPIRATION_BLOCKS))) (* "Blockhash can't be queried by EVM." *); requireCorrectReceipt((((4 + 32) + 32) + 4n)); const canonicalHash : bytes = ("00": bytes); const uncleHash : bytes = ("00": bytes); (canonicalHash, uncleHash) := verifyMerkleProof(commit, ((4 + 32) + 32n)); assert((("00" : bytes) (* Should be blockhash of canonicalBlockNumber *) = canonicalHash)); const tmp_0 : (list(operation) * state) = settleBetCommon(test_self, bet, reveal, uncleHash); opList := tmp_0.0; test_self := tmp_0.1; } with (opList, test_self); function refundBet (const opList : list(operation); const test_self : state; const commit : nat) : (list(operation) * state) is block { const bet : dice2Win_Bet = (case test_self.bets[commit] of | None -> dice2Win_Bet_default | Some(x) -> x end); const #{config.reserved}__amount : nat = bet.#{config.reserved}__amount; assert((#{config.reserved}__amount =/= 0n)) (* "Bet should be in an 'active' _state" *); assert((0n > (bet.placeBlockNumber + bET_EXPIRATION_BLOCKS))) (* "Blockhash can't be queried by EVM." *); bet.#{config.reserved}__amount := 0n; const diceWinAmount : nat = 0n; const jackpotFee : nat = 0n; (diceWinAmount, jackpotFee) := getDiceWinAmount(test_self, #{config.reserved}__amount, bet.modulo, bet.rollUnder); test_self.lockedInBets := abs(test_self.lockedInBets - diceWinAmount); test_self.jackpotSize := abs(test_self.jackpotSize - jackpotFee); opList := sendFunds((test_self : address), bet.gambler, #{config.reserved}__amount, #{config.reserved}__amount); } with (opList, test_self); function main (const action : router_enum; const test_self : state) : (list(operation) * state) is (case action of | Constructor(match_action) -> ((nil: list(operation)), constructor(test_self)) | ApproveNextOwner(match_action) -> ((nil: list(operation)), approveNextOwner(test_self, match_action.nextOwner_)) | AcceptNextOwner(match_action) -> ((nil: list(operation)), acceptNextOwner(test_self)) | Fallback(match_action) -> block { (* This function does nothing, but it's present in router *) const tmp : unit = fallback(unit); } with (((nil: list(operation)), test_self)) | SetSecretSigner(match_action) -> ((nil: list(operation)), setSecretSigner(test_self, match_action.newSecretSigner)) | SetCroupier(match_action) -> ((nil: list(operation)), setCroupier(test_self, match_action.newCroupier)) | SetMaxProfit(match_action) -> ((nil: list(operation)), setMaxProfit(test_self, match_action.maxProfit_)) | IncreaseJackpot(match_action) -> ((nil: list(operation)), increaseJackpot(test_self, match_action.increaseAmount)) | WithdrawFunds(match_action) -> (withdrawFunds((nil: list(operation)), test_self, match_action.beneficiary, match_action.withdrawAmount), test_self) | Kill(match_action) -> block { (* This function does nothing, but it's present in router *) const tmp : unit = kill(test_self); } with (((nil: list(operation)), test_self)) | PlaceBet(match_action) -> ((nil: list(operation)), placeBet(test_self, match_action.betMask, match_action.modulo, match_action.commitLastBlock, match_action.commit, match_action.r, match_action.s)) | SettleBet(match_action) -> settleBet((nil: list(operation)), test_self, match_action.reveal, match_action.blockHash) | SettleBetUncleMerkleProof(match_action) -> settleBetUncleMerkleProof((nil: list(operation)), test_self, match_action.reveal, match_action.canonicalBlockNumber) | RefundBet(match_action) -> refundBet((nil: list(operation)), test_self, match_action.commit) end); """#" make_test text_i, text_o, router: true, allow_need_prevent_deploy: true # ################################################################################################### it "Creatures", ()-> text_i = """ pragma solidity ^0.4.16; contract Permissions { address ownerAddress; address storageAddress; address callerAddress; function Permissions() public { ownerAddress = msg.sender; } modifier onlyOwner() { require(msg.sender == ownerAddress); _; } modifier onlyCaller() { require(msg.sender == callerAddress); _; } function getOwner() external view returns (address) { return ownerAddress; } function getStorageAddress() external view returns (address) { return storageAddress; } function getCaller() external view returns (address) { return callerAddress; } function transferOwnership(address newOwner) external onlyOwner { if (newOwner != address(0)) { ownerAddress = newOwner; } } function newStorage(address _new) external onlyOwner { if (_new != address(0)) { storageAddress = _new; } } function newCaller(address _new) external onlyOwner { if (_new != address(0)) { callerAddress = _new; } } } contract Creatures is Permissions { struct Creature { uint16 species; uint8 subSpecies; uint8 eyeColor; uint64 timestamp; } Creature[] creatures; mapping(uint256 => address) public creatureIndexToOwner; mapping(address => uint256) ownershipTokenCount; event CreateCreature(uint256 id, address indexed owner); event Transfer(address _from, address _to, uint256 creatureID); function add( address _owner, uint16 _species, uint8 _subSpecies, uint8 _eyeColor ) external onlyCaller { // do checks in caller function Creature memory _creature = Creature({ species: _species, subSpecies: _subSpecies, eyeColor: _eyeColor, timestamp: uint64(now) }); uint256 newCreatureID = creatures.push(_creature) - 1; transfer(0, _owner, newCreatureID); CreateCreature(newCreatureID, _owner); } function getCreature(uint256 id) external view returns (address, uint16, uint8, uint8, uint64) { Creature storage c = creatures[id]; address owner = creatureIndexToOwner[id]; return (owner, c.species, c.subSpecies, c.eyeColor, c.timestamp); } function transfer(address _from, address _to, uint256 _tokenId) public onlyCaller { // do checks in caller function creatureIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; } ownershipTokenCount[_to]++; Transfer(_from, _to, _tokenId); } } """#" text_o = """ type creatures_Creature is record species : nat; subSpecies : nat; eyeColor : nat; timestamp : nat; end; type newCaller_args is record new_ : address; end; type newStorage_args is record new_ : address; end; type transferOwnership_args is record newOwner : address; end; type getCaller_args is record callbackAddress : address; end; type getStorageAddress_args is record callbackAddress : address; end; type getOwner_args is record callbackAddress : address; end; type transfer_args is record from_ : address; to_ : address; tokenId_ : nat; end; type add_args is record owner_ : address; species_ : nat; subSpecies_ : nat; eyeColor_ : nat; end; type getCreature_args is record id : nat; callbackAddress : address; end; type constructor_args is unit; type state is record callerAddress : address; storageAddress : address; ownerAddress : address; creatures : map(nat, creatures_Creature); creatureIndexToOwner : map(nat, address); ownershipTokenCount : map(address, nat); end; const burn_address : address = ("tz1ZZZZZZZZZZZZZZZZZZZZZZZZZZZZNkiRg" : address); const creatures_Creature_default : creatures_Creature = record [ species = 0n; subSpecies = 0n; eyeColor = 0n; timestamp = 0n ]; type router_enum is | NewCaller of newCaller_args | NewStorage of newStorage_args | TransferOwnership of transferOwnership_args | GetCaller of getCaller_args | GetStorageAddress of getStorageAddress_args | GetOwner of getOwner_args | Transfer of transfer_args | Add of add_args | GetCreature of getCreature_args | Constructor of constructor_args; (* EventDefinition CreateCreature(id : nat; owner : address) *) (* EventDefinition Transfer(from_ : address; to_ : address; creatureID : nat) *) function newCaller (const test_self : state; const new_ : address) : (state) is block { assert((Tezos.sender = test_self.ownerAddress)); if (new_ =/= burn_address) then block { test_self.callerAddress := new_; } else block { skip }; } with (test_self); function newStorage (const test_self : state; const new_ : address) : (state) is block { assert((Tezos.sender = test_self.ownerAddress)); if (new_ =/= burn_address) then block { test_self.storageAddress := new_; } else block { skip }; } with (test_self); function transferOwnership (const test_self : state; const newOwner : address) : (state) is block { assert((Tezos.sender = test_self.ownerAddress)); if (newOwner =/= burn_address) then block { test_self.ownerAddress := newOwner; } else block { skip }; } with (test_self); function getCaller (const test_self : state) : (address) is block { skip } with (test_self.callerAddress); function getStorageAddress (const test_self : state) : (address) is block { skip } with (test_self.storageAddress); function getOwner (const test_self : state) : (address) is block { skip } with (test_self.ownerAddress); function permissions_constructor (const test_self : state) : (state) is block { test_self.ownerAddress := Tezos.sender; } with (test_self); function transfer (const test_self : state; const from_ : address; const to_ : address; const tokenId_ : nat) : (state) is block { assert((Tezos.sender = test_self.callerAddress)); test_self.creatureIndexToOwner[tokenId_] := to_; if (from_ =/= burn_address) then block { (case test_self.ownershipTokenCount[from_] of | None -> 0n | Some(x) -> x end) := abs((case test_self.ownershipTokenCount[from_] of | None -> 0n | Some(x) -> x end) - 1n); } else block { skip }; (case test_self.ownershipTokenCount[to_] of | None -> 0n | Some(x) -> x end) := (case test_self.ownershipTokenCount[to_] of | None -> 0n | Some(x) -> x end) + 1n; (* EmitStatement Transfer(_from, _to, _tokenId) *) } with (test_self); function add (const opList : list(operation); const test_self : state; const owner_ : address; const species_ : nat; const subSpecies_ : nat; const eyeColor_ : nat) : (list(operation) * state) is block { assert((Tezos.sender = test_self.callerAddress)); const creature_ : creatures_Creature = record [ species = species_; subSpecies = subSpecies_; eyeColor = eyeColor_; timestamp = abs(abs(now - ("1970-01-01T00:00:00Z" : timestamp))) ]; const tmp_0 : map(nat, creatures_Creature) = test_self.creatures; const newCreatureID : nat = abs(tmp_0[size(tmp_0)] := creature_ - 1n); transfer(burn_address, owner_, newCreatureID); (* EmitStatement CreateCreature(newCreatureID, _owner) *) } with (opList, test_self); function getCreature (const test_self : state; const id : nat) : ((address * nat * nat * nat * nat)) is block { const c : creatures_Creature = (case test_self.creatures[id] of | None -> creatures_Creature_default | Some(x) -> x end); const owner : address = (case test_self.creatureIndexToOwner[id] of | None -> burn_address | Some(x) -> x end); } with ((owner, c.species, c.subSpecies, c.eyeColor, c.timestamp)); function constructor (const test_self : state) : (state) is block { test_self := permissions_constructor(test_self); } with (test_self); function main (const action : router_enum; const test_self : state) : (list(operation) * state) is (case action of | NewCaller(match_action) -> ((nil: list(operation)), newCaller(test_self, match_action.new_)) | NewStorage(match_action) -> ((nil: list(operation)), newStorage(test_self, match_action.new_)) | TransferOwnership(match_action) -> ((nil: list(operation)), transferOwnership(test_self, match_action.newOwner)) | GetCaller(match_action) -> block { const tmp : (address) = getCaller(test_self); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(address))) end; } with ((opList, test_self)) | GetStorageAddress(match_action) -> block { const tmp : (address) = getStorageAddress(test_self); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(address))) end; } with ((opList, test_self)) | GetOwner(match_action) -> block { const tmp : (address) = getOwner(test_self); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(address))) end; } with ((opList, test_self)) | Transfer(match_action) -> ((nil: list(operation)), transfer(test_self, match_action.from_, match_action.to_, match_action.tokenId_)) | Add(match_action) -> add((nil: list(operation)), test_self, match_action.owner_, match_action.species_, match_action.subSpecies_, match_action.eyeColor_) | GetCreature(match_action) -> block { const tmp : ((address * nat * nat * nat * nat)) = getCreature(test_self, match_action.id); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract((address * nat * nat * nat * nat)))) end; } with ((opList, test_self)) | Constructor(match_action) -> ((nil: list(operation)), constructor(test_self)) end); """#" make_test text_i, text_o, router: true
150885
config = require "../src/config" { translate_ligo_make_test : make_test } = require("./util") describe "translate ligo online examples", ()-> @timeout 10000 # NOTE some duplication with other tests # ################################################################################################### it "int arithmetic", ()-> text_i = """ pragma solidity ^0.5.11; contract Arith { int public value; function arith() public returns (int ret_val) { int a = 0; int b = 0; int c = 0; c = -c; c = a + b; c = a - b; c = a * b; c = a / b; return c; } } """#" text_o = """ type arith_args is record callbackAddress : address; end; type state is record value : int; end; type router_enum is | Arith of arith_args; function arith (const #{config.reserved}__unit : unit) : (int) is block { const ret_val : int = 0; const a : int = 0; const b : int = 0; const c : int = 0; c := -(c); c := (a + b); c := (a - b); c := (a * b); c := (a / b); } with (c); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Arith(match_action) -> block { const tmp : (int) = arith(unit); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(int))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "uint arithmetic", ()-> text_i = """ pragma solidity ^0.5.11; contract Arith { uint public value; function arith() public returns (uint ret_val) { uint a = 0; uint b = 0; uint c = 0; c = a + b; c = a * b; c = a / b; c = a | b; c = a & b; c = a ^ b; return c; } } """#" text_o = """ type arith_args is record callbackAddress : address; end; type state is record value : nat; end; type router_enum is | Arith of arith_args; function arith (const #{config.reserved}__unit : unit) : (nat) is block { const ret_val : nat = 0n; const a : nat = 0n; const b : nat = 0n; const c : nat = 0n; c := (a + b); c := (a * b); c := (a / b); c := Bitwise.or(a, b); c := Bitwise.and(a, b); c := Bitwise.xor(a, b); } with (c); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Arith(match_action) -> block { const tmp : (nat) = arith(unit); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(nat))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "if", ()-> text_i = """ pragma solidity ^0.5.11; contract Ifer { uint public value; function ifer() public returns (uint) { uint x = 6; if (x == 5) { x += 1; } else { x += 10; } return x; } } """#" text_o = """ type ifer_args is record callbackAddress : address; end; type state is record value : nat; end; type router_enum is | Ifer of ifer_args; function ifer (const #{config.reserved}__unit : unit) : (nat) is block { const x : nat = 6n; if (x = 5n) then block { x := (x + 1n); } else block { x := (x + 10n); }; } with (x); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Ifer(match_action) -> block { const tmp : (nat) = ifer(unit); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(nat))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "for", ()-> text_i = """ pragma solidity ^0.5.11; contract Forer { uint public value; function forer() public returns (uint ret_val) { uint y = 0; for (uint i=0; i<5; i+=1) { y += 1; } return y; } } """#" text_o = """ type forer_args is record callbackAddress : address; end; type state is record value : nat; end; type router_enum is | Forer of forer_args; function forer (const #{config.reserved}__unit : unit) : (nat) is block { const ret_val : nat = 0n; const y : nat = 0n; const i : nat = 0n; while (i < 5n) block { y := (y + 1n); i := (i + 1n); }; } with (y); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Forer(match_action) -> block { const tmp : (nat) = forer(unit); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(nat))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "while", ()-> text_i = """ pragma solidity ^0.5.11; contract Whiler { uint public value; function whiler() public returns (uint ret_val) { uint y = 0; while (y != 2) { y += 1; } return y; } } """#" text_o = """ type whiler_args is record callbackAddress : address; end; type state is record value : nat; end; type router_enum is | Whiler of whiler_args; function whiler (const #{config.reserved}__unit : unit) : (nat) is block { const ret_val : nat = 0n; const y : nat = 0n; while (y =/= 2n) block { y := (y + 1n); }; } with (y); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Whiler(match_action) -> block { const tmp : (nat) = whiler(unit); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(nat))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "fn call", ()-> text_i = """ pragma solidity ^0.5.11; contract Fn_call { int public value; function fn1(int a) public returns (int ret_val) { value += 1; return a; } function fn2() public returns (int ret_val) { fn1(1); int res = 1; return res; } } """#" text_o = """ type fn1_args is record a : int; callbackAddress : address; end; type fn2_args is record callbackAddress : address; end; type state is record value : int; end; type router_enum is | Fn1 of fn1_args | Fn2 of fn2_args; function fn1 (const contract_storage : state; const a : int) : (state * int) is block { const ret_val : int = 0; contract_storage.value := (contract_storage.value + 1); } with (contract_storage, a); function fn2 (const contract_storage : state) : (state * int) is block { const ret_val : int = 0; const tmp_0 : (state * int) = fn1(contract_storage, 1); contract_storage := tmp_0.0; const res : int = 1; } with (contract_storage, res); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Fn1(match_action) -> block { const tmp : (state * int) = fn1(contract_storage, match_action.a); var opList : list(operation) := list transaction((tmp.0), 0mutez, (get_contract(match_action.callbackAddress) : contract(state))) end; } with ((opList, tmp.0)) | Fn2(match_action) -> block { const tmp : (state * int) = fn2(contract_storage); var opList : list(operation) := list transaction((tmp.0), 0mutez, (get_contract(match_action.callbackAddress) : contract(state))) end; } with ((opList, tmp.0)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "simplecoin", ()-> text_i = """ pragma solidity ^0.5.11; contract Coin { address minter; mapping (address => uint) balances; constructor() public { minter = msg.sender; } function mint(address owner, uint amount) public { if (msg.sender == minter) { balances[owner] += amount; } } function send(address receiver, uint amount) public { if (balances[msg.sender] >= amount) { balances[msg.sender] -= amount; balances[receiver] += amount; } } function queryBalance(address addr) public view returns (uint balance) { return balances[addr]; } } """#" text_o = """ type constructor_args is unit; type mint_args is record owner : address; #{config.reserved}__amount : nat; end; type send_args is record receiver : address; #{config.reserved}__amount : nat; end; type queryBalance_args is record addr : address; callbackAddress : address; end; type state is record minter : address; balances : map(address, nat); end; type router_enum is | Constructor of constructor_args | Mint of mint_args | Send of send_args | QueryBalance of queryBalance_args; function constructor (const contract_storage : state) : (state) is block { contract_storage.minter := Tezos.sender; } with (contract_storage); function mint (const contract_storage : state; const owner : address; const #{config.reserved}__amount : nat) : (state) is block { if (Tezos.sender = contract_storage.minter) then block { contract_storage.balances[owner] := ((case contract_storage.balances[owner] of | None -> 0n | Some(x) -> x end) + #{config.reserved}__amount); } else block { skip }; } with (contract_storage); function send (const contract_storage : state; const receiver : address; const #{config.reserved}__amount : nat) : (state) is block { if ((case contract_storage.balances[Tezos.sender] of | None -> 0n | Some(x) -> x end) >= #{config.reserved}__amount) then block { contract_storage.balances[Tezos.sender] := abs((case contract_storage.balances[Tezos.sender] of | None -> 0n | Some(x) -> x end) - #{config.reserved}__amount); contract_storage.balances[receiver] := ((case contract_storage.balances[receiver] of | None -> 0n | Some(x) -> x end) + #{config.reserved}__amount); } else block { skip }; } with (contract_storage); function queryBalance (const contract_storage : state; const addr : address) : (nat) is block { const #{config.reserved}__balance : nat = 0n; } with ((case contract_storage.balances[addr] of | None -> 0n | Some(x) -> x end)); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Constructor(match_action) -> ((nil: list(operation)), constructor(contract_storage)) | Mint(match_action) -> ((nil: list(operation)), mint(contract_storage, match_action.owner, match_action.#{config.reserved}__amount)) | Send(match_action) -> ((nil: list(operation)), send(contract_storage, match_action.receiver, match_action.#{config.reserved}__amount)) | QueryBalance(match_action) -> block { const tmp : (nat) = queryBalance(contract_storage, match_action.addr); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(nat))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "AtomicSwap", ()-> text_i = """ pragma solidity ^0.4.18; contract AtomicSwapEther { struct Swap { uint256 timelock; uint256 value; address ethTrader; address withdrawTrader; bytes32 secretLock; bytes secretKey; } enum States { INVALID, OPEN, CLOSED, EXPIRED } mapping (bytes32 => Swap) private swaps; mapping (bytes32 => States) private swapStates; event Open(bytes32 _swapID, address _withdrawTrader,bytes32 _secretLock); event Expire(bytes32 _swapID); event Close(bytes32 _swapID, bytes _secretKey); modifier onlyInvalidSwaps(bytes32 _swapID) { require (swapStates[_swapID] == States.INVALID); _; } modifier onlyOpenSwaps(bytes32 _swapID) { require (swapStates[_swapID] == States.OPEN); _; } modifier onlyClosedSwaps(bytes32 _swapID) { require (swapStates[_swapID] == States.CLOSED); _; } modifier onlyExpirableSwaps(bytes32 _swapID) { require (now >= swaps[_swapID].timelock); _; } modifier onlyWithSecretKey(bytes32 _swapID, bytes _secretKey) { // TODO: Require _secretKey length to conform to the spec require (swaps[_swapID].secretLock == sha256(_secretKey)); _; } function open(bytes32 _swapID, address _withdrawTrader, bytes32 _secretLock, uint256 _timelock) public onlyInvalidSwaps(_swapID) payable { // Store the details of the swap. Swap memory swap = Swap({ timelock: _timelock, value: msg.value, ethTrader: msg.sender, withdrawTrader: _withdrawTrader, secretLock: _secretLock, secretKey: new bytes(0) }); swaps[_swapID] = swap; swapStates[_swapID] = States.OPEN; // Trigger open event. Open(_swapID, _withdrawTrader, _secretLock); } function close(bytes32 _swapID, bytes _secretKey) public onlyOpenSwaps(_swapID) onlyWithSecretKey(_swapID, _secretKey) { // Close the swap. Swap memory swap = swaps[_swapID]; swaps[_swapID].secretKey = _secretKey; swapStates[_swapID] = States.CLOSED; // Transfer the ETH funds from this contract to the withdrawing trader. swap.withdrawTrader.transfer(swap.value); // Trigger close event. Close(_swapID, _secretKey); } function expire(bytes32 _swapID) public onlyOpenSwaps(_swapID) onlyExpirableSwaps(_swapID) { // Expire the swap. Swap memory swap = swaps[_swapID]; swapStates[_swapID] = States.EXPIRED; // Transfer the ETH value from this contract back to the ETH trader. swap.ethTrader.transfer(swap.value); // Trigger expire event. Expire(_swapID); } function check(bytes32 _swapID) public view returns (uint256 timelock, uint256 value, address withdrawTrader, bytes32 secretLock) { Swap memory swap = swaps[_swapID]; return (swap.timelock, swap.value, swap.withdrawTrader, swap.secretLock); } function checkSecretKey(bytes32 _swapID) public view onlyClosedSwaps(_swapID) returns (bytes secretKey) { Swap memory swap = swaps[_swapID]; return swap.secretKey; } } """#" text_o = """ type atomicSwapEther_Swap is record timelock : nat; value : nat; ethTrader : address; withdrawTrader : address; secretLock : bytes; secretKey : bytes; end; type open_args is record swapID_ : bytes; withdrawTrader_ : address; secretLock_ : bytes; timelock_ : nat; end; type close_args is record swapID_ : bytes; secretKey_ : bytes; end; type expire_args is record swapID_ : bytes; end; type check_args is record swapID_ : bytes; callbackAddress : address; end; type checkSecretKey_args is record swapID_ : bytes; callbackAddress : address; end; type state is record swaps : map(bytes, atomicSwapEther_Swap); swapStates : map(bytes, nat); end; const burn_address : address = ("tz1ZZZZZZZZZZZZZZZZZZZZZZZZZZZZNkiRg" : address); const atomicSwapEther_Swap_default : atomicSwapEther_Swap = record [ timelock = 0n; value = 0n; ethTrader = burn_address; withdrawTrader = burn_address; secretLock = ("00": bytes); secretKey = ("0<KEY>": bytes) ]; const states_INVALID : nat = 0n; const states_OPEN : nat = 1n; const states_CLOSED : nat = 2n; const states_EXPIRED : nat = 3n; type router_enum is | Open of open_args | Close of close_args | Expire of expire_args | Check of check_args | CheckSecretKey of checkSecretKey_args; (* EventDefinition Open(swapID_ : bytes; withdrawTrader_ : address; secretLock_ : bytes) *) (* EventDefinition Expire(swapID_ : bytes) *) (* EventDefinition Close(swapID_ : bytes; secretKey_ : bytes) *) (* enum States converted into list of nats *) (* modifier onlyInvalidSwaps inlined *) (* modifier onlyOpenSwaps inlined *) (* modifier onlyClosedSwaps inlined *) (* modifier onlyExpirableSwaps inlined *) (* modifier onlyWithSecretKey inlined *) function open (const test_self : state; const swapID_ : bytes; const withdrawTrader_ : address; const secretLock_ : bytes; const timelock_ : nat) : (state) is block { assert(((case test_self.swapStates[swapID_] of | None -> 0n | Some(x) -> x end) = states_INVALID)); const swap : atomicSwapEther_Swap = record [ timelock = timelock_; value = (amount / 1mutez); ethTrader = Tezos.sender; withdrawTrader = withdrawTrader_; secretLock = secretLock_; secretKey = ("0<KEY>": bytes) (* args: 0 *) ]; test_self.swaps[swapID_] := swap; test_self.swapStates[swapID_] := states_OPEN; (* EmitStatement Open(_swapID, _withdrawTrader, _secretLock) *) } with (test_self); function close (const opList : list(operation); const test_self : state; const swapID_ : bytes; const secretKey_ : bytes) : (list(operation) * state) is block { assert(((case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end).secretLock = sha_256(secretKey_))); assert(((case test_self.swapStates[swapID_] of | None -> 0n | Some(x) -> x end) = states_OPEN)); const swap : atomicSwapEther_Swap = (case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end); test_self.swaps[swapID_].secretKey := secretKey_; test_self.swapStates[swapID_] := states_CLOSED; const op0 : operation = transaction((unit), (swap.value * 1mutez), (get_contract(swap.withdrawTrader) : contract(unit))); (* EmitStatement Close(_swapID, _secretKey) *) } with (list [op0], test_self); function expire (const opList : list(operation); const test_self : state; const swapID_ : bytes) : (list(operation) * state) is block { assert((abs(now - ("1970-01-01T00:00:00Z" : timestamp)) >= (case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end).timelock)); assert(((case test_self.swapStates[swapID_] of | None -> 0n | Some(x) -> x end) = states_OPEN)); const swap : atomicSwapEther_Swap = (case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end); test_self.swapStates[swapID_] := states_EXPIRED; const op0 : operation = transaction((unit), (swap.value * 1mutez), (get_contract(swap.ethTrader) : contract(unit))); (* EmitStatement Expire(_swapID) *) } with (list [op0], test_self); function check (const test_self : state; const swapID_ : bytes) : ((nat * nat * address * bytes)) is block { const timelock : nat = 0n; const value : nat = 0n; const withdrawTrader : address = burn_address; const secretLock : bytes = ("00": bytes); const swap : atomicSwapEther_Swap = (case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end); } with ((swap.timelock, swap.value, swap.withdrawTrader, swap.secretLock)); function checkSecretKey (const test_self : state; const swapID_ : bytes) : (bytes) is block { assert(((case test_self.swapStates[swapID_] of | None -> 0n | Some(x) -> x end) = states_CLOSED)); const secretKey : bytes = ("00": bytes); const swap : atomicSwapEther_Swap = (case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end); } with (swap.secretKey); function main (const action : router_enum; const test_self : state) : (list(operation) * state) is (case action of | Open(match_action) -> ((nil: list(operation)), open(test_self, match_action.swapID_, match_action.withdrawTrader_, match_action.secretLock_, match_action.timelock_)) | Close(match_action) -> close((nil: list(operation)), test_self, match_action.swapID_, match_action.secretKey_) | Expire(match_action) -> expire((nil: list(operation)), test_self, match_action.swapID_) | Check(match_action) -> block { const tmp : ((nat * nat * address * bytes)) = check(test_self, match_action.swapID_); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract((nat * nat * address * bytes)))) end; } with ((opList, test_self)) | CheckSecretKey(match_action) -> block { const tmp : (bytes) = checkSecretKey(test_self, match_action.swapID_); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(bytes))) end; } with ((opList, test_self)) end); """#" make_test text_i, text_o, router: true # ################################################################################################### it "Dice", ()-> text_i = """ pragma solidity ^0.4.24; // * dice2.win - fair games that pay Ether. Version 5. // // * Ethereum smart contract, deployed at 0xD1CEeeeee83F8bCF3BEDad437202b6154E9F5405. // // * Uses hybrid commit-reveal + block hash random number generation that is immune // to tampering by players, house and miners. Apart from being fully transparent, // this also allows arbitrarily high bets. // // * Refer to https://dice2.win/whitepaper.pdf for detailed description and proofs. contract Dice2Win { /// *** Constants section // Each bet is deducted 1% in favour of the house, but no less than some minimum. // The lower bound is dictated by gas costs of the settleBet transaction, providing // headroom for up to 10 Gwei prices. uint256 constant HOUSE_EDGE_PERCENT = 1; uint256 constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0003 ether; // Bets lower than this amount do not participate in jackpot rolls (and are // not deducted JACKPOT_FEE). uint256 constant MIN_JACKPOT_BET = 0.1 ether; // Chance to win jackpot (currently 0.1%) and fee deducted into jackpot fund. uint256 constant JACKPOT_MODULO = 1000; uint256 constant JACKPOT_FEE = 0.001 ether; // There is minimum and maximum bets. uint256 constant MIN_BET = 0.01 ether; uint256 constant MAX_AMOUNT = 300000 ether; // Modulo is a number of equiprobable outcomes in a game: // - 2 for coin flip // - 6 for dice // - 6*6 = 36 for double dice // - 100 for etheroll // - 37 for roulette // etc. // It's called so because 256-bit entropy is treated like a huge integer and // the remainder of its division by modulo is considered bet outcome. uint256 constant MAX_MODULO = 100; // For modulos below this threshold rolls are checked against a bit mask, // thus allowing betting on any combination of outcomes. For example, given // modulo 6 for dice, 101000 mask (base-2, big endian) means betting on // 4 and 6; for games with modulos higher than threshold (Etheroll), a simple // limit is used, allowing betting on any outcome in [0, N) range. // // The specific value is dictated by the fact that 256-bit intermediate // multiplication result allows implementing population count efficiently // for numbers that are up to 42 bits, and 40 is the highest multiple of // eight below 42. uint256 constant MAX_MASK_MODULO = 40; // This is a check on bet mask overflow. uint256 constant MAX_BET_MASK = 2**MAX_MASK_MODULO; // EVM BLOCKHASH opcode can query no further than 256 blocks into the // past. Given that settleBet uses block hash of placeBet as one of // complementary entropy sources, we cannot process bets older than this // threshold. On rare occasions dice2.win croupier may fail to invoke // settleBet in this timespan due to technical issues or extreme Ethereum // congestion; such bets can be refunded via invoking refundBet. uint256 constant BET_EXPIRATION_BLOCKS = 250; // Some deliberately invalid address to initialize the secret signer with. // Forces maintainers to invoke setSecretSigner before processing any bets. address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // Standard contract ownership transfer. address public owner; address private nextOwner; // Adjustable max bet profit. Used to cap bets against dynamic odds. uint256 public maxProfit; // The address corresponding to a private key used to sign placeBet commits. address public secretSigner; // Accumulated jackpot fund. uint128 public jackpotSize; // Funds that are locked in potentially winning bets. Prevents contract from // committing to bets it cannot pay out. uint128 public lockedInBets; // A structure representing a single bet. struct Bet { // Wager amount in wei. uint256 amount; // Modulo of a game. uint8 modulo; // Number of winning outcomes, used to compute winning payment (* modulo/rollUnder), // and used instead of mask for games with modulo > MAX_MASK_MODULO. uint8 rollUnder; // Block number of placeBet tx. uint40 placeBlockNumber; // Bit mask representing winning bet outcomes (see MAX_MASK_MODULO comment). uint40 mask; // Address of a gambler, used to pay out winning bets. address gambler; } // Mapping from commits to all currently active & processed bets. mapping(uint256 => Bet) bets; // Croupier account. address public croupier; // Events that are issued to make statistic recovery easier. event FailedPayment(address indexed beneficiary, uint256 amount); event Payment(address indexed beneficiary, uint256 amount); event JackpotPayment(address indexed beneficiary, uint256 amount); // This event is emitted in placeBet to record commit in the logs. event Commit(uint256 commit); // Constructor. Deliberately does not take any parameters. constructor() public { owner = msg.sender; secretSigner = DUMMY_ADDRESS; croupier = DUMMY_ADDRESS; } // Standard modifier on methods invokable only by contract owner. modifier onlyOwner { require(msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } // Standard modifier on methods invokable only by contract owner. modifier onlyCroupier { require( msg.sender == croupier, "OnlyCroupier methods called by non-croupier." ); _; } // Standard contract ownership transfer implementation, function approveNextOwner(address _nextOwner) external onlyOwner { require(_nextOwner != owner, "Cannot approve current owner."); nextOwner = _nextOwner; } function acceptNextOwner() external { require( msg.sender == nextOwner, "Can only accept preapproved new owner." ); owner = nextOwner; } // Fallback function deliberately left empty. It's primary use case // is to top up the bank roll. function() public payable {} // See comment for "secretSigner" variable. function setSecretSigner(address newSecretSigner) external onlyOwner { secretSigner = newSecretSigner; } // Change the croupier address. function setCroupier(address newCroupier) external onlyOwner { croupier = newCroupier; } // Change max bet reward. Setting this to zero effectively disables betting. function setMaxProfit(uint256 _maxProfit) public onlyOwner { require(_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number."); maxProfit = _maxProfit; } // This function is used to bump up the jackpot fund. Cannot be used to lower it. function increaseJackpot(uint256 increaseAmount) external onlyOwner { require( increaseAmount <= address(this).balance, "Increase amount larger than balance." ); require( jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds." ); jackpotSize += uint128(increaseAmount); } // Funds withdrawal to cover costs of dice2.win operation. function withdrawFunds(address beneficiary, uint256 withdrawAmount) external onlyOwner { require( withdrawAmount <= address(this).balance, "Increase amount larger than balance." ); require( jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds." ); sendFunds(beneficiary, withdrawAmount, withdrawAmount); } // Contract may be destroyed only when there are no ongoing bets, // either settled or refunded. All funds are transferred to contract owner. function kill() external onlyOwner { require( lockedInBets == 0, "All bets should be processed (settled or refunded) before test_self-destruct." ); selfdestruct(owner); } /// *** Betting logic // Bet states: // amount == 0 && gambler == 0 - 'clean' (can place a bet) // amount != 0 && gambler != 0 - 'active' (can be settled or refunded) // amount == 0 && gambler != 0 - 'processed' (can clean storage) // // NOTE: Storage cleaning is not implemented in this contract version; it will be added // with the next upgrade to prevent polluting Ethereum state with expired bets. // Bet placing transaction - issued by the player. // betMask - bet outcomes bit mask for modulo <= MAX_MASK_MODULO, // [0, betMask) for larger modulos. // modulo - game modulo. // commitLastBlock - number of the maximum block where "commit" is still considered valid. // commit - Keccak256 hash of some secret "reveal" random number, to be supplied // by the dice2.win croupier bot in the settleBet transaction. Supplying // "commit" ensures that "reveal" cannot be changed behind the scenes // after placeBet have been mined. // r, s - components of ECDSA signature of (commitLastBlock, commit). v is // guaranteed to always equal 27. // // Commit, being essentially random 256-bit number, is used as a unique bet identifier in // the 'bets' mapping. // // Commits are signed with a block limit to ensure that they are used at most once - otherwise // it would be possible for a miner to place a bet with a known commit/reveal pair and tamper // with the blockhash. Croupier guarantees that commitLastBlock will always be not greater than // placeBet block number plus BET_EXPIRATION_BLOCKS. See whitepaper for details. function placeBet( uint256 betMask, uint256 modulo, uint256 commitLastBlock, uint256 commit, bytes32 r, bytes32 s ) external payable { // Check that the bet is in 'clean' state. Bet storage bet = bets[commit]; require(bet.gambler == address(0), "Bet should be in a 'clean' _state."); // Validate input data ranges. uint256 amount = msg.value; require( modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range." ); require( amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range." ); require( betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range." ); // Check that commit is valid - it has not expired and its signature is valid. require(block.number <= commitLastBlock, "Commit has expired."); bytes32 signatureHash = keccak256( abi.encodePacked(uint40(commitLastBlock), commit) ); require( secretSigner == ecrecover(signatureHash, 27, r, s), "ECDSA signature is not valid." ); uint256 rollUnder; uint256 mask; if (modulo <= MAX_MASK_MODULO) { // Small modulo games specify bet outcomes via bit mask. // rollUnder is a number of 1 bits in this mask (population count). // This magic looking formula is an efficient way to compute population // count on EVM for numbers below 2**40. For detailed proof consult // the dice2.win whitepaper. rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO; mask = betMask; } else { // Larger modulos specify the right edge of half-open interval of // winning bet outcomes. require( betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo." ); rollUnder = betMask; } // Winning amount and jackpot increase. uint256 possibleWinAmount; uint256 jackpotFee; (possibleWinAmount, jackpotFee) = getDiceWinAmount( amount, modulo, rollUnder ); // Enforce max profit limit. require( possibleWinAmount <= amount + maxProfit, "maxProfit limit violation." ); // Lock funds. lockedInBets += uint128(possibleWinAmount); jackpotSize += uint128(jackpotFee); // Check whether contract has enough funds to process this bet. require( jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet." ); // Record commit in logs. emit Commit(commit); // Store bet parameters on blockchain. bet.amount = amount; bet.modulo = uint8(modulo); bet.rollUnder = uint8(rollUnder); bet.placeBlockNumber = uint40(block.number); bet.mask = uint40(mask); bet.gambler = msg.sender; } // This is the method used to settle 99% of bets. To process a bet with a specific // "commit", settleBet should supply a "reveal" number that would Keccak256-hash to // "commit". "blockHash" is the block hash of placeBet block as seen by croupier; it // is additionally asserted to prevent changing the bet outcomes on Ethereum reorgs. function settleBet(uint256 reveal, bytes32 blockHash) external onlyCroupier { uint256 commit = uint256(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; uint256 placeBlockNumber = bet.placeBlockNumber; // Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS). require( block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before." ); require( block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM." ); require(blockhash(placeBlockNumber) == blockHash); // Settle bet using reveal and blockHash as entropy sources. settleBetCommon(bet, reveal, blockHash); } // This method is used to settle a bet that was mined into an uncle block. At this // point the player was shown some bet outcome, but the blockhash at placeBet height // is different because of Ethereum chain reorg. We supply a full merkle proof of the // placeBet transaction receipt to provide untamperable evidence that uncle block hash // indeed was present on-chain at some point. function settleBetUncleMerkleProof( uint256 reveal, uint40 canonicalBlockNumber ) external onlyCroupier { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint256 commit = uint256(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; // Check that canonical block hash can still be verified. require( block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM." ); // Verify placeBet receipt. requireCorrectReceipt(4 + 32 + 32 + 4); // Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them. bytes32 canonicalHash; bytes32 uncleHash; (canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32); require(blockhash(canonicalBlockNumber) == canonicalHash); // Settle bet using reveal and uncleHash as entropy sources. settleBetCommon(bet, reveal, uncleHash); } // Common settlement code for settleBet & settleBetUncleMerkleProof. function settleBetCommon( Bet storage bet, uint256 reveal, bytes32 entropyBlockHash ) private { // Fetch bet parameters into local variables (to save gas). uint256 amount = bet.amount; uint256 modulo = bet.modulo; uint256 rollUnder = bet.rollUnder; address gambler = bet.gambler; // Check that bet is in 'active' state. require(amount != 0, "Bet should be in an 'active' _state"); // Move bet into 'processed' state already. bet.amount = 0; // The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners // are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256 // preimage is intractable), and house is unable to alter the "reveal" after // placeBet have been mined (as Keccak256 collision finding is also intractable). bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash)); // Do a roll by taking a modulo of entropy. Compute winning amount. uint256 dice = uint256(entropy) % modulo; uint256 diceWinAmount; uint256 _jackpotFee; (diceWinAmount, _jackpotFee) = getDiceWinAmount( amount, modulo, rollUnder ); uint256 diceWin = 0; uint256 jackpotWin = 0; // Determine dice outcome. if (modulo <= MAX_MASK_MODULO) { // For small modulo games, check the outcome against a bit mask. if ((2**dice) & bet.mask != 0) { diceWin = diceWinAmount; } } else { // For larger modulos, check inclusion into half-open interval. if (dice < rollUnder) { diceWin = diceWinAmount; } } // Unlock the bet amount, regardless of the outcome. lockedInBets -= uint128(diceWinAmount); // Roll for a jackpot (if eligible). if (amount >= MIN_JACKPOT_BET) { // The second modulo, statistically independent from the "main" dice roll. // Effectively you are playing two games at once! uint256 jackpotRng = (uint256(entropy) / modulo) % JACKPOT_MODULO; // Bingo! if (jackpotRng == 0) { jackpotWin = jackpotSize; jackpotSize = 0; } } // Log jackpot win. if (jackpotWin > 0) { emit JackpotPayment(gambler, jackpotWin); } // Send the funds to gambler. sendFunds( gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin ); } // Refund transaction - return the bet amount of a roll that was not processed in a // due timeframe. Processing such blocks is not possible due to EVM limitations (see // BET_EXPIRATION_BLOCKS comment above for details). In case you ever find yourself // in a situation like this, just contact the dice2.win support, however nothing // precludes you from invoking this method yourself. function refundBet(uint256 commit) external { // Check that bet is in 'active' state. Bet storage bet = bets[commit]; uint256 amount = bet.amount; require(amount != 0, "Bet should be in an 'active' _state"); // Check that bet has already expired. require( block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM." ); // Move bet into 'processed' state, release funds. bet.amount = 0; uint256 diceWinAmount; uint256 jackpotFee; (diceWinAmount, jackpotFee) = getDiceWinAmount( amount, bet.modulo, bet.rollUnder ); lockedInBets -= uint128(diceWinAmount); jackpotSize -= uint128(jackpotFee); // Send the refund. sendFunds(bet.gambler, amount, amount); } // Get the expected win amount after house edge is subtracted. function getDiceWinAmount(uint256 amount, uint256 modulo, uint256 rollUnder) private pure returns (uint256 winAmount, uint256 jackpotFee) { require( 0 < rollUnder && rollUnder <= modulo, "Win probability out of range." ); jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0; uint256 houseEdge = (amount * HOUSE_EDGE_PERCENT) / 100; if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) { houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT; } require( houseEdge + jackpotFee <= amount, "Bet doesn't even cover house edge." ); winAmount = ((amount - houseEdge - jackpotFee) * modulo) / rollUnder; } // Helper routine to process the payment. function sendFunds( address beneficiary, uint256 amount, uint256 successLogAmount ) private { if (beneficiary.send(amount)) { emit Payment(beneficiary, successLogAmount); } else { emit FailedPayment(beneficiary, amount); } } // This are some constants making O(1) population count in placeBet possible. // See whitepaper for intuition and proofs behind it. uint256 constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001; uint256 constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041; uint256 constant POPCNT_MODULO = 0x3F; // *** Merkle proofs. // This helpers are used to verify cryptographic proofs of placeBet inclusion into // uncle blocks. They are used to prevent bet outcome changing on Ethereum reorgs without // compromising the security of the smart contract. Proof data is appended to the input data // in a simple prefix length format and does not adhere to the ABI. // Invariants checked: // - receipt trie entry contains a (1) successful transaction (2) directed at this smart // contract (3) containing commit as a payload. // - receipt trie entry is a part of a valid merkle proof of a block header // - the block header is a part of uncle list of some block on canonical chain // The implementation is optimized for gas cost and relies on the specifics of Ethereum internal data structures. // Read the whitepaper for details. // Helper to verify a full merkle proof starting from some seedHash (usually commit). "offset" is the location of the proof // beginning in the calldata. function verifyMerkleProof(uint256 seedHash, uint256 offset) private pure returns (bytes32 blockHash, bytes32 uncleHash) { // (Safe) assumption - nobody will write into RAM during this method invocation. uint256 scratchBuf1; assembly { scratchBuf1 := mload(0x40) } uint256 uncleHeaderLength; uint256 blobLength; uint256 shift; uint256 hashSlot; // Verify merkle proofs up to uncle block header. Calldata layout is: // - 2 byte big-endian slice length // - 2 byte big-endian offset to the beginning of previous slice hash within the current slice (should be zeroed) // - followed by the current slice verbatim for (; ; offset += blobLength) { assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) } if (blobLength == 0) { // Zero slice length marks the end of uncle proof. break; } assembly { shift := and(calldataload(sub(offset, 28)), 0xffff) } require(shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly { hashSlot := calldataload(add(offset, shift)) } require(hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) seedHash := sha3(scratchBuf1, blobLength) uncleHeaderLength := blobLength } } // At this moment the uncle hash is known. uncleHash = bytes32(seedHash); // Construct the uncle list of a canonical block. uint256 scratchBuf2 = scratchBuf1 + uncleHeaderLength; uint256 unclesLength; assembly { unclesLength := and(calldataload(sub(offset, 28)), 0xffff) } uint256 unclesShift; assembly { unclesShift := and(calldataload(sub(offset, 26)), 0xffff) } require( unclesShift + uncleHeaderLength <= unclesLength, "Shift bounds check." ); offset += 6; assembly { calldatacopy(scratchBuf2, offset, unclesLength) } memcpy(scratchBuf2 + unclesShift, scratchBuf1, uncleHeaderLength); assembly { seedHash := sha3(scratchBuf2, unclesLength) } offset += unclesLength; // Verify the canonical block header using the computed sha3Uncles. assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) shift := and(calldataload(sub(offset, 28)), 0xffff) } require(shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly { hashSlot := calldataload(add(offset, shift)) } require(hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) // At this moment the canonical block hash is known. blockHash := sha3(scratchBuf1, blobLength) } } // Helper to check the placeBet receipt. "offset" is the location of the proof beginning in the calldata. // RLP layout: [triePath, str([status, cumGasUsed, bloomFilter, [[address, [topics], data]])] function requireCorrectReceipt(uint256 offset) private view { uint256 leafHeaderByte; assembly { leafHeaderByte := byte(0, calldataload(offset)) } require(leafHeaderByte >= 0xf7, "Receipt leaf longer than 55 bytes."); offset += leafHeaderByte - 0xf6; uint256 pathHeaderByte; assembly { pathHeaderByte := byte(0, calldataload(offset)) } if (pathHeaderByte <= 0x7f) { offset += 1; } else { require( pathHeaderByte >= 0x80 && pathHeaderByte <= 0xb7, "Path is an RLP string." ); offset += pathHeaderByte - 0x7f; } uint256 receiptStringHeaderByte; assembly { receiptStringHeaderByte := byte(0, calldataload(offset)) } require( receiptStringHeaderByte == 0xb9, "Receipt string is always at least 256 bytes long, but less than 64k." ); offset += 3; uint256 receiptHeaderByte; assembly { receiptHeaderByte := byte(0, calldataload(offset)) } require( receiptHeaderByte == 0xf9, "Receipt is always at least 256 bytes long, but less than 64k." ); offset += 3; uint256 statusByte; assembly { statusByte := byte(0, calldataload(offset)) } require(statusByte == 0x1, "Status should be success."); offset += 1; uint256 cumGasHeaderByte; assembly { cumGasHeaderByte := byte(0, calldataload(offset)) } if (cumGasHeaderByte <= 0x7f) { offset += 1; } else { require( cumGasHeaderByte >= 0x80 && cumGasHeaderByte <= 0xb7, "Cumulative gas is an RLP string." ); offset += cumGasHeaderByte - 0x7f; } uint256 bloomHeaderByte; assembly { bloomHeaderByte := byte(0, calldataload(offset)) } require( bloomHeaderByte == 0xb9, "Bloom filter is always 256 bytes long." ); offset += 256 + 3; uint256 logsListHeaderByte; assembly { logsListHeaderByte := byte(0, calldataload(offset)) } require( logsListHeaderByte == 0xf8, "Logs list is less than 256 bytes long." ); offset += 2; uint256 logEntryHeaderByte; assembly { logEntryHeaderByte := byte(0, calldataload(offset)) } require( logEntryHeaderByte == 0xf8, "Log entry is less than 256 bytes long." ); offset += 2; uint256 addressHeaderByte; assembly { addressHeaderByte := byte(0, calldataload(offset)) } require(addressHeaderByte == 0x94, "Address is 20 bytes long."); uint256 logAddress; assembly { logAddress := and( calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff ) } require(logAddress == uint256(address(this))); } // Memory copy. function memcpy(uint256 dest, uint256 src, uint256 len) private pure { // Full 32 byte words for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Remaining bytes uint256 mask = 256**(32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } """#" text_o = """ type dice2Win_Bet is record #{config.reserved}__amount : nat; modulo : nat; rollUnder : nat; placeBlockNumber : nat; mask : nat; gambler : address; end; type constructor_args is unit; type approveNextOwner_args is record nextOwner_ : address; end; type acceptNextOwner_args is unit; type fallback_args is unit; type setSecretSigner_args is record newSecretSigner : address; end; type setCroupier_args is record newCroupier : address; end; type setMaxProfit_args is record maxProfit_ : nat; end; type increaseJackpot_args is record increaseAmount : nat; end; type withdrawFunds_args is record beneficiary : address; withdrawAmount : nat; end; type kill_args is unit; type placeBet_args is record betMask : nat; modulo : nat; commitLastBlock : nat; commit : nat; r : bytes; s : bytes; end; type settleBet_args is record reveal : nat; blockHash : bytes; end; type settleBetUncleMerkleProof_args is record reveal : nat; canonicalBlockNumber : nat; end; type refundBet_args is record commit : nat; end; type state is record owner : address; nextOwner : address; maxProfit : nat; secretSigner : address; jackpotSize : nat; lockedInBets : nat; bets : map(nat, dice2Win_Bet); croupier : address; end; function pow (const base : nat; const exp : nat) : nat is block { var b : nat := base; var e : nat := exp; var r : nat := 1n; while e > 0n block { if e mod 2n = 1n then { r := r * b; } else skip; b := b * b; e := e / 2n; } } with r; const burn_address : address = ("tz1ZZZZZZZZZZZZZZZZZZZZZZZZZZZZNkiRg" : address); const dice2Win_Bet_default : dice2Win_Bet = record [ #{config.reserved}__amount = 0n; modulo = 0n; rollUnder = 0n; placeBlockNumber = 0n; mask = 0n; gambler = burn_address ]; type router_enum is | Constructor of constructor_args | ApproveNextOwner of approveNextOwner_args | AcceptNextOwner of acceptNextOwner_args | Fallback of fallback_args | SetSecretSigner of setSecretSigner_args | SetCroupier of setCroupier_args | SetMaxProfit of setMaxProfit_args | IncreaseJackpot of increaseJackpot_args | WithdrawFunds of withdrawFunds_args | Kill of kill_args | PlaceBet of placeBet_args | SettleBet of settleBet_args | SettleBetUncleMerkleProof of settleBetUncleMerkleProof_args | RefundBet of refundBet_args; const hOUSE_EDGE_PERCENT : nat = 1n const hOUSE_EDGE_MINIMUM_AMOUNT : nat = (0.0003n * 1000000n) const mIN_JACKPOT_BET : nat = (0.1n * 1000000n) const jACKPOT_MODULO : nat = 1000n const jACKPOT_FEE : nat = (0.001n * 1000000n) const mIN_BET : nat = (0.01n * 1000000n) const mAX_AMOUNT : nat = (300000n * 1000000n) const mAX_MODULO : nat = 100n const mAX_MASK_MODULO : nat = 40n const mAX_BET_MASK : nat = pow(2n, mAX_MASK_MODULO) const bET_EXPIRATION_BLOCKS : nat = 250n const dUMMY_ADDRESS : address = ("PLEASE_REPLACE_ETH_ADDRESS_0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE_WITH_A_TEZOS_ADDRESS" : address) (* EventDefinition FailedPayment(beneficiary : address; #{config.reserved}__amount : nat) *) (* EventDefinition Payment(beneficiary : address; #{config.reserved}__amount : nat) *) (* EventDefinition JackpotPayment(beneficiary : address; #{config.reserved}__amount : nat) *) (* EventDefinition Commit(commit : nat) *) const pOPCNT_MULT : nat = 0x0000000000002000000000100000000008000000000400000000020000000001n const pOPCNT_MASK : nat = 0x0001041041041041041041041041041041041041041041041041041041041041n const pOPCNT_MODULO : nat = 0x3Fn function constructor (const test_self : state) : (state) is block { test_self.owner := Tezos.sender; test_self.secretSigner := dUMMY_ADDRESS; test_self.croupier := dUMMY_ADDRESS; } with (test_self); (* modifier onlyOwner inlined *) (* modifier onlyCroupier inlined *) function approveNextOwner (const test_self : state; const nextOwner_ : address) : (state) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); assert((nextOwner_ =/= test_self.owner)) (* "Cannot approve current owner." *); test_self.nextOwner := nextOwner_; } with (test_self); function acceptNextOwner (const test_self : state) : (state) is block { assert((Tezos.sender = test_self.nextOwner)) (* "Can only accept preapproved new owner." *); test_self.owner := test_self.nextOwner; } with (test_self); function fallback (const #{config.reserved}__unit : unit) : (unit) is block { skip } with (unit); function setSecretSigner (const test_self : state; const newSecretSigner : address) : (state) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); test_self.secretSigner := newSecretSigner; } with (test_self); function setCroupier (const test_self : state; const newCroupier : address) : (state) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); test_self.croupier := newCroupier; } with (test_self); function setMaxProfit (const test_self : state; const maxProfit_ : nat) : (state) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); assert((maxProfit_ < mAX_AMOUNT)) (* "maxProfit should be a sane number." *); test_self.maxProfit := maxProfit_; } with (test_self); function increaseJackpot (const test_self : state; const increaseAmount : nat) : (state) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); assert((increaseAmount <= self_address.#{config.reserved}__balance)) (* "Increase amount larger than balance." *); assert((((test_self.jackpotSize + test_self.lockedInBets) + increaseAmount) <= self_address.#{config.reserved}__balance)) (* "Not enough funds." *); test_self.jackpotSize := (test_self.jackpotSize + increaseAmount); } with (test_self); function sendFunds (const opList : list(operation); const test_self : state; const beneficiary : address; const #{config.reserved}__amount : nat; const successLogAmount : nat) : (list(operation)) is block { if (const op0 : operation = transaction((unit), (#{config.reserved}__amount * 1mutez), (get_contract(beneficiary) : contract(unit)))) then block { (* EmitStatement Payment(beneficiary, successLogAmount) *) } else block { (* EmitStatement FailedPayment(beneficiary, amount) *) }; } with (list [op0]); function withdrawFunds (const opList : list(operation); const test_self : state; const beneficiary : address; const withdrawAmount : nat) : (list(operation)) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); assert((withdrawAmount <= self_address.#{config.reserved}__balance)) (* "Increase amount larger than balance." *); assert((((test_self.jackpotSize + test_self.lockedInBets) + withdrawAmount) <= self_address.#{config.reserved}__balance)) (* "Not enough funds." *); opList := sendFunds((test_self : address), beneficiary, withdrawAmount, withdrawAmount); } with (opList); function kill (const test_self : state) : (unit) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); assert((test_self.lockedInBets = 0n)) (* "All bets should be processed (settled or refunded) before test_self-destruct." *); selfdestruct(test_self.owner) (* unsupported *); } with (unit); function getDiceWinAmount (const test_self : state; const #{config.reserved}__amount : nat; const modulo : nat; const rollUnder : nat) : ((nat * nat)) is block { const winAmount : nat = 0n; const jackpotFee : nat = 0n; assert(((0n < rollUnder) and (rollUnder <= modulo))) (* "Win probability out of range." *); jackpotFee := (case (#{config.reserved}__amount >= mIN_JACKPOT_BET) of | True -> jACKPOT_FEE | False -> 0n end); const houseEdge : nat = ((#{config.reserved}__amount * hOUSE_EDGE_PERCENT) / 100n); if (houseEdge < hOUSE_EDGE_MINIMUM_AMOUNT) then block { houseEdge := hOUSE_EDGE_MINIMUM_AMOUNT; } else block { skip }; assert(((houseEdge + jackpotFee) <= #{config.reserved}__amount)) (* "Bet doesn't even cover house edge." *); winAmount := ((abs(abs(#{config.reserved}__amount - houseEdge) - jackpotFee) * modulo) / rollUnder); } with ((winAmount, jackpotFee)); function placeBet (const test_self : state; const betMask : nat; const modulo : nat; const commitLastBlock : nat; const commit : nat; const r : bytes; const s : bytes) : (state) is block { const bet : dice2Win_Bet = (case test_self.bets[commit] of | None -> dice2Win_Bet_default | Some(x) -> x end); assert((bet.gambler = burn_address)) (* "Bet should be in a 'clean' _state." *); const #{config.reserved}__amount : nat = (amount / 1mutez); assert(((modulo > 1n) and (modulo <= mAX_MODULO))) (* "Modulo should be within range." *); assert(((#{config.reserved}__amount >= mIN_BET) and (#{config.reserved}__amount <= mAX_AMOUNT))) (* "Amount should be within range." *); assert(((betMask > 0n) and (betMask < mAX_BET_MASK))) (* "Mask should be within range." *); assert((0n <= commitLastBlock)) (* "Commit has expired." *); const signatureHash : bytes = sha_256((commitLastBlock, commit)); assert((test_self.secretSigner = ecrecover(signatureHash, 27n, r, s))) (* "ECDSA signature is not valid." *); const rollUnder : nat = 0n; const mask : nat = 0n; if (modulo <= mAX_MASK_MODULO) then block { rollUnder := (Bitwise.and((betMask * pOPCNT_MULT), pOPCNT_MASK) mod pOPCNT_MODULO); mask := betMask; } else block { assert(((betMask > 0n) and (betMask <= modulo))) (* "High modulo range, betMask larger than modulo." *); rollUnder := betMask; }; const possibleWinAmount : nat = 0n; const jackpotFee : nat = 0n; (possibleWinAmount, jackpotFee) := getDiceWinAmount(test_self, #{config.reserved}__amount, modulo, rollUnder); assert((possibleWinAmount <= (#{config.reserved}__amount + test_self.maxProfit))) (* "maxProfit limit violation." *); test_self.lockedInBets := (test_self.lockedInBets + possibleWinAmount); test_self.jackpotSize := (test_self.jackpotSize + jackpotFee); assert(((test_self.jackpotSize + test_self.lockedInBets) <= self_address.#{config.reserved}__balance)) (* "Cannot afford to lose this bet." *); (* EmitStatement Commit(commit) *) bet.#{config.reserved}__amount := #{config.reserved}__amount; bet.modulo := modulo; bet.rollUnder := rollUnder; bet.placeBlockNumber := 0n; bet.mask := mask; bet.gambler := Tezos.sender; } with (test_self); function settleBetCommon (const opList : list(operation); const test_self : state; const bet : dice2Win_Bet; const reveal : nat; const entropyBlockHash : bytes) : (list(operation) * state) is block { const #{config.reserved}__amount : nat = bet.#{config.reserved}__amount; const modulo : nat = bet.modulo; const rollUnder : nat = bet.rollUnder; const gambler : address = bet.gambler; assert((#{config.reserved}__amount =/= 0n)) (* "Bet should be in an 'active' _state" *); bet.#{config.reserved}__amount := 0n; const entropy : bytes = sha_256((reveal, entropyBlockHash)); const dice : nat = (abs(entropy) mod modulo); const diceWinAmount : nat = 0n; const jackpotFee_ : nat = 0n; (diceWinAmount, jackpotFee_) := getDiceWinAmount(test_self, #{config.reserved}__amount, modulo, rollUnder); const diceWin : nat = 0n; const jackpotWin : nat = 0n; if (modulo <= mAX_MASK_MODULO) then block { if (Bitwise.and(pow(2n, dice), bet.mask) =/= 0n) then block { diceWin := diceWinAmount; } else block { skip }; } else block { if (dice < rollUnder) then block { diceWin := diceWinAmount; } else block { skip }; }; test_self.lockedInBets := abs(test_self.lockedInBets - diceWinAmount); if (#{config.reserved}__amount >= mIN_JACKPOT_BET) then block { const jackpotRng : nat = ((abs(entropy) / modulo) mod jACKPOT_MODULO); if (jackpotRng = 0n) then block { jackpotWin := test_self.jackpotSize; test_self.jackpotSize := 0n; } else block { skip }; } else block { skip }; if (jackpotWin > 0n) then block { (* EmitStatement JackpotPayment(gambler, jackpotWin) *) } else block { skip }; opList := sendFunds((test_self : address), gambler, (case ((diceWin + jackpotWin) = 0n) of | True -> 1n | False -> (diceWin + jackpotWin) end), diceWin); } with (opList, test_self); function settleBet (const opList : list(operation); const test_self : state; const reveal : nat; const blockHash : bytes) : (list(operation) * state) is block { assert((Tezos.sender = test_self.croupier)) (* "OnlyCroupier methods called by non-croupier." *); const commit : nat = abs(sha_256((reveal))); const bet : dice2Win_Bet = (case test_self.bets[commit] of | None -> dice2Win_Bet_default | Some(x) -> x end); const placeBlockNumber : nat = bet.placeBlockNumber; assert((0n > placeBlockNumber)) (* "settleBet in the same block as placeBet, or before." *); assert((0n <= (placeBlockNumber + bET_EXPIRATION_BLOCKS))) (* "Blockhash can't be queried by EVM." *); assert((("00" : bytes) (* Should be blockhash of placeBlockNumber *) = blockHash)); const tmp_0 : (list(operation) * state) = settleBetCommon(test_self, bet, reveal, blockHash); opList := tmp_0.0; test_self := tmp_0.1; } with (opList, test_self); function memcpy (const dest : nat; const src : nat; const len : nat) : (unit) is block { while (len >= 32n) block { failwith("Unsupported InlineAssembly"); (* InlineAssembly { mstore(dest, mload(src)) } *) dest := (dest + 32n); src := (src + 32n); len := abs(len - 32n); }; const mask : nat = abs(pow(256n, abs(32n - len)) - 1n); failwith("Unsupported InlineAssembly"); (* InlineAssembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } *) } with (unit); function verifyMerkleProof (const seedHash : nat; const offset : nat) : ((bytes * bytes)) is block { const blockHash : bytes = ("00": bytes); const uncleHash : bytes = ("00": bytes); const scratchBuf1 : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { scratchBuf1 := mload(0x40) } *) const uncleHeaderLength : nat = 0n; const blobLength : nat = 0n; const shift : nat = 0n; const hashSlot : nat = 0n; while (True) block { failwith("Unsupported InlineAssembly"); (* InlineAssembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) } *) if (blobLength = 0n) then block { (* `break` statement is not supported in LIGO *); } else block { skip }; failwith("Unsupported InlineAssembly"); (* InlineAssembly { shift := and(calldataload(sub(offset, 28)), 0xffff) } *) assert(((shift + 32n) <= blobLength)) (* "Shift bounds check." *); offset := (offset + 4n); failwith("Unsupported InlineAssembly"); (* InlineAssembly { hashSlot := calldataload(add(offset, shift)) } *) assert((hashSlot = 0n)) (* "Non-empty hash slot." *); failwith("Unsupported InlineAssembly"); (* InlineAssembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) seedHash := keccak256(scratchBuf1, blobLength) uncleHeaderLength := blobLength } *) offset := (offset + blobLength); }; uncleHash := (seedHash : bytes); const scratchBuf2 : nat = (scratchBuf1 + uncleHeaderLength); const unclesLength : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { unclesLength := and(calldataload(sub(offset, 28)), 0xffff) } *) const unclesShift : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { unclesShift := and(calldataload(sub(offset, 26)), 0xffff) } *) assert(((unclesShift + uncleHeaderLength) <= unclesLength)) (* "Shift bounds check." *); offset := (offset + 6n); failwith("Unsupported InlineAssembly"); (* InlineAssembly { calldatacopy(scratchBuf2, offset, unclesLength) } *) memcpy((scratchBuf2 + unclesShift), scratchBuf1, uncleHeaderLength); failwith("Unsupported InlineAssembly"); (* InlineAssembly { seedHash := keccak256(scratchBuf2, unclesLength) } *) offset := (offset + unclesLength); failwith("Unsupported InlineAssembly"); (* InlineAssembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) shift := and(calldataload(sub(offset, 28)), 0xffff) } *) assert(((shift + 32n) <= blobLength)) (* "Shift bounds check." *); offset := (offset + 4n); failwith("Unsupported InlineAssembly"); (* InlineAssembly { hashSlot := calldataload(add(offset, shift)) } *) assert((hashSlot = 0n)) (* "Non-empty hash slot." *); failwith("Unsupported InlineAssembly"); (* InlineAssembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) blockHash := keccak256(scratchBuf1, blobLength) } *) } with ((blockHash, uncleHash)); function requireCorrectReceipt (const offset : nat) : (unit) is block { const leafHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { leafHeaderByte := byte(0, calldataload(offset)) } *) assert((leafHeaderByte >= 0xf7n)) (* "Receipt leaf longer than 55 bytes." *); offset := (offset + abs(leafHeaderByte - 0xf6n)); const pathHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { pathHeaderByte := byte(0, calldataload(offset)) } *) if (pathHeaderByte <= 0x7fn) then block { offset := (offset + 1n); } else block { assert(((pathHeaderByte >= 0x80n) and (pathHeaderByte <= 0xb7n))) (* "Path is an RLP string." *); offset := (offset + abs(pathHeaderByte - 0x7fn)); }; const receiptStringHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { receiptStringHeaderByte := byte(0, calldataload(offset)) } *) assert((receiptStringHeaderByte = 0xb9n)) (* "Receipt string is always at least 256 bytes long, but less than 64k." *); offset := (offset + 3n); const receiptHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { receiptHeaderByte := byte(0, calldataload(offset)) } *) assert((receiptHeaderByte = 0xf9n)) (* "Receipt is always at least 256 bytes long, but less than 64k." *); offset := (offset + 3n); const statusByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { statusByte := byte(0, calldataload(offset)) } *) assert((statusByte = 0x1n)) (* "Status should be success." *); offset := (offset + 1n); const cumGasHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { cumGasHeaderByte := byte(0, calldataload(offset)) } *) if (cumGasHeaderByte <= 0x7fn) then block { offset := (offset + 1n); } else block { assert(((cumGasHeaderByte >= 0x80n) and (cumGasHeaderByte <= 0xb7n))) (* "Cumulative gas is an RLP string." *); offset := (offset + abs(cumGasHeaderByte - 0x7fn)); }; const bloomHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { bloomHeaderByte := byte(0, calldataload(offset)) } *) assert((bloomHeaderByte = 0xb9n)) (* "Bloom filter is always 256 bytes long." *); offset := (offset + (256 + 3)); const logsListHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { logsListHeaderByte := byte(0, calldataload(offset)) } *) assert((logsListHeaderByte = 0xf8n)) (* "Logs list is less than 256 bytes long." *); offset := (offset + 2n); const logEntryHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { logEntryHeaderByte := byte(0, calldataload(offset)) } *) assert((logEntryHeaderByte = 0xf8n)) (* "Log entry is less than 256 bytes long." *); offset := (offset + 2n); const addressHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { addressHeaderByte := byte(0, calldataload(offset)) } *) assert((addressHeaderByte = 0x94n)) (* "Address is 20 bytes long." *); const logAddress : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { logAddress := and(calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff) } *) assert((logAddress = abs(self_address))); } with (unit); function settleBetUncleMerkleProof (const opList : list(operation); const test_self : state; const reveal : nat; const canonicalBlockNumber : nat) : (list(operation) * state) is block { assert((Tezos.sender = test_self.croupier)) (* "OnlyCroupier methods called by non-croupier." *); const commit : nat = abs(sha_256((reveal))); const bet : dice2Win_Bet = (case test_self.bets[commit] of | None -> dice2Win_Bet_default | Some(x) -> x end); assert((0n <= (canonicalBlockNumber + bET_EXPIRATION_BLOCKS))) (* "Blockhash can't be queried by EVM." *); requireCorrectReceipt((((4 + 32) + 32) + 4n)); const canonicalHash : bytes = ("00": bytes); const uncleHash : bytes = ("00": bytes); (canonicalHash, uncleHash) := verifyMerkleProof(commit, ((4 + 32) + 32n)); assert((("00" : bytes) (* Should be blockhash of canonicalBlockNumber *) = canonicalHash)); const tmp_0 : (list(operation) * state) = settleBetCommon(test_self, bet, reveal, uncleHash); opList := tmp_0.0; test_self := tmp_0.1; } with (opList, test_self); function refundBet (const opList : list(operation); const test_self : state; const commit : nat) : (list(operation) * state) is block { const bet : dice2Win_Bet = (case test_self.bets[commit] of | None -> dice2Win_Bet_default | Some(x) -> x end); const #{config.reserved}__amount : nat = bet.#{config.reserved}__amount; assert((#{config.reserved}__amount =/= 0n)) (* "Bet should be in an 'active' _state" *); assert((0n > (bet.placeBlockNumber + bET_EXPIRATION_BLOCKS))) (* "Blockhash can't be queried by EVM." *); bet.#{config.reserved}__amount := 0n; const diceWinAmount : nat = 0n; const jackpotFee : nat = 0n; (diceWinAmount, jackpotFee) := getDiceWinAmount(test_self, #{config.reserved}__amount, bet.modulo, bet.rollUnder); test_self.lockedInBets := abs(test_self.lockedInBets - diceWinAmount); test_self.jackpotSize := abs(test_self.jackpotSize - jackpotFee); opList := sendFunds((test_self : address), bet.gambler, #{config.reserved}__amount, #{config.reserved}__amount); } with (opList, test_self); function main (const action : router_enum; const test_self : state) : (list(operation) * state) is (case action of | Constructor(match_action) -> ((nil: list(operation)), constructor(test_self)) | ApproveNextOwner(match_action) -> ((nil: list(operation)), approveNextOwner(test_self, match_action.nextOwner_)) | AcceptNextOwner(match_action) -> ((nil: list(operation)), acceptNextOwner(test_self)) | Fallback(match_action) -> block { (* This function does nothing, but it's present in router *) const tmp : unit = fallback(unit); } with (((nil: list(operation)), test_self)) | SetSecretSigner(match_action) -> ((nil: list(operation)), setSecretSigner(test_self, match_action.newSecretSigner)) | SetCroupier(match_action) -> ((nil: list(operation)), setCroupier(test_self, match_action.newCroupier)) | SetMaxProfit(match_action) -> ((nil: list(operation)), setMaxProfit(test_self, match_action.maxProfit_)) | IncreaseJackpot(match_action) -> ((nil: list(operation)), increaseJackpot(test_self, match_action.increaseAmount)) | WithdrawFunds(match_action) -> (withdrawFunds((nil: list(operation)), test_self, match_action.beneficiary, match_action.withdrawAmount), test_self) | Kill(match_action) -> block { (* This function does nothing, but it's present in router *) const tmp : unit = kill(test_self); } with (((nil: list(operation)), test_self)) | PlaceBet(match_action) -> ((nil: list(operation)), placeBet(test_self, match_action.betMask, match_action.modulo, match_action.commitLastBlock, match_action.commit, match_action.r, match_action.s)) | SettleBet(match_action) -> settleBet((nil: list(operation)), test_self, match_action.reveal, match_action.blockHash) | SettleBetUncleMerkleProof(match_action) -> settleBetUncleMerkleProof((nil: list(operation)), test_self, match_action.reveal, match_action.canonicalBlockNumber) | RefundBet(match_action) -> refundBet((nil: list(operation)), test_self, match_action.commit) end); """#" make_test text_i, text_o, router: true, allow_need_prevent_deploy: true # ################################################################################################### it "Creatures", ()-> text_i = """ pragma solidity ^0.4.16; contract Permissions { address ownerAddress; address storageAddress; address callerAddress; function Permissions() public { ownerAddress = msg.sender; } modifier onlyOwner() { require(msg.sender == ownerAddress); _; } modifier onlyCaller() { require(msg.sender == callerAddress); _; } function getOwner() external view returns (address) { return ownerAddress; } function getStorageAddress() external view returns (address) { return storageAddress; } function getCaller() external view returns (address) { return callerAddress; } function transferOwnership(address newOwner) external onlyOwner { if (newOwner != address(0)) { ownerAddress = newOwner; } } function newStorage(address _new) external onlyOwner { if (_new != address(0)) { storageAddress = _new; } } function newCaller(address _new) external onlyOwner { if (_new != address(0)) { callerAddress = _new; } } } contract Creatures is Permissions { struct Creature { uint16 species; uint8 subSpecies; uint8 eyeColor; uint64 timestamp; } Creature[] creatures; mapping(uint256 => address) public creatureIndexToOwner; mapping(address => uint256) ownershipTokenCount; event CreateCreature(uint256 id, address indexed owner); event Transfer(address _from, address _to, uint256 creatureID); function add( address _owner, uint16 _species, uint8 _subSpecies, uint8 _eyeColor ) external onlyCaller { // do checks in caller function Creature memory _creature = Creature({ species: _species, subSpecies: _subSpecies, eyeColor: _eyeColor, timestamp: uint64(now) }); uint256 newCreatureID = creatures.push(_creature) - 1; transfer(0, _owner, newCreatureID); CreateCreature(newCreatureID, _owner); } function getCreature(uint256 id) external view returns (address, uint16, uint8, uint8, uint64) { Creature storage c = creatures[id]; address owner = creatureIndexToOwner[id]; return (owner, c.species, c.subSpecies, c.eyeColor, c.timestamp); } function transfer(address _from, address _to, uint256 _tokenId) public onlyCaller { // do checks in caller function creatureIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; } ownershipTokenCount[_to]++; Transfer(_from, _to, _tokenId); } } """#" text_o = """ type creatures_Creature is record species : nat; subSpecies : nat; eyeColor : nat; timestamp : nat; end; type newCaller_args is record new_ : address; end; type newStorage_args is record new_ : address; end; type transferOwnership_args is record newOwner : address; end; type getCaller_args is record callbackAddress : address; end; type getStorageAddress_args is record callbackAddress : address; end; type getOwner_args is record callbackAddress : address; end; type transfer_args is record from_ : address; to_ : address; tokenId_ : nat; end; type add_args is record owner_ : address; species_ : nat; subSpecies_ : nat; eyeColor_ : nat; end; type getCreature_args is record id : nat; callbackAddress : address; end; type constructor_args is unit; type state is record callerAddress : address; storageAddress : address; ownerAddress : address; creatures : map(nat, creatures_Creature); creatureIndexToOwner : map(nat, address); ownershipTokenCount : map(address, nat); end; const burn_address : address = ("tz1ZZZZZZZZZZZZZZZZZZZZZZZZZZZZNkiRg" : address); const creatures_Creature_default : creatures_Creature = record [ species = 0n; subSpecies = 0n; eyeColor = 0n; timestamp = 0n ]; type router_enum is | NewCaller of newCaller_args | NewStorage of newStorage_args | TransferOwnership of transferOwnership_args | GetCaller of getCaller_args | GetStorageAddress of getStorageAddress_args | GetOwner of getOwner_args | Transfer of transfer_args | Add of add_args | GetCreature of getCreature_args | Constructor of constructor_args; (* EventDefinition CreateCreature(id : nat; owner : address) *) (* EventDefinition Transfer(from_ : address; to_ : address; creatureID : nat) *) function newCaller (const test_self : state; const new_ : address) : (state) is block { assert((Tezos.sender = test_self.ownerAddress)); if (new_ =/= burn_address) then block { test_self.callerAddress := new_; } else block { skip }; } with (test_self); function newStorage (const test_self : state; const new_ : address) : (state) is block { assert((Tezos.sender = test_self.ownerAddress)); if (new_ =/= burn_address) then block { test_self.storageAddress := new_; } else block { skip }; } with (test_self); function transferOwnership (const test_self : state; const newOwner : address) : (state) is block { assert((Tezos.sender = test_self.ownerAddress)); if (newOwner =/= burn_address) then block { test_self.ownerAddress := newOwner; } else block { skip }; } with (test_self); function getCaller (const test_self : state) : (address) is block { skip } with (test_self.callerAddress); function getStorageAddress (const test_self : state) : (address) is block { skip } with (test_self.storageAddress); function getOwner (const test_self : state) : (address) is block { skip } with (test_self.ownerAddress); function permissions_constructor (const test_self : state) : (state) is block { test_self.ownerAddress := Tezos.sender; } with (test_self); function transfer (const test_self : state; const from_ : address; const to_ : address; const tokenId_ : nat) : (state) is block { assert((Tezos.sender = test_self.callerAddress)); test_self.creatureIndexToOwner[tokenId_] := to_; if (from_ =/= burn_address) then block { (case test_self.ownershipTokenCount[from_] of | None -> 0n | Some(x) -> x end) := abs((case test_self.ownershipTokenCount[from_] of | None -> 0n | Some(x) -> x end) - 1n); } else block { skip }; (case test_self.ownershipTokenCount[to_] of | None -> 0n | Some(x) -> x end) := (case test_self.ownershipTokenCount[to_] of | None -> 0n | Some(x) -> x end) + 1n; (* EmitStatement Transfer(_from, _to, _tokenId) *) } with (test_self); function add (const opList : list(operation); const test_self : state; const owner_ : address; const species_ : nat; const subSpecies_ : nat; const eyeColor_ : nat) : (list(operation) * state) is block { assert((Tezos.sender = test_self.callerAddress)); const creature_ : creatures_Creature = record [ species = species_; subSpecies = subSpecies_; eyeColor = eyeColor_; timestamp = abs(abs(now - ("1970-01-01T00:00:00Z" : timestamp))) ]; const tmp_0 : map(nat, creatures_Creature) = test_self.creatures; const newCreatureID : nat = abs(tmp_0[size(tmp_0)] := creature_ - 1n); transfer(burn_address, owner_, newCreatureID); (* EmitStatement CreateCreature(newCreatureID, _owner) *) } with (opList, test_self); function getCreature (const test_self : state; const id : nat) : ((address * nat * nat * nat * nat)) is block { const c : creatures_Creature = (case test_self.creatures[id] of | None -> creatures_Creature_default | Some(x) -> x end); const owner : address = (case test_self.creatureIndexToOwner[id] of | None -> burn_address | Some(x) -> x end); } with ((owner, c.species, c.subSpecies, c.eyeColor, c.timestamp)); function constructor (const test_self : state) : (state) is block { test_self := permissions_constructor(test_self); } with (test_self); function main (const action : router_enum; const test_self : state) : (list(operation) * state) is (case action of | NewCaller(match_action) -> ((nil: list(operation)), newCaller(test_self, match_action.new_)) | NewStorage(match_action) -> ((nil: list(operation)), newStorage(test_self, match_action.new_)) | TransferOwnership(match_action) -> ((nil: list(operation)), transferOwnership(test_self, match_action.newOwner)) | GetCaller(match_action) -> block { const tmp : (address) = getCaller(test_self); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(address))) end; } with ((opList, test_self)) | GetStorageAddress(match_action) -> block { const tmp : (address) = getStorageAddress(test_self); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(address))) end; } with ((opList, test_self)) | GetOwner(match_action) -> block { const tmp : (address) = getOwner(test_self); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(address))) end; } with ((opList, test_self)) | Transfer(match_action) -> ((nil: list(operation)), transfer(test_self, match_action.from_, match_action.to_, match_action.tokenId_)) | Add(match_action) -> add((nil: list(operation)), test_self, match_action.owner_, match_action.species_, match_action.subSpecies_, match_action.eyeColor_) | GetCreature(match_action) -> block { const tmp : ((address * nat * nat * nat * nat)) = getCreature(test_self, match_action.id); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract((address * nat * nat * nat * nat)))) end; } with ((opList, test_self)) | Constructor(match_action) -> ((nil: list(operation)), constructor(test_self)) end); """#" make_test text_i, text_o, router: true
true
config = require "../src/config" { translate_ligo_make_test : make_test } = require("./util") describe "translate ligo online examples", ()-> @timeout 10000 # NOTE some duplication with other tests # ################################################################################################### it "int arithmetic", ()-> text_i = """ pragma solidity ^0.5.11; contract Arith { int public value; function arith() public returns (int ret_val) { int a = 0; int b = 0; int c = 0; c = -c; c = a + b; c = a - b; c = a * b; c = a / b; return c; } } """#" text_o = """ type arith_args is record callbackAddress : address; end; type state is record value : int; end; type router_enum is | Arith of arith_args; function arith (const #{config.reserved}__unit : unit) : (int) is block { const ret_val : int = 0; const a : int = 0; const b : int = 0; const c : int = 0; c := -(c); c := (a + b); c := (a - b); c := (a * b); c := (a / b); } with (c); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Arith(match_action) -> block { const tmp : (int) = arith(unit); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(int))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "uint arithmetic", ()-> text_i = """ pragma solidity ^0.5.11; contract Arith { uint public value; function arith() public returns (uint ret_val) { uint a = 0; uint b = 0; uint c = 0; c = a + b; c = a * b; c = a / b; c = a | b; c = a & b; c = a ^ b; return c; } } """#" text_o = """ type arith_args is record callbackAddress : address; end; type state is record value : nat; end; type router_enum is | Arith of arith_args; function arith (const #{config.reserved}__unit : unit) : (nat) is block { const ret_val : nat = 0n; const a : nat = 0n; const b : nat = 0n; const c : nat = 0n; c := (a + b); c := (a * b); c := (a / b); c := Bitwise.or(a, b); c := Bitwise.and(a, b); c := Bitwise.xor(a, b); } with (c); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Arith(match_action) -> block { const tmp : (nat) = arith(unit); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(nat))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "if", ()-> text_i = """ pragma solidity ^0.5.11; contract Ifer { uint public value; function ifer() public returns (uint) { uint x = 6; if (x == 5) { x += 1; } else { x += 10; } return x; } } """#" text_o = """ type ifer_args is record callbackAddress : address; end; type state is record value : nat; end; type router_enum is | Ifer of ifer_args; function ifer (const #{config.reserved}__unit : unit) : (nat) is block { const x : nat = 6n; if (x = 5n) then block { x := (x + 1n); } else block { x := (x + 10n); }; } with (x); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Ifer(match_action) -> block { const tmp : (nat) = ifer(unit); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(nat))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "for", ()-> text_i = """ pragma solidity ^0.5.11; contract Forer { uint public value; function forer() public returns (uint ret_val) { uint y = 0; for (uint i=0; i<5; i+=1) { y += 1; } return y; } } """#" text_o = """ type forer_args is record callbackAddress : address; end; type state is record value : nat; end; type router_enum is | Forer of forer_args; function forer (const #{config.reserved}__unit : unit) : (nat) is block { const ret_val : nat = 0n; const y : nat = 0n; const i : nat = 0n; while (i < 5n) block { y := (y + 1n); i := (i + 1n); }; } with (y); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Forer(match_action) -> block { const tmp : (nat) = forer(unit); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(nat))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "while", ()-> text_i = """ pragma solidity ^0.5.11; contract Whiler { uint public value; function whiler() public returns (uint ret_val) { uint y = 0; while (y != 2) { y += 1; } return y; } } """#" text_o = """ type whiler_args is record callbackAddress : address; end; type state is record value : nat; end; type router_enum is | Whiler of whiler_args; function whiler (const #{config.reserved}__unit : unit) : (nat) is block { const ret_val : nat = 0n; const y : nat = 0n; while (y =/= 2n) block { y := (y + 1n); }; } with (y); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Whiler(match_action) -> block { const tmp : (nat) = whiler(unit); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(nat))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "fn call", ()-> text_i = """ pragma solidity ^0.5.11; contract Fn_call { int public value; function fn1(int a) public returns (int ret_val) { value += 1; return a; } function fn2() public returns (int ret_val) { fn1(1); int res = 1; return res; } } """#" text_o = """ type fn1_args is record a : int; callbackAddress : address; end; type fn2_args is record callbackAddress : address; end; type state is record value : int; end; type router_enum is | Fn1 of fn1_args | Fn2 of fn2_args; function fn1 (const contract_storage : state; const a : int) : (state * int) is block { const ret_val : int = 0; contract_storage.value := (contract_storage.value + 1); } with (contract_storage, a); function fn2 (const contract_storage : state) : (state * int) is block { const ret_val : int = 0; const tmp_0 : (state * int) = fn1(contract_storage, 1); contract_storage := tmp_0.0; const res : int = 1; } with (contract_storage, res); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Fn1(match_action) -> block { const tmp : (state * int) = fn1(contract_storage, match_action.a); var opList : list(operation) := list transaction((tmp.0), 0mutez, (get_contract(match_action.callbackAddress) : contract(state))) end; } with ((opList, tmp.0)) | Fn2(match_action) -> block { const tmp : (state * int) = fn2(contract_storage); var opList : list(operation) := list transaction((tmp.0), 0mutez, (get_contract(match_action.callbackAddress) : contract(state))) end; } with ((opList, tmp.0)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "simplecoin", ()-> text_i = """ pragma solidity ^0.5.11; contract Coin { address minter; mapping (address => uint) balances; constructor() public { minter = msg.sender; } function mint(address owner, uint amount) public { if (msg.sender == minter) { balances[owner] += amount; } } function send(address receiver, uint amount) public { if (balances[msg.sender] >= amount) { balances[msg.sender] -= amount; balances[receiver] += amount; } } function queryBalance(address addr) public view returns (uint balance) { return balances[addr]; } } """#" text_o = """ type constructor_args is unit; type mint_args is record owner : address; #{config.reserved}__amount : nat; end; type send_args is record receiver : address; #{config.reserved}__amount : nat; end; type queryBalance_args is record addr : address; callbackAddress : address; end; type state is record minter : address; balances : map(address, nat); end; type router_enum is | Constructor of constructor_args | Mint of mint_args | Send of send_args | QueryBalance of queryBalance_args; function constructor (const contract_storage : state) : (state) is block { contract_storage.minter := Tezos.sender; } with (contract_storage); function mint (const contract_storage : state; const owner : address; const #{config.reserved}__amount : nat) : (state) is block { if (Tezos.sender = contract_storage.minter) then block { contract_storage.balances[owner] := ((case contract_storage.balances[owner] of | None -> 0n | Some(x) -> x end) + #{config.reserved}__amount); } else block { skip }; } with (contract_storage); function send (const contract_storage : state; const receiver : address; const #{config.reserved}__amount : nat) : (state) is block { if ((case contract_storage.balances[Tezos.sender] of | None -> 0n | Some(x) -> x end) >= #{config.reserved}__amount) then block { contract_storage.balances[Tezos.sender] := abs((case contract_storage.balances[Tezos.sender] of | None -> 0n | Some(x) -> x end) - #{config.reserved}__amount); contract_storage.balances[receiver] := ((case contract_storage.balances[receiver] of | None -> 0n | Some(x) -> x end) + #{config.reserved}__amount); } else block { skip }; } with (contract_storage); function queryBalance (const contract_storage : state; const addr : address) : (nat) is block { const #{config.reserved}__balance : nat = 0n; } with ((case contract_storage.balances[addr] of | None -> 0n | Some(x) -> x end)); function main (const action : router_enum; const contract_storage : state) : (list(operation) * state) is (case action of | Constructor(match_action) -> ((nil: list(operation)), constructor(contract_storage)) | Mint(match_action) -> ((nil: list(operation)), mint(contract_storage, match_action.owner, match_action.#{config.reserved}__amount)) | Send(match_action) -> ((nil: list(operation)), send(contract_storage, match_action.receiver, match_action.#{config.reserved}__amount)) | QueryBalance(match_action) -> block { const tmp : (nat) = queryBalance(contract_storage, match_action.addr); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(nat))) end; } with ((opList, contract_storage)) end); """ make_test text_i, text_o, router: true # ################################################################################################### it "AtomicSwap", ()-> text_i = """ pragma solidity ^0.4.18; contract AtomicSwapEther { struct Swap { uint256 timelock; uint256 value; address ethTrader; address withdrawTrader; bytes32 secretLock; bytes secretKey; } enum States { INVALID, OPEN, CLOSED, EXPIRED } mapping (bytes32 => Swap) private swaps; mapping (bytes32 => States) private swapStates; event Open(bytes32 _swapID, address _withdrawTrader,bytes32 _secretLock); event Expire(bytes32 _swapID); event Close(bytes32 _swapID, bytes _secretKey); modifier onlyInvalidSwaps(bytes32 _swapID) { require (swapStates[_swapID] == States.INVALID); _; } modifier onlyOpenSwaps(bytes32 _swapID) { require (swapStates[_swapID] == States.OPEN); _; } modifier onlyClosedSwaps(bytes32 _swapID) { require (swapStates[_swapID] == States.CLOSED); _; } modifier onlyExpirableSwaps(bytes32 _swapID) { require (now >= swaps[_swapID].timelock); _; } modifier onlyWithSecretKey(bytes32 _swapID, bytes _secretKey) { // TODO: Require _secretKey length to conform to the spec require (swaps[_swapID].secretLock == sha256(_secretKey)); _; } function open(bytes32 _swapID, address _withdrawTrader, bytes32 _secretLock, uint256 _timelock) public onlyInvalidSwaps(_swapID) payable { // Store the details of the swap. Swap memory swap = Swap({ timelock: _timelock, value: msg.value, ethTrader: msg.sender, withdrawTrader: _withdrawTrader, secretLock: _secretLock, secretKey: new bytes(0) }); swaps[_swapID] = swap; swapStates[_swapID] = States.OPEN; // Trigger open event. Open(_swapID, _withdrawTrader, _secretLock); } function close(bytes32 _swapID, bytes _secretKey) public onlyOpenSwaps(_swapID) onlyWithSecretKey(_swapID, _secretKey) { // Close the swap. Swap memory swap = swaps[_swapID]; swaps[_swapID].secretKey = _secretKey; swapStates[_swapID] = States.CLOSED; // Transfer the ETH funds from this contract to the withdrawing trader. swap.withdrawTrader.transfer(swap.value); // Trigger close event. Close(_swapID, _secretKey); } function expire(bytes32 _swapID) public onlyOpenSwaps(_swapID) onlyExpirableSwaps(_swapID) { // Expire the swap. Swap memory swap = swaps[_swapID]; swapStates[_swapID] = States.EXPIRED; // Transfer the ETH value from this contract back to the ETH trader. swap.ethTrader.transfer(swap.value); // Trigger expire event. Expire(_swapID); } function check(bytes32 _swapID) public view returns (uint256 timelock, uint256 value, address withdrawTrader, bytes32 secretLock) { Swap memory swap = swaps[_swapID]; return (swap.timelock, swap.value, swap.withdrawTrader, swap.secretLock); } function checkSecretKey(bytes32 _swapID) public view onlyClosedSwaps(_swapID) returns (bytes secretKey) { Swap memory swap = swaps[_swapID]; return swap.secretKey; } } """#" text_o = """ type atomicSwapEther_Swap is record timelock : nat; value : nat; ethTrader : address; withdrawTrader : address; secretLock : bytes; secretKey : bytes; end; type open_args is record swapID_ : bytes; withdrawTrader_ : address; secretLock_ : bytes; timelock_ : nat; end; type close_args is record swapID_ : bytes; secretKey_ : bytes; end; type expire_args is record swapID_ : bytes; end; type check_args is record swapID_ : bytes; callbackAddress : address; end; type checkSecretKey_args is record swapID_ : bytes; callbackAddress : address; end; type state is record swaps : map(bytes, atomicSwapEther_Swap); swapStates : map(bytes, nat); end; const burn_address : address = ("tz1ZZZZZZZZZZZZZZZZZZZZZZZZZZZZNkiRg" : address); const atomicSwapEther_Swap_default : atomicSwapEther_Swap = record [ timelock = 0n; value = 0n; ethTrader = burn_address; withdrawTrader = burn_address; secretLock = ("00": bytes); secretKey = ("0PI:KEY:<KEY>END_PI": bytes) ]; const states_INVALID : nat = 0n; const states_OPEN : nat = 1n; const states_CLOSED : nat = 2n; const states_EXPIRED : nat = 3n; type router_enum is | Open of open_args | Close of close_args | Expire of expire_args | Check of check_args | CheckSecretKey of checkSecretKey_args; (* EventDefinition Open(swapID_ : bytes; withdrawTrader_ : address; secretLock_ : bytes) *) (* EventDefinition Expire(swapID_ : bytes) *) (* EventDefinition Close(swapID_ : bytes; secretKey_ : bytes) *) (* enum States converted into list of nats *) (* modifier onlyInvalidSwaps inlined *) (* modifier onlyOpenSwaps inlined *) (* modifier onlyClosedSwaps inlined *) (* modifier onlyExpirableSwaps inlined *) (* modifier onlyWithSecretKey inlined *) function open (const test_self : state; const swapID_ : bytes; const withdrawTrader_ : address; const secretLock_ : bytes; const timelock_ : nat) : (state) is block { assert(((case test_self.swapStates[swapID_] of | None -> 0n | Some(x) -> x end) = states_INVALID)); const swap : atomicSwapEther_Swap = record [ timelock = timelock_; value = (amount / 1mutez); ethTrader = Tezos.sender; withdrawTrader = withdrawTrader_; secretLock = secretLock_; secretKey = ("0PI:KEY:<KEY>END_PI": bytes) (* args: 0 *) ]; test_self.swaps[swapID_] := swap; test_self.swapStates[swapID_] := states_OPEN; (* EmitStatement Open(_swapID, _withdrawTrader, _secretLock) *) } with (test_self); function close (const opList : list(operation); const test_self : state; const swapID_ : bytes; const secretKey_ : bytes) : (list(operation) * state) is block { assert(((case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end).secretLock = sha_256(secretKey_))); assert(((case test_self.swapStates[swapID_] of | None -> 0n | Some(x) -> x end) = states_OPEN)); const swap : atomicSwapEther_Swap = (case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end); test_self.swaps[swapID_].secretKey := secretKey_; test_self.swapStates[swapID_] := states_CLOSED; const op0 : operation = transaction((unit), (swap.value * 1mutez), (get_contract(swap.withdrawTrader) : contract(unit))); (* EmitStatement Close(_swapID, _secretKey) *) } with (list [op0], test_self); function expire (const opList : list(operation); const test_self : state; const swapID_ : bytes) : (list(operation) * state) is block { assert((abs(now - ("1970-01-01T00:00:00Z" : timestamp)) >= (case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end).timelock)); assert(((case test_self.swapStates[swapID_] of | None -> 0n | Some(x) -> x end) = states_OPEN)); const swap : atomicSwapEther_Swap = (case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end); test_self.swapStates[swapID_] := states_EXPIRED; const op0 : operation = transaction((unit), (swap.value * 1mutez), (get_contract(swap.ethTrader) : contract(unit))); (* EmitStatement Expire(_swapID) *) } with (list [op0], test_self); function check (const test_self : state; const swapID_ : bytes) : ((nat * nat * address * bytes)) is block { const timelock : nat = 0n; const value : nat = 0n; const withdrawTrader : address = burn_address; const secretLock : bytes = ("00": bytes); const swap : atomicSwapEther_Swap = (case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end); } with ((swap.timelock, swap.value, swap.withdrawTrader, swap.secretLock)); function checkSecretKey (const test_self : state; const swapID_ : bytes) : (bytes) is block { assert(((case test_self.swapStates[swapID_] of | None -> 0n | Some(x) -> x end) = states_CLOSED)); const secretKey : bytes = ("00": bytes); const swap : atomicSwapEther_Swap = (case test_self.swaps[swapID_] of | None -> atomicSwapEther_Swap_default | Some(x) -> x end); } with (swap.secretKey); function main (const action : router_enum; const test_self : state) : (list(operation) * state) is (case action of | Open(match_action) -> ((nil: list(operation)), open(test_self, match_action.swapID_, match_action.withdrawTrader_, match_action.secretLock_, match_action.timelock_)) | Close(match_action) -> close((nil: list(operation)), test_self, match_action.swapID_, match_action.secretKey_) | Expire(match_action) -> expire((nil: list(operation)), test_self, match_action.swapID_) | Check(match_action) -> block { const tmp : ((nat * nat * address * bytes)) = check(test_self, match_action.swapID_); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract((nat * nat * address * bytes)))) end; } with ((opList, test_self)) | CheckSecretKey(match_action) -> block { const tmp : (bytes) = checkSecretKey(test_self, match_action.swapID_); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(bytes))) end; } with ((opList, test_self)) end); """#" make_test text_i, text_o, router: true # ################################################################################################### it "Dice", ()-> text_i = """ pragma solidity ^0.4.24; // * dice2.win - fair games that pay Ether. Version 5. // // * Ethereum smart contract, deployed at 0xD1CEeeeee83F8bCF3BEDad437202b6154E9F5405. // // * Uses hybrid commit-reveal + block hash random number generation that is immune // to tampering by players, house and miners. Apart from being fully transparent, // this also allows arbitrarily high bets. // // * Refer to https://dice2.win/whitepaper.pdf for detailed description and proofs. contract Dice2Win { /// *** Constants section // Each bet is deducted 1% in favour of the house, but no less than some minimum. // The lower bound is dictated by gas costs of the settleBet transaction, providing // headroom for up to 10 Gwei prices. uint256 constant HOUSE_EDGE_PERCENT = 1; uint256 constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0003 ether; // Bets lower than this amount do not participate in jackpot rolls (and are // not deducted JACKPOT_FEE). uint256 constant MIN_JACKPOT_BET = 0.1 ether; // Chance to win jackpot (currently 0.1%) and fee deducted into jackpot fund. uint256 constant JACKPOT_MODULO = 1000; uint256 constant JACKPOT_FEE = 0.001 ether; // There is minimum and maximum bets. uint256 constant MIN_BET = 0.01 ether; uint256 constant MAX_AMOUNT = 300000 ether; // Modulo is a number of equiprobable outcomes in a game: // - 2 for coin flip // - 6 for dice // - 6*6 = 36 for double dice // - 100 for etheroll // - 37 for roulette // etc. // It's called so because 256-bit entropy is treated like a huge integer and // the remainder of its division by modulo is considered bet outcome. uint256 constant MAX_MODULO = 100; // For modulos below this threshold rolls are checked against a bit mask, // thus allowing betting on any combination of outcomes. For example, given // modulo 6 for dice, 101000 mask (base-2, big endian) means betting on // 4 and 6; for games with modulos higher than threshold (Etheroll), a simple // limit is used, allowing betting on any outcome in [0, N) range. // // The specific value is dictated by the fact that 256-bit intermediate // multiplication result allows implementing population count efficiently // for numbers that are up to 42 bits, and 40 is the highest multiple of // eight below 42. uint256 constant MAX_MASK_MODULO = 40; // This is a check on bet mask overflow. uint256 constant MAX_BET_MASK = 2**MAX_MASK_MODULO; // EVM BLOCKHASH opcode can query no further than 256 blocks into the // past. Given that settleBet uses block hash of placeBet as one of // complementary entropy sources, we cannot process bets older than this // threshold. On rare occasions dice2.win croupier may fail to invoke // settleBet in this timespan due to technical issues or extreme Ethereum // congestion; such bets can be refunded via invoking refundBet. uint256 constant BET_EXPIRATION_BLOCKS = 250; // Some deliberately invalid address to initialize the secret signer with. // Forces maintainers to invoke setSecretSigner before processing any bets. address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // Standard contract ownership transfer. address public owner; address private nextOwner; // Adjustable max bet profit. Used to cap bets against dynamic odds. uint256 public maxProfit; // The address corresponding to a private key used to sign placeBet commits. address public secretSigner; // Accumulated jackpot fund. uint128 public jackpotSize; // Funds that are locked in potentially winning bets. Prevents contract from // committing to bets it cannot pay out. uint128 public lockedInBets; // A structure representing a single bet. struct Bet { // Wager amount in wei. uint256 amount; // Modulo of a game. uint8 modulo; // Number of winning outcomes, used to compute winning payment (* modulo/rollUnder), // and used instead of mask for games with modulo > MAX_MASK_MODULO. uint8 rollUnder; // Block number of placeBet tx. uint40 placeBlockNumber; // Bit mask representing winning bet outcomes (see MAX_MASK_MODULO comment). uint40 mask; // Address of a gambler, used to pay out winning bets. address gambler; } // Mapping from commits to all currently active & processed bets. mapping(uint256 => Bet) bets; // Croupier account. address public croupier; // Events that are issued to make statistic recovery easier. event FailedPayment(address indexed beneficiary, uint256 amount); event Payment(address indexed beneficiary, uint256 amount); event JackpotPayment(address indexed beneficiary, uint256 amount); // This event is emitted in placeBet to record commit in the logs. event Commit(uint256 commit); // Constructor. Deliberately does not take any parameters. constructor() public { owner = msg.sender; secretSigner = DUMMY_ADDRESS; croupier = DUMMY_ADDRESS; } // Standard modifier on methods invokable only by contract owner. modifier onlyOwner { require(msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } // Standard modifier on methods invokable only by contract owner. modifier onlyCroupier { require( msg.sender == croupier, "OnlyCroupier methods called by non-croupier." ); _; } // Standard contract ownership transfer implementation, function approveNextOwner(address _nextOwner) external onlyOwner { require(_nextOwner != owner, "Cannot approve current owner."); nextOwner = _nextOwner; } function acceptNextOwner() external { require( msg.sender == nextOwner, "Can only accept preapproved new owner." ); owner = nextOwner; } // Fallback function deliberately left empty. It's primary use case // is to top up the bank roll. function() public payable {} // See comment for "secretSigner" variable. function setSecretSigner(address newSecretSigner) external onlyOwner { secretSigner = newSecretSigner; } // Change the croupier address. function setCroupier(address newCroupier) external onlyOwner { croupier = newCroupier; } // Change max bet reward. Setting this to zero effectively disables betting. function setMaxProfit(uint256 _maxProfit) public onlyOwner { require(_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number."); maxProfit = _maxProfit; } // This function is used to bump up the jackpot fund. Cannot be used to lower it. function increaseJackpot(uint256 increaseAmount) external onlyOwner { require( increaseAmount <= address(this).balance, "Increase amount larger than balance." ); require( jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds." ); jackpotSize += uint128(increaseAmount); } // Funds withdrawal to cover costs of dice2.win operation. function withdrawFunds(address beneficiary, uint256 withdrawAmount) external onlyOwner { require( withdrawAmount <= address(this).balance, "Increase amount larger than balance." ); require( jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds." ); sendFunds(beneficiary, withdrawAmount, withdrawAmount); } // Contract may be destroyed only when there are no ongoing bets, // either settled or refunded. All funds are transferred to contract owner. function kill() external onlyOwner { require( lockedInBets == 0, "All bets should be processed (settled or refunded) before test_self-destruct." ); selfdestruct(owner); } /// *** Betting logic // Bet states: // amount == 0 && gambler == 0 - 'clean' (can place a bet) // amount != 0 && gambler != 0 - 'active' (can be settled or refunded) // amount == 0 && gambler != 0 - 'processed' (can clean storage) // // NOTE: Storage cleaning is not implemented in this contract version; it will be added // with the next upgrade to prevent polluting Ethereum state with expired bets. // Bet placing transaction - issued by the player. // betMask - bet outcomes bit mask for modulo <= MAX_MASK_MODULO, // [0, betMask) for larger modulos. // modulo - game modulo. // commitLastBlock - number of the maximum block where "commit" is still considered valid. // commit - Keccak256 hash of some secret "reveal" random number, to be supplied // by the dice2.win croupier bot in the settleBet transaction. Supplying // "commit" ensures that "reveal" cannot be changed behind the scenes // after placeBet have been mined. // r, s - components of ECDSA signature of (commitLastBlock, commit). v is // guaranteed to always equal 27. // // Commit, being essentially random 256-bit number, is used as a unique bet identifier in // the 'bets' mapping. // // Commits are signed with a block limit to ensure that they are used at most once - otherwise // it would be possible for a miner to place a bet with a known commit/reveal pair and tamper // with the blockhash. Croupier guarantees that commitLastBlock will always be not greater than // placeBet block number plus BET_EXPIRATION_BLOCKS. See whitepaper for details. function placeBet( uint256 betMask, uint256 modulo, uint256 commitLastBlock, uint256 commit, bytes32 r, bytes32 s ) external payable { // Check that the bet is in 'clean' state. Bet storage bet = bets[commit]; require(bet.gambler == address(0), "Bet should be in a 'clean' _state."); // Validate input data ranges. uint256 amount = msg.value; require( modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range." ); require( amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range." ); require( betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range." ); // Check that commit is valid - it has not expired and its signature is valid. require(block.number <= commitLastBlock, "Commit has expired."); bytes32 signatureHash = keccak256( abi.encodePacked(uint40(commitLastBlock), commit) ); require( secretSigner == ecrecover(signatureHash, 27, r, s), "ECDSA signature is not valid." ); uint256 rollUnder; uint256 mask; if (modulo <= MAX_MASK_MODULO) { // Small modulo games specify bet outcomes via bit mask. // rollUnder is a number of 1 bits in this mask (population count). // This magic looking formula is an efficient way to compute population // count on EVM for numbers below 2**40. For detailed proof consult // the dice2.win whitepaper. rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO; mask = betMask; } else { // Larger modulos specify the right edge of half-open interval of // winning bet outcomes. require( betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo." ); rollUnder = betMask; } // Winning amount and jackpot increase. uint256 possibleWinAmount; uint256 jackpotFee; (possibleWinAmount, jackpotFee) = getDiceWinAmount( amount, modulo, rollUnder ); // Enforce max profit limit. require( possibleWinAmount <= amount + maxProfit, "maxProfit limit violation." ); // Lock funds. lockedInBets += uint128(possibleWinAmount); jackpotSize += uint128(jackpotFee); // Check whether contract has enough funds to process this bet. require( jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet." ); // Record commit in logs. emit Commit(commit); // Store bet parameters on blockchain. bet.amount = amount; bet.modulo = uint8(modulo); bet.rollUnder = uint8(rollUnder); bet.placeBlockNumber = uint40(block.number); bet.mask = uint40(mask); bet.gambler = msg.sender; } // This is the method used to settle 99% of bets. To process a bet with a specific // "commit", settleBet should supply a "reveal" number that would Keccak256-hash to // "commit". "blockHash" is the block hash of placeBet block as seen by croupier; it // is additionally asserted to prevent changing the bet outcomes on Ethereum reorgs. function settleBet(uint256 reveal, bytes32 blockHash) external onlyCroupier { uint256 commit = uint256(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; uint256 placeBlockNumber = bet.placeBlockNumber; // Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS). require( block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before." ); require( block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM." ); require(blockhash(placeBlockNumber) == blockHash); // Settle bet using reveal and blockHash as entropy sources. settleBetCommon(bet, reveal, blockHash); } // This method is used to settle a bet that was mined into an uncle block. At this // point the player was shown some bet outcome, but the blockhash at placeBet height // is different because of Ethereum chain reorg. We supply a full merkle proof of the // placeBet transaction receipt to provide untamperable evidence that uncle block hash // indeed was present on-chain at some point. function settleBetUncleMerkleProof( uint256 reveal, uint40 canonicalBlockNumber ) external onlyCroupier { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint256 commit = uint256(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; // Check that canonical block hash can still be verified. require( block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM." ); // Verify placeBet receipt. requireCorrectReceipt(4 + 32 + 32 + 4); // Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them. bytes32 canonicalHash; bytes32 uncleHash; (canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32); require(blockhash(canonicalBlockNumber) == canonicalHash); // Settle bet using reveal and uncleHash as entropy sources. settleBetCommon(bet, reveal, uncleHash); } // Common settlement code for settleBet & settleBetUncleMerkleProof. function settleBetCommon( Bet storage bet, uint256 reveal, bytes32 entropyBlockHash ) private { // Fetch bet parameters into local variables (to save gas). uint256 amount = bet.amount; uint256 modulo = bet.modulo; uint256 rollUnder = bet.rollUnder; address gambler = bet.gambler; // Check that bet is in 'active' state. require(amount != 0, "Bet should be in an 'active' _state"); // Move bet into 'processed' state already. bet.amount = 0; // The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners // are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256 // preimage is intractable), and house is unable to alter the "reveal" after // placeBet have been mined (as Keccak256 collision finding is also intractable). bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash)); // Do a roll by taking a modulo of entropy. Compute winning amount. uint256 dice = uint256(entropy) % modulo; uint256 diceWinAmount; uint256 _jackpotFee; (diceWinAmount, _jackpotFee) = getDiceWinAmount( amount, modulo, rollUnder ); uint256 diceWin = 0; uint256 jackpotWin = 0; // Determine dice outcome. if (modulo <= MAX_MASK_MODULO) { // For small modulo games, check the outcome against a bit mask. if ((2**dice) & bet.mask != 0) { diceWin = diceWinAmount; } } else { // For larger modulos, check inclusion into half-open interval. if (dice < rollUnder) { diceWin = diceWinAmount; } } // Unlock the bet amount, regardless of the outcome. lockedInBets -= uint128(diceWinAmount); // Roll for a jackpot (if eligible). if (amount >= MIN_JACKPOT_BET) { // The second modulo, statistically independent from the "main" dice roll. // Effectively you are playing two games at once! uint256 jackpotRng = (uint256(entropy) / modulo) % JACKPOT_MODULO; // Bingo! if (jackpotRng == 0) { jackpotWin = jackpotSize; jackpotSize = 0; } } // Log jackpot win. if (jackpotWin > 0) { emit JackpotPayment(gambler, jackpotWin); } // Send the funds to gambler. sendFunds( gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin ); } // Refund transaction - return the bet amount of a roll that was not processed in a // due timeframe. Processing such blocks is not possible due to EVM limitations (see // BET_EXPIRATION_BLOCKS comment above for details). In case you ever find yourself // in a situation like this, just contact the dice2.win support, however nothing // precludes you from invoking this method yourself. function refundBet(uint256 commit) external { // Check that bet is in 'active' state. Bet storage bet = bets[commit]; uint256 amount = bet.amount; require(amount != 0, "Bet should be in an 'active' _state"); // Check that bet has already expired. require( block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM." ); // Move bet into 'processed' state, release funds. bet.amount = 0; uint256 diceWinAmount; uint256 jackpotFee; (diceWinAmount, jackpotFee) = getDiceWinAmount( amount, bet.modulo, bet.rollUnder ); lockedInBets -= uint128(diceWinAmount); jackpotSize -= uint128(jackpotFee); // Send the refund. sendFunds(bet.gambler, amount, amount); } // Get the expected win amount after house edge is subtracted. function getDiceWinAmount(uint256 amount, uint256 modulo, uint256 rollUnder) private pure returns (uint256 winAmount, uint256 jackpotFee) { require( 0 < rollUnder && rollUnder <= modulo, "Win probability out of range." ); jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0; uint256 houseEdge = (amount * HOUSE_EDGE_PERCENT) / 100; if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) { houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT; } require( houseEdge + jackpotFee <= amount, "Bet doesn't even cover house edge." ); winAmount = ((amount - houseEdge - jackpotFee) * modulo) / rollUnder; } // Helper routine to process the payment. function sendFunds( address beneficiary, uint256 amount, uint256 successLogAmount ) private { if (beneficiary.send(amount)) { emit Payment(beneficiary, successLogAmount); } else { emit FailedPayment(beneficiary, amount); } } // This are some constants making O(1) population count in placeBet possible. // See whitepaper for intuition and proofs behind it. uint256 constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001; uint256 constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041; uint256 constant POPCNT_MODULO = 0x3F; // *** Merkle proofs. // This helpers are used to verify cryptographic proofs of placeBet inclusion into // uncle blocks. They are used to prevent bet outcome changing on Ethereum reorgs without // compromising the security of the smart contract. Proof data is appended to the input data // in a simple prefix length format and does not adhere to the ABI. // Invariants checked: // - receipt trie entry contains a (1) successful transaction (2) directed at this smart // contract (3) containing commit as a payload. // - receipt trie entry is a part of a valid merkle proof of a block header // - the block header is a part of uncle list of some block on canonical chain // The implementation is optimized for gas cost and relies on the specifics of Ethereum internal data structures. // Read the whitepaper for details. // Helper to verify a full merkle proof starting from some seedHash (usually commit). "offset" is the location of the proof // beginning in the calldata. function verifyMerkleProof(uint256 seedHash, uint256 offset) private pure returns (bytes32 blockHash, bytes32 uncleHash) { // (Safe) assumption - nobody will write into RAM during this method invocation. uint256 scratchBuf1; assembly { scratchBuf1 := mload(0x40) } uint256 uncleHeaderLength; uint256 blobLength; uint256 shift; uint256 hashSlot; // Verify merkle proofs up to uncle block header. Calldata layout is: // - 2 byte big-endian slice length // - 2 byte big-endian offset to the beginning of previous slice hash within the current slice (should be zeroed) // - followed by the current slice verbatim for (; ; offset += blobLength) { assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) } if (blobLength == 0) { // Zero slice length marks the end of uncle proof. break; } assembly { shift := and(calldataload(sub(offset, 28)), 0xffff) } require(shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly { hashSlot := calldataload(add(offset, shift)) } require(hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) seedHash := sha3(scratchBuf1, blobLength) uncleHeaderLength := blobLength } } // At this moment the uncle hash is known. uncleHash = bytes32(seedHash); // Construct the uncle list of a canonical block. uint256 scratchBuf2 = scratchBuf1 + uncleHeaderLength; uint256 unclesLength; assembly { unclesLength := and(calldataload(sub(offset, 28)), 0xffff) } uint256 unclesShift; assembly { unclesShift := and(calldataload(sub(offset, 26)), 0xffff) } require( unclesShift + uncleHeaderLength <= unclesLength, "Shift bounds check." ); offset += 6; assembly { calldatacopy(scratchBuf2, offset, unclesLength) } memcpy(scratchBuf2 + unclesShift, scratchBuf1, uncleHeaderLength); assembly { seedHash := sha3(scratchBuf2, unclesLength) } offset += unclesLength; // Verify the canonical block header using the computed sha3Uncles. assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) shift := and(calldataload(sub(offset, 28)), 0xffff) } require(shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly { hashSlot := calldataload(add(offset, shift)) } require(hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) // At this moment the canonical block hash is known. blockHash := sha3(scratchBuf1, blobLength) } } // Helper to check the placeBet receipt. "offset" is the location of the proof beginning in the calldata. // RLP layout: [triePath, str([status, cumGasUsed, bloomFilter, [[address, [topics], data]])] function requireCorrectReceipt(uint256 offset) private view { uint256 leafHeaderByte; assembly { leafHeaderByte := byte(0, calldataload(offset)) } require(leafHeaderByte >= 0xf7, "Receipt leaf longer than 55 bytes."); offset += leafHeaderByte - 0xf6; uint256 pathHeaderByte; assembly { pathHeaderByte := byte(0, calldataload(offset)) } if (pathHeaderByte <= 0x7f) { offset += 1; } else { require( pathHeaderByte >= 0x80 && pathHeaderByte <= 0xb7, "Path is an RLP string." ); offset += pathHeaderByte - 0x7f; } uint256 receiptStringHeaderByte; assembly { receiptStringHeaderByte := byte(0, calldataload(offset)) } require( receiptStringHeaderByte == 0xb9, "Receipt string is always at least 256 bytes long, but less than 64k." ); offset += 3; uint256 receiptHeaderByte; assembly { receiptHeaderByte := byte(0, calldataload(offset)) } require( receiptHeaderByte == 0xf9, "Receipt is always at least 256 bytes long, but less than 64k." ); offset += 3; uint256 statusByte; assembly { statusByte := byte(0, calldataload(offset)) } require(statusByte == 0x1, "Status should be success."); offset += 1; uint256 cumGasHeaderByte; assembly { cumGasHeaderByte := byte(0, calldataload(offset)) } if (cumGasHeaderByte <= 0x7f) { offset += 1; } else { require( cumGasHeaderByte >= 0x80 && cumGasHeaderByte <= 0xb7, "Cumulative gas is an RLP string." ); offset += cumGasHeaderByte - 0x7f; } uint256 bloomHeaderByte; assembly { bloomHeaderByte := byte(0, calldataload(offset)) } require( bloomHeaderByte == 0xb9, "Bloom filter is always 256 bytes long." ); offset += 256 + 3; uint256 logsListHeaderByte; assembly { logsListHeaderByte := byte(0, calldataload(offset)) } require( logsListHeaderByte == 0xf8, "Logs list is less than 256 bytes long." ); offset += 2; uint256 logEntryHeaderByte; assembly { logEntryHeaderByte := byte(0, calldataload(offset)) } require( logEntryHeaderByte == 0xf8, "Log entry is less than 256 bytes long." ); offset += 2; uint256 addressHeaderByte; assembly { addressHeaderByte := byte(0, calldataload(offset)) } require(addressHeaderByte == 0x94, "Address is 20 bytes long."); uint256 logAddress; assembly { logAddress := and( calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff ) } require(logAddress == uint256(address(this))); } // Memory copy. function memcpy(uint256 dest, uint256 src, uint256 len) private pure { // Full 32 byte words for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Remaining bytes uint256 mask = 256**(32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } """#" text_o = """ type dice2Win_Bet is record #{config.reserved}__amount : nat; modulo : nat; rollUnder : nat; placeBlockNumber : nat; mask : nat; gambler : address; end; type constructor_args is unit; type approveNextOwner_args is record nextOwner_ : address; end; type acceptNextOwner_args is unit; type fallback_args is unit; type setSecretSigner_args is record newSecretSigner : address; end; type setCroupier_args is record newCroupier : address; end; type setMaxProfit_args is record maxProfit_ : nat; end; type increaseJackpot_args is record increaseAmount : nat; end; type withdrawFunds_args is record beneficiary : address; withdrawAmount : nat; end; type kill_args is unit; type placeBet_args is record betMask : nat; modulo : nat; commitLastBlock : nat; commit : nat; r : bytes; s : bytes; end; type settleBet_args is record reveal : nat; blockHash : bytes; end; type settleBetUncleMerkleProof_args is record reveal : nat; canonicalBlockNumber : nat; end; type refundBet_args is record commit : nat; end; type state is record owner : address; nextOwner : address; maxProfit : nat; secretSigner : address; jackpotSize : nat; lockedInBets : nat; bets : map(nat, dice2Win_Bet); croupier : address; end; function pow (const base : nat; const exp : nat) : nat is block { var b : nat := base; var e : nat := exp; var r : nat := 1n; while e > 0n block { if e mod 2n = 1n then { r := r * b; } else skip; b := b * b; e := e / 2n; } } with r; const burn_address : address = ("tz1ZZZZZZZZZZZZZZZZZZZZZZZZZZZZNkiRg" : address); const dice2Win_Bet_default : dice2Win_Bet = record [ #{config.reserved}__amount = 0n; modulo = 0n; rollUnder = 0n; placeBlockNumber = 0n; mask = 0n; gambler = burn_address ]; type router_enum is | Constructor of constructor_args | ApproveNextOwner of approveNextOwner_args | AcceptNextOwner of acceptNextOwner_args | Fallback of fallback_args | SetSecretSigner of setSecretSigner_args | SetCroupier of setCroupier_args | SetMaxProfit of setMaxProfit_args | IncreaseJackpot of increaseJackpot_args | WithdrawFunds of withdrawFunds_args | Kill of kill_args | PlaceBet of placeBet_args | SettleBet of settleBet_args | SettleBetUncleMerkleProof of settleBetUncleMerkleProof_args | RefundBet of refundBet_args; const hOUSE_EDGE_PERCENT : nat = 1n const hOUSE_EDGE_MINIMUM_AMOUNT : nat = (0.0003n * 1000000n) const mIN_JACKPOT_BET : nat = (0.1n * 1000000n) const jACKPOT_MODULO : nat = 1000n const jACKPOT_FEE : nat = (0.001n * 1000000n) const mIN_BET : nat = (0.01n * 1000000n) const mAX_AMOUNT : nat = (300000n * 1000000n) const mAX_MODULO : nat = 100n const mAX_MASK_MODULO : nat = 40n const mAX_BET_MASK : nat = pow(2n, mAX_MASK_MODULO) const bET_EXPIRATION_BLOCKS : nat = 250n const dUMMY_ADDRESS : address = ("PLEASE_REPLACE_ETH_ADDRESS_0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE_WITH_A_TEZOS_ADDRESS" : address) (* EventDefinition FailedPayment(beneficiary : address; #{config.reserved}__amount : nat) *) (* EventDefinition Payment(beneficiary : address; #{config.reserved}__amount : nat) *) (* EventDefinition JackpotPayment(beneficiary : address; #{config.reserved}__amount : nat) *) (* EventDefinition Commit(commit : nat) *) const pOPCNT_MULT : nat = 0x0000000000002000000000100000000008000000000400000000020000000001n const pOPCNT_MASK : nat = 0x0001041041041041041041041041041041041041041041041041041041041041n const pOPCNT_MODULO : nat = 0x3Fn function constructor (const test_self : state) : (state) is block { test_self.owner := Tezos.sender; test_self.secretSigner := dUMMY_ADDRESS; test_self.croupier := dUMMY_ADDRESS; } with (test_self); (* modifier onlyOwner inlined *) (* modifier onlyCroupier inlined *) function approveNextOwner (const test_self : state; const nextOwner_ : address) : (state) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); assert((nextOwner_ =/= test_self.owner)) (* "Cannot approve current owner." *); test_self.nextOwner := nextOwner_; } with (test_self); function acceptNextOwner (const test_self : state) : (state) is block { assert((Tezos.sender = test_self.nextOwner)) (* "Can only accept preapproved new owner." *); test_self.owner := test_self.nextOwner; } with (test_self); function fallback (const #{config.reserved}__unit : unit) : (unit) is block { skip } with (unit); function setSecretSigner (const test_self : state; const newSecretSigner : address) : (state) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); test_self.secretSigner := newSecretSigner; } with (test_self); function setCroupier (const test_self : state; const newCroupier : address) : (state) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); test_self.croupier := newCroupier; } with (test_self); function setMaxProfit (const test_self : state; const maxProfit_ : nat) : (state) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); assert((maxProfit_ < mAX_AMOUNT)) (* "maxProfit should be a sane number." *); test_self.maxProfit := maxProfit_; } with (test_self); function increaseJackpot (const test_self : state; const increaseAmount : nat) : (state) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); assert((increaseAmount <= self_address.#{config.reserved}__balance)) (* "Increase amount larger than balance." *); assert((((test_self.jackpotSize + test_self.lockedInBets) + increaseAmount) <= self_address.#{config.reserved}__balance)) (* "Not enough funds." *); test_self.jackpotSize := (test_self.jackpotSize + increaseAmount); } with (test_self); function sendFunds (const opList : list(operation); const test_self : state; const beneficiary : address; const #{config.reserved}__amount : nat; const successLogAmount : nat) : (list(operation)) is block { if (const op0 : operation = transaction((unit), (#{config.reserved}__amount * 1mutez), (get_contract(beneficiary) : contract(unit)))) then block { (* EmitStatement Payment(beneficiary, successLogAmount) *) } else block { (* EmitStatement FailedPayment(beneficiary, amount) *) }; } with (list [op0]); function withdrawFunds (const opList : list(operation); const test_self : state; const beneficiary : address; const withdrawAmount : nat) : (list(operation)) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); assert((withdrawAmount <= self_address.#{config.reserved}__balance)) (* "Increase amount larger than balance." *); assert((((test_self.jackpotSize + test_self.lockedInBets) + withdrawAmount) <= self_address.#{config.reserved}__balance)) (* "Not enough funds." *); opList := sendFunds((test_self : address), beneficiary, withdrawAmount, withdrawAmount); } with (opList); function kill (const test_self : state) : (unit) is block { assert((Tezos.sender = test_self.owner)) (* "OnlyOwner methods called by non-owner." *); assert((test_self.lockedInBets = 0n)) (* "All bets should be processed (settled or refunded) before test_self-destruct." *); selfdestruct(test_self.owner) (* unsupported *); } with (unit); function getDiceWinAmount (const test_self : state; const #{config.reserved}__amount : nat; const modulo : nat; const rollUnder : nat) : ((nat * nat)) is block { const winAmount : nat = 0n; const jackpotFee : nat = 0n; assert(((0n < rollUnder) and (rollUnder <= modulo))) (* "Win probability out of range." *); jackpotFee := (case (#{config.reserved}__amount >= mIN_JACKPOT_BET) of | True -> jACKPOT_FEE | False -> 0n end); const houseEdge : nat = ((#{config.reserved}__amount * hOUSE_EDGE_PERCENT) / 100n); if (houseEdge < hOUSE_EDGE_MINIMUM_AMOUNT) then block { houseEdge := hOUSE_EDGE_MINIMUM_AMOUNT; } else block { skip }; assert(((houseEdge + jackpotFee) <= #{config.reserved}__amount)) (* "Bet doesn't even cover house edge." *); winAmount := ((abs(abs(#{config.reserved}__amount - houseEdge) - jackpotFee) * modulo) / rollUnder); } with ((winAmount, jackpotFee)); function placeBet (const test_self : state; const betMask : nat; const modulo : nat; const commitLastBlock : nat; const commit : nat; const r : bytes; const s : bytes) : (state) is block { const bet : dice2Win_Bet = (case test_self.bets[commit] of | None -> dice2Win_Bet_default | Some(x) -> x end); assert((bet.gambler = burn_address)) (* "Bet should be in a 'clean' _state." *); const #{config.reserved}__amount : nat = (amount / 1mutez); assert(((modulo > 1n) and (modulo <= mAX_MODULO))) (* "Modulo should be within range." *); assert(((#{config.reserved}__amount >= mIN_BET) and (#{config.reserved}__amount <= mAX_AMOUNT))) (* "Amount should be within range." *); assert(((betMask > 0n) and (betMask < mAX_BET_MASK))) (* "Mask should be within range." *); assert((0n <= commitLastBlock)) (* "Commit has expired." *); const signatureHash : bytes = sha_256((commitLastBlock, commit)); assert((test_self.secretSigner = ecrecover(signatureHash, 27n, r, s))) (* "ECDSA signature is not valid." *); const rollUnder : nat = 0n; const mask : nat = 0n; if (modulo <= mAX_MASK_MODULO) then block { rollUnder := (Bitwise.and((betMask * pOPCNT_MULT), pOPCNT_MASK) mod pOPCNT_MODULO); mask := betMask; } else block { assert(((betMask > 0n) and (betMask <= modulo))) (* "High modulo range, betMask larger than modulo." *); rollUnder := betMask; }; const possibleWinAmount : nat = 0n; const jackpotFee : nat = 0n; (possibleWinAmount, jackpotFee) := getDiceWinAmount(test_self, #{config.reserved}__amount, modulo, rollUnder); assert((possibleWinAmount <= (#{config.reserved}__amount + test_self.maxProfit))) (* "maxProfit limit violation." *); test_self.lockedInBets := (test_self.lockedInBets + possibleWinAmount); test_self.jackpotSize := (test_self.jackpotSize + jackpotFee); assert(((test_self.jackpotSize + test_self.lockedInBets) <= self_address.#{config.reserved}__balance)) (* "Cannot afford to lose this bet." *); (* EmitStatement Commit(commit) *) bet.#{config.reserved}__amount := #{config.reserved}__amount; bet.modulo := modulo; bet.rollUnder := rollUnder; bet.placeBlockNumber := 0n; bet.mask := mask; bet.gambler := Tezos.sender; } with (test_self); function settleBetCommon (const opList : list(operation); const test_self : state; const bet : dice2Win_Bet; const reveal : nat; const entropyBlockHash : bytes) : (list(operation) * state) is block { const #{config.reserved}__amount : nat = bet.#{config.reserved}__amount; const modulo : nat = bet.modulo; const rollUnder : nat = bet.rollUnder; const gambler : address = bet.gambler; assert((#{config.reserved}__amount =/= 0n)) (* "Bet should be in an 'active' _state" *); bet.#{config.reserved}__amount := 0n; const entropy : bytes = sha_256((reveal, entropyBlockHash)); const dice : nat = (abs(entropy) mod modulo); const diceWinAmount : nat = 0n; const jackpotFee_ : nat = 0n; (diceWinAmount, jackpotFee_) := getDiceWinAmount(test_self, #{config.reserved}__amount, modulo, rollUnder); const diceWin : nat = 0n; const jackpotWin : nat = 0n; if (modulo <= mAX_MASK_MODULO) then block { if (Bitwise.and(pow(2n, dice), bet.mask) =/= 0n) then block { diceWin := diceWinAmount; } else block { skip }; } else block { if (dice < rollUnder) then block { diceWin := diceWinAmount; } else block { skip }; }; test_self.lockedInBets := abs(test_self.lockedInBets - diceWinAmount); if (#{config.reserved}__amount >= mIN_JACKPOT_BET) then block { const jackpotRng : nat = ((abs(entropy) / modulo) mod jACKPOT_MODULO); if (jackpotRng = 0n) then block { jackpotWin := test_self.jackpotSize; test_self.jackpotSize := 0n; } else block { skip }; } else block { skip }; if (jackpotWin > 0n) then block { (* EmitStatement JackpotPayment(gambler, jackpotWin) *) } else block { skip }; opList := sendFunds((test_self : address), gambler, (case ((diceWin + jackpotWin) = 0n) of | True -> 1n | False -> (diceWin + jackpotWin) end), diceWin); } with (opList, test_self); function settleBet (const opList : list(operation); const test_self : state; const reveal : nat; const blockHash : bytes) : (list(operation) * state) is block { assert((Tezos.sender = test_self.croupier)) (* "OnlyCroupier methods called by non-croupier." *); const commit : nat = abs(sha_256((reveal))); const bet : dice2Win_Bet = (case test_self.bets[commit] of | None -> dice2Win_Bet_default | Some(x) -> x end); const placeBlockNumber : nat = bet.placeBlockNumber; assert((0n > placeBlockNumber)) (* "settleBet in the same block as placeBet, or before." *); assert((0n <= (placeBlockNumber + bET_EXPIRATION_BLOCKS))) (* "Blockhash can't be queried by EVM." *); assert((("00" : bytes) (* Should be blockhash of placeBlockNumber *) = blockHash)); const tmp_0 : (list(operation) * state) = settleBetCommon(test_self, bet, reveal, blockHash); opList := tmp_0.0; test_self := tmp_0.1; } with (opList, test_self); function memcpy (const dest : nat; const src : nat; const len : nat) : (unit) is block { while (len >= 32n) block { failwith("Unsupported InlineAssembly"); (* InlineAssembly { mstore(dest, mload(src)) } *) dest := (dest + 32n); src := (src + 32n); len := abs(len - 32n); }; const mask : nat = abs(pow(256n, abs(32n - len)) - 1n); failwith("Unsupported InlineAssembly"); (* InlineAssembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } *) } with (unit); function verifyMerkleProof (const seedHash : nat; const offset : nat) : ((bytes * bytes)) is block { const blockHash : bytes = ("00": bytes); const uncleHash : bytes = ("00": bytes); const scratchBuf1 : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { scratchBuf1 := mload(0x40) } *) const uncleHeaderLength : nat = 0n; const blobLength : nat = 0n; const shift : nat = 0n; const hashSlot : nat = 0n; while (True) block { failwith("Unsupported InlineAssembly"); (* InlineAssembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) } *) if (blobLength = 0n) then block { (* `break` statement is not supported in LIGO *); } else block { skip }; failwith("Unsupported InlineAssembly"); (* InlineAssembly { shift := and(calldataload(sub(offset, 28)), 0xffff) } *) assert(((shift + 32n) <= blobLength)) (* "Shift bounds check." *); offset := (offset + 4n); failwith("Unsupported InlineAssembly"); (* InlineAssembly { hashSlot := calldataload(add(offset, shift)) } *) assert((hashSlot = 0n)) (* "Non-empty hash slot." *); failwith("Unsupported InlineAssembly"); (* InlineAssembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) seedHash := keccak256(scratchBuf1, blobLength) uncleHeaderLength := blobLength } *) offset := (offset + blobLength); }; uncleHash := (seedHash : bytes); const scratchBuf2 : nat = (scratchBuf1 + uncleHeaderLength); const unclesLength : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { unclesLength := and(calldataload(sub(offset, 28)), 0xffff) } *) const unclesShift : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { unclesShift := and(calldataload(sub(offset, 26)), 0xffff) } *) assert(((unclesShift + uncleHeaderLength) <= unclesLength)) (* "Shift bounds check." *); offset := (offset + 6n); failwith("Unsupported InlineAssembly"); (* InlineAssembly { calldatacopy(scratchBuf2, offset, unclesLength) } *) memcpy((scratchBuf2 + unclesShift), scratchBuf1, uncleHeaderLength); failwith("Unsupported InlineAssembly"); (* InlineAssembly { seedHash := keccak256(scratchBuf2, unclesLength) } *) offset := (offset + unclesLength); failwith("Unsupported InlineAssembly"); (* InlineAssembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) shift := and(calldataload(sub(offset, 28)), 0xffff) } *) assert(((shift + 32n) <= blobLength)) (* "Shift bounds check." *); offset := (offset + 4n); failwith("Unsupported InlineAssembly"); (* InlineAssembly { hashSlot := calldataload(add(offset, shift)) } *) assert((hashSlot = 0n)) (* "Non-empty hash slot." *); failwith("Unsupported InlineAssembly"); (* InlineAssembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) blockHash := keccak256(scratchBuf1, blobLength) } *) } with ((blockHash, uncleHash)); function requireCorrectReceipt (const offset : nat) : (unit) is block { const leafHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { leafHeaderByte := byte(0, calldataload(offset)) } *) assert((leafHeaderByte >= 0xf7n)) (* "Receipt leaf longer than 55 bytes." *); offset := (offset + abs(leafHeaderByte - 0xf6n)); const pathHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { pathHeaderByte := byte(0, calldataload(offset)) } *) if (pathHeaderByte <= 0x7fn) then block { offset := (offset + 1n); } else block { assert(((pathHeaderByte >= 0x80n) and (pathHeaderByte <= 0xb7n))) (* "Path is an RLP string." *); offset := (offset + abs(pathHeaderByte - 0x7fn)); }; const receiptStringHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { receiptStringHeaderByte := byte(0, calldataload(offset)) } *) assert((receiptStringHeaderByte = 0xb9n)) (* "Receipt string is always at least 256 bytes long, but less than 64k." *); offset := (offset + 3n); const receiptHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { receiptHeaderByte := byte(0, calldataload(offset)) } *) assert((receiptHeaderByte = 0xf9n)) (* "Receipt is always at least 256 bytes long, but less than 64k." *); offset := (offset + 3n); const statusByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { statusByte := byte(0, calldataload(offset)) } *) assert((statusByte = 0x1n)) (* "Status should be success." *); offset := (offset + 1n); const cumGasHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { cumGasHeaderByte := byte(0, calldataload(offset)) } *) if (cumGasHeaderByte <= 0x7fn) then block { offset := (offset + 1n); } else block { assert(((cumGasHeaderByte >= 0x80n) and (cumGasHeaderByte <= 0xb7n))) (* "Cumulative gas is an RLP string." *); offset := (offset + abs(cumGasHeaderByte - 0x7fn)); }; const bloomHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { bloomHeaderByte := byte(0, calldataload(offset)) } *) assert((bloomHeaderByte = 0xb9n)) (* "Bloom filter is always 256 bytes long." *); offset := (offset + (256 + 3)); const logsListHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { logsListHeaderByte := byte(0, calldataload(offset)) } *) assert((logsListHeaderByte = 0xf8n)) (* "Logs list is less than 256 bytes long." *); offset := (offset + 2n); const logEntryHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { logEntryHeaderByte := byte(0, calldataload(offset)) } *) assert((logEntryHeaderByte = 0xf8n)) (* "Log entry is less than 256 bytes long." *); offset := (offset + 2n); const addressHeaderByte : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { addressHeaderByte := byte(0, calldataload(offset)) } *) assert((addressHeaderByte = 0x94n)) (* "Address is 20 bytes long." *); const logAddress : nat = 0n; failwith("Unsupported InlineAssembly"); (* InlineAssembly { logAddress := and(calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff) } *) assert((logAddress = abs(self_address))); } with (unit); function settleBetUncleMerkleProof (const opList : list(operation); const test_self : state; const reveal : nat; const canonicalBlockNumber : nat) : (list(operation) * state) is block { assert((Tezos.sender = test_self.croupier)) (* "OnlyCroupier methods called by non-croupier." *); const commit : nat = abs(sha_256((reveal))); const bet : dice2Win_Bet = (case test_self.bets[commit] of | None -> dice2Win_Bet_default | Some(x) -> x end); assert((0n <= (canonicalBlockNumber + bET_EXPIRATION_BLOCKS))) (* "Blockhash can't be queried by EVM." *); requireCorrectReceipt((((4 + 32) + 32) + 4n)); const canonicalHash : bytes = ("00": bytes); const uncleHash : bytes = ("00": bytes); (canonicalHash, uncleHash) := verifyMerkleProof(commit, ((4 + 32) + 32n)); assert((("00" : bytes) (* Should be blockhash of canonicalBlockNumber *) = canonicalHash)); const tmp_0 : (list(operation) * state) = settleBetCommon(test_self, bet, reveal, uncleHash); opList := tmp_0.0; test_self := tmp_0.1; } with (opList, test_self); function refundBet (const opList : list(operation); const test_self : state; const commit : nat) : (list(operation) * state) is block { const bet : dice2Win_Bet = (case test_self.bets[commit] of | None -> dice2Win_Bet_default | Some(x) -> x end); const #{config.reserved}__amount : nat = bet.#{config.reserved}__amount; assert((#{config.reserved}__amount =/= 0n)) (* "Bet should be in an 'active' _state" *); assert((0n > (bet.placeBlockNumber + bET_EXPIRATION_BLOCKS))) (* "Blockhash can't be queried by EVM." *); bet.#{config.reserved}__amount := 0n; const diceWinAmount : nat = 0n; const jackpotFee : nat = 0n; (diceWinAmount, jackpotFee) := getDiceWinAmount(test_self, #{config.reserved}__amount, bet.modulo, bet.rollUnder); test_self.lockedInBets := abs(test_self.lockedInBets - diceWinAmount); test_self.jackpotSize := abs(test_self.jackpotSize - jackpotFee); opList := sendFunds((test_self : address), bet.gambler, #{config.reserved}__amount, #{config.reserved}__amount); } with (opList, test_self); function main (const action : router_enum; const test_self : state) : (list(operation) * state) is (case action of | Constructor(match_action) -> ((nil: list(operation)), constructor(test_self)) | ApproveNextOwner(match_action) -> ((nil: list(operation)), approveNextOwner(test_self, match_action.nextOwner_)) | AcceptNextOwner(match_action) -> ((nil: list(operation)), acceptNextOwner(test_self)) | Fallback(match_action) -> block { (* This function does nothing, but it's present in router *) const tmp : unit = fallback(unit); } with (((nil: list(operation)), test_self)) | SetSecretSigner(match_action) -> ((nil: list(operation)), setSecretSigner(test_self, match_action.newSecretSigner)) | SetCroupier(match_action) -> ((nil: list(operation)), setCroupier(test_self, match_action.newCroupier)) | SetMaxProfit(match_action) -> ((nil: list(operation)), setMaxProfit(test_self, match_action.maxProfit_)) | IncreaseJackpot(match_action) -> ((nil: list(operation)), increaseJackpot(test_self, match_action.increaseAmount)) | WithdrawFunds(match_action) -> (withdrawFunds((nil: list(operation)), test_self, match_action.beneficiary, match_action.withdrawAmount), test_self) | Kill(match_action) -> block { (* This function does nothing, but it's present in router *) const tmp : unit = kill(test_self); } with (((nil: list(operation)), test_self)) | PlaceBet(match_action) -> ((nil: list(operation)), placeBet(test_self, match_action.betMask, match_action.modulo, match_action.commitLastBlock, match_action.commit, match_action.r, match_action.s)) | SettleBet(match_action) -> settleBet((nil: list(operation)), test_self, match_action.reveal, match_action.blockHash) | SettleBetUncleMerkleProof(match_action) -> settleBetUncleMerkleProof((nil: list(operation)), test_self, match_action.reveal, match_action.canonicalBlockNumber) | RefundBet(match_action) -> refundBet((nil: list(operation)), test_self, match_action.commit) end); """#" make_test text_i, text_o, router: true, allow_need_prevent_deploy: true # ################################################################################################### it "Creatures", ()-> text_i = """ pragma solidity ^0.4.16; contract Permissions { address ownerAddress; address storageAddress; address callerAddress; function Permissions() public { ownerAddress = msg.sender; } modifier onlyOwner() { require(msg.sender == ownerAddress); _; } modifier onlyCaller() { require(msg.sender == callerAddress); _; } function getOwner() external view returns (address) { return ownerAddress; } function getStorageAddress() external view returns (address) { return storageAddress; } function getCaller() external view returns (address) { return callerAddress; } function transferOwnership(address newOwner) external onlyOwner { if (newOwner != address(0)) { ownerAddress = newOwner; } } function newStorage(address _new) external onlyOwner { if (_new != address(0)) { storageAddress = _new; } } function newCaller(address _new) external onlyOwner { if (_new != address(0)) { callerAddress = _new; } } } contract Creatures is Permissions { struct Creature { uint16 species; uint8 subSpecies; uint8 eyeColor; uint64 timestamp; } Creature[] creatures; mapping(uint256 => address) public creatureIndexToOwner; mapping(address => uint256) ownershipTokenCount; event CreateCreature(uint256 id, address indexed owner); event Transfer(address _from, address _to, uint256 creatureID); function add( address _owner, uint16 _species, uint8 _subSpecies, uint8 _eyeColor ) external onlyCaller { // do checks in caller function Creature memory _creature = Creature({ species: _species, subSpecies: _subSpecies, eyeColor: _eyeColor, timestamp: uint64(now) }); uint256 newCreatureID = creatures.push(_creature) - 1; transfer(0, _owner, newCreatureID); CreateCreature(newCreatureID, _owner); } function getCreature(uint256 id) external view returns (address, uint16, uint8, uint8, uint64) { Creature storage c = creatures[id]; address owner = creatureIndexToOwner[id]; return (owner, c.species, c.subSpecies, c.eyeColor, c.timestamp); } function transfer(address _from, address _to, uint256 _tokenId) public onlyCaller { // do checks in caller function creatureIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; } ownershipTokenCount[_to]++; Transfer(_from, _to, _tokenId); } } """#" text_o = """ type creatures_Creature is record species : nat; subSpecies : nat; eyeColor : nat; timestamp : nat; end; type newCaller_args is record new_ : address; end; type newStorage_args is record new_ : address; end; type transferOwnership_args is record newOwner : address; end; type getCaller_args is record callbackAddress : address; end; type getStorageAddress_args is record callbackAddress : address; end; type getOwner_args is record callbackAddress : address; end; type transfer_args is record from_ : address; to_ : address; tokenId_ : nat; end; type add_args is record owner_ : address; species_ : nat; subSpecies_ : nat; eyeColor_ : nat; end; type getCreature_args is record id : nat; callbackAddress : address; end; type constructor_args is unit; type state is record callerAddress : address; storageAddress : address; ownerAddress : address; creatures : map(nat, creatures_Creature); creatureIndexToOwner : map(nat, address); ownershipTokenCount : map(address, nat); end; const burn_address : address = ("tz1ZZZZZZZZZZZZZZZZZZZZZZZZZZZZNkiRg" : address); const creatures_Creature_default : creatures_Creature = record [ species = 0n; subSpecies = 0n; eyeColor = 0n; timestamp = 0n ]; type router_enum is | NewCaller of newCaller_args | NewStorage of newStorage_args | TransferOwnership of transferOwnership_args | GetCaller of getCaller_args | GetStorageAddress of getStorageAddress_args | GetOwner of getOwner_args | Transfer of transfer_args | Add of add_args | GetCreature of getCreature_args | Constructor of constructor_args; (* EventDefinition CreateCreature(id : nat; owner : address) *) (* EventDefinition Transfer(from_ : address; to_ : address; creatureID : nat) *) function newCaller (const test_self : state; const new_ : address) : (state) is block { assert((Tezos.sender = test_self.ownerAddress)); if (new_ =/= burn_address) then block { test_self.callerAddress := new_; } else block { skip }; } with (test_self); function newStorage (const test_self : state; const new_ : address) : (state) is block { assert((Tezos.sender = test_self.ownerAddress)); if (new_ =/= burn_address) then block { test_self.storageAddress := new_; } else block { skip }; } with (test_self); function transferOwnership (const test_self : state; const newOwner : address) : (state) is block { assert((Tezos.sender = test_self.ownerAddress)); if (newOwner =/= burn_address) then block { test_self.ownerAddress := newOwner; } else block { skip }; } with (test_self); function getCaller (const test_self : state) : (address) is block { skip } with (test_self.callerAddress); function getStorageAddress (const test_self : state) : (address) is block { skip } with (test_self.storageAddress); function getOwner (const test_self : state) : (address) is block { skip } with (test_self.ownerAddress); function permissions_constructor (const test_self : state) : (state) is block { test_self.ownerAddress := Tezos.sender; } with (test_self); function transfer (const test_self : state; const from_ : address; const to_ : address; const tokenId_ : nat) : (state) is block { assert((Tezos.sender = test_self.callerAddress)); test_self.creatureIndexToOwner[tokenId_] := to_; if (from_ =/= burn_address) then block { (case test_self.ownershipTokenCount[from_] of | None -> 0n | Some(x) -> x end) := abs((case test_self.ownershipTokenCount[from_] of | None -> 0n | Some(x) -> x end) - 1n); } else block { skip }; (case test_self.ownershipTokenCount[to_] of | None -> 0n | Some(x) -> x end) := (case test_self.ownershipTokenCount[to_] of | None -> 0n | Some(x) -> x end) + 1n; (* EmitStatement Transfer(_from, _to, _tokenId) *) } with (test_self); function add (const opList : list(operation); const test_self : state; const owner_ : address; const species_ : nat; const subSpecies_ : nat; const eyeColor_ : nat) : (list(operation) * state) is block { assert((Tezos.sender = test_self.callerAddress)); const creature_ : creatures_Creature = record [ species = species_; subSpecies = subSpecies_; eyeColor = eyeColor_; timestamp = abs(abs(now - ("1970-01-01T00:00:00Z" : timestamp))) ]; const tmp_0 : map(nat, creatures_Creature) = test_self.creatures; const newCreatureID : nat = abs(tmp_0[size(tmp_0)] := creature_ - 1n); transfer(burn_address, owner_, newCreatureID); (* EmitStatement CreateCreature(newCreatureID, _owner) *) } with (opList, test_self); function getCreature (const test_self : state; const id : nat) : ((address * nat * nat * nat * nat)) is block { const c : creatures_Creature = (case test_self.creatures[id] of | None -> creatures_Creature_default | Some(x) -> x end); const owner : address = (case test_self.creatureIndexToOwner[id] of | None -> burn_address | Some(x) -> x end); } with ((owner, c.species, c.subSpecies, c.eyeColor, c.timestamp)); function constructor (const test_self : state) : (state) is block { test_self := permissions_constructor(test_self); } with (test_self); function main (const action : router_enum; const test_self : state) : (list(operation) * state) is (case action of | NewCaller(match_action) -> ((nil: list(operation)), newCaller(test_self, match_action.new_)) | NewStorage(match_action) -> ((nil: list(operation)), newStorage(test_self, match_action.new_)) | TransferOwnership(match_action) -> ((nil: list(operation)), transferOwnership(test_self, match_action.newOwner)) | GetCaller(match_action) -> block { const tmp : (address) = getCaller(test_self); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(address))) end; } with ((opList, test_self)) | GetStorageAddress(match_action) -> block { const tmp : (address) = getStorageAddress(test_self); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(address))) end; } with ((opList, test_self)) | GetOwner(match_action) -> block { const tmp : (address) = getOwner(test_self); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract(address))) end; } with ((opList, test_self)) | Transfer(match_action) -> ((nil: list(operation)), transfer(test_self, match_action.from_, match_action.to_, match_action.tokenId_)) | Add(match_action) -> add((nil: list(operation)), test_self, match_action.owner_, match_action.species_, match_action.subSpecies_, match_action.eyeColor_) | GetCreature(match_action) -> block { const tmp : ((address * nat * nat * nat * nat)) = getCreature(test_self, match_action.id); var opList : list(operation) := list transaction((tmp), 0mutez, (get_contract(match_action.callbackAddress) : contract((address * nat * nat * nat * nat)))) end; } with ((opList, test_self)) | Constructor(match_action) -> ((nil: list(operation)), constructor(test_self)) end); """#" make_test text_i, text_o, router: true
[ { "context": "e\"]?.value)\n when \"email\" then email\n when \"samaccountname\" then lowerId\n else email\n\n uaacCreateUserReq", "end": 10626, "score": 0.9996519088745117, "start": 10612, "tag": "USERNAME", "value": "samaccountname" }, { "context": "\n uaacChangePasswordRequest =\n \"oldPassword\":\"#{oldpassword}\"\n \"password\":\"#{newpassword}\"\n ua", "end": 11448, "score": 0.8277571797370911, "start": 11448, "tag": "PASSWORD", "value": "" }, { "context": " uaacChangePasswordRequest =\n \"oldPassword\":\"#{oldpassword}\"\n \"password\":\"#{newpassword}\"\n uaacChangePas", "end": 11461, "score": 0.867573082447052, "start": 11450, "tag": "PASSWORD", "value": "oldpassword" }, { "context": " \"oldPassword\":\"#{oldpassword}\"\n \"password\":\"#{newpassword}\"\n uaacChangePasswordRequest\n\nfetchAl", "end": 11480, "score": 0.8451858162879944, "start": 11480, "tag": "PASSWORD", "value": "" }, { "context": " \"oldPassword\":\"#{oldpassword}\"\n \"password\":\"#{newpassword}\"\n uaacChangePasswordRequest\n\nfetchAllUsers = (t", "end": 11493, "score": 0.8808057904243469, "start": 11482, "tag": "PASSWORD", "value": "newpassword" } ]
routes/cfapi.coffee
MonsantoCo/cf-users
14
Promise = require 'promise' adminOauth = require "./AdminOauth" uaaadminOauth = require "./uaaAdminOauth" services = require "./serviceBindings" requestjs = require 'request' cfapi = {} adminOauth.initOauth2() uaaadminOauth.initOauth2() cfapi.allOrganizations = (req,res) -> fetchAllOrganizations(req.headers['authorization'],[],1).then (orgs)=> res.json resources: orgs resolve(orgs) , (error)-> res.status(500).send(error) reject(error) cfapi.adminOrganizations = (req,res) -> adminOauth.refreshToken (token) -> fetchAllOrganizations("Bearer #{token.token.access_token}",[],1).then (orgs)=> res.json resources: orgs resolve(orgs) , (error)-> res.status(500).send(error) reject(error) cfapi.listUserAssociation = (req,res)-> fetchUser(req,res).then (userInfo)-> adminOauth.refreshToken (token) -> fetchListCfRequest("Bearer #{token?.token?.access_token}",[], "users",req.params.userGuid, req.params.associationType, req.query?.q, 1).then (values)=> res.json total_pages: 1 resources: values ,(error)-> res.sendStatus(500).send(error) reject(error) , (error) -> console.log("Unauthenticated user attempt to call listUserAccociation") cfapi.listCfRequest = (req,res)-> adminOauth.refreshToken (token) -> fetchListCfRequest("Bearer #{token.token.access_token}",[], req.params.level,req.params.levelGuid, req.params.associationType, req.query?.q, 1).then (values)=> res.json total_pages: 1 resources: values ,(error)-> res.sendStatus(500).send(error) reject(error) cfapi.userInfo = (req,res)-> fetchUser(req,res).then (userInfo)-> res.status(200).json userInfo , (error)-> res.status(500).send(error) fetchUser = (req,res)-> new Promise (resolve,reject)-> options = url: "https://#{services["cloud_foundry_api-uaa-domain"].value}/userinfo" headers: {'Authorization': req.headers['authorization']} requestjs options, (error,response,body) -> if(!error && response.statusCode==200) userInfo=JSON.parse(body) resolve(userInfo) else reject(error) cfapi.allUsers = (req,res) -> fetchUser(req,res).then (userinfo)-> adminOauth.refreshToken (token) -> fetchAllUsers(token,[], 1).then (values)=> res.json total_pages : 1 resources: values ,(error)-> res.sendStatus(500).send(error) reject(error) , (error) -> console.log("Unauthenticated user attempt to fetch all users") cfapi.allUAAUsers = (req,res) -> fetchUser(req,res).then (userinfo)-> uaaadminOauth.refreshToken (token) -> fetchAllUAAUsers(token,[], 1).then (values)=> res.json total_pages : 1 resources: values ,(error)-> res.sendStatus(500).send(error) reject(error) , (error) -> console.log("Unauthenticated user attempt to fetch all users") cfapi.samlIdentityProviders = (req,res) -> fetchUser(req,res).then (userinfo)-> if(services["cloud_foundry_api-saml-provider"]?.value) res.status(200).send [ services["cloud_foundry_api-saml-provider"]?.value ] else res.status(200).send [ ] , (error) -> res.status(401).send("Unauthenticated user attempt to fetch saml identity providers") console.log("Unauthenticated user attempt to fetch saml identity providers") doRole = (method,token,level,levelGuid,associationType,associationGuid)-> new Promise (resolve,reject)-> options = method: method url: "https://#{services["cloud_foundry_api-domain"].value}/v2/#{level}/#{levelGuid}/#{associationType}/#{associationGuid}" headers: {'Authorization': token} requestjs options, (error,response,body) -> if((!error)&&(response.statusCode == 201)) resolve status : response.statusCode body : JSON.parse(body) else if((!error)&& (response.statusCode == 204)) resolve status : response.statusCode else if(!error) reject status : 500 body: response else reject status : 500 body : error cfapi.putOrgUser = (req,res)-> #first check if space manager authHeader = req.headers['authorization'] fetchUser(req,res).then (userData)-> adminOauth.refreshToken (token) -> options = method: "GET" url: "https://#{services["cloud_foundry_api-domain"].value}/v2/users/#{userData.user_id}/managed_spaces?q=organization_guid:#{req.params.levelGuid}" headers : {'Authorization' : "Bearer #{token.token.access_token}"} requestjs options, (error,response,body) -> responseBody = JSON.parse(body) if(!error && response.statusCode == 200 && responseBody["total_results"] > 0) authHeader = "Bearer #{token.token.access_token}" doRole('PUT',authHeader,"organizations",req.params.levelGuid,"users",req.params.associationGuid).then (response)-> res.status(response.status).json(response.body) , (response)-> res.status(response.status).send(response.body) , ()-> res.status(403).send("Verboten") cfapi.putRole = (req,res)-> doRole('PUT',req.headers['authorization'],req.params.level,req.params.levelGuid,req.params.associationType,req.params.associationGuid).then (response)-> res.status(response.status).json(response.body) , (response)-> res.status(response.status).send(response.body) cfapi.deleteRole = (req,res)-> doRole('DELETE',req.headers['authorization'],req.params.level,req.params.levelGuid,req.params.associationType,req.params.associationGuid).then (response)-> res.status(response.status).json(response.body) , (response)-> res.status(response.status).send(response.body) doPut = (url,token,form)-> doRequest("PUT",url,token,form) doPost = (url,token,form)-> doRequest("POST",url,token,form) doRequest = (method,url,token,form) -> new Promise (resolve,reject) -> options = method : method url: url headers : {'Authorization': "Bearer " + token.token.access_token} json : form try requestjs options, (error,response,body) -> if(!error && response.statusCode == 201) resolve status : response.statusCode body : body else if(!error ) reject status : response.statusCode body: if(body) then body else "failed" else reject status : 500 body : error catch error console.log("error=#{error}") reject status: 500 body : error cfapi.createUser = (req,res) -> #first check if space manager orgAuthToken = req.headers['authorization'].split(" ")[1] fetchUser(req,res).then (userData)-> adminOauth.refreshToken (token) -> options = method: "GET" url: "https://#{services["cloud_foundry_api-domain"].value}/v2/users/#{userData.user_id}/managed_spaces?q=organization_guid:#{req.body.org.guid}" headers : {'Authorization' : "Bearer #{token.token.access_token}"} requestjs options, (error,response,body) -> responseBody = JSON.parse(body) if(!error && response.statusCode == 200 && responseBody["total_results"] > 0) orgAuthToken = token.token.access_token doPost("https://#{services["cloud_foundry_api-uaa-domain"].value}/Users",token,buildUaacCreateUserRequest(req)).then (response)-> userId = response.body.id doPost("https://#{services["cloud_foundry_api-domain"].value}/v2/users",token, { "guid" : userId }).then (response)-> orgGuid = req.body.org.guid doRole('PUT',"Bearer #{orgAuthToken}","organizations",orgGuid,"users",userId).then (response)-> roleFutures = [] if(req.body.org.manager) roleFutures.push doRole 'PUT',req.headers['authorization'],"organizations",orgGuid,"managers",userId if(req.body.org.auditor) roleFutures.push doRole 'PUT',req.headers['authorization'],"organizations",orgGuid,"auditors",userId for space in req.body.spaces if(space.developer) roleFutures.push doRole 'PUT',req.headers['authorization'],"spaces",space.guid,"developers",userId if(space.manager) roleFutures.push doRole 'PUT',req.headers['authorization'],"spaces",space.guid,"managers",userId if(space.auditor) roleFutures.push doRole 'PUT',req.headers['authorization'],"spaces",space.guid,"auditors",userId Promise.all(roleFutures).then (responses)-> res.status(201).send("user created") , (responses)-> failedResponses = ( response for response in responses when response.status!=201 || response.error ) res.status(response.status).send(response.body) , (response)-> res.status(response.status).send(response.body) , (response)-> res.status(response.status).send(response.body) , (response)-> res.status(response.status).send(response.body) , (error)-> console.log("Unauthenticated user attempted to createUser") res.status(403).send("verboten") cfapi.changePassword = (req,res) -> uaaadminOauth.refreshToken (uaatoken) -> doPut("https://#{services["cloud_foundry_api-uaa-domain"].value}/Users/#{req.body.userId}/password",uaatoken,buildUaacChangePasswordRequest(req)).then (response)-> res.status(response.status).send(response.body) , (response)-> res.status(response.status).send(response.body) , (error)-> console.log("Unauthenticated user attempted to createUser") res.status(403).send("verboten") buildUaacCreateUserRequest = (req)-> userId =req.body.userId identityProvider = req.body.identityProvider password = if req.body.password then req.body.password else "" userIdComponents = userId.split("@") upperId = userIdComponents[0].toUpperCase() lowerId = userIdComponents[0].toLowerCase() givenName = userIdComponents[0] email = if (identityProvider!="uaa") then "#{lowerId}@#{services["cloud_foundry_api-default-email-domain"].value}" else lowerId familyName = if(identityProvider!="uaa") then services["cloud_foundry_api-default-email-domain"].value else lowerId username = switch(services["cloud_foundry_api-user-name-type"]?.value) when "email" then email when "samaccountname" then lowerId else email uaacCreateUserRequest = "schemas":["urn:scim:schemas:core:1.0"] "userName": username "name": "familyName": "#{familyName}" "givenName": "#{givenName}" "emails": [ "value": email ] "approvals": [ ] "active": true "verified": true "origin": identityProvider if (identityProvider=="uaa") uaacCreateUserRequest["password"] = password if (identityProvider!="uaa"&&identityProvider!="ldap") uaacCreateUserRequest["externalId"]= email uaacCreateUserRequest buildUaacChangePasswordRequest = (req)-> userId =req.body.userId oldpassword = if req.body.oldpassword then req.body.oldpassword else "" newpassword = if req.body.newpassword then req.body.newpassword else "" uaacChangePasswordRequest = "oldPassword":"#{oldpassword}" "password":"#{newpassword}" uaacChangePasswordRequest fetchAllUsers = (token, usersToReturn, page)-> new Promise (resolve,reject) -> options = url: "https://#{services["cloud_foundry_api-domain"].value}/v2/users?order-direction=asc&results-per-page=50&page=#{page}" headers: {'Authorization': "Bearer " + token.token.access_token} requestjs options, (error,response,body) -> if(!error && response.statusCode == 200) users = JSON.parse(body) pages=users.total_pages usersToReturn.push user for user in users.resources if(page<pages) fetchAllUsers(token,usersToReturn,page+1).then ()=> resolve(usersToReturn) , (error)=> reject(error) else resolve(usersToReturn) else reject(error) fetchAllUAAUsers = (token, usersToReturn, page)-> new Promise (resolve,reject) -> options = url: "https://#{services["cloud_foundry_api-uaa-domain"].value}/Users?filter=origin+eq+%22uaa%22&count=50&sortOrder=ascending&startIndex=#{page}" headers: {'Authorization': "Bearer " + token.token.access_token} requestjs options, (error,response,body) -> if(!error && response.statusCode == 200) users = JSON.parse(body) usersToReturn.push user for user in users.resources if((page+50)<users.totalResults) fetchAllUAAUsers(token,usersToReturn,page+50).then ()=> resolve(usersToReturn) , (error)=> reject(error) else resolve(usersToReturn) else reject(error) fetchAllOrganizations = (token,orgsToReturn,page) -> fetchOrganizations(token, orgsToReturn, page, "https://#{services["cloud_foundry_api-domain"].value}/v2/organizations") fetchOrganizations = (token,orgsToReturn,page,url)-> new Promise (resolve,reject) -> options = url: "#{url}?order-direction=asc&page=#{page}&results-per-page=50" headers: {'Authorization': token} requestjs options, (error,response,body) -> if(!error && response.statusCode == 200) orgs = JSON.parse(body) pages=orgs.total_pages quotaPromises = [] for org in orgs.resources do (org) -> orgsToReturn.push entity : name : org.entity.name metadata : guid : org.metadata.guid if(page<pages) fetchOrganizations(token,orgsToReturn,page+1,url).then ()=> resolve(orgsToReturn) , (error)=> reject(error) else resolve(orgsToReturn) else reject(error) fetchListCfRequest = (token,resourcesToReturn, level,levelGuid, associationType, filter, page)-> new Promise (resolve,reject) -> options = url: "https://#{services["cloud_foundry_api-domain"].value}/v2/#{level}/#{levelGuid}/#{associationType}?order-direction=asc&page=#{page}#{if filter then "&q="+filter else ""}&results-per-page=50" headers: {'Authorization': token} requestjs options, (error,response,body) -> if(!error && response.statusCode == 200) orgs = JSON.parse(body) pages=orgs.total_pages resourcesToReturn.push resource for resource in orgs.resources if(page<pages) fetchListCfRequest(token,resourcesToReturn,level,levelGuid, associationType,filter,page+1).then ()=> resolve(resourcesToReturn) , (error)=> console.log("fetchListCfRequest error") reject(error) else resolve(resourcesToReturn) else console.log("fetchListCfRequest status: #{response.statusCode}, error: #{error}") reject(error) module.exports = cfapi
97005
Promise = require 'promise' adminOauth = require "./AdminOauth" uaaadminOauth = require "./uaaAdminOauth" services = require "./serviceBindings" requestjs = require 'request' cfapi = {} adminOauth.initOauth2() uaaadminOauth.initOauth2() cfapi.allOrganizations = (req,res) -> fetchAllOrganizations(req.headers['authorization'],[],1).then (orgs)=> res.json resources: orgs resolve(orgs) , (error)-> res.status(500).send(error) reject(error) cfapi.adminOrganizations = (req,res) -> adminOauth.refreshToken (token) -> fetchAllOrganizations("Bearer #{token.token.access_token}",[],1).then (orgs)=> res.json resources: orgs resolve(orgs) , (error)-> res.status(500).send(error) reject(error) cfapi.listUserAssociation = (req,res)-> fetchUser(req,res).then (userInfo)-> adminOauth.refreshToken (token) -> fetchListCfRequest("Bearer #{token?.token?.access_token}",[], "users",req.params.userGuid, req.params.associationType, req.query?.q, 1).then (values)=> res.json total_pages: 1 resources: values ,(error)-> res.sendStatus(500).send(error) reject(error) , (error) -> console.log("Unauthenticated user attempt to call listUserAccociation") cfapi.listCfRequest = (req,res)-> adminOauth.refreshToken (token) -> fetchListCfRequest("Bearer #{token.token.access_token}",[], req.params.level,req.params.levelGuid, req.params.associationType, req.query?.q, 1).then (values)=> res.json total_pages: 1 resources: values ,(error)-> res.sendStatus(500).send(error) reject(error) cfapi.userInfo = (req,res)-> fetchUser(req,res).then (userInfo)-> res.status(200).json userInfo , (error)-> res.status(500).send(error) fetchUser = (req,res)-> new Promise (resolve,reject)-> options = url: "https://#{services["cloud_foundry_api-uaa-domain"].value}/userinfo" headers: {'Authorization': req.headers['authorization']} requestjs options, (error,response,body) -> if(!error && response.statusCode==200) userInfo=JSON.parse(body) resolve(userInfo) else reject(error) cfapi.allUsers = (req,res) -> fetchUser(req,res).then (userinfo)-> adminOauth.refreshToken (token) -> fetchAllUsers(token,[], 1).then (values)=> res.json total_pages : 1 resources: values ,(error)-> res.sendStatus(500).send(error) reject(error) , (error) -> console.log("Unauthenticated user attempt to fetch all users") cfapi.allUAAUsers = (req,res) -> fetchUser(req,res).then (userinfo)-> uaaadminOauth.refreshToken (token) -> fetchAllUAAUsers(token,[], 1).then (values)=> res.json total_pages : 1 resources: values ,(error)-> res.sendStatus(500).send(error) reject(error) , (error) -> console.log("Unauthenticated user attempt to fetch all users") cfapi.samlIdentityProviders = (req,res) -> fetchUser(req,res).then (userinfo)-> if(services["cloud_foundry_api-saml-provider"]?.value) res.status(200).send [ services["cloud_foundry_api-saml-provider"]?.value ] else res.status(200).send [ ] , (error) -> res.status(401).send("Unauthenticated user attempt to fetch saml identity providers") console.log("Unauthenticated user attempt to fetch saml identity providers") doRole = (method,token,level,levelGuid,associationType,associationGuid)-> new Promise (resolve,reject)-> options = method: method url: "https://#{services["cloud_foundry_api-domain"].value}/v2/#{level}/#{levelGuid}/#{associationType}/#{associationGuid}" headers: {'Authorization': token} requestjs options, (error,response,body) -> if((!error)&&(response.statusCode == 201)) resolve status : response.statusCode body : JSON.parse(body) else if((!error)&& (response.statusCode == 204)) resolve status : response.statusCode else if(!error) reject status : 500 body: response else reject status : 500 body : error cfapi.putOrgUser = (req,res)-> #first check if space manager authHeader = req.headers['authorization'] fetchUser(req,res).then (userData)-> adminOauth.refreshToken (token) -> options = method: "GET" url: "https://#{services["cloud_foundry_api-domain"].value}/v2/users/#{userData.user_id}/managed_spaces?q=organization_guid:#{req.params.levelGuid}" headers : {'Authorization' : "Bearer #{token.token.access_token}"} requestjs options, (error,response,body) -> responseBody = JSON.parse(body) if(!error && response.statusCode == 200 && responseBody["total_results"] > 0) authHeader = "Bearer #{token.token.access_token}" doRole('PUT',authHeader,"organizations",req.params.levelGuid,"users",req.params.associationGuid).then (response)-> res.status(response.status).json(response.body) , (response)-> res.status(response.status).send(response.body) , ()-> res.status(403).send("Verboten") cfapi.putRole = (req,res)-> doRole('PUT',req.headers['authorization'],req.params.level,req.params.levelGuid,req.params.associationType,req.params.associationGuid).then (response)-> res.status(response.status).json(response.body) , (response)-> res.status(response.status).send(response.body) cfapi.deleteRole = (req,res)-> doRole('DELETE',req.headers['authorization'],req.params.level,req.params.levelGuid,req.params.associationType,req.params.associationGuid).then (response)-> res.status(response.status).json(response.body) , (response)-> res.status(response.status).send(response.body) doPut = (url,token,form)-> doRequest("PUT",url,token,form) doPost = (url,token,form)-> doRequest("POST",url,token,form) doRequest = (method,url,token,form) -> new Promise (resolve,reject) -> options = method : method url: url headers : {'Authorization': "Bearer " + token.token.access_token} json : form try requestjs options, (error,response,body) -> if(!error && response.statusCode == 201) resolve status : response.statusCode body : body else if(!error ) reject status : response.statusCode body: if(body) then body else "failed" else reject status : 500 body : error catch error console.log("error=#{error}") reject status: 500 body : error cfapi.createUser = (req,res) -> #first check if space manager orgAuthToken = req.headers['authorization'].split(" ")[1] fetchUser(req,res).then (userData)-> adminOauth.refreshToken (token) -> options = method: "GET" url: "https://#{services["cloud_foundry_api-domain"].value}/v2/users/#{userData.user_id}/managed_spaces?q=organization_guid:#{req.body.org.guid}" headers : {'Authorization' : "Bearer #{token.token.access_token}"} requestjs options, (error,response,body) -> responseBody = JSON.parse(body) if(!error && response.statusCode == 200 && responseBody["total_results"] > 0) orgAuthToken = token.token.access_token doPost("https://#{services["cloud_foundry_api-uaa-domain"].value}/Users",token,buildUaacCreateUserRequest(req)).then (response)-> userId = response.body.id doPost("https://#{services["cloud_foundry_api-domain"].value}/v2/users",token, { "guid" : userId }).then (response)-> orgGuid = req.body.org.guid doRole('PUT',"Bearer #{orgAuthToken}","organizations",orgGuid,"users",userId).then (response)-> roleFutures = [] if(req.body.org.manager) roleFutures.push doRole 'PUT',req.headers['authorization'],"organizations",orgGuid,"managers",userId if(req.body.org.auditor) roleFutures.push doRole 'PUT',req.headers['authorization'],"organizations",orgGuid,"auditors",userId for space in req.body.spaces if(space.developer) roleFutures.push doRole 'PUT',req.headers['authorization'],"spaces",space.guid,"developers",userId if(space.manager) roleFutures.push doRole 'PUT',req.headers['authorization'],"spaces",space.guid,"managers",userId if(space.auditor) roleFutures.push doRole 'PUT',req.headers['authorization'],"spaces",space.guid,"auditors",userId Promise.all(roleFutures).then (responses)-> res.status(201).send("user created") , (responses)-> failedResponses = ( response for response in responses when response.status!=201 || response.error ) res.status(response.status).send(response.body) , (response)-> res.status(response.status).send(response.body) , (response)-> res.status(response.status).send(response.body) , (response)-> res.status(response.status).send(response.body) , (error)-> console.log("Unauthenticated user attempted to createUser") res.status(403).send("verboten") cfapi.changePassword = (req,res) -> uaaadminOauth.refreshToken (uaatoken) -> doPut("https://#{services["cloud_foundry_api-uaa-domain"].value}/Users/#{req.body.userId}/password",uaatoken,buildUaacChangePasswordRequest(req)).then (response)-> res.status(response.status).send(response.body) , (response)-> res.status(response.status).send(response.body) , (error)-> console.log("Unauthenticated user attempted to createUser") res.status(403).send("verboten") buildUaacCreateUserRequest = (req)-> userId =req.body.userId identityProvider = req.body.identityProvider password = if req.body.password then req.body.password else "" userIdComponents = userId.split("@") upperId = userIdComponents[0].toUpperCase() lowerId = userIdComponents[0].toLowerCase() givenName = userIdComponents[0] email = if (identityProvider!="uaa") then "#{lowerId}@#{services["cloud_foundry_api-default-email-domain"].value}" else lowerId familyName = if(identityProvider!="uaa") then services["cloud_foundry_api-default-email-domain"].value else lowerId username = switch(services["cloud_foundry_api-user-name-type"]?.value) when "email" then email when "samaccountname" then lowerId else email uaacCreateUserRequest = "schemas":["urn:scim:schemas:core:1.0"] "userName": username "name": "familyName": "#{familyName}" "givenName": "#{givenName}" "emails": [ "value": email ] "approvals": [ ] "active": true "verified": true "origin": identityProvider if (identityProvider=="uaa") uaacCreateUserRequest["password"] = password if (identityProvider!="uaa"&&identityProvider!="ldap") uaacCreateUserRequest["externalId"]= email uaacCreateUserRequest buildUaacChangePasswordRequest = (req)-> userId =req.body.userId oldpassword = if req.body.oldpassword then req.body.oldpassword else "" newpassword = if req.body.newpassword then req.body.newpassword else "" uaacChangePasswordRequest = "oldPassword":"<PASSWORD>#{<PASSWORD>}" "password":"<PASSWORD>#{<PASSWORD>}" uaacChangePasswordRequest fetchAllUsers = (token, usersToReturn, page)-> new Promise (resolve,reject) -> options = url: "https://#{services["cloud_foundry_api-domain"].value}/v2/users?order-direction=asc&results-per-page=50&page=#{page}" headers: {'Authorization': "Bearer " + token.token.access_token} requestjs options, (error,response,body) -> if(!error && response.statusCode == 200) users = JSON.parse(body) pages=users.total_pages usersToReturn.push user for user in users.resources if(page<pages) fetchAllUsers(token,usersToReturn,page+1).then ()=> resolve(usersToReturn) , (error)=> reject(error) else resolve(usersToReturn) else reject(error) fetchAllUAAUsers = (token, usersToReturn, page)-> new Promise (resolve,reject) -> options = url: "https://#{services["cloud_foundry_api-uaa-domain"].value}/Users?filter=origin+eq+%22uaa%22&count=50&sortOrder=ascending&startIndex=#{page}" headers: {'Authorization': "Bearer " + token.token.access_token} requestjs options, (error,response,body) -> if(!error && response.statusCode == 200) users = JSON.parse(body) usersToReturn.push user for user in users.resources if((page+50)<users.totalResults) fetchAllUAAUsers(token,usersToReturn,page+50).then ()=> resolve(usersToReturn) , (error)=> reject(error) else resolve(usersToReturn) else reject(error) fetchAllOrganizations = (token,orgsToReturn,page) -> fetchOrganizations(token, orgsToReturn, page, "https://#{services["cloud_foundry_api-domain"].value}/v2/organizations") fetchOrganizations = (token,orgsToReturn,page,url)-> new Promise (resolve,reject) -> options = url: "#{url}?order-direction=asc&page=#{page}&results-per-page=50" headers: {'Authorization': token} requestjs options, (error,response,body) -> if(!error && response.statusCode == 200) orgs = JSON.parse(body) pages=orgs.total_pages quotaPromises = [] for org in orgs.resources do (org) -> orgsToReturn.push entity : name : org.entity.name metadata : guid : org.metadata.guid if(page<pages) fetchOrganizations(token,orgsToReturn,page+1,url).then ()=> resolve(orgsToReturn) , (error)=> reject(error) else resolve(orgsToReturn) else reject(error) fetchListCfRequest = (token,resourcesToReturn, level,levelGuid, associationType, filter, page)-> new Promise (resolve,reject) -> options = url: "https://#{services["cloud_foundry_api-domain"].value}/v2/#{level}/#{levelGuid}/#{associationType}?order-direction=asc&page=#{page}#{if filter then "&q="+filter else ""}&results-per-page=50" headers: {'Authorization': token} requestjs options, (error,response,body) -> if(!error && response.statusCode == 200) orgs = JSON.parse(body) pages=orgs.total_pages resourcesToReturn.push resource for resource in orgs.resources if(page<pages) fetchListCfRequest(token,resourcesToReturn,level,levelGuid, associationType,filter,page+1).then ()=> resolve(resourcesToReturn) , (error)=> console.log("fetchListCfRequest error") reject(error) else resolve(resourcesToReturn) else console.log("fetchListCfRequest status: #{response.statusCode}, error: #{error}") reject(error) module.exports = cfapi
true
Promise = require 'promise' adminOauth = require "./AdminOauth" uaaadminOauth = require "./uaaAdminOauth" services = require "./serviceBindings" requestjs = require 'request' cfapi = {} adminOauth.initOauth2() uaaadminOauth.initOauth2() cfapi.allOrganizations = (req,res) -> fetchAllOrganizations(req.headers['authorization'],[],1).then (orgs)=> res.json resources: orgs resolve(orgs) , (error)-> res.status(500).send(error) reject(error) cfapi.adminOrganizations = (req,res) -> adminOauth.refreshToken (token) -> fetchAllOrganizations("Bearer #{token.token.access_token}",[],1).then (orgs)=> res.json resources: orgs resolve(orgs) , (error)-> res.status(500).send(error) reject(error) cfapi.listUserAssociation = (req,res)-> fetchUser(req,res).then (userInfo)-> adminOauth.refreshToken (token) -> fetchListCfRequest("Bearer #{token?.token?.access_token}",[], "users",req.params.userGuid, req.params.associationType, req.query?.q, 1).then (values)=> res.json total_pages: 1 resources: values ,(error)-> res.sendStatus(500).send(error) reject(error) , (error) -> console.log("Unauthenticated user attempt to call listUserAccociation") cfapi.listCfRequest = (req,res)-> adminOauth.refreshToken (token) -> fetchListCfRequest("Bearer #{token.token.access_token}",[], req.params.level,req.params.levelGuid, req.params.associationType, req.query?.q, 1).then (values)=> res.json total_pages: 1 resources: values ,(error)-> res.sendStatus(500).send(error) reject(error) cfapi.userInfo = (req,res)-> fetchUser(req,res).then (userInfo)-> res.status(200).json userInfo , (error)-> res.status(500).send(error) fetchUser = (req,res)-> new Promise (resolve,reject)-> options = url: "https://#{services["cloud_foundry_api-uaa-domain"].value}/userinfo" headers: {'Authorization': req.headers['authorization']} requestjs options, (error,response,body) -> if(!error && response.statusCode==200) userInfo=JSON.parse(body) resolve(userInfo) else reject(error) cfapi.allUsers = (req,res) -> fetchUser(req,res).then (userinfo)-> adminOauth.refreshToken (token) -> fetchAllUsers(token,[], 1).then (values)=> res.json total_pages : 1 resources: values ,(error)-> res.sendStatus(500).send(error) reject(error) , (error) -> console.log("Unauthenticated user attempt to fetch all users") cfapi.allUAAUsers = (req,res) -> fetchUser(req,res).then (userinfo)-> uaaadminOauth.refreshToken (token) -> fetchAllUAAUsers(token,[], 1).then (values)=> res.json total_pages : 1 resources: values ,(error)-> res.sendStatus(500).send(error) reject(error) , (error) -> console.log("Unauthenticated user attempt to fetch all users") cfapi.samlIdentityProviders = (req,res) -> fetchUser(req,res).then (userinfo)-> if(services["cloud_foundry_api-saml-provider"]?.value) res.status(200).send [ services["cloud_foundry_api-saml-provider"]?.value ] else res.status(200).send [ ] , (error) -> res.status(401).send("Unauthenticated user attempt to fetch saml identity providers") console.log("Unauthenticated user attempt to fetch saml identity providers") doRole = (method,token,level,levelGuid,associationType,associationGuid)-> new Promise (resolve,reject)-> options = method: method url: "https://#{services["cloud_foundry_api-domain"].value}/v2/#{level}/#{levelGuid}/#{associationType}/#{associationGuid}" headers: {'Authorization': token} requestjs options, (error,response,body) -> if((!error)&&(response.statusCode == 201)) resolve status : response.statusCode body : JSON.parse(body) else if((!error)&& (response.statusCode == 204)) resolve status : response.statusCode else if(!error) reject status : 500 body: response else reject status : 500 body : error cfapi.putOrgUser = (req,res)-> #first check if space manager authHeader = req.headers['authorization'] fetchUser(req,res).then (userData)-> adminOauth.refreshToken (token) -> options = method: "GET" url: "https://#{services["cloud_foundry_api-domain"].value}/v2/users/#{userData.user_id}/managed_spaces?q=organization_guid:#{req.params.levelGuid}" headers : {'Authorization' : "Bearer #{token.token.access_token}"} requestjs options, (error,response,body) -> responseBody = JSON.parse(body) if(!error && response.statusCode == 200 && responseBody["total_results"] > 0) authHeader = "Bearer #{token.token.access_token}" doRole('PUT',authHeader,"organizations",req.params.levelGuid,"users",req.params.associationGuid).then (response)-> res.status(response.status).json(response.body) , (response)-> res.status(response.status).send(response.body) , ()-> res.status(403).send("Verboten") cfapi.putRole = (req,res)-> doRole('PUT',req.headers['authorization'],req.params.level,req.params.levelGuid,req.params.associationType,req.params.associationGuid).then (response)-> res.status(response.status).json(response.body) , (response)-> res.status(response.status).send(response.body) cfapi.deleteRole = (req,res)-> doRole('DELETE',req.headers['authorization'],req.params.level,req.params.levelGuid,req.params.associationType,req.params.associationGuid).then (response)-> res.status(response.status).json(response.body) , (response)-> res.status(response.status).send(response.body) doPut = (url,token,form)-> doRequest("PUT",url,token,form) doPost = (url,token,form)-> doRequest("POST",url,token,form) doRequest = (method,url,token,form) -> new Promise (resolve,reject) -> options = method : method url: url headers : {'Authorization': "Bearer " + token.token.access_token} json : form try requestjs options, (error,response,body) -> if(!error && response.statusCode == 201) resolve status : response.statusCode body : body else if(!error ) reject status : response.statusCode body: if(body) then body else "failed" else reject status : 500 body : error catch error console.log("error=#{error}") reject status: 500 body : error cfapi.createUser = (req,res) -> #first check if space manager orgAuthToken = req.headers['authorization'].split(" ")[1] fetchUser(req,res).then (userData)-> adminOauth.refreshToken (token) -> options = method: "GET" url: "https://#{services["cloud_foundry_api-domain"].value}/v2/users/#{userData.user_id}/managed_spaces?q=organization_guid:#{req.body.org.guid}" headers : {'Authorization' : "Bearer #{token.token.access_token}"} requestjs options, (error,response,body) -> responseBody = JSON.parse(body) if(!error && response.statusCode == 200 && responseBody["total_results"] > 0) orgAuthToken = token.token.access_token doPost("https://#{services["cloud_foundry_api-uaa-domain"].value}/Users",token,buildUaacCreateUserRequest(req)).then (response)-> userId = response.body.id doPost("https://#{services["cloud_foundry_api-domain"].value}/v2/users",token, { "guid" : userId }).then (response)-> orgGuid = req.body.org.guid doRole('PUT',"Bearer #{orgAuthToken}","organizations",orgGuid,"users",userId).then (response)-> roleFutures = [] if(req.body.org.manager) roleFutures.push doRole 'PUT',req.headers['authorization'],"organizations",orgGuid,"managers",userId if(req.body.org.auditor) roleFutures.push doRole 'PUT',req.headers['authorization'],"organizations",orgGuid,"auditors",userId for space in req.body.spaces if(space.developer) roleFutures.push doRole 'PUT',req.headers['authorization'],"spaces",space.guid,"developers",userId if(space.manager) roleFutures.push doRole 'PUT',req.headers['authorization'],"spaces",space.guid,"managers",userId if(space.auditor) roleFutures.push doRole 'PUT',req.headers['authorization'],"spaces",space.guid,"auditors",userId Promise.all(roleFutures).then (responses)-> res.status(201).send("user created") , (responses)-> failedResponses = ( response for response in responses when response.status!=201 || response.error ) res.status(response.status).send(response.body) , (response)-> res.status(response.status).send(response.body) , (response)-> res.status(response.status).send(response.body) , (response)-> res.status(response.status).send(response.body) , (error)-> console.log("Unauthenticated user attempted to createUser") res.status(403).send("verboten") cfapi.changePassword = (req,res) -> uaaadminOauth.refreshToken (uaatoken) -> doPut("https://#{services["cloud_foundry_api-uaa-domain"].value}/Users/#{req.body.userId}/password",uaatoken,buildUaacChangePasswordRequest(req)).then (response)-> res.status(response.status).send(response.body) , (response)-> res.status(response.status).send(response.body) , (error)-> console.log("Unauthenticated user attempted to createUser") res.status(403).send("verboten") buildUaacCreateUserRequest = (req)-> userId =req.body.userId identityProvider = req.body.identityProvider password = if req.body.password then req.body.password else "" userIdComponents = userId.split("@") upperId = userIdComponents[0].toUpperCase() lowerId = userIdComponents[0].toLowerCase() givenName = userIdComponents[0] email = if (identityProvider!="uaa") then "#{lowerId}@#{services["cloud_foundry_api-default-email-domain"].value}" else lowerId familyName = if(identityProvider!="uaa") then services["cloud_foundry_api-default-email-domain"].value else lowerId username = switch(services["cloud_foundry_api-user-name-type"]?.value) when "email" then email when "samaccountname" then lowerId else email uaacCreateUserRequest = "schemas":["urn:scim:schemas:core:1.0"] "userName": username "name": "familyName": "#{familyName}" "givenName": "#{givenName}" "emails": [ "value": email ] "approvals": [ ] "active": true "verified": true "origin": identityProvider if (identityProvider=="uaa") uaacCreateUserRequest["password"] = password if (identityProvider!="uaa"&&identityProvider!="ldap") uaacCreateUserRequest["externalId"]= email uaacCreateUserRequest buildUaacChangePasswordRequest = (req)-> userId =req.body.userId oldpassword = if req.body.oldpassword then req.body.oldpassword else "" newpassword = if req.body.newpassword then req.body.newpassword else "" uaacChangePasswordRequest = "oldPassword":"PI:PASSWORD:<PASSWORD>END_PI#{PI:PASSWORD:<PASSWORD>END_PI}" "password":"PI:PASSWORD:<PASSWORD>END_PI#{PI:PASSWORD:<PASSWORD>END_PI}" uaacChangePasswordRequest fetchAllUsers = (token, usersToReturn, page)-> new Promise (resolve,reject) -> options = url: "https://#{services["cloud_foundry_api-domain"].value}/v2/users?order-direction=asc&results-per-page=50&page=#{page}" headers: {'Authorization': "Bearer " + token.token.access_token} requestjs options, (error,response,body) -> if(!error && response.statusCode == 200) users = JSON.parse(body) pages=users.total_pages usersToReturn.push user for user in users.resources if(page<pages) fetchAllUsers(token,usersToReturn,page+1).then ()=> resolve(usersToReturn) , (error)=> reject(error) else resolve(usersToReturn) else reject(error) fetchAllUAAUsers = (token, usersToReturn, page)-> new Promise (resolve,reject) -> options = url: "https://#{services["cloud_foundry_api-uaa-domain"].value}/Users?filter=origin+eq+%22uaa%22&count=50&sortOrder=ascending&startIndex=#{page}" headers: {'Authorization': "Bearer " + token.token.access_token} requestjs options, (error,response,body) -> if(!error && response.statusCode == 200) users = JSON.parse(body) usersToReturn.push user for user in users.resources if((page+50)<users.totalResults) fetchAllUAAUsers(token,usersToReturn,page+50).then ()=> resolve(usersToReturn) , (error)=> reject(error) else resolve(usersToReturn) else reject(error) fetchAllOrganizations = (token,orgsToReturn,page) -> fetchOrganizations(token, orgsToReturn, page, "https://#{services["cloud_foundry_api-domain"].value}/v2/organizations") fetchOrganizations = (token,orgsToReturn,page,url)-> new Promise (resolve,reject) -> options = url: "#{url}?order-direction=asc&page=#{page}&results-per-page=50" headers: {'Authorization': token} requestjs options, (error,response,body) -> if(!error && response.statusCode == 200) orgs = JSON.parse(body) pages=orgs.total_pages quotaPromises = [] for org in orgs.resources do (org) -> orgsToReturn.push entity : name : org.entity.name metadata : guid : org.metadata.guid if(page<pages) fetchOrganizations(token,orgsToReturn,page+1,url).then ()=> resolve(orgsToReturn) , (error)=> reject(error) else resolve(orgsToReturn) else reject(error) fetchListCfRequest = (token,resourcesToReturn, level,levelGuid, associationType, filter, page)-> new Promise (resolve,reject) -> options = url: "https://#{services["cloud_foundry_api-domain"].value}/v2/#{level}/#{levelGuid}/#{associationType}?order-direction=asc&page=#{page}#{if filter then "&q="+filter else ""}&results-per-page=50" headers: {'Authorization': token} requestjs options, (error,response,body) -> if(!error && response.statusCode == 200) orgs = JSON.parse(body) pages=orgs.total_pages resourcesToReturn.push resource for resource in orgs.resources if(page<pages) fetchListCfRequest(token,resourcesToReturn,level,levelGuid, associationType,filter,page+1).then ()=> resolve(resourcesToReturn) , (error)=> console.log("fetchListCfRequest error") reject(error) else resolve(resourcesToReturn) else console.log("fetchListCfRequest status: #{response.statusCode}, error: #{error}") reject(error) module.exports = cfapi
[ { "context": "g-schema\")\n\n @username = @config.username # \"email@domain.com\";\n @password = @config.password #\"a1b2c3d4\";", "end": 524, "score": 0.9999203681945801, "start": 508, "tag": "EMAIL", "value": "email@domain.com" }, { "context": "domain.com\";\n @password = @config.password #\"a1b2c3d4\";\n @region = @config.region ? 'EU'\n @pi", "end": 572, "score": 0.9994808435440063, "start": 564, "tag": "PASSWORD", "value": "a1b2c3d4" }, { "context": " = @config.pin\n\n options = \n username: @username\n password: @password\n region: @regi", "end": 683, "score": 0.9992547631263733, "start": 674, "tag": "USERNAME", "value": "@username" }, { "context": "s = \n username: @username\n password: @password\n region: @region\n pin: @pin\n @", "end": 711, "score": 0.999141275882721, "start": 702, "tag": "PASSWORD", "value": "@password" }, { "context": "solve()\n )\n\n getEngine: -> Promise.resolve(@_engine)\n getAirco: -> Promise.resolve(@_airco)\n ge", "end": 18426, "score": 0.9729203581809998, "start": 18418, "tag": "USERNAME", "value": "@_engine" }, { "context": "resolve(@_engine)\n getAirco: -> Promise.resolve(@_airco)\n getDoor: -> Promise.resolve(@_door)\n getD", "end": 18468, "score": 0.7342713475227356, "start": 18461, "tag": "USERNAME", "value": "@_airco" }, { "context": "ntRight)\n getDoorBackLeft: -> Promise.resolve(@_doorBackLeft)\n getDoorBackRight: -> Promise.resolve", "end": 18674, "score": 0.5302540063858032, "start": 18670, "tag": "USERNAME", "value": "door" }, { "context": "e.resolve(@_hood)\n getTrunk: -> Promise.resolve(@_trunk)\n getCharging: -> Promise.resolve(@_charging)\n", "end": 18822, "score": 0.8401128649711609, "start": 18815, "tag": "USERNAME", "value": "@_trunk" }, { "context": "solve(@_trunk)\n getCharging: -> Promise.resolve(@_charging)\n getBattery: -> Promise.resolve(@_battery)\n ", "end": 18870, "score": 0.9367396235466003, "start": 18860, "tag": "USERNAME", "value": "@_charging" }, { "context": "lve(@_charging)\n getBattery: -> Promise.resolve(@_battery)\n getTwelveVoltBattery: -> Promise.resolve(@_t", "end": 18916, "score": 0.8674150109291077, "start": 18907, "tag": "USERNAME", "value": "@_battery" }, { "context": "tery)\n getTwelveVoltBattery: -> Promise.resolve(@_twelveVoltBattery)\n getPluggedIn: -> Promise.resolve(@_pluggedIn", "end": 18982, "score": 0.9686254262924194, "start": 18963, "tag": "USERNAME", "value": "@_twelveVoltBattery" }, { "context": "eVoltBattery)\n getPluggedIn: -> Promise.resolve(@_pluggedIn)\n getOdo: -> Promise.resolve(@_odo)\n getSpe", "end": 19032, "score": 0.9617401361465454, "start": 19021, "tag": "USERNAME", "value": "@_pluggedIn" }, { "context": "esolve(@_pluggedIn)\n getOdo: -> Promise.resolve(@_odo)\n getSpeed: -> Promise.resolve(@_speed)\n ge", "end": 19070, "score": 0.8521761894226074, "start": 19065, "tag": "USERNAME", "value": "@_odo" }, { "context": ".resolve(@_odo)\n getSpeed: -> Promise.resolve(@_speed)\n getMaximum: -> Promise.resolve(@_maximum)\n ", "end": 19112, "score": 0.8621662855148315, "start": 19107, "tag": "USERNAME", "value": "speed" }, { "context": "esolve(@_speed)\n getMaximum: -> Promise.resolve(@_maximum)\n getRemainingRange: -> Promise.resolve(@_rema", "end": 19158, "score": 0.8832777142524719, "start": 19149, "tag": "USERNAME", "value": "@_maximum" }, { "context": "maximum)\n getRemainingRange: -> Promise.resolve(@_remainingRange)\n getLat: -> Promise.resolve(@_lat)\n getLon", "end": 19218, "score": 0.8224278688430786, "start": 19202, "tag": "USERNAME", "value": "@_remainingRange" }, { "context": "e(@_remainingRange)\n getLat: -> Promise.resolve(@_lat)\n getLon: -> Promise.resolve(@_lon)\n getSta", "end": 19256, "score": 0.9285925030708313, "start": 19251, "tag": "USERNAME", "value": "@_lat" }, { "context": "mise.resolve(@_lat)\n getLon: -> Promise.resolve(@_lon)\n getStatus: -> Promise.resolve(@_status)\n ", "end": 19294, "score": 0.8612797260284424, "start": 19289, "tag": "USERNAME", "value": "@_lon" }, { "context": "e.resolve(@_lon)\n getStatus: -> Promise.resolve(@_status)\n getChargingTime: -> Promise.resolve(@_chargi", "end": 19338, "score": 0.956366777420044, "start": 19330, "tag": "USERNAME", "value": "@_status" }, { "context": "(@_status)\n getChargingTime: -> Promise.resolve(@_chargingTime)\n\n\n setStatus: (status, command)=>\n switc", "end": 19394, "score": 0.8877304196357727, "start": 19380, "tag": "USERNAME", "value": "@_chargingTime" } ]
pimatic-bluelink.coffee
bertreb/pimatic-bluelink
1
module.exports = (env) -> Promise = env.require 'bluebird' assert = env.require 'cassert' M = env.matcher _ = require('lodash') fs = require('fs') path = require('path') #Bluelinky = require('kuvork') Bluelinky = require('bluelinky') class BluelinkPlugin extends env.plugins.Plugin init: (app, @framework, @config) => pluginConfigDef = require './pimatic-bluelink-config-schema' @deviceConfigDef = require("./device-config-schema") @username = @config.username # "email@domain.com"; @password = @config.password #"a1b2c3d4"; @region = @config.region ? 'EU' @pin = @config.pin options = username: @username password: @password region: @region pin: @pin @brand = @config.brand ? "kia" if @brand is "hyundai" #Bluelinky = require('bluelinky') @_discoveryClass = "HyundaiDevice" options["brand"] = "hyundai" else #Bluelinky = require('kuvork') @_discoveryClass = "KiaDevice" options["brand"] = "kia" options["vin"] = "KNA" #for detecting the Kia or Hyandai api, brand deduction: VIN numbers of KIA are KNA/KNC/KNE @client = null @clientReady = false @framework.on 'after init', ()=> mobileFrontend = @framework.pluginManager.getPlugin 'mobile-frontend' if mobileFrontend? mobileFrontend.registerAssetFile 'js', "pimatic-bluelink/app/bluelink.coffee" mobileFrontend.registerAssetFile 'html', "pimatic-bluelink/app/bluelink.jade" mobileFrontend.registerAssetFile 'css', "pimatic-bluelink/app/bluelink.css" @client = new Bluelinky(options) @client.on 'ready',() => env.logger.debug "Plugin emit clientReady" @clientReady = true @emit "clientReady" @client.on 'error',(err) => env.logger.debug "Bluelink login error: " + JSON.stringify(err,null,2) @clientReady = false @framework.deviceManager.registerDeviceClass('KiaDevice', { configDef: @deviceConfigDef.KiaDevice, createCallback: (config, lastState) => new KiaDevice(config, lastState, @, @client, @framework) }) @framework.deviceManager.registerDeviceClass('HyundaiDevice', { configDef: @deviceConfigDef.HyundaiDevice, createCallback: (config, lastState) => new HyundaiDevice(config, lastState, @, @client, @framework) }) @framework.ruleManager.addActionProvider(new BluelinkActionProvider(@framework)) @framework.deviceManager.on('discover', (eventData) => @framework.deviceManager.discoverMessage 'pimatic-bluelink', 'Searching for new devices' if @clientReady @client.getVehicles() .then((vehicles) => for vehicle in vehicles carConfig = vehicle.vehicleConfig env.logger.info "CarConfig: " + JSON.stringify(carConfig,null,2) _did = (carConfig.nickname).split(' ').join("_") if _.find(@framework.deviceManager.devicesConfig,(d) => d.id is _did) env.logger.info "Device '" + _did + "' already in config" else config = id: _did #(carConfig.nickname).split(' ').join("_").toLowerCase() name: carConfig.nickname class: @_discoveryClass vin: carConfig.vin vehicleId: carConfig.id type: carConfig.name @framework.deviceManager.discoveredDevice( "Bluelink", config.name, config) ).catch((e) => env.logger.error 'Error in getVehicles: ' + e.message ) ) class BluelinkDevice extends env.devices.Device template: "bluelink" actions: changeActionTo: description: "Sets the action" params: action: type: "string" attributes: engine: description: "Status of engine" type: "boolean" acronym: "engine" labels: ["on","off"] hidden: false airco: description: "Status of airco" type: "string" acronym: "airco" enum: ["start","startPlus","off"] hidden: true door: description: "Status of doorlock" type: "boolean" acronym: "door" labels: ["locked","unlocked"] hidden: true charging: description: "If vehicle is charging" type: "boolean" acronym: "charging" labels: ["on","off"] hidden: true pluggedIn: description: "If vehicle is pluggedIn" type: "string" acronym: "batteryPlugin" chargingTime: description: "Time left for charging" type: "string" acronym: "charging time" doorFrontLeft: description: "door fl" type: "boolean" acronym: "door fl" labels: ["opened","closed"] doorFrontRight: description: "door fr" type: "boolean" acronym: "door fr" labels: ["opened","closed"] doorBackLeft: description: "door bl" type: "boolean" acronym: "door bl" labels: ["opened","closed"] doorBackRight: description: "door br" type: "boolean" acronym: "door br" labels: ["opened","closed"] hood: description: "hood" type: "boolean" acronym: "hood" labels: ["opened","closed"] trunk: description: "trunk" type: "boolean" acronym: "trunk" labels: ["opened","closed"] battery: description: "The battery level" type: "number" unit: '%' acronym: "battery" remainingRange: description: "Remaining range basing on current battery resp. fuel level" type: "number" acronym: "remaining" unit: "km" twelveVoltBattery: description: "The 12 volt battery level" type: "number" unit: '%' acronym: "12V" odo: description: "The car odo value" type: "number" unit: 'km' acronym: "odo" speed: description: "Speed of the car" type: "number" acronym: "speed" unit: "km/h" maximum: description: "Maximum range basing on current battery resp. fuel level" type: "string" acronym: "maximum" lat: description: "The cars latitude" type: "number" acronym: "lat" lon: description: "The cars longitude" type: "number" acronym: "lon" status: description: "The connection status" type: "string" acronym: "status" getTemplateName: -> "bluelink" statusCodes = init: 0 ready: 1 getStatus: 2 getStatusError: 3 commandSend: 4 commandSuccess: 5 commanderror: 6 constructor: (config, lastState, @plugin, client, @framework) -> @config = config @id = @config.id @name = @config.name @client = @plugin.client @pollTimePassive = @config.pollTimePassive ? 3600000 # 1 hour @pollTimeActive = @config.pollTimeActive ? 600000 # 10 minutes @currentPollTime = @pollTimeActive @_defrost = @config.defrost ? false @_windscreenHeating = @config.windscreenHeating ? false @_temperature = @config.temperature ? 20 @_optionsVariable = @config.optionsVariable ? "" @_engine = laststate?.engine?.value ? false @_speed = laststate?.speed?.value ? 0 @_airco = laststate?.airco?.value ? "off" @_door = laststate?.door?.value ? false @_charging = laststate?.charging?.value ? false @_chargingTime = laststate?.chargingTime?.value ? 0 @_battery = laststate?.battery?.value ? 0 @_twelveVoltBattery = laststate?.twelveVoltBattery?.value ? 0 @_pluggedIn = laststate?.pluggedIn?.value ? "unplugged" @_odo = laststate?.odo?.value ? 0 @_maximum = laststate?.maximum?.value ? 0 @_remainingRange = laststate?.remainingRange?.value ? 0 @_doorFrontLeft = laststate?.doorFrontLeft?.value ? 0 @_doorFrontRight = laststate?.doorFrontRight?.value ? 0 @_doorBackLeft = laststate?.doorBackLeft?.value ? 0 @_doorBackRight = laststate?.doorBackRight?.value ? 0 @_hood = laststate?.hood?.value ? 0 @_trunk = laststate?.trunk?.value ? 0 @_lat = laststate?.lat?.value ? 0 @_lon = laststate?.lon?.value ? 0 @_status = statusCodes.init @setStatus(statusCodes.init) retries = 0 maxRetries = 20 @vehicle = null ### @config.xAttributeOptions = [] unless @config.xAttributeOptions? for i, _attr of @attributes do (_attr) => if _attr.type is 'number' _hideSparklineNumber = name: i displaySparkline: false @config.xAttributeOptions.push _hideSparklineNumber ### @plugin.on 'clientReady', @clientListener = () => unless @statusTimer? env.logger.debug "Plugin ClientReady, requesting vehicle" @vehicle = @plugin.client.getVehicle(@config.vin) env.logger.debug "From plugin start - starting status update cyle" @setStatus(statusCodes.ready) @getCarStatus(true) # actual car status on start else env.logger.debug "Error: plugin start but @statusTimer alredy running!" @framework.variableManager.waitForInit() .then ()=> if @plugin.clientReady and not @statusTimer? env.logger.debug "ClientReady ready, Device starting, requesting vehicle" @vehicle = @plugin.client.getVehicle(@config.vin) env.logger.debug "From device start - starting status update cyle" @setStatus(statusCodes.ready) @getCarStatus(true) # actual car status on start @getCarStatus = (_refresh=false) => if @plugin.clientReady clearTimeout(@statusTimer) if @statusTimer? env.logger.debug "requesting status, refresh: " + _refresh @setStatus(statusCodes.getStatus) @vehicle.status({refresh:_refresh}) .then (status)=> @handleStatus(status) return @vehicle.location() .then (location)=> env.logger.debug "location " + JSON.stringify(location,null,2) @handleLocation(location) return @vehicle.odometer() .then (odometer) => env.logger.debug "odo " + JSON.stringify(odometer,null,2) @handleOdo(odometer) @setStatus(statusCodes.ready) .catch (e) => @setStatus(statusCodes.getStatusError) env.logger.debug "getStatus error: " + JSON.stringify(e.body,null,2) @statusTimer = setTimeout(@getCarStatus, @currentPollTime) env.logger.debug "Next poll in " + @currentPollTime + " ms" else env.logger.debug "(re)requesting status in 5 seconds, client not ready" retries += 1 if retries < maxRetries @statusTimer = setTimeout(@getCarStatus, 5000) else env.logger.debug "Max number of retries(#{maxRetries}) reached, Client not ready, stop trying" super() handleLocation: (location) => @setLocation(location.latitude, location.longitude) @setSpeed(location.speed.value) handleOdo: (odo) => @setOdo(odo.value) handleStatus: (status) => env.logger.debug "Status: " + JSON.stringify(status,null,2) if status.doorLock? @setDoor(status.doorLock) if status.doorOpen? @setDoors(status) if status.engine? @setEngine(status.engine) if status.airCtrlOn? if status.airCtrlOn @setAirco("start") else @setAirco("off") if status.battery?.batSoc? @setTwelveVoltBattery(status.battery.batSoc) if status.evStatus? @setEvStatus(status.evStatus) #update polltime to active if engine is on, charging or airco is on active = (Boolean status.engine) or (Boolean status.evStatus.batteryCharge) or (Boolean status.airCtrlOn) env.logger.debug "Car status PollTimeActive is " + active @setPollTime(active) parseOptions: (_options) -> climateOptions = defrost: @_defrost windscreenHeating: @_windscreenHeating temperature: @_temperature unit: 'C' if _options? try parameters = _options.split(",") for parameter in parameters tokens = parameter.split(":") _key = tokens[0].trim() _val = tokens[1].trim() env.logger.debug "_key: " + _key + ", _val: " + _val switch _key when "defrost" climateOptions.defrost = (if _val is "false" then false else true) when "windscreenHeating" climateOptions.windscreenHeating = (if _val is "false" then false else true) when "temperature" # check if number unless Number.isNaN(Number _val) climateOptions.temperature = Number _val catch err env.logger.debug "Handled error in parseOptions " + err return climateOptions changeActionTo: (action) => _action = action options = null if action is "startPlus" if @_optionsVariable isnt "" _optionsString = @framework.variableManager.getVariableValue(@_optionsVariable) if _optionsString? options = _optionsString else return Promise.reject("optionsVariable '#{@_optionsVariable}' does not exsist") else return Promise.reject("No optionsVariable defined") return @execute(_action, options) execute: (command, options) => return new Promise((resolve,reject) => unless @vehicle? then return reject("No active vehicle") @setStatus(statusCodes.commandSend, command) switch command when "start" env.logger.debug "Start with options: " + JSON.stringify(@parseOptions(options),null,2) @vehicle.start(@parseOptions(options)) .then (resp)=> env.logger.debug "Started: " + JSON.stringify(resp,null,2) #@setEngine(true) @setAirco("start") @setPollTime(true) # set to active poll @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error start car: " + JSON.stringify(err,null,2) reject() when "startPlus" env.logger.debug "StartPlus with options: " + JSON.stringify(@parseOptions(options),null,2) @vehicle.start(@parseOptions(options)) .then (resp)=> env.logger.debug "Started: " + JSON.stringify(resp,null,2) #@setEngine(true) @setAirco("startPlus") @setPollTime(true) # set to active poll @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error start car: " + JSON.stringify(err,null,2) reject() when "stop" @vehicle.stop() .then (resp)=> #@setEngine(false) @setAirco("off") env.logger.debug "Stopped: " + JSON.stringify(resp,null,2) @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error stop car: " + JSON.stringify(err,null,2) reject() when "lock" @vehicle.lock() .then (resp)=> @setDoor(true) env.logger.debug "Locked: " + JSON.stringify(resp,null,2) @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error lock car: " + JSON.stringify(err,null,2) reject() when "unlock" @vehicle.unlock() .then (resp)=> @setDoor(false) @setPollTime(true) # set to active poll env.logger.debug "Unlocked: " + JSON.stringify(resp,null,2) @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error unlock car: " + JSON.stringify(err,null,2) reject() when "startCharge" @vehicle.startCharge() .then (resp)=> @setCharge(true) @setPollTime(true) # set to active poll env.logger.debug "startCharge: " + JSON.stringify(resp,null,2) @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error startCharge car: " + JSON.stringify(err,null,2) reject() when "stopCharge" @vehicle.stopCharge() .then (resp)=> @setCharge(false) env.logger.debug "stopCharge: " + JSON.stringify(resp,null,2) @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error stopCharge car: " + JSON.stringify(err,null,2) reject() when "refresh" clearTimeout(@statusTimer) if @statusTimer? @getCarStatus(true) env.logger.debug "refreshing status" @setStatus(statusCodes.commandSuccess, command) resolve() else @setStatus(statusCodes.commandError, command) env.logger.debug "Unknown command " + command reject() resolve() ) getEngine: -> Promise.resolve(@_engine) getAirco: -> Promise.resolve(@_airco) getDoor: -> Promise.resolve(@_door) getDoorFrontLeft: -> Promise.resolve(@_doorFrontLeft) getDoorFrontRight: -> Promise.resolve(@_doorFrontRight) getDoorBackLeft: -> Promise.resolve(@_doorBackLeft) getDoorBackRight: -> Promise.resolve(@_doorBackRight) getHood: -> Promise.resolve(@_hood) getTrunk: -> Promise.resolve(@_trunk) getCharging: -> Promise.resolve(@_charging) getBattery: -> Promise.resolve(@_battery) getTwelveVoltBattery: -> Promise.resolve(@_twelveVoltBattery) getPluggedIn: -> Promise.resolve(@_pluggedIn) getOdo: -> Promise.resolve(@_odo) getSpeed: -> Promise.resolve(@_speed) getMaximum: -> Promise.resolve(@_maximum) getRemainingRange: -> Promise.resolve(@_remainingRange) getLat: -> Promise.resolve(@_lat) getLon: -> Promise.resolve(@_lon) getStatus: -> Promise.resolve(@_status) getChargingTime: -> Promise.resolve(@_chargingTime) setStatus: (status, command)=> switch status when statusCodes.init _status = "initializing" when statusCodes.ready _status = "ready" when statusCodes.getStatus _status = "get status" when statusCodes.getStatusError _status = "get status error" when statusCodes.commandSend _status = "execute " + command when statusCodes.commandSuccess _status = command + " executed" setTimeout(=> @setStatus(statusCodes.ready) ,3000) when statusCodes.commandError _status = command + " error" else _status = "unknown status " + status @_status = _status @emit 'status', _status setPollTime: (active) => # true is active, false is passive if (active and @currentPollTime == @pollTimeActive) or (!active and @currentPollTime == @pollTimePassive) then return #env.logger.debug("Test for active " + active + ", @currentPollTime:"+@currentPollTime+", @pollTimePassive:"+@pollTimePassive+", == "+ (@currentPollTimer == @pollTimePassive)) if (active) and (@currentPollTime == @pollTimePassive) clearTimeout(@statusTimer) if @statusTimer? @currentPollTime = @pollTimeActive env.logger.debug "Switching to active poll, with polltime of " + @pollTimeActive + " ms" @statusTimer = setTimeout(@getCarStatus, @pollTimeActive) return if not active and @currentPollTime == @pollTimeActive clearTimeout(@statusTimer) if @statusTimer? @currentPollTime = @pollTimePassive env.logger.debug "Switching to passive poll, with polltime of " + @pollTimePassive + " ms" @statusTimer = setTimeout(@getCarStatus, @pollTimePassive) setMaximum: (_range) => @_maximum = _range @emit 'maximum', _range setRemainingRange: (_range) => @_remainingRange = Number _range @emit 'remainingRange', Number _range setEngine: (_status) => @_engine = Boolean _status @emit 'engine', Boolean _status setSpeed: (_status) => @_speed = Number _status @emit 'speed', Number _status setDoor: (_status) => @_door = Boolean _status @emit 'door', Boolean _status setTwelveVoltBattery: (_status) => @_twelveVoltBattery = Number _status # Math.round (_status / 2.55 ) @emit 'twelveVoltBattery', Number _status # Math.round (_status / 2.55 ) setChargingTime: (_status) => @_chargingTime = _status @emit 'chargingTime', _status setDoors: (_status) => if _status.doorOpen? @_doorFrontLeft = Boolean _status.doorOpen.frontLeft @emit 'doorFrontLeft', Boolean _status.doorOpen.frontLeft @_doorFrontRight = Boolean _status.doorOpen.doorFrontRight @emit 'doorFrontRight', Boolean _status.doorOpen.doorFrontRight @_doorBackLeft = Boolean _status.doorOpen.backLeft @emit 'doorBackLeft', Boolean _status.doorOpen.backLeft @_doorBackRight = Boolean _status.doorOpen.backRight @emit 'doorBackRight', Boolean _status.doorOpen.backRight if _status.trunkOpen? @_trunk = Boolean _status.trunkOpen @emit 'trunk', Boolean _status.trunkOpen if _status.hoodOpen? @_hood = Boolean _status.hoodOpen @emit 'hood', Boolean _status.hoodOpen setEvStatus: (evStatus) => @_battery = Number evStatus.batteryStatus @emit 'battery', Number evStatus.batteryStatus switch evStatus.batteryPlugin when 0 @_pluggedIn = "unplugged" _chargingTime = "no value" when 1 @_pluggedIn = "DC" _chargingTime = evStatus.remainTime2.etc1.value + "min (DC)" when 2 #@_pluggedIn = "ACportable" #_chargingTime = evStatus.remainTime2.etc2.value + "min (ACport)" @_pluggedIn = "AC" _chargingTime = evStatus.remainTime2.etc3.value + "min (AC)" when 3 @_pluggedIn = "AC" _chargingTime = evStatus.remainTime2.etc3.value + "min (AC)" else @_pluggedIn = "unknown" _chargingTime = "" @setChargingTime(_chargingTime) @emit 'pluggedIn', @_pluggedIn @_charging = Boolean evStatus.batteryCharge @emit 'charging', Boolean evStatus.batteryCharge #if @_charging # @_pluggedIn = true # @emit 'pluggedIn', (evStatus.batteryPlugin > 0) # DC maximum if evStatus.reservChargeInfos.targetSOClist?[0]?.dte?.rangeByFuel?.totalAvailableRange?.value? _maximumDC = Number evStatus.reservChargeInfos.targetSOClist[0].dte.rangeByFuel.totalAvailableRange.value _maximumDCperc = Number evStatus.reservChargeInfos.targetSOClist[0].targetSOClevel if evStatus.reservChargeInfos.targetSOClist?[1]?.dte?.rangeByFuel?.totalAvailableRange?.value? _maximumAC = Number evStatus.reservChargeInfos.targetSOClist[1].dte.rangeByFuel.totalAvailableRange.value _maximumACperc = Number evStatus.reservChargeInfos.targetSOClist[1].targetSOClevel if _maximumDC? and _maximumAC? _maximum = _maximumDC + "km (DC@" + _maximumDCperc + "%) " + _maximumAC + "km (AC@" + _maximumACperc + "%)" @setMaximum(_maximum) else @setMaximum("no value") if evStatus.drvDistance?[0]?.rangeByFuel?.totalAvailableRange?.value? _remainingRange = Number evStatus.drvDistance[0].rangeByFuel.totalAvailableRange.value if _remainingRange > 0 @setRemainingRange(_remainingRange) setAirco: (_status) => @_airco = _status @emit 'airco', _status setOdo: (_status) => @_odo = Number _status @emit 'odo', Number _status setLocation: (_lat, _lon) => @_lat = _lat @_lon = _lon @emit 'lat', _lat @emit 'lon', _lon setCharge: (charging) => @_charging = Boolean charging @emit 'charging', Boolean charging #if charging # @_pluggedIn = true # if charging, must be pluggedIn # @emit 'pluggedIn', @_pluggedIn destroy:() => clearTimeout(@statusTimer) if @statusTimer? @plugin.removeListener('clientReady', @clientListener) super() class BluelinkActionProvider extends env.actions.ActionProvider constructor: (@framework) -> parseAction: (input, context) => bluelinkDevice = null @options = null supportedCarClasses = ["KiaDevice","HyundaiDevice"] bluelinkDevices = _(@framework.deviceManager.devices).values().filter( (device) => device.config.class in supportedCarClasses ).value() setCommand = (command) => @command = command optionsString = (m,tokens) => unless tokens? context?.addError("No variable") return @options = tokens setCommand("start") m = M(input, context) .match('bluelink ') .matchDevice(bluelinkDevices, (m, d) -> # Already had a match with another device? if bluelinkDevice? and bluelinkDevices.id isnt d.id context?.addError(""""#{input.trim()}" is ambiguous.""") return bluelinkDevice = d ) .or([ ((m) => return m.match(' startDefault', (m) => setCommand('start') match = m.getFullMatch() ) ), ((m) => return m.match(' start ') .matchVariable(optionsString) ), ((m) => return m.match(' startPlus', (m) => setCommand('startPlus') match = m.getFullMatch() ) ), ((m) => return m.match(' stop', (m) => setCommand('stop') match = m.getFullMatch() ) ), ((m) => return m.match(' lock', (m) => setCommand('lock') match = m.getFullMatch() ) ), ((m) => return m.match(' unlock', (m) => setCommand('unlock') match = m.getFullMatch() ) ), ((m) => return m.match(' startCharge', (m) => setCommand('startCharge') match = m.getFullMatch() ) ), ((m) => return m.match(' stopCharge', (m) => setCommand('stopCharge') match = m.getFullMatch() ) ), ((m) => return m.match(' refresh', (m) => setCommand('refresh') match = m.getFullMatch() ) ) ]) match = m.getFullMatch() if match? #m.hadMatch() env.logger.debug "Rule matched: '", match, "' and passed to Action handler" return { token: match nextInput: input.substring(match.length) actionHandler: new BluelinkActionHandler(@framework, bluelinkDevice, @command, @options) } else return null class BluelinkActionHandler extends env.actions.ActionHandler constructor: (@framework, @bluelinkDevice, @command, @options) -> executeAction: (simulate) => if simulate return __("would have cleaned \"%s\"", "") else if @options? _var = @options.slice(1) if @options.indexOf('$') >= 0 _options = @framework.variableManager.getVariableValue(_var) unless _options? return __("\"%s\" Rule not executed, #{_var} is not a valid variable", "") else _options = null @bluelinkDevice.execute(@command, _options) .then(()=> return __("\"%s\" Rule executed", @command) ).catch((err)=> return __("\"%s\" Rule not executed", "") ) class KiaDevice extends BluelinkDevice class HyundaiDevice extends BluelinkDevice bluelinkPlugin = new BluelinkPlugin return bluelinkPlugin
119974
module.exports = (env) -> Promise = env.require 'bluebird' assert = env.require 'cassert' M = env.matcher _ = require('lodash') fs = require('fs') path = require('path') #Bluelinky = require('kuvork') Bluelinky = require('bluelinky') class BluelinkPlugin extends env.plugins.Plugin init: (app, @framework, @config) => pluginConfigDef = require './pimatic-bluelink-config-schema' @deviceConfigDef = require("./device-config-schema") @username = @config.username # "<EMAIL>"; @password = @config.password #"<PASSWORD>"; @region = @config.region ? 'EU' @pin = @config.pin options = username: @username password: <PASSWORD> region: @region pin: @pin @brand = @config.brand ? "kia" if @brand is "hyundai" #Bluelinky = require('bluelinky') @_discoveryClass = "HyundaiDevice" options["brand"] = "hyundai" else #Bluelinky = require('kuvork') @_discoveryClass = "KiaDevice" options["brand"] = "kia" options["vin"] = "KNA" #for detecting the Kia or Hyandai api, brand deduction: VIN numbers of KIA are KNA/KNC/KNE @client = null @clientReady = false @framework.on 'after init', ()=> mobileFrontend = @framework.pluginManager.getPlugin 'mobile-frontend' if mobileFrontend? mobileFrontend.registerAssetFile 'js', "pimatic-bluelink/app/bluelink.coffee" mobileFrontend.registerAssetFile 'html', "pimatic-bluelink/app/bluelink.jade" mobileFrontend.registerAssetFile 'css', "pimatic-bluelink/app/bluelink.css" @client = new Bluelinky(options) @client.on 'ready',() => env.logger.debug "Plugin emit clientReady" @clientReady = true @emit "clientReady" @client.on 'error',(err) => env.logger.debug "Bluelink login error: " + JSON.stringify(err,null,2) @clientReady = false @framework.deviceManager.registerDeviceClass('KiaDevice', { configDef: @deviceConfigDef.KiaDevice, createCallback: (config, lastState) => new KiaDevice(config, lastState, @, @client, @framework) }) @framework.deviceManager.registerDeviceClass('HyundaiDevice', { configDef: @deviceConfigDef.HyundaiDevice, createCallback: (config, lastState) => new HyundaiDevice(config, lastState, @, @client, @framework) }) @framework.ruleManager.addActionProvider(new BluelinkActionProvider(@framework)) @framework.deviceManager.on('discover', (eventData) => @framework.deviceManager.discoverMessage 'pimatic-bluelink', 'Searching for new devices' if @clientReady @client.getVehicles() .then((vehicles) => for vehicle in vehicles carConfig = vehicle.vehicleConfig env.logger.info "CarConfig: " + JSON.stringify(carConfig,null,2) _did = (carConfig.nickname).split(' ').join("_") if _.find(@framework.deviceManager.devicesConfig,(d) => d.id is _did) env.logger.info "Device '" + _did + "' already in config" else config = id: _did #(carConfig.nickname).split(' ').join("_").toLowerCase() name: carConfig.nickname class: @_discoveryClass vin: carConfig.vin vehicleId: carConfig.id type: carConfig.name @framework.deviceManager.discoveredDevice( "Bluelink", config.name, config) ).catch((e) => env.logger.error 'Error in getVehicles: ' + e.message ) ) class BluelinkDevice extends env.devices.Device template: "bluelink" actions: changeActionTo: description: "Sets the action" params: action: type: "string" attributes: engine: description: "Status of engine" type: "boolean" acronym: "engine" labels: ["on","off"] hidden: false airco: description: "Status of airco" type: "string" acronym: "airco" enum: ["start","startPlus","off"] hidden: true door: description: "Status of doorlock" type: "boolean" acronym: "door" labels: ["locked","unlocked"] hidden: true charging: description: "If vehicle is charging" type: "boolean" acronym: "charging" labels: ["on","off"] hidden: true pluggedIn: description: "If vehicle is pluggedIn" type: "string" acronym: "batteryPlugin" chargingTime: description: "Time left for charging" type: "string" acronym: "charging time" doorFrontLeft: description: "door fl" type: "boolean" acronym: "door fl" labels: ["opened","closed"] doorFrontRight: description: "door fr" type: "boolean" acronym: "door fr" labels: ["opened","closed"] doorBackLeft: description: "door bl" type: "boolean" acronym: "door bl" labels: ["opened","closed"] doorBackRight: description: "door br" type: "boolean" acronym: "door br" labels: ["opened","closed"] hood: description: "hood" type: "boolean" acronym: "hood" labels: ["opened","closed"] trunk: description: "trunk" type: "boolean" acronym: "trunk" labels: ["opened","closed"] battery: description: "The battery level" type: "number" unit: '%' acronym: "battery" remainingRange: description: "Remaining range basing on current battery resp. fuel level" type: "number" acronym: "remaining" unit: "km" twelveVoltBattery: description: "The 12 volt battery level" type: "number" unit: '%' acronym: "12V" odo: description: "The car odo value" type: "number" unit: 'km' acronym: "odo" speed: description: "Speed of the car" type: "number" acronym: "speed" unit: "km/h" maximum: description: "Maximum range basing on current battery resp. fuel level" type: "string" acronym: "maximum" lat: description: "The cars latitude" type: "number" acronym: "lat" lon: description: "The cars longitude" type: "number" acronym: "lon" status: description: "The connection status" type: "string" acronym: "status" getTemplateName: -> "bluelink" statusCodes = init: 0 ready: 1 getStatus: 2 getStatusError: 3 commandSend: 4 commandSuccess: 5 commanderror: 6 constructor: (config, lastState, @plugin, client, @framework) -> @config = config @id = @config.id @name = @config.name @client = @plugin.client @pollTimePassive = @config.pollTimePassive ? 3600000 # 1 hour @pollTimeActive = @config.pollTimeActive ? 600000 # 10 minutes @currentPollTime = @pollTimeActive @_defrost = @config.defrost ? false @_windscreenHeating = @config.windscreenHeating ? false @_temperature = @config.temperature ? 20 @_optionsVariable = @config.optionsVariable ? "" @_engine = laststate?.engine?.value ? false @_speed = laststate?.speed?.value ? 0 @_airco = laststate?.airco?.value ? "off" @_door = laststate?.door?.value ? false @_charging = laststate?.charging?.value ? false @_chargingTime = laststate?.chargingTime?.value ? 0 @_battery = laststate?.battery?.value ? 0 @_twelveVoltBattery = laststate?.twelveVoltBattery?.value ? 0 @_pluggedIn = laststate?.pluggedIn?.value ? "unplugged" @_odo = laststate?.odo?.value ? 0 @_maximum = laststate?.maximum?.value ? 0 @_remainingRange = laststate?.remainingRange?.value ? 0 @_doorFrontLeft = laststate?.doorFrontLeft?.value ? 0 @_doorFrontRight = laststate?.doorFrontRight?.value ? 0 @_doorBackLeft = laststate?.doorBackLeft?.value ? 0 @_doorBackRight = laststate?.doorBackRight?.value ? 0 @_hood = laststate?.hood?.value ? 0 @_trunk = laststate?.trunk?.value ? 0 @_lat = laststate?.lat?.value ? 0 @_lon = laststate?.lon?.value ? 0 @_status = statusCodes.init @setStatus(statusCodes.init) retries = 0 maxRetries = 20 @vehicle = null ### @config.xAttributeOptions = [] unless @config.xAttributeOptions? for i, _attr of @attributes do (_attr) => if _attr.type is 'number' _hideSparklineNumber = name: i displaySparkline: false @config.xAttributeOptions.push _hideSparklineNumber ### @plugin.on 'clientReady', @clientListener = () => unless @statusTimer? env.logger.debug "Plugin ClientReady, requesting vehicle" @vehicle = @plugin.client.getVehicle(@config.vin) env.logger.debug "From plugin start - starting status update cyle" @setStatus(statusCodes.ready) @getCarStatus(true) # actual car status on start else env.logger.debug "Error: plugin start but @statusTimer alredy running!" @framework.variableManager.waitForInit() .then ()=> if @plugin.clientReady and not @statusTimer? env.logger.debug "ClientReady ready, Device starting, requesting vehicle" @vehicle = @plugin.client.getVehicle(@config.vin) env.logger.debug "From device start - starting status update cyle" @setStatus(statusCodes.ready) @getCarStatus(true) # actual car status on start @getCarStatus = (_refresh=false) => if @plugin.clientReady clearTimeout(@statusTimer) if @statusTimer? env.logger.debug "requesting status, refresh: " + _refresh @setStatus(statusCodes.getStatus) @vehicle.status({refresh:_refresh}) .then (status)=> @handleStatus(status) return @vehicle.location() .then (location)=> env.logger.debug "location " + JSON.stringify(location,null,2) @handleLocation(location) return @vehicle.odometer() .then (odometer) => env.logger.debug "odo " + JSON.stringify(odometer,null,2) @handleOdo(odometer) @setStatus(statusCodes.ready) .catch (e) => @setStatus(statusCodes.getStatusError) env.logger.debug "getStatus error: " + JSON.stringify(e.body,null,2) @statusTimer = setTimeout(@getCarStatus, @currentPollTime) env.logger.debug "Next poll in " + @currentPollTime + " ms" else env.logger.debug "(re)requesting status in 5 seconds, client not ready" retries += 1 if retries < maxRetries @statusTimer = setTimeout(@getCarStatus, 5000) else env.logger.debug "Max number of retries(#{maxRetries}) reached, Client not ready, stop trying" super() handleLocation: (location) => @setLocation(location.latitude, location.longitude) @setSpeed(location.speed.value) handleOdo: (odo) => @setOdo(odo.value) handleStatus: (status) => env.logger.debug "Status: " + JSON.stringify(status,null,2) if status.doorLock? @setDoor(status.doorLock) if status.doorOpen? @setDoors(status) if status.engine? @setEngine(status.engine) if status.airCtrlOn? if status.airCtrlOn @setAirco("start") else @setAirco("off") if status.battery?.batSoc? @setTwelveVoltBattery(status.battery.batSoc) if status.evStatus? @setEvStatus(status.evStatus) #update polltime to active if engine is on, charging or airco is on active = (Boolean status.engine) or (Boolean status.evStatus.batteryCharge) or (Boolean status.airCtrlOn) env.logger.debug "Car status PollTimeActive is " + active @setPollTime(active) parseOptions: (_options) -> climateOptions = defrost: @_defrost windscreenHeating: @_windscreenHeating temperature: @_temperature unit: 'C' if _options? try parameters = _options.split(",") for parameter in parameters tokens = parameter.split(":") _key = tokens[0].trim() _val = tokens[1].trim() env.logger.debug "_key: " + _key + ", _val: " + _val switch _key when "defrost" climateOptions.defrost = (if _val is "false" then false else true) when "windscreenHeating" climateOptions.windscreenHeating = (if _val is "false" then false else true) when "temperature" # check if number unless Number.isNaN(Number _val) climateOptions.temperature = Number _val catch err env.logger.debug "Handled error in parseOptions " + err return climateOptions changeActionTo: (action) => _action = action options = null if action is "startPlus" if @_optionsVariable isnt "" _optionsString = @framework.variableManager.getVariableValue(@_optionsVariable) if _optionsString? options = _optionsString else return Promise.reject("optionsVariable '#{@_optionsVariable}' does not exsist") else return Promise.reject("No optionsVariable defined") return @execute(_action, options) execute: (command, options) => return new Promise((resolve,reject) => unless @vehicle? then return reject("No active vehicle") @setStatus(statusCodes.commandSend, command) switch command when "start" env.logger.debug "Start with options: " + JSON.stringify(@parseOptions(options),null,2) @vehicle.start(@parseOptions(options)) .then (resp)=> env.logger.debug "Started: " + JSON.stringify(resp,null,2) #@setEngine(true) @setAirco("start") @setPollTime(true) # set to active poll @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error start car: " + JSON.stringify(err,null,2) reject() when "startPlus" env.logger.debug "StartPlus with options: " + JSON.stringify(@parseOptions(options),null,2) @vehicle.start(@parseOptions(options)) .then (resp)=> env.logger.debug "Started: " + JSON.stringify(resp,null,2) #@setEngine(true) @setAirco("startPlus") @setPollTime(true) # set to active poll @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error start car: " + JSON.stringify(err,null,2) reject() when "stop" @vehicle.stop() .then (resp)=> #@setEngine(false) @setAirco("off") env.logger.debug "Stopped: " + JSON.stringify(resp,null,2) @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error stop car: " + JSON.stringify(err,null,2) reject() when "lock" @vehicle.lock() .then (resp)=> @setDoor(true) env.logger.debug "Locked: " + JSON.stringify(resp,null,2) @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error lock car: " + JSON.stringify(err,null,2) reject() when "unlock" @vehicle.unlock() .then (resp)=> @setDoor(false) @setPollTime(true) # set to active poll env.logger.debug "Unlocked: " + JSON.stringify(resp,null,2) @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error unlock car: " + JSON.stringify(err,null,2) reject() when "startCharge" @vehicle.startCharge() .then (resp)=> @setCharge(true) @setPollTime(true) # set to active poll env.logger.debug "startCharge: " + JSON.stringify(resp,null,2) @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error startCharge car: " + JSON.stringify(err,null,2) reject() when "stopCharge" @vehicle.stopCharge() .then (resp)=> @setCharge(false) env.logger.debug "stopCharge: " + JSON.stringify(resp,null,2) @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error stopCharge car: " + JSON.stringify(err,null,2) reject() when "refresh" clearTimeout(@statusTimer) if @statusTimer? @getCarStatus(true) env.logger.debug "refreshing status" @setStatus(statusCodes.commandSuccess, command) resolve() else @setStatus(statusCodes.commandError, command) env.logger.debug "Unknown command " + command reject() resolve() ) getEngine: -> Promise.resolve(@_engine) getAirco: -> Promise.resolve(@_airco) getDoor: -> Promise.resolve(@_door) getDoorFrontLeft: -> Promise.resolve(@_doorFrontLeft) getDoorFrontRight: -> Promise.resolve(@_doorFrontRight) getDoorBackLeft: -> Promise.resolve(@_doorBackLeft) getDoorBackRight: -> Promise.resolve(@_doorBackRight) getHood: -> Promise.resolve(@_hood) getTrunk: -> Promise.resolve(@_trunk) getCharging: -> Promise.resolve(@_charging) getBattery: -> Promise.resolve(@_battery) getTwelveVoltBattery: -> Promise.resolve(@_twelveVoltBattery) getPluggedIn: -> Promise.resolve(@_pluggedIn) getOdo: -> Promise.resolve(@_odo) getSpeed: -> Promise.resolve(@_speed) getMaximum: -> Promise.resolve(@_maximum) getRemainingRange: -> Promise.resolve(@_remainingRange) getLat: -> Promise.resolve(@_lat) getLon: -> Promise.resolve(@_lon) getStatus: -> Promise.resolve(@_status) getChargingTime: -> Promise.resolve(@_chargingTime) setStatus: (status, command)=> switch status when statusCodes.init _status = "initializing" when statusCodes.ready _status = "ready" when statusCodes.getStatus _status = "get status" when statusCodes.getStatusError _status = "get status error" when statusCodes.commandSend _status = "execute " + command when statusCodes.commandSuccess _status = command + " executed" setTimeout(=> @setStatus(statusCodes.ready) ,3000) when statusCodes.commandError _status = command + " error" else _status = "unknown status " + status @_status = _status @emit 'status', _status setPollTime: (active) => # true is active, false is passive if (active and @currentPollTime == @pollTimeActive) or (!active and @currentPollTime == @pollTimePassive) then return #env.logger.debug("Test for active " + active + ", @currentPollTime:"+@currentPollTime+", @pollTimePassive:"+@pollTimePassive+", == "+ (@currentPollTimer == @pollTimePassive)) if (active) and (@currentPollTime == @pollTimePassive) clearTimeout(@statusTimer) if @statusTimer? @currentPollTime = @pollTimeActive env.logger.debug "Switching to active poll, with polltime of " + @pollTimeActive + " ms" @statusTimer = setTimeout(@getCarStatus, @pollTimeActive) return if not active and @currentPollTime == @pollTimeActive clearTimeout(@statusTimer) if @statusTimer? @currentPollTime = @pollTimePassive env.logger.debug "Switching to passive poll, with polltime of " + @pollTimePassive + " ms" @statusTimer = setTimeout(@getCarStatus, @pollTimePassive) setMaximum: (_range) => @_maximum = _range @emit 'maximum', _range setRemainingRange: (_range) => @_remainingRange = Number _range @emit 'remainingRange', Number _range setEngine: (_status) => @_engine = Boolean _status @emit 'engine', Boolean _status setSpeed: (_status) => @_speed = Number _status @emit 'speed', Number _status setDoor: (_status) => @_door = Boolean _status @emit 'door', Boolean _status setTwelveVoltBattery: (_status) => @_twelveVoltBattery = Number _status # Math.round (_status / 2.55 ) @emit 'twelveVoltBattery', Number _status # Math.round (_status / 2.55 ) setChargingTime: (_status) => @_chargingTime = _status @emit 'chargingTime', _status setDoors: (_status) => if _status.doorOpen? @_doorFrontLeft = Boolean _status.doorOpen.frontLeft @emit 'doorFrontLeft', Boolean _status.doorOpen.frontLeft @_doorFrontRight = Boolean _status.doorOpen.doorFrontRight @emit 'doorFrontRight', Boolean _status.doorOpen.doorFrontRight @_doorBackLeft = Boolean _status.doorOpen.backLeft @emit 'doorBackLeft', Boolean _status.doorOpen.backLeft @_doorBackRight = Boolean _status.doorOpen.backRight @emit 'doorBackRight', Boolean _status.doorOpen.backRight if _status.trunkOpen? @_trunk = Boolean _status.trunkOpen @emit 'trunk', Boolean _status.trunkOpen if _status.hoodOpen? @_hood = Boolean _status.hoodOpen @emit 'hood', Boolean _status.hoodOpen setEvStatus: (evStatus) => @_battery = Number evStatus.batteryStatus @emit 'battery', Number evStatus.batteryStatus switch evStatus.batteryPlugin when 0 @_pluggedIn = "unplugged" _chargingTime = "no value" when 1 @_pluggedIn = "DC" _chargingTime = evStatus.remainTime2.etc1.value + "min (DC)" when 2 #@_pluggedIn = "ACportable" #_chargingTime = evStatus.remainTime2.etc2.value + "min (ACport)" @_pluggedIn = "AC" _chargingTime = evStatus.remainTime2.etc3.value + "min (AC)" when 3 @_pluggedIn = "AC" _chargingTime = evStatus.remainTime2.etc3.value + "min (AC)" else @_pluggedIn = "unknown" _chargingTime = "" @setChargingTime(_chargingTime) @emit 'pluggedIn', @_pluggedIn @_charging = Boolean evStatus.batteryCharge @emit 'charging', Boolean evStatus.batteryCharge #if @_charging # @_pluggedIn = true # @emit 'pluggedIn', (evStatus.batteryPlugin > 0) # DC maximum if evStatus.reservChargeInfos.targetSOClist?[0]?.dte?.rangeByFuel?.totalAvailableRange?.value? _maximumDC = Number evStatus.reservChargeInfos.targetSOClist[0].dte.rangeByFuel.totalAvailableRange.value _maximumDCperc = Number evStatus.reservChargeInfos.targetSOClist[0].targetSOClevel if evStatus.reservChargeInfos.targetSOClist?[1]?.dte?.rangeByFuel?.totalAvailableRange?.value? _maximumAC = Number evStatus.reservChargeInfos.targetSOClist[1].dte.rangeByFuel.totalAvailableRange.value _maximumACperc = Number evStatus.reservChargeInfos.targetSOClist[1].targetSOClevel if _maximumDC? and _maximumAC? _maximum = _maximumDC + "km (DC@" + _maximumDCperc + "%) " + _maximumAC + "km (AC@" + _maximumACperc + "%)" @setMaximum(_maximum) else @setMaximum("no value") if evStatus.drvDistance?[0]?.rangeByFuel?.totalAvailableRange?.value? _remainingRange = Number evStatus.drvDistance[0].rangeByFuel.totalAvailableRange.value if _remainingRange > 0 @setRemainingRange(_remainingRange) setAirco: (_status) => @_airco = _status @emit 'airco', _status setOdo: (_status) => @_odo = Number _status @emit 'odo', Number _status setLocation: (_lat, _lon) => @_lat = _lat @_lon = _lon @emit 'lat', _lat @emit 'lon', _lon setCharge: (charging) => @_charging = Boolean charging @emit 'charging', Boolean charging #if charging # @_pluggedIn = true # if charging, must be pluggedIn # @emit 'pluggedIn', @_pluggedIn destroy:() => clearTimeout(@statusTimer) if @statusTimer? @plugin.removeListener('clientReady', @clientListener) super() class BluelinkActionProvider extends env.actions.ActionProvider constructor: (@framework) -> parseAction: (input, context) => bluelinkDevice = null @options = null supportedCarClasses = ["KiaDevice","HyundaiDevice"] bluelinkDevices = _(@framework.deviceManager.devices).values().filter( (device) => device.config.class in supportedCarClasses ).value() setCommand = (command) => @command = command optionsString = (m,tokens) => unless tokens? context?.addError("No variable") return @options = tokens setCommand("start") m = M(input, context) .match('bluelink ') .matchDevice(bluelinkDevices, (m, d) -> # Already had a match with another device? if bluelinkDevice? and bluelinkDevices.id isnt d.id context?.addError(""""#{input.trim()}" is ambiguous.""") return bluelinkDevice = d ) .or([ ((m) => return m.match(' startDefault', (m) => setCommand('start') match = m.getFullMatch() ) ), ((m) => return m.match(' start ') .matchVariable(optionsString) ), ((m) => return m.match(' startPlus', (m) => setCommand('startPlus') match = m.getFullMatch() ) ), ((m) => return m.match(' stop', (m) => setCommand('stop') match = m.getFullMatch() ) ), ((m) => return m.match(' lock', (m) => setCommand('lock') match = m.getFullMatch() ) ), ((m) => return m.match(' unlock', (m) => setCommand('unlock') match = m.getFullMatch() ) ), ((m) => return m.match(' startCharge', (m) => setCommand('startCharge') match = m.getFullMatch() ) ), ((m) => return m.match(' stopCharge', (m) => setCommand('stopCharge') match = m.getFullMatch() ) ), ((m) => return m.match(' refresh', (m) => setCommand('refresh') match = m.getFullMatch() ) ) ]) match = m.getFullMatch() if match? #m.hadMatch() env.logger.debug "Rule matched: '", match, "' and passed to Action handler" return { token: match nextInput: input.substring(match.length) actionHandler: new BluelinkActionHandler(@framework, bluelinkDevice, @command, @options) } else return null class BluelinkActionHandler extends env.actions.ActionHandler constructor: (@framework, @bluelinkDevice, @command, @options) -> executeAction: (simulate) => if simulate return __("would have cleaned \"%s\"", "") else if @options? _var = @options.slice(1) if @options.indexOf('$') >= 0 _options = @framework.variableManager.getVariableValue(_var) unless _options? return __("\"%s\" Rule not executed, #{_var} is not a valid variable", "") else _options = null @bluelinkDevice.execute(@command, _options) .then(()=> return __("\"%s\" Rule executed", @command) ).catch((err)=> return __("\"%s\" Rule not executed", "") ) class KiaDevice extends BluelinkDevice class HyundaiDevice extends BluelinkDevice bluelinkPlugin = new BluelinkPlugin return bluelinkPlugin
true
module.exports = (env) -> Promise = env.require 'bluebird' assert = env.require 'cassert' M = env.matcher _ = require('lodash') fs = require('fs') path = require('path') #Bluelinky = require('kuvork') Bluelinky = require('bluelinky') class BluelinkPlugin extends env.plugins.Plugin init: (app, @framework, @config) => pluginConfigDef = require './pimatic-bluelink-config-schema' @deviceConfigDef = require("./device-config-schema") @username = @config.username # "PI:EMAIL:<EMAIL>END_PI"; @password = @config.password #"PI:PASSWORD:<PASSWORD>END_PI"; @region = @config.region ? 'EU' @pin = @config.pin options = username: @username password: PI:PASSWORD:<PASSWORD>END_PI region: @region pin: @pin @brand = @config.brand ? "kia" if @brand is "hyundai" #Bluelinky = require('bluelinky') @_discoveryClass = "HyundaiDevice" options["brand"] = "hyundai" else #Bluelinky = require('kuvork') @_discoveryClass = "KiaDevice" options["brand"] = "kia" options["vin"] = "KNA" #for detecting the Kia or Hyandai api, brand deduction: VIN numbers of KIA are KNA/KNC/KNE @client = null @clientReady = false @framework.on 'after init', ()=> mobileFrontend = @framework.pluginManager.getPlugin 'mobile-frontend' if mobileFrontend? mobileFrontend.registerAssetFile 'js', "pimatic-bluelink/app/bluelink.coffee" mobileFrontend.registerAssetFile 'html', "pimatic-bluelink/app/bluelink.jade" mobileFrontend.registerAssetFile 'css', "pimatic-bluelink/app/bluelink.css" @client = new Bluelinky(options) @client.on 'ready',() => env.logger.debug "Plugin emit clientReady" @clientReady = true @emit "clientReady" @client.on 'error',(err) => env.logger.debug "Bluelink login error: " + JSON.stringify(err,null,2) @clientReady = false @framework.deviceManager.registerDeviceClass('KiaDevice', { configDef: @deviceConfigDef.KiaDevice, createCallback: (config, lastState) => new KiaDevice(config, lastState, @, @client, @framework) }) @framework.deviceManager.registerDeviceClass('HyundaiDevice', { configDef: @deviceConfigDef.HyundaiDevice, createCallback: (config, lastState) => new HyundaiDevice(config, lastState, @, @client, @framework) }) @framework.ruleManager.addActionProvider(new BluelinkActionProvider(@framework)) @framework.deviceManager.on('discover', (eventData) => @framework.deviceManager.discoverMessage 'pimatic-bluelink', 'Searching for new devices' if @clientReady @client.getVehicles() .then((vehicles) => for vehicle in vehicles carConfig = vehicle.vehicleConfig env.logger.info "CarConfig: " + JSON.stringify(carConfig,null,2) _did = (carConfig.nickname).split(' ').join("_") if _.find(@framework.deviceManager.devicesConfig,(d) => d.id is _did) env.logger.info "Device '" + _did + "' already in config" else config = id: _did #(carConfig.nickname).split(' ').join("_").toLowerCase() name: carConfig.nickname class: @_discoveryClass vin: carConfig.vin vehicleId: carConfig.id type: carConfig.name @framework.deviceManager.discoveredDevice( "Bluelink", config.name, config) ).catch((e) => env.logger.error 'Error in getVehicles: ' + e.message ) ) class BluelinkDevice extends env.devices.Device template: "bluelink" actions: changeActionTo: description: "Sets the action" params: action: type: "string" attributes: engine: description: "Status of engine" type: "boolean" acronym: "engine" labels: ["on","off"] hidden: false airco: description: "Status of airco" type: "string" acronym: "airco" enum: ["start","startPlus","off"] hidden: true door: description: "Status of doorlock" type: "boolean" acronym: "door" labels: ["locked","unlocked"] hidden: true charging: description: "If vehicle is charging" type: "boolean" acronym: "charging" labels: ["on","off"] hidden: true pluggedIn: description: "If vehicle is pluggedIn" type: "string" acronym: "batteryPlugin" chargingTime: description: "Time left for charging" type: "string" acronym: "charging time" doorFrontLeft: description: "door fl" type: "boolean" acronym: "door fl" labels: ["opened","closed"] doorFrontRight: description: "door fr" type: "boolean" acronym: "door fr" labels: ["opened","closed"] doorBackLeft: description: "door bl" type: "boolean" acronym: "door bl" labels: ["opened","closed"] doorBackRight: description: "door br" type: "boolean" acronym: "door br" labels: ["opened","closed"] hood: description: "hood" type: "boolean" acronym: "hood" labels: ["opened","closed"] trunk: description: "trunk" type: "boolean" acronym: "trunk" labels: ["opened","closed"] battery: description: "The battery level" type: "number" unit: '%' acronym: "battery" remainingRange: description: "Remaining range basing on current battery resp. fuel level" type: "number" acronym: "remaining" unit: "km" twelveVoltBattery: description: "The 12 volt battery level" type: "number" unit: '%' acronym: "12V" odo: description: "The car odo value" type: "number" unit: 'km' acronym: "odo" speed: description: "Speed of the car" type: "number" acronym: "speed" unit: "km/h" maximum: description: "Maximum range basing on current battery resp. fuel level" type: "string" acronym: "maximum" lat: description: "The cars latitude" type: "number" acronym: "lat" lon: description: "The cars longitude" type: "number" acronym: "lon" status: description: "The connection status" type: "string" acronym: "status" getTemplateName: -> "bluelink" statusCodes = init: 0 ready: 1 getStatus: 2 getStatusError: 3 commandSend: 4 commandSuccess: 5 commanderror: 6 constructor: (config, lastState, @plugin, client, @framework) -> @config = config @id = @config.id @name = @config.name @client = @plugin.client @pollTimePassive = @config.pollTimePassive ? 3600000 # 1 hour @pollTimeActive = @config.pollTimeActive ? 600000 # 10 minutes @currentPollTime = @pollTimeActive @_defrost = @config.defrost ? false @_windscreenHeating = @config.windscreenHeating ? false @_temperature = @config.temperature ? 20 @_optionsVariable = @config.optionsVariable ? "" @_engine = laststate?.engine?.value ? false @_speed = laststate?.speed?.value ? 0 @_airco = laststate?.airco?.value ? "off" @_door = laststate?.door?.value ? false @_charging = laststate?.charging?.value ? false @_chargingTime = laststate?.chargingTime?.value ? 0 @_battery = laststate?.battery?.value ? 0 @_twelveVoltBattery = laststate?.twelveVoltBattery?.value ? 0 @_pluggedIn = laststate?.pluggedIn?.value ? "unplugged" @_odo = laststate?.odo?.value ? 0 @_maximum = laststate?.maximum?.value ? 0 @_remainingRange = laststate?.remainingRange?.value ? 0 @_doorFrontLeft = laststate?.doorFrontLeft?.value ? 0 @_doorFrontRight = laststate?.doorFrontRight?.value ? 0 @_doorBackLeft = laststate?.doorBackLeft?.value ? 0 @_doorBackRight = laststate?.doorBackRight?.value ? 0 @_hood = laststate?.hood?.value ? 0 @_trunk = laststate?.trunk?.value ? 0 @_lat = laststate?.lat?.value ? 0 @_lon = laststate?.lon?.value ? 0 @_status = statusCodes.init @setStatus(statusCodes.init) retries = 0 maxRetries = 20 @vehicle = null ### @config.xAttributeOptions = [] unless @config.xAttributeOptions? for i, _attr of @attributes do (_attr) => if _attr.type is 'number' _hideSparklineNumber = name: i displaySparkline: false @config.xAttributeOptions.push _hideSparklineNumber ### @plugin.on 'clientReady', @clientListener = () => unless @statusTimer? env.logger.debug "Plugin ClientReady, requesting vehicle" @vehicle = @plugin.client.getVehicle(@config.vin) env.logger.debug "From plugin start - starting status update cyle" @setStatus(statusCodes.ready) @getCarStatus(true) # actual car status on start else env.logger.debug "Error: plugin start but @statusTimer alredy running!" @framework.variableManager.waitForInit() .then ()=> if @plugin.clientReady and not @statusTimer? env.logger.debug "ClientReady ready, Device starting, requesting vehicle" @vehicle = @plugin.client.getVehicle(@config.vin) env.logger.debug "From device start - starting status update cyle" @setStatus(statusCodes.ready) @getCarStatus(true) # actual car status on start @getCarStatus = (_refresh=false) => if @plugin.clientReady clearTimeout(@statusTimer) if @statusTimer? env.logger.debug "requesting status, refresh: " + _refresh @setStatus(statusCodes.getStatus) @vehicle.status({refresh:_refresh}) .then (status)=> @handleStatus(status) return @vehicle.location() .then (location)=> env.logger.debug "location " + JSON.stringify(location,null,2) @handleLocation(location) return @vehicle.odometer() .then (odometer) => env.logger.debug "odo " + JSON.stringify(odometer,null,2) @handleOdo(odometer) @setStatus(statusCodes.ready) .catch (e) => @setStatus(statusCodes.getStatusError) env.logger.debug "getStatus error: " + JSON.stringify(e.body,null,2) @statusTimer = setTimeout(@getCarStatus, @currentPollTime) env.logger.debug "Next poll in " + @currentPollTime + " ms" else env.logger.debug "(re)requesting status in 5 seconds, client not ready" retries += 1 if retries < maxRetries @statusTimer = setTimeout(@getCarStatus, 5000) else env.logger.debug "Max number of retries(#{maxRetries}) reached, Client not ready, stop trying" super() handleLocation: (location) => @setLocation(location.latitude, location.longitude) @setSpeed(location.speed.value) handleOdo: (odo) => @setOdo(odo.value) handleStatus: (status) => env.logger.debug "Status: " + JSON.stringify(status,null,2) if status.doorLock? @setDoor(status.doorLock) if status.doorOpen? @setDoors(status) if status.engine? @setEngine(status.engine) if status.airCtrlOn? if status.airCtrlOn @setAirco("start") else @setAirco("off") if status.battery?.batSoc? @setTwelveVoltBattery(status.battery.batSoc) if status.evStatus? @setEvStatus(status.evStatus) #update polltime to active if engine is on, charging or airco is on active = (Boolean status.engine) or (Boolean status.evStatus.batteryCharge) or (Boolean status.airCtrlOn) env.logger.debug "Car status PollTimeActive is " + active @setPollTime(active) parseOptions: (_options) -> climateOptions = defrost: @_defrost windscreenHeating: @_windscreenHeating temperature: @_temperature unit: 'C' if _options? try parameters = _options.split(",") for parameter in parameters tokens = parameter.split(":") _key = tokens[0].trim() _val = tokens[1].trim() env.logger.debug "_key: " + _key + ", _val: " + _val switch _key when "defrost" climateOptions.defrost = (if _val is "false" then false else true) when "windscreenHeating" climateOptions.windscreenHeating = (if _val is "false" then false else true) when "temperature" # check if number unless Number.isNaN(Number _val) climateOptions.temperature = Number _val catch err env.logger.debug "Handled error in parseOptions " + err return climateOptions changeActionTo: (action) => _action = action options = null if action is "startPlus" if @_optionsVariable isnt "" _optionsString = @framework.variableManager.getVariableValue(@_optionsVariable) if _optionsString? options = _optionsString else return Promise.reject("optionsVariable '#{@_optionsVariable}' does not exsist") else return Promise.reject("No optionsVariable defined") return @execute(_action, options) execute: (command, options) => return new Promise((resolve,reject) => unless @vehicle? then return reject("No active vehicle") @setStatus(statusCodes.commandSend, command) switch command when "start" env.logger.debug "Start with options: " + JSON.stringify(@parseOptions(options),null,2) @vehicle.start(@parseOptions(options)) .then (resp)=> env.logger.debug "Started: " + JSON.stringify(resp,null,2) #@setEngine(true) @setAirco("start") @setPollTime(true) # set to active poll @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error start car: " + JSON.stringify(err,null,2) reject() when "startPlus" env.logger.debug "StartPlus with options: " + JSON.stringify(@parseOptions(options),null,2) @vehicle.start(@parseOptions(options)) .then (resp)=> env.logger.debug "Started: " + JSON.stringify(resp,null,2) #@setEngine(true) @setAirco("startPlus") @setPollTime(true) # set to active poll @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error start car: " + JSON.stringify(err,null,2) reject() when "stop" @vehicle.stop() .then (resp)=> #@setEngine(false) @setAirco("off") env.logger.debug "Stopped: " + JSON.stringify(resp,null,2) @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error stop car: " + JSON.stringify(err,null,2) reject() when "lock" @vehicle.lock() .then (resp)=> @setDoor(true) env.logger.debug "Locked: " + JSON.stringify(resp,null,2) @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error lock car: " + JSON.stringify(err,null,2) reject() when "unlock" @vehicle.unlock() .then (resp)=> @setDoor(false) @setPollTime(true) # set to active poll env.logger.debug "Unlocked: " + JSON.stringify(resp,null,2) @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error unlock car: " + JSON.stringify(err,null,2) reject() when "startCharge" @vehicle.startCharge() .then (resp)=> @setCharge(true) @setPollTime(true) # set to active poll env.logger.debug "startCharge: " + JSON.stringify(resp,null,2) @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error startCharge car: " + JSON.stringify(err,null,2) reject() when "stopCharge" @vehicle.stopCharge() .then (resp)=> @setCharge(false) env.logger.debug "stopCharge: " + JSON.stringify(resp,null,2) @setStatus(statusCodes.commandSuccess, command) resolve() .catch (err) => @setStatus(statusCodes.commandError, command) env.logger.debug "Error stopCharge car: " + JSON.stringify(err,null,2) reject() when "refresh" clearTimeout(@statusTimer) if @statusTimer? @getCarStatus(true) env.logger.debug "refreshing status" @setStatus(statusCodes.commandSuccess, command) resolve() else @setStatus(statusCodes.commandError, command) env.logger.debug "Unknown command " + command reject() resolve() ) getEngine: -> Promise.resolve(@_engine) getAirco: -> Promise.resolve(@_airco) getDoor: -> Promise.resolve(@_door) getDoorFrontLeft: -> Promise.resolve(@_doorFrontLeft) getDoorFrontRight: -> Promise.resolve(@_doorFrontRight) getDoorBackLeft: -> Promise.resolve(@_doorBackLeft) getDoorBackRight: -> Promise.resolve(@_doorBackRight) getHood: -> Promise.resolve(@_hood) getTrunk: -> Promise.resolve(@_trunk) getCharging: -> Promise.resolve(@_charging) getBattery: -> Promise.resolve(@_battery) getTwelveVoltBattery: -> Promise.resolve(@_twelveVoltBattery) getPluggedIn: -> Promise.resolve(@_pluggedIn) getOdo: -> Promise.resolve(@_odo) getSpeed: -> Promise.resolve(@_speed) getMaximum: -> Promise.resolve(@_maximum) getRemainingRange: -> Promise.resolve(@_remainingRange) getLat: -> Promise.resolve(@_lat) getLon: -> Promise.resolve(@_lon) getStatus: -> Promise.resolve(@_status) getChargingTime: -> Promise.resolve(@_chargingTime) setStatus: (status, command)=> switch status when statusCodes.init _status = "initializing" when statusCodes.ready _status = "ready" when statusCodes.getStatus _status = "get status" when statusCodes.getStatusError _status = "get status error" when statusCodes.commandSend _status = "execute " + command when statusCodes.commandSuccess _status = command + " executed" setTimeout(=> @setStatus(statusCodes.ready) ,3000) when statusCodes.commandError _status = command + " error" else _status = "unknown status " + status @_status = _status @emit 'status', _status setPollTime: (active) => # true is active, false is passive if (active and @currentPollTime == @pollTimeActive) or (!active and @currentPollTime == @pollTimePassive) then return #env.logger.debug("Test for active " + active + ", @currentPollTime:"+@currentPollTime+", @pollTimePassive:"+@pollTimePassive+", == "+ (@currentPollTimer == @pollTimePassive)) if (active) and (@currentPollTime == @pollTimePassive) clearTimeout(@statusTimer) if @statusTimer? @currentPollTime = @pollTimeActive env.logger.debug "Switching to active poll, with polltime of " + @pollTimeActive + " ms" @statusTimer = setTimeout(@getCarStatus, @pollTimeActive) return if not active and @currentPollTime == @pollTimeActive clearTimeout(@statusTimer) if @statusTimer? @currentPollTime = @pollTimePassive env.logger.debug "Switching to passive poll, with polltime of " + @pollTimePassive + " ms" @statusTimer = setTimeout(@getCarStatus, @pollTimePassive) setMaximum: (_range) => @_maximum = _range @emit 'maximum', _range setRemainingRange: (_range) => @_remainingRange = Number _range @emit 'remainingRange', Number _range setEngine: (_status) => @_engine = Boolean _status @emit 'engine', Boolean _status setSpeed: (_status) => @_speed = Number _status @emit 'speed', Number _status setDoor: (_status) => @_door = Boolean _status @emit 'door', Boolean _status setTwelveVoltBattery: (_status) => @_twelveVoltBattery = Number _status # Math.round (_status / 2.55 ) @emit 'twelveVoltBattery', Number _status # Math.round (_status / 2.55 ) setChargingTime: (_status) => @_chargingTime = _status @emit 'chargingTime', _status setDoors: (_status) => if _status.doorOpen? @_doorFrontLeft = Boolean _status.doorOpen.frontLeft @emit 'doorFrontLeft', Boolean _status.doorOpen.frontLeft @_doorFrontRight = Boolean _status.doorOpen.doorFrontRight @emit 'doorFrontRight', Boolean _status.doorOpen.doorFrontRight @_doorBackLeft = Boolean _status.doorOpen.backLeft @emit 'doorBackLeft', Boolean _status.doorOpen.backLeft @_doorBackRight = Boolean _status.doorOpen.backRight @emit 'doorBackRight', Boolean _status.doorOpen.backRight if _status.trunkOpen? @_trunk = Boolean _status.trunkOpen @emit 'trunk', Boolean _status.trunkOpen if _status.hoodOpen? @_hood = Boolean _status.hoodOpen @emit 'hood', Boolean _status.hoodOpen setEvStatus: (evStatus) => @_battery = Number evStatus.batteryStatus @emit 'battery', Number evStatus.batteryStatus switch evStatus.batteryPlugin when 0 @_pluggedIn = "unplugged" _chargingTime = "no value" when 1 @_pluggedIn = "DC" _chargingTime = evStatus.remainTime2.etc1.value + "min (DC)" when 2 #@_pluggedIn = "ACportable" #_chargingTime = evStatus.remainTime2.etc2.value + "min (ACport)" @_pluggedIn = "AC" _chargingTime = evStatus.remainTime2.etc3.value + "min (AC)" when 3 @_pluggedIn = "AC" _chargingTime = evStatus.remainTime2.etc3.value + "min (AC)" else @_pluggedIn = "unknown" _chargingTime = "" @setChargingTime(_chargingTime) @emit 'pluggedIn', @_pluggedIn @_charging = Boolean evStatus.batteryCharge @emit 'charging', Boolean evStatus.batteryCharge #if @_charging # @_pluggedIn = true # @emit 'pluggedIn', (evStatus.batteryPlugin > 0) # DC maximum if evStatus.reservChargeInfos.targetSOClist?[0]?.dte?.rangeByFuel?.totalAvailableRange?.value? _maximumDC = Number evStatus.reservChargeInfos.targetSOClist[0].dte.rangeByFuel.totalAvailableRange.value _maximumDCperc = Number evStatus.reservChargeInfos.targetSOClist[0].targetSOClevel if evStatus.reservChargeInfos.targetSOClist?[1]?.dte?.rangeByFuel?.totalAvailableRange?.value? _maximumAC = Number evStatus.reservChargeInfos.targetSOClist[1].dte.rangeByFuel.totalAvailableRange.value _maximumACperc = Number evStatus.reservChargeInfos.targetSOClist[1].targetSOClevel if _maximumDC? and _maximumAC? _maximum = _maximumDC + "km (DC@" + _maximumDCperc + "%) " + _maximumAC + "km (AC@" + _maximumACperc + "%)" @setMaximum(_maximum) else @setMaximum("no value") if evStatus.drvDistance?[0]?.rangeByFuel?.totalAvailableRange?.value? _remainingRange = Number evStatus.drvDistance[0].rangeByFuel.totalAvailableRange.value if _remainingRange > 0 @setRemainingRange(_remainingRange) setAirco: (_status) => @_airco = _status @emit 'airco', _status setOdo: (_status) => @_odo = Number _status @emit 'odo', Number _status setLocation: (_lat, _lon) => @_lat = _lat @_lon = _lon @emit 'lat', _lat @emit 'lon', _lon setCharge: (charging) => @_charging = Boolean charging @emit 'charging', Boolean charging #if charging # @_pluggedIn = true # if charging, must be pluggedIn # @emit 'pluggedIn', @_pluggedIn destroy:() => clearTimeout(@statusTimer) if @statusTimer? @plugin.removeListener('clientReady', @clientListener) super() class BluelinkActionProvider extends env.actions.ActionProvider constructor: (@framework) -> parseAction: (input, context) => bluelinkDevice = null @options = null supportedCarClasses = ["KiaDevice","HyundaiDevice"] bluelinkDevices = _(@framework.deviceManager.devices).values().filter( (device) => device.config.class in supportedCarClasses ).value() setCommand = (command) => @command = command optionsString = (m,tokens) => unless tokens? context?.addError("No variable") return @options = tokens setCommand("start") m = M(input, context) .match('bluelink ') .matchDevice(bluelinkDevices, (m, d) -> # Already had a match with another device? if bluelinkDevice? and bluelinkDevices.id isnt d.id context?.addError(""""#{input.trim()}" is ambiguous.""") return bluelinkDevice = d ) .or([ ((m) => return m.match(' startDefault', (m) => setCommand('start') match = m.getFullMatch() ) ), ((m) => return m.match(' start ') .matchVariable(optionsString) ), ((m) => return m.match(' startPlus', (m) => setCommand('startPlus') match = m.getFullMatch() ) ), ((m) => return m.match(' stop', (m) => setCommand('stop') match = m.getFullMatch() ) ), ((m) => return m.match(' lock', (m) => setCommand('lock') match = m.getFullMatch() ) ), ((m) => return m.match(' unlock', (m) => setCommand('unlock') match = m.getFullMatch() ) ), ((m) => return m.match(' startCharge', (m) => setCommand('startCharge') match = m.getFullMatch() ) ), ((m) => return m.match(' stopCharge', (m) => setCommand('stopCharge') match = m.getFullMatch() ) ), ((m) => return m.match(' refresh', (m) => setCommand('refresh') match = m.getFullMatch() ) ) ]) match = m.getFullMatch() if match? #m.hadMatch() env.logger.debug "Rule matched: '", match, "' and passed to Action handler" return { token: match nextInput: input.substring(match.length) actionHandler: new BluelinkActionHandler(@framework, bluelinkDevice, @command, @options) } else return null class BluelinkActionHandler extends env.actions.ActionHandler constructor: (@framework, @bluelinkDevice, @command, @options) -> executeAction: (simulate) => if simulate return __("would have cleaned \"%s\"", "") else if @options? _var = @options.slice(1) if @options.indexOf('$') >= 0 _options = @framework.variableManager.getVariableValue(_var) unless _options? return __("\"%s\" Rule not executed, #{_var} is not a valid variable", "") else _options = null @bluelinkDevice.execute(@command, _options) .then(()=> return __("\"%s\" Rule executed", @command) ).catch((err)=> return __("\"%s\" Rule not executed", "") ) class KiaDevice extends BluelinkDevice class HyundaiDevice extends BluelinkDevice bluelinkPlugin = new BluelinkPlugin return bluelinkPlugin
[ { "context": "lte lat, lng, und zoom von der aktuellen Karte\n #@map_handler.getMap().getCenter(); // --> .lat(), .lng()\n #@map_handl", "end": 1972, "score": 0.953532874584198, "start": 1952, "tag": "EMAIL", "value": "#@map_handler.getMap" }, { "context": "er.getMap().getCenter(); // --> .lat(), .lng()\n #@map_handler.getMap().getZoom(); //--> e.g. 9\n # rufe eine URL mit la", "end": 2034, "score": 0.9842625856399536, "start": 2014, "tag": "EMAIL", "value": "#@map_handler.getMap" } ]
app/assets/javascripts/points.js.coffee
Bjoernsen/geopoints
0
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ window.markers = [] jQuery -> map_handler = false opt = false points = [] init_map = (map_id, get_opt, get_points)-> opt = get_opt points = get_points map_handler = Gmaps.build("Google") map_handler.buildMap provider: disableDefaultUI: false internal: id: map_id , -> if navigator.geolocation navigator.geolocation.getCurrentPosition add_points else # position = {coords: {latitude: 52.36132, longitude: 9.628606}} add_points(opt.default_map_position) return map_handler.getMap().setZoom(12) window.map_handler = map_handler add_points = (position)-> # a) ersten den point auf den die map zentiert wird center_on_marker = map_handler.addMarker( lat: position.coords.latitude lng: position.coords.longitude picture: { url: "https://addons.cdn.mozilla.net/img/uploads/addon_icons/13/13028-64.png" width: 36 height: 36 } infowindow: if position.default then 'Default start position' else 'Your current position' ) map_handler.map.centerOn center_on_marker # b) dann 'alle' points, die sich im Umkreis des point aus a) befinden --> ajax get_points_near_center() # c) wenn @points schon points beinhaltet, dann diese auch rendern if points.length > 0 map_handler.addMarkers(points) window.map_handler = map_handler update_points = ()-> get_points_near_center() # entweder lösche alle bestehenden Marker aus der Karte und fülle diese neu auf # oder schecke, ob new_marker schon vorhanden ist window.map_handler = map_handler get_points_near_center = ()-> # erhalte lat, lng, und zoom von der aktuellen Karte #@map_handler.getMap().getCenter(); // --> .lat(), .lng() #@map_handler.getMap().getZoom(); //--> e.g. 9 # rufe eine URL mit lat, lng und zoom auf und erhalte json map_data = map_handler.getMap() params = { zoom: map_data.getZoom() latitude: map_data.getCenter().lat() longitude: map_data.getCenter().lng() } $.get('/points.json', params, (res, status, xhr)-> map_handler.addMarkers(res) , 'json') # wie bauen ich einen event linstener ein, wenn gezoomt, oder verschoben wird? #init_map() window.init_map = init_map window.map_handler = map_handler
47998
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ window.markers = [] jQuery -> map_handler = false opt = false points = [] init_map = (map_id, get_opt, get_points)-> opt = get_opt points = get_points map_handler = Gmaps.build("Google") map_handler.buildMap provider: disableDefaultUI: false internal: id: map_id , -> if navigator.geolocation navigator.geolocation.getCurrentPosition add_points else # position = {coords: {latitude: 52.36132, longitude: 9.628606}} add_points(opt.default_map_position) return map_handler.getMap().setZoom(12) window.map_handler = map_handler add_points = (position)-> # a) ersten den point auf den die map zentiert wird center_on_marker = map_handler.addMarker( lat: position.coords.latitude lng: position.coords.longitude picture: { url: "https://addons.cdn.mozilla.net/img/uploads/addon_icons/13/13028-64.png" width: 36 height: 36 } infowindow: if position.default then 'Default start position' else 'Your current position' ) map_handler.map.centerOn center_on_marker # b) dann 'alle' points, die sich im Umkreis des point aus a) befinden --> ajax get_points_near_center() # c) wenn @points schon points beinhaltet, dann diese auch rendern if points.length > 0 map_handler.addMarkers(points) window.map_handler = map_handler update_points = ()-> get_points_near_center() # entweder lösche alle bestehenden Marker aus der Karte und fülle diese neu auf # oder schecke, ob new_marker schon vorhanden ist window.map_handler = map_handler get_points_near_center = ()-> # erhalte lat, lng, und zoom von der aktuellen Karte <EMAIL>().getCenter(); // --> .lat(), .lng() <EMAIL>().getZoom(); //--> e.g. 9 # rufe eine URL mit lat, lng und zoom auf und erhalte json map_data = map_handler.getMap() params = { zoom: map_data.getZoom() latitude: map_data.getCenter().lat() longitude: map_data.getCenter().lng() } $.get('/points.json', params, (res, status, xhr)-> map_handler.addMarkers(res) , 'json') # wie bauen ich einen event linstener ein, wenn gezoomt, oder verschoben wird? #init_map() window.init_map = init_map window.map_handler = map_handler
true
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ window.markers = [] jQuery -> map_handler = false opt = false points = [] init_map = (map_id, get_opt, get_points)-> opt = get_opt points = get_points map_handler = Gmaps.build("Google") map_handler.buildMap provider: disableDefaultUI: false internal: id: map_id , -> if navigator.geolocation navigator.geolocation.getCurrentPosition add_points else # position = {coords: {latitude: 52.36132, longitude: 9.628606}} add_points(opt.default_map_position) return map_handler.getMap().setZoom(12) window.map_handler = map_handler add_points = (position)-> # a) ersten den point auf den die map zentiert wird center_on_marker = map_handler.addMarker( lat: position.coords.latitude lng: position.coords.longitude picture: { url: "https://addons.cdn.mozilla.net/img/uploads/addon_icons/13/13028-64.png" width: 36 height: 36 } infowindow: if position.default then 'Default start position' else 'Your current position' ) map_handler.map.centerOn center_on_marker # b) dann 'alle' points, die sich im Umkreis des point aus a) befinden --> ajax get_points_near_center() # c) wenn @points schon points beinhaltet, dann diese auch rendern if points.length > 0 map_handler.addMarkers(points) window.map_handler = map_handler update_points = ()-> get_points_near_center() # entweder lösche alle bestehenden Marker aus der Karte und fülle diese neu auf # oder schecke, ob new_marker schon vorhanden ist window.map_handler = map_handler get_points_near_center = ()-> # erhalte lat, lng, und zoom von der aktuellen Karte PI:EMAIL:<EMAIL>END_PI().getCenter(); // --> .lat(), .lng() PI:EMAIL:<EMAIL>END_PI().getZoom(); //--> e.g. 9 # rufe eine URL mit lat, lng und zoom auf und erhalte json map_data = map_handler.getMap() params = { zoom: map_data.getZoom() latitude: map_data.getCenter().lat() longitude: map_data.getCenter().lng() } $.get('/points.json', params, (res, status, xhr)-> map_handler.addMarkers(res) , 'json') # wie bauen ich einen event linstener ein, wenn gezoomt, oder verschoben wird? #init_map() window.init_map = init_map window.map_handler = map_handler
[ { "context": "# Hey-Coffee!\n# TJ Eastmond - tj.eastmond@gmail.com\n# Copyright 2013\n\nfs = re", "end": 27, "score": 0.9998341798782349, "start": 16, "tag": "NAME", "value": "TJ Eastmond" }, { "context": "# Hey-Coffee!\n# TJ Eastmond - tj.eastmond@gmail.com\n# Copyright 2013\n\nfs = require 'fs'\npath = requir", "end": 51, "score": 0.9999275207519531, "start": 30, "tag": "EMAIL", "value": "tj.eastmond@gmail.com" }, { "context": "\"siteTitle\": \"Hey-coffee Blog\",'\n\t\t\t' \"author\": \"Dunkin\",'\n\t\t\t' \"description\": \"My awesome blog, JACK!\",", "end": 10771, "score": 0.9916019439697266, "start": 10765, "tag": "NAME", "value": "Dunkin" }, { "context": ",'\n\t\t\t' \"postsOnHomePage\": 20,'\n\t\t\t' \"server\": \"user@yoursite.com:/path/to/your/blog\",'\n\t\t\t' \"port\": 22,'\n\t\t\t' \"p", "end": 10925, "score": 0.8554518818855286, "start": 10908, "tag": "EMAIL", "value": "user@yoursite.com" } ]
hey.coffee
tjeastmond/hey-coffee
1
# Hey-Coffee! # TJ Eastmond - tj.eastmond@gmail.com # Copyright 2013 fs = require 'fs' path = require 'path' crypto = require 'crypto' http = require 'http' url = require 'url' {spawn, exec} = require 'child_process' async = require 'async' _ = require 'underscore' marked = require 'marked' handlebars = require 'handlebars' mkdirp = require 'mkdirp' rss = require 'rss' colors = require 'colors' require 'date-utils' Hey = module.exports = class constructor: (dir) -> @cwd = dir or process.cwd() + "/" @template = null @webServer = null @layouts = {} @layoutsDir = "#{@cwd}layouts/" @pagesDir = "#{@cwd}pages/" @siteDir = "#{@cwd}site/" @publicDir = "#{@cwd}public/" @versionsDir = "#{@cwd}versions/" @cacheFile = "#{@cwd}hey-cache.json" @configFile = "#{@cwd}hey-config.json" @defaultTemplateFile = "template.html" @rssFile = "#{@cwd}site/rss.xml" init: -> if fs.existsSync(@configFile) and fs.existsSync(@postPath()) throw new Error 'A blog is already setup here' mkdirp @siteDir mkdirp @pagesDir mkdirp @publicDir mkdirp @layoutsDir mkdirp @postPath() defaults = @defaults() fs.writeFileSync @cacheFile, '', 'utf8' fs.writeFileSync "#{@layoutsDir}#{@defaultTemplateFile}", defaults.tpl, 'utf8' fs.writeFileSync @configFile, defaults.config, 'utf8' fs.writeFileSync @postPath('first-post.md'), defaults.post, 'utf8' yes server: (silent, callback) => do @loadConfig @webServer = http.createServer (req, res) => uri = url.parse(req.url).pathname filename = path.join "#{@cwd}site", uri fs.exists filename, (exists) -> if exists is false res.writeHead 404, 'Content-Type': 'text/plain' res.write '404 Not Found\n' res.end() return false filename += '/index.html' if fs.statSync(filename).isDirectory() fs.readFile filename, 'binary', (error, file) -> if error? res.writeHead 500, 'Content-Type': 'text/plain' res.write error + "\n" res.end() return false res.writeHead 200 res.write file, 'binary' res.end() @webServer.listen 3000 if silent isnt true console.log "Server running at http://localhost:3000".green console.log "CTRL+C to stop it".white callback?() stopServer: (callback) -> @webServer.close callback or -> publish: -> do @loadConfig @rsync @siteDir, @config.server rsync: (from, to, callback) -> port = "ssh -p #{@config.port or 22}" child = spawn "rsync", ['-vurz', '--delete', '-e', port, from, to] child.stdout.on 'data', (out) -> console.log out.toString() child.stderr.on 'data', (err) -> console.error err.toString() child.on 'exit', callback if callback loadConfig: -> @config = readJSON @configFile @defaultTemplateFile = @config.defaultTemplate if @config.defaultTemplate yes loadCache: -> @cache = readJSON(@cacheFile) or [] yes loadTemplate: (name) -> return false unless name return true if @layouts[name] @layouts[name] = @readAndCompileTemplateFile @templatePath(name) yes readAndCompileTemplateFile: (filename) -> handlebars.compile fs.readFileSync(filename).toString() postPath: (filename) -> "#{@cwd}posts/#{filename or ''}" templatePath: (filename) -> "#{@layoutsDir}#{filename}" templateExists: (name) -> fs.existsSync @templatePath name postFiles: -> readDir @postPath() pageFiles: -> readDir @pagesDir layoutFiles: -> readDir @layoutFiles setType: (post) -> return post unless post.type post["is#{ucWord post.type}"] = true post postInfo: (filename, isPage) -> file = if isPage is true then "#{@pagesDir}#{filename}" else @postPath filename content = fs.readFileSync(file).toString() hash = md5 content content = content.split '\n\n' top = content.shift().split '\n' body = content.join '\n\n' post = name: filename title: top[0] slug: path.basename filename, '.md' hash: hash body: @markup body summary: @summary body tags: [] for setting in top[2..] parts = setting.split ': ' key = parts[0].toLowerCase() post[key] = if key is 'tags' parts[1].split(',').map((s) -> s.trim()) else parts[1] if post.published date = new Date post.published post.prettyDate = date.toFormat @config.prettyDateFormat post.ymd = date.toFormat @config.ymdFormat post.permalink = @permalink post.published, post.slug post.archiveDir = post.published[0..6] post.canonical = @config.site + post.permalink if isPage is true post.slug += '/' post.type = 'page' @setType post summary: (body) -> summary = _.find(marked.lexer(body), (token) -> token.type is 'paragraph')?.text summary = summary[0..summary.length - 2] marked.parser marked.lexer _.template("#{summary}...")(summary) update: (callback) -> do @loadConfig @cache = [] @cache.push @postInfo(post) for post in @postFiles() @cache = _.sortBy @cache, (post) -> (if post.published then new Date(post.published) else 0) * -1 fs.writeFile @cacheFile, JSON.stringify(@cache), (error) -> throw new Error error if error? callback?() yes ymd: (pubDate) -> date = new Date pubDate date.toFormat 'YYYY/MM/DD' postDir: (pubDate, slug) -> "#{@cwd}site/#{@ymd(pubDate)}/#{slug}" permalink: (pubDate, slug) -> "/#{@ymd(pubDate)}/#{slug}/" build: (callback) -> @update => exec "rsync -vur --delete #{@publicDir} #{@siteDir}", (err, stdout, stderr) => throw err if err writePostFile = (post, next) => return next null unless _.has post, 'published' dir = @postDir post.published, post.slug mkdirp.sync dir unless fs.existsSync dir fs.writeFile "#{dir}/index.html", @render([post]), 'utf8' do next process = [ @buildArchive @buildArchiveList @buildTags @buildIndex @buildPages ] async.each @cache, writePostFile, (error) => async.parallel process, (error) -> callback?() buildIndex: (callback) => index = @config.postsOnHomePage - 1 posts = @cache.filter((p) -> 'published' in _.keys p)[0..index] blogIndex = siteIndex = "#{@cwd}site/" staticIndex = "index.md" if @config.homepage is 'page' and fs.existsSync "#{@pagesDir}#{staticIndex}" data = @postInfo staticIndex, yes blogIndex = "#{@siteDir}#{@config.blogDirectory}/" mkdirp.sync blogIndex fs.writeFileSync siteIndex, @render([data]), 'utf8' fs.writeFile "#{blogIndex}index.html", @render(posts), 'utf8' @buildRss posts callback? null buildRss: (posts, callback) => feed = new rss title: @config.siteTitle description: @config.description feed_url: "#{@config.site}/rss.xml" site_url: @config.site author: @config.author for post in posts body = if _.has post, 'image' then "<p><img src='#{post.image}' /></p>#{post.body}" else post.body feed.item title: post.title description: body url: "#{@config.site}#{post.permalink}" date: post.published fs.writeFile @rssFile, feed.xml(), 'utf8' callback? null # @todo: add parallel async buildPages: (callback) => for page in @pageFiles() continue if page is 'index.md' data = @postInfo page, yes pageDir = "#{@siteDir}#{data.slug}" mkdirp.sync pageDir fs.writeFileSync "#{pageDir}index.html", @render([data]), 'utf8' callback? null # @todo: add parallel async buildTags: (callback) => @tags = {} for post in @cache when post.tags.length > 0 for tag in post.tags when _.has post, 'published' @tags[tag] = [] unless _.has @tags, tag @tags[tag].push post for tag, posts of @tags tagDir = "#{@siteDir}tags/#{tag}/" mkdirp.sync tagDir unless fs.existsSync tagDir fs.writeFile "#{tagDir}index.html", @render(posts), 'utf8' callback? null buildArchive: (callback) => @archive = {} for post in @cache when 'published' in _.keys post @archive[post.archiveDir] = [] unless _.has @archive, post.archiveDir @archive[post.archiveDir].push post for archiveDir, posts of @archive archiveDir = "#{@siteDir}#{archiveDir.replace('-', '/')}/" mkdirp.sync archiveDir unless fs.existsSync archiveDir fs.writeFile "#{archiveDir}index.html", @render(posts), 'utf8' callback?(null) buildArchiveList: (callback) => @archiveIndex = [] posts = @cache.filter (post) -> _.has post, 'published' for archive in _.uniq _.pluck posts, 'archiveDir' @archiveIndex.push name: new Date(archive.replace /-/g, ' ').toFormat 'MMMM YYYY' link: "/#{archive.replace('-', '/')}/" _.sortBy @archiveIndex, (result) -> result.link.replace '/', '' callback?() backup: (name, callback) -> if typeof name is 'function' callback = name name = null name = if typeof name is 'string' then " - #{name}" else '' @build => fstream = require 'fstream' tar = require 'tar' zlib = require 'zlib' date = new Date w = fstream.Writer path: "#{@versionsDir}#{date.toFormat 'YYYYMMDD'}#{name}.tar.gz" mkdirp.sync @versionsDir unless fs.existsSync @versionsDir fstream.Reader({ path: @siteDir, type: 'Directory' }) .on('end', callback or ->) .pipe(tar.Pack()) .pipe(zlib.Gzip()) .pipe w watch: (callback) => console.log 'Watching for changes and starting the server'.yellow do @server rebuild = (msg) => @build -> console.log "#{new Date().toFormat('HH24:MI:SS')} #{msg}".grey handlePostsAndPages = (ev, filename) => rebuild 'Recompiling posts and pages' if filename and path.extname(filename) is '.md' # watch templates, posts and pages for changes fs.watch @postPath(), handlePostsAndPages fs.watch @pagesDir, handlePostsAndPages fs.watch @layoutsDir, (ev, filename) => if filename and path.extname(filename) is '.html' @layouts = {} rebuild 'Recompiling template' rebuild 'Built the site' markup: (content) -> content = marked(content).trim() content.replace /\n/g, "" render: (posts) -> throw "Posts must be an array" unless _.isArray posts options = _.omit @config, 'server' options.pageTitle = @pageTitle if posts.length is 1 then posts[0].title else '' options.archiveList = @archiveIndex if posts.length is 1 and posts[0].type isnt 'page' options.isArticle = true options.opengraph = true options.og_title = posts[0].title options.og_canonical = posts[0].canonical options.isIndex = true if posts.length > 1 template = if posts.length is 1 and posts[0]['layout'] and @templateExists(posts[0]['layout']) posts[0]['layout'] else @defaultTemplateFile @loadTemplate template html = @layouts[template] _.extend options, posts: posts html.replace /\n|\r|\t/g, '' pageTitle: (postTitle) -> if postTitle then "#{postTitle} | #{@config.siteTitle}" else @config.siteTitle defaults: -> config = [ '{' ' "siteTitle": "Hey-coffee Blog",' ' "author": "Dunkin",' ' "description": "My awesome blog, JACK!",' ' "site": "http://yoursite.com",' ' "postsOnHomePage": 20,' ' "server": "user@yoursite.com:/path/to/your/blog",' ' "port": 22,' ' "prettyDateFormat": "DDDD, DD MMMM YYYY",' ' "ymdFormat": "YYYY-MM-DD",' ' "defaultTemplate": "template.html",' ' "homepage": "blog",' ' "blogDirectory": "blog"' '}' ].join '\n' post = [ 'First Post' '==========' 'Published: 2013-04-22 12:00:00' 'Type: text' 'Tags: tests' '' 'This is a test post.' '' 'This is a second paragraph.' ].join '\n' tpl = [ '<!DOCTYPE html>' '<html>' ' <head>' ' <title>{{siteTitle}}</title>' ' </head>' ' <body>' ' {{#each posts}}' ' <article>' ' <h2><a href="{{permalink}}">{{title}}</a></h2>' ' {{{body}}}' ' </article>' ' {{/each}}' ' </body>' '</html>' ].join '\n' { config, post, tpl } # utility functions readJSON = (file) -> throw new Error "JSON file doesn't exist: #{file}" unless fs.existsSync file fileContents = fs.readFileSync(file).toString() if fileContents then JSON.parse(fileContents) else [] readDir = (dir) -> throw "Directory doesn't exist: #{dir}" unless fs.existsSync dir files = fs.readdirSync(dir).filter (f) -> f.charAt(0) isnt '.' files or [] md5 = (string) -> crypto.createHash('md5').update(string).digest('hex') ucWord = (string) -> string.charAt(0).toUpperCase() + string.slice 1
80890
# Hey-Coffee! # <NAME> - <EMAIL> # Copyright 2013 fs = require 'fs' path = require 'path' crypto = require 'crypto' http = require 'http' url = require 'url' {spawn, exec} = require 'child_process' async = require 'async' _ = require 'underscore' marked = require 'marked' handlebars = require 'handlebars' mkdirp = require 'mkdirp' rss = require 'rss' colors = require 'colors' require 'date-utils' Hey = module.exports = class constructor: (dir) -> @cwd = dir or process.cwd() + "/" @template = null @webServer = null @layouts = {} @layoutsDir = "#{@cwd}layouts/" @pagesDir = "#{@cwd}pages/" @siteDir = "#{@cwd}site/" @publicDir = "#{@cwd}public/" @versionsDir = "#{@cwd}versions/" @cacheFile = "#{@cwd}hey-cache.json" @configFile = "#{@cwd}hey-config.json" @defaultTemplateFile = "template.html" @rssFile = "#{@cwd}site/rss.xml" init: -> if fs.existsSync(@configFile) and fs.existsSync(@postPath()) throw new Error 'A blog is already setup here' mkdirp @siteDir mkdirp @pagesDir mkdirp @publicDir mkdirp @layoutsDir mkdirp @postPath() defaults = @defaults() fs.writeFileSync @cacheFile, '', 'utf8' fs.writeFileSync "#{@layoutsDir}#{@defaultTemplateFile}", defaults.tpl, 'utf8' fs.writeFileSync @configFile, defaults.config, 'utf8' fs.writeFileSync @postPath('first-post.md'), defaults.post, 'utf8' yes server: (silent, callback) => do @loadConfig @webServer = http.createServer (req, res) => uri = url.parse(req.url).pathname filename = path.join "#{@cwd}site", uri fs.exists filename, (exists) -> if exists is false res.writeHead 404, 'Content-Type': 'text/plain' res.write '404 Not Found\n' res.end() return false filename += '/index.html' if fs.statSync(filename).isDirectory() fs.readFile filename, 'binary', (error, file) -> if error? res.writeHead 500, 'Content-Type': 'text/plain' res.write error + "\n" res.end() return false res.writeHead 200 res.write file, 'binary' res.end() @webServer.listen 3000 if silent isnt true console.log "Server running at http://localhost:3000".green console.log "CTRL+C to stop it".white callback?() stopServer: (callback) -> @webServer.close callback or -> publish: -> do @loadConfig @rsync @siteDir, @config.server rsync: (from, to, callback) -> port = "ssh -p #{@config.port or 22}" child = spawn "rsync", ['-vurz', '--delete', '-e', port, from, to] child.stdout.on 'data', (out) -> console.log out.toString() child.stderr.on 'data', (err) -> console.error err.toString() child.on 'exit', callback if callback loadConfig: -> @config = readJSON @configFile @defaultTemplateFile = @config.defaultTemplate if @config.defaultTemplate yes loadCache: -> @cache = readJSON(@cacheFile) or [] yes loadTemplate: (name) -> return false unless name return true if @layouts[name] @layouts[name] = @readAndCompileTemplateFile @templatePath(name) yes readAndCompileTemplateFile: (filename) -> handlebars.compile fs.readFileSync(filename).toString() postPath: (filename) -> "#{@cwd}posts/#{filename or ''}" templatePath: (filename) -> "#{@layoutsDir}#{filename}" templateExists: (name) -> fs.existsSync @templatePath name postFiles: -> readDir @postPath() pageFiles: -> readDir @pagesDir layoutFiles: -> readDir @layoutFiles setType: (post) -> return post unless post.type post["is#{ucWord post.type}"] = true post postInfo: (filename, isPage) -> file = if isPage is true then "#{@pagesDir}#{filename}" else @postPath filename content = fs.readFileSync(file).toString() hash = md5 content content = content.split '\n\n' top = content.shift().split '\n' body = content.join '\n\n' post = name: filename title: top[0] slug: path.basename filename, '.md' hash: hash body: @markup body summary: @summary body tags: [] for setting in top[2..] parts = setting.split ': ' key = parts[0].toLowerCase() post[key] = if key is 'tags' parts[1].split(',').map((s) -> s.trim()) else parts[1] if post.published date = new Date post.published post.prettyDate = date.toFormat @config.prettyDateFormat post.ymd = date.toFormat @config.ymdFormat post.permalink = @permalink post.published, post.slug post.archiveDir = post.published[0..6] post.canonical = @config.site + post.permalink if isPage is true post.slug += '/' post.type = 'page' @setType post summary: (body) -> summary = _.find(marked.lexer(body), (token) -> token.type is 'paragraph')?.text summary = summary[0..summary.length - 2] marked.parser marked.lexer _.template("#{summary}...")(summary) update: (callback) -> do @loadConfig @cache = [] @cache.push @postInfo(post) for post in @postFiles() @cache = _.sortBy @cache, (post) -> (if post.published then new Date(post.published) else 0) * -1 fs.writeFile @cacheFile, JSON.stringify(@cache), (error) -> throw new Error error if error? callback?() yes ymd: (pubDate) -> date = new Date pubDate date.toFormat 'YYYY/MM/DD' postDir: (pubDate, slug) -> "#{@cwd}site/#{@ymd(pubDate)}/#{slug}" permalink: (pubDate, slug) -> "/#{@ymd(pubDate)}/#{slug}/" build: (callback) -> @update => exec "rsync -vur --delete #{@publicDir} #{@siteDir}", (err, stdout, stderr) => throw err if err writePostFile = (post, next) => return next null unless _.has post, 'published' dir = @postDir post.published, post.slug mkdirp.sync dir unless fs.existsSync dir fs.writeFile "#{dir}/index.html", @render([post]), 'utf8' do next process = [ @buildArchive @buildArchiveList @buildTags @buildIndex @buildPages ] async.each @cache, writePostFile, (error) => async.parallel process, (error) -> callback?() buildIndex: (callback) => index = @config.postsOnHomePage - 1 posts = @cache.filter((p) -> 'published' in _.keys p)[0..index] blogIndex = siteIndex = "#{@cwd}site/" staticIndex = "index.md" if @config.homepage is 'page' and fs.existsSync "#{@pagesDir}#{staticIndex}" data = @postInfo staticIndex, yes blogIndex = "#{@siteDir}#{@config.blogDirectory}/" mkdirp.sync blogIndex fs.writeFileSync siteIndex, @render([data]), 'utf8' fs.writeFile "#{blogIndex}index.html", @render(posts), 'utf8' @buildRss posts callback? null buildRss: (posts, callback) => feed = new rss title: @config.siteTitle description: @config.description feed_url: "#{@config.site}/rss.xml" site_url: @config.site author: @config.author for post in posts body = if _.has post, 'image' then "<p><img src='#{post.image}' /></p>#{post.body}" else post.body feed.item title: post.title description: body url: "#{@config.site}#{post.permalink}" date: post.published fs.writeFile @rssFile, feed.xml(), 'utf8' callback? null # @todo: add parallel async buildPages: (callback) => for page in @pageFiles() continue if page is 'index.md' data = @postInfo page, yes pageDir = "#{@siteDir}#{data.slug}" mkdirp.sync pageDir fs.writeFileSync "#{pageDir}index.html", @render([data]), 'utf8' callback? null # @todo: add parallel async buildTags: (callback) => @tags = {} for post in @cache when post.tags.length > 0 for tag in post.tags when _.has post, 'published' @tags[tag] = [] unless _.has @tags, tag @tags[tag].push post for tag, posts of @tags tagDir = "#{@siteDir}tags/#{tag}/" mkdirp.sync tagDir unless fs.existsSync tagDir fs.writeFile "#{tagDir}index.html", @render(posts), 'utf8' callback? null buildArchive: (callback) => @archive = {} for post in @cache when 'published' in _.keys post @archive[post.archiveDir] = [] unless _.has @archive, post.archiveDir @archive[post.archiveDir].push post for archiveDir, posts of @archive archiveDir = "#{@siteDir}#{archiveDir.replace('-', '/')}/" mkdirp.sync archiveDir unless fs.existsSync archiveDir fs.writeFile "#{archiveDir}index.html", @render(posts), 'utf8' callback?(null) buildArchiveList: (callback) => @archiveIndex = [] posts = @cache.filter (post) -> _.has post, 'published' for archive in _.uniq _.pluck posts, 'archiveDir' @archiveIndex.push name: new Date(archive.replace /-/g, ' ').toFormat 'MMMM YYYY' link: "/#{archive.replace('-', '/')}/" _.sortBy @archiveIndex, (result) -> result.link.replace '/', '' callback?() backup: (name, callback) -> if typeof name is 'function' callback = name name = null name = if typeof name is 'string' then " - #{name}" else '' @build => fstream = require 'fstream' tar = require 'tar' zlib = require 'zlib' date = new Date w = fstream.Writer path: "#{@versionsDir}#{date.toFormat 'YYYYMMDD'}#{name}.tar.gz" mkdirp.sync @versionsDir unless fs.existsSync @versionsDir fstream.Reader({ path: @siteDir, type: 'Directory' }) .on('end', callback or ->) .pipe(tar.Pack()) .pipe(zlib.Gzip()) .pipe w watch: (callback) => console.log 'Watching for changes and starting the server'.yellow do @server rebuild = (msg) => @build -> console.log "#{new Date().toFormat('HH24:MI:SS')} #{msg}".grey handlePostsAndPages = (ev, filename) => rebuild 'Recompiling posts and pages' if filename and path.extname(filename) is '.md' # watch templates, posts and pages for changes fs.watch @postPath(), handlePostsAndPages fs.watch @pagesDir, handlePostsAndPages fs.watch @layoutsDir, (ev, filename) => if filename and path.extname(filename) is '.html' @layouts = {} rebuild 'Recompiling template' rebuild 'Built the site' markup: (content) -> content = marked(content).trim() content.replace /\n/g, "" render: (posts) -> throw "Posts must be an array" unless _.isArray posts options = _.omit @config, 'server' options.pageTitle = @pageTitle if posts.length is 1 then posts[0].title else '' options.archiveList = @archiveIndex if posts.length is 1 and posts[0].type isnt 'page' options.isArticle = true options.opengraph = true options.og_title = posts[0].title options.og_canonical = posts[0].canonical options.isIndex = true if posts.length > 1 template = if posts.length is 1 and posts[0]['layout'] and @templateExists(posts[0]['layout']) posts[0]['layout'] else @defaultTemplateFile @loadTemplate template html = @layouts[template] _.extend options, posts: posts html.replace /\n|\r|\t/g, '' pageTitle: (postTitle) -> if postTitle then "#{postTitle} | #{@config.siteTitle}" else @config.siteTitle defaults: -> config = [ '{' ' "siteTitle": "Hey-coffee Blog",' ' "author": "<NAME>",' ' "description": "My awesome blog, JACK!",' ' "site": "http://yoursite.com",' ' "postsOnHomePage": 20,' ' "server": "<EMAIL>:/path/to/your/blog",' ' "port": 22,' ' "prettyDateFormat": "DDDD, DD MMMM YYYY",' ' "ymdFormat": "YYYY-MM-DD",' ' "defaultTemplate": "template.html",' ' "homepage": "blog",' ' "blogDirectory": "blog"' '}' ].join '\n' post = [ 'First Post' '==========' 'Published: 2013-04-22 12:00:00' 'Type: text' 'Tags: tests' '' 'This is a test post.' '' 'This is a second paragraph.' ].join '\n' tpl = [ '<!DOCTYPE html>' '<html>' ' <head>' ' <title>{{siteTitle}}</title>' ' </head>' ' <body>' ' {{#each posts}}' ' <article>' ' <h2><a href="{{permalink}}">{{title}}</a></h2>' ' {{{body}}}' ' </article>' ' {{/each}}' ' </body>' '</html>' ].join '\n' { config, post, tpl } # utility functions readJSON = (file) -> throw new Error "JSON file doesn't exist: #{file}" unless fs.existsSync file fileContents = fs.readFileSync(file).toString() if fileContents then JSON.parse(fileContents) else [] readDir = (dir) -> throw "Directory doesn't exist: #{dir}" unless fs.existsSync dir files = fs.readdirSync(dir).filter (f) -> f.charAt(0) isnt '.' files or [] md5 = (string) -> crypto.createHash('md5').update(string).digest('hex') ucWord = (string) -> string.charAt(0).toUpperCase() + string.slice 1
true
# Hey-Coffee! # PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI # Copyright 2013 fs = require 'fs' path = require 'path' crypto = require 'crypto' http = require 'http' url = require 'url' {spawn, exec} = require 'child_process' async = require 'async' _ = require 'underscore' marked = require 'marked' handlebars = require 'handlebars' mkdirp = require 'mkdirp' rss = require 'rss' colors = require 'colors' require 'date-utils' Hey = module.exports = class constructor: (dir) -> @cwd = dir or process.cwd() + "/" @template = null @webServer = null @layouts = {} @layoutsDir = "#{@cwd}layouts/" @pagesDir = "#{@cwd}pages/" @siteDir = "#{@cwd}site/" @publicDir = "#{@cwd}public/" @versionsDir = "#{@cwd}versions/" @cacheFile = "#{@cwd}hey-cache.json" @configFile = "#{@cwd}hey-config.json" @defaultTemplateFile = "template.html" @rssFile = "#{@cwd}site/rss.xml" init: -> if fs.existsSync(@configFile) and fs.existsSync(@postPath()) throw new Error 'A blog is already setup here' mkdirp @siteDir mkdirp @pagesDir mkdirp @publicDir mkdirp @layoutsDir mkdirp @postPath() defaults = @defaults() fs.writeFileSync @cacheFile, '', 'utf8' fs.writeFileSync "#{@layoutsDir}#{@defaultTemplateFile}", defaults.tpl, 'utf8' fs.writeFileSync @configFile, defaults.config, 'utf8' fs.writeFileSync @postPath('first-post.md'), defaults.post, 'utf8' yes server: (silent, callback) => do @loadConfig @webServer = http.createServer (req, res) => uri = url.parse(req.url).pathname filename = path.join "#{@cwd}site", uri fs.exists filename, (exists) -> if exists is false res.writeHead 404, 'Content-Type': 'text/plain' res.write '404 Not Found\n' res.end() return false filename += '/index.html' if fs.statSync(filename).isDirectory() fs.readFile filename, 'binary', (error, file) -> if error? res.writeHead 500, 'Content-Type': 'text/plain' res.write error + "\n" res.end() return false res.writeHead 200 res.write file, 'binary' res.end() @webServer.listen 3000 if silent isnt true console.log "Server running at http://localhost:3000".green console.log "CTRL+C to stop it".white callback?() stopServer: (callback) -> @webServer.close callback or -> publish: -> do @loadConfig @rsync @siteDir, @config.server rsync: (from, to, callback) -> port = "ssh -p #{@config.port or 22}" child = spawn "rsync", ['-vurz', '--delete', '-e', port, from, to] child.stdout.on 'data', (out) -> console.log out.toString() child.stderr.on 'data', (err) -> console.error err.toString() child.on 'exit', callback if callback loadConfig: -> @config = readJSON @configFile @defaultTemplateFile = @config.defaultTemplate if @config.defaultTemplate yes loadCache: -> @cache = readJSON(@cacheFile) or [] yes loadTemplate: (name) -> return false unless name return true if @layouts[name] @layouts[name] = @readAndCompileTemplateFile @templatePath(name) yes readAndCompileTemplateFile: (filename) -> handlebars.compile fs.readFileSync(filename).toString() postPath: (filename) -> "#{@cwd}posts/#{filename or ''}" templatePath: (filename) -> "#{@layoutsDir}#{filename}" templateExists: (name) -> fs.existsSync @templatePath name postFiles: -> readDir @postPath() pageFiles: -> readDir @pagesDir layoutFiles: -> readDir @layoutFiles setType: (post) -> return post unless post.type post["is#{ucWord post.type}"] = true post postInfo: (filename, isPage) -> file = if isPage is true then "#{@pagesDir}#{filename}" else @postPath filename content = fs.readFileSync(file).toString() hash = md5 content content = content.split '\n\n' top = content.shift().split '\n' body = content.join '\n\n' post = name: filename title: top[0] slug: path.basename filename, '.md' hash: hash body: @markup body summary: @summary body tags: [] for setting in top[2..] parts = setting.split ': ' key = parts[0].toLowerCase() post[key] = if key is 'tags' parts[1].split(',').map((s) -> s.trim()) else parts[1] if post.published date = new Date post.published post.prettyDate = date.toFormat @config.prettyDateFormat post.ymd = date.toFormat @config.ymdFormat post.permalink = @permalink post.published, post.slug post.archiveDir = post.published[0..6] post.canonical = @config.site + post.permalink if isPage is true post.slug += '/' post.type = 'page' @setType post summary: (body) -> summary = _.find(marked.lexer(body), (token) -> token.type is 'paragraph')?.text summary = summary[0..summary.length - 2] marked.parser marked.lexer _.template("#{summary}...")(summary) update: (callback) -> do @loadConfig @cache = [] @cache.push @postInfo(post) for post in @postFiles() @cache = _.sortBy @cache, (post) -> (if post.published then new Date(post.published) else 0) * -1 fs.writeFile @cacheFile, JSON.stringify(@cache), (error) -> throw new Error error if error? callback?() yes ymd: (pubDate) -> date = new Date pubDate date.toFormat 'YYYY/MM/DD' postDir: (pubDate, slug) -> "#{@cwd}site/#{@ymd(pubDate)}/#{slug}" permalink: (pubDate, slug) -> "/#{@ymd(pubDate)}/#{slug}/" build: (callback) -> @update => exec "rsync -vur --delete #{@publicDir} #{@siteDir}", (err, stdout, stderr) => throw err if err writePostFile = (post, next) => return next null unless _.has post, 'published' dir = @postDir post.published, post.slug mkdirp.sync dir unless fs.existsSync dir fs.writeFile "#{dir}/index.html", @render([post]), 'utf8' do next process = [ @buildArchive @buildArchiveList @buildTags @buildIndex @buildPages ] async.each @cache, writePostFile, (error) => async.parallel process, (error) -> callback?() buildIndex: (callback) => index = @config.postsOnHomePage - 1 posts = @cache.filter((p) -> 'published' in _.keys p)[0..index] blogIndex = siteIndex = "#{@cwd}site/" staticIndex = "index.md" if @config.homepage is 'page' and fs.existsSync "#{@pagesDir}#{staticIndex}" data = @postInfo staticIndex, yes blogIndex = "#{@siteDir}#{@config.blogDirectory}/" mkdirp.sync blogIndex fs.writeFileSync siteIndex, @render([data]), 'utf8' fs.writeFile "#{blogIndex}index.html", @render(posts), 'utf8' @buildRss posts callback? null buildRss: (posts, callback) => feed = new rss title: @config.siteTitle description: @config.description feed_url: "#{@config.site}/rss.xml" site_url: @config.site author: @config.author for post in posts body = if _.has post, 'image' then "<p><img src='#{post.image}' /></p>#{post.body}" else post.body feed.item title: post.title description: body url: "#{@config.site}#{post.permalink}" date: post.published fs.writeFile @rssFile, feed.xml(), 'utf8' callback? null # @todo: add parallel async buildPages: (callback) => for page in @pageFiles() continue if page is 'index.md' data = @postInfo page, yes pageDir = "#{@siteDir}#{data.slug}" mkdirp.sync pageDir fs.writeFileSync "#{pageDir}index.html", @render([data]), 'utf8' callback? null # @todo: add parallel async buildTags: (callback) => @tags = {} for post in @cache when post.tags.length > 0 for tag in post.tags when _.has post, 'published' @tags[tag] = [] unless _.has @tags, tag @tags[tag].push post for tag, posts of @tags tagDir = "#{@siteDir}tags/#{tag}/" mkdirp.sync tagDir unless fs.existsSync tagDir fs.writeFile "#{tagDir}index.html", @render(posts), 'utf8' callback? null buildArchive: (callback) => @archive = {} for post in @cache when 'published' in _.keys post @archive[post.archiveDir] = [] unless _.has @archive, post.archiveDir @archive[post.archiveDir].push post for archiveDir, posts of @archive archiveDir = "#{@siteDir}#{archiveDir.replace('-', '/')}/" mkdirp.sync archiveDir unless fs.existsSync archiveDir fs.writeFile "#{archiveDir}index.html", @render(posts), 'utf8' callback?(null) buildArchiveList: (callback) => @archiveIndex = [] posts = @cache.filter (post) -> _.has post, 'published' for archive in _.uniq _.pluck posts, 'archiveDir' @archiveIndex.push name: new Date(archive.replace /-/g, ' ').toFormat 'MMMM YYYY' link: "/#{archive.replace('-', '/')}/" _.sortBy @archiveIndex, (result) -> result.link.replace '/', '' callback?() backup: (name, callback) -> if typeof name is 'function' callback = name name = null name = if typeof name is 'string' then " - #{name}" else '' @build => fstream = require 'fstream' tar = require 'tar' zlib = require 'zlib' date = new Date w = fstream.Writer path: "#{@versionsDir}#{date.toFormat 'YYYYMMDD'}#{name}.tar.gz" mkdirp.sync @versionsDir unless fs.existsSync @versionsDir fstream.Reader({ path: @siteDir, type: 'Directory' }) .on('end', callback or ->) .pipe(tar.Pack()) .pipe(zlib.Gzip()) .pipe w watch: (callback) => console.log 'Watching for changes and starting the server'.yellow do @server rebuild = (msg) => @build -> console.log "#{new Date().toFormat('HH24:MI:SS')} #{msg}".grey handlePostsAndPages = (ev, filename) => rebuild 'Recompiling posts and pages' if filename and path.extname(filename) is '.md' # watch templates, posts and pages for changes fs.watch @postPath(), handlePostsAndPages fs.watch @pagesDir, handlePostsAndPages fs.watch @layoutsDir, (ev, filename) => if filename and path.extname(filename) is '.html' @layouts = {} rebuild 'Recompiling template' rebuild 'Built the site' markup: (content) -> content = marked(content).trim() content.replace /\n/g, "" render: (posts) -> throw "Posts must be an array" unless _.isArray posts options = _.omit @config, 'server' options.pageTitle = @pageTitle if posts.length is 1 then posts[0].title else '' options.archiveList = @archiveIndex if posts.length is 1 and posts[0].type isnt 'page' options.isArticle = true options.opengraph = true options.og_title = posts[0].title options.og_canonical = posts[0].canonical options.isIndex = true if posts.length > 1 template = if posts.length is 1 and posts[0]['layout'] and @templateExists(posts[0]['layout']) posts[0]['layout'] else @defaultTemplateFile @loadTemplate template html = @layouts[template] _.extend options, posts: posts html.replace /\n|\r|\t/g, '' pageTitle: (postTitle) -> if postTitle then "#{postTitle} | #{@config.siteTitle}" else @config.siteTitle defaults: -> config = [ '{' ' "siteTitle": "Hey-coffee Blog",' ' "author": "PI:NAME:<NAME>END_PI",' ' "description": "My awesome blog, JACK!",' ' "site": "http://yoursite.com",' ' "postsOnHomePage": 20,' ' "server": "PI:EMAIL:<EMAIL>END_PI:/path/to/your/blog",' ' "port": 22,' ' "prettyDateFormat": "DDDD, DD MMMM YYYY",' ' "ymdFormat": "YYYY-MM-DD",' ' "defaultTemplate": "template.html",' ' "homepage": "blog",' ' "blogDirectory": "blog"' '}' ].join '\n' post = [ 'First Post' '==========' 'Published: 2013-04-22 12:00:00' 'Type: text' 'Tags: tests' '' 'This is a test post.' '' 'This is a second paragraph.' ].join '\n' tpl = [ '<!DOCTYPE html>' '<html>' ' <head>' ' <title>{{siteTitle}}</title>' ' </head>' ' <body>' ' {{#each posts}}' ' <article>' ' <h2><a href="{{permalink}}">{{title}}</a></h2>' ' {{{body}}}' ' </article>' ' {{/each}}' ' </body>' '</html>' ].join '\n' { config, post, tpl } # utility functions readJSON = (file) -> throw new Error "JSON file doesn't exist: #{file}" unless fs.existsSync file fileContents = fs.readFileSync(file).toString() if fileContents then JSON.parse(fileContents) else [] readDir = (dir) -> throw "Directory doesn't exist: #{dir}" unless fs.existsSync dir files = fs.readdirSync(dir).filter (f) -> f.charAt(0) isnt '.' files or [] md5 = (string) -> crypto.createHash('md5').update(string).digest('hex') ucWord = (string) -> string.charAt(0).toUpperCase() + string.slice 1
[ { "context": "_GIT_URL}:#{gitlab_name}.git\"\n githubRemote = \"git@github.com:#{GITHUB_ORG}/#{github_name}.git\"\n\n rm \"-rf\", ", "end": 392, "score": 0.9909152984619141, "start": 378, "tag": "EMAIL", "value": "git@github.com" }, { "context": "URL}:#{gitlab_name}.wiki.git\"\n githubRemote = \"git@github.com:#{GITHUB_ORG}/#{github_name}.wiki.git\"\n\n rm \"-", "end": 982, "score": 0.9810299873352051, "start": 968, "tag": "EMAIL", "value": "git@github.com" } ]
lib/git.coffee
leilerg/gitlab-github-migrate
62
require('dotenv').load() require 'shelljs/global' _ = require 'underscore' GitHub = require './github' Git = module.exports = migrateRepo: (options) -> { gitlab_name, github_name } = options { GITLAB_GIT_URL, GITHUB_ORG } = process.env repo = "#{_.last(gitlab_name.split('/'))}.git" gitlabRemote = "#{GITLAB_GIT_URL}:#{gitlab_name}.git" githubRemote = "git@github.com:#{GITHUB_ORG}/#{github_name}.git" rm "-rf", repo exec "git clone --mirror #{gitlabRemote}" cd repo exec "git remote add github #{githubRemote}" GitHub.createRepo(github_name) .then -> exec "git push github --mirror" rm "-rf", repo .catch (err) -> console.log err.error migrateWiki: (options) -> { gitlab_name, github_name } = options { GITLAB_GIT_URL, GITHUB_ORG } = process.env repo = "#{_.last(gitlab_name.split('/'))}.git" gitlabRemote = "#{GITLAB_GIT_URL}:#{gitlab_name}.wiki.git" githubRemote = "git@github.com:#{GITHUB_ORG}/#{github_name}.wiki.git" rm "-rf", repo exec "git clone #{gitlabRemote} #{repo}" cd repo exec "git remote add github #{githubRemote}" exec "git push github --force" rm "-rf", repo
140338
require('dotenv').load() require 'shelljs/global' _ = require 'underscore' GitHub = require './github' Git = module.exports = migrateRepo: (options) -> { gitlab_name, github_name } = options { GITLAB_GIT_URL, GITHUB_ORG } = process.env repo = "#{_.last(gitlab_name.split('/'))}.git" gitlabRemote = "#{GITLAB_GIT_URL}:#{gitlab_name}.git" githubRemote = "<EMAIL>:#{GITHUB_ORG}/#{github_name}.git" rm "-rf", repo exec "git clone --mirror #{gitlabRemote}" cd repo exec "git remote add github #{githubRemote}" GitHub.createRepo(github_name) .then -> exec "git push github --mirror" rm "-rf", repo .catch (err) -> console.log err.error migrateWiki: (options) -> { gitlab_name, github_name } = options { GITLAB_GIT_URL, GITHUB_ORG } = process.env repo = "#{_.last(gitlab_name.split('/'))}.git" gitlabRemote = "#{GITLAB_GIT_URL}:#{gitlab_name}.wiki.git" githubRemote = "<EMAIL>:#{GITHUB_ORG}/#{github_name}.wiki.git" rm "-rf", repo exec "git clone #{gitlabRemote} #{repo}" cd repo exec "git remote add github #{githubRemote}" exec "git push github --force" rm "-rf", repo
true
require('dotenv').load() require 'shelljs/global' _ = require 'underscore' GitHub = require './github' Git = module.exports = migrateRepo: (options) -> { gitlab_name, github_name } = options { GITLAB_GIT_URL, GITHUB_ORG } = process.env repo = "#{_.last(gitlab_name.split('/'))}.git" gitlabRemote = "#{GITLAB_GIT_URL}:#{gitlab_name}.git" githubRemote = "PI:EMAIL:<EMAIL>END_PI:#{GITHUB_ORG}/#{github_name}.git" rm "-rf", repo exec "git clone --mirror #{gitlabRemote}" cd repo exec "git remote add github #{githubRemote}" GitHub.createRepo(github_name) .then -> exec "git push github --mirror" rm "-rf", repo .catch (err) -> console.log err.error migrateWiki: (options) -> { gitlab_name, github_name } = options { GITLAB_GIT_URL, GITHUB_ORG } = process.env repo = "#{_.last(gitlab_name.split('/'))}.git" gitlabRemote = "#{GITLAB_GIT_URL}:#{gitlab_name}.wiki.git" githubRemote = "PI:EMAIL:<EMAIL>END_PI:#{GITHUB_ORG}/#{github_name}.wiki.git" rm "-rf", repo exec "git clone #{gitlabRemote} #{repo}" cd repo exec "git remote add github #{githubRemote}" exec "git push github --force" rm "-rf", repo
[ { "context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.", "end": 215, "score": 0.9998300671577454, "start": 198, "tag": "NAME", "value": "Benjamin Blundell" }, { "context": " PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.com\n\n This so", "end": 231, "score": 0.9999305605888367, "start": 218, "tag": "EMAIL", "value": "ben@pxljs.com" } ]
src/light/light.coffee
OniDaito/pxljs
1
### .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js Benjamin Blundell - ben@pxljs.com http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details Basic forward rendering lights such as ambient, spotlight and such - TODO * Issue arises with timing of shader definitions such as num-lights. Shader will need to be rebuilt essentially if the lights change. To do that we have a set of define lines in the shader which we can modify easily. A user will need to set these if they wish to mess with stuff *updating the pos and the matrix together :S tricksy ### {Matrix4, Vec2, Vec3, Vec4, degToRad} = require '../math/math' {RGB,RGBA} = require '../colour/colour' {Contract} = require '../gl/contract' {Fbo} = require '../gl/fbo' # These are set in stone and are the actual values passed to the # shader. Ideally we'd reference them, but the are basically a cache LIGHTING_NUM_POINT_LIGHTS = 5 LIGHTING_NUM_SPOT_LIGHTS = 5 # ## AmbientLight # Basic ambient lighting. Should be included with all basic lights class AmbientLight # **@constructor** # - **colour** - a Colour.RGB - Default RGB(0,0,0) constructor : (@ambientcolour) -> if not @ambientcolour? @ambientcolour = new RGB(0,0,0) @contract = new Contract() @contract.roles.uAmbientLightingColour = "ambientcolour" _addToNode: (node) -> # Overwrite and give no warning? node.ambientLight = @ @ # ## PointLight # A very basic light, a point in space. Used by the node class at present # Doesnt create shadows at present (might use a different class for that) # TODO - At some point this class will need to detect forward and deferred # lighting solutions. # The static class if you will, of PointLight (the protoype) keeps a record # of all the lights in the system and it is this which is passed to the uber # shader in the end. That way, they can be passed as arrays and looped over class PointLight @_posGlobal = new Float32Array(LIGHTING_NUM_POINT_LIGHTS * 3) @_colourGlobal = new Float32Array(LIGHTING_NUM_POINT_LIGHTS * 3) @_attenuationGlobal = new Float32Array(LIGHTING_NUM_POINT_LIGHTS * 4) @contract = new Contract() @contract.roles.uPointLightPos = "_posGlobal" @contract.roles.uPointLightColour = "_colourGlobal" @contract.roles.uPointLightAttenuation = "_attenuationGlobal" @contract.roles.uPointLightNum = "_numGlobal" # Called by the node traversal section when we create our node tree # We modify the positions in place with the current matrix. This way # the light positions are pre-computed before they hit the shader @_preDraw : (lights, matrix) -> idx = 0 if not lights? return for light in lights # Light transforms are now done in the shader ll = Matrix4.multVec(matrix,light.pos) PointLight._posGlobal[idx * 3] = ll.x PointLight._posGlobal[idx * 3 + 1] = ll.y PointLight._posGlobal[idx * 3 + 2] = ll.z PointLight._colourGlobal[idx * 3] = light.colour.r PointLight._colourGlobal[idx * 3 + 1] = light.colour.g PointLight._colourGlobal[idx * 3 + 2] = light.colour.b PointLight._attenuationGlobal[idx * 4] = light.attenuation.x PointLight._attenuationGlobal[idx * 4 + 1] = light.attenuation.y PointLight._attenuationGlobal[idx * 4 + 2] = light.attenuation.z PointLight._attenuationGlobal[idx * 4 + 3] = light.attenuation.w idx += 1 PointLight._numGlobal = lights.length # **@constructor** # - **pos** - a Vec3 - Default (1,1,1) # - **colour** - a Colour.RGB - Default RGB.WHITE # - **attenutation** - an Array of Number - Length 4 - Default [100, 1.0, 0.045, 0.0075] - **NOT IMPLEMENTED YET** # TODO - need to add attenuation to our ubershader constructor : (@pos, @colour, @attenuation) -> # this is a bit of a hack to get things bound to shaders but it works @contract = PointLight.contract @_posGlobal = PointLight._posGlobal @_colourGlobal = PointLight._colourGlobal @_attenuationGlobal = PointLight._attenuationGlobal @_numGlobal = PointLight._numGlobal if not @pos? @pos = new Vec3(1,1,1) if not @colour? @colour = RGB.WHITE() # Attention has 4 components - range, constant, linear and quadratic if not @attenuation? @attenuation = [ 100, 1.0, 0.045, 0.0075 ] # _addToNode - called when this class is added to a node _addToNode: (node) -> node.pointLights.push @ @ # _removeFromNode - called when this class is removed from a node _removeFromNode: (node) -> node.pointLights.splice node.pointLights.indexOf @ @ # ## SpotLight # A SpotLight with a direction and angle (which represents how wide the beam is) # Just as in PointLight, the spotlight prototype records all spots class SpotLight @_posGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS * 3) @_colourGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS * 3) @_attenuationGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS * 4) @_dirGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS * 3) @_angleGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS) @_expGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS) @_mvpMatrixGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS * 16) @_samplerGlobal = new Int32Array(LIGHTING_NUM_SPOT_LIGHTS) @contract = new Contract() @contract.roles.uSpotLightPos = "_posGlobal" @contract.roles.uSpotLightColour = "_colourGlobal" @contract.roles.uSpotLightAttenuation = "_attenuationGlobal" @contract.roles.uSpotLightDir = "_dirGlobal" @contract.roles.uSpotLightAngle = "_angleGlobal" @contract.roles.uSpotLightExp = "_expGlobal" @contract.roles.uSpotLightNum = "_numGlobal" @contract.roles.uSpotLightMatrix = "_mvpMatrixGlobal" @contract.roles.uSamplerSpotShadow = "_samplerGlobal" # called internally - sets up the global contract array @_preDraw : (lights, matrix) -> idx = 0 if not lights? return for light in lights ll = Matrix4.multVec(matrix, light.pos) SpotLight._posGlobal[idx * 3] = ll.x SpotLight._posGlobal[idx * 3 + 1] = ll.y SpotLight._posGlobal[idx * 3 + 2] = ll.z SpotLight._colourGlobal[idx * 3] = light.colour.r SpotLight._colourGlobal[idx * 3 + 1] = light.colour.g SpotLight._colourGlobal[idx * 3 + 2] = light.colour.b SpotLight._attenuationGlobal[idx * 4] = light.attenuation.x SpotLight._attenuationGlobal[idx * 4 + 1] = light.attenuation.y SpotLight._attenuationGlobal[idx * 4 + 2] = light.attenuation.z SpotLight._attenuationGlobal[idx * 4 + 3] = light.attenuation.w SpotLight._dirGlobal[idx * 3] = light.dir.x SpotLight._dirGlobal[idx * 3 + 1] = light.dir.y SpotLight._dirGlobal[idx * 3 + 2] = light.dir.z SpotLight._angleGlobal[idx] = light.angle SpotLight._expGlobal[idx] = light.exponent if light.shadowmap for i in [0..15] SpotLight._mvpMatrixGlobal[idx*16+i] = light.mvpMatrix.a[i] # Bind the shadowmap texture, ready for sampling light.shadowmap_fbo.texture.bind() SpotLight._samplerGlobal[idx] = light.shadowmap_fbo.texture.unit idx += 1 SpotLight.numGlobal = lights.length # Called internally, mostly to unbind the shadowmaps @_postDraw : (lights) -> for light in lights if light.shadowmap light.shadowmap_fbo.texture.unbind() # TODO - Add a mask here that basically says which lights are on or off # We need this because we may call draw on a subnode of a node that has a light # and that light should not affect the scene. this mask would be passed to the shader # **@constructor** # -**pos** - a Vec3 # -**colour** - an RGB # -**dir** - a Vec3 # -**angle** - a Number - radians # -**exponent** - a Number # -**shadowmap** - a Boolean # -**attentuation** - a List of Number - length 4 - optional - default [10, 1.0, 0.045, 0.0075] constructor : (@pos, @colour, @dir, @angle, @shadowmap, @exponent, @attenuation) -> @contract = SpotLight.contract @_posGlobal = SpotLight._posGlobal @_colourGlobal = SpotLight._colourGlobal @_attenuationGlobal = SpotLight._attenuationGlobal @_dirGlobal = SpotLight._dirGlobal @_angleGlobal = SpotLight._angleGlobal @_expGlobal = SpotLight._expGlobal @_mvpMatrixGlobal = SpotLight._mvpMatrixGlobal @_samplerGlobal = SpotLight._samplerGlobal if not @pos? @pos = new Vec3(1,1,1) if not @colour? @colour = RGB.WHITE() if not @shadowmap? @shadowmap = false if @shadowmap @shadowmap_fbo = new Fbo(512,512) @mvpMatrix = new Matrix4() # Attenuation has 4 components - range, constant, linear and quadratic if not @attenuation? @attenuation = [ 10.0, 1.0, 0.045, 0.0075 ] if not @dir? @dir = new Vec3(0,-1,0) @dir.normalize() if not @angle? @angle = degToRad 45.0 if not @exponent? @exponent = 100.0 @idx = -1 # Used to say where in the global array this light is # _addToNode - called when this class is added to a node _addToNode: (node) -> node.spotLights.push @ @ # _removeFromNode - called when this class is removed from a node _removeFromNode: (node) -> node.spotLights.splice node.spotLights.indexOf @ @ module.exports = PointLight : PointLight AmbientLight : AmbientLight SpotLight : SpotLight
204592
### .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js <NAME> - <EMAIL> http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details Basic forward rendering lights such as ambient, spotlight and such - TODO * Issue arises with timing of shader definitions such as num-lights. Shader will need to be rebuilt essentially if the lights change. To do that we have a set of define lines in the shader which we can modify easily. A user will need to set these if they wish to mess with stuff *updating the pos and the matrix together :S tricksy ### {Matrix4, Vec2, Vec3, Vec4, degToRad} = require '../math/math' {RGB,RGBA} = require '../colour/colour' {Contract} = require '../gl/contract' {Fbo} = require '../gl/fbo' # These are set in stone and are the actual values passed to the # shader. Ideally we'd reference them, but the are basically a cache LIGHTING_NUM_POINT_LIGHTS = 5 LIGHTING_NUM_SPOT_LIGHTS = 5 # ## AmbientLight # Basic ambient lighting. Should be included with all basic lights class AmbientLight # **@constructor** # - **colour** - a Colour.RGB - Default RGB(0,0,0) constructor : (@ambientcolour) -> if not @ambientcolour? @ambientcolour = new RGB(0,0,0) @contract = new Contract() @contract.roles.uAmbientLightingColour = "ambientcolour" _addToNode: (node) -> # Overwrite and give no warning? node.ambientLight = @ @ # ## PointLight # A very basic light, a point in space. Used by the node class at present # Doesnt create shadows at present (might use a different class for that) # TODO - At some point this class will need to detect forward and deferred # lighting solutions. # The static class if you will, of PointLight (the protoype) keeps a record # of all the lights in the system and it is this which is passed to the uber # shader in the end. That way, they can be passed as arrays and looped over class PointLight @_posGlobal = new Float32Array(LIGHTING_NUM_POINT_LIGHTS * 3) @_colourGlobal = new Float32Array(LIGHTING_NUM_POINT_LIGHTS * 3) @_attenuationGlobal = new Float32Array(LIGHTING_NUM_POINT_LIGHTS * 4) @contract = new Contract() @contract.roles.uPointLightPos = "_posGlobal" @contract.roles.uPointLightColour = "_colourGlobal" @contract.roles.uPointLightAttenuation = "_attenuationGlobal" @contract.roles.uPointLightNum = "_numGlobal" # Called by the node traversal section when we create our node tree # We modify the positions in place with the current matrix. This way # the light positions are pre-computed before they hit the shader @_preDraw : (lights, matrix) -> idx = 0 if not lights? return for light in lights # Light transforms are now done in the shader ll = Matrix4.multVec(matrix,light.pos) PointLight._posGlobal[idx * 3] = ll.x PointLight._posGlobal[idx * 3 + 1] = ll.y PointLight._posGlobal[idx * 3 + 2] = ll.z PointLight._colourGlobal[idx * 3] = light.colour.r PointLight._colourGlobal[idx * 3 + 1] = light.colour.g PointLight._colourGlobal[idx * 3 + 2] = light.colour.b PointLight._attenuationGlobal[idx * 4] = light.attenuation.x PointLight._attenuationGlobal[idx * 4 + 1] = light.attenuation.y PointLight._attenuationGlobal[idx * 4 + 2] = light.attenuation.z PointLight._attenuationGlobal[idx * 4 + 3] = light.attenuation.w idx += 1 PointLight._numGlobal = lights.length # **@constructor** # - **pos** - a Vec3 - Default (1,1,1) # - **colour** - a Colour.RGB - Default RGB.WHITE # - **attenutation** - an Array of Number - Length 4 - Default [100, 1.0, 0.045, 0.0075] - **NOT IMPLEMENTED YET** # TODO - need to add attenuation to our ubershader constructor : (@pos, @colour, @attenuation) -> # this is a bit of a hack to get things bound to shaders but it works @contract = PointLight.contract @_posGlobal = PointLight._posGlobal @_colourGlobal = PointLight._colourGlobal @_attenuationGlobal = PointLight._attenuationGlobal @_numGlobal = PointLight._numGlobal if not @pos? @pos = new Vec3(1,1,1) if not @colour? @colour = RGB.WHITE() # Attention has 4 components - range, constant, linear and quadratic if not @attenuation? @attenuation = [ 100, 1.0, 0.045, 0.0075 ] # _addToNode - called when this class is added to a node _addToNode: (node) -> node.pointLights.push @ @ # _removeFromNode - called when this class is removed from a node _removeFromNode: (node) -> node.pointLights.splice node.pointLights.indexOf @ @ # ## SpotLight # A SpotLight with a direction and angle (which represents how wide the beam is) # Just as in PointLight, the spotlight prototype records all spots class SpotLight @_posGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS * 3) @_colourGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS * 3) @_attenuationGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS * 4) @_dirGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS * 3) @_angleGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS) @_expGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS) @_mvpMatrixGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS * 16) @_samplerGlobal = new Int32Array(LIGHTING_NUM_SPOT_LIGHTS) @contract = new Contract() @contract.roles.uSpotLightPos = "_posGlobal" @contract.roles.uSpotLightColour = "_colourGlobal" @contract.roles.uSpotLightAttenuation = "_attenuationGlobal" @contract.roles.uSpotLightDir = "_dirGlobal" @contract.roles.uSpotLightAngle = "_angleGlobal" @contract.roles.uSpotLightExp = "_expGlobal" @contract.roles.uSpotLightNum = "_numGlobal" @contract.roles.uSpotLightMatrix = "_mvpMatrixGlobal" @contract.roles.uSamplerSpotShadow = "_samplerGlobal" # called internally - sets up the global contract array @_preDraw : (lights, matrix) -> idx = 0 if not lights? return for light in lights ll = Matrix4.multVec(matrix, light.pos) SpotLight._posGlobal[idx * 3] = ll.x SpotLight._posGlobal[idx * 3 + 1] = ll.y SpotLight._posGlobal[idx * 3 + 2] = ll.z SpotLight._colourGlobal[idx * 3] = light.colour.r SpotLight._colourGlobal[idx * 3 + 1] = light.colour.g SpotLight._colourGlobal[idx * 3 + 2] = light.colour.b SpotLight._attenuationGlobal[idx * 4] = light.attenuation.x SpotLight._attenuationGlobal[idx * 4 + 1] = light.attenuation.y SpotLight._attenuationGlobal[idx * 4 + 2] = light.attenuation.z SpotLight._attenuationGlobal[idx * 4 + 3] = light.attenuation.w SpotLight._dirGlobal[idx * 3] = light.dir.x SpotLight._dirGlobal[idx * 3 + 1] = light.dir.y SpotLight._dirGlobal[idx * 3 + 2] = light.dir.z SpotLight._angleGlobal[idx] = light.angle SpotLight._expGlobal[idx] = light.exponent if light.shadowmap for i in [0..15] SpotLight._mvpMatrixGlobal[idx*16+i] = light.mvpMatrix.a[i] # Bind the shadowmap texture, ready for sampling light.shadowmap_fbo.texture.bind() SpotLight._samplerGlobal[idx] = light.shadowmap_fbo.texture.unit idx += 1 SpotLight.numGlobal = lights.length # Called internally, mostly to unbind the shadowmaps @_postDraw : (lights) -> for light in lights if light.shadowmap light.shadowmap_fbo.texture.unbind() # TODO - Add a mask here that basically says which lights are on or off # We need this because we may call draw on a subnode of a node that has a light # and that light should not affect the scene. this mask would be passed to the shader # **@constructor** # -**pos** - a Vec3 # -**colour** - an RGB # -**dir** - a Vec3 # -**angle** - a Number - radians # -**exponent** - a Number # -**shadowmap** - a Boolean # -**attentuation** - a List of Number - length 4 - optional - default [10, 1.0, 0.045, 0.0075] constructor : (@pos, @colour, @dir, @angle, @shadowmap, @exponent, @attenuation) -> @contract = SpotLight.contract @_posGlobal = SpotLight._posGlobal @_colourGlobal = SpotLight._colourGlobal @_attenuationGlobal = SpotLight._attenuationGlobal @_dirGlobal = SpotLight._dirGlobal @_angleGlobal = SpotLight._angleGlobal @_expGlobal = SpotLight._expGlobal @_mvpMatrixGlobal = SpotLight._mvpMatrixGlobal @_samplerGlobal = SpotLight._samplerGlobal if not @pos? @pos = new Vec3(1,1,1) if not @colour? @colour = RGB.WHITE() if not @shadowmap? @shadowmap = false if @shadowmap @shadowmap_fbo = new Fbo(512,512) @mvpMatrix = new Matrix4() # Attenuation has 4 components - range, constant, linear and quadratic if not @attenuation? @attenuation = [ 10.0, 1.0, 0.045, 0.0075 ] if not @dir? @dir = new Vec3(0,-1,0) @dir.normalize() if not @angle? @angle = degToRad 45.0 if not @exponent? @exponent = 100.0 @idx = -1 # Used to say where in the global array this light is # _addToNode - called when this class is added to a node _addToNode: (node) -> node.spotLights.push @ @ # _removeFromNode - called when this class is removed from a node _removeFromNode: (node) -> node.spotLights.splice node.spotLights.indexOf @ @ module.exports = PointLight : PointLight AmbientLight : AmbientLight SpotLight : SpotLight
true
### .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details Basic forward rendering lights such as ambient, spotlight and such - TODO * Issue arises with timing of shader definitions such as num-lights. Shader will need to be rebuilt essentially if the lights change. To do that we have a set of define lines in the shader which we can modify easily. A user will need to set these if they wish to mess with stuff *updating the pos and the matrix together :S tricksy ### {Matrix4, Vec2, Vec3, Vec4, degToRad} = require '../math/math' {RGB,RGBA} = require '../colour/colour' {Contract} = require '../gl/contract' {Fbo} = require '../gl/fbo' # These are set in stone and are the actual values passed to the # shader. Ideally we'd reference them, but the are basically a cache LIGHTING_NUM_POINT_LIGHTS = 5 LIGHTING_NUM_SPOT_LIGHTS = 5 # ## AmbientLight # Basic ambient lighting. Should be included with all basic lights class AmbientLight # **@constructor** # - **colour** - a Colour.RGB - Default RGB(0,0,0) constructor : (@ambientcolour) -> if not @ambientcolour? @ambientcolour = new RGB(0,0,0) @contract = new Contract() @contract.roles.uAmbientLightingColour = "ambientcolour" _addToNode: (node) -> # Overwrite and give no warning? node.ambientLight = @ @ # ## PointLight # A very basic light, a point in space. Used by the node class at present # Doesnt create shadows at present (might use a different class for that) # TODO - At some point this class will need to detect forward and deferred # lighting solutions. # The static class if you will, of PointLight (the protoype) keeps a record # of all the lights in the system and it is this which is passed to the uber # shader in the end. That way, they can be passed as arrays and looped over class PointLight @_posGlobal = new Float32Array(LIGHTING_NUM_POINT_LIGHTS * 3) @_colourGlobal = new Float32Array(LIGHTING_NUM_POINT_LIGHTS * 3) @_attenuationGlobal = new Float32Array(LIGHTING_NUM_POINT_LIGHTS * 4) @contract = new Contract() @contract.roles.uPointLightPos = "_posGlobal" @contract.roles.uPointLightColour = "_colourGlobal" @contract.roles.uPointLightAttenuation = "_attenuationGlobal" @contract.roles.uPointLightNum = "_numGlobal" # Called by the node traversal section when we create our node tree # We modify the positions in place with the current matrix. This way # the light positions are pre-computed before they hit the shader @_preDraw : (lights, matrix) -> idx = 0 if not lights? return for light in lights # Light transforms are now done in the shader ll = Matrix4.multVec(matrix,light.pos) PointLight._posGlobal[idx * 3] = ll.x PointLight._posGlobal[idx * 3 + 1] = ll.y PointLight._posGlobal[idx * 3 + 2] = ll.z PointLight._colourGlobal[idx * 3] = light.colour.r PointLight._colourGlobal[idx * 3 + 1] = light.colour.g PointLight._colourGlobal[idx * 3 + 2] = light.colour.b PointLight._attenuationGlobal[idx * 4] = light.attenuation.x PointLight._attenuationGlobal[idx * 4 + 1] = light.attenuation.y PointLight._attenuationGlobal[idx * 4 + 2] = light.attenuation.z PointLight._attenuationGlobal[idx * 4 + 3] = light.attenuation.w idx += 1 PointLight._numGlobal = lights.length # **@constructor** # - **pos** - a Vec3 - Default (1,1,1) # - **colour** - a Colour.RGB - Default RGB.WHITE # - **attenutation** - an Array of Number - Length 4 - Default [100, 1.0, 0.045, 0.0075] - **NOT IMPLEMENTED YET** # TODO - need to add attenuation to our ubershader constructor : (@pos, @colour, @attenuation) -> # this is a bit of a hack to get things bound to shaders but it works @contract = PointLight.contract @_posGlobal = PointLight._posGlobal @_colourGlobal = PointLight._colourGlobal @_attenuationGlobal = PointLight._attenuationGlobal @_numGlobal = PointLight._numGlobal if not @pos? @pos = new Vec3(1,1,1) if not @colour? @colour = RGB.WHITE() # Attention has 4 components - range, constant, linear and quadratic if not @attenuation? @attenuation = [ 100, 1.0, 0.045, 0.0075 ] # _addToNode - called when this class is added to a node _addToNode: (node) -> node.pointLights.push @ @ # _removeFromNode - called when this class is removed from a node _removeFromNode: (node) -> node.pointLights.splice node.pointLights.indexOf @ @ # ## SpotLight # A SpotLight with a direction and angle (which represents how wide the beam is) # Just as in PointLight, the spotlight prototype records all spots class SpotLight @_posGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS * 3) @_colourGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS * 3) @_attenuationGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS * 4) @_dirGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS * 3) @_angleGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS) @_expGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS) @_mvpMatrixGlobal = new Float32Array(LIGHTING_NUM_SPOT_LIGHTS * 16) @_samplerGlobal = new Int32Array(LIGHTING_NUM_SPOT_LIGHTS) @contract = new Contract() @contract.roles.uSpotLightPos = "_posGlobal" @contract.roles.uSpotLightColour = "_colourGlobal" @contract.roles.uSpotLightAttenuation = "_attenuationGlobal" @contract.roles.uSpotLightDir = "_dirGlobal" @contract.roles.uSpotLightAngle = "_angleGlobal" @contract.roles.uSpotLightExp = "_expGlobal" @contract.roles.uSpotLightNum = "_numGlobal" @contract.roles.uSpotLightMatrix = "_mvpMatrixGlobal" @contract.roles.uSamplerSpotShadow = "_samplerGlobal" # called internally - sets up the global contract array @_preDraw : (lights, matrix) -> idx = 0 if not lights? return for light in lights ll = Matrix4.multVec(matrix, light.pos) SpotLight._posGlobal[idx * 3] = ll.x SpotLight._posGlobal[idx * 3 + 1] = ll.y SpotLight._posGlobal[idx * 3 + 2] = ll.z SpotLight._colourGlobal[idx * 3] = light.colour.r SpotLight._colourGlobal[idx * 3 + 1] = light.colour.g SpotLight._colourGlobal[idx * 3 + 2] = light.colour.b SpotLight._attenuationGlobal[idx * 4] = light.attenuation.x SpotLight._attenuationGlobal[idx * 4 + 1] = light.attenuation.y SpotLight._attenuationGlobal[idx * 4 + 2] = light.attenuation.z SpotLight._attenuationGlobal[idx * 4 + 3] = light.attenuation.w SpotLight._dirGlobal[idx * 3] = light.dir.x SpotLight._dirGlobal[idx * 3 + 1] = light.dir.y SpotLight._dirGlobal[idx * 3 + 2] = light.dir.z SpotLight._angleGlobal[idx] = light.angle SpotLight._expGlobal[idx] = light.exponent if light.shadowmap for i in [0..15] SpotLight._mvpMatrixGlobal[idx*16+i] = light.mvpMatrix.a[i] # Bind the shadowmap texture, ready for sampling light.shadowmap_fbo.texture.bind() SpotLight._samplerGlobal[idx] = light.shadowmap_fbo.texture.unit idx += 1 SpotLight.numGlobal = lights.length # Called internally, mostly to unbind the shadowmaps @_postDraw : (lights) -> for light in lights if light.shadowmap light.shadowmap_fbo.texture.unbind() # TODO - Add a mask here that basically says which lights are on or off # We need this because we may call draw on a subnode of a node that has a light # and that light should not affect the scene. this mask would be passed to the shader # **@constructor** # -**pos** - a Vec3 # -**colour** - an RGB # -**dir** - a Vec3 # -**angle** - a Number - radians # -**exponent** - a Number # -**shadowmap** - a Boolean # -**attentuation** - a List of Number - length 4 - optional - default [10, 1.0, 0.045, 0.0075] constructor : (@pos, @colour, @dir, @angle, @shadowmap, @exponent, @attenuation) -> @contract = SpotLight.contract @_posGlobal = SpotLight._posGlobal @_colourGlobal = SpotLight._colourGlobal @_attenuationGlobal = SpotLight._attenuationGlobal @_dirGlobal = SpotLight._dirGlobal @_angleGlobal = SpotLight._angleGlobal @_expGlobal = SpotLight._expGlobal @_mvpMatrixGlobal = SpotLight._mvpMatrixGlobal @_samplerGlobal = SpotLight._samplerGlobal if not @pos? @pos = new Vec3(1,1,1) if not @colour? @colour = RGB.WHITE() if not @shadowmap? @shadowmap = false if @shadowmap @shadowmap_fbo = new Fbo(512,512) @mvpMatrix = new Matrix4() # Attenuation has 4 components - range, constant, linear and quadratic if not @attenuation? @attenuation = [ 10.0, 1.0, 0.045, 0.0075 ] if not @dir? @dir = new Vec3(0,-1,0) @dir.normalize() if not @angle? @angle = degToRad 45.0 if not @exponent? @exponent = 100.0 @idx = -1 # Used to say where in the global array this light is # _addToNode - called when this class is added to a node _addToNode: (node) -> node.spotLights.push @ @ # _removeFromNode - called when this class is removed from a node _removeFromNode: (node) -> node.spotLights.splice node.spotLights.indexOf @ @ module.exports = PointLight : PointLight AmbientLight : AmbientLight SpotLight : SpotLight
[ { "context": "\n ###\n uBerscore adaptation of deepExtend, by [Kurt Milam](https://gist.github.com/1868955)\n\n Its mainly ", "end": 202, "score": 0.999880850315094, "start": 192, "tag": "NAME", "value": "Kurt Milam" }, { "context": "pExtend, by [Kurt Milam](https://gist.github.com/1868955)\n\n Its mainly a demonstration of uBerscore's _", "end": 234, "score": 0.9804784059524536, "start": 229, "tag": "USERNAME", "value": "86895" } ]
source/code/blending/blenders/DeepExtendBlender.coffee
anodynos/uBerscore
1
#Blender = require '../Blender' #if true define ['../Blender'], (Blender)-> l = new (require '../../Logger') 'uberscore/DeepExtendBlender' ### uBerscore adaptation of deepExtend, by [Kurt Milam](https://gist.github.com/1868955) Its mainly a demonstration of uBerscore's _B.Blender abilities. It can be easily further extended is you desire. It passes deepExtend's tests. # Changes/extra features # - extra: allow lodash'es 'shadowed' variables # - change: ${} instead of #{} in parentRE, cause it conflicts with Coffeescript! # - null _deletes_ object key, as well as array item # - copying Function over Object should replace it first @see /blending/deepExtend #todo: not working with Blender API for read/write/createAs/properties ### class DeepExtendBlender extends Blender @behavior: order: ['src', 'dst'] String: '*': 'overwriteOrReplace' '[]': '[]': (prop, src, dst)-> # Filter null / undefined. (note `type.areEqual('[]', 'Array') is true`) _.reject @deepOverwrite(prop, src, dst), (v)-> v in [null, undefined] '*': (prop, src, dst)-> throw """ deepExtend: Error: Trying to combine an array with a non-array. Property: #{prop} destination[prop]: #{l.prettify dst[prop]} source[prop]: #{l.prettify src[prop]} """ '{}': '{}': (prop, src, dst)-> # Delete null / undefined (note `type.areEqual('{}', 'Object') is true`) for key, val of deepBlended = @getAction('deepOverwrite')(prop, src, dst) if (val is null) or (val is undefined) delete deepBlended[key] deepBlended '*': (prop, src, dst)-> throw """ deepExtend: Error trying to combine a PlainObject with a non-PlainObject. Property: #{prop} destination[prop]: #{l.prettify dst[prop]} source[prop]: #{l.prettify src[prop]} """ # Actions - local to this blenderBehavior ### Overwrites a source value on top of destination, but if sourceVal is a replaceRE holder, it _mainly_ returns `src[prop].replace @replaceRE, dst[prop]` ### overwriteOrReplace: (prop, src, dst)-> replaceRE = /\${\s*?_\s*?}/ # it becomes a @ member of Blender instance if _.isString(src[prop]) and replaceRE.test(src[prop]) if _.isString dst[prop] src[prop].replace replaceRE, dst[prop] else # if our dest is not a 'isPlain' value (eg String, Number), eg {key: "${}"}-> {key: someNonPlainVal} # it means it can't 'accept' a replacement, but we are just holding its value dst[prop] else src[prop] # simply overwrite
40470
#Blender = require '../Blender' #if true define ['../Blender'], (Blender)-> l = new (require '../../Logger') 'uberscore/DeepExtendBlender' ### uBerscore adaptation of deepExtend, by [<NAME>](https://gist.github.com/1868955) Its mainly a demonstration of uBerscore's _B.Blender abilities. It can be easily further extended is you desire. It passes deepExtend's tests. # Changes/extra features # - extra: allow lodash'es 'shadowed' variables # - change: ${} instead of #{} in parentRE, cause it conflicts with Coffeescript! # - null _deletes_ object key, as well as array item # - copying Function over Object should replace it first @see /blending/deepExtend #todo: not working with Blender API for read/write/createAs/properties ### class DeepExtendBlender extends Blender @behavior: order: ['src', 'dst'] String: '*': 'overwriteOrReplace' '[]': '[]': (prop, src, dst)-> # Filter null / undefined. (note `type.areEqual('[]', 'Array') is true`) _.reject @deepOverwrite(prop, src, dst), (v)-> v in [null, undefined] '*': (prop, src, dst)-> throw """ deepExtend: Error: Trying to combine an array with a non-array. Property: #{prop} destination[prop]: #{l.prettify dst[prop]} source[prop]: #{l.prettify src[prop]} """ '{}': '{}': (prop, src, dst)-> # Delete null / undefined (note `type.areEqual('{}', 'Object') is true`) for key, val of deepBlended = @getAction('deepOverwrite')(prop, src, dst) if (val is null) or (val is undefined) delete deepBlended[key] deepBlended '*': (prop, src, dst)-> throw """ deepExtend: Error trying to combine a PlainObject with a non-PlainObject. Property: #{prop} destination[prop]: #{l.prettify dst[prop]} source[prop]: #{l.prettify src[prop]} """ # Actions - local to this blenderBehavior ### Overwrites a source value on top of destination, but if sourceVal is a replaceRE holder, it _mainly_ returns `src[prop].replace @replaceRE, dst[prop]` ### overwriteOrReplace: (prop, src, dst)-> replaceRE = /\${\s*?_\s*?}/ # it becomes a @ member of Blender instance if _.isString(src[prop]) and replaceRE.test(src[prop]) if _.isString dst[prop] src[prop].replace replaceRE, dst[prop] else # if our dest is not a 'isPlain' value (eg String, Number), eg {key: "${}"}-> {key: someNonPlainVal} # it means it can't 'accept' a replacement, but we are just holding its value dst[prop] else src[prop] # simply overwrite
true
#Blender = require '../Blender' #if true define ['../Blender'], (Blender)-> l = new (require '../../Logger') 'uberscore/DeepExtendBlender' ### uBerscore adaptation of deepExtend, by [PI:NAME:<NAME>END_PI](https://gist.github.com/1868955) Its mainly a demonstration of uBerscore's _B.Blender abilities. It can be easily further extended is you desire. It passes deepExtend's tests. # Changes/extra features # - extra: allow lodash'es 'shadowed' variables # - change: ${} instead of #{} in parentRE, cause it conflicts with Coffeescript! # - null _deletes_ object key, as well as array item # - copying Function over Object should replace it first @see /blending/deepExtend #todo: not working with Blender API for read/write/createAs/properties ### class DeepExtendBlender extends Blender @behavior: order: ['src', 'dst'] String: '*': 'overwriteOrReplace' '[]': '[]': (prop, src, dst)-> # Filter null / undefined. (note `type.areEqual('[]', 'Array') is true`) _.reject @deepOverwrite(prop, src, dst), (v)-> v in [null, undefined] '*': (prop, src, dst)-> throw """ deepExtend: Error: Trying to combine an array with a non-array. Property: #{prop} destination[prop]: #{l.prettify dst[prop]} source[prop]: #{l.prettify src[prop]} """ '{}': '{}': (prop, src, dst)-> # Delete null / undefined (note `type.areEqual('{}', 'Object') is true`) for key, val of deepBlended = @getAction('deepOverwrite')(prop, src, dst) if (val is null) or (val is undefined) delete deepBlended[key] deepBlended '*': (prop, src, dst)-> throw """ deepExtend: Error trying to combine a PlainObject with a non-PlainObject. Property: #{prop} destination[prop]: #{l.prettify dst[prop]} source[prop]: #{l.prettify src[prop]} """ # Actions - local to this blenderBehavior ### Overwrites a source value on top of destination, but if sourceVal is a replaceRE holder, it _mainly_ returns `src[prop].replace @replaceRE, dst[prop]` ### overwriteOrReplace: (prop, src, dst)-> replaceRE = /\${\s*?_\s*?}/ # it becomes a @ member of Blender instance if _.isString(src[prop]) and replaceRE.test(src[prop]) if _.isString dst[prop] src[prop].replace replaceRE, dst[prop] else # if our dest is not a 'isPlain' value (eg String, Number), eg {key: "${}"}-> {key: someNonPlainVal} # it means it can't 'accept' a replacement, but we are just holding its value dst[prop] else src[prop] # simply overwrite
[ { "context": "sion =\n 'Core': [\n {\n name: 'X-Wing'\n type: 'ship'\n count: 1\n ", "end": 363, "score": 0.9993854761123657, "start": 357, "tag": "NAME", "value": "X-Wing" }, { "context": " count: 1\n }\n {\n name: 'TIE Fighter'\n type: 'ship'\n count: 2\n ", "end": 461, "score": 0.9968727231025696, "start": 450, "tag": "NAME", "value": "TIE Fighter" }, { "context": " count: 2\n }\n {\n name: 'Luke Skywalker'\n type: 'pilot'\n count: 1\n ", "end": 562, "score": 0.9998165369033813, "start": 548, "tag": "NAME", "value": "Luke Skywalker" }, { "context": " count: 1\n }\n {\n name: 'Biggs Darklighter'\n type: 'pilot'\n count: 1\n ", "end": 667, "score": 0.9186961054801941, "start": 650, "tag": "NAME", "value": "Biggs Darklighter" }, { "context": " count: 1\n }\n {\n name: 'Rookie Pilot'\n type: 'pilot'\n count: 1\n ", "end": 873, "score": 0.9268491268157959, "start": 861, "tag": "NAME", "value": "Rookie Pilot" }, { "context": " count: 1\n }\n {\n name: '\"Mauler Mithel\"'\n type: 'pilot'\n count: 1\n", "end": 975, "score": 0.9998620748519897, "start": 962, "tag": "NAME", "value": "Mauler Mithel" }, { "context": " count: 1\n }\n {\n name: '\"Dark Curse\"'\n type: 'pilot'\n count: ", "end": 1073, "score": 0.8060024976730347, "start": 1065, "tag": "NAME", "value": "Dark Cur" }, { "context": " count: 2\n }\n {\n name: 'Proton Torpedoes'\n type: 'upgrade'\n count: 1", "end": 1601, "score": 0.9806245565414429, "start": 1585, "tag": "NAME", "value": "Proton Torpedoes" }, { "context": " count: 1\n }\n {\n name: 'Determination'\n type: 'upgrade'\n cou", "end": 1889, "score": 0.6350724101066589, "start": 1881, "tag": "NAME", "value": "Determin" }, { "context": " count: 1\n }\n {\n name: 'Marksmanship'\n type: 'upgrade'\n count: 1", "end": 1996, "score": 0.999225914478302, "start": 1984, "tag": "NAME", "value": "Marksmanship" }, { "context": "g Expansion Pack': [\n {\n name: 'X-Wing'\n type: 'ship'\n count: 1\n ", "end": 2129, "score": 0.9994977116584778, "start": 2123, "tag": "NAME", "value": "X-Wing" }, { "context": " count: 1\n }\n {\n name: 'Wedge Antilles'\n type: 'pilot'\n count: 1\n ", "end": 2230, "score": 0.9997708201408386, "start": 2216, "tag": "NAME", "value": "Wedge Antilles" }, { "context": " count: 1\n }\n {\n name: 'Garven Dreis'\n type: 'pilot'\n count: 1\n ", "end": 2330, "score": 0.9998427629470825, "start": 2318, "tag": "NAME", "value": "Garven Dreis" }, { "context": " count: 1\n }\n {\n name: 'Rookie Pilot'\n type: 'pilot'\n coun", "end": 2530, "score": 0.7805571556091309, "start": 2524, "tag": "NAME", "value": "Rookie" }, { "context": " count: 1\n }\n {\n name: 'Proton Torpedoes'\n type: 'upgrade'\n count: 1", "end": 2640, "score": 0.9697517156600952, "start": 2624, "tag": "NAME", "value": "Proton Torpedoes" }, { "context": " count: 1\n }\n {\n name: 'Expert Handling'\n type: 'upgrade'\n count: 1", "end": 2942, "score": 0.941042959690094, "start": 2927, "tag": "NAME", "value": "Expert Handling" }, { "context": " count: 1\n }\n {\n name: 'Marksmanship'\n type: 'upgrade'\n count: 1", "end": 3044, "score": 0.9989102482795715, "start": 3032, "tag": "NAME", "value": "Marksmanship" }, { "context": "g Expansion Pack': [\n {\n name: 'Y-Wing'\n type: 'ship'\n count: 1\n ", "end": 3177, "score": 0.9995550513267517, "start": 3171, "tag": "NAME", "value": "Y-Wing" }, { "context": " count: 1\n }\n {\n name: 'Horton Salm'\n type: 'pilot'\n count: 1\n ", "end": 3275, "score": 0.9997495412826538, "start": 3264, "tag": "NAME", "value": "Horton Salm" }, { "context": " count: 1\n }\n {\n name: '\"Dutch\" Vander'\n type: 'pilot'\n count: 1\n ", "end": 3377, "score": 0.9987824559211731, "start": 3364, "tag": "NAME", "value": "Dutch\" Vander" }, { "context": " count: 1\n }\n {\n name: 'Proton Torpedoes'\n type: 'upgrade'\n ", "end": 3685, "score": 0.6881424188613892, "start": 3679, "tag": "NAME", "value": "Proton" }, { "context": "\n }\n {\n name: 'Proton Torpedoes'\n type: 'upgrade'\n count: 2", "end": 3695, "score": 0.6030818223953247, "start": 3689, "tag": "NAME", "value": "pedoes" }, { "context": "r Expansion Pack': [\n {\n name: 'TIE Fighter'\n type: 'ship'\n count: 1\n ", "end": 4142, "score": 0.9541347622871399, "start": 4131, "tag": "NAME", "value": "TIE Fighter" }, { "context": " count: 1\n }\n {\n name: '\"Howlrunner\"'\n type: 'pilot'\n count: 1\n", "end": 4240, "score": 0.9997765421867371, "start": 4230, "tag": "NAME", "value": "Howlrunner" }, { "context": " count: 1\n }\n {\n name: '\"Backstabber\"'\n type: 'pilot'\n count: 1\n", "end": 4341, "score": 0.9996261596679688, "start": 4330, "tag": "NAME", "value": "Backstabber" }, { "context": " count: 1\n }\n {\n name: '\"Winged Gundark\"'\n type: 'pilot'\n count: 1\n", "end": 4445, "score": 0.999842643737793, "start": 4431, "tag": "NAME", "value": "Winged Gundark" }, { "context": " count: 1\n }\n {\n name: 'Determination'\n type: 'upgrade'\n count: 1", "end": 4867, "score": 0.9119735956192017, "start": 4854, "tag": "NAME", "value": "Determination" }, { "context": "d Expansion Pack': [\n {\n name: 'TIE Advanced'\n type: 'ship'\n count: 1\n ", "end": 5115, "score": 0.8951435089111328, "start": 5103, "tag": "NAME", "value": "TIE Advanced" }, { "context": " count: 1\n }\n {\n name: 'Darth Vader'\n type: 'pilot'\n count: 1\n ", "end": 5213, "score": 0.9998643398284912, "start": 5202, "tag": "NAME", "value": "Darth Vader" }, { "context": " count: 1\n }\n {\n name: 'Maarek Stele'\n type: 'pilot'\n count: 1\n ", "end": 5313, "score": 0.9998880624771118, "start": 5301, "tag": "NAME", "value": "Maarek Stele" }, { "context": "g Expansion Pack': [\n {\n name: 'A-Wing'\n type: 'ship'\n count: 1\n ", "end": 6187, "score": 0.9998384714126587, "start": 6181, "tag": "NAME", "value": "A-Wing" }, { "context": " count: 1\n }\n {\n name: 'Tycho Celchu'\n type: 'pilot'\n count: 1\n ", "end": 6286, "score": 0.9998860955238342, "start": 6274, "tag": "NAME", "value": "Tycho Celchu" }, { "context": " count: 1\n }\n {\n name: 'Arvel Crynyd'\n type: 'pilot'\n count: 1\n ", "end": 6386, "score": 0.9998418688774109, "start": 6374, "tag": "NAME", "value": "Arvel Crynyd" }, { "context": " count: 1\n }\n {\n name: 'Deadeye'\n type: 'upgrade'\n count: 1", "end": 7116, "score": 0.848499596118927, "start": 7109, "tag": "NAME", "value": "Deadeye" }, { "context": " count: 1\n }\n {\n name: 'Han Solo'\n type: 'pilot'\n count: 1\n ", "end": 7356, "score": 0.9998795986175537, "start": 7348, "tag": "NAME", "value": "Han Solo" }, { "context": " count: 1\n }\n {\n name: 'Lando Calrissian'\n type: 'pilot'\n count: 1\n ", "end": 7460, "score": 0.999886691570282, "start": 7444, "tag": "NAME", "value": "Lando Calrissian" }, { "context": " count: 1\n }\n {\n name: 'Chewbacca'\n type: 'pilot'\n count: 1\n ", "end": 7557, "score": 0.9997885823249817, "start": 7548, "tag": "NAME", "value": "Chewbacca" }, { "context": " count: 1\n }\n {\n name: 'Outer Rim Smuggler'\n type: 'pilot'\n count: 1\n ", "end": 7663, "score": 0.9782282710075378, "start": 7645, "tag": "NAME", "value": "Outer Rim Smuggler" }, { "context": " count: 1\n }\n {\n name: 'Luke Skywalker'\n type: 'upgrade'\n count: 1", "end": 8293, "score": 0.9986945390701294, "start": 8279, "tag": "NAME", "value": "Luke Skywalker" }, { "context": " count: 1\n }\n {\n name: 'Nien Nunb'\n type: 'upgrade'\n count: 1", "end": 8392, "score": 0.9998714327812195, "start": 8383, "tag": "NAME", "value": "Nien Nunb" }, { "context": " count: 1\n }\n {\n name: 'Chewbacca'\n type: 'upgrade'\n count: 1", "end": 8491, "score": 0.9983500242233276, "start": 8482, "tag": "NAME", "value": "Chewbacca" }, { "context": " count: 2\n }\n {\n name: 'Millennium Falcon'\n type: 'title'\n count: 1\n ", "end": 8922, "score": 0.9949503540992737, "start": 8905, "tag": "NAME", "value": "Millennium Falcon" }, { "context": "r Expansion Pack': [\n {\n name: 'TIE Interceptor'\n type: 'ship'\n count: 1\n ", "end": 9071, "score": 0.7839670181274414, "start": 9056, "tag": "NAME", "value": "TIE Interceptor" }, { "context": " count: 1\n }\n {\n name: 'Soontir Fel'\n type: 'pilot'\n count: 1\n ", "end": 9169, "score": 0.999869167804718, "start": 9158, "tag": "NAME", "value": "Soontir Fel" }, { "context": " count: 1\n }\n {\n name: 'Turr Phennir'\n type: 'pilot'\n count: 1\n ", "end": 9269, "score": 0.9998775720596313, "start": 9257, "tag": "NAME", "value": "Turr Phennir" }, { "context": "ount: 1\n }\n {\n name: '''\"Fel's Wrath\"'''\n type: 'pilot'\n count: ", "end": 9371, "score": 0.999679684638977, "start": 9360, "tag": "NAME", "value": "Fel's Wrath" }, { "context": " count: 1\n }\n {\n name: 'Daredevil'\n type: 'upgrade'\n count: 1", "end": 9797, "score": 0.9997605085372925, "start": 9788, "tag": "NAME", "value": "Daredevil" }, { "context": " count: 1\n }\n {\n name: 'Elusiveness'\n type: 'upgrade'\n count: 1", "end": 9898, "score": 0.9867187142372131, "start": 9887, "tag": "NAME", "value": "Elusiveness" }, { "context": "I Expansion Pack': [\n {\n name: 'Firespray-31'\n type: 'ship'\n count: 1\n ", "end": 10038, "score": 0.9740340113639832, "start": 10026, "tag": "NAME", "value": "Firespray-31" }, { "context": " count: 1\n }\n {\n name: 'Boba Fett'\n type: 'pilot'\n count: 1\n ", "end": 10134, "score": 0.9998747110366821, "start": 10125, "tag": "NAME", "value": "Boba Fett" }, { "context": " count: 1\n }\n {\n name: 'Kath Scarlet'\n type: 'pilot'\n count: 1\n ", "end": 10234, "score": 0.9998455047607422, "start": 10222, "tag": "NAME", "value": "Kath Scarlet" }, { "context": " count: 1\n }\n {\n name: 'Krassis Trelix'\n type: 'pilot'\n count: 1\n ", "end": 10336, "score": 0.9998782873153687, "start": 10322, "tag": "NAME", "value": "Krassis Trelix" }, { "context": " count: 1\n }\n {\n name: 'Bounty Hunter'\n type: 'pilot'\n count: 1\n ", "end": 10437, "score": 0.9995935559272766, "start": 10424, "tag": "NAME", "value": "Bounty Hunter" }, { "context": " count: 1\n }\n {\n name: 'Homing Missiles'\n type: 'upgrade'\n count: 1", "end": 10540, "score": 0.844929039478302, "start": 10525, "tag": "NAME", "value": "Homing Missiles" }, { "context": " count: 1\n }\n {\n name: 'Assault Missiles'\n type: 'upgrade'\n count: 1", "end": 10646, "score": 0.743015468120575, "start": 10630, "tag": "NAME", "value": "Assault Missiles" }, { "context": " count: 1\n }\n {\n name: 'Ion Cannon'\n type: 'upgrade'\n count: 1", "end": 10746, "score": 0.853895902633667, "start": 10736, "tag": "NAME", "value": "Ion Cannon" }, { "context": " count: 1\n }\n {\n name: 'Heavy Laser Cannon'\n type: 'upgrade'\n count: 1", "end": 10854, "score": 0.7054955363273621, "start": 10836, "tag": "NAME", "value": "Heavy Laser Cannon" }, { "context": " count: 1\n }\n {\n name: 'Veteran Instincts'\n type: 'upgrade'\n count: 1", "end": 10961, "score": 0.7304837107658386, "start": 10944, "tag": "NAME", "value": "Veteran Instincts" }, { "context": " count: 1\n }\n {\n name: 'Expose'\n type: 'upgrade'\n count: 1", "end": 11057, "score": 0.7091546654701233, "start": 11051, "tag": "NAME", "value": "Expose" }, { "context": ": 1\n }\n {\n name: 'Seismic Charges'\n type: 'upgrade'\n count: 1", "end": 11162, "score": 0.6138384938240051, "start": 11155, "tag": "NAME", "value": "Charges" }, { "context": " count: 1\n }\n {\n name: 'Proximity Mines'\n type: 'upgrade'\n count: 1", "end": 11267, "score": 0.8772961497306824, "start": 11252, "tag": "NAME", "value": "Proximity Mines" }, { "context": " count: 1\n }\n {\n name: 'Gunner'\n type: 'upgrade'\n count: 1", "end": 11363, "score": 0.997692346572876, "start": 11357, "tag": "NAME", "value": "Gunner" }, { "context": " count: 1\n }\n {\n name: 'Mercenary Copilot'\n type: 'upgrade'\n ", "end": 11457, "score": 0.7768869400024414, "start": 11453, "tag": "NAME", "value": "Merc" }, { "context": "t: 1\n }\n {\n name: 'Mercenary Copilot'\n type: 'upgrade'\n count: 1", "end": 11470, "score": 0.7424054741859436, "start": 11459, "tag": "NAME", "value": "ary Copilot" }, { "context": " count: 2\n }\n {\n name: 'Slave I'\n type: 'title'\n count: 1", "end": 11674, "score": 0.5368678569793701, "start": 11669, "tag": "NAME", "value": "Slave" }, { "context": "g Expansion Pack': [\n {\n name: 'B-Wing'\n type: 'ship'\n count: 1\n ", "end": 11807, "score": 0.9960587024688721, "start": 11801, "tag": "NAME", "value": "B-Wing" }, { "context": " count: 1\n }\n {\n name: 'Ten Numb'\n type: 'pilot'\n count: 1\n ", "end": 11902, "score": 0.9990904927253723, "start": 11894, "tag": "NAME", "value": "Ten Numb" }, { "context": " count: 1\n }\n {\n name: 'Ibtisam'\n type: 'pilot'\n count: 1\n ", "end": 11997, "score": 0.9993717670440674, "start": 11990, "tag": "NAME", "value": "Ibtisam" }, { "context": " count: 1\n }\n {\n name: 'Dagger Squadron Pilot'\n type: 'pilot'\n count: 1\n ", "end": 12106, "score": 0.7716182470321655, "start": 12085, "tag": "NAME", "value": "Dagger Squadron Pilot" }, { "context": " count: 1\n }\n {\n name: 'Blue Squadron Pilot'\n type: 'pilot'\n ", "end": 12198, "score": 0.5679826736450195, "start": 12194, "tag": "NAME", "value": "Blue" }, { "context": "Expansion Pack\": [\n {\n name: 'HWK-290'\n type: 'ship'\n count: ", "end": 12873, "score": 0.5609631538391113, "start": 12872, "tag": "NAME", "value": "K" }, { "context": "nsion Pack\": [\n {\n name: 'HWK-290'\n type: 'ship'\n count: 1\n ", "end": 12877, "score": 0.7110232710838318, "start": 12876, "tag": "NAME", "value": "0" }, { "context": " count: 1\n }\n {\n name: 'Jan Ors'\n type: 'pilot'\n count: 1\n ", "end": 12971, "score": 0.9998511672019958, "start": 12964, "tag": "NAME", "value": "Jan Ors" }, { "context": " count: 1\n }\n {\n name: 'Kyle Katarn'\n type: 'pilot'\n count: 1\n ", "end": 13070, "score": 0.9998968839645386, "start": 13059, "tag": "NAME", "value": "Kyle Katarn" }, { "context": " count: 1\n }\n {\n name: 'Roark Garnet'\n type: 'pilot'\n count: 1\n ", "end": 13170, "score": 0.9998927116394043, "start": 13158, "tag": "NAME", "value": "Roark Garnet" }, { "context": " count: 1\n }\n {\n name: 'Recon Specialist'\n type: 'upgrade'\n ", "end": 13473, "score": 0.6131247282028198, "start": 13468, "tag": "NAME", "value": "Recon" }, { "context": " count: 1\n }\n {\n name: 'Moldy Crow'\n type: 'title'\n count: 1\n ", "end": 13584, "score": 0.9997795224189758, "start": 13574, "tag": "NAME", "value": "Moldy Crow" }, { "context": " count: 1\n }\n {\n name: 'Saboteur'\n type: 'upgrade'\n count: 1", "end": 13784, "score": 0.9471680521965027, "start": 13776, "tag": "NAME", "value": "Saboteur" }, { "context": "r Expansion Pack\": [\n {\n name: 'TIE Bomber'\n type: 'ship'\n count: 1\n ", "end": 14033, "score": 0.8354455828666687, "start": 14023, "tag": "NAME", "value": "TIE Bomber" }, { "context": " count: 1\n }\n {\n name: 'Major Rhymer'\n type: 'pilot'\n count: 1\n ", "end": 14132, "score": 0.9947042465209961, "start": 14120, "tag": "NAME", "value": "Major Rhymer" }, { "context": " count: 1\n }\n {\n name: 'Captain Jonus'\n type: 'pilot'\n count: 1\n ", "end": 14233, "score": 0.9982865452766418, "start": 14220, "tag": "NAME", "value": "Captain Jonus" }, { "context": " count: 1\n }\n {\n name: 'Gamma Squadron Pilot'\n type: 'pilot'\n ", "end": 14326, "score": 0.6054731011390686, "start": 14321, "tag": "NAME", "value": "Gamma" }, { "context": " count: 1\n }\n {\n name: 'Scimitar Squadron Pilot'\n type: 'pilot'\n ", "end": 14431, "score": 0.6836246252059937, "start": 14429, "tag": "NAME", "value": "Sc" }, { "context": " count: 1\n }\n {\n name: 'Proton Bombs'\n type: 'upgrade'\n count: 1", "end": 14552, "score": 0.9292634725570679, "start": 14540, "tag": "NAME", "value": "Proton Bombs" }, { "context": " count: 1\n }\n {\n name: 'Assault Missiles'\n type: 'upgrade'\n count: 1", "end": 14658, "score": 0.9850274324417114, "start": 14642, "tag": "NAME", "value": "Assault Missiles" }, { "context": " count: 1\n }\n {\n name: 'Seismic Charges'\n type: 'upgrade'\n count: 1", "end": 14878, "score": 0.8799153566360474, "start": 14863, "tag": "NAME", "value": "Seismic Charges" }, { "context": " count: 1\n }\n {\n name: 'Adrenaline Rush'\n type: 'upgrade'\n count: 1", "end": 14983, "score": 0.9997425079345703, "start": 14968, "tag": "NAME", "value": "Adrenaline Rush" }, { "context": " count: 1\n }\n {\n name: 'Captain Kagi'\n type: 'pilot'\n count: 1\n ", "end": 15243, "score": 0.9997551441192627, "start": 15231, "tag": "NAME", "value": "Captain Kagi" }, { "context": " count: 1\n }\n {\n name: 'Colonel Jendon'\n type: 'pilot'\n count: 1\n ", "end": 15345, "score": 0.9998736381530762, "start": 15331, "tag": "NAME", "value": "Colonel Jendon" }, { "context": " count: 1\n }\n {\n name: 'Captain Yorr'\n type: 'pilot'\n count: 1\n ", "end": 15445, "score": 0.9997941255569458, "start": 15433, "tag": "NAME", "value": "Captain Yorr" }, { "context": " count: 1\n }\n {\n name: 'Omicron Group Pilot'\n type: 'pilot'\n ", "end": 15534, "score": 0.7808864712715149, "start": 15533, "tag": "NAME", "value": "O" }, { "context": " count: 1\n }\n {\n name: 'Sensor Jammer'\n type: 'upgrade'\n count: 1", "end": 15653, "score": 0.9186296463012695, "start": 15640, "tag": "NAME", "value": "Sensor Jammer" }, { "context": " count: 1\n }\n {\n name: 'Rebel Captive'\n type: 'upgrade'\n count: 1", "end": 15756, "score": 0.7691481709480286, "start": 15743, "tag": "NAME", "value": "Rebel Captive" }, { "context": " count: 1\n }\n {\n name: 'Heavy Laser Cannon'\n type: 'upgrade'\n ", "end": 16051, "score": 0.7690691351890564, "start": 16046, "tag": "NAME", "value": "Heavy" }, { "context": " }\n {\n name: 'Heavy Laser Cannon'\n type: 'upgrade'\n count: 1", "end": 16064, "score": 0.5581018924713135, "start": 16058, "tag": "NAME", "value": "Cannon" }, { "context": " count: 1\n }\n {\n name: 'Darth Vader'\n type: 'upgrade'\n count: 1", "end": 16271, "score": 0.9948567748069763, "start": 16260, "tag": "NAME", "value": "Darth Vader" }, { "context": "r Expansion Pack\": [\n {\n name: 'Z-95 Headhunter'\n type: 'ship'\n count: 1\n ", "end": 16850, "score": 0.9400296211242676, "start": 16835, "tag": "NAME", "value": "Z-95 Headhunter" }, { "context": " count: 1\n }\n {\n name: 'Airen Cracken'\n type: 'pilot'\n count: 1\n ", "end": 16950, "score": 0.999884307384491, "start": 16937, "tag": "NAME", "value": "Airen Cracken" }, { "context": " count: 1\n }\n {\n name: 'Lieutenant Blount'\n type: 'pilot'\n count: 1\n ", "end": 17055, "score": 0.9998869895935059, "start": 17038, "tag": "NAME", "value": "Lieutenant Blount" }, { "context": " count: 1\n }\n {\n name: 'Munitions Failsafe'\n type: 'modification", "end": 17360, "score": 0.67742520570755, "start": 17359, "tag": "NAME", "value": "M" }, { "context": "ount: 1\n }\n {\n name: 'Munitions Failsafe'\n type: 'modification'\n ", "end": 17368, "score": 0.5146759748458862, "start": 17362, "tag": "NAME", "value": "itions" }, { "context": " count: 1\n }\n {\n name: 'Decoy'\n type: 'upgrade'\n count: 1", "end": 17477, "score": 0.9997832775115967, "start": 17472, "tag": "NAME", "value": "Decoy" }, { "context": " count: 1\n }\n {\n name: 'Wingman'\n type: 'upgrade'\n count: 1", "end": 17574, "score": 0.9998181462287903, "start": 17567, "tag": "NAME", "value": "Wingman" }, { "context": " count: 1\n }\n {\n name: 'Ion Pulse Missiles'\n type: 'upgrade'\n c", "end": 17675, "score": 0.7144477963447571, "start": 17664, "tag": "NAME", "value": "Ion Pulse M" }, { "context": " }\n {\n name: 'Ion Pulse Missiles'\n type: 'upgrade'\n count: 1", "end": 17682, "score": 0.6140984296798706, "start": 17678, "tag": "NAME", "value": "iles" }, { "context": " count: 1\n }\n {\n name: 'Assault Missiles'\n type: 'upgrade'\n count: 1", "end": 17788, "score": 0.9151938557624817, "start": 17772, "tag": "NAME", "value": "Assault Missiles" }, { "context": "g Expansion Pack': [\n {\n name: 'E-Wing'\n type: 'ship'\n count: 1\n ", "end": 17921, "score": 0.9998239874839783, "start": 17915, "tag": "NAME", "value": "E-Wing" }, { "context": " count: 1\n }\n {\n name: 'Corran Horn'\n type: 'pilot'\n count: 1\n ", "end": 18019, "score": 0.9998844265937805, "start": 18008, "tag": "NAME", "value": "Corran Horn" }, { "context": " count: 1\n }\n {\n name: \"Etahn A'baht\"\n type: 'pilot'\n count: 1\n ", "end": 18119, "score": 0.9998796582221985, "start": 18107, "tag": "NAME", "value": "Etahn A'baht" }, { "context": " count: 1\n }\n {\n name: 'Flechette Torpedoes'\n type: 'upgrade'\n count: 1", "end": 18850, "score": 0.9997885823249817, "start": 18831, "tag": "NAME", "value": "Flechette Torpedoes" }, { "context": "r Expansion Pack': [\n {\n name: 'TIE Defender'\n type: 'ship'\n count: 1\n ", "end": 18995, "score": 0.7690897583961487, "start": 18983, "tag": "NAME", "value": "TIE Defender" }, { "context": " count: 1\n }\n {\n name: 'Rexler Brath'\n type: 'pilot'\n count: 1\n ", "end": 19094, "score": 0.999722957611084, "start": 19082, "tag": "NAME", "value": "Rexler Brath" }, { "context": " count: 1\n }\n {\n name: 'Colonel Vessery'\n type: 'pilot'\n count: 1\n ", "end": 19197, "score": 0.9997279047966003, "start": 19182, "tag": "NAME", "value": "Colonel Vessery" }, { "context": " count: 1\n }\n {\n name: 'Munitions Failsafe'\n type: 'modification'\n cou", "end": 19518, "score": 0.8165180683135986, "start": 19500, "tag": "NAME", "value": "Munitions Failsafe" }, { "context": " count: 1\n }\n {\n name: 'Predator'\n type: 'upgrade'\n count: 1", "end": 19621, "score": 0.9628735780715942, "start": 19613, "tag": "NAME", "value": "Predator" }, { "context": " count: 1\n }\n {\n name: 'Outmaneuver'\n type: 'upgrade'\n count: 1", "end": 19722, "score": 0.982125997543335, "start": 19711, "tag": "NAME", "value": "Outmaneuver" }, { "context": " count: 1\n }\n {\n name: 'Ion Cannon'\n type: 'upgrade'\n count: 1", "end": 19822, "score": 0.9661717414855957, "start": 19812, "tag": "NAME", "value": "Ion Cannon" }, { "context": " count: 1\n }\n {\n name: 'Ion Pulse Missiles'\n type: 'upgrade'\n count: 1", "end": 19930, "score": 0.8306599855422974, "start": 19912, "tag": "NAME", "value": "Ion Pulse Missiles" }, { "context": "m Expansion Pack': [\n {\n name: 'TIE Phantom'\n type: 'ship'\n count: 1\n ", "end": 20073, "score": 0.8871397972106934, "start": 20062, "tag": "NAME", "value": "TIE Phantom" }, { "context": " count: 1\n }\n {\n name: '\"Whisper\"'\n type: 'pilot'\n count: 1\n", "end": 20168, "score": 0.9868411421775818, "start": 20161, "tag": "NAME", "value": "Whisper" }, { "context": " count: 1\n }\n {\n name: '\"Echo\"'\n type: 'pilot'\n count: 1\n", "end": 20262, "score": 0.9919689297676086, "start": 20258, "tag": "NAME", "value": "Echo" }, { "context": " count: 1\n }\n {\n name: 'Tactician'\n type: 'upgrade'\n count: 1", "end": 20686, "score": 0.8764980435371399, "start": 20677, "tag": "NAME", "value": "Tactician" }, { "context": "r Expansion Pack': [\n {\n name: 'YT-2400'\n type: 'ship'\n count:", "end": 21174, "score": 0.8111615777015686, "start": 21172, "tag": "NAME", "value": "YT" }, { "context": "nsion Pack': [\n {\n name: 'YT-2400'\n type: 'ship'\n count: 1\n ", "end": 21179, "score": 0.5906370282173157, "start": 21178, "tag": "NAME", "value": "0" }, { "context": " count: 1\n }\n {\n name: 'Dash Rendar'\n type: 'pilot'\n count: 1\n ", "end": 21277, "score": 0.9988924860954285, "start": 21266, "tag": "NAME", "value": "Dash Rendar" }, { "context": " count: 1\n }\n {\n name: 'Eaden Vrill'\n type: 'pilot'\n count: 1\n ", "end": 21376, "score": 0.9998235702514648, "start": 21365, "tag": "NAME", "value": "Eaden Vrill" }, { "context": " count: 1\n }\n {\n name: '\"Leebo\"'\n type: 'pilot'\n count: 1\n", "end": 21470, "score": 0.9997444152832031, "start": 21465, "tag": "NAME", "value": "Leebo" }, { "context": " count: 1\n }\n {\n name: 'Wild Space Fringer'\n type: 'pilot'\n count: 1\n ", "end": 21577, "score": 0.9986348152160645, "start": 21559, "tag": "NAME", "value": "Wild Space Fringer" }, { "context": " count: 1\n }\n {\n name: 'Countermeasures'\n type: 'modification'\n cou", "end": 21797, "score": 0.92637699842453, "start": 21782, "tag": "NAME", "value": "Countermeasures" }, { "context": " count: 2\n }\n {\n name: 'Outrider'\n type: 'title'\n count: 1\n ", "end": 21900, "score": 0.999457597732544, "start": 21892, "tag": "NAME", "value": "Outrider" }, { "context": " count: 1\n }\n {\n name: 'Lone Wolf'\n type: 'upgrade'\n count: 1", "end": 21997, "score": 0.9997149705886841, "start": 21988, "tag": "NAME", "value": "Lone Wolf" }, { "context": " count: 1\n }\n {\n name: '\"Leebo\"'\n type: 'upgrade'\n count: ", "end": 22093, "score": 0.9997517466545105, "start": 22088, "tag": "NAME", "value": "Leebo" }, { "context": " count: 1\n }\n {\n name: 'Lando Calrissian'\n type: 'upgrade'\n count: 1", "end": 22200, "score": 0.9998839497566223, "start": 22184, "tag": "NAME", "value": "Lando Calrissian" }, { "context": " count: 1\n }\n {\n name: 'Stay On Target'\n type: 'upgrade'\n ", "end": 22294, "score": 0.7490811944007874, "start": 22290, "tag": "NAME", "value": "Stay" }, { "context": " count: 1\n }\n {\n name: 'Dash Rendar'\n type: 'upgrade'\n count: 1", "end": 22405, "score": 0.9989874958992004, "start": 22394, "tag": "NAME", "value": "Dash Rendar" }, { "context": " count: 1\n }\n {\n name: 'Gunner'\n type: 'upgrade'\n count: 1", "end": 22501, "score": 0.9995249509811401, "start": 22495, "tag": "NAME", "value": "Gunner" }, { "context": " count: 1\n }\n {\n name: 'Mercenary Copilot'\n type: 'upgrade'\n count: 1", "end": 22608, "score": 0.9925405979156494, "start": 22591, "tag": "NAME", "value": "Mercenary Copilot" }, { "context": " count: 1\n }\n {\n name: 'Proton Rockets'\n type: 'upgrade'\n count: 1", "end": 22712, "score": 0.9950169324874878, "start": 22698, "tag": "NAME", "value": "Proton Rockets" }, { "context": " count: 1\n }\n {\n name: 'Heavy Laser Cannon'\n type: 'upgrade'\n count: 1", "end": 22820, "score": 0.9073722958564758, "start": 22802, "tag": "NAME", "value": "Heavy Laser Cannon" }, { "context": " count: 1\n }\n {\n name: 'Captain Oicunn'\n type: 'pilot'\n count: 1\n ", "end": 23072, "score": 0.9998132586479187, "start": 23058, "tag": "NAME", "value": "Captain Oicunn" }, { "context": " count: 1\n }\n {\n name: 'Rear Admiral Chiraneau'\n type: 'pilot'\n count: 1\n ", "end": 23182, "score": 0.9998750686645508, "start": 23160, "tag": "NAME", "value": "Rear Admiral Chiraneau" }, { "context": " count: 1\n }\n {\n name: 'Commander Kenkirk'\n type: 'pilot'\n count: 1\n ", "end": 23287, "score": 0.9998524785041809, "start": 23270, "tag": "NAME", "value": "Commander Kenkirk" }, { "context": " count: 1\n }\n {\n name: 'Patrol Leader'\n type: 'pilot'\n count: 1\n ", "end": 23388, "score": 0.9941772818565369, "start": 23375, "tag": "NAME", "value": "Patrol Leader" }, { "context": " count: 1\n }\n {\n name: 'Ruthlessness'\n type: 'upgrade'\n count: 2", "end": 23488, "score": 0.9998236894607544, "start": 23476, "tag": "NAME", "value": "Ruthlessness" }, { "context": " count: 2\n }\n {\n name: 'Dauntless'\n type: 'title'\n count: 1\n ", "end": 23587, "score": 0.9998261332511902, "start": 23578, "tag": "NAME", "value": "Dauntless" }, { "context": " count: 1\n }\n {\n name: 'Ysanne Isard'\n type: 'upgrade'\n count: 1", "end": 23687, "score": 0.9998823404312134, "start": 23675, "tag": "NAME", "value": "Ysanne Isard" }, { "context": " count: 1\n }\n {\n name: 'Moff Jerjerrod'\n type: 'upgrade'\n count: 1", "end": 23791, "score": 0.999883770942688, "start": 23777, "tag": "NAME", "value": "Moff Jerjerrod" }, { "context": " count: 1\n }\n {\n name: 'Intimidation'\n type: 'upgrade'\n count: 1", "end": 23893, "score": 0.998902440071106, "start": 23881, "tag": "NAME", "value": "Intimidation" }, { "context": " count: 1\n }\n {\n name: 'Tactical Jammer'\n type: 'modification'\n cou", "end": 23998, "score": 0.9997212290763855, "start": 23983, "tag": "NAME", "value": "Tactical Jammer" }, { "context": " count: 2\n }\n {\n name: 'Proton Bombs'\n type: 'upgrade'\n count: 1", "end": 24105, "score": 0.9998361468315125, "start": 24093, "tag": "NAME", "value": "Proton Bombs" }, { "context": " count: 1\n }\n {\n name: 'Mara Jade'\n type: 'upgrade'\n count: 1", "end": 24204, "score": 0.9998722672462463, "start": 24195, "tag": "NAME", "value": "Mara Jade" }, { "context": " count: 1\n }\n {\n name: 'Fleet Officer'\n type: 'upgrade'\n count: 1", "end": 24307, "score": 0.915902853012085, "start": 24294, "tag": "NAME", "value": "Fleet Officer" }, { "context": " count: 1\n }\n {\n name: 'Ion Torpedoes'\n type: 'upgrade'\n count: 2", "end": 24410, "score": 0.9948805570602417, "start": 24397, "tag": "NAME", "value": "Ion Torpedoes" }, { "context": "s Expansion Pack': [\n {\n name: 'TIE Interceptor'\n type: 'ship'\n count: 2\n ", "end": 24559, "score": 0.9724907875061035, "start": 24544, "tag": "NAME", "value": "TIE Interceptor" }, { "context": " count: 2\n }\n {\n name: 'Carnor Jax'\n type: 'pilot'\n count: 1\n ", "end": 24656, "score": 0.9998779296875, "start": 24646, "tag": "NAME", "value": "Carnor Jax" }, { "context": " count: 1\n }\n {\n name: 'Kir Kanos'\n type: 'pilot'\n count: 1\n ", "end": 24753, "score": 0.999869167804718, "start": 24744, "tag": "NAME", "value": "Kir Kanos" }, { "context": " count: 2\n }\n {\n name: 'Tetran Cowall'\n type: 'pilot'\n count: 1\n ", "end": 24959, "score": 0.9998792409896851, "start": 24946, "tag": "NAME", "value": "Tetran Cowall" }, { "context": " count: 1\n }\n {\n name: 'Lieutenant Lorrir'\n type: 'pilot'\n count: 1\n ", "end": 25064, "score": 0.9998579621315002, "start": 25047, "tag": "NAME", "value": "Lieutenant Lorrir" }, { "context": "s Expansion Pack': [\n {\n name: 'A-Wing'\n type: 'ship'\n count: 1\n ", "end": 25944, "score": 0.9811991453170776, "start": 25938, "tag": "NAME", "value": "A-Wing" }, { "context": " count: 1\n }\n {\n name: 'B-Wing'\n type: 'ship'\n count: 1\n ", "end": 26037, "score": 0.9958579540252686, "start": 26031, "tag": "NAME", "value": "B-Wing" }, { "context": " count: 1\n }\n {\n name: 'Jake Farrell'\n type: 'pilot'\n count: 1\n ", "end": 26136, "score": 0.9998513460159302, "start": 26124, "tag": "NAME", "value": "Jake Farrell" }, { "context": " count: 1\n }\n {\n name: 'Gemmer Sojan'\n type: 'pilot'\n count: 1\n ", "end": 26236, "score": 0.9998786449432373, "start": 26224, "tag": "NAME", "value": "Gemmer Sojan" }, { "context": " count: 1\n }\n {\n name: 'Keyan Farlander'\n type: 'pilot'\n count: 1\n ", "end": 26550, "score": 0.9998753666877747, "start": 26535, "tag": "NAME", "value": "Keyan Farlander" }, { "context": " count: 1\n }\n {\n name: 'Nera Dantels'\n type: 'pilot'\n count: 1\n ", "end": 26650, "score": 0.9998632669448853, "start": 26638, "tag": "NAME", "value": "Nera Dantels" }, { "context": "count: 1\n }\n {\n name: 'Chardaan Refit'\n type: 'upgrade'\n ", "end": 26959, "score": 0.5220643877983093, "start": 26956, "tag": "NAME", "value": "ard" }, { "context": " count: 2\n }\n {\n name: 'Kyle Katarn'\n type: 'upgrade'\n count: 1", "end": 27487, "score": 0.9998632669448853, "start": 27476, "tag": "NAME", "value": "Kyle Katarn" }, { "context": " count: 1\n }\n {\n name: 'Jan Ors'\n type: 'upgrade'\n count: 1", "end": 27584, "score": 0.9998762011528015, "start": 27577, "tag": "NAME", "value": "Jan Ors" }, { "context": "t Expansion Pack': [\n {\n name: 'X-Wing'\n type: 'ship'\n count: 1\n ", "end": 27726, "score": 0.989816427230835, "start": 27720, "tag": "NAME", "value": "X-Wing" }, { "context": " count: 1\n }\n {\n name: 'Wes Janson'\n type: 'pilot'\n count: 1\n ", "end": 28042, "score": 0.9998701214790344, "start": 28032, "tag": "NAME", "value": "Wes Janson" }, { "context": " count: 1\n }\n {\n name: 'Jek Porkins'\n type: 'pilot'\n count: 1\n ", "end": 28141, "score": 0.999856173992157, "start": 28130, "tag": "NAME", "value": "Jek Porkins" }, { "context": " count: 1\n }\n {\n name: '\"Hobbie\" Klivian'\n type: 'pilot'\n co", "end": 28236, "score": 0.981188952922821, "start": 28230, "tag": "NAME", "value": "Hobbie" }, { "context": " 1\n }\n {\n name: '\"Hobbie\" Klivian'\n type: 'pilot'\n count: 1\n ", "end": 28245, "score": 0.9994855523109436, "start": 28238, "tag": "NAME", "value": "Klivian" }, { "context": " count: 1\n }\n {\n name: 'Tarn Mison'\n type: 'pilot'\n count: 1\n ", "end": 28343, "score": 0.9998645782470703, "start": 28333, "tag": "NAME", "value": "Tarn Mison" }, { "context": "nt: 1\n }\n {\n name: 'Red Squadron Pilot'\n type: 'pilot'\n c", "end": 28440, "score": 0.6504037976264954, "start": 28436, "tag": "NAME", "value": "quad" }, { "context": " }\n {\n name: 'Red Squadron Pilot'\n type: 'pilot'\n count: 1\n ", "end": 28449, "score": 0.6998727321624756, "start": 28444, "tag": "NAME", "value": "Pilot" }, { "context": " count: 1\n }\n {\n name: 'Rookie Pilot'\n type: 'pilot'\n count: 1\n ", "end": 28549, "score": 0.9873076677322388, "start": 28537, "tag": "NAME", "value": "Rookie Pilot" }, { "context": "unt: 1\n }\n {\n name: 'Dutyfree'\n type: 'title'\n count: 1\n ", "end": 28645, "score": 0.7698737978935242, "start": 28641, "tag": "NAME", "value": "free" }, { "context": " count: 1\n }\n {\n name: 'Bright Hope'\n type: 'title'\n count: 1\n ", "end": 28845, "score": 0.9991950988769531, "start": 28834, "tag": "NAME", "value": "Bright Hope" }, { "context": " count: 1\n }\n {\n name: 'Flechette Torpedoes'\n type: 'upgrade'\n count: 3", "end": 29251, "score": 0.8139654994010925, "start": 29232, "tag": "NAME", "value": "Flechette Torpedoes" }, { "context": " count: 1\n }\n {\n name: 'Carlist Rieekan'\n type: 'upgrade'\n count: 1", "end": 29673, "score": 0.999904453754425, "start": 29658, "tag": "NAME", "value": "Carlist Rieekan" }, { "context": " count: 1\n }\n {\n name: 'Tibanna Gas Supplies'\n type: 'upgrade'\n count: 1", "end": 30397, "score": 0.999859631061554, "start": 30377, "tag": "NAME", "value": "Tibanna Gas Supplies" }, { "context": " count: 1\n }\n {\n name: 'Jan Dodonna'\n type: 'upgrade'\n count: 1", "end": 30498, "score": 0.9998921155929565, "start": 30487, "tag": "NAME", "value": "Jan Dodonna" }, { "context": " count: 1\n }\n {\n name: 'Toryn Farr'\n type: 'upgrade'\n count: 1", "end": 30598, "score": 0.9998995661735535, "start": 30588, "tag": "NAME", "value": "Toryn Farr" }, { "context": "count: 1\n # }\n {\n name: \"Jaina's Light\"\n type: 'title'\n count: 1\n ", "end": 31635, "score": 0.9994668960571289, "start": 31622, "tag": "NAME", "value": "Jaina's Light" }, { "context": " count: 1\n }\n {\n name: \"Dodonna's Pride\"\n type: 'title'\n count: 1\n ", "end": 31738, "score": 0.9987568855285645, "start": 31723, "tag": "NAME", "value": "Dodonna's Pride" }, { "context": " count: 1\n }\n {\n name: 'Tantive IV'\n type: 'title'\n count: 1\n ", "end": 31836, "score": 0.9981685876846313, "start": 31826, "tag": "NAME", "value": "Tantive IV" }, { "context": " count: 1\n }\n {\n name: 'Han Solo'\n type: 'upgrade'\n count: 1", "end": 32045, "score": 0.9954075217247009, "start": 32037, "tag": "NAME", "value": "Han Solo" }, { "context": " count: 1\n }\n {\n name: 'C-3PO'\n type: 'upgrade'\n coun", "end": 32136, "score": 0.5987476110458374, "start": 32135, "tag": "NAME", "value": "C" }, { "context": "ount: 1\n }\n {\n name: 'C-3PO'\n type: 'upgrade'\n count: 1", "end": 32140, "score": 0.6975762844085693, "start": 32138, "tag": "NAME", "value": "PO" }, { "context": " count: 1\n }\n {\n name: 'Engine Booster'\n type: 'upgrade'\n count: 1", "end": 32244, "score": 0.7261530756950378, "start": 32230, "tag": "NAME", "value": "Engine Booster" }, { "context": " count: 1\n }\n {\n name: 'Comms Booster'\n type: 'upgrade'\n count: 2", "end": 32347, "score": 0.9038687944412231, "start": 32334, "tag": "NAME", "value": "Comms Booster" }, { "context": " count: 1\n }\n {\n name: 'Gunnery Team'\n type: 'upgrade'\n count: 1", "end": 32555, "score": 0.899224042892456, "start": 32543, "tag": "NAME", "value": "Gunnery Team" }, { "context": " count: 1\n }\n {\n name: 'Ionization Reactor'\n type: 'upgrade'\n count: 1", "end": 32663, "score": 0.966256856918335, "start": 32645, "tag": "NAME", "value": "Ionization Reactor" }, { "context": " count: 1\n }\n {\n name: 'Leia Organa'\n type: 'upgrade'\n count: 1", "end": 32764, "score": 0.9997085332870483, "start": 32753, "tag": "NAME", "value": "Leia Organa" }, { "context": " count: 1\n }\n {\n name: 'R2-D2 (Crew)'\n type: 'upgrade'\n cou", "end": 32859, "score": 0.8550530076026917, "start": 32854, "tag": "NAME", "value": "R2-D2" }, { "context": ": 1\n }\n {\n name: 'R2-D2 (Crew)'\n type: 'upgrade'\n count: ", "end": 32865, "score": 0.8824753761291504, "start": 32861, "tag": "NAME", "value": "Crew" }, { "context": " count: 1\n }\n {\n name: 'Sensor Team'\n type: 'upgrade'\n count: 1", "end": 32967, "score": 0.8080542087554932, "start": 32956, "tag": "NAME", "value": "Sensor Team" }, { "context": " count: 1\n }\n {\n name: 'Targeting Coordinator'\n type: 'upgrade'\n count: 1", "end": 33078, "score": 0.841965913772583, "start": 33057, "tag": "NAME", "value": "Targeting Coordinator" }, { "context": " count: 1\n }\n {\n name: 'Tibanna Gas Supplies'\n type: 'upgrade'\n count: 1", "end": 33188, "score": 0.9994422197341919, "start": 33168, "tag": "NAME", "value": "Tibanna Gas Supplies" }, { "context": " count: 1\n }\n {\n name: 'Raymus Antilles'\n type: 'upgrade'\n count: 1", "end": 33293, "score": 0.9995870590209961, "start": 33278, "tag": "NAME", "value": "Raymus Antilles" }, { "context": " count: 1\n }\n {\n name: 'Quad Laser Cannons'\n type: 'upgrade'\n count: 3", "end": 33401, "score": 0.9758502840995789, "start": 33383, "tag": "NAME", "value": "Quad Laser Cannons" }, { "context": "r Expansion Pack': [\n {\n name: 'StarViper'\n type: 'ship'\n count: 1\n ", "end": 33648, "score": 0.982495129108429, "start": 33639, "tag": "NAME", "value": "StarViper" }, { "context": " count: 1\n }\n {\n name: 'Prince Xizor'\n type: 'pilot'\n count: 1\n ", "end": 33747, "score": 0.9998694658279419, "start": 33735, "tag": "NAME", "value": "Prince Xizor" }, { "context": " count: 1\n }\n {\n name: 'Guri'\n type: 'pilot'\n count: 1\n ", "end": 33839, "score": 0.9997965097427368, "start": 33835, "tag": "NAME", "value": "Guri" }, { "context": " count: 1\n }\n {\n name: 'Black Sun Vigo'\n type: 'pilot'\n count: 1\n ", "end": 33941, "score": 0.791115939617157, "start": 33927, "tag": "NAME", "value": "Black Sun Vigo" }, { "context": " count: 1\n }\n {\n name: 'Black Sun Enforcer'\n type: 'pilot'\n ", "end": 34034, "score": 0.768164873123169, "start": 34029, "tag": "NAME", "value": "Black" }, { "context": "1\n }\n {\n name: 'Black Sun Enforcer'\n type: 'pilot'\n count: 1\n ", "end": 34047, "score": 0.5933842062950134, "start": 34039, "tag": "NAME", "value": "Enforcer" }, { "context": " count: 1\n }\n {\n name: 'Virago'\n type: 'title'\n count: 1\n ", "end": 34141, "score": 0.9997856020927429, "start": 34135, "tag": "NAME", "value": "Virago" }, { "context": " count: 1\n }\n {\n name: 'Bodyguard'\n type: 'upgrade'\n count: 1", "end": 34238, "score": 0.9496352672576904, "start": 34229, "tag": "NAME", "value": "Bodyguard" }, { "context": " count: 1\n }\n {\n name: 'Accuracy Corrector'\n type: 'upgrade'\n count: 1", "end": 34346, "score": 0.9297869205474854, "start": 34328, "tag": "NAME", "value": "Accuracy Corrector" }, { "context": " count: 1\n }\n {\n name: 'Inertial Dampeners'\n type: 'upgrade'\n count: 1", "end": 34454, "score": 0.704624354839325, "start": 34436, "tag": "NAME", "value": "Inertial Dampeners" }, { "context": " count: 1\n }\n {\n name: 'Autothrusters'\n type: 'modification'\n cou", "end": 34557, "score": 0.9667242169380188, "start": 34544, "tag": "NAME", "value": "Autothrusters" }, { "context": " count: 2\n }\n {\n name: 'Calculation'\n type: 'upgrade'\n count: 1", "end": 34663, "score": 0.8351225852966309, "start": 34652, "tag": "NAME", "value": "Calculation" }, { "context": " count: 1\n }\n {\n name: 'Ion Torpedoes'\n type: 'upgrade'\n count: 1", "end": 34766, "score": 0.9432917833328247, "start": 34753, "tag": "NAME", "value": "Ion Torpedoes" }, { "context": " count: 1\n }\n {\n name: 'Hull Upgrade'\n type: 'modification'\n cou", "end": 34868, "score": 0.8517224788665771, "start": 34856, "tag": "NAME", "value": "Hull Upgrade" }, { "context": "r Expansion Pack\": [\n {\n name: 'M3-A Interceptor'\n type: 'ship'\n ", "end": 35011, "score": 0.6964259743690491, "start": 35010, "tag": "NAME", "value": "M" }, { "context": "xpansion Pack\": [\n {\n name: 'M3-A Interceptor'\n type: 'ship'\n count: 1\n ", "end": 35026, "score": 0.6596398949623108, "start": 35013, "tag": "NAME", "value": "A Interceptor" }, { "context": " count: 1\n }\n {\n name: 'Serissu'\n type: 'pilot'\n count: 1\n ", "end": 35120, "score": 0.9995064735412598, "start": 35113, "tag": "NAME", "value": "Serissu" }, { "context": " count: 1\n }\n {\n name: \"Laetin A'shera\"\n type: 'pilot'\n count: 1\n ", "end": 35222, "score": 0.9998631477355957, "start": 35208, "tag": "NAME", "value": "Laetin A'shera" }, { "context": " count: 1\n }\n {\n name: \"Tansarii Point Veteran\"\n type: 'pilot'\n count: 1\n ", "end": 35332, "score": 0.997606635093689, "start": 35310, "tag": "NAME", "value": "Tansarii Point Veteran" }, { "context": " count: 1\n }\n {\n name: \"Cartel Spacer\"\n type: 'pilot'\n count: 1\n ", "end": 35433, "score": 0.9952113628387451, "start": 35420, "tag": "NAME", "value": "Cartel Spacer" }, { "context": ":(\n }\n {\n name: '\"Heavy Scyk\" Interceptor (Torpedo)'\n type: 'title", "end": 35957, "score": 0.6134443283081055, "start": 35955, "tag": "NAME", "value": "cy" }, { "context": "special :(\n }\n {\n name: 'Flechette Cannon'\n type: 'upgrade'\n count: 1", "end": 36098, "score": 0.9990412592887878, "start": 36082, "tag": "NAME", "value": "Flechette Cannon" }, { "context": " count: 1\n }\n {\n name: 'Ion Cannon'\n type: 'upgrade'\n count: 1", "end": 36198, "score": 0.9938614964485168, "start": 36188, "tag": "NAME", "value": "Ion Cannon" }, { "context": " count: 1\n }\n {\n name: '\"Mangler\" Cannon'\n type: 'upgrade'\n c", "end": 36296, "score": 0.8839826583862305, "start": 36289, "tag": "NAME", "value": "Mangler" }, { "context": "1\n }\n {\n name: '\"Mangler\" Cannon'\n type: 'upgrade'\n count: 1", "end": 36304, "score": 0.9668159484863281, "start": 36298, "tag": "NAME", "value": "Cannon" }, { "context": "0 Expansion Pack\": [\n {\n name: 'Aggressor'\n type: 'ship'\n coun", "end": 36543, "score": 0.747381329536438, "start": 36541, "tag": "NAME", "value": "Ag" }, { "context": " count: 1\n }\n {\n name: 'Accuracy Corrector'\n type: 'upgrade'\n count: 1", "end": 37126, "score": 0.7970108985900879, "start": 37108, "tag": "NAME", "value": "Accuracy Corrector" }, { "context": " count: 1\n }\n {\n name: 'Autoblaster'\n type: 'upgrade'\n count: 1", "end": 37227, "score": 0.8413980007171631, "start": 37216, "tag": "NAME", "value": "Autoblaster" }, { "context": " count: 1\n }\n {\n name: '\"Mangler\" Cannon'\n type: 'upgrade'\n c", "end": 37325, "score": 0.8770900964736938, "start": 37318, "tag": "NAME", "value": "Mangler" }, { "context": "1\n }\n {\n name: '\"Mangler\" Cannon'\n type: 'upgrade'\n count: 1", "end": 37333, "score": 0.9639053344726562, "start": 37327, "tag": "NAME", "value": "Cannon" }, { "context": " count: 1\n }\n {\n name: 'Proximity Mines'\n type: 'upgrade'\n ", "end": 37427, "score": 0.8335429430007935, "start": 37423, "tag": "NAME", "value": "Prox" }, { "context": " }\n {\n name: 'Proximity Mines'\n type: 'upgrade'\n count: 1", "end": 37438, "score": 0.8151594400405884, "start": 37434, "tag": "NAME", "value": "ines" }, { "context": " count: 1\n }\n {\n name: 'Seismic Charges'\n type: 'upgrade'\n ", "end": 37530, "score": 0.560525119304657, "start": 37528, "tag": "NAME", "value": "Se" }, { "context": " count: 2\n }\n {\n name: '\"Hot Shot\" Blaster'\n type: 'upgrade'\n ", "end": 37848, "score": 0.5607370734214783, "start": 37845, "tag": "NAME", "value": "Hot" }, { "context": " count: 1\n }\n {\n name: 'Inertial Dampeners'\n type: 'upgrade'\n count: 1", "end": 37970, "score": 0.9754589200019836, "start": 37952, "tag": "NAME", "value": "Inertial Dampeners" }, { "context": "d Expansion Pack\": [\n {\n name: 'Z-95 Headhunter'\n type: 'ship'\n count: 2\n ", "end": 38117, "score": 0.855666995048523, "start": 38102, "tag": "NAME", "value": "Z-95 Headhunter" }, { "context": " count: 2\n }\n {\n name: 'Y-Wing'\n type: 'ship'\n count: 1\n ", "end": 38210, "score": 0.9911407828330994, "start": 38204, "tag": "NAME", "value": "Y-Wing" }, { "context": " count: 1\n }\n {\n name: \"N'Dru Suhlak\"\n type: 'pilot'\n count: 1\n ", "end": 38309, "score": 0.9998788833618164, "start": 38297, "tag": "NAME", "value": "N'Dru Suhlak" }, { "context": " count: 1\n }\n {\n name: \"Kaa'to Leeachos\"\n type: 'pilot'\n count: 1\n ", "end": 38412, "score": 0.9998884797096252, "start": 38397, "tag": "NAME", "value": "Kaa'to Leeachos" }, { "context": " count: 1\n }\n {\n name: \"Black Sun Soldier\"\n type: 'pilot'\n ", "end": 38505, "score": 0.7951367497444153, "start": 38500, "tag": "NAME", "value": "Black" }, { "context": "1\n }\n {\n name: \"Black Sun Soldier\"\n type: 'pilot'\n count: 2\n ", "end": 38517, "score": 0.5612885355949402, "start": 38510, "tag": "NAME", "value": "Soldier" }, { "context": " count: 2\n }\n {\n name: \"Binayre Pirate\"\n type: 'pilot'\n count: 2\n ", "end": 38619, "score": 0.9998655319213867, "start": 38605, "tag": "NAME", "value": "Binayre Pirate" }, { "context": " count: 2\n }\n {\n name: \"Kavil\"\n type: 'pilot'\n count: 1\n ", "end": 38712, "score": 0.9998605847358704, "start": 38707, "tag": "NAME", "value": "Kavil" }, { "context": " count: 1\n }\n {\n name: \"Drea Renthal\"\n type: 'pilot'\n count: 1\n ", "end": 38812, "score": 0.9998458623886108, "start": 38800, "tag": "NAME", "value": "Drea Renthal" }, { "context": " count: 1\n }\n {\n name: \"Hired Gun\"\n type: 'pilot'\n count: 2\n ", "end": 38909, "score": 0.9998738169670105, "start": 38900, "tag": "NAME", "value": "Hired Gun" }, { "context": " count: 2\n }\n {\n name: \"Syndicate Thug\"\n type: 'pilot'\n count: 2\n ", "end": 39011, "score": 0.9998728632926941, "start": 38997, "tag": "NAME", "value": "Syndicate Thug" }, { "context": " count: 2\n }\n {\n name: \"Boba Fett (Scum)\"\n type: 'pilot'\n cou", "end": 39108, "score": 0.9998351335525513, "start": 39099, "tag": "NAME", "value": "Boba Fett" }, { "context": " count: 1\n }\n {\n name: \"Kath Scarlet (Scum)\"\n type: 'pilot'\n cou", "end": 39215, "score": 0.999838650226593, "start": 39203, "tag": "NAME", "value": "Kath Scarlet" }, { "context": " count: 1\n }\n {\n name: \"Emon Azzameen\"\n type: 'pilot'\n count: 1\n ", "end": 39323, "score": 0.9998623728752136, "start": 39310, "tag": "NAME", "value": "Emon Azzameen" }, { "context": " count: 1\n }\n {\n name: \"Mandalorian Mercenary\"\n type: 'pilot'\n count: 1\n ", "end": 39432, "score": 0.9998499155044556, "start": 39411, "tag": "NAME", "value": "Mandalorian Mercenary" }, { "context": " count: 1\n }\n {\n name: \"Dace Bonearm\"\n type: 'pilot'\n count: 1\n ", "end": 39532, "score": 0.9998747110366821, "start": 39520, "tag": "NAME", "value": "Dace Bonearm" }, { "context": " count: 1\n }\n {\n name: \"Palob Godalhi\"\n type: 'pilot'\n count: 1\n ", "end": 39633, "score": 0.9998728036880493, "start": 39620, "tag": "NAME", "value": "Palob Godalhi" }, { "context": " count: 1\n }\n {\n name: \"Torkil Mux\"\n type: 'pilot'\n count: 1\n ", "end": 39731, "score": 0.999834418296814, "start": 39721, "tag": "NAME", "value": "Torkil Mux" }, { "context": " count: 1\n }\n {\n name: \"Spice Runner\"\n type: 'pilot'\n count: 1\n ", "end": 39831, "score": 0.9987235069274902, "start": 39819, "tag": "NAME", "value": "Spice Runner" }, { "context": " count: 1\n }\n {\n name: \"Greedo\"\n type: 'upgrade'\n count: 1", "end": 39925, "score": 0.9998518824577332, "start": 39919, "tag": "NAME", "value": "Greedo" }, { "context": " count: 1\n }\n {\n name: '\"Genius\"'\n type: 'upgrade'\n count: ", "end": 40536, "score": 0.7392443418502808, "start": 40530, "tag": "NAME", "value": "Genius" }, { "context": " count: 2\n }\n {\n name: \"Andrasta\"\n type: 'title'\n count: 1\n ", "end": 41053, "score": 0.9979324340820312, "start": 41045, "tag": "NAME", "value": "Andrasta" }, { "context": " count: 1\n }\n {\n name: 'Bossk'\n type: 'pilot'\n count: 1\n ", "end": 41391, "score": 0.9993171095848083, "start": 41386, "tag": "NAME", "value": "Bossk" }, { "context": " count: 1\n }\n {\n name: 'Moralo Eval'\n type: 'pilot'\n count: 1\n ", "end": 41490, "score": 0.9998299479484558, "start": 41479, "tag": "NAME", "value": "Moralo Eval" }, { "context": " count: 1\n }\n {\n name: 'Latts Razzi'\n type: 'pilot'\n count: 1\n ", "end": 41589, "score": 0.9998872876167297, "start": 41578, "tag": "NAME", "value": "Latts Razzi" }, { "context": " count: 1\n }\n {\n name: 'Trandoshan Slaver'\n type: 'pilot'\n count: 1\n ", "end": 41694, "score": 0.9998911023139954, "start": 41677, "tag": "NAME", "value": "Trandoshan Slaver" }, { "context": " count: 1\n }\n {\n name: 'Lone Wolf'\n type: 'upgrade'\n count: 1", "end": 41791, "score": 0.9822618365287781, "start": 41782, "tag": "NAME", "value": "Lone Wolf" }, { "context": " count: 1\n }\n {\n name: 'Heavy Laser Cannon'\n type: 'upgrade'\n count: 1", "end": 42103, "score": 0.799631655216217, "start": 42085, "tag": "NAME", "value": "Heavy Laser Cannon" }, { "context": " count: 1\n }\n {\n name: 'Bossk'\n type: 'upgrade'\n count: 1", "end": 42198, "score": 0.9503566026687622, "start": 42193, "tag": "NAME", "value": "Bossk" }, { "context": " count: 1\n }\n {\n name: 'Glitterstim'\n type: 'upgrade'\n count: 1", "end": 42507, "score": 0.9519056677818298, "start": 42496, "tag": "NAME", "value": "Glitterstim" }, { "context": " count: 1\n }\n {\n name: 'Engine Upgrade'\n type: 'modification'\n cou", "end": 42611, "score": 0.817336916923523, "start": 42597, "tag": "NAME", "value": "Engine Upgrade" }, { "context": " count: 1\n }\n {\n name: 'Ion Projector'\n type: 'modification'\n cou", "end": 42719, "score": 0.9097216129302979, "start": 42706, "tag": "NAME", "value": "Ion Projector" }, { "context": " count: 2\n }\n {\n name: 'Maneuvering Fins'\n type: 'modification'\n cou", "end": 42830, "score": 0.8857171535491943, "start": 42814, "tag": "NAME", "value": "Maneuvering Fins" }, { "context": " count: 1\n }\n {\n name: \"Hound's Tooth\"\n type: 'title'\n count: 1\n ", "end": 42938, "score": 0.998988151550293, "start": 42925, "tag": "NAME", "value": "Hound's Tooth" }, { "context": "r Expansion Pack': [\n {\n name: 'Kihraxz Fighter'\n type: 'ship'\n count: 1\n ", "end": 43087, "score": 0.9995415806770325, "start": 43072, "tag": "NAME", "value": "Kihraxz Fighter" }, { "context": " count: 1\n }\n {\n name: 'Talonbane Cobra'\n type: 'pilot'\n count: 1\n ", "end": 43189, "score": 0.9998245239257812, "start": 43174, "tag": "NAME", "value": "Talonbane Cobra" }, { "context": " count: 1\n }\n {\n name: 'Graz the Hunter'\n type: 'pilot'\n count: 1\n ", "end": 43292, "score": 0.9997473955154419, "start": 43277, "tag": "NAME", "value": "Graz the Hunter" }, { "context": " count: 1\n }\n {\n name: 'Black Sun Ace'\n type: 'pilot'\n count: 1\n ", "end": 43393, "score": 0.9994264245033264, "start": 43380, "tag": "NAME", "value": "Black Sun Ace" }, { "context": " count: 1\n }\n {\n name: 'Cartel Marauder'\n type: 'pilot'\n count: 1\n ", "end": 43496, "score": 0.9998408555984497, "start": 43481, "tag": "NAME", "value": "Cartel Marauder" }, { "context": " count: 1\n }\n {\n name: 'Crack Shot'\n type: 'upgrade'\n count: 1", "end": 43594, "score": 0.99733567237854, "start": 43584, "tag": "NAME", "value": "Crack Shot" }, { "context": " count: 1\n }\n {\n name: 'Lightning Reflexes'\n type: 'upgrade'\n count: 1", "end": 43702, "score": 0.9919215440750122, "start": 43684, "tag": "NAME", "value": "Lightning Reflexes" }, { "context": " count: 1\n }\n {\n name: 'Predator'\n type: 'upgrade'\n count: 1", "end": 43800, "score": 0.9954947829246521, "start": 43792, "tag": "NAME", "value": "Predator" }, { "context": " count: 1\n }\n {\n name: 'Homing Missiles'\n type: 'upgrade'\n count: 1", "end": 43905, "score": 0.9927471280097961, "start": 43890, "tag": "NAME", "value": "Homing Missiles" }, { "context": " count: 1\n }\n {\n name: 'Glitterstim'\n type: 'upgrade'\n count: 1", "end": 44006, "score": 0.9745341539382935, "start": 43995, "tag": "NAME", "value": "Glitterstim" }, { "context": "g Expansion Pack': [\n {\n name: 'K-Wing'\n type: 'ship'\n count: 1\n ", "end": 44139, "score": 0.995331883430481, "start": 44133, "tag": "NAME", "value": "K-Wing" }, { "context": " count: 1\n }\n {\n name: 'Miranda Doni'\n type: 'pilot'\n count: 1\n ", "end": 44238, "score": 0.9998849630355835, "start": 44226, "tag": "NAME", "value": "Miranda Doni" }, { "context": " count: 1\n }\n {\n name: 'Esege Tuketu'\n type: 'pilot'\n count: 1\n ", "end": 44338, "score": 0.9998558163642883, "start": 44326, "tag": "NAME", "value": "Esege Tuketu" }, { "context": " count: 1\n }\n {\n name: 'Bombardier'\n type: 'upgrade'\n count: 1", "end": 44983, "score": 0.9533405900001526, "start": 44973, "tag": "NAME", "value": "Bombardier" }, { "context": " count: 1\n }\n {\n name: 'Conner Net'\n type: 'upgrade'\n count: 1", "end": 45083, "score": 0.8096234202384949, "start": 45073, "tag": "NAME", "value": "Conner Net" }, { "context": " count: 1\n }\n {\n name: 'Ion Bombs'\n type: 'upgrade'\n count: 1", "end": 45287, "score": 0.7910692691802979, "start": 45278, "tag": "NAME", "value": "Ion Bombs" }, { "context": " count: 1\n }\n {\n name: '\"Redline\"'\n type: 'pilot'\n count: 1\n", "end": 45635, "score": 0.9977158308029175, "start": 45628, "tag": "NAME", "value": "Redline" }, { "context": " count: 1\n }\n {\n name: '\"Deathrain\"'\n type: 'pilot'\n count: 1\n", "end": 45734, "score": 0.9947360157966614, "start": 45725, "tag": "NAME", "value": "Deathrain" }, { "context": " count: 1\n }\n {\n name: \"Juno Eclipse\"\n type: 'pilot'\n count: 1\n ", "end": 47522, "score": 0.9997790455818176, "start": 47510, "tag": "NAME", "value": "Juno Eclipse" }, { "context": " count: 1\n }\n {\n name: \"Zertik Strom\"\n type: 'pilot'\n count: 1\n ", "end": 47622, "score": 0.9998548626899719, "start": 47610, "tag": "NAME", "value": "Zertik Strom" }, { "context": " count: 1\n }\n {\n name: \"Commander Alozen\"\n type: 'pilot'\n count: 1\n ", "end": 47726, "score": 0.9998817443847656, "start": 47710, "tag": "NAME", "value": "Commander Alozen" }, { "context": " count: 1\n }\n {\n name: \"Lieutenant Colzet\"\n type: 'pilot'\n count: 1\n ", "end": 47831, "score": 0.9998860359191895, "start": 47814, "tag": "NAME", "value": "Lieutenant Colzet" }, { "context": " count: 1\n }\n {\n name: \"Proton Rockets\"\n type: 'upgrade'\n count: 1", "end": 48468, "score": 0.995574951171875, "start": 48454, "tag": "NAME", "value": "Proton Rockets" }, { "context": " count: 1\n }\n {\n name: \"Captain Needa\"\n type: 'upgrade'\n count: 1", "end": 48571, "score": 0.9997780323028564, "start": 48558, "tag": "NAME", "value": "Captain Needa" }, { "context": " count: 1\n }\n {\n name: \"Grand Moff Tarkin\"\n type: 'upgrade'\n count: 1", "end": 48678, "score": 0.9998595118522644, "start": 48661, "tag": "NAME", "value": "Grand Moff Tarkin" }, { "context": " count: 1\n }\n {\n name: \"Emperor Palpatine\"\n type: 'upgrade'\n count: 1", "end": 48785, "score": 0.9998571276664734, "start": 48768, "tag": "NAME", "value": "Emperor Palpatine" }, { "context": " count: 1\n }\n {\n name: \"Admiral Ozzel\"\n type: 'upgrade'\n count: 1", "end": 48888, "score": 0.9998813271522522, "start": 48875, "tag": "NAME", "value": "Admiral Ozzel" }, { "context": "t: 1\n }\n {\n name: \"Shield Technician\"\n type: 'upgrade'\n co", "end": 48989, "score": 0.7800172567367554, "start": 48985, "tag": "NAME", "value": "Tech" }, { "context": " count: 1\n }\n {\n name: \"Single Turbolasers\"\n type: 'upgrade'\n count: 2", "end": 49412, "score": 0.7187744379043579, "start": 49394, "tag": "NAME", "value": "Single Turbolasers" }, { "context": " count: 2\n }\n {\n name: \"Ion Cannon Battery\"\n type: 'upgrade'\n count: 4", "end": 49520, "score": 0.7901021838188171, "start": 49502, "tag": "NAME", "value": "Ion Cannon Battery" }, { "context": " count: 4\n }\n {\n name: \"Quad Laser Cannons\"\n type: 'upgrade'\n count: 2", "end": 49628, "score": 0.8435220122337341, "start": 49610, "tag": "NAME", "value": "Quad Laser Cannons" }, { "context": " count: 2\n }\n {\n name: \"Tibanna Gas Supplies\"\n type: 'upgrade'\n count: 2", "end": 49738, "score": 0.9937037229537964, "start": 49718, "tag": "NAME", "value": "Tibanna Gas Supplies" }, { "context": " count: 2\n }\n {\n name: \"Engine Booster\"\n type: 'upgrade'\n ", "end": 49834, "score": 0.5680930614471436, "start": 49828, "tag": "NAME", "value": "Engine" }, { "context": " }\n {\n name: \"Engine Booster\"\n type: 'upgrade'\n count: 1", "end": 49842, "score": 0.6981395483016968, "start": 49840, "tag": "NAME", "value": "er" }, { "context": " count: 1\n }\n {\n name: \"Comms Booster\"\n type: 'upgrade'\n count: 1", "end": 50058, "score": 0.8445245623588562, "start": 50045, "tag": "NAME", "value": "Comms Booster" }, { "context": " count: 1\n }\n {\n name: \"Assailer\"\n type: 'title'\n count: 1\n ", "end": 50156, "score": 0.9822585582733154, "start": 50148, "tag": "NAME", "value": "Assailer" }, { "context": " count: 1\n }\n {\n name: \"Instigator\"\n type: 'title'\n count: 1\n ", "end": 50254, "score": 0.9499683380126953, "start": 50244, "tag": "NAME", "value": "Instigator" }, { "context": " count: 1\n }\n {\n name: \"Impetuous\"\n type: 'title'\n count: 1\n ", "end": 50351, "score": 0.946445882320404, "start": 50342, "tag": "NAME", "value": "Impetuous" }, { "context": "Awakens Core Set': [\n {\n name: 'T-70 X-Wing'\n type: 'ship'\n count: 1\n ", "end": 50492, "score": 0.9930950999259949, "start": 50481, "tag": "NAME", "value": "T-70 X-Wing" }, { "context": " count: 1\n }\n {\n name: 'TIE/fo Fighter'\n type: 'ship'\n ", "end": 50582, "score": 0.6489866971969604, "start": 50579, "tag": "NAME", "value": "TIE" }, { "context": "t: 1\n }\n {\n name: 'TIE/fo Fighter'\n type: 'ship'\n count", "end": 50587, "score": 0.5054855346679688, "start": 50586, "tag": "NAME", "value": "F" }, { "context": " count: 2\n }\n {\n name: 'Poe Dameron'\n type: 'pilot'\n count: 1\n ", "end": 50691, "score": 0.9997159838676453, "start": 50680, "tag": "NAME", "value": "Poe Dameron" }, { "context": " count: 1\n }\n {\n name: '\"Blue Ace\"'\n type: 'pilot'\n count: 1\n", "end": 50788, "score": 0.985309362411499, "start": 50780, "tag": "NAME", "value": "Blue Ace" }, { "context": " count: 1\n }\n {\n name: 'Red Squadron Veteran'\n type: 'pilot'\n count: 1\n ", "end": 50897, "score": 0.9342833757400513, "start": 50877, "tag": "NAME", "value": "Red Squadron Veteran" }, { "context": " count: 1\n }\n {\n name: 'Blue Squadron Novice'\n type: 'pilot'\n ", "end": 50989, "score": 0.5218790173530579, "start": 50985, "tag": "NAME", "value": "Blue" }, { "context": "t: 1\n }\n {\n name: 'Blue Squadron Novice'\n type: 'pilot'\n ", "end": 50995, "score": 0.5460987091064453, "start": 50991, "tag": "NAME", "value": "quad" }, { "context": " }\n {\n name: 'Blue Squadron Novice'\n type: 'pilot'\n count: 1\n ", "end": 51005, "score": 0.5382789969444275, "start": 51001, "tag": "NAME", "value": "vice" }, { "context": " count: 1\n }\n {\n name: '\"Omega Ace\"'\n type: 'pilot'\n count: 1\n", "end": 51103, "score": 0.9709224700927734, "start": 51094, "tag": "NAME", "value": "Omega Ace" }, { "context": " count: 1\n }\n {\n name: '\"Epsilon Leader\"'\n type: 'pilot'\n count: 1\n", "end": 51207, "score": 0.852353572845459, "start": 51193, "tag": "NAME", "value": "Epsilon Leader" }, { "context": " count: 1\n }\n {\n name: '\"Zeta Ace\"'\n type: 'pilot'\n count: 1\n", "end": 51305, "score": 0.9924529790878296, "start": 51297, "tag": "NAME", "value": "Zeta Ace" }, { "context": " count: 1\n }\n {\n name: 'Omega Squadron Pilot'\n type: 'pilot'\n ", "end": 51399, "score": 0.6132760047912598, "start": 51394, "tag": "NAME", "value": "Omega" }, { "context": " count: 2\n }\n {\n name: 'Zeta Squadron Pilot'\n type: 'pilot'\n count: 2\n ", "end": 51521, "score": 0.7297337651252747, "start": 51502, "tag": "NAME", "value": "Zeta Squadron Pilot" }, { "context": " count: 2\n }\n {\n name: 'Epsilon Squadron Pilot'\n type: 'pilot'\n coun", "end": 51625, "score": 0.6327396631240845, "start": 51609, "tag": "NAME", "value": "Epsilon Squadron" }, { "context": "}\n {\n name: 'Epsilon Squadron Pilot'\n type: 'pilot'\n count: 2\n ", "end": 51631, "score": 0.6569266319274902, "start": 51628, "tag": "NAME", "value": "lot" }, { "context": " count: 2\n }\n {\n name: 'Wired'\n type: 'upgrade'\n count: 1", "end": 51724, "score": 0.9459754824638367, "start": 51719, "tag": "NAME", "value": "Wired" }, { "context": " count: 1\n }\n {\n name: 'Proton Torpedoes'\n type: 'upgrade'\n count: 1", "end": 52019, "score": 0.9917759895324707, "start": 52003, "tag": "NAME", "value": "Proton Torpedoes" }, { "context": "r Expansion Pack': [\n {\n name: 'TIE Fighter'\n type: 'ship'\n cou", "end": 52273, "score": 0.6110801100730896, "start": 52270, "tag": "NAME", "value": "TIE" }, { "context": " count: 1\n }\n {\n name: '\"Scourge\"'\n type: 'pilot'\n count: 1\n", "end": 52593, "score": 0.9756364822387695, "start": 52586, "tag": "NAME", "value": "Scourge" }, { "context": " count: 1\n }\n {\n name: '\"Wampa\"'\n type: 'pilot'\n count: 1\n", "end": 52688, "score": 0.9996991157531738, "start": 52683, "tag": "NAME", "value": "Wampa" }, { "context": " count: 1\n }\n {\n name: '\"Youngster\"'\n type: 'pilot'\n count: 1\n", "end": 52787, "score": 0.9989919066429138, "start": 52778, "tag": "NAME", "value": "Youngster" }, { "context": " count: 1\n }\n {\n name: '\"Chaser\"'\n type: 'pilot'\n count: 1\n", "end": 52883, "score": 0.998483419418335, "start": 52877, "tag": "NAME", "value": "Chaser" }, { "context": " count: 2\n }\n {\n name: 'Marksmanship'\n type: 'upgrade'\n coun", "end": 53300, "score": 0.6747820377349854, "start": 53292, "tag": "NAME", "value": "Marksman" }, { "context": " count: 1\n }\n {\n name: 'Ion Torpedoes'\n type: 'upgrade'\n count: 1", "end": 53608, "score": 0.6747937798500061, "start": 53595, "tag": "NAME", "value": "Ion Torpedoes" }, { "context": " count: 1\n }\n {\n name: 'Homing Missiles'\n type: 'upgrade'\n ", "end": 53807, "score": 0.5680856108665466, "start": 53804, "tag": "NAME", "value": "Hom" }, { "context": " }\n {\n name: 'Homing Missiles'\n type: 'upgrade'\n count: 1", "end": 53819, "score": 0.6965529918670654, "start": 53815, "tag": "NAME", "value": "iles" }, { "context": " count: 1\n }\n {\n name: 'Dual Laser Turret'\n type: 'upgrade'\n ", "end": 53913, "score": 0.5141859650611877, "start": 53909, "tag": "NAME", "value": "Dual" }, { "context": " count: 1\n }\n {\n name: 'Construction Droid'\n type: 'upgrade'\n count: 2", "end": 54139, "score": 0.6636640429496765, "start": 54121, "tag": "NAME", "value": "Construction Droid" }, { "context": " count: 2\n }\n {\n name: 'Agent Kallus'\n type: 'upgrade'\n count: 1", "end": 54241, "score": 0.9874638915061951, "start": 54229, "tag": "NAME", "value": "Agent Kallus" }, { "context": " count: 1\n }\n {\n name: 'Rear Admiral Chiraneau'\n type: 'upgrade'\n count: 1", "end": 54353, "score": 0.9920496344566345, "start": 54331, "tag": "NAME", "value": "Rear Admiral Chiraneau" }, { "context": " count: 3\n }\n {\n name: 'Ordnance Tubes'\n type: 'modification'\n cou", "end": 54999, "score": 0.9324766993522644, "start": 54985, "tag": "NAME", "value": "Ordnance Tubes" }, { "context": " count: 2\n }\n {\n name: 'Requiem'\n type: 'title'\n count: 1\n ", "end": 55101, "score": 0.9939732551574707, "start": 55094, "tag": "NAME", "value": "Requiem" }, { "context": " count: 1\n }\n {\n name: 'Vector'\n type: 'title'\n count: 1\n ", "end": 55195, "score": 0.9889897704124451, "start": 55189, "tag": "NAME", "value": "Vector" }, { "context": " count: 1\n }\n {\n name: 'Suppressor'\n type: 'title'\n count: 1\n ", "end": 55293, "score": 0.9924818277359009, "start": 55283, "tag": "NAME", "value": "Suppressor" }, { "context": "g Expansion Pack': [\n {\n name: 'T-70 X-Wing'\n type: 'ship'\n count: 1\n ", "end": 55434, "score": 0.8910164833068848, "start": 55423, "tag": "NAME", "value": "T-70 X-Wing" }, { "context": " count: 1\n }\n {\n name: 'Ello Asty'\n type: 'pilot'\n count: 1\n ", "end": 55530, "score": 0.9914276599884033, "start": 55521, "tag": "NAME", "value": "Ello Asty" }, { "context": " count: 1\n }\n {\n name: '\"Red Ace\"'\n type: 'pilot'\n count: 1\n", "end": 55626, "score": 0.9491138458251953, "start": 55619, "tag": "NAME", "value": "Red Ace" }, { "context": " count: 1\n }\n {\n name: 'Red Squadron Veteran'\n type: 'pilot'\n count: 1\n ", "end": 55735, "score": 0.8730827569961548, "start": 55715, "tag": "NAME", "value": "Red Squadron Veteran" }, { "context": " count: 1\n }\n {\n name: 'Blue Squadron Novice'\n type: 'pilot'\n count: 1\n ", "end": 55843, "score": 0.8863461017608643, "start": 55823, "tag": "NAME", "value": "Blue Squadron Novice" }, { "context": " count: 1\n }\n {\n name: 'Cool Hand'\n type: 'upgrade'\n count: 1", "end": 55940, "score": 0.8544824123382568, "start": 55931, "tag": "NAME", "value": "Cool Hand" }, { "context": "r Expansion Pack': [\n {\n name: 'TIE/fo Fighter'\n type: 'ship'\n ", "end": 56523, "score": 0.7274504899978638, "start": 56520, "tag": "NAME", "value": "TIE" }, { "context": "pansion Pack': [\n {\n name: 'TIE/fo Fighter'\n type: 'ship'\n count: 1\n ", "end": 56534, "score": 0.6033486127853394, "start": 56524, "tag": "NAME", "value": "fo Fighter" }, { "context": " count: 1\n }\n {\n name: '\"Zeta Leader\"'\n type: 'pilot'\n ", "end": 56725, "score": 0.5836392045021057, "start": 56724, "tag": "NAME", "value": "Z" }, { "context": " count: 1\n }\n {\n name: '\"Epsilon Ace\"'\n type: 'pilot'\n count: 1\n", "end": 56836, "score": 0.9182040095329285, "start": 56825, "tag": "NAME", "value": "Epsilon Ace" }, { "context": " count: 1\n }\n {\n name: 'Juke'\n type: 'upgrade'\n count: 1", "end": 57254, "score": 0.9598040580749512, "start": 57250, "tag": "NAME", "value": "Juke" }, { "context": " count: 1\n }\n {\n name: 'Hera Syndulla'\n type: 'pilot'\n count: 1\n ", "end": 57688, "score": 0.9998663067817688, "start": 57675, "tag": "NAME", "value": "Hera Syndulla" }, { "context": " count: 1\n }\n {\n name: 'Kanan Jarrus'\n type: 'pilot'\n count: 1\n ", "end": 57788, "score": 0.9998775720596313, "start": 57776, "tag": "NAME", "value": "Kanan Jarrus" }, { "context": " count: 1\n }\n {\n name: '\"Chopper\"'\n type: 'pilot'\n count: 1\n", "end": 57884, "score": 0.9998345971107483, "start": 57877, "tag": "NAME", "value": "Chopper" }, { "context": " count: 1\n }\n {\n name: 'Lothal Rebel'\n type: 'pilot'\n count: 1\n ", "end": 57985, "score": 0.9994242787361145, "start": 57973, "tag": "NAME", "value": "Lothal Rebel" }, { "context": " count: 1\n }\n {\n name: 'Hera Syndulla (Attack Shuttle)'\n type: 'pilot'\n ", "end": 58086, "score": 0.9998504519462585, "start": 58073, "tag": "NAME", "value": "Hera Syndulla" }, { "context": " count: 1\n }\n {\n name: 'Sabine Wren'\n type: 'pilot'\n count: 1\n ", "end": 58202, "score": 0.9998794794082642, "start": 58191, "tag": "NAME", "value": "Sabine Wren" }, { "context": " count: 1\n }\n {\n name: 'Ezra Bridger'\n type: 'pilot'\n count: 1\n ", "end": 58302, "score": 0.9998638033866882, "start": 58290, "tag": "NAME", "value": "Ezra Bridger" }, { "context": " count: 1\n }\n {\n name: '\"Zeb\" Orrelios'\n type: 'pilot'\n ", "end": 58394, "score": 0.9997291564941406, "start": 58391, "tag": "NAME", "value": "Zeb" }, { "context": "nt: 1\n }\n {\n name: '\"Zeb\" Orrelios'\n type: 'pilot'\n count: 1\n ", "end": 58404, "score": 0.9829846024513245, "start": 58396, "tag": "NAME", "value": "Orrelios" }, { "context": " count: 1\n }\n {\n name: 'Predator'\n type: 'upgrade'\n count: 1", "end": 58500, "score": 0.9805651307106018, "start": 58492, "tag": "NAME", "value": "Predator" }, { "context": " count: 1\n }\n {\n name: 'Hera Syndulla'\n type: 'upgrade'\n count: 1", "end": 58932, "score": 0.9998345375061035, "start": 58919, "tag": "NAME", "value": "Hera Syndulla" }, { "context": " count: 1\n }\n {\n name: '\"Zeb\" Orrelios'\n type: 'upgrade'\n ", "end": 59026, "score": 0.9995896816253662, "start": 59023, "tag": "NAME", "value": "Zeb" }, { "context": "nt: 1\n }\n {\n name: '\"Zeb\" Orrelios'\n type: 'upgrade'\n count: 1", "end": 59036, "score": 0.9806614518165588, "start": 59028, "tag": "NAME", "value": "Orrelios" }, { "context": " count: 1\n }\n {\n name: 'Kanan Jarrus'\n type: 'upgrade'\n count: 1", "end": 59138, "score": 0.9998763799667358, "start": 59126, "tag": "NAME", "value": "Kanan Jarrus" }, { "context": " count: 1\n }\n {\n name: 'Ezra Bridger'\n type: 'upgrade'\n count: 1", "end": 59240, "score": 0.9998794794082642, "start": 59228, "tag": "NAME", "value": "Ezra Bridger" }, { "context": " count: 1\n }\n {\n name: 'Sabine Wren'\n type: 'upgrade'\n count: 1", "end": 59341, "score": 0.9998807907104492, "start": 59330, "tag": "NAME", "value": "Sabine Wren" }, { "context": " count: 1\n }\n {\n name: '\"Chopper\"'\n type: 'upgrade'\n count: ", "end": 59439, "score": 0.9996342658996582, "start": 59432, "tag": "NAME", "value": "Chopper" }, { "context": " count: 1\n }\n {\n name: 'Conner Net'\n type: 'upgrade'\n count: 1", "end": 59540, "score": 0.9947245121002197, "start": 59530, "tag": "NAME", "value": "Conner Net" }, { "context": " count: 1\n }\n {\n name: 'Cluster Mines'\n type: 'upgrade'\n count: 1", "end": 59643, "score": 0.981060802936554, "start": 59630, "tag": "NAME", "value": "Cluster Mines" }, { "context": " count: 1\n }\n {\n name: 'Thermal Detonators'\n type: 'upgrade'\n count: 1", "end": 59751, "score": 0.9730020761489868, "start": 59733, "tag": "NAME", "value": "Thermal Detonators" }, { "context": " count: 1\n }\n {\n name: 'Ghost'\n type: 'title'\n count: 1\n ", "end": 59846, "score": 0.9992994666099548, "start": 59841, "tag": "NAME", "value": "Ghost" }, { "context": " count: 1\n }\n {\n name: 'Phantom'\n type: 'title'\n count: 1\n ", "end": 59941, "score": 0.9993962049484253, "start": 59934, "tag": "NAME", "value": "Phantom" }, { "context": "e Expansion Pack': [\n {\n name: 'JumpMaster 5000'\n type: 'ship'\n count: 1\n ", "end": 60088, "score": 0.8841524720191956, "start": 60073, "tag": "NAME", "value": "JumpMaster 5000" }, { "context": " count: 1\n }\n {\n name: 'Dengar'\n type: 'pilot'\n count: 1\n ", "end": 60181, "score": 0.9998419284820557, "start": 60175, "tag": "NAME", "value": "Dengar" }, { "context": " count: 1\n }\n {\n name: 'Tel Trevura'\n type: 'pilot'\n count: 1\n ", "end": 60280, "score": 0.9998357892036438, "start": 60269, "tag": "NAME", "value": "Tel Trevura" }, { "context": " count: 1\n }\n {\n name: 'Manaroo'\n type: 'pilot'\n count: 1\n ", "end": 60375, "score": 0.9998471140861511, "start": 60368, "tag": "NAME", "value": "Manaroo" }, { "context": " count: 1\n }\n {\n name: 'Contracted Scout'\n type: 'pilot'\n count: 1\n ", "end": 60479, "score": 0.9960485100746155, "start": 60463, "tag": "NAME", "value": "Contracted Scout" }, { "context": " count: 1\n }\n {\n name: 'Rage'\n type: 'upgrade'\n count: 1", "end": 60571, "score": 0.9998012781143188, "start": 60567, "tag": "NAME", "value": "Rage" }, { "context": " count: 1\n }\n {\n name: 'Attanni Mindlink'\n type: 'upgrade'\n count: 2", "end": 60677, "score": 0.9998608231544495, "start": 60661, "tag": "NAME", "value": "Attanni Mindlink" }, { "context": " count: 2\n }\n {\n name: 'Plasma Torpedoes'\n type: 'upgrade'\n count: 1", "end": 60783, "score": 0.9996320009231567, "start": 60767, "tag": "NAME", "value": "Plasma Torpedoes" }, { "context": " count: 1\n }\n {\n name: 'Dengar'\n type: 'upgrade'\n count: 1", "end": 60879, "score": 0.9998559951782227, "start": 60873, "tag": "NAME", "value": "Dengar" }, { "context": " count: 1\n }\n {\n name: 'Boba Fett'\n type: 'upgrade'\n count: 1", "end": 60978, "score": 0.9998561143875122, "start": 60969, "tag": "NAME", "value": "Boba Fett" }, { "context": " count: 1\n }\n {\n name: '\"Gonk\"'\n type: 'upgrade'\n count: ", "end": 61073, "score": 0.9997022151947021, "start": 61069, "tag": "NAME", "value": "Gonk" }, { "context": " count: 1\n }\n {\n name: 'R5-P8'\n type: 'upgrade'\n count: 1", "end": 61169, "score": 0.9861986041069031, "start": 61164, "tag": "NAME", "value": "R5-P8" }, { "context": " count: 1\n }\n {\n name: 'Overclocked R4'\n type: 'upgrade'\n count", "end": 61270, "score": 0.9064434170722961, "start": 61259, "tag": "NAME", "value": "Overclocked" }, { "context": " }\n {\n name: 'Overclocked R4'\n type: 'upgrade'\n count: 2", "end": 61273, "score": 0.7242071032524109, "start": 61271, "tag": "NAME", "value": "R4" }, { "context": " count: 2\n }\n {\n name: 'Feedback Array'\n type: 'upgrade'\n count: 1", "end": 61377, "score": 0.8305284976959229, "start": 61363, "tag": "NAME", "value": "Feedback Array" }, { "context": " count: 1\n }\n {\n name: 'Punishing One'\n type: 'title'\n count: 1\n ", "end": 61480, "score": 0.9592264890670776, "start": 61467, "tag": "NAME", "value": "Punishing One" }, { "context": " count: 1\n }\n {\n name: 'Guidance Chips'\n type: 'modification'\n cou", "end": 61582, "score": 0.6237146258354187, "start": 61568, "tag": "NAME", "value": "Guidance Chips" }, { "context": "r Expansion Pack': [\n {\n name: 'G-1A Starfighter'\n type: 'ship'\n count: 1\n ", "end": 61735, "score": 0.991669237613678, "start": 61719, "tag": "NAME", "value": "G-1A Starfighter" }, { "context": " count: 1\n }\n {\n name: 'Zuckuss'\n type: 'pilot'\n count: 1\n ", "end": 61829, "score": 0.9987877011299133, "start": 61822, "tag": "NAME", "value": "Zuckuss" }, { "context": " count: 1\n }\n {\n name: '4-LOM'\n type: 'pilot'\n count: 1\n ", "end": 61922, "score": 0.8963276147842407, "start": 61917, "tag": "NAME", "value": "4-LOM" }, { "context": " count: 1\n }\n {\n name: 'Gand Findsman'\n type: 'pilot'\n count: 1\n ", "end": 62023, "score": 0.9997612237930298, "start": 62010, "tag": "NAME", "value": "Gand Findsman" }, { "context": " count: 1\n }\n {\n name: 'Ruthless Freelancer'\n type: 'pilot'\n count: 1\n ", "end": 62130, "score": 0.9991810917854309, "start": 62111, "tag": "NAME", "value": "Ruthless Freelancer" }, { "context": " count: 1\n }\n {\n name: 'Adaptability'\n type: 'upgrade'\n count: 2", "end": 62230, "score": 0.9459977746009827, "start": 62218, "tag": "NAME", "value": "Adaptability" }, { "context": " count: 2\n }\n {\n name: 'Tractor Beam'\n type: 'upgrade'\n count: 1", "end": 62332, "score": 0.9842497110366821, "start": 62320, "tag": "NAME", "value": "Tractor Beam" }, { "context": " count: 1\n }\n {\n name: 'Electronic Baffle'\n type: 'upgrade'\n count: 2", "end": 62439, "score": 0.9788193702697754, "start": 62422, "tag": "NAME", "value": "Electronic Baffle" }, { "context": " count: 2\n }\n {\n name: '4-LOM'\n type: 'upgrade'\n count: 1", "end": 62534, "score": 0.9010515809059143, "start": 62529, "tag": "NAME", "value": "4-LOM" }, { "context": " count: 1\n }\n {\n name: 'Zuckuss'\n type: 'upgrade'\n count: 1", "end": 62631, "score": 0.9966278076171875, "start": 62624, "tag": "NAME", "value": "Zuckuss" }, { "context": "ount: 1\n }\n {\n name: 'Cloaking Device'\n type: 'upgrade'\n c", "end": 62729, "score": 0.5961357951164246, "start": 62724, "tag": "NAME", "value": "aking" }, { "context": " count: 1\n }\n {\n name: 'Mist Hunter'\n type: 'title'\n count: 1\n ", "end": 62837, "score": 0.9946560859680176, "start": 62826, "tag": "NAME", "value": "Mist Hunter" }, { "context": " count: 1\n }\n {\n name: 'The Inquisitor'\n type: 'pilot'\n count: 1\n ", "end": 63095, "score": 0.9868590831756592, "start": 63081, "tag": "NAME", "value": "The Inquisitor" }, { "context": " count: 1\n }\n {\n name: 'Valen Rudor'\n type: 'pilot'\n count: 1\n ", "end": 63194, "score": 0.9996052980422974, "start": 63183, "tag": "NAME", "value": "Valen Rudor" }, { "context": " count: 1\n }\n {\n name: 'Baron of the Empire'\n type: 'pilot'\n count: 1\n ", "end": 63301, "score": 0.9994854927062988, "start": 63282, "tag": "NAME", "value": "Baron of the Empire" }, { "context": " count: 1\n }\n {\n name: 'Sienar Test Pilot'\n type: 'pilot'\n count: 1\n ", "end": 63406, "score": 0.657844603061676, "start": 63389, "tag": "NAME", "value": "Sienar Test Pilot" }, { "context": "count: 1\n }\n {\n name: 'Deadeye'\n type: 'upgrade'\n count: 1", "end": 63501, "score": 0.7265195846557617, "start": 63496, "tag": "NAME", "value": "adeye" }, { "context": " count: 1\n }\n {\n name: 'Homing Missiles'\n type: 'upgrade'\n count: 1", "end": 63606, "score": 0.8202489614486694, "start": 63591, "tag": "NAME", "value": "Homing Missiles" }, { "context": "s Expansion Pack\": [\n {\n name: 'TIE Bomber'\n type: 'ship'\n count: 1\n ", "end": 64069, "score": 0.7752512693405151, "start": 64059, "tag": "NAME", "value": "TIE Bomber" }, { "context": " count: 1\n }\n {\n name: 'TIE Defender'\n type: 'ship'\n count: 1\n ", "end": 64168, "score": 0.6829967498779297, "start": 64156, "tag": "NAME", "value": "TIE Defender" }, { "context": " count: 1\n }\n {\n name: 'Tomax Bren'\n type: 'pilot'\n count: 1\n ", "end": 64265, "score": 0.9998563528060913, "start": 64255, "tag": "NAME", "value": "Tomax Bren" }, { "context": " count: 1\n }\n {\n name: '\"Deathfire\"'\n type: 'pilot'\n count: 1\n", "end": 64363, "score": 0.9651644825935364, "start": 64354, "tag": "NAME", "value": "Deathfire" }, { "context": " count: 1\n }\n {\n name: 'Gamma Squadron Veteran'\n type: 'pilot'\n count: 2\n ", "end": 64474, "score": 0.7495436668395996, "start": 64452, "tag": "NAME", "value": "Gamma Squadron Veteran" }, { "context": " count: 2\n }\n {\n name: 'Maarek Stele (TIE Defender)'\n type: 'pilot'\n ", "end": 64574, "score": 0.9998321533203125, "start": 64562, "tag": "NAME", "value": "Maarek Stele" }, { "context": " count: 1\n }\n {\n name: 'Countess Ryad'\n type: 'pilot'\n count: 1\n ", "end": 64690, "score": 0.9995304942131042, "start": 64677, "tag": "NAME", "value": "Countess Ryad" }, { "context": " count: 1\n }\n {\n name: 'Glaive Squadron Pilot'\n type: 'pilot'\n count: 2\n ", "end": 64799, "score": 0.9148315191268921, "start": 64778, "tag": "NAME", "value": "Glaive Squadron Pilot" }, { "context": " count: 2\n }\n {\n name: 'Crack Shot'\n type: 'upgrade'\n count: 1", "end": 64897, "score": 0.7593114972114563, "start": 64887, "tag": "NAME", "value": "Crack Shot" }, { "context": "count: 2\n }\n {\n name: 'TIE/D'\n type: 'title'\n count: 2", "end": 65613, "score": 0.6943657398223877, "start": 65612, "tag": "NAME", "value": "E" }, { "context": " count: 2\n }\n {\n name: 'TIE Shuttle'\n type: 'title'\n count: 2\n ", "end": 65714, "score": 0.9445236325263977, "start": 65703, "tag": "NAME", "value": "TIE Shuttle" }, { "context": "0 Expansion Pack': [\n {\n name: 'ARC-170'\n type: 'ship'\n count: ", "end": 65843, "score": 0.5821109414100647, "start": 65840, "tag": "NAME", "value": "ARC" }, { "context": "nsion Pack': [\n {\n name: 'ARC-170'\n type: 'ship'\n count: 1\n ", "end": 65847, "score": 0.6209144592285156, "start": 65846, "tag": "NAME", "value": "0" }, { "context": " count: 1\n }\n {\n name: 'Norra Wexley'\n type: 'pilot'\n count: 1\n ", "end": 65946, "score": 0.9998818635940552, "start": 65934, "tag": "NAME", "value": "Norra Wexley" }, { "context": " count: 1\n }\n {\n name: 'Shara Bey'\n type: 'pilot'\n count: 1\n ", "end": 66043, "score": 0.9998657703399658, "start": 66034, "tag": "NAME", "value": "Shara Bey" }, { "context": " count: 1\n }\n {\n name: 'Thane Kyrell'\n type: 'pilot'\n count: 1\n ", "end": 66143, "score": 0.9998781085014343, "start": 66131, "tag": "NAME", "value": "Thane Kyrell" }, { "context": " count: 1\n }\n {\n name: 'Braylen Stramm'\n type: 'pilot'\n count: 1\n ", "end": 66245, "score": 0.9998852014541626, "start": 66231, "tag": "NAME", "value": "Braylen Stramm" }, { "context": " count: 1\n }\n {\n name: 'Adrenaline Rush'\n type: 'upgrade'\n count: 1", "end": 66348, "score": 0.9998806118965149, "start": 66333, "tag": "NAME", "value": "Adrenaline Rush" }, { "context": " count: 1\n }\n {\n name: 'Recon Specialist'\n type: 'upgrade'\n ", "end": 66443, "score": 0.9016764163970947, "start": 66438, "tag": "NAME", "value": "Recon" }, { "context": " count: 1\n }\n {\n name: 'Tail Gunner'\n type: 'upgrade'\n count: 1", "end": 66555, "score": 0.9993748664855957, "start": 66544, "tag": "NAME", "value": "Tail Gunner" }, { "context": " count: 1\n }\n {\n name: 'R3 Astromech'\n type: 'upgrade'\n count: 2", "end": 66657, "score": 0.9528658986091614, "start": 66645, "tag": "NAME", "value": "R3 Astromech" }, { "context": " count: 2\n }\n {\n name: 'Seismic Torpedo'\n type: 'upgrade'\n count: 1", "end": 66762, "score": 0.9983451962471008, "start": 66747, "tag": "NAME", "value": "Seismic Torpedo" }, { "context": " count: 1\n }\n {\n name: 'Vectored Thrusters'\n type: 'modification'\n cou", "end": 66870, "score": 0.996624767780304, "start": 66852, "tag": "NAME", "value": "Vectored Thrusters" }, { "context": " count: 2\n }\n {\n name: 'Alliance Overhaul'\n type: 'title'\n count:", "end": 66978, "score": 0.6295045018196106, "start": 66965, "tag": "NAME", "value": "Alliance Over" }, { "context": " }\n {\n name: 'Alliance Overhaul'\n type: 'title'\n count: 1\n ", "end": 66982, "score": 0.5588609576225281, "start": 66980, "tag": "NAME", "value": "ul" }, { "context": " }\n {\n name: 'Zeta Specialist'\n type: 'pilot'\n count: 1\n ", "end": 67537, "score": 0.9985439777374268, "start": 67534, "tag": "NAME", "value": "ist" }, { "context": " count: 1\n }\n {\n name: 'Fenn Rau'\n type: 'pilot'\n count: 1\n ", "end": 68214, "score": 0.9998660683631897, "start": 68206, "tag": "NAME", "value": "Fenn Rau" }, { "context": " count: 1\n }\n {\n name: 'Old Teroch'\n type: 'pilot'\n count: 1\n ", "end": 68312, "score": 0.999680757522583, "start": 68302, "tag": "NAME", "value": "Old Teroch" }, { "context": " count: 1\n }\n {\n name: 'Kad Solus'\n type: 'pilot'\n count: 1\n ", "end": 68409, "score": 0.9998845458030701, "start": 68400, "tag": "NAME", "value": "Kad Solus" }, { "context": " count: 1\n }\n {\n name: 'Concord Dawn Ace'\n type: 'pilot'\n count: 1\n ", "end": 68513, "score": 0.9998491406440735, "start": 68497, "tag": "NAME", "value": "Concord Dawn Ace" }, { "context": " count: 1\n }\n {\n name: 'Concord Dawn Veteran'\n type: 'pilot'\n count: 1\n ", "end": 68621, "score": 0.9996905326843262, "start": 68601, "tag": "NAME", "value": "Concord Dawn Veteran" }, { "context": " count: 1\n }\n {\n name: 'Zealous Recruit'\n type: 'pilot'\n count: 1\n ", "end": 68724, "score": 0.9349960088729858, "start": 68709, "tag": "NAME", "value": "Zealous Recruit" }, { "context": " count: 1\n }\n {\n name: 'Fearlessness'\n type: 'upgrade'\n count: 1", "end": 68824, "score": 0.9497352838516235, "start": 68812, "tag": "NAME", "value": "Fearlessness" }, { "context": " count: 1\n }\n {\n name: 'Concord Dawn Protector'\n type: 'title'\n ", "end": 68921, "score": 0.700243353843689, "start": 68914, "tag": "NAME", "value": "Concord" }, { "context": "1\n }\n {\n name: 'Concord Dawn Protector'\n type: 'title'\n ", "end": 68926, "score": 0.5134392976760864, "start": 68923, "tag": "NAME", "value": "awn" }, { "context": " count: 1\n }\n {\n name: 'Ketsu Onyo'\n type: 'pilot'\n count: 1\n ", "end": 69191, "score": 0.9998750686645508, "start": 69181, "tag": "NAME", "value": "Ketsu Onyo" }, { "context": " count: 1\n }\n {\n name: 'Asajj Ventress'\n type: 'pilot'\n count: 1\n ", "end": 69293, "score": 0.9998785853385925, "start": 69279, "tag": "NAME", "value": "Asajj Ventress" }, { "context": " count: 1\n }\n {\n name: 'Sabine Wren (Scum)'\n type: 'pilot'\n cou", "end": 69392, "score": 0.9998801946640015, "start": 69381, "tag": "NAME", "value": "Sabine Wren" }, { "context": " count: 1\n }\n {\n name: 'Shadowport Hunter'\n type: 'pilot'\n count: 1\n ", "end": 69504, "score": 0.999602198600769, "start": 69487, "tag": "NAME", "value": "Shadowport Hunter" }, { "context": " count: 1\n }\n {\n name: 'Veteran Instincts'\n type: 'upgrade'\n count: 1", "end": 69609, "score": 0.9776784777641296, "start": 69592, "tag": "NAME", "value": "Veteran Instincts" }, { "context": " count: 1\n }\n {\n name: 'Ketsu Onyo'\n type: 'upgrade'\n count: 1", "end": 69805, "score": 0.9991677403450012, "start": 69795, "tag": "NAME", "value": "Ketsu Onyo" }, { "context": " count: 1\n }\n {\n name: 'Latts Razzi'\n type: 'upgrade'\n count: 1", "end": 69906, "score": 0.9980257749557495, "start": 69895, "tag": "NAME", "value": "Latts Razzi" }, { "context": " count: 2\n }\n {\n name: 'Shadow Caster'\n type: 'title'\n count: 1\n ", "end": 70567, "score": 0.6580296158790588, "start": 70554, "tag": "NAME", "value": "Shadow Caster" }, { "context": " count: 1\n }\n {\n name: 'T-70 X-Wing'\n type: 'ship'\n c", "end": 70805, "score": 0.5446779131889343, "start": 70804, "tag": "NAME", "value": "T" }, { "context": "count: 1\n }\n {\n name: 'T-70 X-Wing'\n type: 'ship'\n count: 1\n ", "end": 70815, "score": 0.855920135974884, "start": 70806, "tag": "NAME", "value": "70 X-Wing" }, { "context": " count: 1\n }\n {\n name: 'Han Solo (TFA)'\n type: 'pilot'\n coun", "end": 70910, "score": 0.9994209408760071, "start": 70902, "tag": "NAME", "value": "Han Solo" }, { "context": " count: 1\n }\n {\n name: 'Rey'\n type: 'pilot'\n count: 1\n ", "end": 71007, "score": 0.9990910291671753, "start": 71004, "tag": "NAME", "value": "Rey" }, { "context": " count: 1\n }\n {\n name: 'Chewbacca (TFA)'\n type: 'pilot'\n coun", "end": 71104, "score": 0.999000072479248, "start": 71095, "tag": "NAME", "value": "Chewbacca" }, { "context": " count: 1\n }\n {\n name: 'Poe Dameron (PS9)'\n type: 'pilot'\n coun", "end": 71319, "score": 0.999830424785614, "start": 71308, "tag": "NAME", "value": "Poe Dameron" }, { "context": " count: 1\n }\n {\n name: 'Nien Nunb'\n type: 'pilot'\n count: 1\n ", "end": 71422, "score": 0.9998775720596313, "start": 71413, "tag": "NAME", "value": "Nien Nunb" }, { "context": "ount: 1\n }\n {\n name: '''\"Snap\" Wexley'''\n type: 'pilot'\n count: 1", "end": 71525, "score": 0.995396614074707, "start": 71513, "tag": "NAME", "value": "Snap\" Wexley" }, { "context": " count: 1\n }\n {\n name: 'Jess Pava'\n type: 'pilot'\n count: 1\n ", "end": 71624, "score": 0.9998546838760376, "start": 71615, "tag": "NAME", "value": "Jess Pava" }, { "context": " count: 1\n }\n {\n name: 'Blue Squadron Novice'\n type: 'pilot'\n ", "end": 71826, "score": 0.7174087762832642, "start": 71820, "tag": "NAME", "value": "Blue S" }, { "context": " }\n {\n name: 'Blue Squadron Novice'\n type: 'pilot'\n count: 1\n ", "end": 71840, "score": 0.709488034248352, "start": 71834, "tag": "NAME", "value": "Novice" }, { "context": " count: 1\n }\n {\n name: 'Snap Shot'\n type: 'upgrade'\n count: 2", "end": 71937, "score": 0.9934037923812866, "start": 71928, "tag": "NAME", "value": "Snap Shot" }, { "context": " count: 2\n }\n {\n name: 'Trick Shot'\n type: 'upgrade'\n count: 2", "end": 72037, "score": 0.9970700740814209, "start": 72027, "tag": "NAME", "value": "Trick Shot" }, { "context": " count: 2\n }\n {\n name: 'Finn'\n type: 'upgrade'\n count: 1", "end": 72131, "score": 0.9975016117095947, "start": 72127, "tag": "NAME", "value": "Finn" }, { "context": " count: 1\n }\n {\n name: 'Hotshot Co-pilot'\n type: 'upgrade'\n count: 1", "end": 72237, "score": 0.9716669321060181, "start": 72221, "tag": "NAME", "value": "Hotshot Co-pilot" }, { "context": " count: 1\n }\n {\n name: 'Rey'\n type: 'upgrade'\n count: 1", "end": 72330, "score": 0.9968087673187256, "start": 72327, "tag": "NAME", "value": "Rey" }, { "context": " count: 1\n }\n {\n name: 'M9-G8'\n type: 'upgrade'\n count: 1", "end": 72425, "score": 0.9756921529769897, "start": 72420, "tag": "NAME", "value": "M9-G8" }, { "context": " count: 1\n }\n {\n name: 'Burnout SLAM'\n type: 'upgrade'\n count: 2", "end": 72527, "score": 0.8569433689117432, "start": 72515, "tag": "NAME", "value": "Burnout SLAM" }, { "context": " count: 2\n }\n {\n name: 'Primed Thrusters'\n type: 'upgrade'\n count: 1", "end": 72633, "score": 0.9885950088500977, "start": 72617, "tag": "NAME", "value": "Primed Thrusters" }, { "context": " count: 1\n }\n {\n name: 'Pattern Analyzer'\n type: 'upgrade'\n count: 2", "end": 72739, "score": 0.9735289216041565, "start": 72723, "tag": "NAME", "value": "Pattern Analyzer" }, { "context": " count: 2\n }\n {\n name: 'Millennium Falcon (TFA)'\n type: 'title'\n coun", "end": 72846, "score": 0.9804838299751282, "start": 72829, "tag": "NAME", "value": "Millennium Falcon" }, { "context": "}\n {\n name: 'Millennium Falcon (TFA)'\n type: 'title'\n count: 1\n", "end": 72851, "score": 0.8854398727416992, "start": 72848, "tag": "NAME", "value": "TFA" }, { "context": " count: 1\n }\n {\n name: 'Black One'\n type: 'title'\n count: 1\n ", "end": 72949, "score": 0.9843366146087646, "start": 72940, "tag": "NAME", "value": "Black One" }, { "context": "g Expansion Pack\": [\n {\n name: 'U-Wing'\n type: 'ship'\n count: 1\n ", "end": 73311, "score": 0.9981431365013123, "start": 73305, "tag": "NAME", "value": "U-Wing" }, { "context": " count: 1\n }\n {\n name: 'Cassian Andor'\n type: 'pilot'\n count: 1\n ", "end": 73411, "score": 0.9998710751533508, "start": 73398, "tag": "NAME", "value": "Cassian Andor" }, { "context": " count: 1\n }\n {\n name: 'Bodhi Rook'\n type: 'pilot'\n count: 1\n ", "end": 73509, "score": 0.9998661875724792, "start": 73499, "tag": "NAME", "value": "Bodhi Rook" }, { "context": " count: 1\n }\n {\n name: 'Heff Tobber'\n type: 'pilot'\n count: 1\n ", "end": 73608, "score": 0.9998612403869629, "start": 73597, "tag": "NAME", "value": "Heff Tobber" }, { "context": " count: 1\n }\n {\n name: 'Blue Squadron Pathfinder'\n type: 'pilot'\n count: 1\n ", "end": 73720, "score": 0.6775079369544983, "start": 73696, "tag": "NAME", "value": "Blue Squadron Pathfinder" }, { "context": " count: 1\n }\n {\n name: 'Inspiring Recruit'\n type: 'upgrade'\n count: 2", "end": 73825, "score": 0.9109477996826172, "start": 73808, "tag": "NAME", "value": "Inspiring Recruit" }, { "context": " count: 2\n }\n {\n name: 'Cassian Andor'\n type: 'upgrade'\n count: 1", "end": 73928, "score": 0.9998663067817688, "start": 73915, "tag": "NAME", "value": "Cassian Andor" }, { "context": " count: 1\n }\n {\n name: 'Bistan'\n type: 'upgrade'\n count: 1", "end": 74024, "score": 0.9997109174728394, "start": 74018, "tag": "NAME", "value": "Bistan" }, { "context": " count: 1\n }\n {\n name: 'Jyn Erso'\n type: 'upgrade'\n count: 1", "end": 74122, "score": 0.9998595714569092, "start": 74114, "tag": "NAME", "value": "Jyn Erso" }, { "context": " count: 1\n }\n {\n name: 'Baze Malbus'\n type: 'upgrade'\n count: 1", "end": 74223, "score": 0.9998685121536255, "start": 74212, "tag": "NAME", "value": "Baze Malbus" }, { "context": " count: 1\n }\n {\n name: 'Bodhi Rook'\n type: 'upgrade'\n count: 1", "end": 74323, "score": 0.9998763799667358, "start": 74313, "tag": "NAME", "value": "Bodhi Rook" }, { "context": " count: 2\n }\n {\n name: 'Pivot Wing'\n type: 'title'\n count: 1\n ", "end": 74522, "score": 0.8715842366218567, "start": 74512, "tag": "NAME", "value": "Pivot Wing" }, { "context": " count: 2\n }\n {\n name: 'Sensor Jammer'\n type: 'upgrade'\n count: 1", "end": 74732, "score": 0.9683804512023926, "start": 74719, "tag": "NAME", "value": "Sensor Jammer" }, { "context": "r Expansion Pack\": [\n {\n name: 'TIE Striker'\n type: 'ship'\n count: 1\n ", "end": 74875, "score": 0.9763737916946411, "start": 74864, "tag": "NAME", "value": "TIE Striker" }, { "context": " count: 1\n }\n {\n name: '\"Duchess\"'\n type: 'pilot'\n count: 1\n", "end": 74970, "score": 0.9977107048034668, "start": 74963, "tag": "NAME", "value": "Duchess" }, { "context": " count: 1\n }\n {\n name: '\"Pure Sabacc\"'\n type: 'pilot'\n count: 1\n", "end": 75071, "score": 0.993482768535614, "start": 75060, "tag": "NAME", "value": "Pure Sabacc" }, { "context": " count: 1\n }\n {\n name: '\"Countdown\"'\n type: 'pilot'\n count: 1\n", "end": 75170, "score": 0.9775252342224121, "start": 75161, "tag": "NAME", "value": "Countdown" }, { "context": " count: 1\n }\n {\n name: 'Black Squadron Scout'\n type: 'pilot'\n count: 1\n ", "end": 75279, "score": 0.9491261839866638, "start": 75259, "tag": "NAME", "value": "Black Squadron Scout" }, { "context": " count: 1\n }\n {\n name: 'Scarif Defender'\n type: 'pilot'\n count: 1\n ", "end": 75382, "score": 0.9965105056762695, "start": 75367, "tag": "NAME", "value": "Scarif Defender" }, { "context": " count: 1\n }\n {\n name: 'Imperial Trainee'\n type: 'pilot'\n count: 1\n ", "end": 75486, "score": 0.9509273767471313, "start": 75470, "tag": "NAME", "value": "Imperial Trainee" }, { "context": " count: 1\n }\n {\n name: 'Swarm Leader'\n type: 'upgrade'\n count: 1", "end": 75586, "score": 0.7051988244056702, "start": 75574, "tag": "NAME", "value": "Swarm Leader" }, { "context": " count: 1\n }\n {\n name: 'Adaptive Ailerons'\n type: 'title'\n cou", "end": 75798, "score": 0.6450757384300232, "start": 75788, "tag": "NAME", "value": "Adaptive A" }, { "context": "r Expansion Pack\": [\n {\n name: 'TIE Fighter'\n type: 'ship'\n count: 1\n ", "end": 75955, "score": 0.8671305775642395, "start": 75944, "tag": "NAME", "value": "TIE Fighter" }, { "context": " count: 1\n }\n {\n name: 'Ahsoka Tano'\n type: 'pilot'\n count: 1\n ", "end": 76053, "score": 0.9996576309204102, "start": 76042, "tag": "NAME", "value": "Ahsoka Tano" }, { "context": " count: 1\n }\n {\n name: 'Sabine Wren (TIE Fighter)'\n type: 'pilot'\n ", "end": 76152, "score": 0.9996975064277649, "start": 76141, "tag": "NAME", "value": "Sabine Wren" }, { "context": " count: 1\n }\n {\n name: 'Captain Rex'\n type: 'pilot'\n count: 1\n ", "end": 76265, "score": 0.9883711338043213, "start": 76254, "tag": "NAME", "value": "Captain Rex" }, { "context": " count: 1\n }\n {\n name: '\"Zeb\" Orrelios (TIE Fighter)'\n type: 'pilot'", "end": 76357, "score": 0.9984025359153748, "start": 76354, "tag": "NAME", "value": "Zeb" }, { "context": "nt: 1\n }\n {\n name: '\"Zeb\" Orrelios (TIE Fighter)'\n type: 'pilot'\n ", "end": 76367, "score": 0.9787120819091797, "start": 76359, "tag": "NAME", "value": "Orrelios" }, { "context": " count: 1\n }\n {\n name: 'Veteran Instincts'\n type: 'upgrade'\n count: 1", "end": 76486, "score": 0.9231176972389221, "start": 76469, "tag": "NAME", "value": "Veteran Instincts" }, { "context": " count: 1\n }\n {\n name: 'Captain Rex'\n type: 'upgrade'\n count: 1", "end": 76587, "score": 0.9889670610427856, "start": 76576, "tag": "NAME", "value": "Captain Rex" }, { "context": " count: 1\n }\n {\n name: 'EMP Device'\n type: 'upgrade'\n count: 1", "end": 76687, "score": 0.7006325721740723, "start": 76677, "tag": "NAME", "value": "EMP Device" }, { "context": "count: 1\n }\n {\n name: '''Sabine's Masterpiece'''\n type: 'title'\n ", "end": 76785, "score": 0.8325643539428711, "start": 76779, "tag": "NAME", "value": "Sabine" }, { "context": " count: 1\n }\n {\n name: 'Captured TIE'\n type: 'modification'\n cou", "end": 76901, "score": 0.8425628542900085, "start": 76889, "tag": "NAME", "value": "Captured TIE" }, { "context": " count: 1\n }\n {\n name: 'Kylo Ren'\n type: 'pilot'\n count: 1\n ", "end": 77164, "score": 0.999779224395752, "start": 77156, "tag": "NAME", "value": "Kylo Ren" }, { "context": " count: 1\n }\n {\n name: 'Major Stridan'\n type: 'pilot'\n count: 1\n ", "end": 77265, "score": 0.9994534850120544, "start": 77252, "tag": "NAME", "value": "Major Stridan" }, { "context": " count: 1\n }\n {\n name: 'Lieutenant Dormitz'\n type: 'pilot'\n count: 1\n ", "end": 77371, "score": 0.9996209144592285, "start": 77353, "tag": "NAME", "value": "Lieutenant Dormitz" }, { "context": " count: 1\n }\n {\n name: 'Starkiller Base Pilot'\n type: 'pilot'\n count: 1\n ", "end": 77480, "score": 0.7966182827949524, "start": 77459, "tag": "NAME", "value": "Starkiller Base Pilot" }, { "context": " count: 1\n }\n {\n name: 'Snap Shot'\n type: 'upgrade'\n count: 2", "end": 77577, "score": 0.9980852007865906, "start": 77568, "tag": "NAME", "value": "Snap Shot" }, { "context": " count: 2\n }\n {\n name: 'Kylo Ren'\n type: 'upgrade'\n count: 1", "end": 77675, "score": 0.9996946454048157, "start": 77667, "tag": "NAME", "value": "Kylo Ren" }, { "context": " count: 1\n }\n {\n name: 'General Hux'\n type: 'upgrade'\n count: 1", "end": 77776, "score": 0.9917173385620117, "start": 77765, "tag": "NAME", "value": "General Hux" }, { "context": " count: 2\n }\n {\n name: 'Targeting Synchronizer'\n type: 'upgrade'\n ", "end": 77983, "score": 0.6420725584030151, "start": 77977, "tag": "NAME", "value": "Target" }, { "context": " count: 2\n }\n {\n name: 'Ion Projector'\n type: 'modification'\n cou", "end": 78214, "score": 0.955545961856842, "start": 78201, "tag": "NAME", "value": "Ion Projector" }, { "context": "count: 2\n }\n {\n name: '''Kylo Ren's Shuttle'''\n type: 'title'\n count: 1", "end": 78329, "score": 0.8936923742294312, "start": 78311, "tag": "NAME", "value": "Kylo Ren's Shuttle" }, { "context": "r Expansion Pack\": [\n {\n name: 'Quadjumper'\n type: 'ship'\n count: 1\n ", "end": 78470, "score": 0.9992364048957825, "start": 78460, "tag": "NAME", "value": "Quadjumper" }, { "context": " count: 1\n }\n {\n name: 'Constable Zuvio'\n type: 'pilot'\n count: 1\n ", "end": 78572, "score": 0.999544620513916, "start": 78557, "tag": "NAME", "value": "Constable Zuvio" }, { "context": " count: 1\n }\n {\n name: 'Sarco Plank'\n type: 'pilot'\n count: 1\n ", "end": 78671, "score": 0.9998509883880615, "start": 78660, "tag": "NAME", "value": "Sarco Plank" }, { "context": " count: 1\n }\n {\n name: 'Unkar Plutt'\n type: 'pilot'\n count: 1\n ", "end": 78770, "score": 0.9997416734695435, "start": 78759, "tag": "NAME", "value": "Unkar Plutt" }, { "context": " count: 1\n }\n {\n name: 'Jakku Gunrunner'\n type: 'pilot'\n count: 1\n ", "end": 78873, "score": 0.9998697638511658, "start": 78858, "tag": "NAME", "value": "Jakku Gunrunner" }, { "context": " count: 1\n }\n {\n name: 'A Score to Settle'\n type: 'upgrade'\n count: 1", "end": 78978, "score": 0.7346096038818359, "start": 78961, "tag": "NAME", "value": "A Score to Settle" }, { "context": " count: 1\n }\n {\n name: 'Unkar Plutt'\n type: 'upgrade'\n count: 1", "end": 79079, "score": 0.9995659589767456, "start": 79068, "tag": "NAME", "value": "Unkar Plutt" }, { "context": " count: 1\n }\n {\n name: 'BoShek'\n type: 'upgrade'\n count: 1", "end": 79175, "score": 0.998572826385498, "start": 79169, "tag": "NAME", "value": "BoShek" }, { "context": " count: 1\n }\n {\n name: 'Thermal Detonators'\n type: 'upgrade'\n ", "end": 79267, "score": 0.6196227669715881, "start": 79265, "tag": "NAME", "value": "Th" }, { "context": ": 1\n }\n {\n name: 'Thermal Detonators'\n type: 'upgrade'\n c", "end": 79276, "score": 0.7413257956504822, "start": 79273, "tag": "NAME", "value": "Det" }, { "context": " }\n {\n name: 'Thermal Detonators'\n type: 'upgrade'\n count: 1", "end": 79283, "score": 0.8636294603347778, "start": 79278, "tag": "NAME", "value": "ators" }, { "context": " count: 1\n }\n {\n name: 'Hyperwave Comm Scanner'\n type: 'upgrade'\n ", "end": 79378, "score": 0.6694020628929138, "start": 79373, "tag": "NAME", "value": "Hyper" }, { "context": " }\n {\n name: 'Hyperwave Comm Scanner'\n type: 'upgrade'\n count: 1", "end": 79395, "score": 0.5746302008628845, "start": 79388, "tag": "NAME", "value": "Scanner" }, { "context": " count: 1\n }\n {\n name: 'Scavenger Crane'\n type: 'upgrade'\n count: 1", "end": 79500, "score": 0.8022521734237671, "start": 79485, "tag": "NAME", "value": "Scavenger Crane" }, { "context": " count: 1\n }\n {\n name: 'Spacetug Tractor Array'\n type: 'modification'\n cou", "end": 79612, "score": 0.7729716897010803, "start": 79590, "tag": "NAME", "value": "Spacetug Tractor Array" }, { "context": "r Expansion Pack': [\n {\n name: 'C-ROC Cruiser'\n type: 'ship'\n count: 1\n ", "end": 79764, "score": 0.920954704284668, "start": 79751, "tag": "NAME", "value": "C-ROC Cruiser" }, { "context": " count: 1\n }\n {\n name: 'M3-A Interceptor'\n type: 'ship'\n count: 1\n ", "end": 79867, "score": 0.8552868962287903, "start": 79851, "tag": "NAME", "value": "M3-A Interceptor" }, { "context": " count: 1\n }\n {\n name: 'C-ROC Cruiser'\n type: 'pilot'\n count: 1\n ", "end": 79967, "score": 0.836939811706543, "start": 79954, "tag": "NAME", "value": "C-ROC Cruiser" }, { "context": " count: 1\n }\n {\n name: 'Genesis Red'\n type: 'pilot'\n count: 1\n ", "end": 80066, "score": 0.9995098114013672, "start": 80055, "tag": "NAME", "value": "Genesis Red" }, { "context": " count: 1\n }\n {\n name: 'Quinn Jast'\n type: 'pilot'\n count: 1\n ", "end": 80164, "score": 0.9998119473457336, "start": 80154, "tag": "NAME", "value": "Quinn Jast" }, { "context": " count: 1\n }\n {\n name: 'Inaldra'\n type: 'pilot'\n count: 1\n ", "end": 80259, "score": 0.9998498558998108, "start": 80252, "tag": "NAME", "value": "Inaldra" }, { "context": " count: 1\n }\n {\n name: 'Sunny Bounder'\n type: 'pilot'\n count: 1\n ", "end": 80360, "score": 0.9998643398284912, "start": 80347, "tag": "NAME", "value": "Sunny Bounder" }, { "context": " count: 1\n }\n {\n name: 'Tansarii Point Veteran'\n type: 'pilot'\n count: 1\n ", "end": 80470, "score": 0.9998922944068909, "start": 80448, "tag": "NAME", "value": "Tansarii Point Veteran" }, { "context": " count: 1\n }\n {\n name: 'Cartel Spacer'\n type: 'pilot'\n count: 1\n ", "end": 80571, "score": 0.999890923500061, "start": 80558, "tag": "NAME", "value": "Cartel Spacer" }, { "context": " count: 1\n }\n {\n name: 'Azmorigan'\n type: 'upgrade'\n count: 1", "end": 80668, "score": 0.9998906254768372, "start": 80659, "tag": "NAME", "value": "Azmorigan" }, { "context": " count: 1\n }\n {\n name: 'Cikatro Vizago'\n type: 'upgrade'\n count: 1", "end": 80772, "score": 0.9998965859413147, "start": 80758, "tag": "NAME", "value": "Cikatro Vizago" }, { "context": " count: 1\n }\n {\n name: 'Jabba the Hutt'\n type: 'upgrade'\n count: 1", "end": 80876, "score": 0.9998729228973389, "start": 80862, "tag": "NAME", "value": "Jabba the Hutt" }, { "context": "nt: 1\n }\n {\n name: 'IG-RM Thug Droids'\n type: 'upgrade'\n ", "end": 80974, "score": 0.5727701187133789, "start": 80972, "tag": "NAME", "value": "Th" }, { "context": " }\n {\n name: 'IG-RM Thug Droids'\n type: 'upgrade'\n count: 1", "end": 80983, "score": 0.8359859585762024, "start": 80978, "tag": "NAME", "value": "roids" }, { "context": " count: 1\n }\n {\n name: 'Broken Horn'\n type: 'title'\n count: 1\n ", "end": 81621, "score": 0.5768312811851501, "start": 81610, "tag": "NAME", "value": "Broken Horn" }, { "context": "p Expansion Pack\": [\n {\n name: 'Auzituck Gunship'\n type: 'ship'\n count: 1\n ", "end": 82441, "score": 0.9994783401489258, "start": 82425, "tag": "NAME", "value": "Auzituck Gunship" }, { "context": " count: 1\n }\n {\n name: 'Wullffwarro'\n type: 'pilot'\n count: 1\n ", "end": 82539, "score": 0.9998648762702942, "start": 82528, "tag": "NAME", "value": "Wullffwarro" }, { "context": " count: 1\n }\n {\n name: 'Lowhhrick'\n type: 'pilot'\n count: 1\n ", "end": 82636, "score": 0.9998652935028076, "start": 82627, "tag": "NAME", "value": "Lowhhrick" }, { "context": " count: 1\n }\n {\n name: 'Wookiee Liberator'\n type: 'pilot'\n count: 1\n ", "end": 82741, "score": 0.9998680949211121, "start": 82724, "tag": "NAME", "value": "Wookiee Liberator" }, { "context": " count: 1\n }\n {\n name: 'Kashyyyk Defender'\n type: 'pilot'\n count: 1\n ", "end": 82846, "score": 0.9998499155044556, "start": 82829, "tag": "NAME", "value": "Kashyyyk Defender" }, { "context": " count: 1\n }\n {\n name: 'Intimidation'\n type: 'upgrade'\n count: 1", "end": 82946, "score": 0.9997138977050781, "start": 82934, "tag": "NAME", "value": "Intimidation" }, { "context": " count: 1\n }\n {\n name: 'Selflessness'\n type: 'upgrade'\n count: 1", "end": 83048, "score": 0.9992110133171082, "start": 83036, "tag": "NAME", "value": "Selflessness" }, { "context": " count: 1\n }\n {\n name: 'Wookiee Commandos'\n type: 'upgrade'\n count: 1", "end": 83155, "score": 0.9998351335525513, "start": 83138, "tag": "NAME", "value": "Wookiee Commandos" }, { "context": " count: 1\n }\n {\n name: 'Tactician'\n type: 'upgrade'\n count: 1", "end": 83254, "score": 0.9997456669807434, "start": 83245, "tag": "NAME", "value": "Tactician" }, { "context": " count: 1\n }\n {\n name: 'Breach Specialist'\n type: 'upgrade'\n count: 1", "end": 83361, "score": 0.9905474185943604, "start": 83344, "tag": "NAME", "value": "Breach Specialist" }, { "context": " count: 1\n }\n {\n name: 'Hull Upgrade'\n type: 'modification'\n cou", "end": 83463, "score": 0.9985895752906799, "start": 83451, "tag": "NAME", "value": "Hull Upgrade" }, { "context": "r Expansion Pack\": [\n {\n name: 'Scurrg H-6 Bomber'\n type: 'ship'\n ", "end": 83612, "score": 0.9940381646156311, "start": 83606, "tag": "NAME", "value": "Scurrg" }, { "context": "ck\": [\n {\n name: 'Scurrg H-6 Bomber'\n type: 'ship'\n count: 1\n ", "end": 83623, "score": 0.867852509021759, "start": 83620, "tag": "NAME", "value": "ber" }, { "context": " count: 1\n }\n {\n name: 'Captain Nym (Rebel)'\n type: 'pilot'\n co", "end": 83721, "score": 0.9996885061264038, "start": 83710, "tag": "NAME", "value": "Captain Nym" }, { "context": " }\n {\n name: 'Captain Nym (Rebel)'\n type: 'pilot'\n count: 1\n", "end": 83728, "score": 0.8398942947387695, "start": 83723, "tag": "NAME", "value": "Rebel" }, { "context": " count: 1\n }\n {\n name: 'Captain Nym (Scum)'\n type: 'pilot'\n cou", "end": 83828, "score": 0.9997716546058655, "start": 83817, "tag": "NAME", "value": "Captain Nym" }, { "context": " }\n {\n name: 'Captain Nym (Scum)'\n type: 'pilot'\n count: 1\n", "end": 83834, "score": 0.7221420407295227, "start": 83830, "tag": "NAME", "value": "Scum" }, { "context": " count: 1\n }\n {\n name: 'Sol Sixxa'\n type: 'pilot'\n count: 1\n ", "end": 83932, "score": 0.9998207092285156, "start": 83923, "tag": "NAME", "value": "Sol Sixxa" }, { "context": " count: 1\n }\n {\n name: 'Lok Revenant'\n type: 'pilot'\n count: 1\n ", "end": 84032, "score": 0.9998806118965149, "start": 84020, "tag": "NAME", "value": "Lok Revenant" }, { "context": " count: 1\n }\n {\n name: 'Karthakk Pirate'\n type: 'pilot'\n count: 1\n ", "end": 84135, "score": 0.9998863339424133, "start": 84120, "tag": "NAME", "value": "Karthakk Pirate" }, { "context": " count: 1\n }\n {\n name: 'Lightning Reflexes'\n type: 'upgrade'\n count: 1", "end": 84241, "score": 0.9986709952354431, "start": 84223, "tag": "NAME", "value": "Lightning Reflexes" }, { "context": " count: 1\n }\n {\n name: 'Seismic Torpedo'\n type: 'upgrade'\n count: 1", "end": 84346, "score": 0.999788761138916, "start": 84331, "tag": "NAME", "value": "Seismic Torpedo" }, { "context": " count: 1\n }\n {\n name: 'Cruise Missiles'\n type: 'upgrade'\n count: 2", "end": 84451, "score": 0.9998306632041931, "start": 84436, "tag": "NAME", "value": "Cruise Missiles" }, { "context": " count: 1\n }\n {\n name: 'Cad Bane'\n type: 'upgrade'\n count: 1", "end": 84865, "score": 0.9623854160308838, "start": 84857, "tag": "NAME", "value": "Cad Bane" }, { "context": " count: 1\n }\n {\n name: 'R4-E1'\n type: 'upgrade'\n count: 1", "end": 84960, "score": 0.7985420227050781, "start": 84955, "tag": "NAME", "value": "R4-E1" }, { "context": " count: 1\n }\n {\n name: 'Havoc'\n type: 'title'\n count: 1\n ", "end": 85055, "score": 0.9972813725471497, "start": 85050, "tag": "NAME", "value": "Havoc" }, { "context": "r Expansion Pack\": [\n {\n name: 'TIE Aggressor'\n type: 'ship'\n c", "end": 85190, "score": 0.726127028465271, "start": 85187, "tag": "NAME", "value": "TIE" }, { "context": "nsion Pack\": [\n {\n name: 'TIE Aggressor'\n type: 'ship'\n count: 1\n ", "end": 85200, "score": 0.5755963325500488, "start": 85193, "tag": "NAME", "value": "gressor" }, { "context": " count: 1\n }\n {\n name: 'Lieutenant Kestal'\n type: 'pilot'\n count: 1\n ", "end": 85304, "score": 0.9998850226402283, "start": 85287, "tag": "NAME", "value": "Lieutenant Kestal" }, { "context": " count: 1\n }\n {\n name: 'Onyx Squadron Escort'\n type: 'pilot'\n count: 1\n ", "end": 85513, "score": 0.7051330804824829, "start": 85493, "tag": "NAME", "value": "Onyx Squadron Escort" }, { "context": " count: 1\n }\n {\n name: 'Sienar Specialist'\n type: 'pilot'\n count: 1\n ", "end": 85618, "score": 0.9876843690872192, "start": 85601, "tag": "NAME", "value": "Sienar Specialist" }, { "context": "e Expansion Pack': [\n {\n name: 'Kihraxz Fighter'\n type: 'ship'\n count: 1\n ", "end": 86292, "score": 0.9996947050094604, "start": 86277, "tag": "NAME", "value": "Kihraxz Fighter" }, { "context": " count: 1\n }\n {\n name: 'StarViper'\n type: 'ship'\n count: 1\n ", "end": 86388, "score": 0.9989385604858398, "start": 86379, "tag": "NAME", "value": "StarViper" }, { "context": " count: 1\n }\n {\n name: 'Viktor Hel'\n type: 'pilot'\n count: 1\n ", "end": 86485, "score": 0.999821662902832, "start": 86475, "tag": "NAME", "value": "Viktor Hel" }, { "context": " count: 1\n }\n {\n name: 'Captain Jostero'\n type: 'pilot'\n count: 1\n ", "end": 86588, "score": 0.999870777130127, "start": 86573, "tag": "NAME", "value": "Captain Jostero" }, { "context": " count: 1\n }\n {\n name: 'Black Sun Ace'\n type: 'pilot'\n count: 1\n ", "end": 86689, "score": 0.9994248747825623, "start": 86676, "tag": "NAME", "value": "Black Sun Ace" }, { "context": " count: 1\n }\n {\n name: 'Cartel Marauder'\n type: 'pilot'\n count: 1\n ", "end": 86792, "score": 0.9998580813407898, "start": 86777, "tag": "NAME", "value": "Cartel Marauder" }, { "context": " count: 1\n }\n {\n name: 'Dalan Oberos'\n type: 'pilot'\n count: 1\n ", "end": 86892, "score": 0.9998536109924316, "start": 86880, "tag": "NAME", "value": "Dalan Oberos" }, { "context": " count: 1\n }\n {\n name: 'Thweek'\n type: 'pilot'\n count: 1\n ", "end": 86986, "score": 0.99937903881073, "start": 86980, "tag": "NAME", "value": "Thweek" }, { "context": " count: 1\n }\n {\n name: 'Black Sun Assassin'\n type: 'pilot'\n count: 2\n ", "end": 87092, "score": 0.9995753169059753, "start": 87074, "tag": "NAME", "value": "Black Sun Assassin" }, { "context": " count: 2\n }\n {\n name: 'Harpoon Missiles'\n type: 'upgrade'\n count: 2", "end": 87196, "score": 0.999789297580719, "start": 87180, "tag": "NAME", "value": "Harpoon Missiles" }, { "context": " count: 2\n }\n {\n name: 'Ion Dischargers'\n type: 'upgrade'\n count: 2", "end": 87301, "score": 0.9956877827644348, "start": 87286, "tag": "NAME", "value": "Ion Dischargers" }, { "context": " count: 2\n }\n {\n name: 'StarViper Mk. II'\n type: 'title'\n count: 2\n ", "end": 87407, "score": 0.9838892221450806, "start": 87391, "tag": "NAME", "value": "StarViper Mk. II" }, { "context": " count: 2\n }\n {\n name: 'Vaksai'\n type: 'title'\n count: 2\n ", "end": 87501, "score": 0.9997348785400391, "start": 87495, "tag": "NAME", "value": "Vaksai" }, { "context": " count: 2\n }\n {\n name: 'Pulsed Ray Shield'\n type: 'modification'\n cou", "end": 87606, "score": 0.8654890060424805, "start": 87589, "tag": "NAME", "value": "Pulsed Ray Shield" }, { "context": " count: 1\n }\n {\n name: 'Vectored Thrusters'\n type: 'modification'\n cou", "end": 87828, "score": 0.8768458962440491, "start": 87810, "tag": "NAME", "value": "Vectored Thrusters" } ]
coffeescripts/manifest.coffee
cbmainz/xwing
0
exportObj = exports ? this String::startsWith ?= (t) -> @indexOf t == 0 sortWithoutQuotes = (a, b) -> a_name = a.replace /[^a-z0-9]/ig, '' b_name = b.replace /[^a-z0-9]/ig, '' if a_name < b_name -1 else if a_name > b_name 1 else 0 exportObj.manifestByExpansion = 'Core': [ { name: 'X-Wing' type: 'ship' count: 1 } { name: 'TIE Fighter' type: 'ship' count: 2 } { name: 'Luke Skywalker' type: 'pilot' count: 1 } { name: 'Biggs Darklighter' type: 'pilot' count: 1 } { name: 'Red Squadron Pilot' type: 'pilot' count: 1 } { name: 'Rookie Pilot' type: 'pilot' count: 1 } { name: '"Mauler Mithel"' type: 'pilot' count: 1 } { name: '"Dark Curse"' type: 'pilot' count: 1 } { name: '"Night Beast"' type: 'pilot' count: 1 } { name: 'Black Squadron Pilot' type: 'pilot' count: 2 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 2 } { name: 'Academy Pilot' type: 'pilot' count: 2 } { name: 'Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'R2-F2' type: 'upgrade' count: 1 } { name: 'R2-D2' type: 'upgrade' count: 1 } { name: 'Determination' type: 'upgrade' count: 1 } { name: 'Marksmanship' type: 'upgrade' count: 1 } ] 'X-Wing Expansion Pack': [ { name: 'X-Wing' type: 'ship' count: 1 } { name: 'Wedge Antilles' type: 'pilot' count: 1 } { name: 'Garven Dreis' type: 'pilot' count: 1 } { name: 'Red Squadron Pilot' type: 'pilot' count: 1 } { name: 'Rookie Pilot' type: 'pilot' count: 1 } { name: 'Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'R5-K6' type: 'upgrade' count: 1 } { name: 'R5 Astromech' type: 'upgrade' count: 1 } { name: 'Expert Handling' type: 'upgrade' count: 1 } { name: 'Marksmanship' type: 'upgrade' count: 1 } ] 'Y-Wing Expansion Pack': [ { name: 'Y-Wing' type: 'ship' count: 1 } { name: 'Horton Salm' type: 'pilot' count: 1 } { name: '"Dutch" Vander' type: 'pilot' count: 1 } { name: 'Gray Squadron Pilot' type: 'pilot' count: 1 } { name: 'Gold Squadron Pilot' type: 'pilot' count: 1 } { name: 'Proton Torpedoes' type: 'upgrade' count: 2 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 1 } { name: 'R5-D8' type: 'upgrade' count: 1 } { name: 'R2 Astromech' type: 'upgrade' count: 1 } ] 'TIE Fighter Expansion Pack': [ { name: 'TIE Fighter' type: 'ship' count: 1 } { name: '"Howlrunner"' type: 'pilot' count: 1 } { name: '"Backstabber"' type: 'pilot' count: 1 } { name: '"Winged Gundark"' type: 'pilot' count: 1 } { name: 'Black Squadron Pilot' type: 'pilot' count: 1 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 1 } { name: 'Academy Pilot' type: 'pilot' count: 1 } { name: 'Determination' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 1 } ] 'TIE Advanced Expansion Pack': [ { name: 'TIE Advanced' type: 'ship' count: 1 } { name: 'Darth Vader' type: 'pilot' count: 1 } { name: 'Maarek Stele' type: 'pilot' count: 1 } { name: 'Storm Squadron Pilot' type: 'pilot' count: 1 } { name: 'Tempest Squadron Pilot' type: 'pilot' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 1 } { name: 'Expert Handling' type: 'upgrade' count: 1 } ] 'A-Wing Expansion Pack': [ { name: 'A-Wing' type: 'ship' count: 1 } { name: 'Tycho Celchu' type: 'pilot' count: 1 } { name: 'Arvel Crynyd' type: 'pilot' count: 1 } { name: 'Green Squadron Pilot' type: 'pilot' count: 1 } { name: 'Prototype Pilot' type: 'pilot' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 1 } { name: 'Homing Missiles' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: 'Push the Limit' type: 'upgrade' count: 1 } { name: 'Deadeye' type: 'upgrade' count: 1 } ] 'Millennium Falcon Expansion Pack': [ { name: 'YT-1300' type: 'ship' count: 1 } { name: 'Han Solo' type: 'pilot' count: 1 } { name: 'Lando Calrissian' type: 'pilot' count: 1 } { name: 'Chewbacca' type: 'pilot' count: 1 } { name: 'Outer Rim Smuggler' type: 'pilot' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 1 } { name: 'Assault Missiles' type: 'upgrade' count: 1 } { name: 'Elusiveness' type: 'upgrade' count: 1 } { name: 'Draw Their Fire' type: 'upgrade' count: 1 } { name: 'Veteran Instincts' type: 'upgrade' count: 1 } { name: 'Luke Skywalker' type: 'upgrade' count: 1 } { name: 'Nien Nunb' type: 'upgrade' count: 1 } { name: 'Chewbacca' type: 'upgrade' count: 1 } { name: 'Weapons Engineer' type: 'upgrade' count: 1 } { name: 'Shield Upgrade' type: 'modification' count: 2 } { name: 'Engine Upgrade' type: 'modification' count: 2 } { name: 'Millennium Falcon' type: 'title' count: 1 } ] 'TIE Interceptor Expansion Pack': [ { name: 'TIE Interceptor' type: 'ship' count: 1 } { name: 'Soontir Fel' type: 'pilot' count: 1 } { name: 'Turr Phennir' type: 'pilot' count: 1 } { name: '''"Fel's Wrath"''' type: 'pilot' count: 1 } { name: 'Saber Squadron Pilot' type: 'pilot' count: 1 } { name: 'Avenger Squadron Pilot' type: 'pilot' count: 1 } { name: 'Alpha Squadron Pilot' type: 'pilot' count: 1 } { name: 'Daredevil' type: 'upgrade' count: 1 } { name: 'Elusiveness' type: 'upgrade' count: 1 } ] 'Slave I Expansion Pack': [ { name: 'Firespray-31' type: 'ship' count: 1 } { name: 'Boba Fett' type: 'pilot' count: 1 } { name: 'Kath Scarlet' type: 'pilot' count: 1 } { name: 'Krassis Trelix' type: 'pilot' count: 1 } { name: 'Bounty Hunter' type: 'pilot' count: 1 } { name: 'Homing Missiles' type: 'upgrade' count: 1 } { name: 'Assault Missiles' type: 'upgrade' count: 1 } { name: 'Ion Cannon' type: 'upgrade' count: 1 } { name: 'Heavy Laser Cannon' type: 'upgrade' count: 1 } { name: 'Veteran Instincts' type: 'upgrade' count: 1 } { name: 'Expose' type: 'upgrade' count: 1 } { name: 'Seismic Charges' type: 'upgrade' count: 1 } { name: 'Proximity Mines' type: 'upgrade' count: 1 } { name: 'Gunner' type: 'upgrade' count: 1 } { name: 'Mercenary Copilot' type: 'upgrade' count: 1 } { name: 'Stealth Device' type: 'modification' count: 2 } { name: 'Slave I' type: 'title' count: 1 } ] 'B-Wing Expansion Pack': [ { name: 'B-Wing' type: 'ship' count: 1 } { name: 'Ten Numb' type: 'pilot' count: 1 } { name: 'Ibtisam' type: 'pilot' count: 1 } { name: 'Dagger Squadron Pilot' type: 'pilot' count: 1 } { name: 'Blue Squadron Pilot' type: 'pilot' count: 1 } { name: 'Fire-Control System' type: 'upgrade' count: 1 } { name: 'Advanced Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'Ion Cannon' type: 'upgrade' count: 1 } { name: 'Autoblaster' type: 'upgrade' count: 1 } ] "HWK-290 Expansion Pack": [ { name: 'HWK-290' type: 'ship' count: 1 } { name: 'Jan Ors' type: 'pilot' count: 1 } { name: 'Kyle Katarn' type: 'pilot' count: 1 } { name: 'Roark Garnet' type: 'pilot' count: 1 } { name: 'Rebel Operative' type: 'pilot' count: 1 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 1 } { name: 'Recon Specialist' type: 'upgrade' count: 1 } { name: 'Moldy Crow' type: 'title' count: 1 } { name: 'Blaster Turret' type: 'upgrade' count: 1 } { name: 'Saboteur' type: 'upgrade' count: 1 } { name: 'Intelligence Agent' type: 'upgrade' count: 1 } ] "TIE Bomber Expansion Pack": [ { name: 'TIE Bomber' type: 'ship' count: 1 } { name: 'Major Rhymer' type: 'pilot' count: 1 } { name: 'Captain Jonus' type: 'pilot' count: 1 } { name: 'Gamma Squadron Pilot' type: 'pilot' count: 1 } { name: 'Scimitar Squadron Pilot' type: 'pilot' count: 1 } { name: 'Proton Bombs' type: 'upgrade' count: 1 } { name: 'Assault Missiles' type: 'upgrade' count: 1 } { name: 'Advanced Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'Seismic Charges' type: 'upgrade' count: 1 } { name: 'Adrenaline Rush' type: 'upgrade' count: 1 } ] "Lambda-Class Shuttle Expansion Pack": [ { name: 'Lambda-Class Shuttle' type: 'ship' count: 1 } { name: 'Captain Kagi' type: 'pilot' count: 1 } { name: 'Colonel Jendon' type: 'pilot' count: 1 } { name: 'Captain Yorr' type: 'pilot' count: 1 } { name: 'Omicron Group Pilot' type: 'pilot' count: 1 } { name: 'Sensor Jammer' type: 'upgrade' count: 1 } { name: 'Rebel Captive' type: 'upgrade' count: 1 } { name: 'Advanced Sensors' type: 'upgrade' count: 1 } { name: 'ST-321' type: 'title' count: 1 } { name: 'Heavy Laser Cannon' type: 'upgrade' count: 1 } { name: 'Weapons Engineer' type: 'upgrade' count: 1 } { name: 'Darth Vader' type: 'upgrade' count: 1 } { name: 'Intelligence Agent' type: 'upgrade' count: 1 } { name: 'Navigator' type: 'upgrade' count: 1 } { name: 'Flight Instructor' type: 'upgrade' count: 1 } { name: 'Anti-Pursuit Lasers' type: 'modification' count: 2 } ] "Z-95 Headhunter Expansion Pack": [ { name: 'Z-95 Headhunter' type: 'ship' count: 1 } { name: 'Airen Cracken' type: 'pilot' count: 1 } { name: 'Lieutenant Blount' type: 'pilot' count: 1 } { name: 'Tala Squadron Pilot' type: 'pilot' count: 1 } { name: 'Bandit Squadron Pilot' type: 'pilot' count: 1 } { name: 'Munitions Failsafe' type: 'modification' count: 1 } { name: 'Decoy' type: 'upgrade' count: 1 } { name: 'Wingman' type: 'upgrade' count: 1 } { name: 'Ion Pulse Missiles' type: 'upgrade' count: 1 } { name: 'Assault Missiles' type: 'upgrade' count: 1 } ] 'E-Wing Expansion Pack': [ { name: 'E-Wing' type: 'ship' count: 1 } { name: 'Corran Horn' type: 'pilot' count: 1 } { name: "Etahn A'baht" type: 'pilot' count: 1 } { name: 'Blackmoon Squadron Pilot' type: 'pilot' count: 1 } { name: 'Knave Squadron Pilot' type: 'pilot' count: 1 } { name: 'Advanced Sensors' type: 'upgrade' count: 1 } { name: 'Outmaneuver' type: 'upgrade' count: 1 } { name: 'R7-T1' type: 'upgrade' count: 1 } { name: 'R7 Astromech' type: 'upgrade' count: 1 } { name: 'Flechette Torpedoes' type: 'upgrade' count: 1 } ] 'TIE Defender Expansion Pack': [ { name: 'TIE Defender' type: 'ship' count: 1 } { name: 'Rexler Brath' type: 'pilot' count: 1 } { name: 'Colonel Vessery' type: 'pilot' count: 1 } { name: 'Onyx Squadron Pilot' type: 'pilot' count: 1 } { name: 'Delta Squadron Pilot' type: 'pilot' count: 1 } { name: 'Munitions Failsafe' type: 'modification' count: 1 } { name: 'Predator' type: 'upgrade' count: 1 } { name: 'Outmaneuver' type: 'upgrade' count: 1 } { name: 'Ion Cannon' type: 'upgrade' count: 1 } { name: 'Ion Pulse Missiles' type: 'upgrade' count: 1 } ] 'TIE Phantom Expansion Pack': [ { name: 'TIE Phantom' type: 'ship' count: 1 } { name: '"Whisper"' type: 'pilot' count: 1 } { name: '"Echo"' type: 'pilot' count: 1 } { name: 'Shadow Squadron Pilot' type: 'pilot' count: 1 } { name: 'Sigma Squadron Pilot' type: 'pilot' count: 1 } { name: 'Fire-Control System' type: 'upgrade' count: 1 } { name: 'Tactician' type: 'upgrade' count: 1 } { name: 'Recon Specialist' type: 'upgrade' count: 1 } { name: 'Advanced Cloaking Device' type: 'modification' count: 1 } { name: 'Stygium Particle Accelerator' type: 'modification' count: 1 } ] 'YT-2400 Freighter Expansion Pack': [ { name: 'YT-2400' type: 'ship' count: 1 } { name: 'Dash Rendar' type: 'pilot' count: 1 } { name: 'Eaden Vrill' type: 'pilot' count: 1 } { name: '"Leebo"' type: 'pilot' count: 1 } { name: 'Wild Space Fringer' type: 'pilot' count: 1 } { name: 'Experimental Interface' type: 'modification' count: 1 } { name: 'Countermeasures' type: 'modification' count: 2 } { name: 'Outrider' type: 'title' count: 1 } { name: 'Lone Wolf' type: 'upgrade' count: 1 } { name: '"Leebo"' type: 'upgrade' count: 1 } { name: 'Lando Calrissian' type: 'upgrade' count: 1 } { name: 'Stay On Target' type: 'upgrade' count: 1 } { name: 'Dash Rendar' type: 'upgrade' count: 1 } { name: 'Gunner' type: 'upgrade' count: 1 } { name: 'Mercenary Copilot' type: 'upgrade' count: 1 } { name: 'Proton Rockets' type: 'upgrade' count: 1 } { name: 'Heavy Laser Cannon' type: 'upgrade' count: 1 } ] "VT-49 Decimator Expansion Pack": [ { name: 'VT-49 Decimator' type: 'ship' count: 1 } { name: 'Captain Oicunn' type: 'pilot' count: 1 } { name: 'Rear Admiral Chiraneau' type: 'pilot' count: 1 } { name: 'Commander Kenkirk' type: 'pilot' count: 1 } { name: 'Patrol Leader' type: 'pilot' count: 1 } { name: 'Ruthlessness' type: 'upgrade' count: 2 } { name: 'Dauntless' type: 'title' count: 1 } { name: 'Ysanne Isard' type: 'upgrade' count: 1 } { name: 'Moff Jerjerrod' type: 'upgrade' count: 1 } { name: 'Intimidation' type: 'upgrade' count: 1 } { name: 'Tactical Jammer' type: 'modification' count: 2 } { name: 'Proton Bombs' type: 'upgrade' count: 1 } { name: 'Mara Jade' type: 'upgrade' count: 1 } { name: 'Fleet Officer' type: 'upgrade' count: 1 } { name: 'Ion Torpedoes' type: 'upgrade' count: 2 } ] 'Imperial Aces Expansion Pack': [ { name: 'TIE Interceptor' type: 'ship' count: 2 } { name: 'Carnor Jax' type: 'pilot' count: 1 } { name: 'Kir Kanos' type: 'pilot' count: 1 } { name: 'Royal Guard Pilot' type: 'pilot' count: 2 } { name: 'Tetran Cowall' type: 'pilot' count: 1 } { name: 'Lieutenant Lorrir' type: 'pilot' count: 1 } { name: 'Saber Squadron Pilot' type: 'pilot' count: 2 } { name: 'Royal Guard TIE' type: 'title' count: 2 } { name: 'Targeting Computer' type: 'modification' count: 2 } { name: 'Hull Upgrade' type: 'modification' count: 2 } { name: 'Push the Limit' type: 'upgrade' count: 2 } { name: 'Opportunist' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'modification' count: 2 } ] 'Rebel Aces Expansion Pack': [ { name: 'A-Wing' type: 'ship' count: 1 } { name: 'B-Wing' type: 'ship' count: 1 } { name: 'Jake Farrell' type: 'pilot' count: 1 } { name: 'Gemmer Sojan' type: 'pilot' count: 1 } { name: 'Green Squadron Pilot' type: 'pilot' count: 1 } { name: 'Prototype Pilot' type: 'pilot' count: 1 } { name: 'Keyan Farlander' type: 'pilot' count: 1 } { name: 'Nera Dantels' type: 'pilot' count: 1 } { name: 'Dagger Squadron Pilot' type: 'pilot' count: 1 } { name: 'Blue Squadron Pilot' type: 'pilot' count: 1 } { name: 'Chardaan Refit' type: 'upgrade' count: 3 } { name: 'A-Wing Test Pilot' type: 'title' count: 2 } { name: 'Enhanced Scopes' type: 'upgrade' count: 2 } { name: 'Proton Rockets' type: 'upgrade' count: 2 } { name: 'B-Wing/E2' type: 'modification' count: 2 } { name: 'Kyle Katarn' type: 'upgrade' count: 1 } { name: 'Jan Ors' type: 'upgrade' count: 1 } ] 'Rebel Transport Expansion Pack': [ { name: 'X-Wing' type: 'ship' count: 1 } { name: 'GR-75 Medium Transport' type: 'ship' count: 1 } { name: 'GR-75 Medium Transport' type: 'pilot' count: 1 } { name: 'Wes Janson' type: 'pilot' count: 1 } { name: 'Jek Porkins' type: 'pilot' count: 1 } { name: '"Hobbie" Klivian' type: 'pilot' count: 1 } { name: 'Tarn Mison' type: 'pilot' count: 1 } { name: 'Red Squadron Pilot' type: 'pilot' count: 1 } { name: 'Rookie Pilot' type: 'pilot' count: 1 } { name: 'Dutyfree' type: 'title' count: 1 } { name: 'Quantum Storm' type: 'title' count: 1 } { name: 'Bright Hope' type: 'title' count: 1 } { name: 'Expanded Cargo Hold' type: 'upgrade' count: 1 } { name: 'R2-D6' type: 'upgrade' count: 1 } { name: 'R4-D6' type: 'upgrade' count: 1 } { name: 'Flechette Torpedoes' type: 'upgrade' count: 3 } { name: 'R3-A2' type: 'upgrade' count: 1 } { name: 'WED-15 Repair Droid' type: 'upgrade' count: 1 } { name: 'Backup Shield Generator' type: 'upgrade' count: 1 } { name: 'Carlist Rieekan' type: 'upgrade' count: 1 } { name: 'EM Emitter' type: 'upgrade' count: 1 } { name: 'Engine Booster' type: 'upgrade' count: 1 } { name: 'R5-P9' type: 'upgrade' count: 1 } { name: 'Comms Booster' type: 'upgrade' count: 1 } { name: 'Frequency Jammer' type: 'upgrade' count: 1 } { name: 'Shield Projector' type: 'upgrade' count: 1 } { name: 'Tibanna Gas Supplies' type: 'upgrade' count: 1 } { name: 'Jan Dodonna' type: 'upgrade' count: 1 } { name: 'Toryn Farr' type: 'upgrade' count: 1 } { name: 'Slicer Tools' type: 'upgrade' count: 1 } { name: 'Combat Retrofit' type: 'modification' count: 1 } ] 'Tantive IV Expansion Pack': [ { name: 'CR90 Corvette (Fore)' type: 'ship' count: 1 } { name: 'CR90 Corvette (Aft)' type: 'ship' count: 1 } { name: 'CR90 Corvette (Fore)' type: 'pilot' count: 1 } # { # name: 'CR90 Corvette (Crippled Fore)' # type: 'pilot' # count: 1 # } { name: 'CR90 Corvette (Aft)' type: 'pilot' count: 1 } # { # name: 'CR90 Corvette (Crippled Aft)' # type: 'pilot' # count: 1 # } { name: "Jaina's Light" type: 'title' count: 1 } { name: "Dodonna's Pride" type: 'title' count: 1 } { name: 'Tantive IV' type: 'title' count: 1 } { name: 'Backup Shield Generator' type: 'upgrade' count: 1 } { name: 'Han Solo' type: 'upgrade' count: 1 } { name: 'C-3PO' type: 'upgrade' count: 1 } { name: 'Engine Booster' type: 'upgrade' count: 1 } { name: 'Comms Booster' type: 'upgrade' count: 2 } { name: 'Engineering Team' type: 'upgrade' count: 1 } { name: 'Gunnery Team' type: 'upgrade' count: 1 } { name: 'Ionization Reactor' type: 'upgrade' count: 1 } { name: 'Leia Organa' type: 'upgrade' count: 1 } { name: 'R2-D2 (Crew)' type: 'upgrade' count: 1 } { name: 'Sensor Team' type: 'upgrade' count: 1 } { name: 'Targeting Coordinator' type: 'upgrade' count: 1 } { name: 'Tibanna Gas Supplies' type: 'upgrade' count: 1 } { name: 'Raymus Antilles' type: 'upgrade' count: 1 } { name: 'Quad Laser Cannons' type: 'upgrade' count: 3 } { name: 'Single Turbolasers' type: 'upgrade' count: 3 } ] 'StarViper Expansion Pack': [ { name: 'StarViper' type: 'ship' count: 1 } { name: 'Prince Xizor' type: 'pilot' count: 1 } { name: 'Guri' type: 'pilot' count: 1 } { name: 'Black Sun Vigo' type: 'pilot' count: 1 } { name: 'Black Sun Enforcer' type: 'pilot' count: 1 } { name: 'Virago' type: 'title' count: 1 } { name: 'Bodyguard' type: 'upgrade' count: 1 } { name: 'Accuracy Corrector' type: 'upgrade' count: 1 } { name: 'Inertial Dampeners' type: 'upgrade' count: 1 } { name: 'Autothrusters' type: 'modification' count: 2 } { name: 'Calculation' type: 'upgrade' count: 1 } { name: 'Ion Torpedoes' type: 'upgrade' count: 1 } { name: 'Hull Upgrade' type: 'modification' count: 1 } ] "M3-A Interceptor Expansion Pack": [ { name: 'M3-A Interceptor' type: 'ship' count: 1 } { name: 'Serissu' type: 'pilot' count: 1 } { name: "Laetin A'shera" type: 'pilot' count: 1 } { name: "Tansarii Point Veteran" type: 'pilot' count: 1 } { name: "Cartel Spacer" type: 'pilot' count: 1 } { name: '"Heavy Scyk" Interceptor' type: 'title' count: 1 skipForSource: true # special :( } { name: '"Heavy Scyk" Interceptor (Cannon)' type: 'title' count: 0 # special :( } { name: '"Heavy Scyk" Interceptor (Missile)' type: 'title' count: 0 # special :( } { name: '"Heavy Scyk" Interceptor (Torpedo)' type: 'title' count: 0 # special :( } { name: 'Flechette Cannon' type: 'upgrade' count: 1 } { name: 'Ion Cannon' type: 'upgrade' count: 1 } { name: '"Mangler" Cannon' type: 'upgrade' count: 1 } { name: 'Stealth Device' type: 'modification' count: 1 } ] "IG-2000 Expansion Pack": [ { name: 'Aggressor' type: 'ship' count: 1 } { name: 'IG-88A' type: 'pilot' count: 1 } { name: 'IG-88B' type: 'pilot' count: 1 } { name: 'IG-88C' type: 'pilot' count: 1 } { name: 'IG-88D' type: 'pilot' count: 1 } { name: 'IG-2000' type: 'title' count: 1 } { name: 'Accuracy Corrector' type: 'upgrade' count: 1 } { name: 'Autoblaster' type: 'upgrade' count: 1 } { name: '"Mangler" Cannon' type: 'upgrade' count: 1 } { name: 'Proximity Mines' type: 'upgrade' count: 1 } { name: 'Seismic Charges' type: 'upgrade' count: 1 } { name: "Dead Man's Switch" type: 'upgrade' count: 2 } { name: 'Feedback Array' type: 'upgrade' count: 2 } { name: '"Hot Shot" Blaster' type: 'upgrade' count: 1 } { name: 'Inertial Dampeners' type: 'upgrade' count: 1 } ] "Most Wanted Expansion Pack": [ { name: 'Z-95 Headhunter' type: 'ship' count: 2 } { name: 'Y-Wing' type: 'ship' count: 1 } { name: "N'Dru Suhlak" type: 'pilot' count: 1 } { name: "Kaa'to Leeachos" type: 'pilot' count: 1 } { name: "Black Sun Soldier" type: 'pilot' count: 2 } { name: "Binayre Pirate" type: 'pilot' count: 2 } { name: "Kavil" type: 'pilot' count: 1 } { name: "Drea Renthal" type: 'pilot' count: 1 } { name: "Hired Gun" type: 'pilot' count: 2 } { name: "Syndicate Thug" type: 'pilot' count: 2 } { name: "Boba Fett (Scum)" type: 'pilot' count: 1 } { name: "Kath Scarlet (Scum)" type: 'pilot' count: 1 } { name: "Emon Azzameen" type: 'pilot' count: 1 } { name: "Mandalorian Mercenary" type: 'pilot' count: 1 } { name: "Dace Bonearm" type: 'pilot' count: 1 } { name: "Palob Godalhi" type: 'pilot' count: 1 } { name: "Torkil Mux" type: 'pilot' count: 1 } { name: "Spice Runner" type: 'pilot' count: 1 } { name: "Greedo" type: 'upgrade' count: 1 } { name: "K4 Security Droid" type: 'upgrade' count: 1 } { name: "Outlaw Tech" type: 'upgrade' count: 1 } { name: "Autoblaster Turret" type: 'upgrade' count: 2 } { name: "Bomb Loadout" type: 'upgrade' count: 2 } { name: "R4-B11" type: 'upgrade' count: 1 } { name: '"Genius"' type: 'upgrade' count: 1 } { name: "R4 Agromech" type: 'upgrade' count: 2 } { name: "Salvaged Astromech" type: 'upgrade' count: 2 } { name: "Unhinged Astromech" type: 'upgrade' count: 2 } { name: "BTL-A4 Y-Wing" type: 'title' count: 2 } { name: "Andrasta" type: 'title' count: 1 } { name: '"Hot Shot" Blaster' type: 'upgrade' count: 1 } ] "Hound's Tooth Expansion Pack": [ { name: 'YV-666' type: 'ship' count: 1 } { name: 'Bossk' type: 'pilot' count: 1 } { name: 'Moralo Eval' type: 'pilot' count: 1 } { name: 'Latts Razzi' type: 'pilot' count: 1 } { name: 'Trandoshan Slaver' type: 'pilot' count: 1 } { name: 'Lone Wolf' type: 'upgrade' count: 1 } { name: 'Crack Shot' type: 'upgrade' count: 1 } { name: 'Stay On Target' type: 'upgrade' count: 1 } { name: 'Heavy Laser Cannon' type: 'upgrade' count: 1 } { name: 'Bossk' type: 'upgrade' count: 1 } { name: 'K4 Security Droid' type: 'upgrade' count: 1 } { name: 'Outlaw Tech' type: 'upgrade' count: 1 } { name: 'Glitterstim' type: 'upgrade' count: 1 } { name: 'Engine Upgrade' type: 'modification' count: 1 } { name: 'Ion Projector' type: 'modification' count: 2 } { name: 'Maneuvering Fins' type: 'modification' count: 1 } { name: "Hound's Tooth" type: 'title' count: 1 } ] 'Kihraxz Fighter Expansion Pack': [ { name: 'Kihraxz Fighter' type: 'ship' count: 1 } { name: 'Talonbane Cobra' type: 'pilot' count: 1 } { name: 'Graz the Hunter' type: 'pilot' count: 1 } { name: 'Black Sun Ace' type: 'pilot' count: 1 } { name: 'Cartel Marauder' type: 'pilot' count: 1 } { name: 'Crack Shot' type: 'upgrade' count: 1 } { name: 'Lightning Reflexes' type: 'upgrade' count: 1 } { name: 'Predator' type: 'upgrade' count: 1 } { name: 'Homing Missiles' type: 'upgrade' count: 1 } { name: 'Glitterstim' type: 'upgrade' count: 1 } ] 'K-Wing Expansion Pack': [ { name: 'K-Wing' type: 'ship' count: 1 } { name: 'Miranda Doni' type: 'pilot' count: 1 } { name: 'Esege Tuketu' type: 'pilot' count: 1 } { name: 'Guardian Squadron Pilot' type: 'pilot' count: 1 } { name: 'Warden Squadron Pilot' type: 'pilot' count: 1 } { name: 'Twin Laser Turret' type: 'upgrade' count: 2 } { name: 'Plasma Torpedoes' type: 'upgrade' count: 1 } { name: 'Advanced Homing Missiles' type: 'upgrade' count: 1 } { name: 'Bombardier' type: 'upgrade' count: 1 } { name: 'Conner Net' type: 'upgrade' count: 1 } { name: 'Extra Munitions' type: 'upgrade' count: 1 } { name: 'Ion Bombs' type: 'upgrade' count: 1 } { name: 'Advanced SLAM' type: 'modification' count: 1 } ] 'TIE Punisher Expansion Pack': [ { name: 'TIE Punisher' type: 'ship' count: 1 } { name: '"Redline"' type: 'pilot' count: 1 } { name: '"Deathrain"' type: 'pilot' count: 1 } { name: 'Black Eight Squadron Pilot' type: 'pilot' count: 1 } { name: 'Cutlass Squadron Pilot' type: 'pilot' count: 1 } { name: 'Enhanced Scopes' type: 'upgrade' count: 1 } { name: 'Extra Munitions' type: 'upgrade' count: 1 } { name: 'Flechette Torpedoes' type: 'upgrade' count: 1 } { name: 'Plasma Torpedoes' type: 'upgrade' count: 1 } { name: 'Advanced Homing Missiles' type: 'upgrade' count: 1 } { name: 'Cluster Mines' type: 'upgrade' count: 1 } { name: 'Ion Bombs' type: 'upgrade' count: 1 } { name: 'Twin Ion Engine Mk. II' type: 'modification' count: 2 } ] "Imperial Raider Expansion Pack": [ { name: "Raider-class Corvette (Fore)" type: 'ship' count: 1 } { name: "Raider-class Corvette (Aft)" type: 'ship' count: 1 } { name: "TIE Advanced" type: 'ship' count: 1 } { name: "Raider-class Corvette (Fore)" type: 'pilot' count: 1 } { name: "Raider-class Corvette (Aft)" type: 'pilot' count: 1 } { name: "Juno Eclipse" type: 'pilot' count: 1 } { name: "Zertik Strom" type: 'pilot' count: 1 } { name: "Commander Alozen" type: 'pilot' count: 1 } { name: "Lieutenant Colzet" type: 'pilot' count: 1 } { name: "Storm Squadron Pilot" type: 'pilot' count: 1 } { name: "Tempest Squadron Pilot" type: 'pilot' count: 1 } { name: "Advanced Targeting Computer" type: 'upgrade' count: 4 } { name: "TIE/x1" type: 'title' count: 4 } { name: "Cluster Missiles" type: 'upgrade' count: 1 } { name: "Proton Rockets" type: 'upgrade' count: 1 } { name: "Captain Needa" type: 'upgrade' count: 1 } { name: "Grand Moff Tarkin" type: 'upgrade' count: 1 } { name: "Emperor Palpatine" type: 'upgrade' count: 1 } { name: "Admiral Ozzel" type: 'upgrade' count: 1 } { name: "Shield Technician" type: 'upgrade' count: 2 } { name: "Gunnery Team" type: 'upgrade' count: 1 } { name: "Engineering Team" type: 'upgrade' count: 1 } { name: "Sensor Team" type: 'upgrade' count: 1 } { name: "Single Turbolasers" type: 'upgrade' count: 2 } { name: "Ion Cannon Battery" type: 'upgrade' count: 4 } { name: "Quad Laser Cannons" type: 'upgrade' count: 2 } { name: "Tibanna Gas Supplies" type: 'upgrade' count: 2 } { name: "Engine Booster" type: 'upgrade' count: 1 } { name: "Backup Shield Generator" type: 'upgrade' count: 1 } { name: "Comms Booster" type: 'upgrade' count: 1 } { name: "Assailer" type: 'title' count: 1 } { name: "Instigator" type: 'title' count: 1 } { name: "Impetuous" type: 'title' count: 1 } ] 'The Force Awakens Core Set': [ { name: 'T-70 X-Wing' type: 'ship' count: 1 } { name: 'TIE/fo Fighter' type: 'ship' count: 2 } { name: 'Poe Dameron' type: 'pilot' count: 1 } { name: '"Blue Ace"' type: 'pilot' count: 1 } { name: 'Red Squadron Veteran' type: 'pilot' count: 1 } { name: 'Blue Squadron Novice' type: 'pilot' count: 1 } { name: '"Omega Ace"' type: 'pilot' count: 1 } { name: '"Epsilon Leader"' type: 'pilot' count: 1 } { name: '"Zeta Ace"' type: 'pilot' count: 1 } { name: 'Omega Squadron Pilot' type: 'pilot' count: 2 } { name: 'Zeta Squadron Pilot' type: 'pilot' count: 2 } { name: 'Epsilon Squadron Pilot' type: 'pilot' count: 2 } { name: 'Wired' type: 'upgrade' count: 1 } { name: 'BB-8' type: 'upgrade' count: 1 } { name: 'R5-X3' type: 'upgrade' count: 1 } { name: 'Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'Weapons Guidance' type: 'upgrade' count: 1 } ] 'Imperial Assault Carrier Expansion Pack': [ { name: 'TIE Fighter' type: 'ship' count: 2 } { name: 'Gozanti-class Cruiser' type: 'ship' count: 1 } { name: 'Gozanti-class Cruiser' type: 'pilot' count: 1 } { name: '"Scourge"' type: 'pilot' count: 1 } { name: '"Wampa"' type: 'pilot' count: 1 } { name: '"Youngster"' type: 'pilot' count: 1 } { name: '"Chaser"' type: 'pilot' count: 1 } { name: 'Academy Pilot' type: 'pilot' count: 2 } { name: 'Black Squadron Pilot' type: 'pilot' count: 2 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 2 } { name: 'Marksmanship' type: 'upgrade' count: 1 } { name: 'Expert Handling' type: 'upgrade' count: 1 } { name: 'Expose' type: 'upgrade' count: 1 } { name: 'Ion Torpedoes' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: 'Homing Missiles' type: 'upgrade' count: 1 } { name: 'Dual Laser Turret' type: 'upgrade' count: 1 } { name: 'Broadcast Array' type: 'upgrade' count: 1 } { name: 'Construction Droid' type: 'upgrade' count: 2 } { name: 'Agent Kallus' type: 'upgrade' count: 1 } { name: 'Rear Admiral Chiraneau' type: 'upgrade' count: 1 } { name: 'Ordnance Experts' type: 'upgrade' count: 2 } { name: 'Docking Clamps' type: 'upgrade' count: 1 } { name: 'Cluster Bombs' type: 'upgrade' count: 2 } { name: 'Automated Protocols' type: 'modification' count: 3 } { name: 'Optimized Generators' type: 'modification' count: 3 } { name: 'Ordnance Tubes' type: 'modification' count: 2 } { name: 'Requiem' type: 'title' count: 1 } { name: 'Vector' type: 'title' count: 1 } { name: 'Suppressor' type: 'title' count: 1 } ] 'T-70 X-Wing Expansion Pack': [ { name: 'T-70 X-Wing' type: 'ship' count: 1 } { name: 'Ello Asty' type: 'pilot' count: 1 } { name: '"Red Ace"' type: 'pilot' count: 1 } { name: 'Red Squadron Veteran' type: 'pilot' count: 1 } { name: 'Blue Squadron Novice' type: 'pilot' count: 1 } { name: 'Cool Hand' type: 'upgrade' count: 1 } { name: 'Targeting Astromech' type: 'upgrade' count: 1 } { name: 'Weapons Guidance' type: 'upgrade' count: 1 } { name: 'Integrated Astromech' type: 'modification' count: 1 } { name: 'Advanced Proton Torpedoes' type: 'upgrade' count: 1 } ] 'TIE/fo Fighter Expansion Pack': [ { name: 'TIE/fo Fighter' type: 'ship' count: 1 } { name: '"Omega Leader"' type: 'pilot' count: 1 } { name: '"Zeta Leader"' type: 'pilot' count: 1 } { name: '"Epsilon Ace"' type: 'pilot' count: 1 } { name: 'Omega Squadron Pilot' type: 'pilot' count: 1 } { name: 'Zeta Squadron Pilot' type: 'pilot' count: 1 } { name: 'Epsilon Squadron Pilot' type: 'pilot' count: 1 } { name: 'Juke' type: 'upgrade' count: 1 } { name: 'Comm Relay' type: 'upgrade' count: 1 } ] 'Ghost Expansion Pack': [ { name: 'VCX-100' type: 'ship' count: 1 } { name: 'Attack Shuttle' type: 'ship' count: 1 } { name: 'Hera Syndulla' type: 'pilot' count: 1 } { name: 'Kanan Jarrus' type: 'pilot' count: 1 } { name: '"Chopper"' type: 'pilot' count: 1 } { name: 'Lothal Rebel' type: 'pilot' count: 1 } { name: 'Hera Syndulla (Attack Shuttle)' type: 'pilot' count: 1 } { name: 'Sabine Wren' type: 'pilot' count: 1 } { name: 'Ezra Bridger' type: 'pilot' count: 1 } { name: '"Zeb" Orrelios' type: 'pilot' count: 1 } { name: 'Predator' type: 'upgrade' count: 1 } { name: 'Reinforced Deflectors' type: 'upgrade' count: 1 } { name: 'Dorsal Turret' type: 'upgrade' count: 2 } { name: 'Advanced Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'Hera Syndulla' type: 'upgrade' count: 1 } { name: '"Zeb" Orrelios' type: 'upgrade' count: 1 } { name: 'Kanan Jarrus' type: 'upgrade' count: 1 } { name: 'Ezra Bridger' type: 'upgrade' count: 1 } { name: 'Sabine Wren' type: 'upgrade' count: 1 } { name: '"Chopper"' type: 'upgrade' count: 1 } { name: 'Conner Net' type: 'upgrade' count: 1 } { name: 'Cluster Mines' type: 'upgrade' count: 1 } { name: 'Thermal Detonators' type: 'upgrade' count: 1 } { name: 'Ghost' type: 'title' count: 1 } { name: 'Phantom' type: 'title' count: 1 } ] 'Punishing One Expansion Pack': [ { name: 'JumpMaster 5000' type: 'ship' count: 1 } { name: 'Dengar' type: 'pilot' count: 1 } { name: 'Tel Trevura' type: 'pilot' count: 1 } { name: 'Manaroo' type: 'pilot' count: 1 } { name: 'Contracted Scout' type: 'pilot' count: 1 } { name: 'Rage' type: 'upgrade' count: 1 } { name: 'Attanni Mindlink' type: 'upgrade' count: 2 } { name: 'Plasma Torpedoes' type: 'upgrade' count: 1 } { name: 'Dengar' type: 'upgrade' count: 1 } { name: 'Boba Fett' type: 'upgrade' count: 1 } { name: '"Gonk"' type: 'upgrade' count: 1 } { name: 'R5-P8' type: 'upgrade' count: 1 } { name: 'Overclocked R4' type: 'upgrade' count: 2 } { name: 'Feedback Array' type: 'upgrade' count: 1 } { name: 'Punishing One' type: 'title' count: 1 } { name: 'Guidance Chips' type: 'modification' count: 2 } ] 'Mist Hunter Expansion Pack': [ { name: 'G-1A Starfighter' type: 'ship' count: 1 } { name: 'Zuckuss' type: 'pilot' count: 1 } { name: '4-LOM' type: 'pilot' count: 1 } { name: 'Gand Findsman' type: 'pilot' count: 1 } { name: 'Ruthless Freelancer' type: 'pilot' count: 1 } { name: 'Adaptability' type: 'upgrade' count: 2 } { name: 'Tractor Beam' type: 'upgrade' count: 1 } { name: 'Electronic Baffle' type: 'upgrade' count: 2 } { name: '4-LOM' type: 'upgrade' count: 1 } { name: 'Zuckuss' type: 'upgrade' count: 1 } { name: 'Cloaking Device' type: 'upgrade' count: 1 } { name: 'Mist Hunter' type: 'title' count: 1 } ] "Inquisitor's TIE Expansion Pack": [ { name: 'TIE Advanced Prototype' type: 'ship' count: 1 } { name: 'The Inquisitor' type: 'pilot' count: 1 } { name: 'Valen Rudor' type: 'pilot' count: 1 } { name: 'Baron of the Empire' type: 'pilot' count: 1 } { name: 'Sienar Test Pilot' type: 'pilot' count: 1 } { name: 'Deadeye' type: 'upgrade' count: 1 } { name: 'Homing Missiles' type: 'upgrade' count: 1 } { name: 'XX-23 S-Thread Tracers' type: 'upgrade' count: 1 } { name: 'Guidance Chips' type: 'modification' count: 1 } { name: 'TIE/v1' type: 'title' count: 1 } ] "Imperial Veterans Expansion Pack": [ { name: 'TIE Bomber' type: 'ship' count: 1 } { name: 'TIE Defender' type: 'ship' count: 1 } { name: 'Tomax Bren' type: 'pilot' count: 1 } { name: '"Deathfire"' type: 'pilot' count: 1 } { name: 'Gamma Squadron Veteran' type: 'pilot' count: 2 } { name: 'Maarek Stele (TIE Defender)' type: 'pilot' count: 1 } { name: 'Countess Ryad' type: 'pilot' count: 1 } { name: 'Glaive Squadron Pilot' type: 'pilot' count: 2 } { name: 'Crack Shot' type: 'upgrade' count: 1 } { name: 'Tractor Beam' type: 'upgrade' count: 1 } { name: 'Systems Officer' type: 'upgrade' count: 1 } { name: 'Cluster Mines' type: 'upgrade' count: 1 } { name: 'Proximity Mines' type: 'upgrade' count: 1 } { name: 'Long-Range Scanners' type: 'modification' count: 2 } { name: 'TIE/x7' type: 'title' count: 2 } { name: 'TIE/D' type: 'title' count: 2 } { name: 'TIE Shuttle' type: 'title' count: 2 } ] 'ARC-170 Expansion Pack': [ { name: 'ARC-170' type: 'ship' count: 1 } { name: 'Norra Wexley' type: 'pilot' count: 1 } { name: 'Shara Bey' type: 'pilot' count: 1 } { name: 'Thane Kyrell' type: 'pilot' count: 1 } { name: 'Braylen Stramm' type: 'pilot' count: 1 } { name: 'Adrenaline Rush' type: 'upgrade' count: 1 } { name: 'Recon Specialist' type: 'upgrade' count: 1 } { name: 'Tail Gunner' type: 'upgrade' count: 1 } { name: 'R3 Astromech' type: 'upgrade' count: 2 } { name: 'Seismic Torpedo' type: 'upgrade' count: 1 } { name: 'Vectored Thrusters' type: 'modification' count: 2 } { name: 'Alliance Overhaul' type: 'title' count: 1 } ] 'Special Forces TIE Expansion Pack': [ { name: 'TIE/sf Fighter' type: 'ship' count: 1 } { name: '"Quickdraw"' type: 'pilot' count: 1 } { name: '"Backdraft"' type: 'pilot' count: 1 } { name: 'Omega Specialist' type: 'pilot' count: 1 } { name: 'Zeta Specialist' type: 'pilot' count: 1 } { name: 'Wired' type: 'upgrade' count: 1 } { name: 'Collision Detector' type: 'upgrade' count: 1 } { name: 'Sensor Cluster' type: 'upgrade' count: 2 } { name: 'Special Ops Training' type: 'title' count: 1 } ] 'Protectorate Starfighter Expansion Pack': [ { name: 'Protectorate Starfighter' type: 'ship' count: 1 } { name: 'Fenn Rau' type: 'pilot' count: 1 } { name: 'Old Teroch' type: 'pilot' count: 1 } { name: 'Kad Solus' type: 'pilot' count: 1 } { name: 'Concord Dawn Ace' type: 'pilot' count: 1 } { name: 'Concord Dawn Veteran' type: 'pilot' count: 1 } { name: 'Zealous Recruit' type: 'pilot' count: 1 } { name: 'Fearlessness' type: 'upgrade' count: 1 } { name: 'Concord Dawn Protector' type: 'title' count: 1 } ] 'Shadow Caster Expansion Pack': [ { name: 'Lancer-class Pursuit Craft' type: 'ship' count: 1 } { name: 'Ketsu Onyo' type: 'pilot' count: 1 } { name: 'Asajj Ventress' type: 'pilot' count: 1 } { name: 'Sabine Wren (Scum)' type: 'pilot' count: 1 } { name: 'Shadowport Hunter' type: 'pilot' count: 1 } { name: 'Veteran Instincts' type: 'upgrade' count: 1 } { name: 'IG-88D' type: 'upgrade' count: 1 } { name: 'Ketsu Onyo' type: 'upgrade' count: 1 } { name: 'Latts Razzi' type: 'upgrade' count: 1 } { name: 'Black Market Slicer Tools' type: 'upgrade' count: 2 } { name: 'Rigged Cargo Chute' type: 'upgrade' count: 1 } { name: 'Countermeasures' type: 'modification' count: 1 } { name: 'Gyroscopic Targeting' type: 'modification' count: 1 } { name: 'Tactical Jammer' type: 'modification' count: 2 } { name: 'Shadow Caster' type: 'title' count: 1 } ] 'Heroes of the Resistance Expansion Pack': [ { name: 'YT-1300' type: 'ship' count: 1 } { name: 'T-70 X-Wing' type: 'ship' count: 1 } { name: 'Han Solo (TFA)' type: 'pilot' count: 1 } { name: 'Rey' type: 'pilot' count: 1 } { name: 'Chewbacca (TFA)' type: 'pilot' count: 1 } { name: 'Resistance Sympathizer' type: 'pilot' count: 1 } { name: 'Poe Dameron (PS9)' type: 'pilot' count: 1 } { name: 'Nien Nunb' type: 'pilot' count: 1 } { name: '''"Snap" Wexley''' type: 'pilot' count: 1 } { name: 'Jess Pava' type: 'pilot' count: 1 } { name: 'Red Squadron Veteran' type: 'pilot' count: 1 } { name: 'Blue Squadron Novice' type: 'pilot' count: 1 } { name: 'Snap Shot' type: 'upgrade' count: 2 } { name: 'Trick Shot' type: 'upgrade' count: 2 } { name: 'Finn' type: 'upgrade' count: 1 } { name: 'Hotshot Co-pilot' type: 'upgrade' count: 1 } { name: 'Rey' type: 'upgrade' count: 1 } { name: 'M9-G8' type: 'upgrade' count: 1 } { name: 'Burnout SLAM' type: 'upgrade' count: 2 } { name: 'Primed Thrusters' type: 'upgrade' count: 1 } { name: 'Pattern Analyzer' type: 'upgrade' count: 2 } { name: 'Millennium Falcon (TFA)' type: 'title' count: 1 } { name: 'Black One' type: 'title' count: 1 } { name: 'Integrated Astromech' type: 'modification' count: 2 } { name: 'Smuggling Compartment' type: 'modification' count: 1 } ] "U-Wing Expansion Pack": [ { name: 'U-Wing' type: 'ship' count: 1 } { name: 'Cassian Andor' type: 'pilot' count: 1 } { name: 'Bodhi Rook' type: 'pilot' count: 1 } { name: 'Heff Tobber' type: 'pilot' count: 1 } { name: 'Blue Squadron Pathfinder' type: 'pilot' count: 1 } { name: 'Inspiring Recruit' type: 'upgrade' count: 2 } { name: 'Cassian Andor' type: 'upgrade' count: 1 } { name: 'Bistan' type: 'upgrade' count: 1 } { name: 'Jyn Erso' type: 'upgrade' count: 1 } { name: 'Baze Malbus' type: 'upgrade' count: 1 } { name: 'Bodhi Rook' type: 'upgrade' count: 1 } { name: 'Expertise' type: 'upgrade' count: 2 } { name: 'Pivot Wing' type: 'title' count: 1 } { name: 'Stealth Device' type: 'modification' count: 2 } { name: 'Sensor Jammer' type: 'upgrade' count: 1 } ] "TIE Striker Expansion Pack": [ { name: 'TIE Striker' type: 'ship' count: 1 } { name: '"Duchess"' type: 'pilot' count: 1 } { name: '"Pure Sabacc"' type: 'pilot' count: 1 } { name: '"Countdown"' type: 'pilot' count: 1 } { name: 'Black Squadron Scout' type: 'pilot' count: 1 } { name: 'Scarif Defender' type: 'pilot' count: 1 } { name: 'Imperial Trainee' type: 'pilot' count: 1 } { name: 'Swarm Leader' type: 'upgrade' count: 1 } { name: 'Lightweight Frame' type: 'modification' count: 1 } { name: 'Adaptive Ailerons' type: 'title' count: 1 } ] "Sabine's TIE Fighter Expansion Pack": [ { name: 'TIE Fighter' type: 'ship' count: 1 } { name: 'Ahsoka Tano' type: 'pilot' count: 1 } { name: 'Sabine Wren (TIE Fighter)' type: 'pilot' count: 1 } { name: 'Captain Rex' type: 'pilot' count: 1 } { name: '"Zeb" Orrelios (TIE Fighter)' type: 'pilot' count: 1 } { name: 'Veteran Instincts' type: 'upgrade' count: 1 } { name: 'Captain Rex' type: 'upgrade' count: 1 } { name: 'EMP Device' type: 'upgrade' count: 1 } { name: '''Sabine's Masterpiece''' type: 'title' count: 1 } { name: 'Captured TIE' type: 'modification' count: 1 } ] "Upsilon-class Shuttle Expansion Pack": [ { name: 'Upsilon-class Shuttle' type: 'ship' count: 1 } { name: 'Kylo Ren' type: 'pilot' count: 1 } { name: 'Major Stridan' type: 'pilot' count: 1 } { name: 'Lieutenant Dormitz' type: 'pilot' count: 1 } { name: 'Starkiller Base Pilot' type: 'pilot' count: 1 } { name: 'Snap Shot' type: 'upgrade' count: 2 } { name: 'Kylo Ren' type: 'upgrade' count: 1 } { name: 'General Hux' type: 'upgrade' count: 1 } { name: 'Operations Specialist' type: 'upgrade' count: 2 } { name: 'Targeting Synchronizer' type: 'upgrade' count: 2 } { name: 'Hyperwave Comm Scanner' type: 'upgrade' count: 2 } { name: 'Ion Projector' type: 'modification' count: 2 } { name: '''Kylo Ren's Shuttle''' type: 'title' count: 1 } ] "Quadjumper Expansion Pack": [ { name: 'Quadjumper' type: 'ship' count: 1 } { name: 'Constable Zuvio' type: 'pilot' count: 1 } { name: 'Sarco Plank' type: 'pilot' count: 1 } { name: 'Unkar Plutt' type: 'pilot' count: 1 } { name: 'Jakku Gunrunner' type: 'pilot' count: 1 } { name: 'A Score to Settle' type: 'upgrade' count: 1 } { name: 'Unkar Plutt' type: 'upgrade' count: 1 } { name: 'BoShek' type: 'upgrade' count: 1 } { name: 'Thermal Detonators' type: 'upgrade' count: 1 } { name: 'Hyperwave Comm Scanner' type: 'upgrade' count: 1 } { name: 'Scavenger Crane' type: 'upgrade' count: 1 } { name: 'Spacetug Tractor Array' type: 'modification' count: 1 } ] 'C-ROC Cruiser Expansion Pack': [ { name: 'C-ROC Cruiser' type: 'ship' count: 1 } { name: 'M3-A Interceptor' type: 'ship' count: 1 } { name: 'C-ROC Cruiser' type: 'pilot' count: 1 } { name: 'Genesis Red' type: 'pilot' count: 1 } { name: 'Quinn Jast' type: 'pilot' count: 1 } { name: 'Inaldra' type: 'pilot' count: 1 } { name: 'Sunny Bounder' type: 'pilot' count: 1 } { name: 'Tansarii Point Veteran' type: 'pilot' count: 1 } { name: 'Cartel Spacer' type: 'pilot' count: 1 } { name: 'Azmorigan' type: 'upgrade' count: 1 } { name: 'Cikatro Vizago' type: 'upgrade' count: 1 } { name: 'Jabba the Hutt' type: 'upgrade' count: 1 } { name: 'IG-RM Thug Droids' type: 'upgrade' count: 1 } { name: 'ARC Caster' type: 'upgrade' count: 5 } { name: 'Heavy Laser Turret' type: 'upgrade' count: 1 } { name: 'Supercharged Power Cells' type: 'upgrade' count: 2 } { name: 'Quick-release Cargo Locks' type: 'upgrade' count: 1 } { name: 'Merchant One' type: 'title' count: 1 } { name: 'Broken Horn' type: 'title' count: 1 } { name: 'Insatiable Worrt' type: 'title' count: 1 } { name: '"Light Scyk" Interceptor' type: 'title' count: 6 } { name: '"Heavy Scyk" Interceptor' type: 'title' count: 1 } { name: 'Automated Protocols' type: 'modification' count: 1 } { name: 'Optimized Generators' type: 'modification' count: 1 } { name: 'Pulsed Ray Shield' type: 'modification' count: 5 } ] "Auzituck Gunship Expansion Pack": [ { name: 'Auzituck Gunship' type: 'ship' count: 1 } { name: 'Wullffwarro' type: 'pilot' count: 1 } { name: 'Lowhhrick' type: 'pilot' count: 1 } { name: 'Wookiee Liberator' type: 'pilot' count: 1 } { name: 'Kashyyyk Defender' type: 'pilot' count: 1 } { name: 'Intimidation' type: 'upgrade' count: 1 } { name: 'Selflessness' type: 'upgrade' count: 1 } { name: 'Wookiee Commandos' type: 'upgrade' count: 1 } { name: 'Tactician' type: 'upgrade' count: 1 } { name: 'Breach Specialist' type: 'upgrade' count: 1 } { name: 'Hull Upgrade' type: 'modification' count: 1 } ] "Scurrg H-6 Bomber Expansion Pack": [ { name: 'Scurrg H-6 Bomber' type: 'ship' count: 1 } { name: 'Captain Nym (Rebel)' type: 'pilot' count: 1 } { name: 'Captain Nym (Scum)' type: 'pilot' count: 1 } { name: 'Sol Sixxa' type: 'pilot' count: 1 } { name: 'Lok Revenant' type: 'pilot' count: 1 } { name: 'Karthakk Pirate' type: 'pilot' count: 1 } { name: 'Lightning Reflexes' type: 'upgrade' count: 1 } { name: 'Seismic Torpedo' type: 'upgrade' count: 1 } { name: 'Cruise Missiles' type: 'upgrade' count: 2 } { name: 'Bomblet Generator' type: 'upgrade' count: 1 } { name: 'Minefield Mapper' type: 'upgrade' count: 1 } { name: 'Synced Turret' type: 'upgrade' count: 1 } { name: 'Cad Bane' type: 'upgrade' count: 1 } { name: 'R4-E1' type: 'upgrade' count: 1 } { name: 'Havoc' type: 'title' count: 1 } ] "TIE Aggressor Expansion Pack": [ { name: 'TIE Aggressor' type: 'ship' count: 1 } { name: 'Lieutenant Kestal' type: 'pilot' count: 1 } { name: '"Double Edge"' type: 'pilot' count: 1 } { name: 'Onyx Squadron Escort' type: 'pilot' count: 1 } { name: 'Sienar Specialist' type: 'pilot' count: 1 } { name: 'Intensity' type: 'upgrade' count: 1 } { name: 'Unguided Rockets' type: 'upgrade' count: 1 } { name: 'Twin Laser Turret' type: 'upgrade' count: 1 } { name: 'Synced Turret' type: 'upgrade' count: 1 } { name: 'Lightweight Frame' type: 'modification' count: 1 } ] 'Guns for Hire Expansion Pack': [ { name: 'Kihraxz Fighter' type: 'ship' count: 1 } { name: 'StarViper' type: 'ship' count: 1 } { name: 'Viktor Hel' type: 'pilot' count: 1 } { name: 'Captain Jostero' type: 'pilot' count: 1 } { name: 'Black Sun Ace' type: 'pilot' count: 1 } { name: 'Cartel Marauder' type: 'pilot' count: 1 } { name: 'Dalan Oberos' type: 'pilot' count: 1 } { name: 'Thweek' type: 'pilot' count: 1 } { name: 'Black Sun Assassin' type: 'pilot' count: 2 } { name: 'Harpoon Missiles' type: 'upgrade' count: 2 } { name: 'Ion Dischargers' type: 'upgrade' count: 2 } { name: 'StarViper Mk. II' type: 'title' count: 2 } { name: 'Vaksai' type: 'title' count: 2 } { name: 'Pulsed Ray Shield' type: 'modification' count: 2 } { name: 'Stealth Device' type: 'modification' count: 1 } { name: 'Vectored Thrusters' type: 'modification' count: 1 } ] class exportObj.Collection # collection = new exportObj.Collection # expansions: # "Core": 2 # "TIE Fighter Expansion Pack": 4 # "B-Wing Expansion Pack": 2 # singletons: # ship: # "T-70 X-Wing": 1 # pilot: # "Academy Pilot": 16 # upgrade: # "C-3PO": 4 # "Gunner": 5 # modification: # "Engine Upgrade": 2 # title: # "TIE/x1": 1 # # # or # # collection = exportObj.Collection.load(backend) # # collection.use "pilot", "Red Squadron Pilot" # collection.use "upgrade", "R2-D2" # collection.use "upgrade", "Ion Pulse Missiles" # returns false # # collection.release "pilot", "Red Squadron Pilot" # collection.release "pilot", "Sigma Squadron Pilot" # returns false constructor: (args) -> @expansions = args.expansions ? {} @singletons = args.singletons ? {} # To save collection (optional) @backend = args.backend @setupUI() @setupHandlers() @reset() @language = 'English' reset: -> @shelf = {} @table = {} for expansion, count of @expansions try count = parseInt count catch count = 0 for _ in [0...count] for card in (exportObj.manifestByExpansion[expansion] ? []) for _ in [0...card.count] ((@shelf[card.type] ?= {})[card.name] ?= []).push expansion for type, counts of @singletons for name, count of counts for _ in [0...count] ((@shelf[type] ?= {})[name] ?= []).push 'singleton' @counts = {} for own type of @shelf for own thing of @shelf[type] (@counts[type] ?= {})[thing] ?= 0 @counts[type][thing] += @shelf[type][thing].length component_content = $ @modal.find('.collection-inventory-content') component_content.text '' for own type, things of @counts contents = component_content.append $.trim """ <div class="row-fluid"> <div class="span12"><h5>#{type.capitalize()}</h5></div> </div> <div class="row-fluid"> <ul id="counts-#{type}" class="span12"></ul> </div> """ ul = $ contents.find("ul#counts-#{type}") for thing in Object.keys(things).sort(sortWithoutQuotes) ul.append """<li>#{thing} - #{things[thing]}</li>""" fixName: (name) -> # Special case handling for Heavy Scyk :( if name.indexOf('"Heavy Scyk" Interceptor') == 0 '"Heavy Scyk" Interceptor' else name check: (where, type, name) -> (((where[type] ? {})[@fixName name] ? []).length ? 0) != 0 checkShelf: (type, name) -> @check @shelf, type, name checkTable: (type, name) -> @check @table, type, name use: (type, name) -> name = @fixName name try card = @shelf[type][name].pop() catch e return false unless card? if card? ((@table[type] ?= {})[name] ?= []).push card true else false release: (type, name) -> name = @fixName name try card = @table[type][name].pop() catch e return false unless card? if card? ((@shelf[type] ?= {})[name] ?= []).push card true else false save: (cb=$.noop) -> @backend.saveCollection(this, cb) if @backend? @load: (backend, cb) -> backend.loadCollection cb setupUI: -> # Create list of released singletons singletonsByType = {} for expname, items of exportObj.manifestByExpansion for item in items (singletonsByType[item.type] ?= {})[item.name] = true for type, names of singletonsByType sorted_names = (name for name of names).sort(sortWithoutQuotes) singletonsByType[type] = sorted_names @modal = $ document.createElement 'DIV' @modal.addClass 'modal hide fade collection-modal hidden-print' $('body').append @modal @modal.append $.trim """ <div class="modal-header"> <button type="button" class="close hidden-print" data-dismiss="modal" aria-hidden="true">&times;</button> <h4>Your Collection</h4> </div> <div class="modal-body"> <ul class="nav nav-tabs"> <li class="active"><a data-target="#collection-expansions" data-toggle="tab">Expansions</a><li> <li><a data-target="#collection-ships" data-toggle="tab">Ships</a><li> <li><a data-target="#collection-pilots" data-toggle="tab">Pilots</a><li> <li><a data-target="#collection-upgrades" data-toggle="tab">Upgrades</a><li> <li><a data-target="#collection-modifications" data-toggle="tab">Mods</a><li> <li><a data-target="#collection-titles" data-toggle="tab">Titles</a><li> <li><a data-target="#collection-components" data-toggle="tab">Inventory</a><li> </ul> <div class="tab-content"> <div id="collection-expansions" class="tab-pane active container-fluid collection-content"></div> <div id="collection-ships" class="tab-pane active container-fluid collection-ship-content"></div> <div id="collection-pilots" class="tab-pane active container-fluid collection-pilot-content"></div> <div id="collection-upgrades" class="tab-pane active container-fluid collection-upgrade-content"></div> <div id="collection-modifications" class="tab-pane active container-fluid collection-modification-content"></div> <div id="collection-titles" class="tab-pane active container-fluid collection-title-content"></div> <div id="collection-components" class="tab-pane container-fluid collection-inventory-content"></div> </div> </div> <div class="modal-footer hidden-print"> <span class="collection-status"></span> &nbsp; <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> </div> """ @modal_status = $ @modal.find('.collection-status') collection_content = $ @modal.find('.collection-content') for expansion in exportObj.expansions count = parseInt(@expansions[expansion] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="expansion-count" type="number" size="3" value="#{count}" /> <span class="expansion-name">#{expansion}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'expansion', expansion input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.expansion-name').data 'english_name', expansion collection_content.append row shipcollection_content = $ @modal.find('.collection-ship-content') for ship in singletonsByType.ship count = parseInt(@singletons.ship?[ship] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="ship-name">#{ship}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'ship' input.data 'singletonName', ship input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.ship-name').data 'english_name', expansion shipcollection_content.append row pilotcollection_content = $ @modal.find('.collection-pilot-content') for pilot in singletonsByType.pilot count = parseInt(@singletons.pilot?[pilot] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="pilot-name">#{pilot}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'pilot' input.data 'singletonName', pilot input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.pilot-name').data 'english_name', expansion pilotcollection_content.append row upgradecollection_content = $ @modal.find('.collection-upgrade-content') for upgrade in singletonsByType.upgrade count = parseInt(@singletons.upgrade?[upgrade] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="upgrade-name">#{upgrade}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'upgrade' input.data 'singletonName', upgrade input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.upgrade-name').data 'english_name', expansion upgradecollection_content.append row modificationcollection_content = $ @modal.find('.collection-modification-content') for modification in singletonsByType.modification count = parseInt(@singletons.modification?[modification] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="modification-name">#{modification}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'modification' input.data 'singletonName', modification input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.modification-name').data 'english_name', expansion modificationcollection_content.append row titlecollection_content = $ @modal.find('.collection-title-content') for title in singletonsByType.title count = parseInt(@singletons.title?[title] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="title-name">#{title}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'title' input.data 'singletonName', title input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.title-name').data 'english_name', expansion titlecollection_content.append row destroyUI: -> @modal.modal 'hide' @modal.remove() $(exportObj).trigger 'xwing-collection:destroyed', this setupHandlers: -> $(exportObj).trigger 'xwing-collection:created', this $(exportObj).on 'xwing-backend:authenticationChanged', (e, authenticated, backend) => # console.log "deauthed, destroying collection UI" @destroyUI() unless authenticated .on 'xwing-collection:saved', (e, collection) => @modal_status.text 'Collection saved' @modal_status.fadeIn 100, => @modal_status.fadeOut 5000 .on 'xwing:languageChanged', @onLanguageChange $ @modal.find('input.expansion-count').change (e) => target = $(e.target) val = target.val() target.val(0) if val < 0 or isNaN(parseInt(val)) @expansions[target.data 'expansion'] = parseInt(target.val()) target.closest('div').css 'background-color', @countToBackgroundColor(val) # console.log "Input changed, triggering collection change" $(exportObj).trigger 'xwing-collection:changed', this $ @modal.find('input.singleton-count').change (e) => target = $(e.target) val = target.val() target.val(0) if val < 0 or isNaN(parseInt(val)) (@singletons[target.data 'singletonType'] ?= {})[target.data 'singletonName'] = parseInt(target.val()) target.closest('div').css 'background-color', @countToBackgroundColor(val) # console.log "Input changed, triggering collection change" $(exportObj).trigger 'xwing-collection:changed', this countToBackgroundColor: (count) -> count = parseInt(count) switch when count == 0 '' when count < 12 i = parseInt(200 * Math.pow(0.9, count - 1)) "rgb(#{i}, 255, #{i})" else 'red' onLanguageChange: (e, language) => if language != @language # console.log "language changed to #{language}" do (language) => @modal.find('.expansion-name').each -> # console.log "translating #{$(this).text()} (#{$(this).data('english_name')}) to #{language}" $(this).text exportObj.translate language, 'sources', $(this).data('english_name') @language = language
202578
exportObj = exports ? this String::startsWith ?= (t) -> @indexOf t == 0 sortWithoutQuotes = (a, b) -> a_name = a.replace /[^a-z0-9]/ig, '' b_name = b.replace /[^a-z0-9]/ig, '' if a_name < b_name -1 else if a_name > b_name 1 else 0 exportObj.manifestByExpansion = 'Core': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'ship' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Red Squadron Pilot' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>se"' type: 'pilot' count: 1 } { name: '"Night Beast"' type: 'pilot' count: 1 } { name: 'Black Squadron Pilot' type: 'pilot' count: 2 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 2 } { name: 'Academy Pilot' type: 'pilot' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'R2-F2' type: 'upgrade' count: 1 } { name: 'R2-D2' type: 'upgrade' count: 1 } { name: '<NAME>ation' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'X-Wing Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Red Squadron Pilot' type: 'pilot' count: 1 } { name: '<NAME> Pilot' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'R5-K6' type: 'upgrade' count: 1 } { name: 'R5 Astromech' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'Y-Wing Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>' type: 'pilot' count: 1 } { name: 'Gray Squadron Pilot' type: 'pilot' count: 1 } { name: 'Gold Squadron Pilot' type: 'pilot' count: 1 } { name: '<NAME> Tor<NAME>' type: 'upgrade' count: 2 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 1 } { name: 'R5-D8' type: 'upgrade' count: 1 } { name: 'R2 Astromech' type: 'upgrade' count: 1 } ] 'TIE Fighter Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: 'Black Squadron Pilot' type: 'pilot' count: 1 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 1 } { name: 'Academy Pilot' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 1 } ] 'TIE Advanced Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Storm Squadron Pilot' type: 'pilot' count: 1 } { name: 'Tempest Squadron Pilot' type: 'pilot' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 1 } { name: 'Expert Handling' type: 'upgrade' count: 1 } ] 'A-Wing Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Green Squadron Pilot' type: 'pilot' count: 1 } { name: 'Prototype Pilot' type: 'pilot' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 1 } { name: 'Homing Missiles' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: 'Push the Limit' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'Millennium Falcon Expansion Pack': [ { name: 'YT-1300' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 1 } { name: 'Assault Missiles' type: 'upgrade' count: 1 } { name: 'Elusiveness' type: 'upgrade' count: 1 } { name: 'Draw Their Fire' type: 'upgrade' count: 1 } { name: 'Veteran Instincts' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Weapons Engineer' type: 'upgrade' count: 1 } { name: 'Shield Upgrade' type: 'modification' count: 2 } { name: 'Engine Upgrade' type: 'modification' count: 2 } { name: '<NAME>' type: 'title' count: 1 } ] 'TIE Interceptor Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '''"<NAME>"''' type: 'pilot' count: 1 } { name: 'Saber Squadron Pilot' type: 'pilot' count: 1 } { name: 'Avenger Squadron Pilot' type: 'pilot' count: 1 } { name: 'Alpha Squadron Pilot' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'Slave I Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Seismic <NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>en<NAME>' type: 'upgrade' count: 1 } { name: 'Stealth Device' type: 'modification' count: 2 } { name: '<NAME> I' type: 'title' count: 1 } ] 'B-Wing Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> Squadron Pilot' type: 'pilot' count: 1 } { name: 'Fire-Control System' type: 'upgrade' count: 1 } { name: 'Advanced Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'Ion Cannon' type: 'upgrade' count: 1 } { name: 'Autoblaster' type: 'upgrade' count: 1 } ] "HWK-290 Expansion Pack": [ { name: 'HW<NAME>-29<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Rebel Operative' type: 'pilot' count: 1 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 1 } { name: '<NAME> Specialist' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'title' count: 1 } { name: 'Blaster Turret' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Intelligence Agent' type: 'upgrade' count: 1 } ] "TIE Bomber Expansion Pack": [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> Squadron Pilot' type: 'pilot' count: 1 } { name: '<NAME>imitar Squadron Pilot' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Advanced Proton Torpedoes' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] "Lambda-Class Shuttle Expansion Pack": [ { name: 'Lambda-Class Shuttle' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>micron Group Pilot' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Advanced Sensors' type: 'upgrade' count: 1 } { name: 'ST-321' type: 'title' count: 1 } { name: '<NAME> Laser <NAME>' type: 'upgrade' count: 1 } { name: 'Weapons Engineer' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Intelligence Agent' type: 'upgrade' count: 1 } { name: 'Navigator' type: 'upgrade' count: 1 } { name: 'Flight Instructor' type: 'upgrade' count: 1 } { name: 'Anti-Pursuit Lasers' type: 'modification' count: 2 } ] "Z-95 Headhunter Expansion Pack": [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Tala Squadron Pilot' type: 'pilot' count: 1 } { name: 'Bandit Squadron Pilot' type: 'pilot' count: 1 } { name: '<NAME>un<NAME> Failsafe' type: 'modification' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>iss<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'E-Wing Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: 'Blackmoon Squadron Pilot' type: 'pilot' count: 1 } { name: 'Knave Squadron Pilot' type: 'pilot' count: 1 } { name: 'Advanced Sensors' type: 'upgrade' count: 1 } { name: 'Outmaneuver' type: 'upgrade' count: 1 } { name: 'R7-T1' type: 'upgrade' count: 1 } { name: 'R7 Astromech' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'TIE Defender Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Onyx Squadron Pilot' type: 'pilot' count: 1 } { name: 'Delta Squadron Pilot' type: 'pilot' count: 1 } { name: '<NAME>' type: 'modification' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'TIE Phantom Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: 'Shadow Squadron Pilot' type: 'pilot' count: 1 } { name: 'Sigma Squadron Pilot' type: 'pilot' count: 1 } { name: 'Fire-Control System' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Recon Specialist' type: 'upgrade' count: 1 } { name: 'Advanced Cloaking Device' type: 'modification' count: 1 } { name: 'Stygium Particle Accelerator' type: 'modification' count: 1 } ] 'YT-2400 Freighter Expansion Pack': [ { name: '<NAME>-240<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Experimental Interface' type: 'modification' count: 1 } { name: '<NAME>' type: 'modification' count: 2 } { name: '<NAME>' type: 'title' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '"<NAME>"' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME> On Target' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] "VT-49 Decimator Expansion Pack": [ { name: 'VT-49 Decimator' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'title' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'modification' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } ] 'Imperial Aces Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Royal Guard Pilot' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Saber Squadron Pilot' type: 'pilot' count: 2 } { name: 'Royal Guard TIE' type: 'title' count: 2 } { name: 'Targeting Computer' type: 'modification' count: 2 } { name: 'Hull Upgrade' type: 'modification' count: 2 } { name: 'Push the Limit' type: 'upgrade' count: 2 } { name: 'Opportunist' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'modification' count: 2 } ] 'Rebel Aces Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Green Squadron Pilot' type: 'pilot' count: 1 } { name: 'Prototype Pilot' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Dagger Squadron Pilot' type: 'pilot' count: 1 } { name: 'Blue Squadron Pilot' type: 'pilot' count: 1 } { name: 'Ch<NAME>aan Refit' type: 'upgrade' count: 3 } { name: 'A-Wing Test Pilot' type: 'title' count: 2 } { name: 'Enhanced Scopes' type: 'upgrade' count: 2 } { name: 'Proton Rockets' type: 'upgrade' count: 2 } { name: 'B-Wing/E2' type: 'modification' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'Rebel Transport Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: 'GR-75 Medium Transport' type: 'ship' count: 1 } { name: 'GR-75 Medium Transport' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>" <NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Red S<NAME>ron <NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Duty<NAME>' type: 'title' count: 1 } { name: 'Quantum Storm' type: 'title' count: 1 } { name: '<NAME>' type: 'title' count: 1 } { name: 'Expanded Cargo Hold' type: 'upgrade' count: 1 } { name: 'R2-D6' type: 'upgrade' count: 1 } { name: 'R4-D6' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: 'R3-A2' type: 'upgrade' count: 1 } { name: 'WED-15 Repair Droid' type: 'upgrade' count: 1 } { name: 'Backup Shield Generator' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'EM Emitter' type: 'upgrade' count: 1 } { name: 'Engine Booster' type: 'upgrade' count: 1 } { name: 'R5-P9' type: 'upgrade' count: 1 } { name: 'Comms Booster' type: 'upgrade' count: 1 } { name: 'Frequency Jammer' type: 'upgrade' count: 1 } { name: 'Shield Projector' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Slicer Tools' type: 'upgrade' count: 1 } { name: 'Combat Retrofit' type: 'modification' count: 1 } ] 'Tantive IV Expansion Pack': [ { name: 'CR90 Corvette (Fore)' type: 'ship' count: 1 } { name: 'CR90 Corvette (Aft)' type: 'ship' count: 1 } { name: 'CR90 Corvette (Fore)' type: 'pilot' count: 1 } # { # name: 'CR90 Corvette (Crippled Fore)' # type: 'pilot' # count: 1 # } { name: 'CR90 Corvette (Aft)' type: 'pilot' count: 1 } # { # name: 'CR90 Corvette (Crippled Aft)' # type: 'pilot' # count: 1 # } { name: "<NAME>" type: 'title' count: 1 } { name: "<NAME>" type: 'title' count: 1 } { name: '<NAME>' type: 'title' count: 1 } { name: 'Backup Shield Generator' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>-3<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: 'Engineering Team' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME> (<NAME>)' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: 'Single Turbolasers' type: 'upgrade' count: 3 } ] 'StarViper Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> Sun <NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'title' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'modification' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'modification' count: 1 } ] "M3-A Interceptor Expansion Pack": [ { name: '<NAME>3-<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: '"Heavy Scyk" Interceptor' type: 'title' count: 1 skipForSource: true # special :( } { name: '"Heavy Scyk" Interceptor (Cannon)' type: 'title' count: 0 # special :( } { name: '"Heavy Scyk" Interceptor (Missile)' type: 'title' count: 0 # special :( } { name: '"Heavy S<NAME>k" Interceptor (Torpedo)' type: 'title' count: 0 # special :( } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '"<NAME>" <NAME>' type: 'upgrade' count: 1 } { name: 'Stealth Device' type: 'modification' count: 1 } ] "IG-2000 Expansion Pack": [ { name: '<NAME>gressor' type: 'ship' count: 1 } { name: 'IG-88A' type: 'pilot' count: 1 } { name: 'IG-88B' type: 'pilot' count: 1 } { name: 'IG-88C' type: 'pilot' count: 1 } { name: 'IG-88D' type: 'pilot' count: 1 } { name: 'IG-2000' type: 'title' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '"<NAME>" <NAME>' type: 'upgrade' count: 1 } { name: '<NAME>imity M<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>ismic Charges' type: 'upgrade' count: 1 } { name: "Dead Man's Switch" type: 'upgrade' count: 2 } { name: 'Feedback Array' type: 'upgrade' count: 2 } { name: '"<NAME> Shot" Blaster' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] "Most Wanted Expansion Pack": [ { name: '<NAME>' type: 'ship' count: 2 } { name: '<NAME>' type: 'ship' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME> Sun <NAME>" type: 'pilot' count: 2 } { name: "<NAME>" type: 'pilot' count: 2 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 2 } { name: "<NAME>" type: 'pilot' count: 2 } { name: "<NAME> (Scum)" type: 'pilot' count: 1 } { name: "<NAME> (Scum)" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: "K4 Security Droid" type: 'upgrade' count: 1 } { name: "Outlaw Tech" type: 'upgrade' count: 1 } { name: "Autoblaster Turret" type: 'upgrade' count: 2 } { name: "Bomb Loadout" type: 'upgrade' count: 2 } { name: "R4-B11" type: 'upgrade' count: 1 } { name: '"<NAME>"' type: 'upgrade' count: 1 } { name: "R4 Agromech" type: 'upgrade' count: 2 } { name: "Salvaged Astromech" type: 'upgrade' count: 2 } { name: "Unhinged Astromech" type: 'upgrade' count: 2 } { name: "BTL-A4 Y-Wing" type: 'title' count: 2 } { name: "<NAME>" type: 'title' count: 1 } { name: '"Hot Shot" Blaster' type: 'upgrade' count: 1 } ] "Hound's Tooth Expansion Pack": [ { name: 'YV-666' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Crack Shot' type: 'upgrade' count: 1 } { name: 'Stay On Target' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'K4 Security Droid' type: 'upgrade' count: 1 } { name: 'Outlaw Tech' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'modification' count: 1 } { name: '<NAME>' type: 'modification' count: 2 } { name: '<NAME>' type: 'modification' count: 1 } { name: "<NAME>" type: 'title' count: 1 } ] 'Kihraxz Fighter Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'K-Wing Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Guardian Squadron Pilot' type: 'pilot' count: 1 } { name: 'Warden Squadron Pilot' type: 'pilot' count: 1 } { name: 'Twin Laser Turret' type: 'upgrade' count: 2 } { name: 'Plasma Torpedoes' type: 'upgrade' count: 1 } { name: 'Advanced Homing Missiles' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Extra Munitions' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Advanced SLAM' type: 'modification' count: 1 } ] 'TIE Punisher Expansion Pack': [ { name: 'TIE Punisher' type: 'ship' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: 'Black Eight Squadron Pilot' type: 'pilot' count: 1 } { name: 'Cutlass Squadron Pilot' type: 'pilot' count: 1 } { name: 'Enhanced Scopes' type: 'upgrade' count: 1 } { name: 'Extra Munitions' type: 'upgrade' count: 1 } { name: 'Flechette Torpedoes' type: 'upgrade' count: 1 } { name: 'Plasma Torpedoes' type: 'upgrade' count: 1 } { name: 'Advanced Homing Missiles' type: 'upgrade' count: 1 } { name: 'Cluster Mines' type: 'upgrade' count: 1 } { name: 'Ion Bombs' type: 'upgrade' count: 1 } { name: 'Twin Ion Engine Mk. II' type: 'modification' count: 2 } ] "Imperial Raider Expansion Pack": [ { name: "Raider-class Corvette (Fore)" type: 'ship' count: 1 } { name: "Raider-class Corvette (Aft)" type: 'ship' count: 1 } { name: "TIE Advanced" type: 'ship' count: 1 } { name: "Raider-class Corvette (Fore)" type: 'pilot' count: 1 } { name: "Raider-class Corvette (Aft)" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "Storm Squadron Pilot" type: 'pilot' count: 1 } { name: "Tempest Squadron Pilot" type: 'pilot' count: 1 } { name: "Advanced Targeting Computer" type: 'upgrade' count: 4 } { name: "TIE/x1" type: 'title' count: 4 } { name: "Cluster Missiles" type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: "Shield <NAME>nician" type: 'upgrade' count: 2 } { name: "Gunnery Team" type: 'upgrade' count: 1 } { name: "Engineering Team" type: 'upgrade' count: 1 } { name: "Sensor Team" type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 2 } { name: "<NAME>" type: 'upgrade' count: 4 } { name: "<NAME>" type: 'upgrade' count: 2 } { name: "<NAME>" type: 'upgrade' count: 2 } { name: "<NAME> Boost<NAME>" type: 'upgrade' count: 1 } { name: "Backup Shield Generator" type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: "<NAME>" type: 'title' count: 1 } { name: "<NAME>" type: 'title' count: 1 } { name: "<NAME>" type: 'title' count: 1 } ] 'The Force Awakens Core Set': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>/fo <NAME>ighter' type: 'ship' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> S<NAME>ron No<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME> Squadron Pilot' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME> Pi<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'BB-8' type: 'upgrade' count: 1 } { name: 'R5-X3' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Weapons Guidance' type: 'upgrade' count: 1 } ] 'Imperial Assault Carrier Expansion Pack': [ { name: '<NAME> Fighter' type: 'ship' count: 2 } { name: 'Gozanti-class Cruiser' type: 'ship' count: 1 } { name: 'Gozanti-class Cruiser' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: 'Academy Pilot' type: 'pilot' count: 2 } { name: 'Black Squadron Pilot' type: 'pilot' count: 2 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 2 } { name: '<NAME>ship' type: 'upgrade' count: 1 } { name: 'Expert Handling' type: 'upgrade' count: 1 } { name: 'Expose' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: '<NAME>ing Miss<NAME>' type: 'upgrade' count: 1 } { name: '<NAME> Laser Turret' type: 'upgrade' count: 1 } { name: 'Broadcast Array' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Ordnance Experts' type: 'upgrade' count: 2 } { name: 'Docking Clamps' type: 'upgrade' count: 1 } { name: 'Cluster Bombs' type: 'upgrade' count: 2 } { name: 'Automated Protocols' type: 'modification' count: 3 } { name: 'Optimized Generators' type: 'modification' count: 3 } { name: '<NAME>' type: 'modification' count: 2 } { name: '<NAME>' type: 'title' count: 1 } { name: '<NAME>' type: 'title' count: 1 } { name: '<NAME>' type: 'title' count: 1 } ] 'T-70 X-Wing Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Targeting Astromech' type: 'upgrade' count: 1 } { name: 'Weapons Guidance' type: 'upgrade' count: 1 } { name: 'Integrated Astromech' type: 'modification' count: 1 } { name: 'Advanced Proton Torpedoes' type: 'upgrade' count: 1 } ] 'TIE/fo Fighter Expansion Pack': [ { name: '<NAME>/<NAME>' type: 'ship' count: 1 } { name: '"Omega Leader"' type: 'pilot' count: 1 } { name: '"<NAME>eta Leader"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: 'Omega Squadron Pilot' type: 'pilot' count: 1 } { name: 'Zeta Squadron Pilot' type: 'pilot' count: 1 } { name: 'Epsilon Squadron Pilot' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Comm Relay' type: 'upgrade' count: 1 } ] 'Ghost Expansion Pack': [ { name: 'VCX-100' type: 'ship' count: 1 } { name: 'Attack Shuttle' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> (Attack Shuttle)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>" <NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Reinforced Deflectors' type: 'upgrade' count: 1 } { name: 'Dorsal Turret' type: 'upgrade' count: 2 } { name: 'Advanced Proton Torpedoes' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '"<NAME>" <NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '"<NAME>"' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'title' count: 1 } { name: '<NAME>' type: 'title' count: 1 } ] 'Punishing One Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '"<NAME>"' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME> <NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'title' count: 1 } { name: '<NAME>' type: 'modification' count: 2 } ] 'Mist Hunter Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Clo<NAME> Device' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'title' count: 1 } ] "Inquisitor's TIE Expansion Pack": [ { name: 'TIE Advanced Prototype' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'De<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'XX-23 S-Thread Tracers' type: 'upgrade' count: 1 } { name: 'Guidance Chips' type: 'modification' count: 1 } { name: 'TIE/v1' type: 'title' count: 1 } ] "Imperial Veterans Expansion Pack": [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME> (TIE Defender)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Tractor Beam' type: 'upgrade' count: 1 } { name: 'Systems Officer' type: 'upgrade' count: 1 } { name: 'Cluster Mines' type: 'upgrade' count: 1 } { name: 'Proximity Mines' type: 'upgrade' count: 1 } { name: 'Long-Range Scanners' type: 'modification' count: 2 } { name: 'TIE/x7' type: 'title' count: 2 } { name: 'TI<NAME>/D' type: 'title' count: 2 } { name: '<NAME>' type: 'title' count: 2 } ] 'ARC-170 Expansion Pack': [ { name: '<NAME>-17<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME> Specialist' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'modification' count: 2 } { name: '<NAME>ha<NAME>' type: 'title' count: 1 } ] 'Special Forces TIE Expansion Pack': [ { name: 'TIE/sf Fighter' type: 'ship' count: 1 } { name: '"Quickdraw"' type: 'pilot' count: 1 } { name: '"Backdraft"' type: 'pilot' count: 1 } { name: 'Omega Specialist' type: 'pilot' count: 1 } { name: 'Zeta Special<NAME>' type: 'pilot' count: 1 } { name: 'Wired' type: 'upgrade' count: 1 } { name: 'Collision Detector' type: 'upgrade' count: 1 } { name: 'Sensor Cluster' type: 'upgrade' count: 2 } { name: 'Special Ops Training' type: 'title' count: 1 } ] 'Protectorate Starfighter Expansion Pack': [ { name: 'Protectorate Starfighter' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME> D<NAME> Protector' type: 'title' count: 1 } ] 'Shadow Caster Expansion Pack': [ { name: 'Lancer-class Pursuit Craft' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> (Scum)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'IG-88D' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Black Market Slicer Tools' type: 'upgrade' count: 2 } { name: 'Rigged Cargo Chute' type: 'upgrade' count: 1 } { name: 'Countermeasures' type: 'modification' count: 1 } { name: 'Gyroscopic Targeting' type: 'modification' count: 1 } { name: 'Tactical Jammer' type: 'modification' count: 2 } { name: '<NAME>' type: 'title' count: 1 } ] 'Heroes of the Resistance Expansion Pack': [ { name: 'YT-1300' type: 'ship' count: 1 } { name: '<NAME>-<NAME>' type: 'ship' count: 1 } { name: '<NAME> (TFA)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> (TFA)' type: 'pilot' count: 1 } { name: 'Resistance Sympathizer' type: 'pilot' count: 1 } { name: '<NAME> (PS9)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '''"<NAME>''' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Red Squadron Veteran' type: 'pilot' count: 1 } { name: '<NAME>quadron <NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME> (<NAME>)' type: 'title' count: 1 } { name: '<NAME>' type: 'title' count: 1 } { name: 'Integrated Astromech' type: 'modification' count: 2 } { name: 'Smuggling Compartment' type: 'modification' count: 1 } ] "U-Wing Expansion Pack": [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Expertise' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'title' count: 1 } { name: 'Stealth Device' type: 'modification' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } ] "TIE Striker Expansion Pack": [ { name: '<NAME>' type: 'ship' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Lightweight Frame' type: 'modification' count: 1 } { name: '<NAME>ilerons' type: 'title' count: 1 } ] "Sabine's TIE Fighter Expansion Pack": [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> (TIE Fighter)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>" <NAME> (TIE Fighter)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '''<NAME>'s Masterpiece''' type: 'title' count: 1 } { name: '<NAME>' type: 'modification' count: 1 } ] "Upsilon-class Shuttle Expansion Pack": [ { name: 'Upsilon-class Shuttle' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Operations Specialist' type: 'upgrade' count: 2 } { name: '<NAME>ing Synchronizer' type: 'upgrade' count: 2 } { name: 'Hyperwave Comm Scanner' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'modification' count: 2 } { name: '''<NAME>''' type: 'title' count: 1 } ] "Quadjumper Expansion Pack": [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>ermal <NAME>on<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>wave Comm <NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'modification' count: 1 } ] 'C-ROC Cruiser Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'IG-RM <NAME>ug D<NAME>' type: 'upgrade' count: 1 } { name: 'ARC Caster' type: 'upgrade' count: 5 } { name: 'Heavy Laser Turret' type: 'upgrade' count: 1 } { name: 'Supercharged Power Cells' type: 'upgrade' count: 2 } { name: 'Quick-release Cargo Locks' type: 'upgrade' count: 1 } { name: 'Merchant One' type: 'title' count: 1 } { name: '<NAME>' type: 'title' count: 1 } { name: 'Insatiable Worrt' type: 'title' count: 1 } { name: '"Light Scyk" Interceptor' type: 'title' count: 6 } { name: '"Heavy Scyk" Interceptor' type: 'title' count: 1 } { name: 'Automated Protocols' type: 'modification' count: 1 } { name: 'Optimized Generators' type: 'modification' count: 1 } { name: 'Pulsed Ray Shield' type: 'modification' count: 5 } ] "Auzituck Gunship Expansion Pack": [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'modification' count: 1 } ] "Scurrg H-6 Bomber Expansion Pack": [ { name: '<NAME> H-6 Bom<NAME>' type: 'ship' count: 1 } { name: '<NAME> (<NAME>)' type: 'pilot' count: 1 } { name: '<NAME> (<NAME>)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: 'Bomblet Generator' type: 'upgrade' count: 1 } { name: 'Minefield Mapper' type: 'upgrade' count: 1 } { name: 'Synced Turret' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'title' count: 1 } ] "TIE Aggressor Expansion Pack": [ { name: '<NAME> Ag<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"Double Edge"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Intensity' type: 'upgrade' count: 1 } { name: 'Unguided Rockets' type: 'upgrade' count: 1 } { name: 'Twin Laser Turret' type: 'upgrade' count: 1 } { name: 'Synced Turret' type: 'upgrade' count: 1 } { name: 'Lightweight Frame' type: 'modification' count: 1 } ] 'Guns for Hire Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'title' count: 2 } { name: '<NAME>' type: 'title' count: 2 } { name: '<NAME>' type: 'modification' count: 2 } { name: 'Stealth Device' type: 'modification' count: 1 } { name: '<NAME>' type: 'modification' count: 1 } ] class exportObj.Collection # collection = new exportObj.Collection # expansions: # "Core": 2 # "TIE Fighter Expansion Pack": 4 # "B-Wing Expansion Pack": 2 # singletons: # ship: # "T-70 X-Wing": 1 # pilot: # "Academy Pilot": 16 # upgrade: # "C-3PO": 4 # "Gunner": 5 # modification: # "Engine Upgrade": 2 # title: # "TIE/x1": 1 # # # or # # collection = exportObj.Collection.load(backend) # # collection.use "pilot", "Red Squadron Pilot" # collection.use "upgrade", "R2-D2" # collection.use "upgrade", "Ion Pulse Missiles" # returns false # # collection.release "pilot", "Red Squadron Pilot" # collection.release "pilot", "Sigma Squadron Pilot" # returns false constructor: (args) -> @expansions = args.expansions ? {} @singletons = args.singletons ? {} # To save collection (optional) @backend = args.backend @setupUI() @setupHandlers() @reset() @language = 'English' reset: -> @shelf = {} @table = {} for expansion, count of @expansions try count = parseInt count catch count = 0 for _ in [0...count] for card in (exportObj.manifestByExpansion[expansion] ? []) for _ in [0...card.count] ((@shelf[card.type] ?= {})[card.name] ?= []).push expansion for type, counts of @singletons for name, count of counts for _ in [0...count] ((@shelf[type] ?= {})[name] ?= []).push 'singleton' @counts = {} for own type of @shelf for own thing of @shelf[type] (@counts[type] ?= {})[thing] ?= 0 @counts[type][thing] += @shelf[type][thing].length component_content = $ @modal.find('.collection-inventory-content') component_content.text '' for own type, things of @counts contents = component_content.append $.trim """ <div class="row-fluid"> <div class="span12"><h5>#{type.capitalize()}</h5></div> </div> <div class="row-fluid"> <ul id="counts-#{type}" class="span12"></ul> </div> """ ul = $ contents.find("ul#counts-#{type}") for thing in Object.keys(things).sort(sortWithoutQuotes) ul.append """<li>#{thing} - #{things[thing]}</li>""" fixName: (name) -> # Special case handling for Heavy Scyk :( if name.indexOf('"Heavy Scyk" Interceptor') == 0 '"Heavy Scyk" Interceptor' else name check: (where, type, name) -> (((where[type] ? {})[@fixName name] ? []).length ? 0) != 0 checkShelf: (type, name) -> @check @shelf, type, name checkTable: (type, name) -> @check @table, type, name use: (type, name) -> name = @fixName name try card = @shelf[type][name].pop() catch e return false unless card? if card? ((@table[type] ?= {})[name] ?= []).push card true else false release: (type, name) -> name = @fixName name try card = @table[type][name].pop() catch e return false unless card? if card? ((@shelf[type] ?= {})[name] ?= []).push card true else false save: (cb=$.noop) -> @backend.saveCollection(this, cb) if @backend? @load: (backend, cb) -> backend.loadCollection cb setupUI: -> # Create list of released singletons singletonsByType = {} for expname, items of exportObj.manifestByExpansion for item in items (singletonsByType[item.type] ?= {})[item.name] = true for type, names of singletonsByType sorted_names = (name for name of names).sort(sortWithoutQuotes) singletonsByType[type] = sorted_names @modal = $ document.createElement 'DIV' @modal.addClass 'modal hide fade collection-modal hidden-print' $('body').append @modal @modal.append $.trim """ <div class="modal-header"> <button type="button" class="close hidden-print" data-dismiss="modal" aria-hidden="true">&times;</button> <h4>Your Collection</h4> </div> <div class="modal-body"> <ul class="nav nav-tabs"> <li class="active"><a data-target="#collection-expansions" data-toggle="tab">Expansions</a><li> <li><a data-target="#collection-ships" data-toggle="tab">Ships</a><li> <li><a data-target="#collection-pilots" data-toggle="tab">Pilots</a><li> <li><a data-target="#collection-upgrades" data-toggle="tab">Upgrades</a><li> <li><a data-target="#collection-modifications" data-toggle="tab">Mods</a><li> <li><a data-target="#collection-titles" data-toggle="tab">Titles</a><li> <li><a data-target="#collection-components" data-toggle="tab">Inventory</a><li> </ul> <div class="tab-content"> <div id="collection-expansions" class="tab-pane active container-fluid collection-content"></div> <div id="collection-ships" class="tab-pane active container-fluid collection-ship-content"></div> <div id="collection-pilots" class="tab-pane active container-fluid collection-pilot-content"></div> <div id="collection-upgrades" class="tab-pane active container-fluid collection-upgrade-content"></div> <div id="collection-modifications" class="tab-pane active container-fluid collection-modification-content"></div> <div id="collection-titles" class="tab-pane active container-fluid collection-title-content"></div> <div id="collection-components" class="tab-pane container-fluid collection-inventory-content"></div> </div> </div> <div class="modal-footer hidden-print"> <span class="collection-status"></span> &nbsp; <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> </div> """ @modal_status = $ @modal.find('.collection-status') collection_content = $ @modal.find('.collection-content') for expansion in exportObj.expansions count = parseInt(@expansions[expansion] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="expansion-count" type="number" size="3" value="#{count}" /> <span class="expansion-name">#{expansion}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'expansion', expansion input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.expansion-name').data 'english_name', expansion collection_content.append row shipcollection_content = $ @modal.find('.collection-ship-content') for ship in singletonsByType.ship count = parseInt(@singletons.ship?[ship] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="ship-name">#{ship}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'ship' input.data 'singletonName', ship input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.ship-name').data 'english_name', expansion shipcollection_content.append row pilotcollection_content = $ @modal.find('.collection-pilot-content') for pilot in singletonsByType.pilot count = parseInt(@singletons.pilot?[pilot] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="pilot-name">#{pilot}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'pilot' input.data 'singletonName', pilot input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.pilot-name').data 'english_name', expansion pilotcollection_content.append row upgradecollection_content = $ @modal.find('.collection-upgrade-content') for upgrade in singletonsByType.upgrade count = parseInt(@singletons.upgrade?[upgrade] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="upgrade-name">#{upgrade}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'upgrade' input.data 'singletonName', upgrade input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.upgrade-name').data 'english_name', expansion upgradecollection_content.append row modificationcollection_content = $ @modal.find('.collection-modification-content') for modification in singletonsByType.modification count = parseInt(@singletons.modification?[modification] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="modification-name">#{modification}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'modification' input.data 'singletonName', modification input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.modification-name').data 'english_name', expansion modificationcollection_content.append row titlecollection_content = $ @modal.find('.collection-title-content') for title in singletonsByType.title count = parseInt(@singletons.title?[title] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="title-name">#{title}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'title' input.data 'singletonName', title input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.title-name').data 'english_name', expansion titlecollection_content.append row destroyUI: -> @modal.modal 'hide' @modal.remove() $(exportObj).trigger 'xwing-collection:destroyed', this setupHandlers: -> $(exportObj).trigger 'xwing-collection:created', this $(exportObj).on 'xwing-backend:authenticationChanged', (e, authenticated, backend) => # console.log "deauthed, destroying collection UI" @destroyUI() unless authenticated .on 'xwing-collection:saved', (e, collection) => @modal_status.text 'Collection saved' @modal_status.fadeIn 100, => @modal_status.fadeOut 5000 .on 'xwing:languageChanged', @onLanguageChange $ @modal.find('input.expansion-count').change (e) => target = $(e.target) val = target.val() target.val(0) if val < 0 or isNaN(parseInt(val)) @expansions[target.data 'expansion'] = parseInt(target.val()) target.closest('div').css 'background-color', @countToBackgroundColor(val) # console.log "Input changed, triggering collection change" $(exportObj).trigger 'xwing-collection:changed', this $ @modal.find('input.singleton-count').change (e) => target = $(e.target) val = target.val() target.val(0) if val < 0 or isNaN(parseInt(val)) (@singletons[target.data 'singletonType'] ?= {})[target.data 'singletonName'] = parseInt(target.val()) target.closest('div').css 'background-color', @countToBackgroundColor(val) # console.log "Input changed, triggering collection change" $(exportObj).trigger 'xwing-collection:changed', this countToBackgroundColor: (count) -> count = parseInt(count) switch when count == 0 '' when count < 12 i = parseInt(200 * Math.pow(0.9, count - 1)) "rgb(#{i}, 255, #{i})" else 'red' onLanguageChange: (e, language) => if language != @language # console.log "language changed to #{language}" do (language) => @modal.find('.expansion-name').each -> # console.log "translating #{$(this).text()} (#{$(this).data('english_name')}) to #{language}" $(this).text exportObj.translate language, 'sources', $(this).data('english_name') @language = language
true
exportObj = exports ? this String::startsWith ?= (t) -> @indexOf t == 0 sortWithoutQuotes = (a, b) -> a_name = a.replace /[^a-z0-9]/ig, '' b_name = b.replace /[^a-z0-9]/ig, '' if a_name < b_name -1 else if a_name > b_name 1 else 0 exportObj.manifestByExpansion = 'Core': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Red Squadron Pilot' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PIse"' type: 'pilot' count: 1 } { name: '"Night Beast"' type: 'pilot' count: 1 } { name: 'Black Squadron Pilot' type: 'pilot' count: 2 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 2 } { name: 'Academy Pilot' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'R2-F2' type: 'upgrade' count: 1 } { name: 'R2-D2' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIation' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'X-Wing Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Red Squadron Pilot' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI Pilot' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'R5-K6' type: 'upgrade' count: 1 } { name: 'R5 Astromech' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'Y-Wing Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Gray Squadron Pilot' type: 'pilot' count: 1 } { name: 'Gold Squadron Pilot' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI TorPI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 1 } { name: 'R5-D8' type: 'upgrade' count: 1 } { name: 'R2 Astromech' type: 'upgrade' count: 1 } ] 'TIE Fighter Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'Black Squadron Pilot' type: 'pilot' count: 1 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 1 } { name: 'Academy Pilot' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 1 } ] 'TIE Advanced Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Storm Squadron Pilot' type: 'pilot' count: 1 } { name: 'Tempest Squadron Pilot' type: 'pilot' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 1 } { name: 'Expert Handling' type: 'upgrade' count: 1 } ] 'A-Wing Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Green Squadron Pilot' type: 'pilot' count: 1 } { name: 'Prototype Pilot' type: 'pilot' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 1 } { name: 'Homing Missiles' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: 'Push the Limit' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'Millennium Falcon Expansion Pack': [ { name: 'YT-1300' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 1 } { name: 'Assault Missiles' type: 'upgrade' count: 1 } { name: 'Elusiveness' type: 'upgrade' count: 1 } { name: 'Draw Their Fire' type: 'upgrade' count: 1 } { name: 'Veteran Instincts' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Weapons Engineer' type: 'upgrade' count: 1 } { name: 'Shield Upgrade' type: 'modification' count: 2 } { name: 'Engine Upgrade' type: 'modification' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } ] 'TIE Interceptor Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '''"PI:NAME:<NAME>END_PI"''' type: 'pilot' count: 1 } { name: 'Saber Squadron Pilot' type: 'pilot' count: 1 } { name: 'Avenger Squadron Pilot' type: 'pilot' count: 1 } { name: 'Alpha Squadron Pilot' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'Slave I Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Seismic PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIenPI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Stealth Device' type: 'modification' count: 2 } { name: 'PI:NAME:<NAME>END_PI I' type: 'title' count: 1 } ] 'B-Wing Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI Squadron Pilot' type: 'pilot' count: 1 } { name: 'Fire-Control System' type: 'upgrade' count: 1 } { name: 'Advanced Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'Ion Cannon' type: 'upgrade' count: 1 } { name: 'Autoblaster' type: 'upgrade' count: 1 } ] "HWK-290 Expansion Pack": [ { name: 'HWPI:NAME:<NAME>END_PI-29PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Rebel Operative' type: 'pilot' count: 1 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI Specialist' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } { name: 'Blaster Turret' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Intelligence Agent' type: 'upgrade' count: 1 } ] "TIE Bomber Expansion Pack": [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI Squadron Pilot' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PIimitar Squadron Pilot' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Advanced Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] "Lambda-Class Shuttle Expansion Pack": [ { name: 'Lambda-Class Shuttle' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PImicron Group Pilot' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Advanced Sensors' type: 'upgrade' count: 1 } { name: 'ST-321' type: 'title' count: 1 } { name: 'PI:NAME:<NAME>END_PI Laser PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Weapons Engineer' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Intelligence Agent' type: 'upgrade' count: 1 } { name: 'Navigator' type: 'upgrade' count: 1 } { name: 'Flight Instructor' type: 'upgrade' count: 1 } { name: 'Anti-Pursuit Lasers' type: 'modification' count: 2 } ] "Z-95 Headhunter Expansion Pack": [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Tala Squadron Pilot' type: 'pilot' count: 1 } { name: 'Bandit Squadron Pilot' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PIunPI:NAME:<NAME>END_PI Failsafe' type: 'modification' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIissPI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'E-Wing Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: 'Blackmoon Squadron Pilot' type: 'pilot' count: 1 } { name: 'Knave Squadron Pilot' type: 'pilot' count: 1 } { name: 'Advanced Sensors' type: 'upgrade' count: 1 } { name: 'Outmaneuver' type: 'upgrade' count: 1 } { name: 'R7-T1' type: 'upgrade' count: 1 } { name: 'R7 Astromech' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'TIE Defender Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Onyx Squadron Pilot' type: 'pilot' count: 1 } { name: 'Delta Squadron Pilot' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'modification' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'TIE Phantom Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'Shadow Squadron Pilot' type: 'pilot' count: 1 } { name: 'Sigma Squadron Pilot' type: 'pilot' count: 1 } { name: 'Fire-Control System' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Recon Specialist' type: 'upgrade' count: 1 } { name: 'Advanced Cloaking Device' type: 'modification' count: 1 } { name: 'Stygium Particle Accelerator' type: 'modification' count: 1 } ] 'YT-2400 Freighter Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI-240PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Experimental Interface' type: 'modification' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'modification' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI On Target' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] "VT-49 Decimator Expansion Pack": [ { name: 'VT-49 Decimator' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'modification' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } ] 'Imperial Aces Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Royal Guard Pilot' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Saber Squadron Pilot' type: 'pilot' count: 2 } { name: 'Royal Guard TIE' type: 'title' count: 2 } { name: 'Targeting Computer' type: 'modification' count: 2 } { name: 'Hull Upgrade' type: 'modification' count: 2 } { name: 'Push the Limit' type: 'upgrade' count: 2 } { name: 'Opportunist' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'modification' count: 2 } ] 'Rebel Aces Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Green Squadron Pilot' type: 'pilot' count: 1 } { name: 'Prototype Pilot' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Dagger Squadron Pilot' type: 'pilot' count: 1 } { name: 'Blue Squadron Pilot' type: 'pilot' count: 1 } { name: 'ChPI:NAME:<NAME>END_PIaan Refit' type: 'upgrade' count: 3 } { name: 'A-Wing Test Pilot' type: 'title' count: 2 } { name: 'Enhanced Scopes' type: 'upgrade' count: 2 } { name: 'Proton Rockets' type: 'upgrade' count: 2 } { name: 'B-Wing/E2' type: 'modification' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'Rebel Transport Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'GR-75 Medium Transport' type: 'ship' count: 1 } { name: 'GR-75 Medium Transport' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Red SPI:NAME:<NAME>END_PIron PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'DutyPI:NAME:<NAME>END_PI' type: 'title' count: 1 } { name: 'Quantum Storm' type: 'title' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } { name: 'Expanded Cargo Hold' type: 'upgrade' count: 1 } { name: 'R2-D6' type: 'upgrade' count: 1 } { name: 'R4-D6' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'R3-A2' type: 'upgrade' count: 1 } { name: 'WED-15 Repair Droid' type: 'upgrade' count: 1 } { name: 'Backup Shield Generator' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'EM Emitter' type: 'upgrade' count: 1 } { name: 'Engine Booster' type: 'upgrade' count: 1 } { name: 'R5-P9' type: 'upgrade' count: 1 } { name: 'Comms Booster' type: 'upgrade' count: 1 } { name: 'Frequency Jammer' type: 'upgrade' count: 1 } { name: 'Shield Projector' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Slicer Tools' type: 'upgrade' count: 1 } { name: 'Combat Retrofit' type: 'modification' count: 1 } ] 'Tantive IV Expansion Pack': [ { name: 'CR90 Corvette (Fore)' type: 'ship' count: 1 } { name: 'CR90 Corvette (Aft)' type: 'ship' count: 1 } { name: 'CR90 Corvette (Fore)' type: 'pilot' count: 1 } # { # name: 'CR90 Corvette (Crippled Fore)' # type: 'pilot' # count: 1 # } { name: 'CR90 Corvette (Aft)' type: 'pilot' count: 1 } # { # name: 'CR90 Corvette (Crippled Aft)' # type: 'pilot' # count: 1 # } { name: "PI:NAME:<NAME>END_PI" type: 'title' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'title' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } { name: 'Backup Shield Generator' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI-3PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Engineering Team' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'Single Turbolasers' type: 'upgrade' count: 3 } ] 'StarViper Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI Sun PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'modification' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'modification' count: 1 } ] "M3-A Interceptor Expansion Pack": [ { name: 'PI:NAME:<NAME>END_PI3-PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: '"Heavy Scyk" Interceptor' type: 'title' count: 1 skipForSource: true # special :( } { name: '"Heavy Scyk" Interceptor (Cannon)' type: 'title' count: 0 # special :( } { name: '"Heavy Scyk" Interceptor (Missile)' type: 'title' count: 0 # special :( } { name: '"Heavy SPI:NAME:<NAME>END_PIk" Interceptor (Torpedo)' type: 'title' count: 0 # special :( } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: '"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Stealth Device' type: 'modification' count: 1 } ] "IG-2000 Expansion Pack": [ { name: 'PI:NAME:<NAME>END_PIgressor' type: 'ship' count: 1 } { name: 'IG-88A' type: 'pilot' count: 1 } { name: 'IG-88B' type: 'pilot' count: 1 } { name: 'IG-88C' type: 'pilot' count: 1 } { name: 'IG-88D' type: 'pilot' count: 1 } { name: 'IG-2000' type: 'title' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: '"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIimity MPI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIismic Charges' type: 'upgrade' count: 1 } { name: "Dead Man's Switch" type: 'upgrade' count: 2 } { name: 'Feedback Array' type: 'upgrade' count: 2 } { name: '"PI:NAME:<NAME>END_PI Shot" Blaster' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] "Most Wanted Expansion Pack": [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI Sun PI:NAME:<NAME>END_PI" type: 'pilot' count: 2 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 2 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 2 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 2 } { name: "PI:NAME:<NAME>END_PI (Scum)" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI (Scum)" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: "K4 Security Droid" type: 'upgrade' count: 1 } { name: "Outlaw Tech" type: 'upgrade' count: 1 } { name: "Autoblaster Turret" type: 'upgrade' count: 2 } { name: "Bomb Loadout" type: 'upgrade' count: 2 } { name: "R4-B11" type: 'upgrade' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'upgrade' count: 1 } { name: "R4 Agromech" type: 'upgrade' count: 2 } { name: "Salvaged Astromech" type: 'upgrade' count: 2 } { name: "Unhinged Astromech" type: 'upgrade' count: 2 } { name: "BTL-A4 Y-Wing" type: 'title' count: 2 } { name: "PI:NAME:<NAME>END_PI" type: 'title' count: 1 } { name: '"Hot Shot" Blaster' type: 'upgrade' count: 1 } ] "Hound's Tooth Expansion Pack": [ { name: 'YV-666' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Crack Shot' type: 'upgrade' count: 1 } { name: 'Stay On Target' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'K4 Security Droid' type: 'upgrade' count: 1 } { name: 'Outlaw Tech' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'modification' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'modification' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'modification' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'title' count: 1 } ] 'Kihraxz Fighter Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'K-Wing Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Guardian Squadron Pilot' type: 'pilot' count: 1 } { name: 'Warden Squadron Pilot' type: 'pilot' count: 1 } { name: 'Twin Laser Turret' type: 'upgrade' count: 2 } { name: 'Plasma Torpedoes' type: 'upgrade' count: 1 } { name: 'Advanced Homing Missiles' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Extra Munitions' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Advanced SLAM' type: 'modification' count: 1 } ] 'TIE Punisher Expansion Pack': [ { name: 'TIE Punisher' type: 'ship' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'Black Eight Squadron Pilot' type: 'pilot' count: 1 } { name: 'Cutlass Squadron Pilot' type: 'pilot' count: 1 } { name: 'Enhanced Scopes' type: 'upgrade' count: 1 } { name: 'Extra Munitions' type: 'upgrade' count: 1 } { name: 'Flechette Torpedoes' type: 'upgrade' count: 1 } { name: 'Plasma Torpedoes' type: 'upgrade' count: 1 } { name: 'Advanced Homing Missiles' type: 'upgrade' count: 1 } { name: 'Cluster Mines' type: 'upgrade' count: 1 } { name: 'Ion Bombs' type: 'upgrade' count: 1 } { name: 'Twin Ion Engine Mk. II' type: 'modification' count: 2 } ] "Imperial Raider Expansion Pack": [ { name: "Raider-class Corvette (Fore)" type: 'ship' count: 1 } { name: "Raider-class Corvette (Aft)" type: 'ship' count: 1 } { name: "TIE Advanced" type: 'ship' count: 1 } { name: "Raider-class Corvette (Fore)" type: 'pilot' count: 1 } { name: "Raider-class Corvette (Aft)" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "Storm Squadron Pilot" type: 'pilot' count: 1 } { name: "Tempest Squadron Pilot" type: 'pilot' count: 1 } { name: "Advanced Targeting Computer" type: 'upgrade' count: 4 } { name: "TIE/x1" type: 'title' count: 4 } { name: "Cluster Missiles" type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: "Shield PI:NAME:<NAME>END_PInician" type: 'upgrade' count: 2 } { name: "Gunnery Team" type: 'upgrade' count: 1 } { name: "Engineering Team" type: 'upgrade' count: 1 } { name: "Sensor Team" type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 2 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 4 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 2 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 2 } { name: "PI:NAME:<NAME>END_PI BoostPI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: "Backup Shield Generator" type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'title' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'title' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'title' count: 1 } ] 'The Force Awakens Core Set': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI/fo PI:NAME:<NAME>END_PIighter' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI SPI:NAME:<NAME>END_PIron NoPI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI Squadron Pilot' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI PiPI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'BB-8' type: 'upgrade' count: 1 } { name: 'R5-X3' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Weapons Guidance' type: 'upgrade' count: 1 } ] 'Imperial Assault Carrier Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI Fighter' type: 'ship' count: 2 } { name: 'Gozanti-class Cruiser' type: 'ship' count: 1 } { name: 'Gozanti-class Cruiser' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'Academy Pilot' type: 'pilot' count: 2 } { name: 'Black Squadron Pilot' type: 'pilot' count: 2 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PIship' type: 'upgrade' count: 1 } { name: 'Expert Handling' type: 'upgrade' count: 1 } { name: 'Expose' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIing MissPI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI Laser Turret' type: 'upgrade' count: 1 } { name: 'Broadcast Array' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Ordnance Experts' type: 'upgrade' count: 2 } { name: 'Docking Clamps' type: 'upgrade' count: 1 } { name: 'Cluster Bombs' type: 'upgrade' count: 2 } { name: 'Automated Protocols' type: 'modification' count: 3 } { name: 'Optimized Generators' type: 'modification' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'modification' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } ] 'T-70 X-Wing Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Targeting Astromech' type: 'upgrade' count: 1 } { name: 'Weapons Guidance' type: 'upgrade' count: 1 } { name: 'Integrated Astromech' type: 'modification' count: 1 } { name: 'Advanced Proton Torpedoes' type: 'upgrade' count: 1 } ] 'TIE/fo Fighter Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI/PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: '"Omega Leader"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PIeta Leader"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'Omega Squadron Pilot' type: 'pilot' count: 1 } { name: 'Zeta Squadron Pilot' type: 'pilot' count: 1 } { name: 'Epsilon Squadron Pilot' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Comm Relay' type: 'upgrade' count: 1 } ] 'Ghost Expansion Pack': [ { name: 'VCX-100' type: 'ship' count: 1 } { name: 'Attack Shuttle' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (Attack Shuttle)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Reinforced Deflectors' type: 'upgrade' count: 1 } { name: 'Dorsal Turret' type: 'upgrade' count: 2 } { name: 'Advanced Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: '"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } ] 'Punishing One Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'modification' count: 2 } ] 'Mist Hunter Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'CloPI:NAME:<NAME>END_PI Device' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } ] "Inquisitor's TIE Expansion Pack": [ { name: 'TIE Advanced Prototype' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'DePI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'XX-23 S-Thread Tracers' type: 'upgrade' count: 1 } { name: 'Guidance Chips' type: 'modification' count: 1 } { name: 'TIE/v1' type: 'title' count: 1 } ] "Imperial Veterans Expansion Pack": [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI (TIE Defender)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Tractor Beam' type: 'upgrade' count: 1 } { name: 'Systems Officer' type: 'upgrade' count: 1 } { name: 'Cluster Mines' type: 'upgrade' count: 1 } { name: 'Proximity Mines' type: 'upgrade' count: 1 } { name: 'Long-Range Scanners' type: 'modification' count: 2 } { name: 'TIE/x7' type: 'title' count: 2 } { name: 'TIPI:NAME:<NAME>END_PI/D' type: 'title' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 2 } ] 'ARC-170 Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI-17PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI Specialist' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'modification' count: 2 } { name: 'PI:NAME:<NAME>END_PIhaPI:NAME:<NAME>END_PI' type: 'title' count: 1 } ] 'Special Forces TIE Expansion Pack': [ { name: 'TIE/sf Fighter' type: 'ship' count: 1 } { name: '"Quickdraw"' type: 'pilot' count: 1 } { name: '"Backdraft"' type: 'pilot' count: 1 } { name: 'Omega Specialist' type: 'pilot' count: 1 } { name: 'Zeta SpecialPI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Wired' type: 'upgrade' count: 1 } { name: 'Collision Detector' type: 'upgrade' count: 1 } { name: 'Sensor Cluster' type: 'upgrade' count: 2 } { name: 'Special Ops Training' type: 'title' count: 1 } ] 'Protectorate Starfighter Expansion Pack': [ { name: 'Protectorate Starfighter' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI DPI:NAME:<NAME>END_PI Protector' type: 'title' count: 1 } ] 'Shadow Caster Expansion Pack': [ { name: 'Lancer-class Pursuit Craft' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (Scum)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'IG-88D' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Black Market Slicer Tools' type: 'upgrade' count: 2 } { name: 'Rigged Cargo Chute' type: 'upgrade' count: 1 } { name: 'Countermeasures' type: 'modification' count: 1 } { name: 'Gyroscopic Targeting' type: 'modification' count: 1 } { name: 'Tactical Jammer' type: 'modification' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } ] 'Heroes of the Resistance Expansion Pack': [ { name: 'YT-1300' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI (TFA)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (TFA)' type: 'pilot' count: 1 } { name: 'Resistance Sympathizer' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (PS9)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '''"PI:NAME:<NAME>END_PI''' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Red Squadron Veteran' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PIquadron PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)' type: 'title' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } { name: 'Integrated Astromech' type: 'modification' count: 2 } { name: 'Smuggling Compartment' type: 'modification' count: 1 } ] "U-Wing Expansion Pack": [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Expertise' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } { name: 'Stealth Device' type: 'modification' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] "TIE Striker Expansion Pack": [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Lightweight Frame' type: 'modification' count: 1 } { name: 'PI:NAME:<NAME>END_PIilerons' type: 'title' count: 1 } ] "Sabine's TIE Fighter Expansion Pack": [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (TIE Fighter)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI (TIE Fighter)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: '''PI:NAME:<NAME>END_PI's Masterpiece''' type: 'title' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'modification' count: 1 } ] "Upsilon-class Shuttle Expansion Pack": [ { name: 'Upsilon-class Shuttle' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Operations Specialist' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIing Synchronizer' type: 'upgrade' count: 2 } { name: 'Hyperwave Comm Scanner' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'modification' count: 2 } { name: '''PI:NAME:<NAME>END_PI''' type: 'title' count: 1 } ] "Quadjumper Expansion Pack": [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIermal PI:NAME:<NAME>END_PIonPI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIwave Comm PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'modification' count: 1 } ] 'C-ROC Cruiser Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'IG-RM PI:NAME:<NAME>END_PIug DPI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'ARC Caster' type: 'upgrade' count: 5 } { name: 'Heavy Laser Turret' type: 'upgrade' count: 1 } { name: 'Supercharged Power Cells' type: 'upgrade' count: 2 } { name: 'Quick-release Cargo Locks' type: 'upgrade' count: 1 } { name: 'Merchant One' type: 'title' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } { name: 'Insatiable Worrt' type: 'title' count: 1 } { name: '"Light Scyk" Interceptor' type: 'title' count: 6 } { name: '"Heavy Scyk" Interceptor' type: 'title' count: 1 } { name: 'Automated Protocols' type: 'modification' count: 1 } { name: 'Optimized Generators' type: 'modification' count: 1 } { name: 'Pulsed Ray Shield' type: 'modification' count: 5 } ] "Auzituck Gunship Expansion Pack": [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'modification' count: 1 } ] "Scurrg H-6 Bomber Expansion Pack": [ { name: 'PI:NAME:<NAME>END_PI H-6 BomPI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Bomblet Generator' type: 'upgrade' count: 1 } { name: 'Minefield Mapper' type: 'upgrade' count: 1 } { name: 'Synced Turret' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 1 } ] "TIE Aggressor Expansion Pack": [ { name: 'PI:NAME:<NAME>END_PI AgPI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"Double Edge"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Intensity' type: 'upgrade' count: 1 } { name: 'Unguided Rockets' type: 'upgrade' count: 1 } { name: 'Twin Laser Turret' type: 'upgrade' count: 1 } { name: 'Synced Turret' type: 'upgrade' count: 1 } { name: 'Lightweight Frame' type: 'modification' count: 1 } ] 'Guns for Hire Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'title' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'modification' count: 2 } { name: 'Stealth Device' type: 'modification' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'modification' count: 1 } ] class exportObj.Collection # collection = new exportObj.Collection # expansions: # "Core": 2 # "TIE Fighter Expansion Pack": 4 # "B-Wing Expansion Pack": 2 # singletons: # ship: # "T-70 X-Wing": 1 # pilot: # "Academy Pilot": 16 # upgrade: # "C-3PO": 4 # "Gunner": 5 # modification: # "Engine Upgrade": 2 # title: # "TIE/x1": 1 # # # or # # collection = exportObj.Collection.load(backend) # # collection.use "pilot", "Red Squadron Pilot" # collection.use "upgrade", "R2-D2" # collection.use "upgrade", "Ion Pulse Missiles" # returns false # # collection.release "pilot", "Red Squadron Pilot" # collection.release "pilot", "Sigma Squadron Pilot" # returns false constructor: (args) -> @expansions = args.expansions ? {} @singletons = args.singletons ? {} # To save collection (optional) @backend = args.backend @setupUI() @setupHandlers() @reset() @language = 'English' reset: -> @shelf = {} @table = {} for expansion, count of @expansions try count = parseInt count catch count = 0 for _ in [0...count] for card in (exportObj.manifestByExpansion[expansion] ? []) for _ in [0...card.count] ((@shelf[card.type] ?= {})[card.name] ?= []).push expansion for type, counts of @singletons for name, count of counts for _ in [0...count] ((@shelf[type] ?= {})[name] ?= []).push 'singleton' @counts = {} for own type of @shelf for own thing of @shelf[type] (@counts[type] ?= {})[thing] ?= 0 @counts[type][thing] += @shelf[type][thing].length component_content = $ @modal.find('.collection-inventory-content') component_content.text '' for own type, things of @counts contents = component_content.append $.trim """ <div class="row-fluid"> <div class="span12"><h5>#{type.capitalize()}</h5></div> </div> <div class="row-fluid"> <ul id="counts-#{type}" class="span12"></ul> </div> """ ul = $ contents.find("ul#counts-#{type}") for thing in Object.keys(things).sort(sortWithoutQuotes) ul.append """<li>#{thing} - #{things[thing]}</li>""" fixName: (name) -> # Special case handling for Heavy Scyk :( if name.indexOf('"Heavy Scyk" Interceptor') == 0 '"Heavy Scyk" Interceptor' else name check: (where, type, name) -> (((where[type] ? {})[@fixName name] ? []).length ? 0) != 0 checkShelf: (type, name) -> @check @shelf, type, name checkTable: (type, name) -> @check @table, type, name use: (type, name) -> name = @fixName name try card = @shelf[type][name].pop() catch e return false unless card? if card? ((@table[type] ?= {})[name] ?= []).push card true else false release: (type, name) -> name = @fixName name try card = @table[type][name].pop() catch e return false unless card? if card? ((@shelf[type] ?= {})[name] ?= []).push card true else false save: (cb=$.noop) -> @backend.saveCollection(this, cb) if @backend? @load: (backend, cb) -> backend.loadCollection cb setupUI: -> # Create list of released singletons singletonsByType = {} for expname, items of exportObj.manifestByExpansion for item in items (singletonsByType[item.type] ?= {})[item.name] = true for type, names of singletonsByType sorted_names = (name for name of names).sort(sortWithoutQuotes) singletonsByType[type] = sorted_names @modal = $ document.createElement 'DIV' @modal.addClass 'modal hide fade collection-modal hidden-print' $('body').append @modal @modal.append $.trim """ <div class="modal-header"> <button type="button" class="close hidden-print" data-dismiss="modal" aria-hidden="true">&times;</button> <h4>Your Collection</h4> </div> <div class="modal-body"> <ul class="nav nav-tabs"> <li class="active"><a data-target="#collection-expansions" data-toggle="tab">Expansions</a><li> <li><a data-target="#collection-ships" data-toggle="tab">Ships</a><li> <li><a data-target="#collection-pilots" data-toggle="tab">Pilots</a><li> <li><a data-target="#collection-upgrades" data-toggle="tab">Upgrades</a><li> <li><a data-target="#collection-modifications" data-toggle="tab">Mods</a><li> <li><a data-target="#collection-titles" data-toggle="tab">Titles</a><li> <li><a data-target="#collection-components" data-toggle="tab">Inventory</a><li> </ul> <div class="tab-content"> <div id="collection-expansions" class="tab-pane active container-fluid collection-content"></div> <div id="collection-ships" class="tab-pane active container-fluid collection-ship-content"></div> <div id="collection-pilots" class="tab-pane active container-fluid collection-pilot-content"></div> <div id="collection-upgrades" class="tab-pane active container-fluid collection-upgrade-content"></div> <div id="collection-modifications" class="tab-pane active container-fluid collection-modification-content"></div> <div id="collection-titles" class="tab-pane active container-fluid collection-title-content"></div> <div id="collection-components" class="tab-pane container-fluid collection-inventory-content"></div> </div> </div> <div class="modal-footer hidden-print"> <span class="collection-status"></span> &nbsp; <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> </div> """ @modal_status = $ @modal.find('.collection-status') collection_content = $ @modal.find('.collection-content') for expansion in exportObj.expansions count = parseInt(@expansions[expansion] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="expansion-count" type="number" size="3" value="#{count}" /> <span class="expansion-name">#{expansion}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'expansion', expansion input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.expansion-name').data 'english_name', expansion collection_content.append row shipcollection_content = $ @modal.find('.collection-ship-content') for ship in singletonsByType.ship count = parseInt(@singletons.ship?[ship] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="ship-name">#{ship}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'ship' input.data 'singletonName', ship input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.ship-name').data 'english_name', expansion shipcollection_content.append row pilotcollection_content = $ @modal.find('.collection-pilot-content') for pilot in singletonsByType.pilot count = parseInt(@singletons.pilot?[pilot] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="pilot-name">#{pilot}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'pilot' input.data 'singletonName', pilot input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.pilot-name').data 'english_name', expansion pilotcollection_content.append row upgradecollection_content = $ @modal.find('.collection-upgrade-content') for upgrade in singletonsByType.upgrade count = parseInt(@singletons.upgrade?[upgrade] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="upgrade-name">#{upgrade}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'upgrade' input.data 'singletonName', upgrade input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.upgrade-name').data 'english_name', expansion upgradecollection_content.append row modificationcollection_content = $ @modal.find('.collection-modification-content') for modification in singletonsByType.modification count = parseInt(@singletons.modification?[modification] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="modification-name">#{modification}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'modification' input.data 'singletonName', modification input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.modification-name').data 'english_name', expansion modificationcollection_content.append row titlecollection_content = $ @modal.find('.collection-title-content') for title in singletonsByType.title count = parseInt(@singletons.title?[title] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="title-name">#{title}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'title' input.data 'singletonName', title input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.title-name').data 'english_name', expansion titlecollection_content.append row destroyUI: -> @modal.modal 'hide' @modal.remove() $(exportObj).trigger 'xwing-collection:destroyed', this setupHandlers: -> $(exportObj).trigger 'xwing-collection:created', this $(exportObj).on 'xwing-backend:authenticationChanged', (e, authenticated, backend) => # console.log "deauthed, destroying collection UI" @destroyUI() unless authenticated .on 'xwing-collection:saved', (e, collection) => @modal_status.text 'Collection saved' @modal_status.fadeIn 100, => @modal_status.fadeOut 5000 .on 'xwing:languageChanged', @onLanguageChange $ @modal.find('input.expansion-count').change (e) => target = $(e.target) val = target.val() target.val(0) if val < 0 or isNaN(parseInt(val)) @expansions[target.data 'expansion'] = parseInt(target.val()) target.closest('div').css 'background-color', @countToBackgroundColor(val) # console.log "Input changed, triggering collection change" $(exportObj).trigger 'xwing-collection:changed', this $ @modal.find('input.singleton-count').change (e) => target = $(e.target) val = target.val() target.val(0) if val < 0 or isNaN(parseInt(val)) (@singletons[target.data 'singletonType'] ?= {})[target.data 'singletonName'] = parseInt(target.val()) target.closest('div').css 'background-color', @countToBackgroundColor(val) # console.log "Input changed, triggering collection change" $(exportObj).trigger 'xwing-collection:changed', this countToBackgroundColor: (count) -> count = parseInt(count) switch when count == 0 '' when count < 12 i = parseInt(200 * Math.pow(0.9, count - 1)) "rgb(#{i}, 255, #{i})" else 'red' onLanguageChange: (e, language) => if language != @language # console.log "language changed to #{language}" do (language) => @modal.find('.expansion-name').each -> # console.log "translating #{$(this).text()} (#{$(this).data('english_name')}) to #{language}" $(this).text exportObj.translate language, 'sources', $(this).data('english_name') @language = language
[ { "context": "d, 'user'\n test.equal opts.token, 'pass'\n super opts\n\n opts = {\n ", "end": 1077, "score": 0.9305680990219116, "start": 1073, "tag": "PASSWORD", "value": "pass" }, { "context": " = {\n uuid: 'user'\n token: 'pass'\n }\n\n connection = new ConnectionSt", "end": 1173, "score": 0.9156089425086975, "start": 1169, "tag": "PASSWORD", "value": "pass" }, { "context": " = {\n uuid: 'user'\n token: 'pass'\n }\n\n target = new OctobluBackend '", "end": 4591, "score": 0.9608159065246582, "start": 4587, "tag": "PASSWORD", "value": "pass" }, { "context": "d, 'user'\n test.equal data.token, 'pass'\n test.throws () ->\n ", "end": 5498, "score": 0.9717814922332764, "start": 5494, "tag": "PASSWORD", "value": "pass" }, { "context": " = {\n uuid: 'user'\n token: 'pass'\n }\n\n target = new OctobluBackend '", "end": 5758, "score": 0.967430591583252, "start": 5754, "tag": "PASSWORD", "value": "pass" }, { "context": " = {\n uuid: 'user'\n token: 'pass'\n }\n\n target = new OctobluBackend '", "end": 6649, "score": 0.9058960676193237, "start": 6645, "tag": "PASSWORD", "value": "pass" }, { "context": "es = [\n new Property 'string', 'KEY', '123'\n new Property 'string', 'monkey', 'bo", "end": 10326, "score": 0.9471619129180908, "start": 10323, "tag": "KEY", "value": "123" }, { "context": "es = [\n new Property 'string', 'KEY', '123'\n new Property 'string', 'monkey', 'bo", "end": 11478, "score": 0.990519106388092, "start": 11475, "tag": "KEY", "value": "123" }, { "context": "es = [\n new Property 'string', 'KEY', '123'\n new Property 'string', 'monkey', 'bo", "end": 12483, "score": 0.987216055393219, "start": 12480, "tag": "KEY", "value": "123" }, { "context": "es = [\n new Property 'string', 'KEY', '123'\n new Property 'string', 'monkey', 'bo", "end": 13528, "score": 0.9820282459259033, "start": 13525, "tag": "KEY", "value": "123" }, { "context": " : (test) ->\n thing1 = {\n KEY: '123'\n monkey: 'boy'\n ROOM: '101", "end": 14501, "score": 0.9973623752593994, "start": 14498, "tag": "KEY", "value": "123" }, { "context": "'\n }\n\n thing2 = {\n KEY: '456'\n monkey: 'island'\n ROOM: '", "end": 14666, "score": 0.9981397986412048, "start": 14663, "tag": "KEY", "value": "456" }, { "context": " : (test) ->\n thing1 = {\n KEY: '123'\n monkey: 'boy'\n ROOM: '101", "end": 15930, "score": 0.9906827807426453, "start": 15927, "tag": "KEY", "value": "123" }, { "context": "'\n }\n\n thing2 = {\n KEY: '456'\n monkey: 'island'\n ROOM: '", "end": 16206, "score": 0.9992632269859314, "start": 16203, "tag": "KEY", "value": "456" }, { "context": "= {\n KEY: '456'\n monkey: 'island'\n ROOM: '101'\n xmpp_jid: 'j", "end": 16235, "score": 0.6534979939460754, "start": 16231, "tag": "KEY", "value": "land" }, { "context": " : (test) ->\n thing1 = {\n KEY: '123'\n monkey: 'boy'\n ROOM: '101", "end": 17611, "score": 0.9990325570106506, "start": 17608, "tag": "KEY", "value": "123" }, { "context": "'\n }\n\n thing2 = {\n KEY: '456'\n monkey: 'island'\n ROOM: '", "end": 17743, "score": 0.9992177486419678, "start": 17740, "tag": "KEY", "value": "456" }, { "context": "= {\n KEY: '456'\n monkey: 'island'\n ROOM: '101'\n xmpp_jid: 'j", "end": 17772, "score": 0.7466270327568054, "start": 17768, "tag": "KEY", "value": "land" }, { "context": " : (test) ->\n thing1 = {\n KEY: '123'\n monkey: 'boy'\n ROOM: '101", "end": 18884, "score": 0.9990315437316895, "start": 18881, "tag": "KEY", "value": "123" }, { "context": " xmpp_jid: 'jid1'\n xmpp_owner: 'owner1'\n xmpp_public: 'true'\n }\n\n ", "end": 18996, "score": 0.5302731394767761, "start": 18995, "tag": "USERNAME", "value": "1" }, { "context": "'\n }\n\n thing2 = {\n KEY: '456'\n monkey: 'island'\n ROOM: '", "end": 19081, "score": 0.999049186706543, "start": 19078, "tag": "KEY", "value": "456" }, { "context": " : (test) ->\n thing1 = {\n KEY: '123'\n monkey: 'boy'\n ROOM: '101", "end": 20300, "score": 0.9978622794151306, "start": 20297, "tag": "KEY", "value": "123" }, { "context": " xmpp_jid: 'jid1'\n xmpp_owner: 'owner1'\n xmpp_removed: 'true'\n }\n\n ", "end": 20412, "score": 0.7901663780212402, "start": 20406, "tag": "USERNAME", "value": "owner1" }, { "context": "'\n }\n\n thing2 = {\n KEY: '456'\n monkey: 'island'\n ROOM: '", "end": 20498, "score": 0.9930205345153809, "start": 20495, "tag": "KEY", "value": "456" }, { "context": " xmpp_jid: 'jid2'\n xmpp_owner: 'owner2'\n }\n\n class ConnectionStub extends ", "end": 20613, "score": 0.8976049423217773, "start": 20612, "tag": "USERNAME", "value": "2" }, { "context": " : (test) ->\n thing1 = {\n KEY: '123'\n monkey: 'boy'\n ROOM: '101", "end": 21676, "score": 0.9971720576286316, "start": 21673, "tag": "KEY", "value": "123" }, { "context": " xmpp_jid: 'jid1'\n xmpp_owner: 'owner1'\n }\n\n thing2 = {\n KEY: '", "end": 21788, "score": 0.8337076902389526, "start": 21782, "tag": "USERNAME", "value": "owner1" }, { "context": "'\n }\n\n thing2 = {\n KEY: '456'\n monkey: 'island'\n ROOM: '", "end": 21841, "score": 0.9939450621604919, "start": 21838, "tag": "KEY", "value": "456" }, { "context": " xmpp_jid: 'jid2'\n xmpp_owner: 'owner2'\n }\n\n thing3 = {\n KEY: '", "end": 21956, "score": 0.938656210899353, "start": 21955, "tag": "USERNAME", "value": "2" }, { "context": "'\n }\n\n thing3 = {\n KEY: '789'\n monkey: 'island'\n ROOM: '", "end": 22009, "score": 0.9963529706001282, "start": 22006, "tag": "KEY", "value": "789" }, { "context": " xmpp_jid: 'jid3'\n xmpp_owner: 'owner3'\n }\n\n thing4 = {\n KEY: '", "end": 22124, "score": 0.7617185711860657, "start": 22123, "tag": "KEY", "value": "3" }, { "context": "'\n }\n\n thing4 = {\n KEY: '012'\n monkey: 'island'\n ROOM: '", "end": 22177, "score": 0.9971134066581726, "start": 22174, "tag": "KEY", "value": "012" }, { "context": " : (test) ->\n thing1 = {\n KEY: '123'\n monkey: 'boy'\n ROOM: '101", "end": 23520, "score": 0.9902136921882629, "start": 23517, "tag": "KEY", "value": "123" }, { "context": " xmpp_jid: 'jid1'\n xmpp_owner: 'owner1'\n }\n\n thing2 = {\n KEY: '", "end": 23632, "score": 0.842866837978363, "start": 23631, "tag": "USERNAME", "value": "1" }, { "context": "'\n }\n\n thing2 = {\n KEY: '456'\n monkey: 'island'\n ROOM: '", "end": 23685, "score": 0.9976314902305603, "start": 23682, "tag": "KEY", "value": "456" }, { "context": " xmpp_jid: 'jid2'\n xmpp_owner: 'owner2'\n }\n\n thing3 = {\n KEY: '", "end": 23800, "score": 0.8257332444190979, "start": 23799, "tag": "USERNAME", "value": "2" }, { "context": "'\n }\n\n thing3 = {\n KEY: '789'\n monkey: 'island'\n ROOM: '", "end": 23853, "score": 0.9979545474052429, "start": 23850, "tag": "KEY", "value": "789" }, { "context": " xmpp_jid: 'jid3'\n xmpp_owner: 'owner3'\n }\n\n thing4 = {\n KEY: '", "end": 23968, "score": 0.8467127084732056, "start": 23967, "tag": "USERNAME", "value": "3" }, { "context": "'\n }\n\n thing4 = {\n KEY: '012'\n monkey: 'island'\n ROOM: '", "end": 24021, "score": 0.9934003353118896, "start": 24018, "tag": "KEY", "value": "012" }, { "context": " : (test) ->\n thing1 = {\n KEY: '123'\n monkey: 'boy'\n ROOM: '101", "end": 25340, "score": 0.998420774936676, "start": 25337, "tag": "KEY", "value": "123" }, { "context": " xmpp_jid: 'jid1'\n xmpp_owner: 'owner1'\n }\n\n thing2 = {\n KEY: '", "end": 25452, "score": 0.7949857711791992, "start": 25446, "tag": "USERNAME", "value": "owner1" }, { "context": "'\n }\n\n thing2 = {\n KEY: '456'\n monkey: 'island'\n ROOM: '", "end": 25505, "score": 0.9943343997001648, "start": 25502, "tag": "KEY", "value": "456" }, { "context": " xmpp_jid: 'jid2'\n xmpp_owner: 'owner2'\n }\n\n thing3 = {\n KEY: '", "end": 25620, "score": 0.9232341647148132, "start": 25619, "tag": "USERNAME", "value": "2" }, { "context": "'\n }\n\n thing3 = {\n KEY: '789'\n monkey: 'island'\n ROOM: '", "end": 25673, "score": 0.9836054444313049, "start": 25670, "tag": "KEY", "value": "789" }, { "context": " xmpp_jid: 'jid3'\n xmpp_owner: 'owner3'\n }\n\n thing4 = {\n KEY: '", "end": 25788, "score": 0.9295865297317505, "start": 25787, "tag": "USERNAME", "value": "3" }, { "context": "'\n }\n\n thing4 = {\n KEY: '012'\n monkey: 'island'\n ROOM: '", "end": 25841, "score": 0.9959673881530762, "start": 25838, "tag": "KEY", "value": "012" }, { "context": " xmpp_jid: 'jid4'\n xmpp_owner: 'owner4'\n }\n\n class ConnectionStub extends ", "end": 25956, "score": 0.7767924070358276, "start": 25950, "tag": "USERNAME", "value": "owner4" }, { "context": " xmpp_owner: 'owner'\n KEY: '123'\n TEST: '456'\n ROOM: '101'\n", "end": 28262, "score": 0.9993743300437927, "start": 28259, "tag": "KEY", "value": "123" }, { "context": "ties)\n\n storedDevice = {\n KEY: '123'\n TEST: '456'\n ROOM: '101'\n", "end": 29964, "score": 0.9992644190788269, "start": 29961, "tag": "KEY", "value": "123" } ]
test/octoblu-backend.test.coffee
TNO-IoT/ekster
3
# Tests if the server component complies to # https://xmpp.org/extensions/xep-0347.html # # Some test cases refer to paragraphs and / or examples from the spec. {EventEmitter} = require 'events' OctobluBackend = require '../src/octoblu-backend.coffee' Thing = require '../src/thing.coffee' Property = require '../src/property.coffee' Filter = require '../src/filter.coffee' Q = require 'q' _ = require 'lodash' class OctobluStub constructor: (@connection) -> createConnection: (opts) -> return @connection exports.OctobluBackendTest = 'test register test if preconditions are not met': (test) -> properties = [ new Property('type', 'name', 'value') ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> class OptionTestStub extends OctobluStub createConnection: (opts) -> test.equal opts.server, 'test' test.equal opts.port, 666 test.equal opts.uuid, 'user' test.equal opts.token, 'pass' super opts opts = { uuid: 'user' token: 'pass' } connection = new ConnectionStub() target = new OctobluBackend 'test', 666, opts, undefined, new OptionTestStub(connection) promise = target.register thing onSuccess = (thing) -> test.equal true, false onFail = (err) -> test.equal err.message, 'Missing property: KEY' test.expect 5 test.done() promise.then onSuccess, onFail 'test register test if reserved words are used': (test) -> properties = [ new Property 'type', 'KEY', 'value' new Property 'type', 'xmpp_nodeId', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> connection = new ConnectionStub() target = new OctobluBackend undefined, undefined, {}, undefined, new OctobluStub(connection) promise = target.register thing onSuccess = (thing) -> test.equal true, false onFail = (err) -> test.equal err.message, 'Illegal property: xmpp_nodeId' test.expect 1 test.done() promise.then onSuccess, onFail 'test register hash value': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) thing.nodeId = 'nodeId' thing.sourceId = 'sourceId' thing.cacheType = 'cacheType' class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> test.equal data.uuid, '582b91b44e49a038a607f09e0d12cc61' test.equal data.token, 'value' result = { xmpp_jid: thing.jid xmpp_nodeId: thing.nodeId xmpp_sourceId: thing.sourceId xmpp_cacheType: thing.cacheType uuid: data.uuid token: data.token } cb result devices: (data, cb) -> test.equal data.uuid, '582b91b44e49a038a607f09e0d12cc61' cb { devices: [] } connection = new ConnectionStub() target = new OctobluBackend undefined, undefined, {}, undefined, new OctobluStub(connection) promise = target.register thing onSuccess = (thing) -> test.equal thing.uuid, '582b91b44e49a038a607f09e0d12cc61' test.equal thing.token, 'value' test.expect 5 test.done() onFail = (err) -> test.expect false, true promise.then onSuccess, onFail 'test no backend account': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> if data.uuid is 'user' test.equal data.token, 'pass' else test.equal data.token, 'value' cb data devices: (data, cb) -> cb { devices: [] } connection = new ConnectionStub() opts = { uuid: 'user' token: 'pass' } target = new OctobluBackend 'test', 666, opts, undefined, new OctobluStub(connection) connection.emit 'notReady' promise = target.register thing onSuccess = (thing) -> test.equal thing.token, 'value' test.equal thing.uuid, '3d4478eb8cae476e97eacd52aa1cca16' test.expect 4 test.done() onFail = (err) -> test.expect false, true promise.then onSuccess, onFail 'test registration of the backend account failed': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> test.equal data.uuid, 'user' test.equal data.token, 'pass' test.throws () -> cb { } test.done() devices: (data, cb) -> cb [] connection = new ConnectionStub() opts = { uuid: 'user' token: 'pass' } target = new OctobluBackend 'test', 666, opts, undefined, new OctobluStub(connection) connection.emit 'notReady' 'test thing already registered': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> cb data devices: (data, cb) -> result = { devices: [ { uuid: data.uuid } ] } cb result unregister: (data, cb) -> test.equal data.uuid, '3d4478eb8cae476e97eacd52aa1cca16' cb data connection = new ConnectionStub() opts = { uuid: 'user' token: 'pass' } target = new OctobluBackend 'test', 666, opts, undefined, new OctobluStub(connection) connection.emit 'notReady' promise = target.register thing onSuccess = (thing) -> test.equal thing.token, 'value' test.equal thing.uuid, '3d4478eb8cae476e97eacd52aa1cca16' test.expect 3 test.done() onFail = (err) -> test.expect false, true promise.then onSuccess, onFail 'test thing already registered and owned': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> cb data devices: (data, cb) -> result = { devices: [ { uuid: data.uuid, xmpp_owner: 'owner' } ] } cb result connection = new ConnectionStub() target = new OctobluBackend undefined, undefined, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.register thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' onFail = (err) -> test.equal err.message, 'claimed' test.equal err.owner, 'owner' test.expect 2 test.done() promise.then onSuccess, onFail 'test thing unregister fails': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> cb data devices: (data, cb) -> result = { devices: [ { uuid: data.uuid } ] } cb result unregister: (data, cb) -> cb { name: 'error' } connection = new ConnectionStub() target = new OctobluBackend undefined, undefined, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.register thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' onFail = (err) -> test.equal err.message, 'unregister failed' test.expect 1 test.done() promise.then onSuccess, onFail 'test register thing: multiple matching things found in the registry': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> cb data devices: (data, cb) -> result = { devices: [ {}, {} ] } cb result connection = new ConnectionStub() target = new OctobluBackend undefined, undefined, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.register thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' onFail = (err) -> test.done() promise.then onSuccess, onFail 'test claim ownership: success case' : (test) -> properties = [ new Property 'string', 'KEY', '123' new Property 'string', 'monkey', 'boy' ] thing = new Thing('jid', properties) thing.owner = 'owner' thing.needsNotification = true class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'xmpp_owner'), false result = { devices: [ data ] } cb result update: (data, cb) -> test.equal data.xmpp_owner, 'owner' cb data connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.claim thing onSuccess = (thing) -> test.equal thing.owner, 'owner' test.expect 3 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test claim ownership: device not found' : (test) -> properties = [ new Property 'string', 'KEY', '123' new Property 'string', 'monkey', 'boy' ] thing = new Thing('jid', properties) thing.owner = 'owner' class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'xmpp_owner'), false result = { devices: [ ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 1, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.claim thing onSuccess = (thing) -> test.equal true, false, 'should not get here' onFail = (err) -> test.equal err.message, 'not-found' test.expect 2 test.done() promise.then onSuccess, onFail 'test claim ownership: device already owned' : (test) -> properties = [ new Property 'string', 'KEY', '123' new Property 'string', 'monkey', 'boy' ] thing = new Thing('jid', properties) thing.owner = 'owner' class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'xmpp_owner'), false data.xmpp_owner = 'taken' result = { devices: [ data ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.claim thing onSuccess = (thing) -> test.equal true, false, 'should not get here' onFail = (err) -> test.equal err.message, 'claimed' test.expect 2 test.done() promise.then onSuccess, onFail 'test claim ownership: multiple results' : (test) -> properties = [ new Property 'string', 'KEY', '123' new Property 'string', 'monkey', 'boy' ] thing = new Thing('jid', properties) thing.owner = 'owner' class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'xmpp_owner'), false result = { devices: [ {}, {} ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.claim thing onSuccess = (thing) -> test.equal true, false, 'should not get here' onFail = (err) -> test.equal err.message, 'illegal state' test.expect 2 test.done() promise.then onSuccess, onFail 'test search: multiple results' : (test) -> thing1 = { KEY: '123' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' } thing2 = { KEY: '456' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters test.expect 6 onSuccess = (result) -> things = result.things test.equal things.length, 2 test.equal things[0].nodeId, undefined test.equal things[0].sourceId, undefined test.equal things[0].cacheType, undefined test.done() onFail = (err) -> test.done() promise.then onSuccess, onFail 'test search: multiple results behing concentrator' : (test) -> thing1 = { KEY: '123' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' xmpp_nodeId: 'node1' xmpp_sourceId: 'source1' xmpp_cacheType: 'cacheType1' } thing2 = { KEY: '456' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' xmpp_nodeId: 'node2' xmpp_sourceId: 'source2' xmpp_cacheType: 'cacheType2' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters onSuccess = (result) -> things = result.things test.equal things.length, 2 test.equal things[0].nodeId, 'node1' test.equal things[0].sourceId, 'source1' test.equal things[0].cacheType, 'cacheType1' test.expect 6 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: filter unowned from results' : (test) -> thing1 = { KEY: '123' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' } thing2 = { KEY: '456' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters onSuccess = (result) -> things = result.things test.equal things.length, 1 test.expect 3 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: filter private things from results' : (test) -> thing1 = { KEY: '123' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' xmpp_public: 'true' } thing2 = { KEY: '456' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' xmpp_public: 'false' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters onSuccess = (result) -> things = result.things test.equal things.length, 1 test.equal things[0].jid, 'jid1' test.expect 4 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: filter removed things from results' : (test) -> thing1 = { KEY: '123' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' xmpp_removed: 'true' } thing2 = { KEY: '456' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters onSuccess = (result) -> things = result.things test.equal things.length, 1 test.equal things[0].jid, 'jid2' test.expect 4 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: testing offset and maxcount' : (test) -> thing1 = { KEY: '123' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' } thing2 = { KEY: '456' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } thing3 = { KEY: '789' monkey: 'island' ROOM: '101' xmpp_jid: 'jid3' xmpp_owner: 'owner3' } thing4 = { KEY: '012' monkey: 'island' ROOM: '101' xmpp_jid: 'jid4' xmpp_owner: 'owner4' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2, thing3, thing4 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters, 1 onSuccess = (result) -> things = result.things more = result.more test.equal things.length, 3 test.equal things[0].jid, 'jid2' test.equal things[1].jid, 'jid3' test.equal things[2].jid, 'jid4' test.equal more, false test.expect 7 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: testing maxcount' : (test) -> thing1 = { KEY: '123' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' } thing2 = { KEY: '456' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } thing3 = { KEY: '789' monkey: 'island' ROOM: '101' xmpp_jid: 'jid3' xmpp_owner: 'owner3' } thing4 = { KEY: '012' monkey: 'island' ROOM: '101' xmpp_jid: 'jid4' xmpp_owner: 'owner4' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2, thing3, thing4 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters, undefined, 2 onSuccess = (result) -> things = result.things more = result.more test.equal things.length, 2 test.equal things[0].jid, 'jid1' test.equal things[1].jid, 'jid2' test.equal more, true test.expect 6 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: testing offset and maxcount' : (test) -> thing1 = { KEY: '123' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' } thing2 = { KEY: '456' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } thing3 = { KEY: '789' monkey: 'island' ROOM: '101' xmpp_jid: 'jid3' xmpp_owner: 'owner3' } thing4 = { KEY: '012' monkey: 'island' ROOM: '101' xmpp_jid: 'jid4' xmpp_owner: 'owner4' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2, thing3, thing4 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters, 1, 2 onSuccess = (result) -> things = result.things more = result.more test.equal things.length, 2 test.equal things[0].jid, 'jid2' test.equal things[1].jid, 'jid3' test.equal more, true test.expect 6 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test update thing: multiple matching things found in the registry': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> result = { devices: [ {}, {} ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.update thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' onFail = (err) -> test.done() promise.then onSuccess, onFail 'test update thing: success case': (test) -> properties = [ new Property 'string', 'KEY', 'value' new Property 'string', 'TEST', '' #empty, should be removed ] thing = new Thing('jid', properties) thing.owner = 'owner' storedDevice = xmpp_owner: 'owner' KEY: '123' TEST: '456' ROOM: '101' class ConnectionStub extends EventEmitter constructor: -> update: (data, cb) -> test.equal data.KEY, 'value' test.equal data.TEST, undefined test.equal data.ROOM, '101' delete data.TEST result = { devices: [ data ] } cb result devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.update thing onSuccess = (thing) -> test.equal thing.properties.length, 2 for property in thing.properties if property.name is 'KEY' test.equal property.value, 'value' if property.name is 'ROOM' test.equal property.value, '101' if property.name is 'TEST' test.done() test.expect 6 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test update thing: not owned': (test) -> properties = [ new Property 'string', 'KEY', 'value' new Property 'string', 'TEST', '' #empty, should be removed ] thing = new Thing('jid', properties) storedDevice = { KEY: '123' TEST: '456' ROOM: '101' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.update thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' onFail = (err) -> test.equal err.message, 'disowned' test.expect 1 test.done() promise.then onSuccess, onFail 'test remove thing: success case': (test) -> thing = new Thing('jid') thing.owner = 'owner' storedDevice = xmpp_jid: 'jid' xmpp_owner: 'owner' TEST: '456' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.notEqual data.uuid, undefined result = { } cb result devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.remove thing onSuccess = (thing) -> test.expect 1 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test remove thing: not found': (test) -> thing = new Thing('jid') thing.owner = 'owner' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.equal true, false, 'should not get here' result = { devices: [ ] } cb result devices: (data, cb) -> result = { devices: [ ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.remove thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, 'not-found' test.expect 1 test.done() promise.then onSuccess, onFail 'test remove thing: not owned': (test) -> thing = new Thing('jid') storedDevice = xmpp_jid: 'jid' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.equal true, false, 'should not get here' result = { devices: [ ] } cb result devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.remove thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, 'not-owned' test.expect 1 test.done() promise.then onSuccess, onFail 'test remove thing: multiple results': (test) -> thing = new Thing('jid') thing.owner = 'not-owner' storedDevice = xmpp_jid: 'jid' xmpp_owner: 'owner' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.equal true, false, 'should not get here' result = { devices: [ ] } cb result devices: (data, cb) -> result = { devices: [ storedDevice, storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.remove thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, '' test.expect 1 test.done() promise.then onSuccess, onFail 'test remove thing: not allowed (not the owner)': (test) -> thing = new Thing('jid') thing.owner = 'not-owner' storedDevice = xmpp_jid: 'jid' xmpp_owner: 'owner' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.equal true, false, 'should not get here' result = { devices: [ ] } cb result devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.remove thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, 'not-allowed' test.expect 1 test.done() promise.then onSuccess, onFail 'test unregister thing: success case': (test) -> thing = new Thing('jid') storedDevice = xmpp_jid: 'jid' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.notEqual data.uuid, undefined result = { } cb result devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.unregister thing onSuccess = () -> test.expect 1 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test unregister thing: not found' : (test) -> thing = new Thing('jid') class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> result = { devices: [ ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.unregister thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, 'not-found' test.expect 1 test.done() promise.then onSuccess, onFail 'test get thing: success' : (test) -> storedDevice = xmpp_jid: 'jid' class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal data.xmpp_jid, 'jid' result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' proto = new Thing 'jid' promise = target.get proto onSuccess = (things) -> test.equal things.length, 1 test.equal things[0].jid, 'jid' test.expect 3 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test get thing: error' : (test) -> class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal data.xmpp_jid, 'jid' result = { error: [ ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' proto = new Thing 'jid' promise = target.get proto onSuccess = (things) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, '' test.expect 2 test.done() promise.then onSuccess, onFail 'test get thing: multiple results found' : (test) -> storedDevice = xmpp_jid: 'jid' class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal data.xmpp_jid, 'jid' result = { devices: [ storedDevice, storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.get new Thing('jid') onSuccess = (things) -> test.equal things.length, 2 test.expect 2 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test get thing: no results found' : (test) -> class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal data.xmpp_jid, 'jid' result = { devices: [ ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.get new Thing('jid') onSuccess = (things) -> test.equal things.length, 0 test.expect 2 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test serialization' : (test) -> thing = new Thing 'jid' thing.needsNotification = true thing.removed = true thing.properties = [] connection = new EventEmitter() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' serialized = target.serialize thing, false test.equal serialized.xmpp_jid, 'jid' test.equal serialized.xmpp_needsNotification, 'true' test.equal serialized.xmpp_removed, 'true' test.equal serialized.xmpp_public, 'true' thing = target.deserialize serialized test.equal thing.needsNotification, true test.equal thing.removed, true test.equal thing.public, true thing.removed = false thing.needsNotification = false thing.public = false serialized = target.serialize thing, false test.equal serialized.xmpp_jid, 'jid' test.equal serialized.xmpp_needsNotification, undefined test.equal serialized.xmpp_removed, undefined test.equal serialized.xmpp_public, 'false' thing = target.deserialize serialized test.equal thing.needsNotification, undefined test.equal thing.removed, undefined test.equal thing.public, false thing.needsNotification = undefined thing.removed = undefined thing.public = undefined serialized = target.serialize thing, false test.equal serialized.xmpp_jid, 'jid' test.equal serialized.xmpp_needsNotification, undefined test.equal serialized.xmpp_removed, undefined test.equal serialized.xmpp_public, 'true' thing = target.deserialize serialized test.equal thing.needsNotification, undefined test.equal thing.removed, undefined test.equal thing.public, true test.expect 21 test.done()
84539
# Tests if the server component complies to # https://xmpp.org/extensions/xep-0347.html # # Some test cases refer to paragraphs and / or examples from the spec. {EventEmitter} = require 'events' OctobluBackend = require '../src/octoblu-backend.coffee' Thing = require '../src/thing.coffee' Property = require '../src/property.coffee' Filter = require '../src/filter.coffee' Q = require 'q' _ = require 'lodash' class OctobluStub constructor: (@connection) -> createConnection: (opts) -> return @connection exports.OctobluBackendTest = 'test register test if preconditions are not met': (test) -> properties = [ new Property('type', 'name', 'value') ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> class OptionTestStub extends OctobluStub createConnection: (opts) -> test.equal opts.server, 'test' test.equal opts.port, 666 test.equal opts.uuid, 'user' test.equal opts.token, '<PASSWORD>' super opts opts = { uuid: 'user' token: '<PASSWORD>' } connection = new ConnectionStub() target = new OctobluBackend 'test', 666, opts, undefined, new OptionTestStub(connection) promise = target.register thing onSuccess = (thing) -> test.equal true, false onFail = (err) -> test.equal err.message, 'Missing property: KEY' test.expect 5 test.done() promise.then onSuccess, onFail 'test register test if reserved words are used': (test) -> properties = [ new Property 'type', 'KEY', 'value' new Property 'type', 'xmpp_nodeId', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> connection = new ConnectionStub() target = new OctobluBackend undefined, undefined, {}, undefined, new OctobluStub(connection) promise = target.register thing onSuccess = (thing) -> test.equal true, false onFail = (err) -> test.equal err.message, 'Illegal property: xmpp_nodeId' test.expect 1 test.done() promise.then onSuccess, onFail 'test register hash value': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) thing.nodeId = 'nodeId' thing.sourceId = 'sourceId' thing.cacheType = 'cacheType' class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> test.equal data.uuid, '582b91b44e49a038a607f09e0d12cc61' test.equal data.token, 'value' result = { xmpp_jid: thing.jid xmpp_nodeId: thing.nodeId xmpp_sourceId: thing.sourceId xmpp_cacheType: thing.cacheType uuid: data.uuid token: data.token } cb result devices: (data, cb) -> test.equal data.uuid, '582b91b44e49a038a607f09e0d12cc61' cb { devices: [] } connection = new ConnectionStub() target = new OctobluBackend undefined, undefined, {}, undefined, new OctobluStub(connection) promise = target.register thing onSuccess = (thing) -> test.equal thing.uuid, '582b91b44e49a038a607f09e0d12cc61' test.equal thing.token, 'value' test.expect 5 test.done() onFail = (err) -> test.expect false, true promise.then onSuccess, onFail 'test no backend account': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> if data.uuid is 'user' test.equal data.token, 'pass' else test.equal data.token, 'value' cb data devices: (data, cb) -> cb { devices: [] } connection = new ConnectionStub() opts = { uuid: 'user' token: '<PASSWORD>' } target = new OctobluBackend 'test', 666, opts, undefined, new OctobluStub(connection) connection.emit 'notReady' promise = target.register thing onSuccess = (thing) -> test.equal thing.token, 'value' test.equal thing.uuid, '3d4478eb8cae476e97eacd52aa1cca16' test.expect 4 test.done() onFail = (err) -> test.expect false, true promise.then onSuccess, onFail 'test registration of the backend account failed': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> test.equal data.uuid, 'user' test.equal data.token, '<PASSWORD>' test.throws () -> cb { } test.done() devices: (data, cb) -> cb [] connection = new ConnectionStub() opts = { uuid: 'user' token: '<PASSWORD>' } target = new OctobluBackend 'test', 666, opts, undefined, new OctobluStub(connection) connection.emit 'notReady' 'test thing already registered': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> cb data devices: (data, cb) -> result = { devices: [ { uuid: data.uuid } ] } cb result unregister: (data, cb) -> test.equal data.uuid, '3d4478eb8cae476e97eacd52aa1cca16' cb data connection = new ConnectionStub() opts = { uuid: 'user' token: '<PASSWORD>' } target = new OctobluBackend 'test', 666, opts, undefined, new OctobluStub(connection) connection.emit 'notReady' promise = target.register thing onSuccess = (thing) -> test.equal thing.token, 'value' test.equal thing.uuid, '3d4478eb8cae476e97eacd52aa1cca16' test.expect 3 test.done() onFail = (err) -> test.expect false, true promise.then onSuccess, onFail 'test thing already registered and owned': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> cb data devices: (data, cb) -> result = { devices: [ { uuid: data.uuid, xmpp_owner: 'owner' } ] } cb result connection = new ConnectionStub() target = new OctobluBackend undefined, undefined, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.register thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' onFail = (err) -> test.equal err.message, 'claimed' test.equal err.owner, 'owner' test.expect 2 test.done() promise.then onSuccess, onFail 'test thing unregister fails': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> cb data devices: (data, cb) -> result = { devices: [ { uuid: data.uuid } ] } cb result unregister: (data, cb) -> cb { name: 'error' } connection = new ConnectionStub() target = new OctobluBackend undefined, undefined, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.register thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' onFail = (err) -> test.equal err.message, 'unregister failed' test.expect 1 test.done() promise.then onSuccess, onFail 'test register thing: multiple matching things found in the registry': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> cb data devices: (data, cb) -> result = { devices: [ {}, {} ] } cb result connection = new ConnectionStub() target = new OctobluBackend undefined, undefined, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.register thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' onFail = (err) -> test.done() promise.then onSuccess, onFail 'test claim ownership: success case' : (test) -> properties = [ new Property 'string', 'KEY', '<KEY>' new Property 'string', 'monkey', 'boy' ] thing = new Thing('jid', properties) thing.owner = 'owner' thing.needsNotification = true class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'xmpp_owner'), false result = { devices: [ data ] } cb result update: (data, cb) -> test.equal data.xmpp_owner, 'owner' cb data connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.claim thing onSuccess = (thing) -> test.equal thing.owner, 'owner' test.expect 3 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test claim ownership: device not found' : (test) -> properties = [ new Property 'string', 'KEY', '<KEY>' new Property 'string', 'monkey', 'boy' ] thing = new Thing('jid', properties) thing.owner = 'owner' class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'xmpp_owner'), false result = { devices: [ ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 1, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.claim thing onSuccess = (thing) -> test.equal true, false, 'should not get here' onFail = (err) -> test.equal err.message, 'not-found' test.expect 2 test.done() promise.then onSuccess, onFail 'test claim ownership: device already owned' : (test) -> properties = [ new Property 'string', 'KEY', '<KEY>' new Property 'string', 'monkey', 'boy' ] thing = new Thing('jid', properties) thing.owner = 'owner' class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'xmpp_owner'), false data.xmpp_owner = 'taken' result = { devices: [ data ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.claim thing onSuccess = (thing) -> test.equal true, false, 'should not get here' onFail = (err) -> test.equal err.message, 'claimed' test.expect 2 test.done() promise.then onSuccess, onFail 'test claim ownership: multiple results' : (test) -> properties = [ new Property 'string', 'KEY', '<KEY>' new Property 'string', 'monkey', 'boy' ] thing = new Thing('jid', properties) thing.owner = 'owner' class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'xmpp_owner'), false result = { devices: [ {}, {} ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.claim thing onSuccess = (thing) -> test.equal true, false, 'should not get here' onFail = (err) -> test.equal err.message, 'illegal state' test.expect 2 test.done() promise.then onSuccess, onFail 'test search: multiple results' : (test) -> thing1 = { KEY: '<KEY>' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' } thing2 = { KEY: '<KEY>' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters test.expect 6 onSuccess = (result) -> things = result.things test.equal things.length, 2 test.equal things[0].nodeId, undefined test.equal things[0].sourceId, undefined test.equal things[0].cacheType, undefined test.done() onFail = (err) -> test.done() promise.then onSuccess, onFail 'test search: multiple results behing concentrator' : (test) -> thing1 = { KEY: '<KEY>' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' xmpp_nodeId: 'node1' xmpp_sourceId: 'source1' xmpp_cacheType: 'cacheType1' } thing2 = { KEY: '<KEY>' monkey: 'is<KEY>' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' xmpp_nodeId: 'node2' xmpp_sourceId: 'source2' xmpp_cacheType: 'cacheType2' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters onSuccess = (result) -> things = result.things test.equal things.length, 2 test.equal things[0].nodeId, 'node1' test.equal things[0].sourceId, 'source1' test.equal things[0].cacheType, 'cacheType1' test.expect 6 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: filter unowned from results' : (test) -> thing1 = { KEY: '<KEY>' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' } thing2 = { KEY: '<KEY>' monkey: 'is<KEY>' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters onSuccess = (result) -> things = result.things test.equal things.length, 1 test.expect 3 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: filter private things from results' : (test) -> thing1 = { KEY: '<KEY>' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' xmpp_public: 'true' } thing2 = { KEY: '<KEY>' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' xmpp_public: 'false' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters onSuccess = (result) -> things = result.things test.equal things.length, 1 test.equal things[0].jid, 'jid1' test.expect 4 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: filter removed things from results' : (test) -> thing1 = { KEY: '<KEY>' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' xmpp_removed: 'true' } thing2 = { KEY: '<KEY>' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters onSuccess = (result) -> things = result.things test.equal things.length, 1 test.equal things[0].jid, 'jid2' test.expect 4 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: testing offset and maxcount' : (test) -> thing1 = { KEY: '<KEY>' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' } thing2 = { KEY: '<KEY>' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } thing3 = { KEY: '<KEY>' monkey: 'island' ROOM: '101' xmpp_jid: 'jid3' xmpp_owner: 'owner<KEY>' } thing4 = { KEY: '<KEY>' monkey: 'island' ROOM: '101' xmpp_jid: 'jid4' xmpp_owner: 'owner4' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2, thing3, thing4 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters, 1 onSuccess = (result) -> things = result.things more = result.more test.equal things.length, 3 test.equal things[0].jid, 'jid2' test.equal things[1].jid, 'jid3' test.equal things[2].jid, 'jid4' test.equal more, false test.expect 7 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: testing maxcount' : (test) -> thing1 = { KEY: '<KEY>' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' } thing2 = { KEY: '<KEY>' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } thing3 = { KEY: '<KEY>' monkey: 'island' ROOM: '101' xmpp_jid: 'jid3' xmpp_owner: 'owner3' } thing4 = { KEY: '<KEY>' monkey: 'island' ROOM: '101' xmpp_jid: 'jid4' xmpp_owner: 'owner4' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2, thing3, thing4 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters, undefined, 2 onSuccess = (result) -> things = result.things more = result.more test.equal things.length, 2 test.equal things[0].jid, 'jid1' test.equal things[1].jid, 'jid2' test.equal more, true test.expect 6 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: testing offset and maxcount' : (test) -> thing1 = { KEY: '<KEY>' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' } thing2 = { KEY: '<KEY>' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } thing3 = { KEY: '<KEY>' monkey: 'island' ROOM: '101' xmpp_jid: 'jid3' xmpp_owner: 'owner3' } thing4 = { KEY: '<KEY>' monkey: 'island' ROOM: '101' xmpp_jid: 'jid4' xmpp_owner: 'owner4' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2, thing3, thing4 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters, 1, 2 onSuccess = (result) -> things = result.things more = result.more test.equal things.length, 2 test.equal things[0].jid, 'jid2' test.equal things[1].jid, 'jid3' test.equal more, true test.expect 6 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test update thing: multiple matching things found in the registry': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> result = { devices: [ {}, {} ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.update thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' onFail = (err) -> test.done() promise.then onSuccess, onFail 'test update thing: success case': (test) -> properties = [ new Property 'string', 'KEY', 'value' new Property 'string', 'TEST', '' #empty, should be removed ] thing = new Thing('jid', properties) thing.owner = 'owner' storedDevice = xmpp_owner: 'owner' KEY: '<KEY>' TEST: '456' ROOM: '101' class ConnectionStub extends EventEmitter constructor: -> update: (data, cb) -> test.equal data.KEY, 'value' test.equal data.TEST, undefined test.equal data.ROOM, '101' delete data.TEST result = { devices: [ data ] } cb result devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.update thing onSuccess = (thing) -> test.equal thing.properties.length, 2 for property in thing.properties if property.name is 'KEY' test.equal property.value, 'value' if property.name is 'ROOM' test.equal property.value, '101' if property.name is 'TEST' test.done() test.expect 6 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test update thing: not owned': (test) -> properties = [ new Property 'string', 'KEY', 'value' new Property 'string', 'TEST', '' #empty, should be removed ] thing = new Thing('jid', properties) storedDevice = { KEY: '<KEY>' TEST: '456' ROOM: '101' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.update thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' onFail = (err) -> test.equal err.message, 'disowned' test.expect 1 test.done() promise.then onSuccess, onFail 'test remove thing: success case': (test) -> thing = new Thing('jid') thing.owner = 'owner' storedDevice = xmpp_jid: 'jid' xmpp_owner: 'owner' TEST: '456' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.notEqual data.uuid, undefined result = { } cb result devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.remove thing onSuccess = (thing) -> test.expect 1 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test remove thing: not found': (test) -> thing = new Thing('jid') thing.owner = 'owner' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.equal true, false, 'should not get here' result = { devices: [ ] } cb result devices: (data, cb) -> result = { devices: [ ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.remove thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, 'not-found' test.expect 1 test.done() promise.then onSuccess, onFail 'test remove thing: not owned': (test) -> thing = new Thing('jid') storedDevice = xmpp_jid: 'jid' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.equal true, false, 'should not get here' result = { devices: [ ] } cb result devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.remove thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, 'not-owned' test.expect 1 test.done() promise.then onSuccess, onFail 'test remove thing: multiple results': (test) -> thing = new Thing('jid') thing.owner = 'not-owner' storedDevice = xmpp_jid: 'jid' xmpp_owner: 'owner' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.equal true, false, 'should not get here' result = { devices: [ ] } cb result devices: (data, cb) -> result = { devices: [ storedDevice, storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.remove thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, '' test.expect 1 test.done() promise.then onSuccess, onFail 'test remove thing: not allowed (not the owner)': (test) -> thing = new Thing('jid') thing.owner = 'not-owner' storedDevice = xmpp_jid: 'jid' xmpp_owner: 'owner' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.equal true, false, 'should not get here' result = { devices: [ ] } cb result devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.remove thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, 'not-allowed' test.expect 1 test.done() promise.then onSuccess, onFail 'test unregister thing: success case': (test) -> thing = new Thing('jid') storedDevice = xmpp_jid: 'jid' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.notEqual data.uuid, undefined result = { } cb result devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.unregister thing onSuccess = () -> test.expect 1 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test unregister thing: not found' : (test) -> thing = new Thing('jid') class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> result = { devices: [ ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.unregister thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, 'not-found' test.expect 1 test.done() promise.then onSuccess, onFail 'test get thing: success' : (test) -> storedDevice = xmpp_jid: 'jid' class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal data.xmpp_jid, 'jid' result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' proto = new Thing 'jid' promise = target.get proto onSuccess = (things) -> test.equal things.length, 1 test.equal things[0].jid, 'jid' test.expect 3 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test get thing: error' : (test) -> class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal data.xmpp_jid, 'jid' result = { error: [ ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' proto = new Thing 'jid' promise = target.get proto onSuccess = (things) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, '' test.expect 2 test.done() promise.then onSuccess, onFail 'test get thing: multiple results found' : (test) -> storedDevice = xmpp_jid: 'jid' class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal data.xmpp_jid, 'jid' result = { devices: [ storedDevice, storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.get new Thing('jid') onSuccess = (things) -> test.equal things.length, 2 test.expect 2 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test get thing: no results found' : (test) -> class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal data.xmpp_jid, 'jid' result = { devices: [ ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.get new Thing('jid') onSuccess = (things) -> test.equal things.length, 0 test.expect 2 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test serialization' : (test) -> thing = new Thing 'jid' thing.needsNotification = true thing.removed = true thing.properties = [] connection = new EventEmitter() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' serialized = target.serialize thing, false test.equal serialized.xmpp_jid, 'jid' test.equal serialized.xmpp_needsNotification, 'true' test.equal serialized.xmpp_removed, 'true' test.equal serialized.xmpp_public, 'true' thing = target.deserialize serialized test.equal thing.needsNotification, true test.equal thing.removed, true test.equal thing.public, true thing.removed = false thing.needsNotification = false thing.public = false serialized = target.serialize thing, false test.equal serialized.xmpp_jid, 'jid' test.equal serialized.xmpp_needsNotification, undefined test.equal serialized.xmpp_removed, undefined test.equal serialized.xmpp_public, 'false' thing = target.deserialize serialized test.equal thing.needsNotification, undefined test.equal thing.removed, undefined test.equal thing.public, false thing.needsNotification = undefined thing.removed = undefined thing.public = undefined serialized = target.serialize thing, false test.equal serialized.xmpp_jid, 'jid' test.equal serialized.xmpp_needsNotification, undefined test.equal serialized.xmpp_removed, undefined test.equal serialized.xmpp_public, 'true' thing = target.deserialize serialized test.equal thing.needsNotification, undefined test.equal thing.removed, undefined test.equal thing.public, true test.expect 21 test.done()
true
# Tests if the server component complies to # https://xmpp.org/extensions/xep-0347.html # # Some test cases refer to paragraphs and / or examples from the spec. {EventEmitter} = require 'events' OctobluBackend = require '../src/octoblu-backend.coffee' Thing = require '../src/thing.coffee' Property = require '../src/property.coffee' Filter = require '../src/filter.coffee' Q = require 'q' _ = require 'lodash' class OctobluStub constructor: (@connection) -> createConnection: (opts) -> return @connection exports.OctobluBackendTest = 'test register test if preconditions are not met': (test) -> properties = [ new Property('type', 'name', 'value') ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> class OptionTestStub extends OctobluStub createConnection: (opts) -> test.equal opts.server, 'test' test.equal opts.port, 666 test.equal opts.uuid, 'user' test.equal opts.token, 'PI:PASSWORD:<PASSWORD>END_PI' super opts opts = { uuid: 'user' token: 'PI:PASSWORD:<PASSWORD>END_PI' } connection = new ConnectionStub() target = new OctobluBackend 'test', 666, opts, undefined, new OptionTestStub(connection) promise = target.register thing onSuccess = (thing) -> test.equal true, false onFail = (err) -> test.equal err.message, 'Missing property: KEY' test.expect 5 test.done() promise.then onSuccess, onFail 'test register test if reserved words are used': (test) -> properties = [ new Property 'type', 'KEY', 'value' new Property 'type', 'xmpp_nodeId', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> connection = new ConnectionStub() target = new OctobluBackend undefined, undefined, {}, undefined, new OctobluStub(connection) promise = target.register thing onSuccess = (thing) -> test.equal true, false onFail = (err) -> test.equal err.message, 'Illegal property: xmpp_nodeId' test.expect 1 test.done() promise.then onSuccess, onFail 'test register hash value': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) thing.nodeId = 'nodeId' thing.sourceId = 'sourceId' thing.cacheType = 'cacheType' class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> test.equal data.uuid, '582b91b44e49a038a607f09e0d12cc61' test.equal data.token, 'value' result = { xmpp_jid: thing.jid xmpp_nodeId: thing.nodeId xmpp_sourceId: thing.sourceId xmpp_cacheType: thing.cacheType uuid: data.uuid token: data.token } cb result devices: (data, cb) -> test.equal data.uuid, '582b91b44e49a038a607f09e0d12cc61' cb { devices: [] } connection = new ConnectionStub() target = new OctobluBackend undefined, undefined, {}, undefined, new OctobluStub(connection) promise = target.register thing onSuccess = (thing) -> test.equal thing.uuid, '582b91b44e49a038a607f09e0d12cc61' test.equal thing.token, 'value' test.expect 5 test.done() onFail = (err) -> test.expect false, true promise.then onSuccess, onFail 'test no backend account': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> if data.uuid is 'user' test.equal data.token, 'pass' else test.equal data.token, 'value' cb data devices: (data, cb) -> cb { devices: [] } connection = new ConnectionStub() opts = { uuid: 'user' token: 'PI:PASSWORD:<PASSWORD>END_PI' } target = new OctobluBackend 'test', 666, opts, undefined, new OctobluStub(connection) connection.emit 'notReady' promise = target.register thing onSuccess = (thing) -> test.equal thing.token, 'value' test.equal thing.uuid, '3d4478eb8cae476e97eacd52aa1cca16' test.expect 4 test.done() onFail = (err) -> test.expect false, true promise.then onSuccess, onFail 'test registration of the backend account failed': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> test.equal data.uuid, 'user' test.equal data.token, 'PI:PASSWORD:<PASSWORD>END_PI' test.throws () -> cb { } test.done() devices: (data, cb) -> cb [] connection = new ConnectionStub() opts = { uuid: 'user' token: 'PI:PASSWORD:<PASSWORD>END_PI' } target = new OctobluBackend 'test', 666, opts, undefined, new OctobluStub(connection) connection.emit 'notReady' 'test thing already registered': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> cb data devices: (data, cb) -> result = { devices: [ { uuid: data.uuid } ] } cb result unregister: (data, cb) -> test.equal data.uuid, '3d4478eb8cae476e97eacd52aa1cca16' cb data connection = new ConnectionStub() opts = { uuid: 'user' token: 'PI:PASSWORD:<PASSWORD>END_PI' } target = new OctobluBackend 'test', 666, opts, undefined, new OctobluStub(connection) connection.emit 'notReady' promise = target.register thing onSuccess = (thing) -> test.equal thing.token, 'value' test.equal thing.uuid, '3d4478eb8cae476e97eacd52aa1cca16' test.expect 3 test.done() onFail = (err) -> test.expect false, true promise.then onSuccess, onFail 'test thing already registered and owned': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> cb data devices: (data, cb) -> result = { devices: [ { uuid: data.uuid, xmpp_owner: 'owner' } ] } cb result connection = new ConnectionStub() target = new OctobluBackend undefined, undefined, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.register thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' onFail = (err) -> test.equal err.message, 'claimed' test.equal err.owner, 'owner' test.expect 2 test.done() promise.then onSuccess, onFail 'test thing unregister fails': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> cb data devices: (data, cb) -> result = { devices: [ { uuid: data.uuid } ] } cb result unregister: (data, cb) -> cb { name: 'error' } connection = new ConnectionStub() target = new OctobluBackend undefined, undefined, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.register thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' onFail = (err) -> test.equal err.message, 'unregister failed' test.expect 1 test.done() promise.then onSuccess, onFail 'test register thing: multiple matching things found in the registry': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> register: (data, cb) -> cb data devices: (data, cb) -> result = { devices: [ {}, {} ] } cb result connection = new ConnectionStub() target = new OctobluBackend undefined, undefined, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.register thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' onFail = (err) -> test.done() promise.then onSuccess, onFail 'test claim ownership: success case' : (test) -> properties = [ new Property 'string', 'KEY', 'PI:KEY:<KEY>END_PI' new Property 'string', 'monkey', 'boy' ] thing = new Thing('jid', properties) thing.owner = 'owner' thing.needsNotification = true class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'xmpp_owner'), false result = { devices: [ data ] } cb result update: (data, cb) -> test.equal data.xmpp_owner, 'owner' cb data connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.claim thing onSuccess = (thing) -> test.equal thing.owner, 'owner' test.expect 3 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test claim ownership: device not found' : (test) -> properties = [ new Property 'string', 'KEY', 'PI:KEY:<KEY>END_PI' new Property 'string', 'monkey', 'boy' ] thing = new Thing('jid', properties) thing.owner = 'owner' class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'xmpp_owner'), false result = { devices: [ ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 1, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.claim thing onSuccess = (thing) -> test.equal true, false, 'should not get here' onFail = (err) -> test.equal err.message, 'not-found' test.expect 2 test.done() promise.then onSuccess, onFail 'test claim ownership: device already owned' : (test) -> properties = [ new Property 'string', 'KEY', 'PI:KEY:<KEY>END_PI' new Property 'string', 'monkey', 'boy' ] thing = new Thing('jid', properties) thing.owner = 'owner' class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'xmpp_owner'), false data.xmpp_owner = 'taken' result = { devices: [ data ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.claim thing onSuccess = (thing) -> test.equal true, false, 'should not get here' onFail = (err) -> test.equal err.message, 'claimed' test.expect 2 test.done() promise.then onSuccess, onFail 'test claim ownership: multiple results' : (test) -> properties = [ new Property 'string', 'KEY', 'PI:KEY:<KEY>END_PI' new Property 'string', 'monkey', 'boy' ] thing = new Thing('jid', properties) thing.owner = 'owner' class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'xmpp_owner'), false result = { devices: [ {}, {} ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.claim thing onSuccess = (thing) -> test.equal true, false, 'should not get here' onFail = (err) -> test.equal err.message, 'illegal state' test.expect 2 test.done() promise.then onSuccess, onFail 'test search: multiple results' : (test) -> thing1 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' } thing2 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters test.expect 6 onSuccess = (result) -> things = result.things test.equal things.length, 2 test.equal things[0].nodeId, undefined test.equal things[0].sourceId, undefined test.equal things[0].cacheType, undefined test.done() onFail = (err) -> test.done() promise.then onSuccess, onFail 'test search: multiple results behing concentrator' : (test) -> thing1 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' xmpp_nodeId: 'node1' xmpp_sourceId: 'source1' xmpp_cacheType: 'cacheType1' } thing2 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'isPI:KEY:<KEY>END_PI' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' xmpp_nodeId: 'node2' xmpp_sourceId: 'source2' xmpp_cacheType: 'cacheType2' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters onSuccess = (result) -> things = result.things test.equal things.length, 2 test.equal things[0].nodeId, 'node1' test.equal things[0].sourceId, 'source1' test.equal things[0].cacheType, 'cacheType1' test.expect 6 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: filter unowned from results' : (test) -> thing1 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' } thing2 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'isPI:KEY:<KEY>END_PI' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters onSuccess = (result) -> things = result.things test.equal things.length, 1 test.expect 3 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: filter private things from results' : (test) -> thing1 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' xmpp_public: 'true' } thing2 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' xmpp_public: 'false' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters onSuccess = (result) -> things = result.things test.equal things.length, 1 test.equal things[0].jid, 'jid1' test.expect 4 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: filter removed things from results' : (test) -> thing1 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' xmpp_removed: 'true' } thing2 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters onSuccess = (result) -> things = result.things test.equal things.length, 1 test.equal things[0].jid, 'jid2' test.expect 4 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: testing offset and maxcount' : (test) -> thing1 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' } thing2 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } thing3 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'island' ROOM: '101' xmpp_jid: 'jid3' xmpp_owner: 'ownerPI:KEY:<KEY>END_PI' } thing4 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'island' ROOM: '101' xmpp_jid: 'jid4' xmpp_owner: 'owner4' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2, thing3, thing4 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters, 1 onSuccess = (result) -> things = result.things more = result.more test.equal things.length, 3 test.equal things[0].jid, 'jid2' test.equal things[1].jid, 'jid3' test.equal things[2].jid, 'jid4' test.equal more, false test.expect 7 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: testing maxcount' : (test) -> thing1 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' } thing2 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } thing3 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'island' ROOM: '101' xmpp_jid: 'jid3' xmpp_owner: 'owner3' } thing4 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'island' ROOM: '101' xmpp_jid: 'jid4' xmpp_owner: 'owner4' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2, thing3, thing4 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters, undefined, 2 onSuccess = (result) -> things = result.things more = result.more test.equal things.length, 2 test.equal things[0].jid, 'jid1' test.equal things[1].jid, 'jid2' test.equal more, true test.expect 6 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test search: testing offset and maxcount' : (test) -> thing1 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'boy' ROOM: '101' xmpp_jid: 'jid1' xmpp_owner: 'owner1' } thing2 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'island' ROOM: '101' xmpp_jid: 'jid2' xmpp_owner: 'owner2' } thing3 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'island' ROOM: '101' xmpp_jid: 'jid3' xmpp_owner: 'owner3' } thing4 = { KEY: 'PI:KEY:<KEY>END_PI' monkey: 'island' ROOM: '101' xmpp_jid: 'jid4' xmpp_owner: 'owner4' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal _.has(data, 'ROOM'), true test.equal data.ROOM, '101' result = { devices: [ thing1, thing2, thing3, thing4 ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' searchFilters = [ new Filter 'strEq', 'ROOM', '101' ] promise = target.search searchFilters, 1, 2 onSuccess = (result) -> things = result.things more = result.more test.equal things.length, 2 test.equal things[0].jid, 'jid2' test.equal things[1].jid, 'jid3' test.equal more, true test.expect 6 test.done() onFail = (err) -> test.equal true, false, 'should not get here' promise.then onSuccess, onFail 'test update thing: multiple matching things found in the registry': (test) -> properties = [ new Property 'string', 'KEY', 'value' ] thing = new Thing('jid', properties) class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> result = { devices: [ {}, {} ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.update thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' onFail = (err) -> test.done() promise.then onSuccess, onFail 'test update thing: success case': (test) -> properties = [ new Property 'string', 'KEY', 'value' new Property 'string', 'TEST', '' #empty, should be removed ] thing = new Thing('jid', properties) thing.owner = 'owner' storedDevice = xmpp_owner: 'owner' KEY: 'PI:KEY:<KEY>END_PI' TEST: '456' ROOM: '101' class ConnectionStub extends EventEmitter constructor: -> update: (data, cb) -> test.equal data.KEY, 'value' test.equal data.TEST, undefined test.equal data.ROOM, '101' delete data.TEST result = { devices: [ data ] } cb result devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.update thing onSuccess = (thing) -> test.equal thing.properties.length, 2 for property in thing.properties if property.name is 'KEY' test.equal property.value, 'value' if property.name is 'ROOM' test.equal property.value, '101' if property.name is 'TEST' test.done() test.expect 6 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test update thing: not owned': (test) -> properties = [ new Property 'string', 'KEY', 'value' new Property 'string', 'TEST', '' #empty, should be removed ] thing = new Thing('jid', properties) storedDevice = { KEY: 'PI:KEY:<KEY>END_PI' TEST: '456' ROOM: '101' } class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.update thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' onFail = (err) -> test.equal err.message, 'disowned' test.expect 1 test.done() promise.then onSuccess, onFail 'test remove thing: success case': (test) -> thing = new Thing('jid') thing.owner = 'owner' storedDevice = xmpp_jid: 'jid' xmpp_owner: 'owner' TEST: '456' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.notEqual data.uuid, undefined result = { } cb result devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.remove thing onSuccess = (thing) -> test.expect 1 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test remove thing: not found': (test) -> thing = new Thing('jid') thing.owner = 'owner' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.equal true, false, 'should not get here' result = { devices: [ ] } cb result devices: (data, cb) -> result = { devices: [ ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.remove thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, 'not-found' test.expect 1 test.done() promise.then onSuccess, onFail 'test remove thing: not owned': (test) -> thing = new Thing('jid') storedDevice = xmpp_jid: 'jid' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.equal true, false, 'should not get here' result = { devices: [ ] } cb result devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.remove thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, 'not-owned' test.expect 1 test.done() promise.then onSuccess, onFail 'test remove thing: multiple results': (test) -> thing = new Thing('jid') thing.owner = 'not-owner' storedDevice = xmpp_jid: 'jid' xmpp_owner: 'owner' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.equal true, false, 'should not get here' result = { devices: [ ] } cb result devices: (data, cb) -> result = { devices: [ storedDevice, storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.remove thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, '' test.expect 1 test.done() promise.then onSuccess, onFail 'test remove thing: not allowed (not the owner)': (test) -> thing = new Thing('jid') thing.owner = 'not-owner' storedDevice = xmpp_jid: 'jid' xmpp_owner: 'owner' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.equal true, false, 'should not get here' result = { devices: [ ] } cb result devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.remove thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, 'not-allowed' test.expect 1 test.done() promise.then onSuccess, onFail 'test unregister thing: success case': (test) -> thing = new Thing('jid') storedDevice = xmpp_jid: 'jid' class ConnectionStub extends EventEmitter constructor: -> unregister: (data, cb) -> test.notEqual data.uuid, undefined result = { } cb result devices: (data, cb) -> result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.unregister thing onSuccess = () -> test.expect 1 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test unregister thing: not found' : (test) -> thing = new Thing('jid') class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> result = { devices: [ ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.unregister thing onSuccess = (thing) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, 'not-found' test.expect 1 test.done() promise.then onSuccess, onFail 'test get thing: success' : (test) -> storedDevice = xmpp_jid: 'jid' class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal data.xmpp_jid, 'jid' result = { devices: [ storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' proto = new Thing 'jid' promise = target.get proto onSuccess = (things) -> test.equal things.length, 1 test.equal things[0].jid, 'jid' test.expect 3 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test get thing: error' : (test) -> class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal data.xmpp_jid, 'jid' result = { error: [ ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' proto = new Thing 'jid' promise = target.get proto onSuccess = (things) -> test.equal true, false, 'should not hit this line' test.done() onFail = (err) -> test.equal err.message, '' test.expect 2 test.done() promise.then onSuccess, onFail 'test get thing: multiple results found' : (test) -> storedDevice = xmpp_jid: 'jid' class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal data.xmpp_jid, 'jid' result = { devices: [ storedDevice, storedDevice ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.get new Thing('jid') onSuccess = (things) -> test.equal things.length, 2 test.expect 2 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test get thing: no results found' : (test) -> class ConnectionStub extends EventEmitter constructor: -> devices: (data, cb) -> test.equal data.xmpp_jid, 'jid' result = { devices: [ ] } cb result connection = new ConnectionStub() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' promise = target.get new Thing('jid') onSuccess = (things) -> test.equal things.length, 0 test.expect 2 test.done() onFail = (err) -> test.equal true, false, 'should not hit this line' test.done() promise.then onSuccess, onFail 'test serialization' : (test) -> thing = new Thing 'jid' thing.needsNotification = true thing.removed = true thing.properties = [] connection = new EventEmitter() target = new OctobluBackend '', 0, {}, undefined, new OctobluStub(connection) connection.emit 'ready' serialized = target.serialize thing, false test.equal serialized.xmpp_jid, 'jid' test.equal serialized.xmpp_needsNotification, 'true' test.equal serialized.xmpp_removed, 'true' test.equal serialized.xmpp_public, 'true' thing = target.deserialize serialized test.equal thing.needsNotification, true test.equal thing.removed, true test.equal thing.public, true thing.removed = false thing.needsNotification = false thing.public = false serialized = target.serialize thing, false test.equal serialized.xmpp_jid, 'jid' test.equal serialized.xmpp_needsNotification, undefined test.equal serialized.xmpp_removed, undefined test.equal serialized.xmpp_public, 'false' thing = target.deserialize serialized test.equal thing.needsNotification, undefined test.equal thing.removed, undefined test.equal thing.public, false thing.needsNotification = undefined thing.removed = undefined thing.public = undefined serialized = target.serialize thing, false test.equal serialized.xmpp_jid, 'jid' test.equal serialized.xmpp_needsNotification, undefined test.equal serialized.xmpp_removed, undefined test.equal serialized.xmpp_public, 'true' thing = target.deserialize serialized test.equal thing.needsNotification, undefined test.equal thing.removed, undefined test.equal thing.public, true test.expect 21 test.done()
[ { "context": "eydown\", charCode: 0, keyCode: 0, which: 0, key: \"👏🏻\")\n triggerEvent(element, \"keypress\", charCod", "end": 2447, "score": 0.7103402018547058, "start": 2445, "tag": "KEY", "value": "👏🏻" }, { "context": "de: 128079, keyCode: 128079, which: 128079, key: \"👏🏻\")\n\n node = document.createTextNode(\"👏🏻\")\n ", "end": 2548, "score": 0.6521567106246948, "start": 2546, "tag": "KEY", "value": "👏🏻" } ]
test/src/system/mutation_input_test.coffee
setastart/trix
0
{assert, defer, testIf, testGroup, triggerEvent, typeCharacters, clickToolbarButton, isToolbarButtonActive, insertNode} = Trix.TestHelpers test = -> testIf(Trix.config.input.getLevel() is 0, arguments...) testGroup "Mutation input", template: "editor_empty", -> test "deleting a newline", (expectDocument) -> element = getEditorElement() element.editor.insertString("a\n\nb") triggerEvent(element, "keydown", charCode: 0, keyCode: 229, which: 229) br = element.querySelectorAll("br")[1] br.parentNode.removeChild(br) requestAnimationFrame -> expectDocument("a\nb\n") test "typing a space in formatted text at the end of a block", (expectDocument) -> element = getEditorElement() clickToolbarButton attribute: "bold", -> typeCharacters "a", -> # Press space key triggerEvent(element, "keydown", charCode: 0, keyCode: 32, which: 32) triggerEvent(element, "keypress", charCode: 32, keyCode: 32, which: 32) boldElement = element.querySelector("strong") boldElement.appendChild(document.createTextNode(" ")) boldElement.appendChild(document.createElement("br")) requestAnimationFrame -> assert.ok isToolbarButtonActive(attribute: "bold") assert.textAttributes([0, 2], bold: true) expectDocument("a \n") test "typing formatted text after a newline at the end of block", (expectDocument) -> element = getEditorElement() element.editor.insertHTML("<ul><li>a</li><li><br></li></ul>") element.editor.setSelectedRange(3) clickToolbarButton attribute: "bold", -> # Press B key triggerEvent(element, "keydown", charCode: 0, keyCode: 66, which: 66) triggerEvent(element, "keypress", charCode: 98, keyCode: 98, which: 98) node = document.createTextNode("b") extraBR = element.querySelectorAll("br")[1] extraBR.parentNode.insertBefore(node, extraBR) extraBR.parentNode.removeChild(extraBR) requestAnimationFrame -> assert.ok isToolbarButtonActive(attribute: "bold") assert.textAttributes([0, 1], {}) assert.textAttributes([3, 4], bold: true) expectDocument("a\n\nb\n") test "typing an emoji after a newline at the end of block", (expectDocument) -> element = getEditorElement() typeCharacters "\n", -> # Tap 👏🏻 on iOS triggerEvent(element, "keydown", charCode: 0, keyCode: 0, which: 0, key: "👏🏻") triggerEvent(element, "keypress", charCode: 128079, keyCode: 128079, which: 128079, key: "👏🏻") node = document.createTextNode("👏🏻") extraBR = element.querySelectorAll("br")[1] extraBR.parentNode.insertBefore(node, extraBR) extraBR.parentNode.removeChild(extraBR) requestAnimationFrame -> expectDocument("\n👏🏻\n") test "backspacing a block comment node", (expectDocument) -> element = getEditorElement() element.editor.loadHTML("""<blockquote>a</blockquote><div>b</div>""") defer -> element.editor.setSelectedRange(2) triggerEvent(element, "keydown", charCode: 0, keyCode: 8, which: 8) commentNode = element.lastChild.firstChild commentNode.parentNode.removeChild(commentNode) defer -> assert.locationRange index: 0, offset: 1 expectDocument("ab\n") test "typing formatted text with autocapitalization on", (expectDocument) -> element = getEditorElement() clickToolbarButton attribute: "bold", -> # Type "b", autocapitalize to "B" triggerEvent(element, "keydown", charCode: 0, keyCode: 66, which: 66) triggerEvent(element, "keypress", charCode: 98, keyCode: 98, which: 98) triggerEvent(element, "textInput", data: "B") insertNode document.createTextNode("B"), -> assert.ok isToolbarButtonActive(attribute: "bold") assert.textAttributes([0, 1], bold: true) expectDocument("B\n")
158231
{assert, defer, testIf, testGroup, triggerEvent, typeCharacters, clickToolbarButton, isToolbarButtonActive, insertNode} = Trix.TestHelpers test = -> testIf(Trix.config.input.getLevel() is 0, arguments...) testGroup "Mutation input", template: "editor_empty", -> test "deleting a newline", (expectDocument) -> element = getEditorElement() element.editor.insertString("a\n\nb") triggerEvent(element, "keydown", charCode: 0, keyCode: 229, which: 229) br = element.querySelectorAll("br")[1] br.parentNode.removeChild(br) requestAnimationFrame -> expectDocument("a\nb\n") test "typing a space in formatted text at the end of a block", (expectDocument) -> element = getEditorElement() clickToolbarButton attribute: "bold", -> typeCharacters "a", -> # Press space key triggerEvent(element, "keydown", charCode: 0, keyCode: 32, which: 32) triggerEvent(element, "keypress", charCode: 32, keyCode: 32, which: 32) boldElement = element.querySelector("strong") boldElement.appendChild(document.createTextNode(" ")) boldElement.appendChild(document.createElement("br")) requestAnimationFrame -> assert.ok isToolbarButtonActive(attribute: "bold") assert.textAttributes([0, 2], bold: true) expectDocument("a \n") test "typing formatted text after a newline at the end of block", (expectDocument) -> element = getEditorElement() element.editor.insertHTML("<ul><li>a</li><li><br></li></ul>") element.editor.setSelectedRange(3) clickToolbarButton attribute: "bold", -> # Press B key triggerEvent(element, "keydown", charCode: 0, keyCode: 66, which: 66) triggerEvent(element, "keypress", charCode: 98, keyCode: 98, which: 98) node = document.createTextNode("b") extraBR = element.querySelectorAll("br")[1] extraBR.parentNode.insertBefore(node, extraBR) extraBR.parentNode.removeChild(extraBR) requestAnimationFrame -> assert.ok isToolbarButtonActive(attribute: "bold") assert.textAttributes([0, 1], {}) assert.textAttributes([3, 4], bold: true) expectDocument("a\n\nb\n") test "typing an emoji after a newline at the end of block", (expectDocument) -> element = getEditorElement() typeCharacters "\n", -> # Tap 👏🏻 on iOS triggerEvent(element, "keydown", charCode: 0, keyCode: 0, which: 0, key: "<KEY>") triggerEvent(element, "keypress", charCode: 128079, keyCode: 128079, which: 128079, key: "<KEY>") node = document.createTextNode("👏🏻") extraBR = element.querySelectorAll("br")[1] extraBR.parentNode.insertBefore(node, extraBR) extraBR.parentNode.removeChild(extraBR) requestAnimationFrame -> expectDocument("\n👏🏻\n") test "backspacing a block comment node", (expectDocument) -> element = getEditorElement() element.editor.loadHTML("""<blockquote>a</blockquote><div>b</div>""") defer -> element.editor.setSelectedRange(2) triggerEvent(element, "keydown", charCode: 0, keyCode: 8, which: 8) commentNode = element.lastChild.firstChild commentNode.parentNode.removeChild(commentNode) defer -> assert.locationRange index: 0, offset: 1 expectDocument("ab\n") test "typing formatted text with autocapitalization on", (expectDocument) -> element = getEditorElement() clickToolbarButton attribute: "bold", -> # Type "b", autocapitalize to "B" triggerEvent(element, "keydown", charCode: 0, keyCode: 66, which: 66) triggerEvent(element, "keypress", charCode: 98, keyCode: 98, which: 98) triggerEvent(element, "textInput", data: "B") insertNode document.createTextNode("B"), -> assert.ok isToolbarButtonActive(attribute: "bold") assert.textAttributes([0, 1], bold: true) expectDocument("B\n")
true
{assert, defer, testIf, testGroup, triggerEvent, typeCharacters, clickToolbarButton, isToolbarButtonActive, insertNode} = Trix.TestHelpers test = -> testIf(Trix.config.input.getLevel() is 0, arguments...) testGroup "Mutation input", template: "editor_empty", -> test "deleting a newline", (expectDocument) -> element = getEditorElement() element.editor.insertString("a\n\nb") triggerEvent(element, "keydown", charCode: 0, keyCode: 229, which: 229) br = element.querySelectorAll("br")[1] br.parentNode.removeChild(br) requestAnimationFrame -> expectDocument("a\nb\n") test "typing a space in formatted text at the end of a block", (expectDocument) -> element = getEditorElement() clickToolbarButton attribute: "bold", -> typeCharacters "a", -> # Press space key triggerEvent(element, "keydown", charCode: 0, keyCode: 32, which: 32) triggerEvent(element, "keypress", charCode: 32, keyCode: 32, which: 32) boldElement = element.querySelector("strong") boldElement.appendChild(document.createTextNode(" ")) boldElement.appendChild(document.createElement("br")) requestAnimationFrame -> assert.ok isToolbarButtonActive(attribute: "bold") assert.textAttributes([0, 2], bold: true) expectDocument("a \n") test "typing formatted text after a newline at the end of block", (expectDocument) -> element = getEditorElement() element.editor.insertHTML("<ul><li>a</li><li><br></li></ul>") element.editor.setSelectedRange(3) clickToolbarButton attribute: "bold", -> # Press B key triggerEvent(element, "keydown", charCode: 0, keyCode: 66, which: 66) triggerEvent(element, "keypress", charCode: 98, keyCode: 98, which: 98) node = document.createTextNode("b") extraBR = element.querySelectorAll("br")[1] extraBR.parentNode.insertBefore(node, extraBR) extraBR.parentNode.removeChild(extraBR) requestAnimationFrame -> assert.ok isToolbarButtonActive(attribute: "bold") assert.textAttributes([0, 1], {}) assert.textAttributes([3, 4], bold: true) expectDocument("a\n\nb\n") test "typing an emoji after a newline at the end of block", (expectDocument) -> element = getEditorElement() typeCharacters "\n", -> # Tap 👏🏻 on iOS triggerEvent(element, "keydown", charCode: 0, keyCode: 0, which: 0, key: "PI:KEY:<KEY>END_PI") triggerEvent(element, "keypress", charCode: 128079, keyCode: 128079, which: 128079, key: "PI:KEY:<KEY>END_PI") node = document.createTextNode("👏🏻") extraBR = element.querySelectorAll("br")[1] extraBR.parentNode.insertBefore(node, extraBR) extraBR.parentNode.removeChild(extraBR) requestAnimationFrame -> expectDocument("\n👏🏻\n") test "backspacing a block comment node", (expectDocument) -> element = getEditorElement() element.editor.loadHTML("""<blockquote>a</blockquote><div>b</div>""") defer -> element.editor.setSelectedRange(2) triggerEvent(element, "keydown", charCode: 0, keyCode: 8, which: 8) commentNode = element.lastChild.firstChild commentNode.parentNode.removeChild(commentNode) defer -> assert.locationRange index: 0, offset: 1 expectDocument("ab\n") test "typing formatted text with autocapitalization on", (expectDocument) -> element = getEditorElement() clickToolbarButton attribute: "bold", -> # Type "b", autocapitalize to "B" triggerEvent(element, "keydown", charCode: 0, keyCode: 66, which: 66) triggerEvent(element, "keypress", charCode: 98, keyCode: 98, which: 98) triggerEvent(element, "textInput", data: "B") insertNode document.createTextNode("B"), -> assert.ok isToolbarButtonActive(attribute: "bold") assert.textAttributes([0, 1], bold: true) expectDocument("B\n")
[ { "context": "Questions? Burning rage? Direct your hatemail to <ddrinkard@sunlightfoundation.com>\n###\n\n@$ = window.jQuery\n@gigya = window.gigya\n@e", "end": 943, "score": 0.999923825263977, "start": 911, "tag": "EMAIL", "value": "ddrinkard@sunlightfoundation.com" } ]
src/gigya.coffee
sunlightlabs/simple-gigya
1
### Gigya social sharing buttons ============================ Adds social media buttons to an element decorated with data-attrs. Requires jQuery, but will poll for it if loaded first Supports multiple sharing contexts on one page Usage: <div class="share-buttons" data-gigya="auto" data-services="twitter, twitter-tweet, facebook, reddit" data-options="linkBack=http%3A%2F%2Fsunlightfoundation.com&amp;title=The%20Sunlight%20Foundation" data-twitter-tweet-options="defaultText=Check%20out%20Sunlight's%20new%20social%20media%20buttons!&amp;countURL=http%3A%2F%2Fwww.sunlightfoundation.com> </div> ... <script src="http://path/to/scripts/gigya.min.js"></script> You can also manually trigger (or re-trigger) button rendering by: - Setting data-gigya to something other than 'auto' - Sending an event with data-gigya's value to the element Questions? Burning rage? Direct your hatemail to <ddrinkard@sunlightfoundation.com> ### @$ = window.jQuery @gigya = window.gigya @els = [] @check_count = 0 @gigya_queued = false @service_button_img = "{% settings.ICON_BASE_URL %}/{size}/{service}.png" check = (stuff, callback) => if window.jQuery? and not window.gigya? and not @gigya_queued window.jQuery.getScript "//cdn.gigya.com/js/socialize.js?apiKey={% settings.GIGYA_KEY %}", (script, status, jqxhr) -> window.jQuery.getScript "//cdn.gigya.com/js/gigyaGAIntegration.js" @gigya_queued = true checks = stuff.length passed_checks = 0 if check_count > 100000 window.console and console.log "A requirements test failed after numerous tries, aborting." return for thing in stuff if window[thing]? passed_checks++ if passed_checks == checks @$ = window.jQuery @gigya = window.gigya callback() else check_count++ window.setTimeout (()-> check(stuff, callback)), 100 null buttonFactory = (widget, options) => options ?= {} button = @$.extend widget, options button parseOptions = (querystring) -> if not querystring? querystring = "" options = querystring.split /[=&](?:amp;)?/ hsh = {} for opt, i in options if i % 2 hsh[options[i-1]] = window.decodeURIComponent options[i] hsh init = () => @$ => @els = @$(".share-buttons[data-gigya]") @els.each (i, el) => el.id or (el.id = "share_buttons_#{i + 1}") el = @$(el) if el.attr("data-gigya") == "auto" handle(el) else el.bind(el.attr("data-gigya"), () => handle(el)) @els @els handle = (el) => try ua = new @gigya.socialize.UserAction() services = el.attr("data-services").split(",") buttons = [] params = containerID: el.attr("id") iconsOnly: true layout: "horizontal" noButtonBorder: true shareButtons: buttons shortURLs: "never" showCounts: "none" userAction: ua options = parseOptions el.attr("data-options") if options.title? ua.setTitle options.title else if (ogtitle = @$("meta[property=og\\:title]")) ua.setTitle ogtitle.attr("content") else ua.setTitle @$("title").text() if options.linkBack? ua.setLinkBack options.linkBack if options.description? ua.setDescription options.description if options.image? ua.addMediaItem type: image href: options.linkBack || window.location.href src: options.image if options.size != "24" options.size = "16" for service_name in services service_name = service_name.replace(" ", "") opts_attr_name = "data-#{service_name}-options" service_options = @$.extend({}, parseOptions(el.attr(opts_attr_name))) widget = provider: service_name iconImgUp: @service_button_img.replace( "{service}", service_name).replace( "{size}", options.size) buttons.push buttonFactory(widget, service_options) @gigya.socialize.showShareBarUI @$.extend( params, options ) catch err window.console && console.log("Caught #{err}") check(['jQuery', 'gigya'], init)
206096
### Gigya social sharing buttons ============================ Adds social media buttons to an element decorated with data-attrs. Requires jQuery, but will poll for it if loaded first Supports multiple sharing contexts on one page Usage: <div class="share-buttons" data-gigya="auto" data-services="twitter, twitter-tweet, facebook, reddit" data-options="linkBack=http%3A%2F%2Fsunlightfoundation.com&amp;title=The%20Sunlight%20Foundation" data-twitter-tweet-options="defaultText=Check%20out%20Sunlight's%20new%20social%20media%20buttons!&amp;countURL=http%3A%2F%2Fwww.sunlightfoundation.com> </div> ... <script src="http://path/to/scripts/gigya.min.js"></script> You can also manually trigger (or re-trigger) button rendering by: - Setting data-gigya to something other than 'auto' - Sending an event with data-gigya's value to the element Questions? Burning rage? Direct your hatemail to <<EMAIL>> ### @$ = window.jQuery @gigya = window.gigya @els = [] @check_count = 0 @gigya_queued = false @service_button_img = "{% settings.ICON_BASE_URL %}/{size}/{service}.png" check = (stuff, callback) => if window.jQuery? and not window.gigya? and not @gigya_queued window.jQuery.getScript "//cdn.gigya.com/js/socialize.js?apiKey={% settings.GIGYA_KEY %}", (script, status, jqxhr) -> window.jQuery.getScript "//cdn.gigya.com/js/gigyaGAIntegration.js" @gigya_queued = true checks = stuff.length passed_checks = 0 if check_count > 100000 window.console and console.log "A requirements test failed after numerous tries, aborting." return for thing in stuff if window[thing]? passed_checks++ if passed_checks == checks @$ = window.jQuery @gigya = window.gigya callback() else check_count++ window.setTimeout (()-> check(stuff, callback)), 100 null buttonFactory = (widget, options) => options ?= {} button = @$.extend widget, options button parseOptions = (querystring) -> if not querystring? querystring = "" options = querystring.split /[=&](?:amp;)?/ hsh = {} for opt, i in options if i % 2 hsh[options[i-1]] = window.decodeURIComponent options[i] hsh init = () => @$ => @els = @$(".share-buttons[data-gigya]") @els.each (i, el) => el.id or (el.id = "share_buttons_#{i + 1}") el = @$(el) if el.attr("data-gigya") == "auto" handle(el) else el.bind(el.attr("data-gigya"), () => handle(el)) @els @els handle = (el) => try ua = new @gigya.socialize.UserAction() services = el.attr("data-services").split(",") buttons = [] params = containerID: el.attr("id") iconsOnly: true layout: "horizontal" noButtonBorder: true shareButtons: buttons shortURLs: "never" showCounts: "none" userAction: ua options = parseOptions el.attr("data-options") if options.title? ua.setTitle options.title else if (ogtitle = @$("meta[property=og\\:title]")) ua.setTitle ogtitle.attr("content") else ua.setTitle @$("title").text() if options.linkBack? ua.setLinkBack options.linkBack if options.description? ua.setDescription options.description if options.image? ua.addMediaItem type: image href: options.linkBack || window.location.href src: options.image if options.size != "24" options.size = "16" for service_name in services service_name = service_name.replace(" ", "") opts_attr_name = "data-#{service_name}-options" service_options = @$.extend({}, parseOptions(el.attr(opts_attr_name))) widget = provider: service_name iconImgUp: @service_button_img.replace( "{service}", service_name).replace( "{size}", options.size) buttons.push buttonFactory(widget, service_options) @gigya.socialize.showShareBarUI @$.extend( params, options ) catch err window.console && console.log("Caught #{err}") check(['jQuery', 'gigya'], init)
true
### Gigya social sharing buttons ============================ Adds social media buttons to an element decorated with data-attrs. Requires jQuery, but will poll for it if loaded first Supports multiple sharing contexts on one page Usage: <div class="share-buttons" data-gigya="auto" data-services="twitter, twitter-tweet, facebook, reddit" data-options="linkBack=http%3A%2F%2Fsunlightfoundation.com&amp;title=The%20Sunlight%20Foundation" data-twitter-tweet-options="defaultText=Check%20out%20Sunlight's%20new%20social%20media%20buttons!&amp;countURL=http%3A%2F%2Fwww.sunlightfoundation.com> </div> ... <script src="http://path/to/scripts/gigya.min.js"></script> You can also manually trigger (or re-trigger) button rendering by: - Setting data-gigya to something other than 'auto' - Sending an event with data-gigya's value to the element Questions? Burning rage? Direct your hatemail to <PI:EMAIL:<EMAIL>END_PI> ### @$ = window.jQuery @gigya = window.gigya @els = [] @check_count = 0 @gigya_queued = false @service_button_img = "{% settings.ICON_BASE_URL %}/{size}/{service}.png" check = (stuff, callback) => if window.jQuery? and not window.gigya? and not @gigya_queued window.jQuery.getScript "//cdn.gigya.com/js/socialize.js?apiKey={% settings.GIGYA_KEY %}", (script, status, jqxhr) -> window.jQuery.getScript "//cdn.gigya.com/js/gigyaGAIntegration.js" @gigya_queued = true checks = stuff.length passed_checks = 0 if check_count > 100000 window.console and console.log "A requirements test failed after numerous tries, aborting." return for thing in stuff if window[thing]? passed_checks++ if passed_checks == checks @$ = window.jQuery @gigya = window.gigya callback() else check_count++ window.setTimeout (()-> check(stuff, callback)), 100 null buttonFactory = (widget, options) => options ?= {} button = @$.extend widget, options button parseOptions = (querystring) -> if not querystring? querystring = "" options = querystring.split /[=&](?:amp;)?/ hsh = {} for opt, i in options if i % 2 hsh[options[i-1]] = window.decodeURIComponent options[i] hsh init = () => @$ => @els = @$(".share-buttons[data-gigya]") @els.each (i, el) => el.id or (el.id = "share_buttons_#{i + 1}") el = @$(el) if el.attr("data-gigya") == "auto" handle(el) else el.bind(el.attr("data-gigya"), () => handle(el)) @els @els handle = (el) => try ua = new @gigya.socialize.UserAction() services = el.attr("data-services").split(",") buttons = [] params = containerID: el.attr("id") iconsOnly: true layout: "horizontal" noButtonBorder: true shareButtons: buttons shortURLs: "never" showCounts: "none" userAction: ua options = parseOptions el.attr("data-options") if options.title? ua.setTitle options.title else if (ogtitle = @$("meta[property=og\\:title]")) ua.setTitle ogtitle.attr("content") else ua.setTitle @$("title").text() if options.linkBack? ua.setLinkBack options.linkBack if options.description? ua.setDescription options.description if options.image? ua.addMediaItem type: image href: options.linkBack || window.location.href src: options.image if options.size != "24" options.size = "16" for service_name in services service_name = service_name.replace(" ", "") opts_attr_name = "data-#{service_name}-options" service_options = @$.extend({}, parseOptions(el.attr(opts_attr_name))) widget = provider: service_name iconImgUp: @service_button_img.replace( "{service}", service_name).replace( "{size}", options.size) buttons.push buttonFactory(widget, service_options) @gigya.socialize.showShareBarUI @$.extend( params, options ) catch err window.console && console.log("Caught #{err}") check(['jQuery', 'gigya'], init)
[ { "context": "original_id:\"656258342147502080\",\n \tcontent:\"RT @GingerLanier: Putin and the Shiite 'Axis of Resistance' http:/", "end": 125, "score": 0.9965165853500366, "start": 112, "tag": "USERNAME", "value": "@GingerLanier" }, { "context": "0.jpg\",\n \tfrom_id:\"308130306\",\n \tfrom_name:\"Novorossiyan\",\n \turl:\"http://twitter.com/statuses/656258342", "end": 394, "score": 0.9998981356620789, "start": 382, "tag": "NAME", "value": "Novorossiyan" } ]
test/object_test.coffee
rubenv/node-xlsx-writer
15
test = require('./common') test 'object-test', [ { original_id:"656258342147502080", content:"RT @GingerLanier: Putin and the Shiite 'Axis of Resistance' http://t.co/eumnAIIrTV", date_created:"2015-10-19 23:59:16", from_display_picture:"http://pbs.twimg.com/profile_images/651504414998396928/hdoQSqiv_400x400.jpg", from_id:"308130306", from_name:"Novorossiyan", url:"http://twitter.com/statuses/656258342147502080", sentiment:5, score:0, social_media:"Twitter", score_breakdown:[], extra:[] } ]
154252
test = require('./common') test 'object-test', [ { original_id:"656258342147502080", content:"RT @GingerLanier: Putin and the Shiite 'Axis of Resistance' http://t.co/eumnAIIrTV", date_created:"2015-10-19 23:59:16", from_display_picture:"http://pbs.twimg.com/profile_images/651504414998396928/hdoQSqiv_400x400.jpg", from_id:"308130306", from_name:"<NAME>", url:"http://twitter.com/statuses/656258342147502080", sentiment:5, score:0, social_media:"Twitter", score_breakdown:[], extra:[] } ]
true
test = require('./common') test 'object-test', [ { original_id:"656258342147502080", content:"RT @GingerLanier: Putin and the Shiite 'Axis of Resistance' http://t.co/eumnAIIrTV", date_created:"2015-10-19 23:59:16", from_display_picture:"http://pbs.twimg.com/profile_images/651504414998396928/hdoQSqiv_400x400.jpg", from_id:"308130306", from_name:"PI:NAME:<NAME>END_PI", url:"http://twitter.com/statuses/656258342147502080", sentiment:5, score:0, social_media:"Twitter", score_breakdown:[], extra:[] } ]
[ { "context": "-- gets tags to silence\n#\n# Notes:\n#\n# Author:\n# lukas.pustina@centerdevice.de\n#\n# Todos:\n# - Readme\n\nLog = require 'log'\nmoment", "end": 1297, "score": 0.9998080134391785, "start": 1268, "tag": "EMAIL", "value": "lukas.pustina@centerdevice.de" } ]
src/centerdevice.coffee
CenterDevice/hubot-centerdevice
0
# Description # DevOps for CenterDevice via Hubot # # Configuration: # HUBOT_CENTERDEVICE_ROLE -- Auth role required, e.g., "centerdevice" # HUBOT_DEPLOYMENT_SILENCE_DURATION -- Duration of deployment silence, default is 15m # HUBOT_CENTERDEVICE_LOG_LEVEL -- Log level, default is "info" # HUBOT_CENTERDEVICE_BOSUN_TIMEOUT -- Timeout to wait for Bosun to react, default is 30000 ms # HUBOT_CENTERDEVICE_SILENCE_CHECK_INTERVAL -- Interval to check, if Bosun silence is still active # # Commands: # start(ing) centerdevice deployment -- automatically sets Bosun silence for `HUBOT_DEPLOYMENT_SILENCE_DURATION` # start(ing) centerdevice deployment because <message> -- automatically sets Bosun silence for `HUBOT_DEPLOYMENT_SILENCE_DURATION` with <message> # finish(ed) centerdevice deployment -- automatically clears previously created Bosun silence # set centerdevice deployment alert to (.*) -- sets alert to silence; default is `HUBOT_CENTERDEVICE_DEPLOYMENT_BOSUN_ALERT` # get centerdevice deployment alert -- gets alert to silence # set centerdevice deployment tags to (.*) -- sets tags to silence; default is `HUBOT_CENTERDEVICE_DEPLOYMENT_BOSUN_TAGS` # get centerdevice deployment tags -- gets tags to silence # # Notes: # # Author: # lukas.pustina@centerdevice.de # # Todos: # - Readme Log = require 'log' moment = require 'moment' module_name = "hubot-centerdevice" BRAIN_CD_ALERT_KEY = "centerdevice.config.alert" BRAIN_CD_TAGS_KEY = "centerdevice.config.tags" config = deployment_bosun_alert: process.env.HUBOT_CENTERDEVICE_DEPLOYMENT_BOSUN_ALERT or "" deployment_bosun_tags: process.env.HUBOT_CENTERDEVICE_DEPLOYMENT_BOSUN_TAGS or "" deployment_silence_duration: process.env.HUBOT_CENTERDEVICE_DEPLOYMENT_SILENCE_DURATION or "15m" log_level: process.env.HUBOT_CENTERDEVICE_LOG_LEVEL or "info" role: process.env.HUBOT_CENTERDEVICE_ROLE silence_check_interval: if process.env.HUBOT_CENTERDEVICE_SILENCE_CHECK_INTERVAL then parseInt process.env.HUBOT_CENTERDEVICE_SILENCE_CHECK_INTERVAL else 60000 silence_clear_delay: if process.env.HUBOT_CENTERDEVICE_SILENCE_CLEAR_DELAY then parseInt process.env.HUBOT_CENTERDEVICE_SILENCE_CLEAR_DELAY else 300000 timeout: if process.env.HUBOT_CENTERDEVICE_BOSUN_TIMEOUT then parseInt process.env.HUBOT_CENTERDEVICE_BOSUN_TIMEOUT else 30000 logger = new Log config.log_level logger.notice "#{module_name}: Started." Timers = {} module.exports = (robot) -> robot.respond /set centerdevice deployment alert to (.*)/i, (res) -> if is_authorized robot, res user_name = res.envelope.user.name alert = res.match[1] logger.info "#{module_name}: setting deployment alert to '#{alert}' requested by #{user_name}." if robot.brain.set BRAIN_CD_ALERT_KEY, alert res.reply "Yay. I just set the deployment alert to silence to '#{alert}'. Happy deploying!" else res.reply "Mah, my brain hurts. I could not change the deployment alert ... Sorry!?" robot.respond /get centerdevice deployment alert/i, (res) -> if is_authorized robot, res user_name = res.envelope.user.name logger.info "#{module_name}: getting deployment alert requested by #{user_name}." alert = if a = robot.brain.get BRAIN_CD_ALERT_KEY then a else config.deployment_bosun_alert res.reply "Ja, the current deployment alert to silence is '#{alert}'. Hope, that helps." robot.respond /set centerdevice deployment tags to (.*)/i, (res) -> if is_authorized robot, res user_name = res.envelope.user.name tags = res.match[1] logger.info "#{module_name}: setting deployment tags to '#{tags}' requested by #{user_name}." if robot.brain.set BRAIN_CD_TAGS_KEY, tags res.reply "Yay. I just set the deployment tags to silence to '#{tags}'. Happy deploying!" else res.reply "Mah, my brain hurts. I could not change the deployment tags ... Sorry!?" robot.respond /get centerdevice deployment tags/i, (res) -> if is_authorized robot, res user_name = res.envelope.user.name logger.info "#{module_name}: getting deployment tags by #{user_name}." tags = if t = robot.brain.get BRAIN_CD_TAGS_KEY then t else config.deployment_bosun_tags res.reply "Ja, the current deployment tags to silence are '#{tags}'. Hope, that helps." robot.respond /start.* centerdevice deployment$/i, (res) -> start_deployment res, "deployment" robot.respond /start.* centerdevice deployment because (.*)/i, (res) -> message = res.match[1] start_deployment res, message start_deployment = (res, message) -> if is_authorized robot, res user_name = res.envelope.user.name logger.info "#{module_name}: starting deployment requested by #{user_name}." event_name = "bosun.set_silence" if silence_id = robot.brain.get "centerdevice.#{event_name}.silence_id" res.reply "Ouuch, there's already a deployment silence with id #{silence_id} pending. Finish that deployment and ask Bosun for active silences." else res.reply random_bullshit_msg() res.reply "Ok, let me silence Bosun because #{message} ..." prepare_timeout event_name, robot.brain logger.debug "#{module_name}: emitting request for Bosun silence." robot.emit event_name, user: res.envelope.user room: res.envelope.room duration: config.deployment_silence_duration alert: robot.brain.get(BRAIN_CD_ALERT_KEY) or config.deployment_bosun_alert tags: robot.brain.get(BRAIN_CD_TAGS_KEY) or config.deployment_bosun_tags message: message set_timeout event_name, robot.brain, res robot.respond /finish.* centerdevice deployment/i, (res) -> if is_authorized robot, res user_name = res.envelope.user.name logger.info "#{module_name}: finished deployment requested by #{user_name}." event_name = "bosun.clear_silence" active_silence_id = robot.brain.get "centerdevice.bosun.set_silence.silence_id" unless active_silence_id? res.reply "Hm, there's no active Bosun silence. You're sure there's a deployment going on?" else res.reply "Ok, I'll clear the Bosun silence for your deployment in #{config.silence_clear_delay / 60000} min so Bosun can calm down ..." clear_silence robot.brain setTimeout () -> res.reply "Trying to clear Bosun silence for your deployment." prepare_timeout event_name, robot.brain logger.debug "#{module_name}: Emitting request for Bosun to clear silence." robot.emit event_name, user: res.envelope.user room: res.envelope.room silence_id: active_silence_id set_timeout event_name, robot.brain, res , config.silence_clear_delay robot.on 'bosun.result.set_silence.successful', (event) -> logger.debug "#{module_name}: Received event bosun.result.set_silence.successful." event_name = "bosun.set_silence" if robot.brain.get "centerdevice.#{event_name}.pending" logger.debug "#{module_name}: Set Bosun silence successful for #{event.duration} with id #{event.silence_id}." clear_timeout event_name, robot.brain robot.brain.set "centerdevice.#{event_name}.silence_id", event.silence_id robot.reply {room: event.room, user: event.user}, "Set Bosun silence successfully for #{event.duration} with id #{event.silence_id}." set_silence_checker {room: event.room, user: event.user, silence_id: event.silence_id}, robot robot.on 'bosun.result.set_silence.failed', (event) -> logger.debug "#{module_name}: Received event bosun.result.set_silence.failed." event_name = "bosun.set_silence" if robot.brain.get "centerdevice.#{event_name}.pending" logger.debug "#{module_name}: Oouch: Failed to set Bosun silence because #{event.message}" clear_timeout event_name, robot.brain robot.reply {room: event.room, user: event.user}, "Oouch: Failed to set Bosun silence because #{event.message}" robot.on 'bosun.result.clear_silence.successful', (event) -> logger.debug "#{module_name}: Received event bosun.result.clear_silence.successful." event_name = "bosun.clear_silence" if robot.brain.get "centerdevice.#{event_name}.pending" logger.debug "#{module_name}: Cleared Bosun silence successfully with id #{event.silence_id}." clear_timeout event_name, robot.brain clear_silence robot.brain robot.reply {room: event.room, user: event.user}, "Cleared Bosun silence successfully with id #{event.silence_id}." robot.on 'bosun.result.clear_silence.failed', (event) -> logger.debug "#{module_name}: Received event bosun.result.clear_silence.failed." event_name = "bosun.clear_silence" if robot.brain.get "centerdevice.#{event_name}.pending" logger.debug "#{module_name}: Oouch: Failed to clear Bosun with id #{event.silence_id} silence because #{event.message}" clear_timeout event_name, robot.brain robot.brain.remove "centerdevice.bosun.set_silence.silence_id" robot.reply {room: event.room, user: event.user}, "Oouch: Failed to clear Bosun silence with id #{event.silence_id}, because #{event.message} Please talk directly to Bosun to clear the silence." robot.on 'bosun.result.check_silence.successful', (event) -> logger.debug "#{module_name}: Received event bosun.result.check_silence.successful." if event.active logger.debug "#{module_name}: currently set silence is still active." set_silence_checker event, robot else logger.debug "#{module_name}: currently set silence became inactive." clear_silence robot.brain robot.reply {room: event.room, user: event.user}, "Hey, your Bosun silence with id #{event.silence_id} expired, but it seems you're still deploying?! Are you okay?" robot.on 'bosun.result.check_silence.failed', (event) -> logger.debug "#{module_name}: Received event bosun.result.check_silence.failed." retries = robot.brain.get("centerdevice.set_silence.checker.failed_retries") or 0 if retries < 3 logger.info "#{module_name}: Reactivating silence checker." retries = robot.brain.set "centerdevice.set_silence.checker.failed_retries", (retries + 1) set_silence_checker event, robot else logger.info "#{module_name}: Giving up on silence checker." clear_silence robot.brain robot.error (err, res) -> robot.logger.error "#{module_name}: DOES NOT COMPUTE" if res? res.reply "DOES NOT COMPUTE: #{err}" prepare_timeout = (name, brain) -> logger.debug "#{module_name}: Preparing timeout for #{name}." brain.set "centerdevice.#{name}.pending", true set_timeout = (name, brain, res) -> logger.debug "#{module_name}: Setting timeout for #{name}." if brain.get "centerdevice.#{name}.pending" logger.debug "#{module_name}: Setting timeout for Bosun silence for #{config.timeout} ms." Timers["#{name}_timeout"] = setTimeout () -> logger.debug "#{module_name}: Ouuch, request for #{name} timed out ... sorry." brain.remove "centerdevice.#{name}.pending" delete Timers["#{name}_timeout"] res.reply "Ouuch, request for #{name} timed out ... sorry." , config.timeout clear_timeout = (name, brain) -> logger.debug "#{module_name}: Clearing timeout for #{name}." brain.remove "centerdevice.#{name}.pending" clearTimeout Timers["#{name}_timeout"] delete Timers["#{name}_timeout"] brain.remove "centerdevice.#{name}.timeout" set_silence_checker = (context, robot) -> logger.debug "#{module_name}: Setting silence checker for #{context}." active_silence_id = robot.brain.get "centerdevice.bosun.set_silence.silence_id" if active_silence_id is context.silence_id logger.debug "#{module_name}: setting timeout for Bosun silence checker #{config.silence_check_interval} ms." Timers["set_silence_checker_timeout"] = setTimeout () -> logger.debug "#{module_name}: Emitting request to Bosun to check if silence with id #{context.silence_id} is still active." robot.emit 'bosun.check_silence', context , config.silence_check_interval clear_silence_checker = (brain) -> logger.debug "#{module_name}: Clearing silence checker." clearTimeout Timers["set_silence_checker_timeout"] delete Timers["set_silence_checker_timeout"] clear_silence = (brain) -> logger.debug "#{module_name}: Clearing silence." clear_silence_checker() brain.remove "centerdevice.bosun.set_silence.silence_id" brain.remove "centerdevice.set_silence.checker.failed_retries" random_bullshit_msg = () -> msgs = [ "Pleaaase nooooo, not again!" "Be gentle, it still hurts from last time ..." "How many tries will you need this time?" "Again? You can't get enough!" "Hit me baby one more time." "Oh yeah, I'm ready for you." "This time I want to cuddle first." "At this time? Don't you have friends?" "But waaaaahy?" "As if it would help ..." "Feelin' lucky, punk?" "Fine ..." "Say 'pretty please'!" "Probably" ] msgs[Math.floor(Math.random() * msgs.length)] is_authorized = (robot, res) -> user = res.envelope.user unless robot.auth.hasRole(user, config.role) warn_unauthorized res false else true warn_unauthorized = (res) -> user = res.envelope.user.name message = res.message.text logger.warning "#{module_name}: #{user} tried to run '#{message}' but was not authorized." res.reply "Sorry, you're not allowed to do that. You need the '#{config.role}' role." format_date_str = (date_str) -> if config.relative_time moment(date_str).fromNow() else date_str.replace(/T/, ' ').replace(/\..+/, ' UTC')
6107
# Description # DevOps for CenterDevice via Hubot # # Configuration: # HUBOT_CENTERDEVICE_ROLE -- Auth role required, e.g., "centerdevice" # HUBOT_DEPLOYMENT_SILENCE_DURATION -- Duration of deployment silence, default is 15m # HUBOT_CENTERDEVICE_LOG_LEVEL -- Log level, default is "info" # HUBOT_CENTERDEVICE_BOSUN_TIMEOUT -- Timeout to wait for Bosun to react, default is 30000 ms # HUBOT_CENTERDEVICE_SILENCE_CHECK_INTERVAL -- Interval to check, if Bosun silence is still active # # Commands: # start(ing) centerdevice deployment -- automatically sets Bosun silence for `HUBOT_DEPLOYMENT_SILENCE_DURATION` # start(ing) centerdevice deployment because <message> -- automatically sets Bosun silence for `HUBOT_DEPLOYMENT_SILENCE_DURATION` with <message> # finish(ed) centerdevice deployment -- automatically clears previously created Bosun silence # set centerdevice deployment alert to (.*) -- sets alert to silence; default is `HUBOT_CENTERDEVICE_DEPLOYMENT_BOSUN_ALERT` # get centerdevice deployment alert -- gets alert to silence # set centerdevice deployment tags to (.*) -- sets tags to silence; default is `HUBOT_CENTERDEVICE_DEPLOYMENT_BOSUN_TAGS` # get centerdevice deployment tags -- gets tags to silence # # Notes: # # Author: # <EMAIL> # # Todos: # - Readme Log = require 'log' moment = require 'moment' module_name = "hubot-centerdevice" BRAIN_CD_ALERT_KEY = "centerdevice.config.alert" BRAIN_CD_TAGS_KEY = "centerdevice.config.tags" config = deployment_bosun_alert: process.env.HUBOT_CENTERDEVICE_DEPLOYMENT_BOSUN_ALERT or "" deployment_bosun_tags: process.env.HUBOT_CENTERDEVICE_DEPLOYMENT_BOSUN_TAGS or "" deployment_silence_duration: process.env.HUBOT_CENTERDEVICE_DEPLOYMENT_SILENCE_DURATION or "15m" log_level: process.env.HUBOT_CENTERDEVICE_LOG_LEVEL or "info" role: process.env.HUBOT_CENTERDEVICE_ROLE silence_check_interval: if process.env.HUBOT_CENTERDEVICE_SILENCE_CHECK_INTERVAL then parseInt process.env.HUBOT_CENTERDEVICE_SILENCE_CHECK_INTERVAL else 60000 silence_clear_delay: if process.env.HUBOT_CENTERDEVICE_SILENCE_CLEAR_DELAY then parseInt process.env.HUBOT_CENTERDEVICE_SILENCE_CLEAR_DELAY else 300000 timeout: if process.env.HUBOT_CENTERDEVICE_BOSUN_TIMEOUT then parseInt process.env.HUBOT_CENTERDEVICE_BOSUN_TIMEOUT else 30000 logger = new Log config.log_level logger.notice "#{module_name}: Started." Timers = {} module.exports = (robot) -> robot.respond /set centerdevice deployment alert to (.*)/i, (res) -> if is_authorized robot, res user_name = res.envelope.user.name alert = res.match[1] logger.info "#{module_name}: setting deployment alert to '#{alert}' requested by #{user_name}." if robot.brain.set BRAIN_CD_ALERT_KEY, alert res.reply "Yay. I just set the deployment alert to silence to '#{alert}'. Happy deploying!" else res.reply "Mah, my brain hurts. I could not change the deployment alert ... Sorry!?" robot.respond /get centerdevice deployment alert/i, (res) -> if is_authorized robot, res user_name = res.envelope.user.name logger.info "#{module_name}: getting deployment alert requested by #{user_name}." alert = if a = robot.brain.get BRAIN_CD_ALERT_KEY then a else config.deployment_bosun_alert res.reply "Ja, the current deployment alert to silence is '#{alert}'. Hope, that helps." robot.respond /set centerdevice deployment tags to (.*)/i, (res) -> if is_authorized robot, res user_name = res.envelope.user.name tags = res.match[1] logger.info "#{module_name}: setting deployment tags to '#{tags}' requested by #{user_name}." if robot.brain.set BRAIN_CD_TAGS_KEY, tags res.reply "Yay. I just set the deployment tags to silence to '#{tags}'. Happy deploying!" else res.reply "Mah, my brain hurts. I could not change the deployment tags ... Sorry!?" robot.respond /get centerdevice deployment tags/i, (res) -> if is_authorized robot, res user_name = res.envelope.user.name logger.info "#{module_name}: getting deployment tags by #{user_name}." tags = if t = robot.brain.get BRAIN_CD_TAGS_KEY then t else config.deployment_bosun_tags res.reply "Ja, the current deployment tags to silence are '#{tags}'. Hope, that helps." robot.respond /start.* centerdevice deployment$/i, (res) -> start_deployment res, "deployment" robot.respond /start.* centerdevice deployment because (.*)/i, (res) -> message = res.match[1] start_deployment res, message start_deployment = (res, message) -> if is_authorized robot, res user_name = res.envelope.user.name logger.info "#{module_name}: starting deployment requested by #{user_name}." event_name = "bosun.set_silence" if silence_id = robot.brain.get "centerdevice.#{event_name}.silence_id" res.reply "Ouuch, there's already a deployment silence with id #{silence_id} pending. Finish that deployment and ask Bosun for active silences." else res.reply random_bullshit_msg() res.reply "Ok, let me silence Bosun because #{message} ..." prepare_timeout event_name, robot.brain logger.debug "#{module_name}: emitting request for Bosun silence." robot.emit event_name, user: res.envelope.user room: res.envelope.room duration: config.deployment_silence_duration alert: robot.brain.get(BRAIN_CD_ALERT_KEY) or config.deployment_bosun_alert tags: robot.brain.get(BRAIN_CD_TAGS_KEY) or config.deployment_bosun_tags message: message set_timeout event_name, robot.brain, res robot.respond /finish.* centerdevice deployment/i, (res) -> if is_authorized robot, res user_name = res.envelope.user.name logger.info "#{module_name}: finished deployment requested by #{user_name}." event_name = "bosun.clear_silence" active_silence_id = robot.brain.get "centerdevice.bosun.set_silence.silence_id" unless active_silence_id? res.reply "Hm, there's no active Bosun silence. You're sure there's a deployment going on?" else res.reply "Ok, I'll clear the Bosun silence for your deployment in #{config.silence_clear_delay / 60000} min so Bosun can calm down ..." clear_silence robot.brain setTimeout () -> res.reply "Trying to clear Bosun silence for your deployment." prepare_timeout event_name, robot.brain logger.debug "#{module_name}: Emitting request for Bosun to clear silence." robot.emit event_name, user: res.envelope.user room: res.envelope.room silence_id: active_silence_id set_timeout event_name, robot.brain, res , config.silence_clear_delay robot.on 'bosun.result.set_silence.successful', (event) -> logger.debug "#{module_name}: Received event bosun.result.set_silence.successful." event_name = "bosun.set_silence" if robot.brain.get "centerdevice.#{event_name}.pending" logger.debug "#{module_name}: Set Bosun silence successful for #{event.duration} with id #{event.silence_id}." clear_timeout event_name, robot.brain robot.brain.set "centerdevice.#{event_name}.silence_id", event.silence_id robot.reply {room: event.room, user: event.user}, "Set Bosun silence successfully for #{event.duration} with id #{event.silence_id}." set_silence_checker {room: event.room, user: event.user, silence_id: event.silence_id}, robot robot.on 'bosun.result.set_silence.failed', (event) -> logger.debug "#{module_name}: Received event bosun.result.set_silence.failed." event_name = "bosun.set_silence" if robot.brain.get "centerdevice.#{event_name}.pending" logger.debug "#{module_name}: Oouch: Failed to set Bosun silence because #{event.message}" clear_timeout event_name, robot.brain robot.reply {room: event.room, user: event.user}, "Oouch: Failed to set Bosun silence because #{event.message}" robot.on 'bosun.result.clear_silence.successful', (event) -> logger.debug "#{module_name}: Received event bosun.result.clear_silence.successful." event_name = "bosun.clear_silence" if robot.brain.get "centerdevice.#{event_name}.pending" logger.debug "#{module_name}: Cleared Bosun silence successfully with id #{event.silence_id}." clear_timeout event_name, robot.brain clear_silence robot.brain robot.reply {room: event.room, user: event.user}, "Cleared Bosun silence successfully with id #{event.silence_id}." robot.on 'bosun.result.clear_silence.failed', (event) -> logger.debug "#{module_name}: Received event bosun.result.clear_silence.failed." event_name = "bosun.clear_silence" if robot.brain.get "centerdevice.#{event_name}.pending" logger.debug "#{module_name}: Oouch: Failed to clear Bosun with id #{event.silence_id} silence because #{event.message}" clear_timeout event_name, robot.brain robot.brain.remove "centerdevice.bosun.set_silence.silence_id" robot.reply {room: event.room, user: event.user}, "Oouch: Failed to clear Bosun silence with id #{event.silence_id}, because #{event.message} Please talk directly to Bosun to clear the silence." robot.on 'bosun.result.check_silence.successful', (event) -> logger.debug "#{module_name}: Received event bosun.result.check_silence.successful." if event.active logger.debug "#{module_name}: currently set silence is still active." set_silence_checker event, robot else logger.debug "#{module_name}: currently set silence became inactive." clear_silence robot.brain robot.reply {room: event.room, user: event.user}, "Hey, your Bosun silence with id #{event.silence_id} expired, but it seems you're still deploying?! Are you okay?" robot.on 'bosun.result.check_silence.failed', (event) -> logger.debug "#{module_name}: Received event bosun.result.check_silence.failed." retries = robot.brain.get("centerdevice.set_silence.checker.failed_retries") or 0 if retries < 3 logger.info "#{module_name}: Reactivating silence checker." retries = robot.brain.set "centerdevice.set_silence.checker.failed_retries", (retries + 1) set_silence_checker event, robot else logger.info "#{module_name}: Giving up on silence checker." clear_silence robot.brain robot.error (err, res) -> robot.logger.error "#{module_name}: DOES NOT COMPUTE" if res? res.reply "DOES NOT COMPUTE: #{err}" prepare_timeout = (name, brain) -> logger.debug "#{module_name}: Preparing timeout for #{name}." brain.set "centerdevice.#{name}.pending", true set_timeout = (name, brain, res) -> logger.debug "#{module_name}: Setting timeout for #{name}." if brain.get "centerdevice.#{name}.pending" logger.debug "#{module_name}: Setting timeout for Bosun silence for #{config.timeout} ms." Timers["#{name}_timeout"] = setTimeout () -> logger.debug "#{module_name}: Ouuch, request for #{name} timed out ... sorry." brain.remove "centerdevice.#{name}.pending" delete Timers["#{name}_timeout"] res.reply "Ouuch, request for #{name} timed out ... sorry." , config.timeout clear_timeout = (name, brain) -> logger.debug "#{module_name}: Clearing timeout for #{name}." brain.remove "centerdevice.#{name}.pending" clearTimeout Timers["#{name}_timeout"] delete Timers["#{name}_timeout"] brain.remove "centerdevice.#{name}.timeout" set_silence_checker = (context, robot) -> logger.debug "#{module_name}: Setting silence checker for #{context}." active_silence_id = robot.brain.get "centerdevice.bosun.set_silence.silence_id" if active_silence_id is context.silence_id logger.debug "#{module_name}: setting timeout for Bosun silence checker #{config.silence_check_interval} ms." Timers["set_silence_checker_timeout"] = setTimeout () -> logger.debug "#{module_name}: Emitting request to Bosun to check if silence with id #{context.silence_id} is still active." robot.emit 'bosun.check_silence', context , config.silence_check_interval clear_silence_checker = (brain) -> logger.debug "#{module_name}: Clearing silence checker." clearTimeout Timers["set_silence_checker_timeout"] delete Timers["set_silence_checker_timeout"] clear_silence = (brain) -> logger.debug "#{module_name}: Clearing silence." clear_silence_checker() brain.remove "centerdevice.bosun.set_silence.silence_id" brain.remove "centerdevice.set_silence.checker.failed_retries" random_bullshit_msg = () -> msgs = [ "Pleaaase nooooo, not again!" "Be gentle, it still hurts from last time ..." "How many tries will you need this time?" "Again? You can't get enough!" "Hit me baby one more time." "Oh yeah, I'm ready for you." "This time I want to cuddle first." "At this time? Don't you have friends?" "But waaaaahy?" "As if it would help ..." "Feelin' lucky, punk?" "Fine ..." "Say 'pretty please'!" "Probably" ] msgs[Math.floor(Math.random() * msgs.length)] is_authorized = (robot, res) -> user = res.envelope.user unless robot.auth.hasRole(user, config.role) warn_unauthorized res false else true warn_unauthorized = (res) -> user = res.envelope.user.name message = res.message.text logger.warning "#{module_name}: #{user} tried to run '#{message}' but was not authorized." res.reply "Sorry, you're not allowed to do that. You need the '#{config.role}' role." format_date_str = (date_str) -> if config.relative_time moment(date_str).fromNow() else date_str.replace(/T/, ' ').replace(/\..+/, ' UTC')
true
# Description # DevOps for CenterDevice via Hubot # # Configuration: # HUBOT_CENTERDEVICE_ROLE -- Auth role required, e.g., "centerdevice" # HUBOT_DEPLOYMENT_SILENCE_DURATION -- Duration of deployment silence, default is 15m # HUBOT_CENTERDEVICE_LOG_LEVEL -- Log level, default is "info" # HUBOT_CENTERDEVICE_BOSUN_TIMEOUT -- Timeout to wait for Bosun to react, default is 30000 ms # HUBOT_CENTERDEVICE_SILENCE_CHECK_INTERVAL -- Interval to check, if Bosun silence is still active # # Commands: # start(ing) centerdevice deployment -- automatically sets Bosun silence for `HUBOT_DEPLOYMENT_SILENCE_DURATION` # start(ing) centerdevice deployment because <message> -- automatically sets Bosun silence for `HUBOT_DEPLOYMENT_SILENCE_DURATION` with <message> # finish(ed) centerdevice deployment -- automatically clears previously created Bosun silence # set centerdevice deployment alert to (.*) -- sets alert to silence; default is `HUBOT_CENTERDEVICE_DEPLOYMENT_BOSUN_ALERT` # get centerdevice deployment alert -- gets alert to silence # set centerdevice deployment tags to (.*) -- sets tags to silence; default is `HUBOT_CENTERDEVICE_DEPLOYMENT_BOSUN_TAGS` # get centerdevice deployment tags -- gets tags to silence # # Notes: # # Author: # PI:EMAIL:<EMAIL>END_PI # # Todos: # - Readme Log = require 'log' moment = require 'moment' module_name = "hubot-centerdevice" BRAIN_CD_ALERT_KEY = "centerdevice.config.alert" BRAIN_CD_TAGS_KEY = "centerdevice.config.tags" config = deployment_bosun_alert: process.env.HUBOT_CENTERDEVICE_DEPLOYMENT_BOSUN_ALERT or "" deployment_bosun_tags: process.env.HUBOT_CENTERDEVICE_DEPLOYMENT_BOSUN_TAGS or "" deployment_silence_duration: process.env.HUBOT_CENTERDEVICE_DEPLOYMENT_SILENCE_DURATION or "15m" log_level: process.env.HUBOT_CENTERDEVICE_LOG_LEVEL or "info" role: process.env.HUBOT_CENTERDEVICE_ROLE silence_check_interval: if process.env.HUBOT_CENTERDEVICE_SILENCE_CHECK_INTERVAL then parseInt process.env.HUBOT_CENTERDEVICE_SILENCE_CHECK_INTERVAL else 60000 silence_clear_delay: if process.env.HUBOT_CENTERDEVICE_SILENCE_CLEAR_DELAY then parseInt process.env.HUBOT_CENTERDEVICE_SILENCE_CLEAR_DELAY else 300000 timeout: if process.env.HUBOT_CENTERDEVICE_BOSUN_TIMEOUT then parseInt process.env.HUBOT_CENTERDEVICE_BOSUN_TIMEOUT else 30000 logger = new Log config.log_level logger.notice "#{module_name}: Started." Timers = {} module.exports = (robot) -> robot.respond /set centerdevice deployment alert to (.*)/i, (res) -> if is_authorized robot, res user_name = res.envelope.user.name alert = res.match[1] logger.info "#{module_name}: setting deployment alert to '#{alert}' requested by #{user_name}." if robot.brain.set BRAIN_CD_ALERT_KEY, alert res.reply "Yay. I just set the deployment alert to silence to '#{alert}'. Happy deploying!" else res.reply "Mah, my brain hurts. I could not change the deployment alert ... Sorry!?" robot.respond /get centerdevice deployment alert/i, (res) -> if is_authorized robot, res user_name = res.envelope.user.name logger.info "#{module_name}: getting deployment alert requested by #{user_name}." alert = if a = robot.brain.get BRAIN_CD_ALERT_KEY then a else config.deployment_bosun_alert res.reply "Ja, the current deployment alert to silence is '#{alert}'. Hope, that helps." robot.respond /set centerdevice deployment tags to (.*)/i, (res) -> if is_authorized robot, res user_name = res.envelope.user.name tags = res.match[1] logger.info "#{module_name}: setting deployment tags to '#{tags}' requested by #{user_name}." if robot.brain.set BRAIN_CD_TAGS_KEY, tags res.reply "Yay. I just set the deployment tags to silence to '#{tags}'. Happy deploying!" else res.reply "Mah, my brain hurts. I could not change the deployment tags ... Sorry!?" robot.respond /get centerdevice deployment tags/i, (res) -> if is_authorized robot, res user_name = res.envelope.user.name logger.info "#{module_name}: getting deployment tags by #{user_name}." tags = if t = robot.brain.get BRAIN_CD_TAGS_KEY then t else config.deployment_bosun_tags res.reply "Ja, the current deployment tags to silence are '#{tags}'. Hope, that helps." robot.respond /start.* centerdevice deployment$/i, (res) -> start_deployment res, "deployment" robot.respond /start.* centerdevice deployment because (.*)/i, (res) -> message = res.match[1] start_deployment res, message start_deployment = (res, message) -> if is_authorized robot, res user_name = res.envelope.user.name logger.info "#{module_name}: starting deployment requested by #{user_name}." event_name = "bosun.set_silence" if silence_id = robot.brain.get "centerdevice.#{event_name}.silence_id" res.reply "Ouuch, there's already a deployment silence with id #{silence_id} pending. Finish that deployment and ask Bosun for active silences." else res.reply random_bullshit_msg() res.reply "Ok, let me silence Bosun because #{message} ..." prepare_timeout event_name, robot.brain logger.debug "#{module_name}: emitting request for Bosun silence." robot.emit event_name, user: res.envelope.user room: res.envelope.room duration: config.deployment_silence_duration alert: robot.brain.get(BRAIN_CD_ALERT_KEY) or config.deployment_bosun_alert tags: robot.brain.get(BRAIN_CD_TAGS_KEY) or config.deployment_bosun_tags message: message set_timeout event_name, robot.brain, res robot.respond /finish.* centerdevice deployment/i, (res) -> if is_authorized robot, res user_name = res.envelope.user.name logger.info "#{module_name}: finished deployment requested by #{user_name}." event_name = "bosun.clear_silence" active_silence_id = robot.brain.get "centerdevice.bosun.set_silence.silence_id" unless active_silence_id? res.reply "Hm, there's no active Bosun silence. You're sure there's a deployment going on?" else res.reply "Ok, I'll clear the Bosun silence for your deployment in #{config.silence_clear_delay / 60000} min so Bosun can calm down ..." clear_silence robot.brain setTimeout () -> res.reply "Trying to clear Bosun silence for your deployment." prepare_timeout event_name, robot.brain logger.debug "#{module_name}: Emitting request for Bosun to clear silence." robot.emit event_name, user: res.envelope.user room: res.envelope.room silence_id: active_silence_id set_timeout event_name, robot.brain, res , config.silence_clear_delay robot.on 'bosun.result.set_silence.successful', (event) -> logger.debug "#{module_name}: Received event bosun.result.set_silence.successful." event_name = "bosun.set_silence" if robot.brain.get "centerdevice.#{event_name}.pending" logger.debug "#{module_name}: Set Bosun silence successful for #{event.duration} with id #{event.silence_id}." clear_timeout event_name, robot.brain robot.brain.set "centerdevice.#{event_name}.silence_id", event.silence_id robot.reply {room: event.room, user: event.user}, "Set Bosun silence successfully for #{event.duration} with id #{event.silence_id}." set_silence_checker {room: event.room, user: event.user, silence_id: event.silence_id}, robot robot.on 'bosun.result.set_silence.failed', (event) -> logger.debug "#{module_name}: Received event bosun.result.set_silence.failed." event_name = "bosun.set_silence" if robot.brain.get "centerdevice.#{event_name}.pending" logger.debug "#{module_name}: Oouch: Failed to set Bosun silence because #{event.message}" clear_timeout event_name, robot.brain robot.reply {room: event.room, user: event.user}, "Oouch: Failed to set Bosun silence because #{event.message}" robot.on 'bosun.result.clear_silence.successful', (event) -> logger.debug "#{module_name}: Received event bosun.result.clear_silence.successful." event_name = "bosun.clear_silence" if robot.brain.get "centerdevice.#{event_name}.pending" logger.debug "#{module_name}: Cleared Bosun silence successfully with id #{event.silence_id}." clear_timeout event_name, robot.brain clear_silence robot.brain robot.reply {room: event.room, user: event.user}, "Cleared Bosun silence successfully with id #{event.silence_id}." robot.on 'bosun.result.clear_silence.failed', (event) -> logger.debug "#{module_name}: Received event bosun.result.clear_silence.failed." event_name = "bosun.clear_silence" if robot.brain.get "centerdevice.#{event_name}.pending" logger.debug "#{module_name}: Oouch: Failed to clear Bosun with id #{event.silence_id} silence because #{event.message}" clear_timeout event_name, robot.brain robot.brain.remove "centerdevice.bosun.set_silence.silence_id" robot.reply {room: event.room, user: event.user}, "Oouch: Failed to clear Bosun silence with id #{event.silence_id}, because #{event.message} Please talk directly to Bosun to clear the silence." robot.on 'bosun.result.check_silence.successful', (event) -> logger.debug "#{module_name}: Received event bosun.result.check_silence.successful." if event.active logger.debug "#{module_name}: currently set silence is still active." set_silence_checker event, robot else logger.debug "#{module_name}: currently set silence became inactive." clear_silence robot.brain robot.reply {room: event.room, user: event.user}, "Hey, your Bosun silence with id #{event.silence_id} expired, but it seems you're still deploying?! Are you okay?" robot.on 'bosun.result.check_silence.failed', (event) -> logger.debug "#{module_name}: Received event bosun.result.check_silence.failed." retries = robot.brain.get("centerdevice.set_silence.checker.failed_retries") or 0 if retries < 3 logger.info "#{module_name}: Reactivating silence checker." retries = robot.brain.set "centerdevice.set_silence.checker.failed_retries", (retries + 1) set_silence_checker event, robot else logger.info "#{module_name}: Giving up on silence checker." clear_silence robot.brain robot.error (err, res) -> robot.logger.error "#{module_name}: DOES NOT COMPUTE" if res? res.reply "DOES NOT COMPUTE: #{err}" prepare_timeout = (name, brain) -> logger.debug "#{module_name}: Preparing timeout for #{name}." brain.set "centerdevice.#{name}.pending", true set_timeout = (name, brain, res) -> logger.debug "#{module_name}: Setting timeout for #{name}." if brain.get "centerdevice.#{name}.pending" logger.debug "#{module_name}: Setting timeout for Bosun silence for #{config.timeout} ms." Timers["#{name}_timeout"] = setTimeout () -> logger.debug "#{module_name}: Ouuch, request for #{name} timed out ... sorry." brain.remove "centerdevice.#{name}.pending" delete Timers["#{name}_timeout"] res.reply "Ouuch, request for #{name} timed out ... sorry." , config.timeout clear_timeout = (name, brain) -> logger.debug "#{module_name}: Clearing timeout for #{name}." brain.remove "centerdevice.#{name}.pending" clearTimeout Timers["#{name}_timeout"] delete Timers["#{name}_timeout"] brain.remove "centerdevice.#{name}.timeout" set_silence_checker = (context, robot) -> logger.debug "#{module_name}: Setting silence checker for #{context}." active_silence_id = robot.brain.get "centerdevice.bosun.set_silence.silence_id" if active_silence_id is context.silence_id logger.debug "#{module_name}: setting timeout for Bosun silence checker #{config.silence_check_interval} ms." Timers["set_silence_checker_timeout"] = setTimeout () -> logger.debug "#{module_name}: Emitting request to Bosun to check if silence with id #{context.silence_id} is still active." robot.emit 'bosun.check_silence', context , config.silence_check_interval clear_silence_checker = (brain) -> logger.debug "#{module_name}: Clearing silence checker." clearTimeout Timers["set_silence_checker_timeout"] delete Timers["set_silence_checker_timeout"] clear_silence = (brain) -> logger.debug "#{module_name}: Clearing silence." clear_silence_checker() brain.remove "centerdevice.bosun.set_silence.silence_id" brain.remove "centerdevice.set_silence.checker.failed_retries" random_bullshit_msg = () -> msgs = [ "Pleaaase nooooo, not again!" "Be gentle, it still hurts from last time ..." "How many tries will you need this time?" "Again? You can't get enough!" "Hit me baby one more time." "Oh yeah, I'm ready for you." "This time I want to cuddle first." "At this time? Don't you have friends?" "But waaaaahy?" "As if it would help ..." "Feelin' lucky, punk?" "Fine ..." "Say 'pretty please'!" "Probably" ] msgs[Math.floor(Math.random() * msgs.length)] is_authorized = (robot, res) -> user = res.envelope.user unless robot.auth.hasRole(user, config.role) warn_unauthorized res false else true warn_unauthorized = (res) -> user = res.envelope.user.name message = res.message.text logger.warning "#{module_name}: #{user} tried to run '#{message}' but was not authorized." res.reply "Sorry, you're not allowed to do that. You need the '#{config.role}' role." format_date_str = (date_str) -> if config.relative_time moment(date_str).fromNow() else date_str.replace(/T/, ' ').replace(/\..+/, ' UTC')
[ { "context": "\n]\n\nclass Repository\n\n username: null\n password: null\n\n rootPath: null\n\n isHgRepository: false\n bina", "end": 940, "score": 0.9938230514526367, "start": 936, "tag": "PASSWORD", "value": "null" } ]
lib/hg-utils.coffee
victor-torres/atom-hg
33
fs = require 'fs' path = require 'path' util = require 'util' urlParser = require 'url' {spawnSync, exec} = require 'child_process' diffLib = require 'jsdifflib' ### Section: Constants used for file/buffer checking against changes ### statusIndexNew = 1 << 0 statusIndexDeleted = 1 << 2 statusWorkingDirNew = 1 << 7 statusWorkingDirModified = 1 << 8 statusWorkingDirDelete = 1 << 9 statusWorkingDirTypeChange = 1 << 10 statusIgnored = 1 << 14 modifiedStatusFlags = statusWorkingDirModified | statusWorkingDirDelete | statusWorkingDirTypeChange | statusIndexDeleted newStatusFlags = statusWorkingDirNew | statusIndexNew deletedStatusFlags = statusWorkingDirDelete | statusIndexDeleted suppressHgWarnings = [ 'W200005' # hg: warning: W200005: 'file' is not under version control 'E200009' # Could not cat all targets because some targets are not versioned ] class Repository username: null password: null rootPath: null isHgRepository: false binaryAvailable: false version: null url: null urlPath: null revision: null diffRevisionProvider: null ### Section: Initialization and startup checks ### constructor: (repoRootPath, diffRevisionProvider) -> @rootPath = path.normalize(repoRootPath) unless fs.existsSync(@rootPath) return lstat = fs.lstatSync(@rootPath) unless lstat.isSymbolicLink() return @diffRevisionProvider = diffRevisionProvider @rootPath = fs.realpathSync(@rootPath) # Checks if there is a hg binary in the os searchpath and returns the # binary version string. # # Returns a {boolean} checkBinaryAvailable: () -> @version = @getHgVersion() if @version? @binaryAvailable = true else @binaryAvailable = false return @binaryAvailable exists: () -> return fs.existsSync(@rootPath + '/.hg') # Parses info from `hg info` and `hgversion` command and checks if repo infos have changed # since last check # # Returns a {Promise} of a {boolean} if repo infos have changed checkRepositoryHasChangedAsync: () => return @getHgWorkingCopyRevisionAsync().then (revision) => if revision? and revision != @revision @revision = revision return true return false getShortHeadAsync: () => return new Promise (resolve) => branchFile = @rootPath + '/.hg/branch' bookmarkFile = @rootPath + '/.hg/bookmarks.current' prompt = 'default' fs.readFile branchFile, 'utf8', (err, data) => prompt = data.trim() unless err fs.readFile bookmarkFile, 'utf8', (err, data) => prompt += ':' + data.trim() unless err @getHgTagsAsync().then (tags) -> prompt += ':' + tags.join(',') if tags?.length .then () -> # Finally resolve prompt ### Section: TreeView Path Mercurial status ### # Parses `hg status`. Gets initially called by hg-repository.refreshStatus() # # Returns a {Promise} of an {Array} array keys are paths, values are change # constants. Or null getStatus: () -> return @getHgStatusAsync() # Parses `hg status`. Gets called by hg-repository.refreshStatus() # # Returns an {Array} Array keys are paths, values are change constants getPathStatus: (hgPath) -> status = @getHgPathStatus(hgPath) return status getPath: () -> return @rootPath isStatusModified: (status=0) -> (status & modifiedStatusFlags) > 0 isPathModified: (path) -> @isStatusModified(@getPathStatus(path)) isStatusNew: (status=0) -> (status & newStatusFlags) > 0 isPathNew: (path) -> @isStatusNew(@getPathStatus(path)) isStatusDeleted: (status=0) -> (status & deletedStatusFlags) > 0 isPathDeleted: (path) -> @isStatusDeleted(@getPathStatus(path)) isPathStaged: (path) -> @isStatusStaged(@getPathStatus(path)) isStatusIgnored: (status=0) -> (status & statusIgnored) > 0 isStatusStaged: (status=0) -> (status & statusWorkingDirNew) == 0 ### Section: Editor Mercurial line diffs ### # Public: Retrieves the number of lines added and removed to a path. # # This compares the working directory contents of the path to the `HEAD` # version. # # * `path` The {String} path to check. # * `lastRevFileContent` filecontent from latest hg revision. # # Returns an {Object} with the following keys: # * `added` The {Number} of added lines. # * `deleted` The {Number} of deleted lines. getDiffStats: (path, lastRevFileContent) -> diffStats = { added: 0 deleted: 0 } if (lastRevFileContent? && fs.existsSync(path)) base = diffLib.stringAsLines(lastRevFileContent) newtxt = diffLib.stringAsLines(fs.readFileSync(path).toString()) # create a SequenceMatcher instance that diffs the two sets of lines sm = new diffLib.SequenceMatcher(base, newtxt) # get the opcodes from the SequenceMatcher instance # opcodes is a list of 3-tuples describing what changes should be made to the base text # in order to yield the new text opcodes = sm.get_opcodes() for opcode in opcodes if opcode[0] == 'insert' || opcode[0] == 'replace' diffStats.added += (opcode[2] - opcode[1]) + (opcode[4] - opcode[3]) if opcode[0] == 'delete' diffStats.deleted += (opcode[2] - opcode[1]) - (opcode[4] - opcode[3]) return diffStats # Public: Retrieves the line diffs comparing the `HEAD` version of the given # path and the given text. # # * `lastRevFileContent` filecontent from latest hg revision. # * `text` The {String} to compare against the `HEAD` contents # # Returns an {Array} of hunk {Object}s with the following keys: # * `oldStart` The line {Number} of the old hunk. # * `newStart` The line {Number} of the new hunk. # * `oldLines` The {Number} of lines in the old hunk. # * `newLines` The {Number} of lines in the new hunk getLineDiffs: (lastRevFileContent, text, options) -> hunks = [] if (lastRevFileContent?) base = diffLib.stringAsLines(lastRevFileContent) newtxt = diffLib.stringAsLines(text) # create a SequenceMatcher instance that diffs the two sets of lines sm = new diffLib.SequenceMatcher(base, newtxt) # get the opcodes from the SequenceMatcher instance # opcodes is a list of 3-tuples describing what changes should be made to the base text # in order to yield the new text opcodes = sm.get_opcodes() actions = ['replace', 'insert', 'delete'] for opcode in opcodes if actions.indexOf(opcode[0]) >= 0 hunk = { oldStart: opcode[1] + 1 oldLines: opcode[2] - opcode[1] newStart: opcode[3] + 1 newLines: opcode[4] - opcode[3] } if opcode[0] == 'delete' hunk.newStart = hunk.newStart - 1 hunks.push(hunk) return hunks ### Section: Mercurial Command handling ### # Spawns an hg command and returns stdout or throws an error if process # exits with an exitcode unequal to zero. # # * `params` The {Array} for commandline arguments # # Returns a {String} of process stdout hgCommand: (params) -> if !params params = [] if !util.isArray(params) params = [params] if !@isCommandForRepo(params) return '' child = spawnSync('hg', params, { cwd: @rootPath }) if child.status != 0 if child.stderr throw new Error(child.stderr.toString()) if child.stdout throw new Error(child.stdout.toString()) throw new Error('Error trying to execute Mercurial binary with params \'' + params + '\'') return child.stdout.toString() hgCommandAsync: (params) -> if !params params = [] if !util.isArray(params) params = [params] if !@isCommandForRepo(params) return Promise.resolve('') flatArgs = params.reduce (prev, next) -> if next.indexOf? and next.indexOf(' ') != -1 next = "\"" + next + "\"" prev + " " + next , "" flatArgs = flatArgs.substring(1) return new Promise (resolve, reject) => opts = cwd: @rootPath maxBuffer: 50 * 1024 * 1024 child = exec 'hg ' + flatArgs, opts, (err, stdout, stderr) -> if err reject err if stderr?.length > 0 reject stderr resolve stdout handleHgError: (error) -> logMessage = true message = error.message for suppressHgWarning in suppressHgWarnings if message.indexOf(suppressHgWarning) > 0 logMessage = false break if logMessage console.error('Mercurial', 'hg-utils', error) # Returns on success the version from the hg binary. Otherwise null. # # Returns a {String} containing the hg-binary version getHgVersion: () -> try version = @hgCommand(['--version', '--quiet']) return version.trim() catch error @handleHgError(error) return null # Returns on success the current working copy revision. Otherwise null. # # Returns a {Promise} of a {String} with the current working copy revision getHgWorkingCopyRevisionAsync: () => @hgCommandAsync(['id', '-i', @rootPath]).catch (error) => @handleHgError(error) return null getRecursiveIgnoreStatuses: () -> revision = @diffRevisionProvider() @hgCommandAsync(['status', @rootPath, "-i", "--rev", revision]) .then (files) => items = [] entries = files.split('\n') if entries for entry in entries parts = entry.split(' ') status = parts[0] pathPart = parts[1] if pathPart? && status? if (status is 'I') # || status is '?') items.push(pathPart.replace('..', '')) (path.join @rootPath, item for item in items) .catch (error) => @handleHgError error [] getHgStatusAsync: () -> revision = @diffRevisionProvider() @hgCommandAsync(['status', @rootPath, '--rev', revision]).then (files) => items = [] entries = files.split('\n') if entries for entry in entries parts = entry.split(' ') status = parts[0] pathPart = parts[1] if pathPart? && status? items.push({ 'path': path.join @rootPath, pathPart 'status': @mapHgStatus(status) }) return items .catch (error) => @handleHgError(error) return null # Returns on success the list of tags for this revision. Otherwise null. # # Returns a {Primise} of an {Array} of {String}s representing the status getHgTagsAsync: () -> @hgCommandAsync(['id', '-t', @rootPath]).then (tags) -> tags = tags.trim() return tags.split(' ').sort() if tags .catch (error) => @handleHgError(error) return null # Returns on success a status bitmask. Otherwise null. # # * `hgPath` The path {String} for the status inquiry # # Returns a {Number} representing the status getHgPathStatus: (hgPath) -> return null unless hgPath try revision = @diffRevisionProvider() files = @hgCommand(['status', hgPath, '--rev', revision]) catch error @handleHgError(error) return null items = [] entries = files.split('\n') if entries path_status = 0 for entry in entries parts = entry.split(' ') status = parts[0] pathPart = parts[1] if status? path_status |= @mapHgStatus(status) return path_status else return null # Translates the status {String} from `hg status` command into a # status {Number}. # # * `status` The status {String} from `hg status` command # # Returns a {Number} representing the status mapHgStatus: (status) -> return 0 unless status statusBitmask = 0 # status workingdir if status == 'M' statusBitmask = statusWorkingDirModified if status == '?' statusBitmask = statusWorkingDirNew if status == '!' statusBitmask = statusWorkingDirDelete if status == 'I' statusBitmask = statusIgnored if status == 'M' statusBitmask = statusWorkingDirTypeChange # status index if status == 'A' statusBitmask = statusIndexNew if status == 'R' statusBitmask = statusIndexDeleted return statusBitmask # This retrieves the contents of the hgpath from the diff revision on success. # Otherwise null. # # * `hgPath` The path {String} # # Returns {Promise} of a {String} with the filecontent getHgCatAsync: (hgPath) -> revision = @diffRevisionProvider() params = ['cat', hgPath, '--rev', revision] return @hgCommandAsync(params).catch (error) => if /no such file in rev/.test(error) return null @handleHgError error return null # This checks to see if the current params indicate whether we are working # with the current repository. # # * `params` The params that are going to be sent to the hg command {Array} # # Returns a {Boolean} indicating if the rootPath was found in the params isCommandForRepo: (params) -> rootPath = @rootPath paths = params.filter (param) -> normalizedPath = path.normalize((param || '')) return normalizedPath.startsWith(rootPath) return paths.length > 0 exports.isStatusModified = (status) -> return (status & modifiedStatusFlags) > 0 exports.isStatusNew = (status) -> return (status & newStatusFlags) > 0 exports.isStatusDeleted = (status) -> return (status & deletedStatusFlags) > 0 exports.isStatusIgnored = (status) -> return (status & statusIgnored) > 0 exports.isStatusStaged = (status) -> return (status & statusWorkingDirNew) == 0 # creates and returns a new {Repository} object if hg-binary could be found # and several infos from are successfully read. Otherwise null. # # * `repositoryPath` The path {String} to the repository root directory # # Returns a new {Repository} object openRepository = (repositoryPath, diffRevisionProvider) -> repository = new Repository(repositoryPath) if repository.checkBinaryAvailable() and repository.exists() repository.diffRevisionProvider = diffRevisionProvider return repository else return null exports.open = (repositoryPath, diffRevisionProvider) -> return openRepository(repositoryPath, diffRevisionProvider) # Verifies if given path is a symbolic link. # Returns original path or null otherwise. resolveSymlink = (repositoryPath) -> lstat = fs.lstatSync(repositoryPath) unless lstat.isSymbolicLink() return null return fs.realpathSync(repositoryPath) exports.resolveSymlink = (repositoryPath) -> return resolveSymlink(repositoryPath)
80151
fs = require 'fs' path = require 'path' util = require 'util' urlParser = require 'url' {spawnSync, exec} = require 'child_process' diffLib = require 'jsdifflib' ### Section: Constants used for file/buffer checking against changes ### statusIndexNew = 1 << 0 statusIndexDeleted = 1 << 2 statusWorkingDirNew = 1 << 7 statusWorkingDirModified = 1 << 8 statusWorkingDirDelete = 1 << 9 statusWorkingDirTypeChange = 1 << 10 statusIgnored = 1 << 14 modifiedStatusFlags = statusWorkingDirModified | statusWorkingDirDelete | statusWorkingDirTypeChange | statusIndexDeleted newStatusFlags = statusWorkingDirNew | statusIndexNew deletedStatusFlags = statusWorkingDirDelete | statusIndexDeleted suppressHgWarnings = [ 'W200005' # hg: warning: W200005: 'file' is not under version control 'E200009' # Could not cat all targets because some targets are not versioned ] class Repository username: null password: <PASSWORD> rootPath: null isHgRepository: false binaryAvailable: false version: null url: null urlPath: null revision: null diffRevisionProvider: null ### Section: Initialization and startup checks ### constructor: (repoRootPath, diffRevisionProvider) -> @rootPath = path.normalize(repoRootPath) unless fs.existsSync(@rootPath) return lstat = fs.lstatSync(@rootPath) unless lstat.isSymbolicLink() return @diffRevisionProvider = diffRevisionProvider @rootPath = fs.realpathSync(@rootPath) # Checks if there is a hg binary in the os searchpath and returns the # binary version string. # # Returns a {boolean} checkBinaryAvailable: () -> @version = @getHgVersion() if @version? @binaryAvailable = true else @binaryAvailable = false return @binaryAvailable exists: () -> return fs.existsSync(@rootPath + '/.hg') # Parses info from `hg info` and `hgversion` command and checks if repo infos have changed # since last check # # Returns a {Promise} of a {boolean} if repo infos have changed checkRepositoryHasChangedAsync: () => return @getHgWorkingCopyRevisionAsync().then (revision) => if revision? and revision != @revision @revision = revision return true return false getShortHeadAsync: () => return new Promise (resolve) => branchFile = @rootPath + '/.hg/branch' bookmarkFile = @rootPath + '/.hg/bookmarks.current' prompt = 'default' fs.readFile branchFile, 'utf8', (err, data) => prompt = data.trim() unless err fs.readFile bookmarkFile, 'utf8', (err, data) => prompt += ':' + data.trim() unless err @getHgTagsAsync().then (tags) -> prompt += ':' + tags.join(',') if tags?.length .then () -> # Finally resolve prompt ### Section: TreeView Path Mercurial status ### # Parses `hg status`. Gets initially called by hg-repository.refreshStatus() # # Returns a {Promise} of an {Array} array keys are paths, values are change # constants. Or null getStatus: () -> return @getHgStatusAsync() # Parses `hg status`. Gets called by hg-repository.refreshStatus() # # Returns an {Array} Array keys are paths, values are change constants getPathStatus: (hgPath) -> status = @getHgPathStatus(hgPath) return status getPath: () -> return @rootPath isStatusModified: (status=0) -> (status & modifiedStatusFlags) > 0 isPathModified: (path) -> @isStatusModified(@getPathStatus(path)) isStatusNew: (status=0) -> (status & newStatusFlags) > 0 isPathNew: (path) -> @isStatusNew(@getPathStatus(path)) isStatusDeleted: (status=0) -> (status & deletedStatusFlags) > 0 isPathDeleted: (path) -> @isStatusDeleted(@getPathStatus(path)) isPathStaged: (path) -> @isStatusStaged(@getPathStatus(path)) isStatusIgnored: (status=0) -> (status & statusIgnored) > 0 isStatusStaged: (status=0) -> (status & statusWorkingDirNew) == 0 ### Section: Editor Mercurial line diffs ### # Public: Retrieves the number of lines added and removed to a path. # # This compares the working directory contents of the path to the `HEAD` # version. # # * `path` The {String} path to check. # * `lastRevFileContent` filecontent from latest hg revision. # # Returns an {Object} with the following keys: # * `added` The {Number} of added lines. # * `deleted` The {Number} of deleted lines. getDiffStats: (path, lastRevFileContent) -> diffStats = { added: 0 deleted: 0 } if (lastRevFileContent? && fs.existsSync(path)) base = diffLib.stringAsLines(lastRevFileContent) newtxt = diffLib.stringAsLines(fs.readFileSync(path).toString()) # create a SequenceMatcher instance that diffs the two sets of lines sm = new diffLib.SequenceMatcher(base, newtxt) # get the opcodes from the SequenceMatcher instance # opcodes is a list of 3-tuples describing what changes should be made to the base text # in order to yield the new text opcodes = sm.get_opcodes() for opcode in opcodes if opcode[0] == 'insert' || opcode[0] == 'replace' diffStats.added += (opcode[2] - opcode[1]) + (opcode[4] - opcode[3]) if opcode[0] == 'delete' diffStats.deleted += (opcode[2] - opcode[1]) - (opcode[4] - opcode[3]) return diffStats # Public: Retrieves the line diffs comparing the `HEAD` version of the given # path and the given text. # # * `lastRevFileContent` filecontent from latest hg revision. # * `text` The {String} to compare against the `HEAD` contents # # Returns an {Array} of hunk {Object}s with the following keys: # * `oldStart` The line {Number} of the old hunk. # * `newStart` The line {Number} of the new hunk. # * `oldLines` The {Number} of lines in the old hunk. # * `newLines` The {Number} of lines in the new hunk getLineDiffs: (lastRevFileContent, text, options) -> hunks = [] if (lastRevFileContent?) base = diffLib.stringAsLines(lastRevFileContent) newtxt = diffLib.stringAsLines(text) # create a SequenceMatcher instance that diffs the two sets of lines sm = new diffLib.SequenceMatcher(base, newtxt) # get the opcodes from the SequenceMatcher instance # opcodes is a list of 3-tuples describing what changes should be made to the base text # in order to yield the new text opcodes = sm.get_opcodes() actions = ['replace', 'insert', 'delete'] for opcode in opcodes if actions.indexOf(opcode[0]) >= 0 hunk = { oldStart: opcode[1] + 1 oldLines: opcode[2] - opcode[1] newStart: opcode[3] + 1 newLines: opcode[4] - opcode[3] } if opcode[0] == 'delete' hunk.newStart = hunk.newStart - 1 hunks.push(hunk) return hunks ### Section: Mercurial Command handling ### # Spawns an hg command and returns stdout or throws an error if process # exits with an exitcode unequal to zero. # # * `params` The {Array} for commandline arguments # # Returns a {String} of process stdout hgCommand: (params) -> if !params params = [] if !util.isArray(params) params = [params] if !@isCommandForRepo(params) return '' child = spawnSync('hg', params, { cwd: @rootPath }) if child.status != 0 if child.stderr throw new Error(child.stderr.toString()) if child.stdout throw new Error(child.stdout.toString()) throw new Error('Error trying to execute Mercurial binary with params \'' + params + '\'') return child.stdout.toString() hgCommandAsync: (params) -> if !params params = [] if !util.isArray(params) params = [params] if !@isCommandForRepo(params) return Promise.resolve('') flatArgs = params.reduce (prev, next) -> if next.indexOf? and next.indexOf(' ') != -1 next = "\"" + next + "\"" prev + " " + next , "" flatArgs = flatArgs.substring(1) return new Promise (resolve, reject) => opts = cwd: @rootPath maxBuffer: 50 * 1024 * 1024 child = exec 'hg ' + flatArgs, opts, (err, stdout, stderr) -> if err reject err if stderr?.length > 0 reject stderr resolve stdout handleHgError: (error) -> logMessage = true message = error.message for suppressHgWarning in suppressHgWarnings if message.indexOf(suppressHgWarning) > 0 logMessage = false break if logMessage console.error('Mercurial', 'hg-utils', error) # Returns on success the version from the hg binary. Otherwise null. # # Returns a {String} containing the hg-binary version getHgVersion: () -> try version = @hgCommand(['--version', '--quiet']) return version.trim() catch error @handleHgError(error) return null # Returns on success the current working copy revision. Otherwise null. # # Returns a {Promise} of a {String} with the current working copy revision getHgWorkingCopyRevisionAsync: () => @hgCommandAsync(['id', '-i', @rootPath]).catch (error) => @handleHgError(error) return null getRecursiveIgnoreStatuses: () -> revision = @diffRevisionProvider() @hgCommandAsync(['status', @rootPath, "-i", "--rev", revision]) .then (files) => items = [] entries = files.split('\n') if entries for entry in entries parts = entry.split(' ') status = parts[0] pathPart = parts[1] if pathPart? && status? if (status is 'I') # || status is '?') items.push(pathPart.replace('..', '')) (path.join @rootPath, item for item in items) .catch (error) => @handleHgError error [] getHgStatusAsync: () -> revision = @diffRevisionProvider() @hgCommandAsync(['status', @rootPath, '--rev', revision]).then (files) => items = [] entries = files.split('\n') if entries for entry in entries parts = entry.split(' ') status = parts[0] pathPart = parts[1] if pathPart? && status? items.push({ 'path': path.join @rootPath, pathPart 'status': @mapHgStatus(status) }) return items .catch (error) => @handleHgError(error) return null # Returns on success the list of tags for this revision. Otherwise null. # # Returns a {Primise} of an {Array} of {String}s representing the status getHgTagsAsync: () -> @hgCommandAsync(['id', '-t', @rootPath]).then (tags) -> tags = tags.trim() return tags.split(' ').sort() if tags .catch (error) => @handleHgError(error) return null # Returns on success a status bitmask. Otherwise null. # # * `hgPath` The path {String} for the status inquiry # # Returns a {Number} representing the status getHgPathStatus: (hgPath) -> return null unless hgPath try revision = @diffRevisionProvider() files = @hgCommand(['status', hgPath, '--rev', revision]) catch error @handleHgError(error) return null items = [] entries = files.split('\n') if entries path_status = 0 for entry in entries parts = entry.split(' ') status = parts[0] pathPart = parts[1] if status? path_status |= @mapHgStatus(status) return path_status else return null # Translates the status {String} from `hg status` command into a # status {Number}. # # * `status` The status {String} from `hg status` command # # Returns a {Number} representing the status mapHgStatus: (status) -> return 0 unless status statusBitmask = 0 # status workingdir if status == 'M' statusBitmask = statusWorkingDirModified if status == '?' statusBitmask = statusWorkingDirNew if status == '!' statusBitmask = statusWorkingDirDelete if status == 'I' statusBitmask = statusIgnored if status == 'M' statusBitmask = statusWorkingDirTypeChange # status index if status == 'A' statusBitmask = statusIndexNew if status == 'R' statusBitmask = statusIndexDeleted return statusBitmask # This retrieves the contents of the hgpath from the diff revision on success. # Otherwise null. # # * `hgPath` The path {String} # # Returns {Promise} of a {String} with the filecontent getHgCatAsync: (hgPath) -> revision = @diffRevisionProvider() params = ['cat', hgPath, '--rev', revision] return @hgCommandAsync(params).catch (error) => if /no such file in rev/.test(error) return null @handleHgError error return null # This checks to see if the current params indicate whether we are working # with the current repository. # # * `params` The params that are going to be sent to the hg command {Array} # # Returns a {Boolean} indicating if the rootPath was found in the params isCommandForRepo: (params) -> rootPath = @rootPath paths = params.filter (param) -> normalizedPath = path.normalize((param || '')) return normalizedPath.startsWith(rootPath) return paths.length > 0 exports.isStatusModified = (status) -> return (status & modifiedStatusFlags) > 0 exports.isStatusNew = (status) -> return (status & newStatusFlags) > 0 exports.isStatusDeleted = (status) -> return (status & deletedStatusFlags) > 0 exports.isStatusIgnored = (status) -> return (status & statusIgnored) > 0 exports.isStatusStaged = (status) -> return (status & statusWorkingDirNew) == 0 # creates and returns a new {Repository} object if hg-binary could be found # and several infos from are successfully read. Otherwise null. # # * `repositoryPath` The path {String} to the repository root directory # # Returns a new {Repository} object openRepository = (repositoryPath, diffRevisionProvider) -> repository = new Repository(repositoryPath) if repository.checkBinaryAvailable() and repository.exists() repository.diffRevisionProvider = diffRevisionProvider return repository else return null exports.open = (repositoryPath, diffRevisionProvider) -> return openRepository(repositoryPath, diffRevisionProvider) # Verifies if given path is a symbolic link. # Returns original path or null otherwise. resolveSymlink = (repositoryPath) -> lstat = fs.lstatSync(repositoryPath) unless lstat.isSymbolicLink() return null return fs.realpathSync(repositoryPath) exports.resolveSymlink = (repositoryPath) -> return resolveSymlink(repositoryPath)
true
fs = require 'fs' path = require 'path' util = require 'util' urlParser = require 'url' {spawnSync, exec} = require 'child_process' diffLib = require 'jsdifflib' ### Section: Constants used for file/buffer checking against changes ### statusIndexNew = 1 << 0 statusIndexDeleted = 1 << 2 statusWorkingDirNew = 1 << 7 statusWorkingDirModified = 1 << 8 statusWorkingDirDelete = 1 << 9 statusWorkingDirTypeChange = 1 << 10 statusIgnored = 1 << 14 modifiedStatusFlags = statusWorkingDirModified | statusWorkingDirDelete | statusWorkingDirTypeChange | statusIndexDeleted newStatusFlags = statusWorkingDirNew | statusIndexNew deletedStatusFlags = statusWorkingDirDelete | statusIndexDeleted suppressHgWarnings = [ 'W200005' # hg: warning: W200005: 'file' is not under version control 'E200009' # Could not cat all targets because some targets are not versioned ] class Repository username: null password: PI:PASSWORD:<PASSWORD>END_PI rootPath: null isHgRepository: false binaryAvailable: false version: null url: null urlPath: null revision: null diffRevisionProvider: null ### Section: Initialization and startup checks ### constructor: (repoRootPath, diffRevisionProvider) -> @rootPath = path.normalize(repoRootPath) unless fs.existsSync(@rootPath) return lstat = fs.lstatSync(@rootPath) unless lstat.isSymbolicLink() return @diffRevisionProvider = diffRevisionProvider @rootPath = fs.realpathSync(@rootPath) # Checks if there is a hg binary in the os searchpath and returns the # binary version string. # # Returns a {boolean} checkBinaryAvailable: () -> @version = @getHgVersion() if @version? @binaryAvailable = true else @binaryAvailable = false return @binaryAvailable exists: () -> return fs.existsSync(@rootPath + '/.hg') # Parses info from `hg info` and `hgversion` command and checks if repo infos have changed # since last check # # Returns a {Promise} of a {boolean} if repo infos have changed checkRepositoryHasChangedAsync: () => return @getHgWorkingCopyRevisionAsync().then (revision) => if revision? and revision != @revision @revision = revision return true return false getShortHeadAsync: () => return new Promise (resolve) => branchFile = @rootPath + '/.hg/branch' bookmarkFile = @rootPath + '/.hg/bookmarks.current' prompt = 'default' fs.readFile branchFile, 'utf8', (err, data) => prompt = data.trim() unless err fs.readFile bookmarkFile, 'utf8', (err, data) => prompt += ':' + data.trim() unless err @getHgTagsAsync().then (tags) -> prompt += ':' + tags.join(',') if tags?.length .then () -> # Finally resolve prompt ### Section: TreeView Path Mercurial status ### # Parses `hg status`. Gets initially called by hg-repository.refreshStatus() # # Returns a {Promise} of an {Array} array keys are paths, values are change # constants. Or null getStatus: () -> return @getHgStatusAsync() # Parses `hg status`. Gets called by hg-repository.refreshStatus() # # Returns an {Array} Array keys are paths, values are change constants getPathStatus: (hgPath) -> status = @getHgPathStatus(hgPath) return status getPath: () -> return @rootPath isStatusModified: (status=0) -> (status & modifiedStatusFlags) > 0 isPathModified: (path) -> @isStatusModified(@getPathStatus(path)) isStatusNew: (status=0) -> (status & newStatusFlags) > 0 isPathNew: (path) -> @isStatusNew(@getPathStatus(path)) isStatusDeleted: (status=0) -> (status & deletedStatusFlags) > 0 isPathDeleted: (path) -> @isStatusDeleted(@getPathStatus(path)) isPathStaged: (path) -> @isStatusStaged(@getPathStatus(path)) isStatusIgnored: (status=0) -> (status & statusIgnored) > 0 isStatusStaged: (status=0) -> (status & statusWorkingDirNew) == 0 ### Section: Editor Mercurial line diffs ### # Public: Retrieves the number of lines added and removed to a path. # # This compares the working directory contents of the path to the `HEAD` # version. # # * `path` The {String} path to check. # * `lastRevFileContent` filecontent from latest hg revision. # # Returns an {Object} with the following keys: # * `added` The {Number} of added lines. # * `deleted` The {Number} of deleted lines. getDiffStats: (path, lastRevFileContent) -> diffStats = { added: 0 deleted: 0 } if (lastRevFileContent? && fs.existsSync(path)) base = diffLib.stringAsLines(lastRevFileContent) newtxt = diffLib.stringAsLines(fs.readFileSync(path).toString()) # create a SequenceMatcher instance that diffs the two sets of lines sm = new diffLib.SequenceMatcher(base, newtxt) # get the opcodes from the SequenceMatcher instance # opcodes is a list of 3-tuples describing what changes should be made to the base text # in order to yield the new text opcodes = sm.get_opcodes() for opcode in opcodes if opcode[0] == 'insert' || opcode[0] == 'replace' diffStats.added += (opcode[2] - opcode[1]) + (opcode[4] - opcode[3]) if opcode[0] == 'delete' diffStats.deleted += (opcode[2] - opcode[1]) - (opcode[4] - opcode[3]) return diffStats # Public: Retrieves the line diffs comparing the `HEAD` version of the given # path and the given text. # # * `lastRevFileContent` filecontent from latest hg revision. # * `text` The {String} to compare against the `HEAD` contents # # Returns an {Array} of hunk {Object}s with the following keys: # * `oldStart` The line {Number} of the old hunk. # * `newStart` The line {Number} of the new hunk. # * `oldLines` The {Number} of lines in the old hunk. # * `newLines` The {Number} of lines in the new hunk getLineDiffs: (lastRevFileContent, text, options) -> hunks = [] if (lastRevFileContent?) base = diffLib.stringAsLines(lastRevFileContent) newtxt = diffLib.stringAsLines(text) # create a SequenceMatcher instance that diffs the two sets of lines sm = new diffLib.SequenceMatcher(base, newtxt) # get the opcodes from the SequenceMatcher instance # opcodes is a list of 3-tuples describing what changes should be made to the base text # in order to yield the new text opcodes = sm.get_opcodes() actions = ['replace', 'insert', 'delete'] for opcode in opcodes if actions.indexOf(opcode[0]) >= 0 hunk = { oldStart: opcode[1] + 1 oldLines: opcode[2] - opcode[1] newStart: opcode[3] + 1 newLines: opcode[4] - opcode[3] } if opcode[0] == 'delete' hunk.newStart = hunk.newStart - 1 hunks.push(hunk) return hunks ### Section: Mercurial Command handling ### # Spawns an hg command and returns stdout or throws an error if process # exits with an exitcode unequal to zero. # # * `params` The {Array} for commandline arguments # # Returns a {String} of process stdout hgCommand: (params) -> if !params params = [] if !util.isArray(params) params = [params] if !@isCommandForRepo(params) return '' child = spawnSync('hg', params, { cwd: @rootPath }) if child.status != 0 if child.stderr throw new Error(child.stderr.toString()) if child.stdout throw new Error(child.stdout.toString()) throw new Error('Error trying to execute Mercurial binary with params \'' + params + '\'') return child.stdout.toString() hgCommandAsync: (params) -> if !params params = [] if !util.isArray(params) params = [params] if !@isCommandForRepo(params) return Promise.resolve('') flatArgs = params.reduce (prev, next) -> if next.indexOf? and next.indexOf(' ') != -1 next = "\"" + next + "\"" prev + " " + next , "" flatArgs = flatArgs.substring(1) return new Promise (resolve, reject) => opts = cwd: @rootPath maxBuffer: 50 * 1024 * 1024 child = exec 'hg ' + flatArgs, opts, (err, stdout, stderr) -> if err reject err if stderr?.length > 0 reject stderr resolve stdout handleHgError: (error) -> logMessage = true message = error.message for suppressHgWarning in suppressHgWarnings if message.indexOf(suppressHgWarning) > 0 logMessage = false break if logMessage console.error('Mercurial', 'hg-utils', error) # Returns on success the version from the hg binary. Otherwise null. # # Returns a {String} containing the hg-binary version getHgVersion: () -> try version = @hgCommand(['--version', '--quiet']) return version.trim() catch error @handleHgError(error) return null # Returns on success the current working copy revision. Otherwise null. # # Returns a {Promise} of a {String} with the current working copy revision getHgWorkingCopyRevisionAsync: () => @hgCommandAsync(['id', '-i', @rootPath]).catch (error) => @handleHgError(error) return null getRecursiveIgnoreStatuses: () -> revision = @diffRevisionProvider() @hgCommandAsync(['status', @rootPath, "-i", "--rev", revision]) .then (files) => items = [] entries = files.split('\n') if entries for entry in entries parts = entry.split(' ') status = parts[0] pathPart = parts[1] if pathPart? && status? if (status is 'I') # || status is '?') items.push(pathPart.replace('..', '')) (path.join @rootPath, item for item in items) .catch (error) => @handleHgError error [] getHgStatusAsync: () -> revision = @diffRevisionProvider() @hgCommandAsync(['status', @rootPath, '--rev', revision]).then (files) => items = [] entries = files.split('\n') if entries for entry in entries parts = entry.split(' ') status = parts[0] pathPart = parts[1] if pathPart? && status? items.push({ 'path': path.join @rootPath, pathPart 'status': @mapHgStatus(status) }) return items .catch (error) => @handleHgError(error) return null # Returns on success the list of tags for this revision. Otherwise null. # # Returns a {Primise} of an {Array} of {String}s representing the status getHgTagsAsync: () -> @hgCommandAsync(['id', '-t', @rootPath]).then (tags) -> tags = tags.trim() return tags.split(' ').sort() if tags .catch (error) => @handleHgError(error) return null # Returns on success a status bitmask. Otherwise null. # # * `hgPath` The path {String} for the status inquiry # # Returns a {Number} representing the status getHgPathStatus: (hgPath) -> return null unless hgPath try revision = @diffRevisionProvider() files = @hgCommand(['status', hgPath, '--rev', revision]) catch error @handleHgError(error) return null items = [] entries = files.split('\n') if entries path_status = 0 for entry in entries parts = entry.split(' ') status = parts[0] pathPart = parts[1] if status? path_status |= @mapHgStatus(status) return path_status else return null # Translates the status {String} from `hg status` command into a # status {Number}. # # * `status` The status {String} from `hg status` command # # Returns a {Number} representing the status mapHgStatus: (status) -> return 0 unless status statusBitmask = 0 # status workingdir if status == 'M' statusBitmask = statusWorkingDirModified if status == '?' statusBitmask = statusWorkingDirNew if status == '!' statusBitmask = statusWorkingDirDelete if status == 'I' statusBitmask = statusIgnored if status == 'M' statusBitmask = statusWorkingDirTypeChange # status index if status == 'A' statusBitmask = statusIndexNew if status == 'R' statusBitmask = statusIndexDeleted return statusBitmask # This retrieves the contents of the hgpath from the diff revision on success. # Otherwise null. # # * `hgPath` The path {String} # # Returns {Promise} of a {String} with the filecontent getHgCatAsync: (hgPath) -> revision = @diffRevisionProvider() params = ['cat', hgPath, '--rev', revision] return @hgCommandAsync(params).catch (error) => if /no such file in rev/.test(error) return null @handleHgError error return null # This checks to see if the current params indicate whether we are working # with the current repository. # # * `params` The params that are going to be sent to the hg command {Array} # # Returns a {Boolean} indicating if the rootPath was found in the params isCommandForRepo: (params) -> rootPath = @rootPath paths = params.filter (param) -> normalizedPath = path.normalize((param || '')) return normalizedPath.startsWith(rootPath) return paths.length > 0 exports.isStatusModified = (status) -> return (status & modifiedStatusFlags) > 0 exports.isStatusNew = (status) -> return (status & newStatusFlags) > 0 exports.isStatusDeleted = (status) -> return (status & deletedStatusFlags) > 0 exports.isStatusIgnored = (status) -> return (status & statusIgnored) > 0 exports.isStatusStaged = (status) -> return (status & statusWorkingDirNew) == 0 # creates and returns a new {Repository} object if hg-binary could be found # and several infos from are successfully read. Otherwise null. # # * `repositoryPath` The path {String} to the repository root directory # # Returns a new {Repository} object openRepository = (repositoryPath, diffRevisionProvider) -> repository = new Repository(repositoryPath) if repository.checkBinaryAvailable() and repository.exists() repository.diffRevisionProvider = diffRevisionProvider return repository else return null exports.open = (repositoryPath, diffRevisionProvider) -> return openRepository(repositoryPath, diffRevisionProvider) # Verifies if given path is a symbolic link. # Returns original path or null otherwise. resolveSymlink = (repositoryPath) -> lstat = fs.lstatSync(repositoryPath) unless lstat.isSymbolicLink() return null return fs.realpathSync(repositoryPath) exports.resolveSymlink = (repositoryPath) -> return resolveSymlink(repositoryPath)
[ { "context": "ptions', 4, ->\n product1 = new @Product(name: \"testA\", cost: 20)\n product2 = new @Product(name: \"te", "end": 605, "score": 0.9799554347991943, "start": 600, "tag": "NAME", "value": "testA" }, { "context": "tA\", cost: 20)\n product2 = new @Product(name: \"testB\", cost: 10)\n @adapter.perform 'create', produc", "end": 658, "score": 0.9840103387832642, "start": 653, "tag": "NAME", "value": "testB" }, { "context": " deepEqual readProducts[0].get('name'), \"testB\"\n @adapter.perform 'readAll', product1.c", "end": 1083, "score": 0.607305109500885, "start": 1078, "tag": "NAME", "value": "testB" }, { "context": " deepEqual readProducts[0].get('name'), \"testA\"\n QUnit.start()\n", "end": 1315, "score": 0.5909738540649414, "start": 1310, "tag": "NAME", "value": "testA" } ]
tests/batman/storage_adapter/local_storage_test.coffee
amco/batman
0
if typeof require isnt 'undefined' {sharedStorageTestSuite} = require('./storage_adapter_helper') else {sharedStorageTestSuite} = window if typeof window.localStorage isnt 'undefined' QUnit.module "Batman.LocalStorage", setup: -> window.localStorage.clear() class @Product extends Batman.Model @encode 'name', 'cost' @adapter = new Batman.LocalStorage(@Product) @Product.persist @adapter sharedStorageTestSuite({}) asyncTest 'reading many from storage: should callback with only records matching the options', 4, -> product1 = new @Product(name: "testA", cost: 20) product2 = new @Product(name: "testB", cost: 10) @adapter.perform 'create', product1, {}, (err, createdRecord1) => throw err if err @adapter.perform 'create', product2, {}, (err, createdRecord2) => throw err if err @adapter.perform 'readAll', product1.constructor, {data: {cost: 10}}, (err, readProducts) => throw err if err equal readProducts.length, 1 deepEqual readProducts[0].get('name'), "testB" @adapter.perform 'readAll', product1.constructor, {data: {cost: 20}}, (err, readProducts) -> throw err if err equal readProducts.length, 1 deepEqual readProducts[0].get('name'), "testA" QUnit.start()
66095
if typeof require isnt 'undefined' {sharedStorageTestSuite} = require('./storage_adapter_helper') else {sharedStorageTestSuite} = window if typeof window.localStorage isnt 'undefined' QUnit.module "Batman.LocalStorage", setup: -> window.localStorage.clear() class @Product extends Batman.Model @encode 'name', 'cost' @adapter = new Batman.LocalStorage(@Product) @Product.persist @adapter sharedStorageTestSuite({}) asyncTest 'reading many from storage: should callback with only records matching the options', 4, -> product1 = new @Product(name: "<NAME>", cost: 20) product2 = new @Product(name: "<NAME>", cost: 10) @adapter.perform 'create', product1, {}, (err, createdRecord1) => throw err if err @adapter.perform 'create', product2, {}, (err, createdRecord2) => throw err if err @adapter.perform 'readAll', product1.constructor, {data: {cost: 10}}, (err, readProducts) => throw err if err equal readProducts.length, 1 deepEqual readProducts[0].get('name'), "<NAME>" @adapter.perform 'readAll', product1.constructor, {data: {cost: 20}}, (err, readProducts) -> throw err if err equal readProducts.length, 1 deepEqual readProducts[0].get('name'), "<NAME>" QUnit.start()
true
if typeof require isnt 'undefined' {sharedStorageTestSuite} = require('./storage_adapter_helper') else {sharedStorageTestSuite} = window if typeof window.localStorage isnt 'undefined' QUnit.module "Batman.LocalStorage", setup: -> window.localStorage.clear() class @Product extends Batman.Model @encode 'name', 'cost' @adapter = new Batman.LocalStorage(@Product) @Product.persist @adapter sharedStorageTestSuite({}) asyncTest 'reading many from storage: should callback with only records matching the options', 4, -> product1 = new @Product(name: "PI:NAME:<NAME>END_PI", cost: 20) product2 = new @Product(name: "PI:NAME:<NAME>END_PI", cost: 10) @adapter.perform 'create', product1, {}, (err, createdRecord1) => throw err if err @adapter.perform 'create', product2, {}, (err, createdRecord2) => throw err if err @adapter.perform 'readAll', product1.constructor, {data: {cost: 10}}, (err, readProducts) => throw err if err equal readProducts.length, 1 deepEqual readProducts[0].get('name'), "PI:NAME:<NAME>END_PI" @adapter.perform 'readAll', product1.constructor, {data: {cost: 20}}, (err, readProducts) -> throw err if err equal readProducts.length, 1 deepEqual readProducts[0].get('name'), "PI:NAME:<NAME>END_PI" QUnit.start()
[ { "context": "eys(env.languages).forEach (lang) =>\n key = \"language#{lang.toUpperCase()}\"\n val = @langIsSet(lang)\n @set(key, val)", "end": 161, "score": 0.990720272064209, "start": 131, "tag": "KEY", "value": "language#{lang.toUpperCase()}\"" }, { "context": "eys(env.languages).forEach (lang) =>\n key = \"language#{lang.toUpperCase()}\"\n newLangs.push(lang) if @get(key)\n\n newVa", "end": 458, "score": 0.98497074842453, "start": 428, "tag": "KEY", "value": "language#{lang.toUpperCase()}\"" }, { "context": "eys(env.languages).forEach (lang) =>\n key = \"language#{lang.toUpperCase()}\"\n @addObserver(key, -> Ember.run.scheduleOnce", "end": 730, "score": 0.993918240070343, "start": 700, "tag": "KEY", "value": "language#{lang.toUpperCase()}\"" } ]
app/assets/javascripts/mixins/language_settings.js.coffee
fwoeck/voice-rails
1
Voice.LanguageSettings = Ember.Mixin.create({ splitLanguages: ( -> Ember.keys(env.languages).forEach (lang) => key = "language#{lang.toUpperCase()}" val = @langIsSet(lang) @set(key, val) if @get(key) != val ).observes('languages.[]') langIsSet: (lang) -> @get('languages').indexOf(lang) > -1 joinLanguages: -> newLangs = [] Ember.keys(env.languages).forEach (lang) => key = "language#{lang.toUpperCase()}" newLangs.push(lang) if @get(key) newVal = newLangs.sort() @set('languages', newVal) if Ember.compare(newVal, @get 'languages') observeLanguages: -> self = @ Ember.keys(env.languages).forEach (lang) => key = "language#{lang.toUpperCase()}" @addObserver(key, -> Ember.run.scheduleOnce 'actions', self, self.joinLanguages) })
142024
Voice.LanguageSettings = Ember.Mixin.create({ splitLanguages: ( -> Ember.keys(env.languages).forEach (lang) => key = "<KEY> val = @langIsSet(lang) @set(key, val) if @get(key) != val ).observes('languages.[]') langIsSet: (lang) -> @get('languages').indexOf(lang) > -1 joinLanguages: -> newLangs = [] Ember.keys(env.languages).forEach (lang) => key = "<KEY> newLangs.push(lang) if @get(key) newVal = newLangs.sort() @set('languages', newVal) if Ember.compare(newVal, @get 'languages') observeLanguages: -> self = @ Ember.keys(env.languages).forEach (lang) => key = "<KEY> @addObserver(key, -> Ember.run.scheduleOnce 'actions', self, self.joinLanguages) })
true
Voice.LanguageSettings = Ember.Mixin.create({ splitLanguages: ( -> Ember.keys(env.languages).forEach (lang) => key = "PI:KEY:<KEY>END_PI val = @langIsSet(lang) @set(key, val) if @get(key) != val ).observes('languages.[]') langIsSet: (lang) -> @get('languages').indexOf(lang) > -1 joinLanguages: -> newLangs = [] Ember.keys(env.languages).forEach (lang) => key = "PI:KEY:<KEY>END_PI newLangs.push(lang) if @get(key) newVal = newLangs.sort() @set('languages', newVal) if Ember.compare(newVal, @get 'languages') observeLanguages: -> self = @ Ember.keys(env.languages).forEach (lang) => key = "PI:KEY:<KEY>END_PI @addObserver(key, -> Ember.run.scheduleOnce 'actions', self, self.joinLanguages) })
[ { "context": "# WiFi SSID Widget\n#\n# Joe Kelley\n#\n# This widget displays the current connected Wi", "end": 33, "score": 0.9998694658279419, "start": 23, "tag": "NAME", "value": "Joe Kelley" } ]
wifi-network.coffee
Johngeorgesample/dhyanabar
2
# WiFi SSID Widget # # Joe Kelley # # This widget displays the current connected WiFi network name. It can be helpful if you are in an environment where multiple networks are available. # It uses the built-in OS X airport framework to get and display the SSID name (up to 20 characters in length) command: "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | grep ' SSID' | cut -c 18-38" refreshFrequency: 10000 # Adjust the style settings to suit. I've set the position to be just below the WiFi icon in my menu bar. style: """ -webkit-font-smoothing: antialiased color: #eee8d5 font: 11px Menlo right: 410px top: 14px span color: #aaa """ render: (output) -> "wifi <span>#{output}</span>"
90985
# WiFi SSID Widget # # <NAME> # # This widget displays the current connected WiFi network name. It can be helpful if you are in an environment where multiple networks are available. # It uses the built-in OS X airport framework to get and display the SSID name (up to 20 characters in length) command: "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | grep ' SSID' | cut -c 18-38" refreshFrequency: 10000 # Adjust the style settings to suit. I've set the position to be just below the WiFi icon in my menu bar. style: """ -webkit-font-smoothing: antialiased color: #eee8d5 font: 11px Menlo right: 410px top: 14px span color: #aaa """ render: (output) -> "wifi <span>#{output}</span>"
true
# WiFi SSID Widget # # PI:NAME:<NAME>END_PI # # This widget displays the current connected WiFi network name. It can be helpful if you are in an environment where multiple networks are available. # It uses the built-in OS X airport framework to get and display the SSID name (up to 20 characters in length) command: "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | grep ' SSID' | cut -c 18-38" refreshFrequency: 10000 # Adjust the style settings to suit. I've set the position to be just below the WiFi icon in my menu bar. style: """ -webkit-font-smoothing: antialiased color: #eee8d5 font: 11px Menlo right: 410px top: 14px span color: #aaa """ render: (output) -> "wifi <span>#{output}</span>"
[ { "context": "'/shops').\n send({name: 'Shop name', email: 'myshop@email.com', password: '123456'}).\n end (err, res) ->\n ", "end": 451, "score": 0.9999238848686218, "start": 435, "tag": "EMAIL", "value": "myshop@email.com" }, { "context": "Shop name', email: 'myshop@email.com', password: '123456'}).\n end (err, res) ->\n shopIdentifie", "end": 471, "score": 0.9993111491203308, "start": 465, "tag": "PASSWORD", "value": "123456" }, { "context": "\n get(apiPreffix + '/shops/emailexists?email=myshop@email.com').\n end (err, res) ->\n res.should.hav", "end": 871, "score": 0.9999160170555115, "start": 855, "tag": "EMAIL", "value": "myshop@email.com" }, { "context": "\n get(apiPreffix + '/shops/emailexists?email=mynonexistantshop@email.com').\n end (err, res) ->\n res.should.hav", "end": 1116, "score": 0.9999197721481323, "start": 1089, "tag": "EMAIL", "value": "mynonexistantshop@email.com" }, { "context": "apiPreffix + '/shops/login').\n send({email: 'myshop@email.com', password: '123456'}).\n end (err, res) ->\n ", "end": 1663, "score": 0.9999237656593323, "start": 1647, "tag": "EMAIL", "value": "myshop@email.com" }, { "context": " send({email: 'myshop@email.com', password: '123456'}).\n end (err, res) ->\n res.should.ha", "end": 1683, "score": 0.9993013739585876, "start": 1677, "tag": "PASSWORD", "value": "123456" }, { "context": " = new Shop\n name: 'new shop',\n email: 'mail@gertuproject.info',\n password: '123456'\n\n newShop.save()\n\n ", "end": 1886, "score": 0.9999312162399292, "start": 1864, "tag": "EMAIL", "value": "mail@gertuproject.info" }, { "context": "email: 'mail@gertuproject.info',\n password: '123456'\n\n newShop.save()\n\n server.\n get('/adm", "end": 1912, "score": 0.9993472099304199, "start": 1906, "tag": "PASSWORD", "value": "123456" }, { "context": "apiPreffix + '/shops/login').\n send({email: 'mynonexistantshop@email.com', password: '123456789'}).\n end (err, res) -", "end": 2331, "score": 0.9999165534973145, "start": 2304, "tag": "EMAIL", "value": "mynonexistantshop@email.com" }, { "context": "{email: 'mynonexistantshop@email.com', password: '123456789'}).\n end (err, res) ->\n res.should.ha", "end": 2354, "score": 0.9993073344230652, "start": 2345, "tag": "PASSWORD", "value": "123456789" }, { "context": "'/shops').\n send({name: 'Shop name', email: 'mail@gertuproject.info', password: '123456'}).\n end (err, res) ->\n ", "end": 3100, "score": 0.9999315738677979, "start": 3078, "tag": "EMAIL", "value": "mail@gertuproject.info" }, { "context": "ame', email: 'mail@gertuproject.info', password: '123456'}).\n end (err, res) ->\n res.should.ha", "end": 3120, "score": 0.9993741512298584, "start": 3114, "tag": "PASSWORD", "value": "123456" } ]
test/shop/api.coffee
gertu/gertu
1
should = require "should" app = require "../../server" mongoose = require "mongoose" request = require "supertest" Shop = mongoose.model "Shop" server = request.agent(app) apiPreffix = '/api/v1' describe "General shop testing", -> after (done) -> Shop.remove().exec() done() it "should signup a new shop", (done) -> server. post(apiPreffix + '/shops'). send({name: 'Shop name', email: 'myshop@email.com', password: '123456'}). end (err, res) -> shopIdentifier = res._id res.should.have.status 200 done() it "should find just one shop in database", (done) -> Shop.find {}, (error, shops) -> shops.should.have.length 1 done() it "should mark an existant email for a shop as existant", (done) -> server. get(apiPreffix + '/shops/emailexists?email=myshop@email.com'). end (err, res) -> res.should.have.status 200 done() it "should mark a non existant email for a shop as non existant", (done) -> server. get(apiPreffix + '/shops/emailexists?email=mynonexistantshop@email.com'). end (err, res) -> res.should.have.status 200 res.text.should.include 'False' done() it "should return error on verifying email existance when no email is passed", (done) -> server. get(apiPreffix + '/shops/emailexists?email='). end (err, res) -> res.should.have.status 422 done() it "should not be able to grant access to the newly created shop because it is not confirmed", (done) -> server. post(apiPreffix + '/shops/login'). send({email: 'myshop@email.com', password: '123456'}). end (err, res) -> res.should.have.status 403 done() it "should confirm a shop", (done) -> newShop = new Shop name: 'new shop', email: 'mail@gertuproject.info', password: '123456' newShop.save() server. get('/admin/confirmaccount/' + newShop._id). end (err, res) -> nextUrl = res.header.location res.should.have.status 302 nextUrl.should.include '/admin/profile?confirmed' done() it "should not let a non-existant shop to login", (done) -> server. post(apiPreffix + '/shops/login'). send({email: 'mynonexistantshop@email.com', password: '123456789'}). end (err, res) -> res.should.have.status 403 done() it "should not signup a new shop if provided data is invalid", (done) -> server. post(apiPreffix + '/shops'). send({name: '', email: '', password: ''}). end (err, res) -> res.should.have.status 422 done() it "should notify incorrect data when login with incomplete data", (done) -> server. post(apiPreffix + '/shops/login'). send({email: '', password: ''}). end (err, res) -> res.should.have.status 422 done() it "should send an email when signing up a new shop", (done) -> server. post(apiPreffix + '/shops'). send({name: 'Shop name', email: 'mail@gertuproject.info', password: '123456'}). end (err, res) -> res.should.have.status 200 done() after (done) -> Shop.remove().exec() done()
145865
should = require "should" app = require "../../server" mongoose = require "mongoose" request = require "supertest" Shop = mongoose.model "Shop" server = request.agent(app) apiPreffix = '/api/v1' describe "General shop testing", -> after (done) -> Shop.remove().exec() done() it "should signup a new shop", (done) -> server. post(apiPreffix + '/shops'). send({name: 'Shop name', email: '<EMAIL>', password: '<PASSWORD>'}). end (err, res) -> shopIdentifier = res._id res.should.have.status 200 done() it "should find just one shop in database", (done) -> Shop.find {}, (error, shops) -> shops.should.have.length 1 done() it "should mark an existant email for a shop as existant", (done) -> server. get(apiPreffix + '/shops/emailexists?email=<EMAIL>'). end (err, res) -> res.should.have.status 200 done() it "should mark a non existant email for a shop as non existant", (done) -> server. get(apiPreffix + '/shops/emailexists?email=<EMAIL>'). end (err, res) -> res.should.have.status 200 res.text.should.include 'False' done() it "should return error on verifying email existance when no email is passed", (done) -> server. get(apiPreffix + '/shops/emailexists?email='). end (err, res) -> res.should.have.status 422 done() it "should not be able to grant access to the newly created shop because it is not confirmed", (done) -> server. post(apiPreffix + '/shops/login'). send({email: '<EMAIL>', password: '<PASSWORD>'}). end (err, res) -> res.should.have.status 403 done() it "should confirm a shop", (done) -> newShop = new Shop name: 'new shop', email: '<EMAIL>', password: '<PASSWORD>' newShop.save() server. get('/admin/confirmaccount/' + newShop._id). end (err, res) -> nextUrl = res.header.location res.should.have.status 302 nextUrl.should.include '/admin/profile?confirmed' done() it "should not let a non-existant shop to login", (done) -> server. post(apiPreffix + '/shops/login'). send({email: '<EMAIL>', password: '<PASSWORD>'}). end (err, res) -> res.should.have.status 403 done() it "should not signup a new shop if provided data is invalid", (done) -> server. post(apiPreffix + '/shops'). send({name: '', email: '', password: ''}). end (err, res) -> res.should.have.status 422 done() it "should notify incorrect data when login with incomplete data", (done) -> server. post(apiPreffix + '/shops/login'). send({email: '', password: ''}). end (err, res) -> res.should.have.status 422 done() it "should send an email when signing up a new shop", (done) -> server. post(apiPreffix + '/shops'). send({name: 'Shop name', email: '<EMAIL>', password: '<PASSWORD>'}). end (err, res) -> res.should.have.status 200 done() after (done) -> Shop.remove().exec() done()
true
should = require "should" app = require "../../server" mongoose = require "mongoose" request = require "supertest" Shop = mongoose.model "Shop" server = request.agent(app) apiPreffix = '/api/v1' describe "General shop testing", -> after (done) -> Shop.remove().exec() done() it "should signup a new shop", (done) -> server. post(apiPreffix + '/shops'). send({name: 'Shop name', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI'}). end (err, res) -> shopIdentifier = res._id res.should.have.status 200 done() it "should find just one shop in database", (done) -> Shop.find {}, (error, shops) -> shops.should.have.length 1 done() it "should mark an existant email for a shop as existant", (done) -> server. get(apiPreffix + '/shops/emailexists?email=PI:EMAIL:<EMAIL>END_PI'). end (err, res) -> res.should.have.status 200 done() it "should mark a non existant email for a shop as non existant", (done) -> server. get(apiPreffix + '/shops/emailexists?email=PI:EMAIL:<EMAIL>END_PI'). end (err, res) -> res.should.have.status 200 res.text.should.include 'False' done() it "should return error on verifying email existance when no email is passed", (done) -> server. get(apiPreffix + '/shops/emailexists?email='). end (err, res) -> res.should.have.status 422 done() it "should not be able to grant access to the newly created shop because it is not confirmed", (done) -> server. post(apiPreffix + '/shops/login'). send({email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI'}). end (err, res) -> res.should.have.status 403 done() it "should confirm a shop", (done) -> newShop = new Shop name: 'new shop', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' newShop.save() server. get('/admin/confirmaccount/' + newShop._id). end (err, res) -> nextUrl = res.header.location res.should.have.status 302 nextUrl.should.include '/admin/profile?confirmed' done() it "should not let a non-existant shop to login", (done) -> server. post(apiPreffix + '/shops/login'). send({email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI'}). end (err, res) -> res.should.have.status 403 done() it "should not signup a new shop if provided data is invalid", (done) -> server. post(apiPreffix + '/shops'). send({name: '', email: '', password: ''}). end (err, res) -> res.should.have.status 422 done() it "should notify incorrect data when login with incomplete data", (done) -> server. post(apiPreffix + '/shops/login'). send({email: '', password: ''}). end (err, res) -> res.should.have.status 422 done() it "should send an email when signing up a new shop", (done) -> server. post(apiPreffix + '/shops'). send({name: 'Shop name', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI'}). end (err, res) -> res.should.have.status 200 done() after (done) -> Shop.remove().exec() done()
[ { "context": "\"|NACHOS\"+\n \"|NOM|NOMS\"+\n \"|POUNCE\" +\n \"|RICK ROLL WIT\" +\n \"|ROUND|ROYGEEBIF2|STRAIGHT\"+\n \"|SHOUT\"", "end": 3100, "score": 0.8411104083061218, "start": 3087, "tag": "NAME", "value": "RICK ROLL WIT" } ]
grammars/lulzcode.cson
ANDnXOR/atom-lulzcode
1
fileTypes: [ "lulz" ] name: "Lolcode" patterns: [ { captures: "1": name: "storage.type.function.lol" "2": name: "entity.name.function.lol" "3": name: "punctuation.definition.parameters.begin.lol" "4": name: "variable.parameter.function.lol" "6": name: "punctuation.definition.parameters.begin.lol" "7": name: "variable.parameter.function.lol" comment: "match stuff like: HOW DUZ I <function name> [YR <argument1> [AN YR <argument2> ...]]" match: "(HOW IZ I)\\s([a-zA-Z][\\w]*)\\s(YR)\\s(\\w*)(\\s(AN YR)\\s(\\w*))*" name: "meta.function.lol" } { comment: "closing a function" match: "(IF U SAY SO|HOW IZ I)" name: "storage.type.function.lol" } { match: "\\b(HAI|KTHXBYE|I HAS A|HAS A|ITZ A|ITZ|R|IM IN YR|IM OUTTA YR|TIL|WILE|PLZ|AWSUM THX|O RLY?|YA RLY|NO WAI|MEBBE|OIC|WTF?|OMG|OMGWTF|FOUND YR|GTFO|AN YR|BOTH SAEM|SRS|YR)\\b" name: "keyword.control.lol" } { match: "\\b(ITZ)\\b" name: "keyword.operator.assignment.lol" } { match: "\\b(BOTH SAEM|AN|DIFFRINT)\\b" name: "keyword.operator.comparison.lol" } { match: "\\b(SUM OF|DIFF OF|PRODUKT OF|QUOSHUNT OF|MOD OF|BIGGR OF|SMALLR OF|IN MAH)\\b" name: "keyword.operator.arithmetic.lol" } { match: "\\b(BOTH OF|EITHER OF|WON OF|NOT|ALL OF|ANY OF)\\b" name: "keyword.operator.logical.lol" } { match: "\\b(UPPIN|NERFIN)\\b" name: "keyword.operator.increment-decrement.lol" } { match: "\\b(WIN)\\b" name: "constant.language.boolean.true.lol" } { match: "\\b(FAIL)\\b" name: "constant.language.boolean.false.lol" } { match: "\\b(YARN|NUMBR|NUMBAR|TROOF|BUKKIT|NOOB|LETR)\\b" name: "storage.type.lol" } { match: "\\b(PLZ|O NOES|O WEL|RTFM)\\b" name: "keyword.control.catch-exception.lol" } { begin: "\"" end: "\"" name: "string.quoted.double.lol" patterns: [ { match: "\\\\\\\\." name: "constant.character.escape.lol" } ] } { captures: "1": name: "punctuation.definition.comment.lol" match: "(BTW).*$\\n?" name: "comment.line.btw.lol" } { begin: "\\b(OBTW)\\b" captures: "0": name: "punctuation.definition.comment.lol" end: "(TLDR)\\n?" name: "comment.block.lol" } { match: "\\b(PLZ|O NOES|O WEL|KTHX|DO NOT WANT)\\b" name: "keyword.control.catch-exception.lol" } { match: "\\b(VISIBLE|BYES|DIAF|GIMMEH|SMOOSH|MKAY|CAN HAS|I IZ"+ "|BLINK|BLINKIES|LOLOL|WINK"+ "|MAEK"+ "|FREND"+ "|ALL|BOX|CATINABOX"+ "|CATINAROUND"+ "|CRAYON"+ "|CRAZY GO NUTS"+ "|CUT|GNAW"+ "|DAB"+ "|DOT"+ "|HOLLABACK"+ "|HSSSVEE2|HSSSVEE2BLINKY"+ "|HOW BIG|HOW SPREAD|HOW WIDE|HOW TALL"+ "|HOW MANY IN"+ "|INSIDEZ"+ "|KATNIP"+ "|BAD KITTEH|KITTEH"+ "|KOUNT"+ "|L33T|CHEEZBURGER"+ "|LOLOLOL"+ "|MAH|LAZER|MEOW|PAWS"+ "|MEMBER|OHIMEMBER" + "|MEOWMIX"+ "|NACHOS"+ "|NOM|NOMS"+ "|POUNCE" + "|RICK ROLL WIT" + "|ROUND|ROYGEEBIF2|STRAIGHT"+ "|SHOUT"+ "|SYSTUM"+ "|TEH" + "|TROLL" + "|WHATSUP|WHATSDOWN|ISLEFF|ISRIGHT|WATTA|WATTB|ISGO" + "|WHO DIS|SAY WUT"+ "|YO"+ ")\\b" name: "support.function.lol" } { match: "\\b(IT)\\b" name: "variable.language.lol" } { match: "\\b(BLUEISH"+ "|DARK"+ "|DARKISH"+ "|GREENISH"+ "|YELLOWISH"+ "|REDISH"+ "|LIGHT"+ "|HACKER_RED|HACKER_GREEN|HACKER_BLUE|HACKER_GRAY)\\b" name: "constant.language.color" } { match: "\\b(HOW WIDE"+ "|HOW TALL"+ "|BADGEZ?"+ "|OUTWAYZ|SIDEWAYZ|UPWAYZ|TILTZ"+ "|TIX"+ "|WHOAMI?"+ "|VERSHUN"+ ")\\b" name: "constant.language.value" } ] scopeName: "source.lol"
110901
fileTypes: [ "lulz" ] name: "Lolcode" patterns: [ { captures: "1": name: "storage.type.function.lol" "2": name: "entity.name.function.lol" "3": name: "punctuation.definition.parameters.begin.lol" "4": name: "variable.parameter.function.lol" "6": name: "punctuation.definition.parameters.begin.lol" "7": name: "variable.parameter.function.lol" comment: "match stuff like: HOW DUZ I <function name> [YR <argument1> [AN YR <argument2> ...]]" match: "(HOW IZ I)\\s([a-zA-Z][\\w]*)\\s(YR)\\s(\\w*)(\\s(AN YR)\\s(\\w*))*" name: "meta.function.lol" } { comment: "closing a function" match: "(IF U SAY SO|HOW IZ I)" name: "storage.type.function.lol" } { match: "\\b(HAI|KTHXBYE|I HAS A|HAS A|ITZ A|ITZ|R|IM IN YR|IM OUTTA YR|TIL|WILE|PLZ|AWSUM THX|O RLY?|YA RLY|NO WAI|MEBBE|OIC|WTF?|OMG|OMGWTF|FOUND YR|GTFO|AN YR|BOTH SAEM|SRS|YR)\\b" name: "keyword.control.lol" } { match: "\\b(ITZ)\\b" name: "keyword.operator.assignment.lol" } { match: "\\b(BOTH SAEM|AN|DIFFRINT)\\b" name: "keyword.operator.comparison.lol" } { match: "\\b(SUM OF|DIFF OF|PRODUKT OF|QUOSHUNT OF|MOD OF|BIGGR OF|SMALLR OF|IN MAH)\\b" name: "keyword.operator.arithmetic.lol" } { match: "\\b(BOTH OF|EITHER OF|WON OF|NOT|ALL OF|ANY OF)\\b" name: "keyword.operator.logical.lol" } { match: "\\b(UPPIN|NERFIN)\\b" name: "keyword.operator.increment-decrement.lol" } { match: "\\b(WIN)\\b" name: "constant.language.boolean.true.lol" } { match: "\\b(FAIL)\\b" name: "constant.language.boolean.false.lol" } { match: "\\b(YARN|NUMBR|NUMBAR|TROOF|BUKKIT|NOOB|LETR)\\b" name: "storage.type.lol" } { match: "\\b(PLZ|O NOES|O WEL|RTFM)\\b" name: "keyword.control.catch-exception.lol" } { begin: "\"" end: "\"" name: "string.quoted.double.lol" patterns: [ { match: "\\\\\\\\." name: "constant.character.escape.lol" } ] } { captures: "1": name: "punctuation.definition.comment.lol" match: "(BTW).*$\\n?" name: "comment.line.btw.lol" } { begin: "\\b(OBTW)\\b" captures: "0": name: "punctuation.definition.comment.lol" end: "(TLDR)\\n?" name: "comment.block.lol" } { match: "\\b(PLZ|O NOES|O WEL|KTHX|DO NOT WANT)\\b" name: "keyword.control.catch-exception.lol" } { match: "\\b(VISIBLE|BYES|DIAF|GIMMEH|SMOOSH|MKAY|CAN HAS|I IZ"+ "|BLINK|BLINKIES|LOLOL|WINK"+ "|MAEK"+ "|FREND"+ "|ALL|BOX|CATINABOX"+ "|CATINAROUND"+ "|CRAYON"+ "|CRAZY GO NUTS"+ "|CUT|GNAW"+ "|DAB"+ "|DOT"+ "|HOLLABACK"+ "|HSSSVEE2|HSSSVEE2BLINKY"+ "|HOW BIG|HOW SPREAD|HOW WIDE|HOW TALL"+ "|HOW MANY IN"+ "|INSIDEZ"+ "|KATNIP"+ "|BAD KITTEH|KITTEH"+ "|KOUNT"+ "|L33T|CHEEZBURGER"+ "|LOLOLOL"+ "|MAH|LAZER|MEOW|PAWS"+ "|MEMBER|OHIMEMBER" + "|MEOWMIX"+ "|NACHOS"+ "|NOM|NOMS"+ "|POUNCE" + "|<NAME>" + "|ROUND|ROYGEEBIF2|STRAIGHT"+ "|SHOUT"+ "|SYSTUM"+ "|TEH" + "|TROLL" + "|WHATSUP|WHATSDOWN|ISLEFF|ISRIGHT|WATTA|WATTB|ISGO" + "|WHO DIS|SAY WUT"+ "|YO"+ ")\\b" name: "support.function.lol" } { match: "\\b(IT)\\b" name: "variable.language.lol" } { match: "\\b(BLUEISH"+ "|DARK"+ "|DARKISH"+ "|GREENISH"+ "|YELLOWISH"+ "|REDISH"+ "|LIGHT"+ "|HACKER_RED|HACKER_GREEN|HACKER_BLUE|HACKER_GRAY)\\b" name: "constant.language.color" } { match: "\\b(HOW WIDE"+ "|HOW TALL"+ "|BADGEZ?"+ "|OUTWAYZ|SIDEWAYZ|UPWAYZ|TILTZ"+ "|TIX"+ "|WHOAMI?"+ "|VERSHUN"+ ")\\b" name: "constant.language.value" } ] scopeName: "source.lol"
true
fileTypes: [ "lulz" ] name: "Lolcode" patterns: [ { captures: "1": name: "storage.type.function.lol" "2": name: "entity.name.function.lol" "3": name: "punctuation.definition.parameters.begin.lol" "4": name: "variable.parameter.function.lol" "6": name: "punctuation.definition.parameters.begin.lol" "7": name: "variable.parameter.function.lol" comment: "match stuff like: HOW DUZ I <function name> [YR <argument1> [AN YR <argument2> ...]]" match: "(HOW IZ I)\\s([a-zA-Z][\\w]*)\\s(YR)\\s(\\w*)(\\s(AN YR)\\s(\\w*))*" name: "meta.function.lol" } { comment: "closing a function" match: "(IF U SAY SO|HOW IZ I)" name: "storage.type.function.lol" } { match: "\\b(HAI|KTHXBYE|I HAS A|HAS A|ITZ A|ITZ|R|IM IN YR|IM OUTTA YR|TIL|WILE|PLZ|AWSUM THX|O RLY?|YA RLY|NO WAI|MEBBE|OIC|WTF?|OMG|OMGWTF|FOUND YR|GTFO|AN YR|BOTH SAEM|SRS|YR)\\b" name: "keyword.control.lol" } { match: "\\b(ITZ)\\b" name: "keyword.operator.assignment.lol" } { match: "\\b(BOTH SAEM|AN|DIFFRINT)\\b" name: "keyword.operator.comparison.lol" } { match: "\\b(SUM OF|DIFF OF|PRODUKT OF|QUOSHUNT OF|MOD OF|BIGGR OF|SMALLR OF|IN MAH)\\b" name: "keyword.operator.arithmetic.lol" } { match: "\\b(BOTH OF|EITHER OF|WON OF|NOT|ALL OF|ANY OF)\\b" name: "keyword.operator.logical.lol" } { match: "\\b(UPPIN|NERFIN)\\b" name: "keyword.operator.increment-decrement.lol" } { match: "\\b(WIN)\\b" name: "constant.language.boolean.true.lol" } { match: "\\b(FAIL)\\b" name: "constant.language.boolean.false.lol" } { match: "\\b(YARN|NUMBR|NUMBAR|TROOF|BUKKIT|NOOB|LETR)\\b" name: "storage.type.lol" } { match: "\\b(PLZ|O NOES|O WEL|RTFM)\\b" name: "keyword.control.catch-exception.lol" } { begin: "\"" end: "\"" name: "string.quoted.double.lol" patterns: [ { match: "\\\\\\\\." name: "constant.character.escape.lol" } ] } { captures: "1": name: "punctuation.definition.comment.lol" match: "(BTW).*$\\n?" name: "comment.line.btw.lol" } { begin: "\\b(OBTW)\\b" captures: "0": name: "punctuation.definition.comment.lol" end: "(TLDR)\\n?" name: "comment.block.lol" } { match: "\\b(PLZ|O NOES|O WEL|KTHX|DO NOT WANT)\\b" name: "keyword.control.catch-exception.lol" } { match: "\\b(VISIBLE|BYES|DIAF|GIMMEH|SMOOSH|MKAY|CAN HAS|I IZ"+ "|BLINK|BLINKIES|LOLOL|WINK"+ "|MAEK"+ "|FREND"+ "|ALL|BOX|CATINABOX"+ "|CATINAROUND"+ "|CRAYON"+ "|CRAZY GO NUTS"+ "|CUT|GNAW"+ "|DAB"+ "|DOT"+ "|HOLLABACK"+ "|HSSSVEE2|HSSSVEE2BLINKY"+ "|HOW BIG|HOW SPREAD|HOW WIDE|HOW TALL"+ "|HOW MANY IN"+ "|INSIDEZ"+ "|KATNIP"+ "|BAD KITTEH|KITTEH"+ "|KOUNT"+ "|L33T|CHEEZBURGER"+ "|LOLOLOL"+ "|MAH|LAZER|MEOW|PAWS"+ "|MEMBER|OHIMEMBER" + "|MEOWMIX"+ "|NACHOS"+ "|NOM|NOMS"+ "|POUNCE" + "|PI:NAME:<NAME>END_PI" + "|ROUND|ROYGEEBIF2|STRAIGHT"+ "|SHOUT"+ "|SYSTUM"+ "|TEH" + "|TROLL" + "|WHATSUP|WHATSDOWN|ISLEFF|ISRIGHT|WATTA|WATTB|ISGO" + "|WHO DIS|SAY WUT"+ "|YO"+ ")\\b" name: "support.function.lol" } { match: "\\b(IT)\\b" name: "variable.language.lol" } { match: "\\b(BLUEISH"+ "|DARK"+ "|DARKISH"+ "|GREENISH"+ "|YELLOWISH"+ "|REDISH"+ "|LIGHT"+ "|HACKER_RED|HACKER_GREEN|HACKER_BLUE|HACKER_GRAY)\\b" name: "constant.language.color" } { match: "\\b(HOW WIDE"+ "|HOW TALL"+ "|BADGEZ?"+ "|OUTWAYZ|SIDEWAYZ|UPWAYZ|TILTZ"+ "|TIX"+ "|WHOAMI?"+ "|VERSHUN"+ ")\\b" name: "constant.language.value" } ] scopeName: "source.lol"
[ { "context": "\n test 'urlFor(App.Post, onlyPath: false, user: \"lance\", password: \"pollard\")', ->\n path = Tower.urlF", "end": 534, "score": 0.9991903305053711, "start": 529, "tag": "USERNAME", "value": "lance" }, { "context": ".Post, onlyPath: false, user: \"lance\", password: \"pollard\")', ->\n path = Tower.urlFor(App.Post, _.extend", "end": 555, "score": 0.9991974234580994, "start": 548, "tag": "PASSWORD", "value": "pollard" }, { "context": "extend defaultUrlOptions, onlyPath: false, user: \"lance\", password: \"pollard\")\n\n assert.equal path, \"h", "end": 654, "score": 0.998682975769043, "start": 649, "tag": "USERNAME", "value": "lance" }, { "context": "tions, onlyPath: false, user: \"lance\", password: \"pollard\")\n\n assert.equal path, \"http://lance:pollard@e", "end": 675, "score": 0.9991486668586731, "start": 668, "tag": "PASSWORD", "value": "pollard" } ]
test/cases/http/urlForTest.coffee
vjsingh/tower
1
require '../../config' post = null defaultUrlOptions = null describe 'urlFor', -> beforeEach -> post = new App.Post(id: 10) defaultUrlOptions = onlyPath: true, params: {} trailingSlash: false, host: "example.com" test 'urlFor(App.Post, onlyPath: false)', -> path = Tower.urlFor(App.Post, _.extend defaultUrlOptions, onlyPath: false) assert.equal path, "http://example.com/posts" test 'urlFor(App.Post, onlyPath: false, user: "lance", password: "pollard")', -> path = Tower.urlFor(App.Post, _.extend defaultUrlOptions, onlyPath: false, user: "lance", password: "pollard") assert.equal path, "http://lance:pollard@example.com/posts" test 'urlFor(App.Post)', -> path = Tower.urlFor(App.Post, defaultUrlOptions) assert.equal path, "/posts" test 'urlFor(post)', -> path = Tower.urlFor(post, defaultUrlOptions) assert.equal path, "/posts/10" test 'urlFor("admin", post)', -> path = Tower.urlFor("admin", post, defaultUrlOptions) assert.equal path, "/admin/posts/10" test 'urlFor(post, likeCount: 10)', -> path = Tower.urlFor(post, _.extend defaultUrlOptions, params: likeCount: 10) assert.equal path, "/posts/10?likeCount=10" test 'urlFor(post, likeCount: ">=": 10)', -> path = Tower.urlFor(post, _.extend defaultUrlOptions, params: likeCount: ">=": 10) assert.equal path, "/posts/10?likeCount=10..n" test 'urlFor(post, likeCount: ">=": 10, "<=": 100)', -> path = Tower.urlFor(post, _.extend defaultUrlOptions, params: likeCount: ">=": 10, "<=": 100) assert.equal path, "/posts/10?likeCount=10..100" test 'urlFor(post, likeCount: ">=": 10, "<=": 100)', -> path = Tower.urlFor(post, _.extend defaultUrlOptions, params: likeCount: ">=": 10, "<=": 100) assert.equal path, "/posts/10?likeCount=10..100" test 'urlFor(post, title: "Hello World", likeCount: ">=": 10, "<=": 100)', -> path = Tower.urlFor(post, _.extend defaultUrlOptions, params: title: "Hello World", likeCount: ">=": 10, "<=": 100) assert.equal path, "/posts/10?likeCount=10..100&title=Hello+World" test 'urlFor(post, [{title: /Rails/}, {likeCount: ">=": 10}])', -> #assert.equal path, "/posts/10?likeCount[1]=10..n&title[0]=/Rails/"
12428
require '../../config' post = null defaultUrlOptions = null describe 'urlFor', -> beforeEach -> post = new App.Post(id: 10) defaultUrlOptions = onlyPath: true, params: {} trailingSlash: false, host: "example.com" test 'urlFor(App.Post, onlyPath: false)', -> path = Tower.urlFor(App.Post, _.extend defaultUrlOptions, onlyPath: false) assert.equal path, "http://example.com/posts" test 'urlFor(App.Post, onlyPath: false, user: "lance", password: "<PASSWORD>")', -> path = Tower.urlFor(App.Post, _.extend defaultUrlOptions, onlyPath: false, user: "lance", password: "<PASSWORD>") assert.equal path, "http://lance:pollard@example.com/posts" test 'urlFor(App.Post)', -> path = Tower.urlFor(App.Post, defaultUrlOptions) assert.equal path, "/posts" test 'urlFor(post)', -> path = Tower.urlFor(post, defaultUrlOptions) assert.equal path, "/posts/10" test 'urlFor("admin", post)', -> path = Tower.urlFor("admin", post, defaultUrlOptions) assert.equal path, "/admin/posts/10" test 'urlFor(post, likeCount: 10)', -> path = Tower.urlFor(post, _.extend defaultUrlOptions, params: likeCount: 10) assert.equal path, "/posts/10?likeCount=10" test 'urlFor(post, likeCount: ">=": 10)', -> path = Tower.urlFor(post, _.extend defaultUrlOptions, params: likeCount: ">=": 10) assert.equal path, "/posts/10?likeCount=10..n" test 'urlFor(post, likeCount: ">=": 10, "<=": 100)', -> path = Tower.urlFor(post, _.extend defaultUrlOptions, params: likeCount: ">=": 10, "<=": 100) assert.equal path, "/posts/10?likeCount=10..100" test 'urlFor(post, likeCount: ">=": 10, "<=": 100)', -> path = Tower.urlFor(post, _.extend defaultUrlOptions, params: likeCount: ">=": 10, "<=": 100) assert.equal path, "/posts/10?likeCount=10..100" test 'urlFor(post, title: "Hello World", likeCount: ">=": 10, "<=": 100)', -> path = Tower.urlFor(post, _.extend defaultUrlOptions, params: title: "Hello World", likeCount: ">=": 10, "<=": 100) assert.equal path, "/posts/10?likeCount=10..100&title=Hello+World" test 'urlFor(post, [{title: /Rails/}, {likeCount: ">=": 10}])', -> #assert.equal path, "/posts/10?likeCount[1]=10..n&title[0]=/Rails/"
true
require '../../config' post = null defaultUrlOptions = null describe 'urlFor', -> beforeEach -> post = new App.Post(id: 10) defaultUrlOptions = onlyPath: true, params: {} trailingSlash: false, host: "example.com" test 'urlFor(App.Post, onlyPath: false)', -> path = Tower.urlFor(App.Post, _.extend defaultUrlOptions, onlyPath: false) assert.equal path, "http://example.com/posts" test 'urlFor(App.Post, onlyPath: false, user: "lance", password: "PI:PASSWORD:<PASSWORD>END_PI")', -> path = Tower.urlFor(App.Post, _.extend defaultUrlOptions, onlyPath: false, user: "lance", password: "PI:PASSWORD:<PASSWORD>END_PI") assert.equal path, "http://lance:pollard@example.com/posts" test 'urlFor(App.Post)', -> path = Tower.urlFor(App.Post, defaultUrlOptions) assert.equal path, "/posts" test 'urlFor(post)', -> path = Tower.urlFor(post, defaultUrlOptions) assert.equal path, "/posts/10" test 'urlFor("admin", post)', -> path = Tower.urlFor("admin", post, defaultUrlOptions) assert.equal path, "/admin/posts/10" test 'urlFor(post, likeCount: 10)', -> path = Tower.urlFor(post, _.extend defaultUrlOptions, params: likeCount: 10) assert.equal path, "/posts/10?likeCount=10" test 'urlFor(post, likeCount: ">=": 10)', -> path = Tower.urlFor(post, _.extend defaultUrlOptions, params: likeCount: ">=": 10) assert.equal path, "/posts/10?likeCount=10..n" test 'urlFor(post, likeCount: ">=": 10, "<=": 100)', -> path = Tower.urlFor(post, _.extend defaultUrlOptions, params: likeCount: ">=": 10, "<=": 100) assert.equal path, "/posts/10?likeCount=10..100" test 'urlFor(post, likeCount: ">=": 10, "<=": 100)', -> path = Tower.urlFor(post, _.extend defaultUrlOptions, params: likeCount: ">=": 10, "<=": 100) assert.equal path, "/posts/10?likeCount=10..100" test 'urlFor(post, title: "Hello World", likeCount: ">=": 10, "<=": 100)', -> path = Tower.urlFor(post, _.extend defaultUrlOptions, params: title: "Hello World", likeCount: ">=": 10, "<=": 100) assert.equal path, "/posts/10?likeCount=10..100&title=Hello+World" test 'urlFor(post, [{title: /Rails/}, {likeCount: ">=": 10}])', -> #assert.equal path, "/posts/10?likeCount[1]=10..n&title[0]=/Rails/"
[ { "context": " 'prefix': 'password'\n 'body': 'password = \"$1\"'\n\n 'auth url':\n 'prefix': 'auth_url'\n 'bo", "end": 3952, "score": 0.8276898860931396, "start": 3951, "tag": "PASSWORD", "value": "1" } ]
snippets/snippets.cson
awilkins/language-terraform
48
'.source.terraform': 'variable': 'prefix': 'variable' 'body': """ variable "$1" { default = "$2" }$3 """ 'variable-map': 'prefix': 'variable-map' 'body': """ variable "${1:name}" { type = "map" default = { ${3:key1} = "${4:val1}" ${5:key2} = "${6:val2}" } }$7 """ 'variable-string': 'prefix': 'variable-string' 'body': """ variable "${1:name}" { type = "string" default = "${2:value}" }$3 """ 'variable-list': 'prefix': 'variable-list' 'body': """ variable "${1:name}" { type = "list" default = ["${2:value1}", "${3:value1}"] }$4 """ 'provisioner': 'prefix': 'provisioner' 'body': """ provisioner "${1:name}" { ${2} } """ 'provider': 'prefix': 'provider' 'body': """ provider "${1:name}" { ${2} } """ 'provider-aws': 'prefix': 'provider-aws' 'body': """ provider "aws" { access_key = "${1}" secret_key = "${2}" region = "${3}" }${4} """ 'value': 'prefix': 'value' 'body': 'value = "$1"' 'tags': 'prefix': 'tags' 'body': """ tags { $1 = "$2" }$3 """ 'alias': 'prefix': 'alias' 'body': """ alias { $1 = "$2" }$3 """ 'ingress': 'prefix': 'ingress' 'body': """ ingress { from_port = $1 to_port = $2 protocol = "$3" cidr_blocks = ["$4"] }$5 """ 'egress': 'prefix': 'egress' 'body': """ egress { from_port = $1 to_port = $2 protocol = "$3" cidr_blocks = ["$4"] }$5 """ 'name': 'prefix': 'name' 'body': 'name = "$1"' 'description': 'prefix': 'description' 'body': 'description = "$1"' 'protocol': 'prefix': 'protocol' 'body': 'protocol = "$1"' 'resource': 'prefix': 'resource' 'body': """ resource "$1" "$2" { $3 }$4 """ 'email': 'prefix': 'email' 'body': 'email = "$1"' 'token': 'prefix': 'token' 'body': 'token = "$1"' 'region': 'prefix': 'region' 'body': 'region = "$1"' 'size': 'prefix': 'size' 'body': 'size = "$1"' 'ip address': 'prefix': 'ip_address' 'body': 'ip_address = "$1"' 'domain': 'prefix': 'domain' 'body': 'domain = "$1"' 'type': 'prefix': 'type' 'body': 'type = "$1"' 'module': 'prefix': 'module' 'body': """ module "$1" { source = "$2" }$3 """ 'module-path': 'prefix': 'module-path' 'body': """ module "${1:name}" { source = "${2:./modules/}" ${3} } """ 'module-git': 'prefix': 'module-git' 'body': """ module "${1:name}" { source = "github.com/${2:owner}/${3:repo}?${4:ref=}" ${5} } """ 'module-git-priv': 'prefix': 'module-git-priv' 'body': """ module "${1:name}" { source = "git::ssh://git@github.com/${2:owner}/${3:repo}.git${4:?ref=}" ${5} } """ 'secret key': 'prefix': 'secret_key' 'body': 'secret_key = "$1"' 'access key': 'prefix': 'access_key' 'body': 'access_key = "$1"' 'api url': 'prefix': 'api_url' 'body': 'api_url = "$1"' 'api key': 'prefix': 'api_key' 'body': 'api_key = "$1"' 'host': 'prefix': 'host' 'body': 'host = "$1"' 'image': 'prefix': 'image' 'body': 'image = "$1"' 'account file': 'prefix': 'account_file' 'body': 'account_file = "$1"' 'project': 'prefix': 'project' 'body': 'project = "$1"' 'user name': 'prefix': 'user_name' 'body': 'user_name = "$1"' 'tenant name': 'prefix': 'tenant_name' 'body': 'tenant_name = "$1"' 'user': 'prefix': 'user' 'body': 'user = "$1"' 'password': 'prefix': 'password' 'body': 'password = "$1"' 'auth url': 'prefix': 'auth_url' 'body': 'auth_url = "$1"' 'akey': 'prefix': 'akey' 'body': 'akey = "$1"' 'skey': 'prefix': 'skey' 'body': 'skey = "$1"' 'usesandbox': 'prefix': 'usesandbox' 'body': 'usesandbox = "$1"' 'domainid': 'prefix': 'domainid' 'body': 'domainid = "$1"' 'address': 'prefix': 'address' 'body': 'address = "$1"' 'path': 'prefix': 'path' 'body': 'path = "$1"' 'datacenter': 'prefix': 'datacenter' 'body': 'datacenter = "$1"' 'ami': 'prefix': 'ami' 'body': 'ami = "$1"' 'instance type': 'prefix': 'instance_type' 'body': 'instance_type = "$1"' 'listener': 'prefix': 'listener' 'body': """ listener { instance_port = $1 instance_protocol = "$2" lb_port = $3 lb_protocol = "$4" }$5 """ 'health check': 'prefix': 'health_check' 'body': """ health_check { healthy_threshold = $1 unhealthy_threshold = $2 timeout = $3 target = "$4" interval = $5 }$6 """
151379
'.source.terraform': 'variable': 'prefix': 'variable' 'body': """ variable "$1" { default = "$2" }$3 """ 'variable-map': 'prefix': 'variable-map' 'body': """ variable "${1:name}" { type = "map" default = { ${3:key1} = "${4:val1}" ${5:key2} = "${6:val2}" } }$7 """ 'variable-string': 'prefix': 'variable-string' 'body': """ variable "${1:name}" { type = "string" default = "${2:value}" }$3 """ 'variable-list': 'prefix': 'variable-list' 'body': """ variable "${1:name}" { type = "list" default = ["${2:value1}", "${3:value1}"] }$4 """ 'provisioner': 'prefix': 'provisioner' 'body': """ provisioner "${1:name}" { ${2} } """ 'provider': 'prefix': 'provider' 'body': """ provider "${1:name}" { ${2} } """ 'provider-aws': 'prefix': 'provider-aws' 'body': """ provider "aws" { access_key = "${1}" secret_key = "${2}" region = "${3}" }${4} """ 'value': 'prefix': 'value' 'body': 'value = "$1"' 'tags': 'prefix': 'tags' 'body': """ tags { $1 = "$2" }$3 """ 'alias': 'prefix': 'alias' 'body': """ alias { $1 = "$2" }$3 """ 'ingress': 'prefix': 'ingress' 'body': """ ingress { from_port = $1 to_port = $2 protocol = "$3" cidr_blocks = ["$4"] }$5 """ 'egress': 'prefix': 'egress' 'body': """ egress { from_port = $1 to_port = $2 protocol = "$3" cidr_blocks = ["$4"] }$5 """ 'name': 'prefix': 'name' 'body': 'name = "$1"' 'description': 'prefix': 'description' 'body': 'description = "$1"' 'protocol': 'prefix': 'protocol' 'body': 'protocol = "$1"' 'resource': 'prefix': 'resource' 'body': """ resource "$1" "$2" { $3 }$4 """ 'email': 'prefix': 'email' 'body': 'email = "$1"' 'token': 'prefix': 'token' 'body': 'token = "$1"' 'region': 'prefix': 'region' 'body': 'region = "$1"' 'size': 'prefix': 'size' 'body': 'size = "$1"' 'ip address': 'prefix': 'ip_address' 'body': 'ip_address = "$1"' 'domain': 'prefix': 'domain' 'body': 'domain = "$1"' 'type': 'prefix': 'type' 'body': 'type = "$1"' 'module': 'prefix': 'module' 'body': """ module "$1" { source = "$2" }$3 """ 'module-path': 'prefix': 'module-path' 'body': """ module "${1:name}" { source = "${2:./modules/}" ${3} } """ 'module-git': 'prefix': 'module-git' 'body': """ module "${1:name}" { source = "github.com/${2:owner}/${3:repo}?${4:ref=}" ${5} } """ 'module-git-priv': 'prefix': 'module-git-priv' 'body': """ module "${1:name}" { source = "git::ssh://git@github.com/${2:owner}/${3:repo}.git${4:?ref=}" ${5} } """ 'secret key': 'prefix': 'secret_key' 'body': 'secret_key = "$1"' 'access key': 'prefix': 'access_key' 'body': 'access_key = "$1"' 'api url': 'prefix': 'api_url' 'body': 'api_url = "$1"' 'api key': 'prefix': 'api_key' 'body': 'api_key = "$1"' 'host': 'prefix': 'host' 'body': 'host = "$1"' 'image': 'prefix': 'image' 'body': 'image = "$1"' 'account file': 'prefix': 'account_file' 'body': 'account_file = "$1"' 'project': 'prefix': 'project' 'body': 'project = "$1"' 'user name': 'prefix': 'user_name' 'body': 'user_name = "$1"' 'tenant name': 'prefix': 'tenant_name' 'body': 'tenant_name = "$1"' 'user': 'prefix': 'user' 'body': 'user = "$1"' 'password': 'prefix': 'password' 'body': 'password = "$<PASSWORD>"' 'auth url': 'prefix': 'auth_url' 'body': 'auth_url = "$1"' 'akey': 'prefix': 'akey' 'body': 'akey = "$1"' 'skey': 'prefix': 'skey' 'body': 'skey = "$1"' 'usesandbox': 'prefix': 'usesandbox' 'body': 'usesandbox = "$1"' 'domainid': 'prefix': 'domainid' 'body': 'domainid = "$1"' 'address': 'prefix': 'address' 'body': 'address = "$1"' 'path': 'prefix': 'path' 'body': 'path = "$1"' 'datacenter': 'prefix': 'datacenter' 'body': 'datacenter = "$1"' 'ami': 'prefix': 'ami' 'body': 'ami = "$1"' 'instance type': 'prefix': 'instance_type' 'body': 'instance_type = "$1"' 'listener': 'prefix': 'listener' 'body': """ listener { instance_port = $1 instance_protocol = "$2" lb_port = $3 lb_protocol = "$4" }$5 """ 'health check': 'prefix': 'health_check' 'body': """ health_check { healthy_threshold = $1 unhealthy_threshold = $2 timeout = $3 target = "$4" interval = $5 }$6 """
true
'.source.terraform': 'variable': 'prefix': 'variable' 'body': """ variable "$1" { default = "$2" }$3 """ 'variable-map': 'prefix': 'variable-map' 'body': """ variable "${1:name}" { type = "map" default = { ${3:key1} = "${4:val1}" ${5:key2} = "${6:val2}" } }$7 """ 'variable-string': 'prefix': 'variable-string' 'body': """ variable "${1:name}" { type = "string" default = "${2:value}" }$3 """ 'variable-list': 'prefix': 'variable-list' 'body': """ variable "${1:name}" { type = "list" default = ["${2:value1}", "${3:value1}"] }$4 """ 'provisioner': 'prefix': 'provisioner' 'body': """ provisioner "${1:name}" { ${2} } """ 'provider': 'prefix': 'provider' 'body': """ provider "${1:name}" { ${2} } """ 'provider-aws': 'prefix': 'provider-aws' 'body': """ provider "aws" { access_key = "${1}" secret_key = "${2}" region = "${3}" }${4} """ 'value': 'prefix': 'value' 'body': 'value = "$1"' 'tags': 'prefix': 'tags' 'body': """ tags { $1 = "$2" }$3 """ 'alias': 'prefix': 'alias' 'body': """ alias { $1 = "$2" }$3 """ 'ingress': 'prefix': 'ingress' 'body': """ ingress { from_port = $1 to_port = $2 protocol = "$3" cidr_blocks = ["$4"] }$5 """ 'egress': 'prefix': 'egress' 'body': """ egress { from_port = $1 to_port = $2 protocol = "$3" cidr_blocks = ["$4"] }$5 """ 'name': 'prefix': 'name' 'body': 'name = "$1"' 'description': 'prefix': 'description' 'body': 'description = "$1"' 'protocol': 'prefix': 'protocol' 'body': 'protocol = "$1"' 'resource': 'prefix': 'resource' 'body': """ resource "$1" "$2" { $3 }$4 """ 'email': 'prefix': 'email' 'body': 'email = "$1"' 'token': 'prefix': 'token' 'body': 'token = "$1"' 'region': 'prefix': 'region' 'body': 'region = "$1"' 'size': 'prefix': 'size' 'body': 'size = "$1"' 'ip address': 'prefix': 'ip_address' 'body': 'ip_address = "$1"' 'domain': 'prefix': 'domain' 'body': 'domain = "$1"' 'type': 'prefix': 'type' 'body': 'type = "$1"' 'module': 'prefix': 'module' 'body': """ module "$1" { source = "$2" }$3 """ 'module-path': 'prefix': 'module-path' 'body': """ module "${1:name}" { source = "${2:./modules/}" ${3} } """ 'module-git': 'prefix': 'module-git' 'body': """ module "${1:name}" { source = "github.com/${2:owner}/${3:repo}?${4:ref=}" ${5} } """ 'module-git-priv': 'prefix': 'module-git-priv' 'body': """ module "${1:name}" { source = "git::ssh://git@github.com/${2:owner}/${3:repo}.git${4:?ref=}" ${5} } """ 'secret key': 'prefix': 'secret_key' 'body': 'secret_key = "$1"' 'access key': 'prefix': 'access_key' 'body': 'access_key = "$1"' 'api url': 'prefix': 'api_url' 'body': 'api_url = "$1"' 'api key': 'prefix': 'api_key' 'body': 'api_key = "$1"' 'host': 'prefix': 'host' 'body': 'host = "$1"' 'image': 'prefix': 'image' 'body': 'image = "$1"' 'account file': 'prefix': 'account_file' 'body': 'account_file = "$1"' 'project': 'prefix': 'project' 'body': 'project = "$1"' 'user name': 'prefix': 'user_name' 'body': 'user_name = "$1"' 'tenant name': 'prefix': 'tenant_name' 'body': 'tenant_name = "$1"' 'user': 'prefix': 'user' 'body': 'user = "$1"' 'password': 'prefix': 'password' 'body': 'password = "$PI:PASSWORD:<PASSWORD>END_PI"' 'auth url': 'prefix': 'auth_url' 'body': 'auth_url = "$1"' 'akey': 'prefix': 'akey' 'body': 'akey = "$1"' 'skey': 'prefix': 'skey' 'body': 'skey = "$1"' 'usesandbox': 'prefix': 'usesandbox' 'body': 'usesandbox = "$1"' 'domainid': 'prefix': 'domainid' 'body': 'domainid = "$1"' 'address': 'prefix': 'address' 'body': 'address = "$1"' 'path': 'prefix': 'path' 'body': 'path = "$1"' 'datacenter': 'prefix': 'datacenter' 'body': 'datacenter = "$1"' 'ami': 'prefix': 'ami' 'body': 'ami = "$1"' 'instance type': 'prefix': 'instance_type' 'body': 'instance_type = "$1"' 'listener': 'prefix': 'listener' 'body': """ listener { instance_port = $1 instance_protocol = "$2" lb_port = $3 lb_protocol = "$4" }$5 """ 'health check': 'prefix': 'health_check' 'body': """ health_check { healthy_threshold = $1 unhealthy_threshold = $2 timeout = $3 target = "$4" interval = $5 }$6 """
[ { "context": "# acorn.js 0.0.0\n# (c) 2012 Juan Batiz-Benet, Ali Yahya, Daniel Windham\n# Acorn is freely dis", "end": 46, "score": 0.9998525381088257, "start": 30, "tag": "NAME", "value": "Juan Batiz-Benet" }, { "context": "# acorn.js 0.0.0\n# (c) 2012 Juan Batiz-Benet, Ali Yahya, Daniel Windham\n# Acorn is freely distributable ", "end": 57, "score": 0.9998564720153809, "start": 48, "tag": "NAME", "value": "Ali Yahya" }, { "context": ".js 0.0.0\n# (c) 2012 Juan Batiz-Benet, Ali Yahya, Daniel Windham\n# Acorn is freely distributable under the MIT li", "end": 73, "score": 0.9998607635498047, "start": 59, "tag": "NAME", "value": "Daniel Windham" }, { "context": "etails and documentation:\n# http://github.com/athenalabs/acorn-player\n\nacorn = (data) ->\n acorn.Model.wit", "end": 282, "score": 0.7938027381896973, "start": 275, "tag": "USERNAME", "value": "enalabs" } ]
coffee/src/acorn.coffee
athenalabs/acorn-player
11
# acorn.js 0.0.0 # (c) 2012 Juan Batiz-Benet, Ali Yahya, Daniel Windham # Acorn is freely distributable under the MIT license. # Inspired by github:gist. # Portions of code from Underscore.js and Backbone.js # For all details and documentation: # http://github.com/athenalabs/acorn-player acorn = (data) -> acorn.Model.withData data acorn.shells = {} acorn.player = {} acorn.player.controls = {}
211034
# acorn.js 0.0.0 # (c) 2012 <NAME>, <NAME>, <NAME> # Acorn is freely distributable under the MIT license. # Inspired by github:gist. # Portions of code from Underscore.js and Backbone.js # For all details and documentation: # http://github.com/athenalabs/acorn-player acorn = (data) -> acorn.Model.withData data acorn.shells = {} acorn.player = {} acorn.player.controls = {}
true
# acorn.js 0.0.0 # (c) 2012 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI # Acorn is freely distributable under the MIT license. # Inspired by github:gist. # Portions of code from Underscore.js and Backbone.js # For all details and documentation: # http://github.com/athenalabs/acorn-player acorn = (data) -> acorn.Model.withData data acorn.shells = {} acorn.player = {} acorn.player.controls = {}
[ { "context": "ect authors. All rights reserved.\n# Copyright 1996 John Maloney and Mario Wolczko.\n\n# This program is free softwa", "end": 91, "score": 0.9998623728752136, "start": 79, "tag": "NAME", "value": "John Maloney" }, { "context": "rights reserved.\n# Copyright 1996 John Maloney and Mario Wolczko.\n\n# This program is free software; you can redist", "end": 109, "score": 0.9998871684074402, "start": 96, "tag": "NAME", "value": "Mario Wolczko" }, { "context": " is derived\n# from the Smalltalk implementation by John Maloney and Mario\n# Wolczko. Some parts have been transla", "end": 924, "score": 0.9998722076416016, "start": 912, "tag": "NAME", "value": "John Maloney" }, { "context": "m the Smalltalk implementation by John Maloney and Mario\n# Wolczko. Some parts have been translated direct", "end": 934, "score": 0.9998379945755005, "start": 929, "tag": "NAME", "value": "Mario" }, { "context": "alltalk implementation by John Maloney and Mario\n# Wolczko. Some parts have been translated directly, wherea", "end": 944, "score": 0.9998531937599182, "start": 937, "tag": "NAME", "value": "Wolczko" }, { "context": "ithm: An Incremental Constraint Hierarchy Solver\"\nBjorn N. Freeman-Benson and John Maloney\nJanuary 1990 Communications of t", "end": 1283, "score": 0.9998273849487305, "start": 1260, "tag": "NAME", "value": "Bjorn N. Freeman-Benson" }, { "context": "aint Hierarchy Solver\"\nBjorn N. Freeman-Benson and John Maloney\nJanuary 1990 Communications of the ACM,\nalso avai", "end": 1300, "score": 0.9998392462730408, "start": 1288, "tag": "NAME", "value": "John Maloney" } ]
deps/v8/benchmarks/deltablue.coffee
lxe/io.coffee
0
# Copyright 2008 the V8 project authors. All rights reserved. # Copyright 1996 John Maloney and Mario Wolczko. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # This implementation of the DeltaBlue benchmark is derived # from the Smalltalk implementation by John Maloney and Mario # Wolczko. Some parts have been translated directly, whereas # others have been modified more aggresively to make it feel # more like a JavaScript program. ###* A JavaScript implementation of the DeltaBlue constraint-solving algorithm, as described in: "The DeltaBlue Algorithm: An Incremental Constraint Hierarchy Solver" Bjorn N. Freeman-Benson and John Maloney January 1990 Communications of the ACM, also available as University of Washington TR 89-08-06. Beware: this benchmark is written in a grotesque style where the constraint model is built by side-effects from constructors. I've kept it this way to avoid deviating too much from the original implementation. ### # --- O b j e c t M o d e l --- OrderedCollection = -> @elms = new Array() return # --- * # * S t r e n g t h # * --- ###* Strengths are used to measure the relative importance of constraints. New strengths may be inserted in the strength hierarchy without disrupting current constraints. Strengths cannot be created outside this class, so pointer comparison can be used for value comparison. ### Strength = (strengthValue, name) -> @strengthValue = strengthValue @name = name return # Strength constants. # --- * # * C o n s t r a i n t # * --- ###* An abstract class representing a system-maintainable relationship (or "constraint") between a set of variables. A constraint supplies a strength instance variable; concrete subclasses provide a means of storing the constrained variables and other information required to represent a constraint. ### Constraint = (strength) -> @strength = strength return ###* Activate this constraint and attempt to satisfy it. ### ###* Attempt to find a way to enforce this constraint. If successful, record the solution, perhaps modifying the current dataflow graph. Answer the constraint that this constraint overrides, if there is one, or nil, if there isn't. Assume: I am not already satisfied. ### ###* Normal constraints are not input constraints. An input constraint is one that depends on external state, such as the mouse, the keybord, a clock, or some arbitraty piece of imperative code. ### # --- * # * U n a r y C o n s t r a i n t # * --- ###* Abstract superclass for constraints having a single possible output variable. ### UnaryConstraint = (v, strength) -> UnaryConstraint.superConstructor.call this, strength @myOutput = v @satisfied = false @addConstraint() return ###* Adds this constraint to the constraint graph ### ###* Decides if this constraint can be satisfied and records that decision. ### ###* Returns true if this constraint is satisfied in the current solution. ### # has no inputs ###* Returns the current output variable. ### ###* Calculate the walkabout strength, the stay flag, and, if it is 'stay', the value for the current output of this constraint. Assume this constraint is satisfied. ### # Stay optimization ###* Records that this constraint is unsatisfied ### # --- * # * S t a y C o n s t r a i n t # * --- ###* Variables that should, with some level of preference, stay the same. Planners may exploit the fact that instances, if satisfied, will not change their output during plan execution. This is called "stay optimization". ### StayConstraint = (v, str) -> StayConstraint.superConstructor.call this, v, str return # Stay constraints do nothing # --- * # * E d i t C o n s t r a i n t # * --- ###* A unary input constraint used to mark a variable that the client wishes to change. ### EditConstraint = (v, str) -> EditConstraint.superConstructor.call this, v, str return ###* Edits indicate that a variable is to be changed by imperative code. ### # Edit constraints do nothing # --- * # * B i n a r y C o n s t r a i n t # * --- ###* Abstract superclass for constraints having two possible output variables. ### BinaryConstraint = (var1, var2, strength) -> BinaryConstraint.superConstructor.call this, strength @v1 = var1 @v2 = var2 @direction = Direction.NONE @addConstraint() return ###* Decides if this constraint can be satisfied and which way it should flow based on the relative strength of the variables related, and record that decision. ### ###* Add this constraint to the constraint graph ### ###* Answer true if this constraint is satisfied in the current solution. ### ###* Mark the input variable with the given mark. ### ###* Returns the current input variable ### ###* Returns the current output variable ### ###* Calculate the walkabout strength, the stay flag, and, if it is 'stay', the value for the current output of this constraint. Assume this constraint is satisfied. ### ###* Record the fact that this constraint is unsatisfied. ### # --- * # * S c a l e C o n s t r a i n t # * --- ###* Relates two variables by the linear scaling relationship: "v2 = (v1 * scale) + offset". Either v1 or v2 may be changed to maintain this relationship but the scale factor and offset are considered read-only. ### ScaleConstraint = (src, scale, offset, dest, strength) -> @direction = Direction.NONE @scale = scale @offset = offset ScaleConstraint.superConstructor.call this, src, dest, strength return ###* Adds this constraint to the constraint graph. ### ###* Enforce this constraint. Assume that it is satisfied. ### ###* Calculate the walkabout strength, the stay flag, and, if it is 'stay', the value for the current output of this constraint. Assume this constraint is satisfied. ### # --- * # * E q u a l i t y C o n s t r a i n t # * --- ###* Constrains two variables to have the same value. ### EqualityConstraint = (var1, var2, strength) -> EqualityConstraint.superConstructor.call this, var1, var2, strength return ###* Enforce this constraint. Assume that it is satisfied. ### # --- * # * V a r i a b l e # * --- ###* A constrained variable. In addition to its value, it maintain the structure of the constraint graph, the current dataflow graph, and various parameters of interest to the DeltaBlue incremental constraint solver. ### Variable = (name, initialValue) -> @value = initialValue or 0 @constraints = new OrderedCollection() @determinedBy = null @mark = 0 @walkStrength = Strength.WEAKEST @stay = true @name = name return ###* Add the given constraint to the set of all constraints that refer this variable. ### ###* Removes all traces of c from this variable. ### # --- * # * P l a n n e r # * --- ###* The DeltaBlue planner ### Planner = -> @currentMark = 0 return ###* Attempt to satisfy the given constraint and, if successful, incrementally update the dataflow graph. Details: If satifying the constraint is successful, it may override a weaker constraint on its output. The algorithm attempts to resatisfy that constraint using some other method. This process is repeated until either a) it reaches a variable that was not previously determined by any constraint or b) it reaches a constraint that is too weak to be satisfied using any of its methods. The variables of constraints that have been processed are marked with a unique mark value so that we know where we've been. This allows the algorithm to avoid getting into an infinite loop even if the constraint graph has an inadvertent cycle. ### ###* Entry point for retracting a constraint. Remove the given constraint and incrementally update the dataflow graph. Details: Retracting the given constraint may allow some currently unsatisfiable downstream constraint to be satisfied. We therefore collect a list of unsatisfied downstream constraints and attempt to satisfy each one in turn. This list is traversed by constraint strength, strongest first, as a heuristic for avoiding unnecessarily adding and then overriding weak constraints. Assume: c is satisfied. ### ###* Select a previously unused mark value. ### ###* Extract a plan for resatisfaction starting from the given source constraints, usually a set of input constraints. This method assumes that stay optimization is desired; the plan will contain only constraints whose output variables are not stay. Constraints that do no computation, such as stay and edit constraints, are not included in the plan. Details: The outputs of a constraint are marked when it is added to the plan under construction. A constraint may be appended to the plan when all its input variables are known. A variable is known if either a) the variable is marked (indicating that has been computed by a constraint appearing earlier in the plan), b) the variable is 'stay' (i.e. it is a constant at plan execution time), or c) the variable is not determined by any constraint. The last provision is for past states of history variables, which are not stay but which are also not computed by any constraint. Assume: sources are all satisfied. ### ###* Extract a plan for resatisfying starting from the output of the given constraints, usually a set of input constraints. ### # not in plan already and eligible for inclusion ###* Recompute the walkabout strengths and stay flags of all variables downstream of the given constraint and recompute the actual values of all variables whose stay flag is true. If a cycle is detected, remove the given constraint and answer false. Otherwise, answer true. Details: Cycles are detected when a marked variable is encountered downstream of the given constraint. The sender is assumed to have marked the inputs of the given constraint with the given mark. Thus, encountering a marked node downstream of the output constraint means that there is a path from the constraint's output to one of its inputs. ### ###* Update the walkabout strengths and stay flags of all variables downstream of the given constraint. Answer a collection of unsatisfied constraints sorted in order of decreasing strength. ### # --- * # * P l a n # * --- ###* A Plan is an ordered list of constraints to be executed in sequence to resatisfy all currently satisfiable constraints in the face of one or more changing inputs. ### Plan = -> @v = new OrderedCollection() return # --- * # * M a i n # * --- ###* This is the standard DeltaBlue benchmark. A long chain of equality constraints is constructed with a stay constraint on one end. An edit constraint is then added to the opposite end and the time is measured for adding and removing this constraint, and extracting and executing a constraint satisfaction plan. There are two cases. In case 1, the added constraint is stronger than the stay constraint and values must propagate down the entire length of the chain. In case 2, the added constraint is weaker than the stay constraint so it cannot be accomodated. The cost in this case is, of course, very low. Typical situations lie somewhere between these two extremes. ### chainTest = (n) -> planner = new Planner() prev = null first = null last = null # Build chain of n equality constraints i = 0 while i <= n name = "v" + i v = new Variable(name) new EqualityConstraint(prev, v, Strength.REQUIRED) if prev? first = v if i is 0 last = v if i is n prev = v i++ new StayConstraint(last, Strength.STRONG_DEFAULT) edit = new EditConstraint(first, Strength.PREFERRED) edits = new OrderedCollection() edits.add edit plan = planner.extractPlanFromConstraints(edits) i = 0 while i < 100 first.value = i plan.execute() alert "Chain test failed." unless last.value is i i++ return ###* This test constructs a two sets of variables related to each other by a simple linear transformation (scale and offset). The time is measured to change a variable on either side of the mapping and to change the scale and offset factors. ### projectionTest = (n) -> planner = new Planner() scale = new Variable("scale", 10) offset = new Variable("offset", 1000) src = null dst = null dests = new OrderedCollection() i = 0 while i < n src = new Variable("src" + i, i) dst = new Variable("dst" + i, i) dests.add dst new StayConstraint(src, Strength.NORMAL) new ScaleConstraint(src, scale, offset, dst, Strength.REQUIRED) i++ change src, 17 alert "Projection 1 failed" unless dst.value is 1170 change dst, 1050 alert "Projection 2 failed" unless src.value is 5 change scale, 5 i = 0 while i < n - 1 alert "Projection 3 failed" unless dests.at(i).value is i * 5 + 1000 i++ change offset, 2000 i = 0 while i < n - 1 alert "Projection 4 failed" unless dests.at(i).value is i * 5 + 2000 i++ return change = (v, newValue) -> edit = new EditConstraint(v, Strength.PREFERRED) edits = new OrderedCollection() edits.add edit plan = planner.extractPlanFromConstraints(edits) i = 0 while i < 10 v.value = newValue plan.execute() i++ edit.destroyConstraint() return # Global variable holding the current planner. deltaBlue = -> chainTest 100 projectionTest 100 return DeltaBlue = new BenchmarkSuite("DeltaBlue", 66118, [new Benchmark("DeltaBlue", deltaBlue)]) Object::inheritsFrom = (shuper) -> Inheriter = -> Inheriter:: = shuper:: @:: = new Inheriter() @superConstructor = shuper return OrderedCollection::add = (elm) -> @elms.push elm return OrderedCollection::at = (index) -> @elms[index] OrderedCollection::size = -> @elms.length OrderedCollection::removeFirst = -> @elms.pop() OrderedCollection::remove = (elm) -> index = 0 skipped = 0 i = 0 while i < @elms.length value = @elms[i] unless value is elm @elms[index] = value index++ else skipped++ i++ i = 0 while i < skipped @elms.pop() i++ return Strength.stronger = (s1, s2) -> s1.strengthValue < s2.strengthValue Strength.weaker = (s1, s2) -> s1.strengthValue > s2.strengthValue Strength.weakestOf = (s1, s2) -> (if @weaker(s1, s2) then s1 else s2) Strength.strongest = (s1, s2) -> (if @stronger(s1, s2) then s1 else s2) Strength::nextWeaker = -> switch @strengthValue when 0 Strength.STRONG_PREFERRED when 1 Strength.PREFERRED when 2 Strength.STRONG_DEFAULT when 3 Strength.NORMAL when 4 Strength.WEAK_DEFAULT when 5 Strength.WEAKEST Strength.REQUIRED = new Strength(0, "required") Strength.STRONG_PREFERRED = new Strength(1, "strongPreferred") Strength.PREFERRED = new Strength(2, "preferred") Strength.STRONG_DEFAULT = new Strength(3, "strongDefault") Strength.NORMAL = new Strength(4, "normal") Strength.WEAK_DEFAULT = new Strength(5, "weakDefault") Strength.WEAKEST = new Strength(6, "weakest") Constraint::addConstraint = -> @addToGraph() planner.incrementalAdd this return Constraint::satisfy = (mark) -> @chooseMethod mark unless @isSatisfied() alert "Could not satisfy a required constraint!" if @strength is Strength.REQUIRED return null @markInputs mark out = @output() overridden = out.determinedBy overridden.markUnsatisfied() if overridden? out.determinedBy = this alert "Cycle encountered" unless planner.addPropagate(this, mark) out.mark = mark overridden Constraint::destroyConstraint = -> if @isSatisfied() planner.incrementalRemove this else @removeFromGraph() return Constraint::isInput = -> false UnaryConstraint.inheritsFrom Constraint UnaryConstraint::addToGraph = -> @myOutput.addConstraint this @satisfied = false return UnaryConstraint::chooseMethod = (mark) -> @satisfied = (@myOutput.mark isnt mark) and Strength.stronger(@strength, @myOutput.walkStrength) return UnaryConstraint::isSatisfied = -> @satisfied UnaryConstraint::markInputs = (mark) -> UnaryConstraint::output = -> @myOutput UnaryConstraint::recalculate = -> @myOutput.walkStrength = @strength @myOutput.stay = not @isInput() @execute() if @myOutput.stay return UnaryConstraint::markUnsatisfied = -> @satisfied = false return UnaryConstraint::inputsKnown = -> true UnaryConstraint::removeFromGraph = -> @myOutput.removeConstraint this if @myOutput? @satisfied = false return StayConstraint.inheritsFrom UnaryConstraint StayConstraint::execute = -> EditConstraint.inheritsFrom UnaryConstraint EditConstraint::isInput = -> true EditConstraint::execute = -> Direction = new Object() Direction.NONE = 0 Direction.FORWARD = 1 Direction.BACKWARD = -1 BinaryConstraint.inheritsFrom Constraint BinaryConstraint::chooseMethod = (mark) -> @direction = (if (@v2.mark isnt mark and Strength.stronger(@strength, @v2.walkStrength)) then Direction.FORWARD else Direction.NONE) if @v1.mark is mark @direction = (if (@v1.mark isnt mark and Strength.stronger(@strength, @v1.walkStrength)) then Direction.BACKWARD else Direction.NONE) if @v2.mark is mark if Strength.weaker(@v1.walkStrength, @v2.walkStrength) @direction = (if Strength.stronger(@strength, @v1.walkStrength) then Direction.BACKWARD else Direction.NONE) else @direction = (if Strength.stronger(@strength, @v2.walkStrength) then Direction.FORWARD else Direction.BACKWARD) return BinaryConstraint::addToGraph = -> @v1.addConstraint this @v2.addConstraint this @direction = Direction.NONE return BinaryConstraint::isSatisfied = -> @direction isnt Direction.NONE BinaryConstraint::markInputs = (mark) -> @input().mark = mark return BinaryConstraint::input = -> (if (@direction is Direction.FORWARD) then @v1 else @v2) BinaryConstraint::output = -> (if (@direction is Direction.FORWARD) then @v2 else @v1) BinaryConstraint::recalculate = -> ihn = @input() out = @output() out.walkStrength = Strength.weakestOf(@strength, ihn.walkStrength) out.stay = ihn.stay @execute() if out.stay return BinaryConstraint::markUnsatisfied = -> @direction = Direction.NONE return BinaryConstraint::inputsKnown = (mark) -> i = @input() i.mark is mark or i.stay or not i.determinedBy? BinaryConstraint::removeFromGraph = -> @v1.removeConstraint this if @v1? @v2.removeConstraint this if @v2? @direction = Direction.NONE return ScaleConstraint.inheritsFrom BinaryConstraint ScaleConstraint::addToGraph = -> ScaleConstraint.superConstructor::addToGraph.call this @scale.addConstraint this @offset.addConstraint this return ScaleConstraint::removeFromGraph = -> ScaleConstraint.superConstructor::removeFromGraph.call this @scale.removeConstraint this if @scale? @offset.removeConstraint this if @offset? return ScaleConstraint::markInputs = (mark) -> ScaleConstraint.superConstructor::markInputs.call this, mark @scale.mark = @offset.mark = mark return ScaleConstraint::execute = -> if @direction is Direction.FORWARD @v2.value = @v1.value * @scale.value + @offset.value else @v1.value = (@v2.value - @offset.value) / @scale.value return ScaleConstraint::recalculate = -> ihn = @input() out = @output() out.walkStrength = Strength.weakestOf(@strength, ihn.walkStrength) out.stay = ihn.stay and @scale.stay and @offset.stay @execute() if out.stay return EqualityConstraint.inheritsFrom BinaryConstraint EqualityConstraint::execute = -> @output().value = @input().value return Variable::addConstraint = (c) -> @constraints.add c return Variable::removeConstraint = (c) -> @constraints.remove c @determinedBy = null if @determinedBy is c return Planner::incrementalAdd = (c) -> mark = @newMark() overridden = c.satisfy(mark) overridden = overridden.satisfy(mark) while overridden? return Planner::incrementalRemove = (c) -> out = c.output() c.markUnsatisfied() c.removeFromGraph() unsatisfied = @removePropagateFrom(out) strength = Strength.REQUIRED loop i = 0 while i < unsatisfied.size() u = unsatisfied.at(i) @incrementalAdd u if u.strength is strength i++ strength = strength.nextWeaker() break unless strength isnt Strength.WEAKEST return Planner::newMark = -> ++@currentMark Planner::makePlan = (sources) -> mark = @newMark() plan = new Plan() todo = sources while todo.size() > 0 c = todo.removeFirst() if c.output().mark isnt mark and c.inputsKnown(mark) plan.addConstraint c c.output().mark = mark @addConstraintsConsumingTo c.output(), todo plan Planner::extractPlanFromConstraints = (constraints) -> sources = new OrderedCollection() i = 0 while i < constraints.size() c = constraints.at(i) sources.add c if c.isInput() and c.isSatisfied() i++ @makePlan sources Planner::addPropagate = (c, mark) -> todo = new OrderedCollection() todo.add c while todo.size() > 0 d = todo.removeFirst() if d.output().mark is mark @incrementalRemove c return false d.recalculate() @addConstraintsConsumingTo d.output(), todo true Planner::removePropagateFrom = (out) -> out.determinedBy = null out.walkStrength = Strength.WEAKEST out.stay = true unsatisfied = new OrderedCollection() todo = new OrderedCollection() todo.add out while todo.size() > 0 v = todo.removeFirst() i = 0 while i < v.constraints.size() c = v.constraints.at(i) unsatisfied.add c unless c.isSatisfied() i++ determining = v.determinedBy i = 0 while i < v.constraints.size() next = v.constraints.at(i) if next isnt determining and next.isSatisfied() next.recalculate() todo.add next.output() i++ unsatisfied Planner::addConstraintsConsumingTo = (v, coll) -> determining = v.determinedBy cc = v.constraints i = 0 while i < cc.size() c = cc.at(i) coll.add c if c isnt determining and c.isSatisfied() i++ return Plan::addConstraint = (c) -> @v.add c return Plan::size = -> @v.size() Plan::constraintAt = (index) -> @v.at index Plan::execute = -> i = 0 while i < @size() c = @constraintAt(i) c.execute() i++ return planner = null
222223
# Copyright 2008 the V8 project authors. All rights reserved. # Copyright 1996 <NAME> and <NAME>. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # This implementation of the DeltaBlue benchmark is derived # from the Smalltalk implementation by <NAME> and <NAME> # <NAME>. Some parts have been translated directly, whereas # others have been modified more aggresively to make it feel # more like a JavaScript program. ###* A JavaScript implementation of the DeltaBlue constraint-solving algorithm, as described in: "The DeltaBlue Algorithm: An Incremental Constraint Hierarchy Solver" <NAME> and <NAME> January 1990 Communications of the ACM, also available as University of Washington TR 89-08-06. Beware: this benchmark is written in a grotesque style where the constraint model is built by side-effects from constructors. I've kept it this way to avoid deviating too much from the original implementation. ### # --- O b j e c t M o d e l --- OrderedCollection = -> @elms = new Array() return # --- * # * S t r e n g t h # * --- ###* Strengths are used to measure the relative importance of constraints. New strengths may be inserted in the strength hierarchy without disrupting current constraints. Strengths cannot be created outside this class, so pointer comparison can be used for value comparison. ### Strength = (strengthValue, name) -> @strengthValue = strengthValue @name = name return # Strength constants. # --- * # * C o n s t r a i n t # * --- ###* An abstract class representing a system-maintainable relationship (or "constraint") between a set of variables. A constraint supplies a strength instance variable; concrete subclasses provide a means of storing the constrained variables and other information required to represent a constraint. ### Constraint = (strength) -> @strength = strength return ###* Activate this constraint and attempt to satisfy it. ### ###* Attempt to find a way to enforce this constraint. If successful, record the solution, perhaps modifying the current dataflow graph. Answer the constraint that this constraint overrides, if there is one, or nil, if there isn't. Assume: I am not already satisfied. ### ###* Normal constraints are not input constraints. An input constraint is one that depends on external state, such as the mouse, the keybord, a clock, or some arbitraty piece of imperative code. ### # --- * # * U n a r y C o n s t r a i n t # * --- ###* Abstract superclass for constraints having a single possible output variable. ### UnaryConstraint = (v, strength) -> UnaryConstraint.superConstructor.call this, strength @myOutput = v @satisfied = false @addConstraint() return ###* Adds this constraint to the constraint graph ### ###* Decides if this constraint can be satisfied and records that decision. ### ###* Returns true if this constraint is satisfied in the current solution. ### # has no inputs ###* Returns the current output variable. ### ###* Calculate the walkabout strength, the stay flag, and, if it is 'stay', the value for the current output of this constraint. Assume this constraint is satisfied. ### # Stay optimization ###* Records that this constraint is unsatisfied ### # --- * # * S t a y C o n s t r a i n t # * --- ###* Variables that should, with some level of preference, stay the same. Planners may exploit the fact that instances, if satisfied, will not change their output during plan execution. This is called "stay optimization". ### StayConstraint = (v, str) -> StayConstraint.superConstructor.call this, v, str return # Stay constraints do nothing # --- * # * E d i t C o n s t r a i n t # * --- ###* A unary input constraint used to mark a variable that the client wishes to change. ### EditConstraint = (v, str) -> EditConstraint.superConstructor.call this, v, str return ###* Edits indicate that a variable is to be changed by imperative code. ### # Edit constraints do nothing # --- * # * B i n a r y C o n s t r a i n t # * --- ###* Abstract superclass for constraints having two possible output variables. ### BinaryConstraint = (var1, var2, strength) -> BinaryConstraint.superConstructor.call this, strength @v1 = var1 @v2 = var2 @direction = Direction.NONE @addConstraint() return ###* Decides if this constraint can be satisfied and which way it should flow based on the relative strength of the variables related, and record that decision. ### ###* Add this constraint to the constraint graph ### ###* Answer true if this constraint is satisfied in the current solution. ### ###* Mark the input variable with the given mark. ### ###* Returns the current input variable ### ###* Returns the current output variable ### ###* Calculate the walkabout strength, the stay flag, and, if it is 'stay', the value for the current output of this constraint. Assume this constraint is satisfied. ### ###* Record the fact that this constraint is unsatisfied. ### # --- * # * S c a l e C o n s t r a i n t # * --- ###* Relates two variables by the linear scaling relationship: "v2 = (v1 * scale) + offset". Either v1 or v2 may be changed to maintain this relationship but the scale factor and offset are considered read-only. ### ScaleConstraint = (src, scale, offset, dest, strength) -> @direction = Direction.NONE @scale = scale @offset = offset ScaleConstraint.superConstructor.call this, src, dest, strength return ###* Adds this constraint to the constraint graph. ### ###* Enforce this constraint. Assume that it is satisfied. ### ###* Calculate the walkabout strength, the stay flag, and, if it is 'stay', the value for the current output of this constraint. Assume this constraint is satisfied. ### # --- * # * E q u a l i t y C o n s t r a i n t # * --- ###* Constrains two variables to have the same value. ### EqualityConstraint = (var1, var2, strength) -> EqualityConstraint.superConstructor.call this, var1, var2, strength return ###* Enforce this constraint. Assume that it is satisfied. ### # --- * # * V a r i a b l e # * --- ###* A constrained variable. In addition to its value, it maintain the structure of the constraint graph, the current dataflow graph, and various parameters of interest to the DeltaBlue incremental constraint solver. ### Variable = (name, initialValue) -> @value = initialValue or 0 @constraints = new OrderedCollection() @determinedBy = null @mark = 0 @walkStrength = Strength.WEAKEST @stay = true @name = name return ###* Add the given constraint to the set of all constraints that refer this variable. ### ###* Removes all traces of c from this variable. ### # --- * # * P l a n n e r # * --- ###* The DeltaBlue planner ### Planner = -> @currentMark = 0 return ###* Attempt to satisfy the given constraint and, if successful, incrementally update the dataflow graph. Details: If satifying the constraint is successful, it may override a weaker constraint on its output. The algorithm attempts to resatisfy that constraint using some other method. This process is repeated until either a) it reaches a variable that was not previously determined by any constraint or b) it reaches a constraint that is too weak to be satisfied using any of its methods. The variables of constraints that have been processed are marked with a unique mark value so that we know where we've been. This allows the algorithm to avoid getting into an infinite loop even if the constraint graph has an inadvertent cycle. ### ###* Entry point for retracting a constraint. Remove the given constraint and incrementally update the dataflow graph. Details: Retracting the given constraint may allow some currently unsatisfiable downstream constraint to be satisfied. We therefore collect a list of unsatisfied downstream constraints and attempt to satisfy each one in turn. This list is traversed by constraint strength, strongest first, as a heuristic for avoiding unnecessarily adding and then overriding weak constraints. Assume: c is satisfied. ### ###* Select a previously unused mark value. ### ###* Extract a plan for resatisfaction starting from the given source constraints, usually a set of input constraints. This method assumes that stay optimization is desired; the plan will contain only constraints whose output variables are not stay. Constraints that do no computation, such as stay and edit constraints, are not included in the plan. Details: The outputs of a constraint are marked when it is added to the plan under construction. A constraint may be appended to the plan when all its input variables are known. A variable is known if either a) the variable is marked (indicating that has been computed by a constraint appearing earlier in the plan), b) the variable is 'stay' (i.e. it is a constant at plan execution time), or c) the variable is not determined by any constraint. The last provision is for past states of history variables, which are not stay but which are also not computed by any constraint. Assume: sources are all satisfied. ### ###* Extract a plan for resatisfying starting from the output of the given constraints, usually a set of input constraints. ### # not in plan already and eligible for inclusion ###* Recompute the walkabout strengths and stay flags of all variables downstream of the given constraint and recompute the actual values of all variables whose stay flag is true. If a cycle is detected, remove the given constraint and answer false. Otherwise, answer true. Details: Cycles are detected when a marked variable is encountered downstream of the given constraint. The sender is assumed to have marked the inputs of the given constraint with the given mark. Thus, encountering a marked node downstream of the output constraint means that there is a path from the constraint's output to one of its inputs. ### ###* Update the walkabout strengths and stay flags of all variables downstream of the given constraint. Answer a collection of unsatisfied constraints sorted in order of decreasing strength. ### # --- * # * P l a n # * --- ###* A Plan is an ordered list of constraints to be executed in sequence to resatisfy all currently satisfiable constraints in the face of one or more changing inputs. ### Plan = -> @v = new OrderedCollection() return # --- * # * M a i n # * --- ###* This is the standard DeltaBlue benchmark. A long chain of equality constraints is constructed with a stay constraint on one end. An edit constraint is then added to the opposite end and the time is measured for adding and removing this constraint, and extracting and executing a constraint satisfaction plan. There are two cases. In case 1, the added constraint is stronger than the stay constraint and values must propagate down the entire length of the chain. In case 2, the added constraint is weaker than the stay constraint so it cannot be accomodated. The cost in this case is, of course, very low. Typical situations lie somewhere between these two extremes. ### chainTest = (n) -> planner = new Planner() prev = null first = null last = null # Build chain of n equality constraints i = 0 while i <= n name = "v" + i v = new Variable(name) new EqualityConstraint(prev, v, Strength.REQUIRED) if prev? first = v if i is 0 last = v if i is n prev = v i++ new StayConstraint(last, Strength.STRONG_DEFAULT) edit = new EditConstraint(first, Strength.PREFERRED) edits = new OrderedCollection() edits.add edit plan = planner.extractPlanFromConstraints(edits) i = 0 while i < 100 first.value = i plan.execute() alert "Chain test failed." unless last.value is i i++ return ###* This test constructs a two sets of variables related to each other by a simple linear transformation (scale and offset). The time is measured to change a variable on either side of the mapping and to change the scale and offset factors. ### projectionTest = (n) -> planner = new Planner() scale = new Variable("scale", 10) offset = new Variable("offset", 1000) src = null dst = null dests = new OrderedCollection() i = 0 while i < n src = new Variable("src" + i, i) dst = new Variable("dst" + i, i) dests.add dst new StayConstraint(src, Strength.NORMAL) new ScaleConstraint(src, scale, offset, dst, Strength.REQUIRED) i++ change src, 17 alert "Projection 1 failed" unless dst.value is 1170 change dst, 1050 alert "Projection 2 failed" unless src.value is 5 change scale, 5 i = 0 while i < n - 1 alert "Projection 3 failed" unless dests.at(i).value is i * 5 + 1000 i++ change offset, 2000 i = 0 while i < n - 1 alert "Projection 4 failed" unless dests.at(i).value is i * 5 + 2000 i++ return change = (v, newValue) -> edit = new EditConstraint(v, Strength.PREFERRED) edits = new OrderedCollection() edits.add edit plan = planner.extractPlanFromConstraints(edits) i = 0 while i < 10 v.value = newValue plan.execute() i++ edit.destroyConstraint() return # Global variable holding the current planner. deltaBlue = -> chainTest 100 projectionTest 100 return DeltaBlue = new BenchmarkSuite("DeltaBlue", 66118, [new Benchmark("DeltaBlue", deltaBlue)]) Object::inheritsFrom = (shuper) -> Inheriter = -> Inheriter:: = shuper:: @:: = new Inheriter() @superConstructor = shuper return OrderedCollection::add = (elm) -> @elms.push elm return OrderedCollection::at = (index) -> @elms[index] OrderedCollection::size = -> @elms.length OrderedCollection::removeFirst = -> @elms.pop() OrderedCollection::remove = (elm) -> index = 0 skipped = 0 i = 0 while i < @elms.length value = @elms[i] unless value is elm @elms[index] = value index++ else skipped++ i++ i = 0 while i < skipped @elms.pop() i++ return Strength.stronger = (s1, s2) -> s1.strengthValue < s2.strengthValue Strength.weaker = (s1, s2) -> s1.strengthValue > s2.strengthValue Strength.weakestOf = (s1, s2) -> (if @weaker(s1, s2) then s1 else s2) Strength.strongest = (s1, s2) -> (if @stronger(s1, s2) then s1 else s2) Strength::nextWeaker = -> switch @strengthValue when 0 Strength.STRONG_PREFERRED when 1 Strength.PREFERRED when 2 Strength.STRONG_DEFAULT when 3 Strength.NORMAL when 4 Strength.WEAK_DEFAULT when 5 Strength.WEAKEST Strength.REQUIRED = new Strength(0, "required") Strength.STRONG_PREFERRED = new Strength(1, "strongPreferred") Strength.PREFERRED = new Strength(2, "preferred") Strength.STRONG_DEFAULT = new Strength(3, "strongDefault") Strength.NORMAL = new Strength(4, "normal") Strength.WEAK_DEFAULT = new Strength(5, "weakDefault") Strength.WEAKEST = new Strength(6, "weakest") Constraint::addConstraint = -> @addToGraph() planner.incrementalAdd this return Constraint::satisfy = (mark) -> @chooseMethod mark unless @isSatisfied() alert "Could not satisfy a required constraint!" if @strength is Strength.REQUIRED return null @markInputs mark out = @output() overridden = out.determinedBy overridden.markUnsatisfied() if overridden? out.determinedBy = this alert "Cycle encountered" unless planner.addPropagate(this, mark) out.mark = mark overridden Constraint::destroyConstraint = -> if @isSatisfied() planner.incrementalRemove this else @removeFromGraph() return Constraint::isInput = -> false UnaryConstraint.inheritsFrom Constraint UnaryConstraint::addToGraph = -> @myOutput.addConstraint this @satisfied = false return UnaryConstraint::chooseMethod = (mark) -> @satisfied = (@myOutput.mark isnt mark) and Strength.stronger(@strength, @myOutput.walkStrength) return UnaryConstraint::isSatisfied = -> @satisfied UnaryConstraint::markInputs = (mark) -> UnaryConstraint::output = -> @myOutput UnaryConstraint::recalculate = -> @myOutput.walkStrength = @strength @myOutput.stay = not @isInput() @execute() if @myOutput.stay return UnaryConstraint::markUnsatisfied = -> @satisfied = false return UnaryConstraint::inputsKnown = -> true UnaryConstraint::removeFromGraph = -> @myOutput.removeConstraint this if @myOutput? @satisfied = false return StayConstraint.inheritsFrom UnaryConstraint StayConstraint::execute = -> EditConstraint.inheritsFrom UnaryConstraint EditConstraint::isInput = -> true EditConstraint::execute = -> Direction = new Object() Direction.NONE = 0 Direction.FORWARD = 1 Direction.BACKWARD = -1 BinaryConstraint.inheritsFrom Constraint BinaryConstraint::chooseMethod = (mark) -> @direction = (if (@v2.mark isnt mark and Strength.stronger(@strength, @v2.walkStrength)) then Direction.FORWARD else Direction.NONE) if @v1.mark is mark @direction = (if (@v1.mark isnt mark and Strength.stronger(@strength, @v1.walkStrength)) then Direction.BACKWARD else Direction.NONE) if @v2.mark is mark if Strength.weaker(@v1.walkStrength, @v2.walkStrength) @direction = (if Strength.stronger(@strength, @v1.walkStrength) then Direction.BACKWARD else Direction.NONE) else @direction = (if Strength.stronger(@strength, @v2.walkStrength) then Direction.FORWARD else Direction.BACKWARD) return BinaryConstraint::addToGraph = -> @v1.addConstraint this @v2.addConstraint this @direction = Direction.NONE return BinaryConstraint::isSatisfied = -> @direction isnt Direction.NONE BinaryConstraint::markInputs = (mark) -> @input().mark = mark return BinaryConstraint::input = -> (if (@direction is Direction.FORWARD) then @v1 else @v2) BinaryConstraint::output = -> (if (@direction is Direction.FORWARD) then @v2 else @v1) BinaryConstraint::recalculate = -> ihn = @input() out = @output() out.walkStrength = Strength.weakestOf(@strength, ihn.walkStrength) out.stay = ihn.stay @execute() if out.stay return BinaryConstraint::markUnsatisfied = -> @direction = Direction.NONE return BinaryConstraint::inputsKnown = (mark) -> i = @input() i.mark is mark or i.stay or not i.determinedBy? BinaryConstraint::removeFromGraph = -> @v1.removeConstraint this if @v1? @v2.removeConstraint this if @v2? @direction = Direction.NONE return ScaleConstraint.inheritsFrom BinaryConstraint ScaleConstraint::addToGraph = -> ScaleConstraint.superConstructor::addToGraph.call this @scale.addConstraint this @offset.addConstraint this return ScaleConstraint::removeFromGraph = -> ScaleConstraint.superConstructor::removeFromGraph.call this @scale.removeConstraint this if @scale? @offset.removeConstraint this if @offset? return ScaleConstraint::markInputs = (mark) -> ScaleConstraint.superConstructor::markInputs.call this, mark @scale.mark = @offset.mark = mark return ScaleConstraint::execute = -> if @direction is Direction.FORWARD @v2.value = @v1.value * @scale.value + @offset.value else @v1.value = (@v2.value - @offset.value) / @scale.value return ScaleConstraint::recalculate = -> ihn = @input() out = @output() out.walkStrength = Strength.weakestOf(@strength, ihn.walkStrength) out.stay = ihn.stay and @scale.stay and @offset.stay @execute() if out.stay return EqualityConstraint.inheritsFrom BinaryConstraint EqualityConstraint::execute = -> @output().value = @input().value return Variable::addConstraint = (c) -> @constraints.add c return Variable::removeConstraint = (c) -> @constraints.remove c @determinedBy = null if @determinedBy is c return Planner::incrementalAdd = (c) -> mark = @newMark() overridden = c.satisfy(mark) overridden = overridden.satisfy(mark) while overridden? return Planner::incrementalRemove = (c) -> out = c.output() c.markUnsatisfied() c.removeFromGraph() unsatisfied = @removePropagateFrom(out) strength = Strength.REQUIRED loop i = 0 while i < unsatisfied.size() u = unsatisfied.at(i) @incrementalAdd u if u.strength is strength i++ strength = strength.nextWeaker() break unless strength isnt Strength.WEAKEST return Planner::newMark = -> ++@currentMark Planner::makePlan = (sources) -> mark = @newMark() plan = new Plan() todo = sources while todo.size() > 0 c = todo.removeFirst() if c.output().mark isnt mark and c.inputsKnown(mark) plan.addConstraint c c.output().mark = mark @addConstraintsConsumingTo c.output(), todo plan Planner::extractPlanFromConstraints = (constraints) -> sources = new OrderedCollection() i = 0 while i < constraints.size() c = constraints.at(i) sources.add c if c.isInput() and c.isSatisfied() i++ @makePlan sources Planner::addPropagate = (c, mark) -> todo = new OrderedCollection() todo.add c while todo.size() > 0 d = todo.removeFirst() if d.output().mark is mark @incrementalRemove c return false d.recalculate() @addConstraintsConsumingTo d.output(), todo true Planner::removePropagateFrom = (out) -> out.determinedBy = null out.walkStrength = Strength.WEAKEST out.stay = true unsatisfied = new OrderedCollection() todo = new OrderedCollection() todo.add out while todo.size() > 0 v = todo.removeFirst() i = 0 while i < v.constraints.size() c = v.constraints.at(i) unsatisfied.add c unless c.isSatisfied() i++ determining = v.determinedBy i = 0 while i < v.constraints.size() next = v.constraints.at(i) if next isnt determining and next.isSatisfied() next.recalculate() todo.add next.output() i++ unsatisfied Planner::addConstraintsConsumingTo = (v, coll) -> determining = v.determinedBy cc = v.constraints i = 0 while i < cc.size() c = cc.at(i) coll.add c if c isnt determining and c.isSatisfied() i++ return Plan::addConstraint = (c) -> @v.add c return Plan::size = -> @v.size() Plan::constraintAt = (index) -> @v.at index Plan::execute = -> i = 0 while i < @size() c = @constraintAt(i) c.execute() i++ return planner = null
true
# Copyright 2008 the V8 project authors. All rights reserved. # Copyright 1996 PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # This implementation of the DeltaBlue benchmark is derived # from the Smalltalk implementation by PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI # PI:NAME:<NAME>END_PI. Some parts have been translated directly, whereas # others have been modified more aggresively to make it feel # more like a JavaScript program. ###* A JavaScript implementation of the DeltaBlue constraint-solving algorithm, as described in: "The DeltaBlue Algorithm: An Incremental Constraint Hierarchy Solver" PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI January 1990 Communications of the ACM, also available as University of Washington TR 89-08-06. Beware: this benchmark is written in a grotesque style where the constraint model is built by side-effects from constructors. I've kept it this way to avoid deviating too much from the original implementation. ### # --- O b j e c t M o d e l --- OrderedCollection = -> @elms = new Array() return # --- * # * S t r e n g t h # * --- ###* Strengths are used to measure the relative importance of constraints. New strengths may be inserted in the strength hierarchy without disrupting current constraints. Strengths cannot be created outside this class, so pointer comparison can be used for value comparison. ### Strength = (strengthValue, name) -> @strengthValue = strengthValue @name = name return # Strength constants. # --- * # * C o n s t r a i n t # * --- ###* An abstract class representing a system-maintainable relationship (or "constraint") between a set of variables. A constraint supplies a strength instance variable; concrete subclasses provide a means of storing the constrained variables and other information required to represent a constraint. ### Constraint = (strength) -> @strength = strength return ###* Activate this constraint and attempt to satisfy it. ### ###* Attempt to find a way to enforce this constraint. If successful, record the solution, perhaps modifying the current dataflow graph. Answer the constraint that this constraint overrides, if there is one, or nil, if there isn't. Assume: I am not already satisfied. ### ###* Normal constraints are not input constraints. An input constraint is one that depends on external state, such as the mouse, the keybord, a clock, or some arbitraty piece of imperative code. ### # --- * # * U n a r y C o n s t r a i n t # * --- ###* Abstract superclass for constraints having a single possible output variable. ### UnaryConstraint = (v, strength) -> UnaryConstraint.superConstructor.call this, strength @myOutput = v @satisfied = false @addConstraint() return ###* Adds this constraint to the constraint graph ### ###* Decides if this constraint can be satisfied and records that decision. ### ###* Returns true if this constraint is satisfied in the current solution. ### # has no inputs ###* Returns the current output variable. ### ###* Calculate the walkabout strength, the stay flag, and, if it is 'stay', the value for the current output of this constraint. Assume this constraint is satisfied. ### # Stay optimization ###* Records that this constraint is unsatisfied ### # --- * # * S t a y C o n s t r a i n t # * --- ###* Variables that should, with some level of preference, stay the same. Planners may exploit the fact that instances, if satisfied, will not change their output during plan execution. This is called "stay optimization". ### StayConstraint = (v, str) -> StayConstraint.superConstructor.call this, v, str return # Stay constraints do nothing # --- * # * E d i t C o n s t r a i n t # * --- ###* A unary input constraint used to mark a variable that the client wishes to change. ### EditConstraint = (v, str) -> EditConstraint.superConstructor.call this, v, str return ###* Edits indicate that a variable is to be changed by imperative code. ### # Edit constraints do nothing # --- * # * B i n a r y C o n s t r a i n t # * --- ###* Abstract superclass for constraints having two possible output variables. ### BinaryConstraint = (var1, var2, strength) -> BinaryConstraint.superConstructor.call this, strength @v1 = var1 @v2 = var2 @direction = Direction.NONE @addConstraint() return ###* Decides if this constraint can be satisfied and which way it should flow based on the relative strength of the variables related, and record that decision. ### ###* Add this constraint to the constraint graph ### ###* Answer true if this constraint is satisfied in the current solution. ### ###* Mark the input variable with the given mark. ### ###* Returns the current input variable ### ###* Returns the current output variable ### ###* Calculate the walkabout strength, the stay flag, and, if it is 'stay', the value for the current output of this constraint. Assume this constraint is satisfied. ### ###* Record the fact that this constraint is unsatisfied. ### # --- * # * S c a l e C o n s t r a i n t # * --- ###* Relates two variables by the linear scaling relationship: "v2 = (v1 * scale) + offset". Either v1 or v2 may be changed to maintain this relationship but the scale factor and offset are considered read-only. ### ScaleConstraint = (src, scale, offset, dest, strength) -> @direction = Direction.NONE @scale = scale @offset = offset ScaleConstraint.superConstructor.call this, src, dest, strength return ###* Adds this constraint to the constraint graph. ### ###* Enforce this constraint. Assume that it is satisfied. ### ###* Calculate the walkabout strength, the stay flag, and, if it is 'stay', the value for the current output of this constraint. Assume this constraint is satisfied. ### # --- * # * E q u a l i t y C o n s t r a i n t # * --- ###* Constrains two variables to have the same value. ### EqualityConstraint = (var1, var2, strength) -> EqualityConstraint.superConstructor.call this, var1, var2, strength return ###* Enforce this constraint. Assume that it is satisfied. ### # --- * # * V a r i a b l e # * --- ###* A constrained variable. In addition to its value, it maintain the structure of the constraint graph, the current dataflow graph, and various parameters of interest to the DeltaBlue incremental constraint solver. ### Variable = (name, initialValue) -> @value = initialValue or 0 @constraints = new OrderedCollection() @determinedBy = null @mark = 0 @walkStrength = Strength.WEAKEST @stay = true @name = name return ###* Add the given constraint to the set of all constraints that refer this variable. ### ###* Removes all traces of c from this variable. ### # --- * # * P l a n n e r # * --- ###* The DeltaBlue planner ### Planner = -> @currentMark = 0 return ###* Attempt to satisfy the given constraint and, if successful, incrementally update the dataflow graph. Details: If satifying the constraint is successful, it may override a weaker constraint on its output. The algorithm attempts to resatisfy that constraint using some other method. This process is repeated until either a) it reaches a variable that was not previously determined by any constraint or b) it reaches a constraint that is too weak to be satisfied using any of its methods. The variables of constraints that have been processed are marked with a unique mark value so that we know where we've been. This allows the algorithm to avoid getting into an infinite loop even if the constraint graph has an inadvertent cycle. ### ###* Entry point for retracting a constraint. Remove the given constraint and incrementally update the dataflow graph. Details: Retracting the given constraint may allow some currently unsatisfiable downstream constraint to be satisfied. We therefore collect a list of unsatisfied downstream constraints and attempt to satisfy each one in turn. This list is traversed by constraint strength, strongest first, as a heuristic for avoiding unnecessarily adding and then overriding weak constraints. Assume: c is satisfied. ### ###* Select a previously unused mark value. ### ###* Extract a plan for resatisfaction starting from the given source constraints, usually a set of input constraints. This method assumes that stay optimization is desired; the plan will contain only constraints whose output variables are not stay. Constraints that do no computation, such as stay and edit constraints, are not included in the plan. Details: The outputs of a constraint are marked when it is added to the plan under construction. A constraint may be appended to the plan when all its input variables are known. A variable is known if either a) the variable is marked (indicating that has been computed by a constraint appearing earlier in the plan), b) the variable is 'stay' (i.e. it is a constant at plan execution time), or c) the variable is not determined by any constraint. The last provision is for past states of history variables, which are not stay but which are also not computed by any constraint. Assume: sources are all satisfied. ### ###* Extract a plan for resatisfying starting from the output of the given constraints, usually a set of input constraints. ### # not in plan already and eligible for inclusion ###* Recompute the walkabout strengths and stay flags of all variables downstream of the given constraint and recompute the actual values of all variables whose stay flag is true. If a cycle is detected, remove the given constraint and answer false. Otherwise, answer true. Details: Cycles are detected when a marked variable is encountered downstream of the given constraint. The sender is assumed to have marked the inputs of the given constraint with the given mark. Thus, encountering a marked node downstream of the output constraint means that there is a path from the constraint's output to one of its inputs. ### ###* Update the walkabout strengths and stay flags of all variables downstream of the given constraint. Answer a collection of unsatisfied constraints sorted in order of decreasing strength. ### # --- * # * P l a n # * --- ###* A Plan is an ordered list of constraints to be executed in sequence to resatisfy all currently satisfiable constraints in the face of one or more changing inputs. ### Plan = -> @v = new OrderedCollection() return # --- * # * M a i n # * --- ###* This is the standard DeltaBlue benchmark. A long chain of equality constraints is constructed with a stay constraint on one end. An edit constraint is then added to the opposite end and the time is measured for adding and removing this constraint, and extracting and executing a constraint satisfaction plan. There are two cases. In case 1, the added constraint is stronger than the stay constraint and values must propagate down the entire length of the chain. In case 2, the added constraint is weaker than the stay constraint so it cannot be accomodated. The cost in this case is, of course, very low. Typical situations lie somewhere between these two extremes. ### chainTest = (n) -> planner = new Planner() prev = null first = null last = null # Build chain of n equality constraints i = 0 while i <= n name = "v" + i v = new Variable(name) new EqualityConstraint(prev, v, Strength.REQUIRED) if prev? first = v if i is 0 last = v if i is n prev = v i++ new StayConstraint(last, Strength.STRONG_DEFAULT) edit = new EditConstraint(first, Strength.PREFERRED) edits = new OrderedCollection() edits.add edit plan = planner.extractPlanFromConstraints(edits) i = 0 while i < 100 first.value = i plan.execute() alert "Chain test failed." unless last.value is i i++ return ###* This test constructs a two sets of variables related to each other by a simple linear transformation (scale and offset). The time is measured to change a variable on either side of the mapping and to change the scale and offset factors. ### projectionTest = (n) -> planner = new Planner() scale = new Variable("scale", 10) offset = new Variable("offset", 1000) src = null dst = null dests = new OrderedCollection() i = 0 while i < n src = new Variable("src" + i, i) dst = new Variable("dst" + i, i) dests.add dst new StayConstraint(src, Strength.NORMAL) new ScaleConstraint(src, scale, offset, dst, Strength.REQUIRED) i++ change src, 17 alert "Projection 1 failed" unless dst.value is 1170 change dst, 1050 alert "Projection 2 failed" unless src.value is 5 change scale, 5 i = 0 while i < n - 1 alert "Projection 3 failed" unless dests.at(i).value is i * 5 + 1000 i++ change offset, 2000 i = 0 while i < n - 1 alert "Projection 4 failed" unless dests.at(i).value is i * 5 + 2000 i++ return change = (v, newValue) -> edit = new EditConstraint(v, Strength.PREFERRED) edits = new OrderedCollection() edits.add edit plan = planner.extractPlanFromConstraints(edits) i = 0 while i < 10 v.value = newValue plan.execute() i++ edit.destroyConstraint() return # Global variable holding the current planner. deltaBlue = -> chainTest 100 projectionTest 100 return DeltaBlue = new BenchmarkSuite("DeltaBlue", 66118, [new Benchmark("DeltaBlue", deltaBlue)]) Object::inheritsFrom = (shuper) -> Inheriter = -> Inheriter:: = shuper:: @:: = new Inheriter() @superConstructor = shuper return OrderedCollection::add = (elm) -> @elms.push elm return OrderedCollection::at = (index) -> @elms[index] OrderedCollection::size = -> @elms.length OrderedCollection::removeFirst = -> @elms.pop() OrderedCollection::remove = (elm) -> index = 0 skipped = 0 i = 0 while i < @elms.length value = @elms[i] unless value is elm @elms[index] = value index++ else skipped++ i++ i = 0 while i < skipped @elms.pop() i++ return Strength.stronger = (s1, s2) -> s1.strengthValue < s2.strengthValue Strength.weaker = (s1, s2) -> s1.strengthValue > s2.strengthValue Strength.weakestOf = (s1, s2) -> (if @weaker(s1, s2) then s1 else s2) Strength.strongest = (s1, s2) -> (if @stronger(s1, s2) then s1 else s2) Strength::nextWeaker = -> switch @strengthValue when 0 Strength.STRONG_PREFERRED when 1 Strength.PREFERRED when 2 Strength.STRONG_DEFAULT when 3 Strength.NORMAL when 4 Strength.WEAK_DEFAULT when 5 Strength.WEAKEST Strength.REQUIRED = new Strength(0, "required") Strength.STRONG_PREFERRED = new Strength(1, "strongPreferred") Strength.PREFERRED = new Strength(2, "preferred") Strength.STRONG_DEFAULT = new Strength(3, "strongDefault") Strength.NORMAL = new Strength(4, "normal") Strength.WEAK_DEFAULT = new Strength(5, "weakDefault") Strength.WEAKEST = new Strength(6, "weakest") Constraint::addConstraint = -> @addToGraph() planner.incrementalAdd this return Constraint::satisfy = (mark) -> @chooseMethod mark unless @isSatisfied() alert "Could not satisfy a required constraint!" if @strength is Strength.REQUIRED return null @markInputs mark out = @output() overridden = out.determinedBy overridden.markUnsatisfied() if overridden? out.determinedBy = this alert "Cycle encountered" unless planner.addPropagate(this, mark) out.mark = mark overridden Constraint::destroyConstraint = -> if @isSatisfied() planner.incrementalRemove this else @removeFromGraph() return Constraint::isInput = -> false UnaryConstraint.inheritsFrom Constraint UnaryConstraint::addToGraph = -> @myOutput.addConstraint this @satisfied = false return UnaryConstraint::chooseMethod = (mark) -> @satisfied = (@myOutput.mark isnt mark) and Strength.stronger(@strength, @myOutput.walkStrength) return UnaryConstraint::isSatisfied = -> @satisfied UnaryConstraint::markInputs = (mark) -> UnaryConstraint::output = -> @myOutput UnaryConstraint::recalculate = -> @myOutput.walkStrength = @strength @myOutput.stay = not @isInput() @execute() if @myOutput.stay return UnaryConstraint::markUnsatisfied = -> @satisfied = false return UnaryConstraint::inputsKnown = -> true UnaryConstraint::removeFromGraph = -> @myOutput.removeConstraint this if @myOutput? @satisfied = false return StayConstraint.inheritsFrom UnaryConstraint StayConstraint::execute = -> EditConstraint.inheritsFrom UnaryConstraint EditConstraint::isInput = -> true EditConstraint::execute = -> Direction = new Object() Direction.NONE = 0 Direction.FORWARD = 1 Direction.BACKWARD = -1 BinaryConstraint.inheritsFrom Constraint BinaryConstraint::chooseMethod = (mark) -> @direction = (if (@v2.mark isnt mark and Strength.stronger(@strength, @v2.walkStrength)) then Direction.FORWARD else Direction.NONE) if @v1.mark is mark @direction = (if (@v1.mark isnt mark and Strength.stronger(@strength, @v1.walkStrength)) then Direction.BACKWARD else Direction.NONE) if @v2.mark is mark if Strength.weaker(@v1.walkStrength, @v2.walkStrength) @direction = (if Strength.stronger(@strength, @v1.walkStrength) then Direction.BACKWARD else Direction.NONE) else @direction = (if Strength.stronger(@strength, @v2.walkStrength) then Direction.FORWARD else Direction.BACKWARD) return BinaryConstraint::addToGraph = -> @v1.addConstraint this @v2.addConstraint this @direction = Direction.NONE return BinaryConstraint::isSatisfied = -> @direction isnt Direction.NONE BinaryConstraint::markInputs = (mark) -> @input().mark = mark return BinaryConstraint::input = -> (if (@direction is Direction.FORWARD) then @v1 else @v2) BinaryConstraint::output = -> (if (@direction is Direction.FORWARD) then @v2 else @v1) BinaryConstraint::recalculate = -> ihn = @input() out = @output() out.walkStrength = Strength.weakestOf(@strength, ihn.walkStrength) out.stay = ihn.stay @execute() if out.stay return BinaryConstraint::markUnsatisfied = -> @direction = Direction.NONE return BinaryConstraint::inputsKnown = (mark) -> i = @input() i.mark is mark or i.stay or not i.determinedBy? BinaryConstraint::removeFromGraph = -> @v1.removeConstraint this if @v1? @v2.removeConstraint this if @v2? @direction = Direction.NONE return ScaleConstraint.inheritsFrom BinaryConstraint ScaleConstraint::addToGraph = -> ScaleConstraint.superConstructor::addToGraph.call this @scale.addConstraint this @offset.addConstraint this return ScaleConstraint::removeFromGraph = -> ScaleConstraint.superConstructor::removeFromGraph.call this @scale.removeConstraint this if @scale? @offset.removeConstraint this if @offset? return ScaleConstraint::markInputs = (mark) -> ScaleConstraint.superConstructor::markInputs.call this, mark @scale.mark = @offset.mark = mark return ScaleConstraint::execute = -> if @direction is Direction.FORWARD @v2.value = @v1.value * @scale.value + @offset.value else @v1.value = (@v2.value - @offset.value) / @scale.value return ScaleConstraint::recalculate = -> ihn = @input() out = @output() out.walkStrength = Strength.weakestOf(@strength, ihn.walkStrength) out.stay = ihn.stay and @scale.stay and @offset.stay @execute() if out.stay return EqualityConstraint.inheritsFrom BinaryConstraint EqualityConstraint::execute = -> @output().value = @input().value return Variable::addConstraint = (c) -> @constraints.add c return Variable::removeConstraint = (c) -> @constraints.remove c @determinedBy = null if @determinedBy is c return Planner::incrementalAdd = (c) -> mark = @newMark() overridden = c.satisfy(mark) overridden = overridden.satisfy(mark) while overridden? return Planner::incrementalRemove = (c) -> out = c.output() c.markUnsatisfied() c.removeFromGraph() unsatisfied = @removePropagateFrom(out) strength = Strength.REQUIRED loop i = 0 while i < unsatisfied.size() u = unsatisfied.at(i) @incrementalAdd u if u.strength is strength i++ strength = strength.nextWeaker() break unless strength isnt Strength.WEAKEST return Planner::newMark = -> ++@currentMark Planner::makePlan = (sources) -> mark = @newMark() plan = new Plan() todo = sources while todo.size() > 0 c = todo.removeFirst() if c.output().mark isnt mark and c.inputsKnown(mark) plan.addConstraint c c.output().mark = mark @addConstraintsConsumingTo c.output(), todo plan Planner::extractPlanFromConstraints = (constraints) -> sources = new OrderedCollection() i = 0 while i < constraints.size() c = constraints.at(i) sources.add c if c.isInput() and c.isSatisfied() i++ @makePlan sources Planner::addPropagate = (c, mark) -> todo = new OrderedCollection() todo.add c while todo.size() > 0 d = todo.removeFirst() if d.output().mark is mark @incrementalRemove c return false d.recalculate() @addConstraintsConsumingTo d.output(), todo true Planner::removePropagateFrom = (out) -> out.determinedBy = null out.walkStrength = Strength.WEAKEST out.stay = true unsatisfied = new OrderedCollection() todo = new OrderedCollection() todo.add out while todo.size() > 0 v = todo.removeFirst() i = 0 while i < v.constraints.size() c = v.constraints.at(i) unsatisfied.add c unless c.isSatisfied() i++ determining = v.determinedBy i = 0 while i < v.constraints.size() next = v.constraints.at(i) if next isnt determining and next.isSatisfied() next.recalculate() todo.add next.output() i++ unsatisfied Planner::addConstraintsConsumingTo = (v, coll) -> determining = v.determinedBy cc = v.constraints i = 0 while i < cc.size() c = cc.at(i) coll.add c if c isnt determining and c.isSatisfied() i++ return Plan::addConstraint = (c) -> @v.add c return Plan::size = -> @v.size() Plan::constraintAt = (index) -> @v.at index Plan::execute = -> i = 0 while i < @size() c = @constraintAt(i) c.execute() i++ return planner = null
[ { "context": "###\n# Author: iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo)\n#", "end": 21, "score": 0.9986658096313477, "start": 14, "tag": "USERNAME", "value": "iTonyYo" }, { "context": "###\n# Author: iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo)\n# Last Update (auth", "end": 39, "score": 0.9999278783798218, "start": 23, "tag": "EMAIL", "value": "ceo@holaever.com" }, { "context": "r: iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo)\n# Last Update (author): iTonyYo <ceo@holaever.co", "end": 68, "score": 0.9995915293693542, "start": 61, "tag": "USERNAME", "value": "iTonyYo" }, { "context": "ttps://github.com/iTonyYo)\n# Last Update (author): iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo)\n#", "end": 101, "score": 0.998927116394043, "start": 94, "tag": "USERNAME", "value": "iTonyYo" }, { "context": "hub.com/iTonyYo)\n# Last Update (author): iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo)\n###\n\n'use strict'\n\n", "end": 119, "score": 0.9999287128448486, "start": 103, "tag": "EMAIL", "value": "ceo@holaever.com" }, { "context": "): iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo)\n###\n\n'use strict'\n\ncfg = require '../conf", "end": 148, "score": 0.9996522068977356, "start": 141, "tag": "USERNAME", "value": "iTonyYo" } ]
node_modules/node-find-folder/gulp/clp.coffee
long-grass/mikey
0
### # Author: iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo) # Last Update (author): iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo) ### 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() parse_args = require 'minimist' __args = parse_args process.argv.slice(2), 'boolean': cfg.clp module.exports = __args
118130
### # Author: iTonyYo <<EMAIL>> (https://github.com/iTonyYo) # Last Update (author): iTonyYo <<EMAIL>> (https://github.com/iTonyYo) ### 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() parse_args = require 'minimist' __args = parse_args process.argv.slice(2), 'boolean': cfg.clp module.exports = __args
true
### # Author: iTonyYo <PI:EMAIL:<EMAIL>END_PI> (https://github.com/iTonyYo) # Last Update (author): iTonyYo <PI:EMAIL:<EMAIL>END_PI> (https://github.com/iTonyYo) ### 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() parse_args = require 'minimist' __args = parse_args process.argv.slice(2), 'boolean': cfg.clp module.exports = __args
[ { "context": "=================================\n# Copyright 2014 Hatio, Lab.\n# Licensed under The MIT License\n# http://o", "end": 67, "score": 0.9366964101791382, "start": 62, "tag": "NAME", "value": "Hatio" } ]
src/spec/SpecGroup.coffee
heartyoh/infopik
0
# ========================================== # Copyright 2014 Hatio, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ 'dou' 'KineticJS' ], (dou, kin) -> "use strict" drag_handler = (e) -> e.targetNode = this if not e.targetNode or e.targetNode is this.__background__ createView = (attributes) -> group = new kin.Group(attributes); background = new kin.Rect(dou.util.shallow_merge({}, attributes, {draggable: false, listening: true, x: 0, y: 0, id: undefined})) group.add background # Hack.. dragmove event lost its targetNode for background if(attributes.draggable) group.on 'dragstart dragmove dragend', drag_handler group.__background__ = background group createHandle = (attributes) -> return new Kin.Group(attributes) { type: 'group' name: 'group' containable: true container_type: 'container' description: 'Group Specification' defaults: { width: 100 height: 50 # fill: 'green' stroke: 'black' strokeWidth: 4 draggable: true listening: true opacity: 1 } view_factory_fn: createView handle_factory_fn: createHandle toolbox_image: 'images/toolbox_group.png' }
20539
# ========================================== # Copyright 2014 <NAME>, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ 'dou' 'KineticJS' ], (dou, kin) -> "use strict" drag_handler = (e) -> e.targetNode = this if not e.targetNode or e.targetNode is this.__background__ createView = (attributes) -> group = new kin.Group(attributes); background = new kin.Rect(dou.util.shallow_merge({}, attributes, {draggable: false, listening: true, x: 0, y: 0, id: undefined})) group.add background # Hack.. dragmove event lost its targetNode for background if(attributes.draggable) group.on 'dragstart dragmove dragend', drag_handler group.__background__ = background group createHandle = (attributes) -> return new Kin.Group(attributes) { type: 'group' name: 'group' containable: true container_type: 'container' description: 'Group Specification' defaults: { width: 100 height: 50 # fill: 'green' stroke: 'black' strokeWidth: 4 draggable: true listening: true opacity: 1 } view_factory_fn: createView handle_factory_fn: createHandle toolbox_image: 'images/toolbox_group.png' }
true
# ========================================== # Copyright 2014 PI:NAME:<NAME>END_PI, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ 'dou' 'KineticJS' ], (dou, kin) -> "use strict" drag_handler = (e) -> e.targetNode = this if not e.targetNode or e.targetNode is this.__background__ createView = (attributes) -> group = new kin.Group(attributes); background = new kin.Rect(dou.util.shallow_merge({}, attributes, {draggable: false, listening: true, x: 0, y: 0, id: undefined})) group.add background # Hack.. dragmove event lost its targetNode for background if(attributes.draggable) group.on 'dragstart dragmove dragend', drag_handler group.__background__ = background group createHandle = (attributes) -> return new Kin.Group(attributes) { type: 'group' name: 'group' containable: true container_type: 'container' description: 'Group Specification' defaults: { width: 100 height: 50 # fill: 'green' stroke: 'black' strokeWidth: 4 draggable: true listening: true opacity: 1 } view_factory_fn: createView handle_factory_fn: createHandle toolbox_image: 'images/toolbox_group.png' }
[ { "context": "\n\n compJID = \"comp.exmaple.tld\"\n clientJID = \"client@exmaple.tld\"\n\n createErrorIq = (type, code, msg, clazz, inst", "end": 297, "score": 0.9994378089904785, "start": 279, "tag": "EMAIL", "value": "client@exmaple.tld" }, { "context": "ses\", ->\n\n class User\n constructor: (@name, @age) ->\n\n @mgr.addClass \"user\", User,\n ", "end": 1831, "score": 0.9291667938232422, "start": 1827, "tag": "USERNAME", "value": "name" }, { "context": "st \"user\"\n class User\n constructor: (@name) -> @id = \"foo\"\n @mgr.addClass \"user\", User,", "end": 2433, "score": 0.8470010757446289, "start": 2429, "tag": "USERNAME", "value": "name" }, { "context": " .cnode(new joap.stanza.Attribute \"name\", \"Markus\").up()\n .cnode(new joap.stanza.Attribute \"", "end": 3846, "score": 0.9997198581695557, "start": 3840, "tag": "NAME", "value": "Markus" }, { "context": "al \"foo\"\n (expect instance.name).to.equal \"Markus\"\n (expect instance.age).to.equal 99\n ", "end": 4304, "score": 0.9997278451919556, "start": 4298, "tag": "NAME", "value": "Markus" }, { "context": " .cnode(new joap.stanza.Attribute \"name\", \"Markus\").up()\n @result = new ltx.Element \"iq\",\n ", "end": 4562, "score": 0.9996645450592041, "start": 4556, "tag": "NAME", "value": "Markus" }, { "context": "user.foo\n (expect instance.name).to.equal \"Markus\"\n (expect instance.age).to.equal 99\n ", "end": 4919, "score": 0.9997389912605286, "start": 4913, "tag": "NAME", "value": "Markus" }, { "context": "ctor: ->\n @id = \"foo\"\n @name = \"Markus\"\n @mgr.addClass \"user\", User\n @mgr.save", "end": 7075, "score": 0.9997972846031189, "start": 7069, "tag": "NAME", "value": "Markus" }, { "context": " .cnode(new joap.stanza.Attribute \"name\", \"Markus\")\n @run (res) => @compare res; done()\n\n ", "end": 7493, "score": 0.9997583627700806, "start": 7487, "tag": "NAME", "value": "Markus" }, { "context": "ctor: ->\n @id = \"foo\"\n @name = \"Markus\"\n @mgr.addClass \"user\", User\n @mgr.save", "end": 7686, "score": 0.999783992767334, "start": 7680, "tag": "NAME", "value": "Markus" }, { "context": " .cnode(new joap.stanza.Attribute \"name\", \"Markus\")\n @run (res) => @compare res; done()\n\n d", "end": 8097, "score": 0.9997663497924805, "start": 8091, "tag": "NAME", "value": "Markus" }, { "context": "tected\"]\n @mgr._objects.user.foo = new User \"Markus\", 123\n @request = createRequest \"edit\", \"use", "end": 8465, "score": 0.9997515678405762, "start": 8459, "tag": "NAME", "value": "Markus" }, { "context": "\"delete\", ->\n\n class User\n constructor: (@name, @age) -> @id = \"foo\"\n\n beforeEach ->\n @m", "end": 12670, "score": 0.9940859079360962, "start": 12666, "tag": "USERNAME", "value": "name" }, { "context": ": [\"id\"]\n @mgr._objects.user.foo = new User \"Markus\", 123\n @request = createRequest \"delete\", \"u", "end": 12885, "score": 0.9946924448013306, "start": 12879, "tag": "NAME", "value": "Markus" }, { "context": "escribe\", ->\n\n class User\n constructor: (@name, @age) ->\n @id = \"foo\"\n\n beforeEach ->\n", "end": 14121, "score": 0.9617994427680969, "start": 14117, "tag": "USERNAME", "value": "name" }, { "context": ": [\"id\"]\n @mgr._objects.user.foo = new User \"Markus\", 123\n @request = createRequest \"describe\"\n\n", "end": 14305, "score": 0.998856782913208, "start": 14299, "tag": "NAME", "value": "Markus" }, { "context": " * param\n @mgr._objects.user.foo = new User \"Markus\", 432\n\n it \"can handle an instance rpc request", "end": 15505, "score": 0.9988524913787842, "start": 15499, "tag": "NAME", "value": "Markus" } ]
spec/Manager.spec.coffee
flosse/node-xmpp-joap
0
chai = require 'chai' expect = chai.expect joap = require "../lib/node-xmpp-joap" ltx = require "ltx" { JID } = require "node-xmpp-core" JOAP_NS = "jabber:iq:joap" RPC_NS = "jabber:iq:rpc" describe "Manager", -> compJID = "comp.exmaple.tld" clientJID = "client@exmaple.tld" createErrorIq = (type, code, msg, clazz, instance) -> from = compJID from = "#{clazz}@#{from}" if clazz? from += "/#{instance}" if instance? errMsg = new joap.stanza.ErrorIq type, code, msg, to : clientJID from : from id : "#{type}_id_0" createRequest = (type, clazz, instance) -> to = compJID to = "#{clazz}@#{to}" if clazz? to += "/#{instance}" if instance? iq = new ltx.Element "iq", to : to from : clientJID id : "#{type}_id_0" type : 'set' if type is "query" iq.c type, xmlns:RPC_NS else iq.c type, xmlns:JOAP_NS iq xmppComp = channels: {} send: (data) -> process.nextTick -> xmppClient.onData data onData: (data) -> on: (channel, cb) -> @channels[channel] = cb connection: jid: new JID compJID xmppClient = send: (data) -> process.nextTick -> xmppComp.channels.stanza data onData: (data, cb) -> beforeEach -> @mgr = new joap.Manager xmppComp @compare = (res) -> (expect res.toString()).to.equal @result.toString() @run = (cb) -> xmppClient.onData = (data) -> cb data xmppClient.send @request it "creates objects for caching objetcs and classes", -> mgr = new joap.Manager xmppComp (expect typeof mgr.classes).to.equal "object" (expect typeof mgr._objects).to.equal "object" describe "registration of classes", -> it "supports a method to register classes", -> class User constructor: (@name, @age) -> @mgr.addClass "user", User, required: ["name"] protected: ["name"] userClz = @mgr.classes.user defAttrs = userClz.definitions.attributes (expect defAttrs.name.required).to.equal true (expect defAttrs.name.writable).to.equal false describe "add", -> createAddRequest = (clazz, instance) -> createRequest("add", clazz, instance) createAddErrorIq = (code, msg, clazz, instance) -> createErrorIq("add", code, msg, clazz, instance) beforeEach -> @request = createAddRequest "user" class User constructor: (@name) -> @id = "foo" @mgr.addClass "user", User, required: ["name"], protected: ["id"] it "returns an error if you are not authorized", (done) -> @result = createAddErrorIq '403', "You are not authorized", "user" @mgr.hasPermission = (a, next) -> next false, a @run (res) => @compare res; done() it "returns an error if address isn't a class", (done) -> @request.attrs.to += "/instance" @result = createAddErrorIq 405, "'user@#{compJID}/instance' isn't a class", "user", "instance" @run (res) => @compare res; done() it "returns an error if class doesn't exists", (done) -> @result = createAddErrorIq 404, "Class 'sun' does not exists", "sun" @request = createAddRequest "sun" @run (res) => @compare; done() it "returns an error if required attributes are not available", (done) -> @result = createAddErrorIq 406, "Invalid constructor parameters", "user" @run (res) => @compare res; done() it "returns an error if required attributes are not correct", (done) -> @request.getChild("add").cnode(new joap.stanza.Attribute "age", 33) @result = createAddErrorIq 406, "Invalid constructor parameters", "user" @run (res) => @compare res; done() it "returns the address of the new instance", (done) -> @request.getChild("add") .cnode(new joap.stanza.Attribute "name", "Markus").up() .cnode(new joap.stanza.Attribute "age", 99).up() @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}" id:'add_id_0' type:'result' @result.c("add", xmlns:JOAP_NS).c("newAddress").t("user@#{compJID}/foo") @run (result) => @compare result instance = @mgr._objects.user.foo (expect instance.id).to.equal "foo" (expect instance.name).to.equal "Markus" (expect instance.age).to.equal 99 done() it "takes care of the attribute names", (done) -> @request.getChild("add") .cnode(new joap.stanza.Attribute "age", 99).up() .cnode(new joap.stanza.Attribute "name", "Markus").up() @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}" id:'add_id_0' type:'result' @result.c("add", xmlns:JOAP_NS).c("newAddress").t("user@#{compJID}/foo") @run (result) => @compare result instance = @mgr._objects.user.foo (expect instance.name).to.equal "Markus" (expect instance.age).to.equal 99 done() it "creates a new ID", (done)-> class Sun @mgr.addClass "sun", Sun @request = createAddRequest "sun" @run (result) -> id = result.getChild("add").getChildText("newAddress").split('/')[1] (expect id).not.to.equal "foo" (expect id).not.to.equal "" (expect false).not.to.equal "" done() it "preserve an ID", (done) -> class Sun constructor: (@id)-> @mgr.addClass "sun", Sun @request = createAddRequest "sun" @request.getChild("add") .cnode(new joap.stanza.Attribute "id", 99.3) @run (result) -> id = result.getChild("add").getChildText("newAddress").split('/')[1] (expect id).to.equal '99.3' done() describe "read", -> beforeEach -> @request = createRequest "read", "user", "foo" it "returns an error if you are not authorized", (done) -> @result = createErrorIq "read", '403', "You are not authorized", "user", "foo" @mgr.hasPermission = (a, next) -> next false @run (res) => @compare res; done() it "returns an error if the class doesn't exists", (done) -> @result = createErrorIq "read", 404, "Class 'user' does not exists", "user", "foo" @run (res) => @compare res; done() it "returns an error if the instance doesn't exists", (done) -> @mgr.addClass "user", (->) @result = createErrorIq "read", 404, "Object 'foo' does not exists", "user", "foo" @run (res) => @compare res; done() it "returns an error if the specified attribute doesn't exists", (done) -> class User constructor: -> @id = "foo" @mgr.addClass "user", User @mgr.saveInstance {class:"user"}, (new User), (err, a, addr) => @request.getChild("read").c("name").t("age") @result = createErrorIq "read", 406, "Requested attribute 'age' doesn't exists", "user", "foo" @run (res) => @compare res; done() it "returns all attributes if nothing was specified", (done) -> class User constructor: -> @id = "foo" @name = "Markus" @mgr.addClass "user", User @mgr.saveInstance {class:"user"}, (new User), (err, a, addr) => @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'read_id_0' type:'result' @result.c("read", {xmlns: JOAP_NS}) .cnode(new joap.stanza.Attribute "id", "foo").up() .cnode(new joap.stanza.Attribute "name", "Markus") @run (res) => @compare res; done() it "returns only the specified attributes", (done) -> class User constructor: -> @id = "foo" @name = "Markus" @mgr.addClass "user", User @mgr.saveInstance {class:"user"}, (new User), (err, a, addr) => @request.getChild("read").c("name").t("name") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'read_id_0' type:'result' @result.c("read", {xmlns: JOAP_NS}) .cnode(new joap.stanza.Attribute "name", "Markus") @run (res) => @compare res; done() describe "edit", -> class User constructor: (@name, @age) -> @id = "foo" @instMethod = -> myMethod: -> @classMethod: -> beforeEach -> @mgr.addClass "user", User, required: ["name"] protected: ["protected"] @mgr._objects.user.foo = new User "Markus", 123 @request = createRequest "edit", "user", "foo" it "returns an error if you are not authorized", (done) -> @result = createErrorIq "edit", '403', "You are not authorized", "user", "foo" @mgr.hasPermission = (a, next) -> next false @run (res) => @compare res; done() it "returns an error if the instance doesn't exists", (done) -> @request = createRequest "edit", "user", "oof" @result = createErrorIq "edit", 404, "Object 'oof' does not exists", "user", "oof" @run (res) => @compare res; done() it "returns an error if specified object attributes are not writeable", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "protected", "oof") @result = createErrorIq "edit", 406, "Attribute 'protected' of class 'user' is not writeable", "user", "foo" @run (res) => @compare res; done() it "returns an error if specified object attribute is a method", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "myMethod", "fn") @result = createErrorIq "edit", 406, "Attribute 'myMethod' of class 'user' is not writeable", "user", "foo" @run (res) => @compare res; done() it "returns an error if specified object attribute is an instance method", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "instMethod", "fn") @result = createErrorIq "edit", 406, "Attribute 'instMethod' of class 'user' is not writeable", "user", "foo" @run (res) => @compare res; done() it "returns an error if specified object attribute is a class method", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "classMethod", "fn") @result = createErrorIq "edit", 406, "Attribute 'classMethod' of class 'user' is not writeable", "user", "foo" @run (res) => @compare res; done() it "changes the specified attributes", (done) -> @request.getChild("edit") .cnode(new joap.stanza.Attribute "name", "oof").up() .cnode(new joap.stanza.Attribute "new", "attr") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'edit_id_0' type:'result' @result.c("edit", {xmlns: JOAP_NS}) @run (res) => instance = @mgr._objects.user.foo (expect instance.name).to.equal "oof" (expect instance.new).to.equal "attr" done() it "returns a new address if the id changed", (done) -> @request.getChild("edit") .cnode(new joap.stanza.Attribute "id", "newId") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'edit_id_0' type:'result' @result.c("edit", {xmlns: JOAP_NS}) .c("newAddress").t("user@#{compJID}/newId") @run (res) => @compare res instance = @mgr._objects.user.newId (expect typeof instance).to.equal "object" (expect instance.id).to.equal "newId" done() it "can be modified before editing", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "foo", "bar").up() @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'edit_id_0' type:'result' @result.c("edit", {xmlns: JOAP_NS}) @mgr.onEnter "edit", (a, next) -> a.attributes.foo = "modified" next null, a (expect @mgr._handlers.enter.edit.length).to.equal 1 @run => instance = @mgr._objects.user.foo (expect instance.foo).to.equal "modified" done() it "returns an error if a modifying function failed", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "foo", "bar").up() @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'edit_id_0' type:'result' @result.c("edit", {xmlns: JOAP_NS}) @mgr.onEnter "edit", (a, next) -> next (new Error "an error occoured"), a (expect @mgr._handlers.enter.edit.length).to.equal 1 @run (res) -> (expect res.getChild "error").to.exist done() describe "delete", -> class User constructor: (@name, @age) -> @id = "foo" beforeEach -> @mgr = new joap.Manager xmppComp @mgr.addClass "user", User, required: ["name"] protected: ["id"] @mgr._objects.user.foo = new User "Markus", 123 @request = createRequest "delete", "user", "foo" it "returns an error if you are not authorized", (done) -> @result = createErrorIq "delete", '403', "You are not authorized", "user", "foo" @mgr.hasPermission = (a, next) -> next false @run (res) => @compare res; done() it "returns an error if the instance doesn't exists", (done) -> @request = createRequest "delete", "user", "oof" @result = createErrorIq "delete", 404, "Object 'oof' does not exists", "user", "oof" @run (res) => @compare res; done() it "returns an error if address is not an instance", (done) -> @request = createRequest "delete" @result = createErrorIq "delete", 405, "'#{compJID}' is not an instance" @run (res) => @compare res; done() it "deletes the specified instance", (done) -> @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'delete_id_0' type:'result' @result.c("delete", {xmlns: JOAP_NS}) users = @mgr._objects.user (expect users.foo).to.exist @run (res) => (expect users.foo).not.to.exist done() describe "describe", -> class User constructor: (@name, @age) -> @id = "foo" beforeEach -> @mgr.addClass "user", User, required: ["name"] protected: ["id"] @mgr._objects.user.foo = new User "Markus", 123 @request = createRequest "describe" it "returns the describtion of the object server", (done) -> serverDesc = "This server manages users" @mgr.serverDescription = { "en-US":serverDesc } @mgr.serverAttributes = x: {type: "int", desc: {"en-US": "a magic number"}, writable: false } @result = new ltx.Element "iq", to:clientJID from:compJID id:'describe_id_0' type:'result' @result.c("describe", {xmlns: JOAP_NS}) .c("desc", "xml:lang":'en-US').t(serverDesc).up() .c("attributeDescription", writable:'false') .c("name").t("x").up() .c("type").t("int").up() .c("desc","xml:lang":'en-US').t("a magic number").up().up() .c("class").t("user").up() @run (res) => @compare res; done() describe "rpc", -> class User constructor: (@name, @age) -> @id = "foo" getAge: -> @age @classMethod: (nr) -> 50 + nr beforeEach -> @mgr.addClass "user", User, required: ["name", "age"] protected: ["id"] @mgr.addServerMethod "serverMethod", (param) -> 2 * param @mgr._objects.user.foo = new User "Markus", 432 it "can handle an instance rpc request", (done) -> @request = createRequest "query", "user", "foo" @request.children[0].c("methodCall").c("methodName").t("getAge") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'query_id_0' type:'result' @result.c("query", {xmlns: RPC_NS}) .c("methodResponse").c("params").c("param").c("value").c("int").t("432") @run (res) => @compare res; done() it "can handle a class rpc request", (done) -> @request = createRequest "query", "user" @request.children[0].c("methodCall") .c("methodName").t("classMethod").up() .c("params").c("param").c("value").c("int").t("5") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}" id:'query_id_0' type:'result' @result.c("query", {xmlns: RPC_NS}) .c("methodResponse").c("params").c("param").c("value").c("int").t("55") @run (res) => @compare res; done() it "can handle a server rpc request", (done) -> @request = createRequest "query" @request.children[0].c("methodCall") .c("methodName").t("serverMethod").up() .c("params").c("param").c("value").c("int").t("3") @result = new ltx.Element "iq", to:clientJID from: compJID id:'query_id_0' type:'result' @result.c("query", {xmlns: RPC_NS}) .c("methodResponse").c("params").c("param").c("value").c("int").t("6") @run (res) => @compare res; done() it "sends an rpc error if something went wrong", (done) -> @request = createRequest "query", "user", "foo" @request.children[0].c("methodCall").c("methodName").t("invalidMethod") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'query_id_0' type:'error' @result.c("query", {xmlns: RPC_NS}) .c("methodResponse").c("fault").c("value").c("struct") .c("member") .c("name").t("faultCode").up() .c("value").c("int").t("0").up().up().up() .c("member") .c("name").t("faultString").up() .c("value").c("string").t("Instance method 'invalidMethod' does not exist").up().up() @run (res) => @compare res; done()
199495
chai = require 'chai' expect = chai.expect joap = require "../lib/node-xmpp-joap" ltx = require "ltx" { JID } = require "node-xmpp-core" JOAP_NS = "jabber:iq:joap" RPC_NS = "jabber:iq:rpc" describe "Manager", -> compJID = "comp.exmaple.tld" clientJID = "<EMAIL>" createErrorIq = (type, code, msg, clazz, instance) -> from = compJID from = "#{clazz}@#{from}" if clazz? from += "/#{instance}" if instance? errMsg = new joap.stanza.ErrorIq type, code, msg, to : clientJID from : from id : "#{type}_id_0" createRequest = (type, clazz, instance) -> to = compJID to = "#{clazz}@#{to}" if clazz? to += "/#{instance}" if instance? iq = new ltx.Element "iq", to : to from : clientJID id : "#{type}_id_0" type : 'set' if type is "query" iq.c type, xmlns:RPC_NS else iq.c type, xmlns:JOAP_NS iq xmppComp = channels: {} send: (data) -> process.nextTick -> xmppClient.onData data onData: (data) -> on: (channel, cb) -> @channels[channel] = cb connection: jid: new JID compJID xmppClient = send: (data) -> process.nextTick -> xmppComp.channels.stanza data onData: (data, cb) -> beforeEach -> @mgr = new joap.Manager xmppComp @compare = (res) -> (expect res.toString()).to.equal @result.toString() @run = (cb) -> xmppClient.onData = (data) -> cb data xmppClient.send @request it "creates objects for caching objetcs and classes", -> mgr = new joap.Manager xmppComp (expect typeof mgr.classes).to.equal "object" (expect typeof mgr._objects).to.equal "object" describe "registration of classes", -> it "supports a method to register classes", -> class User constructor: (@name, @age) -> @mgr.addClass "user", User, required: ["name"] protected: ["name"] userClz = @mgr.classes.user defAttrs = userClz.definitions.attributes (expect defAttrs.name.required).to.equal true (expect defAttrs.name.writable).to.equal false describe "add", -> createAddRequest = (clazz, instance) -> createRequest("add", clazz, instance) createAddErrorIq = (code, msg, clazz, instance) -> createErrorIq("add", code, msg, clazz, instance) beforeEach -> @request = createAddRequest "user" class User constructor: (@name) -> @id = "foo" @mgr.addClass "user", User, required: ["name"], protected: ["id"] it "returns an error if you are not authorized", (done) -> @result = createAddErrorIq '403', "You are not authorized", "user" @mgr.hasPermission = (a, next) -> next false, a @run (res) => @compare res; done() it "returns an error if address isn't a class", (done) -> @request.attrs.to += "/instance" @result = createAddErrorIq 405, "'user@#{compJID}/instance' isn't a class", "user", "instance" @run (res) => @compare res; done() it "returns an error if class doesn't exists", (done) -> @result = createAddErrorIq 404, "Class 'sun' does not exists", "sun" @request = createAddRequest "sun" @run (res) => @compare; done() it "returns an error if required attributes are not available", (done) -> @result = createAddErrorIq 406, "Invalid constructor parameters", "user" @run (res) => @compare res; done() it "returns an error if required attributes are not correct", (done) -> @request.getChild("add").cnode(new joap.stanza.Attribute "age", 33) @result = createAddErrorIq 406, "Invalid constructor parameters", "user" @run (res) => @compare res; done() it "returns the address of the new instance", (done) -> @request.getChild("add") .cnode(new joap.stanza.Attribute "name", "<NAME>").up() .cnode(new joap.stanza.Attribute "age", 99).up() @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}" id:'add_id_0' type:'result' @result.c("add", xmlns:JOAP_NS).c("newAddress").t("user@#{compJID}/foo") @run (result) => @compare result instance = @mgr._objects.user.foo (expect instance.id).to.equal "foo" (expect instance.name).to.equal "<NAME>" (expect instance.age).to.equal 99 done() it "takes care of the attribute names", (done) -> @request.getChild("add") .cnode(new joap.stanza.Attribute "age", 99).up() .cnode(new joap.stanza.Attribute "name", "<NAME>").up() @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}" id:'add_id_0' type:'result' @result.c("add", xmlns:JOAP_NS).c("newAddress").t("user@#{compJID}/foo") @run (result) => @compare result instance = @mgr._objects.user.foo (expect instance.name).to.equal "<NAME>" (expect instance.age).to.equal 99 done() it "creates a new ID", (done)-> class Sun @mgr.addClass "sun", Sun @request = createAddRequest "sun" @run (result) -> id = result.getChild("add").getChildText("newAddress").split('/')[1] (expect id).not.to.equal "foo" (expect id).not.to.equal "" (expect false).not.to.equal "" done() it "preserve an ID", (done) -> class Sun constructor: (@id)-> @mgr.addClass "sun", Sun @request = createAddRequest "sun" @request.getChild("add") .cnode(new joap.stanza.Attribute "id", 99.3) @run (result) -> id = result.getChild("add").getChildText("newAddress").split('/')[1] (expect id).to.equal '99.3' done() describe "read", -> beforeEach -> @request = createRequest "read", "user", "foo" it "returns an error if you are not authorized", (done) -> @result = createErrorIq "read", '403', "You are not authorized", "user", "foo" @mgr.hasPermission = (a, next) -> next false @run (res) => @compare res; done() it "returns an error if the class doesn't exists", (done) -> @result = createErrorIq "read", 404, "Class 'user' does not exists", "user", "foo" @run (res) => @compare res; done() it "returns an error if the instance doesn't exists", (done) -> @mgr.addClass "user", (->) @result = createErrorIq "read", 404, "Object 'foo' does not exists", "user", "foo" @run (res) => @compare res; done() it "returns an error if the specified attribute doesn't exists", (done) -> class User constructor: -> @id = "foo" @mgr.addClass "user", User @mgr.saveInstance {class:"user"}, (new User), (err, a, addr) => @request.getChild("read").c("name").t("age") @result = createErrorIq "read", 406, "Requested attribute 'age' doesn't exists", "user", "foo" @run (res) => @compare res; done() it "returns all attributes if nothing was specified", (done) -> class User constructor: -> @id = "foo" @name = "<NAME>" @mgr.addClass "user", User @mgr.saveInstance {class:"user"}, (new User), (err, a, addr) => @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'read_id_0' type:'result' @result.c("read", {xmlns: JOAP_NS}) .cnode(new joap.stanza.Attribute "id", "foo").up() .cnode(new joap.stanza.Attribute "name", "<NAME>") @run (res) => @compare res; done() it "returns only the specified attributes", (done) -> class User constructor: -> @id = "foo" @name = "<NAME>" @mgr.addClass "user", User @mgr.saveInstance {class:"user"}, (new User), (err, a, addr) => @request.getChild("read").c("name").t("name") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'read_id_0' type:'result' @result.c("read", {xmlns: JOAP_NS}) .cnode(new joap.stanza.Attribute "name", "<NAME>") @run (res) => @compare res; done() describe "edit", -> class User constructor: (@name, @age) -> @id = "foo" @instMethod = -> myMethod: -> @classMethod: -> beforeEach -> @mgr.addClass "user", User, required: ["name"] protected: ["protected"] @mgr._objects.user.foo = new User "<NAME>", 123 @request = createRequest "edit", "user", "foo" it "returns an error if you are not authorized", (done) -> @result = createErrorIq "edit", '403', "You are not authorized", "user", "foo" @mgr.hasPermission = (a, next) -> next false @run (res) => @compare res; done() it "returns an error if the instance doesn't exists", (done) -> @request = createRequest "edit", "user", "oof" @result = createErrorIq "edit", 404, "Object 'oof' does not exists", "user", "oof" @run (res) => @compare res; done() it "returns an error if specified object attributes are not writeable", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "protected", "oof") @result = createErrorIq "edit", 406, "Attribute 'protected' of class 'user' is not writeable", "user", "foo" @run (res) => @compare res; done() it "returns an error if specified object attribute is a method", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "myMethod", "fn") @result = createErrorIq "edit", 406, "Attribute 'myMethod' of class 'user' is not writeable", "user", "foo" @run (res) => @compare res; done() it "returns an error if specified object attribute is an instance method", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "instMethod", "fn") @result = createErrorIq "edit", 406, "Attribute 'instMethod' of class 'user' is not writeable", "user", "foo" @run (res) => @compare res; done() it "returns an error if specified object attribute is a class method", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "classMethod", "fn") @result = createErrorIq "edit", 406, "Attribute 'classMethod' of class 'user' is not writeable", "user", "foo" @run (res) => @compare res; done() it "changes the specified attributes", (done) -> @request.getChild("edit") .cnode(new joap.stanza.Attribute "name", "oof").up() .cnode(new joap.stanza.Attribute "new", "attr") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'edit_id_0' type:'result' @result.c("edit", {xmlns: JOAP_NS}) @run (res) => instance = @mgr._objects.user.foo (expect instance.name).to.equal "oof" (expect instance.new).to.equal "attr" done() it "returns a new address if the id changed", (done) -> @request.getChild("edit") .cnode(new joap.stanza.Attribute "id", "newId") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'edit_id_0' type:'result' @result.c("edit", {xmlns: JOAP_NS}) .c("newAddress").t("user@#{compJID}/newId") @run (res) => @compare res instance = @mgr._objects.user.newId (expect typeof instance).to.equal "object" (expect instance.id).to.equal "newId" done() it "can be modified before editing", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "foo", "bar").up() @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'edit_id_0' type:'result' @result.c("edit", {xmlns: JOAP_NS}) @mgr.onEnter "edit", (a, next) -> a.attributes.foo = "modified" next null, a (expect @mgr._handlers.enter.edit.length).to.equal 1 @run => instance = @mgr._objects.user.foo (expect instance.foo).to.equal "modified" done() it "returns an error if a modifying function failed", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "foo", "bar").up() @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'edit_id_0' type:'result' @result.c("edit", {xmlns: JOAP_NS}) @mgr.onEnter "edit", (a, next) -> next (new Error "an error occoured"), a (expect @mgr._handlers.enter.edit.length).to.equal 1 @run (res) -> (expect res.getChild "error").to.exist done() describe "delete", -> class User constructor: (@name, @age) -> @id = "foo" beforeEach -> @mgr = new joap.Manager xmppComp @mgr.addClass "user", User, required: ["name"] protected: ["id"] @mgr._objects.user.foo = new User "<NAME>", 123 @request = createRequest "delete", "user", "foo" it "returns an error if you are not authorized", (done) -> @result = createErrorIq "delete", '403', "You are not authorized", "user", "foo" @mgr.hasPermission = (a, next) -> next false @run (res) => @compare res; done() it "returns an error if the instance doesn't exists", (done) -> @request = createRequest "delete", "user", "oof" @result = createErrorIq "delete", 404, "Object 'oof' does not exists", "user", "oof" @run (res) => @compare res; done() it "returns an error if address is not an instance", (done) -> @request = createRequest "delete" @result = createErrorIq "delete", 405, "'#{compJID}' is not an instance" @run (res) => @compare res; done() it "deletes the specified instance", (done) -> @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'delete_id_0' type:'result' @result.c("delete", {xmlns: JOAP_NS}) users = @mgr._objects.user (expect users.foo).to.exist @run (res) => (expect users.foo).not.to.exist done() describe "describe", -> class User constructor: (@name, @age) -> @id = "foo" beforeEach -> @mgr.addClass "user", User, required: ["name"] protected: ["id"] @mgr._objects.user.foo = new User "<NAME>", 123 @request = createRequest "describe" it "returns the describtion of the object server", (done) -> serverDesc = "This server manages users" @mgr.serverDescription = { "en-US":serverDesc } @mgr.serverAttributes = x: {type: "int", desc: {"en-US": "a magic number"}, writable: false } @result = new ltx.Element "iq", to:clientJID from:compJID id:'describe_id_0' type:'result' @result.c("describe", {xmlns: JOAP_NS}) .c("desc", "xml:lang":'en-US').t(serverDesc).up() .c("attributeDescription", writable:'false') .c("name").t("x").up() .c("type").t("int").up() .c("desc","xml:lang":'en-US').t("a magic number").up().up() .c("class").t("user").up() @run (res) => @compare res; done() describe "rpc", -> class User constructor: (@name, @age) -> @id = "foo" getAge: -> @age @classMethod: (nr) -> 50 + nr beforeEach -> @mgr.addClass "user", User, required: ["name", "age"] protected: ["id"] @mgr.addServerMethod "serverMethod", (param) -> 2 * param @mgr._objects.user.foo = new User "<NAME>", 432 it "can handle an instance rpc request", (done) -> @request = createRequest "query", "user", "foo" @request.children[0].c("methodCall").c("methodName").t("getAge") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'query_id_0' type:'result' @result.c("query", {xmlns: RPC_NS}) .c("methodResponse").c("params").c("param").c("value").c("int").t("432") @run (res) => @compare res; done() it "can handle a class rpc request", (done) -> @request = createRequest "query", "user" @request.children[0].c("methodCall") .c("methodName").t("classMethod").up() .c("params").c("param").c("value").c("int").t("5") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}" id:'query_id_0' type:'result' @result.c("query", {xmlns: RPC_NS}) .c("methodResponse").c("params").c("param").c("value").c("int").t("55") @run (res) => @compare res; done() it "can handle a server rpc request", (done) -> @request = createRequest "query" @request.children[0].c("methodCall") .c("methodName").t("serverMethod").up() .c("params").c("param").c("value").c("int").t("3") @result = new ltx.Element "iq", to:clientJID from: compJID id:'query_id_0' type:'result' @result.c("query", {xmlns: RPC_NS}) .c("methodResponse").c("params").c("param").c("value").c("int").t("6") @run (res) => @compare res; done() it "sends an rpc error if something went wrong", (done) -> @request = createRequest "query", "user", "foo" @request.children[0].c("methodCall").c("methodName").t("invalidMethod") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'query_id_0' type:'error' @result.c("query", {xmlns: RPC_NS}) .c("methodResponse").c("fault").c("value").c("struct") .c("member") .c("name").t("faultCode").up() .c("value").c("int").t("0").up().up().up() .c("member") .c("name").t("faultString").up() .c("value").c("string").t("Instance method 'invalidMethod' does not exist").up().up() @run (res) => @compare res; done()
true
chai = require 'chai' expect = chai.expect joap = require "../lib/node-xmpp-joap" ltx = require "ltx" { JID } = require "node-xmpp-core" JOAP_NS = "jabber:iq:joap" RPC_NS = "jabber:iq:rpc" describe "Manager", -> compJID = "comp.exmaple.tld" clientJID = "PI:EMAIL:<EMAIL>END_PI" createErrorIq = (type, code, msg, clazz, instance) -> from = compJID from = "#{clazz}@#{from}" if clazz? from += "/#{instance}" if instance? errMsg = new joap.stanza.ErrorIq type, code, msg, to : clientJID from : from id : "#{type}_id_0" createRequest = (type, clazz, instance) -> to = compJID to = "#{clazz}@#{to}" if clazz? to += "/#{instance}" if instance? iq = new ltx.Element "iq", to : to from : clientJID id : "#{type}_id_0" type : 'set' if type is "query" iq.c type, xmlns:RPC_NS else iq.c type, xmlns:JOAP_NS iq xmppComp = channels: {} send: (data) -> process.nextTick -> xmppClient.onData data onData: (data) -> on: (channel, cb) -> @channels[channel] = cb connection: jid: new JID compJID xmppClient = send: (data) -> process.nextTick -> xmppComp.channels.stanza data onData: (data, cb) -> beforeEach -> @mgr = new joap.Manager xmppComp @compare = (res) -> (expect res.toString()).to.equal @result.toString() @run = (cb) -> xmppClient.onData = (data) -> cb data xmppClient.send @request it "creates objects for caching objetcs and classes", -> mgr = new joap.Manager xmppComp (expect typeof mgr.classes).to.equal "object" (expect typeof mgr._objects).to.equal "object" describe "registration of classes", -> it "supports a method to register classes", -> class User constructor: (@name, @age) -> @mgr.addClass "user", User, required: ["name"] protected: ["name"] userClz = @mgr.classes.user defAttrs = userClz.definitions.attributes (expect defAttrs.name.required).to.equal true (expect defAttrs.name.writable).to.equal false describe "add", -> createAddRequest = (clazz, instance) -> createRequest("add", clazz, instance) createAddErrorIq = (code, msg, clazz, instance) -> createErrorIq("add", code, msg, clazz, instance) beforeEach -> @request = createAddRequest "user" class User constructor: (@name) -> @id = "foo" @mgr.addClass "user", User, required: ["name"], protected: ["id"] it "returns an error if you are not authorized", (done) -> @result = createAddErrorIq '403', "You are not authorized", "user" @mgr.hasPermission = (a, next) -> next false, a @run (res) => @compare res; done() it "returns an error if address isn't a class", (done) -> @request.attrs.to += "/instance" @result = createAddErrorIq 405, "'user@#{compJID}/instance' isn't a class", "user", "instance" @run (res) => @compare res; done() it "returns an error if class doesn't exists", (done) -> @result = createAddErrorIq 404, "Class 'sun' does not exists", "sun" @request = createAddRequest "sun" @run (res) => @compare; done() it "returns an error if required attributes are not available", (done) -> @result = createAddErrorIq 406, "Invalid constructor parameters", "user" @run (res) => @compare res; done() it "returns an error if required attributes are not correct", (done) -> @request.getChild("add").cnode(new joap.stanza.Attribute "age", 33) @result = createAddErrorIq 406, "Invalid constructor parameters", "user" @run (res) => @compare res; done() it "returns the address of the new instance", (done) -> @request.getChild("add") .cnode(new joap.stanza.Attribute "name", "PI:NAME:<NAME>END_PI").up() .cnode(new joap.stanza.Attribute "age", 99).up() @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}" id:'add_id_0' type:'result' @result.c("add", xmlns:JOAP_NS).c("newAddress").t("user@#{compJID}/foo") @run (result) => @compare result instance = @mgr._objects.user.foo (expect instance.id).to.equal "foo" (expect instance.name).to.equal "PI:NAME:<NAME>END_PI" (expect instance.age).to.equal 99 done() it "takes care of the attribute names", (done) -> @request.getChild("add") .cnode(new joap.stanza.Attribute "age", 99).up() .cnode(new joap.stanza.Attribute "name", "PI:NAME:<NAME>END_PI").up() @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}" id:'add_id_0' type:'result' @result.c("add", xmlns:JOAP_NS).c("newAddress").t("user@#{compJID}/foo") @run (result) => @compare result instance = @mgr._objects.user.foo (expect instance.name).to.equal "PI:NAME:<NAME>END_PI" (expect instance.age).to.equal 99 done() it "creates a new ID", (done)-> class Sun @mgr.addClass "sun", Sun @request = createAddRequest "sun" @run (result) -> id = result.getChild("add").getChildText("newAddress").split('/')[1] (expect id).not.to.equal "foo" (expect id).not.to.equal "" (expect false).not.to.equal "" done() it "preserve an ID", (done) -> class Sun constructor: (@id)-> @mgr.addClass "sun", Sun @request = createAddRequest "sun" @request.getChild("add") .cnode(new joap.stanza.Attribute "id", 99.3) @run (result) -> id = result.getChild("add").getChildText("newAddress").split('/')[1] (expect id).to.equal '99.3' done() describe "read", -> beforeEach -> @request = createRequest "read", "user", "foo" it "returns an error if you are not authorized", (done) -> @result = createErrorIq "read", '403', "You are not authorized", "user", "foo" @mgr.hasPermission = (a, next) -> next false @run (res) => @compare res; done() it "returns an error if the class doesn't exists", (done) -> @result = createErrorIq "read", 404, "Class 'user' does not exists", "user", "foo" @run (res) => @compare res; done() it "returns an error if the instance doesn't exists", (done) -> @mgr.addClass "user", (->) @result = createErrorIq "read", 404, "Object 'foo' does not exists", "user", "foo" @run (res) => @compare res; done() it "returns an error if the specified attribute doesn't exists", (done) -> class User constructor: -> @id = "foo" @mgr.addClass "user", User @mgr.saveInstance {class:"user"}, (new User), (err, a, addr) => @request.getChild("read").c("name").t("age") @result = createErrorIq "read", 406, "Requested attribute 'age' doesn't exists", "user", "foo" @run (res) => @compare res; done() it "returns all attributes if nothing was specified", (done) -> class User constructor: -> @id = "foo" @name = "PI:NAME:<NAME>END_PI" @mgr.addClass "user", User @mgr.saveInstance {class:"user"}, (new User), (err, a, addr) => @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'read_id_0' type:'result' @result.c("read", {xmlns: JOAP_NS}) .cnode(new joap.stanza.Attribute "id", "foo").up() .cnode(new joap.stanza.Attribute "name", "PI:NAME:<NAME>END_PI") @run (res) => @compare res; done() it "returns only the specified attributes", (done) -> class User constructor: -> @id = "foo" @name = "PI:NAME:<NAME>END_PI" @mgr.addClass "user", User @mgr.saveInstance {class:"user"}, (new User), (err, a, addr) => @request.getChild("read").c("name").t("name") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'read_id_0' type:'result' @result.c("read", {xmlns: JOAP_NS}) .cnode(new joap.stanza.Attribute "name", "PI:NAME:<NAME>END_PI") @run (res) => @compare res; done() describe "edit", -> class User constructor: (@name, @age) -> @id = "foo" @instMethod = -> myMethod: -> @classMethod: -> beforeEach -> @mgr.addClass "user", User, required: ["name"] protected: ["protected"] @mgr._objects.user.foo = new User "PI:NAME:<NAME>END_PI", 123 @request = createRequest "edit", "user", "foo" it "returns an error if you are not authorized", (done) -> @result = createErrorIq "edit", '403', "You are not authorized", "user", "foo" @mgr.hasPermission = (a, next) -> next false @run (res) => @compare res; done() it "returns an error if the instance doesn't exists", (done) -> @request = createRequest "edit", "user", "oof" @result = createErrorIq "edit", 404, "Object 'oof' does not exists", "user", "oof" @run (res) => @compare res; done() it "returns an error if specified object attributes are not writeable", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "protected", "oof") @result = createErrorIq "edit", 406, "Attribute 'protected' of class 'user' is not writeable", "user", "foo" @run (res) => @compare res; done() it "returns an error if specified object attribute is a method", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "myMethod", "fn") @result = createErrorIq "edit", 406, "Attribute 'myMethod' of class 'user' is not writeable", "user", "foo" @run (res) => @compare res; done() it "returns an error if specified object attribute is an instance method", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "instMethod", "fn") @result = createErrorIq "edit", 406, "Attribute 'instMethod' of class 'user' is not writeable", "user", "foo" @run (res) => @compare res; done() it "returns an error if specified object attribute is a class method", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "classMethod", "fn") @result = createErrorIq "edit", 406, "Attribute 'classMethod' of class 'user' is not writeable", "user", "foo" @run (res) => @compare res; done() it "changes the specified attributes", (done) -> @request.getChild("edit") .cnode(new joap.stanza.Attribute "name", "oof").up() .cnode(new joap.stanza.Attribute "new", "attr") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'edit_id_0' type:'result' @result.c("edit", {xmlns: JOAP_NS}) @run (res) => instance = @mgr._objects.user.foo (expect instance.name).to.equal "oof" (expect instance.new).to.equal "attr" done() it "returns a new address if the id changed", (done) -> @request.getChild("edit") .cnode(new joap.stanza.Attribute "id", "newId") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'edit_id_0' type:'result' @result.c("edit", {xmlns: JOAP_NS}) .c("newAddress").t("user@#{compJID}/newId") @run (res) => @compare res instance = @mgr._objects.user.newId (expect typeof instance).to.equal "object" (expect instance.id).to.equal "newId" done() it "can be modified before editing", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "foo", "bar").up() @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'edit_id_0' type:'result' @result.c("edit", {xmlns: JOAP_NS}) @mgr.onEnter "edit", (a, next) -> a.attributes.foo = "modified" next null, a (expect @mgr._handlers.enter.edit.length).to.equal 1 @run => instance = @mgr._objects.user.foo (expect instance.foo).to.equal "modified" done() it "returns an error if a modifying function failed", (done) -> @request.getChild("edit").cnode(new joap.stanza.Attribute "foo", "bar").up() @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'edit_id_0' type:'result' @result.c("edit", {xmlns: JOAP_NS}) @mgr.onEnter "edit", (a, next) -> next (new Error "an error occoured"), a (expect @mgr._handlers.enter.edit.length).to.equal 1 @run (res) -> (expect res.getChild "error").to.exist done() describe "delete", -> class User constructor: (@name, @age) -> @id = "foo" beforeEach -> @mgr = new joap.Manager xmppComp @mgr.addClass "user", User, required: ["name"] protected: ["id"] @mgr._objects.user.foo = new User "PI:NAME:<NAME>END_PI", 123 @request = createRequest "delete", "user", "foo" it "returns an error if you are not authorized", (done) -> @result = createErrorIq "delete", '403', "You are not authorized", "user", "foo" @mgr.hasPermission = (a, next) -> next false @run (res) => @compare res; done() it "returns an error if the instance doesn't exists", (done) -> @request = createRequest "delete", "user", "oof" @result = createErrorIq "delete", 404, "Object 'oof' does not exists", "user", "oof" @run (res) => @compare res; done() it "returns an error if address is not an instance", (done) -> @request = createRequest "delete" @result = createErrorIq "delete", 405, "'#{compJID}' is not an instance" @run (res) => @compare res; done() it "deletes the specified instance", (done) -> @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'delete_id_0' type:'result' @result.c("delete", {xmlns: JOAP_NS}) users = @mgr._objects.user (expect users.foo).to.exist @run (res) => (expect users.foo).not.to.exist done() describe "describe", -> class User constructor: (@name, @age) -> @id = "foo" beforeEach -> @mgr.addClass "user", User, required: ["name"] protected: ["id"] @mgr._objects.user.foo = new User "PI:NAME:<NAME>END_PI", 123 @request = createRequest "describe" it "returns the describtion of the object server", (done) -> serverDesc = "This server manages users" @mgr.serverDescription = { "en-US":serverDesc } @mgr.serverAttributes = x: {type: "int", desc: {"en-US": "a magic number"}, writable: false } @result = new ltx.Element "iq", to:clientJID from:compJID id:'describe_id_0' type:'result' @result.c("describe", {xmlns: JOAP_NS}) .c("desc", "xml:lang":'en-US').t(serverDesc).up() .c("attributeDescription", writable:'false') .c("name").t("x").up() .c("type").t("int").up() .c("desc","xml:lang":'en-US').t("a magic number").up().up() .c("class").t("user").up() @run (res) => @compare res; done() describe "rpc", -> class User constructor: (@name, @age) -> @id = "foo" getAge: -> @age @classMethod: (nr) -> 50 + nr beforeEach -> @mgr.addClass "user", User, required: ["name", "age"] protected: ["id"] @mgr.addServerMethod "serverMethod", (param) -> 2 * param @mgr._objects.user.foo = new User "PI:NAME:<NAME>END_PI", 432 it "can handle an instance rpc request", (done) -> @request = createRequest "query", "user", "foo" @request.children[0].c("methodCall").c("methodName").t("getAge") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'query_id_0' type:'result' @result.c("query", {xmlns: RPC_NS}) .c("methodResponse").c("params").c("param").c("value").c("int").t("432") @run (res) => @compare res; done() it "can handle a class rpc request", (done) -> @request = createRequest "query", "user" @request.children[0].c("methodCall") .c("methodName").t("classMethod").up() .c("params").c("param").c("value").c("int").t("5") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}" id:'query_id_0' type:'result' @result.c("query", {xmlns: RPC_NS}) .c("methodResponse").c("params").c("param").c("value").c("int").t("55") @run (res) => @compare res; done() it "can handle a server rpc request", (done) -> @request = createRequest "query" @request.children[0].c("methodCall") .c("methodName").t("serverMethod").up() .c("params").c("param").c("value").c("int").t("3") @result = new ltx.Element "iq", to:clientJID from: compJID id:'query_id_0' type:'result' @result.c("query", {xmlns: RPC_NS}) .c("methodResponse").c("params").c("param").c("value").c("int").t("6") @run (res) => @compare res; done() it "sends an rpc error if something went wrong", (done) -> @request = createRequest "query", "user", "foo" @request.children[0].c("methodCall").c("methodName").t("invalidMethod") @result = new ltx.Element "iq", to:clientJID from:"user@#{compJID}/foo" id:'query_id_0' type:'error' @result.c("query", {xmlns: RPC_NS}) .c("methodResponse").c("fault").c("value").c("struct") .c("member") .c("name").t("faultCode").up() .c("value").c("int").t("0").up().up().up() .c("member") .c("name").t("faultString").up() .c("value").c("string").t("Instance method 'invalidMethod' does not exist").up().up() @run (res) => @compare res; done()
[ { "context": "ht?'\n options: [\n { value: 'male', text: 'Man' }\n { value: 'female', text: 'Vrouw' }\n ", "end": 225, "score": 0.9197440147399902, "start": 222, "tag": "NAME", "value": "Man" }, { "context": "e', text: 'Man' }\n { value: 'female', text: 'Vrouw' }\n { value: 'other', text: 'Anders' }\n ]", "end": 266, "score": 0.9113290309906006, "start": 261, "tag": "NAME", "value": "Vrouw" }, { "context": "', text: 'Vrouw' }\n { value: 'other', text: 'Anders' }\n ]\n ), (\n id: 'age'\n text: 'Wat is u", "end": 307, "score": 0.9953917264938354, "start": 301, "tag": "NAME", "value": "Anders" } ]
app/assets/javascripts/components/CompletionForm.coffee
roqua/screensmart
2
{ div, input, option, span, small, ul, li, p, label, button, form, i } = React.DOM { reduxForm } = ReduxForm questions = [ ( id: 'gender' text: 'Wat is uw geslacht?' options: [ { value: 'male', text: 'Man' } { value: 'female', text: 'Vrouw' } { value: 'other', text: 'Anders' } ] ), ( id: 'age' text: 'Wat is uw leeftijd?' ), ( id: 'educationLevel' text: 'Wat is uw opleidingsniveau (hoogst afgerond)?' options: [ { value: 'vmbo_or_below', text: 'VMBO of lager' } { value: 'mbo', text: 'MBO' } { value: 'havo', text: 'HAVO' } { value: 'vwo', text: 'VWO' } { value: 'hbo', text: 'HBO' } { value: 'wo', text: 'WO' } ] ), ( id: 'employmentStatus' intro: 'Kies hetgeen waar u de meeste tijd aan besteedt' text: 'Volgt u een opleiding of heeft u werk?' options: [ { value: 'education', text: 'Opleiding' } { value: 'looking_for_work', text: 'Werkzoekend' } { value: 'parttime', text: 'Parttime' } { value: 'fulltime', text: 'Fulltime' } ] ), ( id: 'relationshipStatus', text: 'Heeft u een relatie?' options: [ { value: 'single', text: 'Alleenstaand' } { value: 'living_alone_together', text: 'Latrelatie (living apart together)' } { value: 'living_together', text: 'Samenwonend' } ] ) ] questionIds = questions.map (question) -> question.id completionForm = React.createClass displayName: 'CompletionForm' submit: (enteredValues) -> { dispatch } = Screensmart.store dispatch Screensmart.Actions.finishResponse(@props.responseUuid, @props.values) render: -> { fields, handleSubmit, valid, submitFailed, submitting } = @props form className: 'form completion-form' onSubmit: handleSubmit(@submit) questions.map (question) => div key: question.id className: 'question' p className: 'intro-text' small className: '' question.intro p className: 'text' question.text if question.options # If not: assume integer text field ul className: 'options' question.options.map (option) => id = "#{question.id}-#{option.value}" li key: option.value className: 'option' input \ merge fields[question.id], type: 'radio' name: question.id id: id value: option.value label className: 'text' htmlFor: id option.text else input \ merge fields[question.id], type: 'text' name: question.id button type: 'submit' disabled: !valid || @finishing 'Afronden' div className: 'sent-form-info' unless valid div className: 'warning' i className: 'fa fa-exclamation-circle' 'Vul a.u.b. alle bovenstaande vragen in' if submitting div className: 'submitting' i className: 'fa fa-hourglass-half' 'Wordt verzonden' validate = (values) -> errors = {} questionIds.forEach (field) -> errors[field] = 'Beantwoord deze vraag' unless values[field] != undefined && values[field] != '' errors @CompletionForm = reduxForm( form: 'demographicInfo' fields: questionIds validate: validate )(completionForm)
52081
{ div, input, option, span, small, ul, li, p, label, button, form, i } = React.DOM { reduxForm } = ReduxForm questions = [ ( id: 'gender' text: 'Wat is uw geslacht?' options: [ { value: 'male', text: '<NAME>' } { value: 'female', text: '<NAME>' } { value: 'other', text: '<NAME>' } ] ), ( id: 'age' text: 'Wat is uw leeftijd?' ), ( id: 'educationLevel' text: 'Wat is uw opleidingsniveau (hoogst afgerond)?' options: [ { value: 'vmbo_or_below', text: 'VMBO of lager' } { value: 'mbo', text: 'MBO' } { value: 'havo', text: 'HAVO' } { value: 'vwo', text: 'VWO' } { value: 'hbo', text: 'HBO' } { value: 'wo', text: 'WO' } ] ), ( id: 'employmentStatus' intro: 'Kies hetgeen waar u de meeste tijd aan besteedt' text: 'Volgt u een opleiding of heeft u werk?' options: [ { value: 'education', text: 'Opleiding' } { value: 'looking_for_work', text: 'Werkzoekend' } { value: 'parttime', text: 'Parttime' } { value: 'fulltime', text: 'Fulltime' } ] ), ( id: 'relationshipStatus', text: 'Heeft u een relatie?' options: [ { value: 'single', text: 'Alleenstaand' } { value: 'living_alone_together', text: 'Latrelatie (living apart together)' } { value: 'living_together', text: 'Samenwonend' } ] ) ] questionIds = questions.map (question) -> question.id completionForm = React.createClass displayName: 'CompletionForm' submit: (enteredValues) -> { dispatch } = Screensmart.store dispatch Screensmart.Actions.finishResponse(@props.responseUuid, @props.values) render: -> { fields, handleSubmit, valid, submitFailed, submitting } = @props form className: 'form completion-form' onSubmit: handleSubmit(@submit) questions.map (question) => div key: question.id className: 'question' p className: 'intro-text' small className: '' question.intro p className: 'text' question.text if question.options # If not: assume integer text field ul className: 'options' question.options.map (option) => id = "#{question.id}-#{option.value}" li key: option.value className: 'option' input \ merge fields[question.id], type: 'radio' name: question.id id: id value: option.value label className: 'text' htmlFor: id option.text else input \ merge fields[question.id], type: 'text' name: question.id button type: 'submit' disabled: !valid || @finishing 'Afronden' div className: 'sent-form-info' unless valid div className: 'warning' i className: 'fa fa-exclamation-circle' 'Vul a.u.b. alle bovenstaande vragen in' if submitting div className: 'submitting' i className: 'fa fa-hourglass-half' 'Wordt verzonden' validate = (values) -> errors = {} questionIds.forEach (field) -> errors[field] = 'Beantwoord deze vraag' unless values[field] != undefined && values[field] != '' errors @CompletionForm = reduxForm( form: 'demographicInfo' fields: questionIds validate: validate )(completionForm)
true
{ div, input, option, span, small, ul, li, p, label, button, form, i } = React.DOM { reduxForm } = ReduxForm questions = [ ( id: 'gender' text: 'Wat is uw geslacht?' options: [ { value: 'male', text: 'PI:NAME:<NAME>END_PI' } { value: 'female', text: 'PI:NAME:<NAME>END_PI' } { value: 'other', text: 'PI:NAME:<NAME>END_PI' } ] ), ( id: 'age' text: 'Wat is uw leeftijd?' ), ( id: 'educationLevel' text: 'Wat is uw opleidingsniveau (hoogst afgerond)?' options: [ { value: 'vmbo_or_below', text: 'VMBO of lager' } { value: 'mbo', text: 'MBO' } { value: 'havo', text: 'HAVO' } { value: 'vwo', text: 'VWO' } { value: 'hbo', text: 'HBO' } { value: 'wo', text: 'WO' } ] ), ( id: 'employmentStatus' intro: 'Kies hetgeen waar u de meeste tijd aan besteedt' text: 'Volgt u een opleiding of heeft u werk?' options: [ { value: 'education', text: 'Opleiding' } { value: 'looking_for_work', text: 'Werkzoekend' } { value: 'parttime', text: 'Parttime' } { value: 'fulltime', text: 'Fulltime' } ] ), ( id: 'relationshipStatus', text: 'Heeft u een relatie?' options: [ { value: 'single', text: 'Alleenstaand' } { value: 'living_alone_together', text: 'Latrelatie (living apart together)' } { value: 'living_together', text: 'Samenwonend' } ] ) ] questionIds = questions.map (question) -> question.id completionForm = React.createClass displayName: 'CompletionForm' submit: (enteredValues) -> { dispatch } = Screensmart.store dispatch Screensmart.Actions.finishResponse(@props.responseUuid, @props.values) render: -> { fields, handleSubmit, valid, submitFailed, submitting } = @props form className: 'form completion-form' onSubmit: handleSubmit(@submit) questions.map (question) => div key: question.id className: 'question' p className: 'intro-text' small className: '' question.intro p className: 'text' question.text if question.options # If not: assume integer text field ul className: 'options' question.options.map (option) => id = "#{question.id}-#{option.value}" li key: option.value className: 'option' input \ merge fields[question.id], type: 'radio' name: question.id id: id value: option.value label className: 'text' htmlFor: id option.text else input \ merge fields[question.id], type: 'text' name: question.id button type: 'submit' disabled: !valid || @finishing 'Afronden' div className: 'sent-form-info' unless valid div className: 'warning' i className: 'fa fa-exclamation-circle' 'Vul a.u.b. alle bovenstaande vragen in' if submitting div className: 'submitting' i className: 'fa fa-hourglass-half' 'Wordt verzonden' validate = (values) -> errors = {} questionIds.forEach (field) -> errors[field] = 'Beantwoord deze vraag' unless values[field] != undefined && values[field] != '' errors @CompletionForm = reduxForm( form: 'demographicInfo' fields: questionIds validate: validate )(completionForm)
[ { "context": "'use strict'\n#\n# Ethan Mick\n# 2015\n#\n\nrequire('./lib/models/log')\n\n# connect ", "end": 27, "score": 0.9996950030326843, "start": 17, "tag": "NAME", "value": "Ethan Mick" } ]
init.coffee
ethanmick/metrics
0
'use strict' # # Ethan Mick # 2015 # require('./lib/models/log') # connect to the database # Start Hapi Server = require './lib/server' log = require 'winston' config = require './config' log.debug 'Start up', config ### # ToDo: Move this when we have a global config object ### s = new Server(config.http) s.setup(config).then -> s.start() .catch (err)-> log.error 'Server Startup Error!', err
14224
'use strict' # # <NAME> # 2015 # require('./lib/models/log') # connect to the database # Start Hapi Server = require './lib/server' log = require 'winston' config = require './config' log.debug 'Start up', config ### # ToDo: Move this when we have a global config object ### s = new Server(config.http) s.setup(config).then -> s.start() .catch (err)-> log.error 'Server Startup Error!', err
true
'use strict' # # PI:NAME:<NAME>END_PI # 2015 # require('./lib/models/log') # connect to the database # Start Hapi Server = require './lib/server' log = require 'winston' config = require './config' log.debug 'Start up', config ### # ToDo: Move this when we have a global config object ### s = new Server(config.http) s.setup(config).then -> s.start() .catch (err)-> log.error 'Server Startup Error!', err
[ { "context": "gent'\n]\n\nclass LocalStamp\n\n constructor: (@id = 'test', @config = {})->\n @logger = klogger.getLogger", "end": 2153, "score": 0.9755637645721436, "start": 2149, "tag": "USERNAME", "value": "test" }, { "context": " roles: ['ADMIN']\n 'addresses': [\"127.0.0.1\"]\n 'port': @admissionPort\n domains:\n ", "end": 4134, "score": 0.9997692108154297, "start": 4125, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " cb\n try\n server.listen currentPort, '0.0.0.0', ->\n server.once 'close', ->\n ", "end": 18342, "score": 0.9993721842765808, "start": 18335, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "rror 'docker0 interface could not be found. Using 172.17.0.1 as fallback.'\n address = '172.17.0.1'\n addres", "end": 23359, "score": 0.9997457265853882, "start": 23349, "tag": "IP_ADDRESS", "value": "172.17.0.1" }, { "context": "nd. Using 172.17.0.1 as fallback.'\n address = '172.17.0.1'\n address\n\nlaunchDockerKibana = ->\n checkDocker", "end": 23399, "score": 0.9997421503067017, "start": 23389, "tag": "IP_ADDRESS", "value": "172.17.0.1" }, { "context": "Router = ->\n mockToken = {\n \"access_token\":\"a7b41398-0027-4e96-a864-9a7c28f9a0cf\",\n \"token_type\":\"Bearer\",\n \"expires_in\"", "end": 26290, "score": 0.8646185398101807, "start": 26254, "tag": "PASSWORD", "value": "a7b41398-0027-4e96-a864-9a7c28f9a0cf" }, { "context": ",\n \"expires_in\":3600,\n \"refresh_token\":\"53ea0719-9758-41e4-9eca-101347f8a3cf\",\n \"user\":{\"name\":\"SAASDK Local Stamp\",\"role", "end": 26406, "score": 0.9354169368743896, "start": 26370, "tag": "PASSWORD", "value": "53ea0719-9758-41e4-9eca-101347f8a3cf" } ]
src/local-stamp.coffee
iti-ict/localstamp
1
Launcher = require './component-launcher' MockPlanner = require './mock-planner' MockRouterAgent = require './mock-ra' WebsocketPublisher = require './websocket-publisher' Resources = require './resources' State = require './state' q = require 'q' net = require 'net' child = require 'child_process' spawn = child.spawn exec = require('child_process').exec execSync = require('child_process').execSync spawnSync = require('child_process').spawnSync fs = require 'fs' http = require 'http' path = require 'path' Docker = require 'dockerode' GW = require 'gateway-component' AdmissionM = (require 'admission') AdmissionRestAPI = AdmissionM.AdmissionRestAPI supertest = require 'supertest' ksockets = require 'k-sockets' klogger = require 'k-logger' kutils = require 'k-utils' KIBANA_IMAGE='eslap.cloud/elk:1_0_0' KIBANA_DOCKER='local-stamp-logger' DEFAULT_CONFIG = daemon: true kibana: true stopLogger: false destroyLogger: false autoUnregister: false autoUndeploy: false CONTAINER_USABLE_MEMORY_PER_UNIT = 512*1024*1024 # 512MB CONTAINER_SWAP_MEMORY_PER_UNIT = CONTAINER_USABLE_MEMORY_PER_UNIT / 2 # 256MB CONTAINER_TOTAL_MEMORY_PER_UNIT = CONTAINER_USABLE_MEMORY_PER_UNIT+ CONTAINER_SWAP_MEMORY_PER_UNIT CONTAINER_RESERVED_MEMORY_PER_UNIT = CONTAINER_USABLE_MEMORY_PER_UNIT / 2 #256MB CONTAINER_KERNEL_MEMORY_PER_UNIT = CONTAINER_USABLE_MEMORY_PER_UNIT / 2 # 256MB CONTAINER_DEV_SHM_SIZE_PER_MEMORY_UNIT = CONTAINER_RESERVED_MEMORY_PER_UNIT / 2 SWAP_WARNING='WARNING: Your kernel does not support swap limit capabilities' DealerSocket = ksockets.DealerSocket DealerReqRep = ksockets.DealerReqRep express = require 'express' bodyParser = require 'body-parser' multer = require 'multer' cors = require 'cors' app = null initialMappedPort = 9000 silencedClasses = [ 'Admission' 'AdmissionRestAPI' 'DealerReqRep' 'ServiceRegistry' 'ComponentRegistry' 'BundleRegistry' 'ManifestStoreRsync' 'ManifestConverter' 'ManifestValidator' 'ManifestStore' 'ManifestHelper' 'RuntimeAgent' ] class LocalStamp constructor: (@id = 'test', @config = {})-> @logger = klogger.getLogger 'LocalStamp' @repos = logFile: '/eslap/runtime-agent/slap.log' manifests: '/eslap/manifest-storage' images: '/eslap/image-storage' instances: '/eslap/instances' volumes: '/eslap/volumes' filterLog @logger, silencedClasses, ['error'] # Hace un rsync de prueba que genera un error. Lo silencio del todo. filterLog @logger, ['ImageFetcher', 'DealerSocket'] @dockerIP = getDocker0IfaceHostIPAddress.call this @state = new State() @routerAgent = new MockRouterAgent this @launcher = new Launcher this # Keeps track of used resources (related to services deployed or deploying) @resourcesInUse = new Resources() @state.addDeployment 'default' @deploymentCounter = 1 @instanceCounter = 1 @busyPorts = {} @links = {} @docker = new Docker() @graceTime = 1000 @admissionPort = @config.admissionPort ? 8090 @domain = @config.domain ? 'local-stamp.slap53.iti.es' @configLogger = @config.logger ? vm: 'local-stamp' transports: file: level: 'debug' filename: 'slap.log' console: level: 'warn' @develBindings = @config.develBindings ? {} @admission_conf = imageFetcher : type : 'blob' config: remoteImageStore: path : "#{@repos.images}/remote" imageFilename : 'image.tgz' localImageStore : path : "#{@repos.images}/local" imageFilename : 'image.tgz' manifestRepository: type : 'rsync' config : remoteImageStore: path : "#{@repos.manifests}/remote" imageFilename : 'manifest.json' localImageStore: path : "#{@repos.manifests}/local" imageFilename : 'manifest.json' acs: 'anonymous-user': id: 'local-stamp', roles: ['ADMIN'] 'addresses': ["127.0.0.1"] 'port': @admissionPort domains: refDomain: @domain limitChecker: limits: max_bundle_size: 10 max_storage_space: 10 deployment_lifespan_days: 10 allow_resources: true allow_domains: true allow_certificates: true allow_volumes: true allow_iopsintensive: true deployments: simultaneous: -1 entrypoints: simultaneous: -1 roles: deployment: -1 simultaneous: -1 maxinstances: arrangement: -1 deployment: -1 simultaneous: -1 cpu: arrangement: -1 deployment: -1 simultaneous: -1 memory: arrangement: -1 deployment: -1 simultaneous: -1 ioperf: arrangement: -1 deployment: -1 simultaneous: -1 bandwidth: arrangement: -1 deployment: -1 simultaneous: -1 # To avoid errors with instances that do not launch an admission instance @wsp = {publishEvt: -> true} init: -> deferred = q.defer() socket = process.env.DOCKER_SOCKET || '/var/run/docker.sock' stats = fs.statSync(socket) if !stats.isSocket() return q.reject new Error 'Are you sure the docker is running?' @docker.listContainers {all:true}, (err, containers)=> return deferred.reject err if err promises = [] for c in containers if c.Names?[0]? and kutils.startsWith(c.Names[0], "/local-stamp_#{@id}_") @logger.debug "Removing previous docker instance #{c.Names[0]}" fc = @docker.getContainer(c.Id) do (fc)-> promises.push (q.ninvoke fc, 'remove', {force: true}) q.all promises .then -> deferred.resolve true deferred.promise .then => # q.ninvoke child, 'exec', " \ # rm -rf #{@lsRepo}; \ # rm -rf /tmp/slap; \ # mkdir -p #{@lsRepo}/manifest-storage/local/; \ # mkdir -p #{@lsRepo}/manifest-storage/remote/; \ # cp -R /eslap/manifest-storage/* #{@lsRepo}/manifest-storage/remote/; \ # mkdir -p #{@lsRepo}/image-storage/local/; \ # mkdir -p #{@lsRepo}/image-storage/remote/; \ # cp -R /eslap/image-storage/* #{@lsRepo}/image-storage/remote/;" q true .then => if @configValue 'kibana' launchKibana.call this .then => if @configValue 'daemon' launchAdmission.call this launchBundle: (path)-> (if not @admAPI launchAdmission.call this else q true ) .then => @logger.debug "Processing bundle in #{path}" deferred = q.defer() @admRest.post '/bundles' .attach 'bundlesZip', path .end (err, res)=> if err? deferred.reject err return if res.status != 200 @logger.error JSON.stringify res, null, 2 deferred.reject new Error 'Unexpected result registering bundle' return # se.log JSON.stringify text, null, 2 @logger.debug 'Bundle correctly deployed' if res.text? res = JSON.parse res.text res = res.data # if res?.deployments?.errors?[0]? # return deferred.reject \ # new Error JSON.stringify res.deployments.errors[0] setTimeout -> deferred.resolve res#.deployments.successful[0] , 3500 deferred.promise launch: (klass, config, deploymentId = 'default')-> @launcher.launch(klass, config, deploymentId) .then (result)=> @state.addInstance deploymentId, result, config result launchGW: (localConfig, config, deploymentId = 'default')-> config.parameters['__gw_local_config'] = localConfig @launcher.launch(GW, config, deploymentId) .then (result)=> result.isGW = true @state.addInstance deploymentId, result, config result launchDocker: (localConfig, config, deployment = 'default')-> console.log "Launching instance #{config.iid}" iid = config.iid ifolder = @instanceFolder iid promiseSocket = promiseStarted = null dealer = control = name = null instanceFolder = socketFolder = tmpFolder = null # First we check if runtime specified is available checkDockerImage.call this, localConfig.runtime .then (found)=> if not found console.error "Docker image for runtime #{localConfig.runtime} is \ not available. Check the platform documentation for information \ on obtaining images of runtimes" return q.reject new Error "Runtime #{localConfig.runtime} \ is not available" [promiseSocket, promiseStarted] = \ @routerAgent.setupInstance config, deployment promiseSocket .then (setupData)=> [control, dealer, sockets] = setupData name = "local-stamp_#{@id}_#{iid}" result = { dealer: dealer control: control isDocker: true dockerName: name logging: true deployment: deployment } @state.addInstance deployment, result, config # This is "simply" a touch slap.log fs.closeSync(fs.openSync(ifolder.local.log, 'w')) tmpPath = commandLine="\ run \ --rm \ --name #{name} \ -v #{ifolder.host.component}:#{localConfig.sourcedir} \ -v #{ifolder.host.data}:/eslap/data \ -v #{ifolder.host.log}:#{@repos.logFile} \ -e RA_CONTROL_SOCKET_URI=#{sockets.control.uri} \ -e RA_DATA_SOCKET_URI=#{sockets.data.uri} \ -e IID=#{config.iid}" agentFolder = null if localConfig.agentPath agentFolder = localConfig.agentPath.host if agentFolder? commandLine = commandLine + " -v #{agentFolder}:/eslap/runtime-agent" if localConfig?.resources?.__memory? m = localConfig.resources.__memory memoryConstraints = [ {constraint: 'memory', factor: CONTAINER_USABLE_MEMORY_PER_UNIT} {constraint: 'memory-swap', factor: CONTAINER_TOTAL_MEMORY_PER_UNIT} {constraint: 'memory-reservation', \ factor: CONTAINER_RESERVED_MEMORY_PER_UNIT} {constraint: 'kernel-memory', \ factor: CONTAINER_KERNEL_MEMORY_PER_UNIT} {constraint: 'shm-size', \ factor: CONTAINER_DEV_SHM_SIZE_PER_MEMORY_UNIT} ] memoryCmd = "" for mc in memoryConstraints memoryCmd = " #{memoryCmd} --#{mc.constraint} #{m * mc.factor}" commandLine = commandLine + memoryCmd + ' ' # if localConfig.runtime is 'eslap.cloud/runtime/java:1_0_1' # commandLine = "#{commandLine} # -v /workspaces/slap/git/gateway-component/src:/eslap/gateway-component/src \ # -v /workspaces/slap/git/runtime-agent/src:/eslap/runtime-agent/src \ # -v /workspaces/slap/git/slap-utils/src:/eslap/runtime-agent/node_modules/slaputils/src \ # -v /workspaces/slap/git/gateway-component/node_modules:/eslap/gateway-component/node_modules \ # -v /workspaces/slap/git/slap-utils/src:/eslap/gateway-component/node_modules/slaputils/src \ # -v /workspaces/slap/git/slap-utils/src:/eslap/component/node_modules/slaputils/src " for v in @config.develBindings?.__all ? [] commandLine = "#{commandLine} -v #{v}" for v in @config.develBindings?[config.role] ? [] commandLine = "#{commandLine} -v #{v}" if localConfig.volumes? for v in localConfig.volumes commandLine = "#{commandLine} -v #{v}" if localConfig.ports? for p in localConfig.ports commandLine = "#{commandLine} -p #{p}" if localConfig.entrypoint? commandLine = "#{commandLine} --entrypoint #{localConfig.entrypoint}" commandLine = "#{commandLine} #{localConfig.runtime}" if localConfig.configdir commandLine = "#{commandLine} #{localConfig.configdir}" commandLine = commandLine.replace(/ +(?= )/g,'') @logger.debug "Creating instance #{config.iid}..." @logger.debug "Docker command line: docker #{commandLine}" # console.log "Docker command line: docker #{commandLine}" try client = spawn 'docker',commandLine.split(' ') client.stdout.on 'data', (data)=> return if not data? # return if not (@instances?[config.iid]?.logging is true) data = data + '' data = data.replace(/[\r\r]+/g, '\r').trim() return if data.length is 0 @logger.debug "DC #{config.iid}: #{data}" console.log "DC #{config.iid}: #{data}" client.stderr.on 'data', (data)=> return if not data? # return if not (@instances?[config.iid]?.logging is true) return if data.indexOf(SWAP_WARNING) is 0 @logger.error "DC error #{config.iid}: #{data}" #console.error "DC error #{config.iid}: #{data}" catch e @logger.error "Error launching Docker #{e} #{e.stack}" promiseStarted.timeout 60 * 1000, "Instance #{config.iid} did not \ started properly, this problem is probably related with its runtime.#{ \ if not localConfig.agentPath? then \ ' Maybe an agent for this runtime should be configured.' \ else \ '' \ }" .then => @state.setInstanceStatus config.iid, {timestamp: (new Date()).getTime()} q.delay 3000 .then => localIP = undefined cmd = ['inspect', '-f', '\"{{ .NetworkSettings.IPAddress }}\"', name] result = spawnSync 'docker', cmd if result.status is 0 localIP = result.stdout.toString().trim().replace(/(^"|"$)/g, '') else if result.stderr?.indexOf 'No such image or container' console.log "Instance #{name} finished unexpectedly. Maybe you \ should examine its log." @state.getInstance(iid).dockerIp = localIP @wsp.publishEvt 'instance', 'created', {instance: iid} shutdownInstance: (iid)-> deferred = q.defer() ref = @state.getInstance iid return if not ref? ref.logging = false (if ref.isDocker ref.control.sendRequest {action: 'instance_stop'} q true else ref.runtime.close() ).then => setTimeout => if ref.isGW ref.instance.destroy() else if ref.isDocker commandLine="stop #{ref.dockerName}" console.log "Shutting down instance #{iid}" client = spawn 'docker',commandLine.split(' ') ref.dealer.close() ref.control.close() @state.removeInstance iid @wsp.publishEvt 'instance', 'removed', {instance: iid} setTimeout -> deferred.resolve true , 1500 , @graceTime deferred.promise loadRuntimes: (runtimes)-> promise = q true for r in runtimes do (r)=> promise = promise.then => @loadRuntime r promise loadRuntime: (runtime)-> rruntime = runtimeURNtoImageName runtime checkDockerImage.call this, rruntime .then (found)=> return true if found himgfile = "#{@imageFolder().host}/#{runtimeURNtoPath runtime}" limgfile = "#{@imageFolder().local}/#{runtimeURNtoPath runtime}" if not fs.existsSync limgfile throw new Error "Runtime #{runtime} is not available. Check the \ platform documentation for information \ on obtaining images of runtimes" commandLine="docker \ load \ -i \ #{limgfile}" console.log "Loading runtime #{runtime}..." @logger.debug "Loading runtime #{himgfile}..." @logger.debug "Docker command line: #{commandLine}" try code = execSync commandLine catch e @logger.error "Error loading runtime #{runtime} #{e} #{e.stack}" throw e shutdown: -> promises = [] for c of @state.getInstances() promises.push @shutdownInstance c q.all promises .then => if @config.destroyLogger removeDockerKibana.call this else if @config.stopLogger stopDockerKibana.call this launchAdmission = -> @planner = new MockPlanner this # @logger.debug 'Creating Admission' setMutedLogger [AdmissionRestAPI.prototype, AdmissionM.Admission.prototype] @admAPI = new AdmissionRestAPI @admission_conf, @planner @admAPI.init() .then => storage = multer.diskStorage { destination: '/tmp/multer' filename: (req, file, cb) -> name = file.fieldname + '-' + \ kutils.generateId() + \ path.extname(file.originalname) cb null, name } upload = multer({ storage: storage }).any() app = express() app.use bodyParser.json() app.use bodyParser.urlencoded({ extended: true }) app.use upload app.use cors() app.use '/admission', @admAPI.getRouter() app.use '/acs', getMockAcsRouter.call(this) # Basic error handler app.use (req, res, next) -> return res.status(404).send('Not Found') # @logger.debug "ADMISSION listening at port #{admissionPort}" httpServer = http.createServer(app) @wsp = new WebsocketPublisher httpServer, @admAPI.httpAuthentication httpServer.listen @admissionPort .then => @admRest = supertest "http://localhost:#{@admissionPort}/admission" q.delay 2000 configValue: (key)-> result = @config[key] ? DEFAULT_CONFIG[key] ? null # console.log "Config #{key}: #{result}" result # allocPort: -> # result = initialMappedPort # while true # sport = result+'' # if not @busyPorts[sport]? # @busyPorts[sport] = true # return sport # result++ # freePort: (port)-> # port = port+'' # if @busyPorts[port]? # delete @busyPorts[port] allocPort: -> getNextAvailablePort = (currentPort, cb) -> server = net.createServer() handleError = -> getNextAvailablePort ++currentPort, cb try server.listen currentPort, '0.0.0.0', -> server.once 'close', -> cb currentPort server.close() server.on 'error', handleError catch e handleError() return new Promise (resolve)-> getNextAvailablePort initialMappedPort, resolve # Now ports are handled finding real free ports because docker, many # times, does not free bound ports as expected freePort: -> nowThisFunctionIsUseless = true instanceFolder: (iid) -> { host: component: "#{@config.instanceFolder}/#{iid}/component" runtime: "#{@config.instanceFolder}/#{iid}/runtime-agent" data: "#{@config.instanceFolder}/#{iid}/data" log: "#{@config.instanceFolder}/#{iid}/slap.log" local: component: "#{@repos.instances}/#{iid}/component" runtime: "#{@repos.instances}/#{iid}/runtime-agent" data: "#{@repos.instances}/#{iid}/data" log: "#{@repos.instances}/#{iid}/slap.log" } volumeFolder: () -> { host: "#{@config.volumeFolder}" local: "#{@repos.volumes}" } manifestFolder: () -> { host: "#{@config.manifestStorage}" local: "#{@repos.manifests}/remote" } imageFolder: () -> { host: "#{@config.imageStorage}" local: "#{@repos.images}/remote" } getPort = (cb)-> port = initialMappedPort server = net.createServer() server.listen port, (err)-> server.once 'close', -> cb(port) server.close() server.on 'error', -> getPort(cb) launchKibana = -> container = @docker.getContainer KIBANA_DOCKER q.ninvoke container, 'inspect' .then (data)=> if not (data?.HostConfig?.PortBindings?['28777/tcp']?) console.log 'Restarting logger' q.ninvoke container, 'remove', {force: true} .then => q.delay 3000 .then => container = @docker.getContainer KIBANA_DOCKER q.ninvoke container, 'inspect' else data .then (data)=> return if data?.State?.Status is 'running' @logger.debug "Removing docker instance #{KIBANA_DOCKER}..." q.ninvoke container, 'remove', {force: true} .then => launchDockerKibana.call this .fail (e)=> return throw e if e.message?.indexOf('404') < 0 launchDockerKibana.call this .then => retries = q.reject false for i in [1..5] do (i)=> retries = retries.fail (e) => q.delay 5000 .then => container = @docker.getContainer KIBANA_DOCKER q.ninvoke container, 'inspect' retries .then (data)=> @loggerIP = data.NetworkSettings.Networks.bridge.IPAddress # With iic=false we can't communicate directly to other container # We communicate using host docker ip @loggerIP = @dockerIP ip = @loggerIP deferred = q.defer() exec = require('child_process').exec; counter = 0 check_logstash = ()-> nc = exec "nc -z #{ip} 28777", -> dummy = 0 nc.on 'exit', (code)-> if code is 0 deferred.resolve() else if counter>20 deferred.reject new Error 'Can\'t contact with logstash' else counter++ console.log "Local-stamp initialization - Waiting for logstash..." setTimeout -> check_logstash() , 5000 do check_logstash deferred.promise .then => deferred = q.defer() @configLogger.transports.logstash = level: 'debug' host: @loggerIP port: 28777 retrier = => @logger.info "Local-stamp connected to logger" @logger.configure @configLogger consoleSilent = @logger._logger.transports.console.silent @logger._logger.transports.console.silent = true @logger._logger.transports.logstash.socket.once 'connect', => cl = @logger._logger.transports.console.log wcl = (level, msg) => return if msg.startsWith 'Logstash Winston transport warning' return if msg.startsWith 'acsStub has no info about acs Location' cl.apply @logger._logger.transports.console, arguments @logger._logger.transports.console.log = wcl setTimeout => @logger._logger.transports.console.log = cl , 30000 @logger._logger.transports.console.silent = consoleSilent @logger._logger.transports.logstash.socket.removeListener 'error', retrier console.log "Connected with logger" console.log "Available Logger in #{@loggerIP}" console.log 'Available Kibana on port 5601' deferred.resolve true @logger._logger.transports.logstash.socket.on 'error', -> setTimeout retrier, 500 retrier() deferred.promise getDocker0IfaceHostIPAddress = -> # os.networkInterfaces() doesn't report DOWN ifaces, # so a less elegant solution is required address = execSync( "ip address show docker0| grep 'inet ' | awk '{print $2}' \ | sed 's/\\/.*//' | tr -d '\\n'").toString() if (not address?) or (address.length is 0 ) @logger.error 'docker0 interface could not be found. Using 172.17.0.1 as fallback.' address = '172.17.0.1' address launchDockerKibana = -> checkDockerImage.call this, KIBANA_IMAGE .then (found)=> if not found console.error "Docker image for #{KIBANA_IMAGE} is \ not available. Check the platform documentation for information \ on obtaining docker images." return q.reject new Error "Docker image not available: #{KIBANA_IMAGE}" commandLine="\ run \ --rm \ --name #{KIBANA_DOCKER} \ -p 5601:5601 \ -p 28777:28777 \ #{KIBANA_IMAGE}" @logger.debug "Creating docker instance #{KIBANA_DOCKER}..." @logger.debug "Docker command line: #{commandLine}" # console.log "Docker command line: #{commandLine}" try client = spawn 'docker',commandLine.split(' ') catch e @logger.error "Error launching Docker #{e} #{e.stack}" .then -> console.log "Local-stamp initialization - \ Waiting for logstash initialization..." #q.delay 15000 removeDockerKibana = -> container = @docker.getContainer KIBANA_DOCKER q.ninvoke container, 'remove', {force: true} .fail -> true stopDockerKibana = -> container = @docker.getContainer KIBANA_DOCKER q.ninvoke container, 'stop' .fail -> true checkDockerImage = (name)-> # console.log "checkDockerImage this:#{this?} docker:#{this.docker?} #{name}" q.ninvoke @docker, 'listImages' .then (images)-> found = false # console.log "Buscando a #{name}" for i in images # console.log JSON.stringify i, null, 2 for t in i.RepoTags ? [] # console.log "Comparando con #{t}" if t is name found = true break found folderExists =(filePath)-> try fs.statSync(filePath).isDirectory() catch err false fileExists =(filePath)-> try fs.statSync(filePath).isFile() catch err false runtimeURNtoImageName =(runtimeURN) -> imageName = runtimeURN.replace('eslap://', '').toLowerCase() index = imageName.lastIndexOf('/') imageName = imageName.substr(0, index) + ':' + imageName.substr(index + 1) imageName runtimeURNtoPath =(runtimeURN) -> imageName = runtimeURN.replace('eslap://', '').toLowerCase() index = imageName.lastIndexOf('/') imageName = imageName.substr(0, index).replace(/_/g, '') + '/' + imageName.substr(index + 1) + '/image.tgz' imageName fakeLogger = debug: -> info: -> error: -> warn: -> log: -> verbose: -> silly: -> setMutedLogger = (refs)-> return for ref in refs ref.logger = fakeLogger if ref? filterLog = (logger, classes, levels = [])-> original = logger._logger.log.bind logger._logger modified = (level, message, metadata)-> if metadata.clazz in classes and level not in levels return original level, message, metadata logger._logger.log = modified getMockAcsRouter = -> mockToken = { "access_token":"a7b41398-0027-4e96-a864-9a7c28f9a0cf", "token_type":"Bearer", "expires_in":3600, "refresh_token":"53ea0719-9758-41e4-9eca-101347f8a3cf", "user":{"name":"SAASDK Local Stamp","roles":["ADMIN"],"id":"local-stamp"} } @acsRouter = express.Router() @acsRouter.get '/login', (req, res) => res.json mockToken @acsRouter.get '/tokens/:token', (req, res) => res.json mockToken module.exports = LocalStamp
88527
Launcher = require './component-launcher' MockPlanner = require './mock-planner' MockRouterAgent = require './mock-ra' WebsocketPublisher = require './websocket-publisher' Resources = require './resources' State = require './state' q = require 'q' net = require 'net' child = require 'child_process' spawn = child.spawn exec = require('child_process').exec execSync = require('child_process').execSync spawnSync = require('child_process').spawnSync fs = require 'fs' http = require 'http' path = require 'path' Docker = require 'dockerode' GW = require 'gateway-component' AdmissionM = (require 'admission') AdmissionRestAPI = AdmissionM.AdmissionRestAPI supertest = require 'supertest' ksockets = require 'k-sockets' klogger = require 'k-logger' kutils = require 'k-utils' KIBANA_IMAGE='eslap.cloud/elk:1_0_0' KIBANA_DOCKER='local-stamp-logger' DEFAULT_CONFIG = daemon: true kibana: true stopLogger: false destroyLogger: false autoUnregister: false autoUndeploy: false CONTAINER_USABLE_MEMORY_PER_UNIT = 512*1024*1024 # 512MB CONTAINER_SWAP_MEMORY_PER_UNIT = CONTAINER_USABLE_MEMORY_PER_UNIT / 2 # 256MB CONTAINER_TOTAL_MEMORY_PER_UNIT = CONTAINER_USABLE_MEMORY_PER_UNIT+ CONTAINER_SWAP_MEMORY_PER_UNIT CONTAINER_RESERVED_MEMORY_PER_UNIT = CONTAINER_USABLE_MEMORY_PER_UNIT / 2 #256MB CONTAINER_KERNEL_MEMORY_PER_UNIT = CONTAINER_USABLE_MEMORY_PER_UNIT / 2 # 256MB CONTAINER_DEV_SHM_SIZE_PER_MEMORY_UNIT = CONTAINER_RESERVED_MEMORY_PER_UNIT / 2 SWAP_WARNING='WARNING: Your kernel does not support swap limit capabilities' DealerSocket = ksockets.DealerSocket DealerReqRep = ksockets.DealerReqRep express = require 'express' bodyParser = require 'body-parser' multer = require 'multer' cors = require 'cors' app = null initialMappedPort = 9000 silencedClasses = [ 'Admission' 'AdmissionRestAPI' 'DealerReqRep' 'ServiceRegistry' 'ComponentRegistry' 'BundleRegistry' 'ManifestStoreRsync' 'ManifestConverter' 'ManifestValidator' 'ManifestStore' 'ManifestHelper' 'RuntimeAgent' ] class LocalStamp constructor: (@id = 'test', @config = {})-> @logger = klogger.getLogger 'LocalStamp' @repos = logFile: '/eslap/runtime-agent/slap.log' manifests: '/eslap/manifest-storage' images: '/eslap/image-storage' instances: '/eslap/instances' volumes: '/eslap/volumes' filterLog @logger, silencedClasses, ['error'] # Hace un rsync de prueba que genera un error. Lo silencio del todo. filterLog @logger, ['ImageFetcher', 'DealerSocket'] @dockerIP = getDocker0IfaceHostIPAddress.call this @state = new State() @routerAgent = new MockRouterAgent this @launcher = new Launcher this # Keeps track of used resources (related to services deployed or deploying) @resourcesInUse = new Resources() @state.addDeployment 'default' @deploymentCounter = 1 @instanceCounter = 1 @busyPorts = {} @links = {} @docker = new Docker() @graceTime = 1000 @admissionPort = @config.admissionPort ? 8090 @domain = @config.domain ? 'local-stamp.slap53.iti.es' @configLogger = @config.logger ? vm: 'local-stamp' transports: file: level: 'debug' filename: 'slap.log' console: level: 'warn' @develBindings = @config.develBindings ? {} @admission_conf = imageFetcher : type : 'blob' config: remoteImageStore: path : "#{@repos.images}/remote" imageFilename : 'image.tgz' localImageStore : path : "#{@repos.images}/local" imageFilename : 'image.tgz' manifestRepository: type : 'rsync' config : remoteImageStore: path : "#{@repos.manifests}/remote" imageFilename : 'manifest.json' localImageStore: path : "#{@repos.manifests}/local" imageFilename : 'manifest.json' acs: 'anonymous-user': id: 'local-stamp', roles: ['ADMIN'] 'addresses': ["127.0.0.1"] 'port': @admissionPort domains: refDomain: @domain limitChecker: limits: max_bundle_size: 10 max_storage_space: 10 deployment_lifespan_days: 10 allow_resources: true allow_domains: true allow_certificates: true allow_volumes: true allow_iopsintensive: true deployments: simultaneous: -1 entrypoints: simultaneous: -1 roles: deployment: -1 simultaneous: -1 maxinstances: arrangement: -1 deployment: -1 simultaneous: -1 cpu: arrangement: -1 deployment: -1 simultaneous: -1 memory: arrangement: -1 deployment: -1 simultaneous: -1 ioperf: arrangement: -1 deployment: -1 simultaneous: -1 bandwidth: arrangement: -1 deployment: -1 simultaneous: -1 # To avoid errors with instances that do not launch an admission instance @wsp = {publishEvt: -> true} init: -> deferred = q.defer() socket = process.env.DOCKER_SOCKET || '/var/run/docker.sock' stats = fs.statSync(socket) if !stats.isSocket() return q.reject new Error 'Are you sure the docker is running?' @docker.listContainers {all:true}, (err, containers)=> return deferred.reject err if err promises = [] for c in containers if c.Names?[0]? and kutils.startsWith(c.Names[0], "/local-stamp_#{@id}_") @logger.debug "Removing previous docker instance #{c.Names[0]}" fc = @docker.getContainer(c.Id) do (fc)-> promises.push (q.ninvoke fc, 'remove', {force: true}) q.all promises .then -> deferred.resolve true deferred.promise .then => # q.ninvoke child, 'exec', " \ # rm -rf #{@lsRepo}; \ # rm -rf /tmp/slap; \ # mkdir -p #{@lsRepo}/manifest-storage/local/; \ # mkdir -p #{@lsRepo}/manifest-storage/remote/; \ # cp -R /eslap/manifest-storage/* #{@lsRepo}/manifest-storage/remote/; \ # mkdir -p #{@lsRepo}/image-storage/local/; \ # mkdir -p #{@lsRepo}/image-storage/remote/; \ # cp -R /eslap/image-storage/* #{@lsRepo}/image-storage/remote/;" q true .then => if @configValue 'kibana' launchKibana.call this .then => if @configValue 'daemon' launchAdmission.call this launchBundle: (path)-> (if not @admAPI launchAdmission.call this else q true ) .then => @logger.debug "Processing bundle in #{path}" deferred = q.defer() @admRest.post '/bundles' .attach 'bundlesZip', path .end (err, res)=> if err? deferred.reject err return if res.status != 200 @logger.error JSON.stringify res, null, 2 deferred.reject new Error 'Unexpected result registering bundle' return # se.log JSON.stringify text, null, 2 @logger.debug 'Bundle correctly deployed' if res.text? res = JSON.parse res.text res = res.data # if res?.deployments?.errors?[0]? # return deferred.reject \ # new Error JSON.stringify res.deployments.errors[0] setTimeout -> deferred.resolve res#.deployments.successful[0] , 3500 deferred.promise launch: (klass, config, deploymentId = 'default')-> @launcher.launch(klass, config, deploymentId) .then (result)=> @state.addInstance deploymentId, result, config result launchGW: (localConfig, config, deploymentId = 'default')-> config.parameters['__gw_local_config'] = localConfig @launcher.launch(GW, config, deploymentId) .then (result)=> result.isGW = true @state.addInstance deploymentId, result, config result launchDocker: (localConfig, config, deployment = 'default')-> console.log "Launching instance #{config.iid}" iid = config.iid ifolder = @instanceFolder iid promiseSocket = promiseStarted = null dealer = control = name = null instanceFolder = socketFolder = tmpFolder = null # First we check if runtime specified is available checkDockerImage.call this, localConfig.runtime .then (found)=> if not found console.error "Docker image for runtime #{localConfig.runtime} is \ not available. Check the platform documentation for information \ on obtaining images of runtimes" return q.reject new Error "Runtime #{localConfig.runtime} \ is not available" [promiseSocket, promiseStarted] = \ @routerAgent.setupInstance config, deployment promiseSocket .then (setupData)=> [control, dealer, sockets] = setupData name = "local-stamp_#{@id}_#{iid}" result = { dealer: dealer control: control isDocker: true dockerName: name logging: true deployment: deployment } @state.addInstance deployment, result, config # This is "simply" a touch slap.log fs.closeSync(fs.openSync(ifolder.local.log, 'w')) tmpPath = commandLine="\ run \ --rm \ --name #{name} \ -v #{ifolder.host.component}:#{localConfig.sourcedir} \ -v #{ifolder.host.data}:/eslap/data \ -v #{ifolder.host.log}:#{@repos.logFile} \ -e RA_CONTROL_SOCKET_URI=#{sockets.control.uri} \ -e RA_DATA_SOCKET_URI=#{sockets.data.uri} \ -e IID=#{config.iid}" agentFolder = null if localConfig.agentPath agentFolder = localConfig.agentPath.host if agentFolder? commandLine = commandLine + " -v #{agentFolder}:/eslap/runtime-agent" if localConfig?.resources?.__memory? m = localConfig.resources.__memory memoryConstraints = [ {constraint: 'memory', factor: CONTAINER_USABLE_MEMORY_PER_UNIT} {constraint: 'memory-swap', factor: CONTAINER_TOTAL_MEMORY_PER_UNIT} {constraint: 'memory-reservation', \ factor: CONTAINER_RESERVED_MEMORY_PER_UNIT} {constraint: 'kernel-memory', \ factor: CONTAINER_KERNEL_MEMORY_PER_UNIT} {constraint: 'shm-size', \ factor: CONTAINER_DEV_SHM_SIZE_PER_MEMORY_UNIT} ] memoryCmd = "" for mc in memoryConstraints memoryCmd = " #{memoryCmd} --#{mc.constraint} #{m * mc.factor}" commandLine = commandLine + memoryCmd + ' ' # if localConfig.runtime is 'eslap.cloud/runtime/java:1_0_1' # commandLine = "#{commandLine} # -v /workspaces/slap/git/gateway-component/src:/eslap/gateway-component/src \ # -v /workspaces/slap/git/runtime-agent/src:/eslap/runtime-agent/src \ # -v /workspaces/slap/git/slap-utils/src:/eslap/runtime-agent/node_modules/slaputils/src \ # -v /workspaces/slap/git/gateway-component/node_modules:/eslap/gateway-component/node_modules \ # -v /workspaces/slap/git/slap-utils/src:/eslap/gateway-component/node_modules/slaputils/src \ # -v /workspaces/slap/git/slap-utils/src:/eslap/component/node_modules/slaputils/src " for v in @config.develBindings?.__all ? [] commandLine = "#{commandLine} -v #{v}" for v in @config.develBindings?[config.role] ? [] commandLine = "#{commandLine} -v #{v}" if localConfig.volumes? for v in localConfig.volumes commandLine = "#{commandLine} -v #{v}" if localConfig.ports? for p in localConfig.ports commandLine = "#{commandLine} -p #{p}" if localConfig.entrypoint? commandLine = "#{commandLine} --entrypoint #{localConfig.entrypoint}" commandLine = "#{commandLine} #{localConfig.runtime}" if localConfig.configdir commandLine = "#{commandLine} #{localConfig.configdir}" commandLine = commandLine.replace(/ +(?= )/g,'') @logger.debug "Creating instance #{config.iid}..." @logger.debug "Docker command line: docker #{commandLine}" # console.log "Docker command line: docker #{commandLine}" try client = spawn 'docker',commandLine.split(' ') client.stdout.on 'data', (data)=> return if not data? # return if not (@instances?[config.iid]?.logging is true) data = data + '' data = data.replace(/[\r\r]+/g, '\r').trim() return if data.length is 0 @logger.debug "DC #{config.iid}: #{data}" console.log "DC #{config.iid}: #{data}" client.stderr.on 'data', (data)=> return if not data? # return if not (@instances?[config.iid]?.logging is true) return if data.indexOf(SWAP_WARNING) is 0 @logger.error "DC error #{config.iid}: #{data}" #console.error "DC error #{config.iid}: #{data}" catch e @logger.error "Error launching Docker #{e} #{e.stack}" promiseStarted.timeout 60 * 1000, "Instance #{config.iid} did not \ started properly, this problem is probably related with its runtime.#{ \ if not localConfig.agentPath? then \ ' Maybe an agent for this runtime should be configured.' \ else \ '' \ }" .then => @state.setInstanceStatus config.iid, {timestamp: (new Date()).getTime()} q.delay 3000 .then => localIP = undefined cmd = ['inspect', '-f', '\"{{ .NetworkSettings.IPAddress }}\"', name] result = spawnSync 'docker', cmd if result.status is 0 localIP = result.stdout.toString().trim().replace(/(^"|"$)/g, '') else if result.stderr?.indexOf 'No such image or container' console.log "Instance #{name} finished unexpectedly. Maybe you \ should examine its log." @state.getInstance(iid).dockerIp = localIP @wsp.publishEvt 'instance', 'created', {instance: iid} shutdownInstance: (iid)-> deferred = q.defer() ref = @state.getInstance iid return if not ref? ref.logging = false (if ref.isDocker ref.control.sendRequest {action: 'instance_stop'} q true else ref.runtime.close() ).then => setTimeout => if ref.isGW ref.instance.destroy() else if ref.isDocker commandLine="stop #{ref.dockerName}" console.log "Shutting down instance #{iid}" client = spawn 'docker',commandLine.split(' ') ref.dealer.close() ref.control.close() @state.removeInstance iid @wsp.publishEvt 'instance', 'removed', {instance: iid} setTimeout -> deferred.resolve true , 1500 , @graceTime deferred.promise loadRuntimes: (runtimes)-> promise = q true for r in runtimes do (r)=> promise = promise.then => @loadRuntime r promise loadRuntime: (runtime)-> rruntime = runtimeURNtoImageName runtime checkDockerImage.call this, rruntime .then (found)=> return true if found himgfile = "#{@imageFolder().host}/#{runtimeURNtoPath runtime}" limgfile = "#{@imageFolder().local}/#{runtimeURNtoPath runtime}" if not fs.existsSync limgfile throw new Error "Runtime #{runtime} is not available. Check the \ platform documentation for information \ on obtaining images of runtimes" commandLine="docker \ load \ -i \ #{limgfile}" console.log "Loading runtime #{runtime}..." @logger.debug "Loading runtime #{himgfile}..." @logger.debug "Docker command line: #{commandLine}" try code = execSync commandLine catch e @logger.error "Error loading runtime #{runtime} #{e} #{e.stack}" throw e shutdown: -> promises = [] for c of @state.getInstances() promises.push @shutdownInstance c q.all promises .then => if @config.destroyLogger removeDockerKibana.call this else if @config.stopLogger stopDockerKibana.call this launchAdmission = -> @planner = new MockPlanner this # @logger.debug 'Creating Admission' setMutedLogger [AdmissionRestAPI.prototype, AdmissionM.Admission.prototype] @admAPI = new AdmissionRestAPI @admission_conf, @planner @admAPI.init() .then => storage = multer.diskStorage { destination: '/tmp/multer' filename: (req, file, cb) -> name = file.fieldname + '-' + \ kutils.generateId() + \ path.extname(file.originalname) cb null, name } upload = multer({ storage: storage }).any() app = express() app.use bodyParser.json() app.use bodyParser.urlencoded({ extended: true }) app.use upload app.use cors() app.use '/admission', @admAPI.getRouter() app.use '/acs', getMockAcsRouter.call(this) # Basic error handler app.use (req, res, next) -> return res.status(404).send('Not Found') # @logger.debug "ADMISSION listening at port #{admissionPort}" httpServer = http.createServer(app) @wsp = new WebsocketPublisher httpServer, @admAPI.httpAuthentication httpServer.listen @admissionPort .then => @admRest = supertest "http://localhost:#{@admissionPort}/admission" q.delay 2000 configValue: (key)-> result = @config[key] ? DEFAULT_CONFIG[key] ? null # console.log "Config #{key}: #{result}" result # allocPort: -> # result = initialMappedPort # while true # sport = result+'' # if not @busyPorts[sport]? # @busyPorts[sport] = true # return sport # result++ # freePort: (port)-> # port = port+'' # if @busyPorts[port]? # delete @busyPorts[port] allocPort: -> getNextAvailablePort = (currentPort, cb) -> server = net.createServer() handleError = -> getNextAvailablePort ++currentPort, cb try server.listen currentPort, '0.0.0.0', -> server.once 'close', -> cb currentPort server.close() server.on 'error', handleError catch e handleError() return new Promise (resolve)-> getNextAvailablePort initialMappedPort, resolve # Now ports are handled finding real free ports because docker, many # times, does not free bound ports as expected freePort: -> nowThisFunctionIsUseless = true instanceFolder: (iid) -> { host: component: "#{@config.instanceFolder}/#{iid}/component" runtime: "#{@config.instanceFolder}/#{iid}/runtime-agent" data: "#{@config.instanceFolder}/#{iid}/data" log: "#{@config.instanceFolder}/#{iid}/slap.log" local: component: "#{@repos.instances}/#{iid}/component" runtime: "#{@repos.instances}/#{iid}/runtime-agent" data: "#{@repos.instances}/#{iid}/data" log: "#{@repos.instances}/#{iid}/slap.log" } volumeFolder: () -> { host: "#{@config.volumeFolder}" local: "#{@repos.volumes}" } manifestFolder: () -> { host: "#{@config.manifestStorage}" local: "#{@repos.manifests}/remote" } imageFolder: () -> { host: "#{@config.imageStorage}" local: "#{@repos.images}/remote" } getPort = (cb)-> port = initialMappedPort server = net.createServer() server.listen port, (err)-> server.once 'close', -> cb(port) server.close() server.on 'error', -> getPort(cb) launchKibana = -> container = @docker.getContainer KIBANA_DOCKER q.ninvoke container, 'inspect' .then (data)=> if not (data?.HostConfig?.PortBindings?['28777/tcp']?) console.log 'Restarting logger' q.ninvoke container, 'remove', {force: true} .then => q.delay 3000 .then => container = @docker.getContainer KIBANA_DOCKER q.ninvoke container, 'inspect' else data .then (data)=> return if data?.State?.Status is 'running' @logger.debug "Removing docker instance #{KIBANA_DOCKER}..." q.ninvoke container, 'remove', {force: true} .then => launchDockerKibana.call this .fail (e)=> return throw e if e.message?.indexOf('404') < 0 launchDockerKibana.call this .then => retries = q.reject false for i in [1..5] do (i)=> retries = retries.fail (e) => q.delay 5000 .then => container = @docker.getContainer KIBANA_DOCKER q.ninvoke container, 'inspect' retries .then (data)=> @loggerIP = data.NetworkSettings.Networks.bridge.IPAddress # With iic=false we can't communicate directly to other container # We communicate using host docker ip @loggerIP = @dockerIP ip = @loggerIP deferred = q.defer() exec = require('child_process').exec; counter = 0 check_logstash = ()-> nc = exec "nc -z #{ip} 28777", -> dummy = 0 nc.on 'exit', (code)-> if code is 0 deferred.resolve() else if counter>20 deferred.reject new Error 'Can\'t contact with logstash' else counter++ console.log "Local-stamp initialization - Waiting for logstash..." setTimeout -> check_logstash() , 5000 do check_logstash deferred.promise .then => deferred = q.defer() @configLogger.transports.logstash = level: 'debug' host: @loggerIP port: 28777 retrier = => @logger.info "Local-stamp connected to logger" @logger.configure @configLogger consoleSilent = @logger._logger.transports.console.silent @logger._logger.transports.console.silent = true @logger._logger.transports.logstash.socket.once 'connect', => cl = @logger._logger.transports.console.log wcl = (level, msg) => return if msg.startsWith 'Logstash Winston transport warning' return if msg.startsWith 'acsStub has no info about acs Location' cl.apply @logger._logger.transports.console, arguments @logger._logger.transports.console.log = wcl setTimeout => @logger._logger.transports.console.log = cl , 30000 @logger._logger.transports.console.silent = consoleSilent @logger._logger.transports.logstash.socket.removeListener 'error', retrier console.log "Connected with logger" console.log "Available Logger in #{@loggerIP}" console.log 'Available Kibana on port 5601' deferred.resolve true @logger._logger.transports.logstash.socket.on 'error', -> setTimeout retrier, 500 retrier() deferred.promise getDocker0IfaceHostIPAddress = -> # os.networkInterfaces() doesn't report DOWN ifaces, # so a less elegant solution is required address = execSync( "ip address show docker0| grep 'inet ' | awk '{print $2}' \ | sed 's/\\/.*//' | tr -d '\\n'").toString() if (not address?) or (address.length is 0 ) @logger.error 'docker0 interface could not be found. Using 172.17.0.1 as fallback.' address = '172.17.0.1' address launchDockerKibana = -> checkDockerImage.call this, KIBANA_IMAGE .then (found)=> if not found console.error "Docker image for #{KIBANA_IMAGE} is \ not available. Check the platform documentation for information \ on obtaining docker images." return q.reject new Error "Docker image not available: #{KIBANA_IMAGE}" commandLine="\ run \ --rm \ --name #{KIBANA_DOCKER} \ -p 5601:5601 \ -p 28777:28777 \ #{KIBANA_IMAGE}" @logger.debug "Creating docker instance #{KIBANA_DOCKER}..." @logger.debug "Docker command line: #{commandLine}" # console.log "Docker command line: #{commandLine}" try client = spawn 'docker',commandLine.split(' ') catch e @logger.error "Error launching Docker #{e} #{e.stack}" .then -> console.log "Local-stamp initialization - \ Waiting for logstash initialization..." #q.delay 15000 removeDockerKibana = -> container = @docker.getContainer KIBANA_DOCKER q.ninvoke container, 'remove', {force: true} .fail -> true stopDockerKibana = -> container = @docker.getContainer KIBANA_DOCKER q.ninvoke container, 'stop' .fail -> true checkDockerImage = (name)-> # console.log "checkDockerImage this:#{this?} docker:#{this.docker?} #{name}" q.ninvoke @docker, 'listImages' .then (images)-> found = false # console.log "Buscando a #{name}" for i in images # console.log JSON.stringify i, null, 2 for t in i.RepoTags ? [] # console.log "Comparando con #{t}" if t is name found = true break found folderExists =(filePath)-> try fs.statSync(filePath).isDirectory() catch err false fileExists =(filePath)-> try fs.statSync(filePath).isFile() catch err false runtimeURNtoImageName =(runtimeURN) -> imageName = runtimeURN.replace('eslap://', '').toLowerCase() index = imageName.lastIndexOf('/') imageName = imageName.substr(0, index) + ':' + imageName.substr(index + 1) imageName runtimeURNtoPath =(runtimeURN) -> imageName = runtimeURN.replace('eslap://', '').toLowerCase() index = imageName.lastIndexOf('/') imageName = imageName.substr(0, index).replace(/_/g, '') + '/' + imageName.substr(index + 1) + '/image.tgz' imageName fakeLogger = debug: -> info: -> error: -> warn: -> log: -> verbose: -> silly: -> setMutedLogger = (refs)-> return for ref in refs ref.logger = fakeLogger if ref? filterLog = (logger, classes, levels = [])-> original = logger._logger.log.bind logger._logger modified = (level, message, metadata)-> if metadata.clazz in classes and level not in levels return original level, message, metadata logger._logger.log = modified getMockAcsRouter = -> mockToken = { "access_token":"<PASSWORD>", "token_type":"Bearer", "expires_in":3600, "refresh_token":"<PASSWORD>", "user":{"name":"SAASDK Local Stamp","roles":["ADMIN"],"id":"local-stamp"} } @acsRouter = express.Router() @acsRouter.get '/login', (req, res) => res.json mockToken @acsRouter.get '/tokens/:token', (req, res) => res.json mockToken module.exports = LocalStamp
true
Launcher = require './component-launcher' MockPlanner = require './mock-planner' MockRouterAgent = require './mock-ra' WebsocketPublisher = require './websocket-publisher' Resources = require './resources' State = require './state' q = require 'q' net = require 'net' child = require 'child_process' spawn = child.spawn exec = require('child_process').exec execSync = require('child_process').execSync spawnSync = require('child_process').spawnSync fs = require 'fs' http = require 'http' path = require 'path' Docker = require 'dockerode' GW = require 'gateway-component' AdmissionM = (require 'admission') AdmissionRestAPI = AdmissionM.AdmissionRestAPI supertest = require 'supertest' ksockets = require 'k-sockets' klogger = require 'k-logger' kutils = require 'k-utils' KIBANA_IMAGE='eslap.cloud/elk:1_0_0' KIBANA_DOCKER='local-stamp-logger' DEFAULT_CONFIG = daemon: true kibana: true stopLogger: false destroyLogger: false autoUnregister: false autoUndeploy: false CONTAINER_USABLE_MEMORY_PER_UNIT = 512*1024*1024 # 512MB CONTAINER_SWAP_MEMORY_PER_UNIT = CONTAINER_USABLE_MEMORY_PER_UNIT / 2 # 256MB CONTAINER_TOTAL_MEMORY_PER_UNIT = CONTAINER_USABLE_MEMORY_PER_UNIT+ CONTAINER_SWAP_MEMORY_PER_UNIT CONTAINER_RESERVED_MEMORY_PER_UNIT = CONTAINER_USABLE_MEMORY_PER_UNIT / 2 #256MB CONTAINER_KERNEL_MEMORY_PER_UNIT = CONTAINER_USABLE_MEMORY_PER_UNIT / 2 # 256MB CONTAINER_DEV_SHM_SIZE_PER_MEMORY_UNIT = CONTAINER_RESERVED_MEMORY_PER_UNIT / 2 SWAP_WARNING='WARNING: Your kernel does not support swap limit capabilities' DealerSocket = ksockets.DealerSocket DealerReqRep = ksockets.DealerReqRep express = require 'express' bodyParser = require 'body-parser' multer = require 'multer' cors = require 'cors' app = null initialMappedPort = 9000 silencedClasses = [ 'Admission' 'AdmissionRestAPI' 'DealerReqRep' 'ServiceRegistry' 'ComponentRegistry' 'BundleRegistry' 'ManifestStoreRsync' 'ManifestConverter' 'ManifestValidator' 'ManifestStore' 'ManifestHelper' 'RuntimeAgent' ] class LocalStamp constructor: (@id = 'test', @config = {})-> @logger = klogger.getLogger 'LocalStamp' @repos = logFile: '/eslap/runtime-agent/slap.log' manifests: '/eslap/manifest-storage' images: '/eslap/image-storage' instances: '/eslap/instances' volumes: '/eslap/volumes' filterLog @logger, silencedClasses, ['error'] # Hace un rsync de prueba que genera un error. Lo silencio del todo. filterLog @logger, ['ImageFetcher', 'DealerSocket'] @dockerIP = getDocker0IfaceHostIPAddress.call this @state = new State() @routerAgent = new MockRouterAgent this @launcher = new Launcher this # Keeps track of used resources (related to services deployed or deploying) @resourcesInUse = new Resources() @state.addDeployment 'default' @deploymentCounter = 1 @instanceCounter = 1 @busyPorts = {} @links = {} @docker = new Docker() @graceTime = 1000 @admissionPort = @config.admissionPort ? 8090 @domain = @config.domain ? 'local-stamp.slap53.iti.es' @configLogger = @config.logger ? vm: 'local-stamp' transports: file: level: 'debug' filename: 'slap.log' console: level: 'warn' @develBindings = @config.develBindings ? {} @admission_conf = imageFetcher : type : 'blob' config: remoteImageStore: path : "#{@repos.images}/remote" imageFilename : 'image.tgz' localImageStore : path : "#{@repos.images}/local" imageFilename : 'image.tgz' manifestRepository: type : 'rsync' config : remoteImageStore: path : "#{@repos.manifests}/remote" imageFilename : 'manifest.json' localImageStore: path : "#{@repos.manifests}/local" imageFilename : 'manifest.json' acs: 'anonymous-user': id: 'local-stamp', roles: ['ADMIN'] 'addresses': ["127.0.0.1"] 'port': @admissionPort domains: refDomain: @domain limitChecker: limits: max_bundle_size: 10 max_storage_space: 10 deployment_lifespan_days: 10 allow_resources: true allow_domains: true allow_certificates: true allow_volumes: true allow_iopsintensive: true deployments: simultaneous: -1 entrypoints: simultaneous: -1 roles: deployment: -1 simultaneous: -1 maxinstances: arrangement: -1 deployment: -1 simultaneous: -1 cpu: arrangement: -1 deployment: -1 simultaneous: -1 memory: arrangement: -1 deployment: -1 simultaneous: -1 ioperf: arrangement: -1 deployment: -1 simultaneous: -1 bandwidth: arrangement: -1 deployment: -1 simultaneous: -1 # To avoid errors with instances that do not launch an admission instance @wsp = {publishEvt: -> true} init: -> deferred = q.defer() socket = process.env.DOCKER_SOCKET || '/var/run/docker.sock' stats = fs.statSync(socket) if !stats.isSocket() return q.reject new Error 'Are you sure the docker is running?' @docker.listContainers {all:true}, (err, containers)=> return deferred.reject err if err promises = [] for c in containers if c.Names?[0]? and kutils.startsWith(c.Names[0], "/local-stamp_#{@id}_") @logger.debug "Removing previous docker instance #{c.Names[0]}" fc = @docker.getContainer(c.Id) do (fc)-> promises.push (q.ninvoke fc, 'remove', {force: true}) q.all promises .then -> deferred.resolve true deferred.promise .then => # q.ninvoke child, 'exec', " \ # rm -rf #{@lsRepo}; \ # rm -rf /tmp/slap; \ # mkdir -p #{@lsRepo}/manifest-storage/local/; \ # mkdir -p #{@lsRepo}/manifest-storage/remote/; \ # cp -R /eslap/manifest-storage/* #{@lsRepo}/manifest-storage/remote/; \ # mkdir -p #{@lsRepo}/image-storage/local/; \ # mkdir -p #{@lsRepo}/image-storage/remote/; \ # cp -R /eslap/image-storage/* #{@lsRepo}/image-storage/remote/;" q true .then => if @configValue 'kibana' launchKibana.call this .then => if @configValue 'daemon' launchAdmission.call this launchBundle: (path)-> (if not @admAPI launchAdmission.call this else q true ) .then => @logger.debug "Processing bundle in #{path}" deferred = q.defer() @admRest.post '/bundles' .attach 'bundlesZip', path .end (err, res)=> if err? deferred.reject err return if res.status != 200 @logger.error JSON.stringify res, null, 2 deferred.reject new Error 'Unexpected result registering bundle' return # se.log JSON.stringify text, null, 2 @logger.debug 'Bundle correctly deployed' if res.text? res = JSON.parse res.text res = res.data # if res?.deployments?.errors?[0]? # return deferred.reject \ # new Error JSON.stringify res.deployments.errors[0] setTimeout -> deferred.resolve res#.deployments.successful[0] , 3500 deferred.promise launch: (klass, config, deploymentId = 'default')-> @launcher.launch(klass, config, deploymentId) .then (result)=> @state.addInstance deploymentId, result, config result launchGW: (localConfig, config, deploymentId = 'default')-> config.parameters['__gw_local_config'] = localConfig @launcher.launch(GW, config, deploymentId) .then (result)=> result.isGW = true @state.addInstance deploymentId, result, config result launchDocker: (localConfig, config, deployment = 'default')-> console.log "Launching instance #{config.iid}" iid = config.iid ifolder = @instanceFolder iid promiseSocket = promiseStarted = null dealer = control = name = null instanceFolder = socketFolder = tmpFolder = null # First we check if runtime specified is available checkDockerImage.call this, localConfig.runtime .then (found)=> if not found console.error "Docker image for runtime #{localConfig.runtime} is \ not available. Check the platform documentation for information \ on obtaining images of runtimes" return q.reject new Error "Runtime #{localConfig.runtime} \ is not available" [promiseSocket, promiseStarted] = \ @routerAgent.setupInstance config, deployment promiseSocket .then (setupData)=> [control, dealer, sockets] = setupData name = "local-stamp_#{@id}_#{iid}" result = { dealer: dealer control: control isDocker: true dockerName: name logging: true deployment: deployment } @state.addInstance deployment, result, config # This is "simply" a touch slap.log fs.closeSync(fs.openSync(ifolder.local.log, 'w')) tmpPath = commandLine="\ run \ --rm \ --name #{name} \ -v #{ifolder.host.component}:#{localConfig.sourcedir} \ -v #{ifolder.host.data}:/eslap/data \ -v #{ifolder.host.log}:#{@repos.logFile} \ -e RA_CONTROL_SOCKET_URI=#{sockets.control.uri} \ -e RA_DATA_SOCKET_URI=#{sockets.data.uri} \ -e IID=#{config.iid}" agentFolder = null if localConfig.agentPath agentFolder = localConfig.agentPath.host if agentFolder? commandLine = commandLine + " -v #{agentFolder}:/eslap/runtime-agent" if localConfig?.resources?.__memory? m = localConfig.resources.__memory memoryConstraints = [ {constraint: 'memory', factor: CONTAINER_USABLE_MEMORY_PER_UNIT} {constraint: 'memory-swap', factor: CONTAINER_TOTAL_MEMORY_PER_UNIT} {constraint: 'memory-reservation', \ factor: CONTAINER_RESERVED_MEMORY_PER_UNIT} {constraint: 'kernel-memory', \ factor: CONTAINER_KERNEL_MEMORY_PER_UNIT} {constraint: 'shm-size', \ factor: CONTAINER_DEV_SHM_SIZE_PER_MEMORY_UNIT} ] memoryCmd = "" for mc in memoryConstraints memoryCmd = " #{memoryCmd} --#{mc.constraint} #{m * mc.factor}" commandLine = commandLine + memoryCmd + ' ' # if localConfig.runtime is 'eslap.cloud/runtime/java:1_0_1' # commandLine = "#{commandLine} # -v /workspaces/slap/git/gateway-component/src:/eslap/gateway-component/src \ # -v /workspaces/slap/git/runtime-agent/src:/eslap/runtime-agent/src \ # -v /workspaces/slap/git/slap-utils/src:/eslap/runtime-agent/node_modules/slaputils/src \ # -v /workspaces/slap/git/gateway-component/node_modules:/eslap/gateway-component/node_modules \ # -v /workspaces/slap/git/slap-utils/src:/eslap/gateway-component/node_modules/slaputils/src \ # -v /workspaces/slap/git/slap-utils/src:/eslap/component/node_modules/slaputils/src " for v in @config.develBindings?.__all ? [] commandLine = "#{commandLine} -v #{v}" for v in @config.develBindings?[config.role] ? [] commandLine = "#{commandLine} -v #{v}" if localConfig.volumes? for v in localConfig.volumes commandLine = "#{commandLine} -v #{v}" if localConfig.ports? for p in localConfig.ports commandLine = "#{commandLine} -p #{p}" if localConfig.entrypoint? commandLine = "#{commandLine} --entrypoint #{localConfig.entrypoint}" commandLine = "#{commandLine} #{localConfig.runtime}" if localConfig.configdir commandLine = "#{commandLine} #{localConfig.configdir}" commandLine = commandLine.replace(/ +(?= )/g,'') @logger.debug "Creating instance #{config.iid}..." @logger.debug "Docker command line: docker #{commandLine}" # console.log "Docker command line: docker #{commandLine}" try client = spawn 'docker',commandLine.split(' ') client.stdout.on 'data', (data)=> return if not data? # return if not (@instances?[config.iid]?.logging is true) data = data + '' data = data.replace(/[\r\r]+/g, '\r').trim() return if data.length is 0 @logger.debug "DC #{config.iid}: #{data}" console.log "DC #{config.iid}: #{data}" client.stderr.on 'data', (data)=> return if not data? # return if not (@instances?[config.iid]?.logging is true) return if data.indexOf(SWAP_WARNING) is 0 @logger.error "DC error #{config.iid}: #{data}" #console.error "DC error #{config.iid}: #{data}" catch e @logger.error "Error launching Docker #{e} #{e.stack}" promiseStarted.timeout 60 * 1000, "Instance #{config.iid} did not \ started properly, this problem is probably related with its runtime.#{ \ if not localConfig.agentPath? then \ ' Maybe an agent for this runtime should be configured.' \ else \ '' \ }" .then => @state.setInstanceStatus config.iid, {timestamp: (new Date()).getTime()} q.delay 3000 .then => localIP = undefined cmd = ['inspect', '-f', '\"{{ .NetworkSettings.IPAddress }}\"', name] result = spawnSync 'docker', cmd if result.status is 0 localIP = result.stdout.toString().trim().replace(/(^"|"$)/g, '') else if result.stderr?.indexOf 'No such image or container' console.log "Instance #{name} finished unexpectedly. Maybe you \ should examine its log." @state.getInstance(iid).dockerIp = localIP @wsp.publishEvt 'instance', 'created', {instance: iid} shutdownInstance: (iid)-> deferred = q.defer() ref = @state.getInstance iid return if not ref? ref.logging = false (if ref.isDocker ref.control.sendRequest {action: 'instance_stop'} q true else ref.runtime.close() ).then => setTimeout => if ref.isGW ref.instance.destroy() else if ref.isDocker commandLine="stop #{ref.dockerName}" console.log "Shutting down instance #{iid}" client = spawn 'docker',commandLine.split(' ') ref.dealer.close() ref.control.close() @state.removeInstance iid @wsp.publishEvt 'instance', 'removed', {instance: iid} setTimeout -> deferred.resolve true , 1500 , @graceTime deferred.promise loadRuntimes: (runtimes)-> promise = q true for r in runtimes do (r)=> promise = promise.then => @loadRuntime r promise loadRuntime: (runtime)-> rruntime = runtimeURNtoImageName runtime checkDockerImage.call this, rruntime .then (found)=> return true if found himgfile = "#{@imageFolder().host}/#{runtimeURNtoPath runtime}" limgfile = "#{@imageFolder().local}/#{runtimeURNtoPath runtime}" if not fs.existsSync limgfile throw new Error "Runtime #{runtime} is not available. Check the \ platform documentation for information \ on obtaining images of runtimes" commandLine="docker \ load \ -i \ #{limgfile}" console.log "Loading runtime #{runtime}..." @logger.debug "Loading runtime #{himgfile}..." @logger.debug "Docker command line: #{commandLine}" try code = execSync commandLine catch e @logger.error "Error loading runtime #{runtime} #{e} #{e.stack}" throw e shutdown: -> promises = [] for c of @state.getInstances() promises.push @shutdownInstance c q.all promises .then => if @config.destroyLogger removeDockerKibana.call this else if @config.stopLogger stopDockerKibana.call this launchAdmission = -> @planner = new MockPlanner this # @logger.debug 'Creating Admission' setMutedLogger [AdmissionRestAPI.prototype, AdmissionM.Admission.prototype] @admAPI = new AdmissionRestAPI @admission_conf, @planner @admAPI.init() .then => storage = multer.diskStorage { destination: '/tmp/multer' filename: (req, file, cb) -> name = file.fieldname + '-' + \ kutils.generateId() + \ path.extname(file.originalname) cb null, name } upload = multer({ storage: storage }).any() app = express() app.use bodyParser.json() app.use bodyParser.urlencoded({ extended: true }) app.use upload app.use cors() app.use '/admission', @admAPI.getRouter() app.use '/acs', getMockAcsRouter.call(this) # Basic error handler app.use (req, res, next) -> return res.status(404).send('Not Found') # @logger.debug "ADMISSION listening at port #{admissionPort}" httpServer = http.createServer(app) @wsp = new WebsocketPublisher httpServer, @admAPI.httpAuthentication httpServer.listen @admissionPort .then => @admRest = supertest "http://localhost:#{@admissionPort}/admission" q.delay 2000 configValue: (key)-> result = @config[key] ? DEFAULT_CONFIG[key] ? null # console.log "Config #{key}: #{result}" result # allocPort: -> # result = initialMappedPort # while true # sport = result+'' # if not @busyPorts[sport]? # @busyPorts[sport] = true # return sport # result++ # freePort: (port)-> # port = port+'' # if @busyPorts[port]? # delete @busyPorts[port] allocPort: -> getNextAvailablePort = (currentPort, cb) -> server = net.createServer() handleError = -> getNextAvailablePort ++currentPort, cb try server.listen currentPort, '0.0.0.0', -> server.once 'close', -> cb currentPort server.close() server.on 'error', handleError catch e handleError() return new Promise (resolve)-> getNextAvailablePort initialMappedPort, resolve # Now ports are handled finding real free ports because docker, many # times, does not free bound ports as expected freePort: -> nowThisFunctionIsUseless = true instanceFolder: (iid) -> { host: component: "#{@config.instanceFolder}/#{iid}/component" runtime: "#{@config.instanceFolder}/#{iid}/runtime-agent" data: "#{@config.instanceFolder}/#{iid}/data" log: "#{@config.instanceFolder}/#{iid}/slap.log" local: component: "#{@repos.instances}/#{iid}/component" runtime: "#{@repos.instances}/#{iid}/runtime-agent" data: "#{@repos.instances}/#{iid}/data" log: "#{@repos.instances}/#{iid}/slap.log" } volumeFolder: () -> { host: "#{@config.volumeFolder}" local: "#{@repos.volumes}" } manifestFolder: () -> { host: "#{@config.manifestStorage}" local: "#{@repos.manifests}/remote" } imageFolder: () -> { host: "#{@config.imageStorage}" local: "#{@repos.images}/remote" } getPort = (cb)-> port = initialMappedPort server = net.createServer() server.listen port, (err)-> server.once 'close', -> cb(port) server.close() server.on 'error', -> getPort(cb) launchKibana = -> container = @docker.getContainer KIBANA_DOCKER q.ninvoke container, 'inspect' .then (data)=> if not (data?.HostConfig?.PortBindings?['28777/tcp']?) console.log 'Restarting logger' q.ninvoke container, 'remove', {force: true} .then => q.delay 3000 .then => container = @docker.getContainer KIBANA_DOCKER q.ninvoke container, 'inspect' else data .then (data)=> return if data?.State?.Status is 'running' @logger.debug "Removing docker instance #{KIBANA_DOCKER}..." q.ninvoke container, 'remove', {force: true} .then => launchDockerKibana.call this .fail (e)=> return throw e if e.message?.indexOf('404') < 0 launchDockerKibana.call this .then => retries = q.reject false for i in [1..5] do (i)=> retries = retries.fail (e) => q.delay 5000 .then => container = @docker.getContainer KIBANA_DOCKER q.ninvoke container, 'inspect' retries .then (data)=> @loggerIP = data.NetworkSettings.Networks.bridge.IPAddress # With iic=false we can't communicate directly to other container # We communicate using host docker ip @loggerIP = @dockerIP ip = @loggerIP deferred = q.defer() exec = require('child_process').exec; counter = 0 check_logstash = ()-> nc = exec "nc -z #{ip} 28777", -> dummy = 0 nc.on 'exit', (code)-> if code is 0 deferred.resolve() else if counter>20 deferred.reject new Error 'Can\'t contact with logstash' else counter++ console.log "Local-stamp initialization - Waiting for logstash..." setTimeout -> check_logstash() , 5000 do check_logstash deferred.promise .then => deferred = q.defer() @configLogger.transports.logstash = level: 'debug' host: @loggerIP port: 28777 retrier = => @logger.info "Local-stamp connected to logger" @logger.configure @configLogger consoleSilent = @logger._logger.transports.console.silent @logger._logger.transports.console.silent = true @logger._logger.transports.logstash.socket.once 'connect', => cl = @logger._logger.transports.console.log wcl = (level, msg) => return if msg.startsWith 'Logstash Winston transport warning' return if msg.startsWith 'acsStub has no info about acs Location' cl.apply @logger._logger.transports.console, arguments @logger._logger.transports.console.log = wcl setTimeout => @logger._logger.transports.console.log = cl , 30000 @logger._logger.transports.console.silent = consoleSilent @logger._logger.transports.logstash.socket.removeListener 'error', retrier console.log "Connected with logger" console.log "Available Logger in #{@loggerIP}" console.log 'Available Kibana on port 5601' deferred.resolve true @logger._logger.transports.logstash.socket.on 'error', -> setTimeout retrier, 500 retrier() deferred.promise getDocker0IfaceHostIPAddress = -> # os.networkInterfaces() doesn't report DOWN ifaces, # so a less elegant solution is required address = execSync( "ip address show docker0| grep 'inet ' | awk '{print $2}' \ | sed 's/\\/.*//' | tr -d '\\n'").toString() if (not address?) or (address.length is 0 ) @logger.error 'docker0 interface could not be found. Using 172.17.0.1 as fallback.' address = '172.17.0.1' address launchDockerKibana = -> checkDockerImage.call this, KIBANA_IMAGE .then (found)=> if not found console.error "Docker image for #{KIBANA_IMAGE} is \ not available. Check the platform documentation for information \ on obtaining docker images." return q.reject new Error "Docker image not available: #{KIBANA_IMAGE}" commandLine="\ run \ --rm \ --name #{KIBANA_DOCKER} \ -p 5601:5601 \ -p 28777:28777 \ #{KIBANA_IMAGE}" @logger.debug "Creating docker instance #{KIBANA_DOCKER}..." @logger.debug "Docker command line: #{commandLine}" # console.log "Docker command line: #{commandLine}" try client = spawn 'docker',commandLine.split(' ') catch e @logger.error "Error launching Docker #{e} #{e.stack}" .then -> console.log "Local-stamp initialization - \ Waiting for logstash initialization..." #q.delay 15000 removeDockerKibana = -> container = @docker.getContainer KIBANA_DOCKER q.ninvoke container, 'remove', {force: true} .fail -> true stopDockerKibana = -> container = @docker.getContainer KIBANA_DOCKER q.ninvoke container, 'stop' .fail -> true checkDockerImage = (name)-> # console.log "checkDockerImage this:#{this?} docker:#{this.docker?} #{name}" q.ninvoke @docker, 'listImages' .then (images)-> found = false # console.log "Buscando a #{name}" for i in images # console.log JSON.stringify i, null, 2 for t in i.RepoTags ? [] # console.log "Comparando con #{t}" if t is name found = true break found folderExists =(filePath)-> try fs.statSync(filePath).isDirectory() catch err false fileExists =(filePath)-> try fs.statSync(filePath).isFile() catch err false runtimeURNtoImageName =(runtimeURN) -> imageName = runtimeURN.replace('eslap://', '').toLowerCase() index = imageName.lastIndexOf('/') imageName = imageName.substr(0, index) + ':' + imageName.substr(index + 1) imageName runtimeURNtoPath =(runtimeURN) -> imageName = runtimeURN.replace('eslap://', '').toLowerCase() index = imageName.lastIndexOf('/') imageName = imageName.substr(0, index).replace(/_/g, '') + '/' + imageName.substr(index + 1) + '/image.tgz' imageName fakeLogger = debug: -> info: -> error: -> warn: -> log: -> verbose: -> silly: -> setMutedLogger = (refs)-> return for ref in refs ref.logger = fakeLogger if ref? filterLog = (logger, classes, levels = [])-> original = logger._logger.log.bind logger._logger modified = (level, message, metadata)-> if metadata.clazz in classes and level not in levels return original level, message, metadata logger._logger.log = modified getMockAcsRouter = -> mockToken = { "access_token":"PI:PASSWORD:<PASSWORD>END_PI", "token_type":"Bearer", "expires_in":3600, "refresh_token":"PI:PASSWORD:<PASSWORD>END_PI", "user":{"name":"SAASDK Local Stamp","roles":["ADMIN"],"id":"local-stamp"} } @acsRouter = express.Router() @acsRouter.get '/login', (req, res) => res.json mockToken @acsRouter.get '/tokens/:token', (req, res) => res.json mockToken module.exports = LocalStamp
[ { "context": "lse\n if indisponibil\n return null if name != \"Pret Minim\"\n return <p className={\"#{name} field #{ if in", "end": 207, "score": 0.9995617866516113, "start": 197, "tag": "NAME", "value": "Pret Minim" }, { "context": "ibil\" else \"\" }\"}>Indisponibil</p>\n\n if name == \"Pret Minim\"\n <p className={\"#{name} field\"}><span>de la <", "end": 342, "score": 0.9997453093528748, "start": 332, "tag": "NAME", "value": "Pret Minim" } ]
custom/renderers/Pret.coffee
alin23/liftoff
0
import React from 'react' Pret = ({ name, value, row = {} }) -> indisponibil = row.fields.filter((f) -> f.name == "Indisponibil")[0]?.value ? false if indisponibil return null if name != "Pret Minim" return <p className={"#{name} field #{ if indisponibil then "indisponibil" else "" }"}>Indisponibil</p> if name == "Pret Minim" <p className={"#{name} field"}><span>de la </span>{value} {if value == 1 then "leu" else "lei"}</p> else <p className={"#{name} field"}><span>la </span>{value} {if value == 1 then "leu" else "lei"}</p> export default Pret
157654
import React from 'react' Pret = ({ name, value, row = {} }) -> indisponibil = row.fields.filter((f) -> f.name == "Indisponibil")[0]?.value ? false if indisponibil return null if name != "<NAME>" return <p className={"#{name} field #{ if indisponibil then "indisponibil" else "" }"}>Indisponibil</p> if name == "<NAME>" <p className={"#{name} field"}><span>de la </span>{value} {if value == 1 then "leu" else "lei"}</p> else <p className={"#{name} field"}><span>la </span>{value} {if value == 1 then "leu" else "lei"}</p> export default Pret
true
import React from 'react' Pret = ({ name, value, row = {} }) -> indisponibil = row.fields.filter((f) -> f.name == "Indisponibil")[0]?.value ? false if indisponibil return null if name != "PI:NAME:<NAME>END_PI" return <p className={"#{name} field #{ if indisponibil then "indisponibil" else "" }"}>Indisponibil</p> if name == "PI:NAME:<NAME>END_PI" <p className={"#{name} field"}><span>de la </span>{value} {if value == 1 then "leu" else "lei"}</p> else <p className={"#{name} field"}><span>la </span>{value} {if value == 1 then "leu" else "lei"}</p> export default Pret
[ { "context": "\t\"license\": \"MIT\",\n\t\"browsers\": true,\n\t\"author\": \"Barry Michael Doyle <barry@barrymichaeldoyle.com> (https://www.barrym", "end": 327, "score": 0.9998925924301147, "start": 308, "tag": "NAME", "value": "Barry Michael Doyle" }, { "context": "browsers\": true,\n\t\"author\": \"Barry Michael Doyle <barry@barrymichaeldoyle.com> (https://www.barrymichaeldoyle.com)\",\n\t\"maintain", "end": 356, "score": 0.9999313354492188, "start": 329, "tag": "EMAIL", "value": "barry@barrymichaeldoyle.com" }, { "context": "www.barrymichaeldoyle.com)\",\n\t\"maintainers\": [\n\t\t\"Barry Michael Doyle <barry@barrymichaeldoyle.com> (https://www.barrym", "end": 436, "score": 0.9998844265937805, "start": 417, "tag": "NAME", "value": "Barry Michael Doyle" }, { "context": ".com)\",\n\t\"maintainers\": [\n\t\t\"Barry Michael Doyle <barry@barrymichaeldoyle.com> (https://www.barrymichaeldoyle.com)\"\n\t],\n\t\"repos", "end": 465, "score": 0.9999322295188904, "start": 438, "tag": "EMAIL", "value": "barry@barrymichaeldoyle.com" }, { "context": ": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"https://github.com/BarryMichaelDoyle/simple-os-platform.git\"\n\t},\n\t\"bugs\": {\n\t\t\"url\": \"", "end": 588, "score": 0.8237806558609009, "start": 571, "tag": "USERNAME", "value": "BarryMichaelDoyle" }, { "context": "bugs\": {\n\t\t\"url\": \"https://github.com/BarryMichaelDoyle/simple-os-platform/issues\"\n\t},\n\t\"badges\": {\n\t\t\"li", "end": 674, "score": 0.5372194051742554, "start": 669, "tag": "USERNAME", "value": "Doyle" }, { "context": "aviddm\",\n\t\t],\n\t\t\"config\": {\n\t\t\t\"githubUsername\": \"BarryMichaelDoyle\"\n\t\t}\n\t}\n}", "end": 920, "score": 0.9878239631652832, "start": 903, "tag": "USERNAME", "value": "BarryMichaelDoyle" } ]
projectz.cson
barrymichaeldoyle/get-os
3
{ "title": "simple-os-platform", "name": "simple-os-platform", "homepage": "https://www.barrymichaeldoyle.com", "description": "A helper that returns the current user's operating system. Eg. \"Windows\", \"Linux\", \"Android\", \"MacOS\", \"iOS\" etc.", "license": "MIT", "browsers": true, "author": "Barry Michael Doyle <barry@barrymichaeldoyle.com> (https://www.barrymichaeldoyle.com)", "maintainers": [ "Barry Michael Doyle <barry@barrymichaeldoyle.com> (https://www.barrymichaeldoyle.com)" ], "repository": { "type": "git", "url": "https://github.com/BarryMichaelDoyle/simple-os-platform.git" }, "bugs": { "url": "https://github.com/BarryMichaelDoyle/simple-os-platform/issues" }, "badges": { "list": [ "nodeico", "---", "travisci", "npmversion", "npmdownloads", "githubfollow", "githubstar", "daviddm", ], "config": { "githubUsername": "BarryMichaelDoyle" } } }
151521
{ "title": "simple-os-platform", "name": "simple-os-platform", "homepage": "https://www.barrymichaeldoyle.com", "description": "A helper that returns the current user's operating system. Eg. \"Windows\", \"Linux\", \"Android\", \"MacOS\", \"iOS\" etc.", "license": "MIT", "browsers": true, "author": "<NAME> <<EMAIL>> (https://www.barrymichaeldoyle.com)", "maintainers": [ "<NAME> <<EMAIL>> (https://www.barrymichaeldoyle.com)" ], "repository": { "type": "git", "url": "https://github.com/BarryMichaelDoyle/simple-os-platform.git" }, "bugs": { "url": "https://github.com/BarryMichaelDoyle/simple-os-platform/issues" }, "badges": { "list": [ "nodeico", "---", "travisci", "npmversion", "npmdownloads", "githubfollow", "githubstar", "daviddm", ], "config": { "githubUsername": "BarryMichaelDoyle" } } }
true
{ "title": "simple-os-platform", "name": "simple-os-platform", "homepage": "https://www.barrymichaeldoyle.com", "description": "A helper that returns the current user's operating system. Eg. \"Windows\", \"Linux\", \"Android\", \"MacOS\", \"iOS\" etc.", "license": "MIT", "browsers": true, "author": "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (https://www.barrymichaeldoyle.com)", "maintainers": [ "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (https://www.barrymichaeldoyle.com)" ], "repository": { "type": "git", "url": "https://github.com/BarryMichaelDoyle/simple-os-platform.git" }, "bugs": { "url": "https://github.com/BarryMichaelDoyle/simple-os-platform/issues" }, "badges": { "list": [ "nodeico", "---", "travisci", "npmversion", "npmdownloads", "githubfollow", "githubstar", "daviddm", ], "config": { "githubUsername": "BarryMichaelDoyle" } } }
[ { "context": "#################\n# Copyright (C) 2014-2017 by Vaughn Iverson\n# fileCollection is free software released un", "end": 124, "score": 0.9997100234031677, "start": 110, "tag": "NAME", "value": "Vaughn Iverson" } ]
src/resumable_server.coffee
swiftcourt/meteor-file-collection
0
############################################################################ # Copyright (C) 2014-2017 by Vaughn Iverson # fileCollection is free software released under the MIT/X11 license. # See included LICENSE file for details. ############################################################################ import share from './share.js' if Meteor.isServer express = Npm.require 'express' mongodb = Npm.require 'mongodb' grid = Npm.require 'gridfs-locking-stream' gridLocks = Npm.require 'gridfs-locks' dicer = Npm.require 'dicer' async = Npm.require 'async' # This function checks to see if all of the parts of a Resumable.js uploaded file are now in the gridFS # Collection. If so, it completes the file by moving all of the chunks to the correct file and cleans up check_order = (file, callback) -> fileId = mongodb.ObjectID("#{file.metadata._Resumable.resumableIdentifier}") lock = gridLocks.Lock(fileId, @locks, {}).obtainWriteLock() lock.on 'locked', () => files = @db.collection "#{@root}.files" cursor = files.find( { 'metadata._Resumable.resumableIdentifier': file.metadata._Resumable.resumableIdentifier length: $ne: 0 }, { fields: length: 1 metadata: 1 sort: 'metadata._Resumable.resumableChunkNumber': 1 } ) cursor.count (err, count) => if err lock.releaseLock() return callback err unless count >= 1 cursor.close() lock.releaseLock() return callback() unless count is file.metadata._Resumable.resumableTotalChunks cursor.close() lock.releaseLock() return callback() # Manipulate the chunks and files collections directly under write lock chunks = @db.collection "#{@root}.chunks" cursor.batchSize file.metadata._Resumable.resumableTotalChunks + 1 cursor.toArray (err, parts) => if err lock.releaseLock() return callback err async.eachLimit parts, 5, (part, cb) => if err console.error "Error from cursor.next()", err cb err return cb new Meteor.Error "Received null part" unless part partId = mongodb.ObjectID("#{part._id}") partlock = gridLocks.Lock(partId, @locks, {}).obtainWriteLock() partlock.on 'locked', () => async.series [ # Move the chunks to the correct file (cb) -> chunks.update { files_id: partId, n: 0 }, { $set: { files_id: fileId, n: part.metadata._Resumable.resumableChunkNumber - 1 }} cb # Delete the temporary chunk file documents (cb) -> files.remove { _id: partId }, cb ], (err, res) => return cb err if err unless part.metadata._Resumable.resumableChunkNumber is part.metadata._Resumable.resumableTotalChunks partlock.removeLock() cb() else # check for a final hanging gridfs chunk chunks.update { files_id: partId, n: 1 }, { $set: { files_id: fileId, n: part.metadata._Resumable.resumableChunkNumber }} (err, res) -> partlock.removeLock() return cb err if err cb() partlock.on 'timed-out', () -> cb new Meteor.Error 'Partlock timed out!' partlock.on 'expired', () -> cb new Meteor.Error 'Partlock expired!' partlock.on 'error', (err) -> console.error "Error obtaining partlock #{part._id}", err cb err (err) => if err lock.releaseLock() return callback err # Build up the command for the md5 hash calculation md5Command = filemd5: fileId root: "#{@root}" # Send the command to calculate the md5 hash of the file @db.command md5Command, (err, results) -> if err lock.releaseLock() return callback err # Update the size and md5 to the file data files.update { _id: fileId }, { $set: { length: file.metadata._Resumable.resumableTotalSize, md5: results.md5 }}, (err, res) => lock.releaseLock() callback err lock.on 'expires-soon', () -> lock.renewLock().once 'renewed', (ld) -> unless ld console.warn "Resumable upload lock renewal failed!" lock.on 'expired', () -> callback new Meteor.Error "File Lock expired" lock.on 'timed-out', () -> callback new Meteor.Error "File Lock timed out" lock.on 'error', (err) -> callback err # Handle HTTP POST requests from Resumable.js resumable_post_lookup = (params, query, multipart) -> return { _id: share.safeObjectID(multipart?.params?.resumableIdentifier) } resumable_post_handler = (req, res, next) -> # This has to be a resumable POST unless req.multipart?.params?.resumableIdentifier console.error "Missing resumable.js multipart information" res.writeHead(501, share.defaultResponseHeaders) res.end() return resumable = req.multipart.params resumable.resumableTotalSize = parseInt resumable.resumableTotalSize resumable.resumableTotalChunks = parseInt resumable.resumableTotalChunks resumable.resumableChunkNumber = parseInt resumable.resumableChunkNumber resumable.resumableChunkSize = parseInt resumable.resumableChunkSize resumable.resumableCurrentChunkSize = parseInt resumable.resumableCurrentChunkSize if req.maxUploadSize > 0 unless resumable.resumableTotalSize <= req.maxUploadSize res.writeHead(413, share.defaultResponseHeaders) res.end() return # Sanity check the chunk sizes that are critical to reassembling the file from parts unless ((req.gridFS.chunkSize is resumable.resumableChunkSize) and (resumable.resumableChunkNumber <= resumable.resumableTotalChunks) and (resumable.resumableTotalSize/resumable.resumableChunkSize <= resumable.resumableTotalChunks+1) and (resumable.resumableCurrentChunkSize is resumable.resumableChunkSize) or ((resumable.resumableChunkNumber is resumable.resumableTotalChunks) and (resumable.resumableCurrentChunkSize < 2*resumable.resumableChunkSize))) res.writeHead(501, share.defaultResponseHeaders) res.end() return chunkQuery = length: resumable.resumableCurrentChunkSize 'metadata._Resumable.resumableIdentifier': resumable.resumableIdentifier 'metadata._Resumable.resumableChunkNumber': resumable.resumableChunkNumber # This is to handle duplicate chunk uploads in case of network weirdness findResult = @findOne chunkQuery, { fields: { _id: 1 }} if findResult # Duplicate chunk... Don't rewrite it. # console.warn "Duplicate chunk detected: #{resumable.resumableChunkNumber}, #{resumable.resumableIdentifier}" res.writeHead(200, share.defaultResponseHeaders) res.end() else # Everything looks good, so write this part req.gridFS.metadata._Resumable = resumable writeStream = @upsertStream filename: "_Resumable_#{resumable.resumableIdentifier}_#{resumable.resumableChunkNumber}_#{resumable.resumableTotalChunks}" metadata: req.gridFS.metadata unless writeStream res.writeHead(404, share.defaultResponseHeaders) res.end() return req.multipart.fileStream.pipe(share.streamChunker(@chunkSize)).pipe(writeStream) .on 'close', share.bind_env((retFile) => if retFile # Check to see if all of the parts are now available and can be reassembled check_order.bind(@)(req.gridFS, (err) -> if err console.error "Error reassembling chunks of resumable.js upload", err res.writeHead(500, share.defaultResponseHeaders) else res.writeHead(200, share.defaultResponseHeaders) res.end() ) else console.error "Missing retFile on pipe close" res.writeHead(500, share.defaultResponseHeaders) res.end() ) .on 'error', share.bind_env((err) => console.error "Piping Error!", err res.writeHead(500, share.defaultResponseHeaders) res.end()) resumable_get_lookup = (params, query) -> q = { _id: share.safeObjectID(query.resumableIdentifier) } return q # This handles Resumable.js "test GET" requests, that exist to determine # if a part is already uploaded. It also handles HEAD requests, which # should be a bit more efficient and resumable.js now supports resumable_get_handler = (req, res, next) -> query = req.query chunkQuery = $or: [ { _id: share.safeObjectID(query.resumableIdentifier) length: parseInt query.resumableTotalSize } { length: parseInt query.resumableCurrentChunkSize 'metadata._Resumable.resumableIdentifier': query.resumableIdentifier 'metadata._Resumable.resumableChunkNumber': parseInt query.resumableChunkNumber } ] result = @findOne chunkQuery, { fields: { _id: 1 }} if result # Chunk is present res.writeHead(200, share.defaultResponseHeaders) else # Chunk is missing res.writeHead(204, share.defaultResponseHeaders) res.end() # Setup the GET and POST HTTP REST paths for Resumable.js in express share.resumablePaths = [ { method: 'head' path: share.resumableBase lookup: resumable_get_lookup handler: resumable_get_handler } { method: 'post' path: share.resumableBase lookup: resumable_post_lookup handler: resumable_post_handler } { method: 'get' path: share.resumableBase lookup: resumable_get_lookup handler: resumable_get_handler } ]
204928
############################################################################ # Copyright (C) 2014-2017 by <NAME> # fileCollection is free software released under the MIT/X11 license. # See included LICENSE file for details. ############################################################################ import share from './share.js' if Meteor.isServer express = Npm.require 'express' mongodb = Npm.require 'mongodb' grid = Npm.require 'gridfs-locking-stream' gridLocks = Npm.require 'gridfs-locks' dicer = Npm.require 'dicer' async = Npm.require 'async' # This function checks to see if all of the parts of a Resumable.js uploaded file are now in the gridFS # Collection. If so, it completes the file by moving all of the chunks to the correct file and cleans up check_order = (file, callback) -> fileId = mongodb.ObjectID("#{file.metadata._Resumable.resumableIdentifier}") lock = gridLocks.Lock(fileId, @locks, {}).obtainWriteLock() lock.on 'locked', () => files = @db.collection "#{@root}.files" cursor = files.find( { 'metadata._Resumable.resumableIdentifier': file.metadata._Resumable.resumableIdentifier length: $ne: 0 }, { fields: length: 1 metadata: 1 sort: 'metadata._Resumable.resumableChunkNumber': 1 } ) cursor.count (err, count) => if err lock.releaseLock() return callback err unless count >= 1 cursor.close() lock.releaseLock() return callback() unless count is file.metadata._Resumable.resumableTotalChunks cursor.close() lock.releaseLock() return callback() # Manipulate the chunks and files collections directly under write lock chunks = @db.collection "#{@root}.chunks" cursor.batchSize file.metadata._Resumable.resumableTotalChunks + 1 cursor.toArray (err, parts) => if err lock.releaseLock() return callback err async.eachLimit parts, 5, (part, cb) => if err console.error "Error from cursor.next()", err cb err return cb new Meteor.Error "Received null part" unless part partId = mongodb.ObjectID("#{part._id}") partlock = gridLocks.Lock(partId, @locks, {}).obtainWriteLock() partlock.on 'locked', () => async.series [ # Move the chunks to the correct file (cb) -> chunks.update { files_id: partId, n: 0 }, { $set: { files_id: fileId, n: part.metadata._Resumable.resumableChunkNumber - 1 }} cb # Delete the temporary chunk file documents (cb) -> files.remove { _id: partId }, cb ], (err, res) => return cb err if err unless part.metadata._Resumable.resumableChunkNumber is part.metadata._Resumable.resumableTotalChunks partlock.removeLock() cb() else # check for a final hanging gridfs chunk chunks.update { files_id: partId, n: 1 }, { $set: { files_id: fileId, n: part.metadata._Resumable.resumableChunkNumber }} (err, res) -> partlock.removeLock() return cb err if err cb() partlock.on 'timed-out', () -> cb new Meteor.Error 'Partlock timed out!' partlock.on 'expired', () -> cb new Meteor.Error 'Partlock expired!' partlock.on 'error', (err) -> console.error "Error obtaining partlock #{part._id}", err cb err (err) => if err lock.releaseLock() return callback err # Build up the command for the md5 hash calculation md5Command = filemd5: fileId root: "#{@root}" # Send the command to calculate the md5 hash of the file @db.command md5Command, (err, results) -> if err lock.releaseLock() return callback err # Update the size and md5 to the file data files.update { _id: fileId }, { $set: { length: file.metadata._Resumable.resumableTotalSize, md5: results.md5 }}, (err, res) => lock.releaseLock() callback err lock.on 'expires-soon', () -> lock.renewLock().once 'renewed', (ld) -> unless ld console.warn "Resumable upload lock renewal failed!" lock.on 'expired', () -> callback new Meteor.Error "File Lock expired" lock.on 'timed-out', () -> callback new Meteor.Error "File Lock timed out" lock.on 'error', (err) -> callback err # Handle HTTP POST requests from Resumable.js resumable_post_lookup = (params, query, multipart) -> return { _id: share.safeObjectID(multipart?.params?.resumableIdentifier) } resumable_post_handler = (req, res, next) -> # This has to be a resumable POST unless req.multipart?.params?.resumableIdentifier console.error "Missing resumable.js multipart information" res.writeHead(501, share.defaultResponseHeaders) res.end() return resumable = req.multipart.params resumable.resumableTotalSize = parseInt resumable.resumableTotalSize resumable.resumableTotalChunks = parseInt resumable.resumableTotalChunks resumable.resumableChunkNumber = parseInt resumable.resumableChunkNumber resumable.resumableChunkSize = parseInt resumable.resumableChunkSize resumable.resumableCurrentChunkSize = parseInt resumable.resumableCurrentChunkSize if req.maxUploadSize > 0 unless resumable.resumableTotalSize <= req.maxUploadSize res.writeHead(413, share.defaultResponseHeaders) res.end() return # Sanity check the chunk sizes that are critical to reassembling the file from parts unless ((req.gridFS.chunkSize is resumable.resumableChunkSize) and (resumable.resumableChunkNumber <= resumable.resumableTotalChunks) and (resumable.resumableTotalSize/resumable.resumableChunkSize <= resumable.resumableTotalChunks+1) and (resumable.resumableCurrentChunkSize is resumable.resumableChunkSize) or ((resumable.resumableChunkNumber is resumable.resumableTotalChunks) and (resumable.resumableCurrentChunkSize < 2*resumable.resumableChunkSize))) res.writeHead(501, share.defaultResponseHeaders) res.end() return chunkQuery = length: resumable.resumableCurrentChunkSize 'metadata._Resumable.resumableIdentifier': resumable.resumableIdentifier 'metadata._Resumable.resumableChunkNumber': resumable.resumableChunkNumber # This is to handle duplicate chunk uploads in case of network weirdness findResult = @findOne chunkQuery, { fields: { _id: 1 }} if findResult # Duplicate chunk... Don't rewrite it. # console.warn "Duplicate chunk detected: #{resumable.resumableChunkNumber}, #{resumable.resumableIdentifier}" res.writeHead(200, share.defaultResponseHeaders) res.end() else # Everything looks good, so write this part req.gridFS.metadata._Resumable = resumable writeStream = @upsertStream filename: "_Resumable_#{resumable.resumableIdentifier}_#{resumable.resumableChunkNumber}_#{resumable.resumableTotalChunks}" metadata: req.gridFS.metadata unless writeStream res.writeHead(404, share.defaultResponseHeaders) res.end() return req.multipart.fileStream.pipe(share.streamChunker(@chunkSize)).pipe(writeStream) .on 'close', share.bind_env((retFile) => if retFile # Check to see if all of the parts are now available and can be reassembled check_order.bind(@)(req.gridFS, (err) -> if err console.error "Error reassembling chunks of resumable.js upload", err res.writeHead(500, share.defaultResponseHeaders) else res.writeHead(200, share.defaultResponseHeaders) res.end() ) else console.error "Missing retFile on pipe close" res.writeHead(500, share.defaultResponseHeaders) res.end() ) .on 'error', share.bind_env((err) => console.error "Piping Error!", err res.writeHead(500, share.defaultResponseHeaders) res.end()) resumable_get_lookup = (params, query) -> q = { _id: share.safeObjectID(query.resumableIdentifier) } return q # This handles Resumable.js "test GET" requests, that exist to determine # if a part is already uploaded. It also handles HEAD requests, which # should be a bit more efficient and resumable.js now supports resumable_get_handler = (req, res, next) -> query = req.query chunkQuery = $or: [ { _id: share.safeObjectID(query.resumableIdentifier) length: parseInt query.resumableTotalSize } { length: parseInt query.resumableCurrentChunkSize 'metadata._Resumable.resumableIdentifier': query.resumableIdentifier 'metadata._Resumable.resumableChunkNumber': parseInt query.resumableChunkNumber } ] result = @findOne chunkQuery, { fields: { _id: 1 }} if result # Chunk is present res.writeHead(200, share.defaultResponseHeaders) else # Chunk is missing res.writeHead(204, share.defaultResponseHeaders) res.end() # Setup the GET and POST HTTP REST paths for Resumable.js in express share.resumablePaths = [ { method: 'head' path: share.resumableBase lookup: resumable_get_lookup handler: resumable_get_handler } { method: 'post' path: share.resumableBase lookup: resumable_post_lookup handler: resumable_post_handler } { method: 'get' path: share.resumableBase lookup: resumable_get_lookup handler: resumable_get_handler } ]
true
############################################################################ # Copyright (C) 2014-2017 by PI:NAME:<NAME>END_PI # fileCollection is free software released under the MIT/X11 license. # See included LICENSE file for details. ############################################################################ import share from './share.js' if Meteor.isServer express = Npm.require 'express' mongodb = Npm.require 'mongodb' grid = Npm.require 'gridfs-locking-stream' gridLocks = Npm.require 'gridfs-locks' dicer = Npm.require 'dicer' async = Npm.require 'async' # This function checks to see if all of the parts of a Resumable.js uploaded file are now in the gridFS # Collection. If so, it completes the file by moving all of the chunks to the correct file and cleans up check_order = (file, callback) -> fileId = mongodb.ObjectID("#{file.metadata._Resumable.resumableIdentifier}") lock = gridLocks.Lock(fileId, @locks, {}).obtainWriteLock() lock.on 'locked', () => files = @db.collection "#{@root}.files" cursor = files.find( { 'metadata._Resumable.resumableIdentifier': file.metadata._Resumable.resumableIdentifier length: $ne: 0 }, { fields: length: 1 metadata: 1 sort: 'metadata._Resumable.resumableChunkNumber': 1 } ) cursor.count (err, count) => if err lock.releaseLock() return callback err unless count >= 1 cursor.close() lock.releaseLock() return callback() unless count is file.metadata._Resumable.resumableTotalChunks cursor.close() lock.releaseLock() return callback() # Manipulate the chunks and files collections directly under write lock chunks = @db.collection "#{@root}.chunks" cursor.batchSize file.metadata._Resumable.resumableTotalChunks + 1 cursor.toArray (err, parts) => if err lock.releaseLock() return callback err async.eachLimit parts, 5, (part, cb) => if err console.error "Error from cursor.next()", err cb err return cb new Meteor.Error "Received null part" unless part partId = mongodb.ObjectID("#{part._id}") partlock = gridLocks.Lock(partId, @locks, {}).obtainWriteLock() partlock.on 'locked', () => async.series [ # Move the chunks to the correct file (cb) -> chunks.update { files_id: partId, n: 0 }, { $set: { files_id: fileId, n: part.metadata._Resumable.resumableChunkNumber - 1 }} cb # Delete the temporary chunk file documents (cb) -> files.remove { _id: partId }, cb ], (err, res) => return cb err if err unless part.metadata._Resumable.resumableChunkNumber is part.metadata._Resumable.resumableTotalChunks partlock.removeLock() cb() else # check for a final hanging gridfs chunk chunks.update { files_id: partId, n: 1 }, { $set: { files_id: fileId, n: part.metadata._Resumable.resumableChunkNumber }} (err, res) -> partlock.removeLock() return cb err if err cb() partlock.on 'timed-out', () -> cb new Meteor.Error 'Partlock timed out!' partlock.on 'expired', () -> cb new Meteor.Error 'Partlock expired!' partlock.on 'error', (err) -> console.error "Error obtaining partlock #{part._id}", err cb err (err) => if err lock.releaseLock() return callback err # Build up the command for the md5 hash calculation md5Command = filemd5: fileId root: "#{@root}" # Send the command to calculate the md5 hash of the file @db.command md5Command, (err, results) -> if err lock.releaseLock() return callback err # Update the size and md5 to the file data files.update { _id: fileId }, { $set: { length: file.metadata._Resumable.resumableTotalSize, md5: results.md5 }}, (err, res) => lock.releaseLock() callback err lock.on 'expires-soon', () -> lock.renewLock().once 'renewed', (ld) -> unless ld console.warn "Resumable upload lock renewal failed!" lock.on 'expired', () -> callback new Meteor.Error "File Lock expired" lock.on 'timed-out', () -> callback new Meteor.Error "File Lock timed out" lock.on 'error', (err) -> callback err # Handle HTTP POST requests from Resumable.js resumable_post_lookup = (params, query, multipart) -> return { _id: share.safeObjectID(multipart?.params?.resumableIdentifier) } resumable_post_handler = (req, res, next) -> # This has to be a resumable POST unless req.multipart?.params?.resumableIdentifier console.error "Missing resumable.js multipart information" res.writeHead(501, share.defaultResponseHeaders) res.end() return resumable = req.multipart.params resumable.resumableTotalSize = parseInt resumable.resumableTotalSize resumable.resumableTotalChunks = parseInt resumable.resumableTotalChunks resumable.resumableChunkNumber = parseInt resumable.resumableChunkNumber resumable.resumableChunkSize = parseInt resumable.resumableChunkSize resumable.resumableCurrentChunkSize = parseInt resumable.resumableCurrentChunkSize if req.maxUploadSize > 0 unless resumable.resumableTotalSize <= req.maxUploadSize res.writeHead(413, share.defaultResponseHeaders) res.end() return # Sanity check the chunk sizes that are critical to reassembling the file from parts unless ((req.gridFS.chunkSize is resumable.resumableChunkSize) and (resumable.resumableChunkNumber <= resumable.resumableTotalChunks) and (resumable.resumableTotalSize/resumable.resumableChunkSize <= resumable.resumableTotalChunks+1) and (resumable.resumableCurrentChunkSize is resumable.resumableChunkSize) or ((resumable.resumableChunkNumber is resumable.resumableTotalChunks) and (resumable.resumableCurrentChunkSize < 2*resumable.resumableChunkSize))) res.writeHead(501, share.defaultResponseHeaders) res.end() return chunkQuery = length: resumable.resumableCurrentChunkSize 'metadata._Resumable.resumableIdentifier': resumable.resumableIdentifier 'metadata._Resumable.resumableChunkNumber': resumable.resumableChunkNumber # This is to handle duplicate chunk uploads in case of network weirdness findResult = @findOne chunkQuery, { fields: { _id: 1 }} if findResult # Duplicate chunk... Don't rewrite it. # console.warn "Duplicate chunk detected: #{resumable.resumableChunkNumber}, #{resumable.resumableIdentifier}" res.writeHead(200, share.defaultResponseHeaders) res.end() else # Everything looks good, so write this part req.gridFS.metadata._Resumable = resumable writeStream = @upsertStream filename: "_Resumable_#{resumable.resumableIdentifier}_#{resumable.resumableChunkNumber}_#{resumable.resumableTotalChunks}" metadata: req.gridFS.metadata unless writeStream res.writeHead(404, share.defaultResponseHeaders) res.end() return req.multipart.fileStream.pipe(share.streamChunker(@chunkSize)).pipe(writeStream) .on 'close', share.bind_env((retFile) => if retFile # Check to see if all of the parts are now available and can be reassembled check_order.bind(@)(req.gridFS, (err) -> if err console.error "Error reassembling chunks of resumable.js upload", err res.writeHead(500, share.defaultResponseHeaders) else res.writeHead(200, share.defaultResponseHeaders) res.end() ) else console.error "Missing retFile on pipe close" res.writeHead(500, share.defaultResponseHeaders) res.end() ) .on 'error', share.bind_env((err) => console.error "Piping Error!", err res.writeHead(500, share.defaultResponseHeaders) res.end()) resumable_get_lookup = (params, query) -> q = { _id: share.safeObjectID(query.resumableIdentifier) } return q # This handles Resumable.js "test GET" requests, that exist to determine # if a part is already uploaded. It also handles HEAD requests, which # should be a bit more efficient and resumable.js now supports resumable_get_handler = (req, res, next) -> query = req.query chunkQuery = $or: [ { _id: share.safeObjectID(query.resumableIdentifier) length: parseInt query.resumableTotalSize } { length: parseInt query.resumableCurrentChunkSize 'metadata._Resumable.resumableIdentifier': query.resumableIdentifier 'metadata._Resumable.resumableChunkNumber': parseInt query.resumableChunkNumber } ] result = @findOne chunkQuery, { fields: { _id: 1 }} if result # Chunk is present res.writeHead(200, share.defaultResponseHeaders) else # Chunk is missing res.writeHead(204, share.defaultResponseHeaders) res.end() # Setup the GET and POST HTTP REST paths for Resumable.js in express share.resumablePaths = [ { method: 'head' path: share.resumableBase lookup: resumable_get_lookup handler: resumable_get_handler } { method: 'post' path: share.resumableBase lookup: resumable_post_lookup handler: resumable_post_handler } { method: 'get' path: share.resumableBase lookup: resumable_get_lookup handler: resumable_get_handler } ]
[ { "context": " expect(user.get('passwordHash')[..5] in ['31dc3d', '948c7e']).toBeTruthy()\n expect(user.get", "end": 1832, "score": 0.9031532406806946, "start": 1826, "tag": "PASSWORD", "value": "31dc3d" }, { "context": "pect(user.get('passwordHash')[..5] in ['31dc3d', '948c7e']).toBeTruthy()\n expect(user.get('permissi", "end": 1842, "score": 0.9282434582710266, "start": 1836, "tag": "PASSWORD", "value": "948c7e" }, { "context": "SON.parse(body)\n expect(user.name).toBe('Joe') # Anyone should be served the username.\n ", "end": 2258, "score": 0.9955286979675293, "start": 2255, "tag": "NAME", "value": "Joe" }, { "context": "ous user name', (done) ->\n createAnonNameUser('Jim', done)\n\n it 'should allow multiple anonymous us", "end": 3269, "score": 0.9967830181121826, "start": 3266, "tag": "NAME", "value": "Jim" }, { "context": "ith same name', (done) ->\n createAnonNameUser('Jim', done)\n\n it 'should allow setting existing user", "end": 3377, "score": 0.9991130232810974, "start": 3374, "tag": "NAME", "value": "Jim" }, { "context": "est.post({url: getURL('/db/user'), json: {email: 'new@user.com', password: 'new'}}, (err, response, body) ->\n ", "end": 3539, "score": 0.9998974800109863, "start": 3527, "tag": "EMAIL", "value": "new@user.com" }, { "context": "/user'), json: {email: 'new@user.com', password: 'new'}}, (err, response, body) ->\n expect(respons", "end": 3556, "score": 0.9979472756385803, "start": 3553, "tag": "PASSWORD", "value": "new" }, { "context": "nonymous).toBeFalsy()\n createAnonNameUser 'Jim', done\n )\n\ndescribe 'PUT /db/user', ->\n\n it '", "end": 3814, "score": 0.9936603903770447, "start": 3811, "tag": "NAME", "value": "Jim" }, { "context": " _id: '513108d4cb8b610000000004',\n email: 'perfectly@good.com'\n }\n request.put {url: getURL(urlUser), jso", "end": 5412, "score": 0.9999258518218994, "start": 5394, "tag": "EMAIL", "value": "perfectly@good.com" }, { "context": "lJoe (joe) ->\n json = { _id: joe._id, name: 'Joe' }\n request.put { url: getURL(urlUser+'/'+jo", "end": 6090, "score": 0.9997833967208862, "start": 6087, "tag": "NAME", "value": "Joe" }, { "context": " json = {\n _id: joe.id\n email: 'New@email.com'\n name: 'Wilhelm'\n }\n request.pu", "end": 6375, "score": 0.9998553395271301, "start": 6362, "tag": "EMAIL", "value": "New@email.com" }, { "context": ".id\n email: 'New@email.com'\n name: 'Wilhelm'\n }\n request.put { url: getURL(urlUser)", "end": 6399, "score": 0.9997861981391907, "start": 6392, "tag": "NAME", "value": "Wilhelm" }, { "context": "s.statusCode).toBe(200)\n unittest.getUser('Wilhelm', 'New@email.com', 'null', (joe) ->\n exp", "end": 6547, "score": 0.9895615577697754, "start": 6540, "tag": "USERNAME", "value": "Wilhelm" }, { "context": "e).toBe(200)\n unittest.getUser('Wilhelm', 'New@email.com', 'null', (joe) ->\n expect(joe.get('name", "end": 6564, "score": 0.9998709559440613, "start": 6551, "tag": "EMAIL", "value": "New@email.com" }, { "context": " (joe) ->\n expect(joe.get('name')).toBe('Wilhelm')\n expect(joe.get('emailLower')).toBe('n", "end": 6631, "score": 0.9997557997703552, "start": 6624, "tag": "NAME", "value": "Wilhelm" }, { "context": "m')\n expect(joe.get('emailLower')).toBe('new@email.com')\n expect(joe.get('email')).toBe('New@em", "end": 6693, "score": 0.9998427629470825, "start": 6680, "tag": "EMAIL", "value": "new@email.com" }, { "context": "il.com')\n expect(joe.get('email')).toBe('New@email.com')\n done())\n \n\n it 'should not allo", "end": 6750, "score": 0.9998189806938171, "start": 6737, "tag": "EMAIL", "value": "New@email.com" }, { "context": "= yield utils.initUser()\n yield utils.loginUser(@user)\n done()\n\n describe 'when a user is in a clas", "end": 10981, "score": 0.7716190814971924, "start": 10976, "tag": "USERNAME", "value": "@user" }, { "context": " classroom = new Classroom({\n members: [@user._id]\n })\n yield classroom.save()\n do", "end": 11137, "score": 0.9431203007698059, "start": 11129, "tag": "USERNAME", "value": "[@user._" }, { "context": "oEqual('student')\n user = yield User.findById @user._id\n expect(user.get('role')).toEqual('stude", "end": 11479, "score": 0.9757105112075806, "start": 11474, "tag": "USERNAME", "value": "@user" }, { "context": " classrooms = yield Classroom.find members: @user._id\n expect(classrooms.length).toEqual(1)\n ", "end": 11588, "score": 0.693548858165741, "start": 11584, "tag": "USERNAME", "value": "user" }, { "context": "al('student')\n user = yield User.findById @user._id\n expect(user.get('role')).toEqual('stu", "end": 12098, "score": 0.6850782036781311, "start": 12094, "tag": "USERNAME", "value": "user" }, { "context": "qual('student')\n user = yield User.findById @user._id\n expect(user.get('role')).toEqual('stu", "end": 12725, "score": 0.9784566164016724, "start": 12720, "tag": "USERNAME", "value": "@user" }, { "context": " classroom = new Classroom({\n ownerID: @user._id\n })\n yield classroom.save()\n d", "end": 13042, "score": 0.9272751808166504, "start": 13037, "tag": "USERNAME", "value": "@user" }, { "context": "oEqual('student')\n user = yield User.findById @user._id\n expect(user.get('role')).toEqual('stude", "end": 13373, "score": 0.9642410278320312, "start": 13368, "tag": "USERNAME", "value": "@user" }, { "context": ")\n classrooms = yield Classroom.find ownerID: @user._id\n expect(classrooms.length).toEqual(0)\n ", "end": 13482, "score": 0.9217140674591064, "start": 13477, "tag": "USERNAME", "value": "@user" }, { "context": "qual('student')\n user = yield User.findById @user._id\n expect(user.get('role')).toEqual('stu", "end": 13980, "score": 0.9583112001419067, "start": 13975, "tag": "USERNAME", "value": "@user" }, { "context": " classrooms = yield Classroom.find ownerID: @user._id\n expect(classrooms.length).toEqual(0)\n", "end": 14093, "score": 0.8043616414070129, "start": 14088, "tag": "USERNAME", "value": "@user" }, { "context": "qual('student')\n user = yield User.findById @user._id\n expect(user.get('role')).toEqual('stu", "end": 14595, "score": 0.9123954772949219, "start": 14590, "tag": "USERNAME", "value": "@user" }, { "context": " classrooms = yield Classroom.find ownerID: @user._id\n expect(classrooms.length).toEqual(0)\n", "end": 14708, "score": 0.9747865200042725, "start": 14703, "tag": "USERNAME", "value": "@user" }, { "context": " classroom = new Classroom({\n members: [@user._id]\n })\n yield classroom.save()\n clas", "end": 14936, "score": 0.9459768533706665, "start": 14926, "tag": "USERNAME", "value": "[@user._id" }, { "context": " classroom = new Classroom({\n ownerID: @user._id\n })\n yield classroom.save()\n d", "end": 15032, "score": 0.9979230761528015, "start": 15027, "tag": "USERNAME", "value": "@user" }, { "context": "oEqual('student')\n user = yield User.findById @user._id\n expect(user.get('role')).toEqual('stude", "end": 15388, "score": 0.9982022047042847, "start": 15383, "tag": "USERNAME", "value": "@user" }, { "context": ")\n classrooms = yield Classroom.find ownerID: @user._id\n expect(classrooms.length).toEqual(0)\n ", "end": 15497, "score": 0.9962148070335388, "start": 15492, "tag": "USERNAME", "value": "@user" }, { "context": ")\n classrooms = yield Classroom.find members: @user._id\n expect(classrooms.length).toEqual(1)\n ", "end": 15599, "score": 0.9943723678588867, "start": 15594, "tag": "USERNAME", "value": "@user" }, { "context": "oom', ->\n beforeEach utils.wrap (done) ->\n @user.set('role', 'student')\n yield @user.save", "end": 15770, "score": 0.5030940771102905, "start": 15770, "tag": "USERNAME", "value": "" }, { "context": " classroom = new Classroom({\n members: [@user._id]\n })\n yield classroom.save()\n clas", "end": 15886, "score": 0.9854140281677246, "start": 15876, "tag": "USERNAME", "value": "[@user._id" }, { "context": " classroom = new Classroom({\n ownerID: @user._id\n })\n yield classroom.save()\n d", "end": 15982, "score": 0.995712399482727, "start": 15977, "tag": "USERNAME", "value": "@user" }, { "context": "oEqual('student')\n user = yield User.findById @user._id\n expect(user.get('role')).toEqual('stude", "end": 16338, "score": 0.997972846031189, "start": 16333, "tag": "USERNAME", "value": "@user" }, { "context": ")\n classrooms = yield Classroom.find ownerID: @user._id\n expect(classrooms.length).toEqual(0)\n ", "end": 16447, "score": 0.9792380332946777, "start": 16442, "tag": "USERNAME", "value": "@user" }, { "context": ")\n classrooms = yield Classroom.find members: @user._id\n expect(classrooms.length).toEqual(1)\n ", "end": 16549, "score": 0.7008670568466187, "start": 16544, "tag": "USERNAME", "value": "@user" }, { "context": " classroom = new Classroom({\n members: [@user._id]\n })\n yield classroom.save()\n cl", "end": 16834, "score": 0.9663577079772949, "start": 16826, "tag": "USERNAME", "value": "[@user._" }, { "context": " classroom = new Classroom({\n ownerID: @user._id\n })\n yield classroom.save()\n d", "end": 16932, "score": 0.9795246124267578, "start": 16927, "tag": "USERNAME", "value": "@user" }, { "context": "oEqual('student')\n user = yield User.findById @user._id\n expect(user.get('role')).toEqual('stude", "end": 17288, "score": 0.9963079690933228, "start": 17283, "tag": "USERNAME", "value": "@user" }, { "context": ")\n classrooms = yield Classroom.find ownerID: @user._id\n expect(classrooms.length).toEqual(0)\n ", "end": 17397, "score": 0.9308553338050842, "start": 17392, "tag": "USERNAME", "value": "@user" }, { "context": ")\n classrooms = yield Classroom.find members: @user._id\n expect(classrooms.length).toEqual(1)\n ", "end": 17499, "score": 0.86320561170578, "start": 17494, "tag": "USERNAME", "value": "@user" }, { "context": "yield utils.initUser()\n yield utils.loginUser(@user)\n @user.set('role', 'teacher')\n yield @", "end": 17828, "score": 0.9960346221923828, "start": 17823, "tag": "USERNAME", "value": "@user" }, { "context": " classroom = new Classroom({\n members: [@user._id]\n })\n yield classroom.save()\n cl", "end": 17949, "score": 0.9123845100402832, "start": 17941, "tag": "USERNAME", "value": "[@user._" }, { "context": " classroom = new Classroom({\n ownerID: @user._id\n })\n yield classroom.save()\n d", "end": 18047, "score": 0.9786532521247864, "start": 18042, "tag": "USERNAME", "value": "@user" }, { "context": "oEqual('teacher')\n user = yield User.findById @user._id\n expect(user.get('role')).toEqual('teach", "end": 18349, "score": 0.9859514236450195, "start": 18344, "tag": "USERNAME", "value": "@user" }, { "context": ")\n classrooms = yield Classroom.find ownerID: @user._id\n expect(classrooms.length).toEqual(1)\n ", "end": 18458, "score": 0.6521095633506775, "start": 18453, "tag": "USERNAME", "value": "@user" }, { "context": "s admin', (done) ->\n json = {\n username: 'admin@afc.com'\n password: '80yqxpb38j'\n }\n request.p", "end": 18729, "score": 0.9999189376831055, "start": 18716, "tag": "EMAIL", "value": "admin@afc.com" }, { "context": "\n username: 'admin@afc.com'\n password: '80yqxpb38j'\n }\n request.post { url: getURL('/auth/logi", "end": 18758, "score": 0.9992571473121643, "start": 18748, "tag": "PASSWORD", "value": "80yqxpb38j" }, { "context": "e) ->\n session = new LevelSession\n name: 'Beat Gandalf'\n permissions: simplePermissions\n state", "end": 23153, "score": 0.9907658100128174, "start": 23141, "tag": "NAME", "value": "Beat Gandalf" }, { "context": "icle edits', (done) ->\n article =\n name: 'My very first'\n body: 'I don\\'t have much to say I\\'m afra", "end": 24309, "score": 0.9160470962524414, "start": 24296, "tag": "NAME", "value": "My very first" }, { "context": "er/#{user.id}/signup-with-password\")\n email = 'some@email.com'\n name = 'someusername'\n json = { name, ema", "end": 27544, "score": 0.9999224543571472, "start": 27530, "tag": "EMAIL", "value": "some@email.com" }, { "context": "ssword\")\n email = 'some@email.com'\n name = 'someusername'\n json = { name, email, password: '12345' }\n ", "end": 27570, "score": 0.9995657205581665, "start": 27558, "tag": "USERNAME", "value": "someusername" }, { "context": "omeusername'\n json = { name, email, password: '12345' }\n [res, body] = yield request.postAsync({url", "end": 27614, "score": 0.9994298815727234, "start": 27609, "tag": "PASSWORD", "value": "12345" }, { "context": "ser/#{user.id}/signup-with-password\")\n name = 'someusername'\n json = { name, password: '12345' }\n [res,", "end": 28130, "score": 0.9995838403701782, "start": 28118, "tag": "USERNAME", "value": "someusername" }, { "context": "me = 'someusername'\n json = { name, password: '12345' }\n [res, body] = yield request.postAsync({url", "end": 28167, "score": 0.9994173049926758, "start": 28162, "tag": "PASSWORD", "value": "12345" }, { "context": "ser/#{user.id}/signup-with-password\")\n name = 'someusername'\n email = 'user@example.com'\n json = { name", "end": 28875, "score": 0.9995390176773071, "start": 28863, "tag": "USERNAME", "value": "someusername" }, { "context": "password\")\n name = 'someusername'\n email = 'user@example.com'\n json = { name, email, password: '12345' }\n ", "end": 28906, "score": 0.9999225735664368, "start": 28890, "tag": "EMAIL", "value": "user@example.com" }, { "context": "example.com'\n json = { name, email, password: '12345' }\n [res, body] = yield request.postAsync({url", "end": 28950, "score": 0.9994166493415833, "start": 28945, "tag": "PASSWORD", "value": "12345" }, { "context": "d}/signup-with-password\")\n json = { password: '12345' }\n [res, body] = yield request.postAsync({url", "end": 29669, "score": 0.9994543194770813, "start": 29664, "tag": "PASSWORD", "value": "12345" }, { "context": "e given email', utils.wrap (done) ->\n email = 'some@email.com'\n initialUser = yield utils.initUser({email})\n", "end": 30052, "score": 0.9999049305915833, "start": 30038, "tag": "EMAIL", "value": "some@email.com" }, { "context": "up-with-password\")\n json = { email, password: '12345' }\n [res, body] = yield request.postAsync({url", "end": 30296, "score": 0.9994281530380249, "start": 30291, "tag": "PASSWORD", "value": "12345" }, { "context": "given username', utils.wrap (done) ->\n name = 'someusername'\n initialUser = yield utils.initUser({name})\n ", "end": 30520, "score": 0.9993273019790649, "start": 30508, "tag": "USERNAME", "value": "someusername" }, { "context": "nup-with-password\")\n json = { name, password: '12345' }\n [res, body] = yield request.postAsync({url", "end": 30761, "score": 0.999444842338562, "start": 30756, "tag": "PASSWORD", "value": "12345" }, { "context": "ld utils.makeTrialRequest({ properties: { email: 'one@email.com' } })\n expect(trialRequest.get('applicant').eq", "end": 31133, "score": 0.9999187588691711, "start": 31120, "tag": "EMAIL", "value": "one@email.com" }, { "context": "er/#{user.id}/signup-with-password\")\n email = 'two@email.com'\n json = { email, password: '12345' }\n [res", "end": 31297, "score": 0.9999187588691711, "start": 31284, "tag": "EMAIL", "value": "two@email.com" }, { "context": " = 'two@email.com'\n json = { email, password: '12345' }\n [res, body] = yield request.postAsync({url", "end": 31335, "score": 0.9993853569030762, "start": 31330, "tag": "PASSWORD", "value": "12345" }, { "context": "ld utils.makeTrialRequest({ properties: { email: 'one@email.com' } })\n expect(trialRequest.get('applicant').eq", "end": 31829, "score": 0.9999163746833801, "start": 31816, "tag": "EMAIL", "value": "one@email.com" }, { "context": "er/#{user.id}/signup-with-password\")\n email = 'one@email.com'\n json = { email, password: '12345' }\n [res", "end": 31993, "score": 0.9999164342880249, "start": 31980, "tag": "EMAIL", "value": "one@email.com" }, { "context": " = 'one@email.com'\n json = { email, password: '12345' }\n [res, body] = yield request.postAsync({url", "end": 32031, "score": 0.9993664622306824, "start": 32026, "tag": "PASSWORD", "value": "12345" }, { "context": "ok', ->\n facebookID = '12345'\n facebookEmail = 'some@email.com'\n name = 'someusername'\n \n validFacebookRespon", "end": 32388, "score": 0.9999233484268188, "start": 32374, "tag": "EMAIL", "value": "some@email.com" }, { "context": "345'\n facebookEmail = 'some@email.com'\n name = 'someusername'\n \n validFacebookResponse = new Promise((resolv", "end": 32412, "score": 0.9989981055259705, "start": 32400, "tag": "USERNAME", "value": "someusername" }, { "context": "ookID,\n email: facebookEmail,\n first_name: 'Some',\n gender: 'male',\n last_name: 'Person',\n ", "end": 32545, "score": 0.9991265535354614, "start": 32541, "tag": "NAME", "value": "Some" }, { "context": "name: 'Some',\n gender: 'male',\n last_name: 'Person',\n link: 'https://www.facebook.com/app_scoped_", "end": 32590, "score": 0.9993415474891663, "start": 32584, "tag": "NAME", "value": "Person" }, { "context": "_user_id/12345/',\n locale: 'en_US',\n name: 'Some Person',\n timezone: -7,\n updated_time: '2015-12-08", "end": 32700, "score": 0.9989266991615295, "start": 32689, "tag": "NAME", "value": "Some Person" }, { "context": "nup-with-facebook\")\n \n json = { name, email: 'some-other@email.com', facebookID, facebookAccessToken: '...' }\n [r", "end": 34599, "score": 0.9999093413352966, "start": 34579, "tag": "EMAIL", "value": "some-other@email.com" }, { "context": "th-gplus', ->\n gplusID = '12345'\n gplusEmail = 'some@email.com'\n name = 'someusername'\n\n validGPlusResponse = ", "end": 35682, "score": 0.9999143481254578, "start": 35668, "tag": "EMAIL", "value": "some@email.com" }, { "context": "'12345'\n gplusEmail = 'some@email.com'\n name = 'someusername'\n\n validGPlusResponse = new Promise((resolve) ->", "end": 35706, "score": 0.9632882475852966, "start": 35694, "tag": "USERNAME", "value": "someusername" }, { "context": " gplusEmail,\n verified_email: true,\n name: 'Some Person',\n given_name: 'Some',\n family_name: 'Perso", "end": 35854, "score": 0.9839862585067749, "start": 35843, "tag": "NAME", "value": "Some Person" }, { "context": ": true,\n name: 'Some Person',\n given_name: 'Some',\n family_name: 'Person',\n link: 'https://p", "end": 35878, "score": 0.9979779124259949, "start": 35874, "tag": "NAME", "value": "Some" }, { "context": "erson',\n given_name: 'Some',\n family_name: 'Person',\n link: 'https://plus.google.com/12345',\n ", "end": 35905, "score": 0.9986323714256287, "start": 35899, "tag": "NAME", "value": "Person" }, { "context": "user.id)\n expect(updatedUser.get('name')).toBe(name)\n expect(updatedUser.get('email')).toBe(gplusE", "end": 37108, "score": 0.582278847694397, "start": 37104, "tag": "NAME", "value": "name" }, { "context": "gnup-with-gplus\")\n\n json = { name, email: 'some-other@email.com', gplusID, gplusAccessToken: '...' }\n [res, bo", "end": 37992, "score": 0.9998869895935059, "start": 37977, "tag": "EMAIL", "value": "other@email.com" }, { "context": ".wrap (done) ->\n# yield utils.initUser({name: 'someusername', email: gplusEmail})\n# spyOn(gplus, 'fetchMe'", "end": 38506, "score": 0.9996435642242432, "start": 38494, "tag": "USERNAME", "value": "someusername" }, { "context": "user.id}/signup-with-gplus\")\n# json = { name: 'differentusername', email: gplusEmail, gplusID, gplusAccessToken: '", "end": 38733, "score": 0.9996075630187988, "start": 38716, "tag": "USERNAME", "value": "differentusername" }, { "context": "e().getTime())\n @url = utils.getURL(\"/db/user/#{@user.id}/verify/#{verificationCode}\")\n done()\n \n ", "end": 47236, "score": 0.6831475496292114, "start": 47231, "tag": "USERNAME", "value": "@user" }, { "context": ".toHaveBeenCalled()\n user = yield User.findById(@user.id)\n expect(user.get('emailVerified')).toBe(true)", "end": 47551, "score": 0.9365450739860535, "start": 47543, "tag": "USERNAME", "value": "@user.id" } ]
spec/server/functional/user.spec.coffee
noscripter/codecombat
0
require '../common' utils = require '../utils' urlUser = '/db/user' User = require '../../../server/models/User' Classroom = require '../../../server/models/Classroom' CourseInstance = require '../../../server/models/CourseInstance' Course = require '../../../server/models/Course' Campaign = require '../../../server/models/Campaign' TrialRequest = require '../../../server/models/TrialRequest' Prepaid = require '../../../server/models/Prepaid' request = require '../request' facebook = require '../../../server/lib/facebook' gplus = require '../../../server/lib/gplus' sendwithus = require '../../../server/sendwithus' Promise = require 'bluebird' Achievement = require '../../../server/models/Achievement' EarnedAchievement = require '../../../server/models/EarnedAchievement' LevelSession = require '../../../server/models/LevelSession' mongoose = require 'mongoose' describe 'POST /db/user', -> createAnonNameUser = (name, done)-> request.post getURL('/auth/logout'), -> request.get getURL('/auth/whoami'), -> req = request.post({ url: getURL('/db/user'), json: {name}}, (err, response) -> expect(response.statusCode).toBe(200) request.get { url: getURL('/auth/whoami'), json: true }, (request, response, body) -> expect(body.anonymous).toBeTruthy() expect(body.name).toEqual(name) done() ) it 'preparing test : clears the db first', (done) -> clearModels [User], (err) -> throw err if err done() it 'converts the password into a hash', (done) -> unittest.getNormalJoe (user) -> expect(user).toBeTruthy() expect(user.get('password')).toBeUndefined() expect(user?.get('passwordHash')).not.toBeUndefined() if user?.get('passwordHash')? expect(user.get('passwordHash')[..5] in ['31dc3d', '948c7e']).toBeTruthy() expect(user.get('permissions').length).toBe(0) done() it 'serves the user through /db/user/id', (done) -> unittest.getNormalJoe (user) -> utils.becomeAnonymous().then -> url = getURL(urlUser+'/'+user._id) request.get url, (err, res, body) -> expect(res.statusCode).toBe(200) user = JSON.parse(body) expect(user.name).toBe('Joe') # Anyone should be served the username. expect(user.email).toBeUndefined() # Shouldn't be available to just anyone. expect(user.passwordHash).toBeUndefined() done() it 'creates admins based on passwords', (done) -> request.post getURL('/auth/logout'), -> unittest.getAdmin (user) -> expect(user).not.toBeUndefined() if user expect(user.get('permissions').length).toBe(1) expect(user.get('permissions')[0]).toBe('admin') done() it 'does not return the full user object for regular users.', (done) -> loginJoe -> unittest.getAdmin (user) -> url = getURL(urlUser+'/'+user._id) request.get url, (err, res, body) -> expect(res.statusCode).toBe(200) user = JSON.parse(body) expect(user.email).toBeUndefined() expect(user.passwordHash).toBeUndefined() done() it 'should allow setting anonymous user name', (done) -> createAnonNameUser('Jim', done) it 'should allow multiple anonymous users with same name', (done) -> createAnonNameUser('Jim', done) it 'should allow setting existing user name to anonymous user', (done) -> req = request.post({url: getURL('/db/user'), json: {email: 'new@user.com', password: 'new'}}, (err, response, body) -> expect(response.statusCode).toBe(200) request.get getURL('/auth/whoami'), (request, response, body) -> res = JSON.parse(response.body) expect(res.anonymous).toBeFalsy() createAnonNameUser 'Jim', done ) describe 'PUT /db/user', -> it 'logs in as normal joe', (done) -> request.post getURL('/auth/logout'), loginJoe -> done() it 'denies requests without any data', (done) -> request.put getURL(urlUser), (err, res) -> expect(res.statusCode).toBe(422) expect(res.body).toBe('No input.') done() it 'denies requests to edit someone who is not joe', (done) -> unittest.getAdmin (admin) -> request.put {url: getURL(urlUser), json: {_id: admin.id}}, (err, res) -> expect(res.statusCode).toBe(403) done() it 'denies invalid data', (done) -> unittest.getNormalJoe (joe) -> json = { _id: joe.id email: 'farghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlar ghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghl' } request.put { url: getURL(urlUser), json }, (err, res) -> expect(res.statusCode).toBe(422) expect(res.body[0].message.indexOf('too long')).toBeGreaterThan(-1) done() it 'does not allow normals to edit their permissions', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: { permissions: ['admin'] }} expect(_.contains(body.permissions, 'admin')).toBe(false) done() it 'logs in as admin', (done) -> loginAdmin -> done() it 'denies non-existent ids', (done) -> json = { _id: '513108d4cb8b610000000004', email: 'perfectly@good.com' } request.put {url: getURL(urlUser), json}, (err, res) -> expect(res.statusCode).toBe(404) done() it 'denies if the email being changed is already taken', (done) -> unittest.getNormalJoe (joe) -> unittest.getAdmin (admin) -> json = { _id: admin.id, email: joe.get('email').toUpperCase() } request.put { url: getURL(urlUser), json }, (err, res) -> expect(res.statusCode).toBe(409) expect(res.body.message.indexOf('already used')).toBeGreaterThan(-1) done() it 'does not care if you include your existing name', (done) -> unittest.getNormalJoe (joe) -> json = { _id: joe._id, name: 'Joe' } request.put { url: getURL(urlUser+'/'+joe._id), json }, (err, res) -> expect(res.statusCode).toBe(200) done() it 'accepts name and email changes', (done) -> unittest.getNormalJoe (joe) -> json = { _id: joe.id email: 'New@email.com' name: 'Wilhelm' } request.put { url: getURL(urlUser), json }, (err, res) -> expect(res.statusCode).toBe(200) unittest.getUser('Wilhelm', 'New@email.com', 'null', (joe) -> expect(joe.get('name')).toBe('Wilhelm') expect(joe.get('emailLower')).toBe('new@email.com') expect(joe.get('email')).toBe('New@email.com') done()) it 'should not allow two users with the same name slug', (done) -> loginSam (sam) -> samsName = sam.get 'name' sam.set 'name', 'admin' request.put {uri:getURL(urlUser + '/' + sam.id), json: sam.toObject()}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe 409 # Restore Sam sam.set 'name', samsName done() it 'should be able to unset a slug by setting an empty name', (done) -> loginSam (sam) -> samsName = sam.get 'name' sam.set 'name', '' request.put {uri:getURL(urlUser + '/' + sam.id), json: sam.toObject()}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe 200 newSam = response.body # Restore Sam sam.set 'name', samsName request.put {uri:getURL(urlUser + '/' + sam.id), json: sam.toObject()}, (err, response) -> expect(err).toBeNull() done() describe 'when role is changed to teacher or other school administrator', -> it 'removes the user from all classrooms they are in', utils.wrap (done) -> user = yield utils.initUser() classroom = new Classroom({members: [user._id]}) yield classroom.save() expect(classroom.get('members').length).toBe(1) yield utils.loginUser(user) [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: { role: 'teacher' }} yield new Promise (resolve) -> setTimeout(resolve, 10) classroom = yield Classroom.findById(classroom.id) expect(classroom.get('members').length).toBe(0) done() it 'changes the role regardless of emailVerified', utils.wrap (done) -> user = yield utils.initUser() user.set('emailVerified', true) yield user.save() yield utils.loginUser(user) attrs = user.toObject() attrs.role = 'teacher' [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: attrs } user = yield User.findById(user.id) expect(user.get('role')).toBe('teacher') done() it 'ignores attempts to change away from a teacher role', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) url = getURL('/db/user/'+user.id) [res, body] = yield request.putAsync { uri: url, json: { role: 'teacher' }} expect(body.role).toBe('teacher') [res, body] = yield request.putAsync { uri: url, json: { role: 'advisor' }} expect(body.role).toBe('advisor') [res, body] = yield request.putAsync { uri: url, json: { role: 'student' }} expect(body.role).toBe('advisor') done() it 'returns 422 if both email and name would be unset for a registered user', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: { email: '', name: '' }} expect(body.code).toBe(422) expect(body.message).toEqual('User needs a username or email address') done() it 'allows unsetting email, even when there\'s a user with email and emailLower set to empty string', utils.wrap (done) -> invalidUser = yield utils.initUser() yield invalidUser.update({$set: {email: '', emailLower: ''}}) user = yield utils.initUser() yield utils.loginUser(user) [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: { email: '' }} expect(res.statusCode).toBe(200) expect(res.body.email).toBeUndefined() done() it 'allows unsetting name, even when there\'s a user with name and nameLower set to empty string', utils.wrap (done) -> invalidUser = yield utils.initUser() yield invalidUser.update({$set: {name: '', nameLower: ''}}) user = yield utils.initUser() yield utils.loginUser(user) [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: { name: '' }} expect(res.statusCode).toBe(200) expect(res.body.name).toBeUndefined() done() describe 'PUT /db/user/-/become-student', -> beforeEach utils.wrap (done) -> @url = getURL('/db/user/-/become-student') @user = yield utils.initUser() yield utils.loginUser(@user) done() describe 'when a user is in a classroom', -> beforeEach utils.wrap (done) -> classroom = new Classroom({ members: [@user._id] }) yield classroom.save() done() it 'keeps the user in their classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'when a teacher', -> beforeEach utils.wrap (done) -> @user.set('role', 'student') yield @user.save() done() it 'keeps the user in their classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'when a student', -> beforeEach utils.wrap (done) -> @user.set('role', 'student') yield @user.save() done() it 'keeps the user in their classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'when a user owns a classroom', -> beforeEach utils.wrap (done) -> classroom = new Classroom({ ownerID: @user._id }) yield classroom.save() done() it 'removes the classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) done() describe 'when a student', -> beforeEach utils.wrap (done) -> @user.set('role', 'student') yield @user.save() done() it 'removes the classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) done() describe 'when a teacher', -> beforeEach utils.wrap (done) -> @user.set('role', 'teacher') yield @user.save() done() it 'removes the classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) done() describe 'when a user in a classroom and owns a classroom', -> beforeEach utils.wrap (done) -> classroom = new Classroom({ members: [@user._id] }) yield classroom.save() classroom = new Classroom({ ownerID: @user._id }) yield classroom.save() done() it 'removes owned classrooms, keeps in classrooms, and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'when a student in a classroom and owns a classroom', -> beforeEach utils.wrap (done) -> @user.set('role', 'student') yield @user.save() classroom = new Classroom({ members: [@user._id] }) yield classroom.save() classroom = new Classroom({ ownerID: @user._id }) yield classroom.save() done() it 'removes owned classrooms, keeps in classrooms, and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'when a teacher in a classroom and owns a classroom', -> beforeEach utils.wrap (done) -> @user.set('role', 'teacher') yield @user.save() classroom = new Classroom({ members: [@user._id] }) yield classroom.save() classroom = new Classroom({ ownerID: @user._id }) yield classroom.save() done() it 'removes owned classrooms, keeps in classrooms, and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'PUT /db/user/-/remain-teacher', -> describe 'when a teacher in classroom and owns a classroom', -> beforeEach utils.wrap (done) -> @url = getURL('/db/user/-/remain-teacher') @user = yield utils.initUser() yield utils.loginUser(@user) @user.set('role', 'teacher') yield @user.save() classroom = new Classroom({ members: [@user._id] }) yield classroom.save() classroom = new Classroom({ ownerID: @user._id }) yield classroom.save() done() it 'removes from classrooms', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('teacher') user = yield User.findById @user._id expect(user.get('role')).toEqual('teacher') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(1) classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(0) done() describe 'GET /db/user', -> it 'logs in as admin', (done) -> json = { username: 'admin@afc.com' password: '80yqxpb38j' } request.post { url: getURL('/auth/login'), json }, (error, response) -> expect(response.statusCode).toBe(200) done() it 'get schema', (done) -> request.get {uri: getURL(urlUser+'/schema')}, (err, res, body) -> expect(res.statusCode).toBe(200) body = JSON.parse(body) expect(body.type).toBeDefined() done() it 'is able to do a semi-sweet query', (done) -> options = { url: getURL(urlUser) + "?conditions[limit]=20&conditions[sort]=-dateCreated" } req = request.get(options, (error, response) -> expect(response.statusCode).toBe(200) res = JSON.parse(response.body) expect(res.length).toBeGreaterThan(0) done() ) it 'rejects bad conditions', (done) -> options = { url: getURL(urlUser) + "?conditions[lime]=20&conditions[sort]=-dateCreated" } req = request.get(options, (error, response) -> expect(response.statusCode).toBe(422) done() ) it 'can fetch myself by id completely', (done) -> loginSam (sam) -> request.get {url: getURL(urlUser + '/' + sam.id)}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe(200) done() it 'can fetch myself by slug completely', (done) -> loginSam (sam) -> request.get {url: getURL(urlUser + '/sam')}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe(200) guy = JSON.parse response.body expect(guy._id).toBe sam.get('_id').toHexString() expect(guy.name).toBe sam.get 'name' done() # TODO Ruben should be able to fetch other users but probably with restricted data access # Add to the test case above an extra data check # xit 'can fetch another user with restricted fields' describe 'GET /db/user/:handle', -> it 'populates coursePrepaid from coursePrepaidID', utils.wrap (done) -> course = yield utils.makeCourse() user = yield utils.initUser({coursePrepaidID: course.id}) [res, body] = yield request.getAsync({url: getURL("/db/user/#{user.id}"), json: true}) expect(res.statusCode).toBe(200) expect(res.body.coursePrepaid._id).toBe(course.id) expect(res.body.coursePrepaid.startDate).toBe(Prepaid.DEFAULT_START_DATE) done() describe 'DELETE /db/user', -> it 'can delete a user', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) beforeDeleted = new Date() [res, body] = yield request.delAsync {uri: "#{getURL(urlUser)}/#{user.id}"} user = yield User.findById user.id expect(user.get('deleted')).toBe(true) expect(user.get('dateDeleted')).toBeGreaterThan(beforeDeleted) expect(user.get('dateDeleted')).toBeLessThan(new Date()) for key, value of user.toObject() continue if key in ['_id', 'deleted', 'dateDeleted'] expect(_.isEmpty(value)).toEqual(true) done() it 'moves user to classroom.deletedMembers', utils.wrap (done) -> user = yield utils.initUser() user2 = yield utils.initUser() yield utils.loginUser(user) classroom = new Classroom({ members: [user._id, user2._id] }) yield classroom.save() [res, body] = yield request.delAsync {uri: "#{getURL(urlUser)}/#{user.id}"} classroom = yield Classroom.findById(classroom.id) expect(classroom.get('members').length).toBe(1) expect(classroom.get('deletedMembers').length).toBe(1) expect(classroom.get('members')[0].toString()).toEqual(user2.id) expect(classroom.get('deletedMembers')[0].toString()).toEqual(user.id) done() it 'returns 401 if no cookie session', utils.wrap (done) -> yield utils.logout() [res, body] = yield request.delAsync {uri: "#{getURL(urlUser)}/1234"} expect(res.statusCode).toBe(401) done() describe 'Statistics', -> LevelSession = require '../../../server/models/LevelSession' Article = require '../../../server/models/Article' Level = require '../../../server/models/Level' LevelSystem = require '../../../server/models/LevelSystem' LevelComponent = require '../../../server/models/LevelComponent' ThangType = require '../../../server/models/ThangType' User = require '../../../server/models/User' UserHandler = require '../../../server/handlers/user_handler' it 'keeps track of games completed', (done) -> session = new LevelSession name: 'Beat Gandalf' permissions: simplePermissions state: complete: true unittest.getNormalJoe (joe) -> expect(joe.get 'stats.gamesCompleted').toBeUndefined() session.set 'creator', joe.get 'id' session.save (err) -> expect(err).toBeNull() f = -> User.findById joe.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get 'id').toBe joe.get 'id' expect(guy.get 'stats.gamesCompleted').toBe 1 done() setTimeout f, 100 it 'recalculates games completed', (done) -> unittest.getNormalJoe (joe) -> loginAdmin -> User.findByIdAndUpdate joe.get('id'), {$unset:'stats.gamesCompleted': ''}, {new: true}, (err, guy) -> expect(err).toBeNull() expect(guy.get 'stats.gamesCompleted').toBeUndefined() UserHandler.statRecalculators.gamesCompleted -> User.findById joe.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get 'stats.gamesCompleted').toBe 1 done() it 'keeps track of article edits', (done) -> article = name: 'My very first' body: 'I don\'t have much to say I\'m afraid' url = getURL('/db/article') loginAdmin (carl) -> expect(carl.get User.statsMapping.edits.article).toBeUndefined() article.creator = carl.get 'id' # Create major version 0.0 request.post {uri:url, json: article}, (err, res, body) -> expect(err).toBeNull() expect(res.statusCode).toBe 201 article = body User.findById carl.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.article).toBe 1 # Create minor version 0.1 newVersionURL = "#{url}/#{article._id}/new-version" request.post {uri:newVersionURL, json: article}, (err, res, body) -> expect(err).toBeNull() User.findById carl.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.article).toBe 2 done() it 'recalculates article edits', (done) -> loginAdmin (carl) -> User.findByIdAndUpdate carl.get('id'), {$unset:'stats.articleEdits': ''}, {new: true}, (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.article).toBeUndefined() UserHandler.statRecalculators.articleEdits -> User.findById carl.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.article).toBe 2 done() it 'keeps track of level edits', (done) -> level = new Level name: "King's Peak 3" description: 'Climb a mountain.' permissions: simplePermissions scripts: [] thangs: [] loginAdmin (carl) -> expect(carl.get User.statsMapping.edits.level).toBeUndefined() level.creator = carl.get 'id' level.save (err) -> expect(err).toBeNull() User.findById carl.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get 'id').toBe carl.get 'id' expect(guy.get User.statsMapping.edits.level).toBe 1 done() it 'recalculates level edits', (done) -> unittest.getAdmin (jose) -> User.findByIdAndUpdate jose.get('id'), {$unset:'stats.levelEdits':''}, {new: true}, (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.level).toBeUndefined() UserHandler.statRecalculators.levelEdits -> User.findById jose.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.level).toBe 1 done() it 'cleans up', (done) -> clearModels [LevelSession, Article, Level, LevelSystem, LevelComponent, ThangType], (err) -> expect(err).toBeNull() done() describe 'POST /db/user/:handle/signup-with-password', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User]) yield new Promise((resolve) -> setTimeout(resolve, 10)) done() it 'signs up the user with the password and sends welcome emails', utils.wrap (done) -> spyOn(sendwithus.api, 'send') user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") email = 'some@email.com' name = 'someusername' json = { name, email, password: '12345' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) updatedUser = yield User.findById(user.id) expect(updatedUser.get('email')).toBe(email) expect(updatedUser.get('passwordHash')).toBeDefined() expect(sendwithus.api.send).toHaveBeenCalled() done() it 'signs up the user with just a name and password', utils.wrap (done) -> user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") name = 'someusername' json = { name, password: '12345' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) updatedUser = yield User.findById(user.id) expect(updatedUser.get('name')).toBe(name) expect(updatedUser.get('nameLower')).toBe(name.toLowerCase()) expect(updatedUser.get('slug')).toBe(name.toLowerCase()) expect(updatedUser.get('passwordHash')).toBeDefined() expect(updatedUser.get('email')).toBeUndefined() expect(updatedUser.get('emailLower')).toBeUndefined() done() it 'signs up the user with a username, email, and password', utils.wrap (done) -> user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") name = 'someusername' email = 'user@example.com' json = { name, email, password: '12345' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) updatedUser = yield User.findById(user.id) expect(updatedUser.get('name')).toBe(name) expect(updatedUser.get('nameLower')).toBe(name.toLowerCase()) expect(updatedUser.get('slug')).toBe(name.toLowerCase()) expect(updatedUser.get('email')).toBe(email) expect(updatedUser.get('emailLower')).toBe(email.toLowerCase()) expect(updatedUser.get('passwordHash')).toBeDefined() done() it 'returns 422 if neither username or email were provided', utils.wrap (done) -> user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") json = { password: '12345' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) updatedUser = yield User.findById(user.id) expect(updatedUser.get('anonymous')).toBe(true) expect(updatedUser.get('passwordHash')).toBeUndefined() done() it 'returns 409 if there is already a user with the given email', utils.wrap (done) -> email = 'some@email.com' initialUser = yield utils.initUser({email}) expect(initialUser.get('emailLower')).toBeDefined() user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") json = { email, password: '12345' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(409) done() it 'returns 409 if there is already a user with the given username', utils.wrap (done) -> name = 'someusername' initialUser = yield utils.initUser({name}) expect(initialUser.get('nameLower')).toBeDefined() user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") json = { name, password: '12345' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(409) done() it 'disassociates the user from their trial request if the trial request email and signup email do not match', utils.wrap (done) -> user = yield utils.becomeAnonymous() trialRequest = yield utils.makeTrialRequest({ properties: { email: 'one@email.com' } }) expect(trialRequest.get('applicant').equals(user._id)).toBe(true) url = getURL("/db/user/#{user.id}/signup-with-password") email = 'two@email.com' json = { email, password: '12345' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) trialRequest = yield TrialRequest.findById(trialRequest.id) expect(trialRequest.get('applicant')).toBeUndefined() done() it 'does NOT disassociate the user from their trial request if the trial request email and signup email DO match', utils.wrap (done) -> user = yield utils.becomeAnonymous() trialRequest = yield utils.makeTrialRequest({ properties: { email: 'one@email.com' } }) expect(trialRequest.get('applicant').equals(user._id)).toBe(true) url = getURL("/db/user/#{user.id}/signup-with-password") email = 'one@email.com' json = { email, password: '12345' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) trialRequest = yield TrialRequest.findById(trialRequest.id) expect(trialRequest.get('applicant').equals(user._id)).toBe(true) done() describe 'POST /db/user/:handle/signup-with-facebook', -> facebookID = '12345' facebookEmail = 'some@email.com' name = 'someusername' validFacebookResponse = new Promise((resolve) -> resolve({ id: facebookID, email: facebookEmail, first_name: 'Some', gender: 'male', last_name: 'Person', link: 'https://www.facebook.com/app_scoped_user_id/12345/', locale: 'en_US', name: 'Some Person', timezone: -7, updated_time: '2015-12-08T17:10:39+0000', verified: true })) invalidFacebookResponse = new Promise((resolve) -> resolve({ error: { message: 'Invalid OAuth access token.', type: 'OAuthException', code: 190, fbtrace_id: 'EC4dEdeKHBH' } })) beforeEach utils.wrap (done) -> yield utils.clearModels([User]) yield new Promise((resolve) -> setTimeout(resolve, 50)) done() it 'signs up the user with the facebookID and sends welcome emails', utils.wrap (done) -> spyOn(facebook, 'fetchMe').and.returnValue(validFacebookResponse) spyOn(sendwithus.api, 'send') user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-facebook") json = { name, email: facebookEmail, facebookID, facebookAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) updatedUser = yield User.findById(user.id) expect(updatedUser.get('email')).toBe(facebookEmail) expect(updatedUser.get('facebookID')).toBe(facebookID) expect(sendwithus.api.send).toHaveBeenCalled() done() it 'returns 422 if facebook does not recognize the access token', utils.wrap (done) -> spyOn(facebook, 'fetchMe').and.returnValue(invalidFacebookResponse) user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-facebook") json = { email: facebookEmail, facebookID, facebookAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) done() it 'returns 422 if the email or id do not match', utils.wrap (done) -> spyOn(facebook, 'fetchMe').and.returnValue(validFacebookResponse) user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-facebook") json = { name, email: 'some-other@email.com', facebookID, facebookAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) json = { name, email: facebookEmail, facebookID: '54321', facebookAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) done() # TODO: Fix this test, res.statusCode is occasionally 200 # it 'returns 409 if there is already a user with the given email', utils.wrap (done) -> # initialUser = yield utils.initUser({email: facebookEmail}) # expect(initialUser.get('emailLower')).toBeDefined() # spyOn(facebook, 'fetchMe').and.returnValue(validFacebookResponse) # user = yield utils.becomeAnonymous() # url = getURL("/db/user/#{user.id}/signup-with-facebook") # json = { name, email: facebookEmail, facebookID, facebookAccessToken: '...' } # [res, body] = yield request.postAsync({url, json}) # expect(res.statusCode).toBe(409) # done() describe 'POST /db/user/:handle/signup-with-gplus', -> gplusID = '12345' gplusEmail = 'some@email.com' name = 'someusername' validGPlusResponse = new Promise((resolve) -> resolve({ id: gplusID email: gplusEmail, verified_email: true, name: 'Some Person', given_name: 'Some', family_name: 'Person', link: 'https://plus.google.com/12345', picture: 'https://lh6.googleusercontent.com/...', gender: 'male', locale: 'en' })) invalidGPlusResponse = new Promise((resolve) -> resolve({ "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" } })) beforeEach utils.wrap (done) -> yield utils.clearModels([User]) yield new Promise((resolve) -> setTimeout(resolve, 50)) done() it 'signs up the user with the gplusID and sends welcome emails', utils.wrap (done) -> spyOn(gplus, 'fetchMe').and.returnValue(validGPlusResponse) spyOn(sendwithus.api, 'send') user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-gplus") json = { name, email: gplusEmail, gplusID, gplusAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) updatedUser = yield User.findById(user.id) expect(updatedUser.get('name')).toBe(name) expect(updatedUser.get('email')).toBe(gplusEmail) expect(updatedUser.get('gplusID')).toBe(gplusID) expect(sendwithus.api.send).toHaveBeenCalled() done() it 'returns 422 if gplus does not recognize the access token', utils.wrap (done) -> spyOn(gplus, 'fetchMe').and.returnValue(invalidGPlusResponse) user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-gplus") json = { name, email: gplusEmail, gplusID, gplusAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) done() it 'returns 422 if the email or id do not match', utils.wrap (done) -> spyOn(gplus, 'fetchMe').and.returnValue(validGPlusResponse) user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-gplus") json = { name, email: 'some-other@email.com', gplusID, gplusAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) json = { name, email: gplusEmail, gplusID: '54321', gplusAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) done() # TODO: Fix this test, res.statusCode is occasionally 200 # it 'returns 409 if there is already a user with the given email', utils.wrap (done) -> # yield utils.initUser({name: 'someusername', email: gplusEmail}) # spyOn(gplus, 'fetchMe').and.returnValue(validGPlusResponse) # user = yield utils.becomeAnonymous() # url = getURL("/db/user/#{user.id}/signup-with-gplus") # json = { name: 'differentusername', email: gplusEmail, gplusID, gplusAccessToken: '...' } # [res, body] = yield request.postAsync({url, json}) # expect(res.statusCode).toBe(409) # done() describe 'POST /db/user/:handle/destudent', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom, CourseInstance, Course, Campaign]) done() it 'removes a student user from all classrooms and unsets their role property', utils.wrap (done) -> student1 = yield utils.initUser({role: 'student'}) student2 = yield utils.initUser({role: 'student'}) members = [student1._id, student2._id] classroom = new Classroom({members}) yield classroom.save() courseInstance = new CourseInstance({members}) yield courseInstance.save() admin = yield utils.initAdmin() yield utils.loginUser(admin) url = getURL("/db/user/#{student1.id}/destudent") [res, body] = yield request.postAsync({url, json:true}) student1 = yield User.findById(student1.id) student2 = yield User.findById(student2.id) classroom = yield Classroom.findById(classroom.id) courseInstance = yield CourseInstance.findById(courseInstance.id) expect(student1.get('role')).toBeUndefined() expect(student2.get('role')).toBe('student') expect(classroom.get('members').length).toBe(1) expect(classroom.get('members')[0].toString()).toBe(student2.id) expect(courseInstance.get('members').length).toBe(1) expect(courseInstance.get('members')[0].toString()).toBe(student2.id) done() describe 'POST /db/user/:handle/deteacher', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, TrialRequest]) done() it 'removes a student user from all classrooms and unsets their role property', utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) trialRequest = yield utils.makeTrialRequest(teacher) admin = yield utils.initAdmin() yield utils.loginUser(admin) trialRequest = yield TrialRequest.findById(trialRequest.id) expect(trialRequest).toBeDefined() expect(teacher.get('role')).toBe('teacher') url = getURL("/db/user/#{teacher.id}/deteacher") [res, body] = yield request.postAsync({url, json:true}) trialRequest = yield TrialRequest.findById(trialRequest.id) expect(trialRequest).toBeNull() teacher = yield User.findById(teacher.id) expect(teacher.get('role')).toBeUndefined() done() describe 'POST /db/user/:handle/check-for-new-achievements', -> achievementURL = getURL('/db/achievement') achievementJSON = { collection: 'users' query: {'points': {$gt: 50}} userField: '_id' recalculable: true worth: 75 rewards: { gems: 50 levels: [new mongoose.Types.ObjectId().toString()] } name: 'Dungeon Arena Started' description: 'Started playing Dungeon Arena.' related: 'a' } beforeEach utils.wrap (done) -> yield utils.clearModels [Achievement, EarnedAchievement, LevelSession, User] Achievement.resetAchievements() done() it 'finds new achievements and awards them to the user', utils.wrap (done) -> user = yield utils.initUser({points: 100}) yield utils.loginUser(user) url = utils.getURL("/db/user/#{user.id}/check-for-new-achievement") json = true [res, body] = yield request.postAsync({ url, json }) earned = yield EarnedAchievement.count() expect(earned).toBe(0) admin = yield utils.initAdmin() yield utils.loginUser(admin) [res, body] = yield request.postAsync { uri: achievementURL, json: achievementJSON } achievementUpdated = res.body.updated expect(res.statusCode).toBe(201) user = yield User.findById(user.id) expect(user.get('earned')).toBeUndefined() yield utils.loginUser(user) [res, body] = yield request.postAsync({ url, json }) expect(body.points).toBe(175) earned = yield EarnedAchievement.count() expect(earned).toBe(1) expect(body.lastAchievementChecked).toBe(achievementUpdated) done() it 'updates the user if they already earned the achievement but the rewards changed', utils.wrap (done) -> user = yield utils.initUser({points: 100}) yield utils.loginUser(user) url = utils.getURL("/db/user/#{user.id}/check-for-new-achievement") json = true [res, body] = yield request.postAsync({ url, json }) admin = yield utils.initAdmin() yield utils.loginUser(admin) [res, body] = yield request.postAsync { uri: achievementURL, json: achievementJSON } achievement = yield Achievement.findById(body._id) expect(res.statusCode).toBe(201) user = yield User.findById(user.id) expect(user.get('rewards')).toBeUndefined() yield utils.loginUser(user) [res, body] = yield request.postAsync({ url, json }) expect(res.body.points).toBe(175) expect(res.body.earned.gems).toBe(50) achievement.set({ updated: new Date().toISOString() rewards: { gems: 100 } worth: 200 }) yield achievement.save() [res, body] = yield request.postAsync({ url, json }) expect(res.body.earned.gems).toBe(100) expect(res.body.points).toBe(300) expect(res.statusCode).toBe(200) # special case: no worth, should default to 10 yield achievement.update({ $set: {updated: new Date().toISOString()}, $unset: {worth:''} }) [res, body] = yield request.postAsync({ url, json }) expect(res.body.earned.gems).toBe(100) expect(res.body.points).toBe(110) expect(res.statusCode).toBe(200) done() it 'works for level sessions', utils.wrap (done) -> admin = yield utils.initAdmin() yield utils.loginUser(admin) level = yield utils.makeLevel() achievement = yield utils.makeAchievement({ collection: 'level.sessions' userField: 'creator' query: { 'level.original': level.get('original').toString() 'state': {complete: true} } worth: 100 proportionalTo: 'state.difficulty' }) levelSession = yield utils.makeLevelSession({state: {complete: true, difficulty:2}}, { creator:admin, level }) url = utils.getURL("/db/user/#{admin.id}/check-for-new-achievement") json = true [res, body] = yield request.postAsync({ url, json }) expect(body.points).toBe(200) # check idempotency achievement.set('updated', new Date().toISOString()) yield achievement.save() [res, body] = yield request.postAsync({ url, json }) expect(body.points).toBe(200) admin = yield User.findById(admin.id) done() it 'skips achievements which have not been satisfied', utils.wrap (done) -> admin = yield utils.initAdmin() yield utils.loginUser(admin) level = yield utils.makeLevel() achievement = yield utils.makeAchievement({ collection: 'level.sessions' userField: 'creator' query: { 'level.original': 'does not matter' } worth: 100 }) expect(admin.get('lastAchievementChecked')).toBeUndefined() url = utils.getURL("/db/user/#{admin.id}/check-for-new-achievement") json = true [res, body] = yield request.postAsync({ url, json }) expect(body.points).toBeUndefined() admin = yield User.findById(admin.id) expect(admin.get('lastAchievementChecked')).toBe(achievement.get('updated')) done() it 'skips achievements which are not either for the users collection or the level sessions collection with level.original included', utils.wrap (done) -> admin = yield utils.initAdmin() yield utils.loginUser(admin) achievement = yield utils.makeAchievement({ collection: 'not.supported' userField: 'creator' query: {} worth: 100 }) expect(admin.get('lastAchievementChecked')).toBeUndefined() url = utils.getURL("/db/user/#{admin.id}/check-for-new-achievement") json = true [res, body] = yield request.postAsync({ url, json }) expect(body.points).toBeUndefined() admin = yield User.findById(admin.id) expect(admin.get('lastAchievementChecked')).toBe(achievement.get('updated')) done() describe 'POST /db/user/:userID/request-verify-email', -> mailChimp = require '../../../server/lib/mail-chimp' beforeEach utils.wrap (done) -> spyOn(mailChimp.api, 'put').and.returnValue(Promise.resolve()) @user = yield utils.initUser() verificationCode = @user.verificationCode(new Date().getTime()) @url = utils.getURL("/db/user/#{@user.id}/verify/#{verificationCode}") done() it 'sets emailVerified to true and updates MailChimp', utils.wrap (done) -> [res, body] = yield request.postAsync({ @url, json: true }) expect(res.statusCode).toBe(200) expect(mailChimp.api.put).toHaveBeenCalled() user = yield User.findById(@user.id) expect(user.get('emailVerified')).toBe(true) done()
141060
require '../common' utils = require '../utils' urlUser = '/db/user' User = require '../../../server/models/User' Classroom = require '../../../server/models/Classroom' CourseInstance = require '../../../server/models/CourseInstance' Course = require '../../../server/models/Course' Campaign = require '../../../server/models/Campaign' TrialRequest = require '../../../server/models/TrialRequest' Prepaid = require '../../../server/models/Prepaid' request = require '../request' facebook = require '../../../server/lib/facebook' gplus = require '../../../server/lib/gplus' sendwithus = require '../../../server/sendwithus' Promise = require 'bluebird' Achievement = require '../../../server/models/Achievement' EarnedAchievement = require '../../../server/models/EarnedAchievement' LevelSession = require '../../../server/models/LevelSession' mongoose = require 'mongoose' describe 'POST /db/user', -> createAnonNameUser = (name, done)-> request.post getURL('/auth/logout'), -> request.get getURL('/auth/whoami'), -> req = request.post({ url: getURL('/db/user'), json: {name}}, (err, response) -> expect(response.statusCode).toBe(200) request.get { url: getURL('/auth/whoami'), json: true }, (request, response, body) -> expect(body.anonymous).toBeTruthy() expect(body.name).toEqual(name) done() ) it 'preparing test : clears the db first', (done) -> clearModels [User], (err) -> throw err if err done() it 'converts the password into a hash', (done) -> unittest.getNormalJoe (user) -> expect(user).toBeTruthy() expect(user.get('password')).toBeUndefined() expect(user?.get('passwordHash')).not.toBeUndefined() if user?.get('passwordHash')? expect(user.get('passwordHash')[..5] in ['<PASSWORD>', '<PASSWORD>']).toBeTruthy() expect(user.get('permissions').length).toBe(0) done() it 'serves the user through /db/user/id', (done) -> unittest.getNormalJoe (user) -> utils.becomeAnonymous().then -> url = getURL(urlUser+'/'+user._id) request.get url, (err, res, body) -> expect(res.statusCode).toBe(200) user = JSON.parse(body) expect(user.name).toBe('<NAME>') # Anyone should be served the username. expect(user.email).toBeUndefined() # Shouldn't be available to just anyone. expect(user.passwordHash).toBeUndefined() done() it 'creates admins based on passwords', (done) -> request.post getURL('/auth/logout'), -> unittest.getAdmin (user) -> expect(user).not.toBeUndefined() if user expect(user.get('permissions').length).toBe(1) expect(user.get('permissions')[0]).toBe('admin') done() it 'does not return the full user object for regular users.', (done) -> loginJoe -> unittest.getAdmin (user) -> url = getURL(urlUser+'/'+user._id) request.get url, (err, res, body) -> expect(res.statusCode).toBe(200) user = JSON.parse(body) expect(user.email).toBeUndefined() expect(user.passwordHash).toBeUndefined() done() it 'should allow setting anonymous user name', (done) -> createAnonNameUser('<NAME>', done) it 'should allow multiple anonymous users with same name', (done) -> createAnonNameUser('<NAME>', done) it 'should allow setting existing user name to anonymous user', (done) -> req = request.post({url: getURL('/db/user'), json: {email: '<EMAIL>', password: '<PASSWORD>'}}, (err, response, body) -> expect(response.statusCode).toBe(200) request.get getURL('/auth/whoami'), (request, response, body) -> res = JSON.parse(response.body) expect(res.anonymous).toBeFalsy() createAnonNameUser '<NAME>', done ) describe 'PUT /db/user', -> it 'logs in as normal joe', (done) -> request.post getURL('/auth/logout'), loginJoe -> done() it 'denies requests without any data', (done) -> request.put getURL(urlUser), (err, res) -> expect(res.statusCode).toBe(422) expect(res.body).toBe('No input.') done() it 'denies requests to edit someone who is not joe', (done) -> unittest.getAdmin (admin) -> request.put {url: getURL(urlUser), json: {_id: admin.id}}, (err, res) -> expect(res.statusCode).toBe(403) done() it 'denies invalid data', (done) -> unittest.getNormalJoe (joe) -> json = { _id: joe.id email: 'farghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlar ghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghl' } request.put { url: getURL(urlUser), json }, (err, res) -> expect(res.statusCode).toBe(422) expect(res.body[0].message.indexOf('too long')).toBeGreaterThan(-1) done() it 'does not allow normals to edit their permissions', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: { permissions: ['admin'] }} expect(_.contains(body.permissions, 'admin')).toBe(false) done() it 'logs in as admin', (done) -> loginAdmin -> done() it 'denies non-existent ids', (done) -> json = { _id: '513108d4cb8b610000000004', email: '<EMAIL>' } request.put {url: getURL(urlUser), json}, (err, res) -> expect(res.statusCode).toBe(404) done() it 'denies if the email being changed is already taken', (done) -> unittest.getNormalJoe (joe) -> unittest.getAdmin (admin) -> json = { _id: admin.id, email: joe.get('email').toUpperCase() } request.put { url: getURL(urlUser), json }, (err, res) -> expect(res.statusCode).toBe(409) expect(res.body.message.indexOf('already used')).toBeGreaterThan(-1) done() it 'does not care if you include your existing name', (done) -> unittest.getNormalJoe (joe) -> json = { _id: joe._id, name: '<NAME>' } request.put { url: getURL(urlUser+'/'+joe._id), json }, (err, res) -> expect(res.statusCode).toBe(200) done() it 'accepts name and email changes', (done) -> unittest.getNormalJoe (joe) -> json = { _id: joe.id email: '<EMAIL>' name: '<NAME>' } request.put { url: getURL(urlUser), json }, (err, res) -> expect(res.statusCode).toBe(200) unittest.getUser('Wilhelm', '<EMAIL>', 'null', (joe) -> expect(joe.get('name')).toBe('<NAME>') expect(joe.get('emailLower')).toBe('<EMAIL>') expect(joe.get('email')).toBe('<EMAIL>') done()) it 'should not allow two users with the same name slug', (done) -> loginSam (sam) -> samsName = sam.get 'name' sam.set 'name', 'admin' request.put {uri:getURL(urlUser + '/' + sam.id), json: sam.toObject()}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe 409 # Restore Sam sam.set 'name', samsName done() it 'should be able to unset a slug by setting an empty name', (done) -> loginSam (sam) -> samsName = sam.get 'name' sam.set 'name', '' request.put {uri:getURL(urlUser + '/' + sam.id), json: sam.toObject()}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe 200 newSam = response.body # Restore Sam sam.set 'name', samsName request.put {uri:getURL(urlUser + '/' + sam.id), json: sam.toObject()}, (err, response) -> expect(err).toBeNull() done() describe 'when role is changed to teacher or other school administrator', -> it 'removes the user from all classrooms they are in', utils.wrap (done) -> user = yield utils.initUser() classroom = new Classroom({members: [user._id]}) yield classroom.save() expect(classroom.get('members').length).toBe(1) yield utils.loginUser(user) [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: { role: 'teacher' }} yield new Promise (resolve) -> setTimeout(resolve, 10) classroom = yield Classroom.findById(classroom.id) expect(classroom.get('members').length).toBe(0) done() it 'changes the role regardless of emailVerified', utils.wrap (done) -> user = yield utils.initUser() user.set('emailVerified', true) yield user.save() yield utils.loginUser(user) attrs = user.toObject() attrs.role = 'teacher' [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: attrs } user = yield User.findById(user.id) expect(user.get('role')).toBe('teacher') done() it 'ignores attempts to change away from a teacher role', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) url = getURL('/db/user/'+user.id) [res, body] = yield request.putAsync { uri: url, json: { role: 'teacher' }} expect(body.role).toBe('teacher') [res, body] = yield request.putAsync { uri: url, json: { role: 'advisor' }} expect(body.role).toBe('advisor') [res, body] = yield request.putAsync { uri: url, json: { role: 'student' }} expect(body.role).toBe('advisor') done() it 'returns 422 if both email and name would be unset for a registered user', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: { email: '', name: '' }} expect(body.code).toBe(422) expect(body.message).toEqual('User needs a username or email address') done() it 'allows unsetting email, even when there\'s a user with email and emailLower set to empty string', utils.wrap (done) -> invalidUser = yield utils.initUser() yield invalidUser.update({$set: {email: '', emailLower: ''}}) user = yield utils.initUser() yield utils.loginUser(user) [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: { email: '' }} expect(res.statusCode).toBe(200) expect(res.body.email).toBeUndefined() done() it 'allows unsetting name, even when there\'s a user with name and nameLower set to empty string', utils.wrap (done) -> invalidUser = yield utils.initUser() yield invalidUser.update({$set: {name: '', nameLower: ''}}) user = yield utils.initUser() yield utils.loginUser(user) [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: { name: '' }} expect(res.statusCode).toBe(200) expect(res.body.name).toBeUndefined() done() describe 'PUT /db/user/-/become-student', -> beforeEach utils.wrap (done) -> @url = getURL('/db/user/-/become-student') @user = yield utils.initUser() yield utils.loginUser(@user) done() describe 'when a user is in a classroom', -> beforeEach utils.wrap (done) -> classroom = new Classroom({ members: [@user._id] }) yield classroom.save() done() it 'keeps the user in their classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'when a teacher', -> beforeEach utils.wrap (done) -> @user.set('role', 'student') yield @user.save() done() it 'keeps the user in their classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'when a student', -> beforeEach utils.wrap (done) -> @user.set('role', 'student') yield @user.save() done() it 'keeps the user in their classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'when a user owns a classroom', -> beforeEach utils.wrap (done) -> classroom = new Classroom({ ownerID: @user._id }) yield classroom.save() done() it 'removes the classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) done() describe 'when a student', -> beforeEach utils.wrap (done) -> @user.set('role', 'student') yield @user.save() done() it 'removes the classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) done() describe 'when a teacher', -> beforeEach utils.wrap (done) -> @user.set('role', 'teacher') yield @user.save() done() it 'removes the classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) done() describe 'when a user in a classroom and owns a classroom', -> beforeEach utils.wrap (done) -> classroom = new Classroom({ members: [@user._id] }) yield classroom.save() classroom = new Classroom({ ownerID: @user._id }) yield classroom.save() done() it 'removes owned classrooms, keeps in classrooms, and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'when a student in a classroom and owns a classroom', -> beforeEach utils.wrap (done) -> @user.set('role', 'student') yield @user.save() classroom = new Classroom({ members: [@user._id] }) yield classroom.save() classroom = new Classroom({ ownerID: @user._id }) yield classroom.save() done() it 'removes owned classrooms, keeps in classrooms, and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'when a teacher in a classroom and owns a classroom', -> beforeEach utils.wrap (done) -> @user.set('role', 'teacher') yield @user.save() classroom = new Classroom({ members: [@user._id] }) yield classroom.save() classroom = new Classroom({ ownerID: @user._id }) yield classroom.save() done() it 'removes owned classrooms, keeps in classrooms, and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'PUT /db/user/-/remain-teacher', -> describe 'when a teacher in classroom and owns a classroom', -> beforeEach utils.wrap (done) -> @url = getURL('/db/user/-/remain-teacher') @user = yield utils.initUser() yield utils.loginUser(@user) @user.set('role', 'teacher') yield @user.save() classroom = new Classroom({ members: [@user._id] }) yield classroom.save() classroom = new Classroom({ ownerID: @user._id }) yield classroom.save() done() it 'removes from classrooms', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('teacher') user = yield User.findById @user._id expect(user.get('role')).toEqual('teacher') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(1) classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(0) done() describe 'GET /db/user', -> it 'logs in as admin', (done) -> json = { username: '<EMAIL>' password: '<PASSWORD>' } request.post { url: getURL('/auth/login'), json }, (error, response) -> expect(response.statusCode).toBe(200) done() it 'get schema', (done) -> request.get {uri: getURL(urlUser+'/schema')}, (err, res, body) -> expect(res.statusCode).toBe(200) body = JSON.parse(body) expect(body.type).toBeDefined() done() it 'is able to do a semi-sweet query', (done) -> options = { url: getURL(urlUser) + "?conditions[limit]=20&conditions[sort]=-dateCreated" } req = request.get(options, (error, response) -> expect(response.statusCode).toBe(200) res = JSON.parse(response.body) expect(res.length).toBeGreaterThan(0) done() ) it 'rejects bad conditions', (done) -> options = { url: getURL(urlUser) + "?conditions[lime]=20&conditions[sort]=-dateCreated" } req = request.get(options, (error, response) -> expect(response.statusCode).toBe(422) done() ) it 'can fetch myself by id completely', (done) -> loginSam (sam) -> request.get {url: getURL(urlUser + '/' + sam.id)}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe(200) done() it 'can fetch myself by slug completely', (done) -> loginSam (sam) -> request.get {url: getURL(urlUser + '/sam')}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe(200) guy = JSON.parse response.body expect(guy._id).toBe sam.get('_id').toHexString() expect(guy.name).toBe sam.get 'name' done() # TODO Ruben should be able to fetch other users but probably with restricted data access # Add to the test case above an extra data check # xit 'can fetch another user with restricted fields' describe 'GET /db/user/:handle', -> it 'populates coursePrepaid from coursePrepaidID', utils.wrap (done) -> course = yield utils.makeCourse() user = yield utils.initUser({coursePrepaidID: course.id}) [res, body] = yield request.getAsync({url: getURL("/db/user/#{user.id}"), json: true}) expect(res.statusCode).toBe(200) expect(res.body.coursePrepaid._id).toBe(course.id) expect(res.body.coursePrepaid.startDate).toBe(Prepaid.DEFAULT_START_DATE) done() describe 'DELETE /db/user', -> it 'can delete a user', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) beforeDeleted = new Date() [res, body] = yield request.delAsync {uri: "#{getURL(urlUser)}/#{user.id}"} user = yield User.findById user.id expect(user.get('deleted')).toBe(true) expect(user.get('dateDeleted')).toBeGreaterThan(beforeDeleted) expect(user.get('dateDeleted')).toBeLessThan(new Date()) for key, value of user.toObject() continue if key in ['_id', 'deleted', 'dateDeleted'] expect(_.isEmpty(value)).toEqual(true) done() it 'moves user to classroom.deletedMembers', utils.wrap (done) -> user = yield utils.initUser() user2 = yield utils.initUser() yield utils.loginUser(user) classroom = new Classroom({ members: [user._id, user2._id] }) yield classroom.save() [res, body] = yield request.delAsync {uri: "#{getURL(urlUser)}/#{user.id}"} classroom = yield Classroom.findById(classroom.id) expect(classroom.get('members').length).toBe(1) expect(classroom.get('deletedMembers').length).toBe(1) expect(classroom.get('members')[0].toString()).toEqual(user2.id) expect(classroom.get('deletedMembers')[0].toString()).toEqual(user.id) done() it 'returns 401 if no cookie session', utils.wrap (done) -> yield utils.logout() [res, body] = yield request.delAsync {uri: "#{getURL(urlUser)}/1234"} expect(res.statusCode).toBe(401) done() describe 'Statistics', -> LevelSession = require '../../../server/models/LevelSession' Article = require '../../../server/models/Article' Level = require '../../../server/models/Level' LevelSystem = require '../../../server/models/LevelSystem' LevelComponent = require '../../../server/models/LevelComponent' ThangType = require '../../../server/models/ThangType' User = require '../../../server/models/User' UserHandler = require '../../../server/handlers/user_handler' it 'keeps track of games completed', (done) -> session = new LevelSession name: '<NAME>' permissions: simplePermissions state: complete: true unittest.getNormalJoe (joe) -> expect(joe.get 'stats.gamesCompleted').toBeUndefined() session.set 'creator', joe.get 'id' session.save (err) -> expect(err).toBeNull() f = -> User.findById joe.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get 'id').toBe joe.get 'id' expect(guy.get 'stats.gamesCompleted').toBe 1 done() setTimeout f, 100 it 'recalculates games completed', (done) -> unittest.getNormalJoe (joe) -> loginAdmin -> User.findByIdAndUpdate joe.get('id'), {$unset:'stats.gamesCompleted': ''}, {new: true}, (err, guy) -> expect(err).toBeNull() expect(guy.get 'stats.gamesCompleted').toBeUndefined() UserHandler.statRecalculators.gamesCompleted -> User.findById joe.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get 'stats.gamesCompleted').toBe 1 done() it 'keeps track of article edits', (done) -> article = name: '<NAME>' body: 'I don\'t have much to say I\'m afraid' url = getURL('/db/article') loginAdmin (carl) -> expect(carl.get User.statsMapping.edits.article).toBeUndefined() article.creator = carl.get 'id' # Create major version 0.0 request.post {uri:url, json: article}, (err, res, body) -> expect(err).toBeNull() expect(res.statusCode).toBe 201 article = body User.findById carl.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.article).toBe 1 # Create minor version 0.1 newVersionURL = "#{url}/#{article._id}/new-version" request.post {uri:newVersionURL, json: article}, (err, res, body) -> expect(err).toBeNull() User.findById carl.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.article).toBe 2 done() it 'recalculates article edits', (done) -> loginAdmin (carl) -> User.findByIdAndUpdate carl.get('id'), {$unset:'stats.articleEdits': ''}, {new: true}, (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.article).toBeUndefined() UserHandler.statRecalculators.articleEdits -> User.findById carl.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.article).toBe 2 done() it 'keeps track of level edits', (done) -> level = new Level name: "King's Peak 3" description: 'Climb a mountain.' permissions: simplePermissions scripts: [] thangs: [] loginAdmin (carl) -> expect(carl.get User.statsMapping.edits.level).toBeUndefined() level.creator = carl.get 'id' level.save (err) -> expect(err).toBeNull() User.findById carl.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get 'id').toBe carl.get 'id' expect(guy.get User.statsMapping.edits.level).toBe 1 done() it 'recalculates level edits', (done) -> unittest.getAdmin (jose) -> User.findByIdAndUpdate jose.get('id'), {$unset:'stats.levelEdits':''}, {new: true}, (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.level).toBeUndefined() UserHandler.statRecalculators.levelEdits -> User.findById jose.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.level).toBe 1 done() it 'cleans up', (done) -> clearModels [LevelSession, Article, Level, LevelSystem, LevelComponent, ThangType], (err) -> expect(err).toBeNull() done() describe 'POST /db/user/:handle/signup-with-password', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User]) yield new Promise((resolve) -> setTimeout(resolve, 10)) done() it 'signs up the user with the password and sends welcome emails', utils.wrap (done) -> spyOn(sendwithus.api, 'send') user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") email = '<EMAIL>' name = 'someusername' json = { name, email, password: '<PASSWORD>' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) updatedUser = yield User.findById(user.id) expect(updatedUser.get('email')).toBe(email) expect(updatedUser.get('passwordHash')).toBeDefined() expect(sendwithus.api.send).toHaveBeenCalled() done() it 'signs up the user with just a name and password', utils.wrap (done) -> user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") name = 'someusername' json = { name, password: '<PASSWORD>' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) updatedUser = yield User.findById(user.id) expect(updatedUser.get('name')).toBe(name) expect(updatedUser.get('nameLower')).toBe(name.toLowerCase()) expect(updatedUser.get('slug')).toBe(name.toLowerCase()) expect(updatedUser.get('passwordHash')).toBeDefined() expect(updatedUser.get('email')).toBeUndefined() expect(updatedUser.get('emailLower')).toBeUndefined() done() it 'signs up the user with a username, email, and password', utils.wrap (done) -> user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") name = 'someusername' email = '<EMAIL>' json = { name, email, password: '<PASSWORD>' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) updatedUser = yield User.findById(user.id) expect(updatedUser.get('name')).toBe(name) expect(updatedUser.get('nameLower')).toBe(name.toLowerCase()) expect(updatedUser.get('slug')).toBe(name.toLowerCase()) expect(updatedUser.get('email')).toBe(email) expect(updatedUser.get('emailLower')).toBe(email.toLowerCase()) expect(updatedUser.get('passwordHash')).toBeDefined() done() it 'returns 422 if neither username or email were provided', utils.wrap (done) -> user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") json = { password: '<PASSWORD>' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) updatedUser = yield User.findById(user.id) expect(updatedUser.get('anonymous')).toBe(true) expect(updatedUser.get('passwordHash')).toBeUndefined() done() it 'returns 409 if there is already a user with the given email', utils.wrap (done) -> email = '<EMAIL>' initialUser = yield utils.initUser({email}) expect(initialUser.get('emailLower')).toBeDefined() user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") json = { email, password: '<PASSWORD>' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(409) done() it 'returns 409 if there is already a user with the given username', utils.wrap (done) -> name = 'someusername' initialUser = yield utils.initUser({name}) expect(initialUser.get('nameLower')).toBeDefined() user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") json = { name, password: '<PASSWORD>' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(409) done() it 'disassociates the user from their trial request if the trial request email and signup email do not match', utils.wrap (done) -> user = yield utils.becomeAnonymous() trialRequest = yield utils.makeTrialRequest({ properties: { email: '<EMAIL>' } }) expect(trialRequest.get('applicant').equals(user._id)).toBe(true) url = getURL("/db/user/#{user.id}/signup-with-password") email = '<EMAIL>' json = { email, password: '<PASSWORD>' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) trialRequest = yield TrialRequest.findById(trialRequest.id) expect(trialRequest.get('applicant')).toBeUndefined() done() it 'does NOT disassociate the user from their trial request if the trial request email and signup email DO match', utils.wrap (done) -> user = yield utils.becomeAnonymous() trialRequest = yield utils.makeTrialRequest({ properties: { email: '<EMAIL>' } }) expect(trialRequest.get('applicant').equals(user._id)).toBe(true) url = getURL("/db/user/#{user.id}/signup-with-password") email = '<EMAIL>' json = { email, password: '<PASSWORD>' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) trialRequest = yield TrialRequest.findById(trialRequest.id) expect(trialRequest.get('applicant').equals(user._id)).toBe(true) done() describe 'POST /db/user/:handle/signup-with-facebook', -> facebookID = '12345' facebookEmail = '<EMAIL>' name = 'someusername' validFacebookResponse = new Promise((resolve) -> resolve({ id: facebookID, email: facebookEmail, first_name: '<NAME>', gender: 'male', last_name: '<NAME>', link: 'https://www.facebook.com/app_scoped_user_id/12345/', locale: 'en_US', name: '<NAME>', timezone: -7, updated_time: '2015-12-08T17:10:39+0000', verified: true })) invalidFacebookResponse = new Promise((resolve) -> resolve({ error: { message: 'Invalid OAuth access token.', type: 'OAuthException', code: 190, fbtrace_id: 'EC4dEdeKHBH' } })) beforeEach utils.wrap (done) -> yield utils.clearModels([User]) yield new Promise((resolve) -> setTimeout(resolve, 50)) done() it 'signs up the user with the facebookID and sends welcome emails', utils.wrap (done) -> spyOn(facebook, 'fetchMe').and.returnValue(validFacebookResponse) spyOn(sendwithus.api, 'send') user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-facebook") json = { name, email: facebookEmail, facebookID, facebookAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) updatedUser = yield User.findById(user.id) expect(updatedUser.get('email')).toBe(facebookEmail) expect(updatedUser.get('facebookID')).toBe(facebookID) expect(sendwithus.api.send).toHaveBeenCalled() done() it 'returns 422 if facebook does not recognize the access token', utils.wrap (done) -> spyOn(facebook, 'fetchMe').and.returnValue(invalidFacebookResponse) user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-facebook") json = { email: facebookEmail, facebookID, facebookAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) done() it 'returns 422 if the email or id do not match', utils.wrap (done) -> spyOn(facebook, 'fetchMe').and.returnValue(validFacebookResponse) user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-facebook") json = { name, email: '<EMAIL>', facebookID, facebookAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) json = { name, email: facebookEmail, facebookID: '54321', facebookAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) done() # TODO: Fix this test, res.statusCode is occasionally 200 # it 'returns 409 if there is already a user with the given email', utils.wrap (done) -> # initialUser = yield utils.initUser({email: facebookEmail}) # expect(initialUser.get('emailLower')).toBeDefined() # spyOn(facebook, 'fetchMe').and.returnValue(validFacebookResponse) # user = yield utils.becomeAnonymous() # url = getURL("/db/user/#{user.id}/signup-with-facebook") # json = { name, email: facebookEmail, facebookID, facebookAccessToken: '...' } # [res, body] = yield request.postAsync({url, json}) # expect(res.statusCode).toBe(409) # done() describe 'POST /db/user/:handle/signup-with-gplus', -> gplusID = '12345' gplusEmail = '<EMAIL>' name = 'someusername' validGPlusResponse = new Promise((resolve) -> resolve({ id: gplusID email: gplusEmail, verified_email: true, name: '<NAME>', given_name: '<NAME>', family_name: '<NAME>', link: 'https://plus.google.com/12345', picture: 'https://lh6.googleusercontent.com/...', gender: 'male', locale: 'en' })) invalidGPlusResponse = new Promise((resolve) -> resolve({ "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" } })) beforeEach utils.wrap (done) -> yield utils.clearModels([User]) yield new Promise((resolve) -> setTimeout(resolve, 50)) done() it 'signs up the user with the gplusID and sends welcome emails', utils.wrap (done) -> spyOn(gplus, 'fetchMe').and.returnValue(validGPlusResponse) spyOn(sendwithus.api, 'send') user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-gplus") json = { name, email: gplusEmail, gplusID, gplusAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) updatedUser = yield User.findById(user.id) expect(updatedUser.get('name')).toBe(<NAME>) expect(updatedUser.get('email')).toBe(gplusEmail) expect(updatedUser.get('gplusID')).toBe(gplusID) expect(sendwithus.api.send).toHaveBeenCalled() done() it 'returns 422 if gplus does not recognize the access token', utils.wrap (done) -> spyOn(gplus, 'fetchMe').and.returnValue(invalidGPlusResponse) user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-gplus") json = { name, email: gplusEmail, gplusID, gplusAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) done() it 'returns 422 if the email or id do not match', utils.wrap (done) -> spyOn(gplus, 'fetchMe').and.returnValue(validGPlusResponse) user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-gplus") json = { name, email: 'some-<EMAIL>', gplusID, gplusAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) json = { name, email: gplusEmail, gplusID: '54321', gplusAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) done() # TODO: Fix this test, res.statusCode is occasionally 200 # it 'returns 409 if there is already a user with the given email', utils.wrap (done) -> # yield utils.initUser({name: 'someusername', email: gplusEmail}) # spyOn(gplus, 'fetchMe').and.returnValue(validGPlusResponse) # user = yield utils.becomeAnonymous() # url = getURL("/db/user/#{user.id}/signup-with-gplus") # json = { name: 'differentusername', email: gplusEmail, gplusID, gplusAccessToken: '...' } # [res, body] = yield request.postAsync({url, json}) # expect(res.statusCode).toBe(409) # done() describe 'POST /db/user/:handle/destudent', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom, CourseInstance, Course, Campaign]) done() it 'removes a student user from all classrooms and unsets their role property', utils.wrap (done) -> student1 = yield utils.initUser({role: 'student'}) student2 = yield utils.initUser({role: 'student'}) members = [student1._id, student2._id] classroom = new Classroom({members}) yield classroom.save() courseInstance = new CourseInstance({members}) yield courseInstance.save() admin = yield utils.initAdmin() yield utils.loginUser(admin) url = getURL("/db/user/#{student1.id}/destudent") [res, body] = yield request.postAsync({url, json:true}) student1 = yield User.findById(student1.id) student2 = yield User.findById(student2.id) classroom = yield Classroom.findById(classroom.id) courseInstance = yield CourseInstance.findById(courseInstance.id) expect(student1.get('role')).toBeUndefined() expect(student2.get('role')).toBe('student') expect(classroom.get('members').length).toBe(1) expect(classroom.get('members')[0].toString()).toBe(student2.id) expect(courseInstance.get('members').length).toBe(1) expect(courseInstance.get('members')[0].toString()).toBe(student2.id) done() describe 'POST /db/user/:handle/deteacher', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, TrialRequest]) done() it 'removes a student user from all classrooms and unsets their role property', utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) trialRequest = yield utils.makeTrialRequest(teacher) admin = yield utils.initAdmin() yield utils.loginUser(admin) trialRequest = yield TrialRequest.findById(trialRequest.id) expect(trialRequest).toBeDefined() expect(teacher.get('role')).toBe('teacher') url = getURL("/db/user/#{teacher.id}/deteacher") [res, body] = yield request.postAsync({url, json:true}) trialRequest = yield TrialRequest.findById(trialRequest.id) expect(trialRequest).toBeNull() teacher = yield User.findById(teacher.id) expect(teacher.get('role')).toBeUndefined() done() describe 'POST /db/user/:handle/check-for-new-achievements', -> achievementURL = getURL('/db/achievement') achievementJSON = { collection: 'users' query: {'points': {$gt: 50}} userField: '_id' recalculable: true worth: 75 rewards: { gems: 50 levels: [new mongoose.Types.ObjectId().toString()] } name: 'Dungeon Arena Started' description: 'Started playing Dungeon Arena.' related: 'a' } beforeEach utils.wrap (done) -> yield utils.clearModels [Achievement, EarnedAchievement, LevelSession, User] Achievement.resetAchievements() done() it 'finds new achievements and awards them to the user', utils.wrap (done) -> user = yield utils.initUser({points: 100}) yield utils.loginUser(user) url = utils.getURL("/db/user/#{user.id}/check-for-new-achievement") json = true [res, body] = yield request.postAsync({ url, json }) earned = yield EarnedAchievement.count() expect(earned).toBe(0) admin = yield utils.initAdmin() yield utils.loginUser(admin) [res, body] = yield request.postAsync { uri: achievementURL, json: achievementJSON } achievementUpdated = res.body.updated expect(res.statusCode).toBe(201) user = yield User.findById(user.id) expect(user.get('earned')).toBeUndefined() yield utils.loginUser(user) [res, body] = yield request.postAsync({ url, json }) expect(body.points).toBe(175) earned = yield EarnedAchievement.count() expect(earned).toBe(1) expect(body.lastAchievementChecked).toBe(achievementUpdated) done() it 'updates the user if they already earned the achievement but the rewards changed', utils.wrap (done) -> user = yield utils.initUser({points: 100}) yield utils.loginUser(user) url = utils.getURL("/db/user/#{user.id}/check-for-new-achievement") json = true [res, body] = yield request.postAsync({ url, json }) admin = yield utils.initAdmin() yield utils.loginUser(admin) [res, body] = yield request.postAsync { uri: achievementURL, json: achievementJSON } achievement = yield Achievement.findById(body._id) expect(res.statusCode).toBe(201) user = yield User.findById(user.id) expect(user.get('rewards')).toBeUndefined() yield utils.loginUser(user) [res, body] = yield request.postAsync({ url, json }) expect(res.body.points).toBe(175) expect(res.body.earned.gems).toBe(50) achievement.set({ updated: new Date().toISOString() rewards: { gems: 100 } worth: 200 }) yield achievement.save() [res, body] = yield request.postAsync({ url, json }) expect(res.body.earned.gems).toBe(100) expect(res.body.points).toBe(300) expect(res.statusCode).toBe(200) # special case: no worth, should default to 10 yield achievement.update({ $set: {updated: new Date().toISOString()}, $unset: {worth:''} }) [res, body] = yield request.postAsync({ url, json }) expect(res.body.earned.gems).toBe(100) expect(res.body.points).toBe(110) expect(res.statusCode).toBe(200) done() it 'works for level sessions', utils.wrap (done) -> admin = yield utils.initAdmin() yield utils.loginUser(admin) level = yield utils.makeLevel() achievement = yield utils.makeAchievement({ collection: 'level.sessions' userField: 'creator' query: { 'level.original': level.get('original').toString() 'state': {complete: true} } worth: 100 proportionalTo: 'state.difficulty' }) levelSession = yield utils.makeLevelSession({state: {complete: true, difficulty:2}}, { creator:admin, level }) url = utils.getURL("/db/user/#{admin.id}/check-for-new-achievement") json = true [res, body] = yield request.postAsync({ url, json }) expect(body.points).toBe(200) # check idempotency achievement.set('updated', new Date().toISOString()) yield achievement.save() [res, body] = yield request.postAsync({ url, json }) expect(body.points).toBe(200) admin = yield User.findById(admin.id) done() it 'skips achievements which have not been satisfied', utils.wrap (done) -> admin = yield utils.initAdmin() yield utils.loginUser(admin) level = yield utils.makeLevel() achievement = yield utils.makeAchievement({ collection: 'level.sessions' userField: 'creator' query: { 'level.original': 'does not matter' } worth: 100 }) expect(admin.get('lastAchievementChecked')).toBeUndefined() url = utils.getURL("/db/user/#{admin.id}/check-for-new-achievement") json = true [res, body] = yield request.postAsync({ url, json }) expect(body.points).toBeUndefined() admin = yield User.findById(admin.id) expect(admin.get('lastAchievementChecked')).toBe(achievement.get('updated')) done() it 'skips achievements which are not either for the users collection or the level sessions collection with level.original included', utils.wrap (done) -> admin = yield utils.initAdmin() yield utils.loginUser(admin) achievement = yield utils.makeAchievement({ collection: 'not.supported' userField: 'creator' query: {} worth: 100 }) expect(admin.get('lastAchievementChecked')).toBeUndefined() url = utils.getURL("/db/user/#{admin.id}/check-for-new-achievement") json = true [res, body] = yield request.postAsync({ url, json }) expect(body.points).toBeUndefined() admin = yield User.findById(admin.id) expect(admin.get('lastAchievementChecked')).toBe(achievement.get('updated')) done() describe 'POST /db/user/:userID/request-verify-email', -> mailChimp = require '../../../server/lib/mail-chimp' beforeEach utils.wrap (done) -> spyOn(mailChimp.api, 'put').and.returnValue(Promise.resolve()) @user = yield utils.initUser() verificationCode = @user.verificationCode(new Date().getTime()) @url = utils.getURL("/db/user/#{@user.id}/verify/#{verificationCode}") done() it 'sets emailVerified to true and updates MailChimp', utils.wrap (done) -> [res, body] = yield request.postAsync({ @url, json: true }) expect(res.statusCode).toBe(200) expect(mailChimp.api.put).toHaveBeenCalled() user = yield User.findById(@user.id) expect(user.get('emailVerified')).toBe(true) done()
true
require '../common' utils = require '../utils' urlUser = '/db/user' User = require '../../../server/models/User' Classroom = require '../../../server/models/Classroom' CourseInstance = require '../../../server/models/CourseInstance' Course = require '../../../server/models/Course' Campaign = require '../../../server/models/Campaign' TrialRequest = require '../../../server/models/TrialRequest' Prepaid = require '../../../server/models/Prepaid' request = require '../request' facebook = require '../../../server/lib/facebook' gplus = require '../../../server/lib/gplus' sendwithus = require '../../../server/sendwithus' Promise = require 'bluebird' Achievement = require '../../../server/models/Achievement' EarnedAchievement = require '../../../server/models/EarnedAchievement' LevelSession = require '../../../server/models/LevelSession' mongoose = require 'mongoose' describe 'POST /db/user', -> createAnonNameUser = (name, done)-> request.post getURL('/auth/logout'), -> request.get getURL('/auth/whoami'), -> req = request.post({ url: getURL('/db/user'), json: {name}}, (err, response) -> expect(response.statusCode).toBe(200) request.get { url: getURL('/auth/whoami'), json: true }, (request, response, body) -> expect(body.anonymous).toBeTruthy() expect(body.name).toEqual(name) done() ) it 'preparing test : clears the db first', (done) -> clearModels [User], (err) -> throw err if err done() it 'converts the password into a hash', (done) -> unittest.getNormalJoe (user) -> expect(user).toBeTruthy() expect(user.get('password')).toBeUndefined() expect(user?.get('passwordHash')).not.toBeUndefined() if user?.get('passwordHash')? expect(user.get('passwordHash')[..5] in ['PI:PASSWORD:<PASSWORD>END_PI', 'PI:PASSWORD:<PASSWORD>END_PI']).toBeTruthy() expect(user.get('permissions').length).toBe(0) done() it 'serves the user through /db/user/id', (done) -> unittest.getNormalJoe (user) -> utils.becomeAnonymous().then -> url = getURL(urlUser+'/'+user._id) request.get url, (err, res, body) -> expect(res.statusCode).toBe(200) user = JSON.parse(body) expect(user.name).toBe('PI:NAME:<NAME>END_PI') # Anyone should be served the username. expect(user.email).toBeUndefined() # Shouldn't be available to just anyone. expect(user.passwordHash).toBeUndefined() done() it 'creates admins based on passwords', (done) -> request.post getURL('/auth/logout'), -> unittest.getAdmin (user) -> expect(user).not.toBeUndefined() if user expect(user.get('permissions').length).toBe(1) expect(user.get('permissions')[0]).toBe('admin') done() it 'does not return the full user object for regular users.', (done) -> loginJoe -> unittest.getAdmin (user) -> url = getURL(urlUser+'/'+user._id) request.get url, (err, res, body) -> expect(res.statusCode).toBe(200) user = JSON.parse(body) expect(user.email).toBeUndefined() expect(user.passwordHash).toBeUndefined() done() it 'should allow setting anonymous user name', (done) -> createAnonNameUser('PI:NAME:<NAME>END_PI', done) it 'should allow multiple anonymous users with same name', (done) -> createAnonNameUser('PI:NAME:<NAME>END_PI', done) it 'should allow setting existing user name to anonymous user', (done) -> req = request.post({url: getURL('/db/user'), json: {email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI'}}, (err, response, body) -> expect(response.statusCode).toBe(200) request.get getURL('/auth/whoami'), (request, response, body) -> res = JSON.parse(response.body) expect(res.anonymous).toBeFalsy() createAnonNameUser 'PI:NAME:<NAME>END_PI', done ) describe 'PUT /db/user', -> it 'logs in as normal joe', (done) -> request.post getURL('/auth/logout'), loginJoe -> done() it 'denies requests without any data', (done) -> request.put getURL(urlUser), (err, res) -> expect(res.statusCode).toBe(422) expect(res.body).toBe('No input.') done() it 'denies requests to edit someone who is not joe', (done) -> unittest.getAdmin (admin) -> request.put {url: getURL(urlUser), json: {_id: admin.id}}, (err, res) -> expect(res.statusCode).toBe(403) done() it 'denies invalid data', (done) -> unittest.getNormalJoe (joe) -> json = { _id: joe.id email: 'farghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlar ghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghl' } request.put { url: getURL(urlUser), json }, (err, res) -> expect(res.statusCode).toBe(422) expect(res.body[0].message.indexOf('too long')).toBeGreaterThan(-1) done() it 'does not allow normals to edit their permissions', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: { permissions: ['admin'] }} expect(_.contains(body.permissions, 'admin')).toBe(false) done() it 'logs in as admin', (done) -> loginAdmin -> done() it 'denies non-existent ids', (done) -> json = { _id: '513108d4cb8b610000000004', email: 'PI:EMAIL:<EMAIL>END_PI' } request.put {url: getURL(urlUser), json}, (err, res) -> expect(res.statusCode).toBe(404) done() it 'denies if the email being changed is already taken', (done) -> unittest.getNormalJoe (joe) -> unittest.getAdmin (admin) -> json = { _id: admin.id, email: joe.get('email').toUpperCase() } request.put { url: getURL(urlUser), json }, (err, res) -> expect(res.statusCode).toBe(409) expect(res.body.message.indexOf('already used')).toBeGreaterThan(-1) done() it 'does not care if you include your existing name', (done) -> unittest.getNormalJoe (joe) -> json = { _id: joe._id, name: 'PI:NAME:<NAME>END_PI' } request.put { url: getURL(urlUser+'/'+joe._id), json }, (err, res) -> expect(res.statusCode).toBe(200) done() it 'accepts name and email changes', (done) -> unittest.getNormalJoe (joe) -> json = { _id: joe.id email: 'PI:EMAIL:<EMAIL>END_PI' name: 'PI:NAME:<NAME>END_PI' } request.put { url: getURL(urlUser), json }, (err, res) -> expect(res.statusCode).toBe(200) unittest.getUser('Wilhelm', 'PI:EMAIL:<EMAIL>END_PI', 'null', (joe) -> expect(joe.get('name')).toBe('PI:NAME:<NAME>END_PI') expect(joe.get('emailLower')).toBe('PI:EMAIL:<EMAIL>END_PI') expect(joe.get('email')).toBe('PI:EMAIL:<EMAIL>END_PI') done()) it 'should not allow two users with the same name slug', (done) -> loginSam (sam) -> samsName = sam.get 'name' sam.set 'name', 'admin' request.put {uri:getURL(urlUser + '/' + sam.id), json: sam.toObject()}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe 409 # Restore Sam sam.set 'name', samsName done() it 'should be able to unset a slug by setting an empty name', (done) -> loginSam (sam) -> samsName = sam.get 'name' sam.set 'name', '' request.put {uri:getURL(urlUser + '/' + sam.id), json: sam.toObject()}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe 200 newSam = response.body # Restore Sam sam.set 'name', samsName request.put {uri:getURL(urlUser + '/' + sam.id), json: sam.toObject()}, (err, response) -> expect(err).toBeNull() done() describe 'when role is changed to teacher or other school administrator', -> it 'removes the user from all classrooms they are in', utils.wrap (done) -> user = yield utils.initUser() classroom = new Classroom({members: [user._id]}) yield classroom.save() expect(classroom.get('members').length).toBe(1) yield utils.loginUser(user) [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: { role: 'teacher' }} yield new Promise (resolve) -> setTimeout(resolve, 10) classroom = yield Classroom.findById(classroom.id) expect(classroom.get('members').length).toBe(0) done() it 'changes the role regardless of emailVerified', utils.wrap (done) -> user = yield utils.initUser() user.set('emailVerified', true) yield user.save() yield utils.loginUser(user) attrs = user.toObject() attrs.role = 'teacher' [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: attrs } user = yield User.findById(user.id) expect(user.get('role')).toBe('teacher') done() it 'ignores attempts to change away from a teacher role', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) url = getURL('/db/user/'+user.id) [res, body] = yield request.putAsync { uri: url, json: { role: 'teacher' }} expect(body.role).toBe('teacher') [res, body] = yield request.putAsync { uri: url, json: { role: 'advisor' }} expect(body.role).toBe('advisor') [res, body] = yield request.putAsync { uri: url, json: { role: 'student' }} expect(body.role).toBe('advisor') done() it 'returns 422 if both email and name would be unset for a registered user', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: { email: '', name: '' }} expect(body.code).toBe(422) expect(body.message).toEqual('User needs a username or email address') done() it 'allows unsetting email, even when there\'s a user with email and emailLower set to empty string', utils.wrap (done) -> invalidUser = yield utils.initUser() yield invalidUser.update({$set: {email: '', emailLower: ''}}) user = yield utils.initUser() yield utils.loginUser(user) [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: { email: '' }} expect(res.statusCode).toBe(200) expect(res.body.email).toBeUndefined() done() it 'allows unsetting name, even when there\'s a user with name and nameLower set to empty string', utils.wrap (done) -> invalidUser = yield utils.initUser() yield invalidUser.update({$set: {name: '', nameLower: ''}}) user = yield utils.initUser() yield utils.loginUser(user) [res, body] = yield request.putAsync { uri: getURL('/db/user/'+user.id), json: { name: '' }} expect(res.statusCode).toBe(200) expect(res.body.name).toBeUndefined() done() describe 'PUT /db/user/-/become-student', -> beforeEach utils.wrap (done) -> @url = getURL('/db/user/-/become-student') @user = yield utils.initUser() yield utils.loginUser(@user) done() describe 'when a user is in a classroom', -> beforeEach utils.wrap (done) -> classroom = new Classroom({ members: [@user._id] }) yield classroom.save() done() it 'keeps the user in their classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'when a teacher', -> beforeEach utils.wrap (done) -> @user.set('role', 'student') yield @user.save() done() it 'keeps the user in their classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'when a student', -> beforeEach utils.wrap (done) -> @user.set('role', 'student') yield @user.save() done() it 'keeps the user in their classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'when a user owns a classroom', -> beforeEach utils.wrap (done) -> classroom = new Classroom({ ownerID: @user._id }) yield classroom.save() done() it 'removes the classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) done() describe 'when a student', -> beforeEach utils.wrap (done) -> @user.set('role', 'student') yield @user.save() done() it 'removes the classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) done() describe 'when a teacher', -> beforeEach utils.wrap (done) -> @user.set('role', 'teacher') yield @user.save() done() it 'removes the classroom and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) done() describe 'when a user in a classroom and owns a classroom', -> beforeEach utils.wrap (done) -> classroom = new Classroom({ members: [@user._id] }) yield classroom.save() classroom = new Classroom({ ownerID: @user._id }) yield classroom.save() done() it 'removes owned classrooms, keeps in classrooms, and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'when a student in a classroom and owns a classroom', -> beforeEach utils.wrap (done) -> @user.set('role', 'student') yield @user.save() classroom = new Classroom({ members: [@user._id] }) yield classroom.save() classroom = new Classroom({ ownerID: @user._id }) yield classroom.save() done() it 'removes owned classrooms, keeps in classrooms, and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'when a teacher in a classroom and owns a classroom', -> beforeEach utils.wrap (done) -> @user.set('role', 'teacher') yield @user.save() classroom = new Classroom({ members: [@user._id] }) yield classroom.save() classroom = new Classroom({ ownerID: @user._id }) yield classroom.save() done() it 'removes owned classrooms, keeps in classrooms, and sets their role to student', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('student') user = yield User.findById @user._id expect(user.get('role')).toEqual('student') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(0) classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(1) done() describe 'PUT /db/user/-/remain-teacher', -> describe 'when a teacher in classroom and owns a classroom', -> beforeEach utils.wrap (done) -> @url = getURL('/db/user/-/remain-teacher') @user = yield utils.initUser() yield utils.loginUser(@user) @user.set('role', 'teacher') yield @user.save() classroom = new Classroom({ members: [@user._id] }) yield classroom.save() classroom = new Classroom({ ownerID: @user._id }) yield classroom.save() done() it 'removes from classrooms', utils.wrap (done) -> [res, body] = yield request.putAsync { uri: @url} expect(res.statusCode).toEqual(200) expect(JSON.parse(body).role).toEqual('teacher') user = yield User.findById @user._id expect(user.get('role')).toEqual('teacher') classrooms = yield Classroom.find ownerID: @user._id expect(classrooms.length).toEqual(1) classrooms = yield Classroom.find members: @user._id expect(classrooms.length).toEqual(0) done() describe 'GET /db/user', -> it 'logs in as admin', (done) -> json = { username: 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI' } request.post { url: getURL('/auth/login'), json }, (error, response) -> expect(response.statusCode).toBe(200) done() it 'get schema', (done) -> request.get {uri: getURL(urlUser+'/schema')}, (err, res, body) -> expect(res.statusCode).toBe(200) body = JSON.parse(body) expect(body.type).toBeDefined() done() it 'is able to do a semi-sweet query', (done) -> options = { url: getURL(urlUser) + "?conditions[limit]=20&conditions[sort]=-dateCreated" } req = request.get(options, (error, response) -> expect(response.statusCode).toBe(200) res = JSON.parse(response.body) expect(res.length).toBeGreaterThan(0) done() ) it 'rejects bad conditions', (done) -> options = { url: getURL(urlUser) + "?conditions[lime]=20&conditions[sort]=-dateCreated" } req = request.get(options, (error, response) -> expect(response.statusCode).toBe(422) done() ) it 'can fetch myself by id completely', (done) -> loginSam (sam) -> request.get {url: getURL(urlUser + '/' + sam.id)}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe(200) done() it 'can fetch myself by slug completely', (done) -> loginSam (sam) -> request.get {url: getURL(urlUser + '/sam')}, (err, response) -> expect(err).toBeNull() expect(response.statusCode).toBe(200) guy = JSON.parse response.body expect(guy._id).toBe sam.get('_id').toHexString() expect(guy.name).toBe sam.get 'name' done() # TODO Ruben should be able to fetch other users but probably with restricted data access # Add to the test case above an extra data check # xit 'can fetch another user with restricted fields' describe 'GET /db/user/:handle', -> it 'populates coursePrepaid from coursePrepaidID', utils.wrap (done) -> course = yield utils.makeCourse() user = yield utils.initUser({coursePrepaidID: course.id}) [res, body] = yield request.getAsync({url: getURL("/db/user/#{user.id}"), json: true}) expect(res.statusCode).toBe(200) expect(res.body.coursePrepaid._id).toBe(course.id) expect(res.body.coursePrepaid.startDate).toBe(Prepaid.DEFAULT_START_DATE) done() describe 'DELETE /db/user', -> it 'can delete a user', utils.wrap (done) -> user = yield utils.initUser() yield utils.loginUser(user) beforeDeleted = new Date() [res, body] = yield request.delAsync {uri: "#{getURL(urlUser)}/#{user.id}"} user = yield User.findById user.id expect(user.get('deleted')).toBe(true) expect(user.get('dateDeleted')).toBeGreaterThan(beforeDeleted) expect(user.get('dateDeleted')).toBeLessThan(new Date()) for key, value of user.toObject() continue if key in ['_id', 'deleted', 'dateDeleted'] expect(_.isEmpty(value)).toEqual(true) done() it 'moves user to classroom.deletedMembers', utils.wrap (done) -> user = yield utils.initUser() user2 = yield utils.initUser() yield utils.loginUser(user) classroom = new Classroom({ members: [user._id, user2._id] }) yield classroom.save() [res, body] = yield request.delAsync {uri: "#{getURL(urlUser)}/#{user.id}"} classroom = yield Classroom.findById(classroom.id) expect(classroom.get('members').length).toBe(1) expect(classroom.get('deletedMembers').length).toBe(1) expect(classroom.get('members')[0].toString()).toEqual(user2.id) expect(classroom.get('deletedMembers')[0].toString()).toEqual(user.id) done() it 'returns 401 if no cookie session', utils.wrap (done) -> yield utils.logout() [res, body] = yield request.delAsync {uri: "#{getURL(urlUser)}/1234"} expect(res.statusCode).toBe(401) done() describe 'Statistics', -> LevelSession = require '../../../server/models/LevelSession' Article = require '../../../server/models/Article' Level = require '../../../server/models/Level' LevelSystem = require '../../../server/models/LevelSystem' LevelComponent = require '../../../server/models/LevelComponent' ThangType = require '../../../server/models/ThangType' User = require '../../../server/models/User' UserHandler = require '../../../server/handlers/user_handler' it 'keeps track of games completed', (done) -> session = new LevelSession name: 'PI:NAME:<NAME>END_PI' permissions: simplePermissions state: complete: true unittest.getNormalJoe (joe) -> expect(joe.get 'stats.gamesCompleted').toBeUndefined() session.set 'creator', joe.get 'id' session.save (err) -> expect(err).toBeNull() f = -> User.findById joe.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get 'id').toBe joe.get 'id' expect(guy.get 'stats.gamesCompleted').toBe 1 done() setTimeout f, 100 it 'recalculates games completed', (done) -> unittest.getNormalJoe (joe) -> loginAdmin -> User.findByIdAndUpdate joe.get('id'), {$unset:'stats.gamesCompleted': ''}, {new: true}, (err, guy) -> expect(err).toBeNull() expect(guy.get 'stats.gamesCompleted').toBeUndefined() UserHandler.statRecalculators.gamesCompleted -> User.findById joe.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get 'stats.gamesCompleted').toBe 1 done() it 'keeps track of article edits', (done) -> article = name: 'PI:NAME:<NAME>END_PI' body: 'I don\'t have much to say I\'m afraid' url = getURL('/db/article') loginAdmin (carl) -> expect(carl.get User.statsMapping.edits.article).toBeUndefined() article.creator = carl.get 'id' # Create major version 0.0 request.post {uri:url, json: article}, (err, res, body) -> expect(err).toBeNull() expect(res.statusCode).toBe 201 article = body User.findById carl.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.article).toBe 1 # Create minor version 0.1 newVersionURL = "#{url}/#{article._id}/new-version" request.post {uri:newVersionURL, json: article}, (err, res, body) -> expect(err).toBeNull() User.findById carl.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.article).toBe 2 done() it 'recalculates article edits', (done) -> loginAdmin (carl) -> User.findByIdAndUpdate carl.get('id'), {$unset:'stats.articleEdits': ''}, {new: true}, (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.article).toBeUndefined() UserHandler.statRecalculators.articleEdits -> User.findById carl.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.article).toBe 2 done() it 'keeps track of level edits', (done) -> level = new Level name: "King's Peak 3" description: 'Climb a mountain.' permissions: simplePermissions scripts: [] thangs: [] loginAdmin (carl) -> expect(carl.get User.statsMapping.edits.level).toBeUndefined() level.creator = carl.get 'id' level.save (err) -> expect(err).toBeNull() User.findById carl.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get 'id').toBe carl.get 'id' expect(guy.get User.statsMapping.edits.level).toBe 1 done() it 'recalculates level edits', (done) -> unittest.getAdmin (jose) -> User.findByIdAndUpdate jose.get('id'), {$unset:'stats.levelEdits':''}, {new: true}, (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.level).toBeUndefined() UserHandler.statRecalculators.levelEdits -> User.findById jose.get('id'), (err, guy) -> expect(err).toBeNull() expect(guy.get User.statsMapping.edits.level).toBe 1 done() it 'cleans up', (done) -> clearModels [LevelSession, Article, Level, LevelSystem, LevelComponent, ThangType], (err) -> expect(err).toBeNull() done() describe 'POST /db/user/:handle/signup-with-password', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User]) yield new Promise((resolve) -> setTimeout(resolve, 10)) done() it 'signs up the user with the password and sends welcome emails', utils.wrap (done) -> spyOn(sendwithus.api, 'send') user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") email = 'PI:EMAIL:<EMAIL>END_PI' name = 'someusername' json = { name, email, password: 'PI:PASSWORD:<PASSWORD>END_PI' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) updatedUser = yield User.findById(user.id) expect(updatedUser.get('email')).toBe(email) expect(updatedUser.get('passwordHash')).toBeDefined() expect(sendwithus.api.send).toHaveBeenCalled() done() it 'signs up the user with just a name and password', utils.wrap (done) -> user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") name = 'someusername' json = { name, password: 'PI:PASSWORD:<PASSWORD>END_PI' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) updatedUser = yield User.findById(user.id) expect(updatedUser.get('name')).toBe(name) expect(updatedUser.get('nameLower')).toBe(name.toLowerCase()) expect(updatedUser.get('slug')).toBe(name.toLowerCase()) expect(updatedUser.get('passwordHash')).toBeDefined() expect(updatedUser.get('email')).toBeUndefined() expect(updatedUser.get('emailLower')).toBeUndefined() done() it 'signs up the user with a username, email, and password', utils.wrap (done) -> user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") name = 'someusername' email = 'PI:EMAIL:<EMAIL>END_PI' json = { name, email, password: 'PI:PASSWORD:<PASSWORD>END_PI' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) updatedUser = yield User.findById(user.id) expect(updatedUser.get('name')).toBe(name) expect(updatedUser.get('nameLower')).toBe(name.toLowerCase()) expect(updatedUser.get('slug')).toBe(name.toLowerCase()) expect(updatedUser.get('email')).toBe(email) expect(updatedUser.get('emailLower')).toBe(email.toLowerCase()) expect(updatedUser.get('passwordHash')).toBeDefined() done() it 'returns 422 if neither username or email were provided', utils.wrap (done) -> user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") json = { password: 'PI:PASSWORD:<PASSWORD>END_PI' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) updatedUser = yield User.findById(user.id) expect(updatedUser.get('anonymous')).toBe(true) expect(updatedUser.get('passwordHash')).toBeUndefined() done() it 'returns 409 if there is already a user with the given email', utils.wrap (done) -> email = 'PI:EMAIL:<EMAIL>END_PI' initialUser = yield utils.initUser({email}) expect(initialUser.get('emailLower')).toBeDefined() user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") json = { email, password: 'PI:PASSWORD:<PASSWORD>END_PI' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(409) done() it 'returns 409 if there is already a user with the given username', utils.wrap (done) -> name = 'someusername' initialUser = yield utils.initUser({name}) expect(initialUser.get('nameLower')).toBeDefined() user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-password") json = { name, password: 'PI:PASSWORD:<PASSWORD>END_PI' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(409) done() it 'disassociates the user from their trial request if the trial request email and signup email do not match', utils.wrap (done) -> user = yield utils.becomeAnonymous() trialRequest = yield utils.makeTrialRequest({ properties: { email: 'PI:EMAIL:<EMAIL>END_PI' } }) expect(trialRequest.get('applicant').equals(user._id)).toBe(true) url = getURL("/db/user/#{user.id}/signup-with-password") email = 'PI:EMAIL:<EMAIL>END_PI' json = { email, password: 'PI:PASSWORD:<PASSWORD>END_PI' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) trialRequest = yield TrialRequest.findById(trialRequest.id) expect(trialRequest.get('applicant')).toBeUndefined() done() it 'does NOT disassociate the user from their trial request if the trial request email and signup email DO match', utils.wrap (done) -> user = yield utils.becomeAnonymous() trialRequest = yield utils.makeTrialRequest({ properties: { email: 'PI:EMAIL:<EMAIL>END_PI' } }) expect(trialRequest.get('applicant').equals(user._id)).toBe(true) url = getURL("/db/user/#{user.id}/signup-with-password") email = 'PI:EMAIL:<EMAIL>END_PI' json = { email, password: 'PI:PASSWORD:<PASSWORD>END_PI' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) trialRequest = yield TrialRequest.findById(trialRequest.id) expect(trialRequest.get('applicant').equals(user._id)).toBe(true) done() describe 'POST /db/user/:handle/signup-with-facebook', -> facebookID = '12345' facebookEmail = 'PI:EMAIL:<EMAIL>END_PI' name = 'someusername' validFacebookResponse = new Promise((resolve) -> resolve({ id: facebookID, email: facebookEmail, first_name: 'PI:NAME:<NAME>END_PI', gender: 'male', last_name: 'PI:NAME:<NAME>END_PI', link: 'https://www.facebook.com/app_scoped_user_id/12345/', locale: 'en_US', name: 'PI:NAME:<NAME>END_PI', timezone: -7, updated_time: '2015-12-08T17:10:39+0000', verified: true })) invalidFacebookResponse = new Promise((resolve) -> resolve({ error: { message: 'Invalid OAuth access token.', type: 'OAuthException', code: 190, fbtrace_id: 'EC4dEdeKHBH' } })) beforeEach utils.wrap (done) -> yield utils.clearModels([User]) yield new Promise((resolve) -> setTimeout(resolve, 50)) done() it 'signs up the user with the facebookID and sends welcome emails', utils.wrap (done) -> spyOn(facebook, 'fetchMe').and.returnValue(validFacebookResponse) spyOn(sendwithus.api, 'send') user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-facebook") json = { name, email: facebookEmail, facebookID, facebookAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) updatedUser = yield User.findById(user.id) expect(updatedUser.get('email')).toBe(facebookEmail) expect(updatedUser.get('facebookID')).toBe(facebookID) expect(sendwithus.api.send).toHaveBeenCalled() done() it 'returns 422 if facebook does not recognize the access token', utils.wrap (done) -> spyOn(facebook, 'fetchMe').and.returnValue(invalidFacebookResponse) user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-facebook") json = { email: facebookEmail, facebookID, facebookAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) done() it 'returns 422 if the email or id do not match', utils.wrap (done) -> spyOn(facebook, 'fetchMe').and.returnValue(validFacebookResponse) user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-facebook") json = { name, email: 'PI:EMAIL:<EMAIL>END_PI', facebookID, facebookAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) json = { name, email: facebookEmail, facebookID: '54321', facebookAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) done() # TODO: Fix this test, res.statusCode is occasionally 200 # it 'returns 409 if there is already a user with the given email', utils.wrap (done) -> # initialUser = yield utils.initUser({email: facebookEmail}) # expect(initialUser.get('emailLower')).toBeDefined() # spyOn(facebook, 'fetchMe').and.returnValue(validFacebookResponse) # user = yield utils.becomeAnonymous() # url = getURL("/db/user/#{user.id}/signup-with-facebook") # json = { name, email: facebookEmail, facebookID, facebookAccessToken: '...' } # [res, body] = yield request.postAsync({url, json}) # expect(res.statusCode).toBe(409) # done() describe 'POST /db/user/:handle/signup-with-gplus', -> gplusID = '12345' gplusEmail = 'PI:EMAIL:<EMAIL>END_PI' name = 'someusername' validGPlusResponse = new Promise((resolve) -> resolve({ id: gplusID email: gplusEmail, verified_email: true, name: 'PI:NAME:<NAME>END_PI', given_name: 'PI:NAME:<NAME>END_PI', family_name: 'PI:NAME:<NAME>END_PI', link: 'https://plus.google.com/12345', picture: 'https://lh6.googleusercontent.com/...', gender: 'male', locale: 'en' })) invalidGPlusResponse = new Promise((resolve) -> resolve({ "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" } })) beforeEach utils.wrap (done) -> yield utils.clearModels([User]) yield new Promise((resolve) -> setTimeout(resolve, 50)) done() it 'signs up the user with the gplusID and sends welcome emails', utils.wrap (done) -> spyOn(gplus, 'fetchMe').and.returnValue(validGPlusResponse) spyOn(sendwithus.api, 'send') user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-gplus") json = { name, email: gplusEmail, gplusID, gplusAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(200) updatedUser = yield User.findById(user.id) expect(updatedUser.get('name')).toBe(PI:NAME:<NAME>END_PI) expect(updatedUser.get('email')).toBe(gplusEmail) expect(updatedUser.get('gplusID')).toBe(gplusID) expect(sendwithus.api.send).toHaveBeenCalled() done() it 'returns 422 if gplus does not recognize the access token', utils.wrap (done) -> spyOn(gplus, 'fetchMe').and.returnValue(invalidGPlusResponse) user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-gplus") json = { name, email: gplusEmail, gplusID, gplusAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) done() it 'returns 422 if the email or id do not match', utils.wrap (done) -> spyOn(gplus, 'fetchMe').and.returnValue(validGPlusResponse) user = yield utils.becomeAnonymous() url = getURL("/db/user/#{user.id}/signup-with-gplus") json = { name, email: 'some-PI:EMAIL:<EMAIL>END_PI', gplusID, gplusAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) json = { name, email: gplusEmail, gplusID: '54321', gplusAccessToken: '...' } [res, body] = yield request.postAsync({url, json}) expect(res.statusCode).toBe(422) done() # TODO: Fix this test, res.statusCode is occasionally 200 # it 'returns 409 if there is already a user with the given email', utils.wrap (done) -> # yield utils.initUser({name: 'someusername', email: gplusEmail}) # spyOn(gplus, 'fetchMe').and.returnValue(validGPlusResponse) # user = yield utils.becomeAnonymous() # url = getURL("/db/user/#{user.id}/signup-with-gplus") # json = { name: 'differentusername', email: gplusEmail, gplusID, gplusAccessToken: '...' } # [res, body] = yield request.postAsync({url, json}) # expect(res.statusCode).toBe(409) # done() describe 'POST /db/user/:handle/destudent', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom, CourseInstance, Course, Campaign]) done() it 'removes a student user from all classrooms and unsets their role property', utils.wrap (done) -> student1 = yield utils.initUser({role: 'student'}) student2 = yield utils.initUser({role: 'student'}) members = [student1._id, student2._id] classroom = new Classroom({members}) yield classroom.save() courseInstance = new CourseInstance({members}) yield courseInstance.save() admin = yield utils.initAdmin() yield utils.loginUser(admin) url = getURL("/db/user/#{student1.id}/destudent") [res, body] = yield request.postAsync({url, json:true}) student1 = yield User.findById(student1.id) student2 = yield User.findById(student2.id) classroom = yield Classroom.findById(classroom.id) courseInstance = yield CourseInstance.findById(courseInstance.id) expect(student1.get('role')).toBeUndefined() expect(student2.get('role')).toBe('student') expect(classroom.get('members').length).toBe(1) expect(classroom.get('members')[0].toString()).toBe(student2.id) expect(courseInstance.get('members').length).toBe(1) expect(courseInstance.get('members')[0].toString()).toBe(student2.id) done() describe 'POST /db/user/:handle/deteacher', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, TrialRequest]) done() it 'removes a student user from all classrooms and unsets their role property', utils.wrap (done) -> teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) trialRequest = yield utils.makeTrialRequest(teacher) admin = yield utils.initAdmin() yield utils.loginUser(admin) trialRequest = yield TrialRequest.findById(trialRequest.id) expect(trialRequest).toBeDefined() expect(teacher.get('role')).toBe('teacher') url = getURL("/db/user/#{teacher.id}/deteacher") [res, body] = yield request.postAsync({url, json:true}) trialRequest = yield TrialRequest.findById(trialRequest.id) expect(trialRequest).toBeNull() teacher = yield User.findById(teacher.id) expect(teacher.get('role')).toBeUndefined() done() describe 'POST /db/user/:handle/check-for-new-achievements', -> achievementURL = getURL('/db/achievement') achievementJSON = { collection: 'users' query: {'points': {$gt: 50}} userField: '_id' recalculable: true worth: 75 rewards: { gems: 50 levels: [new mongoose.Types.ObjectId().toString()] } name: 'Dungeon Arena Started' description: 'Started playing Dungeon Arena.' related: 'a' } beforeEach utils.wrap (done) -> yield utils.clearModels [Achievement, EarnedAchievement, LevelSession, User] Achievement.resetAchievements() done() it 'finds new achievements and awards them to the user', utils.wrap (done) -> user = yield utils.initUser({points: 100}) yield utils.loginUser(user) url = utils.getURL("/db/user/#{user.id}/check-for-new-achievement") json = true [res, body] = yield request.postAsync({ url, json }) earned = yield EarnedAchievement.count() expect(earned).toBe(0) admin = yield utils.initAdmin() yield utils.loginUser(admin) [res, body] = yield request.postAsync { uri: achievementURL, json: achievementJSON } achievementUpdated = res.body.updated expect(res.statusCode).toBe(201) user = yield User.findById(user.id) expect(user.get('earned')).toBeUndefined() yield utils.loginUser(user) [res, body] = yield request.postAsync({ url, json }) expect(body.points).toBe(175) earned = yield EarnedAchievement.count() expect(earned).toBe(1) expect(body.lastAchievementChecked).toBe(achievementUpdated) done() it 'updates the user if they already earned the achievement but the rewards changed', utils.wrap (done) -> user = yield utils.initUser({points: 100}) yield utils.loginUser(user) url = utils.getURL("/db/user/#{user.id}/check-for-new-achievement") json = true [res, body] = yield request.postAsync({ url, json }) admin = yield utils.initAdmin() yield utils.loginUser(admin) [res, body] = yield request.postAsync { uri: achievementURL, json: achievementJSON } achievement = yield Achievement.findById(body._id) expect(res.statusCode).toBe(201) user = yield User.findById(user.id) expect(user.get('rewards')).toBeUndefined() yield utils.loginUser(user) [res, body] = yield request.postAsync({ url, json }) expect(res.body.points).toBe(175) expect(res.body.earned.gems).toBe(50) achievement.set({ updated: new Date().toISOString() rewards: { gems: 100 } worth: 200 }) yield achievement.save() [res, body] = yield request.postAsync({ url, json }) expect(res.body.earned.gems).toBe(100) expect(res.body.points).toBe(300) expect(res.statusCode).toBe(200) # special case: no worth, should default to 10 yield achievement.update({ $set: {updated: new Date().toISOString()}, $unset: {worth:''} }) [res, body] = yield request.postAsync({ url, json }) expect(res.body.earned.gems).toBe(100) expect(res.body.points).toBe(110) expect(res.statusCode).toBe(200) done() it 'works for level sessions', utils.wrap (done) -> admin = yield utils.initAdmin() yield utils.loginUser(admin) level = yield utils.makeLevel() achievement = yield utils.makeAchievement({ collection: 'level.sessions' userField: 'creator' query: { 'level.original': level.get('original').toString() 'state': {complete: true} } worth: 100 proportionalTo: 'state.difficulty' }) levelSession = yield utils.makeLevelSession({state: {complete: true, difficulty:2}}, { creator:admin, level }) url = utils.getURL("/db/user/#{admin.id}/check-for-new-achievement") json = true [res, body] = yield request.postAsync({ url, json }) expect(body.points).toBe(200) # check idempotency achievement.set('updated', new Date().toISOString()) yield achievement.save() [res, body] = yield request.postAsync({ url, json }) expect(body.points).toBe(200) admin = yield User.findById(admin.id) done() it 'skips achievements which have not been satisfied', utils.wrap (done) -> admin = yield utils.initAdmin() yield utils.loginUser(admin) level = yield utils.makeLevel() achievement = yield utils.makeAchievement({ collection: 'level.sessions' userField: 'creator' query: { 'level.original': 'does not matter' } worth: 100 }) expect(admin.get('lastAchievementChecked')).toBeUndefined() url = utils.getURL("/db/user/#{admin.id}/check-for-new-achievement") json = true [res, body] = yield request.postAsync({ url, json }) expect(body.points).toBeUndefined() admin = yield User.findById(admin.id) expect(admin.get('lastAchievementChecked')).toBe(achievement.get('updated')) done() it 'skips achievements which are not either for the users collection or the level sessions collection with level.original included', utils.wrap (done) -> admin = yield utils.initAdmin() yield utils.loginUser(admin) achievement = yield utils.makeAchievement({ collection: 'not.supported' userField: 'creator' query: {} worth: 100 }) expect(admin.get('lastAchievementChecked')).toBeUndefined() url = utils.getURL("/db/user/#{admin.id}/check-for-new-achievement") json = true [res, body] = yield request.postAsync({ url, json }) expect(body.points).toBeUndefined() admin = yield User.findById(admin.id) expect(admin.get('lastAchievementChecked')).toBe(achievement.get('updated')) done() describe 'POST /db/user/:userID/request-verify-email', -> mailChimp = require '../../../server/lib/mail-chimp' beforeEach utils.wrap (done) -> spyOn(mailChimp.api, 'put').and.returnValue(Promise.resolve()) @user = yield utils.initUser() verificationCode = @user.verificationCode(new Date().getTime()) @url = utils.getURL("/db/user/#{@user.id}/verify/#{verificationCode}") done() it 'sets emailVerified to true and updates MailChimp', utils.wrap (done) -> [res, body] = yield request.postAsync({ @url, json: true }) expect(res.statusCode).toBe(200) expect(mailChimp.api.put).toHaveBeenCalled() user = yield User.findById(@user.id) expect(user.get('emailVerified')).toBe(true) done()
[ { "context": "nd details are available at:\n# https://github.com/rcbops/opencenter or upon written request.\n#\n# You may o", "end": 656, "score": 0.9096388816833496, "start": 650, "tag": "USERNAME", "value": "rcbops" }, { "context": "r/facts/\",\n JSON.stringify\n key: \"parent_id\"\n value: parent\n node_id: optio", "end": 10256, "score": 0.8734920620918274, "start": 10247, "tag": "KEY", "value": "parent_id" } ]
source/coffee/index.coffee
rcbops/opencenter-dashboard
0
# OpenCenter™ is Copyright 2013 by Rackspace US, Inc. # ############################################################################### # # OpenCenter is licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. This version # of OpenCenter includes Rackspace trademarks and logos, and in accordance with # Section 6 of the License, the provision of commercial support services in # conjunction with a version of OpenCenter which includes Rackspace trademarks # and logos is prohibited. OpenCenter source code and details are available at: # https://github.com/rcbops/opencenter or upon written request. # # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 and a copy, including this notice, # is available in the LICENSE file accompanying this software. # # 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. # # ############################################################################### # Grab namespace dashboard = exports?.dashboard ? @dashboard $ -> IndexModel = -> # TODO: Map from data source @siteNav = ko.observableArray [ name: "OpenCenter" template: "indexTemplate" ] # Track this for UI caching @siteLocked = ko.observable false # Temp storage for node mapping @tmpItems = ko.observableArray() @tmpCache = ko.observableArray() # Computed wrapper for coalescing changes @wsItems = ko.computed => if @siteLocked() @tmpCache() else # Otherwise fill cache and return @tmpCache @tmpItems() @tmpItems() # Execution plans @wsPlans = ko.observableArray() # Flat node list, keyed by id @keyItems = {} # Current task list @wsTasks = ko.observableArray() # Flat task list, keyed by id @keyTasks = {} @getTaskCounts = ko.computed => counts = {} for task in @wsTasks() status = task.dash.statusClass() counts[status] ?= 0 counts[status] += 1 for k,v of counts statusClass: k count: v @wsTaskTitle = ko.observable("Select a task to view its log") @getTaskTitle = ko.computed => @wsTaskTitle() @wsTaskLog = ko.observable("...") @getTaskLog = ko.computed => @wsTaskLog() @selectTask = (data, event) => $node = $(event.target).closest(".task") $node.siblings().removeClass("active") $node.addClass("active") for k,v of @keyTasks @keyTasks[k].dash["active"] = false id = $node.attr("data-id") dash = @keyTasks[id].dash dash["active"] = true @wsTaskTitle dash.label @wsTaskLog "Retrieving log..." # Kill any pending watch requests dashboard.killRequests /logs\?watch/i # Log streaming dashboard.getData "/octr/tasks/#{id}/logs?watch", (data) => if data?.request? dashboard.killRequests /logs\//i # Kill any existing log streams url = "/octr/tasks/#{id}/logs/#{data.request}" xhr = new XMLHttpRequest() xhr.open "GET", url xhr.setRequestHeader('Authorization', dashboard.authHeader.Authorization) xhr.onloadstart = -> dashboard.pendingRequests[url] = xhr # Store xhr.onprogress = => @wsTaskLog xhr.responseText # Update log observable $contents = $("#logPane .pane-contents") $contents.scrollTop $contents.prop("scrollHeight") # Scroll to bottom xhr.onloadend = -> delete dashboard.pendingRequests[url] # Clean up xhr.send() # Do it! , -> true # Retry if fails # Update on request success/failure @siteEnabled = ko.computed -> unless dashboard.siteEnabled() dashboard.showModal "#indexNoConnectionModal" else dashboard.hideModal "#indexNoConnectionModal" # Get config and grab initial set of nodes dashboard.getData "/api/config", (data) => # Store config @config = data # Debounce node changes (x msec settling period) @wsItems.extend throttle: @config?.throttle?.nodes ? 500 # Debounce site disabled overlay @siteEnabled.extend throttle: @config?.throttle?.site ? 2000 # Start long-poller dashboard.pollNodes (nodes, cb) => # Recursive node grabber pnodes = [] resolver = (stack) => id = stack.pop() unless id? # End of ID list dashboard.updateNodes nodes: pnodes, @tmpItems, @keyItems cb() if cb? else dashboard.getData "/octr/nodes/#{id}" , (node) -> pnodes.push node.node # Got a node, so push it resolver stack # Continue , (jqXHR) => switch jqXHR.status when 404 node = @keyItems[id] unless node? # Already deleted? resolver stack # Continue break # Bail this thread pid = node?.facts?.parent_id if pid? # Have parent? delete @keyItems[pid].dash.children[id] # Delete from parent's children delete @keyItems[id] # Remove node resolver stack # Continue else true # Retry GET false # Don't retry GET resolver nodes , @config?.timeout?.long ? 30000 # Start dumb poller dashboard.pollTasks (tasks) => dashboard.updateTasks tasks, @wsTasks, @keyTasks , @config?.throttle?.tasks ? 2000 # Load initial data dashboard.getNodes "/octr/nodes/", @tmpItems, @keyItems dashboard.getTasks "/octr/tasks/", @wsTasks, @keyTasks @siteActive = dashboard.selector (data) => null # TODO: Do something useful with multiple tabs , @siteNav()[0] # Set to first by default # Template accessor that avoids data-loading race @getTemplate = ko.computed => @siteActive()?.template ? {} # TODO: Needs .template?() if @siteNav is mapped # Index template sub-accessor. TODO: unstub for zero-state template progression @getIndexTemplate = ko.computed => name: "indexItemTemplate" foreach: @wsItems # Plan flattener @getPlans = ko.computed => if not @wsPlans()?.plan?.length return null ret = [] #ret.push (dashboard.toArray n?.args)... for n in @wsPlans()?.plan for plan in @wsPlans()?.plan step = {} step.name = '' #TODO: Possibly create a name for each step. step.args = dashboard.toArray plan?.args # Fixup missing/empty friendly names for arg,index in step.args unless arg.value?.friendly? and !!arg.value.friendly step.args[index].value.friendly = step.args[index].key if step.args.length ret.push (step) ret # Document clicks hide menus and bubble up here $(document).click => @siteLocked false @getActions = (node) => $el = $("[data-id=#{node.id()}]") $place = $el.siblings(".dropdown-menu").find("#placeHolder") open = $el.parent().hasClass("open") if open # Closing menu @siteLocked false else # Opening menu @siteLocked true $place.empty() # Clear children $place.append("<div class='form-throb' />") # Show throbber dashboard.getData "/octr/nodes/#{node.id()}/adventures", (data) -> if data?.adventures?.length # Have adventures? node.dash.actions (n for n in data?.adventures) else # No adventures $place.text "No actions available" # Show sad message @doAction = (object, action) => dashboard.post "/octr/adventures/#{action.id}/execute", JSON.stringify node: object.id() , (data) -> # success handler null #TODO: Use success for something , (jqXHR, textStatus, errorThrown) => # error handler switch jqXHR.status when 409 # Need more data @wsPlans JSON.parse jqXHR.responseText @wsPlans().node = object.id() dashboard.showModal "#indexInputModal" else console.log "Error (#{jqXHR.status}): #{errorThrown}" @toggleTaskLogPane = -> unless ko.utils.unwrapObservable(dashboard.displayTaskLogPane()) dashboard.displayTaskLogPane true else dashboard.displayTaskLogPane false # Input form validator; here for scoping plan args $('#inputForm').validate focusCleanup: true highlight: (element) -> $(element).closest('.control-group').removeClass('success').addClass('error') success: (element) -> $(element).closest('.control-group').removeClass('error').addClass('success') submitHandler: (form) => $(form).find('.control-group').each (index, element) => key = $(element).find('label').first().attr('for') val = $(element).find('input').val() for plan in @wsPlans().plan if plan?.args?[key]? plan.args[key].value = val dashboard.post "/octr/plan/", JSON.stringify node: @wsPlans().node plan: @wsPlans().plan , (data) -> dashboard.hideModal "#indexInputModal" , (jqXHR, textStatus, errorThrown) -> dashboard.hideModal "#indexInputModal" console.log "Error (#{jqXHR.status}): #{errorThrown}" # Multi-step form controls; here for manipulating form controls based on form's page #$("#indexInputModal").on "show", (e) -> # dashboard.drawStepProgress() # Sortable afterMove hook; here for scoping updateNodes args ko.bindingHandlers.sortable.afterMove = (options) => dashboard.setBusy options.item # Set busy immediately on drop parent = options.sourceParentNode.attributes["data-id"].value dashboard.post "/octr/facts/", JSON.stringify key: "parent_id" value: parent node_id: options.item.id() , (data) -> null # TODO: Do something with success? , (jqXHR, textStatus, errorThrown) => console.log "Error: (#{jqXHR.status}): #{errorThrown}" dashboard.updateNodes null, @tmpItems, @keyItems # Remap from keys on fails # In case we don't get an update for a while, make sure we at least periodically update node statuses setInterval(dashboard.updateNodes, 90000, null, @tmpItems, @keyItems) @ # Return ourself ko.bindingHandlers.popper = init: (el, data) -> $(el).hover (event) -> id = data().id() obj = dashboard.indexModel.keyItems[id] dashboard.killPopovers() if dashboard.indexModel.siteLocked() return # Don't pop when locked if event.type is "mouseenter" obj.hovered = true dashboard.updatePopover this, obj, true else obj.hovered = false dashboard.killPopovers() ko.bindingHandlers.sortable.options = handle: ".draggable" cancel: ".dragDisable" opacity: 0.35 placeholder: "place-holder" start: (event, ui) -> $("[data-bind~='popper']").popover "disable" dashboard.killPopovers() dashboard.indexModel.siteLocked true stop: (event, ui) -> dashboard.indexModel.siteLocked false $.validator.addMethod "cidrType", (value, element) -> dot2num = (dot) -> d = dot.split('.') ((((((+d[0])*0x100)+(+d[1]))*0x100)+(+d[2]))*0x100)+(+d[3]) num2dot = (num) -> ((num >> 24) & 0xff) + "." + ((num >> 16) & 0xff) + "." + ((num >> 8) & 0xff) + "." + (num & 0xff) regex = /^((?:(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5]))(?:\/(\d|[1-2]\d|3[0-2]))$/ match = regex.exec value if match? mask = +match[2] num = dot2num match[1] masked = num2dot(num & (0xffffffff << (32-mask))) if masked is match[1] then true else false else false , "Validate CIDR" # Login form validator $('#loginForm').validate #focusCleanup: true highlight: (element) -> $(element).closest('.control-group').removeClass('success').addClass('error') success: (element) -> $(element).closest('.control-group').removeClass('error').addClass('success') submitHandler: (form) -> form = $(form) group = form.find('.control-group') user = group.first().find('input') pass = group.next().find('input') throb = form.find('.form-throb') resetForm = -> throb.hide() group.find('input').val "" group.removeClass ['error', 'success'] group.find('.controls label').remove() dashboard.makeBasicAuth user.val(), pass.val() throb.show() $.ajax # Test the auth url: "/octr/" headers: dashboard.authHeader success: -> dashboard.loggingIn = false # Done logging in resetForm() form.find('.alert').hide() dashboard.hideModal "#indexLoginModal" error: -> resetForm() form.find('.alert').show() user.focus() ko.bindingHandlers.showPane = init: (el, data) -> update: (el, data) -> paneHeight = $(el).height() footerHeight = $("#footer").height() #footerNotifications = $('#tasklog-toggle .pane-notifications') unless ko.utils.unwrapObservable(data()) bottom = -1 * paneHeight fadeOpacity = 1 else bottom = footerHeight fadeOpacity = 0 #footerNotifications.fadeTo 300, fadeOpacity $(el).animate bottom: bottom , 300, -> ko.bindingHandlers.tipper = init: (el, data) -> opts = title: data().description trigger: "hover" container: "#indexInputModal" animation: false $(el).tooltip opts ko.bindingHandlers.dropper = update: (el, data) -> if ko.utils.unwrapObservable data() $(el).removeClass("ko_container").removeClass("ui-sortable") else $(el).addClass("ko_container").addClass("ui-sortable") # Custom binding provider with error handling ErrorHandlingBindingProvider = -> original = new ko.bindingProvider() # Determine if an element has any bindings @nodeHasBindings = original.nodeHasBindings # Return the bindings given a node and the bindingContext @getBindings = (node, bindingContext) -> try original.getBindings node, bindingContext catch e console.log "Error in binding: " + e.message, node @ ko.bindingProvider.instance = new ErrorHandlingBindingProvider() dashboard.indexModel = new IndexModel() ko.applyBindings dashboard.indexModel
146595
# OpenCenter™ is Copyright 2013 by Rackspace US, Inc. # ############################################################################### # # OpenCenter is licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. This version # of OpenCenter includes Rackspace trademarks and logos, and in accordance with # Section 6 of the License, the provision of commercial support services in # conjunction with a version of OpenCenter which includes Rackspace trademarks # and logos is prohibited. OpenCenter source code and details are available at: # https://github.com/rcbops/opencenter or upon written request. # # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 and a copy, including this notice, # is available in the LICENSE file accompanying this software. # # 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. # # ############################################################################### # Grab namespace dashboard = exports?.dashboard ? @dashboard $ -> IndexModel = -> # TODO: Map from data source @siteNav = ko.observableArray [ name: "OpenCenter" template: "indexTemplate" ] # Track this for UI caching @siteLocked = ko.observable false # Temp storage for node mapping @tmpItems = ko.observableArray() @tmpCache = ko.observableArray() # Computed wrapper for coalescing changes @wsItems = ko.computed => if @siteLocked() @tmpCache() else # Otherwise fill cache and return @tmpCache @tmpItems() @tmpItems() # Execution plans @wsPlans = ko.observableArray() # Flat node list, keyed by id @keyItems = {} # Current task list @wsTasks = ko.observableArray() # Flat task list, keyed by id @keyTasks = {} @getTaskCounts = ko.computed => counts = {} for task in @wsTasks() status = task.dash.statusClass() counts[status] ?= 0 counts[status] += 1 for k,v of counts statusClass: k count: v @wsTaskTitle = ko.observable("Select a task to view its log") @getTaskTitle = ko.computed => @wsTaskTitle() @wsTaskLog = ko.observable("...") @getTaskLog = ko.computed => @wsTaskLog() @selectTask = (data, event) => $node = $(event.target).closest(".task") $node.siblings().removeClass("active") $node.addClass("active") for k,v of @keyTasks @keyTasks[k].dash["active"] = false id = $node.attr("data-id") dash = @keyTasks[id].dash dash["active"] = true @wsTaskTitle dash.label @wsTaskLog "Retrieving log..." # Kill any pending watch requests dashboard.killRequests /logs\?watch/i # Log streaming dashboard.getData "/octr/tasks/#{id}/logs?watch", (data) => if data?.request? dashboard.killRequests /logs\//i # Kill any existing log streams url = "/octr/tasks/#{id}/logs/#{data.request}" xhr = new XMLHttpRequest() xhr.open "GET", url xhr.setRequestHeader('Authorization', dashboard.authHeader.Authorization) xhr.onloadstart = -> dashboard.pendingRequests[url] = xhr # Store xhr.onprogress = => @wsTaskLog xhr.responseText # Update log observable $contents = $("#logPane .pane-contents") $contents.scrollTop $contents.prop("scrollHeight") # Scroll to bottom xhr.onloadend = -> delete dashboard.pendingRequests[url] # Clean up xhr.send() # Do it! , -> true # Retry if fails # Update on request success/failure @siteEnabled = ko.computed -> unless dashboard.siteEnabled() dashboard.showModal "#indexNoConnectionModal" else dashboard.hideModal "#indexNoConnectionModal" # Get config and grab initial set of nodes dashboard.getData "/api/config", (data) => # Store config @config = data # Debounce node changes (x msec settling period) @wsItems.extend throttle: @config?.throttle?.nodes ? 500 # Debounce site disabled overlay @siteEnabled.extend throttle: @config?.throttle?.site ? 2000 # Start long-poller dashboard.pollNodes (nodes, cb) => # Recursive node grabber pnodes = [] resolver = (stack) => id = stack.pop() unless id? # End of ID list dashboard.updateNodes nodes: pnodes, @tmpItems, @keyItems cb() if cb? else dashboard.getData "/octr/nodes/#{id}" , (node) -> pnodes.push node.node # Got a node, so push it resolver stack # Continue , (jqXHR) => switch jqXHR.status when 404 node = @keyItems[id] unless node? # Already deleted? resolver stack # Continue break # Bail this thread pid = node?.facts?.parent_id if pid? # Have parent? delete @keyItems[pid].dash.children[id] # Delete from parent's children delete @keyItems[id] # Remove node resolver stack # Continue else true # Retry GET false # Don't retry GET resolver nodes , @config?.timeout?.long ? 30000 # Start dumb poller dashboard.pollTasks (tasks) => dashboard.updateTasks tasks, @wsTasks, @keyTasks , @config?.throttle?.tasks ? 2000 # Load initial data dashboard.getNodes "/octr/nodes/", @tmpItems, @keyItems dashboard.getTasks "/octr/tasks/", @wsTasks, @keyTasks @siteActive = dashboard.selector (data) => null # TODO: Do something useful with multiple tabs , @siteNav()[0] # Set to first by default # Template accessor that avoids data-loading race @getTemplate = ko.computed => @siteActive()?.template ? {} # TODO: Needs .template?() if @siteNav is mapped # Index template sub-accessor. TODO: unstub for zero-state template progression @getIndexTemplate = ko.computed => name: "indexItemTemplate" foreach: @wsItems # Plan flattener @getPlans = ko.computed => if not @wsPlans()?.plan?.length return null ret = [] #ret.push (dashboard.toArray n?.args)... for n in @wsPlans()?.plan for plan in @wsPlans()?.plan step = {} step.name = '' #TODO: Possibly create a name for each step. step.args = dashboard.toArray plan?.args # Fixup missing/empty friendly names for arg,index in step.args unless arg.value?.friendly? and !!arg.value.friendly step.args[index].value.friendly = step.args[index].key if step.args.length ret.push (step) ret # Document clicks hide menus and bubble up here $(document).click => @siteLocked false @getActions = (node) => $el = $("[data-id=#{node.id()}]") $place = $el.siblings(".dropdown-menu").find("#placeHolder") open = $el.parent().hasClass("open") if open # Closing menu @siteLocked false else # Opening menu @siteLocked true $place.empty() # Clear children $place.append("<div class='form-throb' />") # Show throbber dashboard.getData "/octr/nodes/#{node.id()}/adventures", (data) -> if data?.adventures?.length # Have adventures? node.dash.actions (n for n in data?.adventures) else # No adventures $place.text "No actions available" # Show sad message @doAction = (object, action) => dashboard.post "/octr/adventures/#{action.id}/execute", JSON.stringify node: object.id() , (data) -> # success handler null #TODO: Use success for something , (jqXHR, textStatus, errorThrown) => # error handler switch jqXHR.status when 409 # Need more data @wsPlans JSON.parse jqXHR.responseText @wsPlans().node = object.id() dashboard.showModal "#indexInputModal" else console.log "Error (#{jqXHR.status}): #{errorThrown}" @toggleTaskLogPane = -> unless ko.utils.unwrapObservable(dashboard.displayTaskLogPane()) dashboard.displayTaskLogPane true else dashboard.displayTaskLogPane false # Input form validator; here for scoping plan args $('#inputForm').validate focusCleanup: true highlight: (element) -> $(element).closest('.control-group').removeClass('success').addClass('error') success: (element) -> $(element).closest('.control-group').removeClass('error').addClass('success') submitHandler: (form) => $(form).find('.control-group').each (index, element) => key = $(element).find('label').first().attr('for') val = $(element).find('input').val() for plan in @wsPlans().plan if plan?.args?[key]? plan.args[key].value = val dashboard.post "/octr/plan/", JSON.stringify node: @wsPlans().node plan: @wsPlans().plan , (data) -> dashboard.hideModal "#indexInputModal" , (jqXHR, textStatus, errorThrown) -> dashboard.hideModal "#indexInputModal" console.log "Error (#{jqXHR.status}): #{errorThrown}" # Multi-step form controls; here for manipulating form controls based on form's page #$("#indexInputModal").on "show", (e) -> # dashboard.drawStepProgress() # Sortable afterMove hook; here for scoping updateNodes args ko.bindingHandlers.sortable.afterMove = (options) => dashboard.setBusy options.item # Set busy immediately on drop parent = options.sourceParentNode.attributes["data-id"].value dashboard.post "/octr/facts/", JSON.stringify key: "<KEY>" value: parent node_id: options.item.id() , (data) -> null # TODO: Do something with success? , (jqXHR, textStatus, errorThrown) => console.log "Error: (#{jqXHR.status}): #{errorThrown}" dashboard.updateNodes null, @tmpItems, @keyItems # Remap from keys on fails # In case we don't get an update for a while, make sure we at least periodically update node statuses setInterval(dashboard.updateNodes, 90000, null, @tmpItems, @keyItems) @ # Return ourself ko.bindingHandlers.popper = init: (el, data) -> $(el).hover (event) -> id = data().id() obj = dashboard.indexModel.keyItems[id] dashboard.killPopovers() if dashboard.indexModel.siteLocked() return # Don't pop when locked if event.type is "mouseenter" obj.hovered = true dashboard.updatePopover this, obj, true else obj.hovered = false dashboard.killPopovers() ko.bindingHandlers.sortable.options = handle: ".draggable" cancel: ".dragDisable" opacity: 0.35 placeholder: "place-holder" start: (event, ui) -> $("[data-bind~='popper']").popover "disable" dashboard.killPopovers() dashboard.indexModel.siteLocked true stop: (event, ui) -> dashboard.indexModel.siteLocked false $.validator.addMethod "cidrType", (value, element) -> dot2num = (dot) -> d = dot.split('.') ((((((+d[0])*0x100)+(+d[1]))*0x100)+(+d[2]))*0x100)+(+d[3]) num2dot = (num) -> ((num >> 24) & 0xff) + "." + ((num >> 16) & 0xff) + "." + ((num >> 8) & 0xff) + "." + (num & 0xff) regex = /^((?:(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5]))(?:\/(\d|[1-2]\d|3[0-2]))$/ match = regex.exec value if match? mask = +match[2] num = dot2num match[1] masked = num2dot(num & (0xffffffff << (32-mask))) if masked is match[1] then true else false else false , "Validate CIDR" # Login form validator $('#loginForm').validate #focusCleanup: true highlight: (element) -> $(element).closest('.control-group').removeClass('success').addClass('error') success: (element) -> $(element).closest('.control-group').removeClass('error').addClass('success') submitHandler: (form) -> form = $(form) group = form.find('.control-group') user = group.first().find('input') pass = group.next().find('input') throb = form.find('.form-throb') resetForm = -> throb.hide() group.find('input').val "" group.removeClass ['error', 'success'] group.find('.controls label').remove() dashboard.makeBasicAuth user.val(), pass.val() throb.show() $.ajax # Test the auth url: "/octr/" headers: dashboard.authHeader success: -> dashboard.loggingIn = false # Done logging in resetForm() form.find('.alert').hide() dashboard.hideModal "#indexLoginModal" error: -> resetForm() form.find('.alert').show() user.focus() ko.bindingHandlers.showPane = init: (el, data) -> update: (el, data) -> paneHeight = $(el).height() footerHeight = $("#footer").height() #footerNotifications = $('#tasklog-toggle .pane-notifications') unless ko.utils.unwrapObservable(data()) bottom = -1 * paneHeight fadeOpacity = 1 else bottom = footerHeight fadeOpacity = 0 #footerNotifications.fadeTo 300, fadeOpacity $(el).animate bottom: bottom , 300, -> ko.bindingHandlers.tipper = init: (el, data) -> opts = title: data().description trigger: "hover" container: "#indexInputModal" animation: false $(el).tooltip opts ko.bindingHandlers.dropper = update: (el, data) -> if ko.utils.unwrapObservable data() $(el).removeClass("ko_container").removeClass("ui-sortable") else $(el).addClass("ko_container").addClass("ui-sortable") # Custom binding provider with error handling ErrorHandlingBindingProvider = -> original = new ko.bindingProvider() # Determine if an element has any bindings @nodeHasBindings = original.nodeHasBindings # Return the bindings given a node and the bindingContext @getBindings = (node, bindingContext) -> try original.getBindings node, bindingContext catch e console.log "Error in binding: " + e.message, node @ ko.bindingProvider.instance = new ErrorHandlingBindingProvider() dashboard.indexModel = new IndexModel() ko.applyBindings dashboard.indexModel
true
# OpenCenter™ is Copyright 2013 by Rackspace US, Inc. # ############################################################################### # # OpenCenter is licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. This version # of OpenCenter includes Rackspace trademarks and logos, and in accordance with # Section 6 of the License, the provision of commercial support services in # conjunction with a version of OpenCenter which includes Rackspace trademarks # and logos is prohibited. OpenCenter source code and details are available at: # https://github.com/rcbops/opencenter or upon written request. # # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 and a copy, including this notice, # is available in the LICENSE file accompanying this software. # # 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. # # ############################################################################### # Grab namespace dashboard = exports?.dashboard ? @dashboard $ -> IndexModel = -> # TODO: Map from data source @siteNav = ko.observableArray [ name: "OpenCenter" template: "indexTemplate" ] # Track this for UI caching @siteLocked = ko.observable false # Temp storage for node mapping @tmpItems = ko.observableArray() @tmpCache = ko.observableArray() # Computed wrapper for coalescing changes @wsItems = ko.computed => if @siteLocked() @tmpCache() else # Otherwise fill cache and return @tmpCache @tmpItems() @tmpItems() # Execution plans @wsPlans = ko.observableArray() # Flat node list, keyed by id @keyItems = {} # Current task list @wsTasks = ko.observableArray() # Flat task list, keyed by id @keyTasks = {} @getTaskCounts = ko.computed => counts = {} for task in @wsTasks() status = task.dash.statusClass() counts[status] ?= 0 counts[status] += 1 for k,v of counts statusClass: k count: v @wsTaskTitle = ko.observable("Select a task to view its log") @getTaskTitle = ko.computed => @wsTaskTitle() @wsTaskLog = ko.observable("...") @getTaskLog = ko.computed => @wsTaskLog() @selectTask = (data, event) => $node = $(event.target).closest(".task") $node.siblings().removeClass("active") $node.addClass("active") for k,v of @keyTasks @keyTasks[k].dash["active"] = false id = $node.attr("data-id") dash = @keyTasks[id].dash dash["active"] = true @wsTaskTitle dash.label @wsTaskLog "Retrieving log..." # Kill any pending watch requests dashboard.killRequests /logs\?watch/i # Log streaming dashboard.getData "/octr/tasks/#{id}/logs?watch", (data) => if data?.request? dashboard.killRequests /logs\//i # Kill any existing log streams url = "/octr/tasks/#{id}/logs/#{data.request}" xhr = new XMLHttpRequest() xhr.open "GET", url xhr.setRequestHeader('Authorization', dashboard.authHeader.Authorization) xhr.onloadstart = -> dashboard.pendingRequests[url] = xhr # Store xhr.onprogress = => @wsTaskLog xhr.responseText # Update log observable $contents = $("#logPane .pane-contents") $contents.scrollTop $contents.prop("scrollHeight") # Scroll to bottom xhr.onloadend = -> delete dashboard.pendingRequests[url] # Clean up xhr.send() # Do it! , -> true # Retry if fails # Update on request success/failure @siteEnabled = ko.computed -> unless dashboard.siteEnabled() dashboard.showModal "#indexNoConnectionModal" else dashboard.hideModal "#indexNoConnectionModal" # Get config and grab initial set of nodes dashboard.getData "/api/config", (data) => # Store config @config = data # Debounce node changes (x msec settling period) @wsItems.extend throttle: @config?.throttle?.nodes ? 500 # Debounce site disabled overlay @siteEnabled.extend throttle: @config?.throttle?.site ? 2000 # Start long-poller dashboard.pollNodes (nodes, cb) => # Recursive node grabber pnodes = [] resolver = (stack) => id = stack.pop() unless id? # End of ID list dashboard.updateNodes nodes: pnodes, @tmpItems, @keyItems cb() if cb? else dashboard.getData "/octr/nodes/#{id}" , (node) -> pnodes.push node.node # Got a node, so push it resolver stack # Continue , (jqXHR) => switch jqXHR.status when 404 node = @keyItems[id] unless node? # Already deleted? resolver stack # Continue break # Bail this thread pid = node?.facts?.parent_id if pid? # Have parent? delete @keyItems[pid].dash.children[id] # Delete from parent's children delete @keyItems[id] # Remove node resolver stack # Continue else true # Retry GET false # Don't retry GET resolver nodes , @config?.timeout?.long ? 30000 # Start dumb poller dashboard.pollTasks (tasks) => dashboard.updateTasks tasks, @wsTasks, @keyTasks , @config?.throttle?.tasks ? 2000 # Load initial data dashboard.getNodes "/octr/nodes/", @tmpItems, @keyItems dashboard.getTasks "/octr/tasks/", @wsTasks, @keyTasks @siteActive = dashboard.selector (data) => null # TODO: Do something useful with multiple tabs , @siteNav()[0] # Set to first by default # Template accessor that avoids data-loading race @getTemplate = ko.computed => @siteActive()?.template ? {} # TODO: Needs .template?() if @siteNav is mapped # Index template sub-accessor. TODO: unstub for zero-state template progression @getIndexTemplate = ko.computed => name: "indexItemTemplate" foreach: @wsItems # Plan flattener @getPlans = ko.computed => if not @wsPlans()?.plan?.length return null ret = [] #ret.push (dashboard.toArray n?.args)... for n in @wsPlans()?.plan for plan in @wsPlans()?.plan step = {} step.name = '' #TODO: Possibly create a name for each step. step.args = dashboard.toArray plan?.args # Fixup missing/empty friendly names for arg,index in step.args unless arg.value?.friendly? and !!arg.value.friendly step.args[index].value.friendly = step.args[index].key if step.args.length ret.push (step) ret # Document clicks hide menus and bubble up here $(document).click => @siteLocked false @getActions = (node) => $el = $("[data-id=#{node.id()}]") $place = $el.siblings(".dropdown-menu").find("#placeHolder") open = $el.parent().hasClass("open") if open # Closing menu @siteLocked false else # Opening menu @siteLocked true $place.empty() # Clear children $place.append("<div class='form-throb' />") # Show throbber dashboard.getData "/octr/nodes/#{node.id()}/adventures", (data) -> if data?.adventures?.length # Have adventures? node.dash.actions (n for n in data?.adventures) else # No adventures $place.text "No actions available" # Show sad message @doAction = (object, action) => dashboard.post "/octr/adventures/#{action.id}/execute", JSON.stringify node: object.id() , (data) -> # success handler null #TODO: Use success for something , (jqXHR, textStatus, errorThrown) => # error handler switch jqXHR.status when 409 # Need more data @wsPlans JSON.parse jqXHR.responseText @wsPlans().node = object.id() dashboard.showModal "#indexInputModal" else console.log "Error (#{jqXHR.status}): #{errorThrown}" @toggleTaskLogPane = -> unless ko.utils.unwrapObservable(dashboard.displayTaskLogPane()) dashboard.displayTaskLogPane true else dashboard.displayTaskLogPane false # Input form validator; here for scoping plan args $('#inputForm').validate focusCleanup: true highlight: (element) -> $(element).closest('.control-group').removeClass('success').addClass('error') success: (element) -> $(element).closest('.control-group').removeClass('error').addClass('success') submitHandler: (form) => $(form).find('.control-group').each (index, element) => key = $(element).find('label').first().attr('for') val = $(element).find('input').val() for plan in @wsPlans().plan if plan?.args?[key]? plan.args[key].value = val dashboard.post "/octr/plan/", JSON.stringify node: @wsPlans().node plan: @wsPlans().plan , (data) -> dashboard.hideModal "#indexInputModal" , (jqXHR, textStatus, errorThrown) -> dashboard.hideModal "#indexInputModal" console.log "Error (#{jqXHR.status}): #{errorThrown}" # Multi-step form controls; here for manipulating form controls based on form's page #$("#indexInputModal").on "show", (e) -> # dashboard.drawStepProgress() # Sortable afterMove hook; here for scoping updateNodes args ko.bindingHandlers.sortable.afterMove = (options) => dashboard.setBusy options.item # Set busy immediately on drop parent = options.sourceParentNode.attributes["data-id"].value dashboard.post "/octr/facts/", JSON.stringify key: "PI:KEY:<KEY>END_PI" value: parent node_id: options.item.id() , (data) -> null # TODO: Do something with success? , (jqXHR, textStatus, errorThrown) => console.log "Error: (#{jqXHR.status}): #{errorThrown}" dashboard.updateNodes null, @tmpItems, @keyItems # Remap from keys on fails # In case we don't get an update for a while, make sure we at least periodically update node statuses setInterval(dashboard.updateNodes, 90000, null, @tmpItems, @keyItems) @ # Return ourself ko.bindingHandlers.popper = init: (el, data) -> $(el).hover (event) -> id = data().id() obj = dashboard.indexModel.keyItems[id] dashboard.killPopovers() if dashboard.indexModel.siteLocked() return # Don't pop when locked if event.type is "mouseenter" obj.hovered = true dashboard.updatePopover this, obj, true else obj.hovered = false dashboard.killPopovers() ko.bindingHandlers.sortable.options = handle: ".draggable" cancel: ".dragDisable" opacity: 0.35 placeholder: "place-holder" start: (event, ui) -> $("[data-bind~='popper']").popover "disable" dashboard.killPopovers() dashboard.indexModel.siteLocked true stop: (event, ui) -> dashboard.indexModel.siteLocked false $.validator.addMethod "cidrType", (value, element) -> dot2num = (dot) -> d = dot.split('.') ((((((+d[0])*0x100)+(+d[1]))*0x100)+(+d[2]))*0x100)+(+d[3]) num2dot = (num) -> ((num >> 24) & 0xff) + "." + ((num >> 16) & 0xff) + "." + ((num >> 8) & 0xff) + "." + (num & 0xff) regex = /^((?:(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5]))(?:\/(\d|[1-2]\d|3[0-2]))$/ match = regex.exec value if match? mask = +match[2] num = dot2num match[1] masked = num2dot(num & (0xffffffff << (32-mask))) if masked is match[1] then true else false else false , "Validate CIDR" # Login form validator $('#loginForm').validate #focusCleanup: true highlight: (element) -> $(element).closest('.control-group').removeClass('success').addClass('error') success: (element) -> $(element).closest('.control-group').removeClass('error').addClass('success') submitHandler: (form) -> form = $(form) group = form.find('.control-group') user = group.first().find('input') pass = group.next().find('input') throb = form.find('.form-throb') resetForm = -> throb.hide() group.find('input').val "" group.removeClass ['error', 'success'] group.find('.controls label').remove() dashboard.makeBasicAuth user.val(), pass.val() throb.show() $.ajax # Test the auth url: "/octr/" headers: dashboard.authHeader success: -> dashboard.loggingIn = false # Done logging in resetForm() form.find('.alert').hide() dashboard.hideModal "#indexLoginModal" error: -> resetForm() form.find('.alert').show() user.focus() ko.bindingHandlers.showPane = init: (el, data) -> update: (el, data) -> paneHeight = $(el).height() footerHeight = $("#footer").height() #footerNotifications = $('#tasklog-toggle .pane-notifications') unless ko.utils.unwrapObservable(data()) bottom = -1 * paneHeight fadeOpacity = 1 else bottom = footerHeight fadeOpacity = 0 #footerNotifications.fadeTo 300, fadeOpacity $(el).animate bottom: bottom , 300, -> ko.bindingHandlers.tipper = init: (el, data) -> opts = title: data().description trigger: "hover" container: "#indexInputModal" animation: false $(el).tooltip opts ko.bindingHandlers.dropper = update: (el, data) -> if ko.utils.unwrapObservable data() $(el).removeClass("ko_container").removeClass("ui-sortable") else $(el).addClass("ko_container").addClass("ui-sortable") # Custom binding provider with error handling ErrorHandlingBindingProvider = -> original = new ko.bindingProvider() # Determine if an element has any bindings @nodeHasBindings = original.nodeHasBindings # Return the bindings given a node and the bindingContext @getBindings = (node, bindingContext) -> try original.getBindings node, bindingContext catch e console.log "Error in binding: " + e.message, node @ ko.bindingProvider.instance = new ErrorHandlingBindingProvider() dashboard.indexModel = new IndexModel() ko.applyBindings dashboard.indexModel
[ { "context": "****\n# JSFileManager - File manage clss\n# Coded by Hajime Oh-yake 2013.03.31\n#*************************************", "end": 103, "score": 0.9998951554298401, "start": 89, "tag": "NAME", "value": "Hajime Oh-yake" } ]
JSKit/01_JSFileManager.coffee
digitarhythm/codeJS
0
#***************************************** # JSFileManager - File manage clss # Coded by Hajime Oh-yake 2013.03.31 #***************************************** class JSFileManager extends JSObject constructor:-> super() escapeHTML:(s) -> s.replace /[&"<>]/g, (c) -> escapeRules[c] escapeRules = "&": "&amp;" "\"": "&quot;" "<": "&lt;" ">": "&gt;" stringWithContentsOfFile:(fname, @readaction)-> if (!fname?) return $.post "syslibs/library.php", mode: "stringWithContentsOfFile" fname: fname ,(data) => if (@readaction?) @readaction(data) writeToFile:(path, string, @saveaction)-> $.post "syslibs/library.php", mode: "writeToFile" fname: path data: string , (ret) => if (@saveaction?) @saveaction(parseInt(ret)) fileList:(path, type, @listaction)-> $.post "syslibs/library.php", mode: "filelist" path: path filter: type ,(filelist) => if (@listaction?) @listaction(filelist) thumbnailList:(path, @imagelistaction)-> $.post "syslibs/library.php", mode: "thumbnailList" path: path ,(filelist) => if (@imagelistaction?) @imagelistaction(filelist) createDirectoryAtPath:(path, @creatediraction)-> $.post "syslibs/library.php", mode: "createDirectoryAtPath" path: path , (ret) => if (@creatediraction?) @creatediraction(parseInt(ret)) removeItemAtPath:(path, @removeaction)-> $.post "syslibs/library.php", mode: "removeFile" path: path , (ret) => if (@removeaction?) @removeaction(parseInt(ret)) moveItemAtPath:(file, path, @moveaction)-> $.post "syslibs/library.php", mode: "moveFile" file: file toPath: path , (ret) => if (@moveaction?) @moveaction(parseInt(ret))
115411
#***************************************** # JSFileManager - File manage clss # Coded by <NAME> 2013.03.31 #***************************************** class JSFileManager extends JSObject constructor:-> super() escapeHTML:(s) -> s.replace /[&"<>]/g, (c) -> escapeRules[c] escapeRules = "&": "&amp;" "\"": "&quot;" "<": "&lt;" ">": "&gt;" stringWithContentsOfFile:(fname, @readaction)-> if (!fname?) return $.post "syslibs/library.php", mode: "stringWithContentsOfFile" fname: fname ,(data) => if (@readaction?) @readaction(data) writeToFile:(path, string, @saveaction)-> $.post "syslibs/library.php", mode: "writeToFile" fname: path data: string , (ret) => if (@saveaction?) @saveaction(parseInt(ret)) fileList:(path, type, @listaction)-> $.post "syslibs/library.php", mode: "filelist" path: path filter: type ,(filelist) => if (@listaction?) @listaction(filelist) thumbnailList:(path, @imagelistaction)-> $.post "syslibs/library.php", mode: "thumbnailList" path: path ,(filelist) => if (@imagelistaction?) @imagelistaction(filelist) createDirectoryAtPath:(path, @creatediraction)-> $.post "syslibs/library.php", mode: "createDirectoryAtPath" path: path , (ret) => if (@creatediraction?) @creatediraction(parseInt(ret)) removeItemAtPath:(path, @removeaction)-> $.post "syslibs/library.php", mode: "removeFile" path: path , (ret) => if (@removeaction?) @removeaction(parseInt(ret)) moveItemAtPath:(file, path, @moveaction)-> $.post "syslibs/library.php", mode: "moveFile" file: file toPath: path , (ret) => if (@moveaction?) @moveaction(parseInt(ret))
true
#***************************************** # JSFileManager - File manage clss # Coded by PI:NAME:<NAME>END_PI 2013.03.31 #***************************************** class JSFileManager extends JSObject constructor:-> super() escapeHTML:(s) -> s.replace /[&"<>]/g, (c) -> escapeRules[c] escapeRules = "&": "&amp;" "\"": "&quot;" "<": "&lt;" ">": "&gt;" stringWithContentsOfFile:(fname, @readaction)-> if (!fname?) return $.post "syslibs/library.php", mode: "stringWithContentsOfFile" fname: fname ,(data) => if (@readaction?) @readaction(data) writeToFile:(path, string, @saveaction)-> $.post "syslibs/library.php", mode: "writeToFile" fname: path data: string , (ret) => if (@saveaction?) @saveaction(parseInt(ret)) fileList:(path, type, @listaction)-> $.post "syslibs/library.php", mode: "filelist" path: path filter: type ,(filelist) => if (@listaction?) @listaction(filelist) thumbnailList:(path, @imagelistaction)-> $.post "syslibs/library.php", mode: "thumbnailList" path: path ,(filelist) => if (@imagelistaction?) @imagelistaction(filelist) createDirectoryAtPath:(path, @creatediraction)-> $.post "syslibs/library.php", mode: "createDirectoryAtPath" path: path , (ret) => if (@creatediraction?) @creatediraction(parseInt(ret)) removeItemAtPath:(path, @removeaction)-> $.post "syslibs/library.php", mode: "removeFile" path: path , (ret) => if (@removeaction?) @removeaction(parseInt(ret)) moveItemAtPath:(file, path, @moveaction)-> $.post "syslibs/library.php", mode: "moveFile" file: file toPath: path , (ret) => if (@moveaction?) @moveaction(parseInt(ret))
[ { "context": "st is run for the second group.\n # file:///Users/daviddellacasa/Fizzygum/Fizzygum-builds/latest/worldWithSystemTe", "end": 16676, "score": 0.9986366033554077, "start": 16662, "tag": "USERNAME", "value": "daviddellacasa" }, { "context": " simple quick test about shadows\n #file:///Users/daviddellacasa/Fizzygum/Fizzygum-builds/latest/worldWithSystemTe", "end": 17270, "score": 0.9976040720939636, "start": 17256, "tag": "USERNAME", "value": "daviddellacasa" }, { "context": "eful tween functions here:\n # https://github.com/ashblue/simple-tween-js/blob/master/tween.js\n expoOut: (", "end": 42112, "score": 0.9995959997177124, "start": 42105, "tag": "USERNAME", "value": "ashblue" }, { "context": "s not sent.\n # See:\n # https://github.com/cdr/code-server/issues/1455\n # https://bugs.webk", "end": 82667, "score": 0.9992181062698364, "start": 82664, "tag": "USERNAME", "value": "cdr" }, { "context": "hn, und das hat mit ihrem \" +\n \"Singen, die Loreley getan.\")\n newWdgt.isEditable = true\n new", "end": 98908, "score": 0.5213779211044312, "start": 98905, "tag": "NAME", "value": "ore" } ]
src/WorldMorph.coffee
intensifier/Fizzygum
110
# The WorldMorph takes over the canvas on the page class WorldMorph extends PanelWdgt @augmentWith GridPositioningOfAddedShortcutsMixin, @name @augmentWith KeepIconicDesktopSystemLinksBackMixin, @name # We need to add and remove # the event listeners so we are # going to put them all in properties # here. # dblclickEventListener: nil mousedownBrowserEventListener: nil mouseupBrowserEventListener: nil mousemoveBrowserEventListener: nil contextmenuEventListener: nil touchstartBrowserEventListener: nil touchendBrowserEventListener: nil touchmoveBrowserEventListener: nil gesturestartBrowserEventListener: nil gesturechangeBrowserEventListener: nil # Note how there can be two handlers for # keyboard events. # This one is attached # to the canvas and reaches the currently # blinking caret if there is one. # See below for the other potential # handler. See "initVirtualKeyboard" # method to see where and when this input and # these handlers are set up. keydownBrowserEventListener: nil keyupBrowserEventListener: nil keypressBrowserEventListener: nil wheelBrowserEventListener: nil cutBrowserEventListener: nil copyBrowserEventListener: nil pasteBrowserEventListener: nil errorConsole: nil # the string for the last serialised morph # is kept in here, to make serialization # and deserialization tests easier. # The alternative would be to refresh and # re-start the tests from where they left... lastSerializationString: "" # Note how there can be two handlers # for keyboard events. This one is # attached to a hidden # "input" div which keeps track of the # text that is being input. inputDOMElementForVirtualKeyboardKeydownBrowserEventListener: nil inputDOMElementForVirtualKeyboardKeyupBrowserEventListener: nil inputDOMElementForVirtualKeyboardKeypressBrowserEventListener: nil # »>> this part is excluded from the fizzygum homepage build keyComboResetWorldEventListener: nil keyComboTurnOnAnimationsPacingControl: nil keyComboTurnOffAnimationsPacingControl: nil keyComboTakeScreenshotEventListener: nil keyComboStopTestRecordingEventListener: nil keyComboTakeScreenshotEventListener: nil keyComboCheckStringsOfItemsInMenuOrderImportant: nil keyComboCheckStringsOfItemsInMenuOrderUnimportant: nil keyComboAddTestCommentEventListener: nil keyComboCheckNumberOfMenuItemsEventListener: nil # this part is excluded from the fizzygum homepage build <<« dragoverEventListener: nil resizeBrowserEventListener: nil otherTasksToBeRunOnStep: [] # »>> this part is excluded from the fizzygum homepage build dropBrowserEventListener: nil # this part is excluded from the fizzygum homepage build <<« # these variables shouldn't be static to the WorldMorph, because # in pure theory you could have multiple worlds in the same # page with different settings # (but anyways, it was global before, so it's not any worse than before) @preferencesAndSettings: nil @dateOfPreviousCycleStart: nil @dateOfCurrentCycleStart: nil showRedraws: false doubleCheckCachedMethodsResults: false automator: nil # this is the actual reference to the canvas # on the html page, where the world is # finally painted to. worldCanvas: nil worldCanvasContext: nil canvasForTextMeasurements: nil canvasContextForTextMeasurements: nil cacheForTextMeasurements: nil cacheForTextParagraphSplits: nil cacheForParagraphsWordsSplits: nil cacheForParagraphsWrappingData: nil cacheForTextWrappingData: nil cacheForTextBreakingIntoLinesTopLevel: nil # By default the world will always fill # the entire page, also when browser window # is resized. # When this flag is set, the onResize callback # automatically adjusts the world size. automaticallyAdjustToFillEntireBrowserAlsoOnResize: true # »>> this part is excluded from the fizzygum homepage build # keypad keys map to special characters # so we can trigger test actions # see more comments below @KEYPAD_TAB_mappedToThaiKeyboard_A: "ฟ" @KEYPAD_SLASH_mappedToThaiKeyboard_B: "ิ" @KEYPAD_MULTIPLY_mappedToThaiKeyboard_C: "แ" @KEYPAD_DELETE_mappedToThaiKeyboard_D: "ก" @KEYPAD_7_mappedToThaiKeyboard_E: "ำ" @KEYPAD_8_mappedToThaiKeyboard_F: "ด" @KEYPAD_9_mappedToThaiKeyboard_G: "เ" @KEYPAD_MINUS_mappedToThaiKeyboard_H: "้" @KEYPAD_4_mappedToThaiKeyboard_I: "ร" @KEYPAD_5_mappedToThaiKeyboard_J: "่" # looks like empty string but isn't :-) @KEYPAD_6_mappedToThaiKeyboard_K: "า" @KEYPAD_PLUS_mappedToThaiKeyboard_L: "ส" @KEYPAD_1_mappedToThaiKeyboard_M: "ท" @KEYPAD_2_mappedToThaiKeyboard_N: "ท" @KEYPAD_3_mappedToThaiKeyboard_O: "ื" @KEYPAD_ENTER_mappedToThaiKeyboard_P: "น" @KEYPAD_0_mappedToThaiKeyboard_Q: "ย" @KEYPAD_DOT_mappedToThaiKeyboard_R: "พ" # this part is excluded from the fizzygum homepage build <<« wdgtsDetectingClickOutsideMeOrAnyOfMeChildren: new Set hierarchyOfClickedWdgts: new Set hierarchyOfClickedMenus: new Set popUpsMarkedForClosure: new Set freshlyCreatedPopUps: new Set openPopUps: new Set toolTipsList: new Set # »>> this part is excluded from the fizzygum homepage build @ongoingUrlActionNumber: 0 # this part is excluded from the fizzygum homepage build <<« @frameCount: 0 @numberOfAddsAndRemoves: 0 @numberOfVisibilityFlagsChanges: 0 @numberOfCollapseFlagsChanges: 0 @numberOfRawMovesAndResizes: 0 broken: nil duplicatedBrokenRectsTracker: nil numberOfDuplicatedBrokenRects: 0 numberOfMergedSourceAndDestination: 0 morphsToBeHighlighted: new Set currentHighlightingMorphs: new Set morphsBeingHighlighted: new Set # »>> this part is excluded from the fizzygum homepage build morphsToBePinouted: new Set currentPinoutingMorphs: new Set morphsBeingPinouted: new Set # this part is excluded from the fizzygum homepage build <<« steppingWdgts: new Set basementWdgt: nil # since the shadow is just a "rendering" effect # there is no morph for it, we need to just clean up # the shadow area ad-hoc. We do that by just growing any # broken rectangle by the maximum shadow offset. # We could be more surgical and remember the offset of the # shadow (if any) in the start and end location of the # morph, just like we do with the position, but it # would complicate things and probably be overkill. # The downside of this is that if we change the # shadow sizes, we have to check that this max size # still captures the biggest. maxShadowSize: 6 eventsQueue: [] widgetsReferencingOtherWidgets: new Set incrementalGcSessionId: 0 desktopSidesPadding: 10 # the desktop lays down icons vertically laysIconsHorizontallyInGrid: false iconsLayingInGridWrapCount: 5 errorsWhileRepainting: [] paintingWidget: nil widgetsGivingErrorWhileRepainting: [] # this one is so we can left/center/right align in # a document editor the last widget that the user "touched" # TODO this could be extended so we keep a "list" of # "selected" widgets (e.g. if the user ctrl-clicks on a widget # then it highlights in some manner and ends up in this list) # and then operations can be performed on the whole list # of widgets. lastNonTextPropertyChangerButtonClickedOrDropped: nil patternName: nil pattern1: "plain" pattern2: "circles" pattern3: "vert. stripes" pattern4: "oblique stripes" pattern5: "dots" pattern6: "zigzag" pattern7: "bricks" howManyUntitledShortcuts: 0 howManyUntitledFoldersShortcuts: 0 lastUsedConnectionsCalculationToken: 0 isIndexPage: nil # »>> this part is excluded from the fizzygum homepage build # This method also handles keypresses from a special # external keypad which is used to # record tests commands (such as capture screen, etc.). # These external keypads are inexpensive # so they are a good device for this kind # of stuff. # http://www.amazon.co.uk/Perixx-PERIPAD-201PLUS-Numeric-Keypad-Laptop/dp/B001R6FZLU/ # They keypad is mapped # to Thai keyboard characters via an OSX app # called keyremap4macbook (also one needs to add the # Thai keyboard, which is just a click from System Preferences) # Those Thai characters are used to trigger test # commands. The only added complexity is about # the "00" key of such keypads - see # note below. doublePressOfZeroKeypadKey: nil # this part is excluded from the fizzygum homepage build <<« healingRectanglesPhase: false # we use the trackChanges array as a stack to # keep track whether a whole segment of code # (including all function calls in it) will # record the broken rectangles. # Using a stack we can correctly track nested "disabling of track # changes" correctly. trackChanges: [true] morphsThatMaybeChangedGeometryOrPosition: [] morphsThatMaybeChangedFullGeometryOrPosition: [] morphsThatMaybeChangedLayout: [] # »>> this part is only needed for Macros macroStepsWaitingTimer: nil nextBlockToBeRun: nil macroVars: nil macroIsRunning: nil # this part is only needed for Macros <<« constructor: ( @worldCanvas, @automaticallyAdjustToFillEntireBrowserAlsoOnResize = true ) -> # The WorldMorph is the very first morph to # be created. # world at the moment is a global variable, there is only one # world and this variable needs to be initialised as soon as possible, which # is right here. This is because there is code in this constructor that # will reference that global world variable, so it needs to be set # very early window.world = @ if window.location.href.includes "worldWithSystemTestHarness" @isIndexPage = false else @isIndexPage = true WorldMorph.preferencesAndSettings = new PreferencesAndSettings super() @patternName = @pattern1 @appearance = new DesktopAppearance @ #console.log WorldMorph.preferencesAndSettings.menuFontName @color = Color.create 205, 205, 205 # (130, 130, 130) @strokeColor = nil @alpha = 1 # additional properties: @isDevMode = false @hand = new ActivePointerWdgt @keyboardEventsReceiver = nil @lastEditedText = nil @caret = nil @temporaryHandlesAndLayoutAdjusters = new Set @inputDOMElementForVirtualKeyboard = nil if @automaticallyAdjustToFillEntireBrowserAlsoOnResize and @isIndexPage @stretchWorldToFillEntirePage() else @sizeCanvasToTestScreenResolution() # @worldCanvas.width and height here are in physical pixels # so we want to bring them back to logical pixels @setBounds new Rectangle 0, 0, @worldCanvas.width / ceilPixelRatio, @worldCanvas.height / ceilPixelRatio @initEventListeners() if Automator? @automator = new Automator @worldCanvasContext = @worldCanvas.getContext "2d" @canvasForTextMeasurements = HTMLCanvasElement.createOfPhysicalDimensions() @canvasContextForTextMeasurements = @canvasForTextMeasurements.getContext "2d" @canvasContextForTextMeasurements.useLogicalPixelsUntilRestore() @canvasContextForTextMeasurements.textAlign = "left" @canvasContextForTextMeasurements.textBaseline = "bottom" # when using an inspector it's not uncommon to render # 400 labels just for the properties, so trying to size # the cache accordingly... @cacheForTextMeasurements = new LRUCache 1000, 1000*60*60*24 @cacheForTextParagraphSplits = new LRUCache 300, 1000*60*60*24 @cacheForParagraphsWordsSplits = new LRUCache 300, 1000*60*60*24 @cacheForParagraphsWrappingData = new LRUCache 300, 1000*60*60*24 @cacheForTextWrappingData = new LRUCache 300, 1000*60*60*24 @cacheForImmutableBackBuffers = new LRUCache 1000, 1000*60*60*24 @cacheForTextBreakingIntoLinesTopLevel = new LRUCache 10, 1000*60*60*24 @changed() # answer the absolute coordinates of the world canvas within the document getCanvasPosition: -> if !@worldCanvas? return {x: 0, y: 0} pos = x: @worldCanvas.offsetLeft y: @worldCanvas.offsetTop offsetParent = @worldCanvas.offsetParent while offsetParent? pos.x += offsetParent.offsetLeft pos.y += offsetParent.offsetTop if offsetParent isnt document.body and offsetParent isnt document.documentElement pos.x -= offsetParent.scrollLeft pos.y -= offsetParent.scrollTop offsetParent = offsetParent.offsetParent pos colloquialName: -> "Desktop" makePrettier: -> WorldMorph.preferencesAndSettings.menuFontSize = 14 WorldMorph.preferencesAndSettings.menuHeaderFontSize = 13 WorldMorph.preferencesAndSettings.menuHeaderColor = Color.create 125, 125, 125 WorldMorph.preferencesAndSettings.menuHeaderBold = false WorldMorph.preferencesAndSettings.menuStrokeColor = Color.create 186, 186, 186 WorldMorph.preferencesAndSettings.menuBackgroundColor = Color.create 250, 250, 250 WorldMorph.preferencesAndSettings.menuButtonsLabelColor = Color.create 50, 50, 50 WorldMorph.preferencesAndSettings.normalTextFontSize = 13 WorldMorph.preferencesAndSettings.titleBarTextFontSize = 13 WorldMorph.preferencesAndSettings.titleBarTextHeight = 16 WorldMorph.preferencesAndSettings.titleBarBoldText = false WorldMorph.preferencesAndSettings.bubbleHelpFontSize = 12 WorldMorph.preferencesAndSettings.iconDarkLineColor = Color.create 37, 37, 37 WorldMorph.preferencesAndSettings.defaultPanelsBackgroundColor = Color.create 249, 249, 249 WorldMorph.preferencesAndSettings.defaultPanelsStrokeColor = Color.create 198, 198, 198 @setPattern nil, nil, "dots" @changed() getNextUntitledShortcutName: -> name = "Untitled" if @howManyUntitledShortcuts > 0 name += " " + (@howManyUntitledShortcuts + 1) @howManyUntitledShortcuts++ return name getNextUntitledFolderShortcutName: -> name = "new folder" if @howManyUntitledFoldersShortcuts > 0 name += " " + (@howManyUntitledFoldersShortcuts + 1) @howManyUntitledFoldersShortcuts++ return name wantsDropOf: (aWdgt) -> return @_acceptsDrops makeNewConnectionsCalculationToken: -> # not nice to read but this means: # first increment and then return the value # this is so the first token we use is 1 # and we can initialise all input/node tokens to 0 # so to make them receptive to the first token generated ++@lastUsedConnectionsCalculationToken createErrorConsole: -> errorsLogViewerMorph = new ErrorsLogViewerMorph "Errors", @, "modifyCodeToBeInjected", "" wm = new WindowWdgt nil, nil, errorsLogViewerMorph wm.setExtent new Point 460, 400 @add wm @errorConsole = wm @errorConsole.fullMoveTo new Point 190,10 @errorConsole.setExtent new Point 550,415 @errorConsole.hide() removeSpinnerAndFakeDesktop: -> # remove the fake desktop for quick launch and the spinner spinner = document.getElementById 'spinner' spinner.parentNode.removeChild spinner splashScreenFakeDesktop = document.getElementById 'splashScreenFakeDesktop' splashScreenFakeDesktop.parentNode.removeChild splashScreenFakeDesktop createDesktop: -> @setColor Color.create 244,243,244 @makePrettier() acm = new AnalogClockWdgt acm.rawSetExtent new Point 80, 80 acm.fullRawMoveTo new Point @right()-80-@desktopSidesPadding, @top() + @desktopSidesPadding @add acm menusHelper.createWelcomeMessageWindowAndShortcut() menusHelper.createHowToSaveMessageOpener() menusHelper.basementIconAndText() menusHelper.createSimpleDocumentLauncher() menusHelper.createFizzyPaintLauncher() menusHelper.createSimpleSlideLauncher() menusHelper.createDashboardsLauncher() menusHelper.createPatchProgrammingLauncher() menusHelper.createGenericPanelLauncher() menusHelper.createToolbarsOpener() exampleDocsFolder = @makeFolder nil, nil, "examples" menusHelper.createDegreesConverterOpener exampleDocsFolder menusHelper.createSampleSlideOpener exampleDocsFolder menusHelper.createSampleDashboardOpener exampleDocsFolder menusHelper.createSampleDocOpener exampleDocsFolder # »>> this part is excluded from the fizzygum homepage build getParameterPassedInURL: (name) -> name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]') regex = new RegExp '[\\?&]' + name + '=([^&#]*)' results = regex.exec location.search if results? return decodeURIComponent results[1].replace(/\+/g, ' ') else return nil # some test urls: # this one contains two actions, two tests each, but only # the second test is run for the second group. # file:///Users/daviddellacasa/Fizzygum/Fizzygum-builds/latest/worldWithSystemTestHarness.html?startupActions=%7B%0D%0A++%22paramsVersion%22%3A+0.1%2C%0D%0A++%22actions%22%3A+%5B%0D%0A++++%7B%0D%0A++++++%22name%22%3A+%22runTests%22%2C%0D%0A++++++%22testsToRun%22%3A+%5B%22bubble%22%5D%0D%0A++++%7D%2C%0D%0A++++%7B%0D%0A++++++%22name%22%3A+%22runTests%22%2C%0D%0A++++++%22testsToRun%22%3A+%5B%22shadow%22%2C+%22SystemTest_basicResize%22%5D%2C%0D%0A++++++%22numberOfGroups%22%3A+2%2C%0D%0A++++++%22groupToBeRun%22%3A+1%0D%0A++++%7D++%5D%0D%0A%7D # # just one simple quick test about shadows #file:///Users/daviddellacasa/Fizzygum/Fizzygum-builds/latest/worldWithSystemTestHarness.html?startupActions=%7B%0A%20%20%22paramsVersion%22%3A%200.1%2C%0A%20%20%22actions%22%3A%20%5B%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%22name%22%3A%20%22runTests%22%2C%0A%20%20%20%20%20%20%22testsToRun%22%3A%20%5B%22shadow%22%5D%0A%20%20%20%20%7D%0A%20%20%5D%0A%7D nextStartupAction: -> if (@getParameterPassedInURL "startupActions")? startupActions = JSON.parse @getParameterPassedInURL "startupActions" if (!startupActions?) or (WorldMorph.ongoingUrlActionNumber == startupActions.actions.length) WorldMorph.ongoingUrlActionNumber = 0 if Automator? if window.location.href.includes("worldWithSystemTestHarness") if @automator.atLeastOneTestHasBeenRun if @automator.allTestsPassedSoFar document.getElementById("background").style.background = Color.GREEN.toString() return if !@isIndexPage then console.log "nextStartupAction " + (WorldMorph.ongoingUrlActionNumber+1) + " / " + startupActions.actions.length currentAction = startupActions.actions[WorldMorph.ongoingUrlActionNumber] if Automator? and currentAction.name == "runTests" @automator.loader.selectTestsFromTagsOrTestNames(currentAction.testsToRun) if currentAction.numberOfGroups? @automator.numberOfGroups = currentAction.numberOfGroups else @automator.numberOfGroups = 1 if currentAction.groupToBeRun? @automator.groupToBeRun = currentAction.groupToBeRun else @automator.groupToBeRun = 0 if currentAction.forceSlowTestPlaying? @automator.forceSlowTestPlaying = true if currentAction.forceTurbo? @automator.forceTurbo = true if currentAction.forceSkippingInBetweenMouseMoves? @automator.forceSkippingInBetweenMouseMoves = true if currentAction.forceRunningInBetweenMouseMoves? @automator.forceRunningInBetweenMouseMoves = true @automator.player.runAllSystemTests() WorldMorph.ongoingUrlActionNumber++ getMorphViaTextLabel: ([textDescription, occurrenceNumber, numberOfOccurrences]) -> allCandidateMorphsWithSameTextDescription = @allChildrenTopToBottomSuchThat (m) -> m.getTextDescription() == textDescription return allCandidateMorphsWithSameTextDescription[occurrenceNumber] # this part is excluded from the fizzygum homepage build <<« mostRecentlyCreatedPopUp: -> mostRecentPopUp = nil mostRecentPopUpID = -1 # we have to check which menus # are actually open, because # the destroy() function used # everywhere is not recursive and # that's where we update the @openPopUps # set so we have to doublecheck here @openPopUps.forEach (eachPopUp) => if eachPopUp.isOrphan() @openPopUps.delete eachPopUp else if eachPopUp.instanceNumericID >= mostRecentPopUpID mostRecentPopUp = eachPopUp return mostRecentPopUp # »>> this part is excluded from the fizzygum homepage build # see roundNumericIDsToNextThousand method in # Widget for an explanation of why we need this # method. alignIDsOfNextMorphsInSystemTests: -> if Automator? and Automator.state != Automator.IDLE # Check which objects end with the word Widget theWordMorph = "Morph" theWordWdgt = "Wdgt" theWordWidget = "Widget" listOfMorphsClasses = (Object.keys(window)).filter (i) -> i.includes(theWordMorph, i.length - theWordMorph.length) or i.includes(theWordWdgt, i.length - theWordWdgt.length) or i.includes(theWordWidget, i.length - theWordWidget.length) for eachMorphClass in listOfMorphsClasses #console.log "bumping up ID of class: " + eachMorphClass window[eachMorphClass].roundNumericIDsToNextThousand?() # this part is excluded from the fizzygum homepage build <<« # used to close temporary menus closePopUpsMarkedForClosure: -> @popUpsMarkedForClosure.forEach (eachMorph) => eachMorph.close() @popUpsMarkedForClosure.clear() # »>> this part is excluded from the fizzygum homepage build # World Widget broken rects debugging # currently unused brokenFor: (aWdgt) -> # private fb = aWdgt.fullBounds() @broken.filter (rect) -> rect.isIntersecting fb # this part is excluded from the fizzygum homepage build <<« # fullPaintIntoAreaOrBlitFromBackBuffer results into actual painting of pieces of # morphs done # by the paintIntoAreaOrBlitFromBackBuffer function. # The paintIntoAreaOrBlitFromBackBuffer function is defined in Widget. fullPaintIntoAreaOrBlitFromBackBuffer: (aContext, aRect) -> # invokes the Widget's fullPaintIntoAreaOrBlitFromBackBuffer, which has only three implementations: # * the default one by Widget which just invokes the paintIntoAreaOrBlitFromBackBuffer of all children # * the interesting one in PanelWdgt which a) narrows the dirty # rectangle (intersecting it with its border # since the PanelWdgt clips at its border) and b) stops recursion on all # the children that are outside such intersection. # * this implementation which just takes into account that the hand # (which could contain a Widget being floatDragged) # is painted on top of everything. super aContext, aRect # the mouse cursor is always drawn on top of everything # and it's not attached to the WorldMorph. @hand.fullPaintIntoAreaOrBlitFromBackBuffer aContext, aRect clippedThroughBounds: -> @checkClippedThroughBoundsCache = WorldMorph.numberOfAddsAndRemoves + "-" + WorldMorph.numberOfVisibilityFlagsChanges + "-" + WorldMorph.numberOfCollapseFlagsChanges + "-" + WorldMorph.numberOfRawMovesAndResizes @clippedThroughBoundsCache = @boundingBox() return @clippedThroughBoundsCache # using the code coverage tool from Chrome, it # doesn't seem that this is ever used # TODO investigate and see whether this is needed clipThrough: -> @checkClipThroughCache = WorldMorph.numberOfAddsAndRemoves + "-" + WorldMorph.numberOfVisibilityFlagsChanges + "-" + WorldMorph.numberOfCollapseFlagsChanges + "-" + WorldMorph.numberOfRawMovesAndResizes @clipThroughCache = @boundingBox() return @clipThroughCache pushBrokenRect: (brokenMorph, theRect, isSrc) -> if @duplicatedBrokenRectsTracker[theRect.toString()]? @numberOfDuplicatedBrokenRects++ else if isSrc brokenMorph.srcBrokenRect = @broken.length else brokenMorph.dstBrokenRect = @broken.length if !theRect? debugger # if @broken.length == 0 # debugger @broken.push theRect @duplicatedBrokenRectsTracker[theRect.toString()] = true # using the code coverage tool from Chrome, it # doesn't seem that this is ever used # TODO investigate and see whether this is needed mergeBrokenRectsIfCloseOrPushBoth: (brokenMorph, sourceBroken, destinationBroken) -> mergedBrokenRect = sourceBroken.merge destinationBroken mergedBrokenRectArea = mergedBrokenRect.area() sumArea = sourceBroken.area() + destinationBroken.area() #console.log "mergedBrokenRectArea: " + mergedBrokenRectArea + " (sumArea + sumArea/10): " + (sumArea + sumArea/10) if mergedBrokenRectArea < sumArea + sumArea/10 @pushBrokenRect brokenMorph, mergedBrokenRect, true @numberOfMergedSourceAndDestination++ else @pushBrokenRect brokenMorph, sourceBroken, true @pushBrokenRect brokenMorph, destinationBroken, false checkARectWithHierarchy: (aRect, brokenMorph, isSrc) -> brokenMorphAncestor = brokenMorph #if brokenMorph instanceof SliderMorph # debugger while brokenMorphAncestor.parent? brokenMorphAncestor = brokenMorphAncestor.parent if brokenMorphAncestor.srcBrokenRect? if !@broken[brokenMorphAncestor.srcBrokenRect]? debugger if @broken[brokenMorphAncestor.srcBrokenRect].containsRectangle aRect if isSrc @broken[brokenMorph.srcBrokenRect] = nil brokenMorph.srcBrokenRect = nil else @broken[brokenMorph.dstBrokenRect] = nil brokenMorph.dstBrokenRect = nil else if aRect.containsRectangle @broken[brokenMorphAncestor.srcBrokenRect] @broken[brokenMorphAncestor.srcBrokenRect] = nil brokenMorphAncestor.srcBrokenRect = nil if brokenMorphAncestor.dstBrokenRect? if !@broken[brokenMorphAncestor.dstBrokenRect]? debugger if @broken[brokenMorphAncestor.dstBrokenRect].containsRectangle aRect if isSrc @broken[brokenMorph.srcBrokenRect] = nil brokenMorph.srcBrokenRect = nil else @broken[brokenMorph.dstBrokenRect] = nil brokenMorph.dstBrokenRect = nil else if aRect.containsRectangle @broken[brokenMorphAncestor.dstBrokenRect] @broken[brokenMorphAncestor.dstBrokenRect] = nil brokenMorphAncestor.dstBrokenRect = nil rectAlreadyIncludedInParentBrokenMorph: -> for brokenMorph in @morphsThatMaybeChangedGeometryOrPosition if brokenMorph.srcBrokenRect? aRect = @broken[brokenMorph.srcBrokenRect] @checkARectWithHierarchy aRect, brokenMorph, true if brokenMorph.dstBrokenRect? aRect = @broken[brokenMorph.dstBrokenRect] @checkARectWithHierarchy aRect, brokenMorph, false for brokenMorph in @morphsThatMaybeChangedFullGeometryOrPosition if brokenMorph.srcBrokenRect? aRect = @broken[brokenMorph.srcBrokenRect] @checkARectWithHierarchy aRect, brokenMorph if brokenMorph.dstBrokenRect? aRect = @broken[brokenMorph.dstBrokenRect] @checkARectWithHierarchy aRect, brokenMorph cleanupSrcAndDestRectsOfMorphs: -> for brokenMorph in @morphsThatMaybeChangedGeometryOrPosition brokenMorph.srcBrokenRect = nil brokenMorph.dstBrokenRect = nil for brokenMorph in @morphsThatMaybeChangedFullGeometryOrPosition brokenMorph.srcBrokenRect = nil brokenMorph.dstBrokenRect = nil fleshOutBroken: -> #if @morphsThatMaybeChangedGeometryOrPosition.length > 0 # debugger sourceBroken = nil destinationBroken = nil for brokenMorph in @morphsThatMaybeChangedGeometryOrPosition # let's see if this Widget that marked itself as broken # was actually painted in the past frame. # If it was then we have to clean up the "before" area # even if the Widget is not visible anymore if brokenMorph.clippedBoundsWhenLastPainted? if brokenMorph.clippedBoundsWhenLastPainted.isNotEmpty() sourceBroken = brokenMorph.clippedBoundsWhenLastPainted.expandBy(1).growBy @maxShadowSize #if brokenMorph!= world and (brokenMorph.clippedBoundsWhenLastPainted.containsPoint (new Point(10,10))) # debugger # for the "destination" broken rectangle we can actually # check whether the Widget is still visible because we # can skip the destination rectangle in that case # (not the source one!) unless brokenMorph.surelyNotShowingUpOnScreenBasedOnVisibilityCollapseAndOrphanage() # @clippedThroughBounds() should be smaller area # than bounds because it clips # the bounds based on the clipping morphs up the # hierarchy boundsToBeChanged = brokenMorph.clippedThroughBounds() if boundsToBeChanged.isNotEmpty() destinationBroken = boundsToBeChanged.spread().expandBy(1).growBy @maxShadowSize #if brokenMorph!= world and (boundsToBeChanged.spread().containsPoint new Point 10, 10) # debugger if sourceBroken? and destinationBroken? @mergeBrokenRectsIfCloseOrPushBoth brokenMorph, sourceBroken, destinationBroken else if sourceBroken? or destinationBroken? if sourceBroken? @pushBrokenRect brokenMorph, sourceBroken, true else @pushBrokenRect brokenMorph, destinationBroken, true brokenMorph.geometryOrPositionPossiblyChanged = false brokenMorph.clippedBoundsWhenLastPainted = nil fleshOutFullBroken: -> #if @morphsThatMaybeChangedFullGeometryOrPosition.length > 0 # debugger sourceBroken = nil destinationBroken = nil for brokenMorph in @morphsThatMaybeChangedFullGeometryOrPosition #console.log "fleshOutFullBroken: " + brokenMorph if brokenMorph.fullClippedBoundsWhenLastPainted? if brokenMorph.fullClippedBoundsWhenLastPainted.isNotEmpty() sourceBroken = brokenMorph.fullClippedBoundsWhenLastPainted.expandBy(1).growBy @maxShadowSize # for the "destination" broken rectangle we can actually # check whether the Widget is still visible because we # can skip the destination rectangle in that case # (not the source one!) unless brokenMorph.surelyNotShowingUpOnScreenBasedOnVisibilityCollapseAndOrphanage() boundsToBeChanged = brokenMorph.fullClippedBounds() if boundsToBeChanged.isNotEmpty() destinationBroken = boundsToBeChanged.spread().expandBy(1).growBy @maxShadowSize #if brokenMorph!= world and (boundsToBeChanged.spread().containsPoint (new Point(10,10))) # debugger if sourceBroken? and destinationBroken? @mergeBrokenRectsIfCloseOrPushBoth brokenMorph, sourceBroken, destinationBroken else if sourceBroken? or destinationBroken? if sourceBroken? @pushBrokenRect brokenMorph, sourceBroken, true else @pushBrokenRect brokenMorph, destinationBroken, true brokenMorph.fullGeometryOrPositionPossiblyChanged = false brokenMorph.fullClippedBoundsWhenLastPainted = nil # »>> this part is excluded from the fizzygum homepage build showBrokenRects: (aContext) -> aContext.save() aContext.globalAlpha = 0.5 aContext.useLogicalPixelsUntilRestore() for eachBrokenRect in @broken if eachBrokenRect? randomR = Math.round Math.random() * 255 randomG = Math.round Math.random() * 255 randomB = Math.round Math.random() * 255 aContext.fillStyle = "rgb("+randomR+","+randomG+","+randomB+")" aContext.fillRect Math.round(eachBrokenRect.origin.x), Math.round(eachBrokenRect.origin.y), Math.round(eachBrokenRect.width()), Math.round(eachBrokenRect.height()) aContext.restore() # this part is excluded from the fizzygum homepage build <<« # layouts are recalculated like so: # there will be several subtrees # that will need relayout. # So take the head of any subtree and re-layout it # The relayout might or might not visit all the subnodes # of the subtree, because you might have a subtree # that lives inside a floating morph, in which # case it's not re-layout. # So, a subtree might not be healed in one go, # rather we keep track of what's left to heal and # we apply the same process: we heal from the head node # and take out of the list what's healed in that step, # and we continue doing so until there is nothing else # to heal. recalculateLayouts: -> until @morphsThatMaybeChangedLayout.length == 0 # find the first Widget which has a broken layout, # take out of queue all the others loop tryThisMorph = @morphsThatMaybeChangedLayout[@morphsThatMaybeChangedLayout.length - 1] if tryThisMorph.layoutIsValid @morphsThatMaybeChangedLayout.pop() if @morphsThatMaybeChangedLayout.length == 0 return else break # now that you have a Widget with a broken layout # go up the chain of broken layouts as much as # possible # QUESTION: would it be safer instead to start from the # very top invalid morph, i.e. on the way to the top, # stop at the last morph with an invalid layout # instead of stopping at the first morph with a # valid layout... while tryThisMorph.parent? if tryThisMorph.layoutSpec == LayoutSpec.ATTACHEDAS_FREEFLOATING or tryThisMorph.parent.layoutIsValid break tryThisMorph = tryThisMorph.parent try # so now you have a "top" element up a chain # of morphs with broken layout. Go do a # doLayout on it, so it might fix a bunch of those # on the chain (but not all) tryThisMorph.doLayout() catch err @softResetWorld() if !@errorConsole? then @createErrorConsole() @errorConsole.contents.showUpWithError err clearGeometryOrPositionPossiblyChangedFlags: -> for m in @morphsThatMaybeChangedGeometryOrPosition m.geometryOrPositionPossiblyChanged = false clearFullGeometryOrPositionPossiblyChangedFlags: -> for m in @morphsThatMaybeChangedFullGeometryOrPosition m.fullGeometryOrPositionPossiblyChanged = false disableTrackChanges: -> @trackChanges.push false maybeEnableTrackChanges: -> @trackChanges.pop() updateBroken: -> #console.log "number of broken rectangles: " + @broken.length @broken = [] @duplicatedBrokenRectsTracker = {} @numberOfDuplicatedBrokenRects = 0 @numberOfMergedSourceAndDestination = 0 @fleshOutFullBroken() @fleshOutBroken() @rectAlreadyIncludedInParentBrokenMorph() @cleanupSrcAndDestRectsOfMorphs() @clearGeometryOrPositionPossiblyChangedFlags() @clearFullGeometryOrPositionPossiblyChangedFlags() @morphsThatMaybeChangedGeometryOrPosition = [] @morphsThatMaybeChangedFullGeometryOrPosition = [] # »>> this part is excluded from the fizzygum homepage build #ProfilingDataCollector.profileBrokenRects @broken, @numberOfDuplicatedBrokenRects, @numberOfMergedSourceAndDestination # this part is excluded from the fizzygum homepage build <<« # each broken rectangle requires traversing the scenegraph to # redraw what's overlapping it. Not all Widgets are traversed # in particular the following can stop the recursion: # - invisible Widgets # - PanelWdgts that don't overlap the broken rectangle # Since potentially there is a lot of traversal ongoing for # each broken rectangle, one might want to consolidate overlapping # and nearby rectangles. @healingRectanglesPhase = true @errorsWhileRepainting = [] @broken.forEach (rect) => if !rect? return if rect.isNotEmpty() try @fullPaintIntoAreaOrBlitFromBackBuffer @worldCanvasContext, rect catch err @resetWorldCanvasContext() @queueErrorForLaterReporting err @hideOffendingWidget() @softResetWorld() # IF we got errors while repainting, the # screen might be in a bad state (because everything in front of the # "bad" widget is not repainted since the offending widget has # thrown, so nothing in front of it could be painted properly) # SO do COMPLETE repaints of the screen and hide # further offending widgets until there are no more errors # (i.e. the offending widgets are progressively hidden so eventually # we should repaint the whole screen without errors, hopefully) if @errorsWhileRepainting.length != 0 @findOutAllOtherOffendingWidgetsAndPaintWholeScreen() if @showRedraws @showBrokenRects @worldCanvasContext @resetDataStructuresForBrokenRects() @healingRectanglesPhase = false if @trackChanges.length != 1 and @trackChanges[0] != true alert "trackChanges array should have only one element (true)" findOutAllOtherOffendingWidgetsAndPaintWholeScreen: -> # we keep repainting the whole screen until there are no # errors. # Why do we need multiple repaints and not just one? # Because remember that when a widget throws an error while # repainting, it bubble all the way up and stops any # further repainting of the other widgets, potentially # preventing the finding of errors in the other # widgets. Hence, we need to keep repainting until # there are no errors. currentErrorsCount = @errorsWhileRepainting.length previousErrorsCount = nil numberOfTotalRepaints = 0 until previousErrorsCount == currentErrorsCount numberOfTotalRepaints++ try @fullPaintIntoAreaOrBlitFromBackBuffer @worldCanvasContext, @bounds catch err @resetWorldCanvasContext() @queueErrorForLaterReporting err @hideOffendingWidget() @softResetWorld() previousErrorsCount = currentErrorsCount currentErrorsCount = @errorsWhileRepainting.length #console.log "total repaints: " + numberOfTotalRepaints resetWorldCanvasContext: -> # when an error is thrown while painting, it's # possible that we are left with a context in a strange # mixed state, so try to bring it back to # normality as much as possible # We are doing this for "cleanliness" of the context # state, not because we care of the drawing being # perfect (we are eventually going to repaint the # whole screen without the offending widgets) @worldCanvasContext.closePath() @worldCanvasContext.resetTransform?() for j in [1...2000] @worldCanvasContext.restore() queueErrorForLaterReporting: (err) -> # now record the error so we can report it in the # next cycle, and add the offending widget to a # "banned" list @errorsWhileRepainting.push err if !@widgetsGivingErrorWhileRepainting.includes @paintingWidget @widgetsGivingErrorWhileRepainting.push @paintingWidget @paintingWidget.silentHide() hideOffendingWidget: -> if !@widgetsGivingErrorWhileRepainting.includes @paintingWidget @widgetsGivingErrorWhileRepainting.push @paintingWidget @paintingWidget.silentHide() resetDataStructuresForBrokenRects: -> @broken = [] @duplicatedBrokenRectsTracker = {} @numberOfDuplicatedBrokenRects = 0 @numberOfMergedSourceAndDestination = 0 # »>> this part is excluded from the fizzygum homepage build addPinoutingMorphs: -> @currentPinoutingMorphs.forEach (eachPinoutingMorph) => if @morphsToBePinouted.has eachPinoutingMorph.wdgtThisWdgtIsPinouting if eachPinoutingMorph.wdgtThisWdgtIsPinouting.hasMaybeChangedGeometryOrPosition() # reposition the pinout morph if needed peekThroughBox = eachPinoutingMorph.wdgtThisWdgtIsPinouting.clippedThroughBounds() eachPinoutingMorph.fullRawMoveTo new Point(peekThroughBox.right() + 10,peekThroughBox.top()) else @currentPinoutingMorphs.delete eachPinoutingMorph @morphsBeingPinouted.delete eachPinoutingMorph.wdgtThisWdgtIsPinouting eachPinoutingMorph.wdgtThisWdgtIsPinouting = nil eachPinoutingMorph.fullDestroy() @morphsToBePinouted.forEach (eachMorphNeedingPinout) => unless @morphsBeingPinouted.has eachMorphNeedingPinout hM = new StringMorph2 eachMorphNeedingPinout.toString() @add hM hM.wdgtThisWdgtIsPinouting = eachMorphNeedingPinout peekThroughBox = eachMorphNeedingPinout.clippedThroughBounds() hM.fullRawMoveTo new Point(peekThroughBox.right() + 10,peekThroughBox.top()) hM.setColor Color.BLUE hM.setWidth 400 @currentPinoutingMorphs.add hM @morphsBeingPinouted.add eachMorphNeedingPinout # this part is excluded from the fizzygum homepage build <<« addHighlightingMorphs: -> @currentHighlightingMorphs.forEach (eachHighlightingMorph) => if @morphsToBeHighlighted.has eachHighlightingMorph.wdgtThisWdgtIsHighlighting if eachHighlightingMorph.wdgtThisWdgtIsHighlighting.hasMaybeChangedGeometryOrPosition() eachHighlightingMorph.rawSetBounds eachHighlightingMorph.wdgtThisWdgtIsHighlighting.clippedThroughBounds() else @currentHighlightingMorphs.delete eachHighlightingMorph @morphsBeingHighlighted.delete eachHighlightingMorph.wdgtThisWdgtIsHighlighting eachHighlightingMorph.wdgtThisWdgtIsHighlighting = nil eachHighlightingMorph.fullDestroy() @morphsToBeHighlighted.forEach (eachMorphNeedingHighlight) => unless @morphsBeingHighlighted.has eachMorphNeedingHighlight hM = new HighlighterMorph @add hM hM.wdgtThisWdgtIsHighlighting = eachMorphNeedingHighlight hM.rawSetBounds eachMorphNeedingHighlight.clippedThroughBounds() hM.setColor Color.BLUE hM.setAlphaScaled 50 @currentHighlightingMorphs.add hM @morphsBeingHighlighted.add eachMorphNeedingHighlight # »>> this part is only needed for Macros progressOnMacroSteps: -> noCodeLoading: -> true noInputsOngoing: -> @eventsQueue.length == 0 # other useful tween functions here: # https://github.com/ashblue/simple-tween-js/blob/master/tween.js expoOut: (i, origin, distance, numberOfEvents) -> distance * (-Math.pow(2, -10 * i/numberOfEvents) + 1) + origin bringUpTestMenu: (millisecondsBetweenKeys = 35, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> @syntheticEventsShortcutsAndSpecialKeys "F2", millisecondsBetweenKeys, startTime syntheticEventsShortcutsAndSpecialKeys: (whichShortcutOrSpecialKey, millisecondsBetweenKeys = 35, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> switch whichShortcutOrSpecialKey when "F2" @eventsQueue.push new KeydownInputEvent "F2", "F2", false, false, false, false, true, startTime @eventsQueue.push new KeyupInputEvent "F2", "F2", false, false, false, false, true, startTime + millisecondsBetweenKeys syntheticEventsStringKeys: (theString, millisecondsBetweenKeys = 35, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> scheduledTimeOfEvent = startTime for i in [0...theString.length] isUpperCase = theString.charAt(i) == theString.charAt(i).toUpperCase() if isUpperCase @eventsQueue.push new KeydownInputEvent "Shift", "ShiftLeft", true, false, false, false, true, scheduledTimeOfEvent scheduledTimeOfEvent += millisecondsBetweenKeys # note that the second parameter (code) we are making up, assuming a hypothetical "1:1" key->code layout @eventsQueue.push new KeydownInputEvent theString.charAt(i), theString.charAt(i), isUpperCase, false, false, false, true, scheduledTimeOfEvent scheduledTimeOfEvent += millisecondsBetweenKeys # note that the second parameter (code) we are making up, assuming a hypothetical "1:1" key->code layout @eventsQueue.push new KeyupInputEvent theString.charAt(i), theString.charAt(i), isUpperCase, false, false, false, true, scheduledTimeOfEvent scheduledTimeOfEvent += millisecondsBetweenKeys if isUpperCase @eventsQueue.push new KeyupInputEvent "Shift", "ShiftLeft", false, false, false, false, true, scheduledTimeOfEvent scheduledTimeOfEvent += millisecondsBetweenKeys syntheticEventsMouseMovePressDragRelease: (orig, dest, millisecondsForDrag = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime(), numberOfEventsPerMillisecond = 1) -> @syntheticEventsMouseMove orig, "left button", 100, nil, startTime, numberOfEventsPerMillisecond @syntheticEventsMouseDown "left button", startTime + 100 @syntheticEventsMouseMove dest, "left button", millisecondsForDrag, orig, startTime + 100 + 100, numberOfEventsPerMillisecond @syntheticEventsMouseUp "left button", startTime + 100 + 100 + millisecondsForDrag + 100 # This should be used if you want to drag from point A to B to C ... # If rather you want to just drag from point A to point B, # then just use syntheticEventsMouseMovePressDragRelease syntheticEventsMouseMoveWhileDragging: (dest, milliseconds = 1000, orig = @hand.position(), startTime = WorldMorph.dateOfCurrentCycleStart.getTime(), numberOfEventsPerMillisecond = 1) -> @syntheticEventsMouseMove dest, "left button", milliseconds, orig, startTime, numberOfEventsPerMillisecond # mouse moves need an origin and a destination, so we # need to place the mouse in _some_ place to begin with # in order to do that. syntheticEventsMousePlace: (place = new Point(0,0), scheduledTimeOfEvent = WorldMorph.dateOfCurrentCycleStart.getTime()) -> @eventsQueue.push new MousemoveInputEvent place.x, place.y, 0, 0, false, false, false, false, true, scheduledTimeOfEvent syntheticEventsMouseMove: (dest, whichButton = "no button", milliseconds = 1000, orig = @hand.position(), startTime = WorldMorph.dateOfCurrentCycleStart.getTime(), numberOfEventsPerMillisecond = 1) -> if whichButton == "left button" button = 0 buttons = 1 else if whichButton == "no button" button = 0 buttons = 0 else if whichButton == "right button" button = 0 buttons = 2 else debugger throw "syntheticEventsMouseMove: whichButton is unknown" if dest instanceof Widget dest = dest.center() if orig instanceof Widget orig = orig.center() numberOfEvents = milliseconds * numberOfEventsPerMillisecond for i in [0...numberOfEvents] scheduledTimeOfEvent = startTime + i/numberOfEventsPerMillisecond nextX = Math.round @expoOut i, orig.x, (dest.x-orig.x), numberOfEvents nextY = Math.round @expoOut i, orig.y, (dest.y-orig.y), numberOfEvents if nextX != prevX or nextY != prevY prevX = nextX prevY = nextY #console.log nextX + " " + nextY + " scheduled at: " + scheduledTimeOfEvent @eventsQueue.push new MousemoveInputEvent nextX, nextY, button, buttons, false, false, false, false, true, scheduledTimeOfEvent syntheticEventsMouseClick: (whichButton = "left button", milliseconds = 100, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> @syntheticEventsMouseDown whichButton, startTime @syntheticEventsMouseUp whichButton, startTime + milliseconds syntheticEventsMouseDown: (whichButton = "left button", startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> if whichButton == "left button" button = 0 buttons = 1 else if whichButton == "right button" button = 2 buttons = 2 else debugger throw "syntheticEventsMouseDown: whichButton is unknown" @eventsQueue.push new MousedownInputEvent button, buttons, false, false, false, false, true, startTime syntheticEventsMouseUp: (whichButton = "left button", startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> if whichButton == "left button" button = 0 buttons = 0 else if whichButton == "right button" button = 2 buttons = 0 else debugger throw "syntheticEventsMouseUp: whichButton is unknown" @eventsQueue.push new MouseupInputEvent button, buttons, false, false, false, false, true, startTime moveToAndClick: (positionOrWidget, whichButton = "left button", milliseconds = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> @syntheticEventsMouseMove positionOrWidget, "no button", milliseconds, nil, startTime, nil @syntheticEventsMouseClick whichButton, 100, startTime + milliseconds + 100 openMenuOf: (widget, milliseconds = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> @moveToAndClick widget, "right button", milliseconds, startTime getMostRecentlyOpenedMenu: -> # gets the last element added to the "freshlyCreatedPopUps" set # (Sets keep order of insertion) Array.from(@freshlyCreatedPopUps).pop() getTextMenuItemFromMenu: (theMenu, theLabel) -> theMenu.topWdgtSuchThat (item) -> if item.labelString? item.labelString == theLabel else false moveToItemOfTopMenuAndClick: (theLabel) -> theMenu = @getMostRecentlyOpenedMenu() theItem = @getTextMenuItemFromMenu theMenu, theLabel @moveToAndClick theItem findTopWidgetByClassNameOrClass: (widgetNameOrClass) -> if typeof widgetNameOrClass == "string" @topWdgtSuchThat (item) -> item.morphClassString() == "AnalogClockWdgt" else @topWdgtSuchThat (item) -> item instanceof widgetNameOrClass calculateVertBarMovement: (vBar, index, total) -> vBarHandle = vBar.children[0] vBarHandleCenter = vBarHandle.center() highestHandlePosition = vBar.top() lowestHandlePosition = vBar.bottom() - vBarHandle.height() highestHandleCenterPosition = highestHandlePosition + vBarHandle.height()/2 lowestHandleCenterPosition = lowestHandlePosition + vBarHandle.height()/2 handleCenterRange = lowestHandleCenterPosition - highestHandleCenterPosition handleCenterOffset = Math.round index * handleCenterRange / (total-1) [vBarHandleCenter, vBarHandleCenter.translateBy new Point(0,handleCenterOffset)] bringListItemFromTopInspectorInView: (listItemString) -> inspectorNaked = @findTopWidgetByClassNameOrClass InspectorMorph2 list = inspectorNaked.list elements = list.elements vBar = list.vBar index = elements.indexOf listItemString total = elements.length [vBarCenterFromHere, vBarCenterToHere] = @calculateVertBarMovement vBar, index, total @syntheticEventsMouseMovePressDragRelease vBarCenterFromHere, vBarCenterToHere clickOnListItemFromTopInspector: (listItemString, milliseconds = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> inspectorNaked = @findTopWidgetByClassNameOrClass InspectorMorph2 list = inspectorNaked.list entry = list.topWdgtSuchThat (item) -> if item.text? item.text == listItemString else false entryTopLeft = entry.topLeft() @moveToAndClick entryTopLeft.translateBy(new Point 10, 2), "left button", milliseconds, startTime clickOnCodeBoxFromTopInspectorAtCodeString: (codeString, occurrenceNumber = 1, after = true, milliseconds = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> inspectorNaked = @findTopWidgetByClassNameOrClass InspectorMorph2 slotCoords = inspectorNaked.textMorph.text.getNthPositionInStringBeforeOrAfter codeString, occurrenceNumber, after clickPosition = inspectorNaked.textMorph.slotCoordinates(slotCoords).translateBy new Point 3,3 @moveToAndClick clickPosition, "left button", milliseconds, startTime clickOnSaveButtonFromTopInspector: (milliseconds = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> inspectorNaked = @findTopWidgetByClassNameOrClass InspectorMorph2 saveButton = inspectorNaked.saveButton @moveToAndClick saveButton, "left button", milliseconds, startTime bringcodeStringFromTopInspectorInView: (codeString, occurrenceNumber = 1, after = true) -> inspectorNaked = @findTopWidgetByClassNameOrClass InspectorMorph2 slotCoords = inspectorNaked.textMorph.text.getNthPositionInStringBeforeOrAfter codeString, occurrenceNumber, after textScrollPane = inspectorNaked.topWdgtSuchThat (item) -> item.morphClassString() == "SimplePlainTextScrollPanelWdgt" textMorph = inspectorNaked.textMorph vBar = textScrollPane.vBar index = textMorph.slotRowAndColumn(slotCoords)[0] total = textMorph.wrappedLines.length [vBarCenterFromHere, vBarCenterToHere] = @calculateVertBarMovement vBar, index, total @syntheticEventsMouseMovePressDragRelease vBarCenterFromHere, vBarCenterToHere draftRunMacro: -> # When does it make sense to generate events "just via functions" vs. # needing a macro? # # **Important Note:** a macro can call functions, while functions # can never include macros!!! # # A macro is needed: # 1. for generating (potentially via functions!) events spanning # multiple cycles. E.g. "opening the inspector for a widget", # which involves moving the mouse there, right-clicking on # the widget, wait a cycle for the menu to come up, then # navigating other menus, until finally finding and # clicking on a "inspect" entry, # and finally waiting a cycle for the inspector to come up. # Those things *together* can't be done using functions alone # (i.e. with no macros), because functions can only push # synthetic events (now or in the future) all at once. # 2. so to have a convenient way to specify pauses between # events. This could also be done with functions, however # it's more convoluted. # # For all other cases, macros are not needed, i.e. functions alone # can suffice. Note that # functions *can* specify events that # happen over time e.g. multiple key strokes and events # happening over a few seconds, as there are parameters that help # to specify dates of events in the future. As mentioned though, # functions alone cannot "see past the effects" of any event happening # in the future. # # Examples of macros (potentially using functions): # - opening a menu of a widget AND clicking on one of its items # - opening inspector for a widget # - opening inspector for a widget, changing a method, then # clicking "save" # # Examples that don't need macros (functions alone are OK): # - moving an icon to the bin # - closing the top window # - opening the menu of a widget # - moving pointer to entry of top menu and clicking it macroSubroutines = new Set macroSubroutines.add Macro.fromString """ Macro bringUpInspector whichWidget ⤷clickMenuItemOfWidget whichWidget | "dev ➜" ▶ when no inputs ongoing @moveToItemOfTopMenuAndClick "inspect" """ macroSubroutines.add Macro.fromString """ Macro bringUpInspectorAndSelectListItem whichWidget | whichItem ⤷bringUpInspector whichWidget ▶ when no inputs ongoing ⤷bringInViewAndClickOnListItemFromTopInspector whichItem """ macroSubroutines.add Macro.fromString """ Macro bringInViewAndClickOnListItemFromTopInspector whichItem @bringListItemFromTopInspectorInView whichItem ▶ when no inputs ongoing @clickOnListItemFromTopInspector whichItem """ macroSubroutines.add Macro.fromString """ Macro clickMenuItemOfWidget whichWidget | whichItem @openMenuOf whichWidget ▶ when no inputs ongoing @moveToItemOfTopMenuAndClick whichItem """ macroSubroutines.add Macro.fromString """ Macro printoutsMacro string1 | string2 | string3 ▶ ⌛ 1s 🖨️ string1 ▶ ⌛ 1s 🖨️ string2 💼aLocalVariableInACall = "" ▶ ⌛ 1s 🖨️ string3 """ macroSubroutines.add Macro.fromString """ Macro macroWithNoParams 🖨️ "macro with no params" """ macroSubroutines.add Macro.fromString """ Macro macroWithOneParam theParameter 🖨️ "macro with one param: " + theParameter """ macroSubroutines.add Macro.fromString """ Macro macroWithOneParamButPassingNone theParameter 🖨️ "macro with one param but passing none, this should be undefined: " + theParameter """ macroSubroutines.add Macro.fromString """ Macro macroWithTwoParamsButPassingOnlyOne param1 | param2 🖨️ "macro with two params but passing only one: param 1: " + param1 + " param 2 should be undefined: " + param2 """ # TODO check that these are handled too # ▶ ⌛ 500 ms, when condition1() # ▶ # ⌛ 500 ms, when conditionCommented() mainMacro = Macro.fromString """ Macro theTestMacro @syntheticEventsStringKeys "SoMeThInG" ▶ ⌛ 1s ▶ ⤷printoutsMacro "first console out" | "second console out" | "third console out" ▶ ⌛ 1s 💼clock = @findTopWidgetByClassNameOrClass AnalogClockWdgt @syntheticEventsMouseMove 💼clock ▶ when no inputs ongoing @syntheticEventsMouseDown() ▶ when no inputs ongoing 💼clockCenter = 💼clock.center() @syntheticEventsMouseMoveWhileDragging ⦿(💼clockCenter.x - 4, 💼clockCenter.y + 4) ▶ ⌛ 1s @syntheticEventsMouseMoveWhileDragging ⦿(250,250) ▶ when no inputs ongoing @syntheticEventsMouseUp() ▶ when no inputs ongoing @syntheticEventsMouseMovePressDragRelease ⦿(5, 5), ⦿(200,200) ▶ when no inputs ongoing 🖨️ "finished the drag events" ⤷printoutsMacro "fourth console out" | "fifth console out" | "sixth console out" ▶ when no inputs ongoing ⤷bringUpInspectorAndSelectListItem 💼clock | "drawSecondsHand" ▶ when no inputs ongoing @bringcodeStringFromTopInspectorInView "context.restore()" ▶ when no inputs ongoing @clickOnCodeBoxFromTopInspectorAtCodeString "@secondsHandAngle", 1, false ▶ when no inputs ongoing @syntheticEventsStringKeys "-" @clickOnSaveButtonFromTopInspector() # some comments here ▶ when no inputs ongoing # also some comments here ⤷macroWithNoParams ⤷macroWithOneParam "here is the one param" ⤷macroWithOneParamButPassingNone ⤷macroWithTwoParamsButPassingOnlyOne "first parameter" ⤷macroWithNoParams # comment1 ⤷macroWithOneParam "here is the one param" # comment2 ⤷macroWithOneParamButPassingNone # comment3 ⤷macroWithTwoParamsButPassingOnlyOne "first parameter" # comment4 @bringUpTestMenu() """ mainMacro.linkTo macroSubroutines mainMacro.start() # this part is only needed for Macros <<« playQueuedEvents: -> try timeOfCurrentCycleStart = WorldMorph.dateOfCurrentCycleStart.getTime() for event in @eventsQueue if !event.time? then debugger # this happens when you consume synthetic events: you can inject # MANY of them across frames (say, a slow drag across the screen), # so you want to consume only the ones that pertain to the current # frame and return if event.time > timeOfCurrentCycleStart @eventsQueue.splice 0, @eventsQueue.indexOf(event) return # currently not handled: DOM virtual keyboard events event.processEvent() catch err @softResetWorld() if !@errorConsole? then @createErrorConsole() @errorConsole.contents.showUpWithError err @eventsQueue = [] # we keep the "pacing" promises in this # framePacedPromises array, (or, more precisely, # we keep their resolving functions) and each frame # we resolve one, so we don't cause gitter. progressFramePacedActions: -> if window.framePacedPromises.length > 0 resolvingFunction = window.framePacedPromises.shift() resolvingFunction.call() showErrorsHappenedInRepaintingStepInPreviousCycle: -> for eachErr in @errorsWhileRepainting if !@errorConsole? then @createErrorConsole() @errorConsole.contents.showUpWithError eachErr updateTimeReferences: -> WorldMorph.dateOfCurrentCycleStart = new Date if !WorldMorph.dateOfPreviousCycleStart? WorldMorph.dateOfPreviousCycleStart = new Date WorldMorph.dateOfCurrentCycleStart.getTime() - 30 # »>> this part is only needed for Macros if !@macroStepsWaitingTimer? @macroStepsWaitingTimer = 0 else @macroStepsWaitingTimer += WorldMorph.dateOfCurrentCycleStart.getTime() - WorldMorph.dateOfPreviousCycleStart.getTime() # this part is only needed for Macros <<« doOneCycle: -> @updateTimeReferences() #console.log TextMorph.instancesCounter + " " + StringMorph.instancesCounter @showErrorsHappenedInRepaintingStepInPreviousCycle() # »>> this part is only needed for Macros @progressOnMacroSteps() # this part is only needed for Macros <<« @playQueuedEvents() # replays test actions at the right time if AutomatorPlayer? and Automator.state == Automator.PLAYING @automator.player.replayTestCommands() # currently unused @runOtherTasksStepFunction() # used to load fizzygum sources progressively @progressFramePacedActions() @runChildrensStepFunction() @hand.reCheckMouseEntersAndMouseLeavesAfterPotentialGeometryChanges() window.recalculatingLayouts = true @recalculateLayouts() window.recalculatingLayouts = false # »>> this part is excluded from the fizzygum homepage build @addPinoutingMorphs() # this part is excluded from the fizzygum homepage build <<« @addHighlightingMorphs() # here is where the repainting on screen happens @updateBroken() WorldMorph.frameCount++ WorldMorph.dateOfPreviousCycleStart = WorldMorph.dateOfCurrentCycleStart WorldMorph.dateOfCurrentCycleStart = nil # Widget stepping: runChildrensStepFunction: -> # TODO all these set modifications should be immutable... @steppingWdgts.forEach (eachSteppingMorph) => #if eachSteppingMorph.isBeingFloatDragged() # continue # for objects where @fps is defined, check which ones are due to be stepped # and which ones want to wait. millisBetweenSteps = Math.round(1000 / eachSteppingMorph.fps) timeOfCurrentCycleStart = WorldMorph.dateOfCurrentCycleStart.getTime() if eachSteppingMorph.fps <= 0 # if fps 0 or negative, then just run as fast as possible, # so 0 milliseconds remaining to the next invocation millisecondsRemainingToWaitedFrame = 0 else if eachSteppingMorph.synchronisedStepping millisecondsRemainingToWaitedFrame = millisBetweenSteps - (timeOfCurrentCycleStart % millisBetweenSteps) if eachSteppingMorph.previousMillisecondsRemainingToWaitedFrame != 0 and millisecondsRemainingToWaitedFrame > eachSteppingMorph.previousMillisecondsRemainingToWaitedFrame millisecondsRemainingToWaitedFrame = 0 eachSteppingMorph.previousMillisecondsRemainingToWaitedFrame = millisecondsRemainingToWaitedFrame #console.log millisBetweenSteps + " " + millisecondsRemainingToWaitedFrame else elapsedMilliseconds = timeOfCurrentCycleStart - eachSteppingMorph.lastTime millisecondsRemainingToWaitedFrame = millisBetweenSteps - elapsedMilliseconds # when the firing time comes (or as soon as it's past): if millisecondsRemainingToWaitedFrame <= 0 @stepWidget eachSteppingMorph # Increment "lastTime" by millisBetweenSteps. Two notes: # 1) We don't just set it to timeOfCurrentCycleStart so that there is no drifting # in running it the next time: we run it the next time as if this time it # ran exactly on time. # 2) We are going to update "last time" with the loop # below. This is because in case the window is not in foreground, # requestAnimationFrame doesn't run, so we might skip a number of steps. # In such cases, just bring "lastTime" up to speed here. # If we don't do that, "skipped" steps would catch up on us and run all # in contiguous frames when the window comes to foreground, so the # widgets would animate frantically (every frame) catching up on # all the steps they missed. We don't want that. # # while eachSteppingMorph.lastTime + millisBetweenSteps < timeOfCurrentCycleStart # eachSteppingMorph.lastTime += millisBetweenSteps # # 3) and finally, here is the equivalent of the loop above, but done # in one shot using remainders. # Again: we are looking for the last "multiple" k such that # lastTime + k * millisBetweenSteps # is less than timeOfCurrentCycleStart. eachSteppingMorph.lastTime = timeOfCurrentCycleStart - ((timeOfCurrentCycleStart - eachSteppingMorph.lastTime) % millisBetweenSteps) stepWidget: (whichWidget) -> if whichWidget.onNextStep nxt = whichWidget.onNextStep whichWidget.onNextStep = nil nxt.call whichWidget if !whichWidget.step? debugger try whichWidget.step() #console.log "stepping " + whichWidget catch err @softResetWorld() if !@errorConsole? then @createErrorConsole() @errorConsole.contents.showUpWithError err runOtherTasksStepFunction : -> for task in @otherTasksToBeRunOnStep #console.log "running a task: " + task task() # »>> this part is excluded from the fizzygum homepage build sizeCanvasToTestScreenResolution: -> @worldCanvas.width = Math.round(960 * ceilPixelRatio) @worldCanvas.height = Math.round(440 * ceilPixelRatio) @worldCanvas.style.width = "960px" @worldCanvas.style.height = "440px" bkground = document.getElementById("background") bkground.style.width = "960px" bkground.style.height = "720px" bkground.style.backgroundColor = Color.WHITESMOKE.toString() # this part is excluded from the fizzygum homepage build <<« stretchWorldToFillEntirePage: -> # once you call this, the world will forever take the whole page @automaticallyAdjustToFillEntireBrowserAlsoOnResize = true pos = @getCanvasPosition() clientHeight = window.innerHeight clientWidth = window.innerWidth if pos.x > 0 @worldCanvas.style.position = "absolute" @worldCanvas.style.left = "0px" pos.x = 0 if pos.y > 0 @worldCanvas.style.position = "absolute" @worldCanvas.style.top = "0px" pos.y = 0 # scrolled down b/c of viewport scaling clientHeight = document.documentElement.clientHeight if document.body.scrollTop # scrolled left b/c of viewport scaling clientWidth = document.documentElement.clientWidth if document.body.scrollLeft if (@worldCanvas.width isnt clientWidth) or (@worldCanvas.height isnt clientHeight) @fullChanged() @worldCanvas.width = (clientWidth * ceilPixelRatio) @worldCanvas.style.width = clientWidth + "px" @worldCanvas.height = (clientHeight * ceilPixelRatio) @worldCanvas.style.height = clientHeight + "px" @rawSetExtent new Point clientWidth, clientHeight @desktopReLayout() desktopReLayout: -> basementOpenerWdgt = @firstChildSuchThat (w) -> w instanceof BasementOpenerWdgt if basementOpenerWdgt? if basementOpenerWdgt.userMovedThisFromComputedPosition basementOpenerWdgt.fullRawMoveInDesktopToFractionalPosition() if !basementOpenerWdgt.wasPositionedSlightlyOutsidePanel basementOpenerWdgt.fullRawMoveWithin @ else basementOpenerWdgt.fullMoveTo @bottomRight().subtract (new Point 75, 75).add @desktopSidesPadding analogClockWdgt = @firstChildSuchThat (w) -> w instanceof AnalogClockWdgt if analogClockWdgt? if analogClockWdgt.userMovedThisFromComputedPosition analogClockWdgt.fullRawMoveInDesktopToFractionalPosition() if !analogClockWdgt.wasPositionedSlightlyOutsidePanel analogClockWdgt.fullRawMoveWithin @ else analogClockWdgt.fullMoveTo new Point @right() - 80 - @desktopSidesPadding, @top() + @desktopSidesPadding @children.forEach (child) => if child != basementOpenerWdgt and child != analogClockWdgt and !(child instanceof WidgetHolderWithCaptionWdgt) if child.positionFractionalInHoldingPanel? child.fullRawMoveInDesktopToFractionalPosition() if !child.wasPositionedSlightlyOutsidePanel child.fullRawMoveWithin @ # WorldMorph events: # »>> this part is excluded from the fizzygum homepage build initVirtualKeyboard: -> if @inputDOMElementForVirtualKeyboard document.body.removeChild @inputDOMElementForVirtualKeyboard @inputDOMElementForVirtualKeyboard = nil unless (WorldMorph.preferencesAndSettings.isTouchDevice and WorldMorph.preferencesAndSettings.useVirtualKeyboard) return @inputDOMElementForVirtualKeyboard = document.createElement "input" @inputDOMElementForVirtualKeyboard.type = "text" @inputDOMElementForVirtualKeyboard.style.color = Color.TRANSPARENT.toString() @inputDOMElementForVirtualKeyboard.style.backgroundColor = Color.TRANSPARENT.toString() @inputDOMElementForVirtualKeyboard.style.border = "none" @inputDOMElementForVirtualKeyboard.style.outline = "none" @inputDOMElementForVirtualKeyboard.style.position = "absolute" @inputDOMElementForVirtualKeyboard.style.top = "0px" @inputDOMElementForVirtualKeyboard.style.left = "0px" @inputDOMElementForVirtualKeyboard.style.width = "0px" @inputDOMElementForVirtualKeyboard.style.height = "0px" @inputDOMElementForVirtualKeyboard.autocapitalize = "none" # iOS specific document.body.appendChild @inputDOMElementForVirtualKeyboard @inputDOMElementForVirtualKeyboardKeydownBrowserEventListener = (event) => @eventsQueue.push InputDOMElementForVirtualKeyboardKeydownInputEvent.fromBrowserEvent event # Default in several browsers # is for the backspace button to trigger # the "back button", so we prevent that # default here. if event.keyIdentifier is "U+0008" or event.keyIdentifier is "Backspace" event.preventDefault() # suppress tab override and make sure tab gets # received by all browsers if event.keyIdentifier is "U+0009" or event.keyIdentifier is "Tab" event.preventDefault() @inputDOMElementForVirtualKeyboard.addEventListener "keydown", @inputDOMElementForVirtualKeyboardKeydownBrowserEventListener, false @inputDOMElementForVirtualKeyboardKeyupBrowserEventListener = (event) => @eventsQueue.push InputDOMElementForVirtualKeyboardKeyupInputEvent.fromBrowserEvent event event.preventDefault() @inputDOMElementForVirtualKeyboard.addEventListener "keyup", @inputDOMElementForVirtualKeyboardKeyupBrowserEventListener, false # Keypress events are deprecated in the JS specs and are not needed @inputDOMElementForVirtualKeyboardKeypressBrowserEventListener = (event) => #@eventsQueue.push event event.preventDefault() @inputDOMElementForVirtualKeyboard.addEventListener "keypress", @inputDOMElementForVirtualKeyboardKeypressBrowserEventListener, false # this part is excluded from the fizzygum homepage build <<« getPointerAndWdgtInfo: (topWdgtUnderPointer = @hand.topWdgtUnderPointer()) -> # we might eliminate this command afterwards if # we find out user is clicking on a menu item # or right-clicking on a morph absoluteBoundsOfMorphRelativeToWorld = topWdgtUnderPointer.boundingBox().asArray_xywh() morphIdentifierViaTextLabel = topWdgtUnderPointer.identifyViaTextLabel() morphPathRelativeToWorld = topWdgtUnderPointer.pathOfChildrenPositionsRelativeToWorld() pointerPositionFractionalInMorph = @hand.positionFractionalInMorph topWdgtUnderPointer pointerPositionPixelsInMorph = @hand.positionPixelsInMorph topWdgtUnderPointer # note that this pointer position is in world # coordinates not in page coordinates pointerPositionPixelsInWorld = @hand.position() isPartOfListMorph = (topWdgtUnderPointer.parentThatIsA ListMorph)? return [ topWdgtUnderPointer.uniqueIDString(), morphPathRelativeToWorld, morphIdentifierViaTextLabel, absoluteBoundsOfMorphRelativeToWorld, pointerPositionFractionalInMorph, pointerPositionPixelsInMorph, pointerPositionPixelsInWorld, isPartOfListMorph] # ----------------------------------------------------- # clipboard events processing # ----------------------------------------------------- initMouseEventListeners: -> canvas = @worldCanvas # there is indeed a "dblclick" JS event # but we reproduce it internally. # The reason is that we do so for "click" # because we want to check that the mouse # button was released in the same morph # where it was pressed (cause in the DOM you'd # be pressing and releasing on the same # element i.e. the canvas anyways # so we receive clicks even though they aren't # so we have to take care of the processing # ourselves). # So we also do the same internal # processing for dblclick. # Hence, don't register this event listener # below... #@dblclickEventListener = (event) => # event.preventDefault() # @hand.processDoubleClick event #canvas.addEventListener "dblclick", @dblclickEventListener, false @mousedownBrowserEventListener = (event) => @eventsQueue.push MousedownInputEvent.fromBrowserEvent event canvas.addEventListener "mousedown", @mousedownBrowserEventListener, false @mouseupBrowserEventListener = (event) => @eventsQueue.push MouseupInputEvent.fromBrowserEvent event canvas.addEventListener "mouseup", @mouseupBrowserEventListener, false @mousemoveBrowserEventListener = (event) => @eventsQueue.push MousemoveInputEvent.fromBrowserEvent event canvas.addEventListener "mousemove", @mousemoveBrowserEventListener, false initTouchEventListeners: -> canvas = @worldCanvas @touchstartBrowserEventListener = (event) => @eventsQueue.push TouchstartInputEvent.fromBrowserEvent event event.preventDefault() # (unsure that this one is needed) canvas.addEventListener "touchstart", @touchstartBrowserEventListener, false @touchendBrowserEventListener = (event) => @eventsQueue.push TouchendInputEvent.fromBrowserEvent event event.preventDefault() # prevent mouse events emulation canvas.addEventListener "touchend", @touchendBrowserEventListener, false @touchmoveBrowserEventListener = (event) => @eventsQueue.push TouchmoveInputEvent.fromBrowserEvent event event.preventDefault() # (unsure that this one is needed) canvas.addEventListener "touchmove", @touchmoveBrowserEventListener, false @gesturestartBrowserEventListener = (event) => # we don't do anything with gestures for the time being event.preventDefault() # (unsure that this one is needed) canvas.addEventListener "gesturestart", @gesturestartBrowserEventListener, false @gesturechangeBrowserEventListener = (event) => # we don't do anything with gestures for the time being event.preventDefault() # (unsure that this one is needed) canvas.addEventListener "gesturechange", @gesturechangeBrowserEventListener, false initKeyboardEventListeners: -> canvas = @worldCanvas @keydownBrowserEventListener = (event) => @eventsQueue.push KeydownInputEvent.fromBrowserEvent event # this paragraph is to prevent the browser going # "back button" when the user presses delete backspace. # taken from http://stackoverflow.com/a/2768256 doPrevent = false if event.key == "Backspace" d = event.srcElement or event.target if d.tagName.toUpperCase() == 'INPUT' and (d.type.toUpperCase() == 'TEXT' or d.type.toUpperCase() == 'PASSWORD' or d.type.toUpperCase() == 'FILE' or d.type.toUpperCase() == 'SEARCH' or d.type.toUpperCase() == 'EMAIL' or d.type.toUpperCase() == 'NUMBER' or d.type.toUpperCase() == 'DATE') or d.tagName.toUpperCase() == 'TEXTAREA' doPrevent = d.readOnly or d.disabled else doPrevent = true # this paragraph is to prevent the browser scrolling when # user presses spacebar, see # https://stackoverflow.com/a/22559917 if event.key == " " and event.target == @worldCanvas # Note that doing a preventDefault on the spacebar # causes it not to generate the keypress event # (just the keydown), so we had to modify the keydown # to also process the space. # (I tried to use stopPropagation instead/inaddition but # it didn't work). doPrevent = true # also browsers tend to do special things when "tab" # is pressed, so let's avoid that if event.key == "Tab" and event.target == @worldCanvas doPrevent = true if doPrevent event.preventDefault() canvas.addEventListener "keydown", @keydownBrowserEventListener, false @keyupBrowserEventListener = (event) => @eventsQueue.push KeyupInputEvent.fromBrowserEvent event canvas.addEventListener "keyup", @keyupBrowserEventListener, false # keypress is deprecated in the latest specs, and it's really not needed/used, # since all keys really have an effect when they are pushed down @keypressBrowserEventListener = (event) => canvas.addEventListener "keypress", @keypressBrowserEventListener, false initClipboardEventListeners: -> # snippets of clipboard-handling code taken from # http://codebits.glennjones.net/editing/setclipboarddata.htm # Note that this works only in Chrome. Firefox and Safari need a piece of # text to be selected in order to even trigger the copy event. Chrome does # enable clipboard access instead even if nothing is selected. # There are a couple of solutions to this - one is to keep a hidden textfield that # handles all copy/paste operations. # Another one is to not use a clipboard, but rather an internal string as # local memory. So the OS clipboard wouldn't be used, but at least there would # be some copy/paste working. Also one would need to intercept the copy/paste # key combinations manually instead of from the copy/paste events. # ----------------------------------------------------- # clipboard events listeners # ----------------------------------------------------- # we deal with the clipboard here in the event listeners # because for security reasons the runtime is not allowed # access to the clipboards outside of here. So we do all # we have to do with the clipboard here, and in every # other place we work with text. @cutBrowserEventListener = (event) => # TODO this should follow the fromBrowserEvent pattern @eventsQueue.push CutInputEvent.fromBrowserEvent event document.body.addEventListener "cut", @cutBrowserEventListener, false @copyBrowserEventListener = (event) => # TODO this should follow the fromBrowserEvent pattern @eventsQueue.push CopyInputEvent.fromBrowserEvent event document.body.addEventListener "copy", @copyBrowserEventListener, false @pasteBrowserEventListener = (event) => # TODO this should follow the fromBrowserEvent pattern @eventsQueue.push PasteInputEvent.fromBrowserEvent event document.body.addEventListener "paste", @pasteBrowserEventListener, false initKeyCombosEventListeners: -> # »>> this part is excluded from the fizzygum homepage build #console.log "binding via mousetrap" @keyComboResetWorldEventListener = (event) => if AutomatorRecorder? @automator.recorder.resetWorld() false Mousetrap.bind ["alt+d"], @keyComboResetWorldEventListener @keyComboTurnOnAnimationsPacingControl = (event) => if Automator? @automator.recorder.turnOnAnimationsPacingControl() false Mousetrap.bind ["alt+e"], @keyComboTurnOnAnimationsPacingControl @keyComboTurnOffAnimationsPacingControl = (event) => if Automator? @automator.recorder.turnOffAnimationsPacingControl() false Mousetrap.bind ["alt+u"], @keyComboTurnOffAnimationsPacingControl @keyComboTakeScreenshotEventListener = (event) => if AutomatorRecorder? @automator.recorder.addTakeScreenshotCommand() false Mousetrap.bind ["alt+c"], @keyComboTakeScreenshotEventListener @keyComboStopTestRecordingEventListener = (event) => if Automator? @automator.recorder.stopTestRecording() false Mousetrap.bind ["alt+t"], @keyComboStopTestRecordingEventListener @keyComboAddTestCommentEventListener = (event) => if Automator? @automator.recorder.addTestComment() false Mousetrap.bind ["alt+m"], @keyComboAddTestCommentEventListener @keyComboCheckNumberOfMenuItemsEventListener = (event) => if AutomatorRecorder? @automator.recorder.addCheckNumberOfItemsInMenuCommand() false Mousetrap.bind ["alt+k"], @keyComboCheckNumberOfMenuItemsEventListener @keyComboCheckStringsOfItemsInMenuOrderImportant = (event) => if AutomatorRecorder? @automator.recorder.addCheckStringsOfItemsInMenuOrderImportantCommand() false Mousetrap.bind ["alt+a"], @keyComboCheckStringsOfItemsInMenuOrderImportant @keyComboCheckStringsOfItemsInMenuOrderUnimportant = (event) => if AutomatorRecorder? @automator.recorder.addCheckStringsOfItemsInMenuOrderUnimportantCommand() false Mousetrap.bind ["alt+z"], @keyComboCheckStringsOfItemsInMenuOrderUnimportant # this part is excluded from the fizzygum homepage build <<« initOtherMiscEventListeners: -> canvas = @worldCanvas @contextmenuEventListener = (event) -> # suppress context menu for Mac-Firefox event.preventDefault() canvas.addEventListener "contextmenu", @contextmenuEventListener, false # Safari, Chrome @wheelBrowserEventListener = (event) => @eventsQueue.push WheelInputEvent.fromBrowserEvent event event.preventDefault() canvas.addEventListener "wheel", @wheelBrowserEventListener, false # CHECK AFTER 15 Jan 2021 00:00:00 GMT # As of Oct 2020, using mouse/trackpad in # Mobile Safari, the wheel event is not sent. # See: # https://github.com/cdr/code-server/issues/1455 # https://bugs.webkit.org/show_bug.cgi?id=210071 # However, the scroll event is sent, and when that is sent, # we can use the window.pageYOffset # to re-create a passable, fake wheel event. if Utils.runningInMobileSafari() window.addEventListener "scroll", @wheelBrowserEventListener, false @dragoverEventListener = (event) -> event.preventDefault() window.addEventListener "dragover", @dragoverEventListener, false @dropBrowserEventListener = (event) => # nothing here, although code for handling a "drop" is in the # comments event.preventDefault() window.addEventListener "drop", @dropBrowserEventListener, false @resizeBrowserEventListener = => @eventsQueue.push ResizeInputEvent.fromBrowserEvent event # this is a DOM thing, little to do with other r e s i z e methods window.addEventListener "resize", @resizeBrowserEventListener, false # note that we don't register the normal click, # we figure that out independently. initEventListeners: -> @initMouseEventListeners() @initTouchEventListeners() @initKeyboardEventListeners() @initClipboardEventListeners() @initKeyCombosEventListeners() @initOtherMiscEventListeners() # »>> this part is excluded from the fizzygum homepage build removeEventListeners: -> canvas = @worldCanvas # canvas.removeEventListener 'dblclick', @dblclickEventListener canvas.removeEventListener 'mousedown', @mousedownBrowserEventListener canvas.removeEventListener 'mouseup', @mouseupBrowserEventListener canvas.removeEventListener 'mousemove', @mousemoveBrowserEventListener canvas.removeEventListener 'contextmenu', @contextmenuEventListener canvas.removeEventListener "touchstart", @touchstartBrowserEventListener canvas.removeEventListener "touchend", @touchendBrowserEventListener canvas.removeEventListener "touchmove", @touchmoveBrowserEventListener canvas.removeEventListener "gesturestart", @gesturestartBrowserEventListener canvas.removeEventListener "gesturechange", @gesturechangeBrowserEventListener canvas.removeEventListener 'keydown', @keydownBrowserEventListener canvas.removeEventListener 'keyup', @keyupBrowserEventListener canvas.removeEventListener 'keypress', @keypressBrowserEventListener canvas.removeEventListener 'wheel', @wheelBrowserEventListener if Utils.runningInMobileSafari() canvas.removeEventListener 'scroll', @wheelBrowserEventListener canvas.removeEventListener 'cut', @cutBrowserEventListener canvas.removeEventListener 'copy', @copyBrowserEventListener canvas.removeEventListener 'paste', @pasteBrowserEventListener Mousetrap.reset() canvas.removeEventListener 'dragover', @dragoverEventListener canvas.removeEventListener 'resize', @resizeBrowserEventListener canvas.removeEventListener 'drop', @dropBrowserEventListener # this part is excluded from the fizzygum homepage build <<« mouseDownLeft: -> noOperation mouseClickLeft: -> noOperation mouseDownRight: -> noOperation # »>> this part is excluded from the fizzygum homepage build droppedImage: -> nil droppedSVG: -> nil # this part is excluded from the fizzygum homepage build <<« # WorldMorph text field tabbing: nextTab: (editField) -> next = @nextEntryField editField if next @switchTextFieldFocus editField, next previousTab: (editField) -> prev = @previousEntryField editField if prev @switchTextFieldFocus editField, prev switchTextFieldFocus: (current, next) -> current.clearSelection() next.bringToForeground() next.selectAll() next.edit() # if an error is thrown, the state of the world might # be messy, for example the pointer might be # dragging an invisible morph, etc. # So, try to clean-up things as much as possible. softResetWorld: -> @hand.drop() @hand.mouseOverList.clear() @hand.nonFloatDraggedWdgt = nil @wdgtsDetectingClickOutsideMeOrAnyOfMeChildren.clear() @lastNonTextPropertyChangerButtonClickedOrDropped = nil # »>> this part is excluded from the fizzygum homepage build resetWorld: -> @softResetWorld() @changed() # redraw the whole screen @fullDestroyChildren() # the "basementWdgt" is not attached to the # world tree so it's not in the children, # so we need to clean up separately @basementWdgt?.empty() # some tests might change the background # color of the world so let's reset it. @setColor Color.create 205, 205, 205 SystemTestsControlPanelUpdater.blinkLink SystemTestsControlPanelUpdater.resetWorldLink # make sure thw window is scrolled to top # so we can see the test results while tests # are running. document.body.scrollTop = document.documentElement.scrollTop = 0 # this part is excluded from the fizzygum homepage build <<« # There is something special about the # "world" version of fullDestroyChildren: # it resets the counter used to count # how many morphs exist of each Widget class. # That counter is also used to determine the # unique ID of a Widget. So, destroying # all morphs from the world causes the # counts and IDs of all the subsequent # morphs to start from scratch again. fullDestroyChildren: -> # Check which objects end with the word Widget theWordMorph = "Morph" theWordWdgt = "Wdgt" theWordWidget = "Widget" ListOfMorphs = (Object.keys(window)).filter (i) -> i.includes(theWordMorph, i.length - theWordMorph.length) or i.includes(theWordWdgt, i.length - theWordWdgt.length) or i.includes(theWordWidget, i.length - theWordWidget.length) for eachMorphClass in ListOfMorphs if eachMorphClass != "WorldMorph" #console.log "resetting " + eachMorphClass + " from " + window[eachMorphClass].instancesCounter # the actual count is in another variable "instancesCounter" # but all labels are built using instanceNumericID # which is set based on lastBuiltInstanceNumericID window[eachMorphClass].lastBuiltInstanceNumericID = 0 # »>> this part is excluded from the fizzygum homepage build if Automator? @automator.recorder.turnOffAnimationsPacingControl() @automator.recorder.turnOffAlignmentOfMorphIDsMechanism() @automator.recorder.turnOffHidingOfMorphsContentExtractInLabels() @automator.recorder.turnOffHidingOfMorphsNumberIDInLabels() # this part is excluded from the fizzygum homepage build <<« super() destroyToolTips: -> # "toolTipsList" keeps the widgets to be deleted upon # the next mouse click, or whenever another temporary Widget decides # that it needs to remove them. # Note that we actually destroy toolTipsList because we are not expecting # anybody to revive them once they are gone (as opposed to menus) @toolTipsList.forEach (tooltip) => unless tooltip.boundsContainPoint @position() tooltip.fullDestroy() @toolTipsList.delete tooltip buildContextMenu: -> if @isIndexPage menu = new MenuMorph @, false, @, true, true, "Desktop" menu.addMenuItem "wallpapers ➜", false, @, "wallpapersMenu", "choose a wallpaper for the Desktop" menu.addMenuItem "new folder", true, @, "makeFolder" return menu if @isDevMode menu = new MenuMorph(@, false, @, true, true, @constructor.name or @constructor.toString().split(" ")[1].split("(")[0]) else menu = new MenuMorph @, false, @, true, true, "Widgetic" # »>> this part is excluded from the fizzygum homepage build if @isDevMode menu.addMenuItem "demo ➜", false, @, "popUpDemoMenu", "sample morphs" menu.addLine() # TODO remove these two, they do nothing now menu.addMenuItem "show all", true, @, "noOperation" menu.addMenuItem "hide all", true, @, "noOperation" menu.addMenuItem "delete all", true, @, "closeChildren" menu.addMenuItem "move all inside", true, @, "keepAllSubmorphsWithin", "keep all submorphs\nwithin and visible" menu.addMenuItem "inspect", true, @, "inspect", "open a window on\nall properties" menu.addMenuItem "test menu ➜", false, @, "testMenu", "debugging and testing operations" menu.addLine() menu.addMenuItem "restore display", true, @, "changed", "redraw the\nscreen once" menu.addMenuItem "fit whole page", true, @, "stretchWorldToFillEntirePage", "let the World automatically\nadjust to browser resizings" menu.addMenuItem "color...", true, @, "popUpColorSetter", "choose the World's\nbackground color" menu.addMenuItem "wallpapers ➜", false, @, "wallpapersMenu", "choose a wallpaper for the Desktop" if WorldMorph.preferencesAndSettings.inputMode is PreferencesAndSettings.INPUT_MODE_MOUSE menu.addMenuItem "touch screen settings", true, WorldMorph.preferencesAndSettings, "toggleInputMode", "bigger menu fonts\nand sliders" else menu.addMenuItem "standard settings", true, WorldMorph.preferencesAndSettings, "toggleInputMode", "smaller menu fonts\nand sliders" menu.addLine() # this part is excluded from the fizzygum homepage build <<« if Automator? menu.addMenuItem "system tests ➜", false, @, "popUpSystemTestsMenu", "" if @isDevMode menu.addMenuItem "switch to user mode", true, @, "toggleDevMode", "disable developers'\ncontext menus" else menu.addMenuItem "switch to dev mode", true, @, "toggleDevMode" menu.addMenuItem "new folder", true, @, "makeFolder" menu.addMenuItem "about Fizzygum...", true, @, "about" menu wallpapersMenu: (a,targetMorph)-> menu = new MenuMorph @, false, targetMorph, true, true, "Wallpapers" # we add the "untick" prefix to all entries # so we allocate the right amount of space for # the labels, we are going to put the # right ticks soon after menu.addMenuItem untick + @pattern1, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern1 menu.addMenuItem untick + @pattern2, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern2 menu.addMenuItem untick + @pattern3, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern3 menu.addMenuItem untick + @pattern4, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern4 menu.addMenuItem untick + @pattern5, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern5 menu.addMenuItem untick + @pattern6, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern6 menu.addMenuItem untick + @pattern7, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern7 @updatePatternsMenuEntriesTicks menu menu.popUpAtHand() setPattern: (menuItem, ignored2, thePatternName) -> if @patternName == thePatternName return @patternName = thePatternName @changed() if menuItem?.parent? and (menuItem.parent instanceof MenuMorph) @updatePatternsMenuEntriesTicks menuItem.parent # cheap way to keep menu consistency when pinned # note that there is no consistency in case # there are multiple copies of this menu changing # the wallpaper, since there is no real subscription # of a menu to react to wallpaper change coming # from other menus or other means (e.g. API)... updatePatternsMenuEntriesTicks: (menu) -> pattern1Tick = pattern2Tick = pattern3Tick = pattern4Tick = pattern5Tick = pattern6Tick = pattern7Tick = untick switch @patternName when @pattern1 pattern1Tick = tick when @pattern2 pattern2Tick = tick when @pattern3 pattern3Tick = tick when @pattern4 pattern4Tick = tick when @pattern5 pattern5Tick = tick when @pattern6 pattern6Tick = tick when @pattern7 pattern7Tick = tick menu.children[1].label.setText pattern1Tick + @pattern1 menu.children[2].label.setText pattern2Tick + @pattern2 menu.children[3].label.setText pattern3Tick + @pattern3 menu.children[4].label.setText pattern4Tick + @pattern4 menu.children[5].label.setText pattern5Tick + @pattern5 menu.children[6].label.setText pattern6Tick + @pattern6 menu.children[7].label.setText pattern7Tick + @pattern7 # »>> this part is excluded from the fizzygum homepage build popUpSystemTestsMenu: -> menu = new MenuMorph @, false, @, true, true, "system tests" menu.addMenuItem "run system tests", true, @automator.player, "runAllSystemTests", "runs all the system tests" menu.addMenuItem "run system tests force slow", true, @automator.player, "runAllSystemTestsForceSlow", "runs all the system tests" menu.addMenuItem "run system tests force fast skip in-between mouse moves", true, @automator.player, "runAllSystemTestsForceFastSkipInbetweenMouseMoves", "runs all the system tests" menu.addMenuItem "run system tests force fast run in-between mouse moves", true, @automator.player, "runAllSystemTestsForceFastRunInbetweenMouseMoves", "runs all the system tests" menu.addMenuItem "start test recording", true, @automator.recorder, "startTestRecording", "start recording a test" menu.addMenuItem "stop test recording", true, @automator.recorder, "stopTestRecording", "stop recording the test" menu.addMenuItem "(re)play recorded test slow", true, @automator.player, "startTestPlayingSlow", "start playing the test" menu.addMenuItem "(re)play recorded test fast skip in-between mouse moves", true, @automator.player, "startTestPlayingFastSkipInbetweenMouseMoves", "start playing the test" menu.addMenuItem "(re)play recorded test fast run in-between mouse moves", true, @automator.player, "startTestPlayingFastRunInbetweenMouseMoves", "start playing the test" menu.addMenuItem "show test source", true, @automator, "showTestSource", "opens a window with the source of the latest test" menu.addMenuItem "save recorded test", true, @automator.recorder, "saveTest", "save the recorded test" menu.addMenuItem "save failed screenshots", true, @automator.player, "saveFailedScreenshots", "save failed screenshots" menu.popUpAtHand() # this part is excluded from the fizzygum homepage build <<« create: (aWdgt) -> aWdgt.pickUp() # »>> this part is excluded from the fizzygum homepage build createNewStackElementsSizeAdjustingMorph: -> @create new StackElementsSizeAdjustingMorph createNewLayoutElementAdderOrDropletMorph: -> @create new LayoutElementAdderOrDropletMorph createNewRectangleMorph: -> @create new RectangleMorph createNewBoxMorph: -> @create new BoxMorph createNewCircleBoxMorph: -> @create new CircleBoxMorph createNewSliderMorph: -> @create new SliderMorph createNewPanelWdgt: -> newWdgt = new PanelWdgt newWdgt.rawSetExtent new Point 350, 250 @create newWdgt createNewScrollPanelWdgt: -> newWdgt = new ScrollPanelWdgt newWdgt.adjustContentsBounds() newWdgt.adjustScrollBars() newWdgt.rawSetExtent new Point 350, 250 @create newWdgt createNewCanvas: -> newWdgt = new CanvasMorph newWdgt.rawSetExtent new Point 350, 250 @create newWdgt createNewHandle: -> @create new HandleMorph createNewString: -> newWdgt = new StringMorph "Hello, World!" newWdgt.isEditable = true @create newWdgt createNewText: -> newWdgt = new TextMorph("Ich weiß nicht, was soll es bedeuten, dass ich so " + "traurig bin, ein Märchen aus uralten Zeiten, das " + "kommt mir nicht aus dem Sinn. Die Luft ist kühl " + "und es dunkelt, und ruhig fließt der Rhein; der " + "Gipfel des Berges funkelt im Abendsonnenschein. " + "Die schönste Jungfrau sitzet dort oben wunderbar, " + "ihr gold'nes Geschmeide blitzet, sie kämmt ihr " + "goldenes Haar, sie kämmt es mit goldenem Kamme, " + "und singt ein Lied dabei; das hat eine wundersame, " + "gewalt'ge Melodei. Den Schiffer im kleinen " + "Schiffe, ergreift es mit wildem Weh; er schaut " + "nicht die Felsenriffe, er schaut nur hinauf in " + "die Höh'. Ich glaube, die Wellen verschlingen " + "am Ende Schiffer und Kahn, und das hat mit ihrem " + "Singen, die Loreley getan.") newWdgt.isEditable = true newWdgt.maxTextWidth = 300 @create newWdgt createNewSpeechBubbleWdgt: -> newWdgt = new SpeechBubbleWdgt @create newWdgt createNewToolTipWdgt: -> newWdgt = new ToolTipWdgt @create newWdgt createNewGrayPaletteMorph: -> @create new GrayPaletteMorph createNewColorPaletteMorph: -> @create new ColorPaletteMorph createNewGrayPaletteMorphInWindow: -> gP = new GrayPaletteMorph wm = new WindowWdgt nil, nil, gP @add wm wm.rawSetExtent new Point 130, 70 wm.fullRawMoveTo @hand.position().subtract new Point 50, 100 createNewColorPaletteMorphInWindow: -> cP = new ColorPaletteMorph wm = new WindowWdgt nil, nil, cP @add wm wm.rawSetExtent new Point 130, 100 wm.fullRawMoveTo @hand.position().subtract new Point 50, 100 createNewColorPickerMorph: -> @create new ColorPickerMorph createNewSensorDemo: -> newWdgt = new MouseSensorMorph newWdgt.setColor Color.create 230, 200, 100 newWdgt.cornerRadius = 35 newWdgt.alpha = 0.2 newWdgt.rawSetExtent new Point 100, 100 @create newWdgt createNewAnimationDemo: -> foo = new BouncerMorph foo.fullRawMoveTo new Point 50, 20 foo.rawSetExtent new Point 300, 200 foo.alpha = 0.9 foo.speed = 3 bar = new BouncerMorph bar.setColor Color.create 50, 50, 50 bar.fullRawMoveTo new Point 80, 80 bar.rawSetExtent new Point 80, 250 bar.type = "horizontal" bar.direction = "right" bar.alpha = 0.9 bar.speed = 5 baz = new BouncerMorph baz.setColor Color.create 20, 20, 20 baz.fullRawMoveTo new Point 90, 140 baz.rawSetExtent new Point 40, 30 baz.type = "horizontal" baz.direction = "right" baz.speed = 3 garply = new BouncerMorph garply.setColor Color.create 200, 20, 20 garply.fullRawMoveTo new Point 90, 140 garply.rawSetExtent new Point 20, 20 garply.type = "vertical" garply.direction = "up" garply.speed = 8 fred = new BouncerMorph fred.setColor Color.create 20, 200, 20 fred.fullRawMoveTo new Point 120, 140 fred.rawSetExtent new Point 20, 20 fred.type = "vertical" fred.direction = "down" fred.speed = 4 bar.add garply bar.add baz foo.add fred foo.add bar @create foo createNewPenMorph: -> @create new PenMorph underTheCarpet: -> newWdgt = new BasementWdgt @create newWdgt popUpDemoMenu: (morphOpeningThePopUp,b,c,d) -> if @isIndexPage menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "parts bin" menu.addMenuItem "rectangle", true, @, "createNewRectangleMorph" menu.addMenuItem "box", true, @, "createNewBoxMorph" menu.addMenuItem "circle box", true, @, "createNewCircleBoxMorph" menu.addMenuItem "slider", true, @, "createNewSliderMorph" menu.addMenuItem "speech bubble", true, @, "createNewSpeechBubbleWdgt" menu.addLine() menu.addMenuItem "gray scale palette", true, @, "createNewGrayPaletteMorphInWindow" menu.addMenuItem "color palette", true, @, "createNewColorPaletteMorphInWindow" menu.addLine() menu.addMenuItem "analog clock", true, @, "analogClock" else menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "make a morph" menu.addMenuItem "rectangle", true, @, "createNewRectangleMorph" menu.addMenuItem "box", true, @, "createNewBoxMorph" menu.addMenuItem "circle box", true, @, "createNewCircleBoxMorph" menu.addLine() menu.addMenuItem "slider", true, @, "createNewSliderMorph" menu.addMenuItem "panel", true, @, "createNewPanelWdgt" menu.addMenuItem "scrollable panel", true, @, "createNewScrollPanelWdgt" menu.addMenuItem "canvas", true, @, "createNewCanvas" menu.addMenuItem "handle", true, @, "createNewHandle" menu.addLine() menu.addMenuItem "string", true, @, "createNewString" menu.addMenuItem "text", true, @, "createNewText" menu.addMenuItem "tool tip", true, @, "createNewToolTipWdgt" menu.addMenuItem "speech bubble", true, @, "createNewSpeechBubbleWdgt" menu.addLine() menu.addMenuItem "gray scale palette", true, @, "createNewGrayPaletteMorph" menu.addMenuItem "color palette", true, @, "createNewColorPaletteMorph" menu.addMenuItem "color picker", true, @, "createNewColorPickerMorph" menu.addLine() menu.addMenuItem "sensor demo", true, @, "createNewSensorDemo" menu.addMenuItem "animation demo", true, @, "createNewAnimationDemo" menu.addMenuItem "pen", true, @, "createNewPenMorph" menu.addLine() menu.addMenuItem "layout tests ➜", false, @, "layoutTestsMenu", "sample morphs" menu.addLine() menu.addMenuItem "under the carpet", true, @, "underTheCarpet" menu.popUpAtHand() layoutTestsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "Layout tests" menu.addMenuItem "adjuster morph", true, @, "createNewStackElementsSizeAdjustingMorph" menu.addMenuItem "adder/droplet", true, @, "createNewLayoutElementAdderOrDropletMorph" menu.addMenuItem "test screen 1", true, Widget, "setupTestScreen1" menu.popUpAtHand() toggleDevMode: -> @isDevMode = not @isDevMode # this part is excluded from the fizzygum homepage build <<« edit: (aStringMorphOrTextMorph) -> # first off, if the Widget is not editable # then there is nothing to do # return nil unless aStringMorphOrTextMorph.isEditable # there is only one caret in the World, so destroy # the previous one if there was one. if @caret # empty the previously ongoing selection # if there was one. previouslyEditedText = @lastEditedText @lastEditedText = @caret.target if @lastEditedText != previouslyEditedText @lastEditedText.clearSelection() @caret = @caret.fullDestroy() # create the new Caret @caret = new CaretMorph aStringMorphOrTextMorph aStringMorphOrTextMorph.parent.add @caret # this is the only place where the @keyboardEventsReceiver is set @keyboardEventsReceiver = @caret if WorldMorph.preferencesAndSettings.isTouchDevice and WorldMorph.preferencesAndSettings.useVirtualKeyboard @initVirtualKeyboard() # For touch devices, giving focus on the textbox causes # the keyboard to slide up, and since the page viewport # shrinks, the page is scrolled to where the texbox is. # So, it is important to position the textbox around # where the caret is, so that the changed text is going to # be visible rather than out of the viewport. pos = @getCanvasPosition() @inputDOMElementForVirtualKeyboard.style.top = @caret.top() + pos.y + "px" @inputDOMElementForVirtualKeyboard.style.left = @caret.left() + pos.x + "px" @inputDOMElementForVirtualKeyboard.focus() # Widgetic.js provides the "slide" method but I must have lost it # in the way, so commenting this out for the time being # #if WorldMorph.preferencesAndSettings.useSliderForInput # if !aStringMorphOrTextMorph.parentThatIsA MenuMorph # @slide aStringMorphOrTextMorph # Editing can stop because of three reasons: # cancel (user hits ESC) # accept (on stringmorph, user hits enter) # user clicks/floatDrags another morph stopEditing: -> if @caret @lastEditedText = @caret.target @lastEditedText.clearSelection() @caret = @caret.fullDestroy() # the only place where the @keyboardEventsReceiver is unset # (and the hidden input is removed) @keyboardEventsReceiver = nil if @inputDOMElementForVirtualKeyboard @inputDOMElementForVirtualKeyboard.blur() document.body.removeChild @inputDOMElementForVirtualKeyboard @inputDOMElementForVirtualKeyboard = nil @worldCanvas.focus() anyReferenceToWdgt: (whichWdgt) -> # go through all the references and check whether they reference # the wanted widget. Note that the reference could be unreachable # in the basement, or even in the trash for eachReferencingWdgt from @widgetsReferencingOtherWidgets if eachReferencingWdgt.target == whichWdgt return true return false
222707
# The WorldMorph takes over the canvas on the page class WorldMorph extends PanelWdgt @augmentWith GridPositioningOfAddedShortcutsMixin, @name @augmentWith KeepIconicDesktopSystemLinksBackMixin, @name # We need to add and remove # the event listeners so we are # going to put them all in properties # here. # dblclickEventListener: nil mousedownBrowserEventListener: nil mouseupBrowserEventListener: nil mousemoveBrowserEventListener: nil contextmenuEventListener: nil touchstartBrowserEventListener: nil touchendBrowserEventListener: nil touchmoveBrowserEventListener: nil gesturestartBrowserEventListener: nil gesturechangeBrowserEventListener: nil # Note how there can be two handlers for # keyboard events. # This one is attached # to the canvas and reaches the currently # blinking caret if there is one. # See below for the other potential # handler. See "initVirtualKeyboard" # method to see where and when this input and # these handlers are set up. keydownBrowserEventListener: nil keyupBrowserEventListener: nil keypressBrowserEventListener: nil wheelBrowserEventListener: nil cutBrowserEventListener: nil copyBrowserEventListener: nil pasteBrowserEventListener: nil errorConsole: nil # the string for the last serialised morph # is kept in here, to make serialization # and deserialization tests easier. # The alternative would be to refresh and # re-start the tests from where they left... lastSerializationString: "" # Note how there can be two handlers # for keyboard events. This one is # attached to a hidden # "input" div which keeps track of the # text that is being input. inputDOMElementForVirtualKeyboardKeydownBrowserEventListener: nil inputDOMElementForVirtualKeyboardKeyupBrowserEventListener: nil inputDOMElementForVirtualKeyboardKeypressBrowserEventListener: nil # »>> this part is excluded from the fizzygum homepage build keyComboResetWorldEventListener: nil keyComboTurnOnAnimationsPacingControl: nil keyComboTurnOffAnimationsPacingControl: nil keyComboTakeScreenshotEventListener: nil keyComboStopTestRecordingEventListener: nil keyComboTakeScreenshotEventListener: nil keyComboCheckStringsOfItemsInMenuOrderImportant: nil keyComboCheckStringsOfItemsInMenuOrderUnimportant: nil keyComboAddTestCommentEventListener: nil keyComboCheckNumberOfMenuItemsEventListener: nil # this part is excluded from the fizzygum homepage build <<« dragoverEventListener: nil resizeBrowserEventListener: nil otherTasksToBeRunOnStep: [] # »>> this part is excluded from the fizzygum homepage build dropBrowserEventListener: nil # this part is excluded from the fizzygum homepage build <<« # these variables shouldn't be static to the WorldMorph, because # in pure theory you could have multiple worlds in the same # page with different settings # (but anyways, it was global before, so it's not any worse than before) @preferencesAndSettings: nil @dateOfPreviousCycleStart: nil @dateOfCurrentCycleStart: nil showRedraws: false doubleCheckCachedMethodsResults: false automator: nil # this is the actual reference to the canvas # on the html page, where the world is # finally painted to. worldCanvas: nil worldCanvasContext: nil canvasForTextMeasurements: nil canvasContextForTextMeasurements: nil cacheForTextMeasurements: nil cacheForTextParagraphSplits: nil cacheForParagraphsWordsSplits: nil cacheForParagraphsWrappingData: nil cacheForTextWrappingData: nil cacheForTextBreakingIntoLinesTopLevel: nil # By default the world will always fill # the entire page, also when browser window # is resized. # When this flag is set, the onResize callback # automatically adjusts the world size. automaticallyAdjustToFillEntireBrowserAlsoOnResize: true # »>> this part is excluded from the fizzygum homepage build # keypad keys map to special characters # so we can trigger test actions # see more comments below @KEYPAD_TAB_mappedToThaiKeyboard_A: "ฟ" @KEYPAD_SLASH_mappedToThaiKeyboard_B: "ิ" @KEYPAD_MULTIPLY_mappedToThaiKeyboard_C: "แ" @KEYPAD_DELETE_mappedToThaiKeyboard_D: "ก" @KEYPAD_7_mappedToThaiKeyboard_E: "ำ" @KEYPAD_8_mappedToThaiKeyboard_F: "ด" @KEYPAD_9_mappedToThaiKeyboard_G: "เ" @KEYPAD_MINUS_mappedToThaiKeyboard_H: "้" @KEYPAD_4_mappedToThaiKeyboard_I: "ร" @KEYPAD_5_mappedToThaiKeyboard_J: "่" # looks like empty string but isn't :-) @KEYPAD_6_mappedToThaiKeyboard_K: "า" @KEYPAD_PLUS_mappedToThaiKeyboard_L: "ส" @KEYPAD_1_mappedToThaiKeyboard_M: "ท" @KEYPAD_2_mappedToThaiKeyboard_N: "ท" @KEYPAD_3_mappedToThaiKeyboard_O: "ื" @KEYPAD_ENTER_mappedToThaiKeyboard_P: "น" @KEYPAD_0_mappedToThaiKeyboard_Q: "ย" @KEYPAD_DOT_mappedToThaiKeyboard_R: "พ" # this part is excluded from the fizzygum homepage build <<« wdgtsDetectingClickOutsideMeOrAnyOfMeChildren: new Set hierarchyOfClickedWdgts: new Set hierarchyOfClickedMenus: new Set popUpsMarkedForClosure: new Set freshlyCreatedPopUps: new Set openPopUps: new Set toolTipsList: new Set # »>> this part is excluded from the fizzygum homepage build @ongoingUrlActionNumber: 0 # this part is excluded from the fizzygum homepage build <<« @frameCount: 0 @numberOfAddsAndRemoves: 0 @numberOfVisibilityFlagsChanges: 0 @numberOfCollapseFlagsChanges: 0 @numberOfRawMovesAndResizes: 0 broken: nil duplicatedBrokenRectsTracker: nil numberOfDuplicatedBrokenRects: 0 numberOfMergedSourceAndDestination: 0 morphsToBeHighlighted: new Set currentHighlightingMorphs: new Set morphsBeingHighlighted: new Set # »>> this part is excluded from the fizzygum homepage build morphsToBePinouted: new Set currentPinoutingMorphs: new Set morphsBeingPinouted: new Set # this part is excluded from the fizzygum homepage build <<« steppingWdgts: new Set basementWdgt: nil # since the shadow is just a "rendering" effect # there is no morph for it, we need to just clean up # the shadow area ad-hoc. We do that by just growing any # broken rectangle by the maximum shadow offset. # We could be more surgical and remember the offset of the # shadow (if any) in the start and end location of the # morph, just like we do with the position, but it # would complicate things and probably be overkill. # The downside of this is that if we change the # shadow sizes, we have to check that this max size # still captures the biggest. maxShadowSize: 6 eventsQueue: [] widgetsReferencingOtherWidgets: new Set incrementalGcSessionId: 0 desktopSidesPadding: 10 # the desktop lays down icons vertically laysIconsHorizontallyInGrid: false iconsLayingInGridWrapCount: 5 errorsWhileRepainting: [] paintingWidget: nil widgetsGivingErrorWhileRepainting: [] # this one is so we can left/center/right align in # a document editor the last widget that the user "touched" # TODO this could be extended so we keep a "list" of # "selected" widgets (e.g. if the user ctrl-clicks on a widget # then it highlights in some manner and ends up in this list) # and then operations can be performed on the whole list # of widgets. lastNonTextPropertyChangerButtonClickedOrDropped: nil patternName: nil pattern1: "plain" pattern2: "circles" pattern3: "vert. stripes" pattern4: "oblique stripes" pattern5: "dots" pattern6: "zigzag" pattern7: "bricks" howManyUntitledShortcuts: 0 howManyUntitledFoldersShortcuts: 0 lastUsedConnectionsCalculationToken: 0 isIndexPage: nil # »>> this part is excluded from the fizzygum homepage build # This method also handles keypresses from a special # external keypad which is used to # record tests commands (such as capture screen, etc.). # These external keypads are inexpensive # so they are a good device for this kind # of stuff. # http://www.amazon.co.uk/Perixx-PERIPAD-201PLUS-Numeric-Keypad-Laptop/dp/B001R6FZLU/ # They keypad is mapped # to Thai keyboard characters via an OSX app # called keyremap4macbook (also one needs to add the # Thai keyboard, which is just a click from System Preferences) # Those Thai characters are used to trigger test # commands. The only added complexity is about # the "00" key of such keypads - see # note below. doublePressOfZeroKeypadKey: nil # this part is excluded from the fizzygum homepage build <<« healingRectanglesPhase: false # we use the trackChanges array as a stack to # keep track whether a whole segment of code # (including all function calls in it) will # record the broken rectangles. # Using a stack we can correctly track nested "disabling of track # changes" correctly. trackChanges: [true] morphsThatMaybeChangedGeometryOrPosition: [] morphsThatMaybeChangedFullGeometryOrPosition: [] morphsThatMaybeChangedLayout: [] # »>> this part is only needed for Macros macroStepsWaitingTimer: nil nextBlockToBeRun: nil macroVars: nil macroIsRunning: nil # this part is only needed for Macros <<« constructor: ( @worldCanvas, @automaticallyAdjustToFillEntireBrowserAlsoOnResize = true ) -> # The WorldMorph is the very first morph to # be created. # world at the moment is a global variable, there is only one # world and this variable needs to be initialised as soon as possible, which # is right here. This is because there is code in this constructor that # will reference that global world variable, so it needs to be set # very early window.world = @ if window.location.href.includes "worldWithSystemTestHarness" @isIndexPage = false else @isIndexPage = true WorldMorph.preferencesAndSettings = new PreferencesAndSettings super() @patternName = @pattern1 @appearance = new DesktopAppearance @ #console.log WorldMorph.preferencesAndSettings.menuFontName @color = Color.create 205, 205, 205 # (130, 130, 130) @strokeColor = nil @alpha = 1 # additional properties: @isDevMode = false @hand = new ActivePointerWdgt @keyboardEventsReceiver = nil @lastEditedText = nil @caret = nil @temporaryHandlesAndLayoutAdjusters = new Set @inputDOMElementForVirtualKeyboard = nil if @automaticallyAdjustToFillEntireBrowserAlsoOnResize and @isIndexPage @stretchWorldToFillEntirePage() else @sizeCanvasToTestScreenResolution() # @worldCanvas.width and height here are in physical pixels # so we want to bring them back to logical pixels @setBounds new Rectangle 0, 0, @worldCanvas.width / ceilPixelRatio, @worldCanvas.height / ceilPixelRatio @initEventListeners() if Automator? @automator = new Automator @worldCanvasContext = @worldCanvas.getContext "2d" @canvasForTextMeasurements = HTMLCanvasElement.createOfPhysicalDimensions() @canvasContextForTextMeasurements = @canvasForTextMeasurements.getContext "2d" @canvasContextForTextMeasurements.useLogicalPixelsUntilRestore() @canvasContextForTextMeasurements.textAlign = "left" @canvasContextForTextMeasurements.textBaseline = "bottom" # when using an inspector it's not uncommon to render # 400 labels just for the properties, so trying to size # the cache accordingly... @cacheForTextMeasurements = new LRUCache 1000, 1000*60*60*24 @cacheForTextParagraphSplits = new LRUCache 300, 1000*60*60*24 @cacheForParagraphsWordsSplits = new LRUCache 300, 1000*60*60*24 @cacheForParagraphsWrappingData = new LRUCache 300, 1000*60*60*24 @cacheForTextWrappingData = new LRUCache 300, 1000*60*60*24 @cacheForImmutableBackBuffers = new LRUCache 1000, 1000*60*60*24 @cacheForTextBreakingIntoLinesTopLevel = new LRUCache 10, 1000*60*60*24 @changed() # answer the absolute coordinates of the world canvas within the document getCanvasPosition: -> if !@worldCanvas? return {x: 0, y: 0} pos = x: @worldCanvas.offsetLeft y: @worldCanvas.offsetTop offsetParent = @worldCanvas.offsetParent while offsetParent? pos.x += offsetParent.offsetLeft pos.y += offsetParent.offsetTop if offsetParent isnt document.body and offsetParent isnt document.documentElement pos.x -= offsetParent.scrollLeft pos.y -= offsetParent.scrollTop offsetParent = offsetParent.offsetParent pos colloquialName: -> "Desktop" makePrettier: -> WorldMorph.preferencesAndSettings.menuFontSize = 14 WorldMorph.preferencesAndSettings.menuHeaderFontSize = 13 WorldMorph.preferencesAndSettings.menuHeaderColor = Color.create 125, 125, 125 WorldMorph.preferencesAndSettings.menuHeaderBold = false WorldMorph.preferencesAndSettings.menuStrokeColor = Color.create 186, 186, 186 WorldMorph.preferencesAndSettings.menuBackgroundColor = Color.create 250, 250, 250 WorldMorph.preferencesAndSettings.menuButtonsLabelColor = Color.create 50, 50, 50 WorldMorph.preferencesAndSettings.normalTextFontSize = 13 WorldMorph.preferencesAndSettings.titleBarTextFontSize = 13 WorldMorph.preferencesAndSettings.titleBarTextHeight = 16 WorldMorph.preferencesAndSettings.titleBarBoldText = false WorldMorph.preferencesAndSettings.bubbleHelpFontSize = 12 WorldMorph.preferencesAndSettings.iconDarkLineColor = Color.create 37, 37, 37 WorldMorph.preferencesAndSettings.defaultPanelsBackgroundColor = Color.create 249, 249, 249 WorldMorph.preferencesAndSettings.defaultPanelsStrokeColor = Color.create 198, 198, 198 @setPattern nil, nil, "dots" @changed() getNextUntitledShortcutName: -> name = "Untitled" if @howManyUntitledShortcuts > 0 name += " " + (@howManyUntitledShortcuts + 1) @howManyUntitledShortcuts++ return name getNextUntitledFolderShortcutName: -> name = "new folder" if @howManyUntitledFoldersShortcuts > 0 name += " " + (@howManyUntitledFoldersShortcuts + 1) @howManyUntitledFoldersShortcuts++ return name wantsDropOf: (aWdgt) -> return @_acceptsDrops makeNewConnectionsCalculationToken: -> # not nice to read but this means: # first increment and then return the value # this is so the first token we use is 1 # and we can initialise all input/node tokens to 0 # so to make them receptive to the first token generated ++@lastUsedConnectionsCalculationToken createErrorConsole: -> errorsLogViewerMorph = new ErrorsLogViewerMorph "Errors", @, "modifyCodeToBeInjected", "" wm = new WindowWdgt nil, nil, errorsLogViewerMorph wm.setExtent new Point 460, 400 @add wm @errorConsole = wm @errorConsole.fullMoveTo new Point 190,10 @errorConsole.setExtent new Point 550,415 @errorConsole.hide() removeSpinnerAndFakeDesktop: -> # remove the fake desktop for quick launch and the spinner spinner = document.getElementById 'spinner' spinner.parentNode.removeChild spinner splashScreenFakeDesktop = document.getElementById 'splashScreenFakeDesktop' splashScreenFakeDesktop.parentNode.removeChild splashScreenFakeDesktop createDesktop: -> @setColor Color.create 244,243,244 @makePrettier() acm = new AnalogClockWdgt acm.rawSetExtent new Point 80, 80 acm.fullRawMoveTo new Point @right()-80-@desktopSidesPadding, @top() + @desktopSidesPadding @add acm menusHelper.createWelcomeMessageWindowAndShortcut() menusHelper.createHowToSaveMessageOpener() menusHelper.basementIconAndText() menusHelper.createSimpleDocumentLauncher() menusHelper.createFizzyPaintLauncher() menusHelper.createSimpleSlideLauncher() menusHelper.createDashboardsLauncher() menusHelper.createPatchProgrammingLauncher() menusHelper.createGenericPanelLauncher() menusHelper.createToolbarsOpener() exampleDocsFolder = @makeFolder nil, nil, "examples" menusHelper.createDegreesConverterOpener exampleDocsFolder menusHelper.createSampleSlideOpener exampleDocsFolder menusHelper.createSampleDashboardOpener exampleDocsFolder menusHelper.createSampleDocOpener exampleDocsFolder # »>> this part is excluded from the fizzygum homepage build getParameterPassedInURL: (name) -> name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]') regex = new RegExp '[\\?&]' + name + '=([^&#]*)' results = regex.exec location.search if results? return decodeURIComponent results[1].replace(/\+/g, ' ') else return nil # some test urls: # this one contains two actions, two tests each, but only # the second test is run for the second group. # file:///Users/daviddellacasa/Fizzygum/Fizzygum-builds/latest/worldWithSystemTestHarness.html?startupActions=%7B%0D%0A++%22paramsVersion%22%3A+0.1%2C%0D%0A++%22actions%22%3A+%5B%0D%0A++++%7B%0D%0A++++++%22name%22%3A+%22runTests%22%2C%0D%0A++++++%22testsToRun%22%3A+%5B%22bubble%22%5D%0D%0A++++%7D%2C%0D%0A++++%7B%0D%0A++++++%22name%22%3A+%22runTests%22%2C%0D%0A++++++%22testsToRun%22%3A+%5B%22shadow%22%2C+%22SystemTest_basicResize%22%5D%2C%0D%0A++++++%22numberOfGroups%22%3A+2%2C%0D%0A++++++%22groupToBeRun%22%3A+1%0D%0A++++%7D++%5D%0D%0A%7D # # just one simple quick test about shadows #file:///Users/daviddellacasa/Fizzygum/Fizzygum-builds/latest/worldWithSystemTestHarness.html?startupActions=%7B%0A%20%20%22paramsVersion%22%3A%200.1%2C%0A%20%20%22actions%22%3A%20%5B%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%22name%22%3A%20%22runTests%22%2C%0A%20%20%20%20%20%20%22testsToRun%22%3A%20%5B%22shadow%22%5D%0A%20%20%20%20%7D%0A%20%20%5D%0A%7D nextStartupAction: -> if (@getParameterPassedInURL "startupActions")? startupActions = JSON.parse @getParameterPassedInURL "startupActions" if (!startupActions?) or (WorldMorph.ongoingUrlActionNumber == startupActions.actions.length) WorldMorph.ongoingUrlActionNumber = 0 if Automator? if window.location.href.includes("worldWithSystemTestHarness") if @automator.atLeastOneTestHasBeenRun if @automator.allTestsPassedSoFar document.getElementById("background").style.background = Color.GREEN.toString() return if !@isIndexPage then console.log "nextStartupAction " + (WorldMorph.ongoingUrlActionNumber+1) + " / " + startupActions.actions.length currentAction = startupActions.actions[WorldMorph.ongoingUrlActionNumber] if Automator? and currentAction.name == "runTests" @automator.loader.selectTestsFromTagsOrTestNames(currentAction.testsToRun) if currentAction.numberOfGroups? @automator.numberOfGroups = currentAction.numberOfGroups else @automator.numberOfGroups = 1 if currentAction.groupToBeRun? @automator.groupToBeRun = currentAction.groupToBeRun else @automator.groupToBeRun = 0 if currentAction.forceSlowTestPlaying? @automator.forceSlowTestPlaying = true if currentAction.forceTurbo? @automator.forceTurbo = true if currentAction.forceSkippingInBetweenMouseMoves? @automator.forceSkippingInBetweenMouseMoves = true if currentAction.forceRunningInBetweenMouseMoves? @automator.forceRunningInBetweenMouseMoves = true @automator.player.runAllSystemTests() WorldMorph.ongoingUrlActionNumber++ getMorphViaTextLabel: ([textDescription, occurrenceNumber, numberOfOccurrences]) -> allCandidateMorphsWithSameTextDescription = @allChildrenTopToBottomSuchThat (m) -> m.getTextDescription() == textDescription return allCandidateMorphsWithSameTextDescription[occurrenceNumber] # this part is excluded from the fizzygum homepage build <<« mostRecentlyCreatedPopUp: -> mostRecentPopUp = nil mostRecentPopUpID = -1 # we have to check which menus # are actually open, because # the destroy() function used # everywhere is not recursive and # that's where we update the @openPopUps # set so we have to doublecheck here @openPopUps.forEach (eachPopUp) => if eachPopUp.isOrphan() @openPopUps.delete eachPopUp else if eachPopUp.instanceNumericID >= mostRecentPopUpID mostRecentPopUp = eachPopUp return mostRecentPopUp # »>> this part is excluded from the fizzygum homepage build # see roundNumericIDsToNextThousand method in # Widget for an explanation of why we need this # method. alignIDsOfNextMorphsInSystemTests: -> if Automator? and Automator.state != Automator.IDLE # Check which objects end with the word Widget theWordMorph = "Morph" theWordWdgt = "Wdgt" theWordWidget = "Widget" listOfMorphsClasses = (Object.keys(window)).filter (i) -> i.includes(theWordMorph, i.length - theWordMorph.length) or i.includes(theWordWdgt, i.length - theWordWdgt.length) or i.includes(theWordWidget, i.length - theWordWidget.length) for eachMorphClass in listOfMorphsClasses #console.log "bumping up ID of class: " + eachMorphClass window[eachMorphClass].roundNumericIDsToNextThousand?() # this part is excluded from the fizzygum homepage build <<« # used to close temporary menus closePopUpsMarkedForClosure: -> @popUpsMarkedForClosure.forEach (eachMorph) => eachMorph.close() @popUpsMarkedForClosure.clear() # »>> this part is excluded from the fizzygum homepage build # World Widget broken rects debugging # currently unused brokenFor: (aWdgt) -> # private fb = aWdgt.fullBounds() @broken.filter (rect) -> rect.isIntersecting fb # this part is excluded from the fizzygum homepage build <<« # fullPaintIntoAreaOrBlitFromBackBuffer results into actual painting of pieces of # morphs done # by the paintIntoAreaOrBlitFromBackBuffer function. # The paintIntoAreaOrBlitFromBackBuffer function is defined in Widget. fullPaintIntoAreaOrBlitFromBackBuffer: (aContext, aRect) -> # invokes the Widget's fullPaintIntoAreaOrBlitFromBackBuffer, which has only three implementations: # * the default one by Widget which just invokes the paintIntoAreaOrBlitFromBackBuffer of all children # * the interesting one in PanelWdgt which a) narrows the dirty # rectangle (intersecting it with its border # since the PanelWdgt clips at its border) and b) stops recursion on all # the children that are outside such intersection. # * this implementation which just takes into account that the hand # (which could contain a Widget being floatDragged) # is painted on top of everything. super aContext, aRect # the mouse cursor is always drawn on top of everything # and it's not attached to the WorldMorph. @hand.fullPaintIntoAreaOrBlitFromBackBuffer aContext, aRect clippedThroughBounds: -> @checkClippedThroughBoundsCache = WorldMorph.numberOfAddsAndRemoves + "-" + WorldMorph.numberOfVisibilityFlagsChanges + "-" + WorldMorph.numberOfCollapseFlagsChanges + "-" + WorldMorph.numberOfRawMovesAndResizes @clippedThroughBoundsCache = @boundingBox() return @clippedThroughBoundsCache # using the code coverage tool from Chrome, it # doesn't seem that this is ever used # TODO investigate and see whether this is needed clipThrough: -> @checkClipThroughCache = WorldMorph.numberOfAddsAndRemoves + "-" + WorldMorph.numberOfVisibilityFlagsChanges + "-" + WorldMorph.numberOfCollapseFlagsChanges + "-" + WorldMorph.numberOfRawMovesAndResizes @clipThroughCache = @boundingBox() return @clipThroughCache pushBrokenRect: (brokenMorph, theRect, isSrc) -> if @duplicatedBrokenRectsTracker[theRect.toString()]? @numberOfDuplicatedBrokenRects++ else if isSrc brokenMorph.srcBrokenRect = @broken.length else brokenMorph.dstBrokenRect = @broken.length if !theRect? debugger # if @broken.length == 0 # debugger @broken.push theRect @duplicatedBrokenRectsTracker[theRect.toString()] = true # using the code coverage tool from Chrome, it # doesn't seem that this is ever used # TODO investigate and see whether this is needed mergeBrokenRectsIfCloseOrPushBoth: (brokenMorph, sourceBroken, destinationBroken) -> mergedBrokenRect = sourceBroken.merge destinationBroken mergedBrokenRectArea = mergedBrokenRect.area() sumArea = sourceBroken.area() + destinationBroken.area() #console.log "mergedBrokenRectArea: " + mergedBrokenRectArea + " (sumArea + sumArea/10): " + (sumArea + sumArea/10) if mergedBrokenRectArea < sumArea + sumArea/10 @pushBrokenRect brokenMorph, mergedBrokenRect, true @numberOfMergedSourceAndDestination++ else @pushBrokenRect brokenMorph, sourceBroken, true @pushBrokenRect brokenMorph, destinationBroken, false checkARectWithHierarchy: (aRect, brokenMorph, isSrc) -> brokenMorphAncestor = brokenMorph #if brokenMorph instanceof SliderMorph # debugger while brokenMorphAncestor.parent? brokenMorphAncestor = brokenMorphAncestor.parent if brokenMorphAncestor.srcBrokenRect? if !@broken[brokenMorphAncestor.srcBrokenRect]? debugger if @broken[brokenMorphAncestor.srcBrokenRect].containsRectangle aRect if isSrc @broken[brokenMorph.srcBrokenRect] = nil brokenMorph.srcBrokenRect = nil else @broken[brokenMorph.dstBrokenRect] = nil brokenMorph.dstBrokenRect = nil else if aRect.containsRectangle @broken[brokenMorphAncestor.srcBrokenRect] @broken[brokenMorphAncestor.srcBrokenRect] = nil brokenMorphAncestor.srcBrokenRect = nil if brokenMorphAncestor.dstBrokenRect? if !@broken[brokenMorphAncestor.dstBrokenRect]? debugger if @broken[brokenMorphAncestor.dstBrokenRect].containsRectangle aRect if isSrc @broken[brokenMorph.srcBrokenRect] = nil brokenMorph.srcBrokenRect = nil else @broken[brokenMorph.dstBrokenRect] = nil brokenMorph.dstBrokenRect = nil else if aRect.containsRectangle @broken[brokenMorphAncestor.dstBrokenRect] @broken[brokenMorphAncestor.dstBrokenRect] = nil brokenMorphAncestor.dstBrokenRect = nil rectAlreadyIncludedInParentBrokenMorph: -> for brokenMorph in @morphsThatMaybeChangedGeometryOrPosition if brokenMorph.srcBrokenRect? aRect = @broken[brokenMorph.srcBrokenRect] @checkARectWithHierarchy aRect, brokenMorph, true if brokenMorph.dstBrokenRect? aRect = @broken[brokenMorph.dstBrokenRect] @checkARectWithHierarchy aRect, brokenMorph, false for brokenMorph in @morphsThatMaybeChangedFullGeometryOrPosition if brokenMorph.srcBrokenRect? aRect = @broken[brokenMorph.srcBrokenRect] @checkARectWithHierarchy aRect, brokenMorph if brokenMorph.dstBrokenRect? aRect = @broken[brokenMorph.dstBrokenRect] @checkARectWithHierarchy aRect, brokenMorph cleanupSrcAndDestRectsOfMorphs: -> for brokenMorph in @morphsThatMaybeChangedGeometryOrPosition brokenMorph.srcBrokenRect = nil brokenMorph.dstBrokenRect = nil for brokenMorph in @morphsThatMaybeChangedFullGeometryOrPosition brokenMorph.srcBrokenRect = nil brokenMorph.dstBrokenRect = nil fleshOutBroken: -> #if @morphsThatMaybeChangedGeometryOrPosition.length > 0 # debugger sourceBroken = nil destinationBroken = nil for brokenMorph in @morphsThatMaybeChangedGeometryOrPosition # let's see if this Widget that marked itself as broken # was actually painted in the past frame. # If it was then we have to clean up the "before" area # even if the Widget is not visible anymore if brokenMorph.clippedBoundsWhenLastPainted? if brokenMorph.clippedBoundsWhenLastPainted.isNotEmpty() sourceBroken = brokenMorph.clippedBoundsWhenLastPainted.expandBy(1).growBy @maxShadowSize #if brokenMorph!= world and (brokenMorph.clippedBoundsWhenLastPainted.containsPoint (new Point(10,10))) # debugger # for the "destination" broken rectangle we can actually # check whether the Widget is still visible because we # can skip the destination rectangle in that case # (not the source one!) unless brokenMorph.surelyNotShowingUpOnScreenBasedOnVisibilityCollapseAndOrphanage() # @clippedThroughBounds() should be smaller area # than bounds because it clips # the bounds based on the clipping morphs up the # hierarchy boundsToBeChanged = brokenMorph.clippedThroughBounds() if boundsToBeChanged.isNotEmpty() destinationBroken = boundsToBeChanged.spread().expandBy(1).growBy @maxShadowSize #if brokenMorph!= world and (boundsToBeChanged.spread().containsPoint new Point 10, 10) # debugger if sourceBroken? and destinationBroken? @mergeBrokenRectsIfCloseOrPushBoth brokenMorph, sourceBroken, destinationBroken else if sourceBroken? or destinationBroken? if sourceBroken? @pushBrokenRect brokenMorph, sourceBroken, true else @pushBrokenRect brokenMorph, destinationBroken, true brokenMorph.geometryOrPositionPossiblyChanged = false brokenMorph.clippedBoundsWhenLastPainted = nil fleshOutFullBroken: -> #if @morphsThatMaybeChangedFullGeometryOrPosition.length > 0 # debugger sourceBroken = nil destinationBroken = nil for brokenMorph in @morphsThatMaybeChangedFullGeometryOrPosition #console.log "fleshOutFullBroken: " + brokenMorph if brokenMorph.fullClippedBoundsWhenLastPainted? if brokenMorph.fullClippedBoundsWhenLastPainted.isNotEmpty() sourceBroken = brokenMorph.fullClippedBoundsWhenLastPainted.expandBy(1).growBy @maxShadowSize # for the "destination" broken rectangle we can actually # check whether the Widget is still visible because we # can skip the destination rectangle in that case # (not the source one!) unless brokenMorph.surelyNotShowingUpOnScreenBasedOnVisibilityCollapseAndOrphanage() boundsToBeChanged = brokenMorph.fullClippedBounds() if boundsToBeChanged.isNotEmpty() destinationBroken = boundsToBeChanged.spread().expandBy(1).growBy @maxShadowSize #if brokenMorph!= world and (boundsToBeChanged.spread().containsPoint (new Point(10,10))) # debugger if sourceBroken? and destinationBroken? @mergeBrokenRectsIfCloseOrPushBoth brokenMorph, sourceBroken, destinationBroken else if sourceBroken? or destinationBroken? if sourceBroken? @pushBrokenRect brokenMorph, sourceBroken, true else @pushBrokenRect brokenMorph, destinationBroken, true brokenMorph.fullGeometryOrPositionPossiblyChanged = false brokenMorph.fullClippedBoundsWhenLastPainted = nil # »>> this part is excluded from the fizzygum homepage build showBrokenRects: (aContext) -> aContext.save() aContext.globalAlpha = 0.5 aContext.useLogicalPixelsUntilRestore() for eachBrokenRect in @broken if eachBrokenRect? randomR = Math.round Math.random() * 255 randomG = Math.round Math.random() * 255 randomB = Math.round Math.random() * 255 aContext.fillStyle = "rgb("+randomR+","+randomG+","+randomB+")" aContext.fillRect Math.round(eachBrokenRect.origin.x), Math.round(eachBrokenRect.origin.y), Math.round(eachBrokenRect.width()), Math.round(eachBrokenRect.height()) aContext.restore() # this part is excluded from the fizzygum homepage build <<« # layouts are recalculated like so: # there will be several subtrees # that will need relayout. # So take the head of any subtree and re-layout it # The relayout might or might not visit all the subnodes # of the subtree, because you might have a subtree # that lives inside a floating morph, in which # case it's not re-layout. # So, a subtree might not be healed in one go, # rather we keep track of what's left to heal and # we apply the same process: we heal from the head node # and take out of the list what's healed in that step, # and we continue doing so until there is nothing else # to heal. recalculateLayouts: -> until @morphsThatMaybeChangedLayout.length == 0 # find the first Widget which has a broken layout, # take out of queue all the others loop tryThisMorph = @morphsThatMaybeChangedLayout[@morphsThatMaybeChangedLayout.length - 1] if tryThisMorph.layoutIsValid @morphsThatMaybeChangedLayout.pop() if @morphsThatMaybeChangedLayout.length == 0 return else break # now that you have a Widget with a broken layout # go up the chain of broken layouts as much as # possible # QUESTION: would it be safer instead to start from the # very top invalid morph, i.e. on the way to the top, # stop at the last morph with an invalid layout # instead of stopping at the first morph with a # valid layout... while tryThisMorph.parent? if tryThisMorph.layoutSpec == LayoutSpec.ATTACHEDAS_FREEFLOATING or tryThisMorph.parent.layoutIsValid break tryThisMorph = tryThisMorph.parent try # so now you have a "top" element up a chain # of morphs with broken layout. Go do a # doLayout on it, so it might fix a bunch of those # on the chain (but not all) tryThisMorph.doLayout() catch err @softResetWorld() if !@errorConsole? then @createErrorConsole() @errorConsole.contents.showUpWithError err clearGeometryOrPositionPossiblyChangedFlags: -> for m in @morphsThatMaybeChangedGeometryOrPosition m.geometryOrPositionPossiblyChanged = false clearFullGeometryOrPositionPossiblyChangedFlags: -> for m in @morphsThatMaybeChangedFullGeometryOrPosition m.fullGeometryOrPositionPossiblyChanged = false disableTrackChanges: -> @trackChanges.push false maybeEnableTrackChanges: -> @trackChanges.pop() updateBroken: -> #console.log "number of broken rectangles: " + @broken.length @broken = [] @duplicatedBrokenRectsTracker = {} @numberOfDuplicatedBrokenRects = 0 @numberOfMergedSourceAndDestination = 0 @fleshOutFullBroken() @fleshOutBroken() @rectAlreadyIncludedInParentBrokenMorph() @cleanupSrcAndDestRectsOfMorphs() @clearGeometryOrPositionPossiblyChangedFlags() @clearFullGeometryOrPositionPossiblyChangedFlags() @morphsThatMaybeChangedGeometryOrPosition = [] @morphsThatMaybeChangedFullGeometryOrPosition = [] # »>> this part is excluded from the fizzygum homepage build #ProfilingDataCollector.profileBrokenRects @broken, @numberOfDuplicatedBrokenRects, @numberOfMergedSourceAndDestination # this part is excluded from the fizzygum homepage build <<« # each broken rectangle requires traversing the scenegraph to # redraw what's overlapping it. Not all Widgets are traversed # in particular the following can stop the recursion: # - invisible Widgets # - PanelWdgts that don't overlap the broken rectangle # Since potentially there is a lot of traversal ongoing for # each broken rectangle, one might want to consolidate overlapping # and nearby rectangles. @healingRectanglesPhase = true @errorsWhileRepainting = [] @broken.forEach (rect) => if !rect? return if rect.isNotEmpty() try @fullPaintIntoAreaOrBlitFromBackBuffer @worldCanvasContext, rect catch err @resetWorldCanvasContext() @queueErrorForLaterReporting err @hideOffendingWidget() @softResetWorld() # IF we got errors while repainting, the # screen might be in a bad state (because everything in front of the # "bad" widget is not repainted since the offending widget has # thrown, so nothing in front of it could be painted properly) # SO do COMPLETE repaints of the screen and hide # further offending widgets until there are no more errors # (i.e. the offending widgets are progressively hidden so eventually # we should repaint the whole screen without errors, hopefully) if @errorsWhileRepainting.length != 0 @findOutAllOtherOffendingWidgetsAndPaintWholeScreen() if @showRedraws @showBrokenRects @worldCanvasContext @resetDataStructuresForBrokenRects() @healingRectanglesPhase = false if @trackChanges.length != 1 and @trackChanges[0] != true alert "trackChanges array should have only one element (true)" findOutAllOtherOffendingWidgetsAndPaintWholeScreen: -> # we keep repainting the whole screen until there are no # errors. # Why do we need multiple repaints and not just one? # Because remember that when a widget throws an error while # repainting, it bubble all the way up and stops any # further repainting of the other widgets, potentially # preventing the finding of errors in the other # widgets. Hence, we need to keep repainting until # there are no errors. currentErrorsCount = @errorsWhileRepainting.length previousErrorsCount = nil numberOfTotalRepaints = 0 until previousErrorsCount == currentErrorsCount numberOfTotalRepaints++ try @fullPaintIntoAreaOrBlitFromBackBuffer @worldCanvasContext, @bounds catch err @resetWorldCanvasContext() @queueErrorForLaterReporting err @hideOffendingWidget() @softResetWorld() previousErrorsCount = currentErrorsCount currentErrorsCount = @errorsWhileRepainting.length #console.log "total repaints: " + numberOfTotalRepaints resetWorldCanvasContext: -> # when an error is thrown while painting, it's # possible that we are left with a context in a strange # mixed state, so try to bring it back to # normality as much as possible # We are doing this for "cleanliness" of the context # state, not because we care of the drawing being # perfect (we are eventually going to repaint the # whole screen without the offending widgets) @worldCanvasContext.closePath() @worldCanvasContext.resetTransform?() for j in [1...2000] @worldCanvasContext.restore() queueErrorForLaterReporting: (err) -> # now record the error so we can report it in the # next cycle, and add the offending widget to a # "banned" list @errorsWhileRepainting.push err if !@widgetsGivingErrorWhileRepainting.includes @paintingWidget @widgetsGivingErrorWhileRepainting.push @paintingWidget @paintingWidget.silentHide() hideOffendingWidget: -> if !@widgetsGivingErrorWhileRepainting.includes @paintingWidget @widgetsGivingErrorWhileRepainting.push @paintingWidget @paintingWidget.silentHide() resetDataStructuresForBrokenRects: -> @broken = [] @duplicatedBrokenRectsTracker = {} @numberOfDuplicatedBrokenRects = 0 @numberOfMergedSourceAndDestination = 0 # »>> this part is excluded from the fizzygum homepage build addPinoutingMorphs: -> @currentPinoutingMorphs.forEach (eachPinoutingMorph) => if @morphsToBePinouted.has eachPinoutingMorph.wdgtThisWdgtIsPinouting if eachPinoutingMorph.wdgtThisWdgtIsPinouting.hasMaybeChangedGeometryOrPosition() # reposition the pinout morph if needed peekThroughBox = eachPinoutingMorph.wdgtThisWdgtIsPinouting.clippedThroughBounds() eachPinoutingMorph.fullRawMoveTo new Point(peekThroughBox.right() + 10,peekThroughBox.top()) else @currentPinoutingMorphs.delete eachPinoutingMorph @morphsBeingPinouted.delete eachPinoutingMorph.wdgtThisWdgtIsPinouting eachPinoutingMorph.wdgtThisWdgtIsPinouting = nil eachPinoutingMorph.fullDestroy() @morphsToBePinouted.forEach (eachMorphNeedingPinout) => unless @morphsBeingPinouted.has eachMorphNeedingPinout hM = new StringMorph2 eachMorphNeedingPinout.toString() @add hM hM.wdgtThisWdgtIsPinouting = eachMorphNeedingPinout peekThroughBox = eachMorphNeedingPinout.clippedThroughBounds() hM.fullRawMoveTo new Point(peekThroughBox.right() + 10,peekThroughBox.top()) hM.setColor Color.BLUE hM.setWidth 400 @currentPinoutingMorphs.add hM @morphsBeingPinouted.add eachMorphNeedingPinout # this part is excluded from the fizzygum homepage build <<« addHighlightingMorphs: -> @currentHighlightingMorphs.forEach (eachHighlightingMorph) => if @morphsToBeHighlighted.has eachHighlightingMorph.wdgtThisWdgtIsHighlighting if eachHighlightingMorph.wdgtThisWdgtIsHighlighting.hasMaybeChangedGeometryOrPosition() eachHighlightingMorph.rawSetBounds eachHighlightingMorph.wdgtThisWdgtIsHighlighting.clippedThroughBounds() else @currentHighlightingMorphs.delete eachHighlightingMorph @morphsBeingHighlighted.delete eachHighlightingMorph.wdgtThisWdgtIsHighlighting eachHighlightingMorph.wdgtThisWdgtIsHighlighting = nil eachHighlightingMorph.fullDestroy() @morphsToBeHighlighted.forEach (eachMorphNeedingHighlight) => unless @morphsBeingHighlighted.has eachMorphNeedingHighlight hM = new HighlighterMorph @add hM hM.wdgtThisWdgtIsHighlighting = eachMorphNeedingHighlight hM.rawSetBounds eachMorphNeedingHighlight.clippedThroughBounds() hM.setColor Color.BLUE hM.setAlphaScaled 50 @currentHighlightingMorphs.add hM @morphsBeingHighlighted.add eachMorphNeedingHighlight # »>> this part is only needed for Macros progressOnMacroSteps: -> noCodeLoading: -> true noInputsOngoing: -> @eventsQueue.length == 0 # other useful tween functions here: # https://github.com/ashblue/simple-tween-js/blob/master/tween.js expoOut: (i, origin, distance, numberOfEvents) -> distance * (-Math.pow(2, -10 * i/numberOfEvents) + 1) + origin bringUpTestMenu: (millisecondsBetweenKeys = 35, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> @syntheticEventsShortcutsAndSpecialKeys "F2", millisecondsBetweenKeys, startTime syntheticEventsShortcutsAndSpecialKeys: (whichShortcutOrSpecialKey, millisecondsBetweenKeys = 35, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> switch whichShortcutOrSpecialKey when "F2" @eventsQueue.push new KeydownInputEvent "F2", "F2", false, false, false, false, true, startTime @eventsQueue.push new KeyupInputEvent "F2", "F2", false, false, false, false, true, startTime + millisecondsBetweenKeys syntheticEventsStringKeys: (theString, millisecondsBetweenKeys = 35, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> scheduledTimeOfEvent = startTime for i in [0...theString.length] isUpperCase = theString.charAt(i) == theString.charAt(i).toUpperCase() if isUpperCase @eventsQueue.push new KeydownInputEvent "Shift", "ShiftLeft", true, false, false, false, true, scheduledTimeOfEvent scheduledTimeOfEvent += millisecondsBetweenKeys # note that the second parameter (code) we are making up, assuming a hypothetical "1:1" key->code layout @eventsQueue.push new KeydownInputEvent theString.charAt(i), theString.charAt(i), isUpperCase, false, false, false, true, scheduledTimeOfEvent scheduledTimeOfEvent += millisecondsBetweenKeys # note that the second parameter (code) we are making up, assuming a hypothetical "1:1" key->code layout @eventsQueue.push new KeyupInputEvent theString.charAt(i), theString.charAt(i), isUpperCase, false, false, false, true, scheduledTimeOfEvent scheduledTimeOfEvent += millisecondsBetweenKeys if isUpperCase @eventsQueue.push new KeyupInputEvent "Shift", "ShiftLeft", false, false, false, false, true, scheduledTimeOfEvent scheduledTimeOfEvent += millisecondsBetweenKeys syntheticEventsMouseMovePressDragRelease: (orig, dest, millisecondsForDrag = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime(), numberOfEventsPerMillisecond = 1) -> @syntheticEventsMouseMove orig, "left button", 100, nil, startTime, numberOfEventsPerMillisecond @syntheticEventsMouseDown "left button", startTime + 100 @syntheticEventsMouseMove dest, "left button", millisecondsForDrag, orig, startTime + 100 + 100, numberOfEventsPerMillisecond @syntheticEventsMouseUp "left button", startTime + 100 + 100 + millisecondsForDrag + 100 # This should be used if you want to drag from point A to B to C ... # If rather you want to just drag from point A to point B, # then just use syntheticEventsMouseMovePressDragRelease syntheticEventsMouseMoveWhileDragging: (dest, milliseconds = 1000, orig = @hand.position(), startTime = WorldMorph.dateOfCurrentCycleStart.getTime(), numberOfEventsPerMillisecond = 1) -> @syntheticEventsMouseMove dest, "left button", milliseconds, orig, startTime, numberOfEventsPerMillisecond # mouse moves need an origin and a destination, so we # need to place the mouse in _some_ place to begin with # in order to do that. syntheticEventsMousePlace: (place = new Point(0,0), scheduledTimeOfEvent = WorldMorph.dateOfCurrentCycleStart.getTime()) -> @eventsQueue.push new MousemoveInputEvent place.x, place.y, 0, 0, false, false, false, false, true, scheduledTimeOfEvent syntheticEventsMouseMove: (dest, whichButton = "no button", milliseconds = 1000, orig = @hand.position(), startTime = WorldMorph.dateOfCurrentCycleStart.getTime(), numberOfEventsPerMillisecond = 1) -> if whichButton == "left button" button = 0 buttons = 1 else if whichButton == "no button" button = 0 buttons = 0 else if whichButton == "right button" button = 0 buttons = 2 else debugger throw "syntheticEventsMouseMove: whichButton is unknown" if dest instanceof Widget dest = dest.center() if orig instanceof Widget orig = orig.center() numberOfEvents = milliseconds * numberOfEventsPerMillisecond for i in [0...numberOfEvents] scheduledTimeOfEvent = startTime + i/numberOfEventsPerMillisecond nextX = Math.round @expoOut i, orig.x, (dest.x-orig.x), numberOfEvents nextY = Math.round @expoOut i, orig.y, (dest.y-orig.y), numberOfEvents if nextX != prevX or nextY != prevY prevX = nextX prevY = nextY #console.log nextX + " " + nextY + " scheduled at: " + scheduledTimeOfEvent @eventsQueue.push new MousemoveInputEvent nextX, nextY, button, buttons, false, false, false, false, true, scheduledTimeOfEvent syntheticEventsMouseClick: (whichButton = "left button", milliseconds = 100, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> @syntheticEventsMouseDown whichButton, startTime @syntheticEventsMouseUp whichButton, startTime + milliseconds syntheticEventsMouseDown: (whichButton = "left button", startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> if whichButton == "left button" button = 0 buttons = 1 else if whichButton == "right button" button = 2 buttons = 2 else debugger throw "syntheticEventsMouseDown: whichButton is unknown" @eventsQueue.push new MousedownInputEvent button, buttons, false, false, false, false, true, startTime syntheticEventsMouseUp: (whichButton = "left button", startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> if whichButton == "left button" button = 0 buttons = 0 else if whichButton == "right button" button = 2 buttons = 0 else debugger throw "syntheticEventsMouseUp: whichButton is unknown" @eventsQueue.push new MouseupInputEvent button, buttons, false, false, false, false, true, startTime moveToAndClick: (positionOrWidget, whichButton = "left button", milliseconds = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> @syntheticEventsMouseMove positionOrWidget, "no button", milliseconds, nil, startTime, nil @syntheticEventsMouseClick whichButton, 100, startTime + milliseconds + 100 openMenuOf: (widget, milliseconds = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> @moveToAndClick widget, "right button", milliseconds, startTime getMostRecentlyOpenedMenu: -> # gets the last element added to the "freshlyCreatedPopUps" set # (Sets keep order of insertion) Array.from(@freshlyCreatedPopUps).pop() getTextMenuItemFromMenu: (theMenu, theLabel) -> theMenu.topWdgtSuchThat (item) -> if item.labelString? item.labelString == theLabel else false moveToItemOfTopMenuAndClick: (theLabel) -> theMenu = @getMostRecentlyOpenedMenu() theItem = @getTextMenuItemFromMenu theMenu, theLabel @moveToAndClick theItem findTopWidgetByClassNameOrClass: (widgetNameOrClass) -> if typeof widgetNameOrClass == "string" @topWdgtSuchThat (item) -> item.morphClassString() == "AnalogClockWdgt" else @topWdgtSuchThat (item) -> item instanceof widgetNameOrClass calculateVertBarMovement: (vBar, index, total) -> vBarHandle = vBar.children[0] vBarHandleCenter = vBarHandle.center() highestHandlePosition = vBar.top() lowestHandlePosition = vBar.bottom() - vBarHandle.height() highestHandleCenterPosition = highestHandlePosition + vBarHandle.height()/2 lowestHandleCenterPosition = lowestHandlePosition + vBarHandle.height()/2 handleCenterRange = lowestHandleCenterPosition - highestHandleCenterPosition handleCenterOffset = Math.round index * handleCenterRange / (total-1) [vBarHandleCenter, vBarHandleCenter.translateBy new Point(0,handleCenterOffset)] bringListItemFromTopInspectorInView: (listItemString) -> inspectorNaked = @findTopWidgetByClassNameOrClass InspectorMorph2 list = inspectorNaked.list elements = list.elements vBar = list.vBar index = elements.indexOf listItemString total = elements.length [vBarCenterFromHere, vBarCenterToHere] = @calculateVertBarMovement vBar, index, total @syntheticEventsMouseMovePressDragRelease vBarCenterFromHere, vBarCenterToHere clickOnListItemFromTopInspector: (listItemString, milliseconds = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> inspectorNaked = @findTopWidgetByClassNameOrClass InspectorMorph2 list = inspectorNaked.list entry = list.topWdgtSuchThat (item) -> if item.text? item.text == listItemString else false entryTopLeft = entry.topLeft() @moveToAndClick entryTopLeft.translateBy(new Point 10, 2), "left button", milliseconds, startTime clickOnCodeBoxFromTopInspectorAtCodeString: (codeString, occurrenceNumber = 1, after = true, milliseconds = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> inspectorNaked = @findTopWidgetByClassNameOrClass InspectorMorph2 slotCoords = inspectorNaked.textMorph.text.getNthPositionInStringBeforeOrAfter codeString, occurrenceNumber, after clickPosition = inspectorNaked.textMorph.slotCoordinates(slotCoords).translateBy new Point 3,3 @moveToAndClick clickPosition, "left button", milliseconds, startTime clickOnSaveButtonFromTopInspector: (milliseconds = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> inspectorNaked = @findTopWidgetByClassNameOrClass InspectorMorph2 saveButton = inspectorNaked.saveButton @moveToAndClick saveButton, "left button", milliseconds, startTime bringcodeStringFromTopInspectorInView: (codeString, occurrenceNumber = 1, after = true) -> inspectorNaked = @findTopWidgetByClassNameOrClass InspectorMorph2 slotCoords = inspectorNaked.textMorph.text.getNthPositionInStringBeforeOrAfter codeString, occurrenceNumber, after textScrollPane = inspectorNaked.topWdgtSuchThat (item) -> item.morphClassString() == "SimplePlainTextScrollPanelWdgt" textMorph = inspectorNaked.textMorph vBar = textScrollPane.vBar index = textMorph.slotRowAndColumn(slotCoords)[0] total = textMorph.wrappedLines.length [vBarCenterFromHere, vBarCenterToHere] = @calculateVertBarMovement vBar, index, total @syntheticEventsMouseMovePressDragRelease vBarCenterFromHere, vBarCenterToHere draftRunMacro: -> # When does it make sense to generate events "just via functions" vs. # needing a macro? # # **Important Note:** a macro can call functions, while functions # can never include macros!!! # # A macro is needed: # 1. for generating (potentially via functions!) events spanning # multiple cycles. E.g. "opening the inspector for a widget", # which involves moving the mouse there, right-clicking on # the widget, wait a cycle for the menu to come up, then # navigating other menus, until finally finding and # clicking on a "inspect" entry, # and finally waiting a cycle for the inspector to come up. # Those things *together* can't be done using functions alone # (i.e. with no macros), because functions can only push # synthetic events (now or in the future) all at once. # 2. so to have a convenient way to specify pauses between # events. This could also be done with functions, however # it's more convoluted. # # For all other cases, macros are not needed, i.e. functions alone # can suffice. Note that # functions *can* specify events that # happen over time e.g. multiple key strokes and events # happening over a few seconds, as there are parameters that help # to specify dates of events in the future. As mentioned though, # functions alone cannot "see past the effects" of any event happening # in the future. # # Examples of macros (potentially using functions): # - opening a menu of a widget AND clicking on one of its items # - opening inspector for a widget # - opening inspector for a widget, changing a method, then # clicking "save" # # Examples that don't need macros (functions alone are OK): # - moving an icon to the bin # - closing the top window # - opening the menu of a widget # - moving pointer to entry of top menu and clicking it macroSubroutines = new Set macroSubroutines.add Macro.fromString """ Macro bringUpInspector whichWidget ⤷clickMenuItemOfWidget whichWidget | "dev ➜" ▶ when no inputs ongoing @moveToItemOfTopMenuAndClick "inspect" """ macroSubroutines.add Macro.fromString """ Macro bringUpInspectorAndSelectListItem whichWidget | whichItem ⤷bringUpInspector whichWidget ▶ when no inputs ongoing ⤷bringInViewAndClickOnListItemFromTopInspector whichItem """ macroSubroutines.add Macro.fromString """ Macro bringInViewAndClickOnListItemFromTopInspector whichItem @bringListItemFromTopInspectorInView whichItem ▶ when no inputs ongoing @clickOnListItemFromTopInspector whichItem """ macroSubroutines.add Macro.fromString """ Macro clickMenuItemOfWidget whichWidget | whichItem @openMenuOf whichWidget ▶ when no inputs ongoing @moveToItemOfTopMenuAndClick whichItem """ macroSubroutines.add Macro.fromString """ Macro printoutsMacro string1 | string2 | string3 ▶ ⌛ 1s 🖨️ string1 ▶ ⌛ 1s 🖨️ string2 💼aLocalVariableInACall = "" ▶ ⌛ 1s 🖨️ string3 """ macroSubroutines.add Macro.fromString """ Macro macroWithNoParams 🖨️ "macro with no params" """ macroSubroutines.add Macro.fromString """ Macro macroWithOneParam theParameter 🖨️ "macro with one param: " + theParameter """ macroSubroutines.add Macro.fromString """ Macro macroWithOneParamButPassingNone theParameter 🖨️ "macro with one param but passing none, this should be undefined: " + theParameter """ macroSubroutines.add Macro.fromString """ Macro macroWithTwoParamsButPassingOnlyOne param1 | param2 🖨️ "macro with two params but passing only one: param 1: " + param1 + " param 2 should be undefined: " + param2 """ # TODO check that these are handled too # ▶ ⌛ 500 ms, when condition1() # ▶ # ⌛ 500 ms, when conditionCommented() mainMacro = Macro.fromString """ Macro theTestMacro @syntheticEventsStringKeys "SoMeThInG" ▶ ⌛ 1s ▶ ⤷printoutsMacro "first console out" | "second console out" | "third console out" ▶ ⌛ 1s 💼clock = @findTopWidgetByClassNameOrClass AnalogClockWdgt @syntheticEventsMouseMove 💼clock ▶ when no inputs ongoing @syntheticEventsMouseDown() ▶ when no inputs ongoing 💼clockCenter = 💼clock.center() @syntheticEventsMouseMoveWhileDragging ⦿(💼clockCenter.x - 4, 💼clockCenter.y + 4) ▶ ⌛ 1s @syntheticEventsMouseMoveWhileDragging ⦿(250,250) ▶ when no inputs ongoing @syntheticEventsMouseUp() ▶ when no inputs ongoing @syntheticEventsMouseMovePressDragRelease ⦿(5, 5), ⦿(200,200) ▶ when no inputs ongoing 🖨️ "finished the drag events" ⤷printoutsMacro "fourth console out" | "fifth console out" | "sixth console out" ▶ when no inputs ongoing ⤷bringUpInspectorAndSelectListItem 💼clock | "drawSecondsHand" ▶ when no inputs ongoing @bringcodeStringFromTopInspectorInView "context.restore()" ▶ when no inputs ongoing @clickOnCodeBoxFromTopInspectorAtCodeString "@secondsHandAngle", 1, false ▶ when no inputs ongoing @syntheticEventsStringKeys "-" @clickOnSaveButtonFromTopInspector() # some comments here ▶ when no inputs ongoing # also some comments here ⤷macroWithNoParams ⤷macroWithOneParam "here is the one param" ⤷macroWithOneParamButPassingNone ⤷macroWithTwoParamsButPassingOnlyOne "first parameter" ⤷macroWithNoParams # comment1 ⤷macroWithOneParam "here is the one param" # comment2 ⤷macroWithOneParamButPassingNone # comment3 ⤷macroWithTwoParamsButPassingOnlyOne "first parameter" # comment4 @bringUpTestMenu() """ mainMacro.linkTo macroSubroutines mainMacro.start() # this part is only needed for Macros <<« playQueuedEvents: -> try timeOfCurrentCycleStart = WorldMorph.dateOfCurrentCycleStart.getTime() for event in @eventsQueue if !event.time? then debugger # this happens when you consume synthetic events: you can inject # MANY of them across frames (say, a slow drag across the screen), # so you want to consume only the ones that pertain to the current # frame and return if event.time > timeOfCurrentCycleStart @eventsQueue.splice 0, @eventsQueue.indexOf(event) return # currently not handled: DOM virtual keyboard events event.processEvent() catch err @softResetWorld() if !@errorConsole? then @createErrorConsole() @errorConsole.contents.showUpWithError err @eventsQueue = [] # we keep the "pacing" promises in this # framePacedPromises array, (or, more precisely, # we keep their resolving functions) and each frame # we resolve one, so we don't cause gitter. progressFramePacedActions: -> if window.framePacedPromises.length > 0 resolvingFunction = window.framePacedPromises.shift() resolvingFunction.call() showErrorsHappenedInRepaintingStepInPreviousCycle: -> for eachErr in @errorsWhileRepainting if !@errorConsole? then @createErrorConsole() @errorConsole.contents.showUpWithError eachErr updateTimeReferences: -> WorldMorph.dateOfCurrentCycleStart = new Date if !WorldMorph.dateOfPreviousCycleStart? WorldMorph.dateOfPreviousCycleStart = new Date WorldMorph.dateOfCurrentCycleStart.getTime() - 30 # »>> this part is only needed for Macros if !@macroStepsWaitingTimer? @macroStepsWaitingTimer = 0 else @macroStepsWaitingTimer += WorldMorph.dateOfCurrentCycleStart.getTime() - WorldMorph.dateOfPreviousCycleStart.getTime() # this part is only needed for Macros <<« doOneCycle: -> @updateTimeReferences() #console.log TextMorph.instancesCounter + " " + StringMorph.instancesCounter @showErrorsHappenedInRepaintingStepInPreviousCycle() # »>> this part is only needed for Macros @progressOnMacroSteps() # this part is only needed for Macros <<« @playQueuedEvents() # replays test actions at the right time if AutomatorPlayer? and Automator.state == Automator.PLAYING @automator.player.replayTestCommands() # currently unused @runOtherTasksStepFunction() # used to load fizzygum sources progressively @progressFramePacedActions() @runChildrensStepFunction() @hand.reCheckMouseEntersAndMouseLeavesAfterPotentialGeometryChanges() window.recalculatingLayouts = true @recalculateLayouts() window.recalculatingLayouts = false # »>> this part is excluded from the fizzygum homepage build @addPinoutingMorphs() # this part is excluded from the fizzygum homepage build <<« @addHighlightingMorphs() # here is where the repainting on screen happens @updateBroken() WorldMorph.frameCount++ WorldMorph.dateOfPreviousCycleStart = WorldMorph.dateOfCurrentCycleStart WorldMorph.dateOfCurrentCycleStart = nil # Widget stepping: runChildrensStepFunction: -> # TODO all these set modifications should be immutable... @steppingWdgts.forEach (eachSteppingMorph) => #if eachSteppingMorph.isBeingFloatDragged() # continue # for objects where @fps is defined, check which ones are due to be stepped # and which ones want to wait. millisBetweenSteps = Math.round(1000 / eachSteppingMorph.fps) timeOfCurrentCycleStart = WorldMorph.dateOfCurrentCycleStart.getTime() if eachSteppingMorph.fps <= 0 # if fps 0 or negative, then just run as fast as possible, # so 0 milliseconds remaining to the next invocation millisecondsRemainingToWaitedFrame = 0 else if eachSteppingMorph.synchronisedStepping millisecondsRemainingToWaitedFrame = millisBetweenSteps - (timeOfCurrentCycleStart % millisBetweenSteps) if eachSteppingMorph.previousMillisecondsRemainingToWaitedFrame != 0 and millisecondsRemainingToWaitedFrame > eachSteppingMorph.previousMillisecondsRemainingToWaitedFrame millisecondsRemainingToWaitedFrame = 0 eachSteppingMorph.previousMillisecondsRemainingToWaitedFrame = millisecondsRemainingToWaitedFrame #console.log millisBetweenSteps + " " + millisecondsRemainingToWaitedFrame else elapsedMilliseconds = timeOfCurrentCycleStart - eachSteppingMorph.lastTime millisecondsRemainingToWaitedFrame = millisBetweenSteps - elapsedMilliseconds # when the firing time comes (or as soon as it's past): if millisecondsRemainingToWaitedFrame <= 0 @stepWidget eachSteppingMorph # Increment "lastTime" by millisBetweenSteps. Two notes: # 1) We don't just set it to timeOfCurrentCycleStart so that there is no drifting # in running it the next time: we run it the next time as if this time it # ran exactly on time. # 2) We are going to update "last time" with the loop # below. This is because in case the window is not in foreground, # requestAnimationFrame doesn't run, so we might skip a number of steps. # In such cases, just bring "lastTime" up to speed here. # If we don't do that, "skipped" steps would catch up on us and run all # in contiguous frames when the window comes to foreground, so the # widgets would animate frantically (every frame) catching up on # all the steps they missed. We don't want that. # # while eachSteppingMorph.lastTime + millisBetweenSteps < timeOfCurrentCycleStart # eachSteppingMorph.lastTime += millisBetweenSteps # # 3) and finally, here is the equivalent of the loop above, but done # in one shot using remainders. # Again: we are looking for the last "multiple" k such that # lastTime + k * millisBetweenSteps # is less than timeOfCurrentCycleStart. eachSteppingMorph.lastTime = timeOfCurrentCycleStart - ((timeOfCurrentCycleStart - eachSteppingMorph.lastTime) % millisBetweenSteps) stepWidget: (whichWidget) -> if whichWidget.onNextStep nxt = whichWidget.onNextStep whichWidget.onNextStep = nil nxt.call whichWidget if !whichWidget.step? debugger try whichWidget.step() #console.log "stepping " + whichWidget catch err @softResetWorld() if !@errorConsole? then @createErrorConsole() @errorConsole.contents.showUpWithError err runOtherTasksStepFunction : -> for task in @otherTasksToBeRunOnStep #console.log "running a task: " + task task() # »>> this part is excluded from the fizzygum homepage build sizeCanvasToTestScreenResolution: -> @worldCanvas.width = Math.round(960 * ceilPixelRatio) @worldCanvas.height = Math.round(440 * ceilPixelRatio) @worldCanvas.style.width = "960px" @worldCanvas.style.height = "440px" bkground = document.getElementById("background") bkground.style.width = "960px" bkground.style.height = "720px" bkground.style.backgroundColor = Color.WHITESMOKE.toString() # this part is excluded from the fizzygum homepage build <<« stretchWorldToFillEntirePage: -> # once you call this, the world will forever take the whole page @automaticallyAdjustToFillEntireBrowserAlsoOnResize = true pos = @getCanvasPosition() clientHeight = window.innerHeight clientWidth = window.innerWidth if pos.x > 0 @worldCanvas.style.position = "absolute" @worldCanvas.style.left = "0px" pos.x = 0 if pos.y > 0 @worldCanvas.style.position = "absolute" @worldCanvas.style.top = "0px" pos.y = 0 # scrolled down b/c of viewport scaling clientHeight = document.documentElement.clientHeight if document.body.scrollTop # scrolled left b/c of viewport scaling clientWidth = document.documentElement.clientWidth if document.body.scrollLeft if (@worldCanvas.width isnt clientWidth) or (@worldCanvas.height isnt clientHeight) @fullChanged() @worldCanvas.width = (clientWidth * ceilPixelRatio) @worldCanvas.style.width = clientWidth + "px" @worldCanvas.height = (clientHeight * ceilPixelRatio) @worldCanvas.style.height = clientHeight + "px" @rawSetExtent new Point clientWidth, clientHeight @desktopReLayout() desktopReLayout: -> basementOpenerWdgt = @firstChildSuchThat (w) -> w instanceof BasementOpenerWdgt if basementOpenerWdgt? if basementOpenerWdgt.userMovedThisFromComputedPosition basementOpenerWdgt.fullRawMoveInDesktopToFractionalPosition() if !basementOpenerWdgt.wasPositionedSlightlyOutsidePanel basementOpenerWdgt.fullRawMoveWithin @ else basementOpenerWdgt.fullMoveTo @bottomRight().subtract (new Point 75, 75).add @desktopSidesPadding analogClockWdgt = @firstChildSuchThat (w) -> w instanceof AnalogClockWdgt if analogClockWdgt? if analogClockWdgt.userMovedThisFromComputedPosition analogClockWdgt.fullRawMoveInDesktopToFractionalPosition() if !analogClockWdgt.wasPositionedSlightlyOutsidePanel analogClockWdgt.fullRawMoveWithin @ else analogClockWdgt.fullMoveTo new Point @right() - 80 - @desktopSidesPadding, @top() + @desktopSidesPadding @children.forEach (child) => if child != basementOpenerWdgt and child != analogClockWdgt and !(child instanceof WidgetHolderWithCaptionWdgt) if child.positionFractionalInHoldingPanel? child.fullRawMoveInDesktopToFractionalPosition() if !child.wasPositionedSlightlyOutsidePanel child.fullRawMoveWithin @ # WorldMorph events: # »>> this part is excluded from the fizzygum homepage build initVirtualKeyboard: -> if @inputDOMElementForVirtualKeyboard document.body.removeChild @inputDOMElementForVirtualKeyboard @inputDOMElementForVirtualKeyboard = nil unless (WorldMorph.preferencesAndSettings.isTouchDevice and WorldMorph.preferencesAndSettings.useVirtualKeyboard) return @inputDOMElementForVirtualKeyboard = document.createElement "input" @inputDOMElementForVirtualKeyboard.type = "text" @inputDOMElementForVirtualKeyboard.style.color = Color.TRANSPARENT.toString() @inputDOMElementForVirtualKeyboard.style.backgroundColor = Color.TRANSPARENT.toString() @inputDOMElementForVirtualKeyboard.style.border = "none" @inputDOMElementForVirtualKeyboard.style.outline = "none" @inputDOMElementForVirtualKeyboard.style.position = "absolute" @inputDOMElementForVirtualKeyboard.style.top = "0px" @inputDOMElementForVirtualKeyboard.style.left = "0px" @inputDOMElementForVirtualKeyboard.style.width = "0px" @inputDOMElementForVirtualKeyboard.style.height = "0px" @inputDOMElementForVirtualKeyboard.autocapitalize = "none" # iOS specific document.body.appendChild @inputDOMElementForVirtualKeyboard @inputDOMElementForVirtualKeyboardKeydownBrowserEventListener = (event) => @eventsQueue.push InputDOMElementForVirtualKeyboardKeydownInputEvent.fromBrowserEvent event # Default in several browsers # is for the backspace button to trigger # the "back button", so we prevent that # default here. if event.keyIdentifier is "U+0008" or event.keyIdentifier is "Backspace" event.preventDefault() # suppress tab override and make sure tab gets # received by all browsers if event.keyIdentifier is "U+0009" or event.keyIdentifier is "Tab" event.preventDefault() @inputDOMElementForVirtualKeyboard.addEventListener "keydown", @inputDOMElementForVirtualKeyboardKeydownBrowserEventListener, false @inputDOMElementForVirtualKeyboardKeyupBrowserEventListener = (event) => @eventsQueue.push InputDOMElementForVirtualKeyboardKeyupInputEvent.fromBrowserEvent event event.preventDefault() @inputDOMElementForVirtualKeyboard.addEventListener "keyup", @inputDOMElementForVirtualKeyboardKeyupBrowserEventListener, false # Keypress events are deprecated in the JS specs and are not needed @inputDOMElementForVirtualKeyboardKeypressBrowserEventListener = (event) => #@eventsQueue.push event event.preventDefault() @inputDOMElementForVirtualKeyboard.addEventListener "keypress", @inputDOMElementForVirtualKeyboardKeypressBrowserEventListener, false # this part is excluded from the fizzygum homepage build <<« getPointerAndWdgtInfo: (topWdgtUnderPointer = @hand.topWdgtUnderPointer()) -> # we might eliminate this command afterwards if # we find out user is clicking on a menu item # or right-clicking on a morph absoluteBoundsOfMorphRelativeToWorld = topWdgtUnderPointer.boundingBox().asArray_xywh() morphIdentifierViaTextLabel = topWdgtUnderPointer.identifyViaTextLabel() morphPathRelativeToWorld = topWdgtUnderPointer.pathOfChildrenPositionsRelativeToWorld() pointerPositionFractionalInMorph = @hand.positionFractionalInMorph topWdgtUnderPointer pointerPositionPixelsInMorph = @hand.positionPixelsInMorph topWdgtUnderPointer # note that this pointer position is in world # coordinates not in page coordinates pointerPositionPixelsInWorld = @hand.position() isPartOfListMorph = (topWdgtUnderPointer.parentThatIsA ListMorph)? return [ topWdgtUnderPointer.uniqueIDString(), morphPathRelativeToWorld, morphIdentifierViaTextLabel, absoluteBoundsOfMorphRelativeToWorld, pointerPositionFractionalInMorph, pointerPositionPixelsInMorph, pointerPositionPixelsInWorld, isPartOfListMorph] # ----------------------------------------------------- # clipboard events processing # ----------------------------------------------------- initMouseEventListeners: -> canvas = @worldCanvas # there is indeed a "dblclick" JS event # but we reproduce it internally. # The reason is that we do so for "click" # because we want to check that the mouse # button was released in the same morph # where it was pressed (cause in the DOM you'd # be pressing and releasing on the same # element i.e. the canvas anyways # so we receive clicks even though they aren't # so we have to take care of the processing # ourselves). # So we also do the same internal # processing for dblclick. # Hence, don't register this event listener # below... #@dblclickEventListener = (event) => # event.preventDefault() # @hand.processDoubleClick event #canvas.addEventListener "dblclick", @dblclickEventListener, false @mousedownBrowserEventListener = (event) => @eventsQueue.push MousedownInputEvent.fromBrowserEvent event canvas.addEventListener "mousedown", @mousedownBrowserEventListener, false @mouseupBrowserEventListener = (event) => @eventsQueue.push MouseupInputEvent.fromBrowserEvent event canvas.addEventListener "mouseup", @mouseupBrowserEventListener, false @mousemoveBrowserEventListener = (event) => @eventsQueue.push MousemoveInputEvent.fromBrowserEvent event canvas.addEventListener "mousemove", @mousemoveBrowserEventListener, false initTouchEventListeners: -> canvas = @worldCanvas @touchstartBrowserEventListener = (event) => @eventsQueue.push TouchstartInputEvent.fromBrowserEvent event event.preventDefault() # (unsure that this one is needed) canvas.addEventListener "touchstart", @touchstartBrowserEventListener, false @touchendBrowserEventListener = (event) => @eventsQueue.push TouchendInputEvent.fromBrowserEvent event event.preventDefault() # prevent mouse events emulation canvas.addEventListener "touchend", @touchendBrowserEventListener, false @touchmoveBrowserEventListener = (event) => @eventsQueue.push TouchmoveInputEvent.fromBrowserEvent event event.preventDefault() # (unsure that this one is needed) canvas.addEventListener "touchmove", @touchmoveBrowserEventListener, false @gesturestartBrowserEventListener = (event) => # we don't do anything with gestures for the time being event.preventDefault() # (unsure that this one is needed) canvas.addEventListener "gesturestart", @gesturestartBrowserEventListener, false @gesturechangeBrowserEventListener = (event) => # we don't do anything with gestures for the time being event.preventDefault() # (unsure that this one is needed) canvas.addEventListener "gesturechange", @gesturechangeBrowserEventListener, false initKeyboardEventListeners: -> canvas = @worldCanvas @keydownBrowserEventListener = (event) => @eventsQueue.push KeydownInputEvent.fromBrowserEvent event # this paragraph is to prevent the browser going # "back button" when the user presses delete backspace. # taken from http://stackoverflow.com/a/2768256 doPrevent = false if event.key == "Backspace" d = event.srcElement or event.target if d.tagName.toUpperCase() == 'INPUT' and (d.type.toUpperCase() == 'TEXT' or d.type.toUpperCase() == 'PASSWORD' or d.type.toUpperCase() == 'FILE' or d.type.toUpperCase() == 'SEARCH' or d.type.toUpperCase() == 'EMAIL' or d.type.toUpperCase() == 'NUMBER' or d.type.toUpperCase() == 'DATE') or d.tagName.toUpperCase() == 'TEXTAREA' doPrevent = d.readOnly or d.disabled else doPrevent = true # this paragraph is to prevent the browser scrolling when # user presses spacebar, see # https://stackoverflow.com/a/22559917 if event.key == " " and event.target == @worldCanvas # Note that doing a preventDefault on the spacebar # causes it not to generate the keypress event # (just the keydown), so we had to modify the keydown # to also process the space. # (I tried to use stopPropagation instead/inaddition but # it didn't work). doPrevent = true # also browsers tend to do special things when "tab" # is pressed, so let's avoid that if event.key == "Tab" and event.target == @worldCanvas doPrevent = true if doPrevent event.preventDefault() canvas.addEventListener "keydown", @keydownBrowserEventListener, false @keyupBrowserEventListener = (event) => @eventsQueue.push KeyupInputEvent.fromBrowserEvent event canvas.addEventListener "keyup", @keyupBrowserEventListener, false # keypress is deprecated in the latest specs, and it's really not needed/used, # since all keys really have an effect when they are pushed down @keypressBrowserEventListener = (event) => canvas.addEventListener "keypress", @keypressBrowserEventListener, false initClipboardEventListeners: -> # snippets of clipboard-handling code taken from # http://codebits.glennjones.net/editing/setclipboarddata.htm # Note that this works only in Chrome. Firefox and Safari need a piece of # text to be selected in order to even trigger the copy event. Chrome does # enable clipboard access instead even if nothing is selected. # There are a couple of solutions to this - one is to keep a hidden textfield that # handles all copy/paste operations. # Another one is to not use a clipboard, but rather an internal string as # local memory. So the OS clipboard wouldn't be used, but at least there would # be some copy/paste working. Also one would need to intercept the copy/paste # key combinations manually instead of from the copy/paste events. # ----------------------------------------------------- # clipboard events listeners # ----------------------------------------------------- # we deal with the clipboard here in the event listeners # because for security reasons the runtime is not allowed # access to the clipboards outside of here. So we do all # we have to do with the clipboard here, and in every # other place we work with text. @cutBrowserEventListener = (event) => # TODO this should follow the fromBrowserEvent pattern @eventsQueue.push CutInputEvent.fromBrowserEvent event document.body.addEventListener "cut", @cutBrowserEventListener, false @copyBrowserEventListener = (event) => # TODO this should follow the fromBrowserEvent pattern @eventsQueue.push CopyInputEvent.fromBrowserEvent event document.body.addEventListener "copy", @copyBrowserEventListener, false @pasteBrowserEventListener = (event) => # TODO this should follow the fromBrowserEvent pattern @eventsQueue.push PasteInputEvent.fromBrowserEvent event document.body.addEventListener "paste", @pasteBrowserEventListener, false initKeyCombosEventListeners: -> # »>> this part is excluded from the fizzygum homepage build #console.log "binding via mousetrap" @keyComboResetWorldEventListener = (event) => if AutomatorRecorder? @automator.recorder.resetWorld() false Mousetrap.bind ["alt+d"], @keyComboResetWorldEventListener @keyComboTurnOnAnimationsPacingControl = (event) => if Automator? @automator.recorder.turnOnAnimationsPacingControl() false Mousetrap.bind ["alt+e"], @keyComboTurnOnAnimationsPacingControl @keyComboTurnOffAnimationsPacingControl = (event) => if Automator? @automator.recorder.turnOffAnimationsPacingControl() false Mousetrap.bind ["alt+u"], @keyComboTurnOffAnimationsPacingControl @keyComboTakeScreenshotEventListener = (event) => if AutomatorRecorder? @automator.recorder.addTakeScreenshotCommand() false Mousetrap.bind ["alt+c"], @keyComboTakeScreenshotEventListener @keyComboStopTestRecordingEventListener = (event) => if Automator? @automator.recorder.stopTestRecording() false Mousetrap.bind ["alt+t"], @keyComboStopTestRecordingEventListener @keyComboAddTestCommentEventListener = (event) => if Automator? @automator.recorder.addTestComment() false Mousetrap.bind ["alt+m"], @keyComboAddTestCommentEventListener @keyComboCheckNumberOfMenuItemsEventListener = (event) => if AutomatorRecorder? @automator.recorder.addCheckNumberOfItemsInMenuCommand() false Mousetrap.bind ["alt+k"], @keyComboCheckNumberOfMenuItemsEventListener @keyComboCheckStringsOfItemsInMenuOrderImportant = (event) => if AutomatorRecorder? @automator.recorder.addCheckStringsOfItemsInMenuOrderImportantCommand() false Mousetrap.bind ["alt+a"], @keyComboCheckStringsOfItemsInMenuOrderImportant @keyComboCheckStringsOfItemsInMenuOrderUnimportant = (event) => if AutomatorRecorder? @automator.recorder.addCheckStringsOfItemsInMenuOrderUnimportantCommand() false Mousetrap.bind ["alt+z"], @keyComboCheckStringsOfItemsInMenuOrderUnimportant # this part is excluded from the fizzygum homepage build <<« initOtherMiscEventListeners: -> canvas = @worldCanvas @contextmenuEventListener = (event) -> # suppress context menu for Mac-Firefox event.preventDefault() canvas.addEventListener "contextmenu", @contextmenuEventListener, false # Safari, Chrome @wheelBrowserEventListener = (event) => @eventsQueue.push WheelInputEvent.fromBrowserEvent event event.preventDefault() canvas.addEventListener "wheel", @wheelBrowserEventListener, false # CHECK AFTER 15 Jan 2021 00:00:00 GMT # As of Oct 2020, using mouse/trackpad in # Mobile Safari, the wheel event is not sent. # See: # https://github.com/cdr/code-server/issues/1455 # https://bugs.webkit.org/show_bug.cgi?id=210071 # However, the scroll event is sent, and when that is sent, # we can use the window.pageYOffset # to re-create a passable, fake wheel event. if Utils.runningInMobileSafari() window.addEventListener "scroll", @wheelBrowserEventListener, false @dragoverEventListener = (event) -> event.preventDefault() window.addEventListener "dragover", @dragoverEventListener, false @dropBrowserEventListener = (event) => # nothing here, although code for handling a "drop" is in the # comments event.preventDefault() window.addEventListener "drop", @dropBrowserEventListener, false @resizeBrowserEventListener = => @eventsQueue.push ResizeInputEvent.fromBrowserEvent event # this is a DOM thing, little to do with other r e s i z e methods window.addEventListener "resize", @resizeBrowserEventListener, false # note that we don't register the normal click, # we figure that out independently. initEventListeners: -> @initMouseEventListeners() @initTouchEventListeners() @initKeyboardEventListeners() @initClipboardEventListeners() @initKeyCombosEventListeners() @initOtherMiscEventListeners() # »>> this part is excluded from the fizzygum homepage build removeEventListeners: -> canvas = @worldCanvas # canvas.removeEventListener 'dblclick', @dblclickEventListener canvas.removeEventListener 'mousedown', @mousedownBrowserEventListener canvas.removeEventListener 'mouseup', @mouseupBrowserEventListener canvas.removeEventListener 'mousemove', @mousemoveBrowserEventListener canvas.removeEventListener 'contextmenu', @contextmenuEventListener canvas.removeEventListener "touchstart", @touchstartBrowserEventListener canvas.removeEventListener "touchend", @touchendBrowserEventListener canvas.removeEventListener "touchmove", @touchmoveBrowserEventListener canvas.removeEventListener "gesturestart", @gesturestartBrowserEventListener canvas.removeEventListener "gesturechange", @gesturechangeBrowserEventListener canvas.removeEventListener 'keydown', @keydownBrowserEventListener canvas.removeEventListener 'keyup', @keyupBrowserEventListener canvas.removeEventListener 'keypress', @keypressBrowserEventListener canvas.removeEventListener 'wheel', @wheelBrowserEventListener if Utils.runningInMobileSafari() canvas.removeEventListener 'scroll', @wheelBrowserEventListener canvas.removeEventListener 'cut', @cutBrowserEventListener canvas.removeEventListener 'copy', @copyBrowserEventListener canvas.removeEventListener 'paste', @pasteBrowserEventListener Mousetrap.reset() canvas.removeEventListener 'dragover', @dragoverEventListener canvas.removeEventListener 'resize', @resizeBrowserEventListener canvas.removeEventListener 'drop', @dropBrowserEventListener # this part is excluded from the fizzygum homepage build <<« mouseDownLeft: -> noOperation mouseClickLeft: -> noOperation mouseDownRight: -> noOperation # »>> this part is excluded from the fizzygum homepage build droppedImage: -> nil droppedSVG: -> nil # this part is excluded from the fizzygum homepage build <<« # WorldMorph text field tabbing: nextTab: (editField) -> next = @nextEntryField editField if next @switchTextFieldFocus editField, next previousTab: (editField) -> prev = @previousEntryField editField if prev @switchTextFieldFocus editField, prev switchTextFieldFocus: (current, next) -> current.clearSelection() next.bringToForeground() next.selectAll() next.edit() # if an error is thrown, the state of the world might # be messy, for example the pointer might be # dragging an invisible morph, etc. # So, try to clean-up things as much as possible. softResetWorld: -> @hand.drop() @hand.mouseOverList.clear() @hand.nonFloatDraggedWdgt = nil @wdgtsDetectingClickOutsideMeOrAnyOfMeChildren.clear() @lastNonTextPropertyChangerButtonClickedOrDropped = nil # »>> this part is excluded from the fizzygum homepage build resetWorld: -> @softResetWorld() @changed() # redraw the whole screen @fullDestroyChildren() # the "basementWdgt" is not attached to the # world tree so it's not in the children, # so we need to clean up separately @basementWdgt?.empty() # some tests might change the background # color of the world so let's reset it. @setColor Color.create 205, 205, 205 SystemTestsControlPanelUpdater.blinkLink SystemTestsControlPanelUpdater.resetWorldLink # make sure thw window is scrolled to top # so we can see the test results while tests # are running. document.body.scrollTop = document.documentElement.scrollTop = 0 # this part is excluded from the fizzygum homepage build <<« # There is something special about the # "world" version of fullDestroyChildren: # it resets the counter used to count # how many morphs exist of each Widget class. # That counter is also used to determine the # unique ID of a Widget. So, destroying # all morphs from the world causes the # counts and IDs of all the subsequent # morphs to start from scratch again. fullDestroyChildren: -> # Check which objects end with the word Widget theWordMorph = "Morph" theWordWdgt = "Wdgt" theWordWidget = "Widget" ListOfMorphs = (Object.keys(window)).filter (i) -> i.includes(theWordMorph, i.length - theWordMorph.length) or i.includes(theWordWdgt, i.length - theWordWdgt.length) or i.includes(theWordWidget, i.length - theWordWidget.length) for eachMorphClass in ListOfMorphs if eachMorphClass != "WorldMorph" #console.log "resetting " + eachMorphClass + " from " + window[eachMorphClass].instancesCounter # the actual count is in another variable "instancesCounter" # but all labels are built using instanceNumericID # which is set based on lastBuiltInstanceNumericID window[eachMorphClass].lastBuiltInstanceNumericID = 0 # »>> this part is excluded from the fizzygum homepage build if Automator? @automator.recorder.turnOffAnimationsPacingControl() @automator.recorder.turnOffAlignmentOfMorphIDsMechanism() @automator.recorder.turnOffHidingOfMorphsContentExtractInLabels() @automator.recorder.turnOffHidingOfMorphsNumberIDInLabels() # this part is excluded from the fizzygum homepage build <<« super() destroyToolTips: -> # "toolTipsList" keeps the widgets to be deleted upon # the next mouse click, or whenever another temporary Widget decides # that it needs to remove them. # Note that we actually destroy toolTipsList because we are not expecting # anybody to revive them once they are gone (as opposed to menus) @toolTipsList.forEach (tooltip) => unless tooltip.boundsContainPoint @position() tooltip.fullDestroy() @toolTipsList.delete tooltip buildContextMenu: -> if @isIndexPage menu = new MenuMorph @, false, @, true, true, "Desktop" menu.addMenuItem "wallpapers ➜", false, @, "wallpapersMenu", "choose a wallpaper for the Desktop" menu.addMenuItem "new folder", true, @, "makeFolder" return menu if @isDevMode menu = new MenuMorph(@, false, @, true, true, @constructor.name or @constructor.toString().split(" ")[1].split("(")[0]) else menu = new MenuMorph @, false, @, true, true, "Widgetic" # »>> this part is excluded from the fizzygum homepage build if @isDevMode menu.addMenuItem "demo ➜", false, @, "popUpDemoMenu", "sample morphs" menu.addLine() # TODO remove these two, they do nothing now menu.addMenuItem "show all", true, @, "noOperation" menu.addMenuItem "hide all", true, @, "noOperation" menu.addMenuItem "delete all", true, @, "closeChildren" menu.addMenuItem "move all inside", true, @, "keepAllSubmorphsWithin", "keep all submorphs\nwithin and visible" menu.addMenuItem "inspect", true, @, "inspect", "open a window on\nall properties" menu.addMenuItem "test menu ➜", false, @, "testMenu", "debugging and testing operations" menu.addLine() menu.addMenuItem "restore display", true, @, "changed", "redraw the\nscreen once" menu.addMenuItem "fit whole page", true, @, "stretchWorldToFillEntirePage", "let the World automatically\nadjust to browser resizings" menu.addMenuItem "color...", true, @, "popUpColorSetter", "choose the World's\nbackground color" menu.addMenuItem "wallpapers ➜", false, @, "wallpapersMenu", "choose a wallpaper for the Desktop" if WorldMorph.preferencesAndSettings.inputMode is PreferencesAndSettings.INPUT_MODE_MOUSE menu.addMenuItem "touch screen settings", true, WorldMorph.preferencesAndSettings, "toggleInputMode", "bigger menu fonts\nand sliders" else menu.addMenuItem "standard settings", true, WorldMorph.preferencesAndSettings, "toggleInputMode", "smaller menu fonts\nand sliders" menu.addLine() # this part is excluded from the fizzygum homepage build <<« if Automator? menu.addMenuItem "system tests ➜", false, @, "popUpSystemTestsMenu", "" if @isDevMode menu.addMenuItem "switch to user mode", true, @, "toggleDevMode", "disable developers'\ncontext menus" else menu.addMenuItem "switch to dev mode", true, @, "toggleDevMode" menu.addMenuItem "new folder", true, @, "makeFolder" menu.addMenuItem "about Fizzygum...", true, @, "about" menu wallpapersMenu: (a,targetMorph)-> menu = new MenuMorph @, false, targetMorph, true, true, "Wallpapers" # we add the "untick" prefix to all entries # so we allocate the right amount of space for # the labels, we are going to put the # right ticks soon after menu.addMenuItem untick + @pattern1, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern1 menu.addMenuItem untick + @pattern2, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern2 menu.addMenuItem untick + @pattern3, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern3 menu.addMenuItem untick + @pattern4, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern4 menu.addMenuItem untick + @pattern5, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern5 menu.addMenuItem untick + @pattern6, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern6 menu.addMenuItem untick + @pattern7, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern7 @updatePatternsMenuEntriesTicks menu menu.popUpAtHand() setPattern: (menuItem, ignored2, thePatternName) -> if @patternName == thePatternName return @patternName = thePatternName @changed() if menuItem?.parent? and (menuItem.parent instanceof MenuMorph) @updatePatternsMenuEntriesTicks menuItem.parent # cheap way to keep menu consistency when pinned # note that there is no consistency in case # there are multiple copies of this menu changing # the wallpaper, since there is no real subscription # of a menu to react to wallpaper change coming # from other menus or other means (e.g. API)... updatePatternsMenuEntriesTicks: (menu) -> pattern1Tick = pattern2Tick = pattern3Tick = pattern4Tick = pattern5Tick = pattern6Tick = pattern7Tick = untick switch @patternName when @pattern1 pattern1Tick = tick when @pattern2 pattern2Tick = tick when @pattern3 pattern3Tick = tick when @pattern4 pattern4Tick = tick when @pattern5 pattern5Tick = tick when @pattern6 pattern6Tick = tick when @pattern7 pattern7Tick = tick menu.children[1].label.setText pattern1Tick + @pattern1 menu.children[2].label.setText pattern2Tick + @pattern2 menu.children[3].label.setText pattern3Tick + @pattern3 menu.children[4].label.setText pattern4Tick + @pattern4 menu.children[5].label.setText pattern5Tick + @pattern5 menu.children[6].label.setText pattern6Tick + @pattern6 menu.children[7].label.setText pattern7Tick + @pattern7 # »>> this part is excluded from the fizzygum homepage build popUpSystemTestsMenu: -> menu = new MenuMorph @, false, @, true, true, "system tests" menu.addMenuItem "run system tests", true, @automator.player, "runAllSystemTests", "runs all the system tests" menu.addMenuItem "run system tests force slow", true, @automator.player, "runAllSystemTestsForceSlow", "runs all the system tests" menu.addMenuItem "run system tests force fast skip in-between mouse moves", true, @automator.player, "runAllSystemTestsForceFastSkipInbetweenMouseMoves", "runs all the system tests" menu.addMenuItem "run system tests force fast run in-between mouse moves", true, @automator.player, "runAllSystemTestsForceFastRunInbetweenMouseMoves", "runs all the system tests" menu.addMenuItem "start test recording", true, @automator.recorder, "startTestRecording", "start recording a test" menu.addMenuItem "stop test recording", true, @automator.recorder, "stopTestRecording", "stop recording the test" menu.addMenuItem "(re)play recorded test slow", true, @automator.player, "startTestPlayingSlow", "start playing the test" menu.addMenuItem "(re)play recorded test fast skip in-between mouse moves", true, @automator.player, "startTestPlayingFastSkipInbetweenMouseMoves", "start playing the test" menu.addMenuItem "(re)play recorded test fast run in-between mouse moves", true, @automator.player, "startTestPlayingFastRunInbetweenMouseMoves", "start playing the test" menu.addMenuItem "show test source", true, @automator, "showTestSource", "opens a window with the source of the latest test" menu.addMenuItem "save recorded test", true, @automator.recorder, "saveTest", "save the recorded test" menu.addMenuItem "save failed screenshots", true, @automator.player, "saveFailedScreenshots", "save failed screenshots" menu.popUpAtHand() # this part is excluded from the fizzygum homepage build <<« create: (aWdgt) -> aWdgt.pickUp() # »>> this part is excluded from the fizzygum homepage build createNewStackElementsSizeAdjustingMorph: -> @create new StackElementsSizeAdjustingMorph createNewLayoutElementAdderOrDropletMorph: -> @create new LayoutElementAdderOrDropletMorph createNewRectangleMorph: -> @create new RectangleMorph createNewBoxMorph: -> @create new BoxMorph createNewCircleBoxMorph: -> @create new CircleBoxMorph createNewSliderMorph: -> @create new SliderMorph createNewPanelWdgt: -> newWdgt = new PanelWdgt newWdgt.rawSetExtent new Point 350, 250 @create newWdgt createNewScrollPanelWdgt: -> newWdgt = new ScrollPanelWdgt newWdgt.adjustContentsBounds() newWdgt.adjustScrollBars() newWdgt.rawSetExtent new Point 350, 250 @create newWdgt createNewCanvas: -> newWdgt = new CanvasMorph newWdgt.rawSetExtent new Point 350, 250 @create newWdgt createNewHandle: -> @create new HandleMorph createNewString: -> newWdgt = new StringMorph "Hello, World!" newWdgt.isEditable = true @create newWdgt createNewText: -> newWdgt = new TextMorph("Ich weiß nicht, was soll es bedeuten, dass ich so " + "traurig bin, ein Märchen aus uralten Zeiten, das " + "kommt mir nicht aus dem Sinn. Die Luft ist kühl " + "und es dunkelt, und ruhig fließt der Rhein; der " + "Gipfel des Berges funkelt im Abendsonnenschein. " + "Die schönste Jungfrau sitzet dort oben wunderbar, " + "ihr gold'nes Geschmeide blitzet, sie kämmt ihr " + "goldenes Haar, sie kämmt es mit goldenem Kamme, " + "und singt ein Lied dabei; das hat eine wundersame, " + "gewalt'ge Melodei. Den Schiffer im kleinen " + "Schiffe, ergreift es mit wildem Weh; er schaut " + "nicht die Felsenriffe, er schaut nur hinauf in " + "die Höh'. Ich glaube, die Wellen verschlingen " + "am Ende Schiffer und Kahn, und das hat mit ihrem " + "Singen, die L<NAME>ley getan.") newWdgt.isEditable = true newWdgt.maxTextWidth = 300 @create newWdgt createNewSpeechBubbleWdgt: -> newWdgt = new SpeechBubbleWdgt @create newWdgt createNewToolTipWdgt: -> newWdgt = new ToolTipWdgt @create newWdgt createNewGrayPaletteMorph: -> @create new GrayPaletteMorph createNewColorPaletteMorph: -> @create new ColorPaletteMorph createNewGrayPaletteMorphInWindow: -> gP = new GrayPaletteMorph wm = new WindowWdgt nil, nil, gP @add wm wm.rawSetExtent new Point 130, 70 wm.fullRawMoveTo @hand.position().subtract new Point 50, 100 createNewColorPaletteMorphInWindow: -> cP = new ColorPaletteMorph wm = new WindowWdgt nil, nil, cP @add wm wm.rawSetExtent new Point 130, 100 wm.fullRawMoveTo @hand.position().subtract new Point 50, 100 createNewColorPickerMorph: -> @create new ColorPickerMorph createNewSensorDemo: -> newWdgt = new MouseSensorMorph newWdgt.setColor Color.create 230, 200, 100 newWdgt.cornerRadius = 35 newWdgt.alpha = 0.2 newWdgt.rawSetExtent new Point 100, 100 @create newWdgt createNewAnimationDemo: -> foo = new BouncerMorph foo.fullRawMoveTo new Point 50, 20 foo.rawSetExtent new Point 300, 200 foo.alpha = 0.9 foo.speed = 3 bar = new BouncerMorph bar.setColor Color.create 50, 50, 50 bar.fullRawMoveTo new Point 80, 80 bar.rawSetExtent new Point 80, 250 bar.type = "horizontal" bar.direction = "right" bar.alpha = 0.9 bar.speed = 5 baz = new BouncerMorph baz.setColor Color.create 20, 20, 20 baz.fullRawMoveTo new Point 90, 140 baz.rawSetExtent new Point 40, 30 baz.type = "horizontal" baz.direction = "right" baz.speed = 3 garply = new BouncerMorph garply.setColor Color.create 200, 20, 20 garply.fullRawMoveTo new Point 90, 140 garply.rawSetExtent new Point 20, 20 garply.type = "vertical" garply.direction = "up" garply.speed = 8 fred = new BouncerMorph fred.setColor Color.create 20, 200, 20 fred.fullRawMoveTo new Point 120, 140 fred.rawSetExtent new Point 20, 20 fred.type = "vertical" fred.direction = "down" fred.speed = 4 bar.add garply bar.add baz foo.add fred foo.add bar @create foo createNewPenMorph: -> @create new PenMorph underTheCarpet: -> newWdgt = new BasementWdgt @create newWdgt popUpDemoMenu: (morphOpeningThePopUp,b,c,d) -> if @isIndexPage menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "parts bin" menu.addMenuItem "rectangle", true, @, "createNewRectangleMorph" menu.addMenuItem "box", true, @, "createNewBoxMorph" menu.addMenuItem "circle box", true, @, "createNewCircleBoxMorph" menu.addMenuItem "slider", true, @, "createNewSliderMorph" menu.addMenuItem "speech bubble", true, @, "createNewSpeechBubbleWdgt" menu.addLine() menu.addMenuItem "gray scale palette", true, @, "createNewGrayPaletteMorphInWindow" menu.addMenuItem "color palette", true, @, "createNewColorPaletteMorphInWindow" menu.addLine() menu.addMenuItem "analog clock", true, @, "analogClock" else menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "make a morph" menu.addMenuItem "rectangle", true, @, "createNewRectangleMorph" menu.addMenuItem "box", true, @, "createNewBoxMorph" menu.addMenuItem "circle box", true, @, "createNewCircleBoxMorph" menu.addLine() menu.addMenuItem "slider", true, @, "createNewSliderMorph" menu.addMenuItem "panel", true, @, "createNewPanelWdgt" menu.addMenuItem "scrollable panel", true, @, "createNewScrollPanelWdgt" menu.addMenuItem "canvas", true, @, "createNewCanvas" menu.addMenuItem "handle", true, @, "createNewHandle" menu.addLine() menu.addMenuItem "string", true, @, "createNewString" menu.addMenuItem "text", true, @, "createNewText" menu.addMenuItem "tool tip", true, @, "createNewToolTipWdgt" menu.addMenuItem "speech bubble", true, @, "createNewSpeechBubbleWdgt" menu.addLine() menu.addMenuItem "gray scale palette", true, @, "createNewGrayPaletteMorph" menu.addMenuItem "color palette", true, @, "createNewColorPaletteMorph" menu.addMenuItem "color picker", true, @, "createNewColorPickerMorph" menu.addLine() menu.addMenuItem "sensor demo", true, @, "createNewSensorDemo" menu.addMenuItem "animation demo", true, @, "createNewAnimationDemo" menu.addMenuItem "pen", true, @, "createNewPenMorph" menu.addLine() menu.addMenuItem "layout tests ➜", false, @, "layoutTestsMenu", "sample morphs" menu.addLine() menu.addMenuItem "under the carpet", true, @, "underTheCarpet" menu.popUpAtHand() layoutTestsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "Layout tests" menu.addMenuItem "adjuster morph", true, @, "createNewStackElementsSizeAdjustingMorph" menu.addMenuItem "adder/droplet", true, @, "createNewLayoutElementAdderOrDropletMorph" menu.addMenuItem "test screen 1", true, Widget, "setupTestScreen1" menu.popUpAtHand() toggleDevMode: -> @isDevMode = not @isDevMode # this part is excluded from the fizzygum homepage build <<« edit: (aStringMorphOrTextMorph) -> # first off, if the Widget is not editable # then there is nothing to do # return nil unless aStringMorphOrTextMorph.isEditable # there is only one caret in the World, so destroy # the previous one if there was one. if @caret # empty the previously ongoing selection # if there was one. previouslyEditedText = @lastEditedText @lastEditedText = @caret.target if @lastEditedText != previouslyEditedText @lastEditedText.clearSelection() @caret = @caret.fullDestroy() # create the new Caret @caret = new CaretMorph aStringMorphOrTextMorph aStringMorphOrTextMorph.parent.add @caret # this is the only place where the @keyboardEventsReceiver is set @keyboardEventsReceiver = @caret if WorldMorph.preferencesAndSettings.isTouchDevice and WorldMorph.preferencesAndSettings.useVirtualKeyboard @initVirtualKeyboard() # For touch devices, giving focus on the textbox causes # the keyboard to slide up, and since the page viewport # shrinks, the page is scrolled to where the texbox is. # So, it is important to position the textbox around # where the caret is, so that the changed text is going to # be visible rather than out of the viewport. pos = @getCanvasPosition() @inputDOMElementForVirtualKeyboard.style.top = @caret.top() + pos.y + "px" @inputDOMElementForVirtualKeyboard.style.left = @caret.left() + pos.x + "px" @inputDOMElementForVirtualKeyboard.focus() # Widgetic.js provides the "slide" method but I must have lost it # in the way, so commenting this out for the time being # #if WorldMorph.preferencesAndSettings.useSliderForInput # if !aStringMorphOrTextMorph.parentThatIsA MenuMorph # @slide aStringMorphOrTextMorph # Editing can stop because of three reasons: # cancel (user hits ESC) # accept (on stringmorph, user hits enter) # user clicks/floatDrags another morph stopEditing: -> if @caret @lastEditedText = @caret.target @lastEditedText.clearSelection() @caret = @caret.fullDestroy() # the only place where the @keyboardEventsReceiver is unset # (and the hidden input is removed) @keyboardEventsReceiver = nil if @inputDOMElementForVirtualKeyboard @inputDOMElementForVirtualKeyboard.blur() document.body.removeChild @inputDOMElementForVirtualKeyboard @inputDOMElementForVirtualKeyboard = nil @worldCanvas.focus() anyReferenceToWdgt: (whichWdgt) -> # go through all the references and check whether they reference # the wanted widget. Note that the reference could be unreachable # in the basement, or even in the trash for eachReferencingWdgt from @widgetsReferencingOtherWidgets if eachReferencingWdgt.target == whichWdgt return true return false
true
# The WorldMorph takes over the canvas on the page class WorldMorph extends PanelWdgt @augmentWith GridPositioningOfAddedShortcutsMixin, @name @augmentWith KeepIconicDesktopSystemLinksBackMixin, @name # We need to add and remove # the event listeners so we are # going to put them all in properties # here. # dblclickEventListener: nil mousedownBrowserEventListener: nil mouseupBrowserEventListener: nil mousemoveBrowserEventListener: nil contextmenuEventListener: nil touchstartBrowserEventListener: nil touchendBrowserEventListener: nil touchmoveBrowserEventListener: nil gesturestartBrowserEventListener: nil gesturechangeBrowserEventListener: nil # Note how there can be two handlers for # keyboard events. # This one is attached # to the canvas and reaches the currently # blinking caret if there is one. # See below for the other potential # handler. See "initVirtualKeyboard" # method to see where and when this input and # these handlers are set up. keydownBrowserEventListener: nil keyupBrowserEventListener: nil keypressBrowserEventListener: nil wheelBrowserEventListener: nil cutBrowserEventListener: nil copyBrowserEventListener: nil pasteBrowserEventListener: nil errorConsole: nil # the string for the last serialised morph # is kept in here, to make serialization # and deserialization tests easier. # The alternative would be to refresh and # re-start the tests from where they left... lastSerializationString: "" # Note how there can be two handlers # for keyboard events. This one is # attached to a hidden # "input" div which keeps track of the # text that is being input. inputDOMElementForVirtualKeyboardKeydownBrowserEventListener: nil inputDOMElementForVirtualKeyboardKeyupBrowserEventListener: nil inputDOMElementForVirtualKeyboardKeypressBrowserEventListener: nil # »>> this part is excluded from the fizzygum homepage build keyComboResetWorldEventListener: nil keyComboTurnOnAnimationsPacingControl: nil keyComboTurnOffAnimationsPacingControl: nil keyComboTakeScreenshotEventListener: nil keyComboStopTestRecordingEventListener: nil keyComboTakeScreenshotEventListener: nil keyComboCheckStringsOfItemsInMenuOrderImportant: nil keyComboCheckStringsOfItemsInMenuOrderUnimportant: nil keyComboAddTestCommentEventListener: nil keyComboCheckNumberOfMenuItemsEventListener: nil # this part is excluded from the fizzygum homepage build <<« dragoverEventListener: nil resizeBrowserEventListener: nil otherTasksToBeRunOnStep: [] # »>> this part is excluded from the fizzygum homepage build dropBrowserEventListener: nil # this part is excluded from the fizzygum homepage build <<« # these variables shouldn't be static to the WorldMorph, because # in pure theory you could have multiple worlds in the same # page with different settings # (but anyways, it was global before, so it's not any worse than before) @preferencesAndSettings: nil @dateOfPreviousCycleStart: nil @dateOfCurrentCycleStart: nil showRedraws: false doubleCheckCachedMethodsResults: false automator: nil # this is the actual reference to the canvas # on the html page, where the world is # finally painted to. worldCanvas: nil worldCanvasContext: nil canvasForTextMeasurements: nil canvasContextForTextMeasurements: nil cacheForTextMeasurements: nil cacheForTextParagraphSplits: nil cacheForParagraphsWordsSplits: nil cacheForParagraphsWrappingData: nil cacheForTextWrappingData: nil cacheForTextBreakingIntoLinesTopLevel: nil # By default the world will always fill # the entire page, also when browser window # is resized. # When this flag is set, the onResize callback # automatically adjusts the world size. automaticallyAdjustToFillEntireBrowserAlsoOnResize: true # »>> this part is excluded from the fizzygum homepage build # keypad keys map to special characters # so we can trigger test actions # see more comments below @KEYPAD_TAB_mappedToThaiKeyboard_A: "ฟ" @KEYPAD_SLASH_mappedToThaiKeyboard_B: "ิ" @KEYPAD_MULTIPLY_mappedToThaiKeyboard_C: "แ" @KEYPAD_DELETE_mappedToThaiKeyboard_D: "ก" @KEYPAD_7_mappedToThaiKeyboard_E: "ำ" @KEYPAD_8_mappedToThaiKeyboard_F: "ด" @KEYPAD_9_mappedToThaiKeyboard_G: "เ" @KEYPAD_MINUS_mappedToThaiKeyboard_H: "้" @KEYPAD_4_mappedToThaiKeyboard_I: "ร" @KEYPAD_5_mappedToThaiKeyboard_J: "่" # looks like empty string but isn't :-) @KEYPAD_6_mappedToThaiKeyboard_K: "า" @KEYPAD_PLUS_mappedToThaiKeyboard_L: "ส" @KEYPAD_1_mappedToThaiKeyboard_M: "ท" @KEYPAD_2_mappedToThaiKeyboard_N: "ท" @KEYPAD_3_mappedToThaiKeyboard_O: "ื" @KEYPAD_ENTER_mappedToThaiKeyboard_P: "น" @KEYPAD_0_mappedToThaiKeyboard_Q: "ย" @KEYPAD_DOT_mappedToThaiKeyboard_R: "พ" # this part is excluded from the fizzygum homepage build <<« wdgtsDetectingClickOutsideMeOrAnyOfMeChildren: new Set hierarchyOfClickedWdgts: new Set hierarchyOfClickedMenus: new Set popUpsMarkedForClosure: new Set freshlyCreatedPopUps: new Set openPopUps: new Set toolTipsList: new Set # »>> this part is excluded from the fizzygum homepage build @ongoingUrlActionNumber: 0 # this part is excluded from the fizzygum homepage build <<« @frameCount: 0 @numberOfAddsAndRemoves: 0 @numberOfVisibilityFlagsChanges: 0 @numberOfCollapseFlagsChanges: 0 @numberOfRawMovesAndResizes: 0 broken: nil duplicatedBrokenRectsTracker: nil numberOfDuplicatedBrokenRects: 0 numberOfMergedSourceAndDestination: 0 morphsToBeHighlighted: new Set currentHighlightingMorphs: new Set morphsBeingHighlighted: new Set # »>> this part is excluded from the fizzygum homepage build morphsToBePinouted: new Set currentPinoutingMorphs: new Set morphsBeingPinouted: new Set # this part is excluded from the fizzygum homepage build <<« steppingWdgts: new Set basementWdgt: nil # since the shadow is just a "rendering" effect # there is no morph for it, we need to just clean up # the shadow area ad-hoc. We do that by just growing any # broken rectangle by the maximum shadow offset. # We could be more surgical and remember the offset of the # shadow (if any) in the start and end location of the # morph, just like we do with the position, but it # would complicate things and probably be overkill. # The downside of this is that if we change the # shadow sizes, we have to check that this max size # still captures the biggest. maxShadowSize: 6 eventsQueue: [] widgetsReferencingOtherWidgets: new Set incrementalGcSessionId: 0 desktopSidesPadding: 10 # the desktop lays down icons vertically laysIconsHorizontallyInGrid: false iconsLayingInGridWrapCount: 5 errorsWhileRepainting: [] paintingWidget: nil widgetsGivingErrorWhileRepainting: [] # this one is so we can left/center/right align in # a document editor the last widget that the user "touched" # TODO this could be extended so we keep a "list" of # "selected" widgets (e.g. if the user ctrl-clicks on a widget # then it highlights in some manner and ends up in this list) # and then operations can be performed on the whole list # of widgets. lastNonTextPropertyChangerButtonClickedOrDropped: nil patternName: nil pattern1: "plain" pattern2: "circles" pattern3: "vert. stripes" pattern4: "oblique stripes" pattern5: "dots" pattern6: "zigzag" pattern7: "bricks" howManyUntitledShortcuts: 0 howManyUntitledFoldersShortcuts: 0 lastUsedConnectionsCalculationToken: 0 isIndexPage: nil # »>> this part is excluded from the fizzygum homepage build # This method also handles keypresses from a special # external keypad which is used to # record tests commands (such as capture screen, etc.). # These external keypads are inexpensive # so they are a good device for this kind # of stuff. # http://www.amazon.co.uk/Perixx-PERIPAD-201PLUS-Numeric-Keypad-Laptop/dp/B001R6FZLU/ # They keypad is mapped # to Thai keyboard characters via an OSX app # called keyremap4macbook (also one needs to add the # Thai keyboard, which is just a click from System Preferences) # Those Thai characters are used to trigger test # commands. The only added complexity is about # the "00" key of such keypads - see # note below. doublePressOfZeroKeypadKey: nil # this part is excluded from the fizzygum homepage build <<« healingRectanglesPhase: false # we use the trackChanges array as a stack to # keep track whether a whole segment of code # (including all function calls in it) will # record the broken rectangles. # Using a stack we can correctly track nested "disabling of track # changes" correctly. trackChanges: [true] morphsThatMaybeChangedGeometryOrPosition: [] morphsThatMaybeChangedFullGeometryOrPosition: [] morphsThatMaybeChangedLayout: [] # »>> this part is only needed for Macros macroStepsWaitingTimer: nil nextBlockToBeRun: nil macroVars: nil macroIsRunning: nil # this part is only needed for Macros <<« constructor: ( @worldCanvas, @automaticallyAdjustToFillEntireBrowserAlsoOnResize = true ) -> # The WorldMorph is the very first morph to # be created. # world at the moment is a global variable, there is only one # world and this variable needs to be initialised as soon as possible, which # is right here. This is because there is code in this constructor that # will reference that global world variable, so it needs to be set # very early window.world = @ if window.location.href.includes "worldWithSystemTestHarness" @isIndexPage = false else @isIndexPage = true WorldMorph.preferencesAndSettings = new PreferencesAndSettings super() @patternName = @pattern1 @appearance = new DesktopAppearance @ #console.log WorldMorph.preferencesAndSettings.menuFontName @color = Color.create 205, 205, 205 # (130, 130, 130) @strokeColor = nil @alpha = 1 # additional properties: @isDevMode = false @hand = new ActivePointerWdgt @keyboardEventsReceiver = nil @lastEditedText = nil @caret = nil @temporaryHandlesAndLayoutAdjusters = new Set @inputDOMElementForVirtualKeyboard = nil if @automaticallyAdjustToFillEntireBrowserAlsoOnResize and @isIndexPage @stretchWorldToFillEntirePage() else @sizeCanvasToTestScreenResolution() # @worldCanvas.width and height here are in physical pixels # so we want to bring them back to logical pixels @setBounds new Rectangle 0, 0, @worldCanvas.width / ceilPixelRatio, @worldCanvas.height / ceilPixelRatio @initEventListeners() if Automator? @automator = new Automator @worldCanvasContext = @worldCanvas.getContext "2d" @canvasForTextMeasurements = HTMLCanvasElement.createOfPhysicalDimensions() @canvasContextForTextMeasurements = @canvasForTextMeasurements.getContext "2d" @canvasContextForTextMeasurements.useLogicalPixelsUntilRestore() @canvasContextForTextMeasurements.textAlign = "left" @canvasContextForTextMeasurements.textBaseline = "bottom" # when using an inspector it's not uncommon to render # 400 labels just for the properties, so trying to size # the cache accordingly... @cacheForTextMeasurements = new LRUCache 1000, 1000*60*60*24 @cacheForTextParagraphSplits = new LRUCache 300, 1000*60*60*24 @cacheForParagraphsWordsSplits = new LRUCache 300, 1000*60*60*24 @cacheForParagraphsWrappingData = new LRUCache 300, 1000*60*60*24 @cacheForTextWrappingData = new LRUCache 300, 1000*60*60*24 @cacheForImmutableBackBuffers = new LRUCache 1000, 1000*60*60*24 @cacheForTextBreakingIntoLinesTopLevel = new LRUCache 10, 1000*60*60*24 @changed() # answer the absolute coordinates of the world canvas within the document getCanvasPosition: -> if !@worldCanvas? return {x: 0, y: 0} pos = x: @worldCanvas.offsetLeft y: @worldCanvas.offsetTop offsetParent = @worldCanvas.offsetParent while offsetParent? pos.x += offsetParent.offsetLeft pos.y += offsetParent.offsetTop if offsetParent isnt document.body and offsetParent isnt document.documentElement pos.x -= offsetParent.scrollLeft pos.y -= offsetParent.scrollTop offsetParent = offsetParent.offsetParent pos colloquialName: -> "Desktop" makePrettier: -> WorldMorph.preferencesAndSettings.menuFontSize = 14 WorldMorph.preferencesAndSettings.menuHeaderFontSize = 13 WorldMorph.preferencesAndSettings.menuHeaderColor = Color.create 125, 125, 125 WorldMorph.preferencesAndSettings.menuHeaderBold = false WorldMorph.preferencesAndSettings.menuStrokeColor = Color.create 186, 186, 186 WorldMorph.preferencesAndSettings.menuBackgroundColor = Color.create 250, 250, 250 WorldMorph.preferencesAndSettings.menuButtonsLabelColor = Color.create 50, 50, 50 WorldMorph.preferencesAndSettings.normalTextFontSize = 13 WorldMorph.preferencesAndSettings.titleBarTextFontSize = 13 WorldMorph.preferencesAndSettings.titleBarTextHeight = 16 WorldMorph.preferencesAndSettings.titleBarBoldText = false WorldMorph.preferencesAndSettings.bubbleHelpFontSize = 12 WorldMorph.preferencesAndSettings.iconDarkLineColor = Color.create 37, 37, 37 WorldMorph.preferencesAndSettings.defaultPanelsBackgroundColor = Color.create 249, 249, 249 WorldMorph.preferencesAndSettings.defaultPanelsStrokeColor = Color.create 198, 198, 198 @setPattern nil, nil, "dots" @changed() getNextUntitledShortcutName: -> name = "Untitled" if @howManyUntitledShortcuts > 0 name += " " + (@howManyUntitledShortcuts + 1) @howManyUntitledShortcuts++ return name getNextUntitledFolderShortcutName: -> name = "new folder" if @howManyUntitledFoldersShortcuts > 0 name += " " + (@howManyUntitledFoldersShortcuts + 1) @howManyUntitledFoldersShortcuts++ return name wantsDropOf: (aWdgt) -> return @_acceptsDrops makeNewConnectionsCalculationToken: -> # not nice to read but this means: # first increment and then return the value # this is so the first token we use is 1 # and we can initialise all input/node tokens to 0 # so to make them receptive to the first token generated ++@lastUsedConnectionsCalculationToken createErrorConsole: -> errorsLogViewerMorph = new ErrorsLogViewerMorph "Errors", @, "modifyCodeToBeInjected", "" wm = new WindowWdgt nil, nil, errorsLogViewerMorph wm.setExtent new Point 460, 400 @add wm @errorConsole = wm @errorConsole.fullMoveTo new Point 190,10 @errorConsole.setExtent new Point 550,415 @errorConsole.hide() removeSpinnerAndFakeDesktop: -> # remove the fake desktop for quick launch and the spinner spinner = document.getElementById 'spinner' spinner.parentNode.removeChild spinner splashScreenFakeDesktop = document.getElementById 'splashScreenFakeDesktop' splashScreenFakeDesktop.parentNode.removeChild splashScreenFakeDesktop createDesktop: -> @setColor Color.create 244,243,244 @makePrettier() acm = new AnalogClockWdgt acm.rawSetExtent new Point 80, 80 acm.fullRawMoveTo new Point @right()-80-@desktopSidesPadding, @top() + @desktopSidesPadding @add acm menusHelper.createWelcomeMessageWindowAndShortcut() menusHelper.createHowToSaveMessageOpener() menusHelper.basementIconAndText() menusHelper.createSimpleDocumentLauncher() menusHelper.createFizzyPaintLauncher() menusHelper.createSimpleSlideLauncher() menusHelper.createDashboardsLauncher() menusHelper.createPatchProgrammingLauncher() menusHelper.createGenericPanelLauncher() menusHelper.createToolbarsOpener() exampleDocsFolder = @makeFolder nil, nil, "examples" menusHelper.createDegreesConverterOpener exampleDocsFolder menusHelper.createSampleSlideOpener exampleDocsFolder menusHelper.createSampleDashboardOpener exampleDocsFolder menusHelper.createSampleDocOpener exampleDocsFolder # »>> this part is excluded from the fizzygum homepage build getParameterPassedInURL: (name) -> name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]') regex = new RegExp '[\\?&]' + name + '=([^&#]*)' results = regex.exec location.search if results? return decodeURIComponent results[1].replace(/\+/g, ' ') else return nil # some test urls: # this one contains two actions, two tests each, but only # the second test is run for the second group. # file:///Users/daviddellacasa/Fizzygum/Fizzygum-builds/latest/worldWithSystemTestHarness.html?startupActions=%7B%0D%0A++%22paramsVersion%22%3A+0.1%2C%0D%0A++%22actions%22%3A+%5B%0D%0A++++%7B%0D%0A++++++%22name%22%3A+%22runTests%22%2C%0D%0A++++++%22testsToRun%22%3A+%5B%22bubble%22%5D%0D%0A++++%7D%2C%0D%0A++++%7B%0D%0A++++++%22name%22%3A+%22runTests%22%2C%0D%0A++++++%22testsToRun%22%3A+%5B%22shadow%22%2C+%22SystemTest_basicResize%22%5D%2C%0D%0A++++++%22numberOfGroups%22%3A+2%2C%0D%0A++++++%22groupToBeRun%22%3A+1%0D%0A++++%7D++%5D%0D%0A%7D # # just one simple quick test about shadows #file:///Users/daviddellacasa/Fizzygum/Fizzygum-builds/latest/worldWithSystemTestHarness.html?startupActions=%7B%0A%20%20%22paramsVersion%22%3A%200.1%2C%0A%20%20%22actions%22%3A%20%5B%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%22name%22%3A%20%22runTests%22%2C%0A%20%20%20%20%20%20%22testsToRun%22%3A%20%5B%22shadow%22%5D%0A%20%20%20%20%7D%0A%20%20%5D%0A%7D nextStartupAction: -> if (@getParameterPassedInURL "startupActions")? startupActions = JSON.parse @getParameterPassedInURL "startupActions" if (!startupActions?) or (WorldMorph.ongoingUrlActionNumber == startupActions.actions.length) WorldMorph.ongoingUrlActionNumber = 0 if Automator? if window.location.href.includes("worldWithSystemTestHarness") if @automator.atLeastOneTestHasBeenRun if @automator.allTestsPassedSoFar document.getElementById("background").style.background = Color.GREEN.toString() return if !@isIndexPage then console.log "nextStartupAction " + (WorldMorph.ongoingUrlActionNumber+1) + " / " + startupActions.actions.length currentAction = startupActions.actions[WorldMorph.ongoingUrlActionNumber] if Automator? and currentAction.name == "runTests" @automator.loader.selectTestsFromTagsOrTestNames(currentAction.testsToRun) if currentAction.numberOfGroups? @automator.numberOfGroups = currentAction.numberOfGroups else @automator.numberOfGroups = 1 if currentAction.groupToBeRun? @automator.groupToBeRun = currentAction.groupToBeRun else @automator.groupToBeRun = 0 if currentAction.forceSlowTestPlaying? @automator.forceSlowTestPlaying = true if currentAction.forceTurbo? @automator.forceTurbo = true if currentAction.forceSkippingInBetweenMouseMoves? @automator.forceSkippingInBetweenMouseMoves = true if currentAction.forceRunningInBetweenMouseMoves? @automator.forceRunningInBetweenMouseMoves = true @automator.player.runAllSystemTests() WorldMorph.ongoingUrlActionNumber++ getMorphViaTextLabel: ([textDescription, occurrenceNumber, numberOfOccurrences]) -> allCandidateMorphsWithSameTextDescription = @allChildrenTopToBottomSuchThat (m) -> m.getTextDescription() == textDescription return allCandidateMorphsWithSameTextDescription[occurrenceNumber] # this part is excluded from the fizzygum homepage build <<« mostRecentlyCreatedPopUp: -> mostRecentPopUp = nil mostRecentPopUpID = -1 # we have to check which menus # are actually open, because # the destroy() function used # everywhere is not recursive and # that's where we update the @openPopUps # set so we have to doublecheck here @openPopUps.forEach (eachPopUp) => if eachPopUp.isOrphan() @openPopUps.delete eachPopUp else if eachPopUp.instanceNumericID >= mostRecentPopUpID mostRecentPopUp = eachPopUp return mostRecentPopUp # »>> this part is excluded from the fizzygum homepage build # see roundNumericIDsToNextThousand method in # Widget for an explanation of why we need this # method. alignIDsOfNextMorphsInSystemTests: -> if Automator? and Automator.state != Automator.IDLE # Check which objects end with the word Widget theWordMorph = "Morph" theWordWdgt = "Wdgt" theWordWidget = "Widget" listOfMorphsClasses = (Object.keys(window)).filter (i) -> i.includes(theWordMorph, i.length - theWordMorph.length) or i.includes(theWordWdgt, i.length - theWordWdgt.length) or i.includes(theWordWidget, i.length - theWordWidget.length) for eachMorphClass in listOfMorphsClasses #console.log "bumping up ID of class: " + eachMorphClass window[eachMorphClass].roundNumericIDsToNextThousand?() # this part is excluded from the fizzygum homepage build <<« # used to close temporary menus closePopUpsMarkedForClosure: -> @popUpsMarkedForClosure.forEach (eachMorph) => eachMorph.close() @popUpsMarkedForClosure.clear() # »>> this part is excluded from the fizzygum homepage build # World Widget broken rects debugging # currently unused brokenFor: (aWdgt) -> # private fb = aWdgt.fullBounds() @broken.filter (rect) -> rect.isIntersecting fb # this part is excluded from the fizzygum homepage build <<« # fullPaintIntoAreaOrBlitFromBackBuffer results into actual painting of pieces of # morphs done # by the paintIntoAreaOrBlitFromBackBuffer function. # The paintIntoAreaOrBlitFromBackBuffer function is defined in Widget. fullPaintIntoAreaOrBlitFromBackBuffer: (aContext, aRect) -> # invokes the Widget's fullPaintIntoAreaOrBlitFromBackBuffer, which has only three implementations: # * the default one by Widget which just invokes the paintIntoAreaOrBlitFromBackBuffer of all children # * the interesting one in PanelWdgt which a) narrows the dirty # rectangle (intersecting it with its border # since the PanelWdgt clips at its border) and b) stops recursion on all # the children that are outside such intersection. # * this implementation which just takes into account that the hand # (which could contain a Widget being floatDragged) # is painted on top of everything. super aContext, aRect # the mouse cursor is always drawn on top of everything # and it's not attached to the WorldMorph. @hand.fullPaintIntoAreaOrBlitFromBackBuffer aContext, aRect clippedThroughBounds: -> @checkClippedThroughBoundsCache = WorldMorph.numberOfAddsAndRemoves + "-" + WorldMorph.numberOfVisibilityFlagsChanges + "-" + WorldMorph.numberOfCollapseFlagsChanges + "-" + WorldMorph.numberOfRawMovesAndResizes @clippedThroughBoundsCache = @boundingBox() return @clippedThroughBoundsCache # using the code coverage tool from Chrome, it # doesn't seem that this is ever used # TODO investigate and see whether this is needed clipThrough: -> @checkClipThroughCache = WorldMorph.numberOfAddsAndRemoves + "-" + WorldMorph.numberOfVisibilityFlagsChanges + "-" + WorldMorph.numberOfCollapseFlagsChanges + "-" + WorldMorph.numberOfRawMovesAndResizes @clipThroughCache = @boundingBox() return @clipThroughCache pushBrokenRect: (brokenMorph, theRect, isSrc) -> if @duplicatedBrokenRectsTracker[theRect.toString()]? @numberOfDuplicatedBrokenRects++ else if isSrc brokenMorph.srcBrokenRect = @broken.length else brokenMorph.dstBrokenRect = @broken.length if !theRect? debugger # if @broken.length == 0 # debugger @broken.push theRect @duplicatedBrokenRectsTracker[theRect.toString()] = true # using the code coverage tool from Chrome, it # doesn't seem that this is ever used # TODO investigate and see whether this is needed mergeBrokenRectsIfCloseOrPushBoth: (brokenMorph, sourceBroken, destinationBroken) -> mergedBrokenRect = sourceBroken.merge destinationBroken mergedBrokenRectArea = mergedBrokenRect.area() sumArea = sourceBroken.area() + destinationBroken.area() #console.log "mergedBrokenRectArea: " + mergedBrokenRectArea + " (sumArea + sumArea/10): " + (sumArea + sumArea/10) if mergedBrokenRectArea < sumArea + sumArea/10 @pushBrokenRect brokenMorph, mergedBrokenRect, true @numberOfMergedSourceAndDestination++ else @pushBrokenRect brokenMorph, sourceBroken, true @pushBrokenRect brokenMorph, destinationBroken, false checkARectWithHierarchy: (aRect, brokenMorph, isSrc) -> brokenMorphAncestor = brokenMorph #if brokenMorph instanceof SliderMorph # debugger while brokenMorphAncestor.parent? brokenMorphAncestor = brokenMorphAncestor.parent if brokenMorphAncestor.srcBrokenRect? if !@broken[brokenMorphAncestor.srcBrokenRect]? debugger if @broken[brokenMorphAncestor.srcBrokenRect].containsRectangle aRect if isSrc @broken[brokenMorph.srcBrokenRect] = nil brokenMorph.srcBrokenRect = nil else @broken[brokenMorph.dstBrokenRect] = nil brokenMorph.dstBrokenRect = nil else if aRect.containsRectangle @broken[brokenMorphAncestor.srcBrokenRect] @broken[brokenMorphAncestor.srcBrokenRect] = nil brokenMorphAncestor.srcBrokenRect = nil if brokenMorphAncestor.dstBrokenRect? if !@broken[brokenMorphAncestor.dstBrokenRect]? debugger if @broken[brokenMorphAncestor.dstBrokenRect].containsRectangle aRect if isSrc @broken[brokenMorph.srcBrokenRect] = nil brokenMorph.srcBrokenRect = nil else @broken[brokenMorph.dstBrokenRect] = nil brokenMorph.dstBrokenRect = nil else if aRect.containsRectangle @broken[brokenMorphAncestor.dstBrokenRect] @broken[brokenMorphAncestor.dstBrokenRect] = nil brokenMorphAncestor.dstBrokenRect = nil rectAlreadyIncludedInParentBrokenMorph: -> for brokenMorph in @morphsThatMaybeChangedGeometryOrPosition if brokenMorph.srcBrokenRect? aRect = @broken[brokenMorph.srcBrokenRect] @checkARectWithHierarchy aRect, brokenMorph, true if brokenMorph.dstBrokenRect? aRect = @broken[brokenMorph.dstBrokenRect] @checkARectWithHierarchy aRect, brokenMorph, false for brokenMorph in @morphsThatMaybeChangedFullGeometryOrPosition if brokenMorph.srcBrokenRect? aRect = @broken[brokenMorph.srcBrokenRect] @checkARectWithHierarchy aRect, brokenMorph if brokenMorph.dstBrokenRect? aRect = @broken[brokenMorph.dstBrokenRect] @checkARectWithHierarchy aRect, brokenMorph cleanupSrcAndDestRectsOfMorphs: -> for brokenMorph in @morphsThatMaybeChangedGeometryOrPosition brokenMorph.srcBrokenRect = nil brokenMorph.dstBrokenRect = nil for brokenMorph in @morphsThatMaybeChangedFullGeometryOrPosition brokenMorph.srcBrokenRect = nil brokenMorph.dstBrokenRect = nil fleshOutBroken: -> #if @morphsThatMaybeChangedGeometryOrPosition.length > 0 # debugger sourceBroken = nil destinationBroken = nil for brokenMorph in @morphsThatMaybeChangedGeometryOrPosition # let's see if this Widget that marked itself as broken # was actually painted in the past frame. # If it was then we have to clean up the "before" area # even if the Widget is not visible anymore if brokenMorph.clippedBoundsWhenLastPainted? if brokenMorph.clippedBoundsWhenLastPainted.isNotEmpty() sourceBroken = brokenMorph.clippedBoundsWhenLastPainted.expandBy(1).growBy @maxShadowSize #if brokenMorph!= world and (brokenMorph.clippedBoundsWhenLastPainted.containsPoint (new Point(10,10))) # debugger # for the "destination" broken rectangle we can actually # check whether the Widget is still visible because we # can skip the destination rectangle in that case # (not the source one!) unless brokenMorph.surelyNotShowingUpOnScreenBasedOnVisibilityCollapseAndOrphanage() # @clippedThroughBounds() should be smaller area # than bounds because it clips # the bounds based on the clipping morphs up the # hierarchy boundsToBeChanged = brokenMorph.clippedThroughBounds() if boundsToBeChanged.isNotEmpty() destinationBroken = boundsToBeChanged.spread().expandBy(1).growBy @maxShadowSize #if brokenMorph!= world and (boundsToBeChanged.spread().containsPoint new Point 10, 10) # debugger if sourceBroken? and destinationBroken? @mergeBrokenRectsIfCloseOrPushBoth brokenMorph, sourceBroken, destinationBroken else if sourceBroken? or destinationBroken? if sourceBroken? @pushBrokenRect brokenMorph, sourceBroken, true else @pushBrokenRect brokenMorph, destinationBroken, true brokenMorph.geometryOrPositionPossiblyChanged = false brokenMorph.clippedBoundsWhenLastPainted = nil fleshOutFullBroken: -> #if @morphsThatMaybeChangedFullGeometryOrPosition.length > 0 # debugger sourceBroken = nil destinationBroken = nil for brokenMorph in @morphsThatMaybeChangedFullGeometryOrPosition #console.log "fleshOutFullBroken: " + brokenMorph if brokenMorph.fullClippedBoundsWhenLastPainted? if brokenMorph.fullClippedBoundsWhenLastPainted.isNotEmpty() sourceBroken = brokenMorph.fullClippedBoundsWhenLastPainted.expandBy(1).growBy @maxShadowSize # for the "destination" broken rectangle we can actually # check whether the Widget is still visible because we # can skip the destination rectangle in that case # (not the source one!) unless brokenMorph.surelyNotShowingUpOnScreenBasedOnVisibilityCollapseAndOrphanage() boundsToBeChanged = brokenMorph.fullClippedBounds() if boundsToBeChanged.isNotEmpty() destinationBroken = boundsToBeChanged.spread().expandBy(1).growBy @maxShadowSize #if brokenMorph!= world and (boundsToBeChanged.spread().containsPoint (new Point(10,10))) # debugger if sourceBroken? and destinationBroken? @mergeBrokenRectsIfCloseOrPushBoth brokenMorph, sourceBroken, destinationBroken else if sourceBroken? or destinationBroken? if sourceBroken? @pushBrokenRect brokenMorph, sourceBroken, true else @pushBrokenRect brokenMorph, destinationBroken, true brokenMorph.fullGeometryOrPositionPossiblyChanged = false brokenMorph.fullClippedBoundsWhenLastPainted = nil # »>> this part is excluded from the fizzygum homepage build showBrokenRects: (aContext) -> aContext.save() aContext.globalAlpha = 0.5 aContext.useLogicalPixelsUntilRestore() for eachBrokenRect in @broken if eachBrokenRect? randomR = Math.round Math.random() * 255 randomG = Math.round Math.random() * 255 randomB = Math.round Math.random() * 255 aContext.fillStyle = "rgb("+randomR+","+randomG+","+randomB+")" aContext.fillRect Math.round(eachBrokenRect.origin.x), Math.round(eachBrokenRect.origin.y), Math.round(eachBrokenRect.width()), Math.round(eachBrokenRect.height()) aContext.restore() # this part is excluded from the fizzygum homepage build <<« # layouts are recalculated like so: # there will be several subtrees # that will need relayout. # So take the head of any subtree and re-layout it # The relayout might or might not visit all the subnodes # of the subtree, because you might have a subtree # that lives inside a floating morph, in which # case it's not re-layout. # So, a subtree might not be healed in one go, # rather we keep track of what's left to heal and # we apply the same process: we heal from the head node # and take out of the list what's healed in that step, # and we continue doing so until there is nothing else # to heal. recalculateLayouts: -> until @morphsThatMaybeChangedLayout.length == 0 # find the first Widget which has a broken layout, # take out of queue all the others loop tryThisMorph = @morphsThatMaybeChangedLayout[@morphsThatMaybeChangedLayout.length - 1] if tryThisMorph.layoutIsValid @morphsThatMaybeChangedLayout.pop() if @morphsThatMaybeChangedLayout.length == 0 return else break # now that you have a Widget with a broken layout # go up the chain of broken layouts as much as # possible # QUESTION: would it be safer instead to start from the # very top invalid morph, i.e. on the way to the top, # stop at the last morph with an invalid layout # instead of stopping at the first morph with a # valid layout... while tryThisMorph.parent? if tryThisMorph.layoutSpec == LayoutSpec.ATTACHEDAS_FREEFLOATING or tryThisMorph.parent.layoutIsValid break tryThisMorph = tryThisMorph.parent try # so now you have a "top" element up a chain # of morphs with broken layout. Go do a # doLayout on it, so it might fix a bunch of those # on the chain (but not all) tryThisMorph.doLayout() catch err @softResetWorld() if !@errorConsole? then @createErrorConsole() @errorConsole.contents.showUpWithError err clearGeometryOrPositionPossiblyChangedFlags: -> for m in @morphsThatMaybeChangedGeometryOrPosition m.geometryOrPositionPossiblyChanged = false clearFullGeometryOrPositionPossiblyChangedFlags: -> for m in @morphsThatMaybeChangedFullGeometryOrPosition m.fullGeometryOrPositionPossiblyChanged = false disableTrackChanges: -> @trackChanges.push false maybeEnableTrackChanges: -> @trackChanges.pop() updateBroken: -> #console.log "number of broken rectangles: " + @broken.length @broken = [] @duplicatedBrokenRectsTracker = {} @numberOfDuplicatedBrokenRects = 0 @numberOfMergedSourceAndDestination = 0 @fleshOutFullBroken() @fleshOutBroken() @rectAlreadyIncludedInParentBrokenMorph() @cleanupSrcAndDestRectsOfMorphs() @clearGeometryOrPositionPossiblyChangedFlags() @clearFullGeometryOrPositionPossiblyChangedFlags() @morphsThatMaybeChangedGeometryOrPosition = [] @morphsThatMaybeChangedFullGeometryOrPosition = [] # »>> this part is excluded from the fizzygum homepage build #ProfilingDataCollector.profileBrokenRects @broken, @numberOfDuplicatedBrokenRects, @numberOfMergedSourceAndDestination # this part is excluded from the fizzygum homepage build <<« # each broken rectangle requires traversing the scenegraph to # redraw what's overlapping it. Not all Widgets are traversed # in particular the following can stop the recursion: # - invisible Widgets # - PanelWdgts that don't overlap the broken rectangle # Since potentially there is a lot of traversal ongoing for # each broken rectangle, one might want to consolidate overlapping # and nearby rectangles. @healingRectanglesPhase = true @errorsWhileRepainting = [] @broken.forEach (rect) => if !rect? return if rect.isNotEmpty() try @fullPaintIntoAreaOrBlitFromBackBuffer @worldCanvasContext, rect catch err @resetWorldCanvasContext() @queueErrorForLaterReporting err @hideOffendingWidget() @softResetWorld() # IF we got errors while repainting, the # screen might be in a bad state (because everything in front of the # "bad" widget is not repainted since the offending widget has # thrown, so nothing in front of it could be painted properly) # SO do COMPLETE repaints of the screen and hide # further offending widgets until there are no more errors # (i.e. the offending widgets are progressively hidden so eventually # we should repaint the whole screen without errors, hopefully) if @errorsWhileRepainting.length != 0 @findOutAllOtherOffendingWidgetsAndPaintWholeScreen() if @showRedraws @showBrokenRects @worldCanvasContext @resetDataStructuresForBrokenRects() @healingRectanglesPhase = false if @trackChanges.length != 1 and @trackChanges[0] != true alert "trackChanges array should have only one element (true)" findOutAllOtherOffendingWidgetsAndPaintWholeScreen: -> # we keep repainting the whole screen until there are no # errors. # Why do we need multiple repaints and not just one? # Because remember that when a widget throws an error while # repainting, it bubble all the way up and stops any # further repainting of the other widgets, potentially # preventing the finding of errors in the other # widgets. Hence, we need to keep repainting until # there are no errors. currentErrorsCount = @errorsWhileRepainting.length previousErrorsCount = nil numberOfTotalRepaints = 0 until previousErrorsCount == currentErrorsCount numberOfTotalRepaints++ try @fullPaintIntoAreaOrBlitFromBackBuffer @worldCanvasContext, @bounds catch err @resetWorldCanvasContext() @queueErrorForLaterReporting err @hideOffendingWidget() @softResetWorld() previousErrorsCount = currentErrorsCount currentErrorsCount = @errorsWhileRepainting.length #console.log "total repaints: " + numberOfTotalRepaints resetWorldCanvasContext: -> # when an error is thrown while painting, it's # possible that we are left with a context in a strange # mixed state, so try to bring it back to # normality as much as possible # We are doing this for "cleanliness" of the context # state, not because we care of the drawing being # perfect (we are eventually going to repaint the # whole screen without the offending widgets) @worldCanvasContext.closePath() @worldCanvasContext.resetTransform?() for j in [1...2000] @worldCanvasContext.restore() queueErrorForLaterReporting: (err) -> # now record the error so we can report it in the # next cycle, and add the offending widget to a # "banned" list @errorsWhileRepainting.push err if !@widgetsGivingErrorWhileRepainting.includes @paintingWidget @widgetsGivingErrorWhileRepainting.push @paintingWidget @paintingWidget.silentHide() hideOffendingWidget: -> if !@widgetsGivingErrorWhileRepainting.includes @paintingWidget @widgetsGivingErrorWhileRepainting.push @paintingWidget @paintingWidget.silentHide() resetDataStructuresForBrokenRects: -> @broken = [] @duplicatedBrokenRectsTracker = {} @numberOfDuplicatedBrokenRects = 0 @numberOfMergedSourceAndDestination = 0 # »>> this part is excluded from the fizzygum homepage build addPinoutingMorphs: -> @currentPinoutingMorphs.forEach (eachPinoutingMorph) => if @morphsToBePinouted.has eachPinoutingMorph.wdgtThisWdgtIsPinouting if eachPinoutingMorph.wdgtThisWdgtIsPinouting.hasMaybeChangedGeometryOrPosition() # reposition the pinout morph if needed peekThroughBox = eachPinoutingMorph.wdgtThisWdgtIsPinouting.clippedThroughBounds() eachPinoutingMorph.fullRawMoveTo new Point(peekThroughBox.right() + 10,peekThroughBox.top()) else @currentPinoutingMorphs.delete eachPinoutingMorph @morphsBeingPinouted.delete eachPinoutingMorph.wdgtThisWdgtIsPinouting eachPinoutingMorph.wdgtThisWdgtIsPinouting = nil eachPinoutingMorph.fullDestroy() @morphsToBePinouted.forEach (eachMorphNeedingPinout) => unless @morphsBeingPinouted.has eachMorphNeedingPinout hM = new StringMorph2 eachMorphNeedingPinout.toString() @add hM hM.wdgtThisWdgtIsPinouting = eachMorphNeedingPinout peekThroughBox = eachMorphNeedingPinout.clippedThroughBounds() hM.fullRawMoveTo new Point(peekThroughBox.right() + 10,peekThroughBox.top()) hM.setColor Color.BLUE hM.setWidth 400 @currentPinoutingMorphs.add hM @morphsBeingPinouted.add eachMorphNeedingPinout # this part is excluded from the fizzygum homepage build <<« addHighlightingMorphs: -> @currentHighlightingMorphs.forEach (eachHighlightingMorph) => if @morphsToBeHighlighted.has eachHighlightingMorph.wdgtThisWdgtIsHighlighting if eachHighlightingMorph.wdgtThisWdgtIsHighlighting.hasMaybeChangedGeometryOrPosition() eachHighlightingMorph.rawSetBounds eachHighlightingMorph.wdgtThisWdgtIsHighlighting.clippedThroughBounds() else @currentHighlightingMorphs.delete eachHighlightingMorph @morphsBeingHighlighted.delete eachHighlightingMorph.wdgtThisWdgtIsHighlighting eachHighlightingMorph.wdgtThisWdgtIsHighlighting = nil eachHighlightingMorph.fullDestroy() @morphsToBeHighlighted.forEach (eachMorphNeedingHighlight) => unless @morphsBeingHighlighted.has eachMorphNeedingHighlight hM = new HighlighterMorph @add hM hM.wdgtThisWdgtIsHighlighting = eachMorphNeedingHighlight hM.rawSetBounds eachMorphNeedingHighlight.clippedThroughBounds() hM.setColor Color.BLUE hM.setAlphaScaled 50 @currentHighlightingMorphs.add hM @morphsBeingHighlighted.add eachMorphNeedingHighlight # »>> this part is only needed for Macros progressOnMacroSteps: -> noCodeLoading: -> true noInputsOngoing: -> @eventsQueue.length == 0 # other useful tween functions here: # https://github.com/ashblue/simple-tween-js/blob/master/tween.js expoOut: (i, origin, distance, numberOfEvents) -> distance * (-Math.pow(2, -10 * i/numberOfEvents) + 1) + origin bringUpTestMenu: (millisecondsBetweenKeys = 35, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> @syntheticEventsShortcutsAndSpecialKeys "F2", millisecondsBetweenKeys, startTime syntheticEventsShortcutsAndSpecialKeys: (whichShortcutOrSpecialKey, millisecondsBetweenKeys = 35, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> switch whichShortcutOrSpecialKey when "F2" @eventsQueue.push new KeydownInputEvent "F2", "F2", false, false, false, false, true, startTime @eventsQueue.push new KeyupInputEvent "F2", "F2", false, false, false, false, true, startTime + millisecondsBetweenKeys syntheticEventsStringKeys: (theString, millisecondsBetweenKeys = 35, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> scheduledTimeOfEvent = startTime for i in [0...theString.length] isUpperCase = theString.charAt(i) == theString.charAt(i).toUpperCase() if isUpperCase @eventsQueue.push new KeydownInputEvent "Shift", "ShiftLeft", true, false, false, false, true, scheduledTimeOfEvent scheduledTimeOfEvent += millisecondsBetweenKeys # note that the second parameter (code) we are making up, assuming a hypothetical "1:1" key->code layout @eventsQueue.push new KeydownInputEvent theString.charAt(i), theString.charAt(i), isUpperCase, false, false, false, true, scheduledTimeOfEvent scheduledTimeOfEvent += millisecondsBetweenKeys # note that the second parameter (code) we are making up, assuming a hypothetical "1:1" key->code layout @eventsQueue.push new KeyupInputEvent theString.charAt(i), theString.charAt(i), isUpperCase, false, false, false, true, scheduledTimeOfEvent scheduledTimeOfEvent += millisecondsBetweenKeys if isUpperCase @eventsQueue.push new KeyupInputEvent "Shift", "ShiftLeft", false, false, false, false, true, scheduledTimeOfEvent scheduledTimeOfEvent += millisecondsBetweenKeys syntheticEventsMouseMovePressDragRelease: (orig, dest, millisecondsForDrag = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime(), numberOfEventsPerMillisecond = 1) -> @syntheticEventsMouseMove orig, "left button", 100, nil, startTime, numberOfEventsPerMillisecond @syntheticEventsMouseDown "left button", startTime + 100 @syntheticEventsMouseMove dest, "left button", millisecondsForDrag, orig, startTime + 100 + 100, numberOfEventsPerMillisecond @syntheticEventsMouseUp "left button", startTime + 100 + 100 + millisecondsForDrag + 100 # This should be used if you want to drag from point A to B to C ... # If rather you want to just drag from point A to point B, # then just use syntheticEventsMouseMovePressDragRelease syntheticEventsMouseMoveWhileDragging: (dest, milliseconds = 1000, orig = @hand.position(), startTime = WorldMorph.dateOfCurrentCycleStart.getTime(), numberOfEventsPerMillisecond = 1) -> @syntheticEventsMouseMove dest, "left button", milliseconds, orig, startTime, numberOfEventsPerMillisecond # mouse moves need an origin and a destination, so we # need to place the mouse in _some_ place to begin with # in order to do that. syntheticEventsMousePlace: (place = new Point(0,0), scheduledTimeOfEvent = WorldMorph.dateOfCurrentCycleStart.getTime()) -> @eventsQueue.push new MousemoveInputEvent place.x, place.y, 0, 0, false, false, false, false, true, scheduledTimeOfEvent syntheticEventsMouseMove: (dest, whichButton = "no button", milliseconds = 1000, orig = @hand.position(), startTime = WorldMorph.dateOfCurrentCycleStart.getTime(), numberOfEventsPerMillisecond = 1) -> if whichButton == "left button" button = 0 buttons = 1 else if whichButton == "no button" button = 0 buttons = 0 else if whichButton == "right button" button = 0 buttons = 2 else debugger throw "syntheticEventsMouseMove: whichButton is unknown" if dest instanceof Widget dest = dest.center() if orig instanceof Widget orig = orig.center() numberOfEvents = milliseconds * numberOfEventsPerMillisecond for i in [0...numberOfEvents] scheduledTimeOfEvent = startTime + i/numberOfEventsPerMillisecond nextX = Math.round @expoOut i, orig.x, (dest.x-orig.x), numberOfEvents nextY = Math.round @expoOut i, orig.y, (dest.y-orig.y), numberOfEvents if nextX != prevX or nextY != prevY prevX = nextX prevY = nextY #console.log nextX + " " + nextY + " scheduled at: " + scheduledTimeOfEvent @eventsQueue.push new MousemoveInputEvent nextX, nextY, button, buttons, false, false, false, false, true, scheduledTimeOfEvent syntheticEventsMouseClick: (whichButton = "left button", milliseconds = 100, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> @syntheticEventsMouseDown whichButton, startTime @syntheticEventsMouseUp whichButton, startTime + milliseconds syntheticEventsMouseDown: (whichButton = "left button", startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> if whichButton == "left button" button = 0 buttons = 1 else if whichButton == "right button" button = 2 buttons = 2 else debugger throw "syntheticEventsMouseDown: whichButton is unknown" @eventsQueue.push new MousedownInputEvent button, buttons, false, false, false, false, true, startTime syntheticEventsMouseUp: (whichButton = "left button", startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> if whichButton == "left button" button = 0 buttons = 0 else if whichButton == "right button" button = 2 buttons = 0 else debugger throw "syntheticEventsMouseUp: whichButton is unknown" @eventsQueue.push new MouseupInputEvent button, buttons, false, false, false, false, true, startTime moveToAndClick: (positionOrWidget, whichButton = "left button", milliseconds = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> @syntheticEventsMouseMove positionOrWidget, "no button", milliseconds, nil, startTime, nil @syntheticEventsMouseClick whichButton, 100, startTime + milliseconds + 100 openMenuOf: (widget, milliseconds = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> @moveToAndClick widget, "right button", milliseconds, startTime getMostRecentlyOpenedMenu: -> # gets the last element added to the "freshlyCreatedPopUps" set # (Sets keep order of insertion) Array.from(@freshlyCreatedPopUps).pop() getTextMenuItemFromMenu: (theMenu, theLabel) -> theMenu.topWdgtSuchThat (item) -> if item.labelString? item.labelString == theLabel else false moveToItemOfTopMenuAndClick: (theLabel) -> theMenu = @getMostRecentlyOpenedMenu() theItem = @getTextMenuItemFromMenu theMenu, theLabel @moveToAndClick theItem findTopWidgetByClassNameOrClass: (widgetNameOrClass) -> if typeof widgetNameOrClass == "string" @topWdgtSuchThat (item) -> item.morphClassString() == "AnalogClockWdgt" else @topWdgtSuchThat (item) -> item instanceof widgetNameOrClass calculateVertBarMovement: (vBar, index, total) -> vBarHandle = vBar.children[0] vBarHandleCenter = vBarHandle.center() highestHandlePosition = vBar.top() lowestHandlePosition = vBar.bottom() - vBarHandle.height() highestHandleCenterPosition = highestHandlePosition + vBarHandle.height()/2 lowestHandleCenterPosition = lowestHandlePosition + vBarHandle.height()/2 handleCenterRange = lowestHandleCenterPosition - highestHandleCenterPosition handleCenterOffset = Math.round index * handleCenterRange / (total-1) [vBarHandleCenter, vBarHandleCenter.translateBy new Point(0,handleCenterOffset)] bringListItemFromTopInspectorInView: (listItemString) -> inspectorNaked = @findTopWidgetByClassNameOrClass InspectorMorph2 list = inspectorNaked.list elements = list.elements vBar = list.vBar index = elements.indexOf listItemString total = elements.length [vBarCenterFromHere, vBarCenterToHere] = @calculateVertBarMovement vBar, index, total @syntheticEventsMouseMovePressDragRelease vBarCenterFromHere, vBarCenterToHere clickOnListItemFromTopInspector: (listItemString, milliseconds = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> inspectorNaked = @findTopWidgetByClassNameOrClass InspectorMorph2 list = inspectorNaked.list entry = list.topWdgtSuchThat (item) -> if item.text? item.text == listItemString else false entryTopLeft = entry.topLeft() @moveToAndClick entryTopLeft.translateBy(new Point 10, 2), "left button", milliseconds, startTime clickOnCodeBoxFromTopInspectorAtCodeString: (codeString, occurrenceNumber = 1, after = true, milliseconds = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> inspectorNaked = @findTopWidgetByClassNameOrClass InspectorMorph2 slotCoords = inspectorNaked.textMorph.text.getNthPositionInStringBeforeOrAfter codeString, occurrenceNumber, after clickPosition = inspectorNaked.textMorph.slotCoordinates(slotCoords).translateBy new Point 3,3 @moveToAndClick clickPosition, "left button", milliseconds, startTime clickOnSaveButtonFromTopInspector: (milliseconds = 1000, startTime = WorldMorph.dateOfCurrentCycleStart.getTime()) -> inspectorNaked = @findTopWidgetByClassNameOrClass InspectorMorph2 saveButton = inspectorNaked.saveButton @moveToAndClick saveButton, "left button", milliseconds, startTime bringcodeStringFromTopInspectorInView: (codeString, occurrenceNumber = 1, after = true) -> inspectorNaked = @findTopWidgetByClassNameOrClass InspectorMorph2 slotCoords = inspectorNaked.textMorph.text.getNthPositionInStringBeforeOrAfter codeString, occurrenceNumber, after textScrollPane = inspectorNaked.topWdgtSuchThat (item) -> item.morphClassString() == "SimplePlainTextScrollPanelWdgt" textMorph = inspectorNaked.textMorph vBar = textScrollPane.vBar index = textMorph.slotRowAndColumn(slotCoords)[0] total = textMorph.wrappedLines.length [vBarCenterFromHere, vBarCenterToHere] = @calculateVertBarMovement vBar, index, total @syntheticEventsMouseMovePressDragRelease vBarCenterFromHere, vBarCenterToHere draftRunMacro: -> # When does it make sense to generate events "just via functions" vs. # needing a macro? # # **Important Note:** a macro can call functions, while functions # can never include macros!!! # # A macro is needed: # 1. for generating (potentially via functions!) events spanning # multiple cycles. E.g. "opening the inspector for a widget", # which involves moving the mouse there, right-clicking on # the widget, wait a cycle for the menu to come up, then # navigating other menus, until finally finding and # clicking on a "inspect" entry, # and finally waiting a cycle for the inspector to come up. # Those things *together* can't be done using functions alone # (i.e. with no macros), because functions can only push # synthetic events (now or in the future) all at once. # 2. so to have a convenient way to specify pauses between # events. This could also be done with functions, however # it's more convoluted. # # For all other cases, macros are not needed, i.e. functions alone # can suffice. Note that # functions *can* specify events that # happen over time e.g. multiple key strokes and events # happening over a few seconds, as there are parameters that help # to specify dates of events in the future. As mentioned though, # functions alone cannot "see past the effects" of any event happening # in the future. # # Examples of macros (potentially using functions): # - opening a menu of a widget AND clicking on one of its items # - opening inspector for a widget # - opening inspector for a widget, changing a method, then # clicking "save" # # Examples that don't need macros (functions alone are OK): # - moving an icon to the bin # - closing the top window # - opening the menu of a widget # - moving pointer to entry of top menu and clicking it macroSubroutines = new Set macroSubroutines.add Macro.fromString """ Macro bringUpInspector whichWidget ⤷clickMenuItemOfWidget whichWidget | "dev ➜" ▶ when no inputs ongoing @moveToItemOfTopMenuAndClick "inspect" """ macroSubroutines.add Macro.fromString """ Macro bringUpInspectorAndSelectListItem whichWidget | whichItem ⤷bringUpInspector whichWidget ▶ when no inputs ongoing ⤷bringInViewAndClickOnListItemFromTopInspector whichItem """ macroSubroutines.add Macro.fromString """ Macro bringInViewAndClickOnListItemFromTopInspector whichItem @bringListItemFromTopInspectorInView whichItem ▶ when no inputs ongoing @clickOnListItemFromTopInspector whichItem """ macroSubroutines.add Macro.fromString """ Macro clickMenuItemOfWidget whichWidget | whichItem @openMenuOf whichWidget ▶ when no inputs ongoing @moveToItemOfTopMenuAndClick whichItem """ macroSubroutines.add Macro.fromString """ Macro printoutsMacro string1 | string2 | string3 ▶ ⌛ 1s 🖨️ string1 ▶ ⌛ 1s 🖨️ string2 💼aLocalVariableInACall = "" ▶ ⌛ 1s 🖨️ string3 """ macroSubroutines.add Macro.fromString """ Macro macroWithNoParams 🖨️ "macro with no params" """ macroSubroutines.add Macro.fromString """ Macro macroWithOneParam theParameter 🖨️ "macro with one param: " + theParameter """ macroSubroutines.add Macro.fromString """ Macro macroWithOneParamButPassingNone theParameter 🖨️ "macro with one param but passing none, this should be undefined: " + theParameter """ macroSubroutines.add Macro.fromString """ Macro macroWithTwoParamsButPassingOnlyOne param1 | param2 🖨️ "macro with two params but passing only one: param 1: " + param1 + " param 2 should be undefined: " + param2 """ # TODO check that these are handled too # ▶ ⌛ 500 ms, when condition1() # ▶ # ⌛ 500 ms, when conditionCommented() mainMacro = Macro.fromString """ Macro theTestMacro @syntheticEventsStringKeys "SoMeThInG" ▶ ⌛ 1s ▶ ⤷printoutsMacro "first console out" | "second console out" | "third console out" ▶ ⌛ 1s 💼clock = @findTopWidgetByClassNameOrClass AnalogClockWdgt @syntheticEventsMouseMove 💼clock ▶ when no inputs ongoing @syntheticEventsMouseDown() ▶ when no inputs ongoing 💼clockCenter = 💼clock.center() @syntheticEventsMouseMoveWhileDragging ⦿(💼clockCenter.x - 4, 💼clockCenter.y + 4) ▶ ⌛ 1s @syntheticEventsMouseMoveWhileDragging ⦿(250,250) ▶ when no inputs ongoing @syntheticEventsMouseUp() ▶ when no inputs ongoing @syntheticEventsMouseMovePressDragRelease ⦿(5, 5), ⦿(200,200) ▶ when no inputs ongoing 🖨️ "finished the drag events" ⤷printoutsMacro "fourth console out" | "fifth console out" | "sixth console out" ▶ when no inputs ongoing ⤷bringUpInspectorAndSelectListItem 💼clock | "drawSecondsHand" ▶ when no inputs ongoing @bringcodeStringFromTopInspectorInView "context.restore()" ▶ when no inputs ongoing @clickOnCodeBoxFromTopInspectorAtCodeString "@secondsHandAngle", 1, false ▶ when no inputs ongoing @syntheticEventsStringKeys "-" @clickOnSaveButtonFromTopInspector() # some comments here ▶ when no inputs ongoing # also some comments here ⤷macroWithNoParams ⤷macroWithOneParam "here is the one param" ⤷macroWithOneParamButPassingNone ⤷macroWithTwoParamsButPassingOnlyOne "first parameter" ⤷macroWithNoParams # comment1 ⤷macroWithOneParam "here is the one param" # comment2 ⤷macroWithOneParamButPassingNone # comment3 ⤷macroWithTwoParamsButPassingOnlyOne "first parameter" # comment4 @bringUpTestMenu() """ mainMacro.linkTo macroSubroutines mainMacro.start() # this part is only needed for Macros <<« playQueuedEvents: -> try timeOfCurrentCycleStart = WorldMorph.dateOfCurrentCycleStart.getTime() for event in @eventsQueue if !event.time? then debugger # this happens when you consume synthetic events: you can inject # MANY of them across frames (say, a slow drag across the screen), # so you want to consume only the ones that pertain to the current # frame and return if event.time > timeOfCurrentCycleStart @eventsQueue.splice 0, @eventsQueue.indexOf(event) return # currently not handled: DOM virtual keyboard events event.processEvent() catch err @softResetWorld() if !@errorConsole? then @createErrorConsole() @errorConsole.contents.showUpWithError err @eventsQueue = [] # we keep the "pacing" promises in this # framePacedPromises array, (or, more precisely, # we keep their resolving functions) and each frame # we resolve one, so we don't cause gitter. progressFramePacedActions: -> if window.framePacedPromises.length > 0 resolvingFunction = window.framePacedPromises.shift() resolvingFunction.call() showErrorsHappenedInRepaintingStepInPreviousCycle: -> for eachErr in @errorsWhileRepainting if !@errorConsole? then @createErrorConsole() @errorConsole.contents.showUpWithError eachErr updateTimeReferences: -> WorldMorph.dateOfCurrentCycleStart = new Date if !WorldMorph.dateOfPreviousCycleStart? WorldMorph.dateOfPreviousCycleStart = new Date WorldMorph.dateOfCurrentCycleStart.getTime() - 30 # »>> this part is only needed for Macros if !@macroStepsWaitingTimer? @macroStepsWaitingTimer = 0 else @macroStepsWaitingTimer += WorldMorph.dateOfCurrentCycleStart.getTime() - WorldMorph.dateOfPreviousCycleStart.getTime() # this part is only needed for Macros <<« doOneCycle: -> @updateTimeReferences() #console.log TextMorph.instancesCounter + " " + StringMorph.instancesCounter @showErrorsHappenedInRepaintingStepInPreviousCycle() # »>> this part is only needed for Macros @progressOnMacroSteps() # this part is only needed for Macros <<« @playQueuedEvents() # replays test actions at the right time if AutomatorPlayer? and Automator.state == Automator.PLAYING @automator.player.replayTestCommands() # currently unused @runOtherTasksStepFunction() # used to load fizzygum sources progressively @progressFramePacedActions() @runChildrensStepFunction() @hand.reCheckMouseEntersAndMouseLeavesAfterPotentialGeometryChanges() window.recalculatingLayouts = true @recalculateLayouts() window.recalculatingLayouts = false # »>> this part is excluded from the fizzygum homepage build @addPinoutingMorphs() # this part is excluded from the fizzygum homepage build <<« @addHighlightingMorphs() # here is where the repainting on screen happens @updateBroken() WorldMorph.frameCount++ WorldMorph.dateOfPreviousCycleStart = WorldMorph.dateOfCurrentCycleStart WorldMorph.dateOfCurrentCycleStart = nil # Widget stepping: runChildrensStepFunction: -> # TODO all these set modifications should be immutable... @steppingWdgts.forEach (eachSteppingMorph) => #if eachSteppingMorph.isBeingFloatDragged() # continue # for objects where @fps is defined, check which ones are due to be stepped # and which ones want to wait. millisBetweenSteps = Math.round(1000 / eachSteppingMorph.fps) timeOfCurrentCycleStart = WorldMorph.dateOfCurrentCycleStart.getTime() if eachSteppingMorph.fps <= 0 # if fps 0 or negative, then just run as fast as possible, # so 0 milliseconds remaining to the next invocation millisecondsRemainingToWaitedFrame = 0 else if eachSteppingMorph.synchronisedStepping millisecondsRemainingToWaitedFrame = millisBetweenSteps - (timeOfCurrentCycleStart % millisBetweenSteps) if eachSteppingMorph.previousMillisecondsRemainingToWaitedFrame != 0 and millisecondsRemainingToWaitedFrame > eachSteppingMorph.previousMillisecondsRemainingToWaitedFrame millisecondsRemainingToWaitedFrame = 0 eachSteppingMorph.previousMillisecondsRemainingToWaitedFrame = millisecondsRemainingToWaitedFrame #console.log millisBetweenSteps + " " + millisecondsRemainingToWaitedFrame else elapsedMilliseconds = timeOfCurrentCycleStart - eachSteppingMorph.lastTime millisecondsRemainingToWaitedFrame = millisBetweenSteps - elapsedMilliseconds # when the firing time comes (or as soon as it's past): if millisecondsRemainingToWaitedFrame <= 0 @stepWidget eachSteppingMorph # Increment "lastTime" by millisBetweenSteps. Two notes: # 1) We don't just set it to timeOfCurrentCycleStart so that there is no drifting # in running it the next time: we run it the next time as if this time it # ran exactly on time. # 2) We are going to update "last time" with the loop # below. This is because in case the window is not in foreground, # requestAnimationFrame doesn't run, so we might skip a number of steps. # In such cases, just bring "lastTime" up to speed here. # If we don't do that, "skipped" steps would catch up on us and run all # in contiguous frames when the window comes to foreground, so the # widgets would animate frantically (every frame) catching up on # all the steps they missed. We don't want that. # # while eachSteppingMorph.lastTime + millisBetweenSteps < timeOfCurrentCycleStart # eachSteppingMorph.lastTime += millisBetweenSteps # # 3) and finally, here is the equivalent of the loop above, but done # in one shot using remainders. # Again: we are looking for the last "multiple" k such that # lastTime + k * millisBetweenSteps # is less than timeOfCurrentCycleStart. eachSteppingMorph.lastTime = timeOfCurrentCycleStart - ((timeOfCurrentCycleStart - eachSteppingMorph.lastTime) % millisBetweenSteps) stepWidget: (whichWidget) -> if whichWidget.onNextStep nxt = whichWidget.onNextStep whichWidget.onNextStep = nil nxt.call whichWidget if !whichWidget.step? debugger try whichWidget.step() #console.log "stepping " + whichWidget catch err @softResetWorld() if !@errorConsole? then @createErrorConsole() @errorConsole.contents.showUpWithError err runOtherTasksStepFunction : -> for task in @otherTasksToBeRunOnStep #console.log "running a task: " + task task() # »>> this part is excluded from the fizzygum homepage build sizeCanvasToTestScreenResolution: -> @worldCanvas.width = Math.round(960 * ceilPixelRatio) @worldCanvas.height = Math.round(440 * ceilPixelRatio) @worldCanvas.style.width = "960px" @worldCanvas.style.height = "440px" bkground = document.getElementById("background") bkground.style.width = "960px" bkground.style.height = "720px" bkground.style.backgroundColor = Color.WHITESMOKE.toString() # this part is excluded from the fizzygum homepage build <<« stretchWorldToFillEntirePage: -> # once you call this, the world will forever take the whole page @automaticallyAdjustToFillEntireBrowserAlsoOnResize = true pos = @getCanvasPosition() clientHeight = window.innerHeight clientWidth = window.innerWidth if pos.x > 0 @worldCanvas.style.position = "absolute" @worldCanvas.style.left = "0px" pos.x = 0 if pos.y > 0 @worldCanvas.style.position = "absolute" @worldCanvas.style.top = "0px" pos.y = 0 # scrolled down b/c of viewport scaling clientHeight = document.documentElement.clientHeight if document.body.scrollTop # scrolled left b/c of viewport scaling clientWidth = document.documentElement.clientWidth if document.body.scrollLeft if (@worldCanvas.width isnt clientWidth) or (@worldCanvas.height isnt clientHeight) @fullChanged() @worldCanvas.width = (clientWidth * ceilPixelRatio) @worldCanvas.style.width = clientWidth + "px" @worldCanvas.height = (clientHeight * ceilPixelRatio) @worldCanvas.style.height = clientHeight + "px" @rawSetExtent new Point clientWidth, clientHeight @desktopReLayout() desktopReLayout: -> basementOpenerWdgt = @firstChildSuchThat (w) -> w instanceof BasementOpenerWdgt if basementOpenerWdgt? if basementOpenerWdgt.userMovedThisFromComputedPosition basementOpenerWdgt.fullRawMoveInDesktopToFractionalPosition() if !basementOpenerWdgt.wasPositionedSlightlyOutsidePanel basementOpenerWdgt.fullRawMoveWithin @ else basementOpenerWdgt.fullMoveTo @bottomRight().subtract (new Point 75, 75).add @desktopSidesPadding analogClockWdgt = @firstChildSuchThat (w) -> w instanceof AnalogClockWdgt if analogClockWdgt? if analogClockWdgt.userMovedThisFromComputedPosition analogClockWdgt.fullRawMoveInDesktopToFractionalPosition() if !analogClockWdgt.wasPositionedSlightlyOutsidePanel analogClockWdgt.fullRawMoveWithin @ else analogClockWdgt.fullMoveTo new Point @right() - 80 - @desktopSidesPadding, @top() + @desktopSidesPadding @children.forEach (child) => if child != basementOpenerWdgt and child != analogClockWdgt and !(child instanceof WidgetHolderWithCaptionWdgt) if child.positionFractionalInHoldingPanel? child.fullRawMoveInDesktopToFractionalPosition() if !child.wasPositionedSlightlyOutsidePanel child.fullRawMoveWithin @ # WorldMorph events: # »>> this part is excluded from the fizzygum homepage build initVirtualKeyboard: -> if @inputDOMElementForVirtualKeyboard document.body.removeChild @inputDOMElementForVirtualKeyboard @inputDOMElementForVirtualKeyboard = nil unless (WorldMorph.preferencesAndSettings.isTouchDevice and WorldMorph.preferencesAndSettings.useVirtualKeyboard) return @inputDOMElementForVirtualKeyboard = document.createElement "input" @inputDOMElementForVirtualKeyboard.type = "text" @inputDOMElementForVirtualKeyboard.style.color = Color.TRANSPARENT.toString() @inputDOMElementForVirtualKeyboard.style.backgroundColor = Color.TRANSPARENT.toString() @inputDOMElementForVirtualKeyboard.style.border = "none" @inputDOMElementForVirtualKeyboard.style.outline = "none" @inputDOMElementForVirtualKeyboard.style.position = "absolute" @inputDOMElementForVirtualKeyboard.style.top = "0px" @inputDOMElementForVirtualKeyboard.style.left = "0px" @inputDOMElementForVirtualKeyboard.style.width = "0px" @inputDOMElementForVirtualKeyboard.style.height = "0px" @inputDOMElementForVirtualKeyboard.autocapitalize = "none" # iOS specific document.body.appendChild @inputDOMElementForVirtualKeyboard @inputDOMElementForVirtualKeyboardKeydownBrowserEventListener = (event) => @eventsQueue.push InputDOMElementForVirtualKeyboardKeydownInputEvent.fromBrowserEvent event # Default in several browsers # is for the backspace button to trigger # the "back button", so we prevent that # default here. if event.keyIdentifier is "U+0008" or event.keyIdentifier is "Backspace" event.preventDefault() # suppress tab override and make sure tab gets # received by all browsers if event.keyIdentifier is "U+0009" or event.keyIdentifier is "Tab" event.preventDefault() @inputDOMElementForVirtualKeyboard.addEventListener "keydown", @inputDOMElementForVirtualKeyboardKeydownBrowserEventListener, false @inputDOMElementForVirtualKeyboardKeyupBrowserEventListener = (event) => @eventsQueue.push InputDOMElementForVirtualKeyboardKeyupInputEvent.fromBrowserEvent event event.preventDefault() @inputDOMElementForVirtualKeyboard.addEventListener "keyup", @inputDOMElementForVirtualKeyboardKeyupBrowserEventListener, false # Keypress events are deprecated in the JS specs and are not needed @inputDOMElementForVirtualKeyboardKeypressBrowserEventListener = (event) => #@eventsQueue.push event event.preventDefault() @inputDOMElementForVirtualKeyboard.addEventListener "keypress", @inputDOMElementForVirtualKeyboardKeypressBrowserEventListener, false # this part is excluded from the fizzygum homepage build <<« getPointerAndWdgtInfo: (topWdgtUnderPointer = @hand.topWdgtUnderPointer()) -> # we might eliminate this command afterwards if # we find out user is clicking on a menu item # or right-clicking on a morph absoluteBoundsOfMorphRelativeToWorld = topWdgtUnderPointer.boundingBox().asArray_xywh() morphIdentifierViaTextLabel = topWdgtUnderPointer.identifyViaTextLabel() morphPathRelativeToWorld = topWdgtUnderPointer.pathOfChildrenPositionsRelativeToWorld() pointerPositionFractionalInMorph = @hand.positionFractionalInMorph topWdgtUnderPointer pointerPositionPixelsInMorph = @hand.positionPixelsInMorph topWdgtUnderPointer # note that this pointer position is in world # coordinates not in page coordinates pointerPositionPixelsInWorld = @hand.position() isPartOfListMorph = (topWdgtUnderPointer.parentThatIsA ListMorph)? return [ topWdgtUnderPointer.uniqueIDString(), morphPathRelativeToWorld, morphIdentifierViaTextLabel, absoluteBoundsOfMorphRelativeToWorld, pointerPositionFractionalInMorph, pointerPositionPixelsInMorph, pointerPositionPixelsInWorld, isPartOfListMorph] # ----------------------------------------------------- # clipboard events processing # ----------------------------------------------------- initMouseEventListeners: -> canvas = @worldCanvas # there is indeed a "dblclick" JS event # but we reproduce it internally. # The reason is that we do so for "click" # because we want to check that the mouse # button was released in the same morph # where it was pressed (cause in the DOM you'd # be pressing and releasing on the same # element i.e. the canvas anyways # so we receive clicks even though they aren't # so we have to take care of the processing # ourselves). # So we also do the same internal # processing for dblclick. # Hence, don't register this event listener # below... #@dblclickEventListener = (event) => # event.preventDefault() # @hand.processDoubleClick event #canvas.addEventListener "dblclick", @dblclickEventListener, false @mousedownBrowserEventListener = (event) => @eventsQueue.push MousedownInputEvent.fromBrowserEvent event canvas.addEventListener "mousedown", @mousedownBrowserEventListener, false @mouseupBrowserEventListener = (event) => @eventsQueue.push MouseupInputEvent.fromBrowserEvent event canvas.addEventListener "mouseup", @mouseupBrowserEventListener, false @mousemoveBrowserEventListener = (event) => @eventsQueue.push MousemoveInputEvent.fromBrowserEvent event canvas.addEventListener "mousemove", @mousemoveBrowserEventListener, false initTouchEventListeners: -> canvas = @worldCanvas @touchstartBrowserEventListener = (event) => @eventsQueue.push TouchstartInputEvent.fromBrowserEvent event event.preventDefault() # (unsure that this one is needed) canvas.addEventListener "touchstart", @touchstartBrowserEventListener, false @touchendBrowserEventListener = (event) => @eventsQueue.push TouchendInputEvent.fromBrowserEvent event event.preventDefault() # prevent mouse events emulation canvas.addEventListener "touchend", @touchendBrowserEventListener, false @touchmoveBrowserEventListener = (event) => @eventsQueue.push TouchmoveInputEvent.fromBrowserEvent event event.preventDefault() # (unsure that this one is needed) canvas.addEventListener "touchmove", @touchmoveBrowserEventListener, false @gesturestartBrowserEventListener = (event) => # we don't do anything with gestures for the time being event.preventDefault() # (unsure that this one is needed) canvas.addEventListener "gesturestart", @gesturestartBrowserEventListener, false @gesturechangeBrowserEventListener = (event) => # we don't do anything with gestures for the time being event.preventDefault() # (unsure that this one is needed) canvas.addEventListener "gesturechange", @gesturechangeBrowserEventListener, false initKeyboardEventListeners: -> canvas = @worldCanvas @keydownBrowserEventListener = (event) => @eventsQueue.push KeydownInputEvent.fromBrowserEvent event # this paragraph is to prevent the browser going # "back button" when the user presses delete backspace. # taken from http://stackoverflow.com/a/2768256 doPrevent = false if event.key == "Backspace" d = event.srcElement or event.target if d.tagName.toUpperCase() == 'INPUT' and (d.type.toUpperCase() == 'TEXT' or d.type.toUpperCase() == 'PASSWORD' or d.type.toUpperCase() == 'FILE' or d.type.toUpperCase() == 'SEARCH' or d.type.toUpperCase() == 'EMAIL' or d.type.toUpperCase() == 'NUMBER' or d.type.toUpperCase() == 'DATE') or d.tagName.toUpperCase() == 'TEXTAREA' doPrevent = d.readOnly or d.disabled else doPrevent = true # this paragraph is to prevent the browser scrolling when # user presses spacebar, see # https://stackoverflow.com/a/22559917 if event.key == " " and event.target == @worldCanvas # Note that doing a preventDefault on the spacebar # causes it not to generate the keypress event # (just the keydown), so we had to modify the keydown # to also process the space. # (I tried to use stopPropagation instead/inaddition but # it didn't work). doPrevent = true # also browsers tend to do special things when "tab" # is pressed, so let's avoid that if event.key == "Tab" and event.target == @worldCanvas doPrevent = true if doPrevent event.preventDefault() canvas.addEventListener "keydown", @keydownBrowserEventListener, false @keyupBrowserEventListener = (event) => @eventsQueue.push KeyupInputEvent.fromBrowserEvent event canvas.addEventListener "keyup", @keyupBrowserEventListener, false # keypress is deprecated in the latest specs, and it's really not needed/used, # since all keys really have an effect when they are pushed down @keypressBrowserEventListener = (event) => canvas.addEventListener "keypress", @keypressBrowserEventListener, false initClipboardEventListeners: -> # snippets of clipboard-handling code taken from # http://codebits.glennjones.net/editing/setclipboarddata.htm # Note that this works only in Chrome. Firefox and Safari need a piece of # text to be selected in order to even trigger the copy event. Chrome does # enable clipboard access instead even if nothing is selected. # There are a couple of solutions to this - one is to keep a hidden textfield that # handles all copy/paste operations. # Another one is to not use a clipboard, but rather an internal string as # local memory. So the OS clipboard wouldn't be used, but at least there would # be some copy/paste working. Also one would need to intercept the copy/paste # key combinations manually instead of from the copy/paste events. # ----------------------------------------------------- # clipboard events listeners # ----------------------------------------------------- # we deal with the clipboard here in the event listeners # because for security reasons the runtime is not allowed # access to the clipboards outside of here. So we do all # we have to do with the clipboard here, and in every # other place we work with text. @cutBrowserEventListener = (event) => # TODO this should follow the fromBrowserEvent pattern @eventsQueue.push CutInputEvent.fromBrowserEvent event document.body.addEventListener "cut", @cutBrowserEventListener, false @copyBrowserEventListener = (event) => # TODO this should follow the fromBrowserEvent pattern @eventsQueue.push CopyInputEvent.fromBrowserEvent event document.body.addEventListener "copy", @copyBrowserEventListener, false @pasteBrowserEventListener = (event) => # TODO this should follow the fromBrowserEvent pattern @eventsQueue.push PasteInputEvent.fromBrowserEvent event document.body.addEventListener "paste", @pasteBrowserEventListener, false initKeyCombosEventListeners: -> # »>> this part is excluded from the fizzygum homepage build #console.log "binding via mousetrap" @keyComboResetWorldEventListener = (event) => if AutomatorRecorder? @automator.recorder.resetWorld() false Mousetrap.bind ["alt+d"], @keyComboResetWorldEventListener @keyComboTurnOnAnimationsPacingControl = (event) => if Automator? @automator.recorder.turnOnAnimationsPacingControl() false Mousetrap.bind ["alt+e"], @keyComboTurnOnAnimationsPacingControl @keyComboTurnOffAnimationsPacingControl = (event) => if Automator? @automator.recorder.turnOffAnimationsPacingControl() false Mousetrap.bind ["alt+u"], @keyComboTurnOffAnimationsPacingControl @keyComboTakeScreenshotEventListener = (event) => if AutomatorRecorder? @automator.recorder.addTakeScreenshotCommand() false Mousetrap.bind ["alt+c"], @keyComboTakeScreenshotEventListener @keyComboStopTestRecordingEventListener = (event) => if Automator? @automator.recorder.stopTestRecording() false Mousetrap.bind ["alt+t"], @keyComboStopTestRecordingEventListener @keyComboAddTestCommentEventListener = (event) => if Automator? @automator.recorder.addTestComment() false Mousetrap.bind ["alt+m"], @keyComboAddTestCommentEventListener @keyComboCheckNumberOfMenuItemsEventListener = (event) => if AutomatorRecorder? @automator.recorder.addCheckNumberOfItemsInMenuCommand() false Mousetrap.bind ["alt+k"], @keyComboCheckNumberOfMenuItemsEventListener @keyComboCheckStringsOfItemsInMenuOrderImportant = (event) => if AutomatorRecorder? @automator.recorder.addCheckStringsOfItemsInMenuOrderImportantCommand() false Mousetrap.bind ["alt+a"], @keyComboCheckStringsOfItemsInMenuOrderImportant @keyComboCheckStringsOfItemsInMenuOrderUnimportant = (event) => if AutomatorRecorder? @automator.recorder.addCheckStringsOfItemsInMenuOrderUnimportantCommand() false Mousetrap.bind ["alt+z"], @keyComboCheckStringsOfItemsInMenuOrderUnimportant # this part is excluded from the fizzygum homepage build <<« initOtherMiscEventListeners: -> canvas = @worldCanvas @contextmenuEventListener = (event) -> # suppress context menu for Mac-Firefox event.preventDefault() canvas.addEventListener "contextmenu", @contextmenuEventListener, false # Safari, Chrome @wheelBrowserEventListener = (event) => @eventsQueue.push WheelInputEvent.fromBrowserEvent event event.preventDefault() canvas.addEventListener "wheel", @wheelBrowserEventListener, false # CHECK AFTER 15 Jan 2021 00:00:00 GMT # As of Oct 2020, using mouse/trackpad in # Mobile Safari, the wheel event is not sent. # See: # https://github.com/cdr/code-server/issues/1455 # https://bugs.webkit.org/show_bug.cgi?id=210071 # However, the scroll event is sent, and when that is sent, # we can use the window.pageYOffset # to re-create a passable, fake wheel event. if Utils.runningInMobileSafari() window.addEventListener "scroll", @wheelBrowserEventListener, false @dragoverEventListener = (event) -> event.preventDefault() window.addEventListener "dragover", @dragoverEventListener, false @dropBrowserEventListener = (event) => # nothing here, although code for handling a "drop" is in the # comments event.preventDefault() window.addEventListener "drop", @dropBrowserEventListener, false @resizeBrowserEventListener = => @eventsQueue.push ResizeInputEvent.fromBrowserEvent event # this is a DOM thing, little to do with other r e s i z e methods window.addEventListener "resize", @resizeBrowserEventListener, false # note that we don't register the normal click, # we figure that out independently. initEventListeners: -> @initMouseEventListeners() @initTouchEventListeners() @initKeyboardEventListeners() @initClipboardEventListeners() @initKeyCombosEventListeners() @initOtherMiscEventListeners() # »>> this part is excluded from the fizzygum homepage build removeEventListeners: -> canvas = @worldCanvas # canvas.removeEventListener 'dblclick', @dblclickEventListener canvas.removeEventListener 'mousedown', @mousedownBrowserEventListener canvas.removeEventListener 'mouseup', @mouseupBrowserEventListener canvas.removeEventListener 'mousemove', @mousemoveBrowserEventListener canvas.removeEventListener 'contextmenu', @contextmenuEventListener canvas.removeEventListener "touchstart", @touchstartBrowserEventListener canvas.removeEventListener "touchend", @touchendBrowserEventListener canvas.removeEventListener "touchmove", @touchmoveBrowserEventListener canvas.removeEventListener "gesturestart", @gesturestartBrowserEventListener canvas.removeEventListener "gesturechange", @gesturechangeBrowserEventListener canvas.removeEventListener 'keydown', @keydownBrowserEventListener canvas.removeEventListener 'keyup', @keyupBrowserEventListener canvas.removeEventListener 'keypress', @keypressBrowserEventListener canvas.removeEventListener 'wheel', @wheelBrowserEventListener if Utils.runningInMobileSafari() canvas.removeEventListener 'scroll', @wheelBrowserEventListener canvas.removeEventListener 'cut', @cutBrowserEventListener canvas.removeEventListener 'copy', @copyBrowserEventListener canvas.removeEventListener 'paste', @pasteBrowserEventListener Mousetrap.reset() canvas.removeEventListener 'dragover', @dragoverEventListener canvas.removeEventListener 'resize', @resizeBrowserEventListener canvas.removeEventListener 'drop', @dropBrowserEventListener # this part is excluded from the fizzygum homepage build <<« mouseDownLeft: -> noOperation mouseClickLeft: -> noOperation mouseDownRight: -> noOperation # »>> this part is excluded from the fizzygum homepage build droppedImage: -> nil droppedSVG: -> nil # this part is excluded from the fizzygum homepage build <<« # WorldMorph text field tabbing: nextTab: (editField) -> next = @nextEntryField editField if next @switchTextFieldFocus editField, next previousTab: (editField) -> prev = @previousEntryField editField if prev @switchTextFieldFocus editField, prev switchTextFieldFocus: (current, next) -> current.clearSelection() next.bringToForeground() next.selectAll() next.edit() # if an error is thrown, the state of the world might # be messy, for example the pointer might be # dragging an invisible morph, etc. # So, try to clean-up things as much as possible. softResetWorld: -> @hand.drop() @hand.mouseOverList.clear() @hand.nonFloatDraggedWdgt = nil @wdgtsDetectingClickOutsideMeOrAnyOfMeChildren.clear() @lastNonTextPropertyChangerButtonClickedOrDropped = nil # »>> this part is excluded from the fizzygum homepage build resetWorld: -> @softResetWorld() @changed() # redraw the whole screen @fullDestroyChildren() # the "basementWdgt" is not attached to the # world tree so it's not in the children, # so we need to clean up separately @basementWdgt?.empty() # some tests might change the background # color of the world so let's reset it. @setColor Color.create 205, 205, 205 SystemTestsControlPanelUpdater.blinkLink SystemTestsControlPanelUpdater.resetWorldLink # make sure thw window is scrolled to top # so we can see the test results while tests # are running. document.body.scrollTop = document.documentElement.scrollTop = 0 # this part is excluded from the fizzygum homepage build <<« # There is something special about the # "world" version of fullDestroyChildren: # it resets the counter used to count # how many morphs exist of each Widget class. # That counter is also used to determine the # unique ID of a Widget. So, destroying # all morphs from the world causes the # counts and IDs of all the subsequent # morphs to start from scratch again. fullDestroyChildren: -> # Check which objects end with the word Widget theWordMorph = "Morph" theWordWdgt = "Wdgt" theWordWidget = "Widget" ListOfMorphs = (Object.keys(window)).filter (i) -> i.includes(theWordMorph, i.length - theWordMorph.length) or i.includes(theWordWdgt, i.length - theWordWdgt.length) or i.includes(theWordWidget, i.length - theWordWidget.length) for eachMorphClass in ListOfMorphs if eachMorphClass != "WorldMorph" #console.log "resetting " + eachMorphClass + " from " + window[eachMorphClass].instancesCounter # the actual count is in another variable "instancesCounter" # but all labels are built using instanceNumericID # which is set based on lastBuiltInstanceNumericID window[eachMorphClass].lastBuiltInstanceNumericID = 0 # »>> this part is excluded from the fizzygum homepage build if Automator? @automator.recorder.turnOffAnimationsPacingControl() @automator.recorder.turnOffAlignmentOfMorphIDsMechanism() @automator.recorder.turnOffHidingOfMorphsContentExtractInLabels() @automator.recorder.turnOffHidingOfMorphsNumberIDInLabels() # this part is excluded from the fizzygum homepage build <<« super() destroyToolTips: -> # "toolTipsList" keeps the widgets to be deleted upon # the next mouse click, or whenever another temporary Widget decides # that it needs to remove them. # Note that we actually destroy toolTipsList because we are not expecting # anybody to revive them once they are gone (as opposed to menus) @toolTipsList.forEach (tooltip) => unless tooltip.boundsContainPoint @position() tooltip.fullDestroy() @toolTipsList.delete tooltip buildContextMenu: -> if @isIndexPage menu = new MenuMorph @, false, @, true, true, "Desktop" menu.addMenuItem "wallpapers ➜", false, @, "wallpapersMenu", "choose a wallpaper for the Desktop" menu.addMenuItem "new folder", true, @, "makeFolder" return menu if @isDevMode menu = new MenuMorph(@, false, @, true, true, @constructor.name or @constructor.toString().split(" ")[1].split("(")[0]) else menu = new MenuMorph @, false, @, true, true, "Widgetic" # »>> this part is excluded from the fizzygum homepage build if @isDevMode menu.addMenuItem "demo ➜", false, @, "popUpDemoMenu", "sample morphs" menu.addLine() # TODO remove these two, they do nothing now menu.addMenuItem "show all", true, @, "noOperation" menu.addMenuItem "hide all", true, @, "noOperation" menu.addMenuItem "delete all", true, @, "closeChildren" menu.addMenuItem "move all inside", true, @, "keepAllSubmorphsWithin", "keep all submorphs\nwithin and visible" menu.addMenuItem "inspect", true, @, "inspect", "open a window on\nall properties" menu.addMenuItem "test menu ➜", false, @, "testMenu", "debugging and testing operations" menu.addLine() menu.addMenuItem "restore display", true, @, "changed", "redraw the\nscreen once" menu.addMenuItem "fit whole page", true, @, "stretchWorldToFillEntirePage", "let the World automatically\nadjust to browser resizings" menu.addMenuItem "color...", true, @, "popUpColorSetter", "choose the World's\nbackground color" menu.addMenuItem "wallpapers ➜", false, @, "wallpapersMenu", "choose a wallpaper for the Desktop" if WorldMorph.preferencesAndSettings.inputMode is PreferencesAndSettings.INPUT_MODE_MOUSE menu.addMenuItem "touch screen settings", true, WorldMorph.preferencesAndSettings, "toggleInputMode", "bigger menu fonts\nand sliders" else menu.addMenuItem "standard settings", true, WorldMorph.preferencesAndSettings, "toggleInputMode", "smaller menu fonts\nand sliders" menu.addLine() # this part is excluded from the fizzygum homepage build <<« if Automator? menu.addMenuItem "system tests ➜", false, @, "popUpSystemTestsMenu", "" if @isDevMode menu.addMenuItem "switch to user mode", true, @, "toggleDevMode", "disable developers'\ncontext menus" else menu.addMenuItem "switch to dev mode", true, @, "toggleDevMode" menu.addMenuItem "new folder", true, @, "makeFolder" menu.addMenuItem "about Fizzygum...", true, @, "about" menu wallpapersMenu: (a,targetMorph)-> menu = new MenuMorph @, false, targetMorph, true, true, "Wallpapers" # we add the "untick" prefix to all entries # so we allocate the right amount of space for # the labels, we are going to put the # right ticks soon after menu.addMenuItem untick + @pattern1, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern1 menu.addMenuItem untick + @pattern2, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern2 menu.addMenuItem untick + @pattern3, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern3 menu.addMenuItem untick + @pattern4, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern4 menu.addMenuItem untick + @pattern5, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern5 menu.addMenuItem untick + @pattern6, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern6 menu.addMenuItem untick + @pattern7, true, @, "setPattern", nil, nil, nil, nil, nil, @pattern7 @updatePatternsMenuEntriesTicks menu menu.popUpAtHand() setPattern: (menuItem, ignored2, thePatternName) -> if @patternName == thePatternName return @patternName = thePatternName @changed() if menuItem?.parent? and (menuItem.parent instanceof MenuMorph) @updatePatternsMenuEntriesTicks menuItem.parent # cheap way to keep menu consistency when pinned # note that there is no consistency in case # there are multiple copies of this menu changing # the wallpaper, since there is no real subscription # of a menu to react to wallpaper change coming # from other menus or other means (e.g. API)... updatePatternsMenuEntriesTicks: (menu) -> pattern1Tick = pattern2Tick = pattern3Tick = pattern4Tick = pattern5Tick = pattern6Tick = pattern7Tick = untick switch @patternName when @pattern1 pattern1Tick = tick when @pattern2 pattern2Tick = tick when @pattern3 pattern3Tick = tick when @pattern4 pattern4Tick = tick when @pattern5 pattern5Tick = tick when @pattern6 pattern6Tick = tick when @pattern7 pattern7Tick = tick menu.children[1].label.setText pattern1Tick + @pattern1 menu.children[2].label.setText pattern2Tick + @pattern2 menu.children[3].label.setText pattern3Tick + @pattern3 menu.children[4].label.setText pattern4Tick + @pattern4 menu.children[5].label.setText pattern5Tick + @pattern5 menu.children[6].label.setText pattern6Tick + @pattern6 menu.children[7].label.setText pattern7Tick + @pattern7 # »>> this part is excluded from the fizzygum homepage build popUpSystemTestsMenu: -> menu = new MenuMorph @, false, @, true, true, "system tests" menu.addMenuItem "run system tests", true, @automator.player, "runAllSystemTests", "runs all the system tests" menu.addMenuItem "run system tests force slow", true, @automator.player, "runAllSystemTestsForceSlow", "runs all the system tests" menu.addMenuItem "run system tests force fast skip in-between mouse moves", true, @automator.player, "runAllSystemTestsForceFastSkipInbetweenMouseMoves", "runs all the system tests" menu.addMenuItem "run system tests force fast run in-between mouse moves", true, @automator.player, "runAllSystemTestsForceFastRunInbetweenMouseMoves", "runs all the system tests" menu.addMenuItem "start test recording", true, @automator.recorder, "startTestRecording", "start recording a test" menu.addMenuItem "stop test recording", true, @automator.recorder, "stopTestRecording", "stop recording the test" menu.addMenuItem "(re)play recorded test slow", true, @automator.player, "startTestPlayingSlow", "start playing the test" menu.addMenuItem "(re)play recorded test fast skip in-between mouse moves", true, @automator.player, "startTestPlayingFastSkipInbetweenMouseMoves", "start playing the test" menu.addMenuItem "(re)play recorded test fast run in-between mouse moves", true, @automator.player, "startTestPlayingFastRunInbetweenMouseMoves", "start playing the test" menu.addMenuItem "show test source", true, @automator, "showTestSource", "opens a window with the source of the latest test" menu.addMenuItem "save recorded test", true, @automator.recorder, "saveTest", "save the recorded test" menu.addMenuItem "save failed screenshots", true, @automator.player, "saveFailedScreenshots", "save failed screenshots" menu.popUpAtHand() # this part is excluded from the fizzygum homepage build <<« create: (aWdgt) -> aWdgt.pickUp() # »>> this part is excluded from the fizzygum homepage build createNewStackElementsSizeAdjustingMorph: -> @create new StackElementsSizeAdjustingMorph createNewLayoutElementAdderOrDropletMorph: -> @create new LayoutElementAdderOrDropletMorph createNewRectangleMorph: -> @create new RectangleMorph createNewBoxMorph: -> @create new BoxMorph createNewCircleBoxMorph: -> @create new CircleBoxMorph createNewSliderMorph: -> @create new SliderMorph createNewPanelWdgt: -> newWdgt = new PanelWdgt newWdgt.rawSetExtent new Point 350, 250 @create newWdgt createNewScrollPanelWdgt: -> newWdgt = new ScrollPanelWdgt newWdgt.adjustContentsBounds() newWdgt.adjustScrollBars() newWdgt.rawSetExtent new Point 350, 250 @create newWdgt createNewCanvas: -> newWdgt = new CanvasMorph newWdgt.rawSetExtent new Point 350, 250 @create newWdgt createNewHandle: -> @create new HandleMorph createNewString: -> newWdgt = new StringMorph "Hello, World!" newWdgt.isEditable = true @create newWdgt createNewText: -> newWdgt = new TextMorph("Ich weiß nicht, was soll es bedeuten, dass ich so " + "traurig bin, ein Märchen aus uralten Zeiten, das " + "kommt mir nicht aus dem Sinn. Die Luft ist kühl " + "und es dunkelt, und ruhig fließt der Rhein; der " + "Gipfel des Berges funkelt im Abendsonnenschein. " + "Die schönste Jungfrau sitzet dort oben wunderbar, " + "ihr gold'nes Geschmeide blitzet, sie kämmt ihr " + "goldenes Haar, sie kämmt es mit goldenem Kamme, " + "und singt ein Lied dabei; das hat eine wundersame, " + "gewalt'ge Melodei. Den Schiffer im kleinen " + "Schiffe, ergreift es mit wildem Weh; er schaut " + "nicht die Felsenriffe, er schaut nur hinauf in " + "die Höh'. Ich glaube, die Wellen verschlingen " + "am Ende Schiffer und Kahn, und das hat mit ihrem " + "Singen, die LPI:NAME:<NAME>END_PIley getan.") newWdgt.isEditable = true newWdgt.maxTextWidth = 300 @create newWdgt createNewSpeechBubbleWdgt: -> newWdgt = new SpeechBubbleWdgt @create newWdgt createNewToolTipWdgt: -> newWdgt = new ToolTipWdgt @create newWdgt createNewGrayPaletteMorph: -> @create new GrayPaletteMorph createNewColorPaletteMorph: -> @create new ColorPaletteMorph createNewGrayPaletteMorphInWindow: -> gP = new GrayPaletteMorph wm = new WindowWdgt nil, nil, gP @add wm wm.rawSetExtent new Point 130, 70 wm.fullRawMoveTo @hand.position().subtract new Point 50, 100 createNewColorPaletteMorphInWindow: -> cP = new ColorPaletteMorph wm = new WindowWdgt nil, nil, cP @add wm wm.rawSetExtent new Point 130, 100 wm.fullRawMoveTo @hand.position().subtract new Point 50, 100 createNewColorPickerMorph: -> @create new ColorPickerMorph createNewSensorDemo: -> newWdgt = new MouseSensorMorph newWdgt.setColor Color.create 230, 200, 100 newWdgt.cornerRadius = 35 newWdgt.alpha = 0.2 newWdgt.rawSetExtent new Point 100, 100 @create newWdgt createNewAnimationDemo: -> foo = new BouncerMorph foo.fullRawMoveTo new Point 50, 20 foo.rawSetExtent new Point 300, 200 foo.alpha = 0.9 foo.speed = 3 bar = new BouncerMorph bar.setColor Color.create 50, 50, 50 bar.fullRawMoveTo new Point 80, 80 bar.rawSetExtent new Point 80, 250 bar.type = "horizontal" bar.direction = "right" bar.alpha = 0.9 bar.speed = 5 baz = new BouncerMorph baz.setColor Color.create 20, 20, 20 baz.fullRawMoveTo new Point 90, 140 baz.rawSetExtent new Point 40, 30 baz.type = "horizontal" baz.direction = "right" baz.speed = 3 garply = new BouncerMorph garply.setColor Color.create 200, 20, 20 garply.fullRawMoveTo new Point 90, 140 garply.rawSetExtent new Point 20, 20 garply.type = "vertical" garply.direction = "up" garply.speed = 8 fred = new BouncerMorph fred.setColor Color.create 20, 200, 20 fred.fullRawMoveTo new Point 120, 140 fred.rawSetExtent new Point 20, 20 fred.type = "vertical" fred.direction = "down" fred.speed = 4 bar.add garply bar.add baz foo.add fred foo.add bar @create foo createNewPenMorph: -> @create new PenMorph underTheCarpet: -> newWdgt = new BasementWdgt @create newWdgt popUpDemoMenu: (morphOpeningThePopUp,b,c,d) -> if @isIndexPage menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "parts bin" menu.addMenuItem "rectangle", true, @, "createNewRectangleMorph" menu.addMenuItem "box", true, @, "createNewBoxMorph" menu.addMenuItem "circle box", true, @, "createNewCircleBoxMorph" menu.addMenuItem "slider", true, @, "createNewSliderMorph" menu.addMenuItem "speech bubble", true, @, "createNewSpeechBubbleWdgt" menu.addLine() menu.addMenuItem "gray scale palette", true, @, "createNewGrayPaletteMorphInWindow" menu.addMenuItem "color palette", true, @, "createNewColorPaletteMorphInWindow" menu.addLine() menu.addMenuItem "analog clock", true, @, "analogClock" else menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "make a morph" menu.addMenuItem "rectangle", true, @, "createNewRectangleMorph" menu.addMenuItem "box", true, @, "createNewBoxMorph" menu.addMenuItem "circle box", true, @, "createNewCircleBoxMorph" menu.addLine() menu.addMenuItem "slider", true, @, "createNewSliderMorph" menu.addMenuItem "panel", true, @, "createNewPanelWdgt" menu.addMenuItem "scrollable panel", true, @, "createNewScrollPanelWdgt" menu.addMenuItem "canvas", true, @, "createNewCanvas" menu.addMenuItem "handle", true, @, "createNewHandle" menu.addLine() menu.addMenuItem "string", true, @, "createNewString" menu.addMenuItem "text", true, @, "createNewText" menu.addMenuItem "tool tip", true, @, "createNewToolTipWdgt" menu.addMenuItem "speech bubble", true, @, "createNewSpeechBubbleWdgt" menu.addLine() menu.addMenuItem "gray scale palette", true, @, "createNewGrayPaletteMorph" menu.addMenuItem "color palette", true, @, "createNewColorPaletteMorph" menu.addMenuItem "color picker", true, @, "createNewColorPickerMorph" menu.addLine() menu.addMenuItem "sensor demo", true, @, "createNewSensorDemo" menu.addMenuItem "animation demo", true, @, "createNewAnimationDemo" menu.addMenuItem "pen", true, @, "createNewPenMorph" menu.addLine() menu.addMenuItem "layout tests ➜", false, @, "layoutTestsMenu", "sample morphs" menu.addLine() menu.addMenuItem "under the carpet", true, @, "underTheCarpet" menu.popUpAtHand() layoutTestsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "Layout tests" menu.addMenuItem "adjuster morph", true, @, "createNewStackElementsSizeAdjustingMorph" menu.addMenuItem "adder/droplet", true, @, "createNewLayoutElementAdderOrDropletMorph" menu.addMenuItem "test screen 1", true, Widget, "setupTestScreen1" menu.popUpAtHand() toggleDevMode: -> @isDevMode = not @isDevMode # this part is excluded from the fizzygum homepage build <<« edit: (aStringMorphOrTextMorph) -> # first off, if the Widget is not editable # then there is nothing to do # return nil unless aStringMorphOrTextMorph.isEditable # there is only one caret in the World, so destroy # the previous one if there was one. if @caret # empty the previously ongoing selection # if there was one. previouslyEditedText = @lastEditedText @lastEditedText = @caret.target if @lastEditedText != previouslyEditedText @lastEditedText.clearSelection() @caret = @caret.fullDestroy() # create the new Caret @caret = new CaretMorph aStringMorphOrTextMorph aStringMorphOrTextMorph.parent.add @caret # this is the only place where the @keyboardEventsReceiver is set @keyboardEventsReceiver = @caret if WorldMorph.preferencesAndSettings.isTouchDevice and WorldMorph.preferencesAndSettings.useVirtualKeyboard @initVirtualKeyboard() # For touch devices, giving focus on the textbox causes # the keyboard to slide up, and since the page viewport # shrinks, the page is scrolled to where the texbox is. # So, it is important to position the textbox around # where the caret is, so that the changed text is going to # be visible rather than out of the viewport. pos = @getCanvasPosition() @inputDOMElementForVirtualKeyboard.style.top = @caret.top() + pos.y + "px" @inputDOMElementForVirtualKeyboard.style.left = @caret.left() + pos.x + "px" @inputDOMElementForVirtualKeyboard.focus() # Widgetic.js provides the "slide" method but I must have lost it # in the way, so commenting this out for the time being # #if WorldMorph.preferencesAndSettings.useSliderForInput # if !aStringMorphOrTextMorph.parentThatIsA MenuMorph # @slide aStringMorphOrTextMorph # Editing can stop because of three reasons: # cancel (user hits ESC) # accept (on stringmorph, user hits enter) # user clicks/floatDrags another morph stopEditing: -> if @caret @lastEditedText = @caret.target @lastEditedText.clearSelection() @caret = @caret.fullDestroy() # the only place where the @keyboardEventsReceiver is unset # (and the hidden input is removed) @keyboardEventsReceiver = nil if @inputDOMElementForVirtualKeyboard @inputDOMElementForVirtualKeyboard.blur() document.body.removeChild @inputDOMElementForVirtualKeyboard @inputDOMElementForVirtualKeyboard = nil @worldCanvas.focus() anyReferenceToWdgt: (whichWdgt) -> # go through all the references and check whether they reference # the wanted widget. Note that the reference could be unreachable # in the basement, or even in the trash for eachReferencingWdgt from @widgetsReferencingOtherWidgets if eachReferencingWdgt.target == whichWdgt return true return false
[ { "context": "= 'WrappedUserInput'\n\nlabelKey = (user) ->\n key = \"@#{user.username}\"\n if user.profile?.fullname\n #k", "end": 1376, "score": 0.963540256023407, "start": 1372, "tag": "KEY", "value": "\"@#{" }, { "context": "dUserInput'\n\nlabelKey = (user) ->\n key = \"@#{user.username}\"\n if user.profile?.fullname\n #key += \" #{user.", "end": 1391, "score": 0.7908930778503418, "start": 1381, "tag": "KEY", "value": "username}\"" }, { "context": "ername}\"\n if user.profile?.fullname\n #key += \" #{user.profile.fullname}\"\n key = \"#{user.profile.", "end": 1436, "score": 0.5641003251075745, "start": 1434, "tag": "KEY", "value": "#{" }, { "context": "er.profile?.fullname\n #key += \" #{user.profile.fullname}\"\n key = \"#{user.profile.fullname} #{key}\"\n key", "end": 1459, "score": 0.7112201452255249, "start": 1449, "tag": "KEY", "value": "fullname}\"" }, { "context": "user.profile.fullname}\"\n key = \"#{user.profile.fullname} #{key}\"\n key\n", "end": 1498, "score": 0.8490195274353027, "start": 1486, "tag": "KEY", "value": "fullname} #{" }, { "context": "llname}\"\n key = \"#{user.profile.fullname} #{key}\"\n key\n", "end": 1501, "score": 0.8166791200637817, "start": 1501, "tag": "KEY", "value": "" } ]
client/UserInput.coffee
mehtank/coauthor
204
import React, {Suspense, useMemo, useRef} from 'react' import {useTracker} from 'meteor/react-meteor-data' Typeahead = React.lazy -> import('react-bootstrap-typeahead/es/components/Typeahead') import {ErrorBoundary} from './ErrorBoundary' import 'react-bootstrap-typeahead/css/Typeahead.css' userInputCount = 0 export UserInput = React.memo (props) -> <ErrorBoundary> <WrappedUserInput {...props}/> </ErrorBoundary> UserInput.displayName = 'UserInput' export WrappedUserInput = React.memo ({group, omit, placeholder, onSelect}) -> count = useMemo -> userInputCount++ , [] users = useTracker -> Meteor.users.find username: $in: groupMembers group .fetch() , [] sorted = useMemo -> if omit? omitted = (user for user in users when not omit user) else omitted = users _.sortBy omitted, userSortKey , [users, omit] ref = useRef() onChange = (selected) -> if selected.length onSelect selected[0] ref.current.clear() <Suspense fallback={ <input type="text" className="form-control disabled" placeholder={placeholder}/> }> <Typeahead ref={ref} placeholder={placeholder} id="userInput#{count}" options={sorted} labelKey={labelKey} align="left" flip onChange={onChange}/> </Suspense> WrappedUserInput.displayName = 'WrappedUserInput' labelKey = (user) -> key = "@#{user.username}" if user.profile?.fullname #key += " #{user.profile.fullname}" key = "#{user.profile.fullname} #{key}" key
156027
import React, {Suspense, useMemo, useRef} from 'react' import {useTracker} from 'meteor/react-meteor-data' Typeahead = React.lazy -> import('react-bootstrap-typeahead/es/components/Typeahead') import {ErrorBoundary} from './ErrorBoundary' import 'react-bootstrap-typeahead/css/Typeahead.css' userInputCount = 0 export UserInput = React.memo (props) -> <ErrorBoundary> <WrappedUserInput {...props}/> </ErrorBoundary> UserInput.displayName = 'UserInput' export WrappedUserInput = React.memo ({group, omit, placeholder, onSelect}) -> count = useMemo -> userInputCount++ , [] users = useTracker -> Meteor.users.find username: $in: groupMembers group .fetch() , [] sorted = useMemo -> if omit? omitted = (user for user in users when not omit user) else omitted = users _.sortBy omitted, userSortKey , [users, omit] ref = useRef() onChange = (selected) -> if selected.length onSelect selected[0] ref.current.clear() <Suspense fallback={ <input type="text" className="form-control disabled" placeholder={placeholder}/> }> <Typeahead ref={ref} placeholder={placeholder} id="userInput#{count}" options={sorted} labelKey={labelKey} align="left" flip onChange={onChange}/> </Suspense> WrappedUserInput.displayName = 'WrappedUserInput' labelKey = (user) -> key = <KEY>user.<KEY> if user.profile?.fullname #key += " <KEY>user.profile.<KEY> key = "#{user.profile.<KEY>key<KEY>}" key
true
import React, {Suspense, useMemo, useRef} from 'react' import {useTracker} from 'meteor/react-meteor-data' Typeahead = React.lazy -> import('react-bootstrap-typeahead/es/components/Typeahead') import {ErrorBoundary} from './ErrorBoundary' import 'react-bootstrap-typeahead/css/Typeahead.css' userInputCount = 0 export UserInput = React.memo (props) -> <ErrorBoundary> <WrappedUserInput {...props}/> </ErrorBoundary> UserInput.displayName = 'UserInput' export WrappedUserInput = React.memo ({group, omit, placeholder, onSelect}) -> count = useMemo -> userInputCount++ , [] users = useTracker -> Meteor.users.find username: $in: groupMembers group .fetch() , [] sorted = useMemo -> if omit? omitted = (user for user in users when not omit user) else omitted = users _.sortBy omitted, userSortKey , [users, omit] ref = useRef() onChange = (selected) -> if selected.length onSelect selected[0] ref.current.clear() <Suspense fallback={ <input type="text" className="form-control disabled" placeholder={placeholder}/> }> <Typeahead ref={ref} placeholder={placeholder} id="userInput#{count}" options={sorted} labelKey={labelKey} align="left" flip onChange={onChange}/> </Suspense> WrappedUserInput.displayName = 'WrappedUserInput' labelKey = (user) -> key = PI:KEY:<KEY>END_PIuser.PI:KEY:<KEY>END_PI if user.profile?.fullname #key += " PI:KEY:<KEY>END_PIuser.profile.PI:KEY:<KEY>END_PI key = "#{user.profile.PI:KEY:<KEY>END_PIkeyPI:KEY:<KEY>END_PI}" key
[ { "context": "setCardSetId(CardSet.Coreshatter)\n\t\t\tcard.name = \"Hatefurnace\"\n\t\t\tcard.setDescription(\"Trial: Cast 7 spells tha", "end": 3668, "score": 0.9937617182731628, "start": 3657, "tag": "NAME", "value": "Hatefurnace" }, { "context": "ard.factionId = Factions.Faction5\n\t\t\tcard.name = \"Angered Okkadok\"\n\t\t\tcard.setDescription(\"Intensify: This minion g", "end": 5701, "score": 0.9998001456260681, "start": 5686, "tag": "NAME", "value": "Angered Okkadok" }, { "context": "d.id = Cards.Spell.IncreasingHeal\n\t\t\tcard.name = \"Invigoration\"\n\t\t\tcard.setDescription(\"Intensify: Restore 3 Hea", "end": 6969, "score": 0.9389826059341431, "start": 6957, "tag": "NAME", "value": "Invigoration" }, { "context": "ard.factionId = Factions.Faction5\n\t\t\tcard.name = \"Mortar-maw\"\n\t\t\tcard.setDescription(\"Ranged\\nWhenever this mi", "end": 7768, "score": 0.9998342990875244, "start": 7758, "tag": "NAME", "value": "Mortar-maw" }, { "context": "ard.factionId = Factions.Faction5\n\t\t\tcard.name = \"Beastclad Hunter\"\n\t\t\tcard.setDescription(\"Takes no damage from min", "end": 9040, "score": 0.9993003010749817, "start": 9024, "tag": "NAME", "value": "Beastclad Hunter" }, { "context": "ard.factionId = Factions.Faction5\n\t\t\tcard.name = \"Oropsisaur\"\n\t\t\tcard.setDescription(\"Grow: +1/+1.\\nWhene", "end": 10308, "score": 0.6658300161361694, "start": 10303, "tag": "NAME", "value": "Orops" }, { "context": "setCardSetId(CardSet.Coreshatter)\n\t\t\tcard.name = \"Krater\"\n\t\t\tcard.setDescription(\"Opening Gambit: Deal 1 d", "end": 11600, "score": 0.9990516901016235, "start": 11594, "tag": "NAME", "value": "Krater" }, { "context": "\n\t\t\tcard.id = Cards.Spell.BigTime\n\t\t\tcard.name = \"Gargantuan Growth\"\n\t\t\tcard.setDescription(\"Give a m", "end": 13564, "score": 0.6128020286560059, "start": 13563, "tag": "NAME", "value": "G" }, { "context": "card.id = Cards.Artifact.EggArmor\n\t\t\tcard.name = \"Zoetic Charm\"\n\t\t\tcard.setDescription(\"Your General has +1 Atta", "end": 14343, "score": 0.5657773017883301, "start": 14331, "tag": "NAME", "value": "Zoetic Charm" }, { "context": "card.id = Cards.Spell.Reggplicate\n\t\t\tcard.name = \"Mitotic Induction\"\n\t\t\tcard.setDescription(\"Summon an ", "end": 15289, "score": 0.5299355983734131, "start": 15286, "tag": "NAME", "value": "Mit" }, { "context": "ard.setIsHiddenInCollection(true)\n\t\t\tcard.name = \"Katastrophosaurus\"\n\t\t\tcard.atk = 6\n\t\t\tcard.maxHP = ", "end": 16042, "score": 0.7917589545249939, "start": 16041, "tag": "NAME", "value": "K" }, { "context": "ard.id = Cards.Spell.YellRealLoud\n\t\t\tcard.name = \"Bellow\"\n\t\t\tcard.setDescription(\"Give a friendly minion +", "end": 18082, "score": 0.9989533424377441, "start": 18076, "tag": "NAME", "value": "Bellow" }, { "context": "setCardSetId(CardSet.Coreshatter)\n\t\t\tcard.name = \"Haruspex\"\n\t\t\tcard.setDescription(\"Whenever this minion tak", "end": 18970, "score": 0.9989340305328369, "start": 18962, "tag": "NAME", "value": "Haruspex" } ]
app/sdk/cards/factory/coreshatter/faction5.coffee
willroberts/duelyst
5
# do not add this file to a package # it is specifically parsed by the package generation script _ = require 'underscore' moment = require 'moment' Logger = require 'app/common/logger' CONFIG = require('app/common/config') RSX = require('app/data/resources') Card = require 'app/sdk/cards/card' Cards = require 'app/sdk/cards/cardsLookupComplete' CardType = require 'app/sdk/cards/cardType' Factions = require 'app/sdk/cards/factionsLookup' FactionFactory = require 'app/sdk/cards/factionFactory' Races = require 'app/sdk/cards/racesLookup' Rarity = require 'app/sdk/cards/rarityLookup' Unit = require 'app/sdk/entities/unit' CardSet = require 'app/sdk/cards/cardSetLookup' Artifact = require 'app/sdk/artifacts/artifact' Modifier = require 'app/sdk/modifiers/modifier' ModifierIntensifyBuffSelf = require 'app/sdk/modifiers/modifierIntensifyBuffSelf' ModifierRanged = require 'app/sdk/modifiers/modifierRanged' ModifierMyAttackWatchAreaAttack = require 'app/sdk/modifiers/modifierMyAttackWatchAreaAttack' ModifierImmuneToDamageByWeakerEnemies = require 'app/sdk/modifiers/modifierImmuneToDamageByWeakerEnemies' ModifierMyOtherMinionsDamagedWatchDamagedMinionGrows = require 'app/sdk/modifiers/modifierMyOtherMinionsDamagedWatchDamagedMinionGrows' ModifierGrow = require 'app/sdk/modifiers/modifierGrow' ModifierOpeningGambitDamageEverything = require 'app/sdk/modifiers/modifierOpeningGambitDamageEverything' ModifierStartsInHand = require 'app/sdk/modifiers/modifierStartsInHand' ModifierForcefield = require 'app/sdk/modifiers/modifierForcefield' ModifierFirstBlood = require 'app/sdk/modifiers/modifierFirstBlood' ModifierTakeDamageWatchOpponentDrawCard = require 'app/sdk/modifiers/modifierTakeDamageWatchOpponentDrawCard' ModifierOnSummonFromHandApplyEmblems = require 'app/sdk/modifiers/modifierOnSummonFromHandApplyEmblems' ModifierStun = require 'app/sdk/modifiers/modifierStun' ModifierToken = require 'app/sdk/modifiers/modifierToken' ModifierTokenCreator = require 'app/sdk/modifiers/modifierTokenCreator' ModifierFrenzy = require 'app/sdk/modifiers/modifierFrenzy' ModifierFateMagmarBuffQuest = require 'app/sdk/modifiers/modifierFateMagmarBuffQuest' ModifierCannotBeReplaced = require 'app/sdk/modifiers/modifierCannotBeReplaced' ModifierIntensify = require 'app/sdk/modifiers/modifierIntensify' ModifierCounterIntensify = require 'app/sdk/modifiers/modifierCounterIntensify' ModifierCannotBeRemovedFromHand = require 'app/sdk/modifiers/modifierCannotBeRemovedFromHand' PlayerModifierEmblemSummonWatchFromHandMagmarBuffQuest = require 'app/sdk/playerModifiers/playerModifierEmblemSummonWatchFromHandMagmarBuffQuest' SpellFilterType = require 'app/sdk/spells/spellFilterType' SpellDamageNotKillMinion = require 'app/sdk/spells/spellDamageNotKillMinion' SpellApplyModifiers = require 'app/sdk/spells/spellApplyModifiers' SpellReggplicate = require 'app/sdk/spells/spellReggplicate' SpellMarchOfTheBrontos = require 'app/sdk/spells/spellMarchOfTheBrontos' SpellYellRealLoud = require 'app/sdk/spells/spellYellRealLoud' SpellIntensifyHealMyGeneral = require 'app/sdk/spells/spellIntensifyHealMyGeneral' i18next = require 'i18next' if i18next.t() is undefined i18next.t = (text) -> return text class CardFactory_CoreshatterSet_Faction5 ###* * Returns a card that matches the identifier. * @param {Number|String} identifier * @param {GameSession} gameSession * @returns {Card} ### @cardForIdentifier: (identifier,gameSession) -> card = null if (identifier == Cards.Faction5.Dinomancer) card = new Unit(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.name = "Hatefurnace" card.setDescription("Trial: Cast 7 spells that cause a minion to gain +Attack.\nDestiny: Minions summoned from your action bar gain Rush and Frenzy.") card.atk = 5 card.maxHP = 4 card.manaCost = 4 card.rarityId = Rarity.Mythron emblemModifier = PlayerModifierEmblemSummonWatchFromHandMagmarBuffQuest.createContextObject([ModifierFirstBlood.createContextObject(), ModifierFrenzy.createContextObject()]) emblemModifier.appliedName = "Spark of Hatred" emblemModifier.appliedDescription = "Minions summoned from your action bar have Rush and Frenzy." card.setInherentModifiersContextObjects([ ModifierStartsInHand.createContextObject(), ModifierCannotBeReplaced.createContextObject(), ModifierOnSummonFromHandApplyEmblems.createContextObject([emblemModifier], true, false), ModifierFateMagmarBuffQuest.createContextObject(7), ModifierCannotBeRemovedFromHand.createContextObject() ]) card.addKeywordClassToInclude(ModifierFirstBlood) card.addKeywordClassToInclude(ModifierFrenzy) card.setFXResource(["FX.Cards.Neutral.Ironclad"]) card.setBoundingBoxWidth(130) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f1ironcliffeguardian_attack_swing.audio receiveDamage : RSX.sfx_f1ironcliffeguardian_hit.audio attackDamage : RSX.sfx_f1ironcliffeguardian_attack_impact.audio death : RSX.sfx_f1ironcliffeguardian_death.audio ) card.setBaseAnimResource( breathing : RSX.f5DinomancerBreathing.name idle : RSX.f5DinomancerIdle.name walk : RSX.f5DinomancerRun.name attack : RSX.f5DinomancerAttack.name attackReleaseDelay: 0.0 attackDelay: 1.7 damage : RSX.f5DinomancerHit.name death : RSX.f5DinomancerDeath.name ) if (identifier == Cards.Faction5.IncreasingDino) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction5 card.name = "Angered Okkadok" card.setDescription("Intensify: This minion gains +1/+1.") card.atk = 1 card.maxHP = 2 card.manaCost = 2 card.rarityId = Rarity.Common card.setInherentModifiersContextObjects([ ModifierIntensifyBuffSelf.createContextObject(1,1,"Even More Angered") ModifierCounterIntensify.createContextObject() ]) card.setFXResource(["FX.Cards.Neutral.VineEntangler"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_komodocharger_attack_swing.audio receiveDamage : RSX.sfx_f6_ancientgrove_hit.audio attackDamage : RSX.sfx_f6_ancientgrove_attack_impact.audio death : RSX.sfx_f6_ancientgrove_death.audio ) card.setBaseAnimResource( breathing : RSX.f5PteryxBreathing.name idle : RSX.f5PteryxIdle.name walk : RSX.f5PteryxRun.name attack : RSX.f5PteryxAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.f5PteryxHit.name death : RSX.f5PteryxDeath.name ) if (identifier == Cards.Spell.IncreasingHeal) card = new SpellIntensifyHealMyGeneral(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.IncreasingHeal card.name = "Invigoration" card.setDescription("Intensify: Restore 3 Health to your General.") card.manaCost = 2 card.healAmount = 3 card.rarityId = Rarity.Common card.spellFilterType = SpellFilterType.None card.addKeywordClassToInclude(ModifierIntensify) card.setInherentModifiersContextObjects([ModifierCounterIntensify.createContextObject()]) card.setFXResource(["FX.Cards.Spell.Invigoration"]) card.setBaseSoundResource( apply : RSX.sfx_spell_lionheartblessing.audio ) card.setBaseAnimResource( idle : RSX.iconIncreasingHealthIdle.name active : RSX.iconIncreasingHealthActive.name ) if (identifier == Cards.Faction5.Firebreather) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction5 card.name = "Mortar-maw" card.setDescription("Ranged\nWhenever this minion attacks, it also damages enemies around its target.") card.atk = 4 card.maxHP = 4 card.manaCost = 5 card.rarityId = Rarity.Epic card.setInherentModifiersContextObjects([ ModifierMyAttackWatchAreaAttack.createContextObject(), ModifierRanged.createContextObject() ]) card.setFXResource(["FX.Cards.Faction5.Firebreather"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_1.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_firespitter_attack_swing.audio receiveDamage : RSX.sfx_neutral_firespitter_hit.audio attackDamage : RSX.sfx_neutral_firespitter_attack_impact.audio death : RSX.sfx_neutral_firespitter_death.audio ) card.setBaseAnimResource( breathing : RSX.f5FireBreatherBreathing.name idle : RSX.f5FireBreatherIdle.name walk : RSX.f5FireBreatherRun.name attack : RSX.f5FireBreatherAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.f5FireBreatherHit.name death : RSX.f5FireBreatherDeath.name ) if (identifier == Cards.Faction5.ToughDino) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction5 card.name = "Beastclad Hunter" card.setDescription("Takes no damage from minions with less Attack.") card.atk = 3 card.maxHP = 6 card.manaCost = 4 card.rarityId = Rarity.Rare card.setInherentModifiersContextObjects([ModifierImmuneToDamageByWeakerEnemies.createContextObject(false)]) card.setFXResource(["FX.Cards.Neutral.RazorcragGolem"]) card.setBoundingBoxWidth(80) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_3.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_stormmetalgolem_attack_swing.audio receiveDamage : RSX.sfx_neutral_stormmetalgolem_hit.audio attackDamage : RSX.sfx_neutral_stormmetalgolem_attack_impact.audio death : RSX.sfx_neutral_stormmetalgolem_death.audio ) card.setBaseAnimResource( breathing : RSX.f5OrphanAspectBreathing.name idle : RSX.f5OrphanAspectIdle.name walk : RSX.f5OrphanAspectRun.name attack : RSX.f5OrphanAspectAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.f5OrphanAspectHit.name death : RSX.f5OrphanAspectDeath.name ) if (identifier == Cards.Faction5.Armadops) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction5 card.name = "Oropsisaur" card.setDescription("Grow: +1/+1.\nWhenever another friendly minion with Grow survives damage, that minion grows.") card.atk = 2 card.maxHP = 5 card.manaCost = 3 card.rarityId = Rarity.Legendary card.setInherentModifiersContextObjects([ ModifierMyOtherMinionsDamagedWatchDamagedMinionGrows.createContextObject(), ModifierGrow.createContextObject(1) ]) card.setFXResource(["FX.Cards.Neutral.ThornNeedler"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_3.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_bluetipscorpion_attack_swing.audio receiveDamage : RSX.sfx_neutral_bluetipscorpion_hit.audio attackDamage : RSX.sfx_neutral_bluetipscorpion_attack_impact.audio death : RSX.sfx_neutral_bluetipscorpion_death.audio ) card.setBaseAnimResource( breathing : RSX.f5AnkylosBreathing.name idle : RSX.f5AnkylosIdle.name walk : RSX.f5AnkylosRun.name attack : RSX.f5AnkylosAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.f5AnkylosHit.name death : RSX.f5AnkylosDeath.name ) if (identifier == Cards.Faction5.BurstLizard) card = new Unit(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.name = "Krater" card.setDescription("Opening Gambit: Deal 1 damage to everything (including itself).") card.atk = 2 card.maxHP = 4 card.manaCost = 3 card.rarityId = Rarity.Common card.setInherentModifiersContextObjects([ModifierOpeningGambitDamageEverything.createContextObject(1, true)]) card.setFXResource(["FX.Cards.Neutral.BlisteringSkorn"]) card.setBaseSoundResource( apply : RSX.sfx_spell_blindscorch.audio walk : RSX.sfx_neutral_firestarter_impact.audio attack : RSX.sfx_neutral_firestarter_attack_swing.audio receiveDamage : RSX.sfx_neutral_firestarter_hit.audio attackDamage : RSX.sfx_neutral_firestarter_impact.audio death : RSX.sfx_neutral_firestarter_death.audio ) card.setBaseAnimResource( breathing : RSX.f5BurstLizardBreathing.name idle : RSX.f5BurstLizardIdle.name walk : RSX.f5BurstLizardRun.name attack : RSX.f5BurstLizardAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.f5BurstLizardHit.name death : RSX.f5BurstLizardDeath.name ) if (identifier == Cards.Spell.Spaghettify) card = new SpellDamageNotKillMinion(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.Spaghettify card.name = "Deep Impact" card.setDescription("Deal damage to a minion to reduce its Health to 1.") card.manaCost = 2 card.rarityId = Rarity.Rare card.spellFilterType = SpellFilterType.NeutralDirect card.canTargetGeneral = false card.setFXResource(["FX.Cards.Spell.DeepImpact"]) card.setBaseAnimResource( idle : RSX.iconMeteorIdle.name active : RSX.iconMeteorActive.name ) card.setBaseSoundResource( apply : RSX.sfx_spell_disintegrate.audio ) if (identifier == Cards.Spell.BigTime) card = new SpellApplyModifiers(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.BigTime card.name = "Gargantuan Growth" card.setDescription("Give a minion, \"Grow: +8/+8.\"") card.manaCost = 4 card.rarityId = Rarity.Rare card.spellFilterType = SpellFilterType.NeutralDirect card.canTargetGeneral = false card.setTargetModifiersContextObjects([ModifierGrow.createContextObject(8)]) card.setFXResource(["FX.Cards.Spell.GargantuanGrowth"]) card.setBaseSoundResource( apply : RSX.sfx_spell_fractalreplication.audio ) card.setBaseAnimResource( idle : RSX.iconBigTimeIdle.name active : RSX.iconBigTimeActive.name ) if (identifier == Cards.Artifact.EggArmor) card = new Artifact(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction5 card.id = Cards.Artifact.EggArmor card.name = "Zoetic Charm" card.setDescription("Your General has +1 Attack.\nYour Eggs have Forcefield.") card.manaCost = 2 card.rarityId = Rarity.Epic card.durability = 3 eggs = [ Cards.Faction5.Egg ] card.setTargetModifiersContextObjects([ Modifier.createContextObjectWithAttributeBuffs(1,undefined), Modifier.createContextObjectWithAuraForAllAllies([ModifierForcefield.createContextObject()], null, eggs) ]) card.addKeywordClassToInclude(ModifierForcefield) card.setFXResource(["FX.Cards.Artifact.OblivionSickle"]) card.setBaseAnimResource( idle: RSX.iconEggArmorIdle.name active: RSX.iconEggArmorActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.Spell.Reggplicate) card = new SpellReggplicate(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.Reggplicate card.name = "Mitotic Induction" card.setDescription("Summon an Egg of the minion most recently summoned from your action bar.") card.manaCost = 2 card.rarityId = Rarity.Epic card.spellFilterType = SpellFilterType.SpawnSource card.addKeywordClassToInclude(ModifierTokenCreator) card.setFXResource(["FX.Cards.Spell.MitoticInduction"]) card.setBaseSoundResource( apply : RSX.sfx_spell_disintegrate.audio ) card.setBaseAnimResource( idle : RSX.iconReggsplicateIdle.name active : RSX.iconReggsplicateActive.name ) if (identifier == Cards.Faction5.Megabrontodon) card = new Unit(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.setIsHiddenInCollection(true) card.name = "Katastrophosaurus" card.atk = 6 card.maxHP = 26 card.manaCost = 5 card.rarityId = Rarity.TokenUnit card.addKeywordClassToInclude(ModifierToken) card.setFXResource(["FX.Cards.Neutral.Khymera"]) card.setBoundingBoxWidth(145) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_rook_hit.audio attack : RSX.sfx_neutral_khymera_attack_swing.audio receiveDamage : RSX.sfx_neutral_khymera_hit.audio attackDamage : RSX.sfx_neutral_khymera_impact.audio death : RSX.sfx_neutral_khymera_death.audio ) card.setBaseAnimResource( breathing : RSX.f5MegaBrontodonBreathing.name idle : RSX.f5MegaBrontodonIdle.name walk : RSX.f5MegaBrontodonRun.name attack : RSX.f5MegaBrontodonAttack.name attackReleaseDelay: 0.0 attackDelay: 0.7 damage : RSX.f5MegaBrontodonHit.name death : RSX.f5MegaBrontodonDeath.name ) if (identifier == Cards.Spell.MarchOfTheBrontos) card = new SpellMarchOfTheBrontos(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.MarchOfTheBrontos card.name = "Extinction Event" card.setDescription("Each of your Eggs hatches into a Katastrophosaurus.") card.manaCost = 8 card.rarityId = Rarity.Legendary card.spellFilterType = SpellFilterType.NeutralIndirect card.radius = CONFIG.WHOLE_BOARD_RADIUS card.addKeywordClassToInclude(ModifierTokenCreator) card.setFXResource(["FX.Cards.Spell.ExtinctionEvent"]) card.setBaseSoundResource( apply : RSX.sfx_spell_darktransformation.audio ) card.setBaseAnimResource( idle : RSX.iconMarchBrontodonIdle.name active : RSX.iconMarchBrontodonActive.name ) if (identifier == Cards.Spell.YellRealLoud) card = new SpellYellRealLoud(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.YellRealLoud card.name = "Bellow" card.setDescription("Give a friendly minion +3 Attack.\nStun enemy minions around it.") card.manaCost = 3 card.rarityId = Rarity.Common card.spellFilterType = SpellFilterType.AllyDirect statContextObject = Modifier.createContextObjectWithAttributeBuffs(3,0) statContextObject.appliedName = "Yelled Real Loud" card.setTargetModifiersContextObjects([ statContextObject ]) card.addKeywordClassToInclude(ModifierStun) card.setFXResource(["FX.Cards.Spell.Bellow"]) card.setBaseSoundResource( apply : RSX.sfx_neutral_windstopper_attack_impact.audio ) card.setBaseAnimResource( idle : RSX.iconYellLoudIdle.name active : RSX.iconYellLoudActive.name ) if (identifier == Cards.Faction5.BrundlBeast) card = new Unit(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.name = "Haruspex" card.setDescription("Whenever this minion takes damage, your opponent draws a card.") card.atk = 7 card.maxHP = 6 card.manaCost = 4 card.rarityId = Rarity.Legendary card.setInherentModifiersContextObjects([ModifierTakeDamageWatchOpponentDrawCard.createContextObject()]) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction2.CelestialPhantom"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_f2_celestialphantom_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f2_celestialphantom_death.audio ) card.setBaseAnimResource( breathing : RSX.f5BrundlebeastBreathing.name idle : RSX.f5BrundlebeastIdle.name walk : RSX.f5BrundlebeastRun.name attack : RSX.f5BrundlebeastAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.f5BrundlebeastHit.name death : RSX.f5BrundlebeastDeath.name ) return card module.exports = CardFactory_CoreshatterSet_Faction5
75812
# do not add this file to a package # it is specifically parsed by the package generation script _ = require 'underscore' moment = require 'moment' Logger = require 'app/common/logger' CONFIG = require('app/common/config') RSX = require('app/data/resources') Card = require 'app/sdk/cards/card' Cards = require 'app/sdk/cards/cardsLookupComplete' CardType = require 'app/sdk/cards/cardType' Factions = require 'app/sdk/cards/factionsLookup' FactionFactory = require 'app/sdk/cards/factionFactory' Races = require 'app/sdk/cards/racesLookup' Rarity = require 'app/sdk/cards/rarityLookup' Unit = require 'app/sdk/entities/unit' CardSet = require 'app/sdk/cards/cardSetLookup' Artifact = require 'app/sdk/artifacts/artifact' Modifier = require 'app/sdk/modifiers/modifier' ModifierIntensifyBuffSelf = require 'app/sdk/modifiers/modifierIntensifyBuffSelf' ModifierRanged = require 'app/sdk/modifiers/modifierRanged' ModifierMyAttackWatchAreaAttack = require 'app/sdk/modifiers/modifierMyAttackWatchAreaAttack' ModifierImmuneToDamageByWeakerEnemies = require 'app/sdk/modifiers/modifierImmuneToDamageByWeakerEnemies' ModifierMyOtherMinionsDamagedWatchDamagedMinionGrows = require 'app/sdk/modifiers/modifierMyOtherMinionsDamagedWatchDamagedMinionGrows' ModifierGrow = require 'app/sdk/modifiers/modifierGrow' ModifierOpeningGambitDamageEverything = require 'app/sdk/modifiers/modifierOpeningGambitDamageEverything' ModifierStartsInHand = require 'app/sdk/modifiers/modifierStartsInHand' ModifierForcefield = require 'app/sdk/modifiers/modifierForcefield' ModifierFirstBlood = require 'app/sdk/modifiers/modifierFirstBlood' ModifierTakeDamageWatchOpponentDrawCard = require 'app/sdk/modifiers/modifierTakeDamageWatchOpponentDrawCard' ModifierOnSummonFromHandApplyEmblems = require 'app/sdk/modifiers/modifierOnSummonFromHandApplyEmblems' ModifierStun = require 'app/sdk/modifiers/modifierStun' ModifierToken = require 'app/sdk/modifiers/modifierToken' ModifierTokenCreator = require 'app/sdk/modifiers/modifierTokenCreator' ModifierFrenzy = require 'app/sdk/modifiers/modifierFrenzy' ModifierFateMagmarBuffQuest = require 'app/sdk/modifiers/modifierFateMagmarBuffQuest' ModifierCannotBeReplaced = require 'app/sdk/modifiers/modifierCannotBeReplaced' ModifierIntensify = require 'app/sdk/modifiers/modifierIntensify' ModifierCounterIntensify = require 'app/sdk/modifiers/modifierCounterIntensify' ModifierCannotBeRemovedFromHand = require 'app/sdk/modifiers/modifierCannotBeRemovedFromHand' PlayerModifierEmblemSummonWatchFromHandMagmarBuffQuest = require 'app/sdk/playerModifiers/playerModifierEmblemSummonWatchFromHandMagmarBuffQuest' SpellFilterType = require 'app/sdk/spells/spellFilterType' SpellDamageNotKillMinion = require 'app/sdk/spells/spellDamageNotKillMinion' SpellApplyModifiers = require 'app/sdk/spells/spellApplyModifiers' SpellReggplicate = require 'app/sdk/spells/spellReggplicate' SpellMarchOfTheBrontos = require 'app/sdk/spells/spellMarchOfTheBrontos' SpellYellRealLoud = require 'app/sdk/spells/spellYellRealLoud' SpellIntensifyHealMyGeneral = require 'app/sdk/spells/spellIntensifyHealMyGeneral' i18next = require 'i18next' if i18next.t() is undefined i18next.t = (text) -> return text class CardFactory_CoreshatterSet_Faction5 ###* * Returns a card that matches the identifier. * @param {Number|String} identifier * @param {GameSession} gameSession * @returns {Card} ### @cardForIdentifier: (identifier,gameSession) -> card = null if (identifier == Cards.Faction5.Dinomancer) card = new Unit(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.name = "<NAME>" card.setDescription("Trial: Cast 7 spells that cause a minion to gain +Attack.\nDestiny: Minions summoned from your action bar gain Rush and Frenzy.") card.atk = 5 card.maxHP = 4 card.manaCost = 4 card.rarityId = Rarity.Mythron emblemModifier = PlayerModifierEmblemSummonWatchFromHandMagmarBuffQuest.createContextObject([ModifierFirstBlood.createContextObject(), ModifierFrenzy.createContextObject()]) emblemModifier.appliedName = "Spark of Hatred" emblemModifier.appliedDescription = "Minions summoned from your action bar have Rush and Frenzy." card.setInherentModifiersContextObjects([ ModifierStartsInHand.createContextObject(), ModifierCannotBeReplaced.createContextObject(), ModifierOnSummonFromHandApplyEmblems.createContextObject([emblemModifier], true, false), ModifierFateMagmarBuffQuest.createContextObject(7), ModifierCannotBeRemovedFromHand.createContextObject() ]) card.addKeywordClassToInclude(ModifierFirstBlood) card.addKeywordClassToInclude(ModifierFrenzy) card.setFXResource(["FX.Cards.Neutral.Ironclad"]) card.setBoundingBoxWidth(130) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f1ironcliffeguardian_attack_swing.audio receiveDamage : RSX.sfx_f1ironcliffeguardian_hit.audio attackDamage : RSX.sfx_f1ironcliffeguardian_attack_impact.audio death : RSX.sfx_f1ironcliffeguardian_death.audio ) card.setBaseAnimResource( breathing : RSX.f5DinomancerBreathing.name idle : RSX.f5DinomancerIdle.name walk : RSX.f5DinomancerRun.name attack : RSX.f5DinomancerAttack.name attackReleaseDelay: 0.0 attackDelay: 1.7 damage : RSX.f5DinomancerHit.name death : RSX.f5DinomancerDeath.name ) if (identifier == Cards.Faction5.IncreasingDino) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction5 card.name = "<NAME>" card.setDescription("Intensify: This minion gains +1/+1.") card.atk = 1 card.maxHP = 2 card.manaCost = 2 card.rarityId = Rarity.Common card.setInherentModifiersContextObjects([ ModifierIntensifyBuffSelf.createContextObject(1,1,"Even More Angered") ModifierCounterIntensify.createContextObject() ]) card.setFXResource(["FX.Cards.Neutral.VineEntangler"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_komodocharger_attack_swing.audio receiveDamage : RSX.sfx_f6_ancientgrove_hit.audio attackDamage : RSX.sfx_f6_ancientgrove_attack_impact.audio death : RSX.sfx_f6_ancientgrove_death.audio ) card.setBaseAnimResource( breathing : RSX.f5PteryxBreathing.name idle : RSX.f5PteryxIdle.name walk : RSX.f5PteryxRun.name attack : RSX.f5PteryxAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.f5PteryxHit.name death : RSX.f5PteryxDeath.name ) if (identifier == Cards.Spell.IncreasingHeal) card = new SpellIntensifyHealMyGeneral(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.IncreasingHeal card.name = "<NAME>" card.setDescription("Intensify: Restore 3 Health to your General.") card.manaCost = 2 card.healAmount = 3 card.rarityId = Rarity.Common card.spellFilterType = SpellFilterType.None card.addKeywordClassToInclude(ModifierIntensify) card.setInherentModifiersContextObjects([ModifierCounterIntensify.createContextObject()]) card.setFXResource(["FX.Cards.Spell.Invigoration"]) card.setBaseSoundResource( apply : RSX.sfx_spell_lionheartblessing.audio ) card.setBaseAnimResource( idle : RSX.iconIncreasingHealthIdle.name active : RSX.iconIncreasingHealthActive.name ) if (identifier == Cards.Faction5.Firebreather) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction5 card.name = "<NAME>" card.setDescription("Ranged\nWhenever this minion attacks, it also damages enemies around its target.") card.atk = 4 card.maxHP = 4 card.manaCost = 5 card.rarityId = Rarity.Epic card.setInherentModifiersContextObjects([ ModifierMyAttackWatchAreaAttack.createContextObject(), ModifierRanged.createContextObject() ]) card.setFXResource(["FX.Cards.Faction5.Firebreather"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_1.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_firespitter_attack_swing.audio receiveDamage : RSX.sfx_neutral_firespitter_hit.audio attackDamage : RSX.sfx_neutral_firespitter_attack_impact.audio death : RSX.sfx_neutral_firespitter_death.audio ) card.setBaseAnimResource( breathing : RSX.f5FireBreatherBreathing.name idle : RSX.f5FireBreatherIdle.name walk : RSX.f5FireBreatherRun.name attack : RSX.f5FireBreatherAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.f5FireBreatherHit.name death : RSX.f5FireBreatherDeath.name ) if (identifier == Cards.Faction5.ToughDino) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction5 card.name = "<NAME>" card.setDescription("Takes no damage from minions with less Attack.") card.atk = 3 card.maxHP = 6 card.manaCost = 4 card.rarityId = Rarity.Rare card.setInherentModifiersContextObjects([ModifierImmuneToDamageByWeakerEnemies.createContextObject(false)]) card.setFXResource(["FX.Cards.Neutral.RazorcragGolem"]) card.setBoundingBoxWidth(80) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_3.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_stormmetalgolem_attack_swing.audio receiveDamage : RSX.sfx_neutral_stormmetalgolem_hit.audio attackDamage : RSX.sfx_neutral_stormmetalgolem_attack_impact.audio death : RSX.sfx_neutral_stormmetalgolem_death.audio ) card.setBaseAnimResource( breathing : RSX.f5OrphanAspectBreathing.name idle : RSX.f5OrphanAspectIdle.name walk : RSX.f5OrphanAspectRun.name attack : RSX.f5OrphanAspectAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.f5OrphanAspectHit.name death : RSX.f5OrphanAspectDeath.name ) if (identifier == Cards.Faction5.Armadops) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction5 card.name = "<NAME>isaur" card.setDescription("Grow: +1/+1.\nWhenever another friendly minion with Grow survives damage, that minion grows.") card.atk = 2 card.maxHP = 5 card.manaCost = 3 card.rarityId = Rarity.Legendary card.setInherentModifiersContextObjects([ ModifierMyOtherMinionsDamagedWatchDamagedMinionGrows.createContextObject(), ModifierGrow.createContextObject(1) ]) card.setFXResource(["FX.Cards.Neutral.ThornNeedler"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_3.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_bluetipscorpion_attack_swing.audio receiveDamage : RSX.sfx_neutral_bluetipscorpion_hit.audio attackDamage : RSX.sfx_neutral_bluetipscorpion_attack_impact.audio death : RSX.sfx_neutral_bluetipscorpion_death.audio ) card.setBaseAnimResource( breathing : RSX.f5AnkylosBreathing.name idle : RSX.f5AnkylosIdle.name walk : RSX.f5AnkylosRun.name attack : RSX.f5AnkylosAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.f5AnkylosHit.name death : RSX.f5AnkylosDeath.name ) if (identifier == Cards.Faction5.BurstLizard) card = new Unit(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.name = "<NAME>" card.setDescription("Opening Gambit: Deal 1 damage to everything (including itself).") card.atk = 2 card.maxHP = 4 card.manaCost = 3 card.rarityId = Rarity.Common card.setInherentModifiersContextObjects([ModifierOpeningGambitDamageEverything.createContextObject(1, true)]) card.setFXResource(["FX.Cards.Neutral.BlisteringSkorn"]) card.setBaseSoundResource( apply : RSX.sfx_spell_blindscorch.audio walk : RSX.sfx_neutral_firestarter_impact.audio attack : RSX.sfx_neutral_firestarter_attack_swing.audio receiveDamage : RSX.sfx_neutral_firestarter_hit.audio attackDamage : RSX.sfx_neutral_firestarter_impact.audio death : RSX.sfx_neutral_firestarter_death.audio ) card.setBaseAnimResource( breathing : RSX.f5BurstLizardBreathing.name idle : RSX.f5BurstLizardIdle.name walk : RSX.f5BurstLizardRun.name attack : RSX.f5BurstLizardAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.f5BurstLizardHit.name death : RSX.f5BurstLizardDeath.name ) if (identifier == Cards.Spell.Spaghettify) card = new SpellDamageNotKillMinion(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.Spaghettify card.name = "Deep Impact" card.setDescription("Deal damage to a minion to reduce its Health to 1.") card.manaCost = 2 card.rarityId = Rarity.Rare card.spellFilterType = SpellFilterType.NeutralDirect card.canTargetGeneral = false card.setFXResource(["FX.Cards.Spell.DeepImpact"]) card.setBaseAnimResource( idle : RSX.iconMeteorIdle.name active : RSX.iconMeteorActive.name ) card.setBaseSoundResource( apply : RSX.sfx_spell_disintegrate.audio ) if (identifier == Cards.Spell.BigTime) card = new SpellApplyModifiers(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.BigTime card.name = "<NAME>argantuan Growth" card.setDescription("Give a minion, \"Grow: +8/+8.\"") card.manaCost = 4 card.rarityId = Rarity.Rare card.spellFilterType = SpellFilterType.NeutralDirect card.canTargetGeneral = false card.setTargetModifiersContextObjects([ModifierGrow.createContextObject(8)]) card.setFXResource(["FX.Cards.Spell.GargantuanGrowth"]) card.setBaseSoundResource( apply : RSX.sfx_spell_fractalreplication.audio ) card.setBaseAnimResource( idle : RSX.iconBigTimeIdle.name active : RSX.iconBigTimeActive.name ) if (identifier == Cards.Artifact.EggArmor) card = new Artifact(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction5 card.id = Cards.Artifact.EggArmor card.name = "<NAME>" card.setDescription("Your General has +1 Attack.\nYour Eggs have Forcefield.") card.manaCost = 2 card.rarityId = Rarity.Epic card.durability = 3 eggs = [ Cards.Faction5.Egg ] card.setTargetModifiersContextObjects([ Modifier.createContextObjectWithAttributeBuffs(1,undefined), Modifier.createContextObjectWithAuraForAllAllies([ModifierForcefield.createContextObject()], null, eggs) ]) card.addKeywordClassToInclude(ModifierForcefield) card.setFXResource(["FX.Cards.Artifact.OblivionSickle"]) card.setBaseAnimResource( idle: RSX.iconEggArmorIdle.name active: RSX.iconEggArmorActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.Spell.Reggplicate) card = new SpellReggplicate(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.Reggplicate card.name = "<NAME>otic Induction" card.setDescription("Summon an Egg of the minion most recently summoned from your action bar.") card.manaCost = 2 card.rarityId = Rarity.Epic card.spellFilterType = SpellFilterType.SpawnSource card.addKeywordClassToInclude(ModifierTokenCreator) card.setFXResource(["FX.Cards.Spell.MitoticInduction"]) card.setBaseSoundResource( apply : RSX.sfx_spell_disintegrate.audio ) card.setBaseAnimResource( idle : RSX.iconReggsplicateIdle.name active : RSX.iconReggsplicateActive.name ) if (identifier == Cards.Faction5.Megabrontodon) card = new Unit(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.setIsHiddenInCollection(true) card.name = "<NAME>atastrophosaurus" card.atk = 6 card.maxHP = 26 card.manaCost = 5 card.rarityId = Rarity.TokenUnit card.addKeywordClassToInclude(ModifierToken) card.setFXResource(["FX.Cards.Neutral.Khymera"]) card.setBoundingBoxWidth(145) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_rook_hit.audio attack : RSX.sfx_neutral_khymera_attack_swing.audio receiveDamage : RSX.sfx_neutral_khymera_hit.audio attackDamage : RSX.sfx_neutral_khymera_impact.audio death : RSX.sfx_neutral_khymera_death.audio ) card.setBaseAnimResource( breathing : RSX.f5MegaBrontodonBreathing.name idle : RSX.f5MegaBrontodonIdle.name walk : RSX.f5MegaBrontodonRun.name attack : RSX.f5MegaBrontodonAttack.name attackReleaseDelay: 0.0 attackDelay: 0.7 damage : RSX.f5MegaBrontodonHit.name death : RSX.f5MegaBrontodonDeath.name ) if (identifier == Cards.Spell.MarchOfTheBrontos) card = new SpellMarchOfTheBrontos(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.MarchOfTheBrontos card.name = "Extinction Event" card.setDescription("Each of your Eggs hatches into a Katastrophosaurus.") card.manaCost = 8 card.rarityId = Rarity.Legendary card.spellFilterType = SpellFilterType.NeutralIndirect card.radius = CONFIG.WHOLE_BOARD_RADIUS card.addKeywordClassToInclude(ModifierTokenCreator) card.setFXResource(["FX.Cards.Spell.ExtinctionEvent"]) card.setBaseSoundResource( apply : RSX.sfx_spell_darktransformation.audio ) card.setBaseAnimResource( idle : RSX.iconMarchBrontodonIdle.name active : RSX.iconMarchBrontodonActive.name ) if (identifier == Cards.Spell.YellRealLoud) card = new SpellYellRealLoud(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.YellRealLoud card.name = "<NAME>" card.setDescription("Give a friendly minion +3 Attack.\nStun enemy minions around it.") card.manaCost = 3 card.rarityId = Rarity.Common card.spellFilterType = SpellFilterType.AllyDirect statContextObject = Modifier.createContextObjectWithAttributeBuffs(3,0) statContextObject.appliedName = "Yelled Real Loud" card.setTargetModifiersContextObjects([ statContextObject ]) card.addKeywordClassToInclude(ModifierStun) card.setFXResource(["FX.Cards.Spell.Bellow"]) card.setBaseSoundResource( apply : RSX.sfx_neutral_windstopper_attack_impact.audio ) card.setBaseAnimResource( idle : RSX.iconYellLoudIdle.name active : RSX.iconYellLoudActive.name ) if (identifier == Cards.Faction5.BrundlBeast) card = new Unit(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.name = "<NAME>" card.setDescription("Whenever this minion takes damage, your opponent draws a card.") card.atk = 7 card.maxHP = 6 card.manaCost = 4 card.rarityId = Rarity.Legendary card.setInherentModifiersContextObjects([ModifierTakeDamageWatchOpponentDrawCard.createContextObject()]) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction2.CelestialPhantom"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_f2_celestialphantom_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f2_celestialphantom_death.audio ) card.setBaseAnimResource( breathing : RSX.f5BrundlebeastBreathing.name idle : RSX.f5BrundlebeastIdle.name walk : RSX.f5BrundlebeastRun.name attack : RSX.f5BrundlebeastAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.f5BrundlebeastHit.name death : RSX.f5BrundlebeastDeath.name ) return card module.exports = CardFactory_CoreshatterSet_Faction5
true
# do not add this file to a package # it is specifically parsed by the package generation script _ = require 'underscore' moment = require 'moment' Logger = require 'app/common/logger' CONFIG = require('app/common/config') RSX = require('app/data/resources') Card = require 'app/sdk/cards/card' Cards = require 'app/sdk/cards/cardsLookupComplete' CardType = require 'app/sdk/cards/cardType' Factions = require 'app/sdk/cards/factionsLookup' FactionFactory = require 'app/sdk/cards/factionFactory' Races = require 'app/sdk/cards/racesLookup' Rarity = require 'app/sdk/cards/rarityLookup' Unit = require 'app/sdk/entities/unit' CardSet = require 'app/sdk/cards/cardSetLookup' Artifact = require 'app/sdk/artifacts/artifact' Modifier = require 'app/sdk/modifiers/modifier' ModifierIntensifyBuffSelf = require 'app/sdk/modifiers/modifierIntensifyBuffSelf' ModifierRanged = require 'app/sdk/modifiers/modifierRanged' ModifierMyAttackWatchAreaAttack = require 'app/sdk/modifiers/modifierMyAttackWatchAreaAttack' ModifierImmuneToDamageByWeakerEnemies = require 'app/sdk/modifiers/modifierImmuneToDamageByWeakerEnemies' ModifierMyOtherMinionsDamagedWatchDamagedMinionGrows = require 'app/sdk/modifiers/modifierMyOtherMinionsDamagedWatchDamagedMinionGrows' ModifierGrow = require 'app/sdk/modifiers/modifierGrow' ModifierOpeningGambitDamageEverything = require 'app/sdk/modifiers/modifierOpeningGambitDamageEverything' ModifierStartsInHand = require 'app/sdk/modifiers/modifierStartsInHand' ModifierForcefield = require 'app/sdk/modifiers/modifierForcefield' ModifierFirstBlood = require 'app/sdk/modifiers/modifierFirstBlood' ModifierTakeDamageWatchOpponentDrawCard = require 'app/sdk/modifiers/modifierTakeDamageWatchOpponentDrawCard' ModifierOnSummonFromHandApplyEmblems = require 'app/sdk/modifiers/modifierOnSummonFromHandApplyEmblems' ModifierStun = require 'app/sdk/modifiers/modifierStun' ModifierToken = require 'app/sdk/modifiers/modifierToken' ModifierTokenCreator = require 'app/sdk/modifiers/modifierTokenCreator' ModifierFrenzy = require 'app/sdk/modifiers/modifierFrenzy' ModifierFateMagmarBuffQuest = require 'app/sdk/modifiers/modifierFateMagmarBuffQuest' ModifierCannotBeReplaced = require 'app/sdk/modifiers/modifierCannotBeReplaced' ModifierIntensify = require 'app/sdk/modifiers/modifierIntensify' ModifierCounterIntensify = require 'app/sdk/modifiers/modifierCounterIntensify' ModifierCannotBeRemovedFromHand = require 'app/sdk/modifiers/modifierCannotBeRemovedFromHand' PlayerModifierEmblemSummonWatchFromHandMagmarBuffQuest = require 'app/sdk/playerModifiers/playerModifierEmblemSummonWatchFromHandMagmarBuffQuest' SpellFilterType = require 'app/sdk/spells/spellFilterType' SpellDamageNotKillMinion = require 'app/sdk/spells/spellDamageNotKillMinion' SpellApplyModifiers = require 'app/sdk/spells/spellApplyModifiers' SpellReggplicate = require 'app/sdk/spells/spellReggplicate' SpellMarchOfTheBrontos = require 'app/sdk/spells/spellMarchOfTheBrontos' SpellYellRealLoud = require 'app/sdk/spells/spellYellRealLoud' SpellIntensifyHealMyGeneral = require 'app/sdk/spells/spellIntensifyHealMyGeneral' i18next = require 'i18next' if i18next.t() is undefined i18next.t = (text) -> return text class CardFactory_CoreshatterSet_Faction5 ###* * Returns a card that matches the identifier. * @param {Number|String} identifier * @param {GameSession} gameSession * @returns {Card} ### @cardForIdentifier: (identifier,gameSession) -> card = null if (identifier == Cards.Faction5.Dinomancer) card = new Unit(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Trial: Cast 7 spells that cause a minion to gain +Attack.\nDestiny: Minions summoned from your action bar gain Rush and Frenzy.") card.atk = 5 card.maxHP = 4 card.manaCost = 4 card.rarityId = Rarity.Mythron emblemModifier = PlayerModifierEmblemSummonWatchFromHandMagmarBuffQuest.createContextObject([ModifierFirstBlood.createContextObject(), ModifierFrenzy.createContextObject()]) emblemModifier.appliedName = "Spark of Hatred" emblemModifier.appliedDescription = "Minions summoned from your action bar have Rush and Frenzy." card.setInherentModifiersContextObjects([ ModifierStartsInHand.createContextObject(), ModifierCannotBeReplaced.createContextObject(), ModifierOnSummonFromHandApplyEmblems.createContextObject([emblemModifier], true, false), ModifierFateMagmarBuffQuest.createContextObject(7), ModifierCannotBeRemovedFromHand.createContextObject() ]) card.addKeywordClassToInclude(ModifierFirstBlood) card.addKeywordClassToInclude(ModifierFrenzy) card.setFXResource(["FX.Cards.Neutral.Ironclad"]) card.setBoundingBoxWidth(130) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f1ironcliffeguardian_attack_swing.audio receiveDamage : RSX.sfx_f1ironcliffeguardian_hit.audio attackDamage : RSX.sfx_f1ironcliffeguardian_attack_impact.audio death : RSX.sfx_f1ironcliffeguardian_death.audio ) card.setBaseAnimResource( breathing : RSX.f5DinomancerBreathing.name idle : RSX.f5DinomancerIdle.name walk : RSX.f5DinomancerRun.name attack : RSX.f5DinomancerAttack.name attackReleaseDelay: 0.0 attackDelay: 1.7 damage : RSX.f5DinomancerHit.name death : RSX.f5DinomancerDeath.name ) if (identifier == Cards.Faction5.IncreasingDino) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction5 card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Intensify: This minion gains +1/+1.") card.atk = 1 card.maxHP = 2 card.manaCost = 2 card.rarityId = Rarity.Common card.setInherentModifiersContextObjects([ ModifierIntensifyBuffSelf.createContextObject(1,1,"Even More Angered") ModifierCounterIntensify.createContextObject() ]) card.setFXResource(["FX.Cards.Neutral.VineEntangler"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_komodocharger_attack_swing.audio receiveDamage : RSX.sfx_f6_ancientgrove_hit.audio attackDamage : RSX.sfx_f6_ancientgrove_attack_impact.audio death : RSX.sfx_f6_ancientgrove_death.audio ) card.setBaseAnimResource( breathing : RSX.f5PteryxBreathing.name idle : RSX.f5PteryxIdle.name walk : RSX.f5PteryxRun.name attack : RSX.f5PteryxAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.f5PteryxHit.name death : RSX.f5PteryxDeath.name ) if (identifier == Cards.Spell.IncreasingHeal) card = new SpellIntensifyHealMyGeneral(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.IncreasingHeal card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Intensify: Restore 3 Health to your General.") card.manaCost = 2 card.healAmount = 3 card.rarityId = Rarity.Common card.spellFilterType = SpellFilterType.None card.addKeywordClassToInclude(ModifierIntensify) card.setInherentModifiersContextObjects([ModifierCounterIntensify.createContextObject()]) card.setFXResource(["FX.Cards.Spell.Invigoration"]) card.setBaseSoundResource( apply : RSX.sfx_spell_lionheartblessing.audio ) card.setBaseAnimResource( idle : RSX.iconIncreasingHealthIdle.name active : RSX.iconIncreasingHealthActive.name ) if (identifier == Cards.Faction5.Firebreather) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction5 card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Ranged\nWhenever this minion attacks, it also damages enemies around its target.") card.atk = 4 card.maxHP = 4 card.manaCost = 5 card.rarityId = Rarity.Epic card.setInherentModifiersContextObjects([ ModifierMyAttackWatchAreaAttack.createContextObject(), ModifierRanged.createContextObject() ]) card.setFXResource(["FX.Cards.Faction5.Firebreather"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_1.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_firespitter_attack_swing.audio receiveDamage : RSX.sfx_neutral_firespitter_hit.audio attackDamage : RSX.sfx_neutral_firespitter_attack_impact.audio death : RSX.sfx_neutral_firespitter_death.audio ) card.setBaseAnimResource( breathing : RSX.f5FireBreatherBreathing.name idle : RSX.f5FireBreatherIdle.name walk : RSX.f5FireBreatherRun.name attack : RSX.f5FireBreatherAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.f5FireBreatherHit.name death : RSX.f5FireBreatherDeath.name ) if (identifier == Cards.Faction5.ToughDino) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction5 card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Takes no damage from minions with less Attack.") card.atk = 3 card.maxHP = 6 card.manaCost = 4 card.rarityId = Rarity.Rare card.setInherentModifiersContextObjects([ModifierImmuneToDamageByWeakerEnemies.createContextObject(false)]) card.setFXResource(["FX.Cards.Neutral.RazorcragGolem"]) card.setBoundingBoxWidth(80) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_3.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_stormmetalgolem_attack_swing.audio receiveDamage : RSX.sfx_neutral_stormmetalgolem_hit.audio attackDamage : RSX.sfx_neutral_stormmetalgolem_attack_impact.audio death : RSX.sfx_neutral_stormmetalgolem_death.audio ) card.setBaseAnimResource( breathing : RSX.f5OrphanAspectBreathing.name idle : RSX.f5OrphanAspectIdle.name walk : RSX.f5OrphanAspectRun.name attack : RSX.f5OrphanAspectAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.f5OrphanAspectHit.name death : RSX.f5OrphanAspectDeath.name ) if (identifier == Cards.Faction5.Armadops) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction5 card.name = "PI:NAME:<NAME>END_PIisaur" card.setDescription("Grow: +1/+1.\nWhenever another friendly minion with Grow survives damage, that minion grows.") card.atk = 2 card.maxHP = 5 card.manaCost = 3 card.rarityId = Rarity.Legendary card.setInherentModifiersContextObjects([ ModifierMyOtherMinionsDamagedWatchDamagedMinionGrows.createContextObject(), ModifierGrow.createContextObject(1) ]) card.setFXResource(["FX.Cards.Neutral.ThornNeedler"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_3.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_bluetipscorpion_attack_swing.audio receiveDamage : RSX.sfx_neutral_bluetipscorpion_hit.audio attackDamage : RSX.sfx_neutral_bluetipscorpion_attack_impact.audio death : RSX.sfx_neutral_bluetipscorpion_death.audio ) card.setBaseAnimResource( breathing : RSX.f5AnkylosBreathing.name idle : RSX.f5AnkylosIdle.name walk : RSX.f5AnkylosRun.name attack : RSX.f5AnkylosAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.f5AnkylosHit.name death : RSX.f5AnkylosDeath.name ) if (identifier == Cards.Faction5.BurstLizard) card = new Unit(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Opening Gambit: Deal 1 damage to everything (including itself).") card.atk = 2 card.maxHP = 4 card.manaCost = 3 card.rarityId = Rarity.Common card.setInherentModifiersContextObjects([ModifierOpeningGambitDamageEverything.createContextObject(1, true)]) card.setFXResource(["FX.Cards.Neutral.BlisteringSkorn"]) card.setBaseSoundResource( apply : RSX.sfx_spell_blindscorch.audio walk : RSX.sfx_neutral_firestarter_impact.audio attack : RSX.sfx_neutral_firestarter_attack_swing.audio receiveDamage : RSX.sfx_neutral_firestarter_hit.audio attackDamage : RSX.sfx_neutral_firestarter_impact.audio death : RSX.sfx_neutral_firestarter_death.audio ) card.setBaseAnimResource( breathing : RSX.f5BurstLizardBreathing.name idle : RSX.f5BurstLizardIdle.name walk : RSX.f5BurstLizardRun.name attack : RSX.f5BurstLizardAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.f5BurstLizardHit.name death : RSX.f5BurstLizardDeath.name ) if (identifier == Cards.Spell.Spaghettify) card = new SpellDamageNotKillMinion(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.Spaghettify card.name = "Deep Impact" card.setDescription("Deal damage to a minion to reduce its Health to 1.") card.manaCost = 2 card.rarityId = Rarity.Rare card.spellFilterType = SpellFilterType.NeutralDirect card.canTargetGeneral = false card.setFXResource(["FX.Cards.Spell.DeepImpact"]) card.setBaseAnimResource( idle : RSX.iconMeteorIdle.name active : RSX.iconMeteorActive.name ) card.setBaseSoundResource( apply : RSX.sfx_spell_disintegrate.audio ) if (identifier == Cards.Spell.BigTime) card = new SpellApplyModifiers(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.BigTime card.name = "PI:NAME:<NAME>END_PIargantuan Growth" card.setDescription("Give a minion, \"Grow: +8/+8.\"") card.manaCost = 4 card.rarityId = Rarity.Rare card.spellFilterType = SpellFilterType.NeutralDirect card.canTargetGeneral = false card.setTargetModifiersContextObjects([ModifierGrow.createContextObject(8)]) card.setFXResource(["FX.Cards.Spell.GargantuanGrowth"]) card.setBaseSoundResource( apply : RSX.sfx_spell_fractalreplication.audio ) card.setBaseAnimResource( idle : RSX.iconBigTimeIdle.name active : RSX.iconBigTimeActive.name ) if (identifier == Cards.Artifact.EggArmor) card = new Artifact(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction5 card.id = Cards.Artifact.EggArmor card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Your General has +1 Attack.\nYour Eggs have Forcefield.") card.manaCost = 2 card.rarityId = Rarity.Epic card.durability = 3 eggs = [ Cards.Faction5.Egg ] card.setTargetModifiersContextObjects([ Modifier.createContextObjectWithAttributeBuffs(1,undefined), Modifier.createContextObjectWithAuraForAllAllies([ModifierForcefield.createContextObject()], null, eggs) ]) card.addKeywordClassToInclude(ModifierForcefield) card.setFXResource(["FX.Cards.Artifact.OblivionSickle"]) card.setBaseAnimResource( idle: RSX.iconEggArmorIdle.name active: RSX.iconEggArmorActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.Spell.Reggplicate) card = new SpellReggplicate(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.Reggplicate card.name = "PI:NAME:<NAME>END_PIotic Induction" card.setDescription("Summon an Egg of the minion most recently summoned from your action bar.") card.manaCost = 2 card.rarityId = Rarity.Epic card.spellFilterType = SpellFilterType.SpawnSource card.addKeywordClassToInclude(ModifierTokenCreator) card.setFXResource(["FX.Cards.Spell.MitoticInduction"]) card.setBaseSoundResource( apply : RSX.sfx_spell_disintegrate.audio ) card.setBaseAnimResource( idle : RSX.iconReggsplicateIdle.name active : RSX.iconReggsplicateActive.name ) if (identifier == Cards.Faction5.Megabrontodon) card = new Unit(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.setIsHiddenInCollection(true) card.name = "PI:NAME:<NAME>END_PIatastrophosaurus" card.atk = 6 card.maxHP = 26 card.manaCost = 5 card.rarityId = Rarity.TokenUnit card.addKeywordClassToInclude(ModifierToken) card.setFXResource(["FX.Cards.Neutral.Khymera"]) card.setBoundingBoxWidth(145) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_rook_hit.audio attack : RSX.sfx_neutral_khymera_attack_swing.audio receiveDamage : RSX.sfx_neutral_khymera_hit.audio attackDamage : RSX.sfx_neutral_khymera_impact.audio death : RSX.sfx_neutral_khymera_death.audio ) card.setBaseAnimResource( breathing : RSX.f5MegaBrontodonBreathing.name idle : RSX.f5MegaBrontodonIdle.name walk : RSX.f5MegaBrontodonRun.name attack : RSX.f5MegaBrontodonAttack.name attackReleaseDelay: 0.0 attackDelay: 0.7 damage : RSX.f5MegaBrontodonHit.name death : RSX.f5MegaBrontodonDeath.name ) if (identifier == Cards.Spell.MarchOfTheBrontos) card = new SpellMarchOfTheBrontos(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.MarchOfTheBrontos card.name = "Extinction Event" card.setDescription("Each of your Eggs hatches into a Katastrophosaurus.") card.manaCost = 8 card.rarityId = Rarity.Legendary card.spellFilterType = SpellFilterType.NeutralIndirect card.radius = CONFIG.WHOLE_BOARD_RADIUS card.addKeywordClassToInclude(ModifierTokenCreator) card.setFXResource(["FX.Cards.Spell.ExtinctionEvent"]) card.setBaseSoundResource( apply : RSX.sfx_spell_darktransformation.audio ) card.setBaseAnimResource( idle : RSX.iconMarchBrontodonIdle.name active : RSX.iconMarchBrontodonActive.name ) if (identifier == Cards.Spell.YellRealLoud) card = new SpellYellRealLoud(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.YellRealLoud card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Give a friendly minion +3 Attack.\nStun enemy minions around it.") card.manaCost = 3 card.rarityId = Rarity.Common card.spellFilterType = SpellFilterType.AllyDirect statContextObject = Modifier.createContextObjectWithAttributeBuffs(3,0) statContextObject.appliedName = "Yelled Real Loud" card.setTargetModifiersContextObjects([ statContextObject ]) card.addKeywordClassToInclude(ModifierStun) card.setFXResource(["FX.Cards.Spell.Bellow"]) card.setBaseSoundResource( apply : RSX.sfx_neutral_windstopper_attack_impact.audio ) card.setBaseAnimResource( idle : RSX.iconYellLoudIdle.name active : RSX.iconYellLoudActive.name ) if (identifier == Cards.Faction5.BrundlBeast) card = new Unit(gameSession) card.factionId = Factions.Faction5 card.setCardSetId(CardSet.Coreshatter) card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Whenever this minion takes damage, your opponent draws a card.") card.atk = 7 card.maxHP = 6 card.manaCost = 4 card.rarityId = Rarity.Legendary card.setInherentModifiersContextObjects([ModifierTakeDamageWatchOpponentDrawCard.createContextObject()]) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction2.CelestialPhantom"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_f2_celestialphantom_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f2_celestialphantom_death.audio ) card.setBaseAnimResource( breathing : RSX.f5BrundlebeastBreathing.name idle : RSX.f5BrundlebeastIdle.name walk : RSX.f5BrundlebeastRun.name attack : RSX.f5BrundlebeastAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.f5BrundlebeastHit.name death : RSX.f5BrundlebeastDeath.name ) return card module.exports = CardFactory_CoreshatterSet_Faction5
[ { "context": "SONBlob').andCallFake (key) =>\n if key is \"NylasSyncWorker:#{TEST_ACCOUNT_ID}\"\n return Promise.resolve ", "end": 1073, "score": 0.9041265249252319, "start": 1058, "tag": "KEY", "value": "lasSyncWorker:#" }, { "context": "e (key) =>\n return 'old-school' if key is \"nylas.#{@account.id}.cursor\"\n return undefined\n\n ", "end": 6612, "score": 0.9909737706184387, "start": 6604, "tag": "KEY", "value": "nylas.#{" }, { "context": " return 'old-school' if key is \"nylas.#{@account.id}.cursor\"\n return undefined\n\n worker = new Nyl", "end": 6631, "score": 0.9699544310569763, "start": 6621, "tag": "KEY", "value": "id}.cursor" } ]
app/internal_packages/worker-sync/spec/nylas-sync-worker-spec.coffee
immershy/nodemail
0
_ = require 'underscore' {Actions, DatabaseStore, DatabaseTransaction, Account, Thread} = require 'nylas-exports' NylasLongConnection = require '../lib/nylas-long-connection' NylasSyncWorker = require '../lib/nylas-sync-worker' describe "NylasSyncWorker", -> beforeEach -> @apiRequests = [] @api = APIRoot: 'https://api.nylas.com' pluginsSupported: true accessTokenForAccountId: => '123' makeRequest: (requestOptions) => @apiRequests.push({requestOptions}) getCollection: (account, model, params, requestOptions) => @apiRequests.push({account, model, params, requestOptions}) getThreads: (account, params, requestOptions) => @apiRequests.push({account, model:'threads', params, requestOptions}) @apiCursorStub = undefined spyOn(NylasSyncWorker.prototype, 'fetchAllMetadata').andCallFake (cb) -> cb() spyOn(DatabaseTransaction.prototype, 'persistJSONBlob').andReturn(Promise.resolve()) spyOn(DatabaseStore, 'findJSONBlob').andCallFake (key) => if key is "NylasSyncWorker:#{TEST_ACCOUNT_ID}" return Promise.resolve _.extend {}, { "cursor": @apiCursorStub "contacts": busy: true complete: false "calendars": busy:false complete: true } else if key.indexOf('ContactRankings') is 0 return Promise.resolve([]) else return throw new Error("Not stubbed! #{key}") @account = new Account(clientId: TEST_ACCOUNT_CLIENT_ID, serverId: TEST_ACCOUNT_ID, organizationUnit: 'label') @worker = new NylasSyncWorker(@api, @account) @worker._metadata = {"a": [{"id":"b"}]} @connection = @worker.connection() spyOn(@connection, 'start') advanceClock() it "should reset `busy` to false when reading state from disk", -> @worker = new NylasSyncWorker(@api, @account) spyOn(@worker, 'resume') advanceClock() expect(@worker.state().contacts.busy).toEqual(false) describe "start", -> it "should open the delta connection", -> @worker.start() advanceClock() expect(@connection.start).toHaveBeenCalled() it "should start querying for model collections and counts that haven't been fully cached", -> @worker.start() advanceClock() expect(@apiRequests.length).toBe(12) modelsRequested = _.compact _.map @apiRequests, ({model}) -> model expect(modelsRequested).toEqual(['threads', 'messages', 'labels', 'drafts', 'contacts', 'events']) countsRequested = _.compact _.map @apiRequests, ({requestOptions}) -> if requestOptions.qs?.view is 'count' return requestOptions.path expect(modelsRequested).toEqual(['threads', 'messages', 'labels', 'drafts', 'contacts', 'events']) expect(countsRequested).toEqual(['/threads', '/messages', '/labels', '/drafts', '/contacts', '/events']) it "should fetch 1000 labels and folders, to prevent issues where Inbox is not in the first page", -> labelsRequest = _.find @apiRequests, (r) -> r.model is 'labels' expect(labelsRequest.params.limit).toBe(1000) it "should mark incomplete collections as `busy`", -> @worker.start() advanceClock() nextState = @worker.state() for collection in ['contacts','threads','drafts', 'labels'] expect(nextState[collection].busy).toEqual(true) it "should initialize count and fetched to 0", -> @worker.start() advanceClock() nextState = @worker.state() for collection in ['contacts','threads','drafts', 'labels'] expect(nextState[collection].fetched).toEqual(0) expect(nextState[collection].count).toEqual(0) it "after failures, it should attempt to resume periodically but back off as failures continue", -> simulateNetworkFailure = => @apiRequests[1].requestOptions.error({statusCode: 400}) @apiRequests = [] spyOn(@worker, 'resume').andCallThrough() @worker.start() expect(@worker.resume.callCount).toBe(1) simulateNetworkFailure(); expect(@worker.resume.callCount).toBe(1) advanceClock(4000); expect(@worker.resume.callCount).toBe(2) simulateNetworkFailure(); expect(@worker.resume.callCount).toBe(2) advanceClock(4000); expect(@worker.resume.callCount).toBe(2) advanceClock(4000); expect(@worker.resume.callCount).toBe(3) simulateNetworkFailure(); expect(@worker.resume.callCount).toBe(3) advanceClock(4000); expect(@worker.resume.callCount).toBe(3) advanceClock(4000); expect(@worker.resume.callCount).toBe(3) advanceClock(4000); expect(@worker.resume.callCount).toBe(4) simulateNetworkFailure(); expect(@worker.resume.callCount).toBe(4) advanceClock(4000); expect(@worker.resume.callCount).toBe(4) advanceClock(4000); expect(@worker.resume.callCount).toBe(4) advanceClock(4000); expect(@worker.resume.callCount).toBe(4) advanceClock(4000); expect(@worker.resume.callCount).toBe(4) advanceClock(4000); expect(@worker.resume.callCount).toBe(5) it "handles the request as a failure if we try and grab labels or folders without an 'inbox'", -> spyOn(@worker, 'resume').andCallThrough() @worker.start() expect(@worker.resume.callCount).toBe(1) request = _.findWhere(@apiRequests, model: 'labels') request.requestOptions.success([]) expect(@worker.resume.callCount).toBe(1) advanceClock(30000) expect(@worker.resume.callCount).toBe(2) it "handles the request as a success if we try and grab labels or folders and it includes the 'inbox'", -> spyOn(@worker, 'resume').andCallThrough() @worker.start() expect(@worker.resume.callCount).toBe(1) request = _.findWhere(@apiRequests, model: 'labels') request.requestOptions.success([{name: "inbox"}, {name: "archive"}]) expect(@worker.resume.callCount).toBe(1) advanceClock(30000) expect(@worker.resume.callCount).toBe(1) describe "delta streaming cursor", -> it "should read the cursor from the database, and the old config format", -> spyOn(NylasLongConnection.prototype, 'withCursor').andCallFake => @apiCursorStub = undefined # no cursor present worker = new NylasSyncWorker(@api, @account) connection = worker.connection() expect(connection.hasCursor()).toBe(false) advanceClock() expect(connection.hasCursor()).toBe(false) # cursor present in config spyOn(NylasEnv.config, 'get').andCallFake (key) => return 'old-school' if key is "nylas.#{@account.id}.cursor" return undefined worker = new NylasSyncWorker(@api, @account) connection = worker.connection() advanceClock() expect(connection.hasCursor()).toBe(true) expect(connection._config.getCursor()).toEqual('old-school') # cursor present in database, overrides cursor in config @apiCursorStub = "new-school" worker = new NylasSyncWorker(@api, @account) connection = worker.connection() expect(connection.hasCursor()).toBe(false) advanceClock() expect(connection.hasCursor()).toBe(true) expect(connection._config.getCursor()).toEqual('new-school') describe "when a count request completes", -> beforeEach -> @worker.start() advanceClock() @request = @apiRequests[0] @apiRequests = [] it "should update the count on the collection", -> @request.requestOptions.success({count: 1001}) nextState = @worker.state() expect(nextState.threads.count).toEqual(1001) describe "resume", -> it "should fetch metadata first and fetch other collections when metadata is ready", -> fetchAllMetadataCallback = null jasmine.unspy(NylasSyncWorker.prototype, 'fetchAllMetadata') spyOn(NylasSyncWorker.prototype, 'fetchAllMetadata').andCallFake (cb) => fetchAllMetadataCallback = cb spyOn(@worker, 'fetchCollection') @worker._state = {} @worker.resume() expect(@worker.fetchAllMetadata).toHaveBeenCalled() expect(@worker.fetchCollection.calls.length).toBe(0) fetchAllMetadataCallback() expect(@worker.fetchCollection.calls.length).not.toBe(0) it "should not fetch metadata pages if pluginsSupported is false", -> @api.pluginsSupported = false spyOn(NylasSyncWorker.prototype, '_fetchWithErrorHandling') spyOn(@worker, 'fetchCollection') @worker._state = {} @worker.resume() expect(@worker._fetchWithErrorHandling).not.toHaveBeenCalled() expect(@worker.fetchCollection.calls.length).not.toBe(0) it "should fetch collections for which `shouldFetchCollection` returns true", -> spyOn(@worker, 'fetchCollection') spyOn(@worker, 'shouldFetchCollection').andCallFake (collection) => return collection in ['threads', 'labels', 'drafts'] @worker.resume() expect(@worker.fetchCollection.calls.map (call) -> call.args[0]).toEqual(['threads', 'labels', 'drafts']) it "should be called when Actions.retrySync is received", -> spyOn(@worker, 'resume').andCallThrough() Actions.retrySync() expect(@worker.resume).toHaveBeenCalled() describe "shouldFetchCollection", -> it "should return false if the collection sync is already in progress", -> @worker._state.threads = { 'busy': true 'complete': false } expect(@worker.shouldFetchCollection('threads')).toBe(false) it "should return false if the collection sync is already complete", -> @worker._state.threads = { 'busy': false 'complete': true } expect(@worker.shouldFetchCollection('threads')).toBe(false) it "should return true otherwise", -> @worker._state.threads = { 'busy': false 'complete': false } expect(@worker.shouldFetchCollection('threads')).toBe(true) @worker._state.threads = undefined expect(@worker.shouldFetchCollection('threads')).toBe(true) describe "fetchCollection", -> beforeEach -> @apiRequests = [] it "should start the request for the model count", -> @worker._state.threads = { 'busy': false 'complete': false } @worker.fetchCollection('threads') expect(@apiRequests[0].requestOptions.path).toBe('/threads') expect(@apiRequests[0].requestOptions.qs.view).toBe('count') it "should pass any metadata it preloaded", -> @worker._state.threads = { 'busy': false 'complete': false } @worker.fetchCollection('threads') expect(@apiRequests[1].model).toBe('threads') expect(@apiRequests[1].requestOptions.metadataToAttach).toBe(@worker._metadata) describe "when there is not a previous page failure (`errorRequestRange`)", -> it "should start the first request for models", -> @worker._state.threads = { 'busy': false 'complete': false } @worker.fetchCollection('threads') expect(@apiRequests[1].model).toBe('threads') expect(@apiRequests[1].params.offset).toBe(0) describe "when there is a previous page failure (`errorRequestRange`)", -> beforeEach -> @worker._state.threads = 'count': 1200 'fetched': 100 'busy': false 'complete': false 'error': new Error("Something bad") 'errorRequestRange': offset: 100 limit: 50 it "should start paginating from the request that failed", -> @worker.fetchCollection('threads') expect(@apiRequests[0].model).toBe('threads') expect(@apiRequests[0].params.offset).toBe(100) expect(@apiRequests[0].params.limit).toBe(50) it "should not reset the `count`, `fetched` or start fetching the count", -> @worker.fetchCollection('threads') expect(@worker._state.threads.fetched).toBe(100) expect(@worker._state.threads.count).toBe(1200) expect(@apiRequests.length).toBe(1) describe 'when maxFetchCount option is specified', -> it "should only fetch maxFetch count on the first request if it is less than initialPageSize", -> @worker._state.messages = count: 1000 fetched: 0 @worker.fetchCollection('messages', {initialPageSize: 30, maxFetchCount: 25}) expect(@apiRequests[0].params.offset).toBe 0 expect(@apiRequests[0].params.limit).toBe 25 it "sould only fetch the maxFetchCount when restoring from saved state", -> @worker._state.messages = count: 1000 fetched: 470 errorRequestRange: { limit: 50, offset: 470, } @worker.fetchCollection('messages', {maxFetchCount: 500}) expect(@apiRequests[0].params.offset).toBe 470 expect(@apiRequests[0].params.limit).toBe 30 describe "fetchCollectionPage", -> beforeEach -> @apiRequests = [] describe 'when maxFetchCount option is specified', -> it 'should not fetch next page if maxFetchCount has been reached', -> @worker._state.messages = count: 1000 fetched: 470 @worker.fetchCollectionPage('messages', {limit: 30, offset: 470}, {maxFetchCount: 500}) {success} = @apiRequests[0].requestOptions success({length: 30}) expect(@worker._state.messages.fetched).toBe 500 advanceClock(2000) expect(@apiRequests.length).toBe 1 it 'should limit by maxFetchCount when requesting the next page', -> @worker._state.messages = count: 1000 fetched: 450 @worker.fetchCollectionPage('messages', {limit: 30, offset: 450 }, {maxFetchCount: 500}) {success} = @apiRequests[0].requestOptions success({length: 30}) expect(@worker._state.messages.fetched).toBe 480 advanceClock(2000) expect(@apiRequests[1].params.offset).toBe 480 expect(@apiRequests[1].params.limit).toBe 20 describe "when an API request completes", -> beforeEach -> @worker.start() advanceClock() @request = @apiRequests[1] @apiRequests = [] describe "successfully, with models", -> it "should start out by requesting a small number of items", -> expect(@request.params.limit).toBe NylasSyncWorker.INITIAL_PAGE_SIZE it "should request the next page", -> pageSize = @request.params.limit models = [] models.push(new Thread) for i in [0..(pageSize-1)] @request.requestOptions.success(models) advanceClock(2000) expect(@apiRequests.length).toBe(1) expect(@apiRequests[0].params.offset).toEqual @request.params.offset + pageSize it "increase the limit on the next page load by 50%", -> pageSize = @request.params.limit models = [] models.push(new Thread) for i in [0..(pageSize-1)] @request.requestOptions.success(models) advanceClock(2000) expect(@apiRequests.length).toBe(1) expect(@apiRequests[0].params.limit).toEqual pageSize * 1.5, it "never requests more then MAX_PAGE_SIZE", -> pageSize = @request.params.limit = NylasSyncWorker.MAX_PAGE_SIZE models = [] models.push(new Thread) for i in [0..(pageSize-1)] @request.requestOptions.success(models) advanceClock(2000) expect(@apiRequests.length).toBe(1) expect(@apiRequests[0].params.limit).toEqual NylasSyncWorker.MAX_PAGE_SIZE it "should update the fetched count on the collection", -> expect(@worker.state().threads.fetched).toEqual(0) pageSize = @request.params.limit models = [] models.push(new Thread) for i in [0..(pageSize-1)] @request.requestOptions.success(models) expect(@worker.state().threads.fetched).toEqual(pageSize) describe "successfully, with fewer models than requested", -> beforeEach -> models = [] models.push(new Thread) for i in [0..100] @request.requestOptions.success(models) it "should not request another page", -> expect(@apiRequests.length).toBe(0) it "should update the state to complete", -> expect(@worker.state().threads.busy).toEqual(false) expect(@worker.state().threads.complete).toEqual(true) it "should update the fetched count on the collection", -> expect(@worker.state().threads.fetched).toEqual(101) describe "successfully, with no models", -> it "should not request another page", -> @request.requestOptions.success([]) expect(@apiRequests.length).toBe(0) it "should update the state to complete", -> @request.requestOptions.success([]) expect(@worker.state().threads.busy).toEqual(false) expect(@worker.state().threads.complete).toEqual(true) describe "with an error", -> it "should log the error to the state, along with the range that failed", -> err = new Error("Oh no a network error") @request.requestOptions.error(err) expect(@worker.state().threads.busy).toEqual(false) expect(@worker.state().threads.complete).toEqual(false) expect(@worker.state().threads.error).toEqual(err.toString()) expect(@worker.state().threads.errorRequestRange).toEqual({offset: 0, limit: 30}) it "should not request another page", -> @request.requestOptions.error(new Error("Oh no a network error")) expect(@apiRequests.length).toBe(0) describe "succeeds after a previous error", -> beforeEach -> @worker._state.threads.error = new Error("Something bad happened") @worker._state.threads.errorRequestRange = {limit: 10, offset: 10} @request.requestOptions.success([]) advanceClock(1) it "should clear any previous error", -> expect(@worker.state().threads.error).toEqual(null) expect(@worker.state().threads.errorRequestRange).toEqual(null) describe "cleanup", -> it "should termiate the delta connection", -> spyOn(@connection, 'end') @worker.cleanup() expect(@connection.end).toHaveBeenCalled() it "should stop trying to restart failed collection syncs", -> spyOn(console, 'log') spyOn(@worker, 'resume').andCallThrough() @worker.cleanup() advanceClock(50000) expect(@worker.resume.callCount).toBe(0)
143468
_ = require 'underscore' {Actions, DatabaseStore, DatabaseTransaction, Account, Thread} = require 'nylas-exports' NylasLongConnection = require '../lib/nylas-long-connection' NylasSyncWorker = require '../lib/nylas-sync-worker' describe "NylasSyncWorker", -> beforeEach -> @apiRequests = [] @api = APIRoot: 'https://api.nylas.com' pluginsSupported: true accessTokenForAccountId: => '123' makeRequest: (requestOptions) => @apiRequests.push({requestOptions}) getCollection: (account, model, params, requestOptions) => @apiRequests.push({account, model, params, requestOptions}) getThreads: (account, params, requestOptions) => @apiRequests.push({account, model:'threads', params, requestOptions}) @apiCursorStub = undefined spyOn(NylasSyncWorker.prototype, 'fetchAllMetadata').andCallFake (cb) -> cb() spyOn(DatabaseTransaction.prototype, 'persistJSONBlob').andReturn(Promise.resolve()) spyOn(DatabaseStore, 'findJSONBlob').andCallFake (key) => if key is "Ny<KEY>{TEST_ACCOUNT_ID}" return Promise.resolve _.extend {}, { "cursor": @apiCursorStub "contacts": busy: true complete: false "calendars": busy:false complete: true } else if key.indexOf('ContactRankings') is 0 return Promise.resolve([]) else return throw new Error("Not stubbed! #{key}") @account = new Account(clientId: TEST_ACCOUNT_CLIENT_ID, serverId: TEST_ACCOUNT_ID, organizationUnit: 'label') @worker = new NylasSyncWorker(@api, @account) @worker._metadata = {"a": [{"id":"b"}]} @connection = @worker.connection() spyOn(@connection, 'start') advanceClock() it "should reset `busy` to false when reading state from disk", -> @worker = new NylasSyncWorker(@api, @account) spyOn(@worker, 'resume') advanceClock() expect(@worker.state().contacts.busy).toEqual(false) describe "start", -> it "should open the delta connection", -> @worker.start() advanceClock() expect(@connection.start).toHaveBeenCalled() it "should start querying for model collections and counts that haven't been fully cached", -> @worker.start() advanceClock() expect(@apiRequests.length).toBe(12) modelsRequested = _.compact _.map @apiRequests, ({model}) -> model expect(modelsRequested).toEqual(['threads', 'messages', 'labels', 'drafts', 'contacts', 'events']) countsRequested = _.compact _.map @apiRequests, ({requestOptions}) -> if requestOptions.qs?.view is 'count' return requestOptions.path expect(modelsRequested).toEqual(['threads', 'messages', 'labels', 'drafts', 'contacts', 'events']) expect(countsRequested).toEqual(['/threads', '/messages', '/labels', '/drafts', '/contacts', '/events']) it "should fetch 1000 labels and folders, to prevent issues where Inbox is not in the first page", -> labelsRequest = _.find @apiRequests, (r) -> r.model is 'labels' expect(labelsRequest.params.limit).toBe(1000) it "should mark incomplete collections as `busy`", -> @worker.start() advanceClock() nextState = @worker.state() for collection in ['contacts','threads','drafts', 'labels'] expect(nextState[collection].busy).toEqual(true) it "should initialize count and fetched to 0", -> @worker.start() advanceClock() nextState = @worker.state() for collection in ['contacts','threads','drafts', 'labels'] expect(nextState[collection].fetched).toEqual(0) expect(nextState[collection].count).toEqual(0) it "after failures, it should attempt to resume periodically but back off as failures continue", -> simulateNetworkFailure = => @apiRequests[1].requestOptions.error({statusCode: 400}) @apiRequests = [] spyOn(@worker, 'resume').andCallThrough() @worker.start() expect(@worker.resume.callCount).toBe(1) simulateNetworkFailure(); expect(@worker.resume.callCount).toBe(1) advanceClock(4000); expect(@worker.resume.callCount).toBe(2) simulateNetworkFailure(); expect(@worker.resume.callCount).toBe(2) advanceClock(4000); expect(@worker.resume.callCount).toBe(2) advanceClock(4000); expect(@worker.resume.callCount).toBe(3) simulateNetworkFailure(); expect(@worker.resume.callCount).toBe(3) advanceClock(4000); expect(@worker.resume.callCount).toBe(3) advanceClock(4000); expect(@worker.resume.callCount).toBe(3) advanceClock(4000); expect(@worker.resume.callCount).toBe(4) simulateNetworkFailure(); expect(@worker.resume.callCount).toBe(4) advanceClock(4000); expect(@worker.resume.callCount).toBe(4) advanceClock(4000); expect(@worker.resume.callCount).toBe(4) advanceClock(4000); expect(@worker.resume.callCount).toBe(4) advanceClock(4000); expect(@worker.resume.callCount).toBe(4) advanceClock(4000); expect(@worker.resume.callCount).toBe(5) it "handles the request as a failure if we try and grab labels or folders without an 'inbox'", -> spyOn(@worker, 'resume').andCallThrough() @worker.start() expect(@worker.resume.callCount).toBe(1) request = _.findWhere(@apiRequests, model: 'labels') request.requestOptions.success([]) expect(@worker.resume.callCount).toBe(1) advanceClock(30000) expect(@worker.resume.callCount).toBe(2) it "handles the request as a success if we try and grab labels or folders and it includes the 'inbox'", -> spyOn(@worker, 'resume').andCallThrough() @worker.start() expect(@worker.resume.callCount).toBe(1) request = _.findWhere(@apiRequests, model: 'labels') request.requestOptions.success([{name: "inbox"}, {name: "archive"}]) expect(@worker.resume.callCount).toBe(1) advanceClock(30000) expect(@worker.resume.callCount).toBe(1) describe "delta streaming cursor", -> it "should read the cursor from the database, and the old config format", -> spyOn(NylasLongConnection.prototype, 'withCursor').andCallFake => @apiCursorStub = undefined # no cursor present worker = new NylasSyncWorker(@api, @account) connection = worker.connection() expect(connection.hasCursor()).toBe(false) advanceClock() expect(connection.hasCursor()).toBe(false) # cursor present in config spyOn(NylasEnv.config, 'get').andCallFake (key) => return 'old-school' if key is "<KEY>@account.<KEY>" return undefined worker = new NylasSyncWorker(@api, @account) connection = worker.connection() advanceClock() expect(connection.hasCursor()).toBe(true) expect(connection._config.getCursor()).toEqual('old-school') # cursor present in database, overrides cursor in config @apiCursorStub = "new-school" worker = new NylasSyncWorker(@api, @account) connection = worker.connection() expect(connection.hasCursor()).toBe(false) advanceClock() expect(connection.hasCursor()).toBe(true) expect(connection._config.getCursor()).toEqual('new-school') describe "when a count request completes", -> beforeEach -> @worker.start() advanceClock() @request = @apiRequests[0] @apiRequests = [] it "should update the count on the collection", -> @request.requestOptions.success({count: 1001}) nextState = @worker.state() expect(nextState.threads.count).toEqual(1001) describe "resume", -> it "should fetch metadata first and fetch other collections when metadata is ready", -> fetchAllMetadataCallback = null jasmine.unspy(NylasSyncWorker.prototype, 'fetchAllMetadata') spyOn(NylasSyncWorker.prototype, 'fetchAllMetadata').andCallFake (cb) => fetchAllMetadataCallback = cb spyOn(@worker, 'fetchCollection') @worker._state = {} @worker.resume() expect(@worker.fetchAllMetadata).toHaveBeenCalled() expect(@worker.fetchCollection.calls.length).toBe(0) fetchAllMetadataCallback() expect(@worker.fetchCollection.calls.length).not.toBe(0) it "should not fetch metadata pages if pluginsSupported is false", -> @api.pluginsSupported = false spyOn(NylasSyncWorker.prototype, '_fetchWithErrorHandling') spyOn(@worker, 'fetchCollection') @worker._state = {} @worker.resume() expect(@worker._fetchWithErrorHandling).not.toHaveBeenCalled() expect(@worker.fetchCollection.calls.length).not.toBe(0) it "should fetch collections for which `shouldFetchCollection` returns true", -> spyOn(@worker, 'fetchCollection') spyOn(@worker, 'shouldFetchCollection').andCallFake (collection) => return collection in ['threads', 'labels', 'drafts'] @worker.resume() expect(@worker.fetchCollection.calls.map (call) -> call.args[0]).toEqual(['threads', 'labels', 'drafts']) it "should be called when Actions.retrySync is received", -> spyOn(@worker, 'resume').andCallThrough() Actions.retrySync() expect(@worker.resume).toHaveBeenCalled() describe "shouldFetchCollection", -> it "should return false if the collection sync is already in progress", -> @worker._state.threads = { 'busy': true 'complete': false } expect(@worker.shouldFetchCollection('threads')).toBe(false) it "should return false if the collection sync is already complete", -> @worker._state.threads = { 'busy': false 'complete': true } expect(@worker.shouldFetchCollection('threads')).toBe(false) it "should return true otherwise", -> @worker._state.threads = { 'busy': false 'complete': false } expect(@worker.shouldFetchCollection('threads')).toBe(true) @worker._state.threads = undefined expect(@worker.shouldFetchCollection('threads')).toBe(true) describe "fetchCollection", -> beforeEach -> @apiRequests = [] it "should start the request for the model count", -> @worker._state.threads = { 'busy': false 'complete': false } @worker.fetchCollection('threads') expect(@apiRequests[0].requestOptions.path).toBe('/threads') expect(@apiRequests[0].requestOptions.qs.view).toBe('count') it "should pass any metadata it preloaded", -> @worker._state.threads = { 'busy': false 'complete': false } @worker.fetchCollection('threads') expect(@apiRequests[1].model).toBe('threads') expect(@apiRequests[1].requestOptions.metadataToAttach).toBe(@worker._metadata) describe "when there is not a previous page failure (`errorRequestRange`)", -> it "should start the first request for models", -> @worker._state.threads = { 'busy': false 'complete': false } @worker.fetchCollection('threads') expect(@apiRequests[1].model).toBe('threads') expect(@apiRequests[1].params.offset).toBe(0) describe "when there is a previous page failure (`errorRequestRange`)", -> beforeEach -> @worker._state.threads = 'count': 1200 'fetched': 100 'busy': false 'complete': false 'error': new Error("Something bad") 'errorRequestRange': offset: 100 limit: 50 it "should start paginating from the request that failed", -> @worker.fetchCollection('threads') expect(@apiRequests[0].model).toBe('threads') expect(@apiRequests[0].params.offset).toBe(100) expect(@apiRequests[0].params.limit).toBe(50) it "should not reset the `count`, `fetched` or start fetching the count", -> @worker.fetchCollection('threads') expect(@worker._state.threads.fetched).toBe(100) expect(@worker._state.threads.count).toBe(1200) expect(@apiRequests.length).toBe(1) describe 'when maxFetchCount option is specified', -> it "should only fetch maxFetch count on the first request if it is less than initialPageSize", -> @worker._state.messages = count: 1000 fetched: 0 @worker.fetchCollection('messages', {initialPageSize: 30, maxFetchCount: 25}) expect(@apiRequests[0].params.offset).toBe 0 expect(@apiRequests[0].params.limit).toBe 25 it "sould only fetch the maxFetchCount when restoring from saved state", -> @worker._state.messages = count: 1000 fetched: 470 errorRequestRange: { limit: 50, offset: 470, } @worker.fetchCollection('messages', {maxFetchCount: 500}) expect(@apiRequests[0].params.offset).toBe 470 expect(@apiRequests[0].params.limit).toBe 30 describe "fetchCollectionPage", -> beforeEach -> @apiRequests = [] describe 'when maxFetchCount option is specified', -> it 'should not fetch next page if maxFetchCount has been reached', -> @worker._state.messages = count: 1000 fetched: 470 @worker.fetchCollectionPage('messages', {limit: 30, offset: 470}, {maxFetchCount: 500}) {success} = @apiRequests[0].requestOptions success({length: 30}) expect(@worker._state.messages.fetched).toBe 500 advanceClock(2000) expect(@apiRequests.length).toBe 1 it 'should limit by maxFetchCount when requesting the next page', -> @worker._state.messages = count: 1000 fetched: 450 @worker.fetchCollectionPage('messages', {limit: 30, offset: 450 }, {maxFetchCount: 500}) {success} = @apiRequests[0].requestOptions success({length: 30}) expect(@worker._state.messages.fetched).toBe 480 advanceClock(2000) expect(@apiRequests[1].params.offset).toBe 480 expect(@apiRequests[1].params.limit).toBe 20 describe "when an API request completes", -> beforeEach -> @worker.start() advanceClock() @request = @apiRequests[1] @apiRequests = [] describe "successfully, with models", -> it "should start out by requesting a small number of items", -> expect(@request.params.limit).toBe NylasSyncWorker.INITIAL_PAGE_SIZE it "should request the next page", -> pageSize = @request.params.limit models = [] models.push(new Thread) for i in [0..(pageSize-1)] @request.requestOptions.success(models) advanceClock(2000) expect(@apiRequests.length).toBe(1) expect(@apiRequests[0].params.offset).toEqual @request.params.offset + pageSize it "increase the limit on the next page load by 50%", -> pageSize = @request.params.limit models = [] models.push(new Thread) for i in [0..(pageSize-1)] @request.requestOptions.success(models) advanceClock(2000) expect(@apiRequests.length).toBe(1) expect(@apiRequests[0].params.limit).toEqual pageSize * 1.5, it "never requests more then MAX_PAGE_SIZE", -> pageSize = @request.params.limit = NylasSyncWorker.MAX_PAGE_SIZE models = [] models.push(new Thread) for i in [0..(pageSize-1)] @request.requestOptions.success(models) advanceClock(2000) expect(@apiRequests.length).toBe(1) expect(@apiRequests[0].params.limit).toEqual NylasSyncWorker.MAX_PAGE_SIZE it "should update the fetched count on the collection", -> expect(@worker.state().threads.fetched).toEqual(0) pageSize = @request.params.limit models = [] models.push(new Thread) for i in [0..(pageSize-1)] @request.requestOptions.success(models) expect(@worker.state().threads.fetched).toEqual(pageSize) describe "successfully, with fewer models than requested", -> beforeEach -> models = [] models.push(new Thread) for i in [0..100] @request.requestOptions.success(models) it "should not request another page", -> expect(@apiRequests.length).toBe(0) it "should update the state to complete", -> expect(@worker.state().threads.busy).toEqual(false) expect(@worker.state().threads.complete).toEqual(true) it "should update the fetched count on the collection", -> expect(@worker.state().threads.fetched).toEqual(101) describe "successfully, with no models", -> it "should not request another page", -> @request.requestOptions.success([]) expect(@apiRequests.length).toBe(0) it "should update the state to complete", -> @request.requestOptions.success([]) expect(@worker.state().threads.busy).toEqual(false) expect(@worker.state().threads.complete).toEqual(true) describe "with an error", -> it "should log the error to the state, along with the range that failed", -> err = new Error("Oh no a network error") @request.requestOptions.error(err) expect(@worker.state().threads.busy).toEqual(false) expect(@worker.state().threads.complete).toEqual(false) expect(@worker.state().threads.error).toEqual(err.toString()) expect(@worker.state().threads.errorRequestRange).toEqual({offset: 0, limit: 30}) it "should not request another page", -> @request.requestOptions.error(new Error("Oh no a network error")) expect(@apiRequests.length).toBe(0) describe "succeeds after a previous error", -> beforeEach -> @worker._state.threads.error = new Error("Something bad happened") @worker._state.threads.errorRequestRange = {limit: 10, offset: 10} @request.requestOptions.success([]) advanceClock(1) it "should clear any previous error", -> expect(@worker.state().threads.error).toEqual(null) expect(@worker.state().threads.errorRequestRange).toEqual(null) describe "cleanup", -> it "should termiate the delta connection", -> spyOn(@connection, 'end') @worker.cleanup() expect(@connection.end).toHaveBeenCalled() it "should stop trying to restart failed collection syncs", -> spyOn(console, 'log') spyOn(@worker, 'resume').andCallThrough() @worker.cleanup() advanceClock(50000) expect(@worker.resume.callCount).toBe(0)
true
_ = require 'underscore' {Actions, DatabaseStore, DatabaseTransaction, Account, Thread} = require 'nylas-exports' NylasLongConnection = require '../lib/nylas-long-connection' NylasSyncWorker = require '../lib/nylas-sync-worker' describe "NylasSyncWorker", -> beforeEach -> @apiRequests = [] @api = APIRoot: 'https://api.nylas.com' pluginsSupported: true accessTokenForAccountId: => '123' makeRequest: (requestOptions) => @apiRequests.push({requestOptions}) getCollection: (account, model, params, requestOptions) => @apiRequests.push({account, model, params, requestOptions}) getThreads: (account, params, requestOptions) => @apiRequests.push({account, model:'threads', params, requestOptions}) @apiCursorStub = undefined spyOn(NylasSyncWorker.prototype, 'fetchAllMetadata').andCallFake (cb) -> cb() spyOn(DatabaseTransaction.prototype, 'persistJSONBlob').andReturn(Promise.resolve()) spyOn(DatabaseStore, 'findJSONBlob').andCallFake (key) => if key is "NyPI:KEY:<KEY>END_PI{TEST_ACCOUNT_ID}" return Promise.resolve _.extend {}, { "cursor": @apiCursorStub "contacts": busy: true complete: false "calendars": busy:false complete: true } else if key.indexOf('ContactRankings') is 0 return Promise.resolve([]) else return throw new Error("Not stubbed! #{key}") @account = new Account(clientId: TEST_ACCOUNT_CLIENT_ID, serverId: TEST_ACCOUNT_ID, organizationUnit: 'label') @worker = new NylasSyncWorker(@api, @account) @worker._metadata = {"a": [{"id":"b"}]} @connection = @worker.connection() spyOn(@connection, 'start') advanceClock() it "should reset `busy` to false when reading state from disk", -> @worker = new NylasSyncWorker(@api, @account) spyOn(@worker, 'resume') advanceClock() expect(@worker.state().contacts.busy).toEqual(false) describe "start", -> it "should open the delta connection", -> @worker.start() advanceClock() expect(@connection.start).toHaveBeenCalled() it "should start querying for model collections and counts that haven't been fully cached", -> @worker.start() advanceClock() expect(@apiRequests.length).toBe(12) modelsRequested = _.compact _.map @apiRequests, ({model}) -> model expect(modelsRequested).toEqual(['threads', 'messages', 'labels', 'drafts', 'contacts', 'events']) countsRequested = _.compact _.map @apiRequests, ({requestOptions}) -> if requestOptions.qs?.view is 'count' return requestOptions.path expect(modelsRequested).toEqual(['threads', 'messages', 'labels', 'drafts', 'contacts', 'events']) expect(countsRequested).toEqual(['/threads', '/messages', '/labels', '/drafts', '/contacts', '/events']) it "should fetch 1000 labels and folders, to prevent issues where Inbox is not in the first page", -> labelsRequest = _.find @apiRequests, (r) -> r.model is 'labels' expect(labelsRequest.params.limit).toBe(1000) it "should mark incomplete collections as `busy`", -> @worker.start() advanceClock() nextState = @worker.state() for collection in ['contacts','threads','drafts', 'labels'] expect(nextState[collection].busy).toEqual(true) it "should initialize count and fetched to 0", -> @worker.start() advanceClock() nextState = @worker.state() for collection in ['contacts','threads','drafts', 'labels'] expect(nextState[collection].fetched).toEqual(0) expect(nextState[collection].count).toEqual(0) it "after failures, it should attempt to resume periodically but back off as failures continue", -> simulateNetworkFailure = => @apiRequests[1].requestOptions.error({statusCode: 400}) @apiRequests = [] spyOn(@worker, 'resume').andCallThrough() @worker.start() expect(@worker.resume.callCount).toBe(1) simulateNetworkFailure(); expect(@worker.resume.callCount).toBe(1) advanceClock(4000); expect(@worker.resume.callCount).toBe(2) simulateNetworkFailure(); expect(@worker.resume.callCount).toBe(2) advanceClock(4000); expect(@worker.resume.callCount).toBe(2) advanceClock(4000); expect(@worker.resume.callCount).toBe(3) simulateNetworkFailure(); expect(@worker.resume.callCount).toBe(3) advanceClock(4000); expect(@worker.resume.callCount).toBe(3) advanceClock(4000); expect(@worker.resume.callCount).toBe(3) advanceClock(4000); expect(@worker.resume.callCount).toBe(4) simulateNetworkFailure(); expect(@worker.resume.callCount).toBe(4) advanceClock(4000); expect(@worker.resume.callCount).toBe(4) advanceClock(4000); expect(@worker.resume.callCount).toBe(4) advanceClock(4000); expect(@worker.resume.callCount).toBe(4) advanceClock(4000); expect(@worker.resume.callCount).toBe(4) advanceClock(4000); expect(@worker.resume.callCount).toBe(5) it "handles the request as a failure if we try and grab labels or folders without an 'inbox'", -> spyOn(@worker, 'resume').andCallThrough() @worker.start() expect(@worker.resume.callCount).toBe(1) request = _.findWhere(@apiRequests, model: 'labels') request.requestOptions.success([]) expect(@worker.resume.callCount).toBe(1) advanceClock(30000) expect(@worker.resume.callCount).toBe(2) it "handles the request as a success if we try and grab labels or folders and it includes the 'inbox'", -> spyOn(@worker, 'resume').andCallThrough() @worker.start() expect(@worker.resume.callCount).toBe(1) request = _.findWhere(@apiRequests, model: 'labels') request.requestOptions.success([{name: "inbox"}, {name: "archive"}]) expect(@worker.resume.callCount).toBe(1) advanceClock(30000) expect(@worker.resume.callCount).toBe(1) describe "delta streaming cursor", -> it "should read the cursor from the database, and the old config format", -> spyOn(NylasLongConnection.prototype, 'withCursor').andCallFake => @apiCursorStub = undefined # no cursor present worker = new NylasSyncWorker(@api, @account) connection = worker.connection() expect(connection.hasCursor()).toBe(false) advanceClock() expect(connection.hasCursor()).toBe(false) # cursor present in config spyOn(NylasEnv.config, 'get').andCallFake (key) => return 'old-school' if key is "PI:KEY:<KEY>END_PI@account.PI:KEY:<KEY>END_PI" return undefined worker = new NylasSyncWorker(@api, @account) connection = worker.connection() advanceClock() expect(connection.hasCursor()).toBe(true) expect(connection._config.getCursor()).toEqual('old-school') # cursor present in database, overrides cursor in config @apiCursorStub = "new-school" worker = new NylasSyncWorker(@api, @account) connection = worker.connection() expect(connection.hasCursor()).toBe(false) advanceClock() expect(connection.hasCursor()).toBe(true) expect(connection._config.getCursor()).toEqual('new-school') describe "when a count request completes", -> beforeEach -> @worker.start() advanceClock() @request = @apiRequests[0] @apiRequests = [] it "should update the count on the collection", -> @request.requestOptions.success({count: 1001}) nextState = @worker.state() expect(nextState.threads.count).toEqual(1001) describe "resume", -> it "should fetch metadata first and fetch other collections when metadata is ready", -> fetchAllMetadataCallback = null jasmine.unspy(NylasSyncWorker.prototype, 'fetchAllMetadata') spyOn(NylasSyncWorker.prototype, 'fetchAllMetadata').andCallFake (cb) => fetchAllMetadataCallback = cb spyOn(@worker, 'fetchCollection') @worker._state = {} @worker.resume() expect(@worker.fetchAllMetadata).toHaveBeenCalled() expect(@worker.fetchCollection.calls.length).toBe(0) fetchAllMetadataCallback() expect(@worker.fetchCollection.calls.length).not.toBe(0) it "should not fetch metadata pages if pluginsSupported is false", -> @api.pluginsSupported = false spyOn(NylasSyncWorker.prototype, '_fetchWithErrorHandling') spyOn(@worker, 'fetchCollection') @worker._state = {} @worker.resume() expect(@worker._fetchWithErrorHandling).not.toHaveBeenCalled() expect(@worker.fetchCollection.calls.length).not.toBe(0) it "should fetch collections for which `shouldFetchCollection` returns true", -> spyOn(@worker, 'fetchCollection') spyOn(@worker, 'shouldFetchCollection').andCallFake (collection) => return collection in ['threads', 'labels', 'drafts'] @worker.resume() expect(@worker.fetchCollection.calls.map (call) -> call.args[0]).toEqual(['threads', 'labels', 'drafts']) it "should be called when Actions.retrySync is received", -> spyOn(@worker, 'resume').andCallThrough() Actions.retrySync() expect(@worker.resume).toHaveBeenCalled() describe "shouldFetchCollection", -> it "should return false if the collection sync is already in progress", -> @worker._state.threads = { 'busy': true 'complete': false } expect(@worker.shouldFetchCollection('threads')).toBe(false) it "should return false if the collection sync is already complete", -> @worker._state.threads = { 'busy': false 'complete': true } expect(@worker.shouldFetchCollection('threads')).toBe(false) it "should return true otherwise", -> @worker._state.threads = { 'busy': false 'complete': false } expect(@worker.shouldFetchCollection('threads')).toBe(true) @worker._state.threads = undefined expect(@worker.shouldFetchCollection('threads')).toBe(true) describe "fetchCollection", -> beforeEach -> @apiRequests = [] it "should start the request for the model count", -> @worker._state.threads = { 'busy': false 'complete': false } @worker.fetchCollection('threads') expect(@apiRequests[0].requestOptions.path).toBe('/threads') expect(@apiRequests[0].requestOptions.qs.view).toBe('count') it "should pass any metadata it preloaded", -> @worker._state.threads = { 'busy': false 'complete': false } @worker.fetchCollection('threads') expect(@apiRequests[1].model).toBe('threads') expect(@apiRequests[1].requestOptions.metadataToAttach).toBe(@worker._metadata) describe "when there is not a previous page failure (`errorRequestRange`)", -> it "should start the first request for models", -> @worker._state.threads = { 'busy': false 'complete': false } @worker.fetchCollection('threads') expect(@apiRequests[1].model).toBe('threads') expect(@apiRequests[1].params.offset).toBe(0) describe "when there is a previous page failure (`errorRequestRange`)", -> beforeEach -> @worker._state.threads = 'count': 1200 'fetched': 100 'busy': false 'complete': false 'error': new Error("Something bad") 'errorRequestRange': offset: 100 limit: 50 it "should start paginating from the request that failed", -> @worker.fetchCollection('threads') expect(@apiRequests[0].model).toBe('threads') expect(@apiRequests[0].params.offset).toBe(100) expect(@apiRequests[0].params.limit).toBe(50) it "should not reset the `count`, `fetched` or start fetching the count", -> @worker.fetchCollection('threads') expect(@worker._state.threads.fetched).toBe(100) expect(@worker._state.threads.count).toBe(1200) expect(@apiRequests.length).toBe(1) describe 'when maxFetchCount option is specified', -> it "should only fetch maxFetch count on the first request if it is less than initialPageSize", -> @worker._state.messages = count: 1000 fetched: 0 @worker.fetchCollection('messages', {initialPageSize: 30, maxFetchCount: 25}) expect(@apiRequests[0].params.offset).toBe 0 expect(@apiRequests[0].params.limit).toBe 25 it "sould only fetch the maxFetchCount when restoring from saved state", -> @worker._state.messages = count: 1000 fetched: 470 errorRequestRange: { limit: 50, offset: 470, } @worker.fetchCollection('messages', {maxFetchCount: 500}) expect(@apiRequests[0].params.offset).toBe 470 expect(@apiRequests[0].params.limit).toBe 30 describe "fetchCollectionPage", -> beforeEach -> @apiRequests = [] describe 'when maxFetchCount option is specified', -> it 'should not fetch next page if maxFetchCount has been reached', -> @worker._state.messages = count: 1000 fetched: 470 @worker.fetchCollectionPage('messages', {limit: 30, offset: 470}, {maxFetchCount: 500}) {success} = @apiRequests[0].requestOptions success({length: 30}) expect(@worker._state.messages.fetched).toBe 500 advanceClock(2000) expect(@apiRequests.length).toBe 1 it 'should limit by maxFetchCount when requesting the next page', -> @worker._state.messages = count: 1000 fetched: 450 @worker.fetchCollectionPage('messages', {limit: 30, offset: 450 }, {maxFetchCount: 500}) {success} = @apiRequests[0].requestOptions success({length: 30}) expect(@worker._state.messages.fetched).toBe 480 advanceClock(2000) expect(@apiRequests[1].params.offset).toBe 480 expect(@apiRequests[1].params.limit).toBe 20 describe "when an API request completes", -> beforeEach -> @worker.start() advanceClock() @request = @apiRequests[1] @apiRequests = [] describe "successfully, with models", -> it "should start out by requesting a small number of items", -> expect(@request.params.limit).toBe NylasSyncWorker.INITIAL_PAGE_SIZE it "should request the next page", -> pageSize = @request.params.limit models = [] models.push(new Thread) for i in [0..(pageSize-1)] @request.requestOptions.success(models) advanceClock(2000) expect(@apiRequests.length).toBe(1) expect(@apiRequests[0].params.offset).toEqual @request.params.offset + pageSize it "increase the limit on the next page load by 50%", -> pageSize = @request.params.limit models = [] models.push(new Thread) for i in [0..(pageSize-1)] @request.requestOptions.success(models) advanceClock(2000) expect(@apiRequests.length).toBe(1) expect(@apiRequests[0].params.limit).toEqual pageSize * 1.5, it "never requests more then MAX_PAGE_SIZE", -> pageSize = @request.params.limit = NylasSyncWorker.MAX_PAGE_SIZE models = [] models.push(new Thread) for i in [0..(pageSize-1)] @request.requestOptions.success(models) advanceClock(2000) expect(@apiRequests.length).toBe(1) expect(@apiRequests[0].params.limit).toEqual NylasSyncWorker.MAX_PAGE_SIZE it "should update the fetched count on the collection", -> expect(@worker.state().threads.fetched).toEqual(0) pageSize = @request.params.limit models = [] models.push(new Thread) for i in [0..(pageSize-1)] @request.requestOptions.success(models) expect(@worker.state().threads.fetched).toEqual(pageSize) describe "successfully, with fewer models than requested", -> beforeEach -> models = [] models.push(new Thread) for i in [0..100] @request.requestOptions.success(models) it "should not request another page", -> expect(@apiRequests.length).toBe(0) it "should update the state to complete", -> expect(@worker.state().threads.busy).toEqual(false) expect(@worker.state().threads.complete).toEqual(true) it "should update the fetched count on the collection", -> expect(@worker.state().threads.fetched).toEqual(101) describe "successfully, with no models", -> it "should not request another page", -> @request.requestOptions.success([]) expect(@apiRequests.length).toBe(0) it "should update the state to complete", -> @request.requestOptions.success([]) expect(@worker.state().threads.busy).toEqual(false) expect(@worker.state().threads.complete).toEqual(true) describe "with an error", -> it "should log the error to the state, along with the range that failed", -> err = new Error("Oh no a network error") @request.requestOptions.error(err) expect(@worker.state().threads.busy).toEqual(false) expect(@worker.state().threads.complete).toEqual(false) expect(@worker.state().threads.error).toEqual(err.toString()) expect(@worker.state().threads.errorRequestRange).toEqual({offset: 0, limit: 30}) it "should not request another page", -> @request.requestOptions.error(new Error("Oh no a network error")) expect(@apiRequests.length).toBe(0) describe "succeeds after a previous error", -> beforeEach -> @worker._state.threads.error = new Error("Something bad happened") @worker._state.threads.errorRequestRange = {limit: 10, offset: 10} @request.requestOptions.success([]) advanceClock(1) it "should clear any previous error", -> expect(@worker.state().threads.error).toEqual(null) expect(@worker.state().threads.errorRequestRange).toEqual(null) describe "cleanup", -> it "should termiate the delta connection", -> spyOn(@connection, 'end') @worker.cleanup() expect(@connection.end).toHaveBeenCalled() it "should stop trying to restart failed collection syncs", -> spyOn(console, 'log') spyOn(@worker, 'resume').andCallThrough() @worker.cleanup() advanceClock(50000) expect(@worker.resume.callCount).toBe(0)
[ { "context": " of heartbeats\n authDigest = new Buffer([@get('username'), @get('password')].join(':'))\n .toString('", "end": 2991, "score": 0.9217311143875122, "start": 2983, "tag": "USERNAME", "value": "username" }, { "context": "rest/#{resource}\"\n auth:\n user: @get('username')\n pass: @get('password')\n @log 'verbos", "end": 3976, "score": 0.9782193899154663, "start": 3968, "tag": "USERNAME", "value": "username" }, { "context": " user: @get('username')\n pass: @get('password')\n @log 'verbose', \"Making request: #{JSON.str", "end": 4007, "score": 0.8233286142349243, "start": 3999, "tag": "PASSWORD", "value": "password" } ]
lib/adapters/isy/IsyAPI.coffee
monitron/jarvis-ha
1
_ = require('underscore') Q = require('q') Backbone = require('backbone') xml2js = require('xml2js') request = require('request') winston = require('winston') WebSocketClient = require('websocket').client module.exports = class IsyAPI extends Backbone.Model defaults: commandTimeout: 10000 initialize: -> @_pendingCommands = {} connect: -> @_subscribe() getNodes: -> deferred = Q.defer() @_request('nodes') .then (data) => nodes = for node in data.nodes.node address: node.address[0] name: node.name[0] type: node.type[0].split('.').map((x) -> parseInt(x)) properties: _.object(for prop in node.property [prop['$'].id, prop['$'].value]) deferred.resolve nodes .fail (err) => deferred.reject err .done() deferred.promise executeCommand: (node, command, args = [], expectResponse = true) -> @log 'verbose', "Command for #{node}: #{command} [#{args.join(', ')}] - " + (if expectResponse then "will await response" else "set and forget") deferred = Q.defer() req = @_request(['nodes', node, 'cmd', command].concat(args).join('/')) .fail (err) => deferred.reject err if expectResponse # If there already was a command pending for this node, mark it failed # (is this wise?) if @_pendingCommands[node]? @log 'debug', "Command superceded for #{node}" @_pendingCommands[node].reject 'superceded' # Add command as pending so it gets resolved when an update arrives @_pendingCommands[node] = deferred # Set a timeout so we notice if the update never happens cleanUpFailure = => @log 'debug', "Command timed out for #{node}" delete @_pendingCommands[node] deferred.reject 'timeout' timeout = setTimeout cleanUpFailure, @get('commandTimeout') # The timeout must go away when the update arrives deferred.promise.then => clearTimeout(timeout) else # No response expected req.done -> deferred.resolve() # Resolve when command sending succeeds deferred.promise log: (level, message) -> winston.log level, "[IsyAPI] #{message}" _processSubscriptionMessage: (msg) -> xml2js.Parser().parseString msg.utf8Data, (err, data) => if err? @log 'debug', "Unable to XML parse subscription message: #{msg}" else if data.Event? and data.Event.control[0][0] != '_' # Not an internal message node = data.Event.node[0] update = node: node property: data.Event.control[0] value: data.Event.action[0] @log 'verbose', "Dispatching property update #{JSON.stringify(update)}" @trigger 'property-update', update if @_pendingCommands[node]? @_pendingCommands[node].resolve() delete @_pendingCommands[node] _subscribe: -> # XXX Notice lack of heartbeats authDigest = new Buffer([@get('username'), @get('password')].join(':')) .toString('base64') socket = new WebSocketClient() socket.on 'connect', (connection) => @log 'debug', 'Subscription successful' @trigger 'connected' @_connection = connection connection.on 'message', (msg) => @_processSubscriptionMessage(msg) connection.on 'close', (reason, desc) => @log 'warn', "Subscription disconnected (#{reason}; #{desc})" @trigger 'disconnected' # XXX Reconnect? socket.on 'connectFailed', (error) => @log 'warn', "Susbscription failed (#{error})" # XXX Try again? @trigger 'error' @trigger 'disconnected' socket.connect( "ws://#{@get('host')}/rest/subscribe", 'ISYSUB', 'com.universal-devices.websockets.isy', {Authorization: 'Basic ' + authDigest}) _request: (resource) -> deferred = Q.defer() options = url: "http://#{@get('host')}/rest/#{resource}" auth: user: @get('username') pass: @get('password') @log 'verbose', "Making request: #{JSON.stringify(options)}" callback = (err, res, body) => if err @log 'error', "Request of #{resource} failed: #{err}" deferred.reject err else xml2js.Parser().parseString body, (err, data) => if err? @log 'warn', "Failed to parse XML: #{body}" deferred.reject err else deferred.resolve data request options, callback deferred.promise
32558
_ = require('underscore') Q = require('q') Backbone = require('backbone') xml2js = require('xml2js') request = require('request') winston = require('winston') WebSocketClient = require('websocket').client module.exports = class IsyAPI extends Backbone.Model defaults: commandTimeout: 10000 initialize: -> @_pendingCommands = {} connect: -> @_subscribe() getNodes: -> deferred = Q.defer() @_request('nodes') .then (data) => nodes = for node in data.nodes.node address: node.address[0] name: node.name[0] type: node.type[0].split('.').map((x) -> parseInt(x)) properties: _.object(for prop in node.property [prop['$'].id, prop['$'].value]) deferred.resolve nodes .fail (err) => deferred.reject err .done() deferred.promise executeCommand: (node, command, args = [], expectResponse = true) -> @log 'verbose', "Command for #{node}: #{command} [#{args.join(', ')}] - " + (if expectResponse then "will await response" else "set and forget") deferred = Q.defer() req = @_request(['nodes', node, 'cmd', command].concat(args).join('/')) .fail (err) => deferred.reject err if expectResponse # If there already was a command pending for this node, mark it failed # (is this wise?) if @_pendingCommands[node]? @log 'debug', "Command superceded for #{node}" @_pendingCommands[node].reject 'superceded' # Add command as pending so it gets resolved when an update arrives @_pendingCommands[node] = deferred # Set a timeout so we notice if the update never happens cleanUpFailure = => @log 'debug', "Command timed out for #{node}" delete @_pendingCommands[node] deferred.reject 'timeout' timeout = setTimeout cleanUpFailure, @get('commandTimeout') # The timeout must go away when the update arrives deferred.promise.then => clearTimeout(timeout) else # No response expected req.done -> deferred.resolve() # Resolve when command sending succeeds deferred.promise log: (level, message) -> winston.log level, "[IsyAPI] #{message}" _processSubscriptionMessage: (msg) -> xml2js.Parser().parseString msg.utf8Data, (err, data) => if err? @log 'debug', "Unable to XML parse subscription message: #{msg}" else if data.Event? and data.Event.control[0][0] != '_' # Not an internal message node = data.Event.node[0] update = node: node property: data.Event.control[0] value: data.Event.action[0] @log 'verbose', "Dispatching property update #{JSON.stringify(update)}" @trigger 'property-update', update if @_pendingCommands[node]? @_pendingCommands[node].resolve() delete @_pendingCommands[node] _subscribe: -> # XXX Notice lack of heartbeats authDigest = new Buffer([@get('username'), @get('password')].join(':')) .toString('base64') socket = new WebSocketClient() socket.on 'connect', (connection) => @log 'debug', 'Subscription successful' @trigger 'connected' @_connection = connection connection.on 'message', (msg) => @_processSubscriptionMessage(msg) connection.on 'close', (reason, desc) => @log 'warn', "Subscription disconnected (#{reason}; #{desc})" @trigger 'disconnected' # XXX Reconnect? socket.on 'connectFailed', (error) => @log 'warn', "Susbscription failed (#{error})" # XXX Try again? @trigger 'error' @trigger 'disconnected' socket.connect( "ws://#{@get('host')}/rest/subscribe", 'ISYSUB', 'com.universal-devices.websockets.isy', {Authorization: 'Basic ' + authDigest}) _request: (resource) -> deferred = Q.defer() options = url: "http://#{@get('host')}/rest/#{resource}" auth: user: @get('username') pass: @get('<PASSWORD>') @log 'verbose', "Making request: #{JSON.stringify(options)}" callback = (err, res, body) => if err @log 'error', "Request of #{resource} failed: #{err}" deferred.reject err else xml2js.Parser().parseString body, (err, data) => if err? @log 'warn', "Failed to parse XML: #{body}" deferred.reject err else deferred.resolve data request options, callback deferred.promise
true
_ = require('underscore') Q = require('q') Backbone = require('backbone') xml2js = require('xml2js') request = require('request') winston = require('winston') WebSocketClient = require('websocket').client module.exports = class IsyAPI extends Backbone.Model defaults: commandTimeout: 10000 initialize: -> @_pendingCommands = {} connect: -> @_subscribe() getNodes: -> deferred = Q.defer() @_request('nodes') .then (data) => nodes = for node in data.nodes.node address: node.address[0] name: node.name[0] type: node.type[0].split('.').map((x) -> parseInt(x)) properties: _.object(for prop in node.property [prop['$'].id, prop['$'].value]) deferred.resolve nodes .fail (err) => deferred.reject err .done() deferred.promise executeCommand: (node, command, args = [], expectResponse = true) -> @log 'verbose', "Command for #{node}: #{command} [#{args.join(', ')}] - " + (if expectResponse then "will await response" else "set and forget") deferred = Q.defer() req = @_request(['nodes', node, 'cmd', command].concat(args).join('/')) .fail (err) => deferred.reject err if expectResponse # If there already was a command pending for this node, mark it failed # (is this wise?) if @_pendingCommands[node]? @log 'debug', "Command superceded for #{node}" @_pendingCommands[node].reject 'superceded' # Add command as pending so it gets resolved when an update arrives @_pendingCommands[node] = deferred # Set a timeout so we notice if the update never happens cleanUpFailure = => @log 'debug', "Command timed out for #{node}" delete @_pendingCommands[node] deferred.reject 'timeout' timeout = setTimeout cleanUpFailure, @get('commandTimeout') # The timeout must go away when the update arrives deferred.promise.then => clearTimeout(timeout) else # No response expected req.done -> deferred.resolve() # Resolve when command sending succeeds deferred.promise log: (level, message) -> winston.log level, "[IsyAPI] #{message}" _processSubscriptionMessage: (msg) -> xml2js.Parser().parseString msg.utf8Data, (err, data) => if err? @log 'debug', "Unable to XML parse subscription message: #{msg}" else if data.Event? and data.Event.control[0][0] != '_' # Not an internal message node = data.Event.node[0] update = node: node property: data.Event.control[0] value: data.Event.action[0] @log 'verbose', "Dispatching property update #{JSON.stringify(update)}" @trigger 'property-update', update if @_pendingCommands[node]? @_pendingCommands[node].resolve() delete @_pendingCommands[node] _subscribe: -> # XXX Notice lack of heartbeats authDigest = new Buffer([@get('username'), @get('password')].join(':')) .toString('base64') socket = new WebSocketClient() socket.on 'connect', (connection) => @log 'debug', 'Subscription successful' @trigger 'connected' @_connection = connection connection.on 'message', (msg) => @_processSubscriptionMessage(msg) connection.on 'close', (reason, desc) => @log 'warn', "Subscription disconnected (#{reason}; #{desc})" @trigger 'disconnected' # XXX Reconnect? socket.on 'connectFailed', (error) => @log 'warn', "Susbscription failed (#{error})" # XXX Try again? @trigger 'error' @trigger 'disconnected' socket.connect( "ws://#{@get('host')}/rest/subscribe", 'ISYSUB', 'com.universal-devices.websockets.isy', {Authorization: 'Basic ' + authDigest}) _request: (resource) -> deferred = Q.defer() options = url: "http://#{@get('host')}/rest/#{resource}" auth: user: @get('username') pass: @get('PI:PASSWORD:<PASSWORD>END_PI') @log 'verbose', "Making request: #{JSON.stringify(options)}" callback = (err, res, body) => if err @log 'error', "Request of #{resource} failed: #{err}" deferred.reject err else xml2js.Parser().parseString body, (err, data) => if err? @log 'warn', "Failed to parse XML: #{body}" deferred.reject err else deferred.resolve data request options, callback deferred.promise
[ { "context": "ach ->\n @view.$('.submit-inquiry-name').val 'Foo Bar'\n @view.$('.submit-inquiry-email').val 'foo@", "end": 1431, "score": 0.9938153028488159, "start": 1424, "tag": "NAME", "value": "Foo Bar" }, { "context": " Bar'\n @view.$('.submit-inquiry-email').val 'foo@bar.com'\n @view.$('.submit-inquiry-message').val 'I ", "end": 1488, "score": 0.9998865127563477, "start": 1477, "tag": "EMAIL", "value": "foo@bar.com" }, { "context": "alize the form input', ->\n output = { name: 'Foo Bar', email: 'foo@bar.com', message: 'I like this foo", "end": 1647, "score": 0.9773794412612915, "start": 1640, "tag": "NAME", "value": "Foo Bar" }, { "context": "ut', ->\n output = { name: 'Foo Bar', email: 'foo@bar.com', message: 'I like this foo for its barring.' }\n ", "end": 1669, "score": 0.9998964071273804, "start": 1658, "tag": "EMAIL", "value": "foo@bar.com" }, { "context": " 'set'\n @view.$('.submit-inquiry-name').val 'Foo Bar'\n @view.$('.submit-inquiry-email').val 'foo@", "end": 1951, "score": 0.9972038865089417, "start": 1944, "tag": "NAME", "value": "Foo Bar" }, { "context": " Bar'\n @view.$('.submit-inquiry-email').val 'foo@bar.com'\n @view.$('.submit-inquiry-message').val 'I ", "end": 2008, "score": 0.9999223947525024, "start": 1997, "tag": "EMAIL", "value": "foo@bar.com" }, { "context": " @view.inquiry.set.args[0][0].name.should.equal 'Foo Bar'\n @view.inquiry.set.args[0][0].email.should.", "end": 2198, "score": 0.9982507228851318, "start": 2191, "tag": "NAME", "value": "Foo Bar" }, { "context": " @view.inquiry.set.args[0][0].email.should.equal 'foo@bar.com'\n @view.inquiry.set.args[0][0].message.shoul", "end": 2266, "score": 0.9999231100082397, "start": 2255, "tag": "EMAIL", "value": "foo@bar.com" }, { "context": "e on success', ->\n @view.inquiry.set email: 'foo@bar.com', name: 'foo'\n sinon.stub(@view.inquiry, 'sa", "end": 2459, "score": 0.9999215006828308, "start": 2448, "tag": "EMAIL", "value": "foo@bar.com" }, { "context": " @view.inquiry.set email: 'foo@bar.com', name: 'foo'\n sinon.stub(@view.inquiry, 'save').yieldsTo", "end": 2472, "score": 0.9913119673728943, "start": 2469, "tag": "NAME", "value": "foo" } ]
src/mobile/apps/artwork/components/bid/test/client/ask_specialist.coffee
kanaabe/force
1
_ = require 'underscore' sinon = require 'sinon' Backbone = require 'backbone' Artwork = require '../../../../../../models/artwork' Profile = require '../../../../../../models/profile' CurrentUser = require '../../../../../../models/current_user' benv = require 'benv' { fabricate } = require 'antigravity' { resolve } = require 'path' SubmitInquiryView = null describe 'SubmitInquiryView', -> beforeEach (done) -> artists = [ fabricate 'artist' ] @artwork = fabricate('artwork', image: { url: 'artwork.png' }, artists: artists) benv.setup => benv.expose { $: benv.require 'jquery' } Backbone.$ = $ benv.render resolve(__dirname, '../../../../templates/ask_specialist_page.jade'), { artwork: @artwork profile: new Profile(fabricate 'profile') sd: {} asset: (->) }, => SubmitInquiryView = benv.requireWithJadeify( resolve(__dirname, '../../client/ask_specialist'), ['formTemplate', 'confirmationTemplate'] ) SubmitInquiryView.__set__ 'Cookies', { set: (->), get: (->) } sinon.stub Backbone, 'sync' @view = new SubmitInquiryView el: $ 'body' model: new Artwork @artwork sessionID: 'foobar' done() afterEach -> benv.teardown() Backbone.sync.restore() describe '#serializeForm', -> beforeEach -> @view.$('.submit-inquiry-name').val 'Foo Bar' @view.$('.submit-inquiry-email').val 'foo@bar.com' @view.$('.submit-inquiry-message').val 'I like this foo for its barring.' it 'should serialize the form input', -> output = { name: 'Foo Bar', email: 'foo@bar.com', message: 'I like this foo for its barring.' } _.isEqual(@view.serializeForm(), output).should.be.ok() describe '#submitInquiry', -> it 'submits a new inquiry from the view', -> sinon.stub @view.inquiry, 'set' @view.$('.submit-inquiry-name').val 'Foo Bar' @view.$('.submit-inquiry-email').val 'foo@bar.com' @view.$('.submit-inquiry-message').val 'I like this foo for its barring.' @view.$('.submit-inquiry-form').submit() @view.inquiry.set.args[0][0].name.should.equal 'Foo Bar' @view.inquiry.set.args[0][0].email.should.equal 'foo@bar.com' @view.inquiry.set.args[0][0].message.should.equal 'I like this foo for its barring.' it 'should render a success message on success', -> @view.inquiry.set email: 'foo@bar.com', name: 'foo' sinon.stub(@view.inquiry, 'save').yieldsTo('success') sinon.stub @view.$el, 'html' @view.$('.submit-inquiry-form').submit() @view.$el.html.args[0][0].should.containEql 'message has been sent' it 'should render an error message on error', -> sinon.stub(@view.inquiry, 'save').yieldsTo('error') sinon.stub @view.$el, 'html' @view.inquiry.validate = sinon.stub() @view.$('.submit-inquiry-form').submit() @view.$el.html.args[0][0].should.containEql 'Sorry, there was an error' it 'sets the referring url, landing_url, and inquiry_url', -> sinon.stub @view.inquiry, 'set' SubmitInquiryView.__get__('Cookies').get = (key) -> switch key when 'inquiry-referrer' then 'foo/bar' when 'inquiry-session-start' then 'baz/bam' global.location.pathname = 'foo/bar' @view.submitInquiry { preventDefault: sinon.stub() } @view.inquiry.set.args[0][0].referring_url.should.containEql 'foo/bar' @view.inquiry.set.args[0][0].landing_url.should.containEql 'baz/bam'
19282
_ = require 'underscore' sinon = require 'sinon' Backbone = require 'backbone' Artwork = require '../../../../../../models/artwork' Profile = require '../../../../../../models/profile' CurrentUser = require '../../../../../../models/current_user' benv = require 'benv' { fabricate } = require 'antigravity' { resolve } = require 'path' SubmitInquiryView = null describe 'SubmitInquiryView', -> beforeEach (done) -> artists = [ fabricate 'artist' ] @artwork = fabricate('artwork', image: { url: 'artwork.png' }, artists: artists) benv.setup => benv.expose { $: benv.require 'jquery' } Backbone.$ = $ benv.render resolve(__dirname, '../../../../templates/ask_specialist_page.jade'), { artwork: @artwork profile: new Profile(fabricate 'profile') sd: {} asset: (->) }, => SubmitInquiryView = benv.requireWithJadeify( resolve(__dirname, '../../client/ask_specialist'), ['formTemplate', 'confirmationTemplate'] ) SubmitInquiryView.__set__ 'Cookies', { set: (->), get: (->) } sinon.stub Backbone, 'sync' @view = new SubmitInquiryView el: $ 'body' model: new Artwork @artwork sessionID: 'foobar' done() afterEach -> benv.teardown() Backbone.sync.restore() describe '#serializeForm', -> beforeEach -> @view.$('.submit-inquiry-name').val '<NAME>' @view.$('.submit-inquiry-email').val '<EMAIL>' @view.$('.submit-inquiry-message').val 'I like this foo for its barring.' it 'should serialize the form input', -> output = { name: '<NAME>', email: '<EMAIL>', message: 'I like this foo for its barring.' } _.isEqual(@view.serializeForm(), output).should.be.ok() describe '#submitInquiry', -> it 'submits a new inquiry from the view', -> sinon.stub @view.inquiry, 'set' @view.$('.submit-inquiry-name').val '<NAME>' @view.$('.submit-inquiry-email').val '<EMAIL>' @view.$('.submit-inquiry-message').val 'I like this foo for its barring.' @view.$('.submit-inquiry-form').submit() @view.inquiry.set.args[0][0].name.should.equal '<NAME>' @view.inquiry.set.args[0][0].email.should.equal '<EMAIL>' @view.inquiry.set.args[0][0].message.should.equal 'I like this foo for its barring.' it 'should render a success message on success', -> @view.inquiry.set email: '<EMAIL>', name: '<NAME>' sinon.stub(@view.inquiry, 'save').yieldsTo('success') sinon.stub @view.$el, 'html' @view.$('.submit-inquiry-form').submit() @view.$el.html.args[0][0].should.containEql 'message has been sent' it 'should render an error message on error', -> sinon.stub(@view.inquiry, 'save').yieldsTo('error') sinon.stub @view.$el, 'html' @view.inquiry.validate = sinon.stub() @view.$('.submit-inquiry-form').submit() @view.$el.html.args[0][0].should.containEql 'Sorry, there was an error' it 'sets the referring url, landing_url, and inquiry_url', -> sinon.stub @view.inquiry, 'set' SubmitInquiryView.__get__('Cookies').get = (key) -> switch key when 'inquiry-referrer' then 'foo/bar' when 'inquiry-session-start' then 'baz/bam' global.location.pathname = 'foo/bar' @view.submitInquiry { preventDefault: sinon.stub() } @view.inquiry.set.args[0][0].referring_url.should.containEql 'foo/bar' @view.inquiry.set.args[0][0].landing_url.should.containEql 'baz/bam'
true
_ = require 'underscore' sinon = require 'sinon' Backbone = require 'backbone' Artwork = require '../../../../../../models/artwork' Profile = require '../../../../../../models/profile' CurrentUser = require '../../../../../../models/current_user' benv = require 'benv' { fabricate } = require 'antigravity' { resolve } = require 'path' SubmitInquiryView = null describe 'SubmitInquiryView', -> beforeEach (done) -> artists = [ fabricate 'artist' ] @artwork = fabricate('artwork', image: { url: 'artwork.png' }, artists: artists) benv.setup => benv.expose { $: benv.require 'jquery' } Backbone.$ = $ benv.render resolve(__dirname, '../../../../templates/ask_specialist_page.jade'), { artwork: @artwork profile: new Profile(fabricate 'profile') sd: {} asset: (->) }, => SubmitInquiryView = benv.requireWithJadeify( resolve(__dirname, '../../client/ask_specialist'), ['formTemplate', 'confirmationTemplate'] ) SubmitInquiryView.__set__ 'Cookies', { set: (->), get: (->) } sinon.stub Backbone, 'sync' @view = new SubmitInquiryView el: $ 'body' model: new Artwork @artwork sessionID: 'foobar' done() afterEach -> benv.teardown() Backbone.sync.restore() describe '#serializeForm', -> beforeEach -> @view.$('.submit-inquiry-name').val 'PI:NAME:<NAME>END_PI' @view.$('.submit-inquiry-email').val 'PI:EMAIL:<EMAIL>END_PI' @view.$('.submit-inquiry-message').val 'I like this foo for its barring.' it 'should serialize the form input', -> output = { name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI', message: 'I like this foo for its barring.' } _.isEqual(@view.serializeForm(), output).should.be.ok() describe '#submitInquiry', -> it 'submits a new inquiry from the view', -> sinon.stub @view.inquiry, 'set' @view.$('.submit-inquiry-name').val 'PI:NAME:<NAME>END_PI' @view.$('.submit-inquiry-email').val 'PI:EMAIL:<EMAIL>END_PI' @view.$('.submit-inquiry-message').val 'I like this foo for its barring.' @view.$('.submit-inquiry-form').submit() @view.inquiry.set.args[0][0].name.should.equal 'PI:NAME:<NAME>END_PI' @view.inquiry.set.args[0][0].email.should.equal 'PI:EMAIL:<EMAIL>END_PI' @view.inquiry.set.args[0][0].message.should.equal 'I like this foo for its barring.' it 'should render a success message on success', -> @view.inquiry.set email: 'PI:EMAIL:<EMAIL>END_PI', name: 'PI:NAME:<NAME>END_PI' sinon.stub(@view.inquiry, 'save').yieldsTo('success') sinon.stub @view.$el, 'html' @view.$('.submit-inquiry-form').submit() @view.$el.html.args[0][0].should.containEql 'message has been sent' it 'should render an error message on error', -> sinon.stub(@view.inquiry, 'save').yieldsTo('error') sinon.stub @view.$el, 'html' @view.inquiry.validate = sinon.stub() @view.$('.submit-inquiry-form').submit() @view.$el.html.args[0][0].should.containEql 'Sorry, there was an error' it 'sets the referring url, landing_url, and inquiry_url', -> sinon.stub @view.inquiry, 'set' SubmitInquiryView.__get__('Cookies').get = (key) -> switch key when 'inquiry-referrer' then 'foo/bar' when 'inquiry-session-start' then 'baz/bam' global.location.pathname = 'foo/bar' @view.submitInquiry { preventDefault: sinon.stub() } @view.inquiry.set.args[0][0].referring_url.should.containEql 'foo/bar' @view.inquiry.set.args[0][0].landing_url.should.containEql 'baz/bam'
[ { "context": ".User\n\ndescribe \"new User\", ->\n user = new User(\"anton\", \"anton@circuithub.com\")\n it \"should have corre", "end": 118, "score": 0.9996451139450073, "start": 113, "tag": "USERNAME", "value": "anton" }, { "context": "scribe \"new User\", ->\n user = new User(\"anton\", \"anton@circuithub.com\")\n it \"should have correct proeprties\", ->\n u", "end": 142, "score": 0.9999311566352844, "start": 122, "tag": "EMAIL", "value": "anton@circuithub.com" }, { "context": "rrect proeprties\", ->\n user.id().should.equal \"anton\"\n user.should.have.property \"email\", \"anton@ci", "end": 220, "score": 0.9996172785758972, "start": 215, "tag": "USERNAME", "value": "anton" }, { "context": "l \"anton\"\n user.should.have.property \"email\", \"anton@circuithub.com\"\n user.attributes().should.have.property \"emai", "end": 282, "score": 0.9999302625656128, "start": 262, "tag": "EMAIL", "value": "anton@circuithub.com" }, { "context": " user.attributes().should.have.property \"email\", \"anton@circuithub.com\"\n\n\n", "end": 357, "score": 0.9999301433563232, "start": 337, "tag": "EMAIL", "value": "anton@circuithub.com" } ]
test/user.coffee
circuithub/massive-git
6
should = require "should" User = require("../lib/objects/user").User describe "new User", -> user = new User("anton", "anton@circuithub.com") it "should have correct proeprties", -> user.id().should.equal "anton" user.should.have.property "email", "anton@circuithub.com" user.attributes().should.have.property "email", "anton@circuithub.com"
40737
should = require "should" User = require("../lib/objects/user").User describe "new User", -> user = new User("anton", "<EMAIL>") it "should have correct proeprties", -> user.id().should.equal "anton" user.should.have.property "email", "<EMAIL>" user.attributes().should.have.property "email", "<EMAIL>"
true
should = require "should" User = require("../lib/objects/user").User describe "new User", -> user = new User("anton", "PI:EMAIL:<EMAIL>END_PI") it "should have correct proeprties", -> user.id().should.equal "anton" user.should.have.property "email", "PI:EMAIL:<EMAIL>END_PI" user.attributes().should.have.property "email", "PI:EMAIL:<EMAIL>END_PI"
[ { "context": "3Adapter.s3.upload.calledWith\n Key: \"retain_30_180/zipped-ff/20164bb1b885c2ff4de9b4c73c557e6c.ff\"\n Body: sinon.match dataZipper.ZIP_P", "end": 2270, "score": 0.9990334510803223, "start": 2211, "tag": "KEY", "value": "retain_30_180/zipped-ff/20164bb1b885c2ff4de9b4c73c557e6c.ff" } ]
test/dataZipper.unit.coffee
balihoo/node-fulfillment-worker
0
assert = require 'assert' sinon = require 'sinon' aws = require 'aws-sdk' S3Adapter = require '../lib/s3Adapter' mockS3 = require './mocks/mockS3' dataZipper = require '../lib/dataZipper' bigTestData = require './bigTestData.json' biggerTestData = require './biggerTestData.json' smallResult = { stuff: 'things' } describe 'dataZipper unit tests', -> describe 'deliver() / receive()', -> context "when the supplied data is less than #{dataZipper.MAX_RESULT_SIZE} bytes", -> it 'returns a JSON stringified copy of the supplied data', -> zipper = new dataZipper.DataZipper null zipper.deliver smallResult .then (result) -> assert.deepEqual result, JSON.stringify smallResult context "when the supplied data is greater than #{dataZipper.MAX_RESULT_SIZE} bytes", -> context "and the compressed data is less than #{dataZipper.MAX_RESULT_SIZE} bytes", -> it 'returns a compressed and base64-encoded string', -> zipper = new dataZipper.DataZipper null expectedStart = dataZipper.ZIP_PREFIX + dataZipper.SEPARATOR zipper.deliver bigTestData .then (encodedResult) -> assert typeof encodedResult is 'string' assert encodedResult.slice(0, expectedStart.length) is expectedStart zipper.receive encodedResult .then (decodedResult) -> result = JSON.parse decodedResult assert.deepEqual result, bigTestData context "and the compressed data is greater than #{dataZipper.MAX_RESULT_SIZE} bytes", -> it 'returns an S3 URL', -> uploadedData = null fakeBucket = 'some.bucket' sinon.stub aws, 'S3', mockS3 s3Adapter = new S3Adapter bucket: fakeBucket region: 'some region' zipper = new dataZipper.DataZipper s3Adapter expectedStart = dataZipper.URL_PREFIX + dataZipper.SEPARATOR zipper.deliver biggerTestData .then (s3Result) -> assert.strictEqual s3Adapter.s3.config.params.Bucket, fakeBucket assert s3Adapter.s3.upload.calledOnce assert s3Adapter.s3.upload.calledWith Key: "retain_30_180/zipped-ff/20164bb1b885c2ff4de9b4c73c557e6c.ff" Body: sinon.match dataZipper.ZIP_PREFIX + dataZipper.SEPARATOR call = s3Adapter.s3.upload.getCall 0 key = call.args[0].Key uploadedData = call.args[0].Body assert typeof s3Result is 'string' assert s3Result.slice(0, expectedStart.length) is expectedStart s3Adapter.s3.getObject = sinon.spy (params, callback) -> if params.Key is key callback null, Body: uploadedData else callback new Error "Unknown key #{params.Key} isnt #{key}" zipper.receive s3Result .then (decodedResult) -> result = JSON.parse decodedResult assert.deepEqual result, biggerTestData
31638
assert = require 'assert' sinon = require 'sinon' aws = require 'aws-sdk' S3Adapter = require '../lib/s3Adapter' mockS3 = require './mocks/mockS3' dataZipper = require '../lib/dataZipper' bigTestData = require './bigTestData.json' biggerTestData = require './biggerTestData.json' smallResult = { stuff: 'things' } describe 'dataZipper unit tests', -> describe 'deliver() / receive()', -> context "when the supplied data is less than #{dataZipper.MAX_RESULT_SIZE} bytes", -> it 'returns a JSON stringified copy of the supplied data', -> zipper = new dataZipper.DataZipper null zipper.deliver smallResult .then (result) -> assert.deepEqual result, JSON.stringify smallResult context "when the supplied data is greater than #{dataZipper.MAX_RESULT_SIZE} bytes", -> context "and the compressed data is less than #{dataZipper.MAX_RESULT_SIZE} bytes", -> it 'returns a compressed and base64-encoded string', -> zipper = new dataZipper.DataZipper null expectedStart = dataZipper.ZIP_PREFIX + dataZipper.SEPARATOR zipper.deliver bigTestData .then (encodedResult) -> assert typeof encodedResult is 'string' assert encodedResult.slice(0, expectedStart.length) is expectedStart zipper.receive encodedResult .then (decodedResult) -> result = JSON.parse decodedResult assert.deepEqual result, bigTestData context "and the compressed data is greater than #{dataZipper.MAX_RESULT_SIZE} bytes", -> it 'returns an S3 URL', -> uploadedData = null fakeBucket = 'some.bucket' sinon.stub aws, 'S3', mockS3 s3Adapter = new S3Adapter bucket: fakeBucket region: 'some region' zipper = new dataZipper.DataZipper s3Adapter expectedStart = dataZipper.URL_PREFIX + dataZipper.SEPARATOR zipper.deliver biggerTestData .then (s3Result) -> assert.strictEqual s3Adapter.s3.config.params.Bucket, fakeBucket assert s3Adapter.s3.upload.calledOnce assert s3Adapter.s3.upload.calledWith Key: "<KEY>" Body: sinon.match dataZipper.ZIP_PREFIX + dataZipper.SEPARATOR call = s3Adapter.s3.upload.getCall 0 key = call.args[0].Key uploadedData = call.args[0].Body assert typeof s3Result is 'string' assert s3Result.slice(0, expectedStart.length) is expectedStart s3Adapter.s3.getObject = sinon.spy (params, callback) -> if params.Key is key callback null, Body: uploadedData else callback new Error "Unknown key #{params.Key} isnt #{key}" zipper.receive s3Result .then (decodedResult) -> result = JSON.parse decodedResult assert.deepEqual result, biggerTestData
true
assert = require 'assert' sinon = require 'sinon' aws = require 'aws-sdk' S3Adapter = require '../lib/s3Adapter' mockS3 = require './mocks/mockS3' dataZipper = require '../lib/dataZipper' bigTestData = require './bigTestData.json' biggerTestData = require './biggerTestData.json' smallResult = { stuff: 'things' } describe 'dataZipper unit tests', -> describe 'deliver() / receive()', -> context "when the supplied data is less than #{dataZipper.MAX_RESULT_SIZE} bytes", -> it 'returns a JSON stringified copy of the supplied data', -> zipper = new dataZipper.DataZipper null zipper.deliver smallResult .then (result) -> assert.deepEqual result, JSON.stringify smallResult context "when the supplied data is greater than #{dataZipper.MAX_RESULT_SIZE} bytes", -> context "and the compressed data is less than #{dataZipper.MAX_RESULT_SIZE} bytes", -> it 'returns a compressed and base64-encoded string', -> zipper = new dataZipper.DataZipper null expectedStart = dataZipper.ZIP_PREFIX + dataZipper.SEPARATOR zipper.deliver bigTestData .then (encodedResult) -> assert typeof encodedResult is 'string' assert encodedResult.slice(0, expectedStart.length) is expectedStart zipper.receive encodedResult .then (decodedResult) -> result = JSON.parse decodedResult assert.deepEqual result, bigTestData context "and the compressed data is greater than #{dataZipper.MAX_RESULT_SIZE} bytes", -> it 'returns an S3 URL', -> uploadedData = null fakeBucket = 'some.bucket' sinon.stub aws, 'S3', mockS3 s3Adapter = new S3Adapter bucket: fakeBucket region: 'some region' zipper = new dataZipper.DataZipper s3Adapter expectedStart = dataZipper.URL_PREFIX + dataZipper.SEPARATOR zipper.deliver biggerTestData .then (s3Result) -> assert.strictEqual s3Adapter.s3.config.params.Bucket, fakeBucket assert s3Adapter.s3.upload.calledOnce assert s3Adapter.s3.upload.calledWith Key: "PI:KEY:<KEY>END_PI" Body: sinon.match dataZipper.ZIP_PREFIX + dataZipper.SEPARATOR call = s3Adapter.s3.upload.getCall 0 key = call.args[0].Key uploadedData = call.args[0].Body assert typeof s3Result is 'string' assert s3Result.slice(0, expectedStart.length) is expectedStart s3Adapter.s3.getObject = sinon.spy (params, callback) -> if params.Key is key callback null, Body: uploadedData else callback new Error "Unknown key #{params.Key} isnt #{key}" zipper.receive s3Result .then (decodedResult) -> result = JSON.parse decodedResult assert.deepEqual result, biggerTestData
[ { "context": "cope.cities = [{\n id: 0\n name: \"Helsinki\"\n country: \"Finland\"\n }, {\n ", "end": 443, "score": 0.6724346876144409, "start": 436, "tag": "NAME", "value": "Helsink" }, { "context": " cities.pop()\n cities.push({id: 3, name: \"Berlin\", country: \"Germany\"})\n )\n expect(@g", "end": 1501, "score": 0.7954109907150269, "start": 1498, "tag": "NAME", "value": "Ber" } ]
test/standard_setup.coffee
TejasMadappa/angular-table
302
describe "angular-table", () -> describe "standard setup", () -> expectedRows = [ ["0", "Helsinki", "Finland"], ["1", "Zurich", "Switzerland"], ["2", "Amsterdam", "Netherlands"], ["3", "Berlin", "Germany"] ] beforeEach(() -> comp = new TemplateCompiler("standard_setup.html") @element = comp.prepareElement((scope) -> scope.cities = [{ id: 0 name: "Helsinki" country: "Finland" }, { id: 1 name: "Zurich" country: "Switzerland" }, { id: 2 name: "Amsterdam" country: "Netherlands" }] ) @gui = new GUI(new TableGUI(@element), null, comp.scope, null) ) it "allows to set an initial sorting direction", () -> expect(@gui.table.rows).toEqual [expectedRows[1], expectedRows[0], expectedRows[2]] it "makes columns sortable which are declared at-sortable", () -> @gui.table.sort(1) expect(@gui.table.rows).toEqual [expectedRows[2], expectedRows[0], expectedRows[1]] it "leaves columns unsortable if at-sortable is not declared", () -> @gui.table.sort(2) expect(@gui.table.rows).toEqual [expectedRows[1], expectedRows[0], expectedRows[2]] it "reloads the table if the entries change but the length doesn't", () -> @gui.alterScope((scopeWrapper, vars) -> cities = scopeWrapper.get("cities") cities.pop() cities.push({id: 3, name: "Berlin", country: "Germany"}) ) expect(@gui.table.rows).toEqual [expectedRows[1], expectedRows[0], expectedRows[3]]
75453
describe "angular-table", () -> describe "standard setup", () -> expectedRows = [ ["0", "Helsinki", "Finland"], ["1", "Zurich", "Switzerland"], ["2", "Amsterdam", "Netherlands"], ["3", "Berlin", "Germany"] ] beforeEach(() -> comp = new TemplateCompiler("standard_setup.html") @element = comp.prepareElement((scope) -> scope.cities = [{ id: 0 name: "<NAME>i" country: "Finland" }, { id: 1 name: "Zurich" country: "Switzerland" }, { id: 2 name: "Amsterdam" country: "Netherlands" }] ) @gui = new GUI(new TableGUI(@element), null, comp.scope, null) ) it "allows to set an initial sorting direction", () -> expect(@gui.table.rows).toEqual [expectedRows[1], expectedRows[0], expectedRows[2]] it "makes columns sortable which are declared at-sortable", () -> @gui.table.sort(1) expect(@gui.table.rows).toEqual [expectedRows[2], expectedRows[0], expectedRows[1]] it "leaves columns unsortable if at-sortable is not declared", () -> @gui.table.sort(2) expect(@gui.table.rows).toEqual [expectedRows[1], expectedRows[0], expectedRows[2]] it "reloads the table if the entries change but the length doesn't", () -> @gui.alterScope((scopeWrapper, vars) -> cities = scopeWrapper.get("cities") cities.pop() cities.push({id: 3, name: "<NAME>lin", country: "Germany"}) ) expect(@gui.table.rows).toEqual [expectedRows[1], expectedRows[0], expectedRows[3]]
true
describe "angular-table", () -> describe "standard setup", () -> expectedRows = [ ["0", "Helsinki", "Finland"], ["1", "Zurich", "Switzerland"], ["2", "Amsterdam", "Netherlands"], ["3", "Berlin", "Germany"] ] beforeEach(() -> comp = new TemplateCompiler("standard_setup.html") @element = comp.prepareElement((scope) -> scope.cities = [{ id: 0 name: "PI:NAME:<NAME>END_PIi" country: "Finland" }, { id: 1 name: "Zurich" country: "Switzerland" }, { id: 2 name: "Amsterdam" country: "Netherlands" }] ) @gui = new GUI(new TableGUI(@element), null, comp.scope, null) ) it "allows to set an initial sorting direction", () -> expect(@gui.table.rows).toEqual [expectedRows[1], expectedRows[0], expectedRows[2]] it "makes columns sortable which are declared at-sortable", () -> @gui.table.sort(1) expect(@gui.table.rows).toEqual [expectedRows[2], expectedRows[0], expectedRows[1]] it "leaves columns unsortable if at-sortable is not declared", () -> @gui.table.sort(2) expect(@gui.table.rows).toEqual [expectedRows[1], expectedRows[0], expectedRows[2]] it "reloads the table if the entries change but the length doesn't", () -> @gui.alterScope((scopeWrapper, vars) -> cities = scopeWrapper.get("cities") cities.pop() cities.push({id: 3, name: "PI:NAME:<NAME>END_PIlin", country: "Germany"}) ) expect(@gui.table.rows).toEqual [expectedRows[1], expectedRows[0], expectedRows[3]]
[ { "context": "###################\n# Title: ViewHelper\n# Author: kevin@wintr.us @ WINTR\n#########################################", "end": 104, "score": 0.9999107718467712, "start": 90, "tag": "EMAIL", "value": "kevin@wintr.us" }, { "context": "##\n# Title: ViewHelper\n# Author: kevin@wintr.us @ WINTR\n#################################################", "end": 112, "score": 0.985119104385376, "start": 107, "tag": "USERNAME", "value": "WINTR" } ]
source/javascripts/helpers/ViewHelper.coffee
WikiEducationFoundation/WikiEduWizard
1
######################################################### # Title: ViewHelper # Author: kevin@wintr.us @ WINTR ######################################################### Handlebars.registerHelper( 'link', ( text, url ) -> text = Handlebars.Utils.escapeExpression( text ) url = Handlebars.Utils.escapeExpression( url ) result = '<a href="' + url + '">' + text + '</a>' return new Handlebars.SafeString( result ) ) Handlebars.registerPartial('courseDetails', 'sup2')
17604
######################################################### # Title: ViewHelper # Author: <EMAIL> @ WINTR ######################################################### Handlebars.registerHelper( 'link', ( text, url ) -> text = Handlebars.Utils.escapeExpression( text ) url = Handlebars.Utils.escapeExpression( url ) result = '<a href="' + url + '">' + text + '</a>' return new Handlebars.SafeString( result ) ) Handlebars.registerPartial('courseDetails', 'sup2')
true
######################################################### # Title: ViewHelper # Author: PI:EMAIL:<EMAIL>END_PI @ WINTR ######################################################### Handlebars.registerHelper( 'link', ( text, url ) -> text = Handlebars.Utils.escapeExpression( text ) url = Handlebars.Utils.escapeExpression( url ) result = '<a href="' + url + '">' + text + '</a>' return new Handlebars.SafeString( result ) ) Handlebars.registerPartial('courseDetails', 'sup2')
[ { "context": "rts of comments would come to an end.\"\n name: \"Joe Bloggs\"\n date: \"14:23pm, 4th Dec 2010\"\n ,\n commen", "end": 352, "score": 0.999870777130127, "start": 342, "tag": "NAME", "value": "Joe Bloggs" }, { "context": "rts of comments would come to an end.\"\n name: \"Joe Bloggs\"\n date: \"14:23pm, 4th Dec 2010\"\n ,\n commen", "end": 589, "score": 0.9998644590377808, "start": 579, "tag": "NAME", "value": "Joe Bloggs" }, { "context": "RTS OF COMMENTS WOULD COME TO AN END.\"\n name: \"Joe Bloggs\"\n date: \"14:23pm, 4th Dec 2010\"\n ,\n commen", "end": 870, "score": 0.9998490810394287, "start": 860, "tag": "NAME", "value": "Joe Bloggs" }, { "context": "rts of comments would come to an end.\"\n name: \"Joe Bloggs\"\n date: \"14:23pm, 4th Dec 2010\"\n ,\n commen", "end": 1128, "score": 0.9998572468757629, "start": 1118, "tag": "NAME", "value": "Joe Bloggs" }, { "context": "rts of comments would come to an end.\"\n name: \"Joe Bloggs\"\n date: \"14:23pm, 4th Dec 2010\"\n ,\n commen", "end": 1410, "score": 0.9998537302017212, "start": 1400, "tag": "NAME", "value": "Joe Bloggs" }, { "context": "r one that will go on for a one line.\"\n name: \"Jane Doe\"\n date: \"14:43pm, 12th Dec 2014\"\n ]\n @commen", "end": 1542, "score": 0.9998546242713928, "start": 1534, "tag": "NAME", "value": "Jane Doe" }, { "context": "bj.comment\n @date = obj.date\n @fancyName = \"Mr Bigglesworth \" + @name + \" IV\"\n\n toString: ->\n @comments[0", "end": 1769, "score": 0.9929499626159668, "start": 1754, "tag": "NAME", "value": "Mr Bigglesworth" } ]
app/models/comments/comment.coffee
Kenspeckled/react_comments
0
Base = require '../baseClass.coffee' _ = require 'lodash' class Comment extends Base #Temporary data = [ comment: "This is a much longer one that will go on for a few lines.<br/>It has multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end." name: "Joe Bloggs" date: "14:23pm, 4th Dec 2010" , comment: "tHIS IS A MUCH LONGER ONE THAT WILL GO ON FOR A FEW LINES of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end." name: "Joe Bloggs" date: "14:23pm, 4th Dec 2010" , comment: "This is a much longer one that will go on for a few lines.<BR/>iT HAS MULTIPLE PARAGRAPHS AND IS FULL OF WAFFLE TO PAD OUT THE COMMENT. uSUALLY, YOU JUST WISH THESE SORTS OF COMMENTS WOULD COME TO AN END." name: "Joe Bloggs" date: "14:23pm, 4th Dec 2010" , comment: "This is a much longer one that will go on for a few linesaragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end." name: "Joe Bloggs" date: "14:23pm, 4th Dec 2010" , comment: "This is a much longer one that will go on for a few lines.<br/>It has multiple paragraphs anja is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end." name: "Joe Bloggs" date: "14:23pm, 4th Dec 2010" , comment: "This is a much longer one that will go on for a one line." name: "Jane Doe" date: "14:43pm, 12th Dec 2014" ] @comments = _.map data, (c) -> return new Comment(c) constructor: (obj) -> @name = obj.name @comment = obj.comment @date = obj.date @fancyName = "Mr Bigglesworth " + @name + " IV" toString: -> @comments[0].comment toJSON: -> { name: @name } @create = (props) -> newObject = new Comment(props) @comments.push newObject @broadcast('change') @all = -> return @comments module.exports = Comment
155793
Base = require '../baseClass.coffee' _ = require 'lodash' class Comment extends Base #Temporary data = [ comment: "This is a much longer one that will go on for a few lines.<br/>It has multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end." name: "<NAME>" date: "14:23pm, 4th Dec 2010" , comment: "tHIS IS A MUCH LONGER ONE THAT WILL GO ON FOR A FEW LINES of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end." name: "<NAME>" date: "14:23pm, 4th Dec 2010" , comment: "This is a much longer one that will go on for a few lines.<BR/>iT HAS MULTIPLE PARAGRAPHS AND IS FULL OF WAFFLE TO PAD OUT THE COMMENT. uSUALLY, YOU JUST WISH THESE SORTS OF COMMENTS WOULD COME TO AN END." name: "<NAME>" date: "14:23pm, 4th Dec 2010" , comment: "This is a much longer one that will go on for a few linesaragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end." name: "<NAME>" date: "14:23pm, 4th Dec 2010" , comment: "This is a much longer one that will go on for a few lines.<br/>It has multiple paragraphs anja is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end." name: "<NAME>" date: "14:23pm, 4th Dec 2010" , comment: "This is a much longer one that will go on for a one line." name: "<NAME>" date: "14:43pm, 12th Dec 2014" ] @comments = _.map data, (c) -> return new Comment(c) constructor: (obj) -> @name = obj.name @comment = obj.comment @date = obj.date @fancyName = "<NAME> " + @name + " IV" toString: -> @comments[0].comment toJSON: -> { name: @name } @create = (props) -> newObject = new Comment(props) @comments.push newObject @broadcast('change') @all = -> return @comments module.exports = Comment
true
Base = require '../baseClass.coffee' _ = require 'lodash' class Comment extends Base #Temporary data = [ comment: "This is a much longer one that will go on for a few lines.<br/>It has multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end." name: "PI:NAME:<NAME>END_PI" date: "14:23pm, 4th Dec 2010" , comment: "tHIS IS A MUCH LONGER ONE THAT WILL GO ON FOR A FEW LINES of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end." name: "PI:NAME:<NAME>END_PI" date: "14:23pm, 4th Dec 2010" , comment: "This is a much longer one that will go on for a few lines.<BR/>iT HAS MULTIPLE PARAGRAPHS AND IS FULL OF WAFFLE TO PAD OUT THE COMMENT. uSUALLY, YOU JUST WISH THESE SORTS OF COMMENTS WOULD COME TO AN END." name: "PI:NAME:<NAME>END_PI" date: "14:23pm, 4th Dec 2010" , comment: "This is a much longer one that will go on for a few linesaragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end." name: "PI:NAME:<NAME>END_PI" date: "14:23pm, 4th Dec 2010" , comment: "This is a much longer one that will go on for a few lines.<br/>It has multiple paragraphs anja is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end." name: "PI:NAME:<NAME>END_PI" date: "14:23pm, 4th Dec 2010" , comment: "This is a much longer one that will go on for a one line." name: "PI:NAME:<NAME>END_PI" date: "14:43pm, 12th Dec 2014" ] @comments = _.map data, (c) -> return new Comment(c) constructor: (obj) -> @name = obj.name @comment = obj.comment @date = obj.date @fancyName = "PI:NAME:<NAME>END_PI " + @name + " IV" toString: -> @comments[0].comment toJSON: -> { name: @name } @create = (props) -> newObject = new Comment(props) @comments.push newObject @broadcast('change') @all = -> return @comments module.exports = Comment
[ { "context": "eStyle = \"#3f3f3f\"\nc.strokeRect 10, 10, 300, 80\n\n# Professor Digman-Rünner text\nc.fillStyle = \"#202020\"\nc.font", "end": 734, "score": 0.7431874871253967, "start": 725, "tag": "NAME", "value": "Professor" }, { "context": "#3f3f3f\"\nc.strokeRect 10, 10, 300, 80\n\n# Professor Digman-Rünner text\nc.fillStyle = \"#202020\"\nc.font = \"14pt monos", "end": 748, "score": 0.9875780940055847, "start": 735, "tag": "NAME", "value": "Digman-Rünner" }, { "context": "= \"#202020\"\nc.font = \"14pt monospace\"\nc.fillText \"Professor Digman-Rünner\", 30, 55\n###\n", "end": 825, "score": 0.967871367931366, "start": 816, "tag": "NAME", "value": "Professor" }, { "context": "0\"\nc.font = \"14pt monospace\"\nc.fillText \"Professor Digman-Rünner\", 30, 55\n###\n", "end": 839, "score": 0.969048261642456, "start": 826, "tag": "NAME", "value": "Digman-Rünner" } ]
src/game.coffee
lazlojuly/jscs-canvas-game
0
# alert "Game loaded! game = init: -> if not gfx.init() alert "Could not set up game canvas!" return # abort # Ready to play gfx.clear() gfx.load -> c = gfx.ctx # c.drawImage gfx.sprites, 10, 20 # Prof solo gfx.drawSprite 0,0,100,50 # Random Map rand = (max) -> Math.floor Math.random() * max for y in [0..19] for x in [0..23] col = rand 7 row = rand 2 gfx.drawSprite col, row, x * 24, y * 24 # Start the game game.init() ### # Title screen c = gfx.ctx # Orange rectangle with a dark-gray border c.fillStyle = "orange" c.fillRect 10, 10, 300, 80 c.strokeStyle = "#3f3f3f" c.strokeRect 10, 10, 300, 80 # Professor Digman-Rünner text c.fillStyle = "#202020" c.font = "14pt monospace" c.fillText "Professor Digman-Rünner", 30, 55 ###
178785
# alert "Game loaded! game = init: -> if not gfx.init() alert "Could not set up game canvas!" return # abort # Ready to play gfx.clear() gfx.load -> c = gfx.ctx # c.drawImage gfx.sprites, 10, 20 # Prof solo gfx.drawSprite 0,0,100,50 # Random Map rand = (max) -> Math.floor Math.random() * max for y in [0..19] for x in [0..23] col = rand 7 row = rand 2 gfx.drawSprite col, row, x * 24, y * 24 # Start the game game.init() ### # Title screen c = gfx.ctx # Orange rectangle with a dark-gray border c.fillStyle = "orange" c.fillRect 10, 10, 300, 80 c.strokeStyle = "#3f3f3f" c.strokeRect 10, 10, 300, 80 # <NAME> <NAME> text c.fillStyle = "#202020" c.font = "14pt monospace" c.fillText "<NAME> <NAME>", 30, 55 ###
true
# alert "Game loaded! game = init: -> if not gfx.init() alert "Could not set up game canvas!" return # abort # Ready to play gfx.clear() gfx.load -> c = gfx.ctx # c.drawImage gfx.sprites, 10, 20 # Prof solo gfx.drawSprite 0,0,100,50 # Random Map rand = (max) -> Math.floor Math.random() * max for y in [0..19] for x in [0..23] col = rand 7 row = rand 2 gfx.drawSprite col, row, x * 24, y * 24 # Start the game game.init() ### # Title screen c = gfx.ctx # Orange rectangle with a dark-gray border c.fillStyle = "orange" c.fillRect 10, 10, 300, 80 c.strokeStyle = "#3f3f3f" c.strokeRect 10, 10, 300, 80 # PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI text c.fillStyle = "#202020" c.font = "14pt monospace" c.fillText "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI", 30, 55 ###
[ { "context": "ctual sliding effect engine\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\nclass Engine\n\n #\n # Constructor. Hooks up the", "end": 96, "score": 0.9998888969421387, "start": 79, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
ui/slideshow/src/engine.coffee
lovely-io/lovely.io-stl
2
# # This file contains the actual sliding effect engine # # Copyright (C) 2012 Nikolay Nemshilov # class Engine # # Constructor. Hooks up the events and stuff # # @param {Slideshow} reference # @return {Engine} this # constructor: (slideshow)-> @slideshow = slideshow slideshow.on touchstart: (event)=> @__sliding = false @__touchstart = event.position().x event.preventDefault() touchmove: (event)=> return if @__sliding x_position = event.position().x threshold = 20 if (x_position - @__touchstart) > threshold @__sliding = true slideshow.previous() @__touchstart = x_position else if (@__touchstart - x_position) > threshold @__sliding = true slideshow.next() @__touchstart = x_position return @ # protected # makes the actual sliding effect _slide: (index, item, cur_item)-> item.radioClass('lui-slideshow-current') return box_size = @_end_size(item) old_size = cur_item.size() end_size = box_size.item_size box_size = box_size.list_size # calculating the left-position for the slide end_left = if old_size.x > end_size.x then old_size.x else end_size.x end_left *= -1 if @currentIndex > index # presetting initial styles @addClass('lui-slideshow-resizing').size(@size()) cur_item.size(old_size).style(position: 'absolute', left: '0px') item.style(display: 'block', position: 'absolute', left: end_left + 'px') # visualizing the slide item.size(end_size).animate {left: '0px'}, duration: @options.fxDuration, finish: -> item.style(position: 'relative', width: '', height: '') cur_item.animate {left: (- end_left) + 'px'}, duration: @options.fxDuration, finish: -> cur_item.style(display: 'none', width: '', height: '') # animating the size change @animate box_size, duration: @options.fxDuration, finish: => @removeClass('lui-slideshow-resizing') global.setTimeout((=>@__sliding = false), 50) # calculates the end size of the whole block _end_size: (item)-> @__clone or= @clone().style(visibility: 'hidden').insertTo(@, 'after') @__clone.style(display: '') item = item.clone().style(display: 'block', position: 'relative') result = list_size: @__clone.update(item).style('width,height') item_size: item.size() @__clone.style(display: 'none') return result
81826
# # This file contains the actual sliding effect engine # # Copyright (C) 2012 <NAME> # class Engine # # Constructor. Hooks up the events and stuff # # @param {Slideshow} reference # @return {Engine} this # constructor: (slideshow)-> @slideshow = slideshow slideshow.on touchstart: (event)=> @__sliding = false @__touchstart = event.position().x event.preventDefault() touchmove: (event)=> return if @__sliding x_position = event.position().x threshold = 20 if (x_position - @__touchstart) > threshold @__sliding = true slideshow.previous() @__touchstart = x_position else if (@__touchstart - x_position) > threshold @__sliding = true slideshow.next() @__touchstart = x_position return @ # protected # makes the actual sliding effect _slide: (index, item, cur_item)-> item.radioClass('lui-slideshow-current') return box_size = @_end_size(item) old_size = cur_item.size() end_size = box_size.item_size box_size = box_size.list_size # calculating the left-position for the slide end_left = if old_size.x > end_size.x then old_size.x else end_size.x end_left *= -1 if @currentIndex > index # presetting initial styles @addClass('lui-slideshow-resizing').size(@size()) cur_item.size(old_size).style(position: 'absolute', left: '0px') item.style(display: 'block', position: 'absolute', left: end_left + 'px') # visualizing the slide item.size(end_size).animate {left: '0px'}, duration: @options.fxDuration, finish: -> item.style(position: 'relative', width: '', height: '') cur_item.animate {left: (- end_left) + 'px'}, duration: @options.fxDuration, finish: -> cur_item.style(display: 'none', width: '', height: '') # animating the size change @animate box_size, duration: @options.fxDuration, finish: => @removeClass('lui-slideshow-resizing') global.setTimeout((=>@__sliding = false), 50) # calculates the end size of the whole block _end_size: (item)-> @__clone or= @clone().style(visibility: 'hidden').insertTo(@, 'after') @__clone.style(display: '') item = item.clone().style(display: 'block', position: 'relative') result = list_size: @__clone.update(item).style('width,height') item_size: item.size() @__clone.style(display: 'none') return result
true
# # This file contains the actual sliding effect engine # # Copyright (C) 2012 PI:NAME:<NAME>END_PI # class Engine # # Constructor. Hooks up the events and stuff # # @param {Slideshow} reference # @return {Engine} this # constructor: (slideshow)-> @slideshow = slideshow slideshow.on touchstart: (event)=> @__sliding = false @__touchstart = event.position().x event.preventDefault() touchmove: (event)=> return if @__sliding x_position = event.position().x threshold = 20 if (x_position - @__touchstart) > threshold @__sliding = true slideshow.previous() @__touchstart = x_position else if (@__touchstart - x_position) > threshold @__sliding = true slideshow.next() @__touchstart = x_position return @ # protected # makes the actual sliding effect _slide: (index, item, cur_item)-> item.radioClass('lui-slideshow-current') return box_size = @_end_size(item) old_size = cur_item.size() end_size = box_size.item_size box_size = box_size.list_size # calculating the left-position for the slide end_left = if old_size.x > end_size.x then old_size.x else end_size.x end_left *= -1 if @currentIndex > index # presetting initial styles @addClass('lui-slideshow-resizing').size(@size()) cur_item.size(old_size).style(position: 'absolute', left: '0px') item.style(display: 'block', position: 'absolute', left: end_left + 'px') # visualizing the slide item.size(end_size).animate {left: '0px'}, duration: @options.fxDuration, finish: -> item.style(position: 'relative', width: '', height: '') cur_item.animate {left: (- end_left) + 'px'}, duration: @options.fxDuration, finish: -> cur_item.style(display: 'none', width: '', height: '') # animating the size change @animate box_size, duration: @options.fxDuration, finish: => @removeClass('lui-slideshow-resizing') global.setTimeout((=>@__sliding = false), 50) # calculates the end size of the whole block _end_size: (item)-> @__clone or= @clone().style(visibility: 'hidden').insertTo(@, 'after') @__clone.style(display: '') item = item.clone().style(display: 'block', position: 'relative') result = list_size: @__clone.update(item).style('width,height') item_size: item.size() @__clone.style(display: 'none') return result
[ { "context": "esses = 1\n\n # final result object\n password: password\n guesses: guesses\n guesses_log10: @log10 gu", "end": 4869, "score": 0.9993947744369507, "start": 4861, "tag": "PASSWORD", "value": "password" } ]
src/scoring.coffee
glensc/zxcvbn
1
adjacency_graphs = require('./adjacency_graphs') # on qwerty, 'g' has degree 6, being adjacent to 'ftyhbv'. '\' has degree 1. # this calculates the average over all keys. calc_average_degree = (graph) -> average = 0 for key, neighbors of graph average += (n for n in neighbors when n).length average /= (k for k,v of graph).length average scoring = nCk: (n, k) -> # http://blog.plover.com/math/choose.html return 0 if k > n return 1 if k == 0 r = 1 for d in [1..k] r *= n r /= d n -= 1 r log10: (n) -> Math.log(n) / Math.log(10) # IE doesn't support Math.log10 :( log2: (n) -> Math.log(n) / Math.log(2) factorial: (n) -> # unoptimized, called only on small n return 1 if n < 2 f = 1 f *= i for i in [2..n] f # ------------------------------------------------------------------------------ # search --- most guessable match sequence ------------------------------------- # ------------------------------------------------------------------------------ # # takes a list of overlapping matches, returns the non-overlapping sublist with # minimum guesses. O(nm) dp alg for length-n password with m candidate matches. # # the optimal "minimum guesses" sublist is here defined to be the sublist that # minimizes: # # product(m.guesses for m in sequence) * factorial(sequence.length) # # the factorial term is the number of ways to order n patterns. it serves as a # light penalty for longer sequences. # # for example, consider a sequence that is date-repeat-dictionary. # - an attacker would need to try other date-repeat-dictionary combinations, # hence the product term. # - an attacker would need to try repeat-date-dictionary, dictionary-repeat-date, # ..., hence the factorial term. # - an attacker would also likely try length-1 and length-2 sequences before # length-3. those terms tend to be small in comparison and are excluded # for simplicity. # # ------------------------------------------------------------------------------ most_guessable_match_sequence: (password, matches) -> # at index k, the product of guesses of the optimal sequence covering password[0..k] optimal_product = [] # at index k, the number of matches in the optimal sequence covering password[0..k]. # used to calculate the factorial term. optimal_sequence_length = [] # if the optimal sequence ends in a bruteforce match, this records those bruteforce # characters, otherwise '' ending_bruteforce_chars = '' # at index k, the final match (match.j == k) in said optimal sequence. backpointers = [] make_bruteforce_match = (i, j) => cardinality = @cardinality password[i..j] guesses = Math.pow cardinality, j - i + 1 # return object: pattern: 'bruteforce' i: i j: j token: password[i..j] guesses: guesses guesses_log10: @log10(guesses) cardinality: cardinality length: j - i + 1 for k in [0...password.length] # starting scenario to beat: # adding a brute-force character to the sequence with min guesses at k-1. ending_bruteforce_chars += password.charAt(k) l = ending_bruteforce_chars.length optimal_product[k] = Math.pow @cardinality(ending_bruteforce_chars), l optimal_sequence_length[k] = 1 if k - l >= 0 optimal_product[k] *= optimal_product[k - l] optimal_sequence_length[k] += optimal_sequence_length[k - l] backpointers[k] = make_bruteforce_match(k - l + 1, k) minimum_guesses = optimal_product[k] * @factorial optimal_sequence_length[k] for match in matches when match.j == k [i, j] = [match.i, match.j] candidate_product = @estimate_guesses match candidate_length = 1 if i - 1 >= 0 candidate_product *= optimal_product[i - 1] candidate_length += optimal_sequence_length[i - 1] candidate_guesses = candidate_product * @factorial candidate_length if candidate_guesses < minimum_guesses minimum_guesses = candidate_guesses ending_bruteforce_chars = '' optimal_product[k] = candidate_product optimal_sequence_length[k] = candidate_length backpointers[k] = match # walk backwards and decode the best sequence match_sequence = [] k = password.length - 1 while k >= 0 match = backpointers[k] match_sequence.push match k = match.i - 1 match_sequence.reverse() if password.length > 0 sequence_length_multiplier = @factorial optimal_sequence_length[password.length - 1] guesses = optimal_product[password.length - 1] * sequence_length_multiplier else sequence_length_multiplier = 1 guesses = 1 # final result object password: password guesses: guesses guesses_log10: @log10 guesses sequence_product_log10: @log10(optimal_product[password.length - 1]) sequence_length_multiplier_log10: @log10 sequence_length_multiplier sequence: match_sequence # ------------------------------------------------------------------------------ # guess estimation -- one function per match pattern --------------------------- # ------------------------------------------------------------------------------ estimate_guesses: (match) -> return match.guesses if match.guesses? # a match's guess estimate doesn't change. cache it. estimation_functions = dictionary: @dictionary_guesses spatial: @spatial_guesses repeat: @repeat_guesses sequence: @sequence_guesses regex: @regex_guesses date: @date_guesses match.guesses = estimation_functions[match.pattern].call this, match match.guesses_log10 = @log10 match.guesses match.guesses repeat_guesses: (match) -> match.base_guesses * match.repeat_count sequence_guesses: (match) -> first_chr = match.token.charAt(0) # lower guesses for obvious starting points if first_chr in ['a', 'A', 'z', 'Z', '0', '1', '9'] base_guesses = 4 else if first_chr.match /\d/ base_guesses = 10 # digits else # could give a higher base for uppercase, # assigning 26 to both upper and lower sequences is more conservative. base_guesses = 26 if not match.ascending # need to try a descending sequence in addition to every ascending sequence -> # 2x guesses base_guesses *= 2 base_guesses * match.token.length MIN_YEAR_SPACE: 20 REFERENCE_YEAR: 2000 regex_guesses: (match) -> char_class_bases = alpha_lower: 26 alpha_upper: 26 alpha: 52 alphanumeric: 62 digits: 10 symbols: 33 if match.regex_name of char_class_bases Math.pow(char_class_bases[match.regex_name], match.token.length) else switch match.regex_name when 'recent_year' # conservative estimate of year space: num years from REFERENCE_YEAR. # if year is close to REFERENCE_YEAR, estimate a year space of MIN_YEAR_SPACE. year_space = Math.abs parseInt(match.regex_match[0]) - @REFERENCE_YEAR year_space = Math.max year_space, @MIN_YEAR_SPACE year_space date_guesses: (match) -> # base guesses: (year distance from REFERENCE_YEAR) * num_days * num_years year_space = Math.max(Math.abs(match.year - @REFERENCE_YEAR), @MIN_YEAR_SPACE) guesses = year_space * 31 * 12 # double for four-digit years guesses *= 2 if match.has_full_year # add factor of 4 for separator selection (one of ~4 choices) guesses *= 4 if match.separator guesses KEYBOARD_AVERAGE_DEGREE: calc_average_degree(adjacency_graphs.qwerty) # slightly different for keypad/mac keypad, but close enough KEYPAD_AVERAGE_DEGREE: calc_average_degree(adjacency_graphs.keypad) KEYBOARD_STARTING_POSITIONS: (k for k,v of adjacency_graphs.qwerty).length KEYPAD_STARTING_POSITIONS: (k for k,v of adjacency_graphs.keypad).length spatial_guesses: (match) -> if match.graph in ['qwerty', 'dvorak'] s = @KEYBOARD_STARTING_POSITIONS d = @KEYBOARD_AVERAGE_DEGREE else s = @KEYPAD_STARTING_POSITIONS d = @KEYPAD_AVERAGE_DEGREE guesses = 0 L = match.token.length t = match.turns # estimate the number of possible patterns w/ length L or less with t turns or less. for i in [2..L] possible_turns = Math.min(t, i - 1) for j in [1..possible_turns] guesses += @nCk(i - 1, j - 1) * s * Math.pow(d, j) # add extra guesses for shifted keys. (% instead of 5, A instead of a.) # math is similar to extra guesses of l33t substitutions in dictionary matches. if match.shifted_count S = match.shifted_count U = match.token.length - match.shifted_count # unshifted count if S == 0 or U == 0 guesses *= 2 else shifted_variations = 0 shifted_variations += @nCk(S + U, i) for i in [1..Math.min(S, U)] guesses *= shifted_variations guesses dictionary_guesses: (match) -> match.base_guesses = match.rank # keep these as properties for display purposes match.uppercase_variations = @uppercase_variations match match.l33t_variations = @l33t_variations match reversed_variations = match.reversed and 2 or 1 match.base_guesses * match.uppercase_variations * match.l33t_variations * reversed_variations START_UPPER: /^[A-Z][^A-Z]+$/ END_UPPER: /^[^A-Z]+[A-Z]$/ ALL_UPPER: /^[^a-z]+$/ ALL_LOWER: /^[^A-Z]+$/ uppercase_variations: (match) -> word = match.token return 1 if word.match @ALL_LOWER # a capitalized word is the most common capitalization scheme, # so it only doubles the search space (uncapitalized + capitalized). # allcaps and end-capitalized are common enough too, underestimate as 2x factor to be safe. for regex in [@START_UPPER, @END_UPPER, @ALL_UPPER] return 2 if word.match regex # otherwise calculate the number of ways to capitalize U+L uppercase+lowercase letters # with U uppercase letters or less. or, if there's more uppercase than lower (for eg. PASSwORD), # the number of ways to lowercase U+L letters with L lowercase letters or less. U = (chr for chr in word.split('') when chr.match /[A-Z]/).length L = (chr for chr in word.split('') when chr.match /[a-z]/).length variations = 0 variations += @nCk(U + L, i) for i in [1..Math.min(U, L)] variations l33t_variations: (match) -> return 1 if not match.l33t variations = 1 for subbed, unsubbed of match.sub # lower-case match.token before calculating: capitalization shouldn't affect l33t calc. chrs = match.token.toLowerCase().split('') S = (chr for chr in chrs when chr == subbed).length # num of subbed chars U = (chr for chr in chrs when chr == unsubbed).length # num of unsubbed chars if S == 0 or U == 0 # for this sub, password is either fully subbed (444) or fully unsubbed (aaa) # treat that as doubling the space (attacker needs to try fully subbed chars in addition to # unsubbed.) variations *= 2 else # this case is similar to capitalization: # with aa44a, U = 3, S = 2, attacker needs to try unsubbed + one sub + two subs p = Math.min(U, S) possibilities = 0 possibilities += @nCk(U + S, i) for i in [1..p] variations *= possibilities variations # utilities -------------------------------------------------------------------- cardinality: (password) -> [lower, upper, digits, symbols, latin1_symbols, latin1_letters] = ( false for i in [0...6] ) unicode_codepoints = [] for chr in password.split('') ord = chr.charCodeAt(0) if 0x30 <= ord <= 0x39 digits = true else if 0x41 <= ord <= 0x5a upper = true else if 0x61 <= ord <= 0x7a lower = true else if ord <= 0x7f symbols = true else if 0x80 <= ord <= 0xBF latin1_symbols = true else if 0xC0 <= ord <= 0xFF latin1_letters = true else if ord > 0xFF unicode_codepoints.push ord c = 0 c += 10 if digits c += 26 if upper c += 26 if lower c += 33 if symbols c += 64 if latin1_symbols c += 64 if latin1_letters if unicode_codepoints.length min_cp = max_cp = unicode_codepoints[0] for cp in unicode_codepoints[1..] min_cp = cp if cp < min_cp max_cp = cp if cp > max_cp # if the range between unicode codepoints is small, # assume one extra alphabet is in use (eg cyrillic, korean) and add a ballpark +40 # # if the range is large, be very conservative and add +100 instead of the range. # (codepoint distance between chinese chars can be many thousand, for example, # but that cardinality boost won't be justified if the characters are common.) range = max_cp - min_cp + 1 range = 40 if range < 40 range = 100 if range > 100 c += range c module.exports = scoring
42016
adjacency_graphs = require('./adjacency_graphs') # on qwerty, 'g' has degree 6, being adjacent to 'ftyhbv'. '\' has degree 1. # this calculates the average over all keys. calc_average_degree = (graph) -> average = 0 for key, neighbors of graph average += (n for n in neighbors when n).length average /= (k for k,v of graph).length average scoring = nCk: (n, k) -> # http://blog.plover.com/math/choose.html return 0 if k > n return 1 if k == 0 r = 1 for d in [1..k] r *= n r /= d n -= 1 r log10: (n) -> Math.log(n) / Math.log(10) # IE doesn't support Math.log10 :( log2: (n) -> Math.log(n) / Math.log(2) factorial: (n) -> # unoptimized, called only on small n return 1 if n < 2 f = 1 f *= i for i in [2..n] f # ------------------------------------------------------------------------------ # search --- most guessable match sequence ------------------------------------- # ------------------------------------------------------------------------------ # # takes a list of overlapping matches, returns the non-overlapping sublist with # minimum guesses. O(nm) dp alg for length-n password with m candidate matches. # # the optimal "minimum guesses" sublist is here defined to be the sublist that # minimizes: # # product(m.guesses for m in sequence) * factorial(sequence.length) # # the factorial term is the number of ways to order n patterns. it serves as a # light penalty for longer sequences. # # for example, consider a sequence that is date-repeat-dictionary. # - an attacker would need to try other date-repeat-dictionary combinations, # hence the product term. # - an attacker would need to try repeat-date-dictionary, dictionary-repeat-date, # ..., hence the factorial term. # - an attacker would also likely try length-1 and length-2 sequences before # length-3. those terms tend to be small in comparison and are excluded # for simplicity. # # ------------------------------------------------------------------------------ most_guessable_match_sequence: (password, matches) -> # at index k, the product of guesses of the optimal sequence covering password[0..k] optimal_product = [] # at index k, the number of matches in the optimal sequence covering password[0..k]. # used to calculate the factorial term. optimal_sequence_length = [] # if the optimal sequence ends in a bruteforce match, this records those bruteforce # characters, otherwise '' ending_bruteforce_chars = '' # at index k, the final match (match.j == k) in said optimal sequence. backpointers = [] make_bruteforce_match = (i, j) => cardinality = @cardinality password[i..j] guesses = Math.pow cardinality, j - i + 1 # return object: pattern: 'bruteforce' i: i j: j token: password[i..j] guesses: guesses guesses_log10: @log10(guesses) cardinality: cardinality length: j - i + 1 for k in [0...password.length] # starting scenario to beat: # adding a brute-force character to the sequence with min guesses at k-1. ending_bruteforce_chars += password.charAt(k) l = ending_bruteforce_chars.length optimal_product[k] = Math.pow @cardinality(ending_bruteforce_chars), l optimal_sequence_length[k] = 1 if k - l >= 0 optimal_product[k] *= optimal_product[k - l] optimal_sequence_length[k] += optimal_sequence_length[k - l] backpointers[k] = make_bruteforce_match(k - l + 1, k) minimum_guesses = optimal_product[k] * @factorial optimal_sequence_length[k] for match in matches when match.j == k [i, j] = [match.i, match.j] candidate_product = @estimate_guesses match candidate_length = 1 if i - 1 >= 0 candidate_product *= optimal_product[i - 1] candidate_length += optimal_sequence_length[i - 1] candidate_guesses = candidate_product * @factorial candidate_length if candidate_guesses < minimum_guesses minimum_guesses = candidate_guesses ending_bruteforce_chars = '' optimal_product[k] = candidate_product optimal_sequence_length[k] = candidate_length backpointers[k] = match # walk backwards and decode the best sequence match_sequence = [] k = password.length - 1 while k >= 0 match = backpointers[k] match_sequence.push match k = match.i - 1 match_sequence.reverse() if password.length > 0 sequence_length_multiplier = @factorial optimal_sequence_length[password.length - 1] guesses = optimal_product[password.length - 1] * sequence_length_multiplier else sequence_length_multiplier = 1 guesses = 1 # final result object password: <PASSWORD> guesses: guesses guesses_log10: @log10 guesses sequence_product_log10: @log10(optimal_product[password.length - 1]) sequence_length_multiplier_log10: @log10 sequence_length_multiplier sequence: match_sequence # ------------------------------------------------------------------------------ # guess estimation -- one function per match pattern --------------------------- # ------------------------------------------------------------------------------ estimate_guesses: (match) -> return match.guesses if match.guesses? # a match's guess estimate doesn't change. cache it. estimation_functions = dictionary: @dictionary_guesses spatial: @spatial_guesses repeat: @repeat_guesses sequence: @sequence_guesses regex: @regex_guesses date: @date_guesses match.guesses = estimation_functions[match.pattern].call this, match match.guesses_log10 = @log10 match.guesses match.guesses repeat_guesses: (match) -> match.base_guesses * match.repeat_count sequence_guesses: (match) -> first_chr = match.token.charAt(0) # lower guesses for obvious starting points if first_chr in ['a', 'A', 'z', 'Z', '0', '1', '9'] base_guesses = 4 else if first_chr.match /\d/ base_guesses = 10 # digits else # could give a higher base for uppercase, # assigning 26 to both upper and lower sequences is more conservative. base_guesses = 26 if not match.ascending # need to try a descending sequence in addition to every ascending sequence -> # 2x guesses base_guesses *= 2 base_guesses * match.token.length MIN_YEAR_SPACE: 20 REFERENCE_YEAR: 2000 regex_guesses: (match) -> char_class_bases = alpha_lower: 26 alpha_upper: 26 alpha: 52 alphanumeric: 62 digits: 10 symbols: 33 if match.regex_name of char_class_bases Math.pow(char_class_bases[match.regex_name], match.token.length) else switch match.regex_name when 'recent_year' # conservative estimate of year space: num years from REFERENCE_YEAR. # if year is close to REFERENCE_YEAR, estimate a year space of MIN_YEAR_SPACE. year_space = Math.abs parseInt(match.regex_match[0]) - @REFERENCE_YEAR year_space = Math.max year_space, @MIN_YEAR_SPACE year_space date_guesses: (match) -> # base guesses: (year distance from REFERENCE_YEAR) * num_days * num_years year_space = Math.max(Math.abs(match.year - @REFERENCE_YEAR), @MIN_YEAR_SPACE) guesses = year_space * 31 * 12 # double for four-digit years guesses *= 2 if match.has_full_year # add factor of 4 for separator selection (one of ~4 choices) guesses *= 4 if match.separator guesses KEYBOARD_AVERAGE_DEGREE: calc_average_degree(adjacency_graphs.qwerty) # slightly different for keypad/mac keypad, but close enough KEYPAD_AVERAGE_DEGREE: calc_average_degree(adjacency_graphs.keypad) KEYBOARD_STARTING_POSITIONS: (k for k,v of adjacency_graphs.qwerty).length KEYPAD_STARTING_POSITIONS: (k for k,v of adjacency_graphs.keypad).length spatial_guesses: (match) -> if match.graph in ['qwerty', 'dvorak'] s = @KEYBOARD_STARTING_POSITIONS d = @KEYBOARD_AVERAGE_DEGREE else s = @KEYPAD_STARTING_POSITIONS d = @KEYPAD_AVERAGE_DEGREE guesses = 0 L = match.token.length t = match.turns # estimate the number of possible patterns w/ length L or less with t turns or less. for i in [2..L] possible_turns = Math.min(t, i - 1) for j in [1..possible_turns] guesses += @nCk(i - 1, j - 1) * s * Math.pow(d, j) # add extra guesses for shifted keys. (% instead of 5, A instead of a.) # math is similar to extra guesses of l33t substitutions in dictionary matches. if match.shifted_count S = match.shifted_count U = match.token.length - match.shifted_count # unshifted count if S == 0 or U == 0 guesses *= 2 else shifted_variations = 0 shifted_variations += @nCk(S + U, i) for i in [1..Math.min(S, U)] guesses *= shifted_variations guesses dictionary_guesses: (match) -> match.base_guesses = match.rank # keep these as properties for display purposes match.uppercase_variations = @uppercase_variations match match.l33t_variations = @l33t_variations match reversed_variations = match.reversed and 2 or 1 match.base_guesses * match.uppercase_variations * match.l33t_variations * reversed_variations START_UPPER: /^[A-Z][^A-Z]+$/ END_UPPER: /^[^A-Z]+[A-Z]$/ ALL_UPPER: /^[^a-z]+$/ ALL_LOWER: /^[^A-Z]+$/ uppercase_variations: (match) -> word = match.token return 1 if word.match @ALL_LOWER # a capitalized word is the most common capitalization scheme, # so it only doubles the search space (uncapitalized + capitalized). # allcaps and end-capitalized are common enough too, underestimate as 2x factor to be safe. for regex in [@START_UPPER, @END_UPPER, @ALL_UPPER] return 2 if word.match regex # otherwise calculate the number of ways to capitalize U+L uppercase+lowercase letters # with U uppercase letters or less. or, if there's more uppercase than lower (for eg. PASSwORD), # the number of ways to lowercase U+L letters with L lowercase letters or less. U = (chr for chr in word.split('') when chr.match /[A-Z]/).length L = (chr for chr in word.split('') when chr.match /[a-z]/).length variations = 0 variations += @nCk(U + L, i) for i in [1..Math.min(U, L)] variations l33t_variations: (match) -> return 1 if not match.l33t variations = 1 for subbed, unsubbed of match.sub # lower-case match.token before calculating: capitalization shouldn't affect l33t calc. chrs = match.token.toLowerCase().split('') S = (chr for chr in chrs when chr == subbed).length # num of subbed chars U = (chr for chr in chrs when chr == unsubbed).length # num of unsubbed chars if S == 0 or U == 0 # for this sub, password is either fully subbed (444) or fully unsubbed (aaa) # treat that as doubling the space (attacker needs to try fully subbed chars in addition to # unsubbed.) variations *= 2 else # this case is similar to capitalization: # with aa44a, U = 3, S = 2, attacker needs to try unsubbed + one sub + two subs p = Math.min(U, S) possibilities = 0 possibilities += @nCk(U + S, i) for i in [1..p] variations *= possibilities variations # utilities -------------------------------------------------------------------- cardinality: (password) -> [lower, upper, digits, symbols, latin1_symbols, latin1_letters] = ( false for i in [0...6] ) unicode_codepoints = [] for chr in password.split('') ord = chr.charCodeAt(0) if 0x30 <= ord <= 0x39 digits = true else if 0x41 <= ord <= 0x5a upper = true else if 0x61 <= ord <= 0x7a lower = true else if ord <= 0x7f symbols = true else if 0x80 <= ord <= 0xBF latin1_symbols = true else if 0xC0 <= ord <= 0xFF latin1_letters = true else if ord > 0xFF unicode_codepoints.push ord c = 0 c += 10 if digits c += 26 if upper c += 26 if lower c += 33 if symbols c += 64 if latin1_symbols c += 64 if latin1_letters if unicode_codepoints.length min_cp = max_cp = unicode_codepoints[0] for cp in unicode_codepoints[1..] min_cp = cp if cp < min_cp max_cp = cp if cp > max_cp # if the range between unicode codepoints is small, # assume one extra alphabet is in use (eg cyrillic, korean) and add a ballpark +40 # # if the range is large, be very conservative and add +100 instead of the range. # (codepoint distance between chinese chars can be many thousand, for example, # but that cardinality boost won't be justified if the characters are common.) range = max_cp - min_cp + 1 range = 40 if range < 40 range = 100 if range > 100 c += range c module.exports = scoring
true
adjacency_graphs = require('./adjacency_graphs') # on qwerty, 'g' has degree 6, being adjacent to 'ftyhbv'. '\' has degree 1. # this calculates the average over all keys. calc_average_degree = (graph) -> average = 0 for key, neighbors of graph average += (n for n in neighbors when n).length average /= (k for k,v of graph).length average scoring = nCk: (n, k) -> # http://blog.plover.com/math/choose.html return 0 if k > n return 1 if k == 0 r = 1 for d in [1..k] r *= n r /= d n -= 1 r log10: (n) -> Math.log(n) / Math.log(10) # IE doesn't support Math.log10 :( log2: (n) -> Math.log(n) / Math.log(2) factorial: (n) -> # unoptimized, called only on small n return 1 if n < 2 f = 1 f *= i for i in [2..n] f # ------------------------------------------------------------------------------ # search --- most guessable match sequence ------------------------------------- # ------------------------------------------------------------------------------ # # takes a list of overlapping matches, returns the non-overlapping sublist with # minimum guesses. O(nm) dp alg for length-n password with m candidate matches. # # the optimal "minimum guesses" sublist is here defined to be the sublist that # minimizes: # # product(m.guesses for m in sequence) * factorial(sequence.length) # # the factorial term is the number of ways to order n patterns. it serves as a # light penalty for longer sequences. # # for example, consider a sequence that is date-repeat-dictionary. # - an attacker would need to try other date-repeat-dictionary combinations, # hence the product term. # - an attacker would need to try repeat-date-dictionary, dictionary-repeat-date, # ..., hence the factorial term. # - an attacker would also likely try length-1 and length-2 sequences before # length-3. those terms tend to be small in comparison and are excluded # for simplicity. # # ------------------------------------------------------------------------------ most_guessable_match_sequence: (password, matches) -> # at index k, the product of guesses of the optimal sequence covering password[0..k] optimal_product = [] # at index k, the number of matches in the optimal sequence covering password[0..k]. # used to calculate the factorial term. optimal_sequence_length = [] # if the optimal sequence ends in a bruteforce match, this records those bruteforce # characters, otherwise '' ending_bruteforce_chars = '' # at index k, the final match (match.j == k) in said optimal sequence. backpointers = [] make_bruteforce_match = (i, j) => cardinality = @cardinality password[i..j] guesses = Math.pow cardinality, j - i + 1 # return object: pattern: 'bruteforce' i: i j: j token: password[i..j] guesses: guesses guesses_log10: @log10(guesses) cardinality: cardinality length: j - i + 1 for k in [0...password.length] # starting scenario to beat: # adding a brute-force character to the sequence with min guesses at k-1. ending_bruteforce_chars += password.charAt(k) l = ending_bruteforce_chars.length optimal_product[k] = Math.pow @cardinality(ending_bruteforce_chars), l optimal_sequence_length[k] = 1 if k - l >= 0 optimal_product[k] *= optimal_product[k - l] optimal_sequence_length[k] += optimal_sequence_length[k - l] backpointers[k] = make_bruteforce_match(k - l + 1, k) minimum_guesses = optimal_product[k] * @factorial optimal_sequence_length[k] for match in matches when match.j == k [i, j] = [match.i, match.j] candidate_product = @estimate_guesses match candidate_length = 1 if i - 1 >= 0 candidate_product *= optimal_product[i - 1] candidate_length += optimal_sequence_length[i - 1] candidate_guesses = candidate_product * @factorial candidate_length if candidate_guesses < minimum_guesses minimum_guesses = candidate_guesses ending_bruteforce_chars = '' optimal_product[k] = candidate_product optimal_sequence_length[k] = candidate_length backpointers[k] = match # walk backwards and decode the best sequence match_sequence = [] k = password.length - 1 while k >= 0 match = backpointers[k] match_sequence.push match k = match.i - 1 match_sequence.reverse() if password.length > 0 sequence_length_multiplier = @factorial optimal_sequence_length[password.length - 1] guesses = optimal_product[password.length - 1] * sequence_length_multiplier else sequence_length_multiplier = 1 guesses = 1 # final result object password: PI:PASSWORD:<PASSWORD>END_PI guesses: guesses guesses_log10: @log10 guesses sequence_product_log10: @log10(optimal_product[password.length - 1]) sequence_length_multiplier_log10: @log10 sequence_length_multiplier sequence: match_sequence # ------------------------------------------------------------------------------ # guess estimation -- one function per match pattern --------------------------- # ------------------------------------------------------------------------------ estimate_guesses: (match) -> return match.guesses if match.guesses? # a match's guess estimate doesn't change. cache it. estimation_functions = dictionary: @dictionary_guesses spatial: @spatial_guesses repeat: @repeat_guesses sequence: @sequence_guesses regex: @regex_guesses date: @date_guesses match.guesses = estimation_functions[match.pattern].call this, match match.guesses_log10 = @log10 match.guesses match.guesses repeat_guesses: (match) -> match.base_guesses * match.repeat_count sequence_guesses: (match) -> first_chr = match.token.charAt(0) # lower guesses for obvious starting points if first_chr in ['a', 'A', 'z', 'Z', '0', '1', '9'] base_guesses = 4 else if first_chr.match /\d/ base_guesses = 10 # digits else # could give a higher base for uppercase, # assigning 26 to both upper and lower sequences is more conservative. base_guesses = 26 if not match.ascending # need to try a descending sequence in addition to every ascending sequence -> # 2x guesses base_guesses *= 2 base_guesses * match.token.length MIN_YEAR_SPACE: 20 REFERENCE_YEAR: 2000 regex_guesses: (match) -> char_class_bases = alpha_lower: 26 alpha_upper: 26 alpha: 52 alphanumeric: 62 digits: 10 symbols: 33 if match.regex_name of char_class_bases Math.pow(char_class_bases[match.regex_name], match.token.length) else switch match.regex_name when 'recent_year' # conservative estimate of year space: num years from REFERENCE_YEAR. # if year is close to REFERENCE_YEAR, estimate a year space of MIN_YEAR_SPACE. year_space = Math.abs parseInt(match.regex_match[0]) - @REFERENCE_YEAR year_space = Math.max year_space, @MIN_YEAR_SPACE year_space date_guesses: (match) -> # base guesses: (year distance from REFERENCE_YEAR) * num_days * num_years year_space = Math.max(Math.abs(match.year - @REFERENCE_YEAR), @MIN_YEAR_SPACE) guesses = year_space * 31 * 12 # double for four-digit years guesses *= 2 if match.has_full_year # add factor of 4 for separator selection (one of ~4 choices) guesses *= 4 if match.separator guesses KEYBOARD_AVERAGE_DEGREE: calc_average_degree(adjacency_graphs.qwerty) # slightly different for keypad/mac keypad, but close enough KEYPAD_AVERAGE_DEGREE: calc_average_degree(adjacency_graphs.keypad) KEYBOARD_STARTING_POSITIONS: (k for k,v of adjacency_graphs.qwerty).length KEYPAD_STARTING_POSITIONS: (k for k,v of adjacency_graphs.keypad).length spatial_guesses: (match) -> if match.graph in ['qwerty', 'dvorak'] s = @KEYBOARD_STARTING_POSITIONS d = @KEYBOARD_AVERAGE_DEGREE else s = @KEYPAD_STARTING_POSITIONS d = @KEYPAD_AVERAGE_DEGREE guesses = 0 L = match.token.length t = match.turns # estimate the number of possible patterns w/ length L or less with t turns or less. for i in [2..L] possible_turns = Math.min(t, i - 1) for j in [1..possible_turns] guesses += @nCk(i - 1, j - 1) * s * Math.pow(d, j) # add extra guesses for shifted keys. (% instead of 5, A instead of a.) # math is similar to extra guesses of l33t substitutions in dictionary matches. if match.shifted_count S = match.shifted_count U = match.token.length - match.shifted_count # unshifted count if S == 0 or U == 0 guesses *= 2 else shifted_variations = 0 shifted_variations += @nCk(S + U, i) for i in [1..Math.min(S, U)] guesses *= shifted_variations guesses dictionary_guesses: (match) -> match.base_guesses = match.rank # keep these as properties for display purposes match.uppercase_variations = @uppercase_variations match match.l33t_variations = @l33t_variations match reversed_variations = match.reversed and 2 or 1 match.base_guesses * match.uppercase_variations * match.l33t_variations * reversed_variations START_UPPER: /^[A-Z][^A-Z]+$/ END_UPPER: /^[^A-Z]+[A-Z]$/ ALL_UPPER: /^[^a-z]+$/ ALL_LOWER: /^[^A-Z]+$/ uppercase_variations: (match) -> word = match.token return 1 if word.match @ALL_LOWER # a capitalized word is the most common capitalization scheme, # so it only doubles the search space (uncapitalized + capitalized). # allcaps and end-capitalized are common enough too, underestimate as 2x factor to be safe. for regex in [@START_UPPER, @END_UPPER, @ALL_UPPER] return 2 if word.match regex # otherwise calculate the number of ways to capitalize U+L uppercase+lowercase letters # with U uppercase letters or less. or, if there's more uppercase than lower (for eg. PASSwORD), # the number of ways to lowercase U+L letters with L lowercase letters or less. U = (chr for chr in word.split('') when chr.match /[A-Z]/).length L = (chr for chr in word.split('') when chr.match /[a-z]/).length variations = 0 variations += @nCk(U + L, i) for i in [1..Math.min(U, L)] variations l33t_variations: (match) -> return 1 if not match.l33t variations = 1 for subbed, unsubbed of match.sub # lower-case match.token before calculating: capitalization shouldn't affect l33t calc. chrs = match.token.toLowerCase().split('') S = (chr for chr in chrs when chr == subbed).length # num of subbed chars U = (chr for chr in chrs when chr == unsubbed).length # num of unsubbed chars if S == 0 or U == 0 # for this sub, password is either fully subbed (444) or fully unsubbed (aaa) # treat that as doubling the space (attacker needs to try fully subbed chars in addition to # unsubbed.) variations *= 2 else # this case is similar to capitalization: # with aa44a, U = 3, S = 2, attacker needs to try unsubbed + one sub + two subs p = Math.min(U, S) possibilities = 0 possibilities += @nCk(U + S, i) for i in [1..p] variations *= possibilities variations # utilities -------------------------------------------------------------------- cardinality: (password) -> [lower, upper, digits, symbols, latin1_symbols, latin1_letters] = ( false for i in [0...6] ) unicode_codepoints = [] for chr in password.split('') ord = chr.charCodeAt(0) if 0x30 <= ord <= 0x39 digits = true else if 0x41 <= ord <= 0x5a upper = true else if 0x61 <= ord <= 0x7a lower = true else if ord <= 0x7f symbols = true else if 0x80 <= ord <= 0xBF latin1_symbols = true else if 0xC0 <= ord <= 0xFF latin1_letters = true else if ord > 0xFF unicode_codepoints.push ord c = 0 c += 10 if digits c += 26 if upper c += 26 if lower c += 33 if symbols c += 64 if latin1_symbols c += 64 if latin1_letters if unicode_codepoints.length min_cp = max_cp = unicode_codepoints[0] for cp in unicode_codepoints[1..] min_cp = cp if cp < min_cp max_cp = cp if cp > max_cp # if the range between unicode codepoints is small, # assume one extra alphabet is in use (eg cyrillic, korean) and add a ballpark +40 # # if the range is large, be very conservative and add +100 instead of the range. # (codepoint distance between chinese chars can be many thousand, for example, # but that cardinality boost won't be justified if the characters are common.) range = max_cp - min_cp + 1 range = 40 if range < 40 range = 100 if range > 100 c += range c module.exports = scoring
[ { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri", "end": 42, "score": 0.9998431205749512, "start": 24, "tag": "NAME", "value": "Alexander Cherniuk" }, { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistribution and use in ", "end": 60, "score": 0.9999298453330994, "start": 44, "tag": "EMAIL", "value": "ts33kr@gmail.com" } ]
library/membrane/api.coffee
ts33kr/granite
6
### Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" logger = require "winston" crossroads = require "crossroads" uuid = require "node-uuid" assert = require "assert" colors = require "colors" crypto = require "crypto" nconf = require "nconf" async = require "async" https = require "https" weak = require "weak" http = require "http" util = require "util" url = require "url" {EOL} = require "os" {format} = require "util" {STATUS_CODES} = require "http" {Barebones} = require "./skeleton" {EndpointToolkit} = require "./endpoint" {remote, external} = require "./remote" # This is an abstract base class for creating services that expose # their functionality as API. The general structure of API is a REST. # Although it is not strictly limited by this ABC, and anything within # the HTTP architecture is basically allowed and can be implemented. # The ABC provides not only the tool set for API definition, but also # an additional tool set for supplementing the APIs with documentation. module.exports.ApiService = class ApiService extends Barebones # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # These declarations below are implantations of the abstracted # components by the means of the dynamic recomposition system. # Please take a look at the `Composition` class implementation # for all sorts of information on the composition system itself. # Each of these will be dynamicall integrated in class hierarchy. @implanting EndpointToolkit # Symbol declaration table, that states what keys, if those are # vectors (arrays) should be exported and then merged with their # counterparts in the destination, once the composition process # takes place. See the `Archetype::composition` hook definition # for more information. Keys are names, values can be anything. @COMPOSITION_EXPORTS: definitions: yes # Walk over list of supported HTTP methods/verbs, defined in # the `RestfulService` abstract base class member `SUPPORTED` # and create a shorthand route definition for an every method. # These shorthand definitions will greatly simplify making new # routes, since they are much shorter than using a full blown # signature of the `define` method in this abstract base class. (do (m) => @[m] = -> @api m, arguments...) for m in @SUPPORTED (assert (this[m.toLowerCase()] = this[m])) for m in @SUPPORTED # The decorator that can be applied to the immediate function # that implements an API declaration. When applied to such fun, # when an API is executed, in case if there is any error in an # implementation, instead of running the exception & rescuing # mechanism, it will automatically respond with the requester # with the specially formed JSON object, describing an error. # This is useful for creating the resistent to failures APIs. this.guard = this.fail = this.g = (implement) -> -> misused = "no implementation func supplied" unisolated = "no isolation engine detected" message = "Invoking a protected API in an %s" invaRequest = "fail to find isolated request" identify = @constructor.identify().underline assert _.isArguments try captured = arguments assert _.isFunction(implement or 0), misused assert @__origin and @__isolated, unisolated assert _.isObject(this.request), invaRequest assert _.isObject ndomain = require "domain" assert _.isObject domain = ndomain.create() assert _.isObject r = this.response or null try logger.debug message.yellow, identify incStack = try nconf.get "api:includeStack" ev = (e, r) => this.emit "guad-error", e, r st = (e) => (incStack and e.stack) or null js = (e) => message: e.message, stack: st(e) kills = (e) => r.send 500, js(e); ev(e, r) @response.on "finish", -> domain.dispose() domain.on "error", (error) -> kills error domain.run => implement.apply @, captured # Process the already macted HTTP request according to the REST # specification. That is, see if the request method conforms to # to the RFC, and if so, dispatch it onto corresponding method # defined in the subclass of this abstract base class. Default # implementation of each method will throw a not implemented. # This implementation executes the processing sequence of the # HTTP request with regards to the Crossroads of the service. process: @spinoff (request, response, next) -> assert identify = try @constructor.identify() assert this.__isolated, "spin-off engine fail" variables = [undefined, undefined] # no token headers = @downstream headers: -> return null partial = _.partial headers, request, response response.on "header", -> partial variables... assert _.isObject request.service = weak this assert mw = @constructor.middleware().bind this signature = [request, response, variables...] message = "Executing Crossroads routing in %s" intake = (func) => @downstream processing: func go = (fn) => usp = intake fn; usp signature... go => mw(signature) (error, results, misc) => assert expanded = _.clone variables or [] expanded.push request.session or undefined malfunction = "no crossroads in an instance" path = url.parse(request.url).pathname or 0 assert _.isObject(@crossroads), malfunction assert _.isString(path), "no request paths" assert copy = Object.create String.prototype assert _.isFunction(copy.toString = -> path) assert copy.method = request.method or null logger.debug message.green, identify or 0 return this.crossroads.parse copy, [this] # This method determines whether the supplied HTTP request # matches this service. This is determined by examining the # domain/host and the path, in accordance with the patterns # that were used for configuring the class of this service. # It is async, so be sure to call the `decide` with boolean! # This implementation checks whether an HTTP request matches # at least one router in the Crossroads instance of service. matches: (request, response, decide) -> assert _.isObject(request), "got invalid request" assert _.isFunction(decide), "incorrect callback" conditions = try @constructor.condition() or null conditions = Array() unless _.isArray conditions identify = try @constructor?.identify().underline return decide no if @constructor.DISABLE_SERVICE p = (i, cn) -> i.limitation request, response, cn fails = "Service #{identify} fails some conditions" notify = "Running %s service conditional sequences" message = "Polling %s service for Crossroads match" logger.debug notify.toString(), identify.toString() logger.debug message.toString().cyan, identify return async.every conditions, p, (confirms) => logger.debug fails.yellow unless confirms return decide false unless confirms is yes malfunction = "no crossroads in an instance" path = url.parse(request.url).pathname or 0 assert _.isObject(@crossroads), malfunction assert _.isString(path), "no request paths" assert copy = Object.create String.prototype assert _.isFunction(copy.toString = -> path) assert copy.method = request.method or null match = (route) -> return route.match copy decide _.any(@crossroads._routes, match) # A hook that will be called prior to registering the service # implementation. Please refer to this prototype signature for # information on the parameters it accepts. Beware, this hook # is asynchronously wired in, so consult with `async` package. # Please be sure invoke the `next` arg to proceed, if relevant. # This implementation sets up the internals of the API service # that will allow to properly expose and execute the methods. register: (kernel, router, next) -> noted = "Setting up %s Crossroads routes in %s" invalidDefs = "invalid type of the definitions" emptyDoc = "the document sequence is not emptied" noCrossr = "unable to load a Crossroads library" noInh = "cannot be inherited from both toolkits" createRouteWrapper = @createRouteWrapper.bind this try identify = @constructor.identify().underline assert not (try this.objectOf Screenplay), noInh assert crs = @crossroads = crossroads.create() defines = @constructor.define() or new Array() assert _.isArray(defines or null), invalidDefs assert _.isEmpty(@constructor.docs()), emptyDoc assert _.isObject(@crossroads or 0), noCrossr assert amount = defines.length.toString().bold try logger.debug noted.yellow, amount, identify async.each defines, createRouteWrapper, next # Part of the internal implementation of the API engine. It # is used to create the wrapping around the Crossroads route # handler. This wrapping is very tightly inegrated with this # abstract base class internals, as well as with the internal # design of some of the parent classes, namely `RestfulService`. # The wrapping provides important boilerplate to set up scope. createRouteWrapper: (definition, next) -> register = "Adding Crossroads route %s to %s" noCross = "no Crossroads router in the service" assert _.isObject(crs = @crossroads), noCross identify = @constructor.identify().underline assert method = try definition.method or null assert implement = definition.implement or 0 assert rules = rls = definition.rules or {} assert not _.isEmpty mask = definition.mask assert p = (mask.source or mask).underline logger.debug register.magenta, p, identify fr = (q) => q.method.toUpperCase() is method rx = (r) => r.rules = rls; rls.request_ = fr fx = (f) => rx crs.addRoute mask, f; next() fx (shadow, parameters...) -> # the wrapper assert (shadow.__isolated or 0) is yes assert _.isObject shadow.__origin or 0 implement.apply shadow, parameters # Define a new API and all of its attributes. Among those # arguments there is an API implementation function and an # URL mask for routing that API and an HTTP version to use # for matching this API. Please consult with a `Crossroads` # package for information on the mask, which can be string # or a regular expression. Also, please see implementation. this.define = this.api = (method, mask, implement) -> wrongMask = "a mask has to be string or regex" noImplement = "no implementation fn supplied" invalidMeth = "an HTTP method is not a string" maskStr = _.isString(mask or null) or false maskReg = _.isRegExp(mask or null) or false assert previous = @definitions or new Array() return previous unless arguments.length > 0 assert _.isFunction(implement), noImplement assert _.isString(method or 0), invalidMeth assert (maskStr or maskReg or 0), wrongMask documents = _.clone this.documents or Array() crossRules = _.reduce @crossRules, _.merge paramStore = _.reduce @paramStore, _.merge delete @documents if @documents # clear doc delete @crossRules if @crossRules # rm rule delete @paramStore if @paramStore # rm argv documents.push method: method.toUpperCase() documents.push mask: (mask?.source or mask) documents.push uid: uid = uuid.v1() or null fn = (arbitraryVector) -> return implement return fn @definitions = previous.concat documents: documents # documentation implement: implement # implements fn params: paramStore # parameters/argv rules: crossRules # Crossroads rules method: method.toUpperCase() # HTTP mask: mask # URL mask for routing uid: uid # unique ID (UUID) tag
128109
### Copyright (c) 2013, <NAME> <<EMAIL>> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" logger = require "winston" crossroads = require "crossroads" uuid = require "node-uuid" assert = require "assert" colors = require "colors" crypto = require "crypto" nconf = require "nconf" async = require "async" https = require "https" weak = require "weak" http = require "http" util = require "util" url = require "url" {EOL} = require "os" {format} = require "util" {STATUS_CODES} = require "http" {Barebones} = require "./skeleton" {EndpointToolkit} = require "./endpoint" {remote, external} = require "./remote" # This is an abstract base class for creating services that expose # their functionality as API. The general structure of API is a REST. # Although it is not strictly limited by this ABC, and anything within # the HTTP architecture is basically allowed and can be implemented. # The ABC provides not only the tool set for API definition, but also # an additional tool set for supplementing the APIs with documentation. module.exports.ApiService = class ApiService extends Barebones # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # These declarations below are implantations of the abstracted # components by the means of the dynamic recomposition system. # Please take a look at the `Composition` class implementation # for all sorts of information on the composition system itself. # Each of these will be dynamicall integrated in class hierarchy. @implanting EndpointToolkit # Symbol declaration table, that states what keys, if those are # vectors (arrays) should be exported and then merged with their # counterparts in the destination, once the composition process # takes place. See the `Archetype::composition` hook definition # for more information. Keys are names, values can be anything. @COMPOSITION_EXPORTS: definitions: yes # Walk over list of supported HTTP methods/verbs, defined in # the `RestfulService` abstract base class member `SUPPORTED` # and create a shorthand route definition for an every method. # These shorthand definitions will greatly simplify making new # routes, since they are much shorter than using a full blown # signature of the `define` method in this abstract base class. (do (m) => @[m] = -> @api m, arguments...) for m in @SUPPORTED (assert (this[m.toLowerCase()] = this[m])) for m in @SUPPORTED # The decorator that can be applied to the immediate function # that implements an API declaration. When applied to such fun, # when an API is executed, in case if there is any error in an # implementation, instead of running the exception & rescuing # mechanism, it will automatically respond with the requester # with the specially formed JSON object, describing an error. # This is useful for creating the resistent to failures APIs. this.guard = this.fail = this.g = (implement) -> -> misused = "no implementation func supplied" unisolated = "no isolation engine detected" message = "Invoking a protected API in an %s" invaRequest = "fail to find isolated request" identify = @constructor.identify().underline assert _.isArguments try captured = arguments assert _.isFunction(implement or 0), misused assert @__origin and @__isolated, unisolated assert _.isObject(this.request), invaRequest assert _.isObject ndomain = require "domain" assert _.isObject domain = ndomain.create() assert _.isObject r = this.response or null try logger.debug message.yellow, identify incStack = try nconf.get "api:includeStack" ev = (e, r) => this.emit "guad-error", e, r st = (e) => (incStack and e.stack) or null js = (e) => message: e.message, stack: st(e) kills = (e) => r.send 500, js(e); ev(e, r) @response.on "finish", -> domain.dispose() domain.on "error", (error) -> kills error domain.run => implement.apply @, captured # Process the already macted HTTP request according to the REST # specification. That is, see if the request method conforms to # to the RFC, and if so, dispatch it onto corresponding method # defined in the subclass of this abstract base class. Default # implementation of each method will throw a not implemented. # This implementation executes the processing sequence of the # HTTP request with regards to the Crossroads of the service. process: @spinoff (request, response, next) -> assert identify = try @constructor.identify() assert this.__isolated, "spin-off engine fail" variables = [undefined, undefined] # no token headers = @downstream headers: -> return null partial = _.partial headers, request, response response.on "header", -> partial variables... assert _.isObject request.service = weak this assert mw = @constructor.middleware().bind this signature = [request, response, variables...] message = "Executing Crossroads routing in %s" intake = (func) => @downstream processing: func go = (fn) => usp = intake fn; usp signature... go => mw(signature) (error, results, misc) => assert expanded = _.clone variables or [] expanded.push request.session or undefined malfunction = "no crossroads in an instance" path = url.parse(request.url).pathname or 0 assert _.isObject(@crossroads), malfunction assert _.isString(path), "no request paths" assert copy = Object.create String.prototype assert _.isFunction(copy.toString = -> path) assert copy.method = request.method or null logger.debug message.green, identify or 0 return this.crossroads.parse copy, [this] # This method determines whether the supplied HTTP request # matches this service. This is determined by examining the # domain/host and the path, in accordance with the patterns # that were used for configuring the class of this service. # It is async, so be sure to call the `decide` with boolean! # This implementation checks whether an HTTP request matches # at least one router in the Crossroads instance of service. matches: (request, response, decide) -> assert _.isObject(request), "got invalid request" assert _.isFunction(decide), "incorrect callback" conditions = try @constructor.condition() or null conditions = Array() unless _.isArray conditions identify = try @constructor?.identify().underline return decide no if @constructor.DISABLE_SERVICE p = (i, cn) -> i.limitation request, response, cn fails = "Service #{identify} fails some conditions" notify = "Running %s service conditional sequences" message = "Polling %s service for Crossroads match" logger.debug notify.toString(), identify.toString() logger.debug message.toString().cyan, identify return async.every conditions, p, (confirms) => logger.debug fails.yellow unless confirms return decide false unless confirms is yes malfunction = "no crossroads in an instance" path = url.parse(request.url).pathname or 0 assert _.isObject(@crossroads), malfunction assert _.isString(path), "no request paths" assert copy = Object.create String.prototype assert _.isFunction(copy.toString = -> path) assert copy.method = request.method or null match = (route) -> return route.match copy decide _.any(@crossroads._routes, match) # A hook that will be called prior to registering the service # implementation. Please refer to this prototype signature for # information on the parameters it accepts. Beware, this hook # is asynchronously wired in, so consult with `async` package. # Please be sure invoke the `next` arg to proceed, if relevant. # This implementation sets up the internals of the API service # that will allow to properly expose and execute the methods. register: (kernel, router, next) -> noted = "Setting up %s Crossroads routes in %s" invalidDefs = "invalid type of the definitions" emptyDoc = "the document sequence is not emptied" noCrossr = "unable to load a Crossroads library" noInh = "cannot be inherited from both toolkits" createRouteWrapper = @createRouteWrapper.bind this try identify = @constructor.identify().underline assert not (try this.objectOf Screenplay), noInh assert crs = @crossroads = crossroads.create() defines = @constructor.define() or new Array() assert _.isArray(defines or null), invalidDefs assert _.isEmpty(@constructor.docs()), emptyDoc assert _.isObject(@crossroads or 0), noCrossr assert amount = defines.length.toString().bold try logger.debug noted.yellow, amount, identify async.each defines, createRouteWrapper, next # Part of the internal implementation of the API engine. It # is used to create the wrapping around the Crossroads route # handler. This wrapping is very tightly inegrated with this # abstract base class internals, as well as with the internal # design of some of the parent classes, namely `RestfulService`. # The wrapping provides important boilerplate to set up scope. createRouteWrapper: (definition, next) -> register = "Adding Crossroads route %s to %s" noCross = "no Crossroads router in the service" assert _.isObject(crs = @crossroads), noCross identify = @constructor.identify().underline assert method = try definition.method or null assert implement = definition.implement or 0 assert rules = rls = definition.rules or {} assert not _.isEmpty mask = definition.mask assert p = (mask.source or mask).underline logger.debug register.magenta, p, identify fr = (q) => q.method.toUpperCase() is method rx = (r) => r.rules = rls; rls.request_ = fr fx = (f) => rx crs.addRoute mask, f; next() fx (shadow, parameters...) -> # the wrapper assert (shadow.__isolated or 0) is yes assert _.isObject shadow.__origin or 0 implement.apply shadow, parameters # Define a new API and all of its attributes. Among those # arguments there is an API implementation function and an # URL mask for routing that API and an HTTP version to use # for matching this API. Please consult with a `Crossroads` # package for information on the mask, which can be string # or a regular expression. Also, please see implementation. this.define = this.api = (method, mask, implement) -> wrongMask = "a mask has to be string or regex" noImplement = "no implementation fn supplied" invalidMeth = "an HTTP method is not a string" maskStr = _.isString(mask or null) or false maskReg = _.isRegExp(mask or null) or false assert previous = @definitions or new Array() return previous unless arguments.length > 0 assert _.isFunction(implement), noImplement assert _.isString(method or 0), invalidMeth assert (maskStr or maskReg or 0), wrongMask documents = _.clone this.documents or Array() crossRules = _.reduce @crossRules, _.merge paramStore = _.reduce @paramStore, _.merge delete @documents if @documents # clear doc delete @crossRules if @crossRules # rm rule delete @paramStore if @paramStore # rm argv documents.push method: method.toUpperCase() documents.push mask: (mask?.source or mask) documents.push uid: uid = uuid.v1() or null fn = (arbitraryVector) -> return implement return fn @definitions = previous.concat documents: documents # documentation implement: implement # implements fn params: paramStore # parameters/argv rules: crossRules # Crossroads rules method: method.toUpperCase() # HTTP mask: mask # URL mask for routing uid: uid # unique ID (UUID) tag
true
### Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" logger = require "winston" crossroads = require "crossroads" uuid = require "node-uuid" assert = require "assert" colors = require "colors" crypto = require "crypto" nconf = require "nconf" async = require "async" https = require "https" weak = require "weak" http = require "http" util = require "util" url = require "url" {EOL} = require "os" {format} = require "util" {STATUS_CODES} = require "http" {Barebones} = require "./skeleton" {EndpointToolkit} = require "./endpoint" {remote, external} = require "./remote" # This is an abstract base class for creating services that expose # their functionality as API. The general structure of API is a REST. # Although it is not strictly limited by this ABC, and anything within # the HTTP architecture is basically allowed and can be implemented. # The ABC provides not only the tool set for API definition, but also # an additional tool set for supplementing the APIs with documentation. module.exports.ApiService = class ApiService extends Barebones # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # These declarations below are implantations of the abstracted # components by the means of the dynamic recomposition system. # Please take a look at the `Composition` class implementation # for all sorts of information on the composition system itself. # Each of these will be dynamicall integrated in class hierarchy. @implanting EndpointToolkit # Symbol declaration table, that states what keys, if those are # vectors (arrays) should be exported and then merged with their # counterparts in the destination, once the composition process # takes place. See the `Archetype::composition` hook definition # for more information. Keys are names, values can be anything. @COMPOSITION_EXPORTS: definitions: yes # Walk over list of supported HTTP methods/verbs, defined in # the `RestfulService` abstract base class member `SUPPORTED` # and create a shorthand route definition for an every method. # These shorthand definitions will greatly simplify making new # routes, since they are much shorter than using a full blown # signature of the `define` method in this abstract base class. (do (m) => @[m] = -> @api m, arguments...) for m in @SUPPORTED (assert (this[m.toLowerCase()] = this[m])) for m in @SUPPORTED # The decorator that can be applied to the immediate function # that implements an API declaration. When applied to such fun, # when an API is executed, in case if there is any error in an # implementation, instead of running the exception & rescuing # mechanism, it will automatically respond with the requester # with the specially formed JSON object, describing an error. # This is useful for creating the resistent to failures APIs. this.guard = this.fail = this.g = (implement) -> -> misused = "no implementation func supplied" unisolated = "no isolation engine detected" message = "Invoking a protected API in an %s" invaRequest = "fail to find isolated request" identify = @constructor.identify().underline assert _.isArguments try captured = arguments assert _.isFunction(implement or 0), misused assert @__origin and @__isolated, unisolated assert _.isObject(this.request), invaRequest assert _.isObject ndomain = require "domain" assert _.isObject domain = ndomain.create() assert _.isObject r = this.response or null try logger.debug message.yellow, identify incStack = try nconf.get "api:includeStack" ev = (e, r) => this.emit "guad-error", e, r st = (e) => (incStack and e.stack) or null js = (e) => message: e.message, stack: st(e) kills = (e) => r.send 500, js(e); ev(e, r) @response.on "finish", -> domain.dispose() domain.on "error", (error) -> kills error domain.run => implement.apply @, captured # Process the already macted HTTP request according to the REST # specification. That is, see if the request method conforms to # to the RFC, and if so, dispatch it onto corresponding method # defined in the subclass of this abstract base class. Default # implementation of each method will throw a not implemented. # This implementation executes the processing sequence of the # HTTP request with regards to the Crossroads of the service. process: @spinoff (request, response, next) -> assert identify = try @constructor.identify() assert this.__isolated, "spin-off engine fail" variables = [undefined, undefined] # no token headers = @downstream headers: -> return null partial = _.partial headers, request, response response.on "header", -> partial variables... assert _.isObject request.service = weak this assert mw = @constructor.middleware().bind this signature = [request, response, variables...] message = "Executing Crossroads routing in %s" intake = (func) => @downstream processing: func go = (fn) => usp = intake fn; usp signature... go => mw(signature) (error, results, misc) => assert expanded = _.clone variables or [] expanded.push request.session or undefined malfunction = "no crossroads in an instance" path = url.parse(request.url).pathname or 0 assert _.isObject(@crossroads), malfunction assert _.isString(path), "no request paths" assert copy = Object.create String.prototype assert _.isFunction(copy.toString = -> path) assert copy.method = request.method or null logger.debug message.green, identify or 0 return this.crossroads.parse copy, [this] # This method determines whether the supplied HTTP request # matches this service. This is determined by examining the # domain/host and the path, in accordance with the patterns # that were used for configuring the class of this service. # It is async, so be sure to call the `decide` with boolean! # This implementation checks whether an HTTP request matches # at least one router in the Crossroads instance of service. matches: (request, response, decide) -> assert _.isObject(request), "got invalid request" assert _.isFunction(decide), "incorrect callback" conditions = try @constructor.condition() or null conditions = Array() unless _.isArray conditions identify = try @constructor?.identify().underline return decide no if @constructor.DISABLE_SERVICE p = (i, cn) -> i.limitation request, response, cn fails = "Service #{identify} fails some conditions" notify = "Running %s service conditional sequences" message = "Polling %s service for Crossroads match" logger.debug notify.toString(), identify.toString() logger.debug message.toString().cyan, identify return async.every conditions, p, (confirms) => logger.debug fails.yellow unless confirms return decide false unless confirms is yes malfunction = "no crossroads in an instance" path = url.parse(request.url).pathname or 0 assert _.isObject(@crossroads), malfunction assert _.isString(path), "no request paths" assert copy = Object.create String.prototype assert _.isFunction(copy.toString = -> path) assert copy.method = request.method or null match = (route) -> return route.match copy decide _.any(@crossroads._routes, match) # A hook that will be called prior to registering the service # implementation. Please refer to this prototype signature for # information on the parameters it accepts. Beware, this hook # is asynchronously wired in, so consult with `async` package. # Please be sure invoke the `next` arg to proceed, if relevant. # This implementation sets up the internals of the API service # that will allow to properly expose and execute the methods. register: (kernel, router, next) -> noted = "Setting up %s Crossroads routes in %s" invalidDefs = "invalid type of the definitions" emptyDoc = "the document sequence is not emptied" noCrossr = "unable to load a Crossroads library" noInh = "cannot be inherited from both toolkits" createRouteWrapper = @createRouteWrapper.bind this try identify = @constructor.identify().underline assert not (try this.objectOf Screenplay), noInh assert crs = @crossroads = crossroads.create() defines = @constructor.define() or new Array() assert _.isArray(defines or null), invalidDefs assert _.isEmpty(@constructor.docs()), emptyDoc assert _.isObject(@crossroads or 0), noCrossr assert amount = defines.length.toString().bold try logger.debug noted.yellow, amount, identify async.each defines, createRouteWrapper, next # Part of the internal implementation of the API engine. It # is used to create the wrapping around the Crossroads route # handler. This wrapping is very tightly inegrated with this # abstract base class internals, as well as with the internal # design of some of the parent classes, namely `RestfulService`. # The wrapping provides important boilerplate to set up scope. createRouteWrapper: (definition, next) -> register = "Adding Crossroads route %s to %s" noCross = "no Crossroads router in the service" assert _.isObject(crs = @crossroads), noCross identify = @constructor.identify().underline assert method = try definition.method or null assert implement = definition.implement or 0 assert rules = rls = definition.rules or {} assert not _.isEmpty mask = definition.mask assert p = (mask.source or mask).underline logger.debug register.magenta, p, identify fr = (q) => q.method.toUpperCase() is method rx = (r) => r.rules = rls; rls.request_ = fr fx = (f) => rx crs.addRoute mask, f; next() fx (shadow, parameters...) -> # the wrapper assert (shadow.__isolated or 0) is yes assert _.isObject shadow.__origin or 0 implement.apply shadow, parameters # Define a new API and all of its attributes. Among those # arguments there is an API implementation function and an # URL mask for routing that API and an HTTP version to use # for matching this API. Please consult with a `Crossroads` # package for information on the mask, which can be string # or a regular expression. Also, please see implementation. this.define = this.api = (method, mask, implement) -> wrongMask = "a mask has to be string or regex" noImplement = "no implementation fn supplied" invalidMeth = "an HTTP method is not a string" maskStr = _.isString(mask or null) or false maskReg = _.isRegExp(mask or null) or false assert previous = @definitions or new Array() return previous unless arguments.length > 0 assert _.isFunction(implement), noImplement assert _.isString(method or 0), invalidMeth assert (maskStr or maskReg or 0), wrongMask documents = _.clone this.documents or Array() crossRules = _.reduce @crossRules, _.merge paramStore = _.reduce @paramStore, _.merge delete @documents if @documents # clear doc delete @crossRules if @crossRules # rm rule delete @paramStore if @paramStore # rm argv documents.push method: method.toUpperCase() documents.push mask: (mask?.source or mask) documents.push uid: uid = uuid.v1() or null fn = (arbitraryVector) -> return implement return fn @definitions = previous.concat documents: documents # documentation implement: implement # implements fn params: paramStore # parameters/argv rules: crossRules # Crossroads rules method: method.toUpperCase() # HTTP mask: mask # URL mask for routing uid: uid # unique ID (UUID) tag
[ { "context": "192, 168, 1, 1])\n test.equal(addr.toString(), '192.168.1.1')\n test.done()\n\n 'returns correct kind for IP", "end": 647, "score": 0.9986698031425476, "start": 636, "tag": "IP_ADDRESS", "value": "192.168.1.1" }, { "context": "at': (test) ->\n test.equal(ipaddr.IPv4.isIPv4('192.168.007.0xa'), true)\n test.equal(ipaddr.IPv4.isIPv4('1024.", "end": 1036, "score": 0.9242700338363647, "start": 1021, "tag": "IP_ADDRESS", "value": "192.168.007.0xa" }, { "context": "7.0xa'), true)\n test.equal(ipaddr.IPv4.isIPv4('1024.0.0.1'), true)\n test.equal(ipaddr.IPv4.isIPv4('", "end": 1091, "score": 0.9950284957885742, "start": 1081, "tag": "IP_ADDRESS", "value": "1024.0.0.1" }, { "context": "s': (test) ->\n test.equal(ipaddr.IPv4.isValid('192.168.007.0xa'), true)\n test.equal(ipaddr.IPv4.isVali", "end": 1267, "score": 0.9496976733207703, "start": 1260, "tag": "IP_ADDRESS", "value": "192.168" }, { "context": " ->\n test.equal(ipaddr.IPv4.isValid('192.168.007.0xa'), true)\n test.equal(ipaddr.IPv4.isValid('1", "end": 1271, "score": 0.8022855520248413, "start": 1270, "tag": "IP_ADDRESS", "value": "7" }, { "context": "0xa'), true)\n test.equal(ipaddr.IPv4.isValid('1024.0.0.1'), false)\n test.equal(ipaddr.IPv4.isValid", "end": 1331, "score": 0.9658691883087158, "start": 1322, "tag": "IP_ADDRESS", "value": "024.0.0.1" }, { "context": ": (test) ->\n test.deepEqual(ipaddr.IPv4.parse('192.168.1.1').octets, [192, 168, 1, 1])\n test.deepEqual(i", "end": 1527, "score": 0.9967659115791321, "start": 1516, "tag": "IP_ADDRESS", "value": "192.168.1.1" }, { "context": "68, 1, 1])\n test.deepEqual(ipaddr.IPv4.parse('0xc0.168.1.1').octets, [192, 168, 1, 1])\n test.deepEqual(ip", "end": 1607, "score": 0.9631794095039368, "start": 1596, "tag": "IP_ADDRESS", "value": "xc0.168.1.1" }, { "context": "168, 1, 1])\n test.deepEqual(ipaddr.IPv4.parse('192.0250.1.1').octets, [192, 168, 1, 1])\n test.deepEqual(ip", "end": 1686, "score": 0.9255116581916809, "start": 1674, "tag": "IP_ADDRESS", "value": "192.0250.1.1" }, { "context": "rue)\n test.equal(addr.match(ipaddr.IPv4.parse('11.0.0.0'), 8), false)\n test.equal(addr.match(ipaddr.I", "end": 2286, "score": 0.9996439814567566, "start": 2278, "tag": "IP_ADDRESS", "value": "11.0.0.0" }, { "context": "lse)\n test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.0'), 8), true)\n test.equal(addr.match(ipaddr.IP", "end": 2355, "score": 0.9995759725570679, "start": 2347, "tag": "IP_ADDRESS", "value": "10.0.0.0" }, { "context": "rue)\n test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.1'), 8), true)\n test.equal(addr.match(ipaddr.IP", "end": 2423, "score": 0.9996541142463684, "start": 2415, "tag": "IP_ADDRESS", "value": "10.0.0.1" }, { "context": "rue)\n test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.10'), 8), true)\n test.equal(addr.match(ipaddr.IPv", "end": 2492, "score": 0.9996533989906311, "start": 2483, "tag": "IP_ADDRESS", "value": "10.0.0.10" }, { "context": "rue)\n test.equal(addr.match(ipaddr.IPv4.parse('10.5.5.0'), 16), true)\n test.equal(addr.match(ipaddr.IP", "end": 2559, "score": 0.999657928943634, "start": 2551, "tag": "IP_ADDRESS", "value": "10.5.5.0" }, { "context": "rue)\n test.equal(addr.match(ipaddr.IPv4.parse('10.4.5.0'), 16), false)\n test.equal(addr.match(ipaddr.I", "end": 2627, "score": 0.9996507167816162, "start": 2619, "tag": "IP_ADDRESS", "value": "10.4.5.0" }, { "context": "lse)\n test.equal(addr.match(ipaddr.IPv4.parse('10.4.5.0'), 15), true)\n test.equal(addr.match(ipaddr.IP", "end": 2696, "score": 0.9996562004089355, "start": 2688, "tag": "IP_ADDRESS", "value": "10.4.5.0" }, { "context": "rue)\n test.equal(addr.match(ipaddr.IPv4.parse('10.5.0.2'), 32), false)\n test.equal(addr.match(addr, 32", "end": 2764, "score": 0.9996577501296997, "start": 2756, "tag": "IP_ADDRESS", "value": "10.5.0.2" }, { "context": "ks': (test) ->\n test.equal(ipaddr.IPv4.parse('0.0.0.0').range(), 'unspecified')\n test.e", "end": 2921, "score": 0.5383054614067078, "start": 2921, "tag": "IP_ADDRESS", "value": "" }, { "context": "': (test) ->\n test.equal(ipaddr.IPv4.parse('0.0.0.0').range(), 'unspecified')\n test.equ", "end": 2923, "score": 0.8510504961013794, "start": 2923, "tag": "IP_ADDRESS", "value": "" }, { "context": " (test) ->\n test.equal(ipaddr.IPv4.parse('0.0.0.0').range(), 'unspecified')\n test.equal", "end": 2925, "score": 0.9805582165718079, "start": 2925, "tag": "IP_ADDRESS", "value": "" }, { "context": "nspecified')\n test.equal(ipaddr.IPv4.parse('0.1.0.0').range(), 'unspecified')\n test.equ", "end": 2999, "score": 0.9734438061714172, "start": 2999, "tag": "IP_ADDRESS", "value": "" }, { "context": "pecified')\n test.equal(ipaddr.IPv4.parse('0.1.0.0').range(), 'unspecified')\n test.equal(", "end": 3003, "score": 0.7572803497314453, "start": 3002, "tag": "IP_ADDRESS", "value": "0" }, { "context": " 'unspecified')\n test.equal(ipaddr.IPv4.parse('10.1.0.1').range(), 'private')\n test.equal(ipadd", "end": 3080, "score": 0.999707043170929, "start": 3072, "tag": "IP_ADDRESS", "value": "10.1.0.1" }, { "context": " 'private')\n test.equal(ipaddr.IPv4.parse('192.168.2.1').range(), 'private')\n test.equal(ipaddr.I", "end": 3155, "score": 0.9997333884239197, "start": 3144, "tag": "IP_ADDRESS", "value": "192.168.2.1" }, { "context": " 'private')\n test.equal(ipaddr.IPv4.parse('224.100.0.1').range(), 'multicast')\n test.equal(ipaddr", "end": 3227, "score": 0.9997193813323975, "start": 3216, "tag": "IP_ADDRESS", "value": "224.100.0.1" }, { "context": " 'multicast')\n test.equal(ipaddr.IPv4.parse('169.254.15.0').range(), 'linkLocal')\n test.equal(ipaddr.", "end": 3302, "score": 0.9997491836547852, "start": 3290, "tag": "IP_ADDRESS", "value": "169.254.15.0" }, { "context": " 'linkLocal')\n test.equal(ipaddr.IPv4.parse('127.1.1.1').range(), 'loopback')\n test.equal(ipadd", "end": 3373, "score": 0.9996951222419739, "start": 3364, "tag": "IP_ADDRESS", "value": "127.1.1.1" }, { "context": " 'loopback')\n test.equal(ipaddr.IPv4.parse('255.255.255.255').range(), 'broadcast')\n test.equal(ipaddr.IPv", "end": 3452, "score": 0.9996834397315979, "start": 3437, "tag": "IP_ADDRESS", "value": "255.255.255.255" }, { "context": "), 'broadcast')\n test.equal(ipaddr.IPv4.parse('240.1.2.3').range(), 'reserved')\n test.equal(ipadd", "end": 3520, "score": 0.9997032880783081, "start": 3511, "tag": "IP_ADDRESS", "value": "240.1.2.3" }, { "context": " 'reserved')\n test.equal(ipaddr.IPv4.parse('8.8.8.8').range(), 'unicast')\n test.done()\n\n ", "end": 3591, "score": 0.990892767906189, "start": 3584, "tag": "IP_ADDRESS", "value": "8.8.8.8" }, { "context": "0, 1])\n test.equal(addr.toNormalizedString(), '2001:db8:f53a:0:0:0:0:1')\n test.equal(addr.toString(), '2001:db8:f53a:", "end": 4179, "score": 0.9994293451309204, "start": 4156, "tag": "IP_ADDRESS", "value": "2001:db8:f53a:0:0:0:0:1" }, { "context": "f53a:0:0:0:0:1')\n test.equal(addr.toString(), '2001:db8:f53a::1')\n test.equal(new ipaddr.IPv6([0, 0, 0, 0, 0, ", "end": 4231, "score": 0.9996403455734253, "start": 4215, "tag": "IP_ADDRESS", "value": "2001:db8:f53a::1" }, { "context": " ipaddr.IPv6([0, 0, 0, 0, 0, 0, 0, 1]).toString(), '::1')\n test.equal(new ipaddr.IPv6([0x2001, 0xdb8, ", "end": 4307, "score": 0.8813645839691162, "start": 4303, "tag": "IP_ADDRESS", "value": "'::1" }, { "context": "6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]).toString(), '2001:db8::')\n test.done()\n\n 'returns correct kind for IP", "end": 4397, "score": 0.999522864818573, "start": 4389, "tag": "IP_ADDRESS", "value": "2001:db8" }, { "context": "at': (test) ->\n test.equal(ipaddr.IPv6.isIPv6('2001:db8:F53A::1'), true)\n test.equal(ipaddr.IPv6.isIPv6('2", "end": 4847, "score": 0.9991142153739929, "start": 4831, "tag": "IP_ADDRESS", "value": "2001:db8:F53A::1" }, { "context": "1'), true)\n test.equal(ipaddr.IPv6.isIPv6('200001::1'), true)\n test.equal(ipaddr.IPv6.is", "end": 4905, "score": 0.9978137016296387, "start": 4896, "tag": "IP_ADDRESS", "value": "200001::1" }, { "context": " true)\n test.equal(ipaddr.IPv6.isIPv6('::ffff:192.168.1.1'), true)\n test.equal(ipaddr.IPv6", "end": 4967, "score": 0.9778022766113281, "start": 4963, "tag": "IP_ADDRESS", "value": "ffff" }, { "context": " true)\n test.equal(ipaddr.IPv6.isIPv6('::ffff:192.168.1.1'), true)\n test.equal(ipaddr.IPv6.isIPv6('::f", "end": 4979, "score": 0.9801793694496155, "start": 4968, "tag": "IP_ADDRESS", "value": "192.168.1.1" }, { "context": "1.1'), true)\n test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1'), true)\n test.equal(ipaddr.IPv6", "end": 5032, "score": 0.9881202578544617, "start": 5028, "tag": "IP_ADDRESS", "value": "ffff" }, { "context": " true)\n test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1'), true)\n test.equal(ipaddr.IPv6.isI", "end": 5036, "score": 0.8481116890907288, "start": 5033, "tag": "IP_ADDRESS", "value": "300" }, { "context": "ue)\n test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1'), true)\n test.equal(ipaddr.IPv6.isIPv6('::f", "end": 5044, "score": 0.9740052819252014, "start": 5037, "tag": "IP_ADDRESS", "value": "168.1.1" }, { "context": "1.1'), true)\n test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1:0'), false)\n test.equal(ipaddr.IPv", "end": 5097, "score": 0.9789690971374512, "start": 5093, "tag": "IP_ADDRESS", "value": "ffff" }, { "context": " true)\n test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1:0'), false)\n test.equal(ipaddr.IPv6.isIPv6('fe", "end": 5109, "score": 0.909221887588501, "start": 5098, "tag": "IP_ADDRESS", "value": "300.168.1.1" }, { "context": ":0'), false)\n test.equal(ipaddr.IPv6.isIPv6('fe80::wtf'), false)\n test.done()\n\n 'val", "end": 5161, "score": 0.5462228059768677, "start": 5159, "tag": "IP_ADDRESS", "value": "80" }, { "context": "s': (test) ->\n test.equal(ipaddr.IPv6.isValid('2001:db8:F53A::1'), true)\n test.equal(ipaddr.IPv6.isValid('2", "end": 5297, "score": 0.9989997744560242, "start": 5281, "tag": "IP_ADDRESS", "value": "2001:db8:F53A::1" }, { "context": "1'), true)\n test.equal(ipaddr.IPv6.isValid('200001::1'), false)\n test.equal(ipaddr.IPv6.is", "end": 5355, "score": 0.9944689273834229, "start": 5346, "tag": "IP_ADDRESS", "value": "200001::1" }, { "context": " false)\n test.equal(ipaddr.IPv6.isValid('::ffff:192.168.1.1'), true)\n test.equal(ipaddr.IPv6", "end": 5418, "score": 0.9863431453704834, "start": 5414, "tag": "IP_ADDRESS", "value": "ffff" }, { "context": "false)\n test.equal(ipaddr.IPv6.isValid('::ffff:192.168.1.1'), true)\n test.equal(ipaddr.IPv6.isValid('::", "end": 5430, "score": 0.9779462218284607, "start": 5419, "tag": "IP_ADDRESS", "value": "192.168.1.1" }, { "context": ".1'), true)\n test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1'), false)\n test.equal(ipaddr.IPv", "end": 5484, "score": 0.9919317960739136, "start": 5480, "tag": "IP_ADDRESS", "value": "ffff" }, { "context": "true)\n test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1'), false)\n test.equal(ipaddr.IPv6.isValid(':", "end": 5496, "score": 0.9335142374038696, "start": 5486, "tag": "IP_ADDRESS", "value": "00.168.1.1" }, { "context": "1'), false)\n test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1:0'), false)\n test.equal(ipaddr.IPv", "end": 5551, "score": 0.9894978404045105, "start": 5547, "tag": "IP_ADDRESS", "value": "ffff" }, { "context": "false)\n test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1:0'), false)\n test.equal(ipaddr.IPv6.is", "end": 5555, "score": 0.8941170573234558, "start": 5552, "tag": "IP_ADDRESS", "value": "300" }, { "context": "e)\n test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1:0'), false)\n test.equal(ipaddr.IPv6.isValid('2", "end": 5563, "score": 0.9637230634689331, "start": 5556, "tag": "IP_ADDRESS", "value": "168.1.1" }, { "context": "1:0'), false)\n test.equal(ipaddr.IPv6.isValid('2001:db8::F53A::1'), false)\n test.equal(ipaddr.IPv6.isValid('f", "end": 5629, "score": 0.9936069846153259, "start": 5612, "tag": "IP_ADDRESS", "value": "2001:db8::F53A::1" }, { "context": "), false)\n test.equal(ipaddr.IPv6.isValid('fe80::wtf'), false)\n test.done()\n\n 'pars", "end": 5682, "score": 0.7082020044326782, "start": 5680, "tag": "IP_ADDRESS", "value": "80" }, { "context": ": (test) ->\n test.deepEqual(ipaddr.IPv6.parse('2001:db8:F53A:0:0:0:0:1').parts, [0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1])\n", "end": 5834, "score": 0.9987611174583435, "start": 5811, "tag": "IP_ADDRESS", "value": "2001:db8:F53A:0:0:0:0:1" }, { "context": ", 0, 0, 1])\n test.deepEqual(ipaddr.IPv6.parse('fe80::10').parts, [0xfe80, 0, 0, 0, 0, 0, 0, 0x10])\n te", "end": 5930, "score": 0.9997289776802063, "start": 5922, "tag": "IP_ADDRESS", "value": "fe80::10" }, { "context": ", 0, 0x10])\n test.deepEqual(ipaddr.IPv6.parse('2001:db8:F53A::').parts, [0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 0])\n", "end": 6025, "score": 0.9997485876083374, "start": 6012, "tag": "IP_ADDRESS", "value": "2001:db8:F53A" }, { "context": ", 0, 0, 0])\n test.deepEqual(ipaddr.IPv6.parse('::1').parts, [0, 0, 0, 0, 0, 0, 0, 1])\n test.deepE", "end": 6118, "score": 0.9978572130203247, "start": 6117, "tag": "IP_ADDRESS", "value": "1" }, { "context": "t) ->\n test.throws ->\n ipaddr.IPv6.parse('fe80::0::1')\n test.done()\n\n 'matches IPv6 CIDR correctly", "end": 6338, "score": 0.9983211159706116, "start": 6328, "tag": "IP_ADDRESS", "value": "fe80::0::1" }, { "context": "rrectly': (test) ->\n addr = ipaddr.IPv6.parse('2001:db8:f53a::1')\n test.equal(addr.match(ipaddr.IPv6.parse('::", "end": 6447, "score": 0.9997478127479553, "start": 6431, "tag": "IP_ADDRESS", "value": "2001:db8:f53a::1" }, { "context": ":1')\n test.equal(addr.match(ipaddr.IPv6.parse('::'), 0), true)\n test.equal(addr", "end": 6495, "score": 0.6544749736785889, "start": 6495, "tag": "IP_ADDRESS", "value": "" }, { "context": "rue)\n test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f53a::1:1'), 64), true)\n test.equal(addr.match(ipaddr.IP", "end": 6591, "score": 0.9994449615478516, "start": 6573, "tag": "IP_ADDRESS", "value": "2001:db8:f53a::1:1" }, { "context": "rue)\n test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f53b::1:1'), 48), false)\n test.equal(addr.match(ipaddr.I", "end": 6669, "score": 0.9995968341827393, "start": 6651, "tag": "IP_ADDRESS", "value": "2001:db8:f53b::1:1" }, { "context": "lse)\n test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f531::1:1'), 44), true)\n test.equal(addr.match(ipaddr.IP", "end": 6748, "score": 0.9996412396430969, "start": 6730, "tag": "IP_ADDRESS", "value": "2001:db8:f531::1:1" }, { "context": "rue)\n test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f500::1'), 40), true)\n test.equal(addr.match(ipaddr.", "end": 6824, "score": 0.999734103679657, "start": 6808, "tag": "IP_ADDRESS", "value": "2001:db8:f500::1" }, { "context": "rue)\n test.equal(addr.match(ipaddr.IPv6.parse('2001:db9:f500::1'), 40), false)\n test.equal(addr.match(addr, ", "end": 6902, "score": 0.9997368454933167, "start": 6886, "tag": "IP_ADDRESS", "value": "2001:db9:f500::1" }, { "context": "dresses': (test) ->\n addr = ipaddr.IPv4.parse('77.88.21.11')\n mapped = addr.toIPv4MappedAddress()\n tes", "end": 7100, "score": 0.9976121783256531, "start": 7089, "tag": "IP_ADDRESS", "value": "77.88.21.11" }, { "context": "t) ->\n test.throws ->\n ipaddr.IPv6.parse('2001:db8::1').toIPv4Address()\n test.done()\n\n 'detects res", "end": 7431, "score": 0.9997199177742004, "start": 7420, "tag": "IP_ADDRESS", "value": "2001:db8::1" }, { "context": " 'unspecified')\n test.equal(ipaddr.IPv6.parse('fe80::1234:5678:abcd:0123').range(), 'linkLocal')\n test.e", "end": 7643, "score": 0.9996321797370911, "start": 7633, "tag": "IP_ADDRESS", "value": "fe80::1234" }, { "context": "), 'linkLocal')\n test.equal(ipaddr.IPv6.parse('ff00::1234').range(), 'multicast')\n test.e", "end": 7727, "score": 0.9996176958084106, "start": 7717, "tag": "IP_ADDRESS", "value": "ff00::1234" }, { "context": " 'multicast')\n test.equal(ipaddr.IPv6.parse('::1').range(), 'loopback')\n ", "end": 7804, "score": 0.9961767792701721, "start": 7803, "tag": "IP_ADDRESS", "value": "1" }, { "context": " 'loopback')\n test.equal(ipaddr.IPv6.parse('fc00::').range(), 'uniqueLocal')\n ", "end": 7888, "score": 0.9345203638076782, "start": 7884, "tag": "IP_ADDRESS", "value": "fc00" }, { "context": " 'uniqueLocal')\n test.equal(ipaddr.IPv6.parse('::ffff:192.168.1.10').range(), 'ipv4Mapped')\n t", "end": 7976, "score": 0.983144998550415, "start": 7972, "tag": "IP_ADDRESS", "value": "ffff" }, { "context": "eLocal')\n test.equal(ipaddr.IPv6.parse('::ffff:192.168.1.10').range(), 'ipv4Mapped')\n test.equal(ipa", "end": 7989, "score": 0.9884322285652161, "start": 7977, "tag": "IP_ADDRESS", "value": "192.168.1.10" }, { "context": " 'ipv4Mapped')\n test.equal(ipaddr.IPv6.parse('::ffff:0:192.168.1.10').range(), 'rfc6145')\n test", "end": 8061, "score": 0.969052255153656, "start": 8057, "tag": "IP_ADDRESS", "value": "ffff" }, { "context": "pped')\n test.equal(ipaddr.IPv6.parse('::ffff:0:192.168.1.10').range(), 'rfc6145')\n test.equal(ipaddr.I", "end": 8076, "score": 0.9867146611213684, "start": 8064, "tag": "IP_ADDRESS", "value": "192.168.1.10" }, { "context": " 'rfc6145')\n test.equal(ipaddr.IPv6.parse('64:ff9b::1234').range(), 'rfc6052')\n test.equal(", "end": 8150, "score": 0.9997192025184631, "start": 8137, "tag": "IP_ADDRESS", "value": "64:ff9b::1234" }, { "context": " 'rfc6052')\n test.equal(ipaddr.IPv6.parse('2002:1f63:45e8::1').range(), '6to4')\n test.equal(ipaddr.", "end": 8236, "score": 0.9996851086616516, "start": 8219, "tag": "IP_ADDRESS", "value": "2002:1f63:45e8::1" }, { "context": " '6to4')\n test.equal(ipaddr.IPv6.parse('2001::4242').range(), 'teredo')\n test.equa", "end": 8308, "score": 0.9996745586395264, "start": 8298, "tag": "IP_ADDRESS", "value": "2001::4242" }, { "context": " 'teredo')\n test.equal(ipaddr.IPv6.parse('2001:db8::3210').range(), 'reserved')\n test.equal(", "end": 8393, "score": 0.9995978474617004, "start": 8379, "tag": "IP_ADDRESS", "value": "2001:db8::3210" }, { "context": " 'reserved')\n test.equal(ipaddr.IPv6.parse('2001:470:8:66::1').range(), 'unicast')\n test.done()\n\n ", "end": 8478, "score": 0.9997088313102722, "start": 8462, "tag": "IP_ADDRESS", "value": "2001:470:8:66::1" }, { "context": ".8').kind(), 'ipv4')\n test.equal(ipaddr.parse('2001:db8:3312::1').kind(), 'ipv6')\n test.done()\n\n 'throws an e", "end": 8679, "score": 0.9996890425682068, "start": 8663, "tag": "IP_ADDRESS", "value": "2001:db8:3312::1" }, { "context": "').kind(), 'ipv4')\n test.equal(ipaddr.process('2001:db8:3312::1').kind(), 'ipv6')\n test.equal(ipaddr.process('", "end": 9018, "score": 0.999687135219574, "start": 9002, "tag": "IP_ADDRESS", "value": "2001:db8:3312::1" }, { "context": "').kind(), 'ipv6')\n test.equal(ipaddr.process('::ffff:192.168.1.1').kind(), 'ipv4')\n test.done()\n\n ", "end": 9074, "score": 0.998612642288208, "start": 9070, "tag": "IP_ADDRESS", "value": "ffff" }, { "context": "(), 'ipv6')\n test.equal(ipaddr.process('::ffff:192.168.1.1').kind(), 'ipv4')\n test.done()\n\n 'correctly c", "end": 9086, "score": 0.9534032344818115, "start": 9075, "tag": "IP_ADDRESS", "value": "192.168.1.1" }, { "context": "dress is 42. 42!\n test.deepEqual(ipaddr.parse('2a00:1450:8007::68').toByteArray(),\n [42, 0x00, 0x14, 0x50,", "end": 9405, "score": 0.9997067451477051, "start": 9387, "tag": "IP_ADDRESS", "value": "2a00:1450:8007::68" }, { "context": "'-1'), false)\n test.done()\n\n 'does not hang on ::8:8:8:8:8:8:8:8:8': (test) ->\n test.equal(ipaddr.I", "end": 10005, "score": 0.9133846759796143, "start": 10000, "tag": "IP_ADDRESS", "value": "::8:8" }, { "context": "false)\n test.done()\n\n 'does not hang on ::8:8:8:8:8:8:8:8:8': (test) ->\n test.equal(ipaddr.IPv", "end": 10007, "score": 0.5182341933250427, "start": 10006, "tag": "IP_ADDRESS", "value": "8" }, { "context": "8': (test) ->\n test.equal(ipaddr.IPv6.isValid('::8:8:8:8:8:8:8:8:8'), false)\n test.done()\n", "end": 10075, "score": 0.7747673392295837, "start": 10070, "tag": "IP_ADDRESS", "value": "8:8:8" } ]
node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee
tuanpembual/anjungan
64
ipaddr = require '../lib/ipaddr' module.exports = 'should define main classes': (test) -> test.ok(ipaddr.IPv4?, 'defines IPv4 class') test.ok(ipaddr.IPv6?, 'defines IPv6 class') test.done() 'can construct IPv4 from octets': (test) -> test.doesNotThrow -> new ipaddr.IPv4([192, 168, 1, 2]) test.done() 'refuses to construct invalid IPv4': (test) -> test.throws -> new ipaddr.IPv4([300, 1, 2, 3]) test.throws -> new ipaddr.IPv4([8, 8, 8]) test.done() 'converts IPv4 to string correctly': (test) -> addr = new ipaddr.IPv4([192, 168, 1, 1]) test.equal(addr.toString(), '192.168.1.1') test.done() 'returns correct kind for IPv4': (test) -> addr = new ipaddr.IPv4([1, 2, 3, 4]) test.equal(addr.kind(), 'ipv4') test.done() 'allows to access IPv4 octets': (test) -> addr = new ipaddr.IPv4([42, 0, 0, 0]) test.equal(addr.octets[0], 42) test.done() 'checks IPv4 address format': (test) -> test.equal(ipaddr.IPv4.isIPv4('192.168.007.0xa'), true) test.equal(ipaddr.IPv4.isIPv4('1024.0.0.1'), true) test.equal(ipaddr.IPv4.isIPv4('8.0xa.wtf.6'), false) test.done() 'validates IPv4 addresses': (test) -> test.equal(ipaddr.IPv4.isValid('192.168.007.0xa'), true) test.equal(ipaddr.IPv4.isValid('1024.0.0.1'), false) test.equal(ipaddr.IPv4.isValid('8.0xa.wtf.6'), false) test.done() 'parses IPv4 in several weird formats': (test) -> test.deepEqual(ipaddr.IPv4.parse('192.168.1.1').octets, [192, 168, 1, 1]) test.deepEqual(ipaddr.IPv4.parse('0xc0.168.1.1').octets, [192, 168, 1, 1]) test.deepEqual(ipaddr.IPv4.parse('192.0250.1.1').octets, [192, 168, 1, 1]) test.deepEqual(ipaddr.IPv4.parse('0xc0a80101').octets, [192, 168, 1, 1]) test.deepEqual(ipaddr.IPv4.parse('030052000401').octets, [192, 168, 1, 1]) test.deepEqual(ipaddr.IPv4.parse('3232235777').octets, [192, 168, 1, 1]) test.done() 'barfs at invalid IPv4': (test) -> test.throws -> ipaddr.IPv4.parse('10.0.0.wtf') test.done() 'matches IPv4 CIDR correctly': (test) -> addr = new ipaddr.IPv4([10, 5, 0, 1]) test.equal(addr.match(ipaddr.IPv4.parse('0.0.0.0'), 0), true) test.equal(addr.match(ipaddr.IPv4.parse('11.0.0.0'), 8), false) test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.0'), 8), true) test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.1'), 8), true) test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.10'), 8), true) test.equal(addr.match(ipaddr.IPv4.parse('10.5.5.0'), 16), true) test.equal(addr.match(ipaddr.IPv4.parse('10.4.5.0'), 16), false) test.equal(addr.match(ipaddr.IPv4.parse('10.4.5.0'), 15), true) test.equal(addr.match(ipaddr.IPv4.parse('10.5.0.2'), 32), false) test.equal(addr.match(addr, 32), true) test.done() 'detects reserved IPv4 networks': (test) -> test.equal(ipaddr.IPv4.parse('0.0.0.0').range(), 'unspecified') test.equal(ipaddr.IPv4.parse('0.1.0.0').range(), 'unspecified') test.equal(ipaddr.IPv4.parse('10.1.0.1').range(), 'private') test.equal(ipaddr.IPv4.parse('192.168.2.1').range(), 'private') test.equal(ipaddr.IPv4.parse('224.100.0.1').range(), 'multicast') test.equal(ipaddr.IPv4.parse('169.254.15.0').range(), 'linkLocal') test.equal(ipaddr.IPv4.parse('127.1.1.1').range(), 'loopback') test.equal(ipaddr.IPv4.parse('255.255.255.255').range(), 'broadcast') test.equal(ipaddr.IPv4.parse('240.1.2.3').range(), 'reserved') test.equal(ipaddr.IPv4.parse('8.8.8.8').range(), 'unicast') test.done() 'can construct IPv6 from parts': (test) -> test.doesNotThrow -> new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) test.done() 'refuses to construct invalid IPv6': (test) -> test.throws -> new ipaddr.IPv6([0xfffff, 0, 0, 0, 0, 0, 0, 1]) test.throws -> new ipaddr.IPv6([0xfffff, 0, 0, 0, 0, 0, 1]) test.done() 'converts IPv6 to string correctly': (test) -> addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) test.equal(addr.toNormalizedString(), '2001:db8:f53a:0:0:0:0:1') test.equal(addr.toString(), '2001:db8:f53a::1') test.equal(new ipaddr.IPv6([0, 0, 0, 0, 0, 0, 0, 1]).toString(), '::1') test.equal(new ipaddr.IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]).toString(), '2001:db8::') test.done() 'returns correct kind for IPv6': (test) -> addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) test.equal(addr.kind(), 'ipv6') test.done() 'allows to access IPv6 address parts': (test) -> addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 42, 0, 1]) test.equal(addr.parts[5], 42) test.done() 'checks IPv6 address format': (test) -> test.equal(ipaddr.IPv6.isIPv6('2001:db8:F53A::1'), true) test.equal(ipaddr.IPv6.isIPv6('200001::1'), true) test.equal(ipaddr.IPv6.isIPv6('::ffff:192.168.1.1'), true) test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1'), true) test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1:0'), false) test.equal(ipaddr.IPv6.isIPv6('fe80::wtf'), false) test.done() 'validates IPv6 addresses': (test) -> test.equal(ipaddr.IPv6.isValid('2001:db8:F53A::1'), true) test.equal(ipaddr.IPv6.isValid('200001::1'), false) test.equal(ipaddr.IPv6.isValid('::ffff:192.168.1.1'), true) test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1'), false) test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1:0'), false) test.equal(ipaddr.IPv6.isValid('2001:db8::F53A::1'), false) test.equal(ipaddr.IPv6.isValid('fe80::wtf'), false) test.done() 'parses IPv6 in different formats': (test) -> test.deepEqual(ipaddr.IPv6.parse('2001:db8:F53A:0:0:0:0:1').parts, [0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) test.deepEqual(ipaddr.IPv6.parse('fe80::10').parts, [0xfe80, 0, 0, 0, 0, 0, 0, 0x10]) test.deepEqual(ipaddr.IPv6.parse('2001:db8:F53A::').parts, [0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 0]) test.deepEqual(ipaddr.IPv6.parse('::1').parts, [0, 0, 0, 0, 0, 0, 0, 1]) test.deepEqual(ipaddr.IPv6.parse('::').parts, [0, 0, 0, 0, 0, 0, 0, 0]) test.done() 'barfs at invalid IPv6': (test) -> test.throws -> ipaddr.IPv6.parse('fe80::0::1') test.done() 'matches IPv6 CIDR correctly': (test) -> addr = ipaddr.IPv6.parse('2001:db8:f53a::1') test.equal(addr.match(ipaddr.IPv6.parse('::'), 0), true) test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f53a::1:1'), 64), true) test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f53b::1:1'), 48), false) test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f531::1:1'), 44), true) test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f500::1'), 40), true) test.equal(addr.match(ipaddr.IPv6.parse('2001:db9:f500::1'), 40), false) test.equal(addr.match(addr, 128), true) test.done() 'converts between IPv4-mapped IPv6 addresses and IPv4 addresses': (test) -> addr = ipaddr.IPv4.parse('77.88.21.11') mapped = addr.toIPv4MappedAddress() test.deepEqual(mapped.parts, [0, 0, 0, 0, 0, 0xffff, 0x4d58, 0x150b]) test.deepEqual(mapped.toIPv4Address().octets, addr.octets) test.done() 'refuses to convert non-IPv4-mapped IPv6 address to IPv4 address': (test) -> test.throws -> ipaddr.IPv6.parse('2001:db8::1').toIPv4Address() test.done() 'detects reserved IPv6 networks': (test) -> test.equal(ipaddr.IPv6.parse('::').range(), 'unspecified') test.equal(ipaddr.IPv6.parse('fe80::1234:5678:abcd:0123').range(), 'linkLocal') test.equal(ipaddr.IPv6.parse('ff00::1234').range(), 'multicast') test.equal(ipaddr.IPv6.parse('::1').range(), 'loopback') test.equal(ipaddr.IPv6.parse('fc00::').range(), 'uniqueLocal') test.equal(ipaddr.IPv6.parse('::ffff:192.168.1.10').range(), 'ipv4Mapped') test.equal(ipaddr.IPv6.parse('::ffff:0:192.168.1.10').range(), 'rfc6145') test.equal(ipaddr.IPv6.parse('64:ff9b::1234').range(), 'rfc6052') test.equal(ipaddr.IPv6.parse('2002:1f63:45e8::1').range(), '6to4') test.equal(ipaddr.IPv6.parse('2001::4242').range(), 'teredo') test.equal(ipaddr.IPv6.parse('2001:db8::3210').range(), 'reserved') test.equal(ipaddr.IPv6.parse('2001:470:8:66::1').range(), 'unicast') test.done() 'is able to determine IP address type': (test) -> test.equal(ipaddr.parse('8.8.8.8').kind(), 'ipv4') test.equal(ipaddr.parse('2001:db8:3312::1').kind(), 'ipv6') test.done() 'throws an error if tried to parse an invalid address': (test) -> test.throws -> ipaddr.parse('::some.nonsense') test.done() 'correctly processes IPv4-mapped addresses': (test) -> test.equal(ipaddr.process('8.8.8.8').kind(), 'ipv4') test.equal(ipaddr.process('2001:db8:3312::1').kind(), 'ipv6') test.equal(ipaddr.process('::ffff:192.168.1.1').kind(), 'ipv4') test.done() 'correctly converts IPv6 and IPv4 addresses to byte arrays': (test) -> test.deepEqual(ipaddr.parse('1.2.3.4').toByteArray(), [0x1, 0x2, 0x3, 0x4]); # Fuck yeah. The first byte of Google's IPv6 address is 42. 42! test.deepEqual(ipaddr.parse('2a00:1450:8007::68').toByteArray(), [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68 ]) test.done() 'correctly parses 1 as an IPv4 address': (test) -> test.equal(ipaddr.IPv6.isValid('1'), false) test.equal(ipaddr.IPv4.isValid('1'), true) test.deepEqual(new ipaddr.IPv4([0, 0, 0, 1]), ipaddr.parse('1')) test.done() 'does not consider a very large or very small number a valid IP address': (test) -> test.equal(ipaddr.isValid('4999999999'), false) test.equal(ipaddr.isValid('-1'), false) test.done() 'does not hang on ::8:8:8:8:8:8:8:8:8': (test) -> test.equal(ipaddr.IPv6.isValid('::8:8:8:8:8:8:8:8:8'), false) test.done()
195678
ipaddr = require '../lib/ipaddr' module.exports = 'should define main classes': (test) -> test.ok(ipaddr.IPv4?, 'defines IPv4 class') test.ok(ipaddr.IPv6?, 'defines IPv6 class') test.done() 'can construct IPv4 from octets': (test) -> test.doesNotThrow -> new ipaddr.IPv4([192, 168, 1, 2]) test.done() 'refuses to construct invalid IPv4': (test) -> test.throws -> new ipaddr.IPv4([300, 1, 2, 3]) test.throws -> new ipaddr.IPv4([8, 8, 8]) test.done() 'converts IPv4 to string correctly': (test) -> addr = new ipaddr.IPv4([192, 168, 1, 1]) test.equal(addr.toString(), '192.168.1.1') test.done() 'returns correct kind for IPv4': (test) -> addr = new ipaddr.IPv4([1, 2, 3, 4]) test.equal(addr.kind(), 'ipv4') test.done() 'allows to access IPv4 octets': (test) -> addr = new ipaddr.IPv4([42, 0, 0, 0]) test.equal(addr.octets[0], 42) test.done() 'checks IPv4 address format': (test) -> test.equal(ipaddr.IPv4.isIPv4('192.168.007.0xa'), true) test.equal(ipaddr.IPv4.isIPv4('1024.0.0.1'), true) test.equal(ipaddr.IPv4.isIPv4('8.0xa.wtf.6'), false) test.done() 'validates IPv4 addresses': (test) -> test.equal(ipaddr.IPv4.isValid('192.168.007.0xa'), true) test.equal(ipaddr.IPv4.isValid('1024.0.0.1'), false) test.equal(ipaddr.IPv4.isValid('8.0xa.wtf.6'), false) test.done() 'parses IPv4 in several weird formats': (test) -> test.deepEqual(ipaddr.IPv4.parse('192.168.1.1').octets, [192, 168, 1, 1]) test.deepEqual(ipaddr.IPv4.parse('0xc0.168.1.1').octets, [192, 168, 1, 1]) test.deepEqual(ipaddr.IPv4.parse('192.0250.1.1').octets, [192, 168, 1, 1]) test.deepEqual(ipaddr.IPv4.parse('0xc0a80101').octets, [192, 168, 1, 1]) test.deepEqual(ipaddr.IPv4.parse('030052000401').octets, [192, 168, 1, 1]) test.deepEqual(ipaddr.IPv4.parse('3232235777').octets, [192, 168, 1, 1]) test.done() 'barfs at invalid IPv4': (test) -> test.throws -> ipaddr.IPv4.parse('10.0.0.wtf') test.done() 'matches IPv4 CIDR correctly': (test) -> addr = new ipaddr.IPv4([10, 5, 0, 1]) test.equal(addr.match(ipaddr.IPv4.parse('0.0.0.0'), 0), true) test.equal(addr.match(ipaddr.IPv4.parse('172.16.31.10'), 8), false) test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.0'), 8), true) test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.1'), 8), true) test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.10'), 8), true) test.equal(addr.match(ipaddr.IPv4.parse('10.5.5.0'), 16), true) test.equal(addr.match(ipaddr.IPv4.parse('10.4.5.0'), 16), false) test.equal(addr.match(ipaddr.IPv4.parse('10.4.5.0'), 15), true) test.equal(addr.match(ipaddr.IPv4.parse('10.5.0.2'), 32), false) test.equal(addr.match(addr, 32), true) test.done() 'detects reserved IPv4 networks': (test) -> test.equal(ipaddr.IPv4.parse('0.0.0.0').range(), 'unspecified') test.equal(ipaddr.IPv4.parse('0.1.0.0').range(), 'unspecified') test.equal(ipaddr.IPv4.parse('10.1.0.1').range(), 'private') test.equal(ipaddr.IPv4.parse('192.168.2.1').range(), 'private') test.equal(ipaddr.IPv4.parse('192.168.3.11').range(), 'multicast') test.equal(ipaddr.IPv4.parse('169.254.15.0').range(), 'linkLocal') test.equal(ipaddr.IPv4.parse('127.1.1.1').range(), 'loopback') test.equal(ipaddr.IPv4.parse('255.255.255.255').range(), 'broadcast') test.equal(ipaddr.IPv4.parse('240.1.2.3').range(), 'reserved') test.equal(ipaddr.IPv4.parse('8.8.8.8').range(), 'unicast') test.done() 'can construct IPv6 from parts': (test) -> test.doesNotThrow -> new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) test.done() 'refuses to construct invalid IPv6': (test) -> test.throws -> new ipaddr.IPv6([0xfffff, 0, 0, 0, 0, 0, 0, 1]) test.throws -> new ipaddr.IPv6([0xfffff, 0, 0, 0, 0, 0, 1]) test.done() 'converts IPv6 to string correctly': (test) -> addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) test.equal(addr.toNormalizedString(), '2001:db8:f53a:0:0:0:0:1') test.equal(addr.toString(), '2001:db8:f53a::1') test.equal(new ipaddr.IPv6([0, 0, 0, 0, 0, 0, 0, 1]).toString(), '::1') test.equal(new ipaddr.IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]).toString(), '2001:db8::') test.done() 'returns correct kind for IPv6': (test) -> addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) test.equal(addr.kind(), 'ipv6') test.done() 'allows to access IPv6 address parts': (test) -> addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 42, 0, 1]) test.equal(addr.parts[5], 42) test.done() 'checks IPv6 address format': (test) -> test.equal(ipaddr.IPv6.isIPv6('2001:db8:F53A::1'), true) test.equal(ipaddr.IPv6.isIPv6('200001::1'), true) test.equal(ipaddr.IPv6.isIPv6('::ffff:192.168.1.1'), true) test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1'), true) test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1:0'), false) test.equal(ipaddr.IPv6.isIPv6('fe80::wtf'), false) test.done() 'validates IPv6 addresses': (test) -> test.equal(ipaddr.IPv6.isValid('2001:db8:F53A::1'), true) test.equal(ipaddr.IPv6.isValid('200001::1'), false) test.equal(ipaddr.IPv6.isValid('::ffff:192.168.1.1'), true) test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1'), false) test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1:0'), false) test.equal(ipaddr.IPv6.isValid('2001:db8::F53A::1'), false) test.equal(ipaddr.IPv6.isValid('fe80::wtf'), false) test.done() 'parses IPv6 in different formats': (test) -> test.deepEqual(ipaddr.IPv6.parse('2001:db8:F53A:0:0:0:0:1').parts, [0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) test.deepEqual(ipaddr.IPv6.parse('fe80::10').parts, [0xfe80, 0, 0, 0, 0, 0, 0, 0x10]) test.deepEqual(ipaddr.IPv6.parse('2001:db8:F53A::').parts, [0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 0]) test.deepEqual(ipaddr.IPv6.parse('::1').parts, [0, 0, 0, 0, 0, 0, 0, 1]) test.deepEqual(ipaddr.IPv6.parse('::').parts, [0, 0, 0, 0, 0, 0, 0, 0]) test.done() 'barfs at invalid IPv6': (test) -> test.throws -> ipaddr.IPv6.parse('fe80::0::1') test.done() 'matches IPv6 CIDR correctly': (test) -> addr = ipaddr.IPv6.parse('2001:db8:f53a::1') test.equal(addr.match(ipaddr.IPv6.parse('::'), 0), true) test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f53a::1:1'), 64), true) test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f53b::1:1'), 48), false) test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f531::1:1'), 44), true) test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f500::1'), 40), true) test.equal(addr.match(ipaddr.IPv6.parse('fc00:e968:6179::de52:7100'), 40), false) test.equal(addr.match(addr, 128), true) test.done() 'converts between IPv4-mapped IPv6 addresses and IPv4 addresses': (test) -> addr = ipaddr.IPv4.parse('172.16.31.10') mapped = addr.toIPv4MappedAddress() test.deepEqual(mapped.parts, [0, 0, 0, 0, 0, 0xffff, 0x4d58, 0x150b]) test.deepEqual(mapped.toIPv4Address().octets, addr.octets) test.done() 'refuses to convert non-IPv4-mapped IPv6 address to IPv4 address': (test) -> test.throws -> ipaddr.IPv6.parse('2001:db8::1').toIPv4Address() test.done() 'detects reserved IPv6 networks': (test) -> test.equal(ipaddr.IPv6.parse('::').range(), 'unspecified') test.equal(ipaddr.IPv6.parse('fe80::1234:5678:abcd:0123').range(), 'linkLocal') test.equal(ipaddr.IPv6.parse('fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b').range(), 'multicast') test.equal(ipaddr.IPv6.parse('::1').range(), 'loopback') test.equal(ipaddr.IPv6.parse('fc00::').range(), 'uniqueLocal') test.equal(ipaddr.IPv6.parse('::ffff:192.168.1.10').range(), 'ipv4Mapped') test.equal(ipaddr.IPv6.parse('::ffff:0:192.168.1.10').range(), 'rfc6145') test.equal(ipaddr.IPv6.parse('fc00:e968:6179::de52:7100').range(), 'rfc6052') test.equal(ipaddr.IPv6.parse('fc00:e968:6179::de52:7100').range(), '6to4') test.equal(ipaddr.IPv6.parse('2001::4242').range(), 'teredo') test.equal(ipaddr.IPv6.parse('2001:db8::3210').range(), 'reserved') test.equal(ipaddr.IPv6.parse('fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b').range(), 'unicast') test.done() 'is able to determine IP address type': (test) -> test.equal(ipaddr.parse('8.8.8.8').kind(), 'ipv4') test.equal(ipaddr.parse('2001:db8:3312::1').kind(), 'ipv6') test.done() 'throws an error if tried to parse an invalid address': (test) -> test.throws -> ipaddr.parse('::some.nonsense') test.done() 'correctly processes IPv4-mapped addresses': (test) -> test.equal(ipaddr.process('8.8.8.8').kind(), 'ipv4') test.equal(ipaddr.process('2001:db8:3312::1').kind(), 'ipv6') test.equal(ipaddr.process('::ffff:192.168.1.1').kind(), 'ipv4') test.done() 'correctly converts IPv6 and IPv4 addresses to byte arrays': (test) -> test.deepEqual(ipaddr.parse('1.2.3.4').toByteArray(), [0x1, 0x2, 0x3, 0x4]); # Fuck yeah. The first byte of Google's IPv6 address is 42. 42! test.deepEqual(ipaddr.parse('fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b').toByteArray(), [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68 ]) test.done() 'correctly parses 1 as an IPv4 address': (test) -> test.equal(ipaddr.IPv6.isValid('1'), false) test.equal(ipaddr.IPv4.isValid('1'), true) test.deepEqual(new ipaddr.IPv4([0, 0, 0, 1]), ipaddr.parse('1')) test.done() 'does not consider a very large or very small number a valid IP address': (test) -> test.equal(ipaddr.isValid('4999999999'), false) test.equal(ipaddr.isValid('-1'), false) test.done() 'does not hang on fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:8:8:8:8:8:8:8': (test) -> test.equal(ipaddr.IPv6.isValid('::8:8:8:8:8:8:8:8:8'), false) test.done()
true
ipaddr = require '../lib/ipaddr' module.exports = 'should define main classes': (test) -> test.ok(ipaddr.IPv4?, 'defines IPv4 class') test.ok(ipaddr.IPv6?, 'defines IPv6 class') test.done() 'can construct IPv4 from octets': (test) -> test.doesNotThrow -> new ipaddr.IPv4([192, 168, 1, 2]) test.done() 'refuses to construct invalid IPv4': (test) -> test.throws -> new ipaddr.IPv4([300, 1, 2, 3]) test.throws -> new ipaddr.IPv4([8, 8, 8]) test.done() 'converts IPv4 to string correctly': (test) -> addr = new ipaddr.IPv4([192, 168, 1, 1]) test.equal(addr.toString(), '192.168.1.1') test.done() 'returns correct kind for IPv4': (test) -> addr = new ipaddr.IPv4([1, 2, 3, 4]) test.equal(addr.kind(), 'ipv4') test.done() 'allows to access IPv4 octets': (test) -> addr = new ipaddr.IPv4([42, 0, 0, 0]) test.equal(addr.octets[0], 42) test.done() 'checks IPv4 address format': (test) -> test.equal(ipaddr.IPv4.isIPv4('192.168.007.0xa'), true) test.equal(ipaddr.IPv4.isIPv4('1024.0.0.1'), true) test.equal(ipaddr.IPv4.isIPv4('8.0xa.wtf.6'), false) test.done() 'validates IPv4 addresses': (test) -> test.equal(ipaddr.IPv4.isValid('192.168.007.0xa'), true) test.equal(ipaddr.IPv4.isValid('1024.0.0.1'), false) test.equal(ipaddr.IPv4.isValid('8.0xa.wtf.6'), false) test.done() 'parses IPv4 in several weird formats': (test) -> test.deepEqual(ipaddr.IPv4.parse('192.168.1.1').octets, [192, 168, 1, 1]) test.deepEqual(ipaddr.IPv4.parse('0xc0.168.1.1').octets, [192, 168, 1, 1]) test.deepEqual(ipaddr.IPv4.parse('192.0250.1.1').octets, [192, 168, 1, 1]) test.deepEqual(ipaddr.IPv4.parse('0xc0a80101').octets, [192, 168, 1, 1]) test.deepEqual(ipaddr.IPv4.parse('030052000401').octets, [192, 168, 1, 1]) test.deepEqual(ipaddr.IPv4.parse('3232235777').octets, [192, 168, 1, 1]) test.done() 'barfs at invalid IPv4': (test) -> test.throws -> ipaddr.IPv4.parse('10.0.0.wtf') test.done() 'matches IPv4 CIDR correctly': (test) -> addr = new ipaddr.IPv4([10, 5, 0, 1]) test.equal(addr.match(ipaddr.IPv4.parse('0.0.0.0'), 0), true) test.equal(addr.match(ipaddr.IPv4.parse('PI:IP_ADDRESS:172.16.31.10END_PI'), 8), false) test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.0'), 8), true) test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.1'), 8), true) test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.10'), 8), true) test.equal(addr.match(ipaddr.IPv4.parse('10.5.5.0'), 16), true) test.equal(addr.match(ipaddr.IPv4.parse('10.4.5.0'), 16), false) test.equal(addr.match(ipaddr.IPv4.parse('10.4.5.0'), 15), true) test.equal(addr.match(ipaddr.IPv4.parse('10.5.0.2'), 32), false) test.equal(addr.match(addr, 32), true) test.done() 'detects reserved IPv4 networks': (test) -> test.equal(ipaddr.IPv4.parse('0.0.0.0').range(), 'unspecified') test.equal(ipaddr.IPv4.parse('0.1.0.0').range(), 'unspecified') test.equal(ipaddr.IPv4.parse('10.1.0.1').range(), 'private') test.equal(ipaddr.IPv4.parse('192.168.2.1').range(), 'private') test.equal(ipaddr.IPv4.parse('PI:IP_ADDRESS:192.168.3.11END_PI').range(), 'multicast') test.equal(ipaddr.IPv4.parse('169.254.15.0').range(), 'linkLocal') test.equal(ipaddr.IPv4.parse('127.1.1.1').range(), 'loopback') test.equal(ipaddr.IPv4.parse('255.255.255.255').range(), 'broadcast') test.equal(ipaddr.IPv4.parse('240.1.2.3').range(), 'reserved') test.equal(ipaddr.IPv4.parse('8.8.8.8').range(), 'unicast') test.done() 'can construct IPv6 from parts': (test) -> test.doesNotThrow -> new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) test.done() 'refuses to construct invalid IPv6': (test) -> test.throws -> new ipaddr.IPv6([0xfffff, 0, 0, 0, 0, 0, 0, 1]) test.throws -> new ipaddr.IPv6([0xfffff, 0, 0, 0, 0, 0, 1]) test.done() 'converts IPv6 to string correctly': (test) -> addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) test.equal(addr.toNormalizedString(), '2001:db8:f53a:0:0:0:0:1') test.equal(addr.toString(), '2001:db8:f53a::1') test.equal(new ipaddr.IPv6([0, 0, 0, 0, 0, 0, 0, 1]).toString(), '::1') test.equal(new ipaddr.IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]).toString(), '2001:db8::') test.done() 'returns correct kind for IPv6': (test) -> addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) test.equal(addr.kind(), 'ipv6') test.done() 'allows to access IPv6 address parts': (test) -> addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 42, 0, 1]) test.equal(addr.parts[5], 42) test.done() 'checks IPv6 address format': (test) -> test.equal(ipaddr.IPv6.isIPv6('2001:db8:F53A::1'), true) test.equal(ipaddr.IPv6.isIPv6('200001::1'), true) test.equal(ipaddr.IPv6.isIPv6('::ffff:192.168.1.1'), true) test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1'), true) test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1:0'), false) test.equal(ipaddr.IPv6.isIPv6('fe80::wtf'), false) test.done() 'validates IPv6 addresses': (test) -> test.equal(ipaddr.IPv6.isValid('2001:db8:F53A::1'), true) test.equal(ipaddr.IPv6.isValid('200001::1'), false) test.equal(ipaddr.IPv6.isValid('::ffff:192.168.1.1'), true) test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1'), false) test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1:0'), false) test.equal(ipaddr.IPv6.isValid('2001:db8::F53A::1'), false) test.equal(ipaddr.IPv6.isValid('fe80::wtf'), false) test.done() 'parses IPv6 in different formats': (test) -> test.deepEqual(ipaddr.IPv6.parse('2001:db8:F53A:0:0:0:0:1').parts, [0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) test.deepEqual(ipaddr.IPv6.parse('fe80::10').parts, [0xfe80, 0, 0, 0, 0, 0, 0, 0x10]) test.deepEqual(ipaddr.IPv6.parse('2001:db8:F53A::').parts, [0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 0]) test.deepEqual(ipaddr.IPv6.parse('::1').parts, [0, 0, 0, 0, 0, 0, 0, 1]) test.deepEqual(ipaddr.IPv6.parse('::').parts, [0, 0, 0, 0, 0, 0, 0, 0]) test.done() 'barfs at invalid IPv6': (test) -> test.throws -> ipaddr.IPv6.parse('fe80::0::1') test.done() 'matches IPv6 CIDR correctly': (test) -> addr = ipaddr.IPv6.parse('2001:db8:f53a::1') test.equal(addr.match(ipaddr.IPv6.parse('::'), 0), true) test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f53a::1:1'), 64), true) test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f53b::1:1'), 48), false) test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f531::1:1'), 44), true) test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f500::1'), 40), true) test.equal(addr.match(ipaddr.IPv6.parse('PI:IP_ADDRESS:fc00:e968:6179::de52:7100END_PI'), 40), false) test.equal(addr.match(addr, 128), true) test.done() 'converts between IPv4-mapped IPv6 addresses and IPv4 addresses': (test) -> addr = ipaddr.IPv4.parse('PI:IP_ADDRESS:172.16.31.10END_PI') mapped = addr.toIPv4MappedAddress() test.deepEqual(mapped.parts, [0, 0, 0, 0, 0, 0xffff, 0x4d58, 0x150b]) test.deepEqual(mapped.toIPv4Address().octets, addr.octets) test.done() 'refuses to convert non-IPv4-mapped IPv6 address to IPv4 address': (test) -> test.throws -> ipaddr.IPv6.parse('2001:db8::1').toIPv4Address() test.done() 'detects reserved IPv6 networks': (test) -> test.equal(ipaddr.IPv6.parse('::').range(), 'unspecified') test.equal(ipaddr.IPv6.parse('fe80::1234:5678:abcd:0123').range(), 'linkLocal') test.equal(ipaddr.IPv6.parse('PI:IP_ADDRESS:fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5bEND_PI').range(), 'multicast') test.equal(ipaddr.IPv6.parse('::1').range(), 'loopback') test.equal(ipaddr.IPv6.parse('fc00::').range(), 'uniqueLocal') test.equal(ipaddr.IPv6.parse('::ffff:192.168.1.10').range(), 'ipv4Mapped') test.equal(ipaddr.IPv6.parse('::ffff:0:192.168.1.10').range(), 'rfc6145') test.equal(ipaddr.IPv6.parse('PI:IP_ADDRESS:fc00:e968:6179::de52:7100END_PI').range(), 'rfc6052') test.equal(ipaddr.IPv6.parse('PI:IP_ADDRESS:fc00:e968:6179::de52:7100END_PI').range(), '6to4') test.equal(ipaddr.IPv6.parse('2001::4242').range(), 'teredo') test.equal(ipaddr.IPv6.parse('2001:db8::3210').range(), 'reserved') test.equal(ipaddr.IPv6.parse('PI:IP_ADDRESS:fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3bEND_PI').range(), 'unicast') test.done() 'is able to determine IP address type': (test) -> test.equal(ipaddr.parse('8.8.8.8').kind(), 'ipv4') test.equal(ipaddr.parse('2001:db8:3312::1').kind(), 'ipv6') test.done() 'throws an error if tried to parse an invalid address': (test) -> test.throws -> ipaddr.parse('::some.nonsense') test.done() 'correctly processes IPv4-mapped addresses': (test) -> test.equal(ipaddr.process('8.8.8.8').kind(), 'ipv4') test.equal(ipaddr.process('2001:db8:3312::1').kind(), 'ipv6') test.equal(ipaddr.process('::ffff:192.168.1.1').kind(), 'ipv4') test.done() 'correctly converts IPv6 and IPv4 addresses to byte arrays': (test) -> test.deepEqual(ipaddr.parse('1.2.3.4').toByteArray(), [0x1, 0x2, 0x3, 0x4]); # Fuck yeah. The first byte of Google's IPv6 address is 42. 42! test.deepEqual(ipaddr.parse('PI:IP_ADDRESS:fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5bEND_PI').toByteArray(), [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68 ]) test.done() 'correctly parses 1 as an IPv4 address': (test) -> test.equal(ipaddr.IPv6.isValid('1'), false) test.equal(ipaddr.IPv4.isValid('1'), true) test.deepEqual(new ipaddr.IPv4([0, 0, 0, 1]), ipaddr.parse('1')) test.done() 'does not consider a very large or very small number a valid IP address': (test) -> test.equal(ipaddr.isValid('4999999999'), false) test.equal(ipaddr.isValid('-1'), false) test.done() 'does not hang on PI:IP_ADDRESS:fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5bEND_PI:8:8:8:8:8:8:8': (test) -> test.equal(ipaddr.IPv6.isValid('::8:8:8:8:8:8:8:8:8'), false) test.done()
[ { "context": "xtFactory.CreateFromKey @network, ECKey.fromWIF \"L36oQYkkqDrE7wzyHGBAoUVHug2daua3sSmuSFkWFTT76hTJgetV\"\n client = new ChannelClient context\n @chan", "end": 2374, "score": 0.9712203145027161, "start": 2323, "tag": "KEY", "value": "36oQYkkqDrE7wzyHGBAoUVHug2daua3sSmuSFkWFTT76hTJgetV" } ]
demo/client_controller.coffee
devktor/micropayments.js
0
{ChannelClientContextFactory, ChannelClientContext} = require "../channel_client_context" ChannelClient = require "../channel_client" {Transaction, Address, ECPubKey, ECKey} = require "bitcoinjs-lib" class Controller constructor:(@network, @node, @db, @channelServer, @notifier)-> @node.subscribe (err, data)=> if err? or not data? or not data.hex? console.log "notification error: ",err else @processDeposit data.hex processDeposit:(hex)-> transaction = Transaction.fromHex hex outputs = [] for output in transaction.outs outputs.push Address.fromOutputScript(output.script, @network).toString() @db.collection("channel").findOne {depositAddress:{$in:outputs}}, (err, contextData)=> if err? or not contextData? or not contextData.active if err? then console.log "error : ",err else console.log "transaction ins: ",transaction.ins context = new ChannelClientContext @network context.fromJSON contextData client = new ChannelClient context contract = client.createContract hex refund = client.createRefund() if client and refund @channelServer.post "/refund", {channel: contextData.id, tx: refund.toHex()}, (err, result)=> if err? console.log "failed to create refund tx: ",err else updates = context.toJSON() updates.refundTx = result.tx updates.id = contextData.id updates.active = contextData.active @node.send contract.toHex(), (err)=> if err? console.log "failed to send transaction : ",err else console.log "contract sent" @db.collection("channel").update {id:updates.id}, {$set:updates}, (err)=> if err? console.log "failed to save context : ",err else console.log "channel #{updates.id} started" @notifier.emit 'update', updates else console.log "failed to create contract" undefined open:(req, res)-> context = ChannelClientContextFactory.Create @network # context = ChannelClientContextFactory.CreateFromKey @network, ECKey.fromWIF "L36oQYkkqDrE7wzyHGBAoUVHug2daua3sSmuSFkWFTT76hTJgetV" client = new ChannelClient context @channelServer.post "/request", {pubkey: context.clientKey.pub.toHex()}, (err, response)=> if err? res.sendStatus 500 else client.setServerKey response.pubkey data = context.toJSON() data.id = context.getContractAddress().toString() data.depositAddress = context.getClientAddress().toString() @node.registerAddresses data.depositAddress, false, (err)=> if err? res.sendStatus 500 else data.active = true @db.collection("channel").insert data, (err)=> if err? res.sendStatus 500 else res.send data status:(req, res)-> @execute req, res, (client)-> context = client.context res.send status:if !context.active then "closed" else if context.refundTx? then "open" else "pending" pay:(req, res)-> if !req.body.amount? res.send 400 else @execute req, res, (client)=> payAmount = parseInt req.body.amount tx = client.createPayment payAmount if !tx console.log "failed to create payment" res.sendStatus 400 else console.log "tx=",tx console.log "context=",client.context.toJSON() hex = tx.toHex() @channelServer.post "/pay", {channel:req.body.channel, tx:hex}, (err, data)=> if err? console.log "payment failed error :", err res.sendStatus 500 else @db.collection("channel").update {id:req.body.channel}, {$set:client.context.toJSON()}, (err)-> if err? console.log "failed to save context: ",err else res.send paymentID:tx.getId(), contractAmount:client.context.contractAmount, paid:data.paidAmount close:(req, res)-> @execute req, res, ()=> @db.collection("channel").update {id:req.body.channel}, {$set:{active:false}}, (err)=> if err? res.sendStatus 500 else @channelServer.post "/close", {channel:req.body.channel}, (err, data)=> if err? res.sendStatus 500 else res.sendStatus 200, data refund:(req, res)-> @execute req, res, (client)=> if !client.context.refundTx? res.send 400 else @node.send client.context.refundTx.toHex(), (err)=> if err? console.log "channel #{client.context.getContractAddress()} failed to send refund tx: ",err res.sendStatus 500 else console.log "channel #{client.context.getContractAddress()} refund transaction sent " res.sendStatus 200 list:(req, res)-> @db.collection("channel").find().toArray (err, channels)-> if err? res.send 500 else res.send channels execute:(req, res, next)-> if !req.body.channel? res.send 400 else @db.collection("channel").findOne {id:req.body.channel}, (err, data)=> if err? or not data? res.sendStatus 500 else context = new ChannelClientContext @network context.fromJSON data context.active = data.active client = new ChannelClient context next client module.exports = Controller
179191
{ChannelClientContextFactory, ChannelClientContext} = require "../channel_client_context" ChannelClient = require "../channel_client" {Transaction, Address, ECPubKey, ECKey} = require "bitcoinjs-lib" class Controller constructor:(@network, @node, @db, @channelServer, @notifier)-> @node.subscribe (err, data)=> if err? or not data? or not data.hex? console.log "notification error: ",err else @processDeposit data.hex processDeposit:(hex)-> transaction = Transaction.fromHex hex outputs = [] for output in transaction.outs outputs.push Address.fromOutputScript(output.script, @network).toString() @db.collection("channel").findOne {depositAddress:{$in:outputs}}, (err, contextData)=> if err? or not contextData? or not contextData.active if err? then console.log "error : ",err else console.log "transaction ins: ",transaction.ins context = new ChannelClientContext @network context.fromJSON contextData client = new ChannelClient context contract = client.createContract hex refund = client.createRefund() if client and refund @channelServer.post "/refund", {channel: contextData.id, tx: refund.toHex()}, (err, result)=> if err? console.log "failed to create refund tx: ",err else updates = context.toJSON() updates.refundTx = result.tx updates.id = contextData.id updates.active = contextData.active @node.send contract.toHex(), (err)=> if err? console.log "failed to send transaction : ",err else console.log "contract sent" @db.collection("channel").update {id:updates.id}, {$set:updates}, (err)=> if err? console.log "failed to save context : ",err else console.log "channel #{updates.id} started" @notifier.emit 'update', updates else console.log "failed to create contract" undefined open:(req, res)-> context = ChannelClientContextFactory.Create @network # context = ChannelClientContextFactory.CreateFromKey @network, ECKey.fromWIF "L<KEY>" client = new ChannelClient context @channelServer.post "/request", {pubkey: context.clientKey.pub.toHex()}, (err, response)=> if err? res.sendStatus 500 else client.setServerKey response.pubkey data = context.toJSON() data.id = context.getContractAddress().toString() data.depositAddress = context.getClientAddress().toString() @node.registerAddresses data.depositAddress, false, (err)=> if err? res.sendStatus 500 else data.active = true @db.collection("channel").insert data, (err)=> if err? res.sendStatus 500 else res.send data status:(req, res)-> @execute req, res, (client)-> context = client.context res.send status:if !context.active then "closed" else if context.refundTx? then "open" else "pending" pay:(req, res)-> if !req.body.amount? res.send 400 else @execute req, res, (client)=> payAmount = parseInt req.body.amount tx = client.createPayment payAmount if !tx console.log "failed to create payment" res.sendStatus 400 else console.log "tx=",tx console.log "context=",client.context.toJSON() hex = tx.toHex() @channelServer.post "/pay", {channel:req.body.channel, tx:hex}, (err, data)=> if err? console.log "payment failed error :", err res.sendStatus 500 else @db.collection("channel").update {id:req.body.channel}, {$set:client.context.toJSON()}, (err)-> if err? console.log "failed to save context: ",err else res.send paymentID:tx.getId(), contractAmount:client.context.contractAmount, paid:data.paidAmount close:(req, res)-> @execute req, res, ()=> @db.collection("channel").update {id:req.body.channel}, {$set:{active:false}}, (err)=> if err? res.sendStatus 500 else @channelServer.post "/close", {channel:req.body.channel}, (err, data)=> if err? res.sendStatus 500 else res.sendStatus 200, data refund:(req, res)-> @execute req, res, (client)=> if !client.context.refundTx? res.send 400 else @node.send client.context.refundTx.toHex(), (err)=> if err? console.log "channel #{client.context.getContractAddress()} failed to send refund tx: ",err res.sendStatus 500 else console.log "channel #{client.context.getContractAddress()} refund transaction sent " res.sendStatus 200 list:(req, res)-> @db.collection("channel").find().toArray (err, channels)-> if err? res.send 500 else res.send channels execute:(req, res, next)-> if !req.body.channel? res.send 400 else @db.collection("channel").findOne {id:req.body.channel}, (err, data)=> if err? or not data? res.sendStatus 500 else context = new ChannelClientContext @network context.fromJSON data context.active = data.active client = new ChannelClient context next client module.exports = Controller
true
{ChannelClientContextFactory, ChannelClientContext} = require "../channel_client_context" ChannelClient = require "../channel_client" {Transaction, Address, ECPubKey, ECKey} = require "bitcoinjs-lib" class Controller constructor:(@network, @node, @db, @channelServer, @notifier)-> @node.subscribe (err, data)=> if err? or not data? or not data.hex? console.log "notification error: ",err else @processDeposit data.hex processDeposit:(hex)-> transaction = Transaction.fromHex hex outputs = [] for output in transaction.outs outputs.push Address.fromOutputScript(output.script, @network).toString() @db.collection("channel").findOne {depositAddress:{$in:outputs}}, (err, contextData)=> if err? or not contextData? or not contextData.active if err? then console.log "error : ",err else console.log "transaction ins: ",transaction.ins context = new ChannelClientContext @network context.fromJSON contextData client = new ChannelClient context contract = client.createContract hex refund = client.createRefund() if client and refund @channelServer.post "/refund", {channel: contextData.id, tx: refund.toHex()}, (err, result)=> if err? console.log "failed to create refund tx: ",err else updates = context.toJSON() updates.refundTx = result.tx updates.id = contextData.id updates.active = contextData.active @node.send contract.toHex(), (err)=> if err? console.log "failed to send transaction : ",err else console.log "contract sent" @db.collection("channel").update {id:updates.id}, {$set:updates}, (err)=> if err? console.log "failed to save context : ",err else console.log "channel #{updates.id} started" @notifier.emit 'update', updates else console.log "failed to create contract" undefined open:(req, res)-> context = ChannelClientContextFactory.Create @network # context = ChannelClientContextFactory.CreateFromKey @network, ECKey.fromWIF "LPI:KEY:<KEY>END_PI" client = new ChannelClient context @channelServer.post "/request", {pubkey: context.clientKey.pub.toHex()}, (err, response)=> if err? res.sendStatus 500 else client.setServerKey response.pubkey data = context.toJSON() data.id = context.getContractAddress().toString() data.depositAddress = context.getClientAddress().toString() @node.registerAddresses data.depositAddress, false, (err)=> if err? res.sendStatus 500 else data.active = true @db.collection("channel").insert data, (err)=> if err? res.sendStatus 500 else res.send data status:(req, res)-> @execute req, res, (client)-> context = client.context res.send status:if !context.active then "closed" else if context.refundTx? then "open" else "pending" pay:(req, res)-> if !req.body.amount? res.send 400 else @execute req, res, (client)=> payAmount = parseInt req.body.amount tx = client.createPayment payAmount if !tx console.log "failed to create payment" res.sendStatus 400 else console.log "tx=",tx console.log "context=",client.context.toJSON() hex = tx.toHex() @channelServer.post "/pay", {channel:req.body.channel, tx:hex}, (err, data)=> if err? console.log "payment failed error :", err res.sendStatus 500 else @db.collection("channel").update {id:req.body.channel}, {$set:client.context.toJSON()}, (err)-> if err? console.log "failed to save context: ",err else res.send paymentID:tx.getId(), contractAmount:client.context.contractAmount, paid:data.paidAmount close:(req, res)-> @execute req, res, ()=> @db.collection("channel").update {id:req.body.channel}, {$set:{active:false}}, (err)=> if err? res.sendStatus 500 else @channelServer.post "/close", {channel:req.body.channel}, (err, data)=> if err? res.sendStatus 500 else res.sendStatus 200, data refund:(req, res)-> @execute req, res, (client)=> if !client.context.refundTx? res.send 400 else @node.send client.context.refundTx.toHex(), (err)=> if err? console.log "channel #{client.context.getContractAddress()} failed to send refund tx: ",err res.sendStatus 500 else console.log "channel #{client.context.getContractAddress()} refund transaction sent " res.sendStatus 200 list:(req, res)-> @db.collection("channel").find().toArray (err, channels)-> if err? res.send 500 else res.send channels execute:(req, res, next)-> if !req.body.channel? res.send 400 else @db.collection("channel").findOne {id:req.body.channel}, (err, data)=> if err? or not data? res.sendStatus 500 else context = new ChannelClientContext @network context.fromJSON data context.active = data.active client = new ChannelClient context next client module.exports = Controller
[ { "context": "uire('dox-parser')\n *\n * Dox\n * Copyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca>\n * MIT Licensed\n ###\n\n###!\n ", "end": 149, "score": 0.9998568296432495, "start": 135, "tag": "NAME", "value": "TJ Holowaychuk" }, { "context": ")\n *\n * Dox\n * Copyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca>\n * MIT Licensed\n ###\n\n###!\n * Module dependencie", "end": 169, "score": 0.9999315142631531, "start": 151, "tag": "EMAIL", "value": "tj@vision-media.ca" } ]
examples/fixtures/dox-parser.coffee
cbou/markdox
90
###* * # The parser * * This is a incredible parser. * * var parser = require('dox-parser') * * Dox * Copyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed ### ###! * Module dependencies. ### markdown = require("github-flavored-markdown").parse ###! * Library version. ### exports.version = "0.0.5" ###* * Parse comments in the given string of `js`. * * @param {String} js * @return {Array} * @see exports.parseComment * @api public ### exports.parseComments = (js) -> comments = [] comment = undefined buf = "" ignore = undefined within = undefined code = undefined i = 0 len = js.length while i < len if "/" is js[i] and "*" is js[i + 1] if buf.trim().length comment = comments[comments.length - 1] comment.code = code = buf.trim() comment.ctx = exports.parseCodeContext(code) buf = "" i += 2 within = true ignore = "!" is js[i] else if "*" is js[i] and "/" is js[i + 1] i += 2 buf = buf.replace(/^ *\* ?/g, "") comment = exports.parseComment(buf) comment.ignore = ignore comments.push comment within = ignore = false buf = "" else buf += js[i] ++i if buf.trim().length comment = comments[comments.length - 1] code = buf.trim() comment.code = code comments ###* * Parse the given comment `str`. * * The comment object returned contains the following: * * - `tags` array of tag objects * - `description` the first line of the comment * - `body` lines following the description * - `content` both the description and the body * - `isPrivate` true when "@api private" is used * * @param {String} str * @return {Object} * @see exports.parseTag * @api public ### exports.parseComment = (str) -> str = str.trim() comment = tags: [] description = {} description.full = str.split("@")[0].replace(/^([\w ]+):/g, "## $1") description.summary = description.full.split("\n\n")[0] description.body = description.full.split("\n\n").slice(1).join("\n\n") comment.description = description if ~str.indexOf("@") tags = "@" + str.split("@").slice(1).join("@") comment.tags = tags.split("\n").map(exports.parseTag) comment.isPrivate = comment.tags.some((tag) -> "api" is tag.type and "private" is tag.visibility ) description.full = markdown(escape(description.full)) description.summary = markdown(escape(description.summary)) description.body = markdown(escape(description.body)) comment ###* * Parse tag string "@param {Array} name description" etc. * * @param {String} * @return {Object} * @api public ### exports.parseTag = (str) -> tag = {} parts = str.split(RegExp(" +")) type = tag.type = parts.shift().replace("@", "") switch type when "param" tag.types = exports.parseTagTypes(parts.shift()) tag.name = parts.shift() or "" tag.description = parts.join(" ") when "return" tag.types = exports.parseTagTypes(parts.shift()) tag.description = parts.join(" ") when "see" if ~str.indexOf("http") tag.title = (if parts.length > 1 then parts.shift() else "") tag.url = parts.join(" ") else tag.local = parts.join(" ") when "api" tag.visibility = parts.shift() when "type" tag.types = exports.parseTagTypes(parts.shift()) tag ###* * Parse tag type string "{Array|Object}" etc. * * @param {String} str * @return {Array} * @api public ### exports.parseTagTypes = (str) -> str.replace(/[{}]/g, "").split RegExp(" *[|,\\/] *") ###* * Parse the context from the given `str` of js. * * This method attempts to discover the context * for the comment based on it's code. Currently * supports: * * - function statements * - function expressions * - prototype methods * - prototype properties * - methods * - properties * - declarations * * @param {String} str * @return {Object} * @api public ### exports.parseCodeContext = (str) -> str = str.split("\n")[0] if /^function (\w+)\(/.exec(str) type: "function" name: RegExp.$1 else if /^var *(\w+) *= *function/.exec(str) type: "function" name: RegExp.$1 else if /^(\w+)\.prototype\.(\w+) *= *function/.exec(str) type: "method" constructor: RegExp.$1 name: RegExp.$2 else if /^(\w+)\.prototype\.(\w+) *= *([^\n;]+)/.exec(str) type: "property" constructor: RegExp.$1 name: RegExp.$2 value: RegExp.$3 else if /^(\w+)\.(\w+) *= *function/.exec(str) type: "method" receiver: RegExp.$1 name: RegExp.$2 else if /^(\w+)\.(\w+) *= *([^\n;]+)/.exec(str) type: "property" receiver: RegExp.$1 name: RegExp.$2 value: RegExp.$3 else if /^var +(\w+) *= *([^\n;]+)/.exec(str) type: "declaration" name: RegExp.$1 value: RegExp.$2 ###* * Escape the given `html`. * * @param {String} html * @return {String} * @api private ### escape = (html) -> String(html) .replace(/&(?!\w+;)/g, "&amp;") .replace(/</g, "&lt;") .replace />/g, "&gt;"
201475
###* * # The parser * * This is a incredible parser. * * var parser = require('dox-parser') * * Dox * Copyright (c) 2010 <NAME> <<EMAIL>> * MIT Licensed ### ###! * Module dependencies. ### markdown = require("github-flavored-markdown").parse ###! * Library version. ### exports.version = "0.0.5" ###* * Parse comments in the given string of `js`. * * @param {String} js * @return {Array} * @see exports.parseComment * @api public ### exports.parseComments = (js) -> comments = [] comment = undefined buf = "" ignore = undefined within = undefined code = undefined i = 0 len = js.length while i < len if "/" is js[i] and "*" is js[i + 1] if buf.trim().length comment = comments[comments.length - 1] comment.code = code = buf.trim() comment.ctx = exports.parseCodeContext(code) buf = "" i += 2 within = true ignore = "!" is js[i] else if "*" is js[i] and "/" is js[i + 1] i += 2 buf = buf.replace(/^ *\* ?/g, "") comment = exports.parseComment(buf) comment.ignore = ignore comments.push comment within = ignore = false buf = "" else buf += js[i] ++i if buf.trim().length comment = comments[comments.length - 1] code = buf.trim() comment.code = code comments ###* * Parse the given comment `str`. * * The comment object returned contains the following: * * - `tags` array of tag objects * - `description` the first line of the comment * - `body` lines following the description * - `content` both the description and the body * - `isPrivate` true when "@api private" is used * * @param {String} str * @return {Object} * @see exports.parseTag * @api public ### exports.parseComment = (str) -> str = str.trim() comment = tags: [] description = {} description.full = str.split("@")[0].replace(/^([\w ]+):/g, "## $1") description.summary = description.full.split("\n\n")[0] description.body = description.full.split("\n\n").slice(1).join("\n\n") comment.description = description if ~str.indexOf("@") tags = "@" + str.split("@").slice(1).join("@") comment.tags = tags.split("\n").map(exports.parseTag) comment.isPrivate = comment.tags.some((tag) -> "api" is tag.type and "private" is tag.visibility ) description.full = markdown(escape(description.full)) description.summary = markdown(escape(description.summary)) description.body = markdown(escape(description.body)) comment ###* * Parse tag string "@param {Array} name description" etc. * * @param {String} * @return {Object} * @api public ### exports.parseTag = (str) -> tag = {} parts = str.split(RegExp(" +")) type = tag.type = parts.shift().replace("@", "") switch type when "param" tag.types = exports.parseTagTypes(parts.shift()) tag.name = parts.shift() or "" tag.description = parts.join(" ") when "return" tag.types = exports.parseTagTypes(parts.shift()) tag.description = parts.join(" ") when "see" if ~str.indexOf("http") tag.title = (if parts.length > 1 then parts.shift() else "") tag.url = parts.join(" ") else tag.local = parts.join(" ") when "api" tag.visibility = parts.shift() when "type" tag.types = exports.parseTagTypes(parts.shift()) tag ###* * Parse tag type string "{Array|Object}" etc. * * @param {String} str * @return {Array} * @api public ### exports.parseTagTypes = (str) -> str.replace(/[{}]/g, "").split RegExp(" *[|,\\/] *") ###* * Parse the context from the given `str` of js. * * This method attempts to discover the context * for the comment based on it's code. Currently * supports: * * - function statements * - function expressions * - prototype methods * - prototype properties * - methods * - properties * - declarations * * @param {String} str * @return {Object} * @api public ### exports.parseCodeContext = (str) -> str = str.split("\n")[0] if /^function (\w+)\(/.exec(str) type: "function" name: RegExp.$1 else if /^var *(\w+) *= *function/.exec(str) type: "function" name: RegExp.$1 else if /^(\w+)\.prototype\.(\w+) *= *function/.exec(str) type: "method" constructor: RegExp.$1 name: RegExp.$2 else if /^(\w+)\.prototype\.(\w+) *= *([^\n;]+)/.exec(str) type: "property" constructor: RegExp.$1 name: RegExp.$2 value: RegExp.$3 else if /^(\w+)\.(\w+) *= *function/.exec(str) type: "method" receiver: RegExp.$1 name: RegExp.$2 else if /^(\w+)\.(\w+) *= *([^\n;]+)/.exec(str) type: "property" receiver: RegExp.$1 name: RegExp.$2 value: RegExp.$3 else if /^var +(\w+) *= *([^\n;]+)/.exec(str) type: "declaration" name: RegExp.$1 value: RegExp.$2 ###* * Escape the given `html`. * * @param {String} html * @return {String} * @api private ### escape = (html) -> String(html) .replace(/&(?!\w+;)/g, "&amp;") .replace(/</g, "&lt;") .replace />/g, "&gt;"
true
###* * # The parser * * This is a incredible parser. * * var parser = require('dox-parser') * * Dox * Copyright (c) 2010 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> * MIT Licensed ### ###! * Module dependencies. ### markdown = require("github-flavored-markdown").parse ###! * Library version. ### exports.version = "0.0.5" ###* * Parse comments in the given string of `js`. * * @param {String} js * @return {Array} * @see exports.parseComment * @api public ### exports.parseComments = (js) -> comments = [] comment = undefined buf = "" ignore = undefined within = undefined code = undefined i = 0 len = js.length while i < len if "/" is js[i] and "*" is js[i + 1] if buf.trim().length comment = comments[comments.length - 1] comment.code = code = buf.trim() comment.ctx = exports.parseCodeContext(code) buf = "" i += 2 within = true ignore = "!" is js[i] else if "*" is js[i] and "/" is js[i + 1] i += 2 buf = buf.replace(/^ *\* ?/g, "") comment = exports.parseComment(buf) comment.ignore = ignore comments.push comment within = ignore = false buf = "" else buf += js[i] ++i if buf.trim().length comment = comments[comments.length - 1] code = buf.trim() comment.code = code comments ###* * Parse the given comment `str`. * * The comment object returned contains the following: * * - `tags` array of tag objects * - `description` the first line of the comment * - `body` lines following the description * - `content` both the description and the body * - `isPrivate` true when "@api private" is used * * @param {String} str * @return {Object} * @see exports.parseTag * @api public ### exports.parseComment = (str) -> str = str.trim() comment = tags: [] description = {} description.full = str.split("@")[0].replace(/^([\w ]+):/g, "## $1") description.summary = description.full.split("\n\n")[0] description.body = description.full.split("\n\n").slice(1).join("\n\n") comment.description = description if ~str.indexOf("@") tags = "@" + str.split("@").slice(1).join("@") comment.tags = tags.split("\n").map(exports.parseTag) comment.isPrivate = comment.tags.some((tag) -> "api" is tag.type and "private" is tag.visibility ) description.full = markdown(escape(description.full)) description.summary = markdown(escape(description.summary)) description.body = markdown(escape(description.body)) comment ###* * Parse tag string "@param {Array} name description" etc. * * @param {String} * @return {Object} * @api public ### exports.parseTag = (str) -> tag = {} parts = str.split(RegExp(" +")) type = tag.type = parts.shift().replace("@", "") switch type when "param" tag.types = exports.parseTagTypes(parts.shift()) tag.name = parts.shift() or "" tag.description = parts.join(" ") when "return" tag.types = exports.parseTagTypes(parts.shift()) tag.description = parts.join(" ") when "see" if ~str.indexOf("http") tag.title = (if parts.length > 1 then parts.shift() else "") tag.url = parts.join(" ") else tag.local = parts.join(" ") when "api" tag.visibility = parts.shift() when "type" tag.types = exports.parseTagTypes(parts.shift()) tag ###* * Parse tag type string "{Array|Object}" etc. * * @param {String} str * @return {Array} * @api public ### exports.parseTagTypes = (str) -> str.replace(/[{}]/g, "").split RegExp(" *[|,\\/] *") ###* * Parse the context from the given `str` of js. * * This method attempts to discover the context * for the comment based on it's code. Currently * supports: * * - function statements * - function expressions * - prototype methods * - prototype properties * - methods * - properties * - declarations * * @param {String} str * @return {Object} * @api public ### exports.parseCodeContext = (str) -> str = str.split("\n")[0] if /^function (\w+)\(/.exec(str) type: "function" name: RegExp.$1 else if /^var *(\w+) *= *function/.exec(str) type: "function" name: RegExp.$1 else if /^(\w+)\.prototype\.(\w+) *= *function/.exec(str) type: "method" constructor: RegExp.$1 name: RegExp.$2 else if /^(\w+)\.prototype\.(\w+) *= *([^\n;]+)/.exec(str) type: "property" constructor: RegExp.$1 name: RegExp.$2 value: RegExp.$3 else if /^(\w+)\.(\w+) *= *function/.exec(str) type: "method" receiver: RegExp.$1 name: RegExp.$2 else if /^(\w+)\.(\w+) *= *([^\n;]+)/.exec(str) type: "property" receiver: RegExp.$1 name: RegExp.$2 value: RegExp.$3 else if /^var +(\w+) *= *([^\n;]+)/.exec(str) type: "declaration" name: RegExp.$1 value: RegExp.$2 ###* * Escape the given `html`. * * @param {String} html * @return {String} * @api private ### escape = (html) -> String(html) .replace(/&(?!\w+;)/g, "&amp;") .replace(/</g, "&lt;") .replace />/g, "&gt;"
[ { "context": "\n @parse: (value) ->\n safe_key_match = /ground\\.(\\S+)\\.(\\S+)\\.(\\S+)\\.(\\S+)\\.bmp/.exec(value)\n\n attributes = {}\n if safe_key_match", "end": 2395, "score": 0.9651799201965332, "start": 2360, "tag": "KEY", "value": "S+)\\.(\\S+)\\.(\\S+)\\.(\\S+)\\.bmp/.exec" } ]
src/land/land-attributes.coffee
starpeace-project/starpeace-website-client-assets
0
class LandAttributes @PLANET_TYPES: { other:'other', earth:'earth' } # FIXME: TODO: add alien swamp @SEASONS: { other:'other', winter:'winter', spring:'spring', summer:'summer', fall:'fall' } @ZONES: { other:'other', border:'border', midgrass:'midgrass', grass:'grass', dryground:'dryground', water:'water' } @TYPES: { other:'other', special:'special', center:'center', neo:'neo', seo:'seo', swo:'swo', nwo:'nwo', nei:'nei', sei:'sei', swi:'swi', nwi:'nwi', n:'n', e:'e', s:'s', w:'w' } @VALID_SEASONS: [ LandAttributes.SEASONS.winter, LandAttributes.SEASONS.spring, LandAttributes.SEASONS.summer, LandAttributes.SEASONS.fall ] @ORIENTATION_ROTATIONS = { '0deg':0, '90deg':1, '180deg':2, '270deg':3 } @TYPE_SINGLE_ROTATION = { other:'other', special:'special', center:'center', n:'w', e:'n', s:'e', w:'s', neo:'nwo', seo:'neo', swo:'seo', nwo:'swo', nei:'nwi', sei:'nei', swi:'sei', nwi:'swi' } @rotate_type: (type, orientation) -> for count in [0...(LandAttributes.ORIENTATION_ROTATIONS[orientation] || 0)] type = @TYPE_SINGLE_ROTATION[type] || 'other' type @planet_type_from_value: (value) -> return LandAttributes.PLANET_TYPES[value] if LandAttributes.PLANET_TYPES[value]? for key of LandAttributes.PLANET_TYPES return LandAttributes.PLANET_TYPES[key] if value.indexOf(key) >= 0 LandAttributes.PLANET_TYPES.other @season_from_value: (value) -> safe_value = value.toLowerCase() return LandAttributes.SEASONS[safe_value] if LandAttributes.SEASONS[safe_value]? for key of LandAttributes.SEASONS return LandAttributes.SEASONS[key] if safe_value.indexOf(key) >= 0 LandAttributes.SEASONS.other @zone_from_value: (value) -> return LandAttributes.ZONES[value] if LandAttributes.ZONES[value]? for key of LandAttributes.ZONES return LandAttributes.ZONES[key] if value.indexOf(key) >= 0 LandAttributes.ZONES.other @type_from_value: (value) -> return LandAttributes.TYPES[value] if LandAttributes.TYPES[value]? for key of LandAttributes.TYPES return LandAttributes.TYPES[key] if value.indexOf(key) >= 0 LandAttributes.TYPES.other @variant_from_value: (value) -> match = /[a-zA-Z]*(\d+)/g.exec(value) if match then new Number(match[1]) else Number.NaN @parse: (value) -> safe_key_match = /ground\.(\S+)\.(\S+)\.(\S+)\.(\S+)\.bmp/.exec(value) attributes = {} if safe_key_match attributes.id = safe_key_match[1] attributes.zone = safe_key_match[2] attributes.type = safe_key_match[3] attributes.variant = safe_key_match[4] else parts = value.toLowerCase().split('.') attributes.id = new Number(parts[1]) if parts.length > 2 main_content = if parts.length > 2 then parts[2] else parts[0] attributes.zone = LandAttributes.zone_from_value(main_content) main_content = main_content.replace(new RegExp(attributes.zone, 'gi'), '') attributes.type = LandAttributes.type_from_value(main_content) main_content = main_content.replace(new RegExp(attributes.type, 'gi'), '') attributes.variant = LandAttributes.variant_from_value(main_content) attributes module.exports = LandAttributes
191076
class LandAttributes @PLANET_TYPES: { other:'other', earth:'earth' } # FIXME: TODO: add alien swamp @SEASONS: { other:'other', winter:'winter', spring:'spring', summer:'summer', fall:'fall' } @ZONES: { other:'other', border:'border', midgrass:'midgrass', grass:'grass', dryground:'dryground', water:'water' } @TYPES: { other:'other', special:'special', center:'center', neo:'neo', seo:'seo', swo:'swo', nwo:'nwo', nei:'nei', sei:'sei', swi:'swi', nwi:'nwi', n:'n', e:'e', s:'s', w:'w' } @VALID_SEASONS: [ LandAttributes.SEASONS.winter, LandAttributes.SEASONS.spring, LandAttributes.SEASONS.summer, LandAttributes.SEASONS.fall ] @ORIENTATION_ROTATIONS = { '0deg':0, '90deg':1, '180deg':2, '270deg':3 } @TYPE_SINGLE_ROTATION = { other:'other', special:'special', center:'center', n:'w', e:'n', s:'e', w:'s', neo:'nwo', seo:'neo', swo:'seo', nwo:'swo', nei:'nwi', sei:'nei', swi:'sei', nwi:'swi' } @rotate_type: (type, orientation) -> for count in [0...(LandAttributes.ORIENTATION_ROTATIONS[orientation] || 0)] type = @TYPE_SINGLE_ROTATION[type] || 'other' type @planet_type_from_value: (value) -> return LandAttributes.PLANET_TYPES[value] if LandAttributes.PLANET_TYPES[value]? for key of LandAttributes.PLANET_TYPES return LandAttributes.PLANET_TYPES[key] if value.indexOf(key) >= 0 LandAttributes.PLANET_TYPES.other @season_from_value: (value) -> safe_value = value.toLowerCase() return LandAttributes.SEASONS[safe_value] if LandAttributes.SEASONS[safe_value]? for key of LandAttributes.SEASONS return LandAttributes.SEASONS[key] if safe_value.indexOf(key) >= 0 LandAttributes.SEASONS.other @zone_from_value: (value) -> return LandAttributes.ZONES[value] if LandAttributes.ZONES[value]? for key of LandAttributes.ZONES return LandAttributes.ZONES[key] if value.indexOf(key) >= 0 LandAttributes.ZONES.other @type_from_value: (value) -> return LandAttributes.TYPES[value] if LandAttributes.TYPES[value]? for key of LandAttributes.TYPES return LandAttributes.TYPES[key] if value.indexOf(key) >= 0 LandAttributes.TYPES.other @variant_from_value: (value) -> match = /[a-zA-Z]*(\d+)/g.exec(value) if match then new Number(match[1]) else Number.NaN @parse: (value) -> safe_key_match = /ground\.(\<KEY>(value) attributes = {} if safe_key_match attributes.id = safe_key_match[1] attributes.zone = safe_key_match[2] attributes.type = safe_key_match[3] attributes.variant = safe_key_match[4] else parts = value.toLowerCase().split('.') attributes.id = new Number(parts[1]) if parts.length > 2 main_content = if parts.length > 2 then parts[2] else parts[0] attributes.zone = LandAttributes.zone_from_value(main_content) main_content = main_content.replace(new RegExp(attributes.zone, 'gi'), '') attributes.type = LandAttributes.type_from_value(main_content) main_content = main_content.replace(new RegExp(attributes.type, 'gi'), '') attributes.variant = LandAttributes.variant_from_value(main_content) attributes module.exports = LandAttributes
true
class LandAttributes @PLANET_TYPES: { other:'other', earth:'earth' } # FIXME: TODO: add alien swamp @SEASONS: { other:'other', winter:'winter', spring:'spring', summer:'summer', fall:'fall' } @ZONES: { other:'other', border:'border', midgrass:'midgrass', grass:'grass', dryground:'dryground', water:'water' } @TYPES: { other:'other', special:'special', center:'center', neo:'neo', seo:'seo', swo:'swo', nwo:'nwo', nei:'nei', sei:'sei', swi:'swi', nwi:'nwi', n:'n', e:'e', s:'s', w:'w' } @VALID_SEASONS: [ LandAttributes.SEASONS.winter, LandAttributes.SEASONS.spring, LandAttributes.SEASONS.summer, LandAttributes.SEASONS.fall ] @ORIENTATION_ROTATIONS = { '0deg':0, '90deg':1, '180deg':2, '270deg':3 } @TYPE_SINGLE_ROTATION = { other:'other', special:'special', center:'center', n:'w', e:'n', s:'e', w:'s', neo:'nwo', seo:'neo', swo:'seo', nwo:'swo', nei:'nwi', sei:'nei', swi:'sei', nwi:'swi' } @rotate_type: (type, orientation) -> for count in [0...(LandAttributes.ORIENTATION_ROTATIONS[orientation] || 0)] type = @TYPE_SINGLE_ROTATION[type] || 'other' type @planet_type_from_value: (value) -> return LandAttributes.PLANET_TYPES[value] if LandAttributes.PLANET_TYPES[value]? for key of LandAttributes.PLANET_TYPES return LandAttributes.PLANET_TYPES[key] if value.indexOf(key) >= 0 LandAttributes.PLANET_TYPES.other @season_from_value: (value) -> safe_value = value.toLowerCase() return LandAttributes.SEASONS[safe_value] if LandAttributes.SEASONS[safe_value]? for key of LandAttributes.SEASONS return LandAttributes.SEASONS[key] if safe_value.indexOf(key) >= 0 LandAttributes.SEASONS.other @zone_from_value: (value) -> return LandAttributes.ZONES[value] if LandAttributes.ZONES[value]? for key of LandAttributes.ZONES return LandAttributes.ZONES[key] if value.indexOf(key) >= 0 LandAttributes.ZONES.other @type_from_value: (value) -> return LandAttributes.TYPES[value] if LandAttributes.TYPES[value]? for key of LandAttributes.TYPES return LandAttributes.TYPES[key] if value.indexOf(key) >= 0 LandAttributes.TYPES.other @variant_from_value: (value) -> match = /[a-zA-Z]*(\d+)/g.exec(value) if match then new Number(match[1]) else Number.NaN @parse: (value) -> safe_key_match = /ground\.(\PI:KEY:<KEY>END_PI(value) attributes = {} if safe_key_match attributes.id = safe_key_match[1] attributes.zone = safe_key_match[2] attributes.type = safe_key_match[3] attributes.variant = safe_key_match[4] else parts = value.toLowerCase().split('.') attributes.id = new Number(parts[1]) if parts.length > 2 main_content = if parts.length > 2 then parts[2] else parts[0] attributes.zone = LandAttributes.zone_from_value(main_content) main_content = main_content.replace(new RegExp(attributes.zone, 'gi'), '') attributes.type = LandAttributes.type_from_value(main_content) main_content = main_content.replace(new RegExp(attributes.type, 'gi'), '') attributes.variant = LandAttributes.variant_from_value(main_content) attributes module.exports = LandAttributes
[ { "context": " for key of clonedProps\n if key.indexOf('$') is 0 and key isnt '$$hashKey'\n obj[k", "end": 3824, "score": 0.7646017670631409, "start": 3823, "tag": "KEY", "value": "$" }, { "context": "\n if key.indexOf('$') is 0 and key isnt '$$hashKey'\n obj[key] = clonedProps[key]\n ", "end": 3855, "score": 0.9503100514411926, "start": 3846, "tag": "KEY", "value": "$$hashKey" } ]
src/index.coffee
ndxbxrme/ndx-rest-client
0
'use strict' module = null try module = angular.module 'ndx' catch e module =angular.module 'ndx', [] module.provider 'rest', -> waitForAuth = false bustCache = false lockAll = false disableCache = false cacheBuster = -> if bustCache then "?#{Math.floor(Math.random() * 9999999999999)}" else '' callbacks = endpoints: [] syncCallback = (name, obj, cb) -> if callbacks[name] and callbacks[name].length for callback in callbacks[name] callback obj cb?() hash = (str) -> h = 5381 i = str.length while i h = (h * 33) ^ str.charCodeAt --i h bustCache: (val) -> bustCache = val waitForAuth: (val) -> waitForAuth = val disableCache: (val) -> disableCache = val $get: ($http, $injector, $timeout) -> okToLoad = true endpoints = {} autoId = '_id' refreshFns = [] waiting = false ndxCheck = null needsRefresh = false maintenanceMode = false loading = 0 startLoading = -> loading++ stopLoading = -> loading-- if loading < 0 loading = 0 listTransform = items: true total: true page: true pageSize: true error: true cache = {} addToCache = (endpoint, args, obj) -> if not disableCache h = hash JSON.stringify args if not cache[endpoint] cache[endpoint] = {} cache[endpoint][h] = JSON.stringify data: obj.data fetchFromCache = (endpoint, args) -> if not disableCache h = hash JSON.stringify args if cache[endpoint] if cache[endpoint][h] str = cache[endpoint][h] newvar = JSON.parse str return newvar return null clearCache = (endpoint) -> if endpoint delete cache[endpoint] else cache = {} callRefreshFns = (isSocket) -> if okToLoad and endpoints for key of endpoints if endpoints[key].needsRefresh for fn in refreshFns fn key, endpoints[key].ids, isSocket endpoints[key].ids = [] endpoints[key].needsRefresh = false destroy = (obj) -> type = Object.prototype.toString.call obj if type is '[object Object]' if obj.destroy obj.destroy() for key in obj destroy obj[key] else if type is '[object Array]' for item in obj destroy item return restore = (obj) -> type = Object.prototype.toString.call obj if type is '[object Object]' if obj.refreshFn refreshFns.push obj.refreshFn for key in obj restore obj[key] else if type is '[object Array]' for item in obj restore item return cloneSpecialProps = (obj) -> output = null type = Object.prototype.toString.call obj if type is '[object Array]' output = output or [] for item in obj if item[autoId] clonedItem = cloneSpecialProps item clonedItem[autoId] = item[autoId] output.push clonedItem else if type is '[object Object]' output = output or {} for key of obj if key.indexOf('$') is 0 output[key] = obj[key] else if Object.prototype.toString.call(obj[key]) is '[object Array]' output[key] = cloneSpecialProps obj[key] output restoreSpecialProps = (obj, clonedProps) -> type = Object.prototype.toString.call obj if type is '[object Array]' for item in obj for clonedItem in clonedProps if item[autoId] is clonedItem[autoId] restoreSpecialProps item, clonedItem break else if type is '[object Object]' for key of clonedProps if key.indexOf('$') is 0 and key isnt '$$hashKey' obj[key] = clonedProps[key] restore obj[key] else restoreSpecialProps obj[key], clonedProps[key] return if $injector.has 'ndxCheck' ndxCheck = $injector.get 'ndxCheck' if $injector.has('Auth') okToLoad = false auth = $injector.get 'Auth' auth.onUser -> $timeout -> okToLoad = true for endpoint of endpoints endpoints[endpoint].needsRefresh = true callRefreshFns() callSocketRefresh = -> hasFuture = false for key, endpoint of endpoints if endpoint.needsRefresh and endpoint.refreshAt > new Date().valueOf() hasFuture = true if hasFuture return $timeout callSocketRefresh, 20 else callRefreshFns true socketRefresh = (data) -> if not lockAll if data clearCache data.table endpoints[data.table].needsRefresh = true endpoints[data.table].refreshAt = new Date().valueOf() + 400 type = Object.prototype.toString.call data.id if type is '[object Array]' for id of data.id endpoints[data.table].ids.push id else if type is '[object String]' endpoints[data.table].ids.push data.id else clearCache() for key of endpoints endpoints[key].needsRefresh = true callSocketRefresh() if $injector.has 'socket' socket = $injector.get 'socket' socket.on 'connect', -> socket.emit 'rest', {} if not $injector.has 'Server' socket.on 'update', socketRefresh socket.on 'insert', socketRefresh socket.on 'delete', socketRefresh $timeout -> $http.get '/rest/endpoints' .then (response) -> if response.data and response.data.endpoints and response.data.endpoints.length for endpoint in response.data.endpoints endpoints[endpoint] = needsRefresh: true lastRefresh: 0 nextRefresh: 0 ids: [] if response.data.autoId autoId = response.data.autoId if response.data.server maintenanceMode = response.data.server is 'maintenance' if needsRefresh callRefreshFns() syncCallback 'endpoints', response.data , (err) -> false lockAll: -> lockAll = true unlockAll: -> lockAll = false on: (name, callback) -> callbacks[name].push callback off: (name, callback) -> callbacks[name].splice callbacks[name].indexOf(callback), 1 endpoints: endpoints autoId: autoId maintenanceMode: -> maintenanceMode socketRefresh: socketRefresh needsRefresh: (val) -> needsRefresh = val callRefreshFns: callRefreshFns startLoading: startLoading stopLoading: stopLoading okToLoad: -> okToLoad save: (endpoint, obj, cb) -> startLoading() $http.post (endpoint.route or "/api/#{endpoint}") + ("/#{obj[autoId] or ''}"), obj .then (response) => stopLoading() endpoints[endpoint].needsRefresh = true ndxCheck and ndxCheck.setPristine() callRefreshFns endpoint response and response.data and cb?(response.data) , (err) -> stopLoading() false 'delete': (endpoint, obj, cb) -> startLoading() $http.delete (endpoint.route or "/api/#{endpoint}") + ("/#{obj[autoId] or ''}") .then (response) => stopLoading() endpoints[endpoint].needsRefresh = true ndxCheck and ndxCheck.setPristine() callRefreshFns endpoint response and response.data and cb?(response.data) , (err) -> stopLoading() false search: (endpoint, args, obj, cb, isSocket) -> isSocket or startLoading() args = args or {} handleResponse = (response) -> isSocket or stopLoading() clonedProps = null if obj.items and obj.items.length clonedProps = cloneSpecialProps obj.items objtrans response.data, (args.transform or listTransform), obj if obj.items and obj.items.length and clonedProps restoreSpecialProps obj.items, clonedProps obj.isSocket = isSocket cb? obj if response = fetchFromCache endpoint, args $timeout -> handleResponse response else $http.post (endpoint.route or "/api/#{endpoint}/search#{cacheBuster()}"), if endpoint.route and args and args.where then args.where else args .then (response) -> addToCache endpoint, args, response return handleResponse response , (err) -> isSocket or stopLoading() obj.items = [] obj.total = 0 obj.page = 1 obj.error = err obj.isSocket = isSocket cb? obj list: (endpoint, obj, cb, isSocket) -> isSocket or startLoading() handleResponse = (response) -> isSocket or stopLoading() clonedProps = null if obj.items and obj.items.length clonedProps = cloneSpecialProps obj.items objtrans response.data, (args.transform or listTransform), obj if obj.items and obj.items.length and clonedProps restoreSpecialProps obj.items, clonedProps obj.isSocket = isSocket cb? obj if response = fetchFromCache(endpoint, {}) $timeout -> handleResponse response else $http.post (endpoint.route or "/api/#{endpoint}#{cacheBuster()}") .then (response) -> addToCache endpoint, {}, response return handleResponse response , (err) -> isSocket or stopLoading() obj.items = [] obj.total = 0 obj.page = 1 obj.error = err obj.isSocket = isSocket cb? obj single: (endpoint, id, obj, cb, isSocket) -> isSocket or startLoading() handleResponse = (response) -> isSocket or stopLoading() clonedProps = null if obj.item clonedProps = cloneSpecialProps obj.item obj.item = response.data if obj.item and clonedProps restoreSpecialProps obj.item, clonedProps obj.isSocket = isSocket cb? obj if Object.prototype.toString.call(id) is '[object Object]' id = escape JSON.stringify id if response = fetchFromCache(endpoint, id:id) $timeout -> handleResponse response else $http.get (endpoint.route or "/api/#{endpoint}") + "/#{id}#{if obj.all then '/all' else ''}#{cacheBuster()}" .then (response) -> addToCache endpoint, id:id, response return handleResponse response , (err) -> isSocket or stopLoading() obj.item = {} obj.isSocket = isSocket cb? obj register: (fn) -> refreshFns.push fn dereg: (fn) -> refreshFns.splice refreshFns.indexOf(fn), 1 destroy: destroy loading: -> loading clearCache: clearCache checkCache: -> cache .run ($rootScope, $http, $timeout, rest) -> #borrowed from underscore.js throttle = (func, wait, options) -> context = undefined args = undefined result = undefined timeout = null previous = 0 if !options options = {} later = -> previous = if options.leading == false then 0 else Date.now() timeout = null result = func.apply(context, args) if !timeout context = args = null return -> now = Date.now() if !previous and options.leading == false previous = now remaining = wait - (now - previous) context = this args = arguments if remaining <= 0 or remaining > wait if timeout $timeout.cancel timeout timeout = null previous = now result = func.apply(context, args) if !timeout context = args = null else if !timeout and options.trailing != false timeout = $timeout(later, remaining) result root = Object.getPrototypeOf $rootScope root.restLoading = rest.loading root.list = (endpoint, args, cb, saveCb, locked) -> ignoreNextWatch = false if args cb = args.onData or cb saveCb = args.onSave or saveCb obj = items: null args: args refreshFn: null endpoint: endpoint locked: locked save: (item, checkFn) -> if checkFn checkFn 'save', endpoint, item, -> rest.save endpoint, item, saveCb else rest.save endpoint, item, saveCb delete: (item, checkFn) -> if checkFn checkFn 'delete', endpoint, item, -> rest.delete endpoint, item else rest.delete endpoint, item destroy: -> dereg?() rest.dereg obj.refreshFn throttledSearch = throttle rest.search, 1000 RefreshFn = (endpoint, args) -> (table, blank, isSocket) -> if args?.preRefresh args.preRefresh args ignoreNextWatch = true if not obj.locked if obj.items rest.destroy obj.items if endpoint.route if endpoint.endpoints and table for ep in endpoint.endpoints if table is ep throttledSearch endpoint, args, obj, cb, (isSocket or obj.args?.isSocket) break else if table is endpoint or not table throttledSearch endpoint, args, obj, cb, (isSocket or obj.args?.isSocket) obj.refreshFn = RefreshFn endpoint, args rest.register obj.refreshFn if endpoint.route and not endpoint.endpoints rest.search endpoint, args, obj, cb dereg = @.$watch -> JSON.stringify args , (n, o) -> if not ignoreNextWatch if rest.okToLoad() ### if endpoint.route if endpoint.endpoints and endpoint.endpoints.length for ep in endpoint.endpoints rest.endpoints[ep].needsRefresh = true else rest.endpoints[endpoint].needsRefresh = true ### obj.refreshFn obj.endpoint else rest.needsRefresh true else ignoreNextWatch = false , true @.$on '$destroy', -> obj.destroy() if not args and rest.endpoints.endpoints obj.refreshFn obj.endpoint if rest.okToLoad() rest.callRefreshFns() obj root.single = (endpoint, id, cb, saveCb, locked, all) -> obj = all: all item: null refreshFn: null endpoint: endpoint locked: locked save: (checkFn) -> if checkFn checkFn 'save', endpoint, @.item, => rest.save endpoint, @.item, saveCb else rest.save endpoint, @.item, saveCb delete: (checkFn) -> if checkFn checkFn 'delete', endpoint, @.item, => rest.delete endpoint, @.item else rest.delete endpoint, @.item destroy: -> rest.dereg obj.refreshFn throttledSingle = throttle rest.single, 1000 RefreshFn = (endpoint, id) -> (table, ids, isSocket) -> if ids and obj.item and ids.indexOf(obj.item[rest.autoId]) is -1 return if not obj.locked if endpoint.route if endpoint.endpoints if endpoint.endpoints.length and table for ep in endpoint.endpoints if table is ep throttledSingle endpoint, id, obj, cb, isSocket break else if table is endpoint or not table throttledSingle endpoint, id, obj, cb, isSocket obj.refreshFn = RefreshFn endpoint, id rest.register obj.refreshFn if rest.okToLoad() and rest.endpoints.endpoints ### if endpoint.route if endpoint.endpoints for ep in endpoint.endpoints rest.endpoints[ep].needsRefresh = true else rest.endpoints[endpoint].needsRefresh = false ### obj.refreshFn obj.endpoint else rest.needsRefresh true #if endpoint.route and not endpoint.endpoints rest.single endpoint, id, obj, cb @.$on '$destroy', obj.destroy obj
146504
'use strict' module = null try module = angular.module 'ndx' catch e module =angular.module 'ndx', [] module.provider 'rest', -> waitForAuth = false bustCache = false lockAll = false disableCache = false cacheBuster = -> if bustCache then "?#{Math.floor(Math.random() * 9999999999999)}" else '' callbacks = endpoints: [] syncCallback = (name, obj, cb) -> if callbacks[name] and callbacks[name].length for callback in callbacks[name] callback obj cb?() hash = (str) -> h = 5381 i = str.length while i h = (h * 33) ^ str.charCodeAt --i h bustCache: (val) -> bustCache = val waitForAuth: (val) -> waitForAuth = val disableCache: (val) -> disableCache = val $get: ($http, $injector, $timeout) -> okToLoad = true endpoints = {} autoId = '_id' refreshFns = [] waiting = false ndxCheck = null needsRefresh = false maintenanceMode = false loading = 0 startLoading = -> loading++ stopLoading = -> loading-- if loading < 0 loading = 0 listTransform = items: true total: true page: true pageSize: true error: true cache = {} addToCache = (endpoint, args, obj) -> if not disableCache h = hash JSON.stringify args if not cache[endpoint] cache[endpoint] = {} cache[endpoint][h] = JSON.stringify data: obj.data fetchFromCache = (endpoint, args) -> if not disableCache h = hash JSON.stringify args if cache[endpoint] if cache[endpoint][h] str = cache[endpoint][h] newvar = JSON.parse str return newvar return null clearCache = (endpoint) -> if endpoint delete cache[endpoint] else cache = {} callRefreshFns = (isSocket) -> if okToLoad and endpoints for key of endpoints if endpoints[key].needsRefresh for fn in refreshFns fn key, endpoints[key].ids, isSocket endpoints[key].ids = [] endpoints[key].needsRefresh = false destroy = (obj) -> type = Object.prototype.toString.call obj if type is '[object Object]' if obj.destroy obj.destroy() for key in obj destroy obj[key] else if type is '[object Array]' for item in obj destroy item return restore = (obj) -> type = Object.prototype.toString.call obj if type is '[object Object]' if obj.refreshFn refreshFns.push obj.refreshFn for key in obj restore obj[key] else if type is '[object Array]' for item in obj restore item return cloneSpecialProps = (obj) -> output = null type = Object.prototype.toString.call obj if type is '[object Array]' output = output or [] for item in obj if item[autoId] clonedItem = cloneSpecialProps item clonedItem[autoId] = item[autoId] output.push clonedItem else if type is '[object Object]' output = output or {} for key of obj if key.indexOf('$') is 0 output[key] = obj[key] else if Object.prototype.toString.call(obj[key]) is '[object Array]' output[key] = cloneSpecialProps obj[key] output restoreSpecialProps = (obj, clonedProps) -> type = Object.prototype.toString.call obj if type is '[object Array]' for item in obj for clonedItem in clonedProps if item[autoId] is clonedItem[autoId] restoreSpecialProps item, clonedItem break else if type is '[object Object]' for key of clonedProps if key.indexOf('<KEY>') is 0 and key isnt '<KEY>' obj[key] = clonedProps[key] restore obj[key] else restoreSpecialProps obj[key], clonedProps[key] return if $injector.has 'ndxCheck' ndxCheck = $injector.get 'ndxCheck' if $injector.has('Auth') okToLoad = false auth = $injector.get 'Auth' auth.onUser -> $timeout -> okToLoad = true for endpoint of endpoints endpoints[endpoint].needsRefresh = true callRefreshFns() callSocketRefresh = -> hasFuture = false for key, endpoint of endpoints if endpoint.needsRefresh and endpoint.refreshAt > new Date().valueOf() hasFuture = true if hasFuture return $timeout callSocketRefresh, 20 else callRefreshFns true socketRefresh = (data) -> if not lockAll if data clearCache data.table endpoints[data.table].needsRefresh = true endpoints[data.table].refreshAt = new Date().valueOf() + 400 type = Object.prototype.toString.call data.id if type is '[object Array]' for id of data.id endpoints[data.table].ids.push id else if type is '[object String]' endpoints[data.table].ids.push data.id else clearCache() for key of endpoints endpoints[key].needsRefresh = true callSocketRefresh() if $injector.has 'socket' socket = $injector.get 'socket' socket.on 'connect', -> socket.emit 'rest', {} if not $injector.has 'Server' socket.on 'update', socketRefresh socket.on 'insert', socketRefresh socket.on 'delete', socketRefresh $timeout -> $http.get '/rest/endpoints' .then (response) -> if response.data and response.data.endpoints and response.data.endpoints.length for endpoint in response.data.endpoints endpoints[endpoint] = needsRefresh: true lastRefresh: 0 nextRefresh: 0 ids: [] if response.data.autoId autoId = response.data.autoId if response.data.server maintenanceMode = response.data.server is 'maintenance' if needsRefresh callRefreshFns() syncCallback 'endpoints', response.data , (err) -> false lockAll: -> lockAll = true unlockAll: -> lockAll = false on: (name, callback) -> callbacks[name].push callback off: (name, callback) -> callbacks[name].splice callbacks[name].indexOf(callback), 1 endpoints: endpoints autoId: autoId maintenanceMode: -> maintenanceMode socketRefresh: socketRefresh needsRefresh: (val) -> needsRefresh = val callRefreshFns: callRefreshFns startLoading: startLoading stopLoading: stopLoading okToLoad: -> okToLoad save: (endpoint, obj, cb) -> startLoading() $http.post (endpoint.route or "/api/#{endpoint}") + ("/#{obj[autoId] or ''}"), obj .then (response) => stopLoading() endpoints[endpoint].needsRefresh = true ndxCheck and ndxCheck.setPristine() callRefreshFns endpoint response and response.data and cb?(response.data) , (err) -> stopLoading() false 'delete': (endpoint, obj, cb) -> startLoading() $http.delete (endpoint.route or "/api/#{endpoint}") + ("/#{obj[autoId] or ''}") .then (response) => stopLoading() endpoints[endpoint].needsRefresh = true ndxCheck and ndxCheck.setPristine() callRefreshFns endpoint response and response.data and cb?(response.data) , (err) -> stopLoading() false search: (endpoint, args, obj, cb, isSocket) -> isSocket or startLoading() args = args or {} handleResponse = (response) -> isSocket or stopLoading() clonedProps = null if obj.items and obj.items.length clonedProps = cloneSpecialProps obj.items objtrans response.data, (args.transform or listTransform), obj if obj.items and obj.items.length and clonedProps restoreSpecialProps obj.items, clonedProps obj.isSocket = isSocket cb? obj if response = fetchFromCache endpoint, args $timeout -> handleResponse response else $http.post (endpoint.route or "/api/#{endpoint}/search#{cacheBuster()}"), if endpoint.route and args and args.where then args.where else args .then (response) -> addToCache endpoint, args, response return handleResponse response , (err) -> isSocket or stopLoading() obj.items = [] obj.total = 0 obj.page = 1 obj.error = err obj.isSocket = isSocket cb? obj list: (endpoint, obj, cb, isSocket) -> isSocket or startLoading() handleResponse = (response) -> isSocket or stopLoading() clonedProps = null if obj.items and obj.items.length clonedProps = cloneSpecialProps obj.items objtrans response.data, (args.transform or listTransform), obj if obj.items and obj.items.length and clonedProps restoreSpecialProps obj.items, clonedProps obj.isSocket = isSocket cb? obj if response = fetchFromCache(endpoint, {}) $timeout -> handleResponse response else $http.post (endpoint.route or "/api/#{endpoint}#{cacheBuster()}") .then (response) -> addToCache endpoint, {}, response return handleResponse response , (err) -> isSocket or stopLoading() obj.items = [] obj.total = 0 obj.page = 1 obj.error = err obj.isSocket = isSocket cb? obj single: (endpoint, id, obj, cb, isSocket) -> isSocket or startLoading() handleResponse = (response) -> isSocket or stopLoading() clonedProps = null if obj.item clonedProps = cloneSpecialProps obj.item obj.item = response.data if obj.item and clonedProps restoreSpecialProps obj.item, clonedProps obj.isSocket = isSocket cb? obj if Object.prototype.toString.call(id) is '[object Object]' id = escape JSON.stringify id if response = fetchFromCache(endpoint, id:id) $timeout -> handleResponse response else $http.get (endpoint.route or "/api/#{endpoint}") + "/#{id}#{if obj.all then '/all' else ''}#{cacheBuster()}" .then (response) -> addToCache endpoint, id:id, response return handleResponse response , (err) -> isSocket or stopLoading() obj.item = {} obj.isSocket = isSocket cb? obj register: (fn) -> refreshFns.push fn dereg: (fn) -> refreshFns.splice refreshFns.indexOf(fn), 1 destroy: destroy loading: -> loading clearCache: clearCache checkCache: -> cache .run ($rootScope, $http, $timeout, rest) -> #borrowed from underscore.js throttle = (func, wait, options) -> context = undefined args = undefined result = undefined timeout = null previous = 0 if !options options = {} later = -> previous = if options.leading == false then 0 else Date.now() timeout = null result = func.apply(context, args) if !timeout context = args = null return -> now = Date.now() if !previous and options.leading == false previous = now remaining = wait - (now - previous) context = this args = arguments if remaining <= 0 or remaining > wait if timeout $timeout.cancel timeout timeout = null previous = now result = func.apply(context, args) if !timeout context = args = null else if !timeout and options.trailing != false timeout = $timeout(later, remaining) result root = Object.getPrototypeOf $rootScope root.restLoading = rest.loading root.list = (endpoint, args, cb, saveCb, locked) -> ignoreNextWatch = false if args cb = args.onData or cb saveCb = args.onSave or saveCb obj = items: null args: args refreshFn: null endpoint: endpoint locked: locked save: (item, checkFn) -> if checkFn checkFn 'save', endpoint, item, -> rest.save endpoint, item, saveCb else rest.save endpoint, item, saveCb delete: (item, checkFn) -> if checkFn checkFn 'delete', endpoint, item, -> rest.delete endpoint, item else rest.delete endpoint, item destroy: -> dereg?() rest.dereg obj.refreshFn throttledSearch = throttle rest.search, 1000 RefreshFn = (endpoint, args) -> (table, blank, isSocket) -> if args?.preRefresh args.preRefresh args ignoreNextWatch = true if not obj.locked if obj.items rest.destroy obj.items if endpoint.route if endpoint.endpoints and table for ep in endpoint.endpoints if table is ep throttledSearch endpoint, args, obj, cb, (isSocket or obj.args?.isSocket) break else if table is endpoint or not table throttledSearch endpoint, args, obj, cb, (isSocket or obj.args?.isSocket) obj.refreshFn = RefreshFn endpoint, args rest.register obj.refreshFn if endpoint.route and not endpoint.endpoints rest.search endpoint, args, obj, cb dereg = @.$watch -> JSON.stringify args , (n, o) -> if not ignoreNextWatch if rest.okToLoad() ### if endpoint.route if endpoint.endpoints and endpoint.endpoints.length for ep in endpoint.endpoints rest.endpoints[ep].needsRefresh = true else rest.endpoints[endpoint].needsRefresh = true ### obj.refreshFn obj.endpoint else rest.needsRefresh true else ignoreNextWatch = false , true @.$on '$destroy', -> obj.destroy() if not args and rest.endpoints.endpoints obj.refreshFn obj.endpoint if rest.okToLoad() rest.callRefreshFns() obj root.single = (endpoint, id, cb, saveCb, locked, all) -> obj = all: all item: null refreshFn: null endpoint: endpoint locked: locked save: (checkFn) -> if checkFn checkFn 'save', endpoint, @.item, => rest.save endpoint, @.item, saveCb else rest.save endpoint, @.item, saveCb delete: (checkFn) -> if checkFn checkFn 'delete', endpoint, @.item, => rest.delete endpoint, @.item else rest.delete endpoint, @.item destroy: -> rest.dereg obj.refreshFn throttledSingle = throttle rest.single, 1000 RefreshFn = (endpoint, id) -> (table, ids, isSocket) -> if ids and obj.item and ids.indexOf(obj.item[rest.autoId]) is -1 return if not obj.locked if endpoint.route if endpoint.endpoints if endpoint.endpoints.length and table for ep in endpoint.endpoints if table is ep throttledSingle endpoint, id, obj, cb, isSocket break else if table is endpoint or not table throttledSingle endpoint, id, obj, cb, isSocket obj.refreshFn = RefreshFn endpoint, id rest.register obj.refreshFn if rest.okToLoad() and rest.endpoints.endpoints ### if endpoint.route if endpoint.endpoints for ep in endpoint.endpoints rest.endpoints[ep].needsRefresh = true else rest.endpoints[endpoint].needsRefresh = false ### obj.refreshFn obj.endpoint else rest.needsRefresh true #if endpoint.route and not endpoint.endpoints rest.single endpoint, id, obj, cb @.$on '$destroy', obj.destroy obj
true
'use strict' module = null try module = angular.module 'ndx' catch e module =angular.module 'ndx', [] module.provider 'rest', -> waitForAuth = false bustCache = false lockAll = false disableCache = false cacheBuster = -> if bustCache then "?#{Math.floor(Math.random() * 9999999999999)}" else '' callbacks = endpoints: [] syncCallback = (name, obj, cb) -> if callbacks[name] and callbacks[name].length for callback in callbacks[name] callback obj cb?() hash = (str) -> h = 5381 i = str.length while i h = (h * 33) ^ str.charCodeAt --i h bustCache: (val) -> bustCache = val waitForAuth: (val) -> waitForAuth = val disableCache: (val) -> disableCache = val $get: ($http, $injector, $timeout) -> okToLoad = true endpoints = {} autoId = '_id' refreshFns = [] waiting = false ndxCheck = null needsRefresh = false maintenanceMode = false loading = 0 startLoading = -> loading++ stopLoading = -> loading-- if loading < 0 loading = 0 listTransform = items: true total: true page: true pageSize: true error: true cache = {} addToCache = (endpoint, args, obj) -> if not disableCache h = hash JSON.stringify args if not cache[endpoint] cache[endpoint] = {} cache[endpoint][h] = JSON.stringify data: obj.data fetchFromCache = (endpoint, args) -> if not disableCache h = hash JSON.stringify args if cache[endpoint] if cache[endpoint][h] str = cache[endpoint][h] newvar = JSON.parse str return newvar return null clearCache = (endpoint) -> if endpoint delete cache[endpoint] else cache = {} callRefreshFns = (isSocket) -> if okToLoad and endpoints for key of endpoints if endpoints[key].needsRefresh for fn in refreshFns fn key, endpoints[key].ids, isSocket endpoints[key].ids = [] endpoints[key].needsRefresh = false destroy = (obj) -> type = Object.prototype.toString.call obj if type is '[object Object]' if obj.destroy obj.destroy() for key in obj destroy obj[key] else if type is '[object Array]' for item in obj destroy item return restore = (obj) -> type = Object.prototype.toString.call obj if type is '[object Object]' if obj.refreshFn refreshFns.push obj.refreshFn for key in obj restore obj[key] else if type is '[object Array]' for item in obj restore item return cloneSpecialProps = (obj) -> output = null type = Object.prototype.toString.call obj if type is '[object Array]' output = output or [] for item in obj if item[autoId] clonedItem = cloneSpecialProps item clonedItem[autoId] = item[autoId] output.push clonedItem else if type is '[object Object]' output = output or {} for key of obj if key.indexOf('$') is 0 output[key] = obj[key] else if Object.prototype.toString.call(obj[key]) is '[object Array]' output[key] = cloneSpecialProps obj[key] output restoreSpecialProps = (obj, clonedProps) -> type = Object.prototype.toString.call obj if type is '[object Array]' for item in obj for clonedItem in clonedProps if item[autoId] is clonedItem[autoId] restoreSpecialProps item, clonedItem break else if type is '[object Object]' for key of clonedProps if key.indexOf('PI:KEY:<KEY>END_PI') is 0 and key isnt 'PI:KEY:<KEY>END_PI' obj[key] = clonedProps[key] restore obj[key] else restoreSpecialProps obj[key], clonedProps[key] return if $injector.has 'ndxCheck' ndxCheck = $injector.get 'ndxCheck' if $injector.has('Auth') okToLoad = false auth = $injector.get 'Auth' auth.onUser -> $timeout -> okToLoad = true for endpoint of endpoints endpoints[endpoint].needsRefresh = true callRefreshFns() callSocketRefresh = -> hasFuture = false for key, endpoint of endpoints if endpoint.needsRefresh and endpoint.refreshAt > new Date().valueOf() hasFuture = true if hasFuture return $timeout callSocketRefresh, 20 else callRefreshFns true socketRefresh = (data) -> if not lockAll if data clearCache data.table endpoints[data.table].needsRefresh = true endpoints[data.table].refreshAt = new Date().valueOf() + 400 type = Object.prototype.toString.call data.id if type is '[object Array]' for id of data.id endpoints[data.table].ids.push id else if type is '[object String]' endpoints[data.table].ids.push data.id else clearCache() for key of endpoints endpoints[key].needsRefresh = true callSocketRefresh() if $injector.has 'socket' socket = $injector.get 'socket' socket.on 'connect', -> socket.emit 'rest', {} if not $injector.has 'Server' socket.on 'update', socketRefresh socket.on 'insert', socketRefresh socket.on 'delete', socketRefresh $timeout -> $http.get '/rest/endpoints' .then (response) -> if response.data and response.data.endpoints and response.data.endpoints.length for endpoint in response.data.endpoints endpoints[endpoint] = needsRefresh: true lastRefresh: 0 nextRefresh: 0 ids: [] if response.data.autoId autoId = response.data.autoId if response.data.server maintenanceMode = response.data.server is 'maintenance' if needsRefresh callRefreshFns() syncCallback 'endpoints', response.data , (err) -> false lockAll: -> lockAll = true unlockAll: -> lockAll = false on: (name, callback) -> callbacks[name].push callback off: (name, callback) -> callbacks[name].splice callbacks[name].indexOf(callback), 1 endpoints: endpoints autoId: autoId maintenanceMode: -> maintenanceMode socketRefresh: socketRefresh needsRefresh: (val) -> needsRefresh = val callRefreshFns: callRefreshFns startLoading: startLoading stopLoading: stopLoading okToLoad: -> okToLoad save: (endpoint, obj, cb) -> startLoading() $http.post (endpoint.route or "/api/#{endpoint}") + ("/#{obj[autoId] or ''}"), obj .then (response) => stopLoading() endpoints[endpoint].needsRefresh = true ndxCheck and ndxCheck.setPristine() callRefreshFns endpoint response and response.data and cb?(response.data) , (err) -> stopLoading() false 'delete': (endpoint, obj, cb) -> startLoading() $http.delete (endpoint.route or "/api/#{endpoint}") + ("/#{obj[autoId] or ''}") .then (response) => stopLoading() endpoints[endpoint].needsRefresh = true ndxCheck and ndxCheck.setPristine() callRefreshFns endpoint response and response.data and cb?(response.data) , (err) -> stopLoading() false search: (endpoint, args, obj, cb, isSocket) -> isSocket or startLoading() args = args or {} handleResponse = (response) -> isSocket or stopLoading() clonedProps = null if obj.items and obj.items.length clonedProps = cloneSpecialProps obj.items objtrans response.data, (args.transform or listTransform), obj if obj.items and obj.items.length and clonedProps restoreSpecialProps obj.items, clonedProps obj.isSocket = isSocket cb? obj if response = fetchFromCache endpoint, args $timeout -> handleResponse response else $http.post (endpoint.route or "/api/#{endpoint}/search#{cacheBuster()}"), if endpoint.route and args and args.where then args.where else args .then (response) -> addToCache endpoint, args, response return handleResponse response , (err) -> isSocket or stopLoading() obj.items = [] obj.total = 0 obj.page = 1 obj.error = err obj.isSocket = isSocket cb? obj list: (endpoint, obj, cb, isSocket) -> isSocket or startLoading() handleResponse = (response) -> isSocket or stopLoading() clonedProps = null if obj.items and obj.items.length clonedProps = cloneSpecialProps obj.items objtrans response.data, (args.transform or listTransform), obj if obj.items and obj.items.length and clonedProps restoreSpecialProps obj.items, clonedProps obj.isSocket = isSocket cb? obj if response = fetchFromCache(endpoint, {}) $timeout -> handleResponse response else $http.post (endpoint.route or "/api/#{endpoint}#{cacheBuster()}") .then (response) -> addToCache endpoint, {}, response return handleResponse response , (err) -> isSocket or stopLoading() obj.items = [] obj.total = 0 obj.page = 1 obj.error = err obj.isSocket = isSocket cb? obj single: (endpoint, id, obj, cb, isSocket) -> isSocket or startLoading() handleResponse = (response) -> isSocket or stopLoading() clonedProps = null if obj.item clonedProps = cloneSpecialProps obj.item obj.item = response.data if obj.item and clonedProps restoreSpecialProps obj.item, clonedProps obj.isSocket = isSocket cb? obj if Object.prototype.toString.call(id) is '[object Object]' id = escape JSON.stringify id if response = fetchFromCache(endpoint, id:id) $timeout -> handleResponse response else $http.get (endpoint.route or "/api/#{endpoint}") + "/#{id}#{if obj.all then '/all' else ''}#{cacheBuster()}" .then (response) -> addToCache endpoint, id:id, response return handleResponse response , (err) -> isSocket or stopLoading() obj.item = {} obj.isSocket = isSocket cb? obj register: (fn) -> refreshFns.push fn dereg: (fn) -> refreshFns.splice refreshFns.indexOf(fn), 1 destroy: destroy loading: -> loading clearCache: clearCache checkCache: -> cache .run ($rootScope, $http, $timeout, rest) -> #borrowed from underscore.js throttle = (func, wait, options) -> context = undefined args = undefined result = undefined timeout = null previous = 0 if !options options = {} later = -> previous = if options.leading == false then 0 else Date.now() timeout = null result = func.apply(context, args) if !timeout context = args = null return -> now = Date.now() if !previous and options.leading == false previous = now remaining = wait - (now - previous) context = this args = arguments if remaining <= 0 or remaining > wait if timeout $timeout.cancel timeout timeout = null previous = now result = func.apply(context, args) if !timeout context = args = null else if !timeout and options.trailing != false timeout = $timeout(later, remaining) result root = Object.getPrototypeOf $rootScope root.restLoading = rest.loading root.list = (endpoint, args, cb, saveCb, locked) -> ignoreNextWatch = false if args cb = args.onData or cb saveCb = args.onSave or saveCb obj = items: null args: args refreshFn: null endpoint: endpoint locked: locked save: (item, checkFn) -> if checkFn checkFn 'save', endpoint, item, -> rest.save endpoint, item, saveCb else rest.save endpoint, item, saveCb delete: (item, checkFn) -> if checkFn checkFn 'delete', endpoint, item, -> rest.delete endpoint, item else rest.delete endpoint, item destroy: -> dereg?() rest.dereg obj.refreshFn throttledSearch = throttle rest.search, 1000 RefreshFn = (endpoint, args) -> (table, blank, isSocket) -> if args?.preRefresh args.preRefresh args ignoreNextWatch = true if not obj.locked if obj.items rest.destroy obj.items if endpoint.route if endpoint.endpoints and table for ep in endpoint.endpoints if table is ep throttledSearch endpoint, args, obj, cb, (isSocket or obj.args?.isSocket) break else if table is endpoint or not table throttledSearch endpoint, args, obj, cb, (isSocket or obj.args?.isSocket) obj.refreshFn = RefreshFn endpoint, args rest.register obj.refreshFn if endpoint.route and not endpoint.endpoints rest.search endpoint, args, obj, cb dereg = @.$watch -> JSON.stringify args , (n, o) -> if not ignoreNextWatch if rest.okToLoad() ### if endpoint.route if endpoint.endpoints and endpoint.endpoints.length for ep in endpoint.endpoints rest.endpoints[ep].needsRefresh = true else rest.endpoints[endpoint].needsRefresh = true ### obj.refreshFn obj.endpoint else rest.needsRefresh true else ignoreNextWatch = false , true @.$on '$destroy', -> obj.destroy() if not args and rest.endpoints.endpoints obj.refreshFn obj.endpoint if rest.okToLoad() rest.callRefreshFns() obj root.single = (endpoint, id, cb, saveCb, locked, all) -> obj = all: all item: null refreshFn: null endpoint: endpoint locked: locked save: (checkFn) -> if checkFn checkFn 'save', endpoint, @.item, => rest.save endpoint, @.item, saveCb else rest.save endpoint, @.item, saveCb delete: (checkFn) -> if checkFn checkFn 'delete', endpoint, @.item, => rest.delete endpoint, @.item else rest.delete endpoint, @.item destroy: -> rest.dereg obj.refreshFn throttledSingle = throttle rest.single, 1000 RefreshFn = (endpoint, id) -> (table, ids, isSocket) -> if ids and obj.item and ids.indexOf(obj.item[rest.autoId]) is -1 return if not obj.locked if endpoint.route if endpoint.endpoints if endpoint.endpoints.length and table for ep in endpoint.endpoints if table is ep throttledSingle endpoint, id, obj, cb, isSocket break else if table is endpoint or not table throttledSingle endpoint, id, obj, cb, isSocket obj.refreshFn = RefreshFn endpoint, id rest.register obj.refreshFn if rest.okToLoad() and rest.endpoints.endpoints ### if endpoint.route if endpoint.endpoints for ep in endpoint.endpoints rest.endpoints[ep].needsRefresh = true else rest.endpoints[endpoint].needsRefresh = false ### obj.refreshFn obj.endpoint else rest.needsRefresh true #if endpoint.route and not endpoint.endpoints rest.single endpoint, id, obj, cb @.$on '$destroy', obj.destroy obj
[ { "context": "48e72ecb51'\n record =\n name: 'Forwarder'\n uuid: @forwarderUuid\n ", "end": 987, "score": 0.5223410129547119, "start": 984, "tag": "NAME", "value": "For" }, { "context": "9c65c98df2'\n record =\n name: 'Forwarder'\n uuid: @forwarderUuid\n mes", "end": 2031, "score": 0.9869455099105835, "start": 2022, "tag": "NAME", "value": "Forwarder" }, { "context": " devices: ['*']\n forwardedFor: [@forwarderUuid]\n\n expect(@MessageWebhook).to.have.been.", "end": 2535, "score": 0.9123618006706238, "start": 2522, "tag": "USERNAME", "value": "forwarderUuid" }, { "context": "847d190ff8'\n record =\n name: 'Forwarder'\n uuid: @forwarderUuid\n con", "end": 2938, "score": 0.9762811064720154, "start": 2929, "tag": "NAME", "value": "Forwarder" }, { "context": " devices: ['*']\n forwardedFor: [@forwarderUuid]\n\n expect(@publisher.publish).to.have.be", "end": 3618, "score": 0.8153085708618164, "start": 3605, "tag": "USERNAME", "value": "forwarderUuid" } ]
test/publish-forwarder-spec.coffee
CESARBR/knot-cloud-source
4
PublishForwarder = require '../src/publish-forwarder' TestDatabase = require './test-database' describe 'PublishForwarder', -> beforeEach (done) -> TestDatabase.open (error, database) => {@devices,@subscriptions} = database @devices.find {}, (error, devices) => done error beforeEach -> @publisher = publish: sinon.stub().yields null @messageWebhook = send: sinon.stub().yields null @MessageWebhook = sinon.spy => @messageWebhook @sut = new PublishForwarder {@publisher}, {@devices, @MessageWebhook, @subscriptions} describe '-> forward', -> beforeEach (done) -> @receiverUuid = 'dc8331b5-33b6-47b0-85db-2106930d0601' record = name: 'Receiver' uuid: @receiverUuid @devices.insert record, done context 'sent', -> context 'with a subscription', -> beforeEach (done) -> @forwarderUuid = '9749b660-b6dc-4189-b248-1248e72ecb51' record = name: 'Forwarder' uuid: @forwarderUuid configureWhitelist: [ @receiverUuid ] @devices.insert record, done beforeEach (done) -> record = emitterUuid: @forwarderUuid subscriberUuid: @receiverUuid type: 'sent' @subscriptions.insert record, done beforeEach (done) -> uuid = @forwarderUuid type = 'sent' message = devices: ['*'] @sut.forward {uuid, type, message}, (error) => done error it 'should forward a message', -> newMessage = devices: ['*'] forwardedFor: [@forwarderUuid] expect(@publisher.publish).to.have.been.calledWith 'sent', @receiverUuid, newMessage context 'type: webhook', -> beforeEach (done) -> @hookOptions = type: 'webhook' url: 'http://example.com' @forwarderUuid = '27aa53ae-a5c0-4b1b-8051-389c65c98df2' record = name: 'Forwarder' uuid: @forwarderUuid meshblu: forwarders: sent: [ @hookOptions ] @devices.insert record, done beforeEach (done) -> uuid = @forwarderUuid type = 'sent' message = devices: ['*'] @sut.forward {uuid, type, message}, (error) => done error it 'should send a webhook', -> newMessage = devices: ['*'] forwardedFor: [@forwarderUuid] expect(@MessageWebhook).to.have.been.calledWith uuid: @forwarderUuid, type: 'sent', options: @hookOptions expect(@messageWebhook.send).to.have.been.calledWith newMessage context 'received', -> context 'with a subscription', -> beforeEach (done) -> @forwarderUuid = 'eb76dac1-83d6-415b-a4e5-d4847d190ff8' record = name: 'Forwarder' uuid: @forwarderUuid configureWhitelist: [ @receiverUuid ] @devices.insert record, done beforeEach (done) -> record = emitterUuid: @forwarderUuid subscriberUuid: @receiverUuid type: 'received' @subscriptions.insert record, done beforeEach (done) -> uuid = @forwarderUuid type = 'received' message = devices: ['*'] @sut.forward {uuid, type, message}, (error) => done error it 'should forward a message', -> newMessage = devices: ['*'] forwardedFor: [@forwarderUuid] expect(@publisher.publish).to.have.been.calledWith 'received', @receiverUuid, newMessage
163173
PublishForwarder = require '../src/publish-forwarder' TestDatabase = require './test-database' describe 'PublishForwarder', -> beforeEach (done) -> TestDatabase.open (error, database) => {@devices,@subscriptions} = database @devices.find {}, (error, devices) => done error beforeEach -> @publisher = publish: sinon.stub().yields null @messageWebhook = send: sinon.stub().yields null @MessageWebhook = sinon.spy => @messageWebhook @sut = new PublishForwarder {@publisher}, {@devices, @MessageWebhook, @subscriptions} describe '-> forward', -> beforeEach (done) -> @receiverUuid = 'dc8331b5-33b6-47b0-85db-2106930d0601' record = name: 'Receiver' uuid: @receiverUuid @devices.insert record, done context 'sent', -> context 'with a subscription', -> beforeEach (done) -> @forwarderUuid = '9749b660-b6dc-4189-b248-1248e72ecb51' record = name: '<NAME>warder' uuid: @forwarderUuid configureWhitelist: [ @receiverUuid ] @devices.insert record, done beforeEach (done) -> record = emitterUuid: @forwarderUuid subscriberUuid: @receiverUuid type: 'sent' @subscriptions.insert record, done beforeEach (done) -> uuid = @forwarderUuid type = 'sent' message = devices: ['*'] @sut.forward {uuid, type, message}, (error) => done error it 'should forward a message', -> newMessage = devices: ['*'] forwardedFor: [@forwarderUuid] expect(@publisher.publish).to.have.been.calledWith 'sent', @receiverUuid, newMessage context 'type: webhook', -> beforeEach (done) -> @hookOptions = type: 'webhook' url: 'http://example.com' @forwarderUuid = '27aa53ae-a5c0-4b1b-8051-389c65c98df2' record = name: '<NAME>' uuid: @forwarderUuid meshblu: forwarders: sent: [ @hookOptions ] @devices.insert record, done beforeEach (done) -> uuid = @forwarderUuid type = 'sent' message = devices: ['*'] @sut.forward {uuid, type, message}, (error) => done error it 'should send a webhook', -> newMessage = devices: ['*'] forwardedFor: [@forwarderUuid] expect(@MessageWebhook).to.have.been.calledWith uuid: @forwarderUuid, type: 'sent', options: @hookOptions expect(@messageWebhook.send).to.have.been.calledWith newMessage context 'received', -> context 'with a subscription', -> beforeEach (done) -> @forwarderUuid = 'eb76dac1-83d6-415b-a4e5-d4847d190ff8' record = name: '<NAME>' uuid: @forwarderUuid configureWhitelist: [ @receiverUuid ] @devices.insert record, done beforeEach (done) -> record = emitterUuid: @forwarderUuid subscriberUuid: @receiverUuid type: 'received' @subscriptions.insert record, done beforeEach (done) -> uuid = @forwarderUuid type = 'received' message = devices: ['*'] @sut.forward {uuid, type, message}, (error) => done error it 'should forward a message', -> newMessage = devices: ['*'] forwardedFor: [@forwarderUuid] expect(@publisher.publish).to.have.been.calledWith 'received', @receiverUuid, newMessage
true
PublishForwarder = require '../src/publish-forwarder' TestDatabase = require './test-database' describe 'PublishForwarder', -> beforeEach (done) -> TestDatabase.open (error, database) => {@devices,@subscriptions} = database @devices.find {}, (error, devices) => done error beforeEach -> @publisher = publish: sinon.stub().yields null @messageWebhook = send: sinon.stub().yields null @MessageWebhook = sinon.spy => @messageWebhook @sut = new PublishForwarder {@publisher}, {@devices, @MessageWebhook, @subscriptions} describe '-> forward', -> beforeEach (done) -> @receiverUuid = 'dc8331b5-33b6-47b0-85db-2106930d0601' record = name: 'Receiver' uuid: @receiverUuid @devices.insert record, done context 'sent', -> context 'with a subscription', -> beforeEach (done) -> @forwarderUuid = '9749b660-b6dc-4189-b248-1248e72ecb51' record = name: 'PI:NAME:<NAME>END_PIwarder' uuid: @forwarderUuid configureWhitelist: [ @receiverUuid ] @devices.insert record, done beforeEach (done) -> record = emitterUuid: @forwarderUuid subscriberUuid: @receiverUuid type: 'sent' @subscriptions.insert record, done beforeEach (done) -> uuid = @forwarderUuid type = 'sent' message = devices: ['*'] @sut.forward {uuid, type, message}, (error) => done error it 'should forward a message', -> newMessage = devices: ['*'] forwardedFor: [@forwarderUuid] expect(@publisher.publish).to.have.been.calledWith 'sent', @receiverUuid, newMessage context 'type: webhook', -> beforeEach (done) -> @hookOptions = type: 'webhook' url: 'http://example.com' @forwarderUuid = '27aa53ae-a5c0-4b1b-8051-389c65c98df2' record = name: 'PI:NAME:<NAME>END_PI' uuid: @forwarderUuid meshblu: forwarders: sent: [ @hookOptions ] @devices.insert record, done beforeEach (done) -> uuid = @forwarderUuid type = 'sent' message = devices: ['*'] @sut.forward {uuid, type, message}, (error) => done error it 'should send a webhook', -> newMessage = devices: ['*'] forwardedFor: [@forwarderUuid] expect(@MessageWebhook).to.have.been.calledWith uuid: @forwarderUuid, type: 'sent', options: @hookOptions expect(@messageWebhook.send).to.have.been.calledWith newMessage context 'received', -> context 'with a subscription', -> beforeEach (done) -> @forwarderUuid = 'eb76dac1-83d6-415b-a4e5-d4847d190ff8' record = name: 'PI:NAME:<NAME>END_PI' uuid: @forwarderUuid configureWhitelist: [ @receiverUuid ] @devices.insert record, done beforeEach (done) -> record = emitterUuid: @forwarderUuid subscriberUuid: @receiverUuid type: 'received' @subscriptions.insert record, done beforeEach (done) -> uuid = @forwarderUuid type = 'received' message = devices: ['*'] @sut.forward {uuid, type, message}, (error) => done error it 'should forward a message', -> newMessage = devices: ['*'] forwardedFor: [@forwarderUuid] expect(@publisher.publish).to.have.been.calledWith 'received', @receiverUuid, newMessage
[ { "context": "fail - Display an image of failure\n#\n# Author:\n# Jenn Basalone - jbasalone@gmail.com\n\nfail = [\n \"http://img4.w", "end": 185, "score": 0.9998584985733032, "start": 172, "tag": "NAME", "value": "Jenn Basalone" }, { "context": "n image of failure\n#\n# Author:\n# Jenn Basalone - jbasalone@gmail.com\n\nfail = [\n \"http://img4.wikia.nocookie.net/__cb", "end": 207, "score": 0.9999308586120605, "start": 188, "tag": "EMAIL", "value": "jbasalone@gmail.com" } ]
scr/fail.coffee
jbasalone/hubot-fail
0
# Description: # Display a fail image # # Dependencies: # None # # Configuration: # None # # Commands: # robot fail - Display an image of failure # # Author: # Jenn Basalone - jbasalone@gmail.com fail = [ "http://img4.wikia.nocookie.net/__cb20130914074755/powerlisting/images/1/12/FAIL-Word-art-300x187.png", "http://www.dumpaday.com/wp-content/uploads/2012/11/funny-fails-12.jpg", "http://www.vitamin-ha.com/wp-content/uploads/2014/03/Funny-Fail-09-024.jpg", "http://www.vitamin-ha.com/wp-content/uploads/2013/07/Funny-Fails-01.jpg", "http://www.dumpaday.com/wp-content/uploads/2012/11/funny-fails-12.jpg", "http://fc07.deviantart.net/fs34/f/2008/299/1/a/There__s_no_word_but_FAIL_by_daveshan.jpg", "http://lh3.ggpht.com/_LEDL5eT3epM/Su8AR_JwDBI/AAAAAAAAAPU/BbLaL5GxiQM/img_3.jpg", "http://sr.photos2.fotosearch.com/bthumb/CSP/CSP992/k14392274.jpg", "http://media.giphy.com/media/Pvd8Gq2sFQ4kE/giphy.gif", "http://www.gifbin.com/bin/052011/1304356562_discus-throwing-fail.gif", "http://www.gifbin.com/bin/102009/1255084444_ramp-fail.gif", "http://fumaga.com/i/trampoline-jumping-fail-animated.gif", "http://www.gifbin.com/bin/062011/1309197288_mortar_fail.gif", "http://cdn1.smosh.com/sites/default/files/legacy.images/smosh-pit/092010/dancefail-5.gif", "http://theunshaven.rooms.cwal.net/Animated%20Gifs/Epic%20Fail.gif", "http://www.colectiva.tv/wordpress/wp-content/uploads/2010/01/Girl_owned_treadmillFAIL.gif", "http://38.media.tumblr.com/tumblr_lh2hb2oGfM1qe8a0fo1_500.gif", "http://www.theditherer.com/pictures/13.01.2014/1389624931.jpg", "http://wackymania.com/image/2010/12/funny-fail-photos/funny-fail-photos-07.jpg", "http://www.funpedia.net/imgs/aug11/funny-fail-photos-01.jpg", "http://mburufleitas.files.wordpress.com/2010/09/fail_08.jpg", "http://cdn2.holytaco.com/wp-content/uploads/images/2009/12/fail-cat.jpg", "http://www.revenue-engineer.com/wp-content/uploads/2011/08/fail.png", "http://www.reactiongifs.us/wp-content/uploads/2014/09/differently_in_my_mind_will_smith.gif", "http://www.reactiongifs.us/wp-content/uploads/2014/04/zoidberg_slinky_fail_futurama.gif", "http://www.reactiongifs.us/wp-content/uploads/2013/09/fail_three_amigos.gif", "http://www.reactiongifs.us/wp-content/uploads/2013/08/i_fucked_up_will_ferrell.gif", "http://www.reactiongifs.us/wp-content/uploads/2013/05/at-at_faceplant.gif", "http://www.reactiongifs.us/wp-content/uploads/2013/06/now_what_finding_nemo.gif", "http://media.tumblr.com/1029626e6c8f487a0d18521eeb043d2d/tumblr_inline_nj4i6cxH1m1raprkq.gif", "http://www.readthesmiths.com/articles/Images/Humor/Fail/epic-fail.jpg", "https://i.imgflip.com/jbjt9.jpg", "http://media.giphy.com/media/12Pq6yTCPMjajS/giphy.gif", "http://www.gurl.com/wp-content/uploads/2012/12/ron-burgundy.gif", "https://s3.amazonaws.com/uploads.hipchat.com/56752/568848/DwXH520ZVxLFizA/11172441_10205873757298302_607477308_n.gif", "https://s3.amazonaws.com/uploads.hipchat.com/56752/1026538/JZGXeOndZbC8hrt/upload.png", "http://images.cryhavok.org/d/1291-1/Computer+Rage.gif", "http://mrwgifs.com/wp-content/uploads/2013/03/Kronk-And-Ymzas-Bad-Luck-In-Emperors-New-Groove.gif", "http://3.bp.blogspot.com/_Nc998m5Qo6c/SoYi7Nxa3OI/AAAAAAAAEUI/L_psdvrPNf4/s400/Welcome_To_Fail.jpg" ] module.exports = (robot) -> robot.hear /\b(fail)\b/i, (msg) -> msg.send msg.random fail
83831
# Description: # Display a fail image # # Dependencies: # None # # Configuration: # None # # Commands: # robot fail - Display an image of failure # # Author: # <NAME> - <EMAIL> fail = [ "http://img4.wikia.nocookie.net/__cb20130914074755/powerlisting/images/1/12/FAIL-Word-art-300x187.png", "http://www.dumpaday.com/wp-content/uploads/2012/11/funny-fails-12.jpg", "http://www.vitamin-ha.com/wp-content/uploads/2014/03/Funny-Fail-09-024.jpg", "http://www.vitamin-ha.com/wp-content/uploads/2013/07/Funny-Fails-01.jpg", "http://www.dumpaday.com/wp-content/uploads/2012/11/funny-fails-12.jpg", "http://fc07.deviantart.net/fs34/f/2008/299/1/a/There__s_no_word_but_FAIL_by_daveshan.jpg", "http://lh3.ggpht.com/_LEDL5eT3epM/Su8AR_JwDBI/AAAAAAAAAPU/BbLaL5GxiQM/img_3.jpg", "http://sr.photos2.fotosearch.com/bthumb/CSP/CSP992/k14392274.jpg", "http://media.giphy.com/media/Pvd8Gq2sFQ4kE/giphy.gif", "http://www.gifbin.com/bin/052011/1304356562_discus-throwing-fail.gif", "http://www.gifbin.com/bin/102009/1255084444_ramp-fail.gif", "http://fumaga.com/i/trampoline-jumping-fail-animated.gif", "http://www.gifbin.com/bin/062011/1309197288_mortar_fail.gif", "http://cdn1.smosh.com/sites/default/files/legacy.images/smosh-pit/092010/dancefail-5.gif", "http://theunshaven.rooms.cwal.net/Animated%20Gifs/Epic%20Fail.gif", "http://www.colectiva.tv/wordpress/wp-content/uploads/2010/01/Girl_owned_treadmillFAIL.gif", "http://38.media.tumblr.com/tumblr_lh2hb2oGfM1qe8a0fo1_500.gif", "http://www.theditherer.com/pictures/13.01.2014/1389624931.jpg", "http://wackymania.com/image/2010/12/funny-fail-photos/funny-fail-photos-07.jpg", "http://www.funpedia.net/imgs/aug11/funny-fail-photos-01.jpg", "http://mburufleitas.files.wordpress.com/2010/09/fail_08.jpg", "http://cdn2.holytaco.com/wp-content/uploads/images/2009/12/fail-cat.jpg", "http://www.revenue-engineer.com/wp-content/uploads/2011/08/fail.png", "http://www.reactiongifs.us/wp-content/uploads/2014/09/differently_in_my_mind_will_smith.gif", "http://www.reactiongifs.us/wp-content/uploads/2014/04/zoidberg_slinky_fail_futurama.gif", "http://www.reactiongifs.us/wp-content/uploads/2013/09/fail_three_amigos.gif", "http://www.reactiongifs.us/wp-content/uploads/2013/08/i_fucked_up_will_ferrell.gif", "http://www.reactiongifs.us/wp-content/uploads/2013/05/at-at_faceplant.gif", "http://www.reactiongifs.us/wp-content/uploads/2013/06/now_what_finding_nemo.gif", "http://media.tumblr.com/1029626e6c8f487a0d18521eeb043d2d/tumblr_inline_nj4i6cxH1m1raprkq.gif", "http://www.readthesmiths.com/articles/Images/Humor/Fail/epic-fail.jpg", "https://i.imgflip.com/jbjt9.jpg", "http://media.giphy.com/media/12Pq6yTCPMjajS/giphy.gif", "http://www.gurl.com/wp-content/uploads/2012/12/ron-burgundy.gif", "https://s3.amazonaws.com/uploads.hipchat.com/56752/568848/DwXH520ZVxLFizA/11172441_10205873757298302_607477308_n.gif", "https://s3.amazonaws.com/uploads.hipchat.com/56752/1026538/JZGXeOndZbC8hrt/upload.png", "http://images.cryhavok.org/d/1291-1/Computer+Rage.gif", "http://mrwgifs.com/wp-content/uploads/2013/03/Kronk-And-Ymzas-Bad-Luck-In-Emperors-New-Groove.gif", "http://3.bp.blogspot.com/_Nc998m5Qo6c/SoYi7Nxa3OI/AAAAAAAAEUI/L_psdvrPNf4/s400/Welcome_To_Fail.jpg" ] module.exports = (robot) -> robot.hear /\b(fail)\b/i, (msg) -> msg.send msg.random fail
true
# Description: # Display a fail image # # Dependencies: # None # # Configuration: # None # # Commands: # robot fail - Display an image of failure # # Author: # PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI fail = [ "http://img4.wikia.nocookie.net/__cb20130914074755/powerlisting/images/1/12/FAIL-Word-art-300x187.png", "http://www.dumpaday.com/wp-content/uploads/2012/11/funny-fails-12.jpg", "http://www.vitamin-ha.com/wp-content/uploads/2014/03/Funny-Fail-09-024.jpg", "http://www.vitamin-ha.com/wp-content/uploads/2013/07/Funny-Fails-01.jpg", "http://www.dumpaday.com/wp-content/uploads/2012/11/funny-fails-12.jpg", "http://fc07.deviantart.net/fs34/f/2008/299/1/a/There__s_no_word_but_FAIL_by_daveshan.jpg", "http://lh3.ggpht.com/_LEDL5eT3epM/Su8AR_JwDBI/AAAAAAAAAPU/BbLaL5GxiQM/img_3.jpg", "http://sr.photos2.fotosearch.com/bthumb/CSP/CSP992/k14392274.jpg", "http://media.giphy.com/media/Pvd8Gq2sFQ4kE/giphy.gif", "http://www.gifbin.com/bin/052011/1304356562_discus-throwing-fail.gif", "http://www.gifbin.com/bin/102009/1255084444_ramp-fail.gif", "http://fumaga.com/i/trampoline-jumping-fail-animated.gif", "http://www.gifbin.com/bin/062011/1309197288_mortar_fail.gif", "http://cdn1.smosh.com/sites/default/files/legacy.images/smosh-pit/092010/dancefail-5.gif", "http://theunshaven.rooms.cwal.net/Animated%20Gifs/Epic%20Fail.gif", "http://www.colectiva.tv/wordpress/wp-content/uploads/2010/01/Girl_owned_treadmillFAIL.gif", "http://38.media.tumblr.com/tumblr_lh2hb2oGfM1qe8a0fo1_500.gif", "http://www.theditherer.com/pictures/13.01.2014/1389624931.jpg", "http://wackymania.com/image/2010/12/funny-fail-photos/funny-fail-photos-07.jpg", "http://www.funpedia.net/imgs/aug11/funny-fail-photos-01.jpg", "http://mburufleitas.files.wordpress.com/2010/09/fail_08.jpg", "http://cdn2.holytaco.com/wp-content/uploads/images/2009/12/fail-cat.jpg", "http://www.revenue-engineer.com/wp-content/uploads/2011/08/fail.png", "http://www.reactiongifs.us/wp-content/uploads/2014/09/differently_in_my_mind_will_smith.gif", "http://www.reactiongifs.us/wp-content/uploads/2014/04/zoidberg_slinky_fail_futurama.gif", "http://www.reactiongifs.us/wp-content/uploads/2013/09/fail_three_amigos.gif", "http://www.reactiongifs.us/wp-content/uploads/2013/08/i_fucked_up_will_ferrell.gif", "http://www.reactiongifs.us/wp-content/uploads/2013/05/at-at_faceplant.gif", "http://www.reactiongifs.us/wp-content/uploads/2013/06/now_what_finding_nemo.gif", "http://media.tumblr.com/1029626e6c8f487a0d18521eeb043d2d/tumblr_inline_nj4i6cxH1m1raprkq.gif", "http://www.readthesmiths.com/articles/Images/Humor/Fail/epic-fail.jpg", "https://i.imgflip.com/jbjt9.jpg", "http://media.giphy.com/media/12Pq6yTCPMjajS/giphy.gif", "http://www.gurl.com/wp-content/uploads/2012/12/ron-burgundy.gif", "https://s3.amazonaws.com/uploads.hipchat.com/56752/568848/DwXH520ZVxLFizA/11172441_10205873757298302_607477308_n.gif", "https://s3.amazonaws.com/uploads.hipchat.com/56752/1026538/JZGXeOndZbC8hrt/upload.png", "http://images.cryhavok.org/d/1291-1/Computer+Rage.gif", "http://mrwgifs.com/wp-content/uploads/2013/03/Kronk-And-Ymzas-Bad-Luck-In-Emperors-New-Groove.gif", "http://3.bp.blogspot.com/_Nc998m5Qo6c/SoYi7Nxa3OI/AAAAAAAAEUI/L_psdvrPNf4/s400/Welcome_To_Fail.jpg" ] module.exports = (robot) -> robot.hear /\b(fail)\b/i, (msg) -> msg.send msg.random fail
[ { "context": "project generator tool\n#\n# Copyright (C) 2011-2012 Nikolay Nemshilov\n#\nfs = require('fs')\nlovelyrc = require('..", "end": 80, "score": 0.999897837638855, "start": 63, "tag": "NAME", "value": "Nikolay Nemshilov" }, { "context": "getFullYear(),\n username: lovelyrc.name || \"Vasily Pupkin\"\n\n\n print \"Creating directory: #{projectname}\"\n ", "end": 1180, "score": 0.9983136057853699, "start": 1167, "tag": "NAME", "value": "Vasily Pupkin" }, { "context": "oject's main unit\n #\n # Copyright (C) %{year} %{username}\n #\n \"\"\" else \"\"\"\n /**\n * Project's main uni", "end": 2239, "score": 0.8891063332557678, "start": 2231, "tag": "USERNAME", "value": "username" }, { "context": "ect's main unit\n *\n * Copyright (C) %{year} %{username}\n */\n \"\"\"\n\n print \" - src/#{filename}\"\n fs.w", "end": 2333, "score": 0.6581404209136963, "start": 2325, "tag": "USERNAME", "value": "username" }, { "context": "'s main unit test\n #\n # Copyright (C) %{year} %{username}\n #\n {Test, assert} = require('lovely')\n\n desc", "end": 2720, "score": 0.9318463802337646, "start": 2712, "tag": "USERNAME", "value": "username" }, { "context": " main unit test\n *\n * Copyright (C) %{year} %{username}\n */\n var Lovely = require('lovely');\n var Te", "end": 3175, "score": 0.9164706468582153, "start": 3167, "tag": "USERNAME", "value": "username" } ]
cli/commands/new.coffee
lovely-io/lovely.io-stl
2
# # The new project generator tool # # Copyright (C) 2011-2012 Nikolay Nemshilov # fs = require('fs') lovelyrc = require('../lovelyrc') placeholders = {} # # Starts the new project generation # # @param {String} projectname # @param {Array} the rest of the arguments # @return void # generate = (projectname, args) -> directory = "#{process.cwd()}/#{projectname}" project_tpl = "#{__dirname}/../project_tpl" use_coffee = args.indexOf('--js') is -1 && lovelyrc.lang.indexOf('js') is -1 use_sass = args.indexOf('--css') is -1 && lovelyrc.lang.indexOf('css') is -1 use_scss = args.indexOf('--scss') isnt -1 || lovelyrc.lang.indexOf('scss') isnt -1 use_stylus = args.indexOf('--stylus') isnt -1 || lovelyrc.lang.indexOf('stylus') isnt -1 use_sass = !use_scss && !use_stylus && use_sass use_css = !use_sass && !use_scss && !use_stylus placeholders = projectname: projectname, projectunit: projectname.replace(/(^|-)([a-z])/g, (m,m1,m2)-> m2.toUpperCase()) projectfile: projectname.replace(/\-/g, '_') year: new Date().getFullYear(), username: lovelyrc.name || "Vasily Pupkin" print "Creating directory: #{projectname}" fs.mkdirSync(directory, 0o0755) # just checking if the file should be copied over suitable = (filename) -> switch filename.split('.').pop() when 'js' then return !use_coffee when 'coffee' then return use_coffee when 'sass' then return use_sass when 'scss' then return use_scss when 'styl' then return use_stylus when 'css' then return use_css else return true for filename in fs.readdirSync(project_tpl) if suitable(filename) source = fs.readFileSync("#{project_tpl}/#{filename}").toString() filename = '.gitignore' if filename is 'gitignore' print " - #{filename}" fs.writeFileSync("#{directory}/#{filename}", patch_source(source)) print " - src/" fs.mkdirSync("#{directory}/src", 0o0755) filename = "#{placeholders.projectfile}.#{ if use_coffee then 'coffee' else 'js' }" source = if use_coffee then """ # # Project's main unit # # Copyright (C) %{year} %{username} # """ else """ /** * Project's main unit * * Copyright (C) %{year} %{username} */ """ print " - src/#{filename}" fs.writeFileSync("#{directory}/src/#{filename}", patch_source(source)) print " - test/" fs.mkdirSync("#{directory}/test", 0o0755) filename = "#{placeholders.projectfile}_test.#{ if use_coffee then 'coffee' else 'js' }" source = if use_coffee then """ # # Project's main unit test # # Copyright (C) %{year} %{username} # {Test, assert} = require('lovely') describe "%{projectunit}", -> %{projectunit} = window = document = $ = null before Test.load (build, win)-> %{projectunit} = build window = win document = win.document $ = win.Lovely.module('dom') it "should have a version", -> assert.ok %{projectunit}.version """ else """ /** * Project's main unit test * * Copyright (C) %{year} %{username} */ var Lovely = require('lovely'); var Test = Lovely.Test; var assert = Lovely.assert; describe("%{projectunit}", function() { var %{projectunit}, window, document, $; before(Test.load(function(build, win) { %{projectunit} = build; window = win; document = win.document; $ = win.Lovely.module('dom'); })); it("should have a version number", function() { assert.ok(%{projectunit}.version); }); }); """ print " - test/#{filename}" fs.writeFileSync("#{directory}/test/#{filename}", patch_source(source)) print " - build/" fs.mkdirSync("#{directory}/build", 0o0755) # fills in all the placeholders patch_source = (source)-> for key of placeholders source = source.replace( new RegExp('%\\{'+ key + '\\}', 'g'), placeholders[key]) source exports.init = (args) -> name_re = /// ^[a-z0-9] # it should start with a letter or a number [a-z0-9\-]+ # should hase only alpha-numberic symbols [a-z0-9]$ # end with a letter or a number /// project_name = args.shift() if !project_name print_error "You have to specify the project name" if !name_re.test(project_name) print_error "Project name should match: " + name_re.toString().yellow if fs.existsSync("#{process.cwd()}/#{project_name}") print_error "Directory already exists" generate(project_name, args) exports.help = (args) -> """ Generates a standard LovelyIO module project Usage: lovely new <project-name> Options: --js use JavaScript for scripting --css use CSS for styles --scss use SCSS for styles --stylus use Stylus for styles """
82301
# # The new project generator tool # # Copyright (C) 2011-2012 <NAME> # fs = require('fs') lovelyrc = require('../lovelyrc') placeholders = {} # # Starts the new project generation # # @param {String} projectname # @param {Array} the rest of the arguments # @return void # generate = (projectname, args) -> directory = "#{process.cwd()}/#{projectname}" project_tpl = "#{__dirname}/../project_tpl" use_coffee = args.indexOf('--js') is -1 && lovelyrc.lang.indexOf('js') is -1 use_sass = args.indexOf('--css') is -1 && lovelyrc.lang.indexOf('css') is -1 use_scss = args.indexOf('--scss') isnt -1 || lovelyrc.lang.indexOf('scss') isnt -1 use_stylus = args.indexOf('--stylus') isnt -1 || lovelyrc.lang.indexOf('stylus') isnt -1 use_sass = !use_scss && !use_stylus && use_sass use_css = !use_sass && !use_scss && !use_stylus placeholders = projectname: projectname, projectunit: projectname.replace(/(^|-)([a-z])/g, (m,m1,m2)-> m2.toUpperCase()) projectfile: projectname.replace(/\-/g, '_') year: new Date().getFullYear(), username: lovelyrc.name || "<NAME>" print "Creating directory: #{projectname}" fs.mkdirSync(directory, 0o0755) # just checking if the file should be copied over suitable = (filename) -> switch filename.split('.').pop() when 'js' then return !use_coffee when 'coffee' then return use_coffee when 'sass' then return use_sass when 'scss' then return use_scss when 'styl' then return use_stylus when 'css' then return use_css else return true for filename in fs.readdirSync(project_tpl) if suitable(filename) source = fs.readFileSync("#{project_tpl}/#{filename}").toString() filename = '.gitignore' if filename is 'gitignore' print " - #{filename}" fs.writeFileSync("#{directory}/#{filename}", patch_source(source)) print " - src/" fs.mkdirSync("#{directory}/src", 0o0755) filename = "#{placeholders.projectfile}.#{ if use_coffee then 'coffee' else 'js' }" source = if use_coffee then """ # # Project's main unit # # Copyright (C) %{year} %{username} # """ else """ /** * Project's main unit * * Copyright (C) %{year} %{username} */ """ print " - src/#{filename}" fs.writeFileSync("#{directory}/src/#{filename}", patch_source(source)) print " - test/" fs.mkdirSync("#{directory}/test", 0o0755) filename = "#{placeholders.projectfile}_test.#{ if use_coffee then 'coffee' else 'js' }" source = if use_coffee then """ # # Project's main unit test # # Copyright (C) %{year} %{username} # {Test, assert} = require('lovely') describe "%{projectunit}", -> %{projectunit} = window = document = $ = null before Test.load (build, win)-> %{projectunit} = build window = win document = win.document $ = win.Lovely.module('dom') it "should have a version", -> assert.ok %{projectunit}.version """ else """ /** * Project's main unit test * * Copyright (C) %{year} %{username} */ var Lovely = require('lovely'); var Test = Lovely.Test; var assert = Lovely.assert; describe("%{projectunit}", function() { var %{projectunit}, window, document, $; before(Test.load(function(build, win) { %{projectunit} = build; window = win; document = win.document; $ = win.Lovely.module('dom'); })); it("should have a version number", function() { assert.ok(%{projectunit}.version); }); }); """ print " - test/#{filename}" fs.writeFileSync("#{directory}/test/#{filename}", patch_source(source)) print " - build/" fs.mkdirSync("#{directory}/build", 0o0755) # fills in all the placeholders patch_source = (source)-> for key of placeholders source = source.replace( new RegExp('%\\{'+ key + '\\}', 'g'), placeholders[key]) source exports.init = (args) -> name_re = /// ^[a-z0-9] # it should start with a letter or a number [a-z0-9\-]+ # should hase only alpha-numberic symbols [a-z0-9]$ # end with a letter or a number /// project_name = args.shift() if !project_name print_error "You have to specify the project name" if !name_re.test(project_name) print_error "Project name should match: " + name_re.toString().yellow if fs.existsSync("#{process.cwd()}/#{project_name}") print_error "Directory already exists" generate(project_name, args) exports.help = (args) -> """ Generates a standard LovelyIO module project Usage: lovely new <project-name> Options: --js use JavaScript for scripting --css use CSS for styles --scss use SCSS for styles --stylus use Stylus for styles """
true
# # The new project generator tool # # Copyright (C) 2011-2012 PI:NAME:<NAME>END_PI # fs = require('fs') lovelyrc = require('../lovelyrc') placeholders = {} # # Starts the new project generation # # @param {String} projectname # @param {Array} the rest of the arguments # @return void # generate = (projectname, args) -> directory = "#{process.cwd()}/#{projectname}" project_tpl = "#{__dirname}/../project_tpl" use_coffee = args.indexOf('--js') is -1 && lovelyrc.lang.indexOf('js') is -1 use_sass = args.indexOf('--css') is -1 && lovelyrc.lang.indexOf('css') is -1 use_scss = args.indexOf('--scss') isnt -1 || lovelyrc.lang.indexOf('scss') isnt -1 use_stylus = args.indexOf('--stylus') isnt -1 || lovelyrc.lang.indexOf('stylus') isnt -1 use_sass = !use_scss && !use_stylus && use_sass use_css = !use_sass && !use_scss && !use_stylus placeholders = projectname: projectname, projectunit: projectname.replace(/(^|-)([a-z])/g, (m,m1,m2)-> m2.toUpperCase()) projectfile: projectname.replace(/\-/g, '_') year: new Date().getFullYear(), username: lovelyrc.name || "PI:NAME:<NAME>END_PI" print "Creating directory: #{projectname}" fs.mkdirSync(directory, 0o0755) # just checking if the file should be copied over suitable = (filename) -> switch filename.split('.').pop() when 'js' then return !use_coffee when 'coffee' then return use_coffee when 'sass' then return use_sass when 'scss' then return use_scss when 'styl' then return use_stylus when 'css' then return use_css else return true for filename in fs.readdirSync(project_tpl) if suitable(filename) source = fs.readFileSync("#{project_tpl}/#{filename}").toString() filename = '.gitignore' if filename is 'gitignore' print " - #{filename}" fs.writeFileSync("#{directory}/#{filename}", patch_source(source)) print " - src/" fs.mkdirSync("#{directory}/src", 0o0755) filename = "#{placeholders.projectfile}.#{ if use_coffee then 'coffee' else 'js' }" source = if use_coffee then """ # # Project's main unit # # Copyright (C) %{year} %{username} # """ else """ /** * Project's main unit * * Copyright (C) %{year} %{username} */ """ print " - src/#{filename}" fs.writeFileSync("#{directory}/src/#{filename}", patch_source(source)) print " - test/" fs.mkdirSync("#{directory}/test", 0o0755) filename = "#{placeholders.projectfile}_test.#{ if use_coffee then 'coffee' else 'js' }" source = if use_coffee then """ # # Project's main unit test # # Copyright (C) %{year} %{username} # {Test, assert} = require('lovely') describe "%{projectunit}", -> %{projectunit} = window = document = $ = null before Test.load (build, win)-> %{projectunit} = build window = win document = win.document $ = win.Lovely.module('dom') it "should have a version", -> assert.ok %{projectunit}.version """ else """ /** * Project's main unit test * * Copyright (C) %{year} %{username} */ var Lovely = require('lovely'); var Test = Lovely.Test; var assert = Lovely.assert; describe("%{projectunit}", function() { var %{projectunit}, window, document, $; before(Test.load(function(build, win) { %{projectunit} = build; window = win; document = win.document; $ = win.Lovely.module('dom'); })); it("should have a version number", function() { assert.ok(%{projectunit}.version); }); }); """ print " - test/#{filename}" fs.writeFileSync("#{directory}/test/#{filename}", patch_source(source)) print " - build/" fs.mkdirSync("#{directory}/build", 0o0755) # fills in all the placeholders patch_source = (source)-> for key of placeholders source = source.replace( new RegExp('%\\{'+ key + '\\}', 'g'), placeholders[key]) source exports.init = (args) -> name_re = /// ^[a-z0-9] # it should start with a letter or a number [a-z0-9\-]+ # should hase only alpha-numberic symbols [a-z0-9]$ # end with a letter or a number /// project_name = args.shift() if !project_name print_error "You have to specify the project name" if !name_re.test(project_name) print_error "Project name should match: " + name_re.toString().yellow if fs.existsSync("#{process.cwd()}/#{project_name}") print_error "Directory already exists" generate(project_name, args) exports.help = (args) -> """ Generates a standard LovelyIO module project Usage: lovely new <project-name> Options: --js use JavaScript for scripting --css use CSS for styles --scss use SCSS for styles --stylus use Stylus for styles """
[ { "context": "ing fields\n sendLogin username: $scope.username, password: $scope.password\n .success (", "end": 526, "score": 0.8789559006690979, "start": 518, "tag": "USERNAME", "value": "username" }, { "context": " sendLogin username: $scope.username, password: $scope.password\n .success (data) ->\n $s", "end": 553, "score": 0.9181007742881775, "start": 539, "tag": "PASSWORD", "value": "scope.password" } ]
public/coffee/controllers/login.coffee
maxaille/PartyFinance
1
App.controller 'loginCtrl', [ '$rootScope' '$scope' '$http' '$state' '$stateParams' '$timeout' 'API' ($rootScope, $scope, $http, $state, $stateParams, $timeout, API) -> sendLogin = (user) -> $http.post API + '/login', user .success (data) -> $rootScope.$broadcast 'user:loggedin', user: data.user, exp: data.exp*1000 $scope.validate = (form) -> # Use 'form' for checking fields sendLogin username: $scope.username, password: $scope.password .success (data) -> $state.go if $stateParams.oldState then $stateParams.oldState.name else 'start' .error (data) -> console.log data if $stateParams.user sendLogin $stateParams.user .success -> $state.go 'start' .error -> console.log 'nok' ]
50813
App.controller 'loginCtrl', [ '$rootScope' '$scope' '$http' '$state' '$stateParams' '$timeout' 'API' ($rootScope, $scope, $http, $state, $stateParams, $timeout, API) -> sendLogin = (user) -> $http.post API + '/login', user .success (data) -> $rootScope.$broadcast 'user:loggedin', user: data.user, exp: data.exp*1000 $scope.validate = (form) -> # Use 'form' for checking fields sendLogin username: $scope.username, password: $<PASSWORD> .success (data) -> $state.go if $stateParams.oldState then $stateParams.oldState.name else 'start' .error (data) -> console.log data if $stateParams.user sendLogin $stateParams.user .success -> $state.go 'start' .error -> console.log 'nok' ]
true
App.controller 'loginCtrl', [ '$rootScope' '$scope' '$http' '$state' '$stateParams' '$timeout' 'API' ($rootScope, $scope, $http, $state, $stateParams, $timeout, API) -> sendLogin = (user) -> $http.post API + '/login', user .success (data) -> $rootScope.$broadcast 'user:loggedin', user: data.user, exp: data.exp*1000 $scope.validate = (form) -> # Use 'form' for checking fields sendLogin username: $scope.username, password: $PI:PASSWORD:<PASSWORD>END_PI .success (data) -> $state.go if $stateParams.oldState then $stateParams.oldState.name else 'start' .error (data) -> console.log data if $stateParams.user sendLogin $stateParams.user .success -> $state.go 'start' .error -> console.log 'nok' ]
[ { "context": "}))\n\n$ ->\n\titems = new itemCollection([\n\t\t{name: 'Wordsworth', id: _.uniqueId() },\n\t\t{name: 'Shelley', id: _.u", "end": 1252, "score": 0.9996829032897949, "start": 1242, "tag": "NAME", "value": "Wordsworth" }, { "context": "name: 'Wordsworth', id: _.uniqueId() },\n\t\t{name: 'Shelley', id: _.uniqueId()},\n\t])\n\tlistView = new listView", "end": 1292, "score": 0.9995687007904053, "start": 1285, "tag": "NAME", "value": "Shelley" } ]
js/site.coffee
zdavis/t3con-na-13
1
class itemModel extends Backbone.Model class itemCollection extends Backbone.Collection model: itemModel class debugView extends Backbone.View initialize: -> @collection.bind('add', @render, @) @collection.bind('remove', @render, @) @render() render: -> json = @collection.toJSON() @$el.html(JSON.stringify(json)) class listView extends Backbone.View events: 'click li': 'removeItem' template: $('#listViewTemplate').html() removeItem: (e) -> id = $(e.currentTarget).data().item @collection.remove(@collection.get(id)) console.log @collection.length initialize: (options) -> @collection.bind('add', @render, @) @collection.bind('remove', @render, @) render: () -> @.$el.html(_.template(@template, {items: @collection})) class addView extends Backbone.View events: 'submit #new-model-form': 'addItem' template: $('#addViewTemplate').html() addItem: (e) -> e.preventDefault() input = @$el.find('#new-model') name = input.val() if name? input.val('') item = new itemModel({name: name, id: _.uniqueId()}) @collection.add(item) initialize: (options) -> render: () -> @.$el.html(_.template(@template, {items: @collection})) $ -> items = new itemCollection([ {name: 'Wordsworth', id: _.uniqueId() }, {name: 'Shelley', id: _.uniqueId()}, ]) listView = new listView({collection: items, el: $('[data-view="list"]')}).render() addView = new addView({collection: items, el: $('[data-view="add"]')}).render() debugView = new debugView({collection: items, el: $('[data-view="debug"]')}).render()
109314
class itemModel extends Backbone.Model class itemCollection extends Backbone.Collection model: itemModel class debugView extends Backbone.View initialize: -> @collection.bind('add', @render, @) @collection.bind('remove', @render, @) @render() render: -> json = @collection.toJSON() @$el.html(JSON.stringify(json)) class listView extends Backbone.View events: 'click li': 'removeItem' template: $('#listViewTemplate').html() removeItem: (e) -> id = $(e.currentTarget).data().item @collection.remove(@collection.get(id)) console.log @collection.length initialize: (options) -> @collection.bind('add', @render, @) @collection.bind('remove', @render, @) render: () -> @.$el.html(_.template(@template, {items: @collection})) class addView extends Backbone.View events: 'submit #new-model-form': 'addItem' template: $('#addViewTemplate').html() addItem: (e) -> e.preventDefault() input = @$el.find('#new-model') name = input.val() if name? input.val('') item = new itemModel({name: name, id: _.uniqueId()}) @collection.add(item) initialize: (options) -> render: () -> @.$el.html(_.template(@template, {items: @collection})) $ -> items = new itemCollection([ {name: '<NAME>', id: _.uniqueId() }, {name: '<NAME>', id: _.uniqueId()}, ]) listView = new listView({collection: items, el: $('[data-view="list"]')}).render() addView = new addView({collection: items, el: $('[data-view="add"]')}).render() debugView = new debugView({collection: items, el: $('[data-view="debug"]')}).render()
true
class itemModel extends Backbone.Model class itemCollection extends Backbone.Collection model: itemModel class debugView extends Backbone.View initialize: -> @collection.bind('add', @render, @) @collection.bind('remove', @render, @) @render() render: -> json = @collection.toJSON() @$el.html(JSON.stringify(json)) class listView extends Backbone.View events: 'click li': 'removeItem' template: $('#listViewTemplate').html() removeItem: (e) -> id = $(e.currentTarget).data().item @collection.remove(@collection.get(id)) console.log @collection.length initialize: (options) -> @collection.bind('add', @render, @) @collection.bind('remove', @render, @) render: () -> @.$el.html(_.template(@template, {items: @collection})) class addView extends Backbone.View events: 'submit #new-model-form': 'addItem' template: $('#addViewTemplate').html() addItem: (e) -> e.preventDefault() input = @$el.find('#new-model') name = input.val() if name? input.val('') item = new itemModel({name: name, id: _.uniqueId()}) @collection.add(item) initialize: (options) -> render: () -> @.$el.html(_.template(@template, {items: @collection})) $ -> items = new itemCollection([ {name: 'PI:NAME:<NAME>END_PI', id: _.uniqueId() }, {name: 'PI:NAME:<NAME>END_PI', id: _.uniqueId()}, ]) listView = new listView({collection: items, el: $('[data-view="list"]')}).render() addView = new addView({collection: items, el: $('[data-view="add"]')}).render() debugView = new debugView({collection: items, el: $('[data-view="debug"]')}).render()
[ { "context": "@user =\n\t\t\t\t\t_id: \"user-id\"\n\t\t\t\t\temail: @email = \"USER@sharelatex.com\"\n\t\t\t\t@unencryptedPassword = \"banana\"\n\t\t\t\t@User.fi", "end": 828, "score": 0.9999144077301025, "start": 809, "tag": "EMAIL", "value": "USER@sharelatex.com" }, { "context": "\"USER@sharelatex.com\"\n\t\t\t\t@unencryptedPassword = \"banana\"\n\t\t\t\t@User.findOne = sinon.stub().callsArgWith(1,", "end": 864, "score": 0.9994673728942871, "start": 858, "tag": "PASSWORD", "value": "banana" }, { "context": "->\n\t\t\t\t\t@user.hashedPassword = @hashedPassword = \"asdfjadflasdf\"\n\t\t\t\t\t@bcrypt.compare = sinon.stub().callsArgWith", "end": 1067, "score": 0.999491274356842, "start": 1054, "tag": "PASSWORD", "value": "asdfjadflasdf" }, { "context": "->\n\t\t\t\t\t@user.hashedPassword = @hashedPassword = \"asdfjadflasdf\"\n\t\t\t\t\t@bcrypt.compare = sinon.stub().callsArgWith", "end": 2229, "score": 0.9994721412658691, "start": 2216, "tag": "PASSWORD", "value": "asdfjadflasdf" }, { "context": "eEach ->\n\t\t\t@user_id = ObjectId()\n\t\t\t@password = \"banana\"\n\t\t\t@hashedPassword = \"asdkjfa;osiuvandf\"\n\t\t\t@sal", "end": 3646, "score": 0.9994675517082214, "start": 3640, "tag": "PASSWORD", "value": "banana" }, { "context": "d()\n\t\t\t@password = \"banana\"\n\t\t\t@hashedPassword = \"asdkjfa;osiuvandf\"\n\t\t\t@salt = \"saltaasdfasdfasdf\"\n\t\t\t@bcrypt.genSal", "end": 3687, "score": 0.9975631237030029, "start": 3670, "tag": "PASSWORD", "value": "asdkjfa;osiuvandf" }, { "context": "@hashedPassword = \"asdkjfa;osiuvandf\"\n\t\t\t@salt = \"saltaasdfasdfasdf\"\n\t\t\t@bcrypt.genSalt = sinon.stub().callsArgWith(1", "end": 3718, "score": 0.9988123178482056, "start": 3701, "tag": "PASSWORD", "value": "saltaasdfasdfasdf" }, { "context": "lsArg(2)\n\t\t\t@AuthenticationManager.setUserPassword(@user_id, @password, @callback)\n\n\t\tit \"should update the u", "end": 3950, "score": 0.9977010488510132, "start": 3942, "tag": "USERNAME", "value": "@user_id" }, { "context": "\t}, {\n\t\t\t\t\t$set: {\n\t\t\t\t\t\t\"hashedPassword\": @hashedPassword\n\t\t\t\t\t}\n\t\t\t\t\t$unset: password: true\n\t\t\t\t})\n\t\t\t\t.sh", "end": 4175, "score": 0.7275636196136475, "start": 4167, "tag": "PASSWORD", "value": "Password" } ]
test/UnitTests/coffee/Authentication/AuthenticationManagerTests.coffee
bowlofstew/web-sharelatex
0
sinon = require('sinon') chai = require('chai') should = chai.should() expect = chai.expect modulePath = "../../../../app/js/Features/Authentication/AuthenticationManager.js" SandboxedModule = require('sandboxed-module') events = require "events" ObjectId = require("mongojs").ObjectId describe "AuthenticationManager", -> beforeEach -> @AuthenticationManager = SandboxedModule.require modulePath, requires: "../../models/User": User: @User = {} "../../infrastructure/mongojs": db: @db = users: {} ObjectId: ObjectId "bcrypt": @bcrypt = {} "settings-sharelatex": { security: { bcryptRounds: 12 } } @callback = sinon.stub() describe "authenticate", -> describe "when the user exists in the database", -> beforeEach -> @user = _id: "user-id" email: @email = "USER@sharelatex.com" @unencryptedPassword = "banana" @User.findOne = sinon.stub().callsArgWith(1, null, @user) describe "when the hashed password matches", -> beforeEach (done) -> @user.hashedPassword = @hashedPassword = "asdfjadflasdf" @bcrypt.compare = sinon.stub().callsArgWith(2, null, true) @bcrypt.getRounds = sinon.stub().returns 12 @AuthenticationManager.authenticate email: @email, @unencryptedPassword, (error, user) => @callback(error, user) done() it "should look up the correct user in the database", -> @User.findOne.calledWith(email: @email).should.equal true it "should check that the passwords match", -> @bcrypt.compare .calledWith(@unencryptedPassword, @hashedPassword) .should.equal true it "should return the user", -> @callback.calledWith(null, @user).should.equal true describe "when the encrypted passwords do not match", -> beforeEach -> @AuthenticationManager._encryptPassword = sinon.stub().returns("Not the encrypted password") @AuthenticationManager.authenticate(email: @email, @unencryptedPassword, @callback) it "should not return the user", -> @callback.calledWith(null, null).should.equal true describe "when the hashed password matches but the number of rounds is too low", -> beforeEach (done) -> @user.hashedPassword = @hashedPassword = "asdfjadflasdf" @bcrypt.compare = sinon.stub().callsArgWith(2, null, true) @bcrypt.getRounds = sinon.stub().returns 7 @AuthenticationManager.setUserPassword = sinon.stub().callsArgWith(2, null) @AuthenticationManager.authenticate email: @email, @unencryptedPassword, (error, user) => @callback(error, user) done() it "should look up the correct user in the database", -> @User.findOne.calledWith(email: @email).should.equal true it "should check that the passwords match", -> @bcrypt.compare .calledWith(@unencryptedPassword, @hashedPassword) .should.equal true it "should check the number of rounds", -> @bcrypt.getRounds.called.should.equal true it "should set the users password (with a higher number of rounds)", -> @AuthenticationManager.setUserPassword .calledWith("user-id", @unencryptedPassword) .should.equal true it "should return the user", -> @callback.calledWith(null, @user).should.equal true describe "when the user does not exist in the database", -> beforeEach -> @User.findOne = sinon.stub().callsArgWith(1, null, null) @AuthenticationManager.authenticate(email: @email, @unencrpytedPassword, @callback) it "should not return a user", -> @callback.calledWith(null, null).should.equal true describe "setUserPassword", -> beforeEach -> @user_id = ObjectId() @password = "banana" @hashedPassword = "asdkjfa;osiuvandf" @salt = "saltaasdfasdfasdf" @bcrypt.genSalt = sinon.stub().callsArgWith(1, null, @salt) @bcrypt.hash = sinon.stub().callsArgWith(2, null, @hashedPassword) @db.users.update = sinon.stub().callsArg(2) @AuthenticationManager.setUserPassword(@user_id, @password, @callback) it "should update the user's password in the database", -> @db.users.update .calledWith({ _id: ObjectId(@user_id.toString()) }, { $set: { "hashedPassword": @hashedPassword } $unset: password: true }) .should.equal true it "should hash the password", -> @bcrypt.genSalt .calledWith(12) .should.equal true @bcrypt.hash .calledWith(@password, @salt) .should.equal true it "should call the callback", -> @callback.called.should.equal true
8233
sinon = require('sinon') chai = require('chai') should = chai.should() expect = chai.expect modulePath = "../../../../app/js/Features/Authentication/AuthenticationManager.js" SandboxedModule = require('sandboxed-module') events = require "events" ObjectId = require("mongojs").ObjectId describe "AuthenticationManager", -> beforeEach -> @AuthenticationManager = SandboxedModule.require modulePath, requires: "../../models/User": User: @User = {} "../../infrastructure/mongojs": db: @db = users: {} ObjectId: ObjectId "bcrypt": @bcrypt = {} "settings-sharelatex": { security: { bcryptRounds: 12 } } @callback = sinon.stub() describe "authenticate", -> describe "when the user exists in the database", -> beforeEach -> @user = _id: "user-id" email: @email = "<EMAIL>" @unencryptedPassword = "<PASSWORD>" @User.findOne = sinon.stub().callsArgWith(1, null, @user) describe "when the hashed password matches", -> beforeEach (done) -> @user.hashedPassword = @hashedPassword = "<PASSWORD>" @bcrypt.compare = sinon.stub().callsArgWith(2, null, true) @bcrypt.getRounds = sinon.stub().returns 12 @AuthenticationManager.authenticate email: @email, @unencryptedPassword, (error, user) => @callback(error, user) done() it "should look up the correct user in the database", -> @User.findOne.calledWith(email: @email).should.equal true it "should check that the passwords match", -> @bcrypt.compare .calledWith(@unencryptedPassword, @hashedPassword) .should.equal true it "should return the user", -> @callback.calledWith(null, @user).should.equal true describe "when the encrypted passwords do not match", -> beforeEach -> @AuthenticationManager._encryptPassword = sinon.stub().returns("Not the encrypted password") @AuthenticationManager.authenticate(email: @email, @unencryptedPassword, @callback) it "should not return the user", -> @callback.calledWith(null, null).should.equal true describe "when the hashed password matches but the number of rounds is too low", -> beforeEach (done) -> @user.hashedPassword = @hashedPassword = "<PASSWORD>" @bcrypt.compare = sinon.stub().callsArgWith(2, null, true) @bcrypt.getRounds = sinon.stub().returns 7 @AuthenticationManager.setUserPassword = sinon.stub().callsArgWith(2, null) @AuthenticationManager.authenticate email: @email, @unencryptedPassword, (error, user) => @callback(error, user) done() it "should look up the correct user in the database", -> @User.findOne.calledWith(email: @email).should.equal true it "should check that the passwords match", -> @bcrypt.compare .calledWith(@unencryptedPassword, @hashedPassword) .should.equal true it "should check the number of rounds", -> @bcrypt.getRounds.called.should.equal true it "should set the users password (with a higher number of rounds)", -> @AuthenticationManager.setUserPassword .calledWith("user-id", @unencryptedPassword) .should.equal true it "should return the user", -> @callback.calledWith(null, @user).should.equal true describe "when the user does not exist in the database", -> beforeEach -> @User.findOne = sinon.stub().callsArgWith(1, null, null) @AuthenticationManager.authenticate(email: @email, @unencrpytedPassword, @callback) it "should not return a user", -> @callback.calledWith(null, null).should.equal true describe "setUserPassword", -> beforeEach -> @user_id = ObjectId() @password = "<PASSWORD>" @hashedPassword = "<PASSWORD>" @salt = "<PASSWORD>" @bcrypt.genSalt = sinon.stub().callsArgWith(1, null, @salt) @bcrypt.hash = sinon.stub().callsArgWith(2, null, @hashedPassword) @db.users.update = sinon.stub().callsArg(2) @AuthenticationManager.setUserPassword(@user_id, @password, @callback) it "should update the user's password in the database", -> @db.users.update .calledWith({ _id: ObjectId(@user_id.toString()) }, { $set: { "hashedPassword": @hashed<PASSWORD> } $unset: password: true }) .should.equal true it "should hash the password", -> @bcrypt.genSalt .calledWith(12) .should.equal true @bcrypt.hash .calledWith(@password, @salt) .should.equal true it "should call the callback", -> @callback.called.should.equal true
true
sinon = require('sinon') chai = require('chai') should = chai.should() expect = chai.expect modulePath = "../../../../app/js/Features/Authentication/AuthenticationManager.js" SandboxedModule = require('sandboxed-module') events = require "events" ObjectId = require("mongojs").ObjectId describe "AuthenticationManager", -> beforeEach -> @AuthenticationManager = SandboxedModule.require modulePath, requires: "../../models/User": User: @User = {} "../../infrastructure/mongojs": db: @db = users: {} ObjectId: ObjectId "bcrypt": @bcrypt = {} "settings-sharelatex": { security: { bcryptRounds: 12 } } @callback = sinon.stub() describe "authenticate", -> describe "when the user exists in the database", -> beforeEach -> @user = _id: "user-id" email: @email = "PI:EMAIL:<EMAIL>END_PI" @unencryptedPassword = "PI:PASSWORD:<PASSWORD>END_PI" @User.findOne = sinon.stub().callsArgWith(1, null, @user) describe "when the hashed password matches", -> beforeEach (done) -> @user.hashedPassword = @hashedPassword = "PI:PASSWORD:<PASSWORD>END_PI" @bcrypt.compare = sinon.stub().callsArgWith(2, null, true) @bcrypt.getRounds = sinon.stub().returns 12 @AuthenticationManager.authenticate email: @email, @unencryptedPassword, (error, user) => @callback(error, user) done() it "should look up the correct user in the database", -> @User.findOne.calledWith(email: @email).should.equal true it "should check that the passwords match", -> @bcrypt.compare .calledWith(@unencryptedPassword, @hashedPassword) .should.equal true it "should return the user", -> @callback.calledWith(null, @user).should.equal true describe "when the encrypted passwords do not match", -> beforeEach -> @AuthenticationManager._encryptPassword = sinon.stub().returns("Not the encrypted password") @AuthenticationManager.authenticate(email: @email, @unencryptedPassword, @callback) it "should not return the user", -> @callback.calledWith(null, null).should.equal true describe "when the hashed password matches but the number of rounds is too low", -> beforeEach (done) -> @user.hashedPassword = @hashedPassword = "PI:PASSWORD:<PASSWORD>END_PI" @bcrypt.compare = sinon.stub().callsArgWith(2, null, true) @bcrypt.getRounds = sinon.stub().returns 7 @AuthenticationManager.setUserPassword = sinon.stub().callsArgWith(2, null) @AuthenticationManager.authenticate email: @email, @unencryptedPassword, (error, user) => @callback(error, user) done() it "should look up the correct user in the database", -> @User.findOne.calledWith(email: @email).should.equal true it "should check that the passwords match", -> @bcrypt.compare .calledWith(@unencryptedPassword, @hashedPassword) .should.equal true it "should check the number of rounds", -> @bcrypt.getRounds.called.should.equal true it "should set the users password (with a higher number of rounds)", -> @AuthenticationManager.setUserPassword .calledWith("user-id", @unencryptedPassword) .should.equal true it "should return the user", -> @callback.calledWith(null, @user).should.equal true describe "when the user does not exist in the database", -> beforeEach -> @User.findOne = sinon.stub().callsArgWith(1, null, null) @AuthenticationManager.authenticate(email: @email, @unencrpytedPassword, @callback) it "should not return a user", -> @callback.calledWith(null, null).should.equal true describe "setUserPassword", -> beforeEach -> @user_id = ObjectId() @password = "PI:PASSWORD:<PASSWORD>END_PI" @hashedPassword = "PI:PASSWORD:<PASSWORD>END_PI" @salt = "PI:PASSWORD:<PASSWORD>END_PI" @bcrypt.genSalt = sinon.stub().callsArgWith(1, null, @salt) @bcrypt.hash = sinon.stub().callsArgWith(2, null, @hashedPassword) @db.users.update = sinon.stub().callsArg(2) @AuthenticationManager.setUserPassword(@user_id, @password, @callback) it "should update the user's password in the database", -> @db.users.update .calledWith({ _id: ObjectId(@user_id.toString()) }, { $set: { "hashedPassword": @hashedPI:PASSWORD:<PASSWORD>END_PI } $unset: password: true }) .should.equal true it "should hash the password", -> @bcrypt.genSalt .calledWith(12) .should.equal true @bcrypt.hash .calledWith(@password, @salt) .should.equal true it "should call the callback", -> @callback.called.should.equal true
[ { "context": "export default\n name: 'Eris'\n type: 'dwarfPlanet'\n radius: 1163\n elements:", "end": 28, "score": 0.9997266530990601, "start": 24, "tag": "NAME", "value": "Eris" } ]
src/data/bodies/eris.coffee
skepticalimagination/solaris-model
5
export default name: 'Eris' type: 'dwarfPlanet' radius: 1163 elements: format: 'jpl-sbdb' base: {a: 67.64830340711272, e: 0.442178729942388, i: 44.19798212835923, L: 392.0654311366, lp: 187.3023562449, node: 35.88062556130805} day: {M: 0.001771408442534513}
131304
export default name: '<NAME>' type: 'dwarfPlanet' radius: 1163 elements: format: 'jpl-sbdb' base: {a: 67.64830340711272, e: 0.442178729942388, i: 44.19798212835923, L: 392.0654311366, lp: 187.3023562449, node: 35.88062556130805} day: {M: 0.001771408442534513}
true
export default name: 'PI:NAME:<NAME>END_PI' type: 'dwarfPlanet' radius: 1163 elements: format: 'jpl-sbdb' base: {a: 67.64830340711272, e: 0.442178729942388, i: 44.19798212835923, L: 392.0654311366, lp: 187.3023562449, node: 35.88062556130805} day: {M: 0.001771408442534513}
[ { "context": "ptional) Defaults to 'us-east-1'\n#\n#\n# Author:\n# Tatsuhiko Miyagawa\n# @chosak\n# @contolini\n\nAWS = require 'aws-sd", "end": 428, "score": 0.9998760223388672, "start": 410, "tag": "NAME", "value": "Tatsuhiko Miyagawa" }, { "context": "s-east-1'\n#\n#\n# Author:\n# Tatsuhiko Miyagawa\n# @chosak\n# @contolini\n\nAWS = require 'aws-sdk'\n\nmodule.e", "end": 440, "score": 0.9983777403831482, "start": 433, "tag": "USERNAME", "value": "@chosak" }, { "context": "#\n# Author:\n# Tatsuhiko Miyagawa\n# @chosak\n# @contolini\n\nAWS = require 'aws-sdk'\n\nmodule.exports = (robot", "end": 455, "score": 0.9982725381851196, "start": 445, "tag": "USERNAME", "value": "@contolini" } ]
src/sqs.coffee
catops/hubot-sqs
0
# Description # Send AWS SQS messages to Hubot # # Configuration: # HUBOT_AWS_SQS_QUEUE_URL - SQS queue to listen to, e.g. https://sqs.us-east-1.amazonaws.com/XXXXXXXXXXXXX/hubot # HUBOT_AWS_SQS_ACCESS_KEY_ID - AWS access key id with SQS permissions # HUBOT_AWS_SQS_SECRET_ACCESS_KEY - AWS secret key with SQS permissions # HUBOT_AWS_SQS_REGION - (optional) Defaults to 'us-east-1' # # # Author: # Tatsuhiko Miyagawa # @chosak # @contolini AWS = require 'aws-sdk' module.exports = (robot) -> unless process.env.HUBOT_AWS_SQS_QUEUE_URL robot.logger.error "Disabling incoming-sqs plugin because HUBOT_AWS_SQS_QUEUE_URL is not set." return sqs = new AWS.SQS { region: process.env.HUBOT_AWS_SQS_REGION or process.env.AWS_REGION or "us-east-1" accessKeyId: process.env.HUBOT_AWS_SQS_ACCESS_KEY_ID secretAccessKey: process.env.HUBOT_AWS_SQS_SECRET_ACCESS_KEY } receiver = (sqs, queue) -> robot.logger.debug "Fetching from #{queue}" sqs.receiveMessage { QueueUrl: queue MaxNumberOfMessages: 10 VisibilityTimeout: 30 WaitTimeSeconds: 20 MessageAttributeNames: [ "room" "user" ] }, (err, data) -> if err? robot.logger.error "Unable to connect to AWS SQS!" return robot.logger.error err else if data.Messages data.Messages.forEach (message) -> if not message.MessageAttributes return robot.logger.error "SQS message is missing user and room attributes." if not message.MessageAttributes.user return robot.logger.error "Username is missing from SQS message." if not message.MessageAttributes.room return robot.logger.error "Room is missing from SQS message." new Command({ user: message.MessageAttributes.user.StringValue room: message.MessageAttributes.room.StringValue } message.Body robot ).run() sqs.deleteMessage { QueueUrl: queue ReceiptHandle: message.ReceiptHandle }, (err, data) -> robot.logger.error err if err? setTimeout receiver, 50, sqs, queue setTimeout receiver, 0, sqs, process.env.HUBOT_AWS_SQS_QUEUE_URL class Command constructor: (@envelope, @message, @robot) -> run: -> try @robot.send @envelope, @message catch err @robot.logger.error err
71031
# Description # Send AWS SQS messages to Hubot # # Configuration: # HUBOT_AWS_SQS_QUEUE_URL - SQS queue to listen to, e.g. https://sqs.us-east-1.amazonaws.com/XXXXXXXXXXXXX/hubot # HUBOT_AWS_SQS_ACCESS_KEY_ID - AWS access key id with SQS permissions # HUBOT_AWS_SQS_SECRET_ACCESS_KEY - AWS secret key with SQS permissions # HUBOT_AWS_SQS_REGION - (optional) Defaults to 'us-east-1' # # # Author: # <NAME> # @chosak # @contolini AWS = require 'aws-sdk' module.exports = (robot) -> unless process.env.HUBOT_AWS_SQS_QUEUE_URL robot.logger.error "Disabling incoming-sqs plugin because HUBOT_AWS_SQS_QUEUE_URL is not set." return sqs = new AWS.SQS { region: process.env.HUBOT_AWS_SQS_REGION or process.env.AWS_REGION or "us-east-1" accessKeyId: process.env.HUBOT_AWS_SQS_ACCESS_KEY_ID secretAccessKey: process.env.HUBOT_AWS_SQS_SECRET_ACCESS_KEY } receiver = (sqs, queue) -> robot.logger.debug "Fetching from #{queue}" sqs.receiveMessage { QueueUrl: queue MaxNumberOfMessages: 10 VisibilityTimeout: 30 WaitTimeSeconds: 20 MessageAttributeNames: [ "room" "user" ] }, (err, data) -> if err? robot.logger.error "Unable to connect to AWS SQS!" return robot.logger.error err else if data.Messages data.Messages.forEach (message) -> if not message.MessageAttributes return robot.logger.error "SQS message is missing user and room attributes." if not message.MessageAttributes.user return robot.logger.error "Username is missing from SQS message." if not message.MessageAttributes.room return robot.logger.error "Room is missing from SQS message." new Command({ user: message.MessageAttributes.user.StringValue room: message.MessageAttributes.room.StringValue } message.Body robot ).run() sqs.deleteMessage { QueueUrl: queue ReceiptHandle: message.ReceiptHandle }, (err, data) -> robot.logger.error err if err? setTimeout receiver, 50, sqs, queue setTimeout receiver, 0, sqs, process.env.HUBOT_AWS_SQS_QUEUE_URL class Command constructor: (@envelope, @message, @robot) -> run: -> try @robot.send @envelope, @message catch err @robot.logger.error err
true
# Description # Send AWS SQS messages to Hubot # # Configuration: # HUBOT_AWS_SQS_QUEUE_URL - SQS queue to listen to, e.g. https://sqs.us-east-1.amazonaws.com/XXXXXXXXXXXXX/hubot # HUBOT_AWS_SQS_ACCESS_KEY_ID - AWS access key id with SQS permissions # HUBOT_AWS_SQS_SECRET_ACCESS_KEY - AWS secret key with SQS permissions # HUBOT_AWS_SQS_REGION - (optional) Defaults to 'us-east-1' # # # Author: # PI:NAME:<NAME>END_PI # @chosak # @contolini AWS = require 'aws-sdk' module.exports = (robot) -> unless process.env.HUBOT_AWS_SQS_QUEUE_URL robot.logger.error "Disabling incoming-sqs plugin because HUBOT_AWS_SQS_QUEUE_URL is not set." return sqs = new AWS.SQS { region: process.env.HUBOT_AWS_SQS_REGION or process.env.AWS_REGION or "us-east-1" accessKeyId: process.env.HUBOT_AWS_SQS_ACCESS_KEY_ID secretAccessKey: process.env.HUBOT_AWS_SQS_SECRET_ACCESS_KEY } receiver = (sqs, queue) -> robot.logger.debug "Fetching from #{queue}" sqs.receiveMessage { QueueUrl: queue MaxNumberOfMessages: 10 VisibilityTimeout: 30 WaitTimeSeconds: 20 MessageAttributeNames: [ "room" "user" ] }, (err, data) -> if err? robot.logger.error "Unable to connect to AWS SQS!" return robot.logger.error err else if data.Messages data.Messages.forEach (message) -> if not message.MessageAttributes return robot.logger.error "SQS message is missing user and room attributes." if not message.MessageAttributes.user return robot.logger.error "Username is missing from SQS message." if not message.MessageAttributes.room return robot.logger.error "Room is missing from SQS message." new Command({ user: message.MessageAttributes.user.StringValue room: message.MessageAttributes.room.StringValue } message.Body robot ).run() sqs.deleteMessage { QueueUrl: queue ReceiptHandle: message.ReceiptHandle }, (err, data) -> robot.logger.error err if err? setTimeout receiver, 50, sqs, queue setTimeout receiver, 0, sqs, process.env.HUBOT_AWS_SQS_QUEUE_URL class Command constructor: (@envelope, @message, @robot) -> run: -> try @robot.send @envelope, @message catch err @robot.logger.error err
[ { "context": "tails: 'Browsing Collection'\n\t\t\t\t\tlargeImageKey: 'idle'\n\t\t\t\t}\n\t\t\t\tDiscord.updatePresence(presence)\n\n\t\t\t#", "end": 35389, "score": 0.8805878758430481, "start": 35385, "tag": "KEY", "value": "idle" }, { "context": "PlayerUsername: ProfileManager.getInstance().get(\"username\")\n\t\tmyPlayerFactionId: gameListingData.faction_id", "end": 53976, "score": 0.8844693303108215, "start": 53968, "tag": "USERNAME", "value": "username" }, { "context": "yerId\"),\n\t\t\tplayer1Username: playerDataModel.get(\"myPlayerUsername\"),\n\t\t\tplayer1FactionId: playerDataModel.get(\"myPl", "end": 54465, "score": 0.9996611475944519, "start": 54449, "tag": "USERNAME", "value": "myPlayerUsername" }, { "context": "yerId\"),\n\t\t\tplayer2Username: playerDataModel.get(\"opponentPlayerUsername\"),\n\t\t\tplayer2FactionId: playerDataModel.get(\"oppo", "end": 54713, "score": 0.9995661377906799, "start": 54691, "tag": "USERNAME", "value": "opponentPlayerUsername" }, { "context": "yerId\"),\n\t\t\tplayer1Username: playerDataModel.get(\"opponentPlayerUsername\"),\n\t\t\tplayer1FactionId: playerDataModel.get(\"oppo", "end": 55007, "score": 0.9995540380477905, "start": 54985, "tag": "USERNAME", "value": "opponentPlayerUsername" }, { "context": "yerId\"),\n\t\t\tplayer2Username: playerDataModel.get(\"myPlayerUsername\"),\n\t\t\tplayer2FactionId: playerDataModel.get(\"myPl", "end": 55255, "score": 0.9995535016059875, "start": 55239, "tag": "USERNAME", "value": "myPlayerUsername" }, { "context": "m_random_cards: aiNumRandomCards,\n\t\t\t\tai_username: aiGeneralName\n\t\t\t}),\n\t\t\ttype: 'POST',\n\t\t\tcontentType: 'applicat", "end": 64610, "score": 0.9718660712242126, "start": 64597, "tag": "USERNAME", "value": "aiGeneralName" }, { "context": ",\n\t\t\t\tai_general_id: aiGeneralId,\n\t\t\t\tai_username: aiGeneralName\n\t\t\t}),\n\t\t\ttype: 'POST',\n\t\t\tcontentType: 'applicat", "end": 68213, "score": 0.9591917991638184, "start": 68200, "tag": "USERNAME", "value": "aiGeneralName" }, { "context": "\tproduct_id: cosmeticKeys[0]\n\t\t}, {\n\t\t\tlabelKey: \"product_id\"\n\t\t})\n\t\tNavigationManager.getInstance().destroyCo", "end": 118432, "score": 0.9915847778320312, "start": 118422, "tag": "KEY", "value": "product_id" } ]
app/application.coffee
open-duelyst/duelyst
5
# User Agent Parsing UAParser = require 'ua-parser-js' uaparser = new UAParser() uaparser.setUA(window.navigator.userAgent) userAgent = uaparser.getResult() # userAgent now contains : browser, os, device, engine objects # ---- Marionette Application ---- # # App = new Backbone.Marionette.Application() # require Firebase via browserify but temporarily alias it global scope Firebase = window.Firebase = require 'firebase' Promise = require 'bluebird' moment = require 'moment' semver = require 'semver' querystring = require 'query-string' # core Storage = require 'app/common/storage' Logger = window.Logger = require 'app/common/logger' Logger.enabled = (process.env.NODE_ENV != 'production' && process.env.NODE_ENV != 'staging') Landing = require 'app/common/landing' Session = window.Session = require 'app/common/session2' CONFIG = window.CONFIG = require 'app/common/config' RSX = window.RSX = require 'app/data/resources' PKGS = window.PKGS = require 'app/data/packages' EventBus = window.EventBus = require 'app/common/eventbus' EVENTS = require 'app/common/event_types' SDK = window.SDK = require 'app/sdk' Analytics = window.Analytics = require 'app/common/analytics' AnalyticsUtil = require 'app/common/analyticsUtil' UtilsJavascript = require 'app/common/utils/utils_javascript' UtilsEnv = require 'app/common/utils/utils_env' UtilsPointer = require 'app/common/utils/utils_pointer' audio_engine = window.audio_engine = require 'app/audio/audio_engine' openUrl = require('app/common/openUrl') i18next = require('i18next') # models and collections CardModel = require 'app/ui/models/card' DuelystFirebase = require 'app/ui/extensions/duelyst_firebase' DuelystBackbone = require 'app/ui/extensions/duelyst_backbone' # Managers / Controllers PackageManager = window.PackageManager = require 'app/ui/managers/package_manager' ProfileManager = window.ProfileManager = require 'app/ui/managers/profile_manager' GameDataManager = window.GameDataManager = require 'app/ui/managers/game_data_manager' GamesManager = window.GamesManager = require 'app/ui/managers/games_manager' CrateManager = window.CrateManager = require 'app/ui/managers/crate_manager' NotificationsManager = window.NotificationsManager = require 'app/ui/managers/notifications_manager' NavigationManager = window.NavigationManager = require 'app/ui/managers/navigation_manager' ChatManager = window.ChatManager = require 'app/ui/managers/chat_manager' InventoryManager = window.InventoryManager = require 'app/ui/managers/inventory_manager' QuestsManager = window.QuestsManager = require 'app/ui/managers/quests_manager' TelemetryManager = window.TelemetryManager = require 'app/ui/managers/telemetry_manager' ProgressionManager = window.ProgressionManager = require 'app/ui/managers/progression_manager' ServerStatusManager = window.ServerStatusManager = require 'app/ui/managers/server_status_manager' NewsManager = window.NewsManager = require 'app/ui/managers/news_manager' NewPlayerManager = window.NewPlayerManager = require 'app/ui/managers/new_player_manager' AchievementsManager = window.AchievementsManager = require 'app/ui/managers/achievements_manager' TwitchManager = window.TwitchManager = require 'app/ui/managers/twitch_manager' ShopManager = window.ShopManager = require 'app/ui/managers/shop_manager' StreamManager = window.StreamManager = require 'app/ui/managers/stream_manager' # Views Helpers = require 'app/ui/views/helpers' LoaderItemView = require 'app/ui/views/item/loader' UtilityLoadingLoginMenuItemView = require 'app/ui/views/item/utility_loading_login_menu' UtilityMainMenuItemView = require 'app/ui/views/item/utility_main_menu' UtilityMatchmakingMenuItemView = require 'app/ui/views/item/utility_matchmaking_menu' UtilityGameMenuItemView = require 'app/ui/views/item/utility_game_menu' EscGameMenuItemView = require 'app/ui/views/item/esc_game_menu' EscMainMenuItemView = require 'app/ui/views/item/esc_main_menu' LoginMenuItemView = require 'app/ui/views/item/login_menu' Discord = if window.isDesktop then require('app/common/discord') else null SelectUsernameItemView = require 'app/ui/views/item/select_username' Scene = require 'app/view/Scene' GameLayer = require 'app/view/layers/game/GameLayer' MainMenuItemView = require 'app/ui/views/item/main_menu' CollectionLayout = require 'app/ui/views2/collection/collection' PlayLayout = require 'app/ui/views/layouts/play' PlayLayer = require 'app/view/layers/pregame/PlayLayer' WatchLayout = require 'app/ui/views2/watch/watch_layout' ShopLayout = require 'app/ui/views2/shop/shop_layout' CodexLayout = require 'app/ui/views2/codex/codex_layout' CodexLayer = require 'app/view/layers/codex/CodexLayer' TutorialLessonsLayout = require 'app/ui/views2/tutorial/tutorial_lessons_layout' QuestLogLayout = require 'app/ui/views2/quests/quest_log_layout' BoosterPackUnlockLayout = require 'app/ui/views/layouts/booster_pack_collection' BoosterPackOpeningLayer = require 'app/view/layers/booster/BoosterPackOpeningLayer' VictoryLayer = require 'app/view/layers/postgame/VictoryLayer' UnlockFactionLayer = require 'app/view/layers/reward/UnlockFactionLayer.js' ProgressionRewardLayer = require 'app/view/layers/reward/ProgressionRewardLayer.js' CosmeticKeyRewardLayer = require 'app/view/layers/reward/CosmeticKeyRewardLayer.js' LadderProgressLayer = require 'app/view/layers/postgame/LadderProgressLayer' RiftProgressLayer = require 'app/view/layers/postgame/RiftProgressLayer' CurrencyRewardLayer = require 'app/view/layers/reward/CurrencyRewardLayer.js' GauntletTicketRewardLayer = require 'app/view/layers/reward/GauntletTicketRewardLayer.js' BoosterRewardLayer = require 'app/view/layers/reward/BoosterRewardLayer.js' LootCrateRewardLayer = require 'app/view/layers/reward/LootCrateRewardLayer.js' FreeCardOfTheDayLayer = require 'app/view/layers/reward/FreeCardOfTheDayLayer.js' CrateOpeningLayer = require 'app/view/layers/crate/CrateOpeningLayer' EndOfSeasonLayer = require 'app/view/layers/season/EndOfSeasonLayer' ResumeGameItemView = require 'app/ui/views/item/resume_game' FindingGameItemView = require 'app/ui/views/item/finding_game' ReconnectToGameItemView = require 'app/ui/views/item/reconnect_to_game' GameLayout = require 'app/ui/views/layouts/game' TutorialLayout = require 'app/ui/views/layouts/tutorial' VictoryItemView = require 'app/ui/views/item/victory' MessagesCompositeView = require 'app/ui/views/composite/messages' ConfirmDialogItemView = require 'app/ui/views/item/confirm_dialog' PromptDialogItemView = require 'app/ui/views/item/prompt_dialog' ActivityDialogItemView = require 'app/ui/views/item/activity_dialog' ErrorDialogItemView = require 'app/ui/views/item/error_dialog' AnnouncementModalView = require 'app/ui/views/item/announcement_modal' ShopSpecialProductAvailableDialogItemView = require 'app/ui/views2/shop/shop_special_product_available_dialog' ReplayEngine = require 'app/replay/replayEngine' AnalyticsTracker = require 'app/common/analyticsTracker' # require the Handlebars Template Helpers extension here since it modifies core Marionette code require 'app/ui/extensions/handlebars_template_helpers' localStorage.debug = 'session:*' # # --- Utility ---- # # App._screenBlurId = "AppScreenBlurId" App._userNavLockId = "AppUserNavLockId" App._queryStringParams = querystring.parse(location.search) # query string params App.getIsLoggedIn = -> return Storage.get('token') # region AI DEV ROUTES # if process.env.AI_TOOLS_ENABLED ### Before using AI DEV ROUTES, make sure you have a terminal open and run `node server/ai/phase_ii_ai.js`. ### window.ai_v1_findNextActions = (playerId, difficulty) -> return new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/v1_find_next_actions", data: JSON.stringify({ game_session_data: SDK.GameSession.getInstance().generateGameSessionSnapshot(), player_id: playerId, difficulty: difficulty }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> actionsData = JSON.parse(res.actions) actions = [] for actionData in actionsData action = SDK.GameSession.getInstance().deserializeActionFromFirebase(actionData) actions.push(action) console.log("v1_find_next_actions -> ", actions) resolve(actions) request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) .catch App._error window.ai_v2_findActionSequence = (playerId, depthLimit, msTimeLimit) -> return new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/v2_find_action_sequence", data: JSON.stringify({ game_session_data: SDK.GameSession.getInstance().generateGameSessionSnapshot(), player_id: playerId, depth_limit: depthLimit, ms_time_limit: msTimeLimit }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> sequenceActionsData = JSON.parse(res.sequence_actions) console.log("ai_v2_findActionSequence -> ", sequenceActionsData) resolve(sequenceActionsData) request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) .catch App._error window.ai_gameStarted = false window.ai_gameRunning = false window.ai_gameStepsData = null window.ai_gameStepsDataPromise = null window.ai_gamePromise = null window.ai_gameNeedsMulligan = false window.ai_stopAIvAIGame = () -> if window.ai_gameStarted window.ai_gameStarted = false window.ai_gameRunning = false window.ai_gameStepsData = null window.ai_gameNeedsMulligan = false if window.ai_gameStepsDataPromise? window.ai_gameStepsDataPromise.cancel() window.ai_gameStepsDataPromise = null if window.ai_gamePromise? window.ai_gamePromise.cancel() window.ai_gamePromise = null return new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/stop_game", data: JSON.stringify({}), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve() request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) .catch App._error window.ai_pauseAIvAIGame = () -> if window.ai_gameRunning window.ai_gameRunning = false window.ai_resumeAIvAIGame = () -> if !window.ai_gameRunning window.ai_gameRunning = true window.ai_stepAIvAIGame() window.ai_runAIvAIGame = (ai1Version, ai2Version, ai1GeneralId, ai2GeneralId, depthLimit, msTimeLimit, ai1NumRandomCards, ai2NumRandomCards) -> # pick random general if none provided if !ai1GeneralId? then ai1GeneralId = _.sample(_.sample(SDK.FactionFactory.getAllPlayableFactions()).generalIds) if !ai2GeneralId? then ai2GeneralId = _.sample(_.sample(SDK.FactionFactory.getAllPlayableFactions()).generalIds) ai1FactionId = SDK.FactionFactory.factionIdForGeneralId(ai1GeneralId) ai2FactionId = SDK.FactionFactory.factionIdForGeneralId(ai2GeneralId) # stop running game window.ai_gamePromise = ai_stopAIvAIGame().then () -> Logger.module("APPLICATION").log("ai_runAIvAIGame - > requesting for v#{ai1Version} w/ general #{SDK.CardFactory.cardForIdentifier(ai1GeneralId, SDK.GameSession.getInstance()).getName()} vs v#{ai2Version} w/ general #{SDK.CardFactory.cardForIdentifier(ai2GeneralId, SDK.GameSession.getInstance()).getName()}") window.ai_gameStarted = true window.ai_gameRunning = true # request run simulation startSimulationPromise = new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/start_game", data: JSON.stringify({ ai_1_version: ai1Version ai_1_general_id: ai1GeneralId ai_2_version: ai2Version ai_2_general_id: ai2GeneralId, depth_limit: depthLimit, ms_time_limit: msTimeLimit, ai_1_num_random_cards: ai1NumRandomCards, ai_2_num_random_cards: ai2NumRandomCards }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve(JSON.parse(res.game_session_data)) request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) # start loading loadingPromise = NavigationManager.getInstance().showDialogForLoad().then () -> return PackageManager.getInstance().loadGamePackageWithoutActivation([ai1FactionId, ai2FactionId]) return Promise.all([ startSimulationPromise, loadingPromise ]) .spread (sessionData) -> Logger.module("APPLICATION").log("ai_runAIvAIGame - > starting #{sessionData.gameId} with data:", sessionData) # reset and deserialize SDK.GameSession.reset() SDK.GameSession.getInstance().deserializeSessionFromFirebase(sessionData) # switch session game type to sandbox SDK.GameSession.getInstance().setGameType(SDK.GameType.Sandbox) # set game user id to match player 1 SDK.GameSession.getInstance().setUserId(SDK.GameSession.getInstance().getPlayer1Id()) return App._startGame() .then () -> Logger.module("APPLICATION").log("ai_runAIvAIGame - > #{SDK.GameSession.getInstance().getGameId()} running") # stop running game when game is terminated Scene.getInstance().getGameLayer().getEventBus().on(EVENTS.terminate, window.ai_stopAIvAIGame) # listen for finished showing step # wait for active (ai will already have mulliganed) return Scene.getInstance().getGameLayer().whenStatus(GameLayer.STATUS.ACTIVE).then () -> Scene.getInstance().getGameLayer().getEventBus().on(EVENTS.after_show_step, window.ai_stepAIvAIGame) # execute first step in sequence window.ai_stepAIvAIGame() .cancellable() .catch Promise.CancellationError, (e)-> Logger.module("APPLICATION").log("ai_runAIvAIGame -> promise chain cancelled") .catch App._error return ai_gamePromise window.ai_runAIvAIGameFromCurrentSession = (ai1Version, ai2Version, depthLimit, msTimeLimit) -> # stop running game window.ai_gamePromise = ai_stopAIvAIGame().then () -> Logger.module("APPLICATION").log("ai_runAIvAIGameFromCurrentSession - > requesting for v#{ai1Version} vs v#{ai2Version}") window.ai_gameStarted = true window.ai_gameRunning = true # set as non authoritative # all steps will be coming from ai simulation server SDK.GameSession.getInstance().setIsRunningAsAuthoritative(false); # request run simulation return new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/start_game_from_data", data: JSON.stringify({ ai_1_version: ai1Version ai_2_version: ai2Version depth_limit: depthLimit, ms_time_limit: msTimeLimit, game_session_data: SDK.GameSession.getInstance().generateGameSessionSnapshot() }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve() request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) .then () -> # stop running game when game is terminated Scene.getInstance().getGameLayer().getEventBus().on(EVENTS.terminate, window.ai_stopAIvAIGame) # listen for finished showing step Scene.getInstance().getGameLayer().whenStatus(GameLayer.STATUS.ACTIVE).then () -> Scene.getInstance().getGameLayer().getEventBus().on(EVENTS.after_show_step, window.ai_stepAIvAIGame) if window.ai_gameNeedsMulligan Logger.module("APPLICATION").log("ai_stepAIvAIGame -> mulligan complete") window.ai_gameNeedsMulligan = false window.ai_stepAIvAIGame() # check if needs mulligan window.ai_gameNeedsMulligan = SDK.GameSession.getInstance().isNew() # execute first step in sequence window.ai_stepAIvAIGame() .cancellable() .catch Promise.CancellationError, (e)-> Logger.module("APPLICATION").log("ai_runAIvAIGameFromCurrentSession -> promise chain cancelled") .catch App._error return ai_gamePromise window.ai_stepAIvAIGame = (event) -> if event?.step?.action instanceof SDK.EndTurnAction then return # ignore auto stepping due to end turn action as start turn will cause auto step Logger.module("APPLICATION").log("ai_stepAIvAIGame -> #{SDK.GameSession.getInstance().getGameId()} step queue length #{Scene.getInstance().getGameLayer()._stepQueue.length}") if !window.ai_gameStepsDataPromise? and Scene.getInstance().getGameLayer()._stepQueue.length == 0 # request step game window.ai_gameStepsDataPromise = new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/step_game", data: JSON.stringify({ game_id: SDK.GameSession.getInstance().getGameId() }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> if res.steps? resolve(JSON.parse(res.steps)) else resolve([]) request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) .then (stepsData) -> Logger.module("APPLICATION").log("ai_stepAIvAIGame -> steps:", stepsData.slice(0)) window.ai_gameStepsData = stepsData .cancellable() .catch Promise.CancellationError, (e)-> Logger.module("APPLICATION").log("ai_stepAIvAIGame -> promise chain cancelled") return window.ai_gameStepsDataPromise.then () -> if window.ai_gameRunning and !SDK.GameSession.getInstance().isOver() and window.ai_gameStepsData? and window.ai_gameStepsData.length > 0 # remove and deserialize next step in sequence stepData = window.ai_gameStepsData.shift() step = SDK.GameSession.getInstance().deserializeStepFromFirebase(stepData) Logger.module("APPLICATION").log("ai_stepAIvAIGame -> step:", step) # execute step SDK.GameSession.getInstance().executeAuthoritativeStep(step) # check game status and steps data if SDK.GameSession.getInstance().isOver() or window.ai_gameStepsData.length == 0 Logger.module("APPLICATION").log("ai_stepAIvAIGame -> done") window.ai_gameStepsData = null window.ai_gameStepsDataPromise = null else if step.action instanceof SDK.EndTurnAction # auto step to start turn Logger.module("APPLICATION").log("ai_stepAIvAIGame -> continuing end turn") window.ai_stepAIvAIGame() else if window.ai_gameNeedsMulligan # auto step to next mulligan Logger.module("APPLICATION").log("ai_stepAIvAIGame -> continuing mulligan") window.ai_stepAIvAIGame() window.ai_runHeadlessAIvAIGames = (numGames, ai1Version, ai2Version, ai1GeneralId, ai2GeneralId, depthLimit, msTimeLimit, ai1NumRandomCards, ai2NumRandomCards) -> Logger.module("APPLICATION").log("ai_runHeadlessAIvAIGames - > requesting #{numGames} games with v#{ai1Version} vs v#{ai2Version}") # request run games return new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/run_headless_games", data: JSON.stringify({ ai_1_version: ai1Version ai_1_general_id: ai1GeneralId ai_2_version: ai2Version ai_2_general_id: ai2GeneralId, num_games: numGames, depth_limit: depthLimit, ms_time_limit: msTimeLimit, ai_1_num_random_cards: ai1NumRandomCards, ai_2_num_random_cards: ai2NumRandomCards }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve() request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) # endregion AI DEV ROUTES # # # --- Main ---- # # App.getIsShowingMain = () -> # temporary method to check if the user can navigate to main (i.e. not already there) # this does NOT work for switching between main sub-screens return NavigationManager.getInstance().getIsShowingContentViewClass(LoginMenuItemView) or NavigationManager.getInstance().getIsShowingContentViewClass(MainMenuItemView) or NavigationManager.getInstance().getIsShowingContentViewClass(ResumeGameItemView) App.main = -> if !App._mainPromise? App._mainPromise = App._startPromise.then(() -> Logger.module("APPLICATION").log("App:main") # get and reset last game data lastGameType = CONFIG.lastGameType wasSpectate = CONFIG.lastGameWasSpectate wasTutorial = CONFIG.lastGameWasTutorial wasDeveloper = CONFIG.lastGameWasDeveloper wasDailyChallenge = CONFIG.lastGameWasDailyChallenge CONFIG.resetLastGameData() # destroy game and clear game data App.cleanupGame() # always make sure we're disconnected from the last game SDK.NetworkManager.getInstance().disconnect() # reset routes to main NavigationManager.getInstance().resetRoutes() NavigationManager.getInstance().addMajorRoute("main", App.main, App) # always restore user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationUnlocked(App._userNavLockId) if App._queryStringParams["replayId"]? Logger.module("APPLICATION").log("jumping straight into replay...") App.setCallbackWhenCancel(()-> alert('all done!')) return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> EventBus.getInstance().trigger(EVENTS.start_replay, { replayId: App._queryStringParams["replayId"] }) return Promise.resolve() ) else if !App.getIsLoggedIn() return App._showLoginMenu() else # all good, show main menu return App.managersReadyDeferred.promise.then(() -> # set user as loading ChatManager.getInstance().setStatus(ChatManager.STATUS_LOADING) # # EULA ACCEPTANCE CHECK HERE SO IT FIRES FOR ALREADY LOGGED IN PLAYERS # # strings used for session storage and profile storage # sessionAcceptedEula = Storage.namespace() + '.hasAcceptedEula' # storageAcceptedEula = 'hasAcceptedEula' # storageSentAcceptedEulaNotify = 'hasSentAcceptedEulaNotify' # # the user has accepted terms in the local session, ensure we are set in profile storage # if window.sessionStorage.getItem(sessionAcceptedEula) # ProfileManager.getInstance().set(storageAcceptedEula, true) # # check in profile storage if the user has accepted terms # if !ProfileManager.getInstance().get(storageAcceptedEula) # # TODO - This is not actually good, but we need to make a new terms and conditions page to replace BNEA one # return App._showTerms() # # user has accepted, check if they have sent notification # else # if !ProfileManager.getInstance().get(storageSentAcceptedEulaNotify) # ProfileManager.getInstance().set(storageSentAcceptedEulaNotify, true) # check for an active game lastGameModel = null if GamesManager.getInstance().playerGames.length > 0 lastGameModel = GamesManager.getInstance().playerGames.first() # calculate minutes since last game msSinceLastGame = moment().utc().valueOf() - (lastGameModel?.get("created_at") || 0) minutesSinceLastGame = moment.duration(msSinceLastGame).asMinutes() # if the last game is an active multiplayer game within last 45 minutes, show the continue game screen if lastGameModel? and lastGameModel.get("cancel_reconnect") != true and (lastGameModel.get("status") == "active" || lastGameModel.get("status") == "new") and lastGameModel.get("created_at") and minutesSinceLastGame < CONFIG.MINUTES_ALLOWED_TO_CONTINUE_GAME and SDK.GameType.isMultiplayerGameType(lastGameModel.get("game_type")) # has active game, prompt user to resume Logger.module("UI").log("Last active game was on ", new Date(lastGameModel.get("created_at")), "with data", lastGameModel) return App._resumeGame(lastGameModel) else if not NewPlayerManager.getInstance().isDoneWithTutorial() # show tutorial layout return App._showTutorialLessons() else if QuestsManager.getInstance().hasUnreadQuests() # show main menu return App._showMainMenu() else # try to return to selection for previous game type if wasSpectate return App._showMainMenu() else if wasDailyChallenge QuestsManager.getInstance().markDailyChallengeCompletionAsUnread() return App._showMainMenu() else if lastGameType == SDK.GameType.Ranked and !NewPlayerManager.getInstance().getEmphasizeBoosterUnlock() return App.showPlay(SDK.PlayModes.Ranked, true) else if lastGameType == SDK.GameType.Casual and !NewPlayerManager.getInstance().getEmphasizeBoosterUnlock() return App.showPlay(SDK.PlayModes.Casual, true) else if lastGameType == SDK.GameType.Gauntlet return App.showPlay(SDK.PlayModes.Gauntlet, true) else if lastGameType == SDK.GameType.Challenge and !wasTutorial return App.showPlay(SDK.PlayModes.Challenges, true) else if lastGameType == SDK.GameType.SinglePlayer return App.showPlay(SDK.PlayModes.Practice, true) else if lastGameType == SDK.GameType.BossBattle return App.showPlay(SDK.PlayModes.BossBattle, true) else if lastGameType == SDK.GameType.Sandbox and !wasDeveloper return App.showPlay(SDK.PlayModes.Sandbox, true) else if lastGameType == SDK.GameType.Rift return App.showPlay(SDK.PlayModes.Rift, true) else return App._showMainMenu() ) ).finally () -> App._mainPromise = null return Promise.resolve() return App._mainPromise App._showLoginMenu = (options) -> Logger.module("APPLICATION").log("App:_showLoginMenu") return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, (() -> # analytics call Analytics.page("Login",{ path: "/#login" }) # show main scene viewPromise = Scene.getInstance().showMain() # show login menu contentPromise = NavigationManager.getInstance().showContentView(new LoginMenuItemView(options)) # show utility menu for desktop only if window.isDesktop utilityPromise = NavigationManager.getInstance().showUtilityView(new UtilityLoadingLoginMenuItemView()) else utilityPromise = Promise.resolve() return Promise.all([ viewPromise, contentPromise, utilityPromise ]) ) ) App._showSelectUsername = (data) -> Logger.module("APPLICATION").log("App:_showSelectUsername") return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, (() -> # show main scene viewPromise = Scene.getInstance().showMain() # show selection dialog selectUsernameModel = new Backbone.Model({}) selectUsernameItemView = new SelectUsernameItemView({model: selectUsernameModel}) selectUsernameItemView.listenToOnce(selectUsernameItemView, "success", () => # TODO: move this into SelectUsernameItemView # We refresh token so the username property is now included Session.refreshToken() .then (refreshed) -> return ) contentPromise = NavigationManager.getInstance().showDialogView(selectUsernameItemView) return Promise.all([ NavigationManager.getInstance().destroyModalView(), NavigationManager.getInstance().destroyContentView(), viewPromise, contentPromise ]) ) ) App._showTerms = (options = {}) -> Logger.module("APPLICATION").log("App:_showTerms") return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, (() -> # show main scene viewPromise = Scene.getInstance().showMain() if App.getIsLoggedIn() if window.isSteam ProfileManager.getInstance().set('hasAcceptedSteamEula', true) else ProfileManager.getInstance().set('hasAcceptedEula', true) mainPromise = App.main() else if window.isSteam window.sessionStorage.setItem(Storage.namespace() + '.hasAcceptedSteamEula', true) else window.sessionStorage.setItem(Storage.namespace() + '.hasAcceptedEula', true) mainPromise = App._showLoginMenu({type: 'register'}) return Promise.all([ viewPromise, # contentPromise mainPromise ]) ) ) App._showTutorialLessons = (lastCompletedChallenge) -> Logger.module("APPLICATION").log("App:_showTutorialChallenges") return PackageManager.getInstance().loadAndActivateMajorPackage "nongame", null, null, () -> # analytics call Analytics.page("Tutorial Lessons",{ path: "/#tutorial_lessons" }) # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # show main scene viewPromise = Scene.getInstance().showMain().then(() -> # play main layer music mainLayer = Scene.getInstance().getMainLayer() if mainLayer? then mainLayer.playMusic() ) # show main menu tutorialLessonsLayoutView = new TutorialLessonsLayout({ lastCompletedChallenge:lastCompletedChallenge, }) contentPromise = NavigationManager.getInstance().showContentView(tutorialLessonsLayoutView) return Promise.all([ viewPromise, contentPromise ]) App._showMainMenu = () -> Logger.module("APPLICATION").log("App:_showMainMenu") return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # analytics call Analytics.page("Main Menu",{ path: "/#main_menu" }) # notify Discord status if Discord presence = { instance: 0 details: 'In Main Menu' largeImageKey: 'idle' } Discord.updatePresence(presence) # show main scene viewPromise = Scene.getInstance().showMain().then(() -> # play main layer music mainLayer = Scene.getInstance().getMainLayer() if mainLayer? then mainLayer.playMusic() ) endOfSeasonRewardsPromise = App.showEndOfSeasonRewards() return endOfSeasonRewardsPromise.then( () -> # show achievement rewards achievementsPromise = App.showAchievementCompletions() return achievementsPromise .then(()-> # show twitch rewards twitchRewardPromise = App.showTwitchRewards() return twitchRewardPromise ).then(() -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # show main menu contentPromise = NavigationManager.getInstance().showContentView(new MainMenuItemView({model: ProfileManager.getInstance().profile})) # show utility menu utilityPromise = NavigationManager.getInstance().showUtilityView(new UtilityMainMenuItemView({model: ProfileManager.getInstance().profile})) if NewsManager.getInstance().getFirstUnreadAnnouncement() # show announcment UI if we have an unread announcement modalPromise = NewsManager.getInstance().getFirstUnreadAnnouncementContentAsync().then((announcementContentModel)-> return NavigationManager.getInstance().showModalView(new AnnouncementModalView({model:announcementContentModel})); ) else # show quests if any quests modalPromise = Promise.resolve() if QuestsManager.getInstance().hasUnreadQuests() or QuestsManager.getInstance().hasUnreadDailyChallenges() modalPromise = NavigationManager.getInstance().toggleModalViewByClass(QuestLogLayout,{ collection: QuestsManager.getInstance().getQuestCollection(), model: ProgressionManager.getInstance().gameCounterModel showConfirm:true }) return Promise.all([ viewPromise, contentPromise, modalPromise, utilityPromise ]) ) ) ) # # --- Major Layouts ---- # # App.showPlay = (playModeIdentifier, showingDirectlyFromGame) -> if !App.getIsLoggedIn() return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # force play mode to string if !_.isString(playModeIdentifier) then playModeIdentifier = "" # add mode to route NavigationManager.getInstance().addMajorRoute("play_" + playModeIdentifier, App.showPlay, App, [playModeIdentifier]) # if currently in play modes, show new play mode direct currentContentView = NavigationManager.getInstance().getContentView() if currentContentView instanceof PlayLayout return currentContentView.showPlayMode(playModeIdentifier) else if showingDirectlyFromGame # show play layer viewPromise = Scene.getInstance().showContentByClass(PlayLayer, true) # show achievement rewards achievementsPromise = App.showAchievementCompletions() else achievementsPromise = viewPromise = Promise.resolve() return achievementsPromise.then(() -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # show UI return Promise.all([ viewPromise, NavigationManager.getInstance().showContentView(new PlayLayout({model: new Backbone.Model({playModeIdentifier: playModeIdentifier})})) ]).then ()-> # update available shop specials with current top rank and win count model and notify user if a new one has become available if ShopManager.getInstance().isNewSpecialAvailable ShopManager.getInstance().markNewAvailableSpecialAsRead() NavigationManager.getInstance().showDialogView(new ShopSpecialProductAvailableDialogItemView({ model: ShopManager.getInstance().availableSpecials.at(ShopManager.getInstance().availableSpecials.length-1) })) ) ) App.showWatch = ()-> if !App.getIsLoggedIn() or NavigationManager.getInstance().getContentView() instanceof WatchLayout return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage "nongame", null, null, () -> Analytics.page("Watch",{ path: "/#watch" }) # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # add mode to route NavigationManager.getInstance().addMajorRoute("watch", App.showWatch, App) # show layout return NavigationManager.getInstance().showContentView(new WatchLayout()) App.showShop = ()-> if !App.getIsLoggedIn() return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage "nongame", null, null, () -> Analytics.page("Shop",{ path: "/#shop" }) # add mode to route NavigationManager.getInstance().addMajorRoute("shop", App.showShop, App) # show layout NavigationManager.getInstance().showContentView(new ShopLayout()) App.showCollection = () -> if !App.getIsLoggedIn() or NavigationManager.getInstance().getContentView() instanceof CollectionLayout return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # add mode to route NavigationManager.getInstance().addMajorRoute("collection", App.showCollection, App) # notify Discord status if Discord presence = { instance: 0 details: 'Browsing Collection' largeImageKey: 'idle' } Discord.updatePresence(presence) # show UI return Promise.all([ Scene.getInstance().showMain() NavigationManager.getInstance().showContentView(new CollectionLayout({model: new Backbone.Model()})) ]) ) App.showCodex = () -> if !App.getIsLoggedIn() or NavigationManager.getInstance().getContentView() instanceof CodexLayout return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # add mode to route NavigationManager.getInstance().addMajorRoute("codex", App.showCodex, App) # show UI return Promise.all([ Scene.getInstance().showContent(new CodexLayer(), true), NavigationManager.getInstance().showContentView(new CodexLayout({model: new Backbone.Model()})) ]) ) App.showBoosterPackUnlock = () -> if !App.getIsLoggedIn() or NavigationManager.getInstance().getContentView() instanceof BoosterPackUnlockLayout return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # add route NavigationManager.getInstance().addMajorRoute("booster_pack_unlock", App.showBoosterPackUnlock, App) # show UI return Promise.all([ Scene.getInstance().showContent(new BoosterPackOpeningLayer(), true), NavigationManager.getInstance().showContentView(new BoosterPackUnlockLayout()) ]) ) App.showCrateInventory = () -> if !App.getIsLoggedIn() or Scene.getInstance().getOverlay() instanceof CrateOpeningLayer return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # add route NavigationManager.getInstance().addMajorRoute("crate_inventory", App.showCrateInventory, App) # show UI return Promise.all([ NavigationManager.getInstance().destroyContentView(), Scene.getInstance().showOverlay(new CrateOpeningLayer()) ]) ) # # --- Session Events ---- # # App.onLogin = (data) -> Logger.module("APPLICATION").log "User logged in: #{data.userId}" # save token to localStorage Storage.set('token', data.token) # setup ajax headers for jquery/backbone requests $.ajaxSetup headers: { Authorization: "Bearer #{data.token}" "Client-Version": window.BUILD_VERSION } # check is new signup flag is passed # can't use analytics data since the first login may have # already happened on /register page if Landing.isNewSignup() Landing.addPixelsToHead() Landing.firePixels() # check for null username here # dialog should be uncancelleable # dialog success should re-trigger session login so new token contains all required params if !Session.username return App._showSelectUsername(data) # Trigger the eventbus login event for the utilty menus EventBus.getInstance().trigger EVENTS.session_logged_in # connect all managers ProfileManager.getInstance().connect({userId: data.userId}) GameDataManager.getInstance().connect() GamesManager.getInstance().connect() ChatManager.getInstance().connect() QuestsManager.getInstance().connect() InventoryManager.getInstance().connect() NavigationManager.getInstance().connect() NotificationsManager.getInstance().connect() ProgressionManager.getInstance().connect() ServerStatusManager.getInstance().connect() TelemetryManager.getInstance().connect() NewsManager.getInstance().connect() NewPlayerManager.getInstance().connect() AchievementsManager.getInstance().connect() TwitchManager.getInstance().connect() CrateManager.getInstance().connect() ShopManager.getInstance().connect() StreamManager.getInstance().connect() TelemetryManager.getInstance().clearSignal("session","not-logged-in") TelemetryManager.getInstance().setSignal("session","logged-in") Promise.all([ ProfileManager.getInstance().onReady(), InventoryManager.getInstance().onReady(), QuestsManager.getInstance().onReady(), GamesManager.getInstance().onReady(), GameDataManager.getInstance().onReady(), ChatManager.getInstance().onReady(), ProgressionManager.getInstance().onReady(), ServerStatusManager.getInstance().onReady(), NewPlayerManager.getInstance().onReady(), AchievementsManager.getInstance().onReady(), TwitchManager.getInstance().onReady(), CrateManager.getInstance().onReady() ]).then () -> # update resolution values as of login App._updateLastResolutionValues() # we're all done loading managers App.managersReadyDeferred.resolve() # setup analytics App.onLoginAnalyticsSetup(data) # show the main screen return App.main() .catch (err) -> App.managersReadyDeferred.reject() Logger.module("APPLICATION").log("ERROR initializing managers") if err == null then err = new Error("ERROR initializing managers") App._error(err.message) throw err .finally () -> # NavigationManager.getInstance().destroyDialogView() App.onLoginAnalyticsSetup = (loginData) -> # region analytics data # Include users analytics data retrieved with session identifyParams = {} utmParams = {} hadPreviousSession = false if loginData.analyticsData? utmParams = _.extend(utmParams, loginData.analyticsData) if (utmParams.first_purchased_at?) # Shouldn't be necessary but just in case utmParams.first_purchased_at = moment.utc(utmParams.first_purchased_at).toISOString() if loginData.analyticsData.last_session_at delete utmParams.last_session_at hadPreviousSession = true # identify the user with the partial data until we connect managers Analytics.identify(loginData.userId, identifyParams, utmParams) if not hadPreviousSession Analytics.track("first login",{ category:Analytics.EventCategory.FTUE, },{ nonInteraction:1 sendUTMData:true }) Analytics.track("registered", { category:Analytics.EventCategory.Marketing },{ sendUTMData:true nonInteraction:1 }) # endregion analytics data # region analytics data # identify the user with their current rank gamesManager = GamesManager.getInstance() rank = gamesManager.rankingModel.get("rank") # default rank to 30 if it's null rank = 30 if (!rank?) # top rank topRank = gamesManager.topRankingModel.get("top_rank") topRank = gamesManager.topRankingModel.get("rank") if(!topRank?) topRank = 30 if(!topRank?) # game count gameCount = ProgressionManager.getInstance().getGameCount() # set up the params to pass for the identify call identifyParams.rank = rank identifyParams.top_ever_rank = topRank identifyParams.game_count = gameCount # if we know the registration date if ProfileManager.getInstance().get("created_at") # turn it to a sortable registered_at = moment.utc(ProfileManager.getInstance().get("created_at")).toISOString() # set it on the identifyParams identifyParams.registration_date = registered_at # if this user has an LTV parameter if ProfileManager.getInstance().get("ltv") # set it on the identifyParams identifyParams.ltv = ProfileManager.getInstance().get("ltv") # Check if today is a recorded seen on day and add it to identifyParams todaysSeenOnIndex = AnalyticsUtil.recordedDayIndexForRegistrationAndSeenOn(moment.utc(ProfileManager.getInstance().get("created_at")),moment.utc()) if todaysSeenOnIndex? identifyParams[AnalyticsUtil.nameForSeenOnDay(todaysSeenOnIndex)] = 1 # re-identify the user with better data now that we have managers connected and pass in the custom dimensions Analytics.identify(ProfileManager.getInstance().get('id'), identifyParams, utmParams) Analytics.track("login", { category:Analytics.EventCategory.Marketing },{ sendUTMData:true nonInteraction:1 }) # endregion analytics data App.onLogout = () -> Logger.module("APPLICATION").log "User logged out." TelemetryManager.getInstance().clearSignal("session","logged-in") TelemetryManager.getInstance().setSignal("session","not-logged-in") # create a new deferred object for managers loading process App.managersReadyDeferred = new Promise.defer() # destroy out any login specific menus NavigationManager.getInstance().destroyNonContentViews() # stop playing any music audio_engine.current().stop_music() Analytics.reset() # reset config CONFIG.reset() # remove token Storage.remove('token') # remove ajax headers with new call to ajaxSetup $.ajaxSetup headers: { Authorization: "" } # Trigger the eventbus logout event for the ui/managers EventBus.getInstance().trigger EVENTS.session_logged_out # go back to main to show login menu App.main() # just logs the error for debugging App.onSessionError = (error) -> Logger.module("APPLICATION").log "Session Error: #{error.message}" # # ---- Pointer ---- # # App._$canvasMouseClassEl = null App._currentMouseClass = null App.onCanvasMouseState = (e) -> if e?.state? then mouseClass = "mouse-" + e.state.toLowerCase() else mouseClass = "mouse-auto" if App._currentMouseClass != mouseClass App._$canvasMouseClassEl ?= $(CONFIG.GAMECANVAS_SELECTOR) if App._currentMouseClass == "mouse-auto" App._$canvasMouseClassEl.addClass(mouseClass) else if mouseClass == "mouse-auto" App._$canvasMouseClassEl.removeClass(App._currentMouseClass) else App._$canvasMouseClassEl.removeClass(App._currentMouseClass).addClass(mouseClass) App._currentMouseClass = mouseClass App.onPointerDown = (event) -> # update pointer if event? $app = $(CONFIG.APP_SELECTOR) offset = $app.offset() UtilsPointer.setPointerFromDownEvent(event, $app.height(), offset.left, offset.top) # trigger pointer event pointerEvent = UtilsPointer.getPointerEvent() pointerEvent.type = EVENTS.pointer_down pointerEvent.target = event.target EventBus.getInstance().trigger(pointerEvent.type, pointerEvent) # before passing event to view, stop propagation when the target of the pointer event is not the game canvas # however, continue pass the event down to the view and let listeners decide whether to use it if !$(CONFIG.GAMECANVAS_SELECTOR).is(event.target) pointerEvent.stopPropagation() Scene.getInstance().getEventBus().trigger(pointerEvent.type, pointerEvent) return true App.onPointerUp = (event) -> # update pointer if event? $app = $(CONFIG.APP_SELECTOR) offset = $app.offset() UtilsPointer.setPointerFromUpEvent(event, $app.height(), offset.left, offset.top) # trigger pointer event pointerEvent = UtilsPointer.getPointerEvent() pointerEvent.type = EVENTS.pointer_up pointerEvent.target = event.target EventBus.getInstance().trigger(pointerEvent.type, pointerEvent) # before passing event to view, stop propagation when the target of the pointer event is not the game canvas # however, continue pass the event down to the view and let listeners decide whether to use it if !$(CONFIG.GAMECANVAS_SELECTOR).is(event.target) pointerEvent.stopPropagation() Scene.getInstance().getEventBus().trigger(pointerEvent.type, pointerEvent) return true App.onPointerMove = (event) -> # update pointer if event? $app = $(CONFIG.APP_SELECTOR) offset = $app.offset() UtilsPointer.setPointerFromMoveEvent(event, $app.height(), offset.left, offset.top) # trigger pointer events pointerEvent = UtilsPointer.getPointerEvent() pointerEvent.type = EVENTS.pointer_move pointerEvent.target = event.target EventBus.getInstance().trigger(pointerEvent.type, pointerEvent) # before passing event to view, stop propagation when the target of the pointer event is not the game canvas # however, continue pass the event down to the view and let listeners decide whether to use it if !$(CONFIG.GAMECANVAS_SELECTOR).is(event.target) pointerEvent.stopPropagation() Scene.getInstance().getEventBus().trigger(pointerEvent.type, pointerEvent) return true App.onPointerWheel = (event) -> # update pointer if event? target = event.target $app = $(CONFIG.APP_SELECTOR) offset = $app.offset() UtilsPointer.setPointerFromWheelEvent(event.originalEvent, $app.height(), offset.left, offset.top) # trigger pointer events pointerEvent = UtilsPointer.getPointerEvent() pointerEvent.type = EVENTS.pointer_wheel pointerEvent.target = target EventBus.getInstance().trigger(pointerEvent.type, pointerEvent) # before passing event to view, stop propagation when the target of the pointer event is not the game canvas # however, continue pass the event down to the view and let listeners decide whether to use it if !$(CONFIG.GAMECANVAS_SELECTOR).is(target) pointerEvent.stopPropagation() Scene.getInstance().getEventBus().trigger(pointerEvent.type, pointerEvent) return true # # --- Game Invites ---- # # App._inviteAccepted = ()-> Logger.module("APPLICATION").log("App._inviteAccepted") App.showPlay(SDK.PlayModes.Friend) App._inviteRejected = () -> Logger.module("APPLICATION").log("App._inviteRejected") return App.main().then(() -> return NavigationManager.getInstance().showDialogView(new PromptDialogItemView({title: i18next.t("buddy_list.message_rejected_game_invite")})) ) App._inviteCancelled = () -> App._cleanupMatchmakingListeners() Logger.module("APPLICATION").log("App._inviteCancelled") return App.main().then(() -> return NavigationManager.getInstance().showDialogView(new PromptDialogItemView({title: i18next.t("buddy_list.message_cancelled_game_invite")})) ) # # --- Game Spectate ---- # # App._spectateGame = (e) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._spectateGame -> cannot start game when already in a game!") return gameListingData = e.gameData playerId = e.playerId spectateToken = e.token Logger.module("APPLICATION").log("App._spectateGame", gameListingData) NavigationManager.getInstance().showDialogForLoad() .then ()-> # load resources for game return PackageManager.getInstance().loadGamePackageWithoutActivation([ gameListingData["faction_id"], gameListingData["opponent_faction_id"] ]) .then () -> # listen to join game events joinGamePromise = App._subscribeToJoinGameEventsPromise() # join game and if a game server is assigned to this listing, connect there SDK.NetworkManager.getInstance().connect(gameListingData["game_id"], playerId, gameListingData["game_server"], ProfileManager.getInstance().get('id'), spectateToken) return joinGamePromise.then((gameSessionData) -> # reset and deserialize SDK.GameSession.reset() SDK.GameSession.getInstance().deserializeSessionFromFirebase(gameSessionData) SDK.GameSession.getInstance().setUserId(playerId) SDK.GameSession.getInstance().setIsSpectateMode(true) # do not start games that are already over if !SDK.GameSession.getInstance().isOver() return App._startGame() else return Promise.reject() ).catch((errorMessage) -> return App._error(errorMessage) ) # See games_manager spectateBuddyGame method, works same way App.spectateBuddyGame = (buddyId) -> return new Promise (resolve, reject) -> request = $.ajax({ url: process.env.API_URL + '/api/me/spectate/' + buddyId, type: 'GET', contentType: 'application/json', dataType: 'json' }) request.done (response) -> App._spectateGame({ gameData: response.gameData, token: response.token, playerId: buddyId }) resolve(response) request.fail (response) -> error = response && response.responseJSON && response.responseJSON.error || 'SPECTATE request failed' EventBus.getInstance().trigger(EVENTS.ajax_error, error) reject(new Error(error)) # Event handler fired when spectate is pressed in Discord with spectateSecret passed in # We use the buddyId as the spectateSecret App.onDiscordSpectate = (args...) -> buddyId = args[0] Logger.module("DISCORD").log("attempting to spectate #{buddyId}") # we wait until managers are loaded as we need to be logged in return App.managersReadyDeferred.promise.then () -> # do nothing if they are already in game or in queue if ChatManager.getInstance().getStatusIsInBattle() || ChatManager.getInstance().getStatusQueue() Logger.module("DISCORD").log("cannot spectate game when already in a game!") return # do nothing if they are attempting to spectate theirselves if ProfileManager.getInstance().get('id') == buddyId Logger.module("DISCORD").log("cannot spectate yourself!") return # fire spectate request return App.main().then () -> App.spectateBuddyGame(buddyId) # # --- Game Matchmaking ---- # # App._error = (errorMessage) -> Logger.module("APPLICATION").log("App._error", errorMessage) # always unlock user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationUnlocked(App._userNavLockId) if errorMessage? # if we're in the process of loading the main menu # show the error dialog and don't go to main menu # to avoid infinite loop of loading main menu if App._mainPromise or process.env.NODE_ENV == "local" return NavigationManager.getInstance().showDialogView(new ErrorDialogItemView({message:errorMessage})) else # otherwise load the main menu and show the error dialog return App.main().then () -> return NavigationManager.getInstance().showDialogView(new ErrorDialogItemView({message:errorMessage})) else return App.main() App._cleanupMatchmakingListeners = ()-> # remove all found game listeners as new ones will be registered when we re-enter matchmaking GamesManager.getInstance().off("found_game") # force reject the existing found game promise when we cancel # this is important because this promise is wrapped around the "found_game" event and a chain of stuff is waiting for it to resolve! # if we don't cancel here, we will have a promise that never resolves and thus leaks memory if App._foundGamePromise? App._foundGamePromise.cancel() App._matchmakingStart = () -> Logger.module("APPLICATION").log("App._matchmakingStart") App._matchmakingCancel = () -> Logger.module("APPLICATION").log("App._matchmakingCancel") App._cleanupMatchmakingListeners() App._matchmakingError = (errorMessage) -> Logger.module("APPLICATION").log("App._matchmakingError", errorMessage) App._cleanupMatchmakingListeners() return App._error(errorMessage) App._playerDataFromGameListingData = (gameListingData) -> myPlayerIsPlayer1 = gameListingData.is_player_1 playerDataModel= new Backbone.Model({ myPlayerIsPlayer1: myPlayerIsPlayer1 myPlayerId: ProfileManager.getInstance().get('id') myPlayerUsername: ProfileManager.getInstance().get("username") myPlayerFactionId: gameListingData.faction_id myPlayerGeneralId: gameListingData.general_id opponentPlayerId: gameListingData.opponent_id opponentPlayerUsername: gameListingData.opponent_username opponentPlayerFactionId: gameListingData.opponent_faction_id opponentPlayerGeneralId: gameListingData.opponent_general_id }) if myPlayerIsPlayer1 playerDataModel.set({ player1Id: playerDataModel.get("myPlayerId"), player1Username: playerDataModel.get("myPlayerUsername"), player1FactionId: playerDataModel.get("myPlayerFactionId"), player1GeneralId: playerDataModel.get("myPlayerGeneralId"), player2Id: playerDataModel.get("opponentPlayerId"), player2Username: playerDataModel.get("opponentPlayerUsername"), player2FactionId: playerDataModel.get("opponentPlayerFactionId"), player2GeneralId: playerDataModel.get("opponentPlayerGeneralId") }) else playerDataModel.set({ player1Id: playerDataModel.get("opponentPlayerId"), player1Username: playerDataModel.get("opponentPlayerUsername"), player1FactionId: playerDataModel.get("opponentPlayerFactionId"), player1GeneralId: playerDataModel.get("opponentPlayerGeneralId"), player2Id: playerDataModel.get("myPlayerId"), player2Username: playerDataModel.get("myPlayerUsername"), player2FactionId: playerDataModel.get("myPlayerFactionId"), player2GeneralId: playerDataModel.get("myPlayerGeneralId") }) return playerDataModel App._findingGame = (gameMatchRequestData) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._findingGame -> cannot start game when already in a game!") return Logger.module("APPLICATION").log("App._findingGame", gameMatchRequestData) # analytics call Analytics.page("Finding Game",{ path: "/#finding_game" }) # notify Discord status if Discord presence = { instance: 0 largeImageKey: 'idle' } if gameMatchRequestData.gameType == 'ranked' presence.details = 'In Ranked Queue' else if gameMatchRequestData.gameType == 'gauntlet' presence.details = 'In Gauntlet Queue' else if gameMatchRequestData.gameType == 'rift' presence.details = 'In Rift Queue' else presence.details = 'In Queue' Discord.updatePresence(presence) # set the chat presence status to in-queue so your buddies see that you're unreachable ChatManager.getInstance().setStatus(ChatManager.STATUS_QUEUE) # add route NavigationManager.getInstance().addMajorRoute("finding_game", App._findingGame, App, [gameMatchRequestData]) # initialize finding game view findingGameItemView = new FindingGameItemView({model: new Backbone.Model({gameType: gameMatchRequestData.gameType, factionId: gameMatchRequestData.factionId, generalId: gameMatchRequestData.generalId})}) # initialize found game promise gameListingData = null # load find game assets and show finding game showFindingGamePromise = PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> return Promise.all([ Scene.getInstance().showContentByClass(PlayLayer, true), Scene.getInstance().showFindingGame(gameMatchRequestData.factionId, gameMatchRequestData.generalId), NavigationManager.getInstance().showContentView(findingGameItemView), NavigationManager.getInstance().showUtilityView(new UtilityMatchmakingMenuItemView({model: ProfileManager.getInstance().profile})) ]) ) # load my game assets as soon as possible loadGamePromise = showFindingGamePromise.then () -> Logger.module("APPLICATION").log("App._findingGame -> showFindingGamePromise DONE") return PackageManager.getInstance().loadGamePackageWithoutActivation([gameMatchRequestData.factionId]) # save this promise to app object so it can be cancelled in the event of "cancelMatchmaking" # this is important because this promise is wrapped around the "found_game" event and a chain of stuff is waiting for it to resolve! # if we don't cancel this later, we will have a promise that never resolves and thus leaks memory App._foundGamePromise = new Promise((resolve, reject) -> # listen for next found game onFoundGame = (foundGameListingData) -> Logger.module("APPLICATION").log("App._findingGame -> onFoundGame()", foundGameListingData) # stop listening GamesManager.getInstance().off("found_game", onFoundGame) # store found data gameListingData = foundGameListingData showFindingGamePromise.then () -> # don't allow user triggered navigation now that we've found a game NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) NavigationManager.getInstance().destroyNonContentViews() Logger.module("APPLICATION").log("App._findingGame -> onFoundGame() App._foundGamePromise RESOLVED") resolve(foundGameListingData) GamesManager.getInstance().once("found_game", onFoundGame) ).cancellable() # wait show finding game and found game, then join found game return Promise.all([ showFindingGamePromise, App._foundGamePromise ]).then(() -> Logger.module("APPLICATION").log("App._findingGame -> show found game", gameListingData) # analytics call Analytics.page("Found Game",{ path: "/#found_game" }) # get found game data from game listing data playerDataModel = App._playerDataFromGameListingData(gameListingData) # show found game return Promise.all([ Scene.getInstance().showVsForGame(playerDataModel.get("myPlayerFactionId"), playerDataModel.get("opponentPlayerFactionId"), playerDataModel.get("myPlayerIsPlayer1"), CONFIG.ANIMATE_MEDIUM_DURATION, playerDataModel.get("myPlayerGeneralId"), playerDataModel.get("opponentPlayerGeneralId")), Scene.getInstance().showNewGame(playerDataModel.get("player1GeneralId"), playerDataModel.get("player2GeneralId")), findingGameItemView.showFoundGame(playerDataModel) ]).then(() -> # join found game return App._joinGame(gameListingData, loadGamePromise) ) ).catch Promise.CancellationError, (e)-> Logger.module("APPLICATION").log("App._findingGame -> promise chain cancelled") App._resumeGame = (lastGameModel) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._resumeGame -> cannot start game when already in a game!") return gameListingData = lastGameModel?.attributes Logger.module("APPLICATION").log("App._resumeGame", gameListingData) # analytics call Analytics.page("Resume Game",{ path: "/#resume_game" }) # set status to in game ChatManager.getInstance().setStatus(ChatManager.STATUS_GAME) # get resume game data from game listing data playerDataModel= App._playerDataFromGameListingData(gameListingData) # playerDataModel.set("gameModel", lastGameModel) # initialize resume ui gameResumeItemView = new ResumeGameItemView({model: playerDataModel}) # initialize continue promise continueGamePromise = new Promise((resolve, reject) -> onContinueGame = () -> stopListeningForContinueGame() # don't allow user triggered navigation now that user has decided to continue NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) NavigationManager.getInstance().destroyNonContentViews() resolve() onCancelContinueGame = (errorMessage) -> stopListeningForContinueGame() # don't try to reconnect to this game again lastGameModel.set("cancel_reconnect",true) reject(errorMessage) stopListeningForContinueGame = () -> gameResumeItemView.stopListening(gameResumeItemView, "continue", onContinueGame) gameResumeItemView.stopListening(lastGameModel, "change") gameResumeItemView.stopListening(NavigationManager.getInstance(), "user_triggered_cancel", onContinueGame) # listen for continue gameResumeItemView.listenToOnce(gameResumeItemView, "continue", onContinueGame) # listen for game over gameResumeItemView.listenTo(lastGameModel, "change", () -> if lastGameModel.get("status") == "over" then onCancelContinueGame("Oops... looks like that game is over!") ) # listen for cancel gameResumeItemView.listenTo(NavigationManager.getInstance(), EVENTS.user_triggered_cancel, () -> if !NavigationManager.getInstance().getIsShowingModalView() then onCancelContinueGame() ) ) # load assets loadAndShowResumeGamePromise = PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # show UI return Promise.all([ Scene.getInstance().showContentByClass(PlayLayer, true), Scene.getInstance().showVsForGame(playerDataModel.get("myPlayerFactionId"), playerDataModel.get("opponentPlayerFactionId"), playerDataModel.get("myPlayerIsPlayer1"), CONFIG.ANIMATE_MEDIUM_DURATION, playerDataModel.get("myPlayerGeneralId"), playerDataModel.get("opponentPlayerGeneralId")), NavigationManager.getInstance().showContentView(gameResumeItemView), NavigationManager.getInstance().showUtilityView(new UtilityMatchmakingMenuItemView({model: ProfileManager.getInstance().profile})) ]) ) # wait for load, show resume game, and click continue, then join in progress game Promise.all([ loadAndShowResumeGamePromise, continueGamePromise ]).then(() -> Logger.module("APPLICATION").log("App._resumeGame -> joining game") # join found game return App._joinGame(gameListingData) ).catch((errorMessage) -> return App._error(errorMessage) ) # only return show promise return loadAndShowResumeGamePromise # # --- Single Player ---- # # App._startSinglePlayerGame = (myPlayerDeck, myPlayerFactionId, myPlayerGeneralId, myPlayerCardBackId, myPlayerBattleMapId, aiGeneralId, aiDifficulty, aiNumRandomCards) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._startSinglePlayerGame -> cannot start game when already in a game!") return Logger.module("APPLICATION").log("App._startSinglePlayerGame") # analytics call Analytics.page("Single Player Game",{ path: "/#single_player" }) # set status to in game ChatManager.getInstance().setStatus(ChatManager.STATUS_GAME) aiGeneralName = null aiGeneralCard = SDK.GameSession.getCardCaches().getCardById(aiGeneralId) if (aiGeneralCard?) aiGeneralName = aiGeneralCard.getName() # request single player game App._singlePlayerGamePromise = new Promise((resolve, reject) -> request = $.ajax url: process.env.API_URL + '/api/me/games/single_player', data: JSON.stringify({ deck: myPlayerDeck, cardBackId: myPlayerCardBackId, battleMapId: myPlayerBattleMapId, hasPremiumBattleMaps: InventoryManager.getInstance().hasAnyBattleMapCosmetics(), ai_general_id: aiGeneralId, ai_difficulty: aiDifficulty, ai_num_random_cards: aiNumRandomCards, ai_username: aiGeneralName }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve(res) request.fail (jqXHR)-> reject(jqXHR and jqXHR.responseJSON and (jqXHR.responseJSON.error or jqXHR.responseJSON.message) or "Connection error. Please retry.") ).cancellable() # init finding game view findingGameItemView = new FindingGameItemView({model: new Backbone.Model({gameType: SDK.GameType.SinglePlayer})}) findingGameItemView.listenTo(findingGameItemView, "destroy", App._cancelSinglePlayer) # show ui return Promise.all([ Scene.getInstance().showContentByClass(PlayLayer, true), Scene.getInstance().showFindingGame(myPlayerFactionId, myPlayerGeneralId), NavigationManager.getInstance().showContentView(findingGameItemView), NavigationManager.getInstance().showUtilityView(new UtilityMatchmakingMenuItemView({model: ProfileManager.getInstance().profile})) ]).then(() -> # when we have single player game data return App._singlePlayerGamePromise?.then((gameListingData) -> App._singlePlayerGamePromise = null # don't allow user triggered navigation now that we've found a game NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) # get found game data from game listing data playerDataModel = App._playerDataFromGameListingData(gameListingData) # show found game return Promise.all([ Scene.getInstance().showVsForGame(playerDataModel.get("myPlayerFactionId"), playerDataModel.get("opponentPlayerFactionId"), playerDataModel.get("myPlayerIsPlayer1"), CONFIG.ANIMATE_MEDIUM_DURATION, playerDataModel.get("myPlayerGeneralId"), playerDataModel.get("opponentPlayerGeneralId")), Scene.getInstance().showNewGame(playerDataModel.get("player1GeneralId"), playerDataModel.get("player2GeneralId")), NavigationManager.getInstance().destroyNonContentViews(), findingGameItemView.showFoundGame(playerDataModel) ]).then(() -> # join found game return App._joinGame(gameListingData) ) ) ).catch(Promise.CancellationError, (e)-> Logger.module("APPLICATION").log("App:_startSinglePlayerGame -> promise chain cancelled") ).catch((errorMessage) -> return App._error(if errorMessage? then "Failed to start single player game: " + errorMessage) ) App._cancelSinglePlayer = () -> if App._singlePlayerGamePromise? App._singlePlayerGamePromise.cancel() App._singlePlayerGamePromise = null App._startBossBattleGame = (myPlayerDeck, myPlayerFactionId, myPlayerGeneralId, myPlayerCardBackId, myPlayerBattleMapId, aiGeneralId) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._startBossBattleGame -> cannot start game when already in a game!") return Logger.module("APPLICATION").log("App._startBossBattleGame") # analytics call Analytics.page("Boss Battle Game",{ path: "/#boss_battle" }) # don't allow user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) # set user as in game ChatManager.getInstance().setStatus(ChatManager.STATUS_GAME) aiGeneralName = null aiGeneralCard = SDK.GameSession.getCardCaches().getCardById(aiGeneralId) if (aiGeneralCard?) aiGeneralName = aiGeneralCard.getName() # request boss battle game bossBattleGamePromise = new Promise((resolve, reject) -> request = $.ajax url: process.env.API_URL + '/api/me/games/boss_battle', data: JSON.stringify({ deck: myPlayerDeck, cardBackId: myPlayerCardBackId, battleMapId: myPlayerBattleMapId, ai_general_id: aiGeneralId, ai_username: aiGeneralName }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve(res) request.fail (jqXHR)-> reject(jqXHR and jqXHR.responseJSON and (jqXHR.responseJSON.error or jqXHR.responseJSON.message) or "Connection error. Please retry.") ) # get ui promise if CONFIG.LOAD_ALL_AT_START ui_promise = Promise.resolve() else ui_promise = NavigationManager.getInstance().showDialogForLoad() return Promise.all([ bossBattleGamePromise, ui_promise ]).spread (gameListingData) -> return App._joinGame(gameListingData) .catch (errorMessage) -> return App._error(if errorMessage? then "Failed to start boss battle: " + errorMessage) # # --- Replays ---- # # App._startGameForReplay = (replayData) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._startGameForReplay -> cannot start game when already in a game!") return userId = replayData.userId gameId = replayData.gameId replayId = replayData.replayId promotedDivisionName = replayData.promotedDivisionName # check for invalid replay data if !replayId? if !gameId? throw new Error("Cannot replay game without game id!") if !userId? and !promotedDivisionName? throw new Error("Cannot replay game without user id or division name!") # don't allow user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) # show loading return NavigationManager.getInstance().showDialogForLoad() .bind {} .then () -> # load replay data if replayId? url = "#{process.env.API_URL}/replays/#{replayId}" else if promotedDivisionName? url = "#{process.env.API_URL}/api/me/games/watchable/#{promotedDivisionName}/#{gameId}/replay_data?playerId=#{userId}" else url = "#{process.env.API_URL}/api/users/#{userId}/games/#{gameId}/replay_data" return new Promise (resolve, reject) -> request = $.ajax({ url: url , type: 'GET', contentType: 'application/json', dataType: 'json' }) request.done (response)-> resolve(response) .fail (response)-> reject(new Error("Error downloading replay data: #{response?.responseJSON?.message}")) .then (replayResponseData) -> @.replayResponseData = replayResponseData gameSessionData = replayResponseData.gameSessionData gameUIData = replayResponseData.mouseUIData replayData = replayResponseData.replayData # validate data gameSetupData = gameSessionData?.gameSetupData if !gameSetupData? throw new Error("ReplayEngine -> loaded game does not have valid replay data!") # store data @_loadedGameSessionData = gameSessionData @_loadedGameUIEventData = gameUIData # load resources for game return PackageManager.getInstance().loadGamePackageWithoutActivation([ gameSetupData.players[0].factionId gameSetupData.players[1].factionId ]) .then () -> # create new game instance but don't deserialize from existing data SDK.GameSession.reset() if userId? # if we explicity requested to spectate a user perspective SDK.GameSession.getInstance().setUserId(userId) else if @.replayResponseData?.replayData # check if the server response includes a shared replay record so we can use that to determine who to spectate SDK.GameSession.getInstance().setUserId(@.replayResponseData?.replayData.user_id) else # ultimately spectate player 1 if nothing provided SDK.GameSession.getInstance().setUserId(@_loadedGameSessionData.players[0].playerId) SDK.GameSession.getInstance().setGameType(@_loadedGameSessionData.gameType) SDK.GameSession.getInstance().setIsRunningAsAuthoritative(false) SDK.GameSession.getInstance().setIsSpectateMode(true) SDK.GameSession.getInstance().setIsReplay(true) # setup GameSession from replay data SDK.GameSetup.setupNewSessionFromExistingSessionData(SDK.GameSession.getInstance(), @_loadedGameSessionData) return App._startGame() .then () -> # start watching replay ReplayEngine.getInstance().watchReplay(@_loadedGameSessionData, @_loadedGameUIEventData) .catch (errorMessage) -> ReplayEngine.getInstance().stopCurrentReplay() return App._error(errorMessage) # # --- Game Connecting ---- # # App._unsubscribeFromJoinGameEvents = () -> SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.join_game) SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.reconnect_failed) App._subscribeToJoinGameEventsPromise = () -> App._unsubscribeFromJoinGameEvents() return new Promise((resolve, reject) -> # wait for join_game event SDK.NetworkManager.getInstance().getEventBus().once(EVENTS.join_game, (response) -> # handle response if response.error reject(response.error) else resolve(response.gameSessionData) ) SDK.NetworkManager.getInstance().getEventBus().once(EVENTS.spectate_game, (response) -> # handle response if response.error reject(response.error) else resolve(response.gameSessionData) ) # wait for reconnect_failed event SDK.NetworkManager.getInstance().getEventBus().once(EVENTS.reconnect_failed, () -> # reject and cancel reconnect reject("Reconnect failed!") ) ).finally(() -> # reset join game listeners App._unsubscribeFromJoinGameEvents() ) App._joinGame = (gameListingData, loadMyGameResourcesPromise, loadOpponentGameResourcesPromise) -> Logger.module("APPLICATION").log("App._joinGame", gameListingData) # load my resources for game loadMyGameResourcesPromise ?= PackageManager.getInstance().loadGamePackageWithoutActivation([gameListingData["faction_id"]]) # load opponent resources for game loadOpponentGameResourcesPromise ?= PackageManager.getInstance().loadMinorPackage(PKGS.getFactionGamePkgIdentifier(gameListingData["opponent_faction_id"]), null, "game") return Promise.all([ loadMyGameResourcesPromise, loadOpponentGameResourcesPromise ]).then(() -> # listen to join game events joinGamePromise = App._subscribeToJoinGameEventsPromise() # join game and if a game server is assigned to this listing, connect there SDK.NetworkManager.getInstance().connect(gameListingData["game_id"], ProfileManager.getInstance().get('id'), gameListingData["game_server"]) return joinGamePromise.then((gameSessionData) -> return App._startGameWithData(gameSessionData) ).catch((errorMessage) -> return App._error(errorMessage) ) ) App._onReconnectToGame = (gameId) -> Logger.module("APPLICATION").log("App._onReconnectToGame", gameId) # destroy the current game App.cleanupGame() # start listening to join game events joinGamePromise = App._subscribeToJoinGameEventsPromise() # blur the view in engine Scene.getInstance().getFX().requestBlurScreen(App._screenBlurId) return Promise.all([ # show user we're reconnecting NavigationManager.getInstance().showContentView(new ReconnectToGameItemView()), NavigationManager.getInstance().showUtilityView(new UtilityMatchmakingMenuItemView({model: ProfileManager.getInstance().profile})) ]).then(() -> return joinGamePromise.then((gameSessionData) -> # start game return App._startGameWithData(gameSessionData) ).catch((errorMessage) -> return App._error(errorMessage) ).finally(() -> App.cleanupReconnectToGame() ) ) App.cleanupReconnectToGame = () -> # unsubscribe from events App._unsubscribeFromJoinGameEvents() # unblur screen Scene.getInstance().getFX().requestUnblurScreen(App._screenBlurId) # # --- Game Events ---- # # App._onNetworkGameEvent = (eventData) -> if (eventData.type == EVENTS.step) Logger.module("APPLICATION").log("App._onNetworkGameEvent -> step", eventData) # step event if eventData.step? # deserialize step sdkStep = SDK.GameSession.getInstance().deserializeStepFromFirebase(eventData.step) # if we are spectating, and connected in the middle of a followup (so we don't have a snapshot), error out to main menu in the event of a rollback since we have nothing to roll back to if (SDK.GameSession.getInstance().getIsSpectateMode() and sdkStep.getAction() instanceof SDK.RollbackToSnapshotAction and !SDK.GameSession.getInstance().getRollbackSnapshotData()) return App._error("You fell out of sync. Please try to spectate again to sync up.") # mark step as transmitted sdkStep.setTransmitted(true) # execute step SDK.GameSession.getInstance().executeAuthoritativeStep(sdkStep) if sdkStep.getAction() AnalyticsTracker.sendAnalyticsForExplicitAction(sdkStep.getAction()) else if (eventData.type == EVENTS.invalid_action) if eventData.playerId == SDK.GameSession.getInstance().getMyPlayerId() if eventData.desync # player is out of sync with server # force them to reconnect to game Analytics.track("player desync", {category:Analytics.EventCategory.Debug}, {nonInteraction:1}) App._error("Your current match appears to be out of sync. To avoid any issues, please select CONTINUE and reconnect to your match.") else # player isn't out of sync but may need to know their action was invalid # this may happen if a player attempts to submit actions after their turn is over SDK.GameSession.getInstance().onAuthoritativeInvalidAction(eventData) else if (eventData.type == EVENTS.network_game_hover) Scene.getInstance().getGameLayer()?.onNetworkHover(eventData) else if (eventData.type == EVENTS.network_game_select) Scene.getInstance().getGameLayer()?.onNetworkSelect(eventData) else if (eventData.type == EVENTS.network_game_mouse_clear) Scene.getInstance().getGameLayer()?.onNetworkMouseClear(eventData) else if (eventData.type == EVENTS.turn_time) # if we are behind in step count for some reason from the server step counter if (!SDK.GameSession.getInstance().getIsSpectateMode() and eventData.stepCount > SDK.GameSession.getInstance().getStepCount()) # we're going to start a pseudo-timeout to reload the game Logger.module("APPLICATION").warn("App._onNetworkGameEvent -> seems like game session is behind server step count") # if we haven't already detected a potential desync state and recorded the moment it started if not App._gameDesyncStartedAt # record the moment the suspected desync started App._gameDesyncStartedAt = moment.utc() # otherwise if we suspect a desync state is already in progress and we have the time it started, see if it's been more than 10s else if moment.duration(moment.utc() - App._gameDesyncStartedAt).asSeconds() > 10.0 # if it's been more than 10s in a desync state, fire off the error state App._error("Your current match appears to be out of sync. To avoid any issues, please select CONTINUE and reconnect to your match.") App._gameDesyncStartedAt = null return else # if we're up to date with our step count, just clear out any suspected desync starting point App._gameDesyncStartedAt = null # the game session emits events from here that inform UI etc. SDK.GameSession.getInstance().setTurnTimeRemaining(eventData.time) else if (eventData.type == EVENTS.show_emote) EventBus.getInstance().trigger(EVENTS.show_emote, eventData) App._onOpponentConnectionStatusChanged = (eventData) -> # when opponent disconnects, force mouse clear if !SDK.NetworkManager.getInstance().isOpponentConnected Scene.getInstance().getGameLayer()?.onNetworkMouseClear({type:EVENTS.network_game_mouse_clear, timestamp: Date.now()}) App._onNetworkGameError = (errorData) -> return App._error(JSON.stringify(errorData)) App._onGameServerShutdown = (errorData) -> if errorData.ip ip = errorData.ip lastGameModel = GamesManager.getInstance().playerGames.first() lastGameModel.set('gameServer',ip) # reconnect SDK.NetworkManager.getInstance().reconnect(ip) # show reconnecting return App._onReconnectToGame() else return App._error("Game server error, no ip!") # # --- Game Setup ---- # # App._startGameWithChallenge = (challenge) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._startGameWithChallenge -> cannot start game when already in a game!") return Logger.module("APPLICATION").log("App:_startGameWithChallenge") # don't allow user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) # set user as in game ChatManager.getInstance().setStatus(ChatManager.STATUS_CHALLENGE) if not challenge instanceof SDK.ChallengeRemote # mark challenge as attempted ProgressionManager.getInstance().markChallengeAsAttemptedWithType(challenge.type); # challenge handles setting up game session SDK.GameSession.reset() SDK.GameSession.getInstance().setUserId(ProfileManager.getInstance().get('id')) challenge.setupSession(SDK.GameSession.getInstance()) # get ui promise if CONFIG.LOAD_ALL_AT_START ui_promise = Promise.resolve() else ui_promise = NavigationManager.getInstance().showDialogForLoad() return ui_promise.then () -> return PackageManager.getInstance().loadGamePackageWithoutActivation([ SDK.GameSession.getInstance().getGeneralForPlayer1().getFactionId(), SDK.GameSession.getInstance().getGeneralForPlayer2().getFactionId() ], [ "tutorial", PKGS.getChallengePkgIdentifier(SDK.GameSession.getInstance().getChallenge().getType()) ]) .then () -> return App._startGame() .catch (errorMessage) -> return App._error(errorMessage) App._startGameWithData = (sessionData) -> Logger.module("APPLICATION").log("App._startGameWithData", sessionData) # reset and deserialize SDK.GameSession.reset() SDK.GameSession.getInstance().deserializeSessionFromFirebase(sessionData) SDK.GameSession.getInstance().setUserId(ProfileManager.getInstance().get('id')) # do not start games that are already over if !SDK.GameSession.getInstance().isOver() return App._startGame() else return Promise.reject() App._startGame = () -> gameSession = SDK.GameSession.getInstance() Logger.module("APPLICATION").log("App:_startGame", gameSession.getStatus()) if gameSession.getIsSpectateMode() ChatManager.getInstance().setStatus(ChatManager.STATUS_WATCHING) else if gameSession.isChallenge() ChatManager.getInstance().setStatus(ChatManager.STATUS_CHALLENGE) else ChatManager.getInstance().setStatus(ChatManager.STATUS_GAME) NotificationsManager.getInstance().dismissNotificationsThatCantBeShown() if Discord getFactionImage = (factionId, opponent = false) -> s = {key: '', text: ''} switch factionId when 1 then s = {key: 'f1', text: 'Lyonar'} when 2 then s = {key: 'f2', text: 'Songhai'} when 3 then s = {key: 'f3', text: 'Vetruvian'} when 4 then s = {key: 'f4', text: 'Abyssian'} when 5 then s = {key: 'f5', text: 'Magmar'} when 6 then s = {key: 'f6', text: 'Vanar'} else s = {key: 'neutral', text: 'Neutral'} if opponent s.key += '_small' return s opponentName = SDK.GameSession.getInstance().getOpponentPlayer().getUsername() opponentFaction = SDK.GameSession.getInstance().getGeneralForPlayer(SDK.GameSession.getInstance().getOpponentPlayer()).factionId opponentFactionImage = getFactionImage(opponentFaction, true) playerName = SDK.GameSession.getInstance().getMyPlayer().getUsername() playerId = SDK.GameSession.getInstance().getMyPlayerId() playerRank = GamesManager.getInstance().getCurrentRank() playerFaction = SDK.GameSession.getInstance().getGeneralForPlayer(SDK.GameSession.getInstance().getMyPlayer()).factionId playerFactionImage = getFactionImage(playerFaction, false) presence = { startTimestamp: Math.floor((new Date).getTime()/1000), instance: 1 largeImageKey: playerFactionImage.key largeImageText: playerFactionImage.text smallImageKey: opponentFactionImage.key smallImageText: opponentFactionImage.text } if gameSession.getIsSpectateMode() if gameSession.getIsReplay() presence.details = "Watching: #{playerName} vs. #{opponentName} replay" presence.state = "Spectating" else presence.details = "Watching: #{playerName} vs. #{opponentName} live" presence.state = "Spectating" else if gameSession.isRanked() presence.details = "Ranked: vs. #{opponentName}" presence.state = "In Match" # check if block is enabled before allowing spectate if !ProfileManager.getInstance().profile.get("blockSpectators") presence.spectateSecret = playerId else if gameSession.isGauntlet() presence.details = "Gauntlet: vs. #{opponentName}" presence.state = "In Match" # check if block is enabled before allowing spectate if !ProfileManager.getInstance().profile.get("blockSpectators") presence.spectateSecret = playerId else if gameSession.isRift() presence.details = "Rift: vs. #{opponentName}" presence.state = "In Match" # check if block is enabled before allowing spectate if !ProfileManager.getInstance().profile.get("blockSpectators") presence.spectateSecret = playerId else if gameSession.isFriendly() presence.details = "Friendly: vs. #{opponentName}" presence.state = "In Game" # check if block is enabled before allowing spectate if !ProfileManager.getInstance().profile.get("blockSpectators") presence.spectateSecret = playerId else if gameSession.isBossBattle() presence.details = "Boss Battle: vs. #{opponentName}" presence.state = "Playing Solo" else if gameSession.isSinglePlayer() || gameSession.isSandbox() || gameSession.isChallenge() presence.state = "Playing Solo" Discord.updatePresence(presence) # analytics call Analytics.page("Game",{ path: "/#game" }) # reset routes as soon as we lock into a game NavigationManager.getInstance().resetRoutes() # record last game data CONFIG.resetLastGameData() CONFIG.lastGameType = gameSession.getGameType() CONFIG.lastGameWasSpectate = gameSession.getIsSpectateMode() CONFIG.lastGameWasTutorial = gameSession.isTutorial() CONFIG.lastGameWasDeveloper = UtilsEnv.getIsInDevelopment() && gameSession.getIsDeveloperMode() CONFIG.lastGameWasDailyChallenge = gameSession.isDailyChallenge() # listen to game network events App._subscribeToGameNetworkEvents() # get game UI view class challenge = gameSession.getChallenge() if challenge? and !(challenge instanceof SDK.Sandbox) gameUIViewClass = TutorialLayout else gameUIViewClass = GameLayout # load resources for game session load_promises = [ # load battlemap assets required for game PackageManager.getInstance().loadMinorPackage(PKGS.getBattleMapPkgIdentifier(gameSession.getBattleMapTemplate().getMap()), null, "game") ] # load all cards in my player's hand preloaded_package_ids = [] for cardIndex in gameSession.getMyPlayer().getDeck().getHand() card = gameSession.getCardByIndex(cardIndex) if card? # get unique id for card preload card_id = card.id card_pkg_id = PKGS.getCardGamePkgIdentifier(card_id) card_preload_pkg_id = card_pkg_id + "_preload_" + UtilsJavascript.generateIncrementalId() preloaded_package_ids.push(card_preload_pkg_id) load_promises.push(PackageManager.getInstance().loadMinorPackage(card_preload_pkg_id, PKGS.getPkgForIdentifier(card_pkg_id), "game")) # load all cards and modifiers on board for card in gameSession.getBoard().getCards(null, allowUntargetable=true) # get unique id for card preload card_id = card.getId() card_pkg_id = PKGS.getCardGamePkgIdentifier(card_id) card_resources_pkg = PKGS.getPkgForIdentifier(card_pkg_id) card_preload_pkg_id = card_pkg_id + "_preload_" + UtilsJavascript.generateIncrementalId() preloaded_package_ids.push(card_preload_pkg_id) # include signature card resources if card instanceof SDK.Entity and card.getWasGeneral() referenceSignatureCard = card.getReferenceSignatureCard() if referenceSignatureCard? signature_card_id = referenceSignatureCard.getId() signature_card_pkg_id = PKGS.getCardGamePkgIdentifier(signature_card_id) signature_card_resources_pkg = PKGS.getPkgForIdentifier(signature_card_pkg_id) card_resources_pkg = [].concat(card_resources_pkg, signature_card_resources_pkg) # load card resources load_promises.push(PackageManager.getInstance().loadMinorPackage(card_preload_pkg_id, card_resources_pkg, "game")) # modifiers for modifier in card.getModifiers() if modifier? # get unique id for modifier preload modifier_type = modifier.getType() modifier_preload_package_id = modifier_type + "_preload_" + UtilsJavascript.generateIncrementalId() preloaded_package_ids.push(modifier_preload_package_id) load_promises.push(PackageManager.getInstance().loadMinorPackage(modifier_preload_package_id, PKGS.getPkgForIdentifier(modifier_type), "game")) # load artifact card if modifier is applied by an artifact if modifier.getIsFromArtifact() artifact_card = modifier.getSourceCard() if artifact_card? # get unique id for artifact card preload artifact_card_id = artifact_card.getId() artifact_card_pkg_id = PKGS.getCardInspectPkgIdentifier(artifact_card_id) artifact_card_preload_pkg_id = artifact_card_pkg_id + "_preload_" + UtilsJavascript.generateIncrementalId() preloaded_package_ids.push(artifact_card_preload_pkg_id) load_promises.push(PackageManager.getInstance().loadMinorPackage(artifact_card_preload_pkg_id, PKGS.getPkgForIdentifier(artifact_card_pkg_id), "game")) return Promise.all(load_promises).then(() -> # destroy all views/layers return NavigationManager.getInstance().destroyAllViewsAndLayers() ).then(() -> return PackageManager.getInstance().activateGamePackage() ).then(() -> # show game and ui overlay_promise = Scene.getInstance().destroyOverlay() game_promise = Scene.getInstance().showGame() content_promise = NavigationManager.getInstance().showContentView(new gameUIViewClass({challenge: challenge})) utility_promise = NavigationManager.getInstance().showUtilityView(new UtilityGameMenuItemView({model: ProfileManager.getInstance().profile})) # listen to game local events App._subscribeToGameLocalEvents() # wait for game to show as active (not status active) then unload all preloaded packages scene = Scene.getInstance() gameLayer = scene? && scene.getGameLayer() if !gameLayer? or gameLayer.getStatus() == GameLayer.STATUS.ACTIVE PackageManager.getInstance().unloadMajorMinorPackages(preloaded_package_ids) else onActiveGame = () -> gameLayer.getEventBus().off(EVENTS.show_active_game, onActiveGame) gameLayer.getEventBus().off(EVENTS.terminate, onTerminate) PackageManager.getInstance().unloadMajorMinorPackages(preloaded_package_ids) onTerminate = () -> gameLayer.getEventBus().off(EVENTS.show_active_game, onActiveGame) gameLayer.getEventBus().off(EVENTS.terminate, onTerminate) gameLayer.getEventBus().on(EVENTS.show_active_game, onActiveGame) gameLayer.getEventBus().on(EVENTS.terminate, onTerminate) return Promise.all([ overlay_promise, game_promise, content_promise, utility_promise ]) ).then(() -> # enable user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationUnlocked(App._userNavLockId) ) ######## App.onAfterShowEndTurn = () -> Logger.module("APPLICATION").log "App:onAfterShowEndTurn" # if we're playing in sandbox mode, we need to let the player play both sides so we swap players here if SDK.GameSession.getInstance().isSandbox() # swap test user id player1 = SDK.GameSession.getInstance().getPlayer1() player2 = SDK.GameSession.getInstance().getPlayer2() if player1.getIsCurrentPlayer() then SDK.GameSession.getInstance().setUserId(player1.getPlayerId()) else SDK.GameSession.getInstance().setUserId(player2.getPlayerId()) # # --- Game Cleanup ---- # # App.cleanupGame = () -> Logger.module("APPLICATION").log "App.cleanupGame" # cleanup reconnect App.cleanupReconnectToGame() # cleanup events App.cleanupGameEvents() # terminate the game layer Scene.getInstance().getGameLayer()?.terminate() # reset the current instance of the game session SDK.GameSession.reset() App.cleanupGameEvents = () -> Logger.module("APPLICATION").log "App.cleanupGameEvents" # cleanup events App._unsubscribeFromGameLocalEvents() App._unsubscribeFromGameNetworkEvents() # # --- Game Over Views ---- # # App._onGameOver = () -> Logger.module("APPLICATION").log "App:_onGameOver" # start loading data as soon as game is over, don't wait for animations App._startLoadingGameOverData() # disconnect from game room on network side # defer it until the call stack clears so any actions that caused the game to be over get broadcast during the current JS tick _.defer () -> SDK.NetworkManager.getInstance().disconnect() # # --- Game Turn Over---- # # App._onEndTurn = (e) -> AnalyticsTracker.sendAnalyticsForCompletedTurn(e.turn) ###* # This method de-registers all game listeners and initiates the game over screen flow. For visual sequencing purposes, it fires when it recieves an event that all game actions are done showing in the game layer. # @public ### App.onShowGameOver = () -> Logger.module("APPLICATION").log "App:onShowGameOver" # analytics call Analytics.page("Game Over",{ path: "/#game_over" }) App.cleanupGameEvents() App.showVictoryWhenGameDataReady() ###* # Load progression, rank, etc... data after a game is over. # @private ### App._startLoadingGameOverData = ()-> # for specated games, don't load any data if SDK.GameSession.current().getIsSpectateMode() App._gameOverDataThenable = Promise.resolve([null,[]]) return # resolve when the last game is confirmed as "over" whenGameJobsProcessedAsync = new Promise (resolve,reject)-> isGameReady = (gameAttrs,jobAttrs)-> # if game is not over yet, the rest of the data is not valid if gameAttrs.status != SDK.GameStatus.over return false switch gameAttrs.game_type when SDK.GameType.Friendly return isFriendlyGameReady(gameAttrs,jobAttrs) when SDK.GameType.Ranked return isRankedGameReady(gameAttrs,jobAttrs) when SDK.GameType.Casual return isCasualGameReady(gameAttrs,jobAttrs) when SDK.GameType.Gauntlet return isGauntletGameReady(gameAttrs,jobAttrs) when SDK.GameType.SinglePlayer return isSinglePlayerGameReady(gameAttrs,jobAttrs) when SDK.GameType.BossBattle return isBossBattleGameReady(gameAttrs,jobAttrs) when SDK.GameType.Rift return isRiftGameReady(gameAttrs,jobAttrs) else return Promise.resolve() isFriendlyGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_scored return jobAttrs.quests and jobAttrs.faction_progression else return true isRankedGameReady = (gameAttrs,jobAttrs)-> doneProcessing = false if gameAttrs.is_scored doneProcessing = (jobAttrs.rank and jobAttrs.quests and jobAttrs.progression and jobAttrs.faction_progression) else doneProcessing = (jobAttrs.rank) # if we're in diamond or above, wait for ladder, othwerwise don't since it's not guaranteed to process if GamesManager.getInstance().getCurrentRank() <= SDK.RankDivisionLookup.Diamond doneProcessing = doneProcessing and jobAttrs.ladder return doneProcessing isCasualGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_scored return (jobAttrs.quests and jobAttrs.progression and jobAttrs.faction_progression) else return true isGauntletGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_scored return (jobAttrs.gauntlet and jobAttrs.quests and jobAttrs.progression and jobAttrs.faction_progression) else return jobAttrs.gauntlet isSinglePlayerGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_scored return jobAttrs.faction_progression else return true isBossBattleGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_winner return (jobAttrs.progression and jobAttrs.cosmetic_chests and jobAttrs.faction_progression) if gameAttrs.is_scored return jobAttrs.faction_progression else return true isRiftGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_scored doneProcessing = (jobAttrs.rift and jobAttrs.quests) else doneProcessing = (jobAttrs.rift) gameSession = SDK.GameSession.getInstance() lastGameModel = GamesManager.getInstance().playerGames.first() if lastGameModel? and SDK.GameType.isNetworkGameType(gameSession.getGameType()) # lastGameModel.onSyncOrReady().then ()-> if isGameReady(lastGameModel.attributes,lastGameModel.attributes.job_status || {}) resolve([lastGameModel,null]) else lastGameModel.on "change", () -> if isGameReady(lastGameModel.attributes,lastGameModel.attributes.job_status || {}) lastGameModel.off "change" resolve([lastGameModel,null]) else if gameSession.isChallenge() challengeId = gameSession.getChallenge().type if gameSession.getChallenge() instanceof SDK.ChallengeRemote and gameSession.getChallenge().isDaily # Don't process daily challenges run by qa tool if gameSession.getChallenge()._generatedForQA resolve([null,null]) else ProgressionManager.getInstance().completeDailyChallenge(challengeId).then (challengeData)-> challengeModel = new Backbone.Model(challengeData) resolve([null,challengeModel]) else ProgressionManager.getInstance().completeChallengeWithType(challengeId).then (challengeData)-> NewPlayerManager.getInstance().setHasSeenBloodbornSpellInfo() challengeModel = new Backbone.Model(challengeData) resolve([null,challengeModel]) else resolve([null, null]) App._gameOverDataThenable = whenGameJobsProcessedAsync .bind {} .spread (userGameModel,challengeModel)-> @.userGameModel = userGameModel @.challengeModel = challengeModel rewardIds = [] gameSession = SDK.GameSession.getInstance() # Send game based analytics AnalyticsTracker.submitGameOverAnalytics(gameSession,userGameModel) # Mark first game of type completions if gameSession.isRanked() NewPlayerManager.getInstance().setHasPlayedRanked(userGameModel) if gameSession.isSinglePlayer() NewPlayerManager.getInstance().setHasPlayedSinglePlayer(userGameModel) if @.userGameModel?.get('rewards') for rewardId,val of @.userGameModel.get('rewards') rewardIds.push rewardId if @.challengeModel?.get('reward_ids') for rewardId in @.challengeModel.get('reward_ids') rewardIds.push rewardId return rewardIds .then (rewardIds)-> allPromises = [] if rewardIds? for rewardId in rewardIds rewardModel = new DuelystBackbone.Model() rewardModel.url = process.env.API_URL + "/api/me/rewards/#{rewardId}" rewardModel.fetch() allPromises.push rewardModel.onSyncOrReady() return Promise.all(allPromises) .then (allRewardModels)-> @.rewardModels = allRewardModels # if we're not done with core progression if not NewPlayerManager.getInstance().isCoreProgressionDone() return NewPlayerManager.getInstance().updateCoreState() else return Promise.resolve() .then (newPlayerProgressionData)-> if newPlayerProgressionData?.quests @.newBeginnerQuestsCollection = new Backbone.Collection(newPlayerProgressionData?.quests) else @.newBeginnerQuestsCollection = new Backbone.Collection() .then ()-> # if we're at a stage where we should start generating daily quests, request them in case any of the quest slots opened up if NewPlayerManager.getInstance().shouldStartGeneratingDailyQuests() return QuestsManager.getInstance().requestNewDailyQuests() else return Promise.resolve() .then ()-> return Promise.all([@.userGameModel,@.rewardModels,@.newBeginnerQuestsCollection]) # don't wait more than ~10 seconds .timeout(10000) ###* # Shows the victory screen after a game is over, all data is loaded, and assets for victory screen are allocated. # @public ### App.showVictoryWhenGameDataReady = () -> # show activity dialog NavigationManager.getInstance().showDialogView(new ActivityDialogItemView()); # resolve when post game assets are done loading return PackageManager.getInstance().loadMinorPackage("postgame") .then ()-> return App._gameOverDataThenable .spread (userGameModel,rewardModels,newBeginnerQuestsCollection)-> if not rewardModels throw new Error() # destroy dialog NavigationManager.getInstance().destroyDialogView() # terminate game layer as we no longer need it to be active Scene.getInstance().getGameLayer()?.terminate() # show victory App.showVictory(userGameModel,rewardModels,newBeginnerQuestsCollection) .catch Promise.TimeoutError, (e) -> # hide dialog NavigationManager.getInstance().destroyDialogView() App._error("We're experiencing some delays in processing your game. Don't worry, you can keep playing and you'll receive credit shortly.") .catch (e)-> # hide dialog NavigationManager.getInstance().destroyDialogView() App._error(e.message) ###* # Shows the victory screen after a game is over. # @public # @param {Backbone.Model} userGameModel Game model that is finished loading / processing all jobs. # @param {Array} rewardModels Rewards that this game needs to show. # @param {Backbone.Collection} newBeginnerQuestsCollection Collection of new beginner quests as of game completion ### App.showVictory = (userGameModel,rewardModels,newBeginnerQuestsCollection) -> Logger.module("APPLICATION").log "App:showVictory" if not SDK.GameSession.getInstance().getIsSpectateMode() and SDK.GameType.isNetworkGameType(SDK.GameSession.getInstance().getGameType()) faction_id = userGameModel.get('faction_id') faction_xp = userGameModel.get('faction_xp') faction_xp_earned = userGameModel.get('faction_xp_earned') faction_level = SDK.FactionProgression.levelForXP(faction_xp + faction_xp_earned) faction_prog_reward = SDK.FactionProgression.rewardDataForLevel(faction_id,faction_level) if SDK.FactionProgression.hasLeveledUp(faction_xp + faction_xp_earned, faction_xp_earned) and faction_prog_reward App.setCallbackWhenCancel(App.showFactionXpReward.bind(App,userGameModel,rewardModels)) else if SDK.GameSession.getInstance().isRanked() App.setCallbackWhenCancel(App.showLadderProgress.bind(App,userGameModel,rewardModels)) else if SDK.GameSession.getInstance().isRift() App.setCallbackWhenCancel(App.showRiftProgress.bind(App,userGameModel,rewardModels)) else App.addNextScreenCallbackToVictoryFlow(rewardModels) else # local games if SDK.GameSession.getInstance().isChallenge() # for challenges App.addNextScreenCallbackToVictoryFlow(rewardModels); userGameModel ?= new Backbone.Model({}) return Promise.all([ Scene.getInstance().showOverlay(new VictoryLayer()) NavigationManager.getInstance().showContentView(new VictoryItemView({model:userGameModel || new Backbone.Model({})})) ]) ###* # Shows the next screen in the victory order: rank, quests, rewards etc. # @public # @param {Backbone.Model} userGameModel Game model that is finished loading / processing all jobs. # @param {Array} rewardModels Rewards that this game needs to show. ### App.addNextScreenCallbackToVictoryFlow = (rewardModels) -> Logger.module("APPLICATION").log "App:addNextScreenCallbackToVictoryFlow" # # if we have any faction progression rewards, show those first # if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "faction xp" and rewardModel.get('is_unread')) # return App.setCallbackWhenCancel(App.showFactionXpReward.bind(App,rewardModels)) # if we have any quest rewards, show those next if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "quest" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showQuestsCompleted.bind(App,rewardModels)) # if we have any progression rewards, show those next if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "progression" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showWinCounterReward.bind(App,rewardModels)) # ... if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "challenge" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showTutorialRewards.bind(App,rewardModels)) # ... if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "daily challenge" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showTutorialRewards.bind(App,rewardModels)) # if we have any ribbon rewards, show those next if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "ribbon" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showNextRibbonReward.bind(App,rewardModels)) # # if we have any gift crate rewards, show those next # if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_type') == "gift crate" and rewardModel.get('is_unread')) # return App.setCallbackWhenCancel(App.showGiftCrateReward.bind(App,rewardModels)) # if we have any cosmetic loot crate rewards, show those next if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "loot crate" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showLootCrateReward.bind(App,rewardModels)) # if we have any faction unlocks, show those next factionUnlockedReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "faction unlock" and rewardModel.get('is_unread')) if factionUnlockedReward return App.setCallbackWhenCancel(App.showUnlockedFaction.bind(App,factionUnlockedReward.get('unlocked_faction_id'))) # if we are doing a tutorial, kick us back to the tutorial screen, unless it's the last lesson: LessonFour, in which case, move along with normal flow (kicks to main menu) if SDK.GameSession.getInstance().getChallenge()?.categoryType == SDK.ChallengeCategory.tutorial.type # for tutorial go show tutorial layout if SDK.GameSession.getInstance().getChallenge().type != "LessonFour" return App.setCallbackWhenCancel(App._showTutorialLessons.bind(App,SDK.GameSession.getInstance().getChallenge())) ###* # Show unlocked faction screen. # @public # @param {String|Number} factionId # @returns {Promise} ### App.showUnlockedFaction = (factionId) -> Logger.module("APPLICATION").log("App:showUnlockedFaction", factionId) unlockFactionLayer = new UnlockFactionLayer(factionId) return Promise.all([ NavigationManager.getInstance().destroyContentView(), NavigationManager.getInstance().destroyDialogView(), Scene.getInstance().showOverlay(unlockFactionLayer) ]) .then () -> if Scene.getInstance().getOverlay() == unlockFactionLayer unlockFactionLayer.animateReward() .catch (error) -> App._error(error) ###* # Show ribbon reward screen if there are any unread ribbon reward models. # @public # @param {Array} rewardModels the reward models array. ### App.showNextRibbonReward = (rewardModels) -> Logger.module("APPLICATION").log "App:showNextRibbonReward" nextReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "ribbon" and rewardModel.get('is_unread')) nextReward.set('is_unread',false) ribbonId = nextReward.get("ribbons")?[0] if ribbonId? ribbonObject = SDK.RibbonFactory.ribbonForIdentifier(ribbonId) # clear ui NavigationManager.getInstance().destroyContentView() NavigationManager.getInstance().destroyDialogView() # show the in-engine card reward animation progressionRewardLayer = new ProgressionRewardLayer() Scene.getInstance().showOverlay(progressionRewardLayer) progressionRewardLayer.showRewardRibbons([ribbonId], "You've earned the #{ribbonObject.title} ribbon.", "Ribbons show on your profile for performing in battle with distinction.") else Logger.module("APPLICATION").log "ERROR: ribbonId is undefined for reward #{nextReward.get("id")}" ###* # Show progression reward screen. # @public # @param {Backbone.Model} rewardModel progression reward model. ### App.showProgressReward = (rewardModel) -> Logger.module("APPLICATION").log "App:showProgressReward" # clear ui NavigationManager.getInstance().destroyContentView() NavigationManager.getInstance().destroyDialogView() # show the in-engine card reward animation if rewardModel.get("cards") # cards cardIds = rewardModel.get("cards") if rewardModel.get("_showStack") cardIds = [cardIds[0]] progressionRewardLayer = new ProgressionRewardLayer() Scene.getInstance().showOverlay(progressionRewardLayer) progressionRewardLayer.showRewardCards(cardIds, rewardModel.get("_showStack"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("cosmetics") # NOTE: only emotes and battle maps will work for this case progressionRewardLayer = new ProgressionRewardLayer() Scene.getInstance().showOverlay(progressionRewardLayer) if SDK.CosmeticsFactory.cosmeticForIdentifier(rewardModel.get("cosmetics")[0]).typeId == SDK.CosmeticsTypeLookup.BattleMap progressionRewardLayer.showRewardBattleMaps(rewardModel.get("cosmetics"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else progressionRewardLayer.showRewardEmotes(rewardModel.get("cosmetics"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("gift_chests") CrateManager.getInstance().refreshGiftCrates() rewardLayer = new LootCrateRewardLayer() Scene.getInstance().showOverlay(rewardLayer) rewardLayer.animateReward(rewardModel.get("gift_chests"),rewardModel.get("_title"),rewardModel.get("_subTitle")) else if rewardModel.get("cosmetic_keys") # cosmetic keys cosmeticKeyRewardLayer = new LootCrateRewardLayer() Scene.getInstance().showOverlay(cosmeticKeyRewardLayer) cosmeticKeyRewardLayer.animateReward(rewardModel.get("cosmetic_keys"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("ribbons") # ribbons progressionRewardLayer = new ProgressionRewardLayer() Scene.getInstance().showOverlay(progressionRewardLayer) progressionRewardLayer.showRewardRibbons(rewardModel.get("ribbons"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("spirit") # spirit currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) currencyRewardLayer.animateReward("spirit", rewardModel.get("spirit"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("gold") # gold currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) currencyRewardLayer.animateReward("gold", rewardModel.get("gold"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("spirit_orbs") # booster boosterRewardLayer = new BoosterRewardLayer() Scene.getInstance().showOverlay(boosterRewardLayer) boosterRewardLayer.animateReward(rewardModel.get("_title"), rewardModel.get("_subTitle"), rewardModel.get("spirit_orbs")) else if rewardModel.get("gauntlet_tickets") # gauntlet ticket gauntletTicketRewardLayer = new GauntletTicketRewardLayer() Scene.getInstance().showOverlay(gauntletTicketRewardLayer) gauntletTicketRewardLayer.animateReward(rewardModel.get("_title"), rewardModel.get("_subTitle")) else Logger.module("APPLICATION").log("Application->showProgressReward: Attempt to show reward model without valid reward") ###* # Show achievement reward screen if there are any unread ones. # @public ### App.showAchievementCompletions = () -> if !AchievementsManager.getInstance().hasUnreadCompletedAchievements() Scene.getInstance().destroyOverlay() return Promise.resolve() else return new Promise( (resolve, reject) -> locResolve = resolve Logger.module("APPLICATION").log "App:showAchievementCompletions" completedAchievementModel = AchievementsManager.getInstance().popNextUnreadAchievementModel() App.setCallbackWhenCancel(locResolve) # show reward App.showProgressReward(completedAchievementModel) ).then () -> return App.showAchievementCompletions() ###* # Show twitch reward screen if there are any unread ones. # @public ### App.showTwitchRewards = () -> if !TwitchManager.getInstance().hasUnclaimedTwitchRewards() Scene.getInstance().destroyOverlay() return Promise.resolve() else return new Promise( (resolve, reject) -> locResolve = resolve Logger.module("APPLICATION").log "App:showTwitchRewards" twitchRewardModel = TwitchManager.getInstance().popNextUnclaimedTwitchRewardModel() App.setCallbackWhenCancel(locResolve) # show reward App.showProgressReward(twitchRewardModel) ).then () -> return App.showTwitchRewards() ###* # Show season rewards screen if the player has an unread season rewards set. # @public ### App.showEndOfSeasonRewards = () -> gamesManager = GamesManager.getInstance() if gamesManager.hasUnreadSeasonReward() return new Promise( (resolve, reject) -> locResolve = resolve # get data seasonModel = gamesManager.getSeasonsWithUnclaimedRewards()[0] bonusChevrons = SDK.RankFactory.chevronsRewardedForReachingRank(seasonModel.get("top_rank")? || 30) seasonRewardIds = seasonModel.get("reward_ids") if bonusChevrons == 0 # If there is no rewards we exit here locResolve() else Logger.module("APPLICATION").log "App:showEndOfSeasonRewards" endOfSeasonLayer = new EndOfSeasonLayer(seasonModel) return Promise.all([ NavigationManager.getInstance().destroyContentView(), NavigationManager.getInstance().destroyDialogView(), Scene.getInstance().showOverlay(endOfSeasonLayer) ]) .then () -> App.setCallbackWhenCancel(() -> Scene.getInstance().destroyOverlay() locResolve() ) if Scene.getInstance().getOverlay() == endOfSeasonLayer return endOfSeasonLayer.animateReward() .catch (error) -> Logger.module("APPLICATION").log("App.showEndOfSeasonRewards error: ", error) locResolve() ) else return Promise.resolve() App.showTutorialRewards = (rewardModels) -> Logger.module("APPLICATION").log "App:showTutorialRewards" nextReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "challenge" and rewardModel.get('is_unread')) nextReward = nextReward || _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "daily challenge" and rewardModel.get('is_unread')) nextReward.set("is_unread",false) App.addNextScreenCallbackToVictoryFlow(rewardModels) # show reward if (nextReward.get("unlocked_faction_id")) App.showUnlockedFaction(nextReward.get("unlocked_faction_id")) else App.showProgressReward(nextReward) App.showLadderProgress = (userGameModel,rewardModels) -> Logger.module("APPLICATION").log "App:showLadderProgress" # set the cancel callback to show the next screen App.addNextScreenCallbackToVictoryFlow(rewardModels) ladderProgressLayer = new LadderProgressLayer() return Promise.all([ NavigationManager.getInstance().destroyContentView(), NavigationManager.getInstance().destroyDialogView(), Scene.getInstance().showOverlay(ladderProgressLayer) ]) .then () -> if Scene.getInstance().getOverlay() == ladderProgressLayer return ladderProgressLayer.showLadderProgress(userGameModel) .catch (error) -> App._error("App.showLadderProgress error: ", error) App.showRiftProgress = (userGameModel,rewardModels) -> Logger.module("APPLICATION").log "App:showRiftProgress" # set the cancel callback to show the next screen App.addNextScreenCallbackToVictoryFlow(rewardModels) riftProgressLayer = new RiftProgressLayer() return Promise.all([ NavigationManager.getInstance().destroyContentView(), NavigationManager.getInstance().destroyDialogView(), Scene.getInstance().showOverlay(riftProgressLayer) ]) .then () -> if Scene.getInstance().getOverlay() == riftProgressLayer return riftProgressLayer.showRiftProgress(userGameModel) .catch (error) -> App._error("App.showRiftProgress error: ", error) App.showQuestsCompleted = (rewardModels) -> Logger.module("APPLICATION").log "App:showQuestsCompleted" nextQuestReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "quest" and rewardModel.get('is_unread')) nextQuestReward.set('is_unread',false) sdkQuest = SDK.QuestFactory.questForIdentifier(nextQuestReward.get('quest_type_id')) questName = sdkQuest.getName() gold = nextQuestReward.get("gold") spiritOrbs = nextQuestReward.get("spirit_orbs") giftChests = null cosmeticKeys = null if sdkQuest.giftChests?.length > 0 giftChests = sdkQuest.giftChests if sdkQuest.cosmeticKeys?.length > 0 cosmeticKeys = sdkQuest.cosmeticKeys # track an event in analytics Analytics.track("quest complete", { category: Analytics.EventCategory.Quest, quest_type_id: nextQuestReward.get('quest_type_id'), gold_amount:nextQuestReward.get("gold") || 0 },{ labelKey:"quest_type_id" valueKey:"gold_amount" nonInteraction:1 }) # set the cancel callback to show the next screen App.addNextScreenCallbackToVictoryFlow(rewardModels) # show quest reward NavigationManager.getInstance().destroyContentView() if gold currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) currencyRewardLayer.animateReward( "gold", gold, i18next.t("rewards.quest_complete_title",{quest_name:questName}) "+#{gold} GOLD for completing #{questName}", "Quest Complete" ) else if spiritOrbs # booster boosterRewardLayer = new BoosterRewardLayer() Scene.getInstance().showOverlay(boosterRewardLayer) boosterRewardLayer.animateReward( i18next.t("rewards.quest_complete_title",{quest_name:questName}) "+#{spiritOrbs} SPIRIT ORBS for completing #{questName}" ) else if giftChests Analytics.track("earned gift crate", { category: Analytics.EventCategory.Crate, product_id: giftChests[0] }, { labelKey: "product_id" }) # show reward setup on the engine side NavigationManager.getInstance().destroyContentView() rewardLayer = new LootCrateRewardLayer() Scene.getInstance().showOverlay(rewardLayer) rewardLayer.animateReward(giftChests, null, i18next.t("rewards.quest_reward_gift_crate_title",{quest_name:questName})) CrateManager.getInstance().refreshGiftCrates() else if cosmeticKeys Analytics.track("earned cosmetic key", { category: Analytics.EventCategory.Crate, product_id: cosmeticKeys[0] }, { labelKey: "product_id" }) NavigationManager.getInstance().destroyContentView() rewardLayer = new CosmeticKeyRewardLayer() Scene.getInstance().showOverlay(rewardLayer) rewardLayer.showRewardKeys(cosmeticKeys, null, "FREE Cosmetic Crate Key for completing the #{questName} quest") CrateManager.getInstance().refreshGiftCrates() # Outdated name, really shows all progression rewards App.showWinCounterReward = (rewardModels) -> Logger.module("APPLICATION").log "App:showWinCounterReward" nextReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "progression" and rewardModel.get('is_unread')) nextReward.set("is_unread",false) App.addNextScreenCallbackToVictoryFlow(rewardModels) # show reward setup on the engine side NavigationManager.getInstance().destroyContentView() # Scene.getInstance().showOverlay(currencyRewardLayer) # TODO: merge How does this even work? rewardView = null switch nextReward.get("reward_type") when "win count" currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) goldAmount = nextReward.get("gold") message = i18next.t("rewards.3_win_gold_reward_message",{gold_amount:goldAmount}) currencyRewardLayer.animateReward( "gold", goldAmount, i18next.t("rewards.3_win_gold_reward_title"), message ) when "play count" currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) goldAmount = nextReward.get("gold") currencyRewardLayer.animateReward( "gold", goldAmount, i18next.t("rewards.4_play_gold_reward_title"), i18next.t("rewards.4_play_gold_reward_message",{gold_amount:goldAmount}) ) when "daily win" currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) goldAmount = nextReward.get("gold") currencyRewardLayer.animateReward( "gold", goldAmount, i18next.t("rewards.first_win_of_the_day_reward_title"), i18next.t("rewards.first_win_of_the_day_reward_message",{gold_amount:goldAmount}) ) when "first 3 games" currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) goldAmount = nextReward.get("gold") currencyRewardLayer.animateReward( "gold", goldAmount, i18next.t("rewards.first_3_games_reward_title"), i18next.t("rewards.first_3_games_reward_message",{gold_amount:goldAmount}) ) when "first 10 games" currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) goldAmount = nextReward.get("gold") currencyRewardLayer.animateReward( "gold", goldAmount, i18next.t("rewards.first_10_games_reward_title"), i18next.t("rewards.first_10_games_reward_message",{gold_amount:goldAmount}) ) when "boss battle" boosterRewardLayer = new BoosterRewardLayer() Scene.getInstance().showOverlay(boosterRewardLayer) cardSetId = nextReward.get("spirit_orbs") boosterRewardLayer.animateReward( i18next.t("rewards.boss_defeated_reward_title"), i18next.t("rewards.boss_defeated_reward_message"), SDK.CardSet.Core ) App.showLootCrateReward = (rewardModels)-> Logger.module("APPLICATION").log "App:showLootCrateReward" nextReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "loot crate" and rewardModel.get('is_unread')) nextReward.set("is_unread",false) Analytics.track("earned cosmetic crate", { category: Analytics.EventCategory.Crate, product_id: nextReward.get("cosmetic_chests")?[0] }, { labelKey: "product_id" }) App.addNextScreenCallbackToVictoryFlow(rewardModels) # show reward setup on the engine side NavigationManager.getInstance().destroyContentView() rewardLayer = new LootCrateRewardLayer() Scene.getInstance().showOverlay(rewardLayer) rewardLayer.animateReward(nextReward.get("cosmetic_chests")) # App.showGiftCrateReward = (rewardModels)-> # Logger.module("APPLICATION").log "App:showGiftCrateReward" # # nextReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_type') == "gift crate" and rewardModel.get('is_unread')) # nextReward.set("is_unread",false) # # Analytics.track("earned gift crate", { # category: Analytics.EventCategory.Crate, # product_id: nextReward.get("gift_crates")?[0] # }, { # labelKey: "product_id" # }) # # App.addNextScreenCallbackToVictoryFlow(rewardModels) # # # show reward setup on the engine side # NavigationManager.getInstance().destroyContentView() # rewardLayer = new LootCrateRewardLayer() # Scene.getInstance().showOverlay(rewardLayer) # rewardLayer.animateReward(nextReward.get("gift_crates")) App.showFactionXpReward = (userGameModel,rewardModels) -> Logger.module("APPLICATION").log "App:showFactionXpReward" nextUnreadReward = _.find rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "faction xp" and rewardModel.get('is_unread') nextUnreadReward.set("is_unread",false) factionId = userGameModel.get("faction_id") factionName = SDK.FactionFactory.factionForIdentifier(factionId).name faction_xp = userGameModel.get('faction_xp') faction_xp_earned = userGameModel.get('faction_xp_earned') level = SDK.FactionProgression.levelForXP(faction_xp + faction_xp_earned) + 1 # set title nextUnreadReward.set("_title", i18next.t("rewards.level_up_reward_title",{ level:level })) # set reward model properties by reward if nextUnreadReward.get("cards") # cards factionCards = GameDataManager.getInstance().visibleCardsCollection.filter (c)-> c.get("factionId") == factionId and c.get("rarityId") == SDK.Rarity.Fixed availableFactionCards = _.filter(factionCards, (c)-> return c.get("inventoryCount") > 0 ) subtitle = i18next.t("rewards.card_reward_subtitle",{ card_count: availableFactionCards.length, total: factionCards.length, factionName: factionName }) nextUnreadReward.set("_subTitle", subtitle) nextUnreadReward.set("_showStack",true) else if nextUnreadReward.get("spirit") # sprit nextUnreadReward.set("_subTitle", i18next.t("rewards.spirit_for_faction_lvl_reward_message",{spirit:nextUnreadReward.get("spirit"),faction_name:factionName,level:level})) else if nextUnreadReward.get("gold") # gold nextUnreadReward.set("_subTitle", i18next.t("rewards.gold_for_faction_lvl_reward_message",{gold:nextUnreadReward.get("spirit"),faction_name:factionName,level:level})) else if nextUnreadReward.get("spirit_orbs") # booster nextUnreadReward.set("_subTitle", i18next.t("rewards.orb_for_faction_lvl_reward_message",{faction_name:factionName,level:level})) # setup next screen if SDK.GameSession.current().isRanked() App.setCallbackWhenCancel(App.showLadderProgress.bind(App,userGameModel,rewardModels)) else if SDK.GameSession.current().isRift() App.setCallbackWhenCancel(App.showRiftProgress.bind(App,userGameModel,rewardModels)) else App.addNextScreenCallbackToVictoryFlow(rewardModels) # show reward App.showProgressReward(nextUnreadReward) App.showNewBeginnerQuests = (beginnerQuestsCollection) -> NavigationManager.getInstance().toggleModalViewByClass(QuestLogLayout,{ collection:beginnerQuestsCollection, showConfirm:true }) App.showFreeCardOfTheDayReward = (opts)-> Promise.all([ NavigationManager.getInstance().destroyModalView(), NavigationManager.getInstance().destroyContentView(), NavigationManager.getInstance().destroyUtilityView() ]).then ()=> rewardLayer = new FreeCardOfTheDayLayer() Scene.getInstance().showOverlay(rewardLayer) rewardLayer.showCoreGem(opts.cardId) App.setCallbackWhenCancel ()-> Scene.getInstance().destroyOverlay() App._showMainMenu().then ()-> NavigationManager.getInstance().toggleModalViewByClass(QuestLogLayout,{ collection:QuestsManager.getInstance().getQuestCollection(), model:ProgressionManager.getInstance().gameCounterModel }) return Promise.resolve() # # ---- User Triggered Navigation ---- # # App.onUserTriggeredExit = () -> Logger.module("APPLICATION").log "App:onUserTriggeredExit" return App.main() App.onUserTriggeredSkip = () -> Logger.module("APPLICATION").log "App:onUserTriggeredSkip" gameSession = SDK.GameSession.getInstance() scene = Scene.getInstance() gameLayer = scene and scene.getGameLayer() if gameLayer? and gameLayer.getIsGameActive() # when in an active game if gameSession.getIsMyFollowupActiveAndCancellable() audio_engine.current().play_effect_for_interaction(RSX.sfx_ui_cancel.audio, CONFIG.CANCEL_SFX_PRIORITY) gameSession.submitExplicitAction(gameSession.getMyPlayer().actionEndFollowup()) else if gameLayer.getIsShowingActionCardSequence() audio_engine.current().play_effect_for_interaction(RSX.sfx_ui_cancel.audio, CONFIG.CANCEL_SFX_PRIORITY) # stop showing played card gameLayer.skipShowActionCardSequence() return Promise.resolve() App.onUserTriggeredCancel = () -> Logger.module("APPLICATION").log "App:onUserTriggeredCancel" cancelPromises = [] if NavigationManager.getInstance().getIsShowingModalView() # close modal screens audio_engine.current().play_effect_for_interaction(RSX.sfx_ui_cancel.audio, CONFIG.CANCEL_SFX_PRIORITY) cancelPromises.push(NavigationManager.getInstance().destroyModalView()) else if NavigationManager.getInstance().getHasLastRoute() # go to last route (handles own sfx) NavigationManager.getInstance().showLastRoute() else gameSession = SDK.GameSession.getInstance() scene = Scene.getInstance() gameLayer = scene and scene.getGameLayer() if gameLayer? and !gameLayer.getIsDisabled() and NavigationManager.getInstance().getIsShowingContentViewClass(GameLayout) # when in game that is not over if gameSession.getIsMyFollowupActiveAndCancellable() audio_engine.current().play_effect_for_interaction(RSX.sfx_ui_cancel.audio, CONFIG.CANCEL_SFX_PRIORITY) gameSession.submitExplicitAction(gameSession.actionRollbackSnapshot()) else if !gameLayer.getMyPlayer().getIsTakingSelectionAction() and !gameLayer.getIsShowingActionCardSequence() # show esc game menu if we are not selecting something in game and not showing an action sequence cancelPromises.push(NavigationManager.getInstance().showModalView(new EscGameMenuItemView())) # always reset game active state gameLayer.resetActiveState() else callback = App.getCallbackWhenCancel() if callback? App.setCallbackWhenCancel(null) callbackResult = callback() if callbackResult instanceof Promise cancelPromises.push(callbackResult) else if (App.getIsLoggedIn() or window.isDesktop) and (NavigationManager.getInstance().getIsShowingContentViewClass(LoaderItemView) or NavigationManager.getInstance().getIsShowingContentViewClass(LoginMenuItemView) or NavigationManager.getInstance().getIsShowingContentViewClass(MainMenuItemView) or NavigationManager.getInstance().getIsShowingContentViewClass(TutorialLessonsLayout)) # show esc main menu when on loading or login or main cancelPromises.push(NavigationManager.getInstance().showModalView(new EscMainMenuItemView())) else if (!gameLayer? or gameLayer.getIsDisabled()) and !App.getIsShowingMain() audio_engine.current().play_effect_for_interaction(RSX.sfx_ui_cancel.audio, CONFIG.CANCEL_SFX_PRIORITY) # for now just go back to main until we implement routing cancelPromises.push(App.main()) return Promise.all(cancelPromises) App.setCallbackWhenCancel = (callback) -> # this is a less than ideal method of setting the next step in cancel sequence App._callbackWhenCancel = callback App.getCallbackWhenCancel = () -> return App._callbackWhenCancel App.onUserTriggeredConfirm = () -> Logger.module("APPLICATION").log "App:onUserTriggeredConfirm" # # ---- Events: Client ---- # # App.beforeunload = (e) -> # return an empty string to trigger alert if App._reloadRequestIds.length == 0 and !window.isDesktop and !UtilsEnv.getIsInLocal() confirmMessage = "" (e || window.event).returnValue = confirmMessage return confirmMessage App.unload = () -> # reset the global event bus so no more events will be handled EventBus.reset() # cancel any ongoing matchmaking GamesManager.getInstance().cancelMatchmaking() App.bindEvents = () -> # attach event listeners to document/window $(window).on('unload', App.unload.bind(App)) $(window).on('mousemove',App.onPointerMove.bind(App)) $(window).on('mousedown',App.onPointerDown.bind(App)) $(window).on('mouseup',App.onPointerUp.bind(App)) $(window).on('wheel',App.onPointerWheel.bind(App)) $(window).on("resize", _.debounce(App.onResize.bind(App), 250)) EventBus.getInstance().on(EVENTS.request_resize, _.debounce(App.onResize.bind(App), 250)) $(document).on("visibilitychange",App.onVisibilityChange.bind(App)) EventBus.getInstance().on(EVENTS.request_reload, App.onRequestReload) EventBus.getInstance().on(EVENTS.cancel_reload_request, App.onCancelReloadRequest) $(CONFIG.GAMECANVAS_SELECTOR).on("webglcontextlost", () -> App.onRequestReload({ id: "webgl_context_lost", message: "Your graphics hit a snag and requires a #{if window.isDesktop then "restart" else "reload"} to avoid any issues." }) ) # session is a plain event emitter Session.on('login', App.onLogin) Session.on('logout', App.onLogout) Session.on('error', App.onSessionError) EventBus.getInstance().on(EVENTS.show_login, App._showLoginMenu, App) EventBus.getInstance().on(EVENTS.show_terms, App._showTerms, App) EventBus.getInstance().on(EVENTS.show_play, App.showPlay, App) EventBus.getInstance().on(EVENTS.show_watch, App.showWatch, App) EventBus.getInstance().on(EVENTS.show_shop, App.showShop, App) EventBus.getInstance().on(EVENTS.show_collection, App.showCollection, App) EventBus.getInstance().on(EVENTS.show_codex, App.showCodex, App) EventBus.getInstance().on(EVENTS.show_booster_pack_unlock, App.showBoosterPackUnlock, App) EventBus.getInstance().on(EVENTS.show_crate_inventory, App.showCrateInventory, App) EventBus.getInstance().on(EVENTS.start_challenge, App._startGameWithChallenge, App) EventBus.getInstance().on(EVENTS.start_single_player, App._startSinglePlayerGame, App) EventBus.getInstance().on(EVENTS.start_boss_battle, App._startBossBattleGame, App) EventBus.getInstance().on(EVENTS.start_replay, App._startGameForReplay, App) EventBus.getInstance().on(EVENTS.show_free_card_of_the_day, App.showFreeCardOfTheDayReward, App) EventBus.getInstance().on(EVENTS.discord_spectate, App.onDiscordSpectate, App) GamesManager.getInstance().on(EVENTS.matchmaking_start, App._matchmakingStart, App) GamesManager.getInstance().on(EVENTS.matchmaking_cancel, App._matchmakingCancel, App) GamesManager.getInstance().on(EVENTS.matchmaking_error, App._matchmakingError, App) GamesManager.getInstance().on(EVENTS.finding_game, App._findingGame, App) GamesManager.getInstance().on(EVENTS.invite_accepted, App._inviteAccepted, App) GamesManager.getInstance().on(EVENTS.invite_rejected, App._inviteRejected, App) GamesManager.getInstance().on(EVENTS.invite_cancelled, App._inviteCancelled, App) GamesManager.getInstance().on(EVENTS.start_spectate, App._spectateGame, App) EventBus.getInstance().on EVENTS.canvas_mouse_state, App.onCanvasMouseState, App NavigationManager.getInstance().on(EVENTS.user_triggered_exit, App.onUserTriggeredExit, App) NavigationManager.getInstance().on(EVENTS.user_triggered_skip, App.onUserTriggeredSkip, App) NavigationManager.getInstance().on(EVENTS.user_triggered_cancel, App.onUserTriggeredCancel, App) NavigationManager.getInstance().on(EVENTS.user_triggered_confirm, App.onUserTriggeredConfirm, App) EventBus.getInstance().on EVENTS.error, App._error, App EventBus.getInstance().on EVENTS.ajax_error, App._error, App App._subscribeToGameLocalEvents = () -> Logger.module("APPLICATION").log "App._subscribeToGameLocalEvents" scene = Scene.getInstance() gameLayer = scene?.getGameLayer() if gameLayer? gameLayer.getEventBus().on(EVENTS.after_show_end_turn, App.onAfterShowEndTurn, App) gameLayer.getEventBus().on(EVENTS.show_game_over, App.onShowGameOver, App) gameLayer.getEventBus().on(EVENTS.canvas_mouse_state, App.onCanvasMouseState, App) SDK.GameSession.getInstance().getEventBus().on(EVENTS.game_over, App._onGameOver, App) SDK.GameSession.getInstance().getEventBus().on(EVENTS.end_turn, App._onEndTurn, App) App._unsubscribeFromGameLocalEvents = () -> Logger.module("APPLICATION").log "App._unsubscribeFromGameLocalEvents" scene = Scene.getInstance() gameLayer = scene?.getGameLayer() if gameLayer? gameLayer.getEventBus().off(EVENTS.after_show_end_turn, App.onAfterShowEndTurn, App) gameLayer.getEventBus().off(EVENTS.show_game_over, App.onShowGameOver, App) gameLayer.getEventBus().off(EVENTS.canvas_mouse_state, App.onCanvasMouseState, App) SDK.GameSession.getInstance().getEventBus().off(EVENTS.game_over, App._onGameOver, App) SDK.GameSession.getInstance().getEventBus().off(EVENTS.end_turn, App._onEndTurn, App) App._subscribeToGameNetworkEvents = () -> Logger.module("APPLICATION").log "App._subscribeToGameNetworkEvents" SDK.NetworkManager.getInstance().getEventBus().on(EVENTS.network_game_event, App._onNetworkGameEvent, App) SDK.NetworkManager.getInstance().getEventBus().on(EVENTS.network_game_error, App._onNetworkGameError, App) SDK.NetworkManager.getInstance().getEventBus().on(EVENTS.game_server_shutdown, App._onGameServerShutdown, App) SDK.NetworkManager.getInstance().getEventBus().on(EVENTS.reconnect_to_game, App._onReconnectToGame, App) SDK.NetworkManager.getInstance().getEventBus().on(EVENTS.opponent_connection_status_changed, App._onOpponentConnectionStatusChanged, App) App._unsubscribeFromGameNetworkEvents = () -> Logger.module("APPLICATION").log "App._unsubscribeFromGameNetworkEvents" SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.network_game_event, App._onNetworkGameEvent, App) SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.network_game_error, App._onNetworkGameError, App) SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.game_server_shutdown, App._onGameServerShutdown, App) SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.reconnect_to_game, App._onReconnectToGame, App) SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.opponent_connection_status_changed, App._onOpponentConnectionStatusChanged, App) App.onVisibilityChange = () -> # TODO: look into why this causes errors # Prevent sound effects that have been queued up from blasting all at once when app regains visibility if document.hidden # Would rather do a resume and start of effects, it doesn't stop them from piling up though audio_engine.current().stop_all_effects() else audio_engine.current().stop_all_effects() # # ---- RESIZE ---- # # App.onResize = (e) -> Logger.module("APPLICATION").log("App.onResize") # store current resolution data ignoreNextResolutionChange = App._ignoreNextResolutionChange App._ignoreNextResolutionChange = false if !ignoreNextResolutionChange currentResolution = CONFIG.resolution confirmResolutionChange = App._lastResolution? and App._lastResolution != currentResolution # before resize EventBus.getInstance().trigger(EVENTS.before_resize) # resize and update scale App._resizeAndScale() # resize the scene to match app Scene.getInstance().resize() # resize the UI EventBus.getInstance().trigger(EVENTS.resize) # after resize EventBus.getInstance().trigger(EVENTS.after_resize) # force user to restart if resource scale for engine has changed # CSS automatically handles resource scale changes # TODO: instead of restarting, destroy all current views, show loading screen, reload images at new scale, and return to current route App._needsRestart = App._lastResourceScaleEngine? and CONFIG.resourceScaleEngine != App._lastResourceScaleEngine if !App._needsRestart # cancel forced reload in case user has restored original window size App._cancelReloadRequestForResolutionChange() if confirmResolutionChange # confirm resolution with user after resizing App._confirmResolutionChange() else if App._needsRestart # force reload as user has changed window size App._requestReloadForResolutionChange() else # update resolution values as no confirm or restart needed App._updateLastResolutionValues() return true App._resizeAndScale = () -> Logger.module("APPLICATION").log("App._resizeAndScale") # resize canvas to match app size # engine bases its window size on the canvas size $html = $("html") $canvas = $(CONFIG.GAMECANVAS_SELECTOR) width = Math.max(CONFIG.REF_WINDOW_SIZE.width, $html.width()) height = Math.max(CONFIG.REF_WINDOW_SIZE.height, $html.height()) $canvas.width(width) $canvas.height(height) # set global scale CONFIG.globalScale = CONFIG.getGlobalScaleForResolution(CONFIG.resolution, width, height) # set css scales CONFIG.pixelScaleCSS = CONFIG.globalScale * window.devicePixelRatio $html.removeClass("resource-scale-" + String(CONFIG.resourceScaleCSS).replace(".", "\.")) CONFIG.resourceScaleCSS = 1 for resourceScale in CONFIG.RESOURCE_SCALES scaleDiff = Math.abs(CONFIG.pixelScaleCSS - resourceScale) currentScaleDiff = Math.abs(CONFIG.pixelScaleCSS - CONFIG.resourceScaleCSS) if scaleDiff < currentScaleDiff or (scaleDiff == currentScaleDiff and resourceScale > CONFIG.resourceScaleCSS) CONFIG.resourceScaleCSS = resourceScale $html.addClass("resource-scale-" + String(CONFIG.resourceScaleCSS).replace(".", "\.")) # html font size by global scale # css layout uses rems, which is based on html font size $html.css("font-size", CONFIG.globalScale * 10.0 + "px") App._lastResolution = null App._lastResourceScaleEngine = null App._ignoreNextResolutionChange = false App._needsRestart = false App._updateLastResolutionValues = () -> App._lastResolution = CONFIG.resolution App._lastResourceScaleEngine = CONFIG.resourceScaleEngine App._confirmResolutionChange = () -> Logger.module("APPLICATION").log "App._confirmResolutionChange" confirmData = {title: 'Do you wish to keep this viewport setting?'} if App._needsRestart if window.isDesktop confirmData.message = 'Warning: switching from your previous viewport to this viewport will require a restart!' else confirmData.message = 'Warning: switching from your previous viewport to this viewport will require a reload!' if ChatManager.getInstance().getStatusIsInBattle() confirmData.message += " You will be able to continue your game, but you may miss your turn!" confirmDialogItemView = new ConfirmDialogItemView(confirmData) confirmDialogItemView.listenToOnce(confirmDialogItemView, 'confirm', ()-> # update resolution after confirm App._lastResolution = CONFIG.resolution if App._needsRestart # defer to ensure this occurs after event resolves _.defer(App._requestReloadForResolutionChange) else # update resource scale if no restart needed App._lastResourceScaleEngine = CONFIG.resourceScaleEngine ) confirmDialogItemView.listenToOnce(confirmDialogItemView, 'cancel', ()-> # defer to ensure this occurs after event resolves _.defer(() -> # reset resolution and don't prompt about changes App._ignoreNextResolutionChange = true res = App._lastResolution || CONFIG.RESOLUTION_DEFAULT CONFIG.resolution = res Storage.set("resolution", res) App.onResize() ) ) # show confirm/cancel NavigationManager.getInstance().showDialogView(confirmDialogItemView) App._requestReloadForResolutionChangeId = "resolution_change" App._requestReloadForResolutionChange = () -> App.onRequestReload({ id: App._requestReloadForResolutionChangeId message: "Your viewport change requires a #{if window.isDesktop then "restart" else "reload"} to avoid any issues." }) App._cancelReloadRequestForResolutionChange = () -> App.onCancelReloadRequest({ id: App._requestReloadForResolutionChangeId }) # # ---- RELOAD ---- # # App._reloadRequestIds = [] ### * Request a reload, optionally passing in a message and id (to avoid conflicts). *### App.onRequestReload = (event) -> requestId = event?.id or 0 if !_.contains(App._reloadRequestIds, requestId) App._reloadRequestIds.push(requestId) if App._reloadRequestIds.length == 1 App._reload(event?.message) ### * Cancel a reload request, optionally passing in an id (to avoid conflicts). *### App.onCancelReloadRequest = (event) -> requestId = event?.id or 0 index = _.indexOf(App._reloadRequestIds, requestId) if index != -1 App._reloadRequestIds.splice(index, 1) if App._reloadRequestIds.length == 0 App._cancelReload() App._reload = (message) -> Logger.module("APPLICATION").log "App._reload" promptDialogItemView = new PromptDialogItemView({title: "Please #{if window.isDesktop then "restart" else "reload"}!", message: message}) promptDialogItemView.listenTo(promptDialogItemView, 'cancel', () -> if window.isDesktop then window.quitDesktop() else location.reload() ) NavigationManager.getInstance().showDialogView(promptDialogItemView) App._cancelReload = () -> Logger.module("APPLICATION").log "App._cancelReload" NavigationManager.getInstance().destroyDialogView() # # ---- Initialization Events ---- # # Sequence of events started with App.start. Can pass options object. # # Pre-Start Event App.on "before:start", (options) -> Logger.module("APPLICATION").log "----BEFORE START----" App.$el = $("#app") # Start Event App.on "start", (options) -> Logger.module("APPLICATION").log "----START----" # set unload alert $(window).on('beforeunload', App.beforeunload.bind(App)) # set initial selected scene selectedScene = parseInt(Storage.get("selectedScene")) if moment.utc().isAfter("2016-11-29") and moment.utc().isBefore("2017-01-01") selectedScene = SDK.CosmeticsLookup.Scene.Frostfire if moment.utc().isAfter("2017-03-14") and moment.utc().isBefore("2017-05-01") selectedScene = SDK.CosmeticsLookup.Scene.Vetruvian if moment.utc().isAfter("2017-07-01") and moment.utc().isBefore("2017-08-01") selectedScene = SDK.CosmeticsLookup.Scene.Shimzar if moment.utc().isAfter("2017-12-01") and moment.utc().isBefore("2018-01-18") selectedScene = SDK.CosmeticsLookup.Scene.Frostfire if selectedScene? and !isNaN(selectedScene) and _.isNumber(selectedScene) then CONFIG.selectedScene = selectedScene # set initial resolution userResolution = parseInt(Storage.get("resolution")) if userResolution? and !isNaN(userResolution) and _.isNumber(userResolution) then CONFIG.resolution = userResolution userHiDPIEnabled = Storage.get("hiDPIEnabled") if userHiDPIEnabled? if userHiDPIEnabled == "true" then CONFIG.hiDPIEnabled = true else if userHiDPIEnabled == "false" then CONFIG.hiDPIEnabled = false # update last resolution values to initial App._updateLastResolutionValues() # resize once for initial values App._resizeAndScale() # create a defered promise object for the loading and login process... sort of an anti-pattern but best for this use case App.managersReadyDeferred = new Promise.defer() # immediately connect the server status manager so we can get notified of any changes during the load process / on the login screen ServerStatusManager.getInstance().connect() # push a telemetry signal that a client is loading TelemetryManager.getInstance().setSignal("lifecycle","loading") TelemetryManager.getInstance().setSignal("session","not-logged-in") # authenticate defered, the isAuthed check must stay here so we can # clear the token in the event it is stale / isAuthed fails # the App._authenticationPromise below does not fire if there's no loading App._authenticationPromise = () -> return Session.isAuthenticated(Storage.get('token')) .then (isAuthed) -> if !isAuthed Storage.remove('token') return isAuthed # VIEW/engine needs to be setup and cocos manages its own setup so we need to wait async Logger.module("APPLICATION").group("LOADING") App._loadingPromise = Scene.setup().then(() -> # update last resolution values to initial App._updateLastResolutionValues() # setup all events App.bindEvents() # load the package of resources that should always loaded return PackageManager.getInstance().loadPackage("alwaysloaded") ).then(() -> # temporary bypass all loader return Promise.resolve() # check if all assets should be loaded now or as needed # we want to know if the client has cached all resources for this version # we only care when not using the desktop client, on the production environment, and not loading all at start # if we need to cache all resources for this version, do a non allocating cache load first version_preloaded = Storage.get("version_preloaded") needs_non_allocating_cache_load = version_preloaded != process.env.VERSION && !window.isDesktop && !CONFIG.LOAD_ALL_AT_START && UtilsEnv.getIsInProduction() needs_non_allocating_cache_load = needs_non_allocating_cache_load && !App._queryStringParams['replayId']? if needs_non_allocating_cache_load || CONFIG.LOAD_ALL_AT_START # temporarily force disable the load all at start flag # this allows the preloader to setup as a major package # so that it gets loaded correctly before we load all load_all_at_start = CONFIG.LOAD_ALL_AT_START CONFIG.LOAD_ALL_AT_START = false # load preloader scene to show load of all resources return PackageManager.getInstance().loadAndActivateMajorPackage("preloader", null, null, () -> # reset load all at start flag CONFIG.LOAD_ALL_AT_START = load_all_at_start # hide loading dialog NavigationManager.getInstance().destroyDialogForLoad() # show load ui viewPromise = Scene.getInstance().showLoad() contentPromise = NavigationManager.getInstance().showContentView(new LoaderItemView()) # once we've authenticated, show utility for loading/login # this way users can quit anytime on desktop, and logout or adjust settings while waiting for load App._authenticationPromise().then (isAuthed) -> if App.getIsLoggedIn() or window.isDesktop return NavigationManager.getInstance().showUtilityView(new UtilityLoadingLoginMenuItemView()) else return Promise.resolve() return Promise.all([ viewPromise, contentPromise ]) ).then(() -> # load all resources return PackageManager.getInstance().loadPackage("all", null, ((progress) -> Scene.getInstance().getLoadLayer()?.showLoadProgress(progress)), needs_non_allocating_cache_load) ).then(() -> # set version assets were preloaded for if !window.isDesktop Storage.set("version_preloaded", process.env.VERSION) ) else # no loading needed now return Promise.resolve() ).then(() -> # clear telemetry signal that a client is loading TelemetryManager.getInstance().clearSignal("lifecycle","loading") # end loading log group Logger.module("APPLICATION").groupEnd() ) # setup start promise App._startPromise = Promise.all([ App._loadingPromise, App._authenticationPromise() ]) # goto main screen App.main() # get minimum browsers from Firebase App.getMinBrowserVersions = () -> if Storage.get("skipBrowserCheck") then return Promise.resolve() return new Promise (resolve, reject) -> minBrowserVersionRef = new Firebase(process.env.FIREBASE_URL).child("system-status").child('browsers') defaults = { "Chrome": 50, "Safari": 10, "Firefox": 57, "Edge": 15 } # create a timeout to skip check in case Firebase lags (so atleast user does not get stuck on black screen) minBrowserVersionTimeout = setTimeout(() -> minBrowserVersionRef.off() resolve(defaults) , 5000) minBrowserVersionRef.once 'value', (snapshot) -> clearTimeout(minBrowserVersionTimeout) if !snapshot.val() resolve(defaults) else resolve(snapshot.val()) # check if given browser is valid when compared against list of allowed browsers App.isBrowserValid = (browserName, browserMajor, browserlist) -> if Storage.get("skipBrowserCheck") then return true if Object.keys(browserlist).includes(browserName) return parseInt(browserMajor, 10) >= browserlist[browserName] else return false App.generateBrowserHtml = (browser, version) -> if browser == 'Chrome' return """ <p><a href='http://google.com/chrome'><strong>Google Chrome</strong> #{version} or newer.</a></p> """ else if browser == 'Safari' return """ <p><a href='https://www.apple.com/safari/'><strong>Apple Safari</strong> #{version} or newer.</a></p> """ else if browser == 'Firefox' return """ <p><a href='https://www.mozilla.org/firefox/'><strong>Mozilla Firefox</strong> #{version} or newer.</a></p> """ else if browser == 'Edge' return """ <p><a href='https://www.microsoft.com/en-us/windows/microsoft-edge'><strong>Microsoft Edge</strong> #{version} or newer.</a></p> """ # show some HTML saying the current browser is not supported if browser detection fails App.browserTestFailed = (browserlist) -> html = """ <div style="margin:auto; position:absolute; height:50%; width:100%; top: 0px; bottom: 0px; font-size: 20px; color: white; text-align: center;"> <p>Looks like your current browser is not supported.</p> <p>Visit <a href='https://support.duelyst.com' style="color: gray;">our support page</a> to submit a request for assistance.</p> <br> """ # dynamically create html containing list of support browsers Object.keys(browserlist).forEach (browser) -> version = browserlist[browser] html += App.generateBrowserHtml(browser, version) html += "</div>" $("#app-preloading").css({display:"none"}) $("#app-content-region").css({margin:"auto", height:"50%", width: "50%"}) $("#app-content-region").html(html) # ensure webgl is correctly running App.glTest = () -> try canvas = document.createElement('canvas') return !! (window.WebGLRenderingContext && (canvas.getContext('webgl') || canvas.getContext('experimental-webgl'))) catch e return false App.glTestFailed = () -> if window.isDesktop html = """ <div style="margin:auto; position:absolute; height:50%; width:100%; top: 0px; bottom: 0px; font-size: 20px; color: white; text-align: center;"> <p>Looks like your video card is not supported.</p> <p>Ensure your video card drivers are up to date.</p> <p>Visit <a id='support-link' href='https://support.duelyst.com' style="color: gray;">our support page</a> to submit a request for assistance.</p> </div> """ else html = """ <div style="margin:auto; position:absolute; height:50%; width:100%; top: 0px; bottom: 0px; font-size: 20px; color: white; text-align: center;"> <p>Looks like WebGL is not enabled in your browser./p> <p>Visit the <a id='webgl-link' href='https://get.webgl.org/' style="color: gray;">WebGL test page</a> for more information.</p> <p>Visit <a id='support-link' href='https://support.duelyst.com' style="color: gray;">our support page</a> to submit a request for assistance.</p> </div> """ $("#app-preloading").css({display:"none"}) $("#app-content-region").css({margin:"auto", height:"50%", width: "50%"}) $("#app-content-region").html(html) $("#webgl-link").click (e) -> openUrl($(e.currentTarget).attr("href")) e.stopPropagation() e.preventDefault() $("#support-link").click (e) -> openUrl($(e.currentTarget).attr("href")) e.stopPropagation() e.preventDefault() # show some HTML saying they are on an old client version App.versionTestFailed = () -> if window.isDesktop html = """ <div style="margin:auto; position:absolute; height:50%; width:100%; top: 0px; bottom: 0px; font-size: 20px; color: white; text-align: center;"> <p>Looks like you are running an old version of DUELYST.</p> <p>Exit and restart DUELYST to update to the latest version.</p> <p>If you are using Steam, you may need to restart Steam before the update appears.</p> <p>Click <a id='reload-link' href='' style="color: gray;">here</a> to exit.</p> </div> """ else html = """ <div style="margin:auto; position:absolute; height:50%; width:100%; top: 0px; bottom: 0px; font-size: 20px; color: white; text-align: center;"> <p>Looks like you are running an old version of DUELYST.</p> <p>Click <a id='reload-link' href='' style="color: gray;">here</a> to refresh your browser to the latest version.</p> </div> """ $("#app-preloading").css({display:"none"}) $("#app-content-region").css({margin:"auto", height:"50%", width: "50%"}) $("#app-content-region").html(html) $("#reload-link").click (e) -> if window.isDesktop then window.quitDesktop() else location.reload() # compare if process.env.VERSION is gte >= than provided minimum version # if minimumVersion is undefined or null, we set to '0.0.0' App.isVersionValid = (minimumVersion) -> Logger.module("APPLICATION").log "#{process.env.VERSION} >= #{minimumVersion || '0.0.0'}" if App._queryStringParams["replayId"] return true else try return semver.gte(process.env.VERSION, minimumVersion || '0.0.0') catch e return true # App.setup is the main entry function into Marionette app # grabs configuration from server we're running on and call App.start() App.setup = () -> # mark all requests with buld version $.ajaxSetup headers: "Client-Version": process.env.VERSION # check if it is a new user and we should redirect otherwise start as normal if Landing.isNewUser() && Landing.shouldRedirect() Landing.redirect() else App.start() # # ---- Application Start Sequence ---- # # App.getMinBrowserVersions() .then (browserlist) -> if !App.isBrowserValid(userAgent.browser.name, userAgent.browser.major, browserlist) return App.browserTestFailed(browserlist) if !App.glTest() return App.glTestFailed() if window.isSteam App.minVersionRef = new Firebase(process.env.FIREBASE_URL).child("system-status").child('steam_minimum_version') else App.minVersionRef = new Firebase(process.env.FIREBASE_URL).child("system-status").child('minimum_version') # wrap App.setup() in _.once() just to be safe from double calling App.setupOnce = _.once(App.setup) # create a timeout to skip version check in case Firebase lags (so atleast user does not get stuck on black screen) App.versionCheckTimeout = setTimeout(() -> App.minVersionRef.off() App.setupOnce() , 5000) # read minimum version from Firebase and perform check, if fails, show error html # otherwise start application as normal App.minVersionRef.once('value', (snapshot) -> clearTimeout(App.versionCheckTimeout) if !App.isVersionValid(snapshot.val()) App.versionTestFailed() else App.setupOnce() )
217195
# User Agent Parsing UAParser = require 'ua-parser-js' uaparser = new UAParser() uaparser.setUA(window.navigator.userAgent) userAgent = uaparser.getResult() # userAgent now contains : browser, os, device, engine objects # ---- Marionette Application ---- # # App = new Backbone.Marionette.Application() # require Firebase via browserify but temporarily alias it global scope Firebase = window.Firebase = require 'firebase' Promise = require 'bluebird' moment = require 'moment' semver = require 'semver' querystring = require 'query-string' # core Storage = require 'app/common/storage' Logger = window.Logger = require 'app/common/logger' Logger.enabled = (process.env.NODE_ENV != 'production' && process.env.NODE_ENV != 'staging') Landing = require 'app/common/landing' Session = window.Session = require 'app/common/session2' CONFIG = window.CONFIG = require 'app/common/config' RSX = window.RSX = require 'app/data/resources' PKGS = window.PKGS = require 'app/data/packages' EventBus = window.EventBus = require 'app/common/eventbus' EVENTS = require 'app/common/event_types' SDK = window.SDK = require 'app/sdk' Analytics = window.Analytics = require 'app/common/analytics' AnalyticsUtil = require 'app/common/analyticsUtil' UtilsJavascript = require 'app/common/utils/utils_javascript' UtilsEnv = require 'app/common/utils/utils_env' UtilsPointer = require 'app/common/utils/utils_pointer' audio_engine = window.audio_engine = require 'app/audio/audio_engine' openUrl = require('app/common/openUrl') i18next = require('i18next') # models and collections CardModel = require 'app/ui/models/card' DuelystFirebase = require 'app/ui/extensions/duelyst_firebase' DuelystBackbone = require 'app/ui/extensions/duelyst_backbone' # Managers / Controllers PackageManager = window.PackageManager = require 'app/ui/managers/package_manager' ProfileManager = window.ProfileManager = require 'app/ui/managers/profile_manager' GameDataManager = window.GameDataManager = require 'app/ui/managers/game_data_manager' GamesManager = window.GamesManager = require 'app/ui/managers/games_manager' CrateManager = window.CrateManager = require 'app/ui/managers/crate_manager' NotificationsManager = window.NotificationsManager = require 'app/ui/managers/notifications_manager' NavigationManager = window.NavigationManager = require 'app/ui/managers/navigation_manager' ChatManager = window.ChatManager = require 'app/ui/managers/chat_manager' InventoryManager = window.InventoryManager = require 'app/ui/managers/inventory_manager' QuestsManager = window.QuestsManager = require 'app/ui/managers/quests_manager' TelemetryManager = window.TelemetryManager = require 'app/ui/managers/telemetry_manager' ProgressionManager = window.ProgressionManager = require 'app/ui/managers/progression_manager' ServerStatusManager = window.ServerStatusManager = require 'app/ui/managers/server_status_manager' NewsManager = window.NewsManager = require 'app/ui/managers/news_manager' NewPlayerManager = window.NewPlayerManager = require 'app/ui/managers/new_player_manager' AchievementsManager = window.AchievementsManager = require 'app/ui/managers/achievements_manager' TwitchManager = window.TwitchManager = require 'app/ui/managers/twitch_manager' ShopManager = window.ShopManager = require 'app/ui/managers/shop_manager' StreamManager = window.StreamManager = require 'app/ui/managers/stream_manager' # Views Helpers = require 'app/ui/views/helpers' LoaderItemView = require 'app/ui/views/item/loader' UtilityLoadingLoginMenuItemView = require 'app/ui/views/item/utility_loading_login_menu' UtilityMainMenuItemView = require 'app/ui/views/item/utility_main_menu' UtilityMatchmakingMenuItemView = require 'app/ui/views/item/utility_matchmaking_menu' UtilityGameMenuItemView = require 'app/ui/views/item/utility_game_menu' EscGameMenuItemView = require 'app/ui/views/item/esc_game_menu' EscMainMenuItemView = require 'app/ui/views/item/esc_main_menu' LoginMenuItemView = require 'app/ui/views/item/login_menu' Discord = if window.isDesktop then require('app/common/discord') else null SelectUsernameItemView = require 'app/ui/views/item/select_username' Scene = require 'app/view/Scene' GameLayer = require 'app/view/layers/game/GameLayer' MainMenuItemView = require 'app/ui/views/item/main_menu' CollectionLayout = require 'app/ui/views2/collection/collection' PlayLayout = require 'app/ui/views/layouts/play' PlayLayer = require 'app/view/layers/pregame/PlayLayer' WatchLayout = require 'app/ui/views2/watch/watch_layout' ShopLayout = require 'app/ui/views2/shop/shop_layout' CodexLayout = require 'app/ui/views2/codex/codex_layout' CodexLayer = require 'app/view/layers/codex/CodexLayer' TutorialLessonsLayout = require 'app/ui/views2/tutorial/tutorial_lessons_layout' QuestLogLayout = require 'app/ui/views2/quests/quest_log_layout' BoosterPackUnlockLayout = require 'app/ui/views/layouts/booster_pack_collection' BoosterPackOpeningLayer = require 'app/view/layers/booster/BoosterPackOpeningLayer' VictoryLayer = require 'app/view/layers/postgame/VictoryLayer' UnlockFactionLayer = require 'app/view/layers/reward/UnlockFactionLayer.js' ProgressionRewardLayer = require 'app/view/layers/reward/ProgressionRewardLayer.js' CosmeticKeyRewardLayer = require 'app/view/layers/reward/CosmeticKeyRewardLayer.js' LadderProgressLayer = require 'app/view/layers/postgame/LadderProgressLayer' RiftProgressLayer = require 'app/view/layers/postgame/RiftProgressLayer' CurrencyRewardLayer = require 'app/view/layers/reward/CurrencyRewardLayer.js' GauntletTicketRewardLayer = require 'app/view/layers/reward/GauntletTicketRewardLayer.js' BoosterRewardLayer = require 'app/view/layers/reward/BoosterRewardLayer.js' LootCrateRewardLayer = require 'app/view/layers/reward/LootCrateRewardLayer.js' FreeCardOfTheDayLayer = require 'app/view/layers/reward/FreeCardOfTheDayLayer.js' CrateOpeningLayer = require 'app/view/layers/crate/CrateOpeningLayer' EndOfSeasonLayer = require 'app/view/layers/season/EndOfSeasonLayer' ResumeGameItemView = require 'app/ui/views/item/resume_game' FindingGameItemView = require 'app/ui/views/item/finding_game' ReconnectToGameItemView = require 'app/ui/views/item/reconnect_to_game' GameLayout = require 'app/ui/views/layouts/game' TutorialLayout = require 'app/ui/views/layouts/tutorial' VictoryItemView = require 'app/ui/views/item/victory' MessagesCompositeView = require 'app/ui/views/composite/messages' ConfirmDialogItemView = require 'app/ui/views/item/confirm_dialog' PromptDialogItemView = require 'app/ui/views/item/prompt_dialog' ActivityDialogItemView = require 'app/ui/views/item/activity_dialog' ErrorDialogItemView = require 'app/ui/views/item/error_dialog' AnnouncementModalView = require 'app/ui/views/item/announcement_modal' ShopSpecialProductAvailableDialogItemView = require 'app/ui/views2/shop/shop_special_product_available_dialog' ReplayEngine = require 'app/replay/replayEngine' AnalyticsTracker = require 'app/common/analyticsTracker' # require the Handlebars Template Helpers extension here since it modifies core Marionette code require 'app/ui/extensions/handlebars_template_helpers' localStorage.debug = 'session:*' # # --- Utility ---- # # App._screenBlurId = "AppScreenBlurId" App._userNavLockId = "AppUserNavLockId" App._queryStringParams = querystring.parse(location.search) # query string params App.getIsLoggedIn = -> return Storage.get('token') # region AI DEV ROUTES # if process.env.AI_TOOLS_ENABLED ### Before using AI DEV ROUTES, make sure you have a terminal open and run `node server/ai/phase_ii_ai.js`. ### window.ai_v1_findNextActions = (playerId, difficulty) -> return new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/v1_find_next_actions", data: JSON.stringify({ game_session_data: SDK.GameSession.getInstance().generateGameSessionSnapshot(), player_id: playerId, difficulty: difficulty }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> actionsData = JSON.parse(res.actions) actions = [] for actionData in actionsData action = SDK.GameSession.getInstance().deserializeActionFromFirebase(actionData) actions.push(action) console.log("v1_find_next_actions -> ", actions) resolve(actions) request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) .catch App._error window.ai_v2_findActionSequence = (playerId, depthLimit, msTimeLimit) -> return new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/v2_find_action_sequence", data: JSON.stringify({ game_session_data: SDK.GameSession.getInstance().generateGameSessionSnapshot(), player_id: playerId, depth_limit: depthLimit, ms_time_limit: msTimeLimit }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> sequenceActionsData = JSON.parse(res.sequence_actions) console.log("ai_v2_findActionSequence -> ", sequenceActionsData) resolve(sequenceActionsData) request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) .catch App._error window.ai_gameStarted = false window.ai_gameRunning = false window.ai_gameStepsData = null window.ai_gameStepsDataPromise = null window.ai_gamePromise = null window.ai_gameNeedsMulligan = false window.ai_stopAIvAIGame = () -> if window.ai_gameStarted window.ai_gameStarted = false window.ai_gameRunning = false window.ai_gameStepsData = null window.ai_gameNeedsMulligan = false if window.ai_gameStepsDataPromise? window.ai_gameStepsDataPromise.cancel() window.ai_gameStepsDataPromise = null if window.ai_gamePromise? window.ai_gamePromise.cancel() window.ai_gamePromise = null return new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/stop_game", data: JSON.stringify({}), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve() request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) .catch App._error window.ai_pauseAIvAIGame = () -> if window.ai_gameRunning window.ai_gameRunning = false window.ai_resumeAIvAIGame = () -> if !window.ai_gameRunning window.ai_gameRunning = true window.ai_stepAIvAIGame() window.ai_runAIvAIGame = (ai1Version, ai2Version, ai1GeneralId, ai2GeneralId, depthLimit, msTimeLimit, ai1NumRandomCards, ai2NumRandomCards) -> # pick random general if none provided if !ai1GeneralId? then ai1GeneralId = _.sample(_.sample(SDK.FactionFactory.getAllPlayableFactions()).generalIds) if !ai2GeneralId? then ai2GeneralId = _.sample(_.sample(SDK.FactionFactory.getAllPlayableFactions()).generalIds) ai1FactionId = SDK.FactionFactory.factionIdForGeneralId(ai1GeneralId) ai2FactionId = SDK.FactionFactory.factionIdForGeneralId(ai2GeneralId) # stop running game window.ai_gamePromise = ai_stopAIvAIGame().then () -> Logger.module("APPLICATION").log("ai_runAIvAIGame - > requesting for v#{ai1Version} w/ general #{SDK.CardFactory.cardForIdentifier(ai1GeneralId, SDK.GameSession.getInstance()).getName()} vs v#{ai2Version} w/ general #{SDK.CardFactory.cardForIdentifier(ai2GeneralId, SDK.GameSession.getInstance()).getName()}") window.ai_gameStarted = true window.ai_gameRunning = true # request run simulation startSimulationPromise = new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/start_game", data: JSON.stringify({ ai_1_version: ai1Version ai_1_general_id: ai1GeneralId ai_2_version: ai2Version ai_2_general_id: ai2GeneralId, depth_limit: depthLimit, ms_time_limit: msTimeLimit, ai_1_num_random_cards: ai1NumRandomCards, ai_2_num_random_cards: ai2NumRandomCards }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve(JSON.parse(res.game_session_data)) request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) # start loading loadingPromise = NavigationManager.getInstance().showDialogForLoad().then () -> return PackageManager.getInstance().loadGamePackageWithoutActivation([ai1FactionId, ai2FactionId]) return Promise.all([ startSimulationPromise, loadingPromise ]) .spread (sessionData) -> Logger.module("APPLICATION").log("ai_runAIvAIGame - > starting #{sessionData.gameId} with data:", sessionData) # reset and deserialize SDK.GameSession.reset() SDK.GameSession.getInstance().deserializeSessionFromFirebase(sessionData) # switch session game type to sandbox SDK.GameSession.getInstance().setGameType(SDK.GameType.Sandbox) # set game user id to match player 1 SDK.GameSession.getInstance().setUserId(SDK.GameSession.getInstance().getPlayer1Id()) return App._startGame() .then () -> Logger.module("APPLICATION").log("ai_runAIvAIGame - > #{SDK.GameSession.getInstance().getGameId()} running") # stop running game when game is terminated Scene.getInstance().getGameLayer().getEventBus().on(EVENTS.terminate, window.ai_stopAIvAIGame) # listen for finished showing step # wait for active (ai will already have mulliganed) return Scene.getInstance().getGameLayer().whenStatus(GameLayer.STATUS.ACTIVE).then () -> Scene.getInstance().getGameLayer().getEventBus().on(EVENTS.after_show_step, window.ai_stepAIvAIGame) # execute first step in sequence window.ai_stepAIvAIGame() .cancellable() .catch Promise.CancellationError, (e)-> Logger.module("APPLICATION").log("ai_runAIvAIGame -> promise chain cancelled") .catch App._error return ai_gamePromise window.ai_runAIvAIGameFromCurrentSession = (ai1Version, ai2Version, depthLimit, msTimeLimit) -> # stop running game window.ai_gamePromise = ai_stopAIvAIGame().then () -> Logger.module("APPLICATION").log("ai_runAIvAIGameFromCurrentSession - > requesting for v#{ai1Version} vs v#{ai2Version}") window.ai_gameStarted = true window.ai_gameRunning = true # set as non authoritative # all steps will be coming from ai simulation server SDK.GameSession.getInstance().setIsRunningAsAuthoritative(false); # request run simulation return new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/start_game_from_data", data: JSON.stringify({ ai_1_version: ai1Version ai_2_version: ai2Version depth_limit: depthLimit, ms_time_limit: msTimeLimit, game_session_data: SDK.GameSession.getInstance().generateGameSessionSnapshot() }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve() request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) .then () -> # stop running game when game is terminated Scene.getInstance().getGameLayer().getEventBus().on(EVENTS.terminate, window.ai_stopAIvAIGame) # listen for finished showing step Scene.getInstance().getGameLayer().whenStatus(GameLayer.STATUS.ACTIVE).then () -> Scene.getInstance().getGameLayer().getEventBus().on(EVENTS.after_show_step, window.ai_stepAIvAIGame) if window.ai_gameNeedsMulligan Logger.module("APPLICATION").log("ai_stepAIvAIGame -> mulligan complete") window.ai_gameNeedsMulligan = false window.ai_stepAIvAIGame() # check if needs mulligan window.ai_gameNeedsMulligan = SDK.GameSession.getInstance().isNew() # execute first step in sequence window.ai_stepAIvAIGame() .cancellable() .catch Promise.CancellationError, (e)-> Logger.module("APPLICATION").log("ai_runAIvAIGameFromCurrentSession -> promise chain cancelled") .catch App._error return ai_gamePromise window.ai_stepAIvAIGame = (event) -> if event?.step?.action instanceof SDK.EndTurnAction then return # ignore auto stepping due to end turn action as start turn will cause auto step Logger.module("APPLICATION").log("ai_stepAIvAIGame -> #{SDK.GameSession.getInstance().getGameId()} step queue length #{Scene.getInstance().getGameLayer()._stepQueue.length}") if !window.ai_gameStepsDataPromise? and Scene.getInstance().getGameLayer()._stepQueue.length == 0 # request step game window.ai_gameStepsDataPromise = new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/step_game", data: JSON.stringify({ game_id: SDK.GameSession.getInstance().getGameId() }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> if res.steps? resolve(JSON.parse(res.steps)) else resolve([]) request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) .then (stepsData) -> Logger.module("APPLICATION").log("ai_stepAIvAIGame -> steps:", stepsData.slice(0)) window.ai_gameStepsData = stepsData .cancellable() .catch Promise.CancellationError, (e)-> Logger.module("APPLICATION").log("ai_stepAIvAIGame -> promise chain cancelled") return window.ai_gameStepsDataPromise.then () -> if window.ai_gameRunning and !SDK.GameSession.getInstance().isOver() and window.ai_gameStepsData? and window.ai_gameStepsData.length > 0 # remove and deserialize next step in sequence stepData = window.ai_gameStepsData.shift() step = SDK.GameSession.getInstance().deserializeStepFromFirebase(stepData) Logger.module("APPLICATION").log("ai_stepAIvAIGame -> step:", step) # execute step SDK.GameSession.getInstance().executeAuthoritativeStep(step) # check game status and steps data if SDK.GameSession.getInstance().isOver() or window.ai_gameStepsData.length == 0 Logger.module("APPLICATION").log("ai_stepAIvAIGame -> done") window.ai_gameStepsData = null window.ai_gameStepsDataPromise = null else if step.action instanceof SDK.EndTurnAction # auto step to start turn Logger.module("APPLICATION").log("ai_stepAIvAIGame -> continuing end turn") window.ai_stepAIvAIGame() else if window.ai_gameNeedsMulligan # auto step to next mulligan Logger.module("APPLICATION").log("ai_stepAIvAIGame -> continuing mulligan") window.ai_stepAIvAIGame() window.ai_runHeadlessAIvAIGames = (numGames, ai1Version, ai2Version, ai1GeneralId, ai2GeneralId, depthLimit, msTimeLimit, ai1NumRandomCards, ai2NumRandomCards) -> Logger.module("APPLICATION").log("ai_runHeadlessAIvAIGames - > requesting #{numGames} games with v#{ai1Version} vs v#{ai2Version}") # request run games return new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/run_headless_games", data: JSON.stringify({ ai_1_version: ai1Version ai_1_general_id: ai1GeneralId ai_2_version: ai2Version ai_2_general_id: ai2GeneralId, num_games: numGames, depth_limit: depthLimit, ms_time_limit: msTimeLimit, ai_1_num_random_cards: ai1NumRandomCards, ai_2_num_random_cards: ai2NumRandomCards }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve() request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) # endregion AI DEV ROUTES # # # --- Main ---- # # App.getIsShowingMain = () -> # temporary method to check if the user can navigate to main (i.e. not already there) # this does NOT work for switching between main sub-screens return NavigationManager.getInstance().getIsShowingContentViewClass(LoginMenuItemView) or NavigationManager.getInstance().getIsShowingContentViewClass(MainMenuItemView) or NavigationManager.getInstance().getIsShowingContentViewClass(ResumeGameItemView) App.main = -> if !App._mainPromise? App._mainPromise = App._startPromise.then(() -> Logger.module("APPLICATION").log("App:main") # get and reset last game data lastGameType = CONFIG.lastGameType wasSpectate = CONFIG.lastGameWasSpectate wasTutorial = CONFIG.lastGameWasTutorial wasDeveloper = CONFIG.lastGameWasDeveloper wasDailyChallenge = CONFIG.lastGameWasDailyChallenge CONFIG.resetLastGameData() # destroy game and clear game data App.cleanupGame() # always make sure we're disconnected from the last game SDK.NetworkManager.getInstance().disconnect() # reset routes to main NavigationManager.getInstance().resetRoutes() NavigationManager.getInstance().addMajorRoute("main", App.main, App) # always restore user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationUnlocked(App._userNavLockId) if App._queryStringParams["replayId"]? Logger.module("APPLICATION").log("jumping straight into replay...") App.setCallbackWhenCancel(()-> alert('all done!')) return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> EventBus.getInstance().trigger(EVENTS.start_replay, { replayId: App._queryStringParams["replayId"] }) return Promise.resolve() ) else if !App.getIsLoggedIn() return App._showLoginMenu() else # all good, show main menu return App.managersReadyDeferred.promise.then(() -> # set user as loading ChatManager.getInstance().setStatus(ChatManager.STATUS_LOADING) # # EULA ACCEPTANCE CHECK HERE SO IT FIRES FOR ALREADY LOGGED IN PLAYERS # # strings used for session storage and profile storage # sessionAcceptedEula = Storage.namespace() + '.hasAcceptedEula' # storageAcceptedEula = 'hasAcceptedEula' # storageSentAcceptedEulaNotify = 'hasSentAcceptedEulaNotify' # # the user has accepted terms in the local session, ensure we are set in profile storage # if window.sessionStorage.getItem(sessionAcceptedEula) # ProfileManager.getInstance().set(storageAcceptedEula, true) # # check in profile storage if the user has accepted terms # if !ProfileManager.getInstance().get(storageAcceptedEula) # # TODO - This is not actually good, but we need to make a new terms and conditions page to replace BNEA one # return App._showTerms() # # user has accepted, check if they have sent notification # else # if !ProfileManager.getInstance().get(storageSentAcceptedEulaNotify) # ProfileManager.getInstance().set(storageSentAcceptedEulaNotify, true) # check for an active game lastGameModel = null if GamesManager.getInstance().playerGames.length > 0 lastGameModel = GamesManager.getInstance().playerGames.first() # calculate minutes since last game msSinceLastGame = moment().utc().valueOf() - (lastGameModel?.get("created_at") || 0) minutesSinceLastGame = moment.duration(msSinceLastGame).asMinutes() # if the last game is an active multiplayer game within last 45 minutes, show the continue game screen if lastGameModel? and lastGameModel.get("cancel_reconnect") != true and (lastGameModel.get("status") == "active" || lastGameModel.get("status") == "new") and lastGameModel.get("created_at") and minutesSinceLastGame < CONFIG.MINUTES_ALLOWED_TO_CONTINUE_GAME and SDK.GameType.isMultiplayerGameType(lastGameModel.get("game_type")) # has active game, prompt user to resume Logger.module("UI").log("Last active game was on ", new Date(lastGameModel.get("created_at")), "with data", lastGameModel) return App._resumeGame(lastGameModel) else if not NewPlayerManager.getInstance().isDoneWithTutorial() # show tutorial layout return App._showTutorialLessons() else if QuestsManager.getInstance().hasUnreadQuests() # show main menu return App._showMainMenu() else # try to return to selection for previous game type if wasSpectate return App._showMainMenu() else if wasDailyChallenge QuestsManager.getInstance().markDailyChallengeCompletionAsUnread() return App._showMainMenu() else if lastGameType == SDK.GameType.Ranked and !NewPlayerManager.getInstance().getEmphasizeBoosterUnlock() return App.showPlay(SDK.PlayModes.Ranked, true) else if lastGameType == SDK.GameType.Casual and !NewPlayerManager.getInstance().getEmphasizeBoosterUnlock() return App.showPlay(SDK.PlayModes.Casual, true) else if lastGameType == SDK.GameType.Gauntlet return App.showPlay(SDK.PlayModes.Gauntlet, true) else if lastGameType == SDK.GameType.Challenge and !wasTutorial return App.showPlay(SDK.PlayModes.Challenges, true) else if lastGameType == SDK.GameType.SinglePlayer return App.showPlay(SDK.PlayModes.Practice, true) else if lastGameType == SDK.GameType.BossBattle return App.showPlay(SDK.PlayModes.BossBattle, true) else if lastGameType == SDK.GameType.Sandbox and !wasDeveloper return App.showPlay(SDK.PlayModes.Sandbox, true) else if lastGameType == SDK.GameType.Rift return App.showPlay(SDK.PlayModes.Rift, true) else return App._showMainMenu() ) ).finally () -> App._mainPromise = null return Promise.resolve() return App._mainPromise App._showLoginMenu = (options) -> Logger.module("APPLICATION").log("App:_showLoginMenu") return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, (() -> # analytics call Analytics.page("Login",{ path: "/#login" }) # show main scene viewPromise = Scene.getInstance().showMain() # show login menu contentPromise = NavigationManager.getInstance().showContentView(new LoginMenuItemView(options)) # show utility menu for desktop only if window.isDesktop utilityPromise = NavigationManager.getInstance().showUtilityView(new UtilityLoadingLoginMenuItemView()) else utilityPromise = Promise.resolve() return Promise.all([ viewPromise, contentPromise, utilityPromise ]) ) ) App._showSelectUsername = (data) -> Logger.module("APPLICATION").log("App:_showSelectUsername") return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, (() -> # show main scene viewPromise = Scene.getInstance().showMain() # show selection dialog selectUsernameModel = new Backbone.Model({}) selectUsernameItemView = new SelectUsernameItemView({model: selectUsernameModel}) selectUsernameItemView.listenToOnce(selectUsernameItemView, "success", () => # TODO: move this into SelectUsernameItemView # We refresh token so the username property is now included Session.refreshToken() .then (refreshed) -> return ) contentPromise = NavigationManager.getInstance().showDialogView(selectUsernameItemView) return Promise.all([ NavigationManager.getInstance().destroyModalView(), NavigationManager.getInstance().destroyContentView(), viewPromise, contentPromise ]) ) ) App._showTerms = (options = {}) -> Logger.module("APPLICATION").log("App:_showTerms") return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, (() -> # show main scene viewPromise = Scene.getInstance().showMain() if App.getIsLoggedIn() if window.isSteam ProfileManager.getInstance().set('hasAcceptedSteamEula', true) else ProfileManager.getInstance().set('hasAcceptedEula', true) mainPromise = App.main() else if window.isSteam window.sessionStorage.setItem(Storage.namespace() + '.hasAcceptedSteamEula', true) else window.sessionStorage.setItem(Storage.namespace() + '.hasAcceptedEula', true) mainPromise = App._showLoginMenu({type: 'register'}) return Promise.all([ viewPromise, # contentPromise mainPromise ]) ) ) App._showTutorialLessons = (lastCompletedChallenge) -> Logger.module("APPLICATION").log("App:_showTutorialChallenges") return PackageManager.getInstance().loadAndActivateMajorPackage "nongame", null, null, () -> # analytics call Analytics.page("Tutorial Lessons",{ path: "/#tutorial_lessons" }) # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # show main scene viewPromise = Scene.getInstance().showMain().then(() -> # play main layer music mainLayer = Scene.getInstance().getMainLayer() if mainLayer? then mainLayer.playMusic() ) # show main menu tutorialLessonsLayoutView = new TutorialLessonsLayout({ lastCompletedChallenge:lastCompletedChallenge, }) contentPromise = NavigationManager.getInstance().showContentView(tutorialLessonsLayoutView) return Promise.all([ viewPromise, contentPromise ]) App._showMainMenu = () -> Logger.module("APPLICATION").log("App:_showMainMenu") return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # analytics call Analytics.page("Main Menu",{ path: "/#main_menu" }) # notify Discord status if Discord presence = { instance: 0 details: 'In Main Menu' largeImageKey: 'idle' } Discord.updatePresence(presence) # show main scene viewPromise = Scene.getInstance().showMain().then(() -> # play main layer music mainLayer = Scene.getInstance().getMainLayer() if mainLayer? then mainLayer.playMusic() ) endOfSeasonRewardsPromise = App.showEndOfSeasonRewards() return endOfSeasonRewardsPromise.then( () -> # show achievement rewards achievementsPromise = App.showAchievementCompletions() return achievementsPromise .then(()-> # show twitch rewards twitchRewardPromise = App.showTwitchRewards() return twitchRewardPromise ).then(() -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # show main menu contentPromise = NavigationManager.getInstance().showContentView(new MainMenuItemView({model: ProfileManager.getInstance().profile})) # show utility menu utilityPromise = NavigationManager.getInstance().showUtilityView(new UtilityMainMenuItemView({model: ProfileManager.getInstance().profile})) if NewsManager.getInstance().getFirstUnreadAnnouncement() # show announcment UI if we have an unread announcement modalPromise = NewsManager.getInstance().getFirstUnreadAnnouncementContentAsync().then((announcementContentModel)-> return NavigationManager.getInstance().showModalView(new AnnouncementModalView({model:announcementContentModel})); ) else # show quests if any quests modalPromise = Promise.resolve() if QuestsManager.getInstance().hasUnreadQuests() or QuestsManager.getInstance().hasUnreadDailyChallenges() modalPromise = NavigationManager.getInstance().toggleModalViewByClass(QuestLogLayout,{ collection: QuestsManager.getInstance().getQuestCollection(), model: ProgressionManager.getInstance().gameCounterModel showConfirm:true }) return Promise.all([ viewPromise, contentPromise, modalPromise, utilityPromise ]) ) ) ) # # --- Major Layouts ---- # # App.showPlay = (playModeIdentifier, showingDirectlyFromGame) -> if !App.getIsLoggedIn() return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # force play mode to string if !_.isString(playModeIdentifier) then playModeIdentifier = "" # add mode to route NavigationManager.getInstance().addMajorRoute("play_" + playModeIdentifier, App.showPlay, App, [playModeIdentifier]) # if currently in play modes, show new play mode direct currentContentView = NavigationManager.getInstance().getContentView() if currentContentView instanceof PlayLayout return currentContentView.showPlayMode(playModeIdentifier) else if showingDirectlyFromGame # show play layer viewPromise = Scene.getInstance().showContentByClass(PlayLayer, true) # show achievement rewards achievementsPromise = App.showAchievementCompletions() else achievementsPromise = viewPromise = Promise.resolve() return achievementsPromise.then(() -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # show UI return Promise.all([ viewPromise, NavigationManager.getInstance().showContentView(new PlayLayout({model: new Backbone.Model({playModeIdentifier: playModeIdentifier})})) ]).then ()-> # update available shop specials with current top rank and win count model and notify user if a new one has become available if ShopManager.getInstance().isNewSpecialAvailable ShopManager.getInstance().markNewAvailableSpecialAsRead() NavigationManager.getInstance().showDialogView(new ShopSpecialProductAvailableDialogItemView({ model: ShopManager.getInstance().availableSpecials.at(ShopManager.getInstance().availableSpecials.length-1) })) ) ) App.showWatch = ()-> if !App.getIsLoggedIn() or NavigationManager.getInstance().getContentView() instanceof WatchLayout return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage "nongame", null, null, () -> Analytics.page("Watch",{ path: "/#watch" }) # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # add mode to route NavigationManager.getInstance().addMajorRoute("watch", App.showWatch, App) # show layout return NavigationManager.getInstance().showContentView(new WatchLayout()) App.showShop = ()-> if !App.getIsLoggedIn() return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage "nongame", null, null, () -> Analytics.page("Shop",{ path: "/#shop" }) # add mode to route NavigationManager.getInstance().addMajorRoute("shop", App.showShop, App) # show layout NavigationManager.getInstance().showContentView(new ShopLayout()) App.showCollection = () -> if !App.getIsLoggedIn() or NavigationManager.getInstance().getContentView() instanceof CollectionLayout return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # add mode to route NavigationManager.getInstance().addMajorRoute("collection", App.showCollection, App) # notify Discord status if Discord presence = { instance: 0 details: 'Browsing Collection' largeImageKey: '<KEY>' } Discord.updatePresence(presence) # show UI return Promise.all([ Scene.getInstance().showMain() NavigationManager.getInstance().showContentView(new CollectionLayout({model: new Backbone.Model()})) ]) ) App.showCodex = () -> if !App.getIsLoggedIn() or NavigationManager.getInstance().getContentView() instanceof CodexLayout return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # add mode to route NavigationManager.getInstance().addMajorRoute("codex", App.showCodex, App) # show UI return Promise.all([ Scene.getInstance().showContent(new CodexLayer(), true), NavigationManager.getInstance().showContentView(new CodexLayout({model: new Backbone.Model()})) ]) ) App.showBoosterPackUnlock = () -> if !App.getIsLoggedIn() or NavigationManager.getInstance().getContentView() instanceof BoosterPackUnlockLayout return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # add route NavigationManager.getInstance().addMajorRoute("booster_pack_unlock", App.showBoosterPackUnlock, App) # show UI return Promise.all([ Scene.getInstance().showContent(new BoosterPackOpeningLayer(), true), NavigationManager.getInstance().showContentView(new BoosterPackUnlockLayout()) ]) ) App.showCrateInventory = () -> if !App.getIsLoggedIn() or Scene.getInstance().getOverlay() instanceof CrateOpeningLayer return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # add route NavigationManager.getInstance().addMajorRoute("crate_inventory", App.showCrateInventory, App) # show UI return Promise.all([ NavigationManager.getInstance().destroyContentView(), Scene.getInstance().showOverlay(new CrateOpeningLayer()) ]) ) # # --- Session Events ---- # # App.onLogin = (data) -> Logger.module("APPLICATION").log "User logged in: #{data.userId}" # save token to localStorage Storage.set('token', data.token) # setup ajax headers for jquery/backbone requests $.ajaxSetup headers: { Authorization: "Bearer #{data.token}" "Client-Version": window.BUILD_VERSION } # check is new signup flag is passed # can't use analytics data since the first login may have # already happened on /register page if Landing.isNewSignup() Landing.addPixelsToHead() Landing.firePixels() # check for null username here # dialog should be uncancelleable # dialog success should re-trigger session login so new token contains all required params if !Session.username return App._showSelectUsername(data) # Trigger the eventbus login event for the utilty menus EventBus.getInstance().trigger EVENTS.session_logged_in # connect all managers ProfileManager.getInstance().connect({userId: data.userId}) GameDataManager.getInstance().connect() GamesManager.getInstance().connect() ChatManager.getInstance().connect() QuestsManager.getInstance().connect() InventoryManager.getInstance().connect() NavigationManager.getInstance().connect() NotificationsManager.getInstance().connect() ProgressionManager.getInstance().connect() ServerStatusManager.getInstance().connect() TelemetryManager.getInstance().connect() NewsManager.getInstance().connect() NewPlayerManager.getInstance().connect() AchievementsManager.getInstance().connect() TwitchManager.getInstance().connect() CrateManager.getInstance().connect() ShopManager.getInstance().connect() StreamManager.getInstance().connect() TelemetryManager.getInstance().clearSignal("session","not-logged-in") TelemetryManager.getInstance().setSignal("session","logged-in") Promise.all([ ProfileManager.getInstance().onReady(), InventoryManager.getInstance().onReady(), QuestsManager.getInstance().onReady(), GamesManager.getInstance().onReady(), GameDataManager.getInstance().onReady(), ChatManager.getInstance().onReady(), ProgressionManager.getInstance().onReady(), ServerStatusManager.getInstance().onReady(), NewPlayerManager.getInstance().onReady(), AchievementsManager.getInstance().onReady(), TwitchManager.getInstance().onReady(), CrateManager.getInstance().onReady() ]).then () -> # update resolution values as of login App._updateLastResolutionValues() # we're all done loading managers App.managersReadyDeferred.resolve() # setup analytics App.onLoginAnalyticsSetup(data) # show the main screen return App.main() .catch (err) -> App.managersReadyDeferred.reject() Logger.module("APPLICATION").log("ERROR initializing managers") if err == null then err = new Error("ERROR initializing managers") App._error(err.message) throw err .finally () -> # NavigationManager.getInstance().destroyDialogView() App.onLoginAnalyticsSetup = (loginData) -> # region analytics data # Include users analytics data retrieved with session identifyParams = {} utmParams = {} hadPreviousSession = false if loginData.analyticsData? utmParams = _.extend(utmParams, loginData.analyticsData) if (utmParams.first_purchased_at?) # Shouldn't be necessary but just in case utmParams.first_purchased_at = moment.utc(utmParams.first_purchased_at).toISOString() if loginData.analyticsData.last_session_at delete utmParams.last_session_at hadPreviousSession = true # identify the user with the partial data until we connect managers Analytics.identify(loginData.userId, identifyParams, utmParams) if not hadPreviousSession Analytics.track("first login",{ category:Analytics.EventCategory.FTUE, },{ nonInteraction:1 sendUTMData:true }) Analytics.track("registered", { category:Analytics.EventCategory.Marketing },{ sendUTMData:true nonInteraction:1 }) # endregion analytics data # region analytics data # identify the user with their current rank gamesManager = GamesManager.getInstance() rank = gamesManager.rankingModel.get("rank") # default rank to 30 if it's null rank = 30 if (!rank?) # top rank topRank = gamesManager.topRankingModel.get("top_rank") topRank = gamesManager.topRankingModel.get("rank") if(!topRank?) topRank = 30 if(!topRank?) # game count gameCount = ProgressionManager.getInstance().getGameCount() # set up the params to pass for the identify call identifyParams.rank = rank identifyParams.top_ever_rank = topRank identifyParams.game_count = gameCount # if we know the registration date if ProfileManager.getInstance().get("created_at") # turn it to a sortable registered_at = moment.utc(ProfileManager.getInstance().get("created_at")).toISOString() # set it on the identifyParams identifyParams.registration_date = registered_at # if this user has an LTV parameter if ProfileManager.getInstance().get("ltv") # set it on the identifyParams identifyParams.ltv = ProfileManager.getInstance().get("ltv") # Check if today is a recorded seen on day and add it to identifyParams todaysSeenOnIndex = AnalyticsUtil.recordedDayIndexForRegistrationAndSeenOn(moment.utc(ProfileManager.getInstance().get("created_at")),moment.utc()) if todaysSeenOnIndex? identifyParams[AnalyticsUtil.nameForSeenOnDay(todaysSeenOnIndex)] = 1 # re-identify the user with better data now that we have managers connected and pass in the custom dimensions Analytics.identify(ProfileManager.getInstance().get('id'), identifyParams, utmParams) Analytics.track("login", { category:Analytics.EventCategory.Marketing },{ sendUTMData:true nonInteraction:1 }) # endregion analytics data App.onLogout = () -> Logger.module("APPLICATION").log "User logged out." TelemetryManager.getInstance().clearSignal("session","logged-in") TelemetryManager.getInstance().setSignal("session","not-logged-in") # create a new deferred object for managers loading process App.managersReadyDeferred = new Promise.defer() # destroy out any login specific menus NavigationManager.getInstance().destroyNonContentViews() # stop playing any music audio_engine.current().stop_music() Analytics.reset() # reset config CONFIG.reset() # remove token Storage.remove('token') # remove ajax headers with new call to ajaxSetup $.ajaxSetup headers: { Authorization: "" } # Trigger the eventbus logout event for the ui/managers EventBus.getInstance().trigger EVENTS.session_logged_out # go back to main to show login menu App.main() # just logs the error for debugging App.onSessionError = (error) -> Logger.module("APPLICATION").log "Session Error: #{error.message}" # # ---- Pointer ---- # # App._$canvasMouseClassEl = null App._currentMouseClass = null App.onCanvasMouseState = (e) -> if e?.state? then mouseClass = "mouse-" + e.state.toLowerCase() else mouseClass = "mouse-auto" if App._currentMouseClass != mouseClass App._$canvasMouseClassEl ?= $(CONFIG.GAMECANVAS_SELECTOR) if App._currentMouseClass == "mouse-auto" App._$canvasMouseClassEl.addClass(mouseClass) else if mouseClass == "mouse-auto" App._$canvasMouseClassEl.removeClass(App._currentMouseClass) else App._$canvasMouseClassEl.removeClass(App._currentMouseClass).addClass(mouseClass) App._currentMouseClass = mouseClass App.onPointerDown = (event) -> # update pointer if event? $app = $(CONFIG.APP_SELECTOR) offset = $app.offset() UtilsPointer.setPointerFromDownEvent(event, $app.height(), offset.left, offset.top) # trigger pointer event pointerEvent = UtilsPointer.getPointerEvent() pointerEvent.type = EVENTS.pointer_down pointerEvent.target = event.target EventBus.getInstance().trigger(pointerEvent.type, pointerEvent) # before passing event to view, stop propagation when the target of the pointer event is not the game canvas # however, continue pass the event down to the view and let listeners decide whether to use it if !$(CONFIG.GAMECANVAS_SELECTOR).is(event.target) pointerEvent.stopPropagation() Scene.getInstance().getEventBus().trigger(pointerEvent.type, pointerEvent) return true App.onPointerUp = (event) -> # update pointer if event? $app = $(CONFIG.APP_SELECTOR) offset = $app.offset() UtilsPointer.setPointerFromUpEvent(event, $app.height(), offset.left, offset.top) # trigger pointer event pointerEvent = UtilsPointer.getPointerEvent() pointerEvent.type = EVENTS.pointer_up pointerEvent.target = event.target EventBus.getInstance().trigger(pointerEvent.type, pointerEvent) # before passing event to view, stop propagation when the target of the pointer event is not the game canvas # however, continue pass the event down to the view and let listeners decide whether to use it if !$(CONFIG.GAMECANVAS_SELECTOR).is(event.target) pointerEvent.stopPropagation() Scene.getInstance().getEventBus().trigger(pointerEvent.type, pointerEvent) return true App.onPointerMove = (event) -> # update pointer if event? $app = $(CONFIG.APP_SELECTOR) offset = $app.offset() UtilsPointer.setPointerFromMoveEvent(event, $app.height(), offset.left, offset.top) # trigger pointer events pointerEvent = UtilsPointer.getPointerEvent() pointerEvent.type = EVENTS.pointer_move pointerEvent.target = event.target EventBus.getInstance().trigger(pointerEvent.type, pointerEvent) # before passing event to view, stop propagation when the target of the pointer event is not the game canvas # however, continue pass the event down to the view and let listeners decide whether to use it if !$(CONFIG.GAMECANVAS_SELECTOR).is(event.target) pointerEvent.stopPropagation() Scene.getInstance().getEventBus().trigger(pointerEvent.type, pointerEvent) return true App.onPointerWheel = (event) -> # update pointer if event? target = event.target $app = $(CONFIG.APP_SELECTOR) offset = $app.offset() UtilsPointer.setPointerFromWheelEvent(event.originalEvent, $app.height(), offset.left, offset.top) # trigger pointer events pointerEvent = UtilsPointer.getPointerEvent() pointerEvent.type = EVENTS.pointer_wheel pointerEvent.target = target EventBus.getInstance().trigger(pointerEvent.type, pointerEvent) # before passing event to view, stop propagation when the target of the pointer event is not the game canvas # however, continue pass the event down to the view and let listeners decide whether to use it if !$(CONFIG.GAMECANVAS_SELECTOR).is(target) pointerEvent.stopPropagation() Scene.getInstance().getEventBus().trigger(pointerEvent.type, pointerEvent) return true # # --- Game Invites ---- # # App._inviteAccepted = ()-> Logger.module("APPLICATION").log("App._inviteAccepted") App.showPlay(SDK.PlayModes.Friend) App._inviteRejected = () -> Logger.module("APPLICATION").log("App._inviteRejected") return App.main().then(() -> return NavigationManager.getInstance().showDialogView(new PromptDialogItemView({title: i18next.t("buddy_list.message_rejected_game_invite")})) ) App._inviteCancelled = () -> App._cleanupMatchmakingListeners() Logger.module("APPLICATION").log("App._inviteCancelled") return App.main().then(() -> return NavigationManager.getInstance().showDialogView(new PromptDialogItemView({title: i18next.t("buddy_list.message_cancelled_game_invite")})) ) # # --- Game Spectate ---- # # App._spectateGame = (e) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._spectateGame -> cannot start game when already in a game!") return gameListingData = e.gameData playerId = e.playerId spectateToken = e.token Logger.module("APPLICATION").log("App._spectateGame", gameListingData) NavigationManager.getInstance().showDialogForLoad() .then ()-> # load resources for game return PackageManager.getInstance().loadGamePackageWithoutActivation([ gameListingData["faction_id"], gameListingData["opponent_faction_id"] ]) .then () -> # listen to join game events joinGamePromise = App._subscribeToJoinGameEventsPromise() # join game and if a game server is assigned to this listing, connect there SDK.NetworkManager.getInstance().connect(gameListingData["game_id"], playerId, gameListingData["game_server"], ProfileManager.getInstance().get('id'), spectateToken) return joinGamePromise.then((gameSessionData) -> # reset and deserialize SDK.GameSession.reset() SDK.GameSession.getInstance().deserializeSessionFromFirebase(gameSessionData) SDK.GameSession.getInstance().setUserId(playerId) SDK.GameSession.getInstance().setIsSpectateMode(true) # do not start games that are already over if !SDK.GameSession.getInstance().isOver() return App._startGame() else return Promise.reject() ).catch((errorMessage) -> return App._error(errorMessage) ) # See games_manager spectateBuddyGame method, works same way App.spectateBuddyGame = (buddyId) -> return new Promise (resolve, reject) -> request = $.ajax({ url: process.env.API_URL + '/api/me/spectate/' + buddyId, type: 'GET', contentType: 'application/json', dataType: 'json' }) request.done (response) -> App._spectateGame({ gameData: response.gameData, token: response.token, playerId: buddyId }) resolve(response) request.fail (response) -> error = response && response.responseJSON && response.responseJSON.error || 'SPECTATE request failed' EventBus.getInstance().trigger(EVENTS.ajax_error, error) reject(new Error(error)) # Event handler fired when spectate is pressed in Discord with spectateSecret passed in # We use the buddyId as the spectateSecret App.onDiscordSpectate = (args...) -> buddyId = args[0] Logger.module("DISCORD").log("attempting to spectate #{buddyId}") # we wait until managers are loaded as we need to be logged in return App.managersReadyDeferred.promise.then () -> # do nothing if they are already in game or in queue if ChatManager.getInstance().getStatusIsInBattle() || ChatManager.getInstance().getStatusQueue() Logger.module("DISCORD").log("cannot spectate game when already in a game!") return # do nothing if they are attempting to spectate theirselves if ProfileManager.getInstance().get('id') == buddyId Logger.module("DISCORD").log("cannot spectate yourself!") return # fire spectate request return App.main().then () -> App.spectateBuddyGame(buddyId) # # --- Game Matchmaking ---- # # App._error = (errorMessage) -> Logger.module("APPLICATION").log("App._error", errorMessage) # always unlock user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationUnlocked(App._userNavLockId) if errorMessage? # if we're in the process of loading the main menu # show the error dialog and don't go to main menu # to avoid infinite loop of loading main menu if App._mainPromise or process.env.NODE_ENV == "local" return NavigationManager.getInstance().showDialogView(new ErrorDialogItemView({message:errorMessage})) else # otherwise load the main menu and show the error dialog return App.main().then () -> return NavigationManager.getInstance().showDialogView(new ErrorDialogItemView({message:errorMessage})) else return App.main() App._cleanupMatchmakingListeners = ()-> # remove all found game listeners as new ones will be registered when we re-enter matchmaking GamesManager.getInstance().off("found_game") # force reject the existing found game promise when we cancel # this is important because this promise is wrapped around the "found_game" event and a chain of stuff is waiting for it to resolve! # if we don't cancel here, we will have a promise that never resolves and thus leaks memory if App._foundGamePromise? App._foundGamePromise.cancel() App._matchmakingStart = () -> Logger.module("APPLICATION").log("App._matchmakingStart") App._matchmakingCancel = () -> Logger.module("APPLICATION").log("App._matchmakingCancel") App._cleanupMatchmakingListeners() App._matchmakingError = (errorMessage) -> Logger.module("APPLICATION").log("App._matchmakingError", errorMessage) App._cleanupMatchmakingListeners() return App._error(errorMessage) App._playerDataFromGameListingData = (gameListingData) -> myPlayerIsPlayer1 = gameListingData.is_player_1 playerDataModel= new Backbone.Model({ myPlayerIsPlayer1: myPlayerIsPlayer1 myPlayerId: ProfileManager.getInstance().get('id') myPlayerUsername: ProfileManager.getInstance().get("username") myPlayerFactionId: gameListingData.faction_id myPlayerGeneralId: gameListingData.general_id opponentPlayerId: gameListingData.opponent_id opponentPlayerUsername: gameListingData.opponent_username opponentPlayerFactionId: gameListingData.opponent_faction_id opponentPlayerGeneralId: gameListingData.opponent_general_id }) if myPlayerIsPlayer1 playerDataModel.set({ player1Id: playerDataModel.get("myPlayerId"), player1Username: playerDataModel.get("myPlayerUsername"), player1FactionId: playerDataModel.get("myPlayerFactionId"), player1GeneralId: playerDataModel.get("myPlayerGeneralId"), player2Id: playerDataModel.get("opponentPlayerId"), player2Username: playerDataModel.get("opponentPlayerUsername"), player2FactionId: playerDataModel.get("opponentPlayerFactionId"), player2GeneralId: playerDataModel.get("opponentPlayerGeneralId") }) else playerDataModel.set({ player1Id: playerDataModel.get("opponentPlayerId"), player1Username: playerDataModel.get("opponentPlayerUsername"), player1FactionId: playerDataModel.get("opponentPlayerFactionId"), player1GeneralId: playerDataModel.get("opponentPlayerGeneralId"), player2Id: playerDataModel.get("myPlayerId"), player2Username: playerDataModel.get("myPlayerUsername"), player2FactionId: playerDataModel.get("myPlayerFactionId"), player2GeneralId: playerDataModel.get("myPlayerGeneralId") }) return playerDataModel App._findingGame = (gameMatchRequestData) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._findingGame -> cannot start game when already in a game!") return Logger.module("APPLICATION").log("App._findingGame", gameMatchRequestData) # analytics call Analytics.page("Finding Game",{ path: "/#finding_game" }) # notify Discord status if Discord presence = { instance: 0 largeImageKey: 'idle' } if gameMatchRequestData.gameType == 'ranked' presence.details = 'In Ranked Queue' else if gameMatchRequestData.gameType == 'gauntlet' presence.details = 'In Gauntlet Queue' else if gameMatchRequestData.gameType == 'rift' presence.details = 'In Rift Queue' else presence.details = 'In Queue' Discord.updatePresence(presence) # set the chat presence status to in-queue so your buddies see that you're unreachable ChatManager.getInstance().setStatus(ChatManager.STATUS_QUEUE) # add route NavigationManager.getInstance().addMajorRoute("finding_game", App._findingGame, App, [gameMatchRequestData]) # initialize finding game view findingGameItemView = new FindingGameItemView({model: new Backbone.Model({gameType: gameMatchRequestData.gameType, factionId: gameMatchRequestData.factionId, generalId: gameMatchRequestData.generalId})}) # initialize found game promise gameListingData = null # load find game assets and show finding game showFindingGamePromise = PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> return Promise.all([ Scene.getInstance().showContentByClass(PlayLayer, true), Scene.getInstance().showFindingGame(gameMatchRequestData.factionId, gameMatchRequestData.generalId), NavigationManager.getInstance().showContentView(findingGameItemView), NavigationManager.getInstance().showUtilityView(new UtilityMatchmakingMenuItemView({model: ProfileManager.getInstance().profile})) ]) ) # load my game assets as soon as possible loadGamePromise = showFindingGamePromise.then () -> Logger.module("APPLICATION").log("App._findingGame -> showFindingGamePromise DONE") return PackageManager.getInstance().loadGamePackageWithoutActivation([gameMatchRequestData.factionId]) # save this promise to app object so it can be cancelled in the event of "cancelMatchmaking" # this is important because this promise is wrapped around the "found_game" event and a chain of stuff is waiting for it to resolve! # if we don't cancel this later, we will have a promise that never resolves and thus leaks memory App._foundGamePromise = new Promise((resolve, reject) -> # listen for next found game onFoundGame = (foundGameListingData) -> Logger.module("APPLICATION").log("App._findingGame -> onFoundGame()", foundGameListingData) # stop listening GamesManager.getInstance().off("found_game", onFoundGame) # store found data gameListingData = foundGameListingData showFindingGamePromise.then () -> # don't allow user triggered navigation now that we've found a game NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) NavigationManager.getInstance().destroyNonContentViews() Logger.module("APPLICATION").log("App._findingGame -> onFoundGame() App._foundGamePromise RESOLVED") resolve(foundGameListingData) GamesManager.getInstance().once("found_game", onFoundGame) ).cancellable() # wait show finding game and found game, then join found game return Promise.all([ showFindingGamePromise, App._foundGamePromise ]).then(() -> Logger.module("APPLICATION").log("App._findingGame -> show found game", gameListingData) # analytics call Analytics.page("Found Game",{ path: "/#found_game" }) # get found game data from game listing data playerDataModel = App._playerDataFromGameListingData(gameListingData) # show found game return Promise.all([ Scene.getInstance().showVsForGame(playerDataModel.get("myPlayerFactionId"), playerDataModel.get("opponentPlayerFactionId"), playerDataModel.get("myPlayerIsPlayer1"), CONFIG.ANIMATE_MEDIUM_DURATION, playerDataModel.get("myPlayerGeneralId"), playerDataModel.get("opponentPlayerGeneralId")), Scene.getInstance().showNewGame(playerDataModel.get("player1GeneralId"), playerDataModel.get("player2GeneralId")), findingGameItemView.showFoundGame(playerDataModel) ]).then(() -> # join found game return App._joinGame(gameListingData, loadGamePromise) ) ).catch Promise.CancellationError, (e)-> Logger.module("APPLICATION").log("App._findingGame -> promise chain cancelled") App._resumeGame = (lastGameModel) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._resumeGame -> cannot start game when already in a game!") return gameListingData = lastGameModel?.attributes Logger.module("APPLICATION").log("App._resumeGame", gameListingData) # analytics call Analytics.page("Resume Game",{ path: "/#resume_game" }) # set status to in game ChatManager.getInstance().setStatus(ChatManager.STATUS_GAME) # get resume game data from game listing data playerDataModel= App._playerDataFromGameListingData(gameListingData) # playerDataModel.set("gameModel", lastGameModel) # initialize resume ui gameResumeItemView = new ResumeGameItemView({model: playerDataModel}) # initialize continue promise continueGamePromise = new Promise((resolve, reject) -> onContinueGame = () -> stopListeningForContinueGame() # don't allow user triggered navigation now that user has decided to continue NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) NavigationManager.getInstance().destroyNonContentViews() resolve() onCancelContinueGame = (errorMessage) -> stopListeningForContinueGame() # don't try to reconnect to this game again lastGameModel.set("cancel_reconnect",true) reject(errorMessage) stopListeningForContinueGame = () -> gameResumeItemView.stopListening(gameResumeItemView, "continue", onContinueGame) gameResumeItemView.stopListening(lastGameModel, "change") gameResumeItemView.stopListening(NavigationManager.getInstance(), "user_triggered_cancel", onContinueGame) # listen for continue gameResumeItemView.listenToOnce(gameResumeItemView, "continue", onContinueGame) # listen for game over gameResumeItemView.listenTo(lastGameModel, "change", () -> if lastGameModel.get("status") == "over" then onCancelContinueGame("Oops... looks like that game is over!") ) # listen for cancel gameResumeItemView.listenTo(NavigationManager.getInstance(), EVENTS.user_triggered_cancel, () -> if !NavigationManager.getInstance().getIsShowingModalView() then onCancelContinueGame() ) ) # load assets loadAndShowResumeGamePromise = PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # show UI return Promise.all([ Scene.getInstance().showContentByClass(PlayLayer, true), Scene.getInstance().showVsForGame(playerDataModel.get("myPlayerFactionId"), playerDataModel.get("opponentPlayerFactionId"), playerDataModel.get("myPlayerIsPlayer1"), CONFIG.ANIMATE_MEDIUM_DURATION, playerDataModel.get("myPlayerGeneralId"), playerDataModel.get("opponentPlayerGeneralId")), NavigationManager.getInstance().showContentView(gameResumeItemView), NavigationManager.getInstance().showUtilityView(new UtilityMatchmakingMenuItemView({model: ProfileManager.getInstance().profile})) ]) ) # wait for load, show resume game, and click continue, then join in progress game Promise.all([ loadAndShowResumeGamePromise, continueGamePromise ]).then(() -> Logger.module("APPLICATION").log("App._resumeGame -> joining game") # join found game return App._joinGame(gameListingData) ).catch((errorMessage) -> return App._error(errorMessage) ) # only return show promise return loadAndShowResumeGamePromise # # --- Single Player ---- # # App._startSinglePlayerGame = (myPlayerDeck, myPlayerFactionId, myPlayerGeneralId, myPlayerCardBackId, myPlayerBattleMapId, aiGeneralId, aiDifficulty, aiNumRandomCards) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._startSinglePlayerGame -> cannot start game when already in a game!") return Logger.module("APPLICATION").log("App._startSinglePlayerGame") # analytics call Analytics.page("Single Player Game",{ path: "/#single_player" }) # set status to in game ChatManager.getInstance().setStatus(ChatManager.STATUS_GAME) aiGeneralName = null aiGeneralCard = SDK.GameSession.getCardCaches().getCardById(aiGeneralId) if (aiGeneralCard?) aiGeneralName = aiGeneralCard.getName() # request single player game App._singlePlayerGamePromise = new Promise((resolve, reject) -> request = $.ajax url: process.env.API_URL + '/api/me/games/single_player', data: JSON.stringify({ deck: myPlayerDeck, cardBackId: myPlayerCardBackId, battleMapId: myPlayerBattleMapId, hasPremiumBattleMaps: InventoryManager.getInstance().hasAnyBattleMapCosmetics(), ai_general_id: aiGeneralId, ai_difficulty: aiDifficulty, ai_num_random_cards: aiNumRandomCards, ai_username: aiGeneralName }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve(res) request.fail (jqXHR)-> reject(jqXHR and jqXHR.responseJSON and (jqXHR.responseJSON.error or jqXHR.responseJSON.message) or "Connection error. Please retry.") ).cancellable() # init finding game view findingGameItemView = new FindingGameItemView({model: new Backbone.Model({gameType: SDK.GameType.SinglePlayer})}) findingGameItemView.listenTo(findingGameItemView, "destroy", App._cancelSinglePlayer) # show ui return Promise.all([ Scene.getInstance().showContentByClass(PlayLayer, true), Scene.getInstance().showFindingGame(myPlayerFactionId, myPlayerGeneralId), NavigationManager.getInstance().showContentView(findingGameItemView), NavigationManager.getInstance().showUtilityView(new UtilityMatchmakingMenuItemView({model: ProfileManager.getInstance().profile})) ]).then(() -> # when we have single player game data return App._singlePlayerGamePromise?.then((gameListingData) -> App._singlePlayerGamePromise = null # don't allow user triggered navigation now that we've found a game NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) # get found game data from game listing data playerDataModel = App._playerDataFromGameListingData(gameListingData) # show found game return Promise.all([ Scene.getInstance().showVsForGame(playerDataModel.get("myPlayerFactionId"), playerDataModel.get("opponentPlayerFactionId"), playerDataModel.get("myPlayerIsPlayer1"), CONFIG.ANIMATE_MEDIUM_DURATION, playerDataModel.get("myPlayerGeneralId"), playerDataModel.get("opponentPlayerGeneralId")), Scene.getInstance().showNewGame(playerDataModel.get("player1GeneralId"), playerDataModel.get("player2GeneralId")), NavigationManager.getInstance().destroyNonContentViews(), findingGameItemView.showFoundGame(playerDataModel) ]).then(() -> # join found game return App._joinGame(gameListingData) ) ) ).catch(Promise.CancellationError, (e)-> Logger.module("APPLICATION").log("App:_startSinglePlayerGame -> promise chain cancelled") ).catch((errorMessage) -> return App._error(if errorMessage? then "Failed to start single player game: " + errorMessage) ) App._cancelSinglePlayer = () -> if App._singlePlayerGamePromise? App._singlePlayerGamePromise.cancel() App._singlePlayerGamePromise = null App._startBossBattleGame = (myPlayerDeck, myPlayerFactionId, myPlayerGeneralId, myPlayerCardBackId, myPlayerBattleMapId, aiGeneralId) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._startBossBattleGame -> cannot start game when already in a game!") return Logger.module("APPLICATION").log("App._startBossBattleGame") # analytics call Analytics.page("Boss Battle Game",{ path: "/#boss_battle" }) # don't allow user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) # set user as in game ChatManager.getInstance().setStatus(ChatManager.STATUS_GAME) aiGeneralName = null aiGeneralCard = SDK.GameSession.getCardCaches().getCardById(aiGeneralId) if (aiGeneralCard?) aiGeneralName = aiGeneralCard.getName() # request boss battle game bossBattleGamePromise = new Promise((resolve, reject) -> request = $.ajax url: process.env.API_URL + '/api/me/games/boss_battle', data: JSON.stringify({ deck: myPlayerDeck, cardBackId: myPlayerCardBackId, battleMapId: myPlayerBattleMapId, ai_general_id: aiGeneralId, ai_username: aiGeneralName }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve(res) request.fail (jqXHR)-> reject(jqXHR and jqXHR.responseJSON and (jqXHR.responseJSON.error or jqXHR.responseJSON.message) or "Connection error. Please retry.") ) # get ui promise if CONFIG.LOAD_ALL_AT_START ui_promise = Promise.resolve() else ui_promise = NavigationManager.getInstance().showDialogForLoad() return Promise.all([ bossBattleGamePromise, ui_promise ]).spread (gameListingData) -> return App._joinGame(gameListingData) .catch (errorMessage) -> return App._error(if errorMessage? then "Failed to start boss battle: " + errorMessage) # # --- Replays ---- # # App._startGameForReplay = (replayData) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._startGameForReplay -> cannot start game when already in a game!") return userId = replayData.userId gameId = replayData.gameId replayId = replayData.replayId promotedDivisionName = replayData.promotedDivisionName # check for invalid replay data if !replayId? if !gameId? throw new Error("Cannot replay game without game id!") if !userId? and !promotedDivisionName? throw new Error("Cannot replay game without user id or division name!") # don't allow user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) # show loading return NavigationManager.getInstance().showDialogForLoad() .bind {} .then () -> # load replay data if replayId? url = "#{process.env.API_URL}/replays/#{replayId}" else if promotedDivisionName? url = "#{process.env.API_URL}/api/me/games/watchable/#{promotedDivisionName}/#{gameId}/replay_data?playerId=#{userId}" else url = "#{process.env.API_URL}/api/users/#{userId}/games/#{gameId}/replay_data" return new Promise (resolve, reject) -> request = $.ajax({ url: url , type: 'GET', contentType: 'application/json', dataType: 'json' }) request.done (response)-> resolve(response) .fail (response)-> reject(new Error("Error downloading replay data: #{response?.responseJSON?.message}")) .then (replayResponseData) -> @.replayResponseData = replayResponseData gameSessionData = replayResponseData.gameSessionData gameUIData = replayResponseData.mouseUIData replayData = replayResponseData.replayData # validate data gameSetupData = gameSessionData?.gameSetupData if !gameSetupData? throw new Error("ReplayEngine -> loaded game does not have valid replay data!") # store data @_loadedGameSessionData = gameSessionData @_loadedGameUIEventData = gameUIData # load resources for game return PackageManager.getInstance().loadGamePackageWithoutActivation([ gameSetupData.players[0].factionId gameSetupData.players[1].factionId ]) .then () -> # create new game instance but don't deserialize from existing data SDK.GameSession.reset() if userId? # if we explicity requested to spectate a user perspective SDK.GameSession.getInstance().setUserId(userId) else if @.replayResponseData?.replayData # check if the server response includes a shared replay record so we can use that to determine who to spectate SDK.GameSession.getInstance().setUserId(@.replayResponseData?.replayData.user_id) else # ultimately spectate player 1 if nothing provided SDK.GameSession.getInstance().setUserId(@_loadedGameSessionData.players[0].playerId) SDK.GameSession.getInstance().setGameType(@_loadedGameSessionData.gameType) SDK.GameSession.getInstance().setIsRunningAsAuthoritative(false) SDK.GameSession.getInstance().setIsSpectateMode(true) SDK.GameSession.getInstance().setIsReplay(true) # setup GameSession from replay data SDK.GameSetup.setupNewSessionFromExistingSessionData(SDK.GameSession.getInstance(), @_loadedGameSessionData) return App._startGame() .then () -> # start watching replay ReplayEngine.getInstance().watchReplay(@_loadedGameSessionData, @_loadedGameUIEventData) .catch (errorMessage) -> ReplayEngine.getInstance().stopCurrentReplay() return App._error(errorMessage) # # --- Game Connecting ---- # # App._unsubscribeFromJoinGameEvents = () -> SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.join_game) SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.reconnect_failed) App._subscribeToJoinGameEventsPromise = () -> App._unsubscribeFromJoinGameEvents() return new Promise((resolve, reject) -> # wait for join_game event SDK.NetworkManager.getInstance().getEventBus().once(EVENTS.join_game, (response) -> # handle response if response.error reject(response.error) else resolve(response.gameSessionData) ) SDK.NetworkManager.getInstance().getEventBus().once(EVENTS.spectate_game, (response) -> # handle response if response.error reject(response.error) else resolve(response.gameSessionData) ) # wait for reconnect_failed event SDK.NetworkManager.getInstance().getEventBus().once(EVENTS.reconnect_failed, () -> # reject and cancel reconnect reject("Reconnect failed!") ) ).finally(() -> # reset join game listeners App._unsubscribeFromJoinGameEvents() ) App._joinGame = (gameListingData, loadMyGameResourcesPromise, loadOpponentGameResourcesPromise) -> Logger.module("APPLICATION").log("App._joinGame", gameListingData) # load my resources for game loadMyGameResourcesPromise ?= PackageManager.getInstance().loadGamePackageWithoutActivation([gameListingData["faction_id"]]) # load opponent resources for game loadOpponentGameResourcesPromise ?= PackageManager.getInstance().loadMinorPackage(PKGS.getFactionGamePkgIdentifier(gameListingData["opponent_faction_id"]), null, "game") return Promise.all([ loadMyGameResourcesPromise, loadOpponentGameResourcesPromise ]).then(() -> # listen to join game events joinGamePromise = App._subscribeToJoinGameEventsPromise() # join game and if a game server is assigned to this listing, connect there SDK.NetworkManager.getInstance().connect(gameListingData["game_id"], ProfileManager.getInstance().get('id'), gameListingData["game_server"]) return joinGamePromise.then((gameSessionData) -> return App._startGameWithData(gameSessionData) ).catch((errorMessage) -> return App._error(errorMessage) ) ) App._onReconnectToGame = (gameId) -> Logger.module("APPLICATION").log("App._onReconnectToGame", gameId) # destroy the current game App.cleanupGame() # start listening to join game events joinGamePromise = App._subscribeToJoinGameEventsPromise() # blur the view in engine Scene.getInstance().getFX().requestBlurScreen(App._screenBlurId) return Promise.all([ # show user we're reconnecting NavigationManager.getInstance().showContentView(new ReconnectToGameItemView()), NavigationManager.getInstance().showUtilityView(new UtilityMatchmakingMenuItemView({model: ProfileManager.getInstance().profile})) ]).then(() -> return joinGamePromise.then((gameSessionData) -> # start game return App._startGameWithData(gameSessionData) ).catch((errorMessage) -> return App._error(errorMessage) ).finally(() -> App.cleanupReconnectToGame() ) ) App.cleanupReconnectToGame = () -> # unsubscribe from events App._unsubscribeFromJoinGameEvents() # unblur screen Scene.getInstance().getFX().requestUnblurScreen(App._screenBlurId) # # --- Game Events ---- # # App._onNetworkGameEvent = (eventData) -> if (eventData.type == EVENTS.step) Logger.module("APPLICATION").log("App._onNetworkGameEvent -> step", eventData) # step event if eventData.step? # deserialize step sdkStep = SDK.GameSession.getInstance().deserializeStepFromFirebase(eventData.step) # if we are spectating, and connected in the middle of a followup (so we don't have a snapshot), error out to main menu in the event of a rollback since we have nothing to roll back to if (SDK.GameSession.getInstance().getIsSpectateMode() and sdkStep.getAction() instanceof SDK.RollbackToSnapshotAction and !SDK.GameSession.getInstance().getRollbackSnapshotData()) return App._error("You fell out of sync. Please try to spectate again to sync up.") # mark step as transmitted sdkStep.setTransmitted(true) # execute step SDK.GameSession.getInstance().executeAuthoritativeStep(sdkStep) if sdkStep.getAction() AnalyticsTracker.sendAnalyticsForExplicitAction(sdkStep.getAction()) else if (eventData.type == EVENTS.invalid_action) if eventData.playerId == SDK.GameSession.getInstance().getMyPlayerId() if eventData.desync # player is out of sync with server # force them to reconnect to game Analytics.track("player desync", {category:Analytics.EventCategory.Debug}, {nonInteraction:1}) App._error("Your current match appears to be out of sync. To avoid any issues, please select CONTINUE and reconnect to your match.") else # player isn't out of sync but may need to know their action was invalid # this may happen if a player attempts to submit actions after their turn is over SDK.GameSession.getInstance().onAuthoritativeInvalidAction(eventData) else if (eventData.type == EVENTS.network_game_hover) Scene.getInstance().getGameLayer()?.onNetworkHover(eventData) else if (eventData.type == EVENTS.network_game_select) Scene.getInstance().getGameLayer()?.onNetworkSelect(eventData) else if (eventData.type == EVENTS.network_game_mouse_clear) Scene.getInstance().getGameLayer()?.onNetworkMouseClear(eventData) else if (eventData.type == EVENTS.turn_time) # if we are behind in step count for some reason from the server step counter if (!SDK.GameSession.getInstance().getIsSpectateMode() and eventData.stepCount > SDK.GameSession.getInstance().getStepCount()) # we're going to start a pseudo-timeout to reload the game Logger.module("APPLICATION").warn("App._onNetworkGameEvent -> seems like game session is behind server step count") # if we haven't already detected a potential desync state and recorded the moment it started if not App._gameDesyncStartedAt # record the moment the suspected desync started App._gameDesyncStartedAt = moment.utc() # otherwise if we suspect a desync state is already in progress and we have the time it started, see if it's been more than 10s else if moment.duration(moment.utc() - App._gameDesyncStartedAt).asSeconds() > 10.0 # if it's been more than 10s in a desync state, fire off the error state App._error("Your current match appears to be out of sync. To avoid any issues, please select CONTINUE and reconnect to your match.") App._gameDesyncStartedAt = null return else # if we're up to date with our step count, just clear out any suspected desync starting point App._gameDesyncStartedAt = null # the game session emits events from here that inform UI etc. SDK.GameSession.getInstance().setTurnTimeRemaining(eventData.time) else if (eventData.type == EVENTS.show_emote) EventBus.getInstance().trigger(EVENTS.show_emote, eventData) App._onOpponentConnectionStatusChanged = (eventData) -> # when opponent disconnects, force mouse clear if !SDK.NetworkManager.getInstance().isOpponentConnected Scene.getInstance().getGameLayer()?.onNetworkMouseClear({type:EVENTS.network_game_mouse_clear, timestamp: Date.now()}) App._onNetworkGameError = (errorData) -> return App._error(JSON.stringify(errorData)) App._onGameServerShutdown = (errorData) -> if errorData.ip ip = errorData.ip lastGameModel = GamesManager.getInstance().playerGames.first() lastGameModel.set('gameServer',ip) # reconnect SDK.NetworkManager.getInstance().reconnect(ip) # show reconnecting return App._onReconnectToGame() else return App._error("Game server error, no ip!") # # --- Game Setup ---- # # App._startGameWithChallenge = (challenge) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._startGameWithChallenge -> cannot start game when already in a game!") return Logger.module("APPLICATION").log("App:_startGameWithChallenge") # don't allow user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) # set user as in game ChatManager.getInstance().setStatus(ChatManager.STATUS_CHALLENGE) if not challenge instanceof SDK.ChallengeRemote # mark challenge as attempted ProgressionManager.getInstance().markChallengeAsAttemptedWithType(challenge.type); # challenge handles setting up game session SDK.GameSession.reset() SDK.GameSession.getInstance().setUserId(ProfileManager.getInstance().get('id')) challenge.setupSession(SDK.GameSession.getInstance()) # get ui promise if CONFIG.LOAD_ALL_AT_START ui_promise = Promise.resolve() else ui_promise = NavigationManager.getInstance().showDialogForLoad() return ui_promise.then () -> return PackageManager.getInstance().loadGamePackageWithoutActivation([ SDK.GameSession.getInstance().getGeneralForPlayer1().getFactionId(), SDK.GameSession.getInstance().getGeneralForPlayer2().getFactionId() ], [ "tutorial", PKGS.getChallengePkgIdentifier(SDK.GameSession.getInstance().getChallenge().getType()) ]) .then () -> return App._startGame() .catch (errorMessage) -> return App._error(errorMessage) App._startGameWithData = (sessionData) -> Logger.module("APPLICATION").log("App._startGameWithData", sessionData) # reset and deserialize SDK.GameSession.reset() SDK.GameSession.getInstance().deserializeSessionFromFirebase(sessionData) SDK.GameSession.getInstance().setUserId(ProfileManager.getInstance().get('id')) # do not start games that are already over if !SDK.GameSession.getInstance().isOver() return App._startGame() else return Promise.reject() App._startGame = () -> gameSession = SDK.GameSession.getInstance() Logger.module("APPLICATION").log("App:_startGame", gameSession.getStatus()) if gameSession.getIsSpectateMode() ChatManager.getInstance().setStatus(ChatManager.STATUS_WATCHING) else if gameSession.isChallenge() ChatManager.getInstance().setStatus(ChatManager.STATUS_CHALLENGE) else ChatManager.getInstance().setStatus(ChatManager.STATUS_GAME) NotificationsManager.getInstance().dismissNotificationsThatCantBeShown() if Discord getFactionImage = (factionId, opponent = false) -> s = {key: '', text: ''} switch factionId when 1 then s = {key: 'f1', text: 'Lyonar'} when 2 then s = {key: 'f2', text: 'Songhai'} when 3 then s = {key: 'f3', text: 'Vetruvian'} when 4 then s = {key: 'f4', text: 'Abyssian'} when 5 then s = {key: 'f5', text: 'Magmar'} when 6 then s = {key: 'f6', text: 'Vanar'} else s = {key: 'neutral', text: 'Neutral'} if opponent s.key += '_small' return s opponentName = SDK.GameSession.getInstance().getOpponentPlayer().getUsername() opponentFaction = SDK.GameSession.getInstance().getGeneralForPlayer(SDK.GameSession.getInstance().getOpponentPlayer()).factionId opponentFactionImage = getFactionImage(opponentFaction, true) playerName = SDK.GameSession.getInstance().getMyPlayer().getUsername() playerId = SDK.GameSession.getInstance().getMyPlayerId() playerRank = GamesManager.getInstance().getCurrentRank() playerFaction = SDK.GameSession.getInstance().getGeneralForPlayer(SDK.GameSession.getInstance().getMyPlayer()).factionId playerFactionImage = getFactionImage(playerFaction, false) presence = { startTimestamp: Math.floor((new Date).getTime()/1000), instance: 1 largeImageKey: playerFactionImage.key largeImageText: playerFactionImage.text smallImageKey: opponentFactionImage.key smallImageText: opponentFactionImage.text } if gameSession.getIsSpectateMode() if gameSession.getIsReplay() presence.details = "Watching: #{playerName} vs. #{opponentName} replay" presence.state = "Spectating" else presence.details = "Watching: #{playerName} vs. #{opponentName} live" presence.state = "Spectating" else if gameSession.isRanked() presence.details = "Ranked: vs. #{opponentName}" presence.state = "In Match" # check if block is enabled before allowing spectate if !ProfileManager.getInstance().profile.get("blockSpectators") presence.spectateSecret = playerId else if gameSession.isGauntlet() presence.details = "Gauntlet: vs. #{opponentName}" presence.state = "In Match" # check if block is enabled before allowing spectate if !ProfileManager.getInstance().profile.get("blockSpectators") presence.spectateSecret = playerId else if gameSession.isRift() presence.details = "Rift: vs. #{opponentName}" presence.state = "In Match" # check if block is enabled before allowing spectate if !ProfileManager.getInstance().profile.get("blockSpectators") presence.spectateSecret = playerId else if gameSession.isFriendly() presence.details = "Friendly: vs. #{opponentName}" presence.state = "In Game" # check if block is enabled before allowing spectate if !ProfileManager.getInstance().profile.get("blockSpectators") presence.spectateSecret = playerId else if gameSession.isBossBattle() presence.details = "Boss Battle: vs. #{opponentName}" presence.state = "Playing Solo" else if gameSession.isSinglePlayer() || gameSession.isSandbox() || gameSession.isChallenge() presence.state = "Playing Solo" Discord.updatePresence(presence) # analytics call Analytics.page("Game",{ path: "/#game" }) # reset routes as soon as we lock into a game NavigationManager.getInstance().resetRoutes() # record last game data CONFIG.resetLastGameData() CONFIG.lastGameType = gameSession.getGameType() CONFIG.lastGameWasSpectate = gameSession.getIsSpectateMode() CONFIG.lastGameWasTutorial = gameSession.isTutorial() CONFIG.lastGameWasDeveloper = UtilsEnv.getIsInDevelopment() && gameSession.getIsDeveloperMode() CONFIG.lastGameWasDailyChallenge = gameSession.isDailyChallenge() # listen to game network events App._subscribeToGameNetworkEvents() # get game UI view class challenge = gameSession.getChallenge() if challenge? and !(challenge instanceof SDK.Sandbox) gameUIViewClass = TutorialLayout else gameUIViewClass = GameLayout # load resources for game session load_promises = [ # load battlemap assets required for game PackageManager.getInstance().loadMinorPackage(PKGS.getBattleMapPkgIdentifier(gameSession.getBattleMapTemplate().getMap()), null, "game") ] # load all cards in my player's hand preloaded_package_ids = [] for cardIndex in gameSession.getMyPlayer().getDeck().getHand() card = gameSession.getCardByIndex(cardIndex) if card? # get unique id for card preload card_id = card.id card_pkg_id = PKGS.getCardGamePkgIdentifier(card_id) card_preload_pkg_id = card_pkg_id + "_preload_" + UtilsJavascript.generateIncrementalId() preloaded_package_ids.push(card_preload_pkg_id) load_promises.push(PackageManager.getInstance().loadMinorPackage(card_preload_pkg_id, PKGS.getPkgForIdentifier(card_pkg_id), "game")) # load all cards and modifiers on board for card in gameSession.getBoard().getCards(null, allowUntargetable=true) # get unique id for card preload card_id = card.getId() card_pkg_id = PKGS.getCardGamePkgIdentifier(card_id) card_resources_pkg = PKGS.getPkgForIdentifier(card_pkg_id) card_preload_pkg_id = card_pkg_id + "_preload_" + UtilsJavascript.generateIncrementalId() preloaded_package_ids.push(card_preload_pkg_id) # include signature card resources if card instanceof SDK.Entity and card.getWasGeneral() referenceSignatureCard = card.getReferenceSignatureCard() if referenceSignatureCard? signature_card_id = referenceSignatureCard.getId() signature_card_pkg_id = PKGS.getCardGamePkgIdentifier(signature_card_id) signature_card_resources_pkg = PKGS.getPkgForIdentifier(signature_card_pkg_id) card_resources_pkg = [].concat(card_resources_pkg, signature_card_resources_pkg) # load card resources load_promises.push(PackageManager.getInstance().loadMinorPackage(card_preload_pkg_id, card_resources_pkg, "game")) # modifiers for modifier in card.getModifiers() if modifier? # get unique id for modifier preload modifier_type = modifier.getType() modifier_preload_package_id = modifier_type + "_preload_" + UtilsJavascript.generateIncrementalId() preloaded_package_ids.push(modifier_preload_package_id) load_promises.push(PackageManager.getInstance().loadMinorPackage(modifier_preload_package_id, PKGS.getPkgForIdentifier(modifier_type), "game")) # load artifact card if modifier is applied by an artifact if modifier.getIsFromArtifact() artifact_card = modifier.getSourceCard() if artifact_card? # get unique id for artifact card preload artifact_card_id = artifact_card.getId() artifact_card_pkg_id = PKGS.getCardInspectPkgIdentifier(artifact_card_id) artifact_card_preload_pkg_id = artifact_card_pkg_id + "_preload_" + UtilsJavascript.generateIncrementalId() preloaded_package_ids.push(artifact_card_preload_pkg_id) load_promises.push(PackageManager.getInstance().loadMinorPackage(artifact_card_preload_pkg_id, PKGS.getPkgForIdentifier(artifact_card_pkg_id), "game")) return Promise.all(load_promises).then(() -> # destroy all views/layers return NavigationManager.getInstance().destroyAllViewsAndLayers() ).then(() -> return PackageManager.getInstance().activateGamePackage() ).then(() -> # show game and ui overlay_promise = Scene.getInstance().destroyOverlay() game_promise = Scene.getInstance().showGame() content_promise = NavigationManager.getInstance().showContentView(new gameUIViewClass({challenge: challenge})) utility_promise = NavigationManager.getInstance().showUtilityView(new UtilityGameMenuItemView({model: ProfileManager.getInstance().profile})) # listen to game local events App._subscribeToGameLocalEvents() # wait for game to show as active (not status active) then unload all preloaded packages scene = Scene.getInstance() gameLayer = scene? && scene.getGameLayer() if !gameLayer? or gameLayer.getStatus() == GameLayer.STATUS.ACTIVE PackageManager.getInstance().unloadMajorMinorPackages(preloaded_package_ids) else onActiveGame = () -> gameLayer.getEventBus().off(EVENTS.show_active_game, onActiveGame) gameLayer.getEventBus().off(EVENTS.terminate, onTerminate) PackageManager.getInstance().unloadMajorMinorPackages(preloaded_package_ids) onTerminate = () -> gameLayer.getEventBus().off(EVENTS.show_active_game, onActiveGame) gameLayer.getEventBus().off(EVENTS.terminate, onTerminate) gameLayer.getEventBus().on(EVENTS.show_active_game, onActiveGame) gameLayer.getEventBus().on(EVENTS.terminate, onTerminate) return Promise.all([ overlay_promise, game_promise, content_promise, utility_promise ]) ).then(() -> # enable user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationUnlocked(App._userNavLockId) ) ######## App.onAfterShowEndTurn = () -> Logger.module("APPLICATION").log "App:onAfterShowEndTurn" # if we're playing in sandbox mode, we need to let the player play both sides so we swap players here if SDK.GameSession.getInstance().isSandbox() # swap test user id player1 = SDK.GameSession.getInstance().getPlayer1() player2 = SDK.GameSession.getInstance().getPlayer2() if player1.getIsCurrentPlayer() then SDK.GameSession.getInstance().setUserId(player1.getPlayerId()) else SDK.GameSession.getInstance().setUserId(player2.getPlayerId()) # # --- Game Cleanup ---- # # App.cleanupGame = () -> Logger.module("APPLICATION").log "App.cleanupGame" # cleanup reconnect App.cleanupReconnectToGame() # cleanup events App.cleanupGameEvents() # terminate the game layer Scene.getInstance().getGameLayer()?.terminate() # reset the current instance of the game session SDK.GameSession.reset() App.cleanupGameEvents = () -> Logger.module("APPLICATION").log "App.cleanupGameEvents" # cleanup events App._unsubscribeFromGameLocalEvents() App._unsubscribeFromGameNetworkEvents() # # --- Game Over Views ---- # # App._onGameOver = () -> Logger.module("APPLICATION").log "App:_onGameOver" # start loading data as soon as game is over, don't wait for animations App._startLoadingGameOverData() # disconnect from game room on network side # defer it until the call stack clears so any actions that caused the game to be over get broadcast during the current JS tick _.defer () -> SDK.NetworkManager.getInstance().disconnect() # # --- Game Turn Over---- # # App._onEndTurn = (e) -> AnalyticsTracker.sendAnalyticsForCompletedTurn(e.turn) ###* # This method de-registers all game listeners and initiates the game over screen flow. For visual sequencing purposes, it fires when it recieves an event that all game actions are done showing in the game layer. # @public ### App.onShowGameOver = () -> Logger.module("APPLICATION").log "App:onShowGameOver" # analytics call Analytics.page("Game Over",{ path: "/#game_over" }) App.cleanupGameEvents() App.showVictoryWhenGameDataReady() ###* # Load progression, rank, etc... data after a game is over. # @private ### App._startLoadingGameOverData = ()-> # for specated games, don't load any data if SDK.GameSession.current().getIsSpectateMode() App._gameOverDataThenable = Promise.resolve([null,[]]) return # resolve when the last game is confirmed as "over" whenGameJobsProcessedAsync = new Promise (resolve,reject)-> isGameReady = (gameAttrs,jobAttrs)-> # if game is not over yet, the rest of the data is not valid if gameAttrs.status != SDK.GameStatus.over return false switch gameAttrs.game_type when SDK.GameType.Friendly return isFriendlyGameReady(gameAttrs,jobAttrs) when SDK.GameType.Ranked return isRankedGameReady(gameAttrs,jobAttrs) when SDK.GameType.Casual return isCasualGameReady(gameAttrs,jobAttrs) when SDK.GameType.Gauntlet return isGauntletGameReady(gameAttrs,jobAttrs) when SDK.GameType.SinglePlayer return isSinglePlayerGameReady(gameAttrs,jobAttrs) when SDK.GameType.BossBattle return isBossBattleGameReady(gameAttrs,jobAttrs) when SDK.GameType.Rift return isRiftGameReady(gameAttrs,jobAttrs) else return Promise.resolve() isFriendlyGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_scored return jobAttrs.quests and jobAttrs.faction_progression else return true isRankedGameReady = (gameAttrs,jobAttrs)-> doneProcessing = false if gameAttrs.is_scored doneProcessing = (jobAttrs.rank and jobAttrs.quests and jobAttrs.progression and jobAttrs.faction_progression) else doneProcessing = (jobAttrs.rank) # if we're in diamond or above, wait for ladder, othwerwise don't since it's not guaranteed to process if GamesManager.getInstance().getCurrentRank() <= SDK.RankDivisionLookup.Diamond doneProcessing = doneProcessing and jobAttrs.ladder return doneProcessing isCasualGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_scored return (jobAttrs.quests and jobAttrs.progression and jobAttrs.faction_progression) else return true isGauntletGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_scored return (jobAttrs.gauntlet and jobAttrs.quests and jobAttrs.progression and jobAttrs.faction_progression) else return jobAttrs.gauntlet isSinglePlayerGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_scored return jobAttrs.faction_progression else return true isBossBattleGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_winner return (jobAttrs.progression and jobAttrs.cosmetic_chests and jobAttrs.faction_progression) if gameAttrs.is_scored return jobAttrs.faction_progression else return true isRiftGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_scored doneProcessing = (jobAttrs.rift and jobAttrs.quests) else doneProcessing = (jobAttrs.rift) gameSession = SDK.GameSession.getInstance() lastGameModel = GamesManager.getInstance().playerGames.first() if lastGameModel? and SDK.GameType.isNetworkGameType(gameSession.getGameType()) # lastGameModel.onSyncOrReady().then ()-> if isGameReady(lastGameModel.attributes,lastGameModel.attributes.job_status || {}) resolve([lastGameModel,null]) else lastGameModel.on "change", () -> if isGameReady(lastGameModel.attributes,lastGameModel.attributes.job_status || {}) lastGameModel.off "change" resolve([lastGameModel,null]) else if gameSession.isChallenge() challengeId = gameSession.getChallenge().type if gameSession.getChallenge() instanceof SDK.ChallengeRemote and gameSession.getChallenge().isDaily # Don't process daily challenges run by qa tool if gameSession.getChallenge()._generatedForQA resolve([null,null]) else ProgressionManager.getInstance().completeDailyChallenge(challengeId).then (challengeData)-> challengeModel = new Backbone.Model(challengeData) resolve([null,challengeModel]) else ProgressionManager.getInstance().completeChallengeWithType(challengeId).then (challengeData)-> NewPlayerManager.getInstance().setHasSeenBloodbornSpellInfo() challengeModel = new Backbone.Model(challengeData) resolve([null,challengeModel]) else resolve([null, null]) App._gameOverDataThenable = whenGameJobsProcessedAsync .bind {} .spread (userGameModel,challengeModel)-> @.userGameModel = userGameModel @.challengeModel = challengeModel rewardIds = [] gameSession = SDK.GameSession.getInstance() # Send game based analytics AnalyticsTracker.submitGameOverAnalytics(gameSession,userGameModel) # Mark first game of type completions if gameSession.isRanked() NewPlayerManager.getInstance().setHasPlayedRanked(userGameModel) if gameSession.isSinglePlayer() NewPlayerManager.getInstance().setHasPlayedSinglePlayer(userGameModel) if @.userGameModel?.get('rewards') for rewardId,val of @.userGameModel.get('rewards') rewardIds.push rewardId if @.challengeModel?.get('reward_ids') for rewardId in @.challengeModel.get('reward_ids') rewardIds.push rewardId return rewardIds .then (rewardIds)-> allPromises = [] if rewardIds? for rewardId in rewardIds rewardModel = new DuelystBackbone.Model() rewardModel.url = process.env.API_URL + "/api/me/rewards/#{rewardId}" rewardModel.fetch() allPromises.push rewardModel.onSyncOrReady() return Promise.all(allPromises) .then (allRewardModels)-> @.rewardModels = allRewardModels # if we're not done with core progression if not NewPlayerManager.getInstance().isCoreProgressionDone() return NewPlayerManager.getInstance().updateCoreState() else return Promise.resolve() .then (newPlayerProgressionData)-> if newPlayerProgressionData?.quests @.newBeginnerQuestsCollection = new Backbone.Collection(newPlayerProgressionData?.quests) else @.newBeginnerQuestsCollection = new Backbone.Collection() .then ()-> # if we're at a stage where we should start generating daily quests, request them in case any of the quest slots opened up if NewPlayerManager.getInstance().shouldStartGeneratingDailyQuests() return QuestsManager.getInstance().requestNewDailyQuests() else return Promise.resolve() .then ()-> return Promise.all([@.userGameModel,@.rewardModels,@.newBeginnerQuestsCollection]) # don't wait more than ~10 seconds .timeout(10000) ###* # Shows the victory screen after a game is over, all data is loaded, and assets for victory screen are allocated. # @public ### App.showVictoryWhenGameDataReady = () -> # show activity dialog NavigationManager.getInstance().showDialogView(new ActivityDialogItemView()); # resolve when post game assets are done loading return PackageManager.getInstance().loadMinorPackage("postgame") .then ()-> return App._gameOverDataThenable .spread (userGameModel,rewardModels,newBeginnerQuestsCollection)-> if not rewardModels throw new Error() # destroy dialog NavigationManager.getInstance().destroyDialogView() # terminate game layer as we no longer need it to be active Scene.getInstance().getGameLayer()?.terminate() # show victory App.showVictory(userGameModel,rewardModels,newBeginnerQuestsCollection) .catch Promise.TimeoutError, (e) -> # hide dialog NavigationManager.getInstance().destroyDialogView() App._error("We're experiencing some delays in processing your game. Don't worry, you can keep playing and you'll receive credit shortly.") .catch (e)-> # hide dialog NavigationManager.getInstance().destroyDialogView() App._error(e.message) ###* # Shows the victory screen after a game is over. # @public # @param {Backbone.Model} userGameModel Game model that is finished loading / processing all jobs. # @param {Array} rewardModels Rewards that this game needs to show. # @param {Backbone.Collection} newBeginnerQuestsCollection Collection of new beginner quests as of game completion ### App.showVictory = (userGameModel,rewardModels,newBeginnerQuestsCollection) -> Logger.module("APPLICATION").log "App:showVictory" if not SDK.GameSession.getInstance().getIsSpectateMode() and SDK.GameType.isNetworkGameType(SDK.GameSession.getInstance().getGameType()) faction_id = userGameModel.get('faction_id') faction_xp = userGameModel.get('faction_xp') faction_xp_earned = userGameModel.get('faction_xp_earned') faction_level = SDK.FactionProgression.levelForXP(faction_xp + faction_xp_earned) faction_prog_reward = SDK.FactionProgression.rewardDataForLevel(faction_id,faction_level) if SDK.FactionProgression.hasLeveledUp(faction_xp + faction_xp_earned, faction_xp_earned) and faction_prog_reward App.setCallbackWhenCancel(App.showFactionXpReward.bind(App,userGameModel,rewardModels)) else if SDK.GameSession.getInstance().isRanked() App.setCallbackWhenCancel(App.showLadderProgress.bind(App,userGameModel,rewardModels)) else if SDK.GameSession.getInstance().isRift() App.setCallbackWhenCancel(App.showRiftProgress.bind(App,userGameModel,rewardModels)) else App.addNextScreenCallbackToVictoryFlow(rewardModels) else # local games if SDK.GameSession.getInstance().isChallenge() # for challenges App.addNextScreenCallbackToVictoryFlow(rewardModels); userGameModel ?= new Backbone.Model({}) return Promise.all([ Scene.getInstance().showOverlay(new VictoryLayer()) NavigationManager.getInstance().showContentView(new VictoryItemView({model:userGameModel || new Backbone.Model({})})) ]) ###* # Shows the next screen in the victory order: rank, quests, rewards etc. # @public # @param {Backbone.Model} userGameModel Game model that is finished loading / processing all jobs. # @param {Array} rewardModels Rewards that this game needs to show. ### App.addNextScreenCallbackToVictoryFlow = (rewardModels) -> Logger.module("APPLICATION").log "App:addNextScreenCallbackToVictoryFlow" # # if we have any faction progression rewards, show those first # if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "faction xp" and rewardModel.get('is_unread')) # return App.setCallbackWhenCancel(App.showFactionXpReward.bind(App,rewardModels)) # if we have any quest rewards, show those next if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "quest" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showQuestsCompleted.bind(App,rewardModels)) # if we have any progression rewards, show those next if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "progression" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showWinCounterReward.bind(App,rewardModels)) # ... if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "challenge" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showTutorialRewards.bind(App,rewardModels)) # ... if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "daily challenge" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showTutorialRewards.bind(App,rewardModels)) # if we have any ribbon rewards, show those next if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "ribbon" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showNextRibbonReward.bind(App,rewardModels)) # # if we have any gift crate rewards, show those next # if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_type') == "gift crate" and rewardModel.get('is_unread')) # return App.setCallbackWhenCancel(App.showGiftCrateReward.bind(App,rewardModels)) # if we have any cosmetic loot crate rewards, show those next if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "loot crate" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showLootCrateReward.bind(App,rewardModels)) # if we have any faction unlocks, show those next factionUnlockedReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "faction unlock" and rewardModel.get('is_unread')) if factionUnlockedReward return App.setCallbackWhenCancel(App.showUnlockedFaction.bind(App,factionUnlockedReward.get('unlocked_faction_id'))) # if we are doing a tutorial, kick us back to the tutorial screen, unless it's the last lesson: LessonFour, in which case, move along with normal flow (kicks to main menu) if SDK.GameSession.getInstance().getChallenge()?.categoryType == SDK.ChallengeCategory.tutorial.type # for tutorial go show tutorial layout if SDK.GameSession.getInstance().getChallenge().type != "LessonFour" return App.setCallbackWhenCancel(App._showTutorialLessons.bind(App,SDK.GameSession.getInstance().getChallenge())) ###* # Show unlocked faction screen. # @public # @param {String|Number} factionId # @returns {Promise} ### App.showUnlockedFaction = (factionId) -> Logger.module("APPLICATION").log("App:showUnlockedFaction", factionId) unlockFactionLayer = new UnlockFactionLayer(factionId) return Promise.all([ NavigationManager.getInstance().destroyContentView(), NavigationManager.getInstance().destroyDialogView(), Scene.getInstance().showOverlay(unlockFactionLayer) ]) .then () -> if Scene.getInstance().getOverlay() == unlockFactionLayer unlockFactionLayer.animateReward() .catch (error) -> App._error(error) ###* # Show ribbon reward screen if there are any unread ribbon reward models. # @public # @param {Array} rewardModels the reward models array. ### App.showNextRibbonReward = (rewardModels) -> Logger.module("APPLICATION").log "App:showNextRibbonReward" nextReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "ribbon" and rewardModel.get('is_unread')) nextReward.set('is_unread',false) ribbonId = nextReward.get("ribbons")?[0] if ribbonId? ribbonObject = SDK.RibbonFactory.ribbonForIdentifier(ribbonId) # clear ui NavigationManager.getInstance().destroyContentView() NavigationManager.getInstance().destroyDialogView() # show the in-engine card reward animation progressionRewardLayer = new ProgressionRewardLayer() Scene.getInstance().showOverlay(progressionRewardLayer) progressionRewardLayer.showRewardRibbons([ribbonId], "You've earned the #{ribbonObject.title} ribbon.", "Ribbons show on your profile for performing in battle with distinction.") else Logger.module("APPLICATION").log "ERROR: ribbonId is undefined for reward #{nextReward.get("id")}" ###* # Show progression reward screen. # @public # @param {Backbone.Model} rewardModel progression reward model. ### App.showProgressReward = (rewardModel) -> Logger.module("APPLICATION").log "App:showProgressReward" # clear ui NavigationManager.getInstance().destroyContentView() NavigationManager.getInstance().destroyDialogView() # show the in-engine card reward animation if rewardModel.get("cards") # cards cardIds = rewardModel.get("cards") if rewardModel.get("_showStack") cardIds = [cardIds[0]] progressionRewardLayer = new ProgressionRewardLayer() Scene.getInstance().showOverlay(progressionRewardLayer) progressionRewardLayer.showRewardCards(cardIds, rewardModel.get("_showStack"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("cosmetics") # NOTE: only emotes and battle maps will work for this case progressionRewardLayer = new ProgressionRewardLayer() Scene.getInstance().showOverlay(progressionRewardLayer) if SDK.CosmeticsFactory.cosmeticForIdentifier(rewardModel.get("cosmetics")[0]).typeId == SDK.CosmeticsTypeLookup.BattleMap progressionRewardLayer.showRewardBattleMaps(rewardModel.get("cosmetics"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else progressionRewardLayer.showRewardEmotes(rewardModel.get("cosmetics"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("gift_chests") CrateManager.getInstance().refreshGiftCrates() rewardLayer = new LootCrateRewardLayer() Scene.getInstance().showOverlay(rewardLayer) rewardLayer.animateReward(rewardModel.get("gift_chests"),rewardModel.get("_title"),rewardModel.get("_subTitle")) else if rewardModel.get("cosmetic_keys") # cosmetic keys cosmeticKeyRewardLayer = new LootCrateRewardLayer() Scene.getInstance().showOverlay(cosmeticKeyRewardLayer) cosmeticKeyRewardLayer.animateReward(rewardModel.get("cosmetic_keys"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("ribbons") # ribbons progressionRewardLayer = new ProgressionRewardLayer() Scene.getInstance().showOverlay(progressionRewardLayer) progressionRewardLayer.showRewardRibbons(rewardModel.get("ribbons"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("spirit") # spirit currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) currencyRewardLayer.animateReward("spirit", rewardModel.get("spirit"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("gold") # gold currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) currencyRewardLayer.animateReward("gold", rewardModel.get("gold"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("spirit_orbs") # booster boosterRewardLayer = new BoosterRewardLayer() Scene.getInstance().showOverlay(boosterRewardLayer) boosterRewardLayer.animateReward(rewardModel.get("_title"), rewardModel.get("_subTitle"), rewardModel.get("spirit_orbs")) else if rewardModel.get("gauntlet_tickets") # gauntlet ticket gauntletTicketRewardLayer = new GauntletTicketRewardLayer() Scene.getInstance().showOverlay(gauntletTicketRewardLayer) gauntletTicketRewardLayer.animateReward(rewardModel.get("_title"), rewardModel.get("_subTitle")) else Logger.module("APPLICATION").log("Application->showProgressReward: Attempt to show reward model without valid reward") ###* # Show achievement reward screen if there are any unread ones. # @public ### App.showAchievementCompletions = () -> if !AchievementsManager.getInstance().hasUnreadCompletedAchievements() Scene.getInstance().destroyOverlay() return Promise.resolve() else return new Promise( (resolve, reject) -> locResolve = resolve Logger.module("APPLICATION").log "App:showAchievementCompletions" completedAchievementModel = AchievementsManager.getInstance().popNextUnreadAchievementModel() App.setCallbackWhenCancel(locResolve) # show reward App.showProgressReward(completedAchievementModel) ).then () -> return App.showAchievementCompletions() ###* # Show twitch reward screen if there are any unread ones. # @public ### App.showTwitchRewards = () -> if !TwitchManager.getInstance().hasUnclaimedTwitchRewards() Scene.getInstance().destroyOverlay() return Promise.resolve() else return new Promise( (resolve, reject) -> locResolve = resolve Logger.module("APPLICATION").log "App:showTwitchRewards" twitchRewardModel = TwitchManager.getInstance().popNextUnclaimedTwitchRewardModel() App.setCallbackWhenCancel(locResolve) # show reward App.showProgressReward(twitchRewardModel) ).then () -> return App.showTwitchRewards() ###* # Show season rewards screen if the player has an unread season rewards set. # @public ### App.showEndOfSeasonRewards = () -> gamesManager = GamesManager.getInstance() if gamesManager.hasUnreadSeasonReward() return new Promise( (resolve, reject) -> locResolve = resolve # get data seasonModel = gamesManager.getSeasonsWithUnclaimedRewards()[0] bonusChevrons = SDK.RankFactory.chevronsRewardedForReachingRank(seasonModel.get("top_rank")? || 30) seasonRewardIds = seasonModel.get("reward_ids") if bonusChevrons == 0 # If there is no rewards we exit here locResolve() else Logger.module("APPLICATION").log "App:showEndOfSeasonRewards" endOfSeasonLayer = new EndOfSeasonLayer(seasonModel) return Promise.all([ NavigationManager.getInstance().destroyContentView(), NavigationManager.getInstance().destroyDialogView(), Scene.getInstance().showOverlay(endOfSeasonLayer) ]) .then () -> App.setCallbackWhenCancel(() -> Scene.getInstance().destroyOverlay() locResolve() ) if Scene.getInstance().getOverlay() == endOfSeasonLayer return endOfSeasonLayer.animateReward() .catch (error) -> Logger.module("APPLICATION").log("App.showEndOfSeasonRewards error: ", error) locResolve() ) else return Promise.resolve() App.showTutorialRewards = (rewardModels) -> Logger.module("APPLICATION").log "App:showTutorialRewards" nextReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "challenge" and rewardModel.get('is_unread')) nextReward = nextReward || _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "daily challenge" and rewardModel.get('is_unread')) nextReward.set("is_unread",false) App.addNextScreenCallbackToVictoryFlow(rewardModels) # show reward if (nextReward.get("unlocked_faction_id")) App.showUnlockedFaction(nextReward.get("unlocked_faction_id")) else App.showProgressReward(nextReward) App.showLadderProgress = (userGameModel,rewardModels) -> Logger.module("APPLICATION").log "App:showLadderProgress" # set the cancel callback to show the next screen App.addNextScreenCallbackToVictoryFlow(rewardModels) ladderProgressLayer = new LadderProgressLayer() return Promise.all([ NavigationManager.getInstance().destroyContentView(), NavigationManager.getInstance().destroyDialogView(), Scene.getInstance().showOverlay(ladderProgressLayer) ]) .then () -> if Scene.getInstance().getOverlay() == ladderProgressLayer return ladderProgressLayer.showLadderProgress(userGameModel) .catch (error) -> App._error("App.showLadderProgress error: ", error) App.showRiftProgress = (userGameModel,rewardModels) -> Logger.module("APPLICATION").log "App:showRiftProgress" # set the cancel callback to show the next screen App.addNextScreenCallbackToVictoryFlow(rewardModels) riftProgressLayer = new RiftProgressLayer() return Promise.all([ NavigationManager.getInstance().destroyContentView(), NavigationManager.getInstance().destroyDialogView(), Scene.getInstance().showOverlay(riftProgressLayer) ]) .then () -> if Scene.getInstance().getOverlay() == riftProgressLayer return riftProgressLayer.showRiftProgress(userGameModel) .catch (error) -> App._error("App.showRiftProgress error: ", error) App.showQuestsCompleted = (rewardModels) -> Logger.module("APPLICATION").log "App:showQuestsCompleted" nextQuestReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "quest" and rewardModel.get('is_unread')) nextQuestReward.set('is_unread',false) sdkQuest = SDK.QuestFactory.questForIdentifier(nextQuestReward.get('quest_type_id')) questName = sdkQuest.getName() gold = nextQuestReward.get("gold") spiritOrbs = nextQuestReward.get("spirit_orbs") giftChests = null cosmeticKeys = null if sdkQuest.giftChests?.length > 0 giftChests = sdkQuest.giftChests if sdkQuest.cosmeticKeys?.length > 0 cosmeticKeys = sdkQuest.cosmeticKeys # track an event in analytics Analytics.track("quest complete", { category: Analytics.EventCategory.Quest, quest_type_id: nextQuestReward.get('quest_type_id'), gold_amount:nextQuestReward.get("gold") || 0 },{ labelKey:"quest_type_id" valueKey:"gold_amount" nonInteraction:1 }) # set the cancel callback to show the next screen App.addNextScreenCallbackToVictoryFlow(rewardModels) # show quest reward NavigationManager.getInstance().destroyContentView() if gold currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) currencyRewardLayer.animateReward( "gold", gold, i18next.t("rewards.quest_complete_title",{quest_name:questName}) "+#{gold} GOLD for completing #{questName}", "Quest Complete" ) else if spiritOrbs # booster boosterRewardLayer = new BoosterRewardLayer() Scene.getInstance().showOverlay(boosterRewardLayer) boosterRewardLayer.animateReward( i18next.t("rewards.quest_complete_title",{quest_name:questName}) "+#{spiritOrbs} SPIRIT ORBS for completing #{questName}" ) else if giftChests Analytics.track("earned gift crate", { category: Analytics.EventCategory.Crate, product_id: giftChests[0] }, { labelKey: "product_id" }) # show reward setup on the engine side NavigationManager.getInstance().destroyContentView() rewardLayer = new LootCrateRewardLayer() Scene.getInstance().showOverlay(rewardLayer) rewardLayer.animateReward(giftChests, null, i18next.t("rewards.quest_reward_gift_crate_title",{quest_name:questName})) CrateManager.getInstance().refreshGiftCrates() else if cosmeticKeys Analytics.track("earned cosmetic key", { category: Analytics.EventCategory.Crate, product_id: cosmeticKeys[0] }, { labelKey: "<KEY>" }) NavigationManager.getInstance().destroyContentView() rewardLayer = new CosmeticKeyRewardLayer() Scene.getInstance().showOverlay(rewardLayer) rewardLayer.showRewardKeys(cosmeticKeys, null, "FREE Cosmetic Crate Key for completing the #{questName} quest") CrateManager.getInstance().refreshGiftCrates() # Outdated name, really shows all progression rewards App.showWinCounterReward = (rewardModels) -> Logger.module("APPLICATION").log "App:showWinCounterReward" nextReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "progression" and rewardModel.get('is_unread')) nextReward.set("is_unread",false) App.addNextScreenCallbackToVictoryFlow(rewardModels) # show reward setup on the engine side NavigationManager.getInstance().destroyContentView() # Scene.getInstance().showOverlay(currencyRewardLayer) # TODO: merge How does this even work? rewardView = null switch nextReward.get("reward_type") when "win count" currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) goldAmount = nextReward.get("gold") message = i18next.t("rewards.3_win_gold_reward_message",{gold_amount:goldAmount}) currencyRewardLayer.animateReward( "gold", goldAmount, i18next.t("rewards.3_win_gold_reward_title"), message ) when "play count" currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) goldAmount = nextReward.get("gold") currencyRewardLayer.animateReward( "gold", goldAmount, i18next.t("rewards.4_play_gold_reward_title"), i18next.t("rewards.4_play_gold_reward_message",{gold_amount:goldAmount}) ) when "daily win" currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) goldAmount = nextReward.get("gold") currencyRewardLayer.animateReward( "gold", goldAmount, i18next.t("rewards.first_win_of_the_day_reward_title"), i18next.t("rewards.first_win_of_the_day_reward_message",{gold_amount:goldAmount}) ) when "first 3 games" currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) goldAmount = nextReward.get("gold") currencyRewardLayer.animateReward( "gold", goldAmount, i18next.t("rewards.first_3_games_reward_title"), i18next.t("rewards.first_3_games_reward_message",{gold_amount:goldAmount}) ) when "first 10 games" currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) goldAmount = nextReward.get("gold") currencyRewardLayer.animateReward( "gold", goldAmount, i18next.t("rewards.first_10_games_reward_title"), i18next.t("rewards.first_10_games_reward_message",{gold_amount:goldAmount}) ) when "boss battle" boosterRewardLayer = new BoosterRewardLayer() Scene.getInstance().showOverlay(boosterRewardLayer) cardSetId = nextReward.get("spirit_orbs") boosterRewardLayer.animateReward( i18next.t("rewards.boss_defeated_reward_title"), i18next.t("rewards.boss_defeated_reward_message"), SDK.CardSet.Core ) App.showLootCrateReward = (rewardModels)-> Logger.module("APPLICATION").log "App:showLootCrateReward" nextReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "loot crate" and rewardModel.get('is_unread')) nextReward.set("is_unread",false) Analytics.track("earned cosmetic crate", { category: Analytics.EventCategory.Crate, product_id: nextReward.get("cosmetic_chests")?[0] }, { labelKey: "product_id" }) App.addNextScreenCallbackToVictoryFlow(rewardModels) # show reward setup on the engine side NavigationManager.getInstance().destroyContentView() rewardLayer = new LootCrateRewardLayer() Scene.getInstance().showOverlay(rewardLayer) rewardLayer.animateReward(nextReward.get("cosmetic_chests")) # App.showGiftCrateReward = (rewardModels)-> # Logger.module("APPLICATION").log "App:showGiftCrateReward" # # nextReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_type') == "gift crate" and rewardModel.get('is_unread')) # nextReward.set("is_unread",false) # # Analytics.track("earned gift crate", { # category: Analytics.EventCategory.Crate, # product_id: nextReward.get("gift_crates")?[0] # }, { # labelKey: "product_id" # }) # # App.addNextScreenCallbackToVictoryFlow(rewardModels) # # # show reward setup on the engine side # NavigationManager.getInstance().destroyContentView() # rewardLayer = new LootCrateRewardLayer() # Scene.getInstance().showOverlay(rewardLayer) # rewardLayer.animateReward(nextReward.get("gift_crates")) App.showFactionXpReward = (userGameModel,rewardModels) -> Logger.module("APPLICATION").log "App:showFactionXpReward" nextUnreadReward = _.find rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "faction xp" and rewardModel.get('is_unread') nextUnreadReward.set("is_unread",false) factionId = userGameModel.get("faction_id") factionName = SDK.FactionFactory.factionForIdentifier(factionId).name faction_xp = userGameModel.get('faction_xp') faction_xp_earned = userGameModel.get('faction_xp_earned') level = SDK.FactionProgression.levelForXP(faction_xp + faction_xp_earned) + 1 # set title nextUnreadReward.set("_title", i18next.t("rewards.level_up_reward_title",{ level:level })) # set reward model properties by reward if nextUnreadReward.get("cards") # cards factionCards = GameDataManager.getInstance().visibleCardsCollection.filter (c)-> c.get("factionId") == factionId and c.get("rarityId") == SDK.Rarity.Fixed availableFactionCards = _.filter(factionCards, (c)-> return c.get("inventoryCount") > 0 ) subtitle = i18next.t("rewards.card_reward_subtitle",{ card_count: availableFactionCards.length, total: factionCards.length, factionName: factionName }) nextUnreadReward.set("_subTitle", subtitle) nextUnreadReward.set("_showStack",true) else if nextUnreadReward.get("spirit") # sprit nextUnreadReward.set("_subTitle", i18next.t("rewards.spirit_for_faction_lvl_reward_message",{spirit:nextUnreadReward.get("spirit"),faction_name:factionName,level:level})) else if nextUnreadReward.get("gold") # gold nextUnreadReward.set("_subTitle", i18next.t("rewards.gold_for_faction_lvl_reward_message",{gold:nextUnreadReward.get("spirit"),faction_name:factionName,level:level})) else if nextUnreadReward.get("spirit_orbs") # booster nextUnreadReward.set("_subTitle", i18next.t("rewards.orb_for_faction_lvl_reward_message",{faction_name:factionName,level:level})) # setup next screen if SDK.GameSession.current().isRanked() App.setCallbackWhenCancel(App.showLadderProgress.bind(App,userGameModel,rewardModels)) else if SDK.GameSession.current().isRift() App.setCallbackWhenCancel(App.showRiftProgress.bind(App,userGameModel,rewardModels)) else App.addNextScreenCallbackToVictoryFlow(rewardModels) # show reward App.showProgressReward(nextUnreadReward) App.showNewBeginnerQuests = (beginnerQuestsCollection) -> NavigationManager.getInstance().toggleModalViewByClass(QuestLogLayout,{ collection:beginnerQuestsCollection, showConfirm:true }) App.showFreeCardOfTheDayReward = (opts)-> Promise.all([ NavigationManager.getInstance().destroyModalView(), NavigationManager.getInstance().destroyContentView(), NavigationManager.getInstance().destroyUtilityView() ]).then ()=> rewardLayer = new FreeCardOfTheDayLayer() Scene.getInstance().showOverlay(rewardLayer) rewardLayer.showCoreGem(opts.cardId) App.setCallbackWhenCancel ()-> Scene.getInstance().destroyOverlay() App._showMainMenu().then ()-> NavigationManager.getInstance().toggleModalViewByClass(QuestLogLayout,{ collection:QuestsManager.getInstance().getQuestCollection(), model:ProgressionManager.getInstance().gameCounterModel }) return Promise.resolve() # # ---- User Triggered Navigation ---- # # App.onUserTriggeredExit = () -> Logger.module("APPLICATION").log "App:onUserTriggeredExit" return App.main() App.onUserTriggeredSkip = () -> Logger.module("APPLICATION").log "App:onUserTriggeredSkip" gameSession = SDK.GameSession.getInstance() scene = Scene.getInstance() gameLayer = scene and scene.getGameLayer() if gameLayer? and gameLayer.getIsGameActive() # when in an active game if gameSession.getIsMyFollowupActiveAndCancellable() audio_engine.current().play_effect_for_interaction(RSX.sfx_ui_cancel.audio, CONFIG.CANCEL_SFX_PRIORITY) gameSession.submitExplicitAction(gameSession.getMyPlayer().actionEndFollowup()) else if gameLayer.getIsShowingActionCardSequence() audio_engine.current().play_effect_for_interaction(RSX.sfx_ui_cancel.audio, CONFIG.CANCEL_SFX_PRIORITY) # stop showing played card gameLayer.skipShowActionCardSequence() return Promise.resolve() App.onUserTriggeredCancel = () -> Logger.module("APPLICATION").log "App:onUserTriggeredCancel" cancelPromises = [] if NavigationManager.getInstance().getIsShowingModalView() # close modal screens audio_engine.current().play_effect_for_interaction(RSX.sfx_ui_cancel.audio, CONFIG.CANCEL_SFX_PRIORITY) cancelPromises.push(NavigationManager.getInstance().destroyModalView()) else if NavigationManager.getInstance().getHasLastRoute() # go to last route (handles own sfx) NavigationManager.getInstance().showLastRoute() else gameSession = SDK.GameSession.getInstance() scene = Scene.getInstance() gameLayer = scene and scene.getGameLayer() if gameLayer? and !gameLayer.getIsDisabled() and NavigationManager.getInstance().getIsShowingContentViewClass(GameLayout) # when in game that is not over if gameSession.getIsMyFollowupActiveAndCancellable() audio_engine.current().play_effect_for_interaction(RSX.sfx_ui_cancel.audio, CONFIG.CANCEL_SFX_PRIORITY) gameSession.submitExplicitAction(gameSession.actionRollbackSnapshot()) else if !gameLayer.getMyPlayer().getIsTakingSelectionAction() and !gameLayer.getIsShowingActionCardSequence() # show esc game menu if we are not selecting something in game and not showing an action sequence cancelPromises.push(NavigationManager.getInstance().showModalView(new EscGameMenuItemView())) # always reset game active state gameLayer.resetActiveState() else callback = App.getCallbackWhenCancel() if callback? App.setCallbackWhenCancel(null) callbackResult = callback() if callbackResult instanceof Promise cancelPromises.push(callbackResult) else if (App.getIsLoggedIn() or window.isDesktop) and (NavigationManager.getInstance().getIsShowingContentViewClass(LoaderItemView) or NavigationManager.getInstance().getIsShowingContentViewClass(LoginMenuItemView) or NavigationManager.getInstance().getIsShowingContentViewClass(MainMenuItemView) or NavigationManager.getInstance().getIsShowingContentViewClass(TutorialLessonsLayout)) # show esc main menu when on loading or login or main cancelPromises.push(NavigationManager.getInstance().showModalView(new EscMainMenuItemView())) else if (!gameLayer? or gameLayer.getIsDisabled()) and !App.getIsShowingMain() audio_engine.current().play_effect_for_interaction(RSX.sfx_ui_cancel.audio, CONFIG.CANCEL_SFX_PRIORITY) # for now just go back to main until we implement routing cancelPromises.push(App.main()) return Promise.all(cancelPromises) App.setCallbackWhenCancel = (callback) -> # this is a less than ideal method of setting the next step in cancel sequence App._callbackWhenCancel = callback App.getCallbackWhenCancel = () -> return App._callbackWhenCancel App.onUserTriggeredConfirm = () -> Logger.module("APPLICATION").log "App:onUserTriggeredConfirm" # # ---- Events: Client ---- # # App.beforeunload = (e) -> # return an empty string to trigger alert if App._reloadRequestIds.length == 0 and !window.isDesktop and !UtilsEnv.getIsInLocal() confirmMessage = "" (e || window.event).returnValue = confirmMessage return confirmMessage App.unload = () -> # reset the global event bus so no more events will be handled EventBus.reset() # cancel any ongoing matchmaking GamesManager.getInstance().cancelMatchmaking() App.bindEvents = () -> # attach event listeners to document/window $(window).on('unload', App.unload.bind(App)) $(window).on('mousemove',App.onPointerMove.bind(App)) $(window).on('mousedown',App.onPointerDown.bind(App)) $(window).on('mouseup',App.onPointerUp.bind(App)) $(window).on('wheel',App.onPointerWheel.bind(App)) $(window).on("resize", _.debounce(App.onResize.bind(App), 250)) EventBus.getInstance().on(EVENTS.request_resize, _.debounce(App.onResize.bind(App), 250)) $(document).on("visibilitychange",App.onVisibilityChange.bind(App)) EventBus.getInstance().on(EVENTS.request_reload, App.onRequestReload) EventBus.getInstance().on(EVENTS.cancel_reload_request, App.onCancelReloadRequest) $(CONFIG.GAMECANVAS_SELECTOR).on("webglcontextlost", () -> App.onRequestReload({ id: "webgl_context_lost", message: "Your graphics hit a snag and requires a #{if window.isDesktop then "restart" else "reload"} to avoid any issues." }) ) # session is a plain event emitter Session.on('login', App.onLogin) Session.on('logout', App.onLogout) Session.on('error', App.onSessionError) EventBus.getInstance().on(EVENTS.show_login, App._showLoginMenu, App) EventBus.getInstance().on(EVENTS.show_terms, App._showTerms, App) EventBus.getInstance().on(EVENTS.show_play, App.showPlay, App) EventBus.getInstance().on(EVENTS.show_watch, App.showWatch, App) EventBus.getInstance().on(EVENTS.show_shop, App.showShop, App) EventBus.getInstance().on(EVENTS.show_collection, App.showCollection, App) EventBus.getInstance().on(EVENTS.show_codex, App.showCodex, App) EventBus.getInstance().on(EVENTS.show_booster_pack_unlock, App.showBoosterPackUnlock, App) EventBus.getInstance().on(EVENTS.show_crate_inventory, App.showCrateInventory, App) EventBus.getInstance().on(EVENTS.start_challenge, App._startGameWithChallenge, App) EventBus.getInstance().on(EVENTS.start_single_player, App._startSinglePlayerGame, App) EventBus.getInstance().on(EVENTS.start_boss_battle, App._startBossBattleGame, App) EventBus.getInstance().on(EVENTS.start_replay, App._startGameForReplay, App) EventBus.getInstance().on(EVENTS.show_free_card_of_the_day, App.showFreeCardOfTheDayReward, App) EventBus.getInstance().on(EVENTS.discord_spectate, App.onDiscordSpectate, App) GamesManager.getInstance().on(EVENTS.matchmaking_start, App._matchmakingStart, App) GamesManager.getInstance().on(EVENTS.matchmaking_cancel, App._matchmakingCancel, App) GamesManager.getInstance().on(EVENTS.matchmaking_error, App._matchmakingError, App) GamesManager.getInstance().on(EVENTS.finding_game, App._findingGame, App) GamesManager.getInstance().on(EVENTS.invite_accepted, App._inviteAccepted, App) GamesManager.getInstance().on(EVENTS.invite_rejected, App._inviteRejected, App) GamesManager.getInstance().on(EVENTS.invite_cancelled, App._inviteCancelled, App) GamesManager.getInstance().on(EVENTS.start_spectate, App._spectateGame, App) EventBus.getInstance().on EVENTS.canvas_mouse_state, App.onCanvasMouseState, App NavigationManager.getInstance().on(EVENTS.user_triggered_exit, App.onUserTriggeredExit, App) NavigationManager.getInstance().on(EVENTS.user_triggered_skip, App.onUserTriggeredSkip, App) NavigationManager.getInstance().on(EVENTS.user_triggered_cancel, App.onUserTriggeredCancel, App) NavigationManager.getInstance().on(EVENTS.user_triggered_confirm, App.onUserTriggeredConfirm, App) EventBus.getInstance().on EVENTS.error, App._error, App EventBus.getInstance().on EVENTS.ajax_error, App._error, App App._subscribeToGameLocalEvents = () -> Logger.module("APPLICATION").log "App._subscribeToGameLocalEvents" scene = Scene.getInstance() gameLayer = scene?.getGameLayer() if gameLayer? gameLayer.getEventBus().on(EVENTS.after_show_end_turn, App.onAfterShowEndTurn, App) gameLayer.getEventBus().on(EVENTS.show_game_over, App.onShowGameOver, App) gameLayer.getEventBus().on(EVENTS.canvas_mouse_state, App.onCanvasMouseState, App) SDK.GameSession.getInstance().getEventBus().on(EVENTS.game_over, App._onGameOver, App) SDK.GameSession.getInstance().getEventBus().on(EVENTS.end_turn, App._onEndTurn, App) App._unsubscribeFromGameLocalEvents = () -> Logger.module("APPLICATION").log "App._unsubscribeFromGameLocalEvents" scene = Scene.getInstance() gameLayer = scene?.getGameLayer() if gameLayer? gameLayer.getEventBus().off(EVENTS.after_show_end_turn, App.onAfterShowEndTurn, App) gameLayer.getEventBus().off(EVENTS.show_game_over, App.onShowGameOver, App) gameLayer.getEventBus().off(EVENTS.canvas_mouse_state, App.onCanvasMouseState, App) SDK.GameSession.getInstance().getEventBus().off(EVENTS.game_over, App._onGameOver, App) SDK.GameSession.getInstance().getEventBus().off(EVENTS.end_turn, App._onEndTurn, App) App._subscribeToGameNetworkEvents = () -> Logger.module("APPLICATION").log "App._subscribeToGameNetworkEvents" SDK.NetworkManager.getInstance().getEventBus().on(EVENTS.network_game_event, App._onNetworkGameEvent, App) SDK.NetworkManager.getInstance().getEventBus().on(EVENTS.network_game_error, App._onNetworkGameError, App) SDK.NetworkManager.getInstance().getEventBus().on(EVENTS.game_server_shutdown, App._onGameServerShutdown, App) SDK.NetworkManager.getInstance().getEventBus().on(EVENTS.reconnect_to_game, App._onReconnectToGame, App) SDK.NetworkManager.getInstance().getEventBus().on(EVENTS.opponent_connection_status_changed, App._onOpponentConnectionStatusChanged, App) App._unsubscribeFromGameNetworkEvents = () -> Logger.module("APPLICATION").log "App._unsubscribeFromGameNetworkEvents" SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.network_game_event, App._onNetworkGameEvent, App) SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.network_game_error, App._onNetworkGameError, App) SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.game_server_shutdown, App._onGameServerShutdown, App) SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.reconnect_to_game, App._onReconnectToGame, App) SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.opponent_connection_status_changed, App._onOpponentConnectionStatusChanged, App) App.onVisibilityChange = () -> # TODO: look into why this causes errors # Prevent sound effects that have been queued up from blasting all at once when app regains visibility if document.hidden # Would rather do a resume and start of effects, it doesn't stop them from piling up though audio_engine.current().stop_all_effects() else audio_engine.current().stop_all_effects() # # ---- RESIZE ---- # # App.onResize = (e) -> Logger.module("APPLICATION").log("App.onResize") # store current resolution data ignoreNextResolutionChange = App._ignoreNextResolutionChange App._ignoreNextResolutionChange = false if !ignoreNextResolutionChange currentResolution = CONFIG.resolution confirmResolutionChange = App._lastResolution? and App._lastResolution != currentResolution # before resize EventBus.getInstance().trigger(EVENTS.before_resize) # resize and update scale App._resizeAndScale() # resize the scene to match app Scene.getInstance().resize() # resize the UI EventBus.getInstance().trigger(EVENTS.resize) # after resize EventBus.getInstance().trigger(EVENTS.after_resize) # force user to restart if resource scale for engine has changed # CSS automatically handles resource scale changes # TODO: instead of restarting, destroy all current views, show loading screen, reload images at new scale, and return to current route App._needsRestart = App._lastResourceScaleEngine? and CONFIG.resourceScaleEngine != App._lastResourceScaleEngine if !App._needsRestart # cancel forced reload in case user has restored original window size App._cancelReloadRequestForResolutionChange() if confirmResolutionChange # confirm resolution with user after resizing App._confirmResolutionChange() else if App._needsRestart # force reload as user has changed window size App._requestReloadForResolutionChange() else # update resolution values as no confirm or restart needed App._updateLastResolutionValues() return true App._resizeAndScale = () -> Logger.module("APPLICATION").log("App._resizeAndScale") # resize canvas to match app size # engine bases its window size on the canvas size $html = $("html") $canvas = $(CONFIG.GAMECANVAS_SELECTOR) width = Math.max(CONFIG.REF_WINDOW_SIZE.width, $html.width()) height = Math.max(CONFIG.REF_WINDOW_SIZE.height, $html.height()) $canvas.width(width) $canvas.height(height) # set global scale CONFIG.globalScale = CONFIG.getGlobalScaleForResolution(CONFIG.resolution, width, height) # set css scales CONFIG.pixelScaleCSS = CONFIG.globalScale * window.devicePixelRatio $html.removeClass("resource-scale-" + String(CONFIG.resourceScaleCSS).replace(".", "\.")) CONFIG.resourceScaleCSS = 1 for resourceScale in CONFIG.RESOURCE_SCALES scaleDiff = Math.abs(CONFIG.pixelScaleCSS - resourceScale) currentScaleDiff = Math.abs(CONFIG.pixelScaleCSS - CONFIG.resourceScaleCSS) if scaleDiff < currentScaleDiff or (scaleDiff == currentScaleDiff and resourceScale > CONFIG.resourceScaleCSS) CONFIG.resourceScaleCSS = resourceScale $html.addClass("resource-scale-" + String(CONFIG.resourceScaleCSS).replace(".", "\.")) # html font size by global scale # css layout uses rems, which is based on html font size $html.css("font-size", CONFIG.globalScale * 10.0 + "px") App._lastResolution = null App._lastResourceScaleEngine = null App._ignoreNextResolutionChange = false App._needsRestart = false App._updateLastResolutionValues = () -> App._lastResolution = CONFIG.resolution App._lastResourceScaleEngine = CONFIG.resourceScaleEngine App._confirmResolutionChange = () -> Logger.module("APPLICATION").log "App._confirmResolutionChange" confirmData = {title: 'Do you wish to keep this viewport setting?'} if App._needsRestart if window.isDesktop confirmData.message = 'Warning: switching from your previous viewport to this viewport will require a restart!' else confirmData.message = 'Warning: switching from your previous viewport to this viewport will require a reload!' if ChatManager.getInstance().getStatusIsInBattle() confirmData.message += " You will be able to continue your game, but you may miss your turn!" confirmDialogItemView = new ConfirmDialogItemView(confirmData) confirmDialogItemView.listenToOnce(confirmDialogItemView, 'confirm', ()-> # update resolution after confirm App._lastResolution = CONFIG.resolution if App._needsRestart # defer to ensure this occurs after event resolves _.defer(App._requestReloadForResolutionChange) else # update resource scale if no restart needed App._lastResourceScaleEngine = CONFIG.resourceScaleEngine ) confirmDialogItemView.listenToOnce(confirmDialogItemView, 'cancel', ()-> # defer to ensure this occurs after event resolves _.defer(() -> # reset resolution and don't prompt about changes App._ignoreNextResolutionChange = true res = App._lastResolution || CONFIG.RESOLUTION_DEFAULT CONFIG.resolution = res Storage.set("resolution", res) App.onResize() ) ) # show confirm/cancel NavigationManager.getInstance().showDialogView(confirmDialogItemView) App._requestReloadForResolutionChangeId = "resolution_change" App._requestReloadForResolutionChange = () -> App.onRequestReload({ id: App._requestReloadForResolutionChangeId message: "Your viewport change requires a #{if window.isDesktop then "restart" else "reload"} to avoid any issues." }) App._cancelReloadRequestForResolutionChange = () -> App.onCancelReloadRequest({ id: App._requestReloadForResolutionChangeId }) # # ---- RELOAD ---- # # App._reloadRequestIds = [] ### * Request a reload, optionally passing in a message and id (to avoid conflicts). *### App.onRequestReload = (event) -> requestId = event?.id or 0 if !_.contains(App._reloadRequestIds, requestId) App._reloadRequestIds.push(requestId) if App._reloadRequestIds.length == 1 App._reload(event?.message) ### * Cancel a reload request, optionally passing in an id (to avoid conflicts). *### App.onCancelReloadRequest = (event) -> requestId = event?.id or 0 index = _.indexOf(App._reloadRequestIds, requestId) if index != -1 App._reloadRequestIds.splice(index, 1) if App._reloadRequestIds.length == 0 App._cancelReload() App._reload = (message) -> Logger.module("APPLICATION").log "App._reload" promptDialogItemView = new PromptDialogItemView({title: "Please #{if window.isDesktop then "restart" else "reload"}!", message: message}) promptDialogItemView.listenTo(promptDialogItemView, 'cancel', () -> if window.isDesktop then window.quitDesktop() else location.reload() ) NavigationManager.getInstance().showDialogView(promptDialogItemView) App._cancelReload = () -> Logger.module("APPLICATION").log "App._cancelReload" NavigationManager.getInstance().destroyDialogView() # # ---- Initialization Events ---- # # Sequence of events started with App.start. Can pass options object. # # Pre-Start Event App.on "before:start", (options) -> Logger.module("APPLICATION").log "----BEFORE START----" App.$el = $("#app") # Start Event App.on "start", (options) -> Logger.module("APPLICATION").log "----START----" # set unload alert $(window).on('beforeunload', App.beforeunload.bind(App)) # set initial selected scene selectedScene = parseInt(Storage.get("selectedScene")) if moment.utc().isAfter("2016-11-29") and moment.utc().isBefore("2017-01-01") selectedScene = SDK.CosmeticsLookup.Scene.Frostfire if moment.utc().isAfter("2017-03-14") and moment.utc().isBefore("2017-05-01") selectedScene = SDK.CosmeticsLookup.Scene.Vetruvian if moment.utc().isAfter("2017-07-01") and moment.utc().isBefore("2017-08-01") selectedScene = SDK.CosmeticsLookup.Scene.Shimzar if moment.utc().isAfter("2017-12-01") and moment.utc().isBefore("2018-01-18") selectedScene = SDK.CosmeticsLookup.Scene.Frostfire if selectedScene? and !isNaN(selectedScene) and _.isNumber(selectedScene) then CONFIG.selectedScene = selectedScene # set initial resolution userResolution = parseInt(Storage.get("resolution")) if userResolution? and !isNaN(userResolution) and _.isNumber(userResolution) then CONFIG.resolution = userResolution userHiDPIEnabled = Storage.get("hiDPIEnabled") if userHiDPIEnabled? if userHiDPIEnabled == "true" then CONFIG.hiDPIEnabled = true else if userHiDPIEnabled == "false" then CONFIG.hiDPIEnabled = false # update last resolution values to initial App._updateLastResolutionValues() # resize once for initial values App._resizeAndScale() # create a defered promise object for the loading and login process... sort of an anti-pattern but best for this use case App.managersReadyDeferred = new Promise.defer() # immediately connect the server status manager so we can get notified of any changes during the load process / on the login screen ServerStatusManager.getInstance().connect() # push a telemetry signal that a client is loading TelemetryManager.getInstance().setSignal("lifecycle","loading") TelemetryManager.getInstance().setSignal("session","not-logged-in") # authenticate defered, the isAuthed check must stay here so we can # clear the token in the event it is stale / isAuthed fails # the App._authenticationPromise below does not fire if there's no loading App._authenticationPromise = () -> return Session.isAuthenticated(Storage.get('token')) .then (isAuthed) -> if !isAuthed Storage.remove('token') return isAuthed # VIEW/engine needs to be setup and cocos manages its own setup so we need to wait async Logger.module("APPLICATION").group("LOADING") App._loadingPromise = Scene.setup().then(() -> # update last resolution values to initial App._updateLastResolutionValues() # setup all events App.bindEvents() # load the package of resources that should always loaded return PackageManager.getInstance().loadPackage("alwaysloaded") ).then(() -> # temporary bypass all loader return Promise.resolve() # check if all assets should be loaded now or as needed # we want to know if the client has cached all resources for this version # we only care when not using the desktop client, on the production environment, and not loading all at start # if we need to cache all resources for this version, do a non allocating cache load first version_preloaded = Storage.get("version_preloaded") needs_non_allocating_cache_load = version_preloaded != process.env.VERSION && !window.isDesktop && !CONFIG.LOAD_ALL_AT_START && UtilsEnv.getIsInProduction() needs_non_allocating_cache_load = needs_non_allocating_cache_load && !App._queryStringParams['replayId']? if needs_non_allocating_cache_load || CONFIG.LOAD_ALL_AT_START # temporarily force disable the load all at start flag # this allows the preloader to setup as a major package # so that it gets loaded correctly before we load all load_all_at_start = CONFIG.LOAD_ALL_AT_START CONFIG.LOAD_ALL_AT_START = false # load preloader scene to show load of all resources return PackageManager.getInstance().loadAndActivateMajorPackage("preloader", null, null, () -> # reset load all at start flag CONFIG.LOAD_ALL_AT_START = load_all_at_start # hide loading dialog NavigationManager.getInstance().destroyDialogForLoad() # show load ui viewPromise = Scene.getInstance().showLoad() contentPromise = NavigationManager.getInstance().showContentView(new LoaderItemView()) # once we've authenticated, show utility for loading/login # this way users can quit anytime on desktop, and logout or adjust settings while waiting for load App._authenticationPromise().then (isAuthed) -> if App.getIsLoggedIn() or window.isDesktop return NavigationManager.getInstance().showUtilityView(new UtilityLoadingLoginMenuItemView()) else return Promise.resolve() return Promise.all([ viewPromise, contentPromise ]) ).then(() -> # load all resources return PackageManager.getInstance().loadPackage("all", null, ((progress) -> Scene.getInstance().getLoadLayer()?.showLoadProgress(progress)), needs_non_allocating_cache_load) ).then(() -> # set version assets were preloaded for if !window.isDesktop Storage.set("version_preloaded", process.env.VERSION) ) else # no loading needed now return Promise.resolve() ).then(() -> # clear telemetry signal that a client is loading TelemetryManager.getInstance().clearSignal("lifecycle","loading") # end loading log group Logger.module("APPLICATION").groupEnd() ) # setup start promise App._startPromise = Promise.all([ App._loadingPromise, App._authenticationPromise() ]) # goto main screen App.main() # get minimum browsers from Firebase App.getMinBrowserVersions = () -> if Storage.get("skipBrowserCheck") then return Promise.resolve() return new Promise (resolve, reject) -> minBrowserVersionRef = new Firebase(process.env.FIREBASE_URL).child("system-status").child('browsers') defaults = { "Chrome": 50, "Safari": 10, "Firefox": 57, "Edge": 15 } # create a timeout to skip check in case Firebase lags (so atleast user does not get stuck on black screen) minBrowserVersionTimeout = setTimeout(() -> minBrowserVersionRef.off() resolve(defaults) , 5000) minBrowserVersionRef.once 'value', (snapshot) -> clearTimeout(minBrowserVersionTimeout) if !snapshot.val() resolve(defaults) else resolve(snapshot.val()) # check if given browser is valid when compared against list of allowed browsers App.isBrowserValid = (browserName, browserMajor, browserlist) -> if Storage.get("skipBrowserCheck") then return true if Object.keys(browserlist).includes(browserName) return parseInt(browserMajor, 10) >= browserlist[browserName] else return false App.generateBrowserHtml = (browser, version) -> if browser == 'Chrome' return """ <p><a href='http://google.com/chrome'><strong>Google Chrome</strong> #{version} or newer.</a></p> """ else if browser == 'Safari' return """ <p><a href='https://www.apple.com/safari/'><strong>Apple Safari</strong> #{version} or newer.</a></p> """ else if browser == 'Firefox' return """ <p><a href='https://www.mozilla.org/firefox/'><strong>Mozilla Firefox</strong> #{version} or newer.</a></p> """ else if browser == 'Edge' return """ <p><a href='https://www.microsoft.com/en-us/windows/microsoft-edge'><strong>Microsoft Edge</strong> #{version} or newer.</a></p> """ # show some HTML saying the current browser is not supported if browser detection fails App.browserTestFailed = (browserlist) -> html = """ <div style="margin:auto; position:absolute; height:50%; width:100%; top: 0px; bottom: 0px; font-size: 20px; color: white; text-align: center;"> <p>Looks like your current browser is not supported.</p> <p>Visit <a href='https://support.duelyst.com' style="color: gray;">our support page</a> to submit a request for assistance.</p> <br> """ # dynamically create html containing list of support browsers Object.keys(browserlist).forEach (browser) -> version = browserlist[browser] html += App.generateBrowserHtml(browser, version) html += "</div>" $("#app-preloading").css({display:"none"}) $("#app-content-region").css({margin:"auto", height:"50%", width: "50%"}) $("#app-content-region").html(html) # ensure webgl is correctly running App.glTest = () -> try canvas = document.createElement('canvas') return !! (window.WebGLRenderingContext && (canvas.getContext('webgl') || canvas.getContext('experimental-webgl'))) catch e return false App.glTestFailed = () -> if window.isDesktop html = """ <div style="margin:auto; position:absolute; height:50%; width:100%; top: 0px; bottom: 0px; font-size: 20px; color: white; text-align: center;"> <p>Looks like your video card is not supported.</p> <p>Ensure your video card drivers are up to date.</p> <p>Visit <a id='support-link' href='https://support.duelyst.com' style="color: gray;">our support page</a> to submit a request for assistance.</p> </div> """ else html = """ <div style="margin:auto; position:absolute; height:50%; width:100%; top: 0px; bottom: 0px; font-size: 20px; color: white; text-align: center;"> <p>Looks like WebGL is not enabled in your browser./p> <p>Visit the <a id='webgl-link' href='https://get.webgl.org/' style="color: gray;">WebGL test page</a> for more information.</p> <p>Visit <a id='support-link' href='https://support.duelyst.com' style="color: gray;">our support page</a> to submit a request for assistance.</p> </div> """ $("#app-preloading").css({display:"none"}) $("#app-content-region").css({margin:"auto", height:"50%", width: "50%"}) $("#app-content-region").html(html) $("#webgl-link").click (e) -> openUrl($(e.currentTarget).attr("href")) e.stopPropagation() e.preventDefault() $("#support-link").click (e) -> openUrl($(e.currentTarget).attr("href")) e.stopPropagation() e.preventDefault() # show some HTML saying they are on an old client version App.versionTestFailed = () -> if window.isDesktop html = """ <div style="margin:auto; position:absolute; height:50%; width:100%; top: 0px; bottom: 0px; font-size: 20px; color: white; text-align: center;"> <p>Looks like you are running an old version of DUELYST.</p> <p>Exit and restart DUELYST to update to the latest version.</p> <p>If you are using Steam, you may need to restart Steam before the update appears.</p> <p>Click <a id='reload-link' href='' style="color: gray;">here</a> to exit.</p> </div> """ else html = """ <div style="margin:auto; position:absolute; height:50%; width:100%; top: 0px; bottom: 0px; font-size: 20px; color: white; text-align: center;"> <p>Looks like you are running an old version of DUELYST.</p> <p>Click <a id='reload-link' href='' style="color: gray;">here</a> to refresh your browser to the latest version.</p> </div> """ $("#app-preloading").css({display:"none"}) $("#app-content-region").css({margin:"auto", height:"50%", width: "50%"}) $("#app-content-region").html(html) $("#reload-link").click (e) -> if window.isDesktop then window.quitDesktop() else location.reload() # compare if process.env.VERSION is gte >= than provided minimum version # if minimumVersion is undefined or null, we set to '0.0.0' App.isVersionValid = (minimumVersion) -> Logger.module("APPLICATION").log "#{process.env.VERSION} >= #{minimumVersion || '0.0.0'}" if App._queryStringParams["replayId"] return true else try return semver.gte(process.env.VERSION, minimumVersion || '0.0.0') catch e return true # App.setup is the main entry function into Marionette app # grabs configuration from server we're running on and call App.start() App.setup = () -> # mark all requests with buld version $.ajaxSetup headers: "Client-Version": process.env.VERSION # check if it is a new user and we should redirect otherwise start as normal if Landing.isNewUser() && Landing.shouldRedirect() Landing.redirect() else App.start() # # ---- Application Start Sequence ---- # # App.getMinBrowserVersions() .then (browserlist) -> if !App.isBrowserValid(userAgent.browser.name, userAgent.browser.major, browserlist) return App.browserTestFailed(browserlist) if !App.glTest() return App.glTestFailed() if window.isSteam App.minVersionRef = new Firebase(process.env.FIREBASE_URL).child("system-status").child('steam_minimum_version') else App.minVersionRef = new Firebase(process.env.FIREBASE_URL).child("system-status").child('minimum_version') # wrap App.setup() in _.once() just to be safe from double calling App.setupOnce = _.once(App.setup) # create a timeout to skip version check in case Firebase lags (so atleast user does not get stuck on black screen) App.versionCheckTimeout = setTimeout(() -> App.minVersionRef.off() App.setupOnce() , 5000) # read minimum version from Firebase and perform check, if fails, show error html # otherwise start application as normal App.minVersionRef.once('value', (snapshot) -> clearTimeout(App.versionCheckTimeout) if !App.isVersionValid(snapshot.val()) App.versionTestFailed() else App.setupOnce() )
true
# User Agent Parsing UAParser = require 'ua-parser-js' uaparser = new UAParser() uaparser.setUA(window.navigator.userAgent) userAgent = uaparser.getResult() # userAgent now contains : browser, os, device, engine objects # ---- Marionette Application ---- # # App = new Backbone.Marionette.Application() # require Firebase via browserify but temporarily alias it global scope Firebase = window.Firebase = require 'firebase' Promise = require 'bluebird' moment = require 'moment' semver = require 'semver' querystring = require 'query-string' # core Storage = require 'app/common/storage' Logger = window.Logger = require 'app/common/logger' Logger.enabled = (process.env.NODE_ENV != 'production' && process.env.NODE_ENV != 'staging') Landing = require 'app/common/landing' Session = window.Session = require 'app/common/session2' CONFIG = window.CONFIG = require 'app/common/config' RSX = window.RSX = require 'app/data/resources' PKGS = window.PKGS = require 'app/data/packages' EventBus = window.EventBus = require 'app/common/eventbus' EVENTS = require 'app/common/event_types' SDK = window.SDK = require 'app/sdk' Analytics = window.Analytics = require 'app/common/analytics' AnalyticsUtil = require 'app/common/analyticsUtil' UtilsJavascript = require 'app/common/utils/utils_javascript' UtilsEnv = require 'app/common/utils/utils_env' UtilsPointer = require 'app/common/utils/utils_pointer' audio_engine = window.audio_engine = require 'app/audio/audio_engine' openUrl = require('app/common/openUrl') i18next = require('i18next') # models and collections CardModel = require 'app/ui/models/card' DuelystFirebase = require 'app/ui/extensions/duelyst_firebase' DuelystBackbone = require 'app/ui/extensions/duelyst_backbone' # Managers / Controllers PackageManager = window.PackageManager = require 'app/ui/managers/package_manager' ProfileManager = window.ProfileManager = require 'app/ui/managers/profile_manager' GameDataManager = window.GameDataManager = require 'app/ui/managers/game_data_manager' GamesManager = window.GamesManager = require 'app/ui/managers/games_manager' CrateManager = window.CrateManager = require 'app/ui/managers/crate_manager' NotificationsManager = window.NotificationsManager = require 'app/ui/managers/notifications_manager' NavigationManager = window.NavigationManager = require 'app/ui/managers/navigation_manager' ChatManager = window.ChatManager = require 'app/ui/managers/chat_manager' InventoryManager = window.InventoryManager = require 'app/ui/managers/inventory_manager' QuestsManager = window.QuestsManager = require 'app/ui/managers/quests_manager' TelemetryManager = window.TelemetryManager = require 'app/ui/managers/telemetry_manager' ProgressionManager = window.ProgressionManager = require 'app/ui/managers/progression_manager' ServerStatusManager = window.ServerStatusManager = require 'app/ui/managers/server_status_manager' NewsManager = window.NewsManager = require 'app/ui/managers/news_manager' NewPlayerManager = window.NewPlayerManager = require 'app/ui/managers/new_player_manager' AchievementsManager = window.AchievementsManager = require 'app/ui/managers/achievements_manager' TwitchManager = window.TwitchManager = require 'app/ui/managers/twitch_manager' ShopManager = window.ShopManager = require 'app/ui/managers/shop_manager' StreamManager = window.StreamManager = require 'app/ui/managers/stream_manager' # Views Helpers = require 'app/ui/views/helpers' LoaderItemView = require 'app/ui/views/item/loader' UtilityLoadingLoginMenuItemView = require 'app/ui/views/item/utility_loading_login_menu' UtilityMainMenuItemView = require 'app/ui/views/item/utility_main_menu' UtilityMatchmakingMenuItemView = require 'app/ui/views/item/utility_matchmaking_menu' UtilityGameMenuItemView = require 'app/ui/views/item/utility_game_menu' EscGameMenuItemView = require 'app/ui/views/item/esc_game_menu' EscMainMenuItemView = require 'app/ui/views/item/esc_main_menu' LoginMenuItemView = require 'app/ui/views/item/login_menu' Discord = if window.isDesktop then require('app/common/discord') else null SelectUsernameItemView = require 'app/ui/views/item/select_username' Scene = require 'app/view/Scene' GameLayer = require 'app/view/layers/game/GameLayer' MainMenuItemView = require 'app/ui/views/item/main_menu' CollectionLayout = require 'app/ui/views2/collection/collection' PlayLayout = require 'app/ui/views/layouts/play' PlayLayer = require 'app/view/layers/pregame/PlayLayer' WatchLayout = require 'app/ui/views2/watch/watch_layout' ShopLayout = require 'app/ui/views2/shop/shop_layout' CodexLayout = require 'app/ui/views2/codex/codex_layout' CodexLayer = require 'app/view/layers/codex/CodexLayer' TutorialLessonsLayout = require 'app/ui/views2/tutorial/tutorial_lessons_layout' QuestLogLayout = require 'app/ui/views2/quests/quest_log_layout' BoosterPackUnlockLayout = require 'app/ui/views/layouts/booster_pack_collection' BoosterPackOpeningLayer = require 'app/view/layers/booster/BoosterPackOpeningLayer' VictoryLayer = require 'app/view/layers/postgame/VictoryLayer' UnlockFactionLayer = require 'app/view/layers/reward/UnlockFactionLayer.js' ProgressionRewardLayer = require 'app/view/layers/reward/ProgressionRewardLayer.js' CosmeticKeyRewardLayer = require 'app/view/layers/reward/CosmeticKeyRewardLayer.js' LadderProgressLayer = require 'app/view/layers/postgame/LadderProgressLayer' RiftProgressLayer = require 'app/view/layers/postgame/RiftProgressLayer' CurrencyRewardLayer = require 'app/view/layers/reward/CurrencyRewardLayer.js' GauntletTicketRewardLayer = require 'app/view/layers/reward/GauntletTicketRewardLayer.js' BoosterRewardLayer = require 'app/view/layers/reward/BoosterRewardLayer.js' LootCrateRewardLayer = require 'app/view/layers/reward/LootCrateRewardLayer.js' FreeCardOfTheDayLayer = require 'app/view/layers/reward/FreeCardOfTheDayLayer.js' CrateOpeningLayer = require 'app/view/layers/crate/CrateOpeningLayer' EndOfSeasonLayer = require 'app/view/layers/season/EndOfSeasonLayer' ResumeGameItemView = require 'app/ui/views/item/resume_game' FindingGameItemView = require 'app/ui/views/item/finding_game' ReconnectToGameItemView = require 'app/ui/views/item/reconnect_to_game' GameLayout = require 'app/ui/views/layouts/game' TutorialLayout = require 'app/ui/views/layouts/tutorial' VictoryItemView = require 'app/ui/views/item/victory' MessagesCompositeView = require 'app/ui/views/composite/messages' ConfirmDialogItemView = require 'app/ui/views/item/confirm_dialog' PromptDialogItemView = require 'app/ui/views/item/prompt_dialog' ActivityDialogItemView = require 'app/ui/views/item/activity_dialog' ErrorDialogItemView = require 'app/ui/views/item/error_dialog' AnnouncementModalView = require 'app/ui/views/item/announcement_modal' ShopSpecialProductAvailableDialogItemView = require 'app/ui/views2/shop/shop_special_product_available_dialog' ReplayEngine = require 'app/replay/replayEngine' AnalyticsTracker = require 'app/common/analyticsTracker' # require the Handlebars Template Helpers extension here since it modifies core Marionette code require 'app/ui/extensions/handlebars_template_helpers' localStorage.debug = 'session:*' # # --- Utility ---- # # App._screenBlurId = "AppScreenBlurId" App._userNavLockId = "AppUserNavLockId" App._queryStringParams = querystring.parse(location.search) # query string params App.getIsLoggedIn = -> return Storage.get('token') # region AI DEV ROUTES # if process.env.AI_TOOLS_ENABLED ### Before using AI DEV ROUTES, make sure you have a terminal open and run `node server/ai/phase_ii_ai.js`. ### window.ai_v1_findNextActions = (playerId, difficulty) -> return new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/v1_find_next_actions", data: JSON.stringify({ game_session_data: SDK.GameSession.getInstance().generateGameSessionSnapshot(), player_id: playerId, difficulty: difficulty }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> actionsData = JSON.parse(res.actions) actions = [] for actionData in actionsData action = SDK.GameSession.getInstance().deserializeActionFromFirebase(actionData) actions.push(action) console.log("v1_find_next_actions -> ", actions) resolve(actions) request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) .catch App._error window.ai_v2_findActionSequence = (playerId, depthLimit, msTimeLimit) -> return new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/v2_find_action_sequence", data: JSON.stringify({ game_session_data: SDK.GameSession.getInstance().generateGameSessionSnapshot(), player_id: playerId, depth_limit: depthLimit, ms_time_limit: msTimeLimit }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> sequenceActionsData = JSON.parse(res.sequence_actions) console.log("ai_v2_findActionSequence -> ", sequenceActionsData) resolve(sequenceActionsData) request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) .catch App._error window.ai_gameStarted = false window.ai_gameRunning = false window.ai_gameStepsData = null window.ai_gameStepsDataPromise = null window.ai_gamePromise = null window.ai_gameNeedsMulligan = false window.ai_stopAIvAIGame = () -> if window.ai_gameStarted window.ai_gameStarted = false window.ai_gameRunning = false window.ai_gameStepsData = null window.ai_gameNeedsMulligan = false if window.ai_gameStepsDataPromise? window.ai_gameStepsDataPromise.cancel() window.ai_gameStepsDataPromise = null if window.ai_gamePromise? window.ai_gamePromise.cancel() window.ai_gamePromise = null return new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/stop_game", data: JSON.stringify({}), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve() request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) .catch App._error window.ai_pauseAIvAIGame = () -> if window.ai_gameRunning window.ai_gameRunning = false window.ai_resumeAIvAIGame = () -> if !window.ai_gameRunning window.ai_gameRunning = true window.ai_stepAIvAIGame() window.ai_runAIvAIGame = (ai1Version, ai2Version, ai1GeneralId, ai2GeneralId, depthLimit, msTimeLimit, ai1NumRandomCards, ai2NumRandomCards) -> # pick random general if none provided if !ai1GeneralId? then ai1GeneralId = _.sample(_.sample(SDK.FactionFactory.getAllPlayableFactions()).generalIds) if !ai2GeneralId? then ai2GeneralId = _.sample(_.sample(SDK.FactionFactory.getAllPlayableFactions()).generalIds) ai1FactionId = SDK.FactionFactory.factionIdForGeneralId(ai1GeneralId) ai2FactionId = SDK.FactionFactory.factionIdForGeneralId(ai2GeneralId) # stop running game window.ai_gamePromise = ai_stopAIvAIGame().then () -> Logger.module("APPLICATION").log("ai_runAIvAIGame - > requesting for v#{ai1Version} w/ general #{SDK.CardFactory.cardForIdentifier(ai1GeneralId, SDK.GameSession.getInstance()).getName()} vs v#{ai2Version} w/ general #{SDK.CardFactory.cardForIdentifier(ai2GeneralId, SDK.GameSession.getInstance()).getName()}") window.ai_gameStarted = true window.ai_gameRunning = true # request run simulation startSimulationPromise = new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/start_game", data: JSON.stringify({ ai_1_version: ai1Version ai_1_general_id: ai1GeneralId ai_2_version: ai2Version ai_2_general_id: ai2GeneralId, depth_limit: depthLimit, ms_time_limit: msTimeLimit, ai_1_num_random_cards: ai1NumRandomCards, ai_2_num_random_cards: ai2NumRandomCards }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve(JSON.parse(res.game_session_data)) request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) # start loading loadingPromise = NavigationManager.getInstance().showDialogForLoad().then () -> return PackageManager.getInstance().loadGamePackageWithoutActivation([ai1FactionId, ai2FactionId]) return Promise.all([ startSimulationPromise, loadingPromise ]) .spread (sessionData) -> Logger.module("APPLICATION").log("ai_runAIvAIGame - > starting #{sessionData.gameId} with data:", sessionData) # reset and deserialize SDK.GameSession.reset() SDK.GameSession.getInstance().deserializeSessionFromFirebase(sessionData) # switch session game type to sandbox SDK.GameSession.getInstance().setGameType(SDK.GameType.Sandbox) # set game user id to match player 1 SDK.GameSession.getInstance().setUserId(SDK.GameSession.getInstance().getPlayer1Id()) return App._startGame() .then () -> Logger.module("APPLICATION").log("ai_runAIvAIGame - > #{SDK.GameSession.getInstance().getGameId()} running") # stop running game when game is terminated Scene.getInstance().getGameLayer().getEventBus().on(EVENTS.terminate, window.ai_stopAIvAIGame) # listen for finished showing step # wait for active (ai will already have mulliganed) return Scene.getInstance().getGameLayer().whenStatus(GameLayer.STATUS.ACTIVE).then () -> Scene.getInstance().getGameLayer().getEventBus().on(EVENTS.after_show_step, window.ai_stepAIvAIGame) # execute first step in sequence window.ai_stepAIvAIGame() .cancellable() .catch Promise.CancellationError, (e)-> Logger.module("APPLICATION").log("ai_runAIvAIGame -> promise chain cancelled") .catch App._error return ai_gamePromise window.ai_runAIvAIGameFromCurrentSession = (ai1Version, ai2Version, depthLimit, msTimeLimit) -> # stop running game window.ai_gamePromise = ai_stopAIvAIGame().then () -> Logger.module("APPLICATION").log("ai_runAIvAIGameFromCurrentSession - > requesting for v#{ai1Version} vs v#{ai2Version}") window.ai_gameStarted = true window.ai_gameRunning = true # set as non authoritative # all steps will be coming from ai simulation server SDK.GameSession.getInstance().setIsRunningAsAuthoritative(false); # request run simulation return new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/start_game_from_data", data: JSON.stringify({ ai_1_version: ai1Version ai_2_version: ai2Version depth_limit: depthLimit, ms_time_limit: msTimeLimit, game_session_data: SDK.GameSession.getInstance().generateGameSessionSnapshot() }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve() request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) .then () -> # stop running game when game is terminated Scene.getInstance().getGameLayer().getEventBus().on(EVENTS.terminate, window.ai_stopAIvAIGame) # listen for finished showing step Scene.getInstance().getGameLayer().whenStatus(GameLayer.STATUS.ACTIVE).then () -> Scene.getInstance().getGameLayer().getEventBus().on(EVENTS.after_show_step, window.ai_stepAIvAIGame) if window.ai_gameNeedsMulligan Logger.module("APPLICATION").log("ai_stepAIvAIGame -> mulligan complete") window.ai_gameNeedsMulligan = false window.ai_stepAIvAIGame() # check if needs mulligan window.ai_gameNeedsMulligan = SDK.GameSession.getInstance().isNew() # execute first step in sequence window.ai_stepAIvAIGame() .cancellable() .catch Promise.CancellationError, (e)-> Logger.module("APPLICATION").log("ai_runAIvAIGameFromCurrentSession -> promise chain cancelled") .catch App._error return ai_gamePromise window.ai_stepAIvAIGame = (event) -> if event?.step?.action instanceof SDK.EndTurnAction then return # ignore auto stepping due to end turn action as start turn will cause auto step Logger.module("APPLICATION").log("ai_stepAIvAIGame -> #{SDK.GameSession.getInstance().getGameId()} step queue length #{Scene.getInstance().getGameLayer()._stepQueue.length}") if !window.ai_gameStepsDataPromise? and Scene.getInstance().getGameLayer()._stepQueue.length == 0 # request step game window.ai_gameStepsDataPromise = new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/step_game", data: JSON.stringify({ game_id: SDK.GameSession.getInstance().getGameId() }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> if res.steps? resolve(JSON.parse(res.steps)) else resolve([]) request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) .then (stepsData) -> Logger.module("APPLICATION").log("ai_stepAIvAIGame -> steps:", stepsData.slice(0)) window.ai_gameStepsData = stepsData .cancellable() .catch Promise.CancellationError, (e)-> Logger.module("APPLICATION").log("ai_stepAIvAIGame -> promise chain cancelled") return window.ai_gameStepsDataPromise.then () -> if window.ai_gameRunning and !SDK.GameSession.getInstance().isOver() and window.ai_gameStepsData? and window.ai_gameStepsData.length > 0 # remove and deserialize next step in sequence stepData = window.ai_gameStepsData.shift() step = SDK.GameSession.getInstance().deserializeStepFromFirebase(stepData) Logger.module("APPLICATION").log("ai_stepAIvAIGame -> step:", step) # execute step SDK.GameSession.getInstance().executeAuthoritativeStep(step) # check game status and steps data if SDK.GameSession.getInstance().isOver() or window.ai_gameStepsData.length == 0 Logger.module("APPLICATION").log("ai_stepAIvAIGame -> done") window.ai_gameStepsData = null window.ai_gameStepsDataPromise = null else if step.action instanceof SDK.EndTurnAction # auto step to start turn Logger.module("APPLICATION").log("ai_stepAIvAIGame -> continuing end turn") window.ai_stepAIvAIGame() else if window.ai_gameNeedsMulligan # auto step to next mulligan Logger.module("APPLICATION").log("ai_stepAIvAIGame -> continuing mulligan") window.ai_stepAIvAIGame() window.ai_runHeadlessAIvAIGames = (numGames, ai1Version, ai2Version, ai1GeneralId, ai2GeneralId, depthLimit, msTimeLimit, ai1NumRandomCards, ai2NumRandomCards) -> Logger.module("APPLICATION").log("ai_runHeadlessAIvAIGames - > requesting #{numGames} games with v#{ai1Version} vs v#{ai2Version}") # request run games return new Promise (resolve, reject) -> request = $.ajax url: "http://localhost:5001/run_headless_games", data: JSON.stringify({ ai_1_version: ai1Version ai_1_general_id: ai1GeneralId ai_2_version: ai2Version ai_2_general_id: ai2GeneralId, num_games: numGames, depth_limit: depthLimit, ms_time_limit: msTimeLimit, ai_1_num_random_cards: ai1NumRandomCards, ai_2_num_random_cards: ai2NumRandomCards }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve() request.fail (jqXHR)-> if (jqXHR.responseJSON && jqXHR.responseJSON.message) errorMessage = jqXHR.responseJSON.message else errorMessage = "Something went wrong." reject(errorMessage) # endregion AI DEV ROUTES # # # --- Main ---- # # App.getIsShowingMain = () -> # temporary method to check if the user can navigate to main (i.e. not already there) # this does NOT work for switching between main sub-screens return NavigationManager.getInstance().getIsShowingContentViewClass(LoginMenuItemView) or NavigationManager.getInstance().getIsShowingContentViewClass(MainMenuItemView) or NavigationManager.getInstance().getIsShowingContentViewClass(ResumeGameItemView) App.main = -> if !App._mainPromise? App._mainPromise = App._startPromise.then(() -> Logger.module("APPLICATION").log("App:main") # get and reset last game data lastGameType = CONFIG.lastGameType wasSpectate = CONFIG.lastGameWasSpectate wasTutorial = CONFIG.lastGameWasTutorial wasDeveloper = CONFIG.lastGameWasDeveloper wasDailyChallenge = CONFIG.lastGameWasDailyChallenge CONFIG.resetLastGameData() # destroy game and clear game data App.cleanupGame() # always make sure we're disconnected from the last game SDK.NetworkManager.getInstance().disconnect() # reset routes to main NavigationManager.getInstance().resetRoutes() NavigationManager.getInstance().addMajorRoute("main", App.main, App) # always restore user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationUnlocked(App._userNavLockId) if App._queryStringParams["replayId"]? Logger.module("APPLICATION").log("jumping straight into replay...") App.setCallbackWhenCancel(()-> alert('all done!')) return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> EventBus.getInstance().trigger(EVENTS.start_replay, { replayId: App._queryStringParams["replayId"] }) return Promise.resolve() ) else if !App.getIsLoggedIn() return App._showLoginMenu() else # all good, show main menu return App.managersReadyDeferred.promise.then(() -> # set user as loading ChatManager.getInstance().setStatus(ChatManager.STATUS_LOADING) # # EULA ACCEPTANCE CHECK HERE SO IT FIRES FOR ALREADY LOGGED IN PLAYERS # # strings used for session storage and profile storage # sessionAcceptedEula = Storage.namespace() + '.hasAcceptedEula' # storageAcceptedEula = 'hasAcceptedEula' # storageSentAcceptedEulaNotify = 'hasSentAcceptedEulaNotify' # # the user has accepted terms in the local session, ensure we are set in profile storage # if window.sessionStorage.getItem(sessionAcceptedEula) # ProfileManager.getInstance().set(storageAcceptedEula, true) # # check in profile storage if the user has accepted terms # if !ProfileManager.getInstance().get(storageAcceptedEula) # # TODO - This is not actually good, but we need to make a new terms and conditions page to replace BNEA one # return App._showTerms() # # user has accepted, check if they have sent notification # else # if !ProfileManager.getInstance().get(storageSentAcceptedEulaNotify) # ProfileManager.getInstance().set(storageSentAcceptedEulaNotify, true) # check for an active game lastGameModel = null if GamesManager.getInstance().playerGames.length > 0 lastGameModel = GamesManager.getInstance().playerGames.first() # calculate minutes since last game msSinceLastGame = moment().utc().valueOf() - (lastGameModel?.get("created_at") || 0) minutesSinceLastGame = moment.duration(msSinceLastGame).asMinutes() # if the last game is an active multiplayer game within last 45 minutes, show the continue game screen if lastGameModel? and lastGameModel.get("cancel_reconnect") != true and (lastGameModel.get("status") == "active" || lastGameModel.get("status") == "new") and lastGameModel.get("created_at") and minutesSinceLastGame < CONFIG.MINUTES_ALLOWED_TO_CONTINUE_GAME and SDK.GameType.isMultiplayerGameType(lastGameModel.get("game_type")) # has active game, prompt user to resume Logger.module("UI").log("Last active game was on ", new Date(lastGameModel.get("created_at")), "with data", lastGameModel) return App._resumeGame(lastGameModel) else if not NewPlayerManager.getInstance().isDoneWithTutorial() # show tutorial layout return App._showTutorialLessons() else if QuestsManager.getInstance().hasUnreadQuests() # show main menu return App._showMainMenu() else # try to return to selection for previous game type if wasSpectate return App._showMainMenu() else if wasDailyChallenge QuestsManager.getInstance().markDailyChallengeCompletionAsUnread() return App._showMainMenu() else if lastGameType == SDK.GameType.Ranked and !NewPlayerManager.getInstance().getEmphasizeBoosterUnlock() return App.showPlay(SDK.PlayModes.Ranked, true) else if lastGameType == SDK.GameType.Casual and !NewPlayerManager.getInstance().getEmphasizeBoosterUnlock() return App.showPlay(SDK.PlayModes.Casual, true) else if lastGameType == SDK.GameType.Gauntlet return App.showPlay(SDK.PlayModes.Gauntlet, true) else if lastGameType == SDK.GameType.Challenge and !wasTutorial return App.showPlay(SDK.PlayModes.Challenges, true) else if lastGameType == SDK.GameType.SinglePlayer return App.showPlay(SDK.PlayModes.Practice, true) else if lastGameType == SDK.GameType.BossBattle return App.showPlay(SDK.PlayModes.BossBattle, true) else if lastGameType == SDK.GameType.Sandbox and !wasDeveloper return App.showPlay(SDK.PlayModes.Sandbox, true) else if lastGameType == SDK.GameType.Rift return App.showPlay(SDK.PlayModes.Rift, true) else return App._showMainMenu() ) ).finally () -> App._mainPromise = null return Promise.resolve() return App._mainPromise App._showLoginMenu = (options) -> Logger.module("APPLICATION").log("App:_showLoginMenu") return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, (() -> # analytics call Analytics.page("Login",{ path: "/#login" }) # show main scene viewPromise = Scene.getInstance().showMain() # show login menu contentPromise = NavigationManager.getInstance().showContentView(new LoginMenuItemView(options)) # show utility menu for desktop only if window.isDesktop utilityPromise = NavigationManager.getInstance().showUtilityView(new UtilityLoadingLoginMenuItemView()) else utilityPromise = Promise.resolve() return Promise.all([ viewPromise, contentPromise, utilityPromise ]) ) ) App._showSelectUsername = (data) -> Logger.module("APPLICATION").log("App:_showSelectUsername") return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, (() -> # show main scene viewPromise = Scene.getInstance().showMain() # show selection dialog selectUsernameModel = new Backbone.Model({}) selectUsernameItemView = new SelectUsernameItemView({model: selectUsernameModel}) selectUsernameItemView.listenToOnce(selectUsernameItemView, "success", () => # TODO: move this into SelectUsernameItemView # We refresh token so the username property is now included Session.refreshToken() .then (refreshed) -> return ) contentPromise = NavigationManager.getInstance().showDialogView(selectUsernameItemView) return Promise.all([ NavigationManager.getInstance().destroyModalView(), NavigationManager.getInstance().destroyContentView(), viewPromise, contentPromise ]) ) ) App._showTerms = (options = {}) -> Logger.module("APPLICATION").log("App:_showTerms") return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, (() -> # show main scene viewPromise = Scene.getInstance().showMain() if App.getIsLoggedIn() if window.isSteam ProfileManager.getInstance().set('hasAcceptedSteamEula', true) else ProfileManager.getInstance().set('hasAcceptedEula', true) mainPromise = App.main() else if window.isSteam window.sessionStorage.setItem(Storage.namespace() + '.hasAcceptedSteamEula', true) else window.sessionStorage.setItem(Storage.namespace() + '.hasAcceptedEula', true) mainPromise = App._showLoginMenu({type: 'register'}) return Promise.all([ viewPromise, # contentPromise mainPromise ]) ) ) App._showTutorialLessons = (lastCompletedChallenge) -> Logger.module("APPLICATION").log("App:_showTutorialChallenges") return PackageManager.getInstance().loadAndActivateMajorPackage "nongame", null, null, () -> # analytics call Analytics.page("Tutorial Lessons",{ path: "/#tutorial_lessons" }) # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # show main scene viewPromise = Scene.getInstance().showMain().then(() -> # play main layer music mainLayer = Scene.getInstance().getMainLayer() if mainLayer? then mainLayer.playMusic() ) # show main menu tutorialLessonsLayoutView = new TutorialLessonsLayout({ lastCompletedChallenge:lastCompletedChallenge, }) contentPromise = NavigationManager.getInstance().showContentView(tutorialLessonsLayoutView) return Promise.all([ viewPromise, contentPromise ]) App._showMainMenu = () -> Logger.module("APPLICATION").log("App:_showMainMenu") return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # analytics call Analytics.page("Main Menu",{ path: "/#main_menu" }) # notify Discord status if Discord presence = { instance: 0 details: 'In Main Menu' largeImageKey: 'idle' } Discord.updatePresence(presence) # show main scene viewPromise = Scene.getInstance().showMain().then(() -> # play main layer music mainLayer = Scene.getInstance().getMainLayer() if mainLayer? then mainLayer.playMusic() ) endOfSeasonRewardsPromise = App.showEndOfSeasonRewards() return endOfSeasonRewardsPromise.then( () -> # show achievement rewards achievementsPromise = App.showAchievementCompletions() return achievementsPromise .then(()-> # show twitch rewards twitchRewardPromise = App.showTwitchRewards() return twitchRewardPromise ).then(() -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # show main menu contentPromise = NavigationManager.getInstance().showContentView(new MainMenuItemView({model: ProfileManager.getInstance().profile})) # show utility menu utilityPromise = NavigationManager.getInstance().showUtilityView(new UtilityMainMenuItemView({model: ProfileManager.getInstance().profile})) if NewsManager.getInstance().getFirstUnreadAnnouncement() # show announcment UI if we have an unread announcement modalPromise = NewsManager.getInstance().getFirstUnreadAnnouncementContentAsync().then((announcementContentModel)-> return NavigationManager.getInstance().showModalView(new AnnouncementModalView({model:announcementContentModel})); ) else # show quests if any quests modalPromise = Promise.resolve() if QuestsManager.getInstance().hasUnreadQuests() or QuestsManager.getInstance().hasUnreadDailyChallenges() modalPromise = NavigationManager.getInstance().toggleModalViewByClass(QuestLogLayout,{ collection: QuestsManager.getInstance().getQuestCollection(), model: ProgressionManager.getInstance().gameCounterModel showConfirm:true }) return Promise.all([ viewPromise, contentPromise, modalPromise, utilityPromise ]) ) ) ) # # --- Major Layouts ---- # # App.showPlay = (playModeIdentifier, showingDirectlyFromGame) -> if !App.getIsLoggedIn() return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # force play mode to string if !_.isString(playModeIdentifier) then playModeIdentifier = "" # add mode to route NavigationManager.getInstance().addMajorRoute("play_" + playModeIdentifier, App.showPlay, App, [playModeIdentifier]) # if currently in play modes, show new play mode direct currentContentView = NavigationManager.getInstance().getContentView() if currentContentView instanceof PlayLayout return currentContentView.showPlayMode(playModeIdentifier) else if showingDirectlyFromGame # show play layer viewPromise = Scene.getInstance().showContentByClass(PlayLayer, true) # show achievement rewards achievementsPromise = App.showAchievementCompletions() else achievementsPromise = viewPromise = Promise.resolve() return achievementsPromise.then(() -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # show UI return Promise.all([ viewPromise, NavigationManager.getInstance().showContentView(new PlayLayout({model: new Backbone.Model({playModeIdentifier: playModeIdentifier})})) ]).then ()-> # update available shop specials with current top rank and win count model and notify user if a new one has become available if ShopManager.getInstance().isNewSpecialAvailable ShopManager.getInstance().markNewAvailableSpecialAsRead() NavigationManager.getInstance().showDialogView(new ShopSpecialProductAvailableDialogItemView({ model: ShopManager.getInstance().availableSpecials.at(ShopManager.getInstance().availableSpecials.length-1) })) ) ) App.showWatch = ()-> if !App.getIsLoggedIn() or NavigationManager.getInstance().getContentView() instanceof WatchLayout return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage "nongame", null, null, () -> Analytics.page("Watch",{ path: "/#watch" }) # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # add mode to route NavigationManager.getInstance().addMajorRoute("watch", App.showWatch, App) # show layout return NavigationManager.getInstance().showContentView(new WatchLayout()) App.showShop = ()-> if !App.getIsLoggedIn() return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage "nongame", null, null, () -> Analytics.page("Shop",{ path: "/#shop" }) # add mode to route NavigationManager.getInstance().addMajorRoute("shop", App.showShop, App) # show layout NavigationManager.getInstance().showContentView(new ShopLayout()) App.showCollection = () -> if !App.getIsLoggedIn() or NavigationManager.getInstance().getContentView() instanceof CollectionLayout return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # add mode to route NavigationManager.getInstance().addMajorRoute("collection", App.showCollection, App) # notify Discord status if Discord presence = { instance: 0 details: 'Browsing Collection' largeImageKey: 'PI:KEY:<KEY>END_PI' } Discord.updatePresence(presence) # show UI return Promise.all([ Scene.getInstance().showMain() NavigationManager.getInstance().showContentView(new CollectionLayout({model: new Backbone.Model()})) ]) ) App.showCodex = () -> if !App.getIsLoggedIn() or NavigationManager.getInstance().getContentView() instanceof CodexLayout return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # add mode to route NavigationManager.getInstance().addMajorRoute("codex", App.showCodex, App) # show UI return Promise.all([ Scene.getInstance().showContent(new CodexLayer(), true), NavigationManager.getInstance().showContentView(new CodexLayout({model: new Backbone.Model()})) ]) ) App.showBoosterPackUnlock = () -> if !App.getIsLoggedIn() or NavigationManager.getInstance().getContentView() instanceof BoosterPackUnlockLayout return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # add route NavigationManager.getInstance().addMajorRoute("booster_pack_unlock", App.showBoosterPackUnlock, App) # show UI return Promise.all([ Scene.getInstance().showContent(new BoosterPackOpeningLayer(), true), NavigationManager.getInstance().showContentView(new BoosterPackUnlockLayout()) ]) ) App.showCrateInventory = () -> if !App.getIsLoggedIn() or Scene.getInstance().getOverlay() instanceof CrateOpeningLayer return Promise.reject() else return PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # set status as online ChatManager.getInstance().setStatus(ChatManager.STATUS_ONLINE) # add route NavigationManager.getInstance().addMajorRoute("crate_inventory", App.showCrateInventory, App) # show UI return Promise.all([ NavigationManager.getInstance().destroyContentView(), Scene.getInstance().showOverlay(new CrateOpeningLayer()) ]) ) # # --- Session Events ---- # # App.onLogin = (data) -> Logger.module("APPLICATION").log "User logged in: #{data.userId}" # save token to localStorage Storage.set('token', data.token) # setup ajax headers for jquery/backbone requests $.ajaxSetup headers: { Authorization: "Bearer #{data.token}" "Client-Version": window.BUILD_VERSION } # check is new signup flag is passed # can't use analytics data since the first login may have # already happened on /register page if Landing.isNewSignup() Landing.addPixelsToHead() Landing.firePixels() # check for null username here # dialog should be uncancelleable # dialog success should re-trigger session login so new token contains all required params if !Session.username return App._showSelectUsername(data) # Trigger the eventbus login event for the utilty menus EventBus.getInstance().trigger EVENTS.session_logged_in # connect all managers ProfileManager.getInstance().connect({userId: data.userId}) GameDataManager.getInstance().connect() GamesManager.getInstance().connect() ChatManager.getInstance().connect() QuestsManager.getInstance().connect() InventoryManager.getInstance().connect() NavigationManager.getInstance().connect() NotificationsManager.getInstance().connect() ProgressionManager.getInstance().connect() ServerStatusManager.getInstance().connect() TelemetryManager.getInstance().connect() NewsManager.getInstance().connect() NewPlayerManager.getInstance().connect() AchievementsManager.getInstance().connect() TwitchManager.getInstance().connect() CrateManager.getInstance().connect() ShopManager.getInstance().connect() StreamManager.getInstance().connect() TelemetryManager.getInstance().clearSignal("session","not-logged-in") TelemetryManager.getInstance().setSignal("session","logged-in") Promise.all([ ProfileManager.getInstance().onReady(), InventoryManager.getInstance().onReady(), QuestsManager.getInstance().onReady(), GamesManager.getInstance().onReady(), GameDataManager.getInstance().onReady(), ChatManager.getInstance().onReady(), ProgressionManager.getInstance().onReady(), ServerStatusManager.getInstance().onReady(), NewPlayerManager.getInstance().onReady(), AchievementsManager.getInstance().onReady(), TwitchManager.getInstance().onReady(), CrateManager.getInstance().onReady() ]).then () -> # update resolution values as of login App._updateLastResolutionValues() # we're all done loading managers App.managersReadyDeferred.resolve() # setup analytics App.onLoginAnalyticsSetup(data) # show the main screen return App.main() .catch (err) -> App.managersReadyDeferred.reject() Logger.module("APPLICATION").log("ERROR initializing managers") if err == null then err = new Error("ERROR initializing managers") App._error(err.message) throw err .finally () -> # NavigationManager.getInstance().destroyDialogView() App.onLoginAnalyticsSetup = (loginData) -> # region analytics data # Include users analytics data retrieved with session identifyParams = {} utmParams = {} hadPreviousSession = false if loginData.analyticsData? utmParams = _.extend(utmParams, loginData.analyticsData) if (utmParams.first_purchased_at?) # Shouldn't be necessary but just in case utmParams.first_purchased_at = moment.utc(utmParams.first_purchased_at).toISOString() if loginData.analyticsData.last_session_at delete utmParams.last_session_at hadPreviousSession = true # identify the user with the partial data until we connect managers Analytics.identify(loginData.userId, identifyParams, utmParams) if not hadPreviousSession Analytics.track("first login",{ category:Analytics.EventCategory.FTUE, },{ nonInteraction:1 sendUTMData:true }) Analytics.track("registered", { category:Analytics.EventCategory.Marketing },{ sendUTMData:true nonInteraction:1 }) # endregion analytics data # region analytics data # identify the user with their current rank gamesManager = GamesManager.getInstance() rank = gamesManager.rankingModel.get("rank") # default rank to 30 if it's null rank = 30 if (!rank?) # top rank topRank = gamesManager.topRankingModel.get("top_rank") topRank = gamesManager.topRankingModel.get("rank") if(!topRank?) topRank = 30 if(!topRank?) # game count gameCount = ProgressionManager.getInstance().getGameCount() # set up the params to pass for the identify call identifyParams.rank = rank identifyParams.top_ever_rank = topRank identifyParams.game_count = gameCount # if we know the registration date if ProfileManager.getInstance().get("created_at") # turn it to a sortable registered_at = moment.utc(ProfileManager.getInstance().get("created_at")).toISOString() # set it on the identifyParams identifyParams.registration_date = registered_at # if this user has an LTV parameter if ProfileManager.getInstance().get("ltv") # set it on the identifyParams identifyParams.ltv = ProfileManager.getInstance().get("ltv") # Check if today is a recorded seen on day and add it to identifyParams todaysSeenOnIndex = AnalyticsUtil.recordedDayIndexForRegistrationAndSeenOn(moment.utc(ProfileManager.getInstance().get("created_at")),moment.utc()) if todaysSeenOnIndex? identifyParams[AnalyticsUtil.nameForSeenOnDay(todaysSeenOnIndex)] = 1 # re-identify the user with better data now that we have managers connected and pass in the custom dimensions Analytics.identify(ProfileManager.getInstance().get('id'), identifyParams, utmParams) Analytics.track("login", { category:Analytics.EventCategory.Marketing },{ sendUTMData:true nonInteraction:1 }) # endregion analytics data App.onLogout = () -> Logger.module("APPLICATION").log "User logged out." TelemetryManager.getInstance().clearSignal("session","logged-in") TelemetryManager.getInstance().setSignal("session","not-logged-in") # create a new deferred object for managers loading process App.managersReadyDeferred = new Promise.defer() # destroy out any login specific menus NavigationManager.getInstance().destroyNonContentViews() # stop playing any music audio_engine.current().stop_music() Analytics.reset() # reset config CONFIG.reset() # remove token Storage.remove('token') # remove ajax headers with new call to ajaxSetup $.ajaxSetup headers: { Authorization: "" } # Trigger the eventbus logout event for the ui/managers EventBus.getInstance().trigger EVENTS.session_logged_out # go back to main to show login menu App.main() # just logs the error for debugging App.onSessionError = (error) -> Logger.module("APPLICATION").log "Session Error: #{error.message}" # # ---- Pointer ---- # # App._$canvasMouseClassEl = null App._currentMouseClass = null App.onCanvasMouseState = (e) -> if e?.state? then mouseClass = "mouse-" + e.state.toLowerCase() else mouseClass = "mouse-auto" if App._currentMouseClass != mouseClass App._$canvasMouseClassEl ?= $(CONFIG.GAMECANVAS_SELECTOR) if App._currentMouseClass == "mouse-auto" App._$canvasMouseClassEl.addClass(mouseClass) else if mouseClass == "mouse-auto" App._$canvasMouseClassEl.removeClass(App._currentMouseClass) else App._$canvasMouseClassEl.removeClass(App._currentMouseClass).addClass(mouseClass) App._currentMouseClass = mouseClass App.onPointerDown = (event) -> # update pointer if event? $app = $(CONFIG.APP_SELECTOR) offset = $app.offset() UtilsPointer.setPointerFromDownEvent(event, $app.height(), offset.left, offset.top) # trigger pointer event pointerEvent = UtilsPointer.getPointerEvent() pointerEvent.type = EVENTS.pointer_down pointerEvent.target = event.target EventBus.getInstance().trigger(pointerEvent.type, pointerEvent) # before passing event to view, stop propagation when the target of the pointer event is not the game canvas # however, continue pass the event down to the view and let listeners decide whether to use it if !$(CONFIG.GAMECANVAS_SELECTOR).is(event.target) pointerEvent.stopPropagation() Scene.getInstance().getEventBus().trigger(pointerEvent.type, pointerEvent) return true App.onPointerUp = (event) -> # update pointer if event? $app = $(CONFIG.APP_SELECTOR) offset = $app.offset() UtilsPointer.setPointerFromUpEvent(event, $app.height(), offset.left, offset.top) # trigger pointer event pointerEvent = UtilsPointer.getPointerEvent() pointerEvent.type = EVENTS.pointer_up pointerEvent.target = event.target EventBus.getInstance().trigger(pointerEvent.type, pointerEvent) # before passing event to view, stop propagation when the target of the pointer event is not the game canvas # however, continue pass the event down to the view and let listeners decide whether to use it if !$(CONFIG.GAMECANVAS_SELECTOR).is(event.target) pointerEvent.stopPropagation() Scene.getInstance().getEventBus().trigger(pointerEvent.type, pointerEvent) return true App.onPointerMove = (event) -> # update pointer if event? $app = $(CONFIG.APP_SELECTOR) offset = $app.offset() UtilsPointer.setPointerFromMoveEvent(event, $app.height(), offset.left, offset.top) # trigger pointer events pointerEvent = UtilsPointer.getPointerEvent() pointerEvent.type = EVENTS.pointer_move pointerEvent.target = event.target EventBus.getInstance().trigger(pointerEvent.type, pointerEvent) # before passing event to view, stop propagation when the target of the pointer event is not the game canvas # however, continue pass the event down to the view and let listeners decide whether to use it if !$(CONFIG.GAMECANVAS_SELECTOR).is(event.target) pointerEvent.stopPropagation() Scene.getInstance().getEventBus().trigger(pointerEvent.type, pointerEvent) return true App.onPointerWheel = (event) -> # update pointer if event? target = event.target $app = $(CONFIG.APP_SELECTOR) offset = $app.offset() UtilsPointer.setPointerFromWheelEvent(event.originalEvent, $app.height(), offset.left, offset.top) # trigger pointer events pointerEvent = UtilsPointer.getPointerEvent() pointerEvent.type = EVENTS.pointer_wheel pointerEvent.target = target EventBus.getInstance().trigger(pointerEvent.type, pointerEvent) # before passing event to view, stop propagation when the target of the pointer event is not the game canvas # however, continue pass the event down to the view and let listeners decide whether to use it if !$(CONFIG.GAMECANVAS_SELECTOR).is(target) pointerEvent.stopPropagation() Scene.getInstance().getEventBus().trigger(pointerEvent.type, pointerEvent) return true # # --- Game Invites ---- # # App._inviteAccepted = ()-> Logger.module("APPLICATION").log("App._inviteAccepted") App.showPlay(SDK.PlayModes.Friend) App._inviteRejected = () -> Logger.module("APPLICATION").log("App._inviteRejected") return App.main().then(() -> return NavigationManager.getInstance().showDialogView(new PromptDialogItemView({title: i18next.t("buddy_list.message_rejected_game_invite")})) ) App._inviteCancelled = () -> App._cleanupMatchmakingListeners() Logger.module("APPLICATION").log("App._inviteCancelled") return App.main().then(() -> return NavigationManager.getInstance().showDialogView(new PromptDialogItemView({title: i18next.t("buddy_list.message_cancelled_game_invite")})) ) # # --- Game Spectate ---- # # App._spectateGame = (e) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._spectateGame -> cannot start game when already in a game!") return gameListingData = e.gameData playerId = e.playerId spectateToken = e.token Logger.module("APPLICATION").log("App._spectateGame", gameListingData) NavigationManager.getInstance().showDialogForLoad() .then ()-> # load resources for game return PackageManager.getInstance().loadGamePackageWithoutActivation([ gameListingData["faction_id"], gameListingData["opponent_faction_id"] ]) .then () -> # listen to join game events joinGamePromise = App._subscribeToJoinGameEventsPromise() # join game and if a game server is assigned to this listing, connect there SDK.NetworkManager.getInstance().connect(gameListingData["game_id"], playerId, gameListingData["game_server"], ProfileManager.getInstance().get('id'), spectateToken) return joinGamePromise.then((gameSessionData) -> # reset and deserialize SDK.GameSession.reset() SDK.GameSession.getInstance().deserializeSessionFromFirebase(gameSessionData) SDK.GameSession.getInstance().setUserId(playerId) SDK.GameSession.getInstance().setIsSpectateMode(true) # do not start games that are already over if !SDK.GameSession.getInstance().isOver() return App._startGame() else return Promise.reject() ).catch((errorMessage) -> return App._error(errorMessage) ) # See games_manager spectateBuddyGame method, works same way App.spectateBuddyGame = (buddyId) -> return new Promise (resolve, reject) -> request = $.ajax({ url: process.env.API_URL + '/api/me/spectate/' + buddyId, type: 'GET', contentType: 'application/json', dataType: 'json' }) request.done (response) -> App._spectateGame({ gameData: response.gameData, token: response.token, playerId: buddyId }) resolve(response) request.fail (response) -> error = response && response.responseJSON && response.responseJSON.error || 'SPECTATE request failed' EventBus.getInstance().trigger(EVENTS.ajax_error, error) reject(new Error(error)) # Event handler fired when spectate is pressed in Discord with spectateSecret passed in # We use the buddyId as the spectateSecret App.onDiscordSpectate = (args...) -> buddyId = args[0] Logger.module("DISCORD").log("attempting to spectate #{buddyId}") # we wait until managers are loaded as we need to be logged in return App.managersReadyDeferred.promise.then () -> # do nothing if they are already in game or in queue if ChatManager.getInstance().getStatusIsInBattle() || ChatManager.getInstance().getStatusQueue() Logger.module("DISCORD").log("cannot spectate game when already in a game!") return # do nothing if they are attempting to spectate theirselves if ProfileManager.getInstance().get('id') == buddyId Logger.module("DISCORD").log("cannot spectate yourself!") return # fire spectate request return App.main().then () -> App.spectateBuddyGame(buddyId) # # --- Game Matchmaking ---- # # App._error = (errorMessage) -> Logger.module("APPLICATION").log("App._error", errorMessage) # always unlock user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationUnlocked(App._userNavLockId) if errorMessage? # if we're in the process of loading the main menu # show the error dialog and don't go to main menu # to avoid infinite loop of loading main menu if App._mainPromise or process.env.NODE_ENV == "local" return NavigationManager.getInstance().showDialogView(new ErrorDialogItemView({message:errorMessage})) else # otherwise load the main menu and show the error dialog return App.main().then () -> return NavigationManager.getInstance().showDialogView(new ErrorDialogItemView({message:errorMessage})) else return App.main() App._cleanupMatchmakingListeners = ()-> # remove all found game listeners as new ones will be registered when we re-enter matchmaking GamesManager.getInstance().off("found_game") # force reject the existing found game promise when we cancel # this is important because this promise is wrapped around the "found_game" event and a chain of stuff is waiting for it to resolve! # if we don't cancel here, we will have a promise that never resolves and thus leaks memory if App._foundGamePromise? App._foundGamePromise.cancel() App._matchmakingStart = () -> Logger.module("APPLICATION").log("App._matchmakingStart") App._matchmakingCancel = () -> Logger.module("APPLICATION").log("App._matchmakingCancel") App._cleanupMatchmakingListeners() App._matchmakingError = (errorMessage) -> Logger.module("APPLICATION").log("App._matchmakingError", errorMessage) App._cleanupMatchmakingListeners() return App._error(errorMessage) App._playerDataFromGameListingData = (gameListingData) -> myPlayerIsPlayer1 = gameListingData.is_player_1 playerDataModel= new Backbone.Model({ myPlayerIsPlayer1: myPlayerIsPlayer1 myPlayerId: ProfileManager.getInstance().get('id') myPlayerUsername: ProfileManager.getInstance().get("username") myPlayerFactionId: gameListingData.faction_id myPlayerGeneralId: gameListingData.general_id opponentPlayerId: gameListingData.opponent_id opponentPlayerUsername: gameListingData.opponent_username opponentPlayerFactionId: gameListingData.opponent_faction_id opponentPlayerGeneralId: gameListingData.opponent_general_id }) if myPlayerIsPlayer1 playerDataModel.set({ player1Id: playerDataModel.get("myPlayerId"), player1Username: playerDataModel.get("myPlayerUsername"), player1FactionId: playerDataModel.get("myPlayerFactionId"), player1GeneralId: playerDataModel.get("myPlayerGeneralId"), player2Id: playerDataModel.get("opponentPlayerId"), player2Username: playerDataModel.get("opponentPlayerUsername"), player2FactionId: playerDataModel.get("opponentPlayerFactionId"), player2GeneralId: playerDataModel.get("opponentPlayerGeneralId") }) else playerDataModel.set({ player1Id: playerDataModel.get("opponentPlayerId"), player1Username: playerDataModel.get("opponentPlayerUsername"), player1FactionId: playerDataModel.get("opponentPlayerFactionId"), player1GeneralId: playerDataModel.get("opponentPlayerGeneralId"), player2Id: playerDataModel.get("myPlayerId"), player2Username: playerDataModel.get("myPlayerUsername"), player2FactionId: playerDataModel.get("myPlayerFactionId"), player2GeneralId: playerDataModel.get("myPlayerGeneralId") }) return playerDataModel App._findingGame = (gameMatchRequestData) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._findingGame -> cannot start game when already in a game!") return Logger.module("APPLICATION").log("App._findingGame", gameMatchRequestData) # analytics call Analytics.page("Finding Game",{ path: "/#finding_game" }) # notify Discord status if Discord presence = { instance: 0 largeImageKey: 'idle' } if gameMatchRequestData.gameType == 'ranked' presence.details = 'In Ranked Queue' else if gameMatchRequestData.gameType == 'gauntlet' presence.details = 'In Gauntlet Queue' else if gameMatchRequestData.gameType == 'rift' presence.details = 'In Rift Queue' else presence.details = 'In Queue' Discord.updatePresence(presence) # set the chat presence status to in-queue so your buddies see that you're unreachable ChatManager.getInstance().setStatus(ChatManager.STATUS_QUEUE) # add route NavigationManager.getInstance().addMajorRoute("finding_game", App._findingGame, App, [gameMatchRequestData]) # initialize finding game view findingGameItemView = new FindingGameItemView({model: new Backbone.Model({gameType: gameMatchRequestData.gameType, factionId: gameMatchRequestData.factionId, generalId: gameMatchRequestData.generalId})}) # initialize found game promise gameListingData = null # load find game assets and show finding game showFindingGamePromise = PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> return Promise.all([ Scene.getInstance().showContentByClass(PlayLayer, true), Scene.getInstance().showFindingGame(gameMatchRequestData.factionId, gameMatchRequestData.generalId), NavigationManager.getInstance().showContentView(findingGameItemView), NavigationManager.getInstance().showUtilityView(new UtilityMatchmakingMenuItemView({model: ProfileManager.getInstance().profile})) ]) ) # load my game assets as soon as possible loadGamePromise = showFindingGamePromise.then () -> Logger.module("APPLICATION").log("App._findingGame -> showFindingGamePromise DONE") return PackageManager.getInstance().loadGamePackageWithoutActivation([gameMatchRequestData.factionId]) # save this promise to app object so it can be cancelled in the event of "cancelMatchmaking" # this is important because this promise is wrapped around the "found_game" event and a chain of stuff is waiting for it to resolve! # if we don't cancel this later, we will have a promise that never resolves and thus leaks memory App._foundGamePromise = new Promise((resolve, reject) -> # listen for next found game onFoundGame = (foundGameListingData) -> Logger.module("APPLICATION").log("App._findingGame -> onFoundGame()", foundGameListingData) # stop listening GamesManager.getInstance().off("found_game", onFoundGame) # store found data gameListingData = foundGameListingData showFindingGamePromise.then () -> # don't allow user triggered navigation now that we've found a game NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) NavigationManager.getInstance().destroyNonContentViews() Logger.module("APPLICATION").log("App._findingGame -> onFoundGame() App._foundGamePromise RESOLVED") resolve(foundGameListingData) GamesManager.getInstance().once("found_game", onFoundGame) ).cancellable() # wait show finding game and found game, then join found game return Promise.all([ showFindingGamePromise, App._foundGamePromise ]).then(() -> Logger.module("APPLICATION").log("App._findingGame -> show found game", gameListingData) # analytics call Analytics.page("Found Game",{ path: "/#found_game" }) # get found game data from game listing data playerDataModel = App._playerDataFromGameListingData(gameListingData) # show found game return Promise.all([ Scene.getInstance().showVsForGame(playerDataModel.get("myPlayerFactionId"), playerDataModel.get("opponentPlayerFactionId"), playerDataModel.get("myPlayerIsPlayer1"), CONFIG.ANIMATE_MEDIUM_DURATION, playerDataModel.get("myPlayerGeneralId"), playerDataModel.get("opponentPlayerGeneralId")), Scene.getInstance().showNewGame(playerDataModel.get("player1GeneralId"), playerDataModel.get("player2GeneralId")), findingGameItemView.showFoundGame(playerDataModel) ]).then(() -> # join found game return App._joinGame(gameListingData, loadGamePromise) ) ).catch Promise.CancellationError, (e)-> Logger.module("APPLICATION").log("App._findingGame -> promise chain cancelled") App._resumeGame = (lastGameModel) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._resumeGame -> cannot start game when already in a game!") return gameListingData = lastGameModel?.attributes Logger.module("APPLICATION").log("App._resumeGame", gameListingData) # analytics call Analytics.page("Resume Game",{ path: "/#resume_game" }) # set status to in game ChatManager.getInstance().setStatus(ChatManager.STATUS_GAME) # get resume game data from game listing data playerDataModel= App._playerDataFromGameListingData(gameListingData) # playerDataModel.set("gameModel", lastGameModel) # initialize resume ui gameResumeItemView = new ResumeGameItemView({model: playerDataModel}) # initialize continue promise continueGamePromise = new Promise((resolve, reject) -> onContinueGame = () -> stopListeningForContinueGame() # don't allow user triggered navigation now that user has decided to continue NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) NavigationManager.getInstance().destroyNonContentViews() resolve() onCancelContinueGame = (errorMessage) -> stopListeningForContinueGame() # don't try to reconnect to this game again lastGameModel.set("cancel_reconnect",true) reject(errorMessage) stopListeningForContinueGame = () -> gameResumeItemView.stopListening(gameResumeItemView, "continue", onContinueGame) gameResumeItemView.stopListening(lastGameModel, "change") gameResumeItemView.stopListening(NavigationManager.getInstance(), "user_triggered_cancel", onContinueGame) # listen for continue gameResumeItemView.listenToOnce(gameResumeItemView, "continue", onContinueGame) # listen for game over gameResumeItemView.listenTo(lastGameModel, "change", () -> if lastGameModel.get("status") == "over" then onCancelContinueGame("Oops... looks like that game is over!") ) # listen for cancel gameResumeItemView.listenTo(NavigationManager.getInstance(), EVENTS.user_triggered_cancel, () -> if !NavigationManager.getInstance().getIsShowingModalView() then onCancelContinueGame() ) ) # load assets loadAndShowResumeGamePromise = PackageManager.getInstance().loadAndActivateMajorPackage("nongame", null, null, () -> # show UI return Promise.all([ Scene.getInstance().showContentByClass(PlayLayer, true), Scene.getInstance().showVsForGame(playerDataModel.get("myPlayerFactionId"), playerDataModel.get("opponentPlayerFactionId"), playerDataModel.get("myPlayerIsPlayer1"), CONFIG.ANIMATE_MEDIUM_DURATION, playerDataModel.get("myPlayerGeneralId"), playerDataModel.get("opponentPlayerGeneralId")), NavigationManager.getInstance().showContentView(gameResumeItemView), NavigationManager.getInstance().showUtilityView(new UtilityMatchmakingMenuItemView({model: ProfileManager.getInstance().profile})) ]) ) # wait for load, show resume game, and click continue, then join in progress game Promise.all([ loadAndShowResumeGamePromise, continueGamePromise ]).then(() -> Logger.module("APPLICATION").log("App._resumeGame -> joining game") # join found game return App._joinGame(gameListingData) ).catch((errorMessage) -> return App._error(errorMessage) ) # only return show promise return loadAndShowResumeGamePromise # # --- Single Player ---- # # App._startSinglePlayerGame = (myPlayerDeck, myPlayerFactionId, myPlayerGeneralId, myPlayerCardBackId, myPlayerBattleMapId, aiGeneralId, aiDifficulty, aiNumRandomCards) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._startSinglePlayerGame -> cannot start game when already in a game!") return Logger.module("APPLICATION").log("App._startSinglePlayerGame") # analytics call Analytics.page("Single Player Game",{ path: "/#single_player" }) # set status to in game ChatManager.getInstance().setStatus(ChatManager.STATUS_GAME) aiGeneralName = null aiGeneralCard = SDK.GameSession.getCardCaches().getCardById(aiGeneralId) if (aiGeneralCard?) aiGeneralName = aiGeneralCard.getName() # request single player game App._singlePlayerGamePromise = new Promise((resolve, reject) -> request = $.ajax url: process.env.API_URL + '/api/me/games/single_player', data: JSON.stringify({ deck: myPlayerDeck, cardBackId: myPlayerCardBackId, battleMapId: myPlayerBattleMapId, hasPremiumBattleMaps: InventoryManager.getInstance().hasAnyBattleMapCosmetics(), ai_general_id: aiGeneralId, ai_difficulty: aiDifficulty, ai_num_random_cards: aiNumRandomCards, ai_username: aiGeneralName }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve(res) request.fail (jqXHR)-> reject(jqXHR and jqXHR.responseJSON and (jqXHR.responseJSON.error or jqXHR.responseJSON.message) or "Connection error. Please retry.") ).cancellable() # init finding game view findingGameItemView = new FindingGameItemView({model: new Backbone.Model({gameType: SDK.GameType.SinglePlayer})}) findingGameItemView.listenTo(findingGameItemView, "destroy", App._cancelSinglePlayer) # show ui return Promise.all([ Scene.getInstance().showContentByClass(PlayLayer, true), Scene.getInstance().showFindingGame(myPlayerFactionId, myPlayerGeneralId), NavigationManager.getInstance().showContentView(findingGameItemView), NavigationManager.getInstance().showUtilityView(new UtilityMatchmakingMenuItemView({model: ProfileManager.getInstance().profile})) ]).then(() -> # when we have single player game data return App._singlePlayerGamePromise?.then((gameListingData) -> App._singlePlayerGamePromise = null # don't allow user triggered navigation now that we've found a game NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) # get found game data from game listing data playerDataModel = App._playerDataFromGameListingData(gameListingData) # show found game return Promise.all([ Scene.getInstance().showVsForGame(playerDataModel.get("myPlayerFactionId"), playerDataModel.get("opponentPlayerFactionId"), playerDataModel.get("myPlayerIsPlayer1"), CONFIG.ANIMATE_MEDIUM_DURATION, playerDataModel.get("myPlayerGeneralId"), playerDataModel.get("opponentPlayerGeneralId")), Scene.getInstance().showNewGame(playerDataModel.get("player1GeneralId"), playerDataModel.get("player2GeneralId")), NavigationManager.getInstance().destroyNonContentViews(), findingGameItemView.showFoundGame(playerDataModel) ]).then(() -> # join found game return App._joinGame(gameListingData) ) ) ).catch(Promise.CancellationError, (e)-> Logger.module("APPLICATION").log("App:_startSinglePlayerGame -> promise chain cancelled") ).catch((errorMessage) -> return App._error(if errorMessage? then "Failed to start single player game: " + errorMessage) ) App._cancelSinglePlayer = () -> if App._singlePlayerGamePromise? App._singlePlayerGamePromise.cancel() App._singlePlayerGamePromise = null App._startBossBattleGame = (myPlayerDeck, myPlayerFactionId, myPlayerGeneralId, myPlayerCardBackId, myPlayerBattleMapId, aiGeneralId) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._startBossBattleGame -> cannot start game when already in a game!") return Logger.module("APPLICATION").log("App._startBossBattleGame") # analytics call Analytics.page("Boss Battle Game",{ path: "/#boss_battle" }) # don't allow user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) # set user as in game ChatManager.getInstance().setStatus(ChatManager.STATUS_GAME) aiGeneralName = null aiGeneralCard = SDK.GameSession.getCardCaches().getCardById(aiGeneralId) if (aiGeneralCard?) aiGeneralName = aiGeneralCard.getName() # request boss battle game bossBattleGamePromise = new Promise((resolve, reject) -> request = $.ajax url: process.env.API_URL + '/api/me/games/boss_battle', data: JSON.stringify({ deck: myPlayerDeck, cardBackId: myPlayerCardBackId, battleMapId: myPlayerBattleMapId, ai_general_id: aiGeneralId, ai_username: aiGeneralName }), type: 'POST', contentType: 'application/json', dataType: 'json' request.done (res)-> resolve(res) request.fail (jqXHR)-> reject(jqXHR and jqXHR.responseJSON and (jqXHR.responseJSON.error or jqXHR.responseJSON.message) or "Connection error. Please retry.") ) # get ui promise if CONFIG.LOAD_ALL_AT_START ui_promise = Promise.resolve() else ui_promise = NavigationManager.getInstance().showDialogForLoad() return Promise.all([ bossBattleGamePromise, ui_promise ]).spread (gameListingData) -> return App._joinGame(gameListingData) .catch (errorMessage) -> return App._error(if errorMessage? then "Failed to start boss battle: " + errorMessage) # # --- Replays ---- # # App._startGameForReplay = (replayData) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._startGameForReplay -> cannot start game when already in a game!") return userId = replayData.userId gameId = replayData.gameId replayId = replayData.replayId promotedDivisionName = replayData.promotedDivisionName # check for invalid replay data if !replayId? if !gameId? throw new Error("Cannot replay game without game id!") if !userId? and !promotedDivisionName? throw new Error("Cannot replay game without user id or division name!") # don't allow user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) # show loading return NavigationManager.getInstance().showDialogForLoad() .bind {} .then () -> # load replay data if replayId? url = "#{process.env.API_URL}/replays/#{replayId}" else if promotedDivisionName? url = "#{process.env.API_URL}/api/me/games/watchable/#{promotedDivisionName}/#{gameId}/replay_data?playerId=#{userId}" else url = "#{process.env.API_URL}/api/users/#{userId}/games/#{gameId}/replay_data" return new Promise (resolve, reject) -> request = $.ajax({ url: url , type: 'GET', contentType: 'application/json', dataType: 'json' }) request.done (response)-> resolve(response) .fail (response)-> reject(new Error("Error downloading replay data: #{response?.responseJSON?.message}")) .then (replayResponseData) -> @.replayResponseData = replayResponseData gameSessionData = replayResponseData.gameSessionData gameUIData = replayResponseData.mouseUIData replayData = replayResponseData.replayData # validate data gameSetupData = gameSessionData?.gameSetupData if !gameSetupData? throw new Error("ReplayEngine -> loaded game does not have valid replay data!") # store data @_loadedGameSessionData = gameSessionData @_loadedGameUIEventData = gameUIData # load resources for game return PackageManager.getInstance().loadGamePackageWithoutActivation([ gameSetupData.players[0].factionId gameSetupData.players[1].factionId ]) .then () -> # create new game instance but don't deserialize from existing data SDK.GameSession.reset() if userId? # if we explicity requested to spectate a user perspective SDK.GameSession.getInstance().setUserId(userId) else if @.replayResponseData?.replayData # check if the server response includes a shared replay record so we can use that to determine who to spectate SDK.GameSession.getInstance().setUserId(@.replayResponseData?.replayData.user_id) else # ultimately spectate player 1 if nothing provided SDK.GameSession.getInstance().setUserId(@_loadedGameSessionData.players[0].playerId) SDK.GameSession.getInstance().setGameType(@_loadedGameSessionData.gameType) SDK.GameSession.getInstance().setIsRunningAsAuthoritative(false) SDK.GameSession.getInstance().setIsSpectateMode(true) SDK.GameSession.getInstance().setIsReplay(true) # setup GameSession from replay data SDK.GameSetup.setupNewSessionFromExistingSessionData(SDK.GameSession.getInstance(), @_loadedGameSessionData) return App._startGame() .then () -> # start watching replay ReplayEngine.getInstance().watchReplay(@_loadedGameSessionData, @_loadedGameUIEventData) .catch (errorMessage) -> ReplayEngine.getInstance().stopCurrentReplay() return App._error(errorMessage) # # --- Game Connecting ---- # # App._unsubscribeFromJoinGameEvents = () -> SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.join_game) SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.reconnect_failed) App._subscribeToJoinGameEventsPromise = () -> App._unsubscribeFromJoinGameEvents() return new Promise((resolve, reject) -> # wait for join_game event SDK.NetworkManager.getInstance().getEventBus().once(EVENTS.join_game, (response) -> # handle response if response.error reject(response.error) else resolve(response.gameSessionData) ) SDK.NetworkManager.getInstance().getEventBus().once(EVENTS.spectate_game, (response) -> # handle response if response.error reject(response.error) else resolve(response.gameSessionData) ) # wait for reconnect_failed event SDK.NetworkManager.getInstance().getEventBus().once(EVENTS.reconnect_failed, () -> # reject and cancel reconnect reject("Reconnect failed!") ) ).finally(() -> # reset join game listeners App._unsubscribeFromJoinGameEvents() ) App._joinGame = (gameListingData, loadMyGameResourcesPromise, loadOpponentGameResourcesPromise) -> Logger.module("APPLICATION").log("App._joinGame", gameListingData) # load my resources for game loadMyGameResourcesPromise ?= PackageManager.getInstance().loadGamePackageWithoutActivation([gameListingData["faction_id"]]) # load opponent resources for game loadOpponentGameResourcesPromise ?= PackageManager.getInstance().loadMinorPackage(PKGS.getFactionGamePkgIdentifier(gameListingData["opponent_faction_id"]), null, "game") return Promise.all([ loadMyGameResourcesPromise, loadOpponentGameResourcesPromise ]).then(() -> # listen to join game events joinGamePromise = App._subscribeToJoinGameEventsPromise() # join game and if a game server is assigned to this listing, connect there SDK.NetworkManager.getInstance().connect(gameListingData["game_id"], ProfileManager.getInstance().get('id'), gameListingData["game_server"]) return joinGamePromise.then((gameSessionData) -> return App._startGameWithData(gameSessionData) ).catch((errorMessage) -> return App._error(errorMessage) ) ) App._onReconnectToGame = (gameId) -> Logger.module("APPLICATION").log("App._onReconnectToGame", gameId) # destroy the current game App.cleanupGame() # start listening to join game events joinGamePromise = App._subscribeToJoinGameEventsPromise() # blur the view in engine Scene.getInstance().getFX().requestBlurScreen(App._screenBlurId) return Promise.all([ # show user we're reconnecting NavigationManager.getInstance().showContentView(new ReconnectToGameItemView()), NavigationManager.getInstance().showUtilityView(new UtilityMatchmakingMenuItemView({model: ProfileManager.getInstance().profile})) ]).then(() -> return joinGamePromise.then((gameSessionData) -> # start game return App._startGameWithData(gameSessionData) ).catch((errorMessage) -> return App._error(errorMessage) ).finally(() -> App.cleanupReconnectToGame() ) ) App.cleanupReconnectToGame = () -> # unsubscribe from events App._unsubscribeFromJoinGameEvents() # unblur screen Scene.getInstance().getFX().requestUnblurScreen(App._screenBlurId) # # --- Game Events ---- # # App._onNetworkGameEvent = (eventData) -> if (eventData.type == EVENTS.step) Logger.module("APPLICATION").log("App._onNetworkGameEvent -> step", eventData) # step event if eventData.step? # deserialize step sdkStep = SDK.GameSession.getInstance().deserializeStepFromFirebase(eventData.step) # if we are spectating, and connected in the middle of a followup (so we don't have a snapshot), error out to main menu in the event of a rollback since we have nothing to roll back to if (SDK.GameSession.getInstance().getIsSpectateMode() and sdkStep.getAction() instanceof SDK.RollbackToSnapshotAction and !SDK.GameSession.getInstance().getRollbackSnapshotData()) return App._error("You fell out of sync. Please try to spectate again to sync up.") # mark step as transmitted sdkStep.setTransmitted(true) # execute step SDK.GameSession.getInstance().executeAuthoritativeStep(sdkStep) if sdkStep.getAction() AnalyticsTracker.sendAnalyticsForExplicitAction(sdkStep.getAction()) else if (eventData.type == EVENTS.invalid_action) if eventData.playerId == SDK.GameSession.getInstance().getMyPlayerId() if eventData.desync # player is out of sync with server # force them to reconnect to game Analytics.track("player desync", {category:Analytics.EventCategory.Debug}, {nonInteraction:1}) App._error("Your current match appears to be out of sync. To avoid any issues, please select CONTINUE and reconnect to your match.") else # player isn't out of sync but may need to know their action was invalid # this may happen if a player attempts to submit actions after their turn is over SDK.GameSession.getInstance().onAuthoritativeInvalidAction(eventData) else if (eventData.type == EVENTS.network_game_hover) Scene.getInstance().getGameLayer()?.onNetworkHover(eventData) else if (eventData.type == EVENTS.network_game_select) Scene.getInstance().getGameLayer()?.onNetworkSelect(eventData) else if (eventData.type == EVENTS.network_game_mouse_clear) Scene.getInstance().getGameLayer()?.onNetworkMouseClear(eventData) else if (eventData.type == EVENTS.turn_time) # if we are behind in step count for some reason from the server step counter if (!SDK.GameSession.getInstance().getIsSpectateMode() and eventData.stepCount > SDK.GameSession.getInstance().getStepCount()) # we're going to start a pseudo-timeout to reload the game Logger.module("APPLICATION").warn("App._onNetworkGameEvent -> seems like game session is behind server step count") # if we haven't already detected a potential desync state and recorded the moment it started if not App._gameDesyncStartedAt # record the moment the suspected desync started App._gameDesyncStartedAt = moment.utc() # otherwise if we suspect a desync state is already in progress and we have the time it started, see if it's been more than 10s else if moment.duration(moment.utc() - App._gameDesyncStartedAt).asSeconds() > 10.0 # if it's been more than 10s in a desync state, fire off the error state App._error("Your current match appears to be out of sync. To avoid any issues, please select CONTINUE and reconnect to your match.") App._gameDesyncStartedAt = null return else # if we're up to date with our step count, just clear out any suspected desync starting point App._gameDesyncStartedAt = null # the game session emits events from here that inform UI etc. SDK.GameSession.getInstance().setTurnTimeRemaining(eventData.time) else if (eventData.type == EVENTS.show_emote) EventBus.getInstance().trigger(EVENTS.show_emote, eventData) App._onOpponentConnectionStatusChanged = (eventData) -> # when opponent disconnects, force mouse clear if !SDK.NetworkManager.getInstance().isOpponentConnected Scene.getInstance().getGameLayer()?.onNetworkMouseClear({type:EVENTS.network_game_mouse_clear, timestamp: Date.now()}) App._onNetworkGameError = (errorData) -> return App._error(JSON.stringify(errorData)) App._onGameServerShutdown = (errorData) -> if errorData.ip ip = errorData.ip lastGameModel = GamesManager.getInstance().playerGames.first() lastGameModel.set('gameServer',ip) # reconnect SDK.NetworkManager.getInstance().reconnect(ip) # show reconnecting return App._onReconnectToGame() else return App._error("Game server error, no ip!") # # --- Game Setup ---- # # App._startGameWithChallenge = (challenge) -> if ChatManager.getInstance().getStatusIsInBattle() Logger.module("APPLICATION").log("App._startGameWithChallenge -> cannot start game when already in a game!") return Logger.module("APPLICATION").log("App:_startGameWithChallenge") # don't allow user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationLocked(App._userNavLockId) # set user as in game ChatManager.getInstance().setStatus(ChatManager.STATUS_CHALLENGE) if not challenge instanceof SDK.ChallengeRemote # mark challenge as attempted ProgressionManager.getInstance().markChallengeAsAttemptedWithType(challenge.type); # challenge handles setting up game session SDK.GameSession.reset() SDK.GameSession.getInstance().setUserId(ProfileManager.getInstance().get('id')) challenge.setupSession(SDK.GameSession.getInstance()) # get ui promise if CONFIG.LOAD_ALL_AT_START ui_promise = Promise.resolve() else ui_promise = NavigationManager.getInstance().showDialogForLoad() return ui_promise.then () -> return PackageManager.getInstance().loadGamePackageWithoutActivation([ SDK.GameSession.getInstance().getGeneralForPlayer1().getFactionId(), SDK.GameSession.getInstance().getGeneralForPlayer2().getFactionId() ], [ "tutorial", PKGS.getChallengePkgIdentifier(SDK.GameSession.getInstance().getChallenge().getType()) ]) .then () -> return App._startGame() .catch (errorMessage) -> return App._error(errorMessage) App._startGameWithData = (sessionData) -> Logger.module("APPLICATION").log("App._startGameWithData", sessionData) # reset and deserialize SDK.GameSession.reset() SDK.GameSession.getInstance().deserializeSessionFromFirebase(sessionData) SDK.GameSession.getInstance().setUserId(ProfileManager.getInstance().get('id')) # do not start games that are already over if !SDK.GameSession.getInstance().isOver() return App._startGame() else return Promise.reject() App._startGame = () -> gameSession = SDK.GameSession.getInstance() Logger.module("APPLICATION").log("App:_startGame", gameSession.getStatus()) if gameSession.getIsSpectateMode() ChatManager.getInstance().setStatus(ChatManager.STATUS_WATCHING) else if gameSession.isChallenge() ChatManager.getInstance().setStatus(ChatManager.STATUS_CHALLENGE) else ChatManager.getInstance().setStatus(ChatManager.STATUS_GAME) NotificationsManager.getInstance().dismissNotificationsThatCantBeShown() if Discord getFactionImage = (factionId, opponent = false) -> s = {key: '', text: ''} switch factionId when 1 then s = {key: 'f1', text: 'Lyonar'} when 2 then s = {key: 'f2', text: 'Songhai'} when 3 then s = {key: 'f3', text: 'Vetruvian'} when 4 then s = {key: 'f4', text: 'Abyssian'} when 5 then s = {key: 'f5', text: 'Magmar'} when 6 then s = {key: 'f6', text: 'Vanar'} else s = {key: 'neutral', text: 'Neutral'} if opponent s.key += '_small' return s opponentName = SDK.GameSession.getInstance().getOpponentPlayer().getUsername() opponentFaction = SDK.GameSession.getInstance().getGeneralForPlayer(SDK.GameSession.getInstance().getOpponentPlayer()).factionId opponentFactionImage = getFactionImage(opponentFaction, true) playerName = SDK.GameSession.getInstance().getMyPlayer().getUsername() playerId = SDK.GameSession.getInstance().getMyPlayerId() playerRank = GamesManager.getInstance().getCurrentRank() playerFaction = SDK.GameSession.getInstance().getGeneralForPlayer(SDK.GameSession.getInstance().getMyPlayer()).factionId playerFactionImage = getFactionImage(playerFaction, false) presence = { startTimestamp: Math.floor((new Date).getTime()/1000), instance: 1 largeImageKey: playerFactionImage.key largeImageText: playerFactionImage.text smallImageKey: opponentFactionImage.key smallImageText: opponentFactionImage.text } if gameSession.getIsSpectateMode() if gameSession.getIsReplay() presence.details = "Watching: #{playerName} vs. #{opponentName} replay" presence.state = "Spectating" else presence.details = "Watching: #{playerName} vs. #{opponentName} live" presence.state = "Spectating" else if gameSession.isRanked() presence.details = "Ranked: vs. #{opponentName}" presence.state = "In Match" # check if block is enabled before allowing spectate if !ProfileManager.getInstance().profile.get("blockSpectators") presence.spectateSecret = playerId else if gameSession.isGauntlet() presence.details = "Gauntlet: vs. #{opponentName}" presence.state = "In Match" # check if block is enabled before allowing spectate if !ProfileManager.getInstance().profile.get("blockSpectators") presence.spectateSecret = playerId else if gameSession.isRift() presence.details = "Rift: vs. #{opponentName}" presence.state = "In Match" # check if block is enabled before allowing spectate if !ProfileManager.getInstance().profile.get("blockSpectators") presence.spectateSecret = playerId else if gameSession.isFriendly() presence.details = "Friendly: vs. #{opponentName}" presence.state = "In Game" # check if block is enabled before allowing spectate if !ProfileManager.getInstance().profile.get("blockSpectators") presence.spectateSecret = playerId else if gameSession.isBossBattle() presence.details = "Boss Battle: vs. #{opponentName}" presence.state = "Playing Solo" else if gameSession.isSinglePlayer() || gameSession.isSandbox() || gameSession.isChallenge() presence.state = "Playing Solo" Discord.updatePresence(presence) # analytics call Analytics.page("Game",{ path: "/#game" }) # reset routes as soon as we lock into a game NavigationManager.getInstance().resetRoutes() # record last game data CONFIG.resetLastGameData() CONFIG.lastGameType = gameSession.getGameType() CONFIG.lastGameWasSpectate = gameSession.getIsSpectateMode() CONFIG.lastGameWasTutorial = gameSession.isTutorial() CONFIG.lastGameWasDeveloper = UtilsEnv.getIsInDevelopment() && gameSession.getIsDeveloperMode() CONFIG.lastGameWasDailyChallenge = gameSession.isDailyChallenge() # listen to game network events App._subscribeToGameNetworkEvents() # get game UI view class challenge = gameSession.getChallenge() if challenge? and !(challenge instanceof SDK.Sandbox) gameUIViewClass = TutorialLayout else gameUIViewClass = GameLayout # load resources for game session load_promises = [ # load battlemap assets required for game PackageManager.getInstance().loadMinorPackage(PKGS.getBattleMapPkgIdentifier(gameSession.getBattleMapTemplate().getMap()), null, "game") ] # load all cards in my player's hand preloaded_package_ids = [] for cardIndex in gameSession.getMyPlayer().getDeck().getHand() card = gameSession.getCardByIndex(cardIndex) if card? # get unique id for card preload card_id = card.id card_pkg_id = PKGS.getCardGamePkgIdentifier(card_id) card_preload_pkg_id = card_pkg_id + "_preload_" + UtilsJavascript.generateIncrementalId() preloaded_package_ids.push(card_preload_pkg_id) load_promises.push(PackageManager.getInstance().loadMinorPackage(card_preload_pkg_id, PKGS.getPkgForIdentifier(card_pkg_id), "game")) # load all cards and modifiers on board for card in gameSession.getBoard().getCards(null, allowUntargetable=true) # get unique id for card preload card_id = card.getId() card_pkg_id = PKGS.getCardGamePkgIdentifier(card_id) card_resources_pkg = PKGS.getPkgForIdentifier(card_pkg_id) card_preload_pkg_id = card_pkg_id + "_preload_" + UtilsJavascript.generateIncrementalId() preloaded_package_ids.push(card_preload_pkg_id) # include signature card resources if card instanceof SDK.Entity and card.getWasGeneral() referenceSignatureCard = card.getReferenceSignatureCard() if referenceSignatureCard? signature_card_id = referenceSignatureCard.getId() signature_card_pkg_id = PKGS.getCardGamePkgIdentifier(signature_card_id) signature_card_resources_pkg = PKGS.getPkgForIdentifier(signature_card_pkg_id) card_resources_pkg = [].concat(card_resources_pkg, signature_card_resources_pkg) # load card resources load_promises.push(PackageManager.getInstance().loadMinorPackage(card_preload_pkg_id, card_resources_pkg, "game")) # modifiers for modifier in card.getModifiers() if modifier? # get unique id for modifier preload modifier_type = modifier.getType() modifier_preload_package_id = modifier_type + "_preload_" + UtilsJavascript.generateIncrementalId() preloaded_package_ids.push(modifier_preload_package_id) load_promises.push(PackageManager.getInstance().loadMinorPackage(modifier_preload_package_id, PKGS.getPkgForIdentifier(modifier_type), "game")) # load artifact card if modifier is applied by an artifact if modifier.getIsFromArtifact() artifact_card = modifier.getSourceCard() if artifact_card? # get unique id for artifact card preload artifact_card_id = artifact_card.getId() artifact_card_pkg_id = PKGS.getCardInspectPkgIdentifier(artifact_card_id) artifact_card_preload_pkg_id = artifact_card_pkg_id + "_preload_" + UtilsJavascript.generateIncrementalId() preloaded_package_ids.push(artifact_card_preload_pkg_id) load_promises.push(PackageManager.getInstance().loadMinorPackage(artifact_card_preload_pkg_id, PKGS.getPkgForIdentifier(artifact_card_pkg_id), "game")) return Promise.all(load_promises).then(() -> # destroy all views/layers return NavigationManager.getInstance().destroyAllViewsAndLayers() ).then(() -> return PackageManager.getInstance().activateGamePackage() ).then(() -> # show game and ui overlay_promise = Scene.getInstance().destroyOverlay() game_promise = Scene.getInstance().showGame() content_promise = NavigationManager.getInstance().showContentView(new gameUIViewClass({challenge: challenge})) utility_promise = NavigationManager.getInstance().showUtilityView(new UtilityGameMenuItemView({model: ProfileManager.getInstance().profile})) # listen to game local events App._subscribeToGameLocalEvents() # wait for game to show as active (not status active) then unload all preloaded packages scene = Scene.getInstance() gameLayer = scene? && scene.getGameLayer() if !gameLayer? or gameLayer.getStatus() == GameLayer.STATUS.ACTIVE PackageManager.getInstance().unloadMajorMinorPackages(preloaded_package_ids) else onActiveGame = () -> gameLayer.getEventBus().off(EVENTS.show_active_game, onActiveGame) gameLayer.getEventBus().off(EVENTS.terminate, onTerminate) PackageManager.getInstance().unloadMajorMinorPackages(preloaded_package_ids) onTerminate = () -> gameLayer.getEventBus().off(EVENTS.show_active_game, onActiveGame) gameLayer.getEventBus().off(EVENTS.terminate, onTerminate) gameLayer.getEventBus().on(EVENTS.show_active_game, onActiveGame) gameLayer.getEventBus().on(EVENTS.terminate, onTerminate) return Promise.all([ overlay_promise, game_promise, content_promise, utility_promise ]) ).then(() -> # enable user triggered navigation NavigationManager.getInstance().requestUserTriggeredNavigationUnlocked(App._userNavLockId) ) ######## App.onAfterShowEndTurn = () -> Logger.module("APPLICATION").log "App:onAfterShowEndTurn" # if we're playing in sandbox mode, we need to let the player play both sides so we swap players here if SDK.GameSession.getInstance().isSandbox() # swap test user id player1 = SDK.GameSession.getInstance().getPlayer1() player2 = SDK.GameSession.getInstance().getPlayer2() if player1.getIsCurrentPlayer() then SDK.GameSession.getInstance().setUserId(player1.getPlayerId()) else SDK.GameSession.getInstance().setUserId(player2.getPlayerId()) # # --- Game Cleanup ---- # # App.cleanupGame = () -> Logger.module("APPLICATION").log "App.cleanupGame" # cleanup reconnect App.cleanupReconnectToGame() # cleanup events App.cleanupGameEvents() # terminate the game layer Scene.getInstance().getGameLayer()?.terminate() # reset the current instance of the game session SDK.GameSession.reset() App.cleanupGameEvents = () -> Logger.module("APPLICATION").log "App.cleanupGameEvents" # cleanup events App._unsubscribeFromGameLocalEvents() App._unsubscribeFromGameNetworkEvents() # # --- Game Over Views ---- # # App._onGameOver = () -> Logger.module("APPLICATION").log "App:_onGameOver" # start loading data as soon as game is over, don't wait for animations App._startLoadingGameOverData() # disconnect from game room on network side # defer it until the call stack clears so any actions that caused the game to be over get broadcast during the current JS tick _.defer () -> SDK.NetworkManager.getInstance().disconnect() # # --- Game Turn Over---- # # App._onEndTurn = (e) -> AnalyticsTracker.sendAnalyticsForCompletedTurn(e.turn) ###* # This method de-registers all game listeners and initiates the game over screen flow. For visual sequencing purposes, it fires when it recieves an event that all game actions are done showing in the game layer. # @public ### App.onShowGameOver = () -> Logger.module("APPLICATION").log "App:onShowGameOver" # analytics call Analytics.page("Game Over",{ path: "/#game_over" }) App.cleanupGameEvents() App.showVictoryWhenGameDataReady() ###* # Load progression, rank, etc... data after a game is over. # @private ### App._startLoadingGameOverData = ()-> # for specated games, don't load any data if SDK.GameSession.current().getIsSpectateMode() App._gameOverDataThenable = Promise.resolve([null,[]]) return # resolve when the last game is confirmed as "over" whenGameJobsProcessedAsync = new Promise (resolve,reject)-> isGameReady = (gameAttrs,jobAttrs)-> # if game is not over yet, the rest of the data is not valid if gameAttrs.status != SDK.GameStatus.over return false switch gameAttrs.game_type when SDK.GameType.Friendly return isFriendlyGameReady(gameAttrs,jobAttrs) when SDK.GameType.Ranked return isRankedGameReady(gameAttrs,jobAttrs) when SDK.GameType.Casual return isCasualGameReady(gameAttrs,jobAttrs) when SDK.GameType.Gauntlet return isGauntletGameReady(gameAttrs,jobAttrs) when SDK.GameType.SinglePlayer return isSinglePlayerGameReady(gameAttrs,jobAttrs) when SDK.GameType.BossBattle return isBossBattleGameReady(gameAttrs,jobAttrs) when SDK.GameType.Rift return isRiftGameReady(gameAttrs,jobAttrs) else return Promise.resolve() isFriendlyGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_scored return jobAttrs.quests and jobAttrs.faction_progression else return true isRankedGameReady = (gameAttrs,jobAttrs)-> doneProcessing = false if gameAttrs.is_scored doneProcessing = (jobAttrs.rank and jobAttrs.quests and jobAttrs.progression and jobAttrs.faction_progression) else doneProcessing = (jobAttrs.rank) # if we're in diamond or above, wait for ladder, othwerwise don't since it's not guaranteed to process if GamesManager.getInstance().getCurrentRank() <= SDK.RankDivisionLookup.Diamond doneProcessing = doneProcessing and jobAttrs.ladder return doneProcessing isCasualGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_scored return (jobAttrs.quests and jobAttrs.progression and jobAttrs.faction_progression) else return true isGauntletGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_scored return (jobAttrs.gauntlet and jobAttrs.quests and jobAttrs.progression and jobAttrs.faction_progression) else return jobAttrs.gauntlet isSinglePlayerGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_scored return jobAttrs.faction_progression else return true isBossBattleGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_winner return (jobAttrs.progression and jobAttrs.cosmetic_chests and jobAttrs.faction_progression) if gameAttrs.is_scored return jobAttrs.faction_progression else return true isRiftGameReady = (gameAttrs,jobAttrs)-> if gameAttrs.is_scored doneProcessing = (jobAttrs.rift and jobAttrs.quests) else doneProcessing = (jobAttrs.rift) gameSession = SDK.GameSession.getInstance() lastGameModel = GamesManager.getInstance().playerGames.first() if lastGameModel? and SDK.GameType.isNetworkGameType(gameSession.getGameType()) # lastGameModel.onSyncOrReady().then ()-> if isGameReady(lastGameModel.attributes,lastGameModel.attributes.job_status || {}) resolve([lastGameModel,null]) else lastGameModel.on "change", () -> if isGameReady(lastGameModel.attributes,lastGameModel.attributes.job_status || {}) lastGameModel.off "change" resolve([lastGameModel,null]) else if gameSession.isChallenge() challengeId = gameSession.getChallenge().type if gameSession.getChallenge() instanceof SDK.ChallengeRemote and gameSession.getChallenge().isDaily # Don't process daily challenges run by qa tool if gameSession.getChallenge()._generatedForQA resolve([null,null]) else ProgressionManager.getInstance().completeDailyChallenge(challengeId).then (challengeData)-> challengeModel = new Backbone.Model(challengeData) resolve([null,challengeModel]) else ProgressionManager.getInstance().completeChallengeWithType(challengeId).then (challengeData)-> NewPlayerManager.getInstance().setHasSeenBloodbornSpellInfo() challengeModel = new Backbone.Model(challengeData) resolve([null,challengeModel]) else resolve([null, null]) App._gameOverDataThenable = whenGameJobsProcessedAsync .bind {} .spread (userGameModel,challengeModel)-> @.userGameModel = userGameModel @.challengeModel = challengeModel rewardIds = [] gameSession = SDK.GameSession.getInstance() # Send game based analytics AnalyticsTracker.submitGameOverAnalytics(gameSession,userGameModel) # Mark first game of type completions if gameSession.isRanked() NewPlayerManager.getInstance().setHasPlayedRanked(userGameModel) if gameSession.isSinglePlayer() NewPlayerManager.getInstance().setHasPlayedSinglePlayer(userGameModel) if @.userGameModel?.get('rewards') for rewardId,val of @.userGameModel.get('rewards') rewardIds.push rewardId if @.challengeModel?.get('reward_ids') for rewardId in @.challengeModel.get('reward_ids') rewardIds.push rewardId return rewardIds .then (rewardIds)-> allPromises = [] if rewardIds? for rewardId in rewardIds rewardModel = new DuelystBackbone.Model() rewardModel.url = process.env.API_URL + "/api/me/rewards/#{rewardId}" rewardModel.fetch() allPromises.push rewardModel.onSyncOrReady() return Promise.all(allPromises) .then (allRewardModels)-> @.rewardModels = allRewardModels # if we're not done with core progression if not NewPlayerManager.getInstance().isCoreProgressionDone() return NewPlayerManager.getInstance().updateCoreState() else return Promise.resolve() .then (newPlayerProgressionData)-> if newPlayerProgressionData?.quests @.newBeginnerQuestsCollection = new Backbone.Collection(newPlayerProgressionData?.quests) else @.newBeginnerQuestsCollection = new Backbone.Collection() .then ()-> # if we're at a stage where we should start generating daily quests, request them in case any of the quest slots opened up if NewPlayerManager.getInstance().shouldStartGeneratingDailyQuests() return QuestsManager.getInstance().requestNewDailyQuests() else return Promise.resolve() .then ()-> return Promise.all([@.userGameModel,@.rewardModels,@.newBeginnerQuestsCollection]) # don't wait more than ~10 seconds .timeout(10000) ###* # Shows the victory screen after a game is over, all data is loaded, and assets for victory screen are allocated. # @public ### App.showVictoryWhenGameDataReady = () -> # show activity dialog NavigationManager.getInstance().showDialogView(new ActivityDialogItemView()); # resolve when post game assets are done loading return PackageManager.getInstance().loadMinorPackage("postgame") .then ()-> return App._gameOverDataThenable .spread (userGameModel,rewardModels,newBeginnerQuestsCollection)-> if not rewardModels throw new Error() # destroy dialog NavigationManager.getInstance().destroyDialogView() # terminate game layer as we no longer need it to be active Scene.getInstance().getGameLayer()?.terminate() # show victory App.showVictory(userGameModel,rewardModels,newBeginnerQuestsCollection) .catch Promise.TimeoutError, (e) -> # hide dialog NavigationManager.getInstance().destroyDialogView() App._error("We're experiencing some delays in processing your game. Don't worry, you can keep playing and you'll receive credit shortly.") .catch (e)-> # hide dialog NavigationManager.getInstance().destroyDialogView() App._error(e.message) ###* # Shows the victory screen after a game is over. # @public # @param {Backbone.Model} userGameModel Game model that is finished loading / processing all jobs. # @param {Array} rewardModels Rewards that this game needs to show. # @param {Backbone.Collection} newBeginnerQuestsCollection Collection of new beginner quests as of game completion ### App.showVictory = (userGameModel,rewardModels,newBeginnerQuestsCollection) -> Logger.module("APPLICATION").log "App:showVictory" if not SDK.GameSession.getInstance().getIsSpectateMode() and SDK.GameType.isNetworkGameType(SDK.GameSession.getInstance().getGameType()) faction_id = userGameModel.get('faction_id') faction_xp = userGameModel.get('faction_xp') faction_xp_earned = userGameModel.get('faction_xp_earned') faction_level = SDK.FactionProgression.levelForXP(faction_xp + faction_xp_earned) faction_prog_reward = SDK.FactionProgression.rewardDataForLevel(faction_id,faction_level) if SDK.FactionProgression.hasLeveledUp(faction_xp + faction_xp_earned, faction_xp_earned) and faction_prog_reward App.setCallbackWhenCancel(App.showFactionXpReward.bind(App,userGameModel,rewardModels)) else if SDK.GameSession.getInstance().isRanked() App.setCallbackWhenCancel(App.showLadderProgress.bind(App,userGameModel,rewardModels)) else if SDK.GameSession.getInstance().isRift() App.setCallbackWhenCancel(App.showRiftProgress.bind(App,userGameModel,rewardModels)) else App.addNextScreenCallbackToVictoryFlow(rewardModels) else # local games if SDK.GameSession.getInstance().isChallenge() # for challenges App.addNextScreenCallbackToVictoryFlow(rewardModels); userGameModel ?= new Backbone.Model({}) return Promise.all([ Scene.getInstance().showOverlay(new VictoryLayer()) NavigationManager.getInstance().showContentView(new VictoryItemView({model:userGameModel || new Backbone.Model({})})) ]) ###* # Shows the next screen in the victory order: rank, quests, rewards etc. # @public # @param {Backbone.Model} userGameModel Game model that is finished loading / processing all jobs. # @param {Array} rewardModels Rewards that this game needs to show. ### App.addNextScreenCallbackToVictoryFlow = (rewardModels) -> Logger.module("APPLICATION").log "App:addNextScreenCallbackToVictoryFlow" # # if we have any faction progression rewards, show those first # if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "faction xp" and rewardModel.get('is_unread')) # return App.setCallbackWhenCancel(App.showFactionXpReward.bind(App,rewardModels)) # if we have any quest rewards, show those next if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "quest" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showQuestsCompleted.bind(App,rewardModels)) # if we have any progression rewards, show those next if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "progression" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showWinCounterReward.bind(App,rewardModels)) # ... if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "challenge" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showTutorialRewards.bind(App,rewardModels)) # ... if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "daily challenge" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showTutorialRewards.bind(App,rewardModels)) # if we have any ribbon rewards, show those next if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "ribbon" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showNextRibbonReward.bind(App,rewardModels)) # # if we have any gift crate rewards, show those next # if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_type') == "gift crate" and rewardModel.get('is_unread')) # return App.setCallbackWhenCancel(App.showGiftCrateReward.bind(App,rewardModels)) # if we have any cosmetic loot crate rewards, show those next if _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "loot crate" and rewardModel.get('is_unread')) return App.setCallbackWhenCancel(App.showLootCrateReward.bind(App,rewardModels)) # if we have any faction unlocks, show those next factionUnlockedReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "faction unlock" and rewardModel.get('is_unread')) if factionUnlockedReward return App.setCallbackWhenCancel(App.showUnlockedFaction.bind(App,factionUnlockedReward.get('unlocked_faction_id'))) # if we are doing a tutorial, kick us back to the tutorial screen, unless it's the last lesson: LessonFour, in which case, move along with normal flow (kicks to main menu) if SDK.GameSession.getInstance().getChallenge()?.categoryType == SDK.ChallengeCategory.tutorial.type # for tutorial go show tutorial layout if SDK.GameSession.getInstance().getChallenge().type != "LessonFour" return App.setCallbackWhenCancel(App._showTutorialLessons.bind(App,SDK.GameSession.getInstance().getChallenge())) ###* # Show unlocked faction screen. # @public # @param {String|Number} factionId # @returns {Promise} ### App.showUnlockedFaction = (factionId) -> Logger.module("APPLICATION").log("App:showUnlockedFaction", factionId) unlockFactionLayer = new UnlockFactionLayer(factionId) return Promise.all([ NavigationManager.getInstance().destroyContentView(), NavigationManager.getInstance().destroyDialogView(), Scene.getInstance().showOverlay(unlockFactionLayer) ]) .then () -> if Scene.getInstance().getOverlay() == unlockFactionLayer unlockFactionLayer.animateReward() .catch (error) -> App._error(error) ###* # Show ribbon reward screen if there are any unread ribbon reward models. # @public # @param {Array} rewardModels the reward models array. ### App.showNextRibbonReward = (rewardModels) -> Logger.module("APPLICATION").log "App:showNextRibbonReward" nextReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "ribbon" and rewardModel.get('is_unread')) nextReward.set('is_unread',false) ribbonId = nextReward.get("ribbons")?[0] if ribbonId? ribbonObject = SDK.RibbonFactory.ribbonForIdentifier(ribbonId) # clear ui NavigationManager.getInstance().destroyContentView() NavigationManager.getInstance().destroyDialogView() # show the in-engine card reward animation progressionRewardLayer = new ProgressionRewardLayer() Scene.getInstance().showOverlay(progressionRewardLayer) progressionRewardLayer.showRewardRibbons([ribbonId], "You've earned the #{ribbonObject.title} ribbon.", "Ribbons show on your profile for performing in battle with distinction.") else Logger.module("APPLICATION").log "ERROR: ribbonId is undefined for reward #{nextReward.get("id")}" ###* # Show progression reward screen. # @public # @param {Backbone.Model} rewardModel progression reward model. ### App.showProgressReward = (rewardModel) -> Logger.module("APPLICATION").log "App:showProgressReward" # clear ui NavigationManager.getInstance().destroyContentView() NavigationManager.getInstance().destroyDialogView() # show the in-engine card reward animation if rewardModel.get("cards") # cards cardIds = rewardModel.get("cards") if rewardModel.get("_showStack") cardIds = [cardIds[0]] progressionRewardLayer = new ProgressionRewardLayer() Scene.getInstance().showOverlay(progressionRewardLayer) progressionRewardLayer.showRewardCards(cardIds, rewardModel.get("_showStack"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("cosmetics") # NOTE: only emotes and battle maps will work for this case progressionRewardLayer = new ProgressionRewardLayer() Scene.getInstance().showOverlay(progressionRewardLayer) if SDK.CosmeticsFactory.cosmeticForIdentifier(rewardModel.get("cosmetics")[0]).typeId == SDK.CosmeticsTypeLookup.BattleMap progressionRewardLayer.showRewardBattleMaps(rewardModel.get("cosmetics"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else progressionRewardLayer.showRewardEmotes(rewardModel.get("cosmetics"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("gift_chests") CrateManager.getInstance().refreshGiftCrates() rewardLayer = new LootCrateRewardLayer() Scene.getInstance().showOverlay(rewardLayer) rewardLayer.animateReward(rewardModel.get("gift_chests"),rewardModel.get("_title"),rewardModel.get("_subTitle")) else if rewardModel.get("cosmetic_keys") # cosmetic keys cosmeticKeyRewardLayer = new LootCrateRewardLayer() Scene.getInstance().showOverlay(cosmeticKeyRewardLayer) cosmeticKeyRewardLayer.animateReward(rewardModel.get("cosmetic_keys"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("ribbons") # ribbons progressionRewardLayer = new ProgressionRewardLayer() Scene.getInstance().showOverlay(progressionRewardLayer) progressionRewardLayer.showRewardRibbons(rewardModel.get("ribbons"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("spirit") # spirit currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) currencyRewardLayer.animateReward("spirit", rewardModel.get("spirit"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("gold") # gold currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) currencyRewardLayer.animateReward("gold", rewardModel.get("gold"), rewardModel.get("_title"), rewardModel.get("_subTitle")) else if rewardModel.get("spirit_orbs") # booster boosterRewardLayer = new BoosterRewardLayer() Scene.getInstance().showOverlay(boosterRewardLayer) boosterRewardLayer.animateReward(rewardModel.get("_title"), rewardModel.get("_subTitle"), rewardModel.get("spirit_orbs")) else if rewardModel.get("gauntlet_tickets") # gauntlet ticket gauntletTicketRewardLayer = new GauntletTicketRewardLayer() Scene.getInstance().showOverlay(gauntletTicketRewardLayer) gauntletTicketRewardLayer.animateReward(rewardModel.get("_title"), rewardModel.get("_subTitle")) else Logger.module("APPLICATION").log("Application->showProgressReward: Attempt to show reward model without valid reward") ###* # Show achievement reward screen if there are any unread ones. # @public ### App.showAchievementCompletions = () -> if !AchievementsManager.getInstance().hasUnreadCompletedAchievements() Scene.getInstance().destroyOverlay() return Promise.resolve() else return new Promise( (resolve, reject) -> locResolve = resolve Logger.module("APPLICATION").log "App:showAchievementCompletions" completedAchievementModel = AchievementsManager.getInstance().popNextUnreadAchievementModel() App.setCallbackWhenCancel(locResolve) # show reward App.showProgressReward(completedAchievementModel) ).then () -> return App.showAchievementCompletions() ###* # Show twitch reward screen if there are any unread ones. # @public ### App.showTwitchRewards = () -> if !TwitchManager.getInstance().hasUnclaimedTwitchRewards() Scene.getInstance().destroyOverlay() return Promise.resolve() else return new Promise( (resolve, reject) -> locResolve = resolve Logger.module("APPLICATION").log "App:showTwitchRewards" twitchRewardModel = TwitchManager.getInstance().popNextUnclaimedTwitchRewardModel() App.setCallbackWhenCancel(locResolve) # show reward App.showProgressReward(twitchRewardModel) ).then () -> return App.showTwitchRewards() ###* # Show season rewards screen if the player has an unread season rewards set. # @public ### App.showEndOfSeasonRewards = () -> gamesManager = GamesManager.getInstance() if gamesManager.hasUnreadSeasonReward() return new Promise( (resolve, reject) -> locResolve = resolve # get data seasonModel = gamesManager.getSeasonsWithUnclaimedRewards()[0] bonusChevrons = SDK.RankFactory.chevronsRewardedForReachingRank(seasonModel.get("top_rank")? || 30) seasonRewardIds = seasonModel.get("reward_ids") if bonusChevrons == 0 # If there is no rewards we exit here locResolve() else Logger.module("APPLICATION").log "App:showEndOfSeasonRewards" endOfSeasonLayer = new EndOfSeasonLayer(seasonModel) return Promise.all([ NavigationManager.getInstance().destroyContentView(), NavigationManager.getInstance().destroyDialogView(), Scene.getInstance().showOverlay(endOfSeasonLayer) ]) .then () -> App.setCallbackWhenCancel(() -> Scene.getInstance().destroyOverlay() locResolve() ) if Scene.getInstance().getOverlay() == endOfSeasonLayer return endOfSeasonLayer.animateReward() .catch (error) -> Logger.module("APPLICATION").log("App.showEndOfSeasonRewards error: ", error) locResolve() ) else return Promise.resolve() App.showTutorialRewards = (rewardModels) -> Logger.module("APPLICATION").log "App:showTutorialRewards" nextReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "challenge" and rewardModel.get('is_unread')) nextReward = nextReward || _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "daily challenge" and rewardModel.get('is_unread')) nextReward.set("is_unread",false) App.addNextScreenCallbackToVictoryFlow(rewardModels) # show reward if (nextReward.get("unlocked_faction_id")) App.showUnlockedFaction(nextReward.get("unlocked_faction_id")) else App.showProgressReward(nextReward) App.showLadderProgress = (userGameModel,rewardModels) -> Logger.module("APPLICATION").log "App:showLadderProgress" # set the cancel callback to show the next screen App.addNextScreenCallbackToVictoryFlow(rewardModels) ladderProgressLayer = new LadderProgressLayer() return Promise.all([ NavigationManager.getInstance().destroyContentView(), NavigationManager.getInstance().destroyDialogView(), Scene.getInstance().showOverlay(ladderProgressLayer) ]) .then () -> if Scene.getInstance().getOverlay() == ladderProgressLayer return ladderProgressLayer.showLadderProgress(userGameModel) .catch (error) -> App._error("App.showLadderProgress error: ", error) App.showRiftProgress = (userGameModel,rewardModels) -> Logger.module("APPLICATION").log "App:showRiftProgress" # set the cancel callback to show the next screen App.addNextScreenCallbackToVictoryFlow(rewardModels) riftProgressLayer = new RiftProgressLayer() return Promise.all([ NavigationManager.getInstance().destroyContentView(), NavigationManager.getInstance().destroyDialogView(), Scene.getInstance().showOverlay(riftProgressLayer) ]) .then () -> if Scene.getInstance().getOverlay() == riftProgressLayer return riftProgressLayer.showRiftProgress(userGameModel) .catch (error) -> App._error("App.showRiftProgress error: ", error) App.showQuestsCompleted = (rewardModels) -> Logger.module("APPLICATION").log "App:showQuestsCompleted" nextQuestReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "quest" and rewardModel.get('is_unread')) nextQuestReward.set('is_unread',false) sdkQuest = SDK.QuestFactory.questForIdentifier(nextQuestReward.get('quest_type_id')) questName = sdkQuest.getName() gold = nextQuestReward.get("gold") spiritOrbs = nextQuestReward.get("spirit_orbs") giftChests = null cosmeticKeys = null if sdkQuest.giftChests?.length > 0 giftChests = sdkQuest.giftChests if sdkQuest.cosmeticKeys?.length > 0 cosmeticKeys = sdkQuest.cosmeticKeys # track an event in analytics Analytics.track("quest complete", { category: Analytics.EventCategory.Quest, quest_type_id: nextQuestReward.get('quest_type_id'), gold_amount:nextQuestReward.get("gold") || 0 },{ labelKey:"quest_type_id" valueKey:"gold_amount" nonInteraction:1 }) # set the cancel callback to show the next screen App.addNextScreenCallbackToVictoryFlow(rewardModels) # show quest reward NavigationManager.getInstance().destroyContentView() if gold currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) currencyRewardLayer.animateReward( "gold", gold, i18next.t("rewards.quest_complete_title",{quest_name:questName}) "+#{gold} GOLD for completing #{questName}", "Quest Complete" ) else if spiritOrbs # booster boosterRewardLayer = new BoosterRewardLayer() Scene.getInstance().showOverlay(boosterRewardLayer) boosterRewardLayer.animateReward( i18next.t("rewards.quest_complete_title",{quest_name:questName}) "+#{spiritOrbs} SPIRIT ORBS for completing #{questName}" ) else if giftChests Analytics.track("earned gift crate", { category: Analytics.EventCategory.Crate, product_id: giftChests[0] }, { labelKey: "product_id" }) # show reward setup on the engine side NavigationManager.getInstance().destroyContentView() rewardLayer = new LootCrateRewardLayer() Scene.getInstance().showOverlay(rewardLayer) rewardLayer.animateReward(giftChests, null, i18next.t("rewards.quest_reward_gift_crate_title",{quest_name:questName})) CrateManager.getInstance().refreshGiftCrates() else if cosmeticKeys Analytics.track("earned cosmetic key", { category: Analytics.EventCategory.Crate, product_id: cosmeticKeys[0] }, { labelKey: "PI:KEY:<KEY>END_PI" }) NavigationManager.getInstance().destroyContentView() rewardLayer = new CosmeticKeyRewardLayer() Scene.getInstance().showOverlay(rewardLayer) rewardLayer.showRewardKeys(cosmeticKeys, null, "FREE Cosmetic Crate Key for completing the #{questName} quest") CrateManager.getInstance().refreshGiftCrates() # Outdated name, really shows all progression rewards App.showWinCounterReward = (rewardModels) -> Logger.module("APPLICATION").log "App:showWinCounterReward" nextReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "progression" and rewardModel.get('is_unread')) nextReward.set("is_unread",false) App.addNextScreenCallbackToVictoryFlow(rewardModels) # show reward setup on the engine side NavigationManager.getInstance().destroyContentView() # Scene.getInstance().showOverlay(currencyRewardLayer) # TODO: merge How does this even work? rewardView = null switch nextReward.get("reward_type") when "win count" currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) goldAmount = nextReward.get("gold") message = i18next.t("rewards.3_win_gold_reward_message",{gold_amount:goldAmount}) currencyRewardLayer.animateReward( "gold", goldAmount, i18next.t("rewards.3_win_gold_reward_title"), message ) when "play count" currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) goldAmount = nextReward.get("gold") currencyRewardLayer.animateReward( "gold", goldAmount, i18next.t("rewards.4_play_gold_reward_title"), i18next.t("rewards.4_play_gold_reward_message",{gold_amount:goldAmount}) ) when "daily win" currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) goldAmount = nextReward.get("gold") currencyRewardLayer.animateReward( "gold", goldAmount, i18next.t("rewards.first_win_of_the_day_reward_title"), i18next.t("rewards.first_win_of_the_day_reward_message",{gold_amount:goldAmount}) ) when "first 3 games" currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) goldAmount = nextReward.get("gold") currencyRewardLayer.animateReward( "gold", goldAmount, i18next.t("rewards.first_3_games_reward_title"), i18next.t("rewards.first_3_games_reward_message",{gold_amount:goldAmount}) ) when "first 10 games" currencyRewardLayer = new CurrencyRewardLayer() Scene.getInstance().showOverlay(currencyRewardLayer) goldAmount = nextReward.get("gold") currencyRewardLayer.animateReward( "gold", goldAmount, i18next.t("rewards.first_10_games_reward_title"), i18next.t("rewards.first_10_games_reward_message",{gold_amount:goldAmount}) ) when "boss battle" boosterRewardLayer = new BoosterRewardLayer() Scene.getInstance().showOverlay(boosterRewardLayer) cardSetId = nextReward.get("spirit_orbs") boosterRewardLayer.animateReward( i18next.t("rewards.boss_defeated_reward_title"), i18next.t("rewards.boss_defeated_reward_message"), SDK.CardSet.Core ) App.showLootCrateReward = (rewardModels)-> Logger.module("APPLICATION").log "App:showLootCrateReward" nextReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "loot crate" and rewardModel.get('is_unread')) nextReward.set("is_unread",false) Analytics.track("earned cosmetic crate", { category: Analytics.EventCategory.Crate, product_id: nextReward.get("cosmetic_chests")?[0] }, { labelKey: "product_id" }) App.addNextScreenCallbackToVictoryFlow(rewardModels) # show reward setup on the engine side NavigationManager.getInstance().destroyContentView() rewardLayer = new LootCrateRewardLayer() Scene.getInstance().showOverlay(rewardLayer) rewardLayer.animateReward(nextReward.get("cosmetic_chests")) # App.showGiftCrateReward = (rewardModels)-> # Logger.module("APPLICATION").log "App:showGiftCrateReward" # # nextReward = _.find(rewardModels, (rewardModel)-> rewardModel.get('reward_type') == "gift crate" and rewardModel.get('is_unread')) # nextReward.set("is_unread",false) # # Analytics.track("earned gift crate", { # category: Analytics.EventCategory.Crate, # product_id: nextReward.get("gift_crates")?[0] # }, { # labelKey: "product_id" # }) # # App.addNextScreenCallbackToVictoryFlow(rewardModels) # # # show reward setup on the engine side # NavigationManager.getInstance().destroyContentView() # rewardLayer = new LootCrateRewardLayer() # Scene.getInstance().showOverlay(rewardLayer) # rewardLayer.animateReward(nextReward.get("gift_crates")) App.showFactionXpReward = (userGameModel,rewardModels) -> Logger.module("APPLICATION").log "App:showFactionXpReward" nextUnreadReward = _.find rewardModels, (rewardModel)-> rewardModel.get('reward_category') == "faction xp" and rewardModel.get('is_unread') nextUnreadReward.set("is_unread",false) factionId = userGameModel.get("faction_id") factionName = SDK.FactionFactory.factionForIdentifier(factionId).name faction_xp = userGameModel.get('faction_xp') faction_xp_earned = userGameModel.get('faction_xp_earned') level = SDK.FactionProgression.levelForXP(faction_xp + faction_xp_earned) + 1 # set title nextUnreadReward.set("_title", i18next.t("rewards.level_up_reward_title",{ level:level })) # set reward model properties by reward if nextUnreadReward.get("cards") # cards factionCards = GameDataManager.getInstance().visibleCardsCollection.filter (c)-> c.get("factionId") == factionId and c.get("rarityId") == SDK.Rarity.Fixed availableFactionCards = _.filter(factionCards, (c)-> return c.get("inventoryCount") > 0 ) subtitle = i18next.t("rewards.card_reward_subtitle",{ card_count: availableFactionCards.length, total: factionCards.length, factionName: factionName }) nextUnreadReward.set("_subTitle", subtitle) nextUnreadReward.set("_showStack",true) else if nextUnreadReward.get("spirit") # sprit nextUnreadReward.set("_subTitle", i18next.t("rewards.spirit_for_faction_lvl_reward_message",{spirit:nextUnreadReward.get("spirit"),faction_name:factionName,level:level})) else if nextUnreadReward.get("gold") # gold nextUnreadReward.set("_subTitle", i18next.t("rewards.gold_for_faction_lvl_reward_message",{gold:nextUnreadReward.get("spirit"),faction_name:factionName,level:level})) else if nextUnreadReward.get("spirit_orbs") # booster nextUnreadReward.set("_subTitle", i18next.t("rewards.orb_for_faction_lvl_reward_message",{faction_name:factionName,level:level})) # setup next screen if SDK.GameSession.current().isRanked() App.setCallbackWhenCancel(App.showLadderProgress.bind(App,userGameModel,rewardModels)) else if SDK.GameSession.current().isRift() App.setCallbackWhenCancel(App.showRiftProgress.bind(App,userGameModel,rewardModels)) else App.addNextScreenCallbackToVictoryFlow(rewardModels) # show reward App.showProgressReward(nextUnreadReward) App.showNewBeginnerQuests = (beginnerQuestsCollection) -> NavigationManager.getInstance().toggleModalViewByClass(QuestLogLayout,{ collection:beginnerQuestsCollection, showConfirm:true }) App.showFreeCardOfTheDayReward = (opts)-> Promise.all([ NavigationManager.getInstance().destroyModalView(), NavigationManager.getInstance().destroyContentView(), NavigationManager.getInstance().destroyUtilityView() ]).then ()=> rewardLayer = new FreeCardOfTheDayLayer() Scene.getInstance().showOverlay(rewardLayer) rewardLayer.showCoreGem(opts.cardId) App.setCallbackWhenCancel ()-> Scene.getInstance().destroyOverlay() App._showMainMenu().then ()-> NavigationManager.getInstance().toggleModalViewByClass(QuestLogLayout,{ collection:QuestsManager.getInstance().getQuestCollection(), model:ProgressionManager.getInstance().gameCounterModel }) return Promise.resolve() # # ---- User Triggered Navigation ---- # # App.onUserTriggeredExit = () -> Logger.module("APPLICATION").log "App:onUserTriggeredExit" return App.main() App.onUserTriggeredSkip = () -> Logger.module("APPLICATION").log "App:onUserTriggeredSkip" gameSession = SDK.GameSession.getInstance() scene = Scene.getInstance() gameLayer = scene and scene.getGameLayer() if gameLayer? and gameLayer.getIsGameActive() # when in an active game if gameSession.getIsMyFollowupActiveAndCancellable() audio_engine.current().play_effect_for_interaction(RSX.sfx_ui_cancel.audio, CONFIG.CANCEL_SFX_PRIORITY) gameSession.submitExplicitAction(gameSession.getMyPlayer().actionEndFollowup()) else if gameLayer.getIsShowingActionCardSequence() audio_engine.current().play_effect_for_interaction(RSX.sfx_ui_cancel.audio, CONFIG.CANCEL_SFX_PRIORITY) # stop showing played card gameLayer.skipShowActionCardSequence() return Promise.resolve() App.onUserTriggeredCancel = () -> Logger.module("APPLICATION").log "App:onUserTriggeredCancel" cancelPromises = [] if NavigationManager.getInstance().getIsShowingModalView() # close modal screens audio_engine.current().play_effect_for_interaction(RSX.sfx_ui_cancel.audio, CONFIG.CANCEL_SFX_PRIORITY) cancelPromises.push(NavigationManager.getInstance().destroyModalView()) else if NavigationManager.getInstance().getHasLastRoute() # go to last route (handles own sfx) NavigationManager.getInstance().showLastRoute() else gameSession = SDK.GameSession.getInstance() scene = Scene.getInstance() gameLayer = scene and scene.getGameLayer() if gameLayer? and !gameLayer.getIsDisabled() and NavigationManager.getInstance().getIsShowingContentViewClass(GameLayout) # when in game that is not over if gameSession.getIsMyFollowupActiveAndCancellable() audio_engine.current().play_effect_for_interaction(RSX.sfx_ui_cancel.audio, CONFIG.CANCEL_SFX_PRIORITY) gameSession.submitExplicitAction(gameSession.actionRollbackSnapshot()) else if !gameLayer.getMyPlayer().getIsTakingSelectionAction() and !gameLayer.getIsShowingActionCardSequence() # show esc game menu if we are not selecting something in game and not showing an action sequence cancelPromises.push(NavigationManager.getInstance().showModalView(new EscGameMenuItemView())) # always reset game active state gameLayer.resetActiveState() else callback = App.getCallbackWhenCancel() if callback? App.setCallbackWhenCancel(null) callbackResult = callback() if callbackResult instanceof Promise cancelPromises.push(callbackResult) else if (App.getIsLoggedIn() or window.isDesktop) and (NavigationManager.getInstance().getIsShowingContentViewClass(LoaderItemView) or NavigationManager.getInstance().getIsShowingContentViewClass(LoginMenuItemView) or NavigationManager.getInstance().getIsShowingContentViewClass(MainMenuItemView) or NavigationManager.getInstance().getIsShowingContentViewClass(TutorialLessonsLayout)) # show esc main menu when on loading or login or main cancelPromises.push(NavigationManager.getInstance().showModalView(new EscMainMenuItemView())) else if (!gameLayer? or gameLayer.getIsDisabled()) and !App.getIsShowingMain() audio_engine.current().play_effect_for_interaction(RSX.sfx_ui_cancel.audio, CONFIG.CANCEL_SFX_PRIORITY) # for now just go back to main until we implement routing cancelPromises.push(App.main()) return Promise.all(cancelPromises) App.setCallbackWhenCancel = (callback) -> # this is a less than ideal method of setting the next step in cancel sequence App._callbackWhenCancel = callback App.getCallbackWhenCancel = () -> return App._callbackWhenCancel App.onUserTriggeredConfirm = () -> Logger.module("APPLICATION").log "App:onUserTriggeredConfirm" # # ---- Events: Client ---- # # App.beforeunload = (e) -> # return an empty string to trigger alert if App._reloadRequestIds.length == 0 and !window.isDesktop and !UtilsEnv.getIsInLocal() confirmMessage = "" (e || window.event).returnValue = confirmMessage return confirmMessage App.unload = () -> # reset the global event bus so no more events will be handled EventBus.reset() # cancel any ongoing matchmaking GamesManager.getInstance().cancelMatchmaking() App.bindEvents = () -> # attach event listeners to document/window $(window).on('unload', App.unload.bind(App)) $(window).on('mousemove',App.onPointerMove.bind(App)) $(window).on('mousedown',App.onPointerDown.bind(App)) $(window).on('mouseup',App.onPointerUp.bind(App)) $(window).on('wheel',App.onPointerWheel.bind(App)) $(window).on("resize", _.debounce(App.onResize.bind(App), 250)) EventBus.getInstance().on(EVENTS.request_resize, _.debounce(App.onResize.bind(App), 250)) $(document).on("visibilitychange",App.onVisibilityChange.bind(App)) EventBus.getInstance().on(EVENTS.request_reload, App.onRequestReload) EventBus.getInstance().on(EVENTS.cancel_reload_request, App.onCancelReloadRequest) $(CONFIG.GAMECANVAS_SELECTOR).on("webglcontextlost", () -> App.onRequestReload({ id: "webgl_context_lost", message: "Your graphics hit a snag and requires a #{if window.isDesktop then "restart" else "reload"} to avoid any issues." }) ) # session is a plain event emitter Session.on('login', App.onLogin) Session.on('logout', App.onLogout) Session.on('error', App.onSessionError) EventBus.getInstance().on(EVENTS.show_login, App._showLoginMenu, App) EventBus.getInstance().on(EVENTS.show_terms, App._showTerms, App) EventBus.getInstance().on(EVENTS.show_play, App.showPlay, App) EventBus.getInstance().on(EVENTS.show_watch, App.showWatch, App) EventBus.getInstance().on(EVENTS.show_shop, App.showShop, App) EventBus.getInstance().on(EVENTS.show_collection, App.showCollection, App) EventBus.getInstance().on(EVENTS.show_codex, App.showCodex, App) EventBus.getInstance().on(EVENTS.show_booster_pack_unlock, App.showBoosterPackUnlock, App) EventBus.getInstance().on(EVENTS.show_crate_inventory, App.showCrateInventory, App) EventBus.getInstance().on(EVENTS.start_challenge, App._startGameWithChallenge, App) EventBus.getInstance().on(EVENTS.start_single_player, App._startSinglePlayerGame, App) EventBus.getInstance().on(EVENTS.start_boss_battle, App._startBossBattleGame, App) EventBus.getInstance().on(EVENTS.start_replay, App._startGameForReplay, App) EventBus.getInstance().on(EVENTS.show_free_card_of_the_day, App.showFreeCardOfTheDayReward, App) EventBus.getInstance().on(EVENTS.discord_spectate, App.onDiscordSpectate, App) GamesManager.getInstance().on(EVENTS.matchmaking_start, App._matchmakingStart, App) GamesManager.getInstance().on(EVENTS.matchmaking_cancel, App._matchmakingCancel, App) GamesManager.getInstance().on(EVENTS.matchmaking_error, App._matchmakingError, App) GamesManager.getInstance().on(EVENTS.finding_game, App._findingGame, App) GamesManager.getInstance().on(EVENTS.invite_accepted, App._inviteAccepted, App) GamesManager.getInstance().on(EVENTS.invite_rejected, App._inviteRejected, App) GamesManager.getInstance().on(EVENTS.invite_cancelled, App._inviteCancelled, App) GamesManager.getInstance().on(EVENTS.start_spectate, App._spectateGame, App) EventBus.getInstance().on EVENTS.canvas_mouse_state, App.onCanvasMouseState, App NavigationManager.getInstance().on(EVENTS.user_triggered_exit, App.onUserTriggeredExit, App) NavigationManager.getInstance().on(EVENTS.user_triggered_skip, App.onUserTriggeredSkip, App) NavigationManager.getInstance().on(EVENTS.user_triggered_cancel, App.onUserTriggeredCancel, App) NavigationManager.getInstance().on(EVENTS.user_triggered_confirm, App.onUserTriggeredConfirm, App) EventBus.getInstance().on EVENTS.error, App._error, App EventBus.getInstance().on EVENTS.ajax_error, App._error, App App._subscribeToGameLocalEvents = () -> Logger.module("APPLICATION").log "App._subscribeToGameLocalEvents" scene = Scene.getInstance() gameLayer = scene?.getGameLayer() if gameLayer? gameLayer.getEventBus().on(EVENTS.after_show_end_turn, App.onAfterShowEndTurn, App) gameLayer.getEventBus().on(EVENTS.show_game_over, App.onShowGameOver, App) gameLayer.getEventBus().on(EVENTS.canvas_mouse_state, App.onCanvasMouseState, App) SDK.GameSession.getInstance().getEventBus().on(EVENTS.game_over, App._onGameOver, App) SDK.GameSession.getInstance().getEventBus().on(EVENTS.end_turn, App._onEndTurn, App) App._unsubscribeFromGameLocalEvents = () -> Logger.module("APPLICATION").log "App._unsubscribeFromGameLocalEvents" scene = Scene.getInstance() gameLayer = scene?.getGameLayer() if gameLayer? gameLayer.getEventBus().off(EVENTS.after_show_end_turn, App.onAfterShowEndTurn, App) gameLayer.getEventBus().off(EVENTS.show_game_over, App.onShowGameOver, App) gameLayer.getEventBus().off(EVENTS.canvas_mouse_state, App.onCanvasMouseState, App) SDK.GameSession.getInstance().getEventBus().off(EVENTS.game_over, App._onGameOver, App) SDK.GameSession.getInstance().getEventBus().off(EVENTS.end_turn, App._onEndTurn, App) App._subscribeToGameNetworkEvents = () -> Logger.module("APPLICATION").log "App._subscribeToGameNetworkEvents" SDK.NetworkManager.getInstance().getEventBus().on(EVENTS.network_game_event, App._onNetworkGameEvent, App) SDK.NetworkManager.getInstance().getEventBus().on(EVENTS.network_game_error, App._onNetworkGameError, App) SDK.NetworkManager.getInstance().getEventBus().on(EVENTS.game_server_shutdown, App._onGameServerShutdown, App) SDK.NetworkManager.getInstance().getEventBus().on(EVENTS.reconnect_to_game, App._onReconnectToGame, App) SDK.NetworkManager.getInstance().getEventBus().on(EVENTS.opponent_connection_status_changed, App._onOpponentConnectionStatusChanged, App) App._unsubscribeFromGameNetworkEvents = () -> Logger.module("APPLICATION").log "App._unsubscribeFromGameNetworkEvents" SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.network_game_event, App._onNetworkGameEvent, App) SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.network_game_error, App._onNetworkGameError, App) SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.game_server_shutdown, App._onGameServerShutdown, App) SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.reconnect_to_game, App._onReconnectToGame, App) SDK.NetworkManager.getInstance().getEventBus().off(EVENTS.opponent_connection_status_changed, App._onOpponentConnectionStatusChanged, App) App.onVisibilityChange = () -> # TODO: look into why this causes errors # Prevent sound effects that have been queued up from blasting all at once when app regains visibility if document.hidden # Would rather do a resume and start of effects, it doesn't stop them from piling up though audio_engine.current().stop_all_effects() else audio_engine.current().stop_all_effects() # # ---- RESIZE ---- # # App.onResize = (e) -> Logger.module("APPLICATION").log("App.onResize") # store current resolution data ignoreNextResolutionChange = App._ignoreNextResolutionChange App._ignoreNextResolutionChange = false if !ignoreNextResolutionChange currentResolution = CONFIG.resolution confirmResolutionChange = App._lastResolution? and App._lastResolution != currentResolution # before resize EventBus.getInstance().trigger(EVENTS.before_resize) # resize and update scale App._resizeAndScale() # resize the scene to match app Scene.getInstance().resize() # resize the UI EventBus.getInstance().trigger(EVENTS.resize) # after resize EventBus.getInstance().trigger(EVENTS.after_resize) # force user to restart if resource scale for engine has changed # CSS automatically handles resource scale changes # TODO: instead of restarting, destroy all current views, show loading screen, reload images at new scale, and return to current route App._needsRestart = App._lastResourceScaleEngine? and CONFIG.resourceScaleEngine != App._lastResourceScaleEngine if !App._needsRestart # cancel forced reload in case user has restored original window size App._cancelReloadRequestForResolutionChange() if confirmResolutionChange # confirm resolution with user after resizing App._confirmResolutionChange() else if App._needsRestart # force reload as user has changed window size App._requestReloadForResolutionChange() else # update resolution values as no confirm or restart needed App._updateLastResolutionValues() return true App._resizeAndScale = () -> Logger.module("APPLICATION").log("App._resizeAndScale") # resize canvas to match app size # engine bases its window size on the canvas size $html = $("html") $canvas = $(CONFIG.GAMECANVAS_SELECTOR) width = Math.max(CONFIG.REF_WINDOW_SIZE.width, $html.width()) height = Math.max(CONFIG.REF_WINDOW_SIZE.height, $html.height()) $canvas.width(width) $canvas.height(height) # set global scale CONFIG.globalScale = CONFIG.getGlobalScaleForResolution(CONFIG.resolution, width, height) # set css scales CONFIG.pixelScaleCSS = CONFIG.globalScale * window.devicePixelRatio $html.removeClass("resource-scale-" + String(CONFIG.resourceScaleCSS).replace(".", "\.")) CONFIG.resourceScaleCSS = 1 for resourceScale in CONFIG.RESOURCE_SCALES scaleDiff = Math.abs(CONFIG.pixelScaleCSS - resourceScale) currentScaleDiff = Math.abs(CONFIG.pixelScaleCSS - CONFIG.resourceScaleCSS) if scaleDiff < currentScaleDiff or (scaleDiff == currentScaleDiff and resourceScale > CONFIG.resourceScaleCSS) CONFIG.resourceScaleCSS = resourceScale $html.addClass("resource-scale-" + String(CONFIG.resourceScaleCSS).replace(".", "\.")) # html font size by global scale # css layout uses rems, which is based on html font size $html.css("font-size", CONFIG.globalScale * 10.0 + "px") App._lastResolution = null App._lastResourceScaleEngine = null App._ignoreNextResolutionChange = false App._needsRestart = false App._updateLastResolutionValues = () -> App._lastResolution = CONFIG.resolution App._lastResourceScaleEngine = CONFIG.resourceScaleEngine App._confirmResolutionChange = () -> Logger.module("APPLICATION").log "App._confirmResolutionChange" confirmData = {title: 'Do you wish to keep this viewport setting?'} if App._needsRestart if window.isDesktop confirmData.message = 'Warning: switching from your previous viewport to this viewport will require a restart!' else confirmData.message = 'Warning: switching from your previous viewport to this viewport will require a reload!' if ChatManager.getInstance().getStatusIsInBattle() confirmData.message += " You will be able to continue your game, but you may miss your turn!" confirmDialogItemView = new ConfirmDialogItemView(confirmData) confirmDialogItemView.listenToOnce(confirmDialogItemView, 'confirm', ()-> # update resolution after confirm App._lastResolution = CONFIG.resolution if App._needsRestart # defer to ensure this occurs after event resolves _.defer(App._requestReloadForResolutionChange) else # update resource scale if no restart needed App._lastResourceScaleEngine = CONFIG.resourceScaleEngine ) confirmDialogItemView.listenToOnce(confirmDialogItemView, 'cancel', ()-> # defer to ensure this occurs after event resolves _.defer(() -> # reset resolution and don't prompt about changes App._ignoreNextResolutionChange = true res = App._lastResolution || CONFIG.RESOLUTION_DEFAULT CONFIG.resolution = res Storage.set("resolution", res) App.onResize() ) ) # show confirm/cancel NavigationManager.getInstance().showDialogView(confirmDialogItemView) App._requestReloadForResolutionChangeId = "resolution_change" App._requestReloadForResolutionChange = () -> App.onRequestReload({ id: App._requestReloadForResolutionChangeId message: "Your viewport change requires a #{if window.isDesktop then "restart" else "reload"} to avoid any issues." }) App._cancelReloadRequestForResolutionChange = () -> App.onCancelReloadRequest({ id: App._requestReloadForResolutionChangeId }) # # ---- RELOAD ---- # # App._reloadRequestIds = [] ### * Request a reload, optionally passing in a message and id (to avoid conflicts). *### App.onRequestReload = (event) -> requestId = event?.id or 0 if !_.contains(App._reloadRequestIds, requestId) App._reloadRequestIds.push(requestId) if App._reloadRequestIds.length == 1 App._reload(event?.message) ### * Cancel a reload request, optionally passing in an id (to avoid conflicts). *### App.onCancelReloadRequest = (event) -> requestId = event?.id or 0 index = _.indexOf(App._reloadRequestIds, requestId) if index != -1 App._reloadRequestIds.splice(index, 1) if App._reloadRequestIds.length == 0 App._cancelReload() App._reload = (message) -> Logger.module("APPLICATION").log "App._reload" promptDialogItemView = new PromptDialogItemView({title: "Please #{if window.isDesktop then "restart" else "reload"}!", message: message}) promptDialogItemView.listenTo(promptDialogItemView, 'cancel', () -> if window.isDesktop then window.quitDesktop() else location.reload() ) NavigationManager.getInstance().showDialogView(promptDialogItemView) App._cancelReload = () -> Logger.module("APPLICATION").log "App._cancelReload" NavigationManager.getInstance().destroyDialogView() # # ---- Initialization Events ---- # # Sequence of events started with App.start. Can pass options object. # # Pre-Start Event App.on "before:start", (options) -> Logger.module("APPLICATION").log "----BEFORE START----" App.$el = $("#app") # Start Event App.on "start", (options) -> Logger.module("APPLICATION").log "----START----" # set unload alert $(window).on('beforeunload', App.beforeunload.bind(App)) # set initial selected scene selectedScene = parseInt(Storage.get("selectedScene")) if moment.utc().isAfter("2016-11-29") and moment.utc().isBefore("2017-01-01") selectedScene = SDK.CosmeticsLookup.Scene.Frostfire if moment.utc().isAfter("2017-03-14") and moment.utc().isBefore("2017-05-01") selectedScene = SDK.CosmeticsLookup.Scene.Vetruvian if moment.utc().isAfter("2017-07-01") and moment.utc().isBefore("2017-08-01") selectedScene = SDK.CosmeticsLookup.Scene.Shimzar if moment.utc().isAfter("2017-12-01") and moment.utc().isBefore("2018-01-18") selectedScene = SDK.CosmeticsLookup.Scene.Frostfire if selectedScene? and !isNaN(selectedScene) and _.isNumber(selectedScene) then CONFIG.selectedScene = selectedScene # set initial resolution userResolution = parseInt(Storage.get("resolution")) if userResolution? and !isNaN(userResolution) and _.isNumber(userResolution) then CONFIG.resolution = userResolution userHiDPIEnabled = Storage.get("hiDPIEnabled") if userHiDPIEnabled? if userHiDPIEnabled == "true" then CONFIG.hiDPIEnabled = true else if userHiDPIEnabled == "false" then CONFIG.hiDPIEnabled = false # update last resolution values to initial App._updateLastResolutionValues() # resize once for initial values App._resizeAndScale() # create a defered promise object for the loading and login process... sort of an anti-pattern but best for this use case App.managersReadyDeferred = new Promise.defer() # immediately connect the server status manager so we can get notified of any changes during the load process / on the login screen ServerStatusManager.getInstance().connect() # push a telemetry signal that a client is loading TelemetryManager.getInstance().setSignal("lifecycle","loading") TelemetryManager.getInstance().setSignal("session","not-logged-in") # authenticate defered, the isAuthed check must stay here so we can # clear the token in the event it is stale / isAuthed fails # the App._authenticationPromise below does not fire if there's no loading App._authenticationPromise = () -> return Session.isAuthenticated(Storage.get('token')) .then (isAuthed) -> if !isAuthed Storage.remove('token') return isAuthed # VIEW/engine needs to be setup and cocos manages its own setup so we need to wait async Logger.module("APPLICATION").group("LOADING") App._loadingPromise = Scene.setup().then(() -> # update last resolution values to initial App._updateLastResolutionValues() # setup all events App.bindEvents() # load the package of resources that should always loaded return PackageManager.getInstance().loadPackage("alwaysloaded") ).then(() -> # temporary bypass all loader return Promise.resolve() # check if all assets should be loaded now or as needed # we want to know if the client has cached all resources for this version # we only care when not using the desktop client, on the production environment, and not loading all at start # if we need to cache all resources for this version, do a non allocating cache load first version_preloaded = Storage.get("version_preloaded") needs_non_allocating_cache_load = version_preloaded != process.env.VERSION && !window.isDesktop && !CONFIG.LOAD_ALL_AT_START && UtilsEnv.getIsInProduction() needs_non_allocating_cache_load = needs_non_allocating_cache_load && !App._queryStringParams['replayId']? if needs_non_allocating_cache_load || CONFIG.LOAD_ALL_AT_START # temporarily force disable the load all at start flag # this allows the preloader to setup as a major package # so that it gets loaded correctly before we load all load_all_at_start = CONFIG.LOAD_ALL_AT_START CONFIG.LOAD_ALL_AT_START = false # load preloader scene to show load of all resources return PackageManager.getInstance().loadAndActivateMajorPackage("preloader", null, null, () -> # reset load all at start flag CONFIG.LOAD_ALL_AT_START = load_all_at_start # hide loading dialog NavigationManager.getInstance().destroyDialogForLoad() # show load ui viewPromise = Scene.getInstance().showLoad() contentPromise = NavigationManager.getInstance().showContentView(new LoaderItemView()) # once we've authenticated, show utility for loading/login # this way users can quit anytime on desktop, and logout or adjust settings while waiting for load App._authenticationPromise().then (isAuthed) -> if App.getIsLoggedIn() or window.isDesktop return NavigationManager.getInstance().showUtilityView(new UtilityLoadingLoginMenuItemView()) else return Promise.resolve() return Promise.all([ viewPromise, contentPromise ]) ).then(() -> # load all resources return PackageManager.getInstance().loadPackage("all", null, ((progress) -> Scene.getInstance().getLoadLayer()?.showLoadProgress(progress)), needs_non_allocating_cache_load) ).then(() -> # set version assets were preloaded for if !window.isDesktop Storage.set("version_preloaded", process.env.VERSION) ) else # no loading needed now return Promise.resolve() ).then(() -> # clear telemetry signal that a client is loading TelemetryManager.getInstance().clearSignal("lifecycle","loading") # end loading log group Logger.module("APPLICATION").groupEnd() ) # setup start promise App._startPromise = Promise.all([ App._loadingPromise, App._authenticationPromise() ]) # goto main screen App.main() # get minimum browsers from Firebase App.getMinBrowserVersions = () -> if Storage.get("skipBrowserCheck") then return Promise.resolve() return new Promise (resolve, reject) -> minBrowserVersionRef = new Firebase(process.env.FIREBASE_URL).child("system-status").child('browsers') defaults = { "Chrome": 50, "Safari": 10, "Firefox": 57, "Edge": 15 } # create a timeout to skip check in case Firebase lags (so atleast user does not get stuck on black screen) minBrowserVersionTimeout = setTimeout(() -> minBrowserVersionRef.off() resolve(defaults) , 5000) minBrowserVersionRef.once 'value', (snapshot) -> clearTimeout(minBrowserVersionTimeout) if !snapshot.val() resolve(defaults) else resolve(snapshot.val()) # check if given browser is valid when compared against list of allowed browsers App.isBrowserValid = (browserName, browserMajor, browserlist) -> if Storage.get("skipBrowserCheck") then return true if Object.keys(browserlist).includes(browserName) return parseInt(browserMajor, 10) >= browserlist[browserName] else return false App.generateBrowserHtml = (browser, version) -> if browser == 'Chrome' return """ <p><a href='http://google.com/chrome'><strong>Google Chrome</strong> #{version} or newer.</a></p> """ else if browser == 'Safari' return """ <p><a href='https://www.apple.com/safari/'><strong>Apple Safari</strong> #{version} or newer.</a></p> """ else if browser == 'Firefox' return """ <p><a href='https://www.mozilla.org/firefox/'><strong>Mozilla Firefox</strong> #{version} or newer.</a></p> """ else if browser == 'Edge' return """ <p><a href='https://www.microsoft.com/en-us/windows/microsoft-edge'><strong>Microsoft Edge</strong> #{version} or newer.</a></p> """ # show some HTML saying the current browser is not supported if browser detection fails App.browserTestFailed = (browserlist) -> html = """ <div style="margin:auto; position:absolute; height:50%; width:100%; top: 0px; bottom: 0px; font-size: 20px; color: white; text-align: center;"> <p>Looks like your current browser is not supported.</p> <p>Visit <a href='https://support.duelyst.com' style="color: gray;">our support page</a> to submit a request for assistance.</p> <br> """ # dynamically create html containing list of support browsers Object.keys(browserlist).forEach (browser) -> version = browserlist[browser] html += App.generateBrowserHtml(browser, version) html += "</div>" $("#app-preloading").css({display:"none"}) $("#app-content-region").css({margin:"auto", height:"50%", width: "50%"}) $("#app-content-region").html(html) # ensure webgl is correctly running App.glTest = () -> try canvas = document.createElement('canvas') return !! (window.WebGLRenderingContext && (canvas.getContext('webgl') || canvas.getContext('experimental-webgl'))) catch e return false App.glTestFailed = () -> if window.isDesktop html = """ <div style="margin:auto; position:absolute; height:50%; width:100%; top: 0px; bottom: 0px; font-size: 20px; color: white; text-align: center;"> <p>Looks like your video card is not supported.</p> <p>Ensure your video card drivers are up to date.</p> <p>Visit <a id='support-link' href='https://support.duelyst.com' style="color: gray;">our support page</a> to submit a request for assistance.</p> </div> """ else html = """ <div style="margin:auto; position:absolute; height:50%; width:100%; top: 0px; bottom: 0px; font-size: 20px; color: white; text-align: center;"> <p>Looks like WebGL is not enabled in your browser./p> <p>Visit the <a id='webgl-link' href='https://get.webgl.org/' style="color: gray;">WebGL test page</a> for more information.</p> <p>Visit <a id='support-link' href='https://support.duelyst.com' style="color: gray;">our support page</a> to submit a request for assistance.</p> </div> """ $("#app-preloading").css({display:"none"}) $("#app-content-region").css({margin:"auto", height:"50%", width: "50%"}) $("#app-content-region").html(html) $("#webgl-link").click (e) -> openUrl($(e.currentTarget).attr("href")) e.stopPropagation() e.preventDefault() $("#support-link").click (e) -> openUrl($(e.currentTarget).attr("href")) e.stopPropagation() e.preventDefault() # show some HTML saying they are on an old client version App.versionTestFailed = () -> if window.isDesktop html = """ <div style="margin:auto; position:absolute; height:50%; width:100%; top: 0px; bottom: 0px; font-size: 20px; color: white; text-align: center;"> <p>Looks like you are running an old version of DUELYST.</p> <p>Exit and restart DUELYST to update to the latest version.</p> <p>If you are using Steam, you may need to restart Steam before the update appears.</p> <p>Click <a id='reload-link' href='' style="color: gray;">here</a> to exit.</p> </div> """ else html = """ <div style="margin:auto; position:absolute; height:50%; width:100%; top: 0px; bottom: 0px; font-size: 20px; color: white; text-align: center;"> <p>Looks like you are running an old version of DUELYST.</p> <p>Click <a id='reload-link' href='' style="color: gray;">here</a> to refresh your browser to the latest version.</p> </div> """ $("#app-preloading").css({display:"none"}) $("#app-content-region").css({margin:"auto", height:"50%", width: "50%"}) $("#app-content-region").html(html) $("#reload-link").click (e) -> if window.isDesktop then window.quitDesktop() else location.reload() # compare if process.env.VERSION is gte >= than provided minimum version # if minimumVersion is undefined or null, we set to '0.0.0' App.isVersionValid = (minimumVersion) -> Logger.module("APPLICATION").log "#{process.env.VERSION} >= #{minimumVersion || '0.0.0'}" if App._queryStringParams["replayId"] return true else try return semver.gte(process.env.VERSION, minimumVersion || '0.0.0') catch e return true # App.setup is the main entry function into Marionette app # grabs configuration from server we're running on and call App.start() App.setup = () -> # mark all requests with buld version $.ajaxSetup headers: "Client-Version": process.env.VERSION # check if it is a new user and we should redirect otherwise start as normal if Landing.isNewUser() && Landing.shouldRedirect() Landing.redirect() else App.start() # # ---- Application Start Sequence ---- # # App.getMinBrowserVersions() .then (browserlist) -> if !App.isBrowserValid(userAgent.browser.name, userAgent.browser.major, browserlist) return App.browserTestFailed(browserlist) if !App.glTest() return App.glTestFailed() if window.isSteam App.minVersionRef = new Firebase(process.env.FIREBASE_URL).child("system-status").child('steam_minimum_version') else App.minVersionRef = new Firebase(process.env.FIREBASE_URL).child("system-status").child('minimum_version') # wrap App.setup() in _.once() just to be safe from double calling App.setupOnce = _.once(App.setup) # create a timeout to skip version check in case Firebase lags (so atleast user does not get stuck on black screen) App.versionCheckTimeout = setTimeout(() -> App.minVersionRef.off() App.setupOnce() , 5000) # read minimum version from Firebase and perform check, if fails, show error html # otherwise start application as normal App.minVersionRef.once('value', (snapshot) -> clearTimeout(App.versionCheckTimeout) if !App.isVersionValid(snapshot.val()) App.versionTestFailed() else App.setupOnce() )
[ { "context": "leoverview enforce a maximum file length\n# @author Alberto Rodríguez\n###\n'use strict'\n\n#------------------------------", "end": 78, "score": 0.9998608827590942, "start": 61, "tag": "NAME", "value": "Alberto Rodríguez" } ]
src/tests/rules/max-lines.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview enforce a maximum file length # @author Alberto Rodríguez ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/max-lines' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ###* # Returns the error message with the specified max number of lines # @param {number} limitLines Maximum number of lines # @param {number} actualLines Actual number of lines # @returns {string} error message ### errorMessage = (limitLines, actualLines) -> "File has too many lines (#{actualLines}). Maximum allowed is #{limitLines}." ruleTester.run 'max-lines', rule, valid: [ 'x' ''' xy xy ''' , code: ''' xy xy ''' options: [2] , code: ''' xy xy ''' options: [max: 2] , code: ''' #a single line comment xy xy ### a multiline really really long comment### ''' options: [max: 2, skipComments: yes] , code: ''' x y, ### inline comment spanning multiple lines ### z ''' options: [max: 2, skipComments: yes] , code: ''' x ### inline comment spanning multiple lines ### z ''' options: [max: 2, skipComments: yes] , code: ''' x \t \t y ''' options: [max: 2, skipBlankLines: yes] , code: ''' #a single line comment xy xy ### a multiline really really long comment### ''' options: [max: 2, skipComments: yes, skipBlankLines: yes] ] invalid: [ code: ''' xyz xyz xyz ''' options: [2] errors: [message: errorMessage 2, 3] , code: ''' ### a multiline comment that goes to many lines### xy xy ''' options: [2] errors: [message: errorMessage 2, 4] , code: ''' #a single line comment xy xy ''' options: [2] errors: [message: errorMessage 2, 3] , code: ''' x y ''' options: [max: 2] errors: [message: errorMessage 2, 5] , code: ''' #a single line comment xy xy ### a multiline really really long comment### ''' options: [max: 2, skipComments: yes] errors: [message: errorMessage 2, 4] , code: ''' x # inline comment y z ''' options: [max: 2, skipComments: yes] errors: [message: errorMessage 2, 3] , code: ''' x ### inline comment spanning multiple lines ### y z ''' options: [max: 2, skipComments: yes] errors: [message: errorMessage 2, 3] , code: ''' #a single line comment xy xy ### a multiline really really long comment### ''' options: [max: 2, skipBlankLines: yes] errors: [message: errorMessage 2, 6] ]
217937
###* # @fileoverview enforce a maximum file length # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/max-lines' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ###* # Returns the error message with the specified max number of lines # @param {number} limitLines Maximum number of lines # @param {number} actualLines Actual number of lines # @returns {string} error message ### errorMessage = (limitLines, actualLines) -> "File has too many lines (#{actualLines}). Maximum allowed is #{limitLines}." ruleTester.run 'max-lines', rule, valid: [ 'x' ''' xy xy ''' , code: ''' xy xy ''' options: [2] , code: ''' xy xy ''' options: [max: 2] , code: ''' #a single line comment xy xy ### a multiline really really long comment### ''' options: [max: 2, skipComments: yes] , code: ''' x y, ### inline comment spanning multiple lines ### z ''' options: [max: 2, skipComments: yes] , code: ''' x ### inline comment spanning multiple lines ### z ''' options: [max: 2, skipComments: yes] , code: ''' x \t \t y ''' options: [max: 2, skipBlankLines: yes] , code: ''' #a single line comment xy xy ### a multiline really really long comment### ''' options: [max: 2, skipComments: yes, skipBlankLines: yes] ] invalid: [ code: ''' xyz xyz xyz ''' options: [2] errors: [message: errorMessage 2, 3] , code: ''' ### a multiline comment that goes to many lines### xy xy ''' options: [2] errors: [message: errorMessage 2, 4] , code: ''' #a single line comment xy xy ''' options: [2] errors: [message: errorMessage 2, 3] , code: ''' x y ''' options: [max: 2] errors: [message: errorMessage 2, 5] , code: ''' #a single line comment xy xy ### a multiline really really long comment### ''' options: [max: 2, skipComments: yes] errors: [message: errorMessage 2, 4] , code: ''' x # inline comment y z ''' options: [max: 2, skipComments: yes] errors: [message: errorMessage 2, 3] , code: ''' x ### inline comment spanning multiple lines ### y z ''' options: [max: 2, skipComments: yes] errors: [message: errorMessage 2, 3] , code: ''' #a single line comment xy xy ### a multiline really really long comment### ''' options: [max: 2, skipBlankLines: yes] errors: [message: errorMessage 2, 6] ]
true
###* # @fileoverview enforce a maximum file length # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/max-lines' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ###* # Returns the error message with the specified max number of lines # @param {number} limitLines Maximum number of lines # @param {number} actualLines Actual number of lines # @returns {string} error message ### errorMessage = (limitLines, actualLines) -> "File has too many lines (#{actualLines}). Maximum allowed is #{limitLines}." ruleTester.run 'max-lines', rule, valid: [ 'x' ''' xy xy ''' , code: ''' xy xy ''' options: [2] , code: ''' xy xy ''' options: [max: 2] , code: ''' #a single line comment xy xy ### a multiline really really long comment### ''' options: [max: 2, skipComments: yes] , code: ''' x y, ### inline comment spanning multiple lines ### z ''' options: [max: 2, skipComments: yes] , code: ''' x ### inline comment spanning multiple lines ### z ''' options: [max: 2, skipComments: yes] , code: ''' x \t \t y ''' options: [max: 2, skipBlankLines: yes] , code: ''' #a single line comment xy xy ### a multiline really really long comment### ''' options: [max: 2, skipComments: yes, skipBlankLines: yes] ] invalid: [ code: ''' xyz xyz xyz ''' options: [2] errors: [message: errorMessage 2, 3] , code: ''' ### a multiline comment that goes to many lines### xy xy ''' options: [2] errors: [message: errorMessage 2, 4] , code: ''' #a single line comment xy xy ''' options: [2] errors: [message: errorMessage 2, 3] , code: ''' x y ''' options: [max: 2] errors: [message: errorMessage 2, 5] , code: ''' #a single line comment xy xy ### a multiline really really long comment### ''' options: [max: 2, skipComments: yes] errors: [message: errorMessage 2, 4] , code: ''' x # inline comment y z ''' options: [max: 2, skipComments: yes] errors: [message: errorMessage 2, 3] , code: ''' x ### inline comment spanning multiple lines ### y z ''' options: [max: 2, skipComments: yes] errors: [message: errorMessage 2, 3] , code: ''' #a single line comment xy xy ### a multiline really really long comment### ''' options: [max: 2, skipBlankLines: yes] errors: [message: errorMessage 2, 6] ]
[ { "context": "#\n# Author: Corey Auger\n# corey@nxtwv.com\n#\n\nwebrtcApp = window.angular.m", "end": 23, "score": 0.9998880624771118, "start": 12, "tag": "NAME", "value": "Corey Auger" }, { "context": "#\n# Author: Corey Auger\n# corey@nxtwv.com\n#\n\nwebrtcApp = window.angular.module('webrtcApp',", "end": 41, "score": 0.9999305009841919, "start": 26, "tag": "EMAIL", "value": "corey@nxtwv.com" } ]
app/assets/javascripts/app.coffee
coreyauger/play-webrtc
18
# # Author: Corey Auger # corey@nxtwv.com # webrtcApp = window.angular.module('webrtcApp', ['ngRoute','ngSanitize','ui.bootstrap','webrtcControllers']).config( ($sceDelegateProvider) -> $sceDelegateProvider.resourceUrlWhitelist( [ 'self' # Allow loading from outer templates domain. 'https://apps.com/**' ] ) ) webrtcApp.config(($locationProvider,$routeProvider) -> # $locationProvider.html5Mode(true); $routeProvider.when('/home', templateUrl: '/assets/partials/home.html', controller: 'HomeCtrl' ).when('/room/:room/:members', templateUrl: '/assets/partials/room.html', controller: 'RoomCtrl' ).otherwise({ redirectTo: '/home' }) ) webrtcApp.run(($rootScope, $location, worker, $modal, $sce) -> $rootScope.page = header: 'nav' title: 'test' online: true error: '' $rootScope.webrtc = support: DetectRTC $rootScope.detect = window.DetectRTC window.addEventListener('online', -> $rootScope.page.online = true $rootScope.page.error = '' setTimeout(-> $rootScope.$apply() ,0) ) window.addEventListener('offline', -> $rootScope.page.online = false $rootScope.page.error = 'You have gone <strong>offline</strong>' setTimeout(-> $rootScope.$apply() ,0) ) ) webrtcApp.directive('errSrc', -> link: (scope, element, attrs) -> element.bind('error', -> element.attr('src', attrs.errSrc) ) )
27358
# # Author: <NAME> # <EMAIL> # webrtcApp = window.angular.module('webrtcApp', ['ngRoute','ngSanitize','ui.bootstrap','webrtcControllers']).config( ($sceDelegateProvider) -> $sceDelegateProvider.resourceUrlWhitelist( [ 'self' # Allow loading from outer templates domain. 'https://apps.com/**' ] ) ) webrtcApp.config(($locationProvider,$routeProvider) -> # $locationProvider.html5Mode(true); $routeProvider.when('/home', templateUrl: '/assets/partials/home.html', controller: 'HomeCtrl' ).when('/room/:room/:members', templateUrl: '/assets/partials/room.html', controller: 'RoomCtrl' ).otherwise({ redirectTo: '/home' }) ) webrtcApp.run(($rootScope, $location, worker, $modal, $sce) -> $rootScope.page = header: 'nav' title: 'test' online: true error: '' $rootScope.webrtc = support: DetectRTC $rootScope.detect = window.DetectRTC window.addEventListener('online', -> $rootScope.page.online = true $rootScope.page.error = '' setTimeout(-> $rootScope.$apply() ,0) ) window.addEventListener('offline', -> $rootScope.page.online = false $rootScope.page.error = 'You have gone <strong>offline</strong>' setTimeout(-> $rootScope.$apply() ,0) ) ) webrtcApp.directive('errSrc', -> link: (scope, element, attrs) -> element.bind('error', -> element.attr('src', attrs.errSrc) ) )
true
# # Author: PI:NAME:<NAME>END_PI # PI:EMAIL:<EMAIL>END_PI # webrtcApp = window.angular.module('webrtcApp', ['ngRoute','ngSanitize','ui.bootstrap','webrtcControllers']).config( ($sceDelegateProvider) -> $sceDelegateProvider.resourceUrlWhitelist( [ 'self' # Allow loading from outer templates domain. 'https://apps.com/**' ] ) ) webrtcApp.config(($locationProvider,$routeProvider) -> # $locationProvider.html5Mode(true); $routeProvider.when('/home', templateUrl: '/assets/partials/home.html', controller: 'HomeCtrl' ).when('/room/:room/:members', templateUrl: '/assets/partials/room.html', controller: 'RoomCtrl' ).otherwise({ redirectTo: '/home' }) ) webrtcApp.run(($rootScope, $location, worker, $modal, $sce) -> $rootScope.page = header: 'nav' title: 'test' online: true error: '' $rootScope.webrtc = support: DetectRTC $rootScope.detect = window.DetectRTC window.addEventListener('online', -> $rootScope.page.online = true $rootScope.page.error = '' setTimeout(-> $rootScope.$apply() ,0) ) window.addEventListener('offline', -> $rootScope.page.online = false $rootScope.page.error = 'You have gone <strong>offline</strong>' setTimeout(-> $rootScope.$apply() ,0) ) ) webrtcApp.directive('errSrc', -> link: (scope, element, attrs) -> element.bind('error', -> element.attr('src', attrs.errSrc) ) )
[ { "context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @", "end": 33, "score": 0.9998952150344849, "start": 17, "tag": "NAME", "value": "Abdelhakim RAFIK" }, { "context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhakim RAFIK\n * @date \t\tJune 2021\n###\n\n\nmodule.exports = (role", "end": 129, "score": 0.999893069267273, "start": 113, "tag": "NAME", "value": "Abdelhakim RAFIK" } ]
src/app/middlewares/roleMiddleware.coffee
AbdelhakimRafik/Project
1
### * @author Abdelhakim RAFIK * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 Abdelhakim RAFIK * @date June 2021 ### module.exports = (roles) -> return (req, res, next) -> # check user roles is in allowed roles if (typeof roles == 'string' and req.user.role != roles) or not roles.includes req.user.role res.status(403).json message: 'Access denied' else do next
101620
### * @author <NAME> * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 <NAME> * @date June 2021 ### module.exports = (roles) -> return (req, res, next) -> # check user roles is in allowed roles if (typeof roles == 'string' and req.user.role != roles) or not roles.includes req.user.role res.status(403).json message: 'Access denied' else do next
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 ### module.exports = (roles) -> return (req, res, next) -> # check user roles is in allowed roles if (typeof roles == 'string' and req.user.role != roles) or not roles.includes req.user.role res.status(403).json message: 'Access denied' else do next
[ { "context": " endpoint += if NODE_ENV is 'development' then '72.89.161.100' else ip\n request\n .get endpoint\n .e", "end": 315, "score": 0.9997092485427856, "start": 302, "tag": "IP_ADDRESS", "value": "72.89.161.100" } ]
src/desktop/apps/geo/routes.coffee
jpoczik/force
377
_ = require 'underscore' geolib = require 'geolib' request = require 'superagent' { Cities } = require 'places' { NODE_ENV, GEOIP_ENDPOINT } = require '../../../config' geoIP = (ip) -> new Promise (resolve, reject) -> endpoint = GEOIP_ENDPOINT endpoint += if NODE_ENV is 'development' then '72.89.161.100' else ip request .get endpoint .end (err, response) -> return reject err if err? resolve response.body @ip = (req, res, next) -> geoIP req.ip .then res.send.bind(res) .catch next @nearest = (req, res, next) -> cities = Cities.map (city) -> city.latitude = city.coords[0] city.longitude = city.coords[1] city geoIP req.ip .then (you) -> geolib.findNearest you, cities .then (nearest) -> yourCity = _.findWhere cities, _.pick(nearest, 'latitude', 'longitude') res.send _.extend nearest, yourCity .catch next
168826
_ = require 'underscore' geolib = require 'geolib' request = require 'superagent' { Cities } = require 'places' { NODE_ENV, GEOIP_ENDPOINT } = require '../../../config' geoIP = (ip) -> new Promise (resolve, reject) -> endpoint = GEOIP_ENDPOINT endpoint += if NODE_ENV is 'development' then '192.168.127.12' else ip request .get endpoint .end (err, response) -> return reject err if err? resolve response.body @ip = (req, res, next) -> geoIP req.ip .then res.send.bind(res) .catch next @nearest = (req, res, next) -> cities = Cities.map (city) -> city.latitude = city.coords[0] city.longitude = city.coords[1] city geoIP req.ip .then (you) -> geolib.findNearest you, cities .then (nearest) -> yourCity = _.findWhere cities, _.pick(nearest, 'latitude', 'longitude') res.send _.extend nearest, yourCity .catch next
true
_ = require 'underscore' geolib = require 'geolib' request = require 'superagent' { Cities } = require 'places' { NODE_ENV, GEOIP_ENDPOINT } = require '../../../config' geoIP = (ip) -> new Promise (resolve, reject) -> endpoint = GEOIP_ENDPOINT endpoint += if NODE_ENV is 'development' then 'PI:IP_ADDRESS:192.168.127.12END_PI' else ip request .get endpoint .end (err, response) -> return reject err if err? resolve response.body @ip = (req, res, next) -> geoIP req.ip .then res.send.bind(res) .catch next @nearest = (req, res, next) -> cities = Cities.map (city) -> city.latitude = city.coords[0] city.longitude = city.coords[1] city geoIP req.ip .then (you) -> geolib.findNearest you, cities .then (nearest) -> yourCity = _.findWhere cities, _.pick(nearest, 'latitude', 'longitude') res.send _.extend nearest, yourCity .catch next
[ { "context": " 'Default'\n enum: [\n \"3024\"\n \"Apathy\"\n \"Ashes\"\n \"Atelier Cave\"\n \"", "end": 123, "score": 0.7871922254562378, "start": 118, "tag": "NAME", "value": "pathy" }, { "context": "num: [\n \"3024\"\n \"Apathy\"\n \"Ashes\"\n \"Atelier Cave\"\n \"Atelier Dune\"\n ", "end": 139, "score": 0.6425122022628784, "start": 136, "tag": "NAME", "value": "hes" }, { "context": " \"3024\"\n \"Apathy\"\n \"Ashes\"\n \"Atelier Cave\"\n \"Atelier Dune\"\n \"Atelier Estuary\"", "end": 162, "score": 0.9088155627250671, "start": 150, "tag": "NAME", "value": "Atelier Cave" }, { "context": "\"\n \"Ashes\"\n \"Atelier Cave\"\n \"Atelier Dune\"\n \"Atelier Estuary\"\n \"Atelier Fores", "end": 185, "score": 0.9058810472488403, "start": 173, "tag": "NAME", "value": "Atelier Dune" }, { "context": "lier Cave\"\n \"Atelier Dune\"\n \"Atelier Estuary\"\n \"Atelier Forest\"\n \"Atelier He", "end": 207, "score": 0.5062707662582397, "start": 204, "tag": "NAME", "value": "Est" }, { "context": "lier Dune\"\n \"Atelier Estuary\"\n \"Atelier Forest\"\n \"Atelier Heath\"\n \"Atelier Lakesid", "end": 236, "score": 0.6082956194877625, "start": 226, "tag": "NAME", "value": "ier Forest" }, { "context": "telier Estuary\"\n \"Atelier Forest\"\n \"Atelier Heath\"\n \"Atelier Lakeside\"\n \"Atelier Plat", "end": 260, "score": 0.8307415843009949, "start": 247, "tag": "NAME", "value": "Atelier Heath" }, { "context": "\"Atelier Forest\"\n \"Atelier Heath\"\n \"Atelier Lakeside\"\n \"Atelier Plateau\"\n \"Atelier Savan", "end": 287, "score": 0.8250005841255188, "start": 271, "tag": "NAME", "value": "Atelier Lakeside" }, { "context": "telier Heath\"\n \"Atelier Lakeside\"\n \"Atelier Plateau\"\n \"Atelier Savanna\"\n \"Atelier Seasi", "end": 313, "score": 0.908604085445404, "start": 298, "tag": "NAME", "value": "Atelier Plateau" }, { "context": "lier Lakeside\"\n \"Atelier Plateau\"\n \"Atelier Savanna\"\n \"Atelier Seaside\"\n \"Atelier Sulph", "end": 339, "score": 0.9657397270202637, "start": 324, "tag": "NAME", "value": "Atelier Savanna" }, { "context": "elier Savanna\"\n \"Atelier Seaside\"\n \"Atelier Sulphurpool\"\n \"Bespin\"\n \"Brewer\"\n \"Brigh", "end": 395, "score": 0.9292258620262146, "start": 376, "tag": "NAME", "value": "Atelier Sulphurpool" }, { "context": " Seaside\"\n \"Atelier Sulphurpool\"\n \"Bespin\"\n \"Brewer\"\n \"Bright\"\n \"Chalk", "end": 412, "score": 0.7070351839065552, "start": 407, "tag": "NAME", "value": "espin" } ]
lib/base16-settings.coffee
danielrsilver/base16-syntax
34
settings = config: scheme: type: 'string' default: 'Default' enum: [ "3024" "Apathy" "Ashes" "Atelier Cave" "Atelier Dune" "Atelier Estuary" "Atelier Forest" "Atelier Heath" "Atelier Lakeside" "Atelier Plateau" "Atelier Savanna" "Atelier Seaside" "Atelier Sulphurpool" "Bespin" "Brewer" "Bright" "Chalk" "Codeschool" "Colors" "Darktooth" "Default" "Eighties" "Embers" "Flat" "GitHub" "Google" "Grayscale" "Greenscreen" "Harmonic" "Hopscotch" "Irblack" "Isotope" "Macintosh" "Marrakesh" "Materia" "Mocha" "Monokai" "Ocean" "OceanicNext" "OneDark" "Paraiso" "PhD" "Pico" "Pop" "Railscasts" "Rebecca" "Seti" "Shapeshifter" "Solarflare" "Solarized" "Spacemacs" "Summerfruit" "Tomorrow" "Tube" "Twilight" "Unikitty" "Yesterday Bright" "Yesterday Night" "Yesterday" ] style: type: 'string' default: 'Dark' enum: ["Dark", "Light"] matchUserInterfaceTheme: type: 'boolean' default: true description: "When enabled the style will be matched to the current UI theme by default." module.exports = settings
145033
settings = config: scheme: type: 'string' default: 'Default' enum: [ "3024" "A<NAME>" "As<NAME>" "<NAME>" "<NAME>" "Atelier <NAME>uary" "Atel<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "Atelier Seaside" "<NAME>" "B<NAME>" "Brewer" "Bright" "Chalk" "Codeschool" "Colors" "Darktooth" "Default" "Eighties" "Embers" "Flat" "GitHub" "Google" "Grayscale" "Greenscreen" "Harmonic" "Hopscotch" "Irblack" "Isotope" "Macintosh" "Marrakesh" "Materia" "Mocha" "Monokai" "Ocean" "OceanicNext" "OneDark" "Paraiso" "PhD" "Pico" "Pop" "Railscasts" "Rebecca" "Seti" "Shapeshifter" "Solarflare" "Solarized" "Spacemacs" "Summerfruit" "Tomorrow" "Tube" "Twilight" "Unikitty" "Yesterday Bright" "Yesterday Night" "Yesterday" ] style: type: 'string' default: 'Dark' enum: ["Dark", "Light"] matchUserInterfaceTheme: type: 'boolean' default: true description: "When enabled the style will be matched to the current UI theme by default." module.exports = settings
true
settings = config: scheme: type: 'string' default: 'Default' enum: [ "3024" "API:NAME:<NAME>END_PI" "AsPI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "Atelier PI:NAME:<NAME>END_PIuary" "AtelPI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "Atelier Seaside" "PI:NAME:<NAME>END_PI" "BPI:NAME:<NAME>END_PI" "Brewer" "Bright" "Chalk" "Codeschool" "Colors" "Darktooth" "Default" "Eighties" "Embers" "Flat" "GitHub" "Google" "Grayscale" "Greenscreen" "Harmonic" "Hopscotch" "Irblack" "Isotope" "Macintosh" "Marrakesh" "Materia" "Mocha" "Monokai" "Ocean" "OceanicNext" "OneDark" "Paraiso" "PhD" "Pico" "Pop" "Railscasts" "Rebecca" "Seti" "Shapeshifter" "Solarflare" "Solarized" "Spacemacs" "Summerfruit" "Tomorrow" "Tube" "Twilight" "Unikitty" "Yesterday Bright" "Yesterday Night" "Yesterday" ] style: type: 'string' default: 'Dark' enum: ["Dark", "Light"] matchUserInterfaceTheme: type: 'boolean' default: true description: "When enabled the style will be matched to the current UI theme by default." module.exports = settings
[ { "context": "uestheader(\"Origin\",\"http://kaosat-dev.github.com/CoffeeSCad/\")\n request.send(params)\n \n consol", "end": 1441, "score": 0.6974589824676514, "start": 1431, "tag": "USERNAME", "value": "CoffeeSCad" }, { "context": "tate == 2\n @tokenUrl = \"https://github.com/login/oauth/access_token\"\n params = \"client_id=#", "end": 2031, "score": 0.9025071263313293, "start": 2026, "tag": "USERNAME", "value": "login" }, { "context": " params = \"client_id=#{@client_id}&client_secret=mlkmlk&code=#{code}\"\n console.log \"sending code r", "end": 2114, "score": 0.9194120168685913, "start": 2108, "tag": "KEY", "value": "mlkmlk" }, { "context": ",params)\n #@tokenUrl = \"https://github.com/login/oauth/access_token?client_id=#{@client_id}&client", "end": 2306, "score": 0.7248899936676025, "start": 2301, "tag": "USERNAME", "value": "login" }, { "context": " ###\n @github = new Github\n token: \"OAUTH_TOKEN\"\n auth: \"oauth\"\n ### \n authentifi", "end": 2971, "score": 0.9408875703811646, "start": 2960, "tag": "PASSWORD", "value": "OAUTH_TOKEN" }, { "context": " ###@client = new Dropbox.Client \n key: \"h8OY5h+ah3A=|AS0FmmbZJrmc8/QbpU6lMzrCd5lSGZPCKVtjMlA7ZA==\"\n sandbox: true\n ###\n #@client.au", "end": 3142, "score": 0.9996522068977356, "start": 3084, "tag": "KEY", "value": "h8OY5h+ah3A=|AS0FmmbZJrmc8/QbpU6lMzrCd5lSGZPCKVtjMlA7ZA==\"" } ]
src/app/stores/github/gitHubStore.coffee
kaosat-dev/CoffeeSCad
110
define (require)-> github = require 'github' vent = require 'core/messaging/appVent' Project = require 'core/projects/project' class GitHubRedirectDriver constructor:-> @state=1 #initial @client_id = "c346489dcec8041bd88f" @redirect_uri=window.location @scopes = "gist" @authUrl = "https://github.com/login/oauth/authorize?client_id=#{@client_id}&redirect_uri=#{window.location}&scope=#{@scopes}" getURLParameter:(paramName)-> searchString = window.location.search.substring(1) i = undefined val = undefined params = searchString.split("&") i = 0 while i < params.length val = params[i].split("=") return unescape(val[1]) if val[0] is paramName i++ null postStuff:(url, params)-> params = encodeURIComponent(params) console.log "params"+params request = new XMLHttpRequest() request.open('get', url, true) if ("withCredentials" in request) console.log "cors supported" request.onreadystatechange = => #Call a function when the state changes. console.log "toto"+request.readyState alert request.responseText if request.readyState is 4 and request.status is 200 request.setRequestHeader("Content-type", "application/x-www-form-urlencoded") request.setRequestheader("Origin","http://kaosat-dev.github.com/CoffeeSCad/") request.send(params) console.log "request" console.log request postJsonP:(url,params)-> foo=(response)-> meta = response.meta data = response.data console.log(meta) console.log(data) run:-> code = @getURLParameter("code") if code? @state=2 console.log("github:phase2") if @state == 1 console.log "gihub auth url #{@authUrl}" console.log "redirecting" window.location.href = @authUrl if @state == 2 @tokenUrl = "https://github.com/login/oauth/access_token" params = "client_id=#{@client_id}&client_secret=mlkmlk&code=#{code}" console.log "sending code request to url #{@tokenUrl} with params #{params}" @postStuff(@tokenUrl,params) #@tokenUrl = "https://github.com/login/oauth/access_token?client_id=#{@client_id}&client_secret=&code=#{code}" #@postStuff(@tokenUrl,"") foo=(response)-> console.log "jsonp response" console.log response ### $.ajax type: "GET" url: @tokenUrl data: null jsonpCallback: 'foo' success: (r)->console.log "github auth phase 2 ok : #{r}" error:(e)->console.log "aie aie error #{e.message}" dataType: 'jsonp' ### class GitHubStore constructor:-> @driver= new GitHubRedirectDriver() ### @github = new Github token: "OAUTH_TOKEN" auth: "oauth" ### authentificate:()=> ###@client = new Dropbox.Client key: "h8OY5h+ah3A=|AS0FmmbZJrmc8/QbpU6lMzrCd5lSGZPCKVtjMlA7ZA==" sandbox: true ### #@client.authDriver new Dropbox.Drivers.Redirect(rememberUser:true, useQuery:true) @driver.run() console.log "here" d = $.Deferred() ### @client.authenticate (error, client)=> console.log "in auth" console.log error console.log client if error? d.reject(@formatError(error)) d.resolve(error) ### return d.promise() sync:()-> class GitHubLibrary extends Backbone.Collection """ a library contains multiple projects, stored on github """ model: Project #sync: backbone_github.sync path: "" defaults: recentProjects: [] constructor:(options)-> super options #@bind("reset", @onReset) comparator: (project)-> date = new Date(project.get('lastModificationDate')) return date.getTime() onReset:()-> console.log "GitHubLibrary reset" console.log @ console.log "_____________" class GitHubStore extends Backbone.Model defaults: name: "gitHubStore" storeType: "gitHub" constructor:(options)-> super options @store = new GitHubStore() @isLogginRequired = true @loggedIn = true @vent = vent @vent.on("gitHubStore:login", @login) @vent.on("gitHubStore:logout", @logout) #experimental @lib = new GitHubLibrary sync: @store.sync @lib.sync = @store.sync login:=> console.log "login requested" try onLoginSucceeded=()=> console.log "github logged in" localStorage.setItem("githubCon-auth",true) @loggedIn = true @vent.trigger("gitHubStore:loggedIn") onLoginFailed=(error)=> console.log "github loggin failed" throw error loginPromise = @store.authentificate() $.when(loginPromise).done(onLoginSucceeded) .fail(onLoginFailed) #@lib.fetch() catch error @vent.trigger("gitHubStore:loginFailed") logout:=> try onLogoutSucceeded=()=> console.log "github logged out" localStorage.removeItem("githubCon-auth") @loggedIn = false @vent.trigger("gitHubStore:loggedOut") onLoginFailed=(error)=> console.log "github logout failed" throw error logoutPromise = @store.signOut() $.when(logoutPromise).done(onLogoutSucceeded) .fail(onLogoutFailed) catch error @vent.trigger("gitHubStore:logoutFailed") authCheck:()-> getURLParameter=(paramName)-> searchString = window.location.search.substring(1) i = undefined val = undefined params = searchString.split("&") i = 0 while i < params.length val = params[i].split("=") return unescape(val[1]) if val[0] is paramName i++ null urlAuthOk = getURLParameter("code") console.log "githubStore got redirect param #{urlAuthOk}" authOk = localStorage.getItem("githubCon-auth") console.log "githubStore got localstorage Param #{authOk}" if urlAuthOk? @login() window.history.replaceState('', '', '/') else if authOk? @login() createProject:(options)=> project = @lib.create(options) project.createFile name: project.get("name") project.createFile name: "config" saveProject:(project)=> @lib.add(project) project.sync=@store.sync project.pathRoot=project.get("name") #fakeCollection = new Backbone.Collection() #fakeCollection.sync = @store.sync #fakeCollection.path = project.get("name") #fakeCollection.add(project) project.pfiles.sync = @store.sync project.pfiles.path = project.get("name") for index, file of project.pfiles.models file.sync = @store.sync file.pathRoot= project.get("name") file.save() #project.save() @vent.trigger("project:saved") loadProject:(projectName)=> console.log "github loading project #{projectName}" project =@lib.get(projectName) console.log "loaded:" console.log project getProjectsName:(callback)=> #hack @store.client.readdir "/", (error, entries) -> if error console.log ("error") else console.log entries callback(entries) return GitHubStore
154703
define (require)-> github = require 'github' vent = require 'core/messaging/appVent' Project = require 'core/projects/project' class GitHubRedirectDriver constructor:-> @state=1 #initial @client_id = "c346489dcec8041bd88f" @redirect_uri=window.location @scopes = "gist" @authUrl = "https://github.com/login/oauth/authorize?client_id=#{@client_id}&redirect_uri=#{window.location}&scope=#{@scopes}" getURLParameter:(paramName)-> searchString = window.location.search.substring(1) i = undefined val = undefined params = searchString.split("&") i = 0 while i < params.length val = params[i].split("=") return unescape(val[1]) if val[0] is paramName i++ null postStuff:(url, params)-> params = encodeURIComponent(params) console.log "params"+params request = new XMLHttpRequest() request.open('get', url, true) if ("withCredentials" in request) console.log "cors supported" request.onreadystatechange = => #Call a function when the state changes. console.log "toto"+request.readyState alert request.responseText if request.readyState is 4 and request.status is 200 request.setRequestHeader("Content-type", "application/x-www-form-urlencoded") request.setRequestheader("Origin","http://kaosat-dev.github.com/CoffeeSCad/") request.send(params) console.log "request" console.log request postJsonP:(url,params)-> foo=(response)-> meta = response.meta data = response.data console.log(meta) console.log(data) run:-> code = @getURLParameter("code") if code? @state=2 console.log("github:phase2") if @state == 1 console.log "gihub auth url #{@authUrl}" console.log "redirecting" window.location.href = @authUrl if @state == 2 @tokenUrl = "https://github.com/login/oauth/access_token" params = "client_id=#{@client_id}&client_secret=<KEY>&code=#{code}" console.log "sending code request to url #{@tokenUrl} with params #{params}" @postStuff(@tokenUrl,params) #@tokenUrl = "https://github.com/login/oauth/access_token?client_id=#{@client_id}&client_secret=&code=#{code}" #@postStuff(@tokenUrl,"") foo=(response)-> console.log "jsonp response" console.log response ### $.ajax type: "GET" url: @tokenUrl data: null jsonpCallback: 'foo' success: (r)->console.log "github auth phase 2 ok : #{r}" error:(e)->console.log "aie aie error #{e.message}" dataType: 'jsonp' ### class GitHubStore constructor:-> @driver= new GitHubRedirectDriver() ### @github = new Github token: "<PASSWORD>" auth: "oauth" ### authentificate:()=> ###@client = new Dropbox.Client key: "<KEY> sandbox: true ### #@client.authDriver new Dropbox.Drivers.Redirect(rememberUser:true, useQuery:true) @driver.run() console.log "here" d = $.Deferred() ### @client.authenticate (error, client)=> console.log "in auth" console.log error console.log client if error? d.reject(@formatError(error)) d.resolve(error) ### return d.promise() sync:()-> class GitHubLibrary extends Backbone.Collection """ a library contains multiple projects, stored on github """ model: Project #sync: backbone_github.sync path: "" defaults: recentProjects: [] constructor:(options)-> super options #@bind("reset", @onReset) comparator: (project)-> date = new Date(project.get('lastModificationDate')) return date.getTime() onReset:()-> console.log "GitHubLibrary reset" console.log @ console.log "_____________" class GitHubStore extends Backbone.Model defaults: name: "gitHubStore" storeType: "gitHub" constructor:(options)-> super options @store = new GitHubStore() @isLogginRequired = true @loggedIn = true @vent = vent @vent.on("gitHubStore:login", @login) @vent.on("gitHubStore:logout", @logout) #experimental @lib = new GitHubLibrary sync: @store.sync @lib.sync = @store.sync login:=> console.log "login requested" try onLoginSucceeded=()=> console.log "github logged in" localStorage.setItem("githubCon-auth",true) @loggedIn = true @vent.trigger("gitHubStore:loggedIn") onLoginFailed=(error)=> console.log "github loggin failed" throw error loginPromise = @store.authentificate() $.when(loginPromise).done(onLoginSucceeded) .fail(onLoginFailed) #@lib.fetch() catch error @vent.trigger("gitHubStore:loginFailed") logout:=> try onLogoutSucceeded=()=> console.log "github logged out" localStorage.removeItem("githubCon-auth") @loggedIn = false @vent.trigger("gitHubStore:loggedOut") onLoginFailed=(error)=> console.log "github logout failed" throw error logoutPromise = @store.signOut() $.when(logoutPromise).done(onLogoutSucceeded) .fail(onLogoutFailed) catch error @vent.trigger("gitHubStore:logoutFailed") authCheck:()-> getURLParameter=(paramName)-> searchString = window.location.search.substring(1) i = undefined val = undefined params = searchString.split("&") i = 0 while i < params.length val = params[i].split("=") return unescape(val[1]) if val[0] is paramName i++ null urlAuthOk = getURLParameter("code") console.log "githubStore got redirect param #{urlAuthOk}" authOk = localStorage.getItem("githubCon-auth") console.log "githubStore got localstorage Param #{authOk}" if urlAuthOk? @login() window.history.replaceState('', '', '/') else if authOk? @login() createProject:(options)=> project = @lib.create(options) project.createFile name: project.get("name") project.createFile name: "config" saveProject:(project)=> @lib.add(project) project.sync=@store.sync project.pathRoot=project.get("name") #fakeCollection = new Backbone.Collection() #fakeCollection.sync = @store.sync #fakeCollection.path = project.get("name") #fakeCollection.add(project) project.pfiles.sync = @store.sync project.pfiles.path = project.get("name") for index, file of project.pfiles.models file.sync = @store.sync file.pathRoot= project.get("name") file.save() #project.save() @vent.trigger("project:saved") loadProject:(projectName)=> console.log "github loading project #{projectName}" project =@lib.get(projectName) console.log "loaded:" console.log project getProjectsName:(callback)=> #hack @store.client.readdir "/", (error, entries) -> if error console.log ("error") else console.log entries callback(entries) return GitHubStore
true
define (require)-> github = require 'github' vent = require 'core/messaging/appVent' Project = require 'core/projects/project' class GitHubRedirectDriver constructor:-> @state=1 #initial @client_id = "c346489dcec8041bd88f" @redirect_uri=window.location @scopes = "gist" @authUrl = "https://github.com/login/oauth/authorize?client_id=#{@client_id}&redirect_uri=#{window.location}&scope=#{@scopes}" getURLParameter:(paramName)-> searchString = window.location.search.substring(1) i = undefined val = undefined params = searchString.split("&") i = 0 while i < params.length val = params[i].split("=") return unescape(val[1]) if val[0] is paramName i++ null postStuff:(url, params)-> params = encodeURIComponent(params) console.log "params"+params request = new XMLHttpRequest() request.open('get', url, true) if ("withCredentials" in request) console.log "cors supported" request.onreadystatechange = => #Call a function when the state changes. console.log "toto"+request.readyState alert request.responseText if request.readyState is 4 and request.status is 200 request.setRequestHeader("Content-type", "application/x-www-form-urlencoded") request.setRequestheader("Origin","http://kaosat-dev.github.com/CoffeeSCad/") request.send(params) console.log "request" console.log request postJsonP:(url,params)-> foo=(response)-> meta = response.meta data = response.data console.log(meta) console.log(data) run:-> code = @getURLParameter("code") if code? @state=2 console.log("github:phase2") if @state == 1 console.log "gihub auth url #{@authUrl}" console.log "redirecting" window.location.href = @authUrl if @state == 2 @tokenUrl = "https://github.com/login/oauth/access_token" params = "client_id=#{@client_id}&client_secret=PI:KEY:<KEY>END_PI&code=#{code}" console.log "sending code request to url #{@tokenUrl} with params #{params}" @postStuff(@tokenUrl,params) #@tokenUrl = "https://github.com/login/oauth/access_token?client_id=#{@client_id}&client_secret=&code=#{code}" #@postStuff(@tokenUrl,"") foo=(response)-> console.log "jsonp response" console.log response ### $.ajax type: "GET" url: @tokenUrl data: null jsonpCallback: 'foo' success: (r)->console.log "github auth phase 2 ok : #{r}" error:(e)->console.log "aie aie error #{e.message}" dataType: 'jsonp' ### class GitHubStore constructor:-> @driver= new GitHubRedirectDriver() ### @github = new Github token: "PI:PASSWORD:<PASSWORD>END_PI" auth: "oauth" ### authentificate:()=> ###@client = new Dropbox.Client key: "PI:KEY:<KEY>END_PI sandbox: true ### #@client.authDriver new Dropbox.Drivers.Redirect(rememberUser:true, useQuery:true) @driver.run() console.log "here" d = $.Deferred() ### @client.authenticate (error, client)=> console.log "in auth" console.log error console.log client if error? d.reject(@formatError(error)) d.resolve(error) ### return d.promise() sync:()-> class GitHubLibrary extends Backbone.Collection """ a library contains multiple projects, stored on github """ model: Project #sync: backbone_github.sync path: "" defaults: recentProjects: [] constructor:(options)-> super options #@bind("reset", @onReset) comparator: (project)-> date = new Date(project.get('lastModificationDate')) return date.getTime() onReset:()-> console.log "GitHubLibrary reset" console.log @ console.log "_____________" class GitHubStore extends Backbone.Model defaults: name: "gitHubStore" storeType: "gitHub" constructor:(options)-> super options @store = new GitHubStore() @isLogginRequired = true @loggedIn = true @vent = vent @vent.on("gitHubStore:login", @login) @vent.on("gitHubStore:logout", @logout) #experimental @lib = new GitHubLibrary sync: @store.sync @lib.sync = @store.sync login:=> console.log "login requested" try onLoginSucceeded=()=> console.log "github logged in" localStorage.setItem("githubCon-auth",true) @loggedIn = true @vent.trigger("gitHubStore:loggedIn") onLoginFailed=(error)=> console.log "github loggin failed" throw error loginPromise = @store.authentificate() $.when(loginPromise).done(onLoginSucceeded) .fail(onLoginFailed) #@lib.fetch() catch error @vent.trigger("gitHubStore:loginFailed") logout:=> try onLogoutSucceeded=()=> console.log "github logged out" localStorage.removeItem("githubCon-auth") @loggedIn = false @vent.trigger("gitHubStore:loggedOut") onLoginFailed=(error)=> console.log "github logout failed" throw error logoutPromise = @store.signOut() $.when(logoutPromise).done(onLogoutSucceeded) .fail(onLogoutFailed) catch error @vent.trigger("gitHubStore:logoutFailed") authCheck:()-> getURLParameter=(paramName)-> searchString = window.location.search.substring(1) i = undefined val = undefined params = searchString.split("&") i = 0 while i < params.length val = params[i].split("=") return unescape(val[1]) if val[0] is paramName i++ null urlAuthOk = getURLParameter("code") console.log "githubStore got redirect param #{urlAuthOk}" authOk = localStorage.getItem("githubCon-auth") console.log "githubStore got localstorage Param #{authOk}" if urlAuthOk? @login() window.history.replaceState('', '', '/') else if authOk? @login() createProject:(options)=> project = @lib.create(options) project.createFile name: project.get("name") project.createFile name: "config" saveProject:(project)=> @lib.add(project) project.sync=@store.sync project.pathRoot=project.get("name") #fakeCollection = new Backbone.Collection() #fakeCollection.sync = @store.sync #fakeCollection.path = project.get("name") #fakeCollection.add(project) project.pfiles.sync = @store.sync project.pfiles.path = project.get("name") for index, file of project.pfiles.models file.sync = @store.sync file.pathRoot= project.get("name") file.save() #project.save() @vent.trigger("project:saved") loadProject:(projectName)=> console.log "github loading project #{projectName}" project =@lib.get(projectName) console.log "loaded:" console.log project getProjectsName:(callback)=> #hack @store.client.readdir "/", (error, entries) -> if error console.log ("error") else console.log entries callback(entries) return GitHubStore
[ { "context": "$ ->\nHan = \"Never tell me the odds! Han Solo\"\nYoda = \"Do. Or do not. There is no try. Yoda\"\nQu", "end": 44, "score": 0.9954753518104553, "start": 36, "tag": "NAME", "value": "Han Solo" }, { "context": "a\"\nQui = \"Your focus determines your reality. Qui-Gon Jinn\"\n\nquotes = [Han, Yoda, Qui]\nindx = Math.floor(Mat", "end": 147, "score": 0.881468653678894, "start": 139, "tag": "NAME", "value": "Gon Jinn" } ]
src/render/scripts/script.js.coffee
CCole/Portolio
0
$ -> Han = "Never tell me the odds! Han Solo" Yoda = "Do. Or do not. There is no try. Yoda" Qui = "Your focus determines your reality. Qui-Gon Jinn" quotes = [Han, Yoda, Qui] indx = Math.floor(Math.random() * 3) randomQuote = quotes[indx] $('#RndQuote').html randomQuote
150855
$ -> Han = "Never tell me the odds! <NAME>" Yoda = "Do. Or do not. There is no try. Yoda" Qui = "Your focus determines your reality. Qui-<NAME>" quotes = [Han, Yoda, Qui] indx = Math.floor(Math.random() * 3) randomQuote = quotes[indx] $('#RndQuote').html randomQuote
true
$ -> Han = "Never tell me the odds! PI:NAME:<NAME>END_PI" Yoda = "Do. Or do not. There is no try. Yoda" Qui = "Your focus determines your reality. Qui-PI:NAME:<NAME>END_PI" quotes = [Han, Yoda, Qui] indx = Math.floor(Math.random() * 3) randomQuote = quotes[indx] $('#RndQuote').html randomQuote
[ { "context": "ipe\",\"description\":\"Recipe description\",\"author\":\"Anonymous Brewer\",\"boilSize\":10,\"batchSize\":20,\"servingSize\":0.355", "end": 180, "score": 0.9990550875663757, "start": 164, "tag": "NAME", "value": "Anonymous Brewer" }, { "context": "dients\n recipe.add 'fermentable',\n name: 'Pilsner malt'\n weight: 4.5\n yield: 74.0\n color:", "end": 7429, "score": 0.9914171099662781, "start": 7417, "tag": "NAME", "value": "Pilsner malt" }, { "context": " color: 1.5\n\n recipe.add 'spice',\n name: 'Cascade hops'\n weight: 0.02835\n aa: 5.0\n use: '", "end": 7534, "score": 0.9521911144256592, "start": 7522, "tag": "NAME", "value": "Cascade hops" }, { "context": "\n recipe.mash = new Brauhaus.Mash\n name: 'Test mash'\n ph: 5.4\n\n recipe.mash.addStep\n nam", "end": 7812, "score": 0.9817099571228027, "start": 7803, "tag": "NAME", "value": "Test mash" }, { "context": "t fermentable'\n\n r.add 'hop',\n name: 'Test hop'\n aa: 3.5\n\n r.add 'yeast',\n ", "end": 9847, "score": 0.5840137004852295, "start": 9843, "tag": "NAME", "value": "Test" }, { "context": " 'Test mash'\n\n r.mash.addStep\n name: 'Test step'\n type: 'infusion'\n\n assert.equa", "end": 10019, "score": 0.5839290618896484, "start": 10015, "tag": "NAME", "value": "Test" } ]
test/recipe.coffee
Metgezel/brauhausjs
94
Brauhaus = Brauhaus ? require '../lib/brauhaus' assert = assert ? require('chai').assert json = '{"name":"New Recipe","description":"Recipe description","author":"Anonymous Brewer","boilSize":10,"batchSize":20,"servingSize":0.355,"steepEfficiency":50,"steepTime":20,"mashEfficiency":75,"style":null,"ibuMethod":"tinseth","fermentables":[{"name":"Test fermentable","weight":1,"yield":75,"color":2,"late":false}],"spices":[{"name":"Test hop","weight":0.025,"aa":3.5,"use":"boil","time":60,"form":"pellet"}],"yeast":[{"name":"Test yeast","type":"ale","form":"liquid","attenuation":75}],"mash":{"name":"Test mash","grainTemp":23,"spargeTemp":76,"ph":null,"notes":"","steps":[{"name":"Test step","type":"infusion","waterRatio":3,"temp":68,"endTemp":null,"time":60,"rampTime":null}]},"bottlingTemp":0,"bottlingPressure":0,"primaryDays":14,"primaryTemp":20,"secondaryDays":0,"secondaryTemp":0,"tertiaryDays":0,"tertiaryTemp":0,"agingDays":14,"agingTemp":20}' describe 'Recipe', -> describe 'Extract', -> recipe = new Brauhaus.Recipe batchSize: 20.0 boilSize: 10.0 secondaryDays: 5 recipe.style = name: 'Saison' category: 'Belgian and French Ale' og: [1.060, 1.080] fg: [1.010, 1.016] ibu: [32, 38] color: [3.5, 8.5] abv: [4.5, 6.0] carb: [1.6, 2.4] # Add some ingredients recipe.add 'fermentable', name: 'Pale liquid extract' weight: 3.5 yield: 75.0 color: 3.5 recipe.add 'spice', name: 'Cascade hops' weight: 0.02835 aa: 5.0 use: 'boil' time: 60 form: 'pellet' recipe.add 'spice', name: 'Cascade hops' weight: 0.014 aa: 5.0 use: 'boil' time: 10 form: 'pellet' recipe.add 'spice', name: 'Cascade hops' weight: 0.014 aa: 5.0 use: 'primary' time: 2880 form: 'whole' recipe.add 'yeast', name: 'Wyeast 3724 - Belgian Saison' type: 'ale' form: 'liquid' attenuation: 80 # Calculate recipe values like og, fg, ibu recipe.calculate() # Run tests it 'Should include a single dry hop step', -> assert.equal 1, (recipe.spices.filter (x) -> x.dry()).length it 'Should have a bottle count of 56', -> assert.equal 56, recipe.bottleCount() it 'Should have a grade of 5', -> assert.equal 5.0, recipe.grade() it 'Should calculate OG as 1.051', -> assert.equal 1.051, recipe.og.toFixed(3) it 'Should calculate FG as 1.010', -> assert.equal 1.010, recipe.fg.toFixed(3) it 'Should calculate ABV as 5.3 %', -> assert.equal 5.3, recipe.abv.toFixed(1) it 'Should calculate color as 4.6 SRM', -> assert.equal 4.6, recipe.color.toFixed(1) it 'Should calculate colorName as yellow', -> assert.equal 'yellow', recipe.colorName() it 'Should calculate calories as 165 kcal', -> assert.equal 165, Math.round(recipe.calories) it 'Should calculate IBU (tinseth) as 14.0', -> assert.equal 14.0, recipe.ibu.toFixed(1) it 'Should calculate BU:GU as 0.28', -> assert.equal 0.28, recipe.buToGu.toFixed(2) it 'Should calculate BV as 0.64', -> assert.equal 0.64, recipe.bv.toFixed(2) it 'Should cost $31.09', -> assert.equal 31.09, recipe.price.toFixed(2) it 'Should calculate priming sugar', -> assert.equal 0.130, recipe.primingCornSugar.toFixed(3) assert.equal 0.118, recipe.primingSugar.toFixed(3) assert.equal 0.159, recipe.primingHoney.toFixed(3) assert.equal 0.173, recipe.primingDme.toFixed(3) it 'Should generate a metric unit timeline', -> timeline = recipe.timeline() assert.ok timeline assert.equal timeline[1][1], 'Add 3.5kg of Pale liquid extract (50.6 GU), 28g of Cascade hops' assert.equal timeline[2][1], 'Add 14g of Cascade hops' assert.include timeline[4][1], 'Pitch Wyeast 3724 - Belgian Saison' it 'Should generate an imperial unit timeline', -> timeline = recipe.timeline(false) assert.ok timeline assert.equal timeline[1][1], 'Add 7lb 11oz of Pale liquid extract (50.6 GU), 1.00oz of Cascade hops' assert.equal timeline[2][1], 'Add 0.49oz of Cascade hops' assert.include timeline[4][1], 'Pitch Wyeast 3724 - Belgian Saison' it 'Should calculate brew day time, start and end of boil', -> assert.equal 21.0, recipe.boilStartTime.toFixed(1) assert.equal 81.0, recipe.boilEndTime.toFixed(1) assert.equal 101.0, recipe.brewDayDuration.toFixed(1) it 'Should scale without changing gravity/bitterness', -> recipe.scale 25, 20 recipe.calculate() assert.equal 25, recipe.batchSize assert.equal 20, recipe.boilSize assert.equal 1.051, recipe.og.toFixed(3) assert.equal 1.010, recipe.fg.toFixed(3) assert.equal 14.0, recipe.ibu.toFixed(1) describe 'Steep', -> recipe = new Brauhaus.Recipe batchSize: 20.0 boilSize: 10.0 ibuMethod: 'rager' # Add some ingredients recipe.add 'fermentable', name: 'Extra pale LME' weight: 4.0 yield: 75.0 color: 2.0 recipe.add 'fermentable', name: 'Caramel 60L' weight: 0.5 yield: 73.0 color: 60.0 recipe.add 'spice', name: 'Cascade hops' weight: 0.02835 aa: 5.0 use: 'boil' time: 60 form: 'pellet' recipe.add 'spice', name: 'Cascade hops' weight: 0.014 aa: 5.0 use: 'boil' time: 20 form: 'pellet' recipe.add 'spice', name: 'Cascade hops' weight: 0.014 aa: 5.0 use: 'boil' time: 5 form: 'pellet' recipe.add 'yeast', name: 'Wyeast 1214 - Belgian Abbey' type: 'ale' form: 'liquid' attenuation: 78 recipe.calculate() it 'Should calculate OG as 1.061', -> assert.equal 1.061, recipe.og.toFixed(3) it 'Should calculate FG as 1.014', -> assert.equal 1.014, recipe.fg.toFixed(3) it 'Should calculate ABV as 6.3 %', -> assert.equal 6.3, recipe.abv.toFixed(1) it 'Should calculate color as 9.9 SRM', -> assert.equal 9.9, recipe.color.toFixed(1) it 'Should calculate calories as 200 kcal', -> assert.equal 200, Math.round(recipe.calories) it 'Should calculate IBU (rager) as 23.2', -> assert.equal 23.2, recipe.ibu.toFixed(1) it 'Should calculate BU:GU as 0.38', -> assert.equal 0.38, recipe.buToGu.toFixed(2) it 'Should calculate BV as 0.84', -> assert.equal 0.84, recipe.bv.toFixed(2) it 'Should cost $36.59', -> assert.equal 36.59, recipe.price.toFixed(2) it 'Should generate a metric unit timeline', -> timeline = recipe.timeline() assert.ok timeline it 'Should generate an imperial unit timeline', -> timeline = recipe.timeline(false) assert.ok timeline it 'Should scale without changing gravity/bitterness', -> recipe.scale 10, 6 recipe.calculate() assert.equal 10, recipe.batchSize assert.equal 6, recipe.boilSize assert.equal 1.061, recipe.og.toFixed(3) assert.equal 1.014, recipe.fg.toFixed(3) assert.equal 23.2, recipe.ibu.toFixed(1) describe 'Mash', -> recipe = new Brauhaus.Recipe batchSize: 20.0 boilSize: 10.0 # Add some ingredients recipe.add 'fermentable', name: 'Pilsner malt' weight: 4.5 yield: 74.0 color: 1.5 recipe.add 'spice', name: 'Cascade hops' weight: 0.02835 aa: 5.0 use: 'boil' time: 45 form: 'pellet' recipe.add 'yeast', name: 'Wyeast 1728 - Scottish Ale' type: 'ale' form: 'liquid' attenuation: 73 recipe.mash = new Brauhaus.Mash name: 'Test mash' ph: 5.4 recipe.mash.addStep name: 'Rest' type: 'Infusion' temp: 60 time: 30 waterRatio: 2.75 recipe.mash.addStep name: 'Saccharification' type: 'Temperature' temp: 70 time: 60 waterRatio: 2.75 recipe.calculate() it 'Should calculate OG as 1.048', -> assert.equal 1.048, recipe.og.toFixed(3) it 'Should calculate FG as 1.013', -> assert.equal 1.013, recipe.fg.toFixed(3) it 'Should calculate ABV as 4.6 %', -> assert.equal 4.6, recipe.abv.toFixed(1) it 'Should calculate color as 3.0 SRM', -> assert.equal 3.0, recipe.color.toFixed(1) it 'Should calculate calories as 158 kcal', -> assert.equal 158, Math.round(recipe.calories) it 'Should calculate IBU (tinseth) as 11.4', -> assert.equal 11.4, recipe.ibu.toFixed(1) it 'Should calculate BU:GU as 0.24', -> assert.equal 0.24, recipe.buToGu.toFixed(2) it 'Should calculate BV as 0.47', -> assert.equal 0.47, recipe.bv.toFixed(2) it 'Should cost $27.30', -> assert.equal 27.30, recipe.price.toFixed(2) it 'Should generate a metric unit timeline', -> timeline = recipe.timeline() assert.ok timeline it 'Should generate an imperial unit timeline', -> timeline = recipe.timeline(false) assert.ok timeline describe 'JSON', -> it 'Should load a recipe from a JSON string', -> r = new Brauhaus.Recipe json assert.equal 'Test fermentable', r.fermentables[0].name assert.equal 2.2, r.fermentables[0].weightLb().toFixed(1) assert.equal 'Test hop', r.spices[0].name assert.equal 0.06, r.spices[0].weightLb().toFixed(2) assert.equal 3.5, r.yeast[0].price() assert.equal 73.4, r.mash.grainTempF() assert.equal 154.4, r.mash.steps[0].tempF() it 'Should convert a recipe to a JSON string', -> r = new Brauhaus.Recipe() r.add 'fermentable', name: 'Test fermentable' r.add 'hop', name: 'Test hop' aa: 3.5 r.add 'yeast', name: 'Test yeast' r.mash = new Brauhaus.Mash name: 'Test mash' r.mash.addStep name: 'Test step' type: 'infusion' assert.equal json, JSON.stringify(r) describe 'Missing Mash', -> it 'Should calculate a timeline without error', -> r = new Brauhaus.Recipe json r.mash = undefined r.calculate() assert.ok r.timeline()
132680
Brauhaus = Brauhaus ? require '../lib/brauhaus' assert = assert ? require('chai').assert json = '{"name":"New Recipe","description":"Recipe description","author":"<NAME>","boilSize":10,"batchSize":20,"servingSize":0.355,"steepEfficiency":50,"steepTime":20,"mashEfficiency":75,"style":null,"ibuMethod":"tinseth","fermentables":[{"name":"Test fermentable","weight":1,"yield":75,"color":2,"late":false}],"spices":[{"name":"Test hop","weight":0.025,"aa":3.5,"use":"boil","time":60,"form":"pellet"}],"yeast":[{"name":"Test yeast","type":"ale","form":"liquid","attenuation":75}],"mash":{"name":"Test mash","grainTemp":23,"spargeTemp":76,"ph":null,"notes":"","steps":[{"name":"Test step","type":"infusion","waterRatio":3,"temp":68,"endTemp":null,"time":60,"rampTime":null}]},"bottlingTemp":0,"bottlingPressure":0,"primaryDays":14,"primaryTemp":20,"secondaryDays":0,"secondaryTemp":0,"tertiaryDays":0,"tertiaryTemp":0,"agingDays":14,"agingTemp":20}' describe 'Recipe', -> describe 'Extract', -> recipe = new Brauhaus.Recipe batchSize: 20.0 boilSize: 10.0 secondaryDays: 5 recipe.style = name: 'Saison' category: 'Belgian and French Ale' og: [1.060, 1.080] fg: [1.010, 1.016] ibu: [32, 38] color: [3.5, 8.5] abv: [4.5, 6.0] carb: [1.6, 2.4] # Add some ingredients recipe.add 'fermentable', name: 'Pale liquid extract' weight: 3.5 yield: 75.0 color: 3.5 recipe.add 'spice', name: 'Cascade hops' weight: 0.02835 aa: 5.0 use: 'boil' time: 60 form: 'pellet' recipe.add 'spice', name: 'Cascade hops' weight: 0.014 aa: 5.0 use: 'boil' time: 10 form: 'pellet' recipe.add 'spice', name: 'Cascade hops' weight: 0.014 aa: 5.0 use: 'primary' time: 2880 form: 'whole' recipe.add 'yeast', name: 'Wyeast 3724 - Belgian Saison' type: 'ale' form: 'liquid' attenuation: 80 # Calculate recipe values like og, fg, ibu recipe.calculate() # Run tests it 'Should include a single dry hop step', -> assert.equal 1, (recipe.spices.filter (x) -> x.dry()).length it 'Should have a bottle count of 56', -> assert.equal 56, recipe.bottleCount() it 'Should have a grade of 5', -> assert.equal 5.0, recipe.grade() it 'Should calculate OG as 1.051', -> assert.equal 1.051, recipe.og.toFixed(3) it 'Should calculate FG as 1.010', -> assert.equal 1.010, recipe.fg.toFixed(3) it 'Should calculate ABV as 5.3 %', -> assert.equal 5.3, recipe.abv.toFixed(1) it 'Should calculate color as 4.6 SRM', -> assert.equal 4.6, recipe.color.toFixed(1) it 'Should calculate colorName as yellow', -> assert.equal 'yellow', recipe.colorName() it 'Should calculate calories as 165 kcal', -> assert.equal 165, Math.round(recipe.calories) it 'Should calculate IBU (tinseth) as 14.0', -> assert.equal 14.0, recipe.ibu.toFixed(1) it 'Should calculate BU:GU as 0.28', -> assert.equal 0.28, recipe.buToGu.toFixed(2) it 'Should calculate BV as 0.64', -> assert.equal 0.64, recipe.bv.toFixed(2) it 'Should cost $31.09', -> assert.equal 31.09, recipe.price.toFixed(2) it 'Should calculate priming sugar', -> assert.equal 0.130, recipe.primingCornSugar.toFixed(3) assert.equal 0.118, recipe.primingSugar.toFixed(3) assert.equal 0.159, recipe.primingHoney.toFixed(3) assert.equal 0.173, recipe.primingDme.toFixed(3) it 'Should generate a metric unit timeline', -> timeline = recipe.timeline() assert.ok timeline assert.equal timeline[1][1], 'Add 3.5kg of Pale liquid extract (50.6 GU), 28g of Cascade hops' assert.equal timeline[2][1], 'Add 14g of Cascade hops' assert.include timeline[4][1], 'Pitch Wyeast 3724 - Belgian Saison' it 'Should generate an imperial unit timeline', -> timeline = recipe.timeline(false) assert.ok timeline assert.equal timeline[1][1], 'Add 7lb 11oz of Pale liquid extract (50.6 GU), 1.00oz of Cascade hops' assert.equal timeline[2][1], 'Add 0.49oz of Cascade hops' assert.include timeline[4][1], 'Pitch Wyeast 3724 - Belgian Saison' it 'Should calculate brew day time, start and end of boil', -> assert.equal 21.0, recipe.boilStartTime.toFixed(1) assert.equal 81.0, recipe.boilEndTime.toFixed(1) assert.equal 101.0, recipe.brewDayDuration.toFixed(1) it 'Should scale without changing gravity/bitterness', -> recipe.scale 25, 20 recipe.calculate() assert.equal 25, recipe.batchSize assert.equal 20, recipe.boilSize assert.equal 1.051, recipe.og.toFixed(3) assert.equal 1.010, recipe.fg.toFixed(3) assert.equal 14.0, recipe.ibu.toFixed(1) describe 'Steep', -> recipe = new Brauhaus.Recipe batchSize: 20.0 boilSize: 10.0 ibuMethod: 'rager' # Add some ingredients recipe.add 'fermentable', name: 'Extra pale LME' weight: 4.0 yield: 75.0 color: 2.0 recipe.add 'fermentable', name: 'Caramel 60L' weight: 0.5 yield: 73.0 color: 60.0 recipe.add 'spice', name: 'Cascade hops' weight: 0.02835 aa: 5.0 use: 'boil' time: 60 form: 'pellet' recipe.add 'spice', name: 'Cascade hops' weight: 0.014 aa: 5.0 use: 'boil' time: 20 form: 'pellet' recipe.add 'spice', name: 'Cascade hops' weight: 0.014 aa: 5.0 use: 'boil' time: 5 form: 'pellet' recipe.add 'yeast', name: 'Wyeast 1214 - Belgian Abbey' type: 'ale' form: 'liquid' attenuation: 78 recipe.calculate() it 'Should calculate OG as 1.061', -> assert.equal 1.061, recipe.og.toFixed(3) it 'Should calculate FG as 1.014', -> assert.equal 1.014, recipe.fg.toFixed(3) it 'Should calculate ABV as 6.3 %', -> assert.equal 6.3, recipe.abv.toFixed(1) it 'Should calculate color as 9.9 SRM', -> assert.equal 9.9, recipe.color.toFixed(1) it 'Should calculate calories as 200 kcal', -> assert.equal 200, Math.round(recipe.calories) it 'Should calculate IBU (rager) as 23.2', -> assert.equal 23.2, recipe.ibu.toFixed(1) it 'Should calculate BU:GU as 0.38', -> assert.equal 0.38, recipe.buToGu.toFixed(2) it 'Should calculate BV as 0.84', -> assert.equal 0.84, recipe.bv.toFixed(2) it 'Should cost $36.59', -> assert.equal 36.59, recipe.price.toFixed(2) it 'Should generate a metric unit timeline', -> timeline = recipe.timeline() assert.ok timeline it 'Should generate an imperial unit timeline', -> timeline = recipe.timeline(false) assert.ok timeline it 'Should scale without changing gravity/bitterness', -> recipe.scale 10, 6 recipe.calculate() assert.equal 10, recipe.batchSize assert.equal 6, recipe.boilSize assert.equal 1.061, recipe.og.toFixed(3) assert.equal 1.014, recipe.fg.toFixed(3) assert.equal 23.2, recipe.ibu.toFixed(1) describe 'Mash', -> recipe = new Brauhaus.Recipe batchSize: 20.0 boilSize: 10.0 # Add some ingredients recipe.add 'fermentable', name: '<NAME>' weight: 4.5 yield: 74.0 color: 1.5 recipe.add 'spice', name: '<NAME>' weight: 0.02835 aa: 5.0 use: 'boil' time: 45 form: 'pellet' recipe.add 'yeast', name: 'Wyeast 1728 - Scottish Ale' type: 'ale' form: 'liquid' attenuation: 73 recipe.mash = new Brauhaus.Mash name: '<NAME>' ph: 5.4 recipe.mash.addStep name: 'Rest' type: 'Infusion' temp: 60 time: 30 waterRatio: 2.75 recipe.mash.addStep name: 'Saccharification' type: 'Temperature' temp: 70 time: 60 waterRatio: 2.75 recipe.calculate() it 'Should calculate OG as 1.048', -> assert.equal 1.048, recipe.og.toFixed(3) it 'Should calculate FG as 1.013', -> assert.equal 1.013, recipe.fg.toFixed(3) it 'Should calculate ABV as 4.6 %', -> assert.equal 4.6, recipe.abv.toFixed(1) it 'Should calculate color as 3.0 SRM', -> assert.equal 3.0, recipe.color.toFixed(1) it 'Should calculate calories as 158 kcal', -> assert.equal 158, Math.round(recipe.calories) it 'Should calculate IBU (tinseth) as 11.4', -> assert.equal 11.4, recipe.ibu.toFixed(1) it 'Should calculate BU:GU as 0.24', -> assert.equal 0.24, recipe.buToGu.toFixed(2) it 'Should calculate BV as 0.47', -> assert.equal 0.47, recipe.bv.toFixed(2) it 'Should cost $27.30', -> assert.equal 27.30, recipe.price.toFixed(2) it 'Should generate a metric unit timeline', -> timeline = recipe.timeline() assert.ok timeline it 'Should generate an imperial unit timeline', -> timeline = recipe.timeline(false) assert.ok timeline describe 'JSON', -> it 'Should load a recipe from a JSON string', -> r = new Brauhaus.Recipe json assert.equal 'Test fermentable', r.fermentables[0].name assert.equal 2.2, r.fermentables[0].weightLb().toFixed(1) assert.equal 'Test hop', r.spices[0].name assert.equal 0.06, r.spices[0].weightLb().toFixed(2) assert.equal 3.5, r.yeast[0].price() assert.equal 73.4, r.mash.grainTempF() assert.equal 154.4, r.mash.steps[0].tempF() it 'Should convert a recipe to a JSON string', -> r = new Brauhaus.Recipe() r.add 'fermentable', name: 'Test fermentable' r.add 'hop', name: '<NAME> hop' aa: 3.5 r.add 'yeast', name: 'Test yeast' r.mash = new Brauhaus.Mash name: 'Test mash' r.mash.addStep name: '<NAME> step' type: 'infusion' assert.equal json, JSON.stringify(r) describe 'Missing Mash', -> it 'Should calculate a timeline without error', -> r = new Brauhaus.Recipe json r.mash = undefined r.calculate() assert.ok r.timeline()
true
Brauhaus = Brauhaus ? require '../lib/brauhaus' assert = assert ? require('chai').assert json = '{"name":"New Recipe","description":"Recipe description","author":"PI:NAME:<NAME>END_PI","boilSize":10,"batchSize":20,"servingSize":0.355,"steepEfficiency":50,"steepTime":20,"mashEfficiency":75,"style":null,"ibuMethod":"tinseth","fermentables":[{"name":"Test fermentable","weight":1,"yield":75,"color":2,"late":false}],"spices":[{"name":"Test hop","weight":0.025,"aa":3.5,"use":"boil","time":60,"form":"pellet"}],"yeast":[{"name":"Test yeast","type":"ale","form":"liquid","attenuation":75}],"mash":{"name":"Test mash","grainTemp":23,"spargeTemp":76,"ph":null,"notes":"","steps":[{"name":"Test step","type":"infusion","waterRatio":3,"temp":68,"endTemp":null,"time":60,"rampTime":null}]},"bottlingTemp":0,"bottlingPressure":0,"primaryDays":14,"primaryTemp":20,"secondaryDays":0,"secondaryTemp":0,"tertiaryDays":0,"tertiaryTemp":0,"agingDays":14,"agingTemp":20}' describe 'Recipe', -> describe 'Extract', -> recipe = new Brauhaus.Recipe batchSize: 20.0 boilSize: 10.0 secondaryDays: 5 recipe.style = name: 'Saison' category: 'Belgian and French Ale' og: [1.060, 1.080] fg: [1.010, 1.016] ibu: [32, 38] color: [3.5, 8.5] abv: [4.5, 6.0] carb: [1.6, 2.4] # Add some ingredients recipe.add 'fermentable', name: 'Pale liquid extract' weight: 3.5 yield: 75.0 color: 3.5 recipe.add 'spice', name: 'Cascade hops' weight: 0.02835 aa: 5.0 use: 'boil' time: 60 form: 'pellet' recipe.add 'spice', name: 'Cascade hops' weight: 0.014 aa: 5.0 use: 'boil' time: 10 form: 'pellet' recipe.add 'spice', name: 'Cascade hops' weight: 0.014 aa: 5.0 use: 'primary' time: 2880 form: 'whole' recipe.add 'yeast', name: 'Wyeast 3724 - Belgian Saison' type: 'ale' form: 'liquid' attenuation: 80 # Calculate recipe values like og, fg, ibu recipe.calculate() # Run tests it 'Should include a single dry hop step', -> assert.equal 1, (recipe.spices.filter (x) -> x.dry()).length it 'Should have a bottle count of 56', -> assert.equal 56, recipe.bottleCount() it 'Should have a grade of 5', -> assert.equal 5.0, recipe.grade() it 'Should calculate OG as 1.051', -> assert.equal 1.051, recipe.og.toFixed(3) it 'Should calculate FG as 1.010', -> assert.equal 1.010, recipe.fg.toFixed(3) it 'Should calculate ABV as 5.3 %', -> assert.equal 5.3, recipe.abv.toFixed(1) it 'Should calculate color as 4.6 SRM', -> assert.equal 4.6, recipe.color.toFixed(1) it 'Should calculate colorName as yellow', -> assert.equal 'yellow', recipe.colorName() it 'Should calculate calories as 165 kcal', -> assert.equal 165, Math.round(recipe.calories) it 'Should calculate IBU (tinseth) as 14.0', -> assert.equal 14.0, recipe.ibu.toFixed(1) it 'Should calculate BU:GU as 0.28', -> assert.equal 0.28, recipe.buToGu.toFixed(2) it 'Should calculate BV as 0.64', -> assert.equal 0.64, recipe.bv.toFixed(2) it 'Should cost $31.09', -> assert.equal 31.09, recipe.price.toFixed(2) it 'Should calculate priming sugar', -> assert.equal 0.130, recipe.primingCornSugar.toFixed(3) assert.equal 0.118, recipe.primingSugar.toFixed(3) assert.equal 0.159, recipe.primingHoney.toFixed(3) assert.equal 0.173, recipe.primingDme.toFixed(3) it 'Should generate a metric unit timeline', -> timeline = recipe.timeline() assert.ok timeline assert.equal timeline[1][1], 'Add 3.5kg of Pale liquid extract (50.6 GU), 28g of Cascade hops' assert.equal timeline[2][1], 'Add 14g of Cascade hops' assert.include timeline[4][1], 'Pitch Wyeast 3724 - Belgian Saison' it 'Should generate an imperial unit timeline', -> timeline = recipe.timeline(false) assert.ok timeline assert.equal timeline[1][1], 'Add 7lb 11oz of Pale liquid extract (50.6 GU), 1.00oz of Cascade hops' assert.equal timeline[2][1], 'Add 0.49oz of Cascade hops' assert.include timeline[4][1], 'Pitch Wyeast 3724 - Belgian Saison' it 'Should calculate brew day time, start and end of boil', -> assert.equal 21.0, recipe.boilStartTime.toFixed(1) assert.equal 81.0, recipe.boilEndTime.toFixed(1) assert.equal 101.0, recipe.brewDayDuration.toFixed(1) it 'Should scale without changing gravity/bitterness', -> recipe.scale 25, 20 recipe.calculate() assert.equal 25, recipe.batchSize assert.equal 20, recipe.boilSize assert.equal 1.051, recipe.og.toFixed(3) assert.equal 1.010, recipe.fg.toFixed(3) assert.equal 14.0, recipe.ibu.toFixed(1) describe 'Steep', -> recipe = new Brauhaus.Recipe batchSize: 20.0 boilSize: 10.0 ibuMethod: 'rager' # Add some ingredients recipe.add 'fermentable', name: 'Extra pale LME' weight: 4.0 yield: 75.0 color: 2.0 recipe.add 'fermentable', name: 'Caramel 60L' weight: 0.5 yield: 73.0 color: 60.0 recipe.add 'spice', name: 'Cascade hops' weight: 0.02835 aa: 5.0 use: 'boil' time: 60 form: 'pellet' recipe.add 'spice', name: 'Cascade hops' weight: 0.014 aa: 5.0 use: 'boil' time: 20 form: 'pellet' recipe.add 'spice', name: 'Cascade hops' weight: 0.014 aa: 5.0 use: 'boil' time: 5 form: 'pellet' recipe.add 'yeast', name: 'Wyeast 1214 - Belgian Abbey' type: 'ale' form: 'liquid' attenuation: 78 recipe.calculate() it 'Should calculate OG as 1.061', -> assert.equal 1.061, recipe.og.toFixed(3) it 'Should calculate FG as 1.014', -> assert.equal 1.014, recipe.fg.toFixed(3) it 'Should calculate ABV as 6.3 %', -> assert.equal 6.3, recipe.abv.toFixed(1) it 'Should calculate color as 9.9 SRM', -> assert.equal 9.9, recipe.color.toFixed(1) it 'Should calculate calories as 200 kcal', -> assert.equal 200, Math.round(recipe.calories) it 'Should calculate IBU (rager) as 23.2', -> assert.equal 23.2, recipe.ibu.toFixed(1) it 'Should calculate BU:GU as 0.38', -> assert.equal 0.38, recipe.buToGu.toFixed(2) it 'Should calculate BV as 0.84', -> assert.equal 0.84, recipe.bv.toFixed(2) it 'Should cost $36.59', -> assert.equal 36.59, recipe.price.toFixed(2) it 'Should generate a metric unit timeline', -> timeline = recipe.timeline() assert.ok timeline it 'Should generate an imperial unit timeline', -> timeline = recipe.timeline(false) assert.ok timeline it 'Should scale without changing gravity/bitterness', -> recipe.scale 10, 6 recipe.calculate() assert.equal 10, recipe.batchSize assert.equal 6, recipe.boilSize assert.equal 1.061, recipe.og.toFixed(3) assert.equal 1.014, recipe.fg.toFixed(3) assert.equal 23.2, recipe.ibu.toFixed(1) describe 'Mash', -> recipe = new Brauhaus.Recipe batchSize: 20.0 boilSize: 10.0 # Add some ingredients recipe.add 'fermentable', name: 'PI:NAME:<NAME>END_PI' weight: 4.5 yield: 74.0 color: 1.5 recipe.add 'spice', name: 'PI:NAME:<NAME>END_PI' weight: 0.02835 aa: 5.0 use: 'boil' time: 45 form: 'pellet' recipe.add 'yeast', name: 'Wyeast 1728 - Scottish Ale' type: 'ale' form: 'liquid' attenuation: 73 recipe.mash = new Brauhaus.Mash name: 'PI:NAME:<NAME>END_PI' ph: 5.4 recipe.mash.addStep name: 'Rest' type: 'Infusion' temp: 60 time: 30 waterRatio: 2.75 recipe.mash.addStep name: 'Saccharification' type: 'Temperature' temp: 70 time: 60 waterRatio: 2.75 recipe.calculate() it 'Should calculate OG as 1.048', -> assert.equal 1.048, recipe.og.toFixed(3) it 'Should calculate FG as 1.013', -> assert.equal 1.013, recipe.fg.toFixed(3) it 'Should calculate ABV as 4.6 %', -> assert.equal 4.6, recipe.abv.toFixed(1) it 'Should calculate color as 3.0 SRM', -> assert.equal 3.0, recipe.color.toFixed(1) it 'Should calculate calories as 158 kcal', -> assert.equal 158, Math.round(recipe.calories) it 'Should calculate IBU (tinseth) as 11.4', -> assert.equal 11.4, recipe.ibu.toFixed(1) it 'Should calculate BU:GU as 0.24', -> assert.equal 0.24, recipe.buToGu.toFixed(2) it 'Should calculate BV as 0.47', -> assert.equal 0.47, recipe.bv.toFixed(2) it 'Should cost $27.30', -> assert.equal 27.30, recipe.price.toFixed(2) it 'Should generate a metric unit timeline', -> timeline = recipe.timeline() assert.ok timeline it 'Should generate an imperial unit timeline', -> timeline = recipe.timeline(false) assert.ok timeline describe 'JSON', -> it 'Should load a recipe from a JSON string', -> r = new Brauhaus.Recipe json assert.equal 'Test fermentable', r.fermentables[0].name assert.equal 2.2, r.fermentables[0].weightLb().toFixed(1) assert.equal 'Test hop', r.spices[0].name assert.equal 0.06, r.spices[0].weightLb().toFixed(2) assert.equal 3.5, r.yeast[0].price() assert.equal 73.4, r.mash.grainTempF() assert.equal 154.4, r.mash.steps[0].tempF() it 'Should convert a recipe to a JSON string', -> r = new Brauhaus.Recipe() r.add 'fermentable', name: 'Test fermentable' r.add 'hop', name: 'PI:NAME:<NAME>END_PI hop' aa: 3.5 r.add 'yeast', name: 'Test yeast' r.mash = new Brauhaus.Mash name: 'Test mash' r.mash.addStep name: 'PI:NAME:<NAME>END_PI step' type: 'infusion' assert.equal json, JSON.stringify(r) describe 'Missing Mash', -> it 'Should calculate a timeline without error', -> r = new Brauhaus.Recipe json r.mash = undefined r.calculate() assert.ok r.timeline()
[ { "context": "le.\n#\n# Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details\n# abo", "end": 491, "score": 0.9997069835662842, "start": 480, "tag": "USERNAME", "value": "sstephenson" }, { "context": "ted_at\n firstName: Curri.user.first_name || 'No'\n lastName: Curri.user.last_name || 'Name'\n\n", "end": 1619, "score": 0.9883949160575867, "start": 1617, "tag": "NAME", "value": "No" }, { "context": " || 'No'\n lastName: Curri.user.last_name || 'Name'\n\n analytics.identify(Curri.user.id, userData)", "end": 1666, "score": 0.9939812421798706, "start": 1662, "tag": "NAME", "value": "Name" } ]
app/assets/javascripts/application.js.coffee
aomra015/curri
1
# This is a manifest file that'll be compiled into application.js, which will include all the files # listed below. # # Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, # or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. # # It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the # compiled file. # # Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details # about supported directives. # #= require jquery #= require jquery_ujs #= require jquery.ui.sortable #= require pickadate/picker #= require pickadate/picker.date #= require pickadate/picker.time #= require matchMedia #= require parser_rules/simple #= require wysihtml5 #= require bootstrap-dismiss #= require jquery.modal #= require utilities #= require_tree ./objects #= require_tree . #= require uservoice $ = jQuery $ -> # Navigation if $('.fixed-nav').length Curri.MainNav.init() $('.collapse-toggle').on 'click', (e) -> e.preventDefault() $('body').toggleClass('nav-open') Curri.MainNav.update() Curri.SubNav.close() $('.subnav-toggle').on 'click', (e) -> e.preventDefault() Curri.SubNav.toggle() # Tracks & Analytics sidebar select menu if Curri.mobileScreen() && $('#track').length Curri.MobileSidebar.init() # SegmentIO if Curri.user userData = email: Curri.user.email classRole: Curri.user.classrole_type created: Curri.user.created_at firstName: Curri.user.first_name || 'No' lastName: Curri.user.last_name || 'Name' analytics.identify(Curri.user.id, userData) analytics.trackLink($('#logout-link'), "Sign out") $('a.open-modal').click -> Curri.SubNav.close() $('.error-message').remove() $(this).modal(fadeDuration: 250) return false
120912
# This is a manifest file that'll be compiled into application.js, which will include all the files # listed below. # # Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, # or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. # # It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the # compiled file. # # Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details # about supported directives. # #= require jquery #= require jquery_ujs #= require jquery.ui.sortable #= require pickadate/picker #= require pickadate/picker.date #= require pickadate/picker.time #= require matchMedia #= require parser_rules/simple #= require wysihtml5 #= require bootstrap-dismiss #= require jquery.modal #= require utilities #= require_tree ./objects #= require_tree . #= require uservoice $ = jQuery $ -> # Navigation if $('.fixed-nav').length Curri.MainNav.init() $('.collapse-toggle').on 'click', (e) -> e.preventDefault() $('body').toggleClass('nav-open') Curri.MainNav.update() Curri.SubNav.close() $('.subnav-toggle').on 'click', (e) -> e.preventDefault() Curri.SubNav.toggle() # Tracks & Analytics sidebar select menu if Curri.mobileScreen() && $('#track').length Curri.MobileSidebar.init() # SegmentIO if Curri.user userData = email: Curri.user.email classRole: Curri.user.classrole_type created: Curri.user.created_at firstName: Curri.user.first_name || '<NAME>' lastName: Curri.user.last_name || '<NAME>' analytics.identify(Curri.user.id, userData) analytics.trackLink($('#logout-link'), "Sign out") $('a.open-modal').click -> Curri.SubNav.close() $('.error-message').remove() $(this).modal(fadeDuration: 250) return false
true
# This is a manifest file that'll be compiled into application.js, which will include all the files # listed below. # # Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, # or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. # # It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the # compiled file. # # Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details # about supported directives. # #= require jquery #= require jquery_ujs #= require jquery.ui.sortable #= require pickadate/picker #= require pickadate/picker.date #= require pickadate/picker.time #= require matchMedia #= require parser_rules/simple #= require wysihtml5 #= require bootstrap-dismiss #= require jquery.modal #= require utilities #= require_tree ./objects #= require_tree . #= require uservoice $ = jQuery $ -> # Navigation if $('.fixed-nav').length Curri.MainNav.init() $('.collapse-toggle').on 'click', (e) -> e.preventDefault() $('body').toggleClass('nav-open') Curri.MainNav.update() Curri.SubNav.close() $('.subnav-toggle').on 'click', (e) -> e.preventDefault() Curri.SubNav.toggle() # Tracks & Analytics sidebar select menu if Curri.mobileScreen() && $('#track').length Curri.MobileSidebar.init() # SegmentIO if Curri.user userData = email: Curri.user.email classRole: Curri.user.classrole_type created: Curri.user.created_at firstName: Curri.user.first_name || 'PI:NAME:<NAME>END_PI' lastName: Curri.user.last_name || 'PI:NAME:<NAME>END_PI' analytics.identify(Curri.user.id, userData) analytics.trackLink($('#logout-link'), "Sign out") $('a.open-modal').click -> Curri.SubNav.close() $('.error-message').remove() $(this).modal(fadeDuration: 250) return false
[ { "context": "f an HTTP POST request to create a model.\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n###\r\nclass CreateAircraftM", "end": 154, "score": 0.999850869178772, "start": 142, "tag": "NAME", "value": "Nathan Klick" } ]
Workspace/QRef/NodeServer/src/specification/request/ajax/CreateAircraftModelAjaxRequest.coffee
qrefdev/qref
0
AjaxRequest = require('../../../serialization/AjaxRequest') ### Object sent as the body of an HTTP POST request to create a model. @author Nathan Klick @copyright QRef 2012 ### class CreateAircraftModelAjaxRequest extends AjaxRequest ### @property [String] (Required) The name of the model. ### name: type: String required: true ### @property [String] (Optional) A detailed description of the model. ### description: type: String required: false ### @property [ObjectId] (Required) The associated manufacturer of this model. @see AircraftManufacturerSchemaInternal ### manufacturer: type: ObjectId required: true ref: 'aircraft.manufacturers' ### @property [String] (Required) A string representing the specific year of this model. ### modelYear: type: String required: true module.exports = CreateAircraftModelAjaxRequest
57256
AjaxRequest = require('../../../serialization/AjaxRequest') ### Object sent as the body of an HTTP POST request to create a model. @author <NAME> @copyright QRef 2012 ### class CreateAircraftModelAjaxRequest extends AjaxRequest ### @property [String] (Required) The name of the model. ### name: type: String required: true ### @property [String] (Optional) A detailed description of the model. ### description: type: String required: false ### @property [ObjectId] (Required) The associated manufacturer of this model. @see AircraftManufacturerSchemaInternal ### manufacturer: type: ObjectId required: true ref: 'aircraft.manufacturers' ### @property [String] (Required) A string representing the specific year of this model. ### modelYear: type: String required: true module.exports = CreateAircraftModelAjaxRequest
true
AjaxRequest = require('../../../serialization/AjaxRequest') ### Object sent as the body of an HTTP POST request to create a model. @author PI:NAME:<NAME>END_PI @copyright QRef 2012 ### class CreateAircraftModelAjaxRequest extends AjaxRequest ### @property [String] (Required) The name of the model. ### name: type: String required: true ### @property [String] (Optional) A detailed description of the model. ### description: type: String required: false ### @property [ObjectId] (Required) The associated manufacturer of this model. @see AircraftManufacturerSchemaInternal ### manufacturer: type: ObjectId required: true ref: 'aircraft.manufacturers' ### @property [String] (Required) A string representing the specific year of this model. ### modelYear: type: String required: true module.exports = CreateAircraftModelAjaxRequest
[ { "context": "\"] = Meteor.userId()\n\t\tauthToken[\"X-Auth-Token\"] = Accounts._storedLoginToken()\n\t\turl = Meteor.absoluteUrl(\"api/setup/sso/\" + p", "end": 757, "score": 0.6606532335281372, "start": 731, "tag": "KEY", "value": "Accounts._storedLoginToken" } ]
creator/packages/steedos-base/client/router.coffee
yicone/steedos-platform
42
checkUserSigned = (context, redirect) -> # if !Meteor.userId() # Setup.validate(); FlowRouter.triggers.enter (context, redirect, stop)-> if context?.queryParams?.app_id Session.set('current_app_id', context.queryParams.app_id) FlowRouter.route '/steedos/sign-in', triggersEnter: [ (context, redirect)-> Steedos.redirectToSignIn() ] FlowRouter.route '/select-users', action: (params, queryParams)-> BlazeLayout.render 'selectUsersLayout', main: "reactSelectUsers" FlowRouter.route '/apps/iframe/:app_id', triggersEnter: [ checkUserSigned ], action: (params, queryParams)-> authToken = {}; authToken["spaceId"] = Steedos.getSpaceId() authToken["X-User-Id"] = Meteor.userId() authToken["X-Auth-Token"] = Accounts._storedLoginToken() url = Meteor.absoluteUrl("api/setup/sso/" + params.app_id + "?" + $.param(authToken)) BlazeLayout.render 'iframeLayout', url: url FlowRouter.route '/steedos/springboard', triggersEnter: [ -> FlowRouter.go "/" ] FlowRouter.route '/springboard', triggersEnter: [ checkUserSigned ], action: (params, queryParams)-> if !Meteor.userId() Steedos.redirectToSignIn() return true NavigationController.reset(); BlazeLayout.render 'masterLayout', main: "springboard" if Steedos.isMobile() $("body").removeClass("sidebar-open") workbenchRoutes = FlowRouter.group prefix: '/workbench', name: 'workbenchRoutes', triggersEnter: [ checkUserSigned ], workbenchRoutes.route '/', action: (params, queryParams)-> if !Meteor.userId() Steedos.redirectToSignIn() return true NavigationController.reset(); BlazeLayout.render 'masterLayout', main: "workbench" if Steedos.isMobile() $("body").removeClass("sidebar-open") workbenchRoutes.route '/manage', action: (params, queryParams)-> BlazeLayout.render 'masterLayout', main: "manageBusiness" if Steedos.isMobile() $("body").removeClass("sidebar-open")
35358
checkUserSigned = (context, redirect) -> # if !Meteor.userId() # Setup.validate(); FlowRouter.triggers.enter (context, redirect, stop)-> if context?.queryParams?.app_id Session.set('current_app_id', context.queryParams.app_id) FlowRouter.route '/steedos/sign-in', triggersEnter: [ (context, redirect)-> Steedos.redirectToSignIn() ] FlowRouter.route '/select-users', action: (params, queryParams)-> BlazeLayout.render 'selectUsersLayout', main: "reactSelectUsers" FlowRouter.route '/apps/iframe/:app_id', triggersEnter: [ checkUserSigned ], action: (params, queryParams)-> authToken = {}; authToken["spaceId"] = Steedos.getSpaceId() authToken["X-User-Id"] = Meteor.userId() authToken["X-Auth-Token"] = <KEY>() url = Meteor.absoluteUrl("api/setup/sso/" + params.app_id + "?" + $.param(authToken)) BlazeLayout.render 'iframeLayout', url: url FlowRouter.route '/steedos/springboard', triggersEnter: [ -> FlowRouter.go "/" ] FlowRouter.route '/springboard', triggersEnter: [ checkUserSigned ], action: (params, queryParams)-> if !Meteor.userId() Steedos.redirectToSignIn() return true NavigationController.reset(); BlazeLayout.render 'masterLayout', main: "springboard" if Steedos.isMobile() $("body").removeClass("sidebar-open") workbenchRoutes = FlowRouter.group prefix: '/workbench', name: 'workbenchRoutes', triggersEnter: [ checkUserSigned ], workbenchRoutes.route '/', action: (params, queryParams)-> if !Meteor.userId() Steedos.redirectToSignIn() return true NavigationController.reset(); BlazeLayout.render 'masterLayout', main: "workbench" if Steedos.isMobile() $("body").removeClass("sidebar-open") workbenchRoutes.route '/manage', action: (params, queryParams)-> BlazeLayout.render 'masterLayout', main: "manageBusiness" if Steedos.isMobile() $("body").removeClass("sidebar-open")
true
checkUserSigned = (context, redirect) -> # if !Meteor.userId() # Setup.validate(); FlowRouter.triggers.enter (context, redirect, stop)-> if context?.queryParams?.app_id Session.set('current_app_id', context.queryParams.app_id) FlowRouter.route '/steedos/sign-in', triggersEnter: [ (context, redirect)-> Steedos.redirectToSignIn() ] FlowRouter.route '/select-users', action: (params, queryParams)-> BlazeLayout.render 'selectUsersLayout', main: "reactSelectUsers" FlowRouter.route '/apps/iframe/:app_id', triggersEnter: [ checkUserSigned ], action: (params, queryParams)-> authToken = {}; authToken["spaceId"] = Steedos.getSpaceId() authToken["X-User-Id"] = Meteor.userId() authToken["X-Auth-Token"] = PI:KEY:<KEY>END_PI() url = Meteor.absoluteUrl("api/setup/sso/" + params.app_id + "?" + $.param(authToken)) BlazeLayout.render 'iframeLayout', url: url FlowRouter.route '/steedos/springboard', triggersEnter: [ -> FlowRouter.go "/" ] FlowRouter.route '/springboard', triggersEnter: [ checkUserSigned ], action: (params, queryParams)-> if !Meteor.userId() Steedos.redirectToSignIn() return true NavigationController.reset(); BlazeLayout.render 'masterLayout', main: "springboard" if Steedos.isMobile() $("body").removeClass("sidebar-open") workbenchRoutes = FlowRouter.group prefix: '/workbench', name: 'workbenchRoutes', triggersEnter: [ checkUserSigned ], workbenchRoutes.route '/', action: (params, queryParams)-> if !Meteor.userId() Steedos.redirectToSignIn() return true NavigationController.reset(); BlazeLayout.render 'masterLayout', main: "workbench" if Steedos.isMobile() $("body").removeClass("sidebar-open") workbenchRoutes.route '/manage', action: (params, queryParams)-> BlazeLayout.render 'masterLayout', main: "manageBusiness" if Steedos.isMobile() $("body").removeClass("sidebar-open")
[ { "context": "lass ContactifyPlugin extends BasePlugin\n\t\tname: 'contactifyr'\n\n\t\tconfig:\n\t\t\tcontact:\n\t\t\t\tpath: '/contact-form'", "end": 184, "score": 0.9630791544914246, "start": 173, "tag": "USERNAME", "value": "contactifyr" }, { "context": "unt (which will have its own 'from')\n\t\t\t\t# from: 'me@site.name',\n\t\t\t\tredirect: '/'\n\t\t\t\tto: 'me@site.name'\n\t\t\t\tsu", "end": 345, "score": 0.999899685382843, "start": 333, "tag": "EMAIL", "value": "me@site.name" }, { "context": " from: 'me@site.name',\n\t\t\t\tredirect: '/'\n\t\t\t\tto: 'me@site.name'\n\t\t\t\tsubject: 'Inquiry' # OPTIONAL\n\t\t\t\ttransport:", "end": 387, "score": 0.9998824000358582, "start": 375, "tag": "EMAIL", "value": "me@site.name" }, { "context": "87,\n\t\t\t\t\tsecure: false,\n\t\t\t\t\tauth: {\n\t\t\t\t\t\tuser: 'contact@me.com',\n\t\t\t\t\t\tpass: 'password'\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\tserverEx", "end": 573, "score": 0.9999160766601562, "start": 559, "tag": "EMAIL", "value": "contact@me.com" }, { "context": "uth: {\n\t\t\t\t\t\tuser: 'contact@me.com',\n\t\t\t\t\t\tpass: 'password'\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\tserverExtend: (opts) ->\n\t\t\t{serv", "end": 597, "score": 0.9987389445304871, "start": 589, "tag": "PASSWORD", "value": "password" } ]
source/contactifyr.plugin.coffee
redbox-mint-contrib/docpad-plugin-contactifyr
0
nodemailer = require 'nodemailer' axios = require 'axios' # docpad = require 'docpad' module.exports = (BasePlugin) -> class ContactifyPlugin extends BasePlugin name: 'contactifyr' config: contact: path: '/contact-form' # No from necessary if using an existing account (which will have its own 'from') # from: 'me@site.name', redirect: '/' to: 'me@site.name' subject: 'Inquiry' # OPTIONAL transport: { service: 'Gmail', host: 'smtp.ethereal.email', port: 587, secure: false, auth: { user: 'contact@me.com', pass: 'password' } } serverExtend: (opts) -> {server} = opts config = @getConfig() smtp = nodemailer.createTransport(config.transport) server.post config.contact.path, (req, res) -> receivers = [] enquiry = req.body console.log('enquiry:', enquiry) # data = { # secret: '', # response: enquiry['g-recaptcha-response'] # } parameters = '?secret=foobar&response=' + enquiry['g-recaptcha-response'] url = 'https://www.google.com/recaptcha/api/siteverify' + parameters console.log('url is', url) axios.post(url).then (response) -> console.log(response) # if recaptcha response fails do not send if response.success # if 'honeypot' field filled out, do not send if not enquiry.email || enquiry.email == '' receivers.push(enquiry.redbox_email, config.contact.to) mailOptions = { to: receivers.join(","), subject: 'Enquiry from ' + enquiry.fname + ' ' + enquiry.lname + ' <' + enquiry.redbox_email + '>', text: enquiry.message, html: '<p>' + enquiry.message + '</p>' } smtp.sendMail mailOptions, (err, resp) -> if(err) console.log("There was an error sending email", err) else console.log("send mail response:", resp) res.redirect config.contact.redirect @
15106
nodemailer = require 'nodemailer' axios = require 'axios' # docpad = require 'docpad' module.exports = (BasePlugin) -> class ContactifyPlugin extends BasePlugin name: 'contactifyr' config: contact: path: '/contact-form' # No from necessary if using an existing account (which will have its own 'from') # from: '<EMAIL>', redirect: '/' to: '<EMAIL>' subject: 'Inquiry' # OPTIONAL transport: { service: 'Gmail', host: 'smtp.ethereal.email', port: 587, secure: false, auth: { user: '<EMAIL>', pass: '<PASSWORD>' } } serverExtend: (opts) -> {server} = opts config = @getConfig() smtp = nodemailer.createTransport(config.transport) server.post config.contact.path, (req, res) -> receivers = [] enquiry = req.body console.log('enquiry:', enquiry) # data = { # secret: '', # response: enquiry['g-recaptcha-response'] # } parameters = '?secret=foobar&response=' + enquiry['g-recaptcha-response'] url = 'https://www.google.com/recaptcha/api/siteverify' + parameters console.log('url is', url) axios.post(url).then (response) -> console.log(response) # if recaptcha response fails do not send if response.success # if 'honeypot' field filled out, do not send if not enquiry.email || enquiry.email == '' receivers.push(enquiry.redbox_email, config.contact.to) mailOptions = { to: receivers.join(","), subject: 'Enquiry from ' + enquiry.fname + ' ' + enquiry.lname + ' <' + enquiry.redbox_email + '>', text: enquiry.message, html: '<p>' + enquiry.message + '</p>' } smtp.sendMail mailOptions, (err, resp) -> if(err) console.log("There was an error sending email", err) else console.log("send mail response:", resp) res.redirect config.contact.redirect @
true
nodemailer = require 'nodemailer' axios = require 'axios' # docpad = require 'docpad' module.exports = (BasePlugin) -> class ContactifyPlugin extends BasePlugin name: 'contactifyr' config: contact: path: '/contact-form' # No from necessary if using an existing account (which will have its own 'from') # from: 'PI:EMAIL:<EMAIL>END_PI', redirect: '/' to: 'PI:EMAIL:<EMAIL>END_PI' subject: 'Inquiry' # OPTIONAL transport: { service: 'Gmail', host: 'smtp.ethereal.email', port: 587, secure: false, auth: { user: 'PI:EMAIL:<EMAIL>END_PI', pass: 'PI:PASSWORD:<PASSWORD>END_PI' } } serverExtend: (opts) -> {server} = opts config = @getConfig() smtp = nodemailer.createTransport(config.transport) server.post config.contact.path, (req, res) -> receivers = [] enquiry = req.body console.log('enquiry:', enquiry) # data = { # secret: '', # response: enquiry['g-recaptcha-response'] # } parameters = '?secret=foobar&response=' + enquiry['g-recaptcha-response'] url = 'https://www.google.com/recaptcha/api/siteverify' + parameters console.log('url is', url) axios.post(url).then (response) -> console.log(response) # if recaptcha response fails do not send if response.success # if 'honeypot' field filled out, do not send if not enquiry.email || enquiry.email == '' receivers.push(enquiry.redbox_email, config.contact.to) mailOptions = { to: receivers.join(","), subject: 'Enquiry from ' + enquiry.fname + ' ' + enquiry.lname + ' <' + enquiry.redbox_email + '>', text: enquiry.message, html: '<p>' + enquiry.message + '</p>' } smtp.sendMail mailOptions, (err, resp) -> if(err) console.log("There was an error sending email", err) else console.log("send mail response:", resp) res.redirect config.contact.redirect @
[ { "context": "###*\n * 表单验证\n * @author vfasky <vfasky@gmail.com>\n###\n'use strict'\n\n{View} = req", "end": 30, "score": 0.9995235800743103, "start": 24, "tag": "USERNAME", "value": "vfasky" }, { "context": "###*\n * 表单验证\n * @author vfasky <vfasky@gmail.com>\n###\n'use strict'\n\n{View} = require 'mcoreapp'\n\nw", "end": 48, "score": 0.9999198317527771, "start": 32, "tag": "EMAIL", "value": "vfasky@gmail.com" } ]
example/src/validator.coffee
vfasky/mcore-weui
0
###* * 表单验证 * @author vfasky <vfasky@gmail.com> ### 'use strict' {View} = require 'mcoreapp' weui = require 'mcore-weui' class Validator extends View init: -> @validator = new weui.Validator @.$el[0] run: -> @render require('../tpl/validator.html') send: (err, data)-> return @validator.showError err if err console.log data module.exports = Validator module.exports.viewName = 'validator'
94963
###* * 表单验证 * @author vfasky <<EMAIL>> ### 'use strict' {View} = require 'mcoreapp' weui = require 'mcore-weui' class Validator extends View init: -> @validator = new weui.Validator @.$el[0] run: -> @render require('../tpl/validator.html') send: (err, data)-> return @validator.showError err if err console.log data module.exports = Validator module.exports.viewName = 'validator'
true
###* * 表单验证 * @author vfasky <PI:EMAIL:<EMAIL>END_PI> ### 'use strict' {View} = require 'mcoreapp' weui = require 'mcore-weui' class Validator extends View init: -> @validator = new weui.Validator @.$el[0] run: -> @render require('../tpl/validator.html') send: (err, data)-> return @validator.showError err if err console.log data module.exports = Validator module.exports.viewName = 'validator'
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9988743662834167, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "ction, and runMain when\n # that occurs. --isaacs\n debugTimeout = +process.env.NODE_DEBUG_TI", "end": 4465, "score": 0.9913687705993652, "start": 4459, "tag": "USERNAME", "value": "isaacs" }, { "context": "vent loop alive.\n # See https://github.com/joyent/node/issues/1726\n stream._handle.unref() ", "end": 7610, "score": 0.9995031356811523, "start": 7604, "tag": "USERNAME", "value": "joyent" }, { "context": "vent loop alive.\n # See https://github.com/joyent/node/issues/1726\n stream._handle.unref() ", "end": 8541, "score": 0.9994926452636719, "start": 8535, "tag": "USERNAME", "value": "joyent" }, { "context": "NativeModule::cache = ->\n NativeModule._cache[@id] = this\n return\n\n startup()\n return\n", "end": 21976, "score": 0.7292811870574951, "start": 21974, "tag": "USERNAME", "value": "id" } ]
src/node.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Hello, and welcome to hacking node.js! # # This file is invoked by node::Load in src/node.cc, and responsible for # bootstrapping the node.js core. Special caution is given to the performance # of the startup process, so many dependencies are invoked lazily. "use strict" (process) -> startup = -> EventEmitter = NativeModule.require("events").EventEmitter process.__proto__ = Object.create(EventEmitter::, constructor: value: process.constructor ) EventEmitter.call process process.EventEmitter = EventEmitter # process.EventEmitter is deprecated # do this good and early, since it handles errors. startup.processFatal() startup.globalVariables() startup.globalTimeouts() startup.globalConsole() startup.processAssert() startup.processConfig() startup.processNextTick() startup.processStdio() startup.processKillAndExit() startup.processSignalHandlers() # Do not initialize channel in debugger agent, it deletes env variable # and the main thread won't see it. startup.processChannel() if process.argv[1] isnt "--debug-agent" startup.processRawDebug() startup.resolveArgv0() # There are various modes that Node can run in. The most common two # are running from a script and running the REPL - but there are a few # others like the debugger or running --eval arguments. Here we decide # which mode we run in. if NativeModule.exists("_third_party_main") # To allow people to extend Node in different ways, this hook allows # one to drop a file lib/_third_party_main.js into the build # directory which will be executed instead of Node's normal loading. process.nextTick -> NativeModule.require "_third_party_main" return else if process.argv[1] is "debug" # Start the debugger agent d = NativeModule.require("_debugger") d.start() else if process.argv[1] is "--debug-agent" # Start the debugger agent d = NativeModule.require("_debug_agent") d.start() else if process._eval? # User passed '-e' or '--eval' arguments to Node. evalScript "[eval]" else if process.argv[1] # make process.argv[1] into a full path path = NativeModule.require("path") process.argv[1] = path.resolve(process.argv[1]) # If this is a worker in cluster mode, start up the communication # channel. if process.env.NODE_UNIQUE_ID cluster = NativeModule.require("cluster") cluster._setupWorker() # Make sure it's not accidentally inherited by child processes. delete process.env.NODE_UNIQUE_ID Module = NativeModule.require("module") if global.v8debug and process.execArgv.some((arg) -> arg.match /^--debug-brk(=[0-9]*)?$/ ) # XXX Fix this terrible hack! # # Give the client program a few ticks to connect. # Otherwise, there's a race condition where `node debug foo.js` # will not be able to connect in time to catch the first # breakpoint message on line 1. # # A better fix would be to somehow get a message from the # global.v8debug object about a connection, and runMain when # that occurs. --isaacs debugTimeout = +process.env.NODE_DEBUG_TIMEOUT or 50 setTimeout Module.runMain, debugTimeout else # Main entry point into most programs: Module.runMain() else Module = NativeModule.require("module") # If -i or --interactive were passed, or stdin is a TTY. if process._forceRepl or NativeModule.require("tty").isatty(0) # REPL opts = useGlobal: true ignoreUndefined: false opts.terminal = false if parseInt(process.env["NODE_NO_READLINE"], 10) opts.useColors = false if parseInt(process.env["NODE_DISABLE_COLORS"], 10) repl = Module.requireRepl().start(opts) repl.on "exit", -> process.exit() return else # Read all of stdin - execute it. process.stdin.setEncoding "utf8" code = "" process.stdin.on "data", (d) -> code += d return process.stdin.on "end", -> process._eval = code evalScript "[stdin]" return return # If someone handled it, then great. otherwise, die in C++ land # since that means that we'll exit the process, emit the 'exit' event # nothing to be done about it at this point. # if we handled an error, then make sure any ticks get processed # used for `process.config`, but not a real module # strip the gyp comment line at the beginning # Used to run V8's micro task queue. # This tickInfo thing is used so that the C++ code in src/node.cc # can have easy accesss to our nextTick state, and avoid unnecessary # *Must* match Environment::TickInfo::Fields in src/env.h. # Needs to be accessible from beyond this scope. # Run callbacks that have no domain. # Using domains will cause this to be overridden. # on the way out, don't bother. it won't get fired anyway. evalScript = (name) -> Module = NativeModule.require("module") path = NativeModule.require("path") cwd = process.cwd() module = new Module(name) module.filename = path.join(cwd, name) module.paths = Module._nodeModulePaths(cwd) script = process._eval unless Module._contextLoad body = script script = "global.__filename = " + JSON.stringify(name) + ";\n" + "global.exports = exports;\n" + "global.module = module;\n" + "global.__dirname = __dirname;\n" + "global.require = require;\n" + "return require(\"vm\").runInThisContext(" + JSON.stringify(body) + ", { filename: " + JSON.stringify(name) + " });\n" result = module._compile(script, name + "-wrapper") console.log result if process._print_eval return createWritableStdioStream = (fd) -> stream = undefined tty_wrap = process.binding("tty_wrap") # Note stream._type is used for test-module-load-list.js switch tty_wrap.guessHandleType(fd) when "TTY" tty = NativeModule.require("tty") stream = new tty.WriteStream(fd) stream._type = "tty" # Hack to have stream not keep the event loop alive. # See https://github.com/joyent/node/issues/1726 stream._handle.unref() if stream._handle and stream._handle.unref when "FILE" fs = NativeModule.require("fs") stream = new fs.SyncWriteStream(fd, autoClose: false ) stream._type = "fs" when "PIPE", "TCP" net = NativeModule.require("net") stream = new net.Socket( fd: fd readable: false writable: true ) # FIXME Should probably have an option in net.Socket to create a # stream from an existing fd which is writable only. But for now # we'll just add this hack and set the `readable` member to false. # Test: ./node test/fixtures/echo.js < /etc/passwd stream.readable = false stream.read = null stream._type = "pipe" # FIXME Hack to have stream not keep the event loop alive. # See https://github.com/joyent/node/issues/1726 stream._handle.unref() if stream._handle and stream._handle.unref else # Probably an error on in uv_guess_handle() throw new Error("Implement me. Unknown stream file type!") # For supporting legacy API we put the FD here. stream.fd = fd stream._isStdio = true stream # It could be that process has been started with an IPC channel # sitting on fd=0, in such case the pipe for this fd is already # present and creating a new one will lead to the assertion failure # in libuv. # Probably an error on in uv_guess_handle() # For supporting legacy API we put the FD here. # stdin starts out life in a paused state, but node doesn't # know yet. Explicitly to readStop() it to put it in the # not-reading state. # if the user calls stdin.pause(), then we need to stop reading # immediately, so that the process can close down. # preserve null signal # Load events module in order to access prototype elements on process like # process.addListener. # Wrap addListener for the special signal types # If we were spawned with env NODE_CHANNEL_FD then load that up and # start parsing data from that stream. # Make sure it's not accidentally inherited by child processes. # Load tcp_wrap to avoid situation where we might immediately receive # a message. # FIXME is this really necessary? # Make process.argv[0] into a full path, but only touch argv[0] if it's # not a system $PATH lookup. # TODO: Make this work on Windows as well. Note that "node" might # execute cwd\node.exe, or some %PATH%\node.exe on Windows, # and that every directory has its own cwd, so d:node.exe is valid. # Below you find a minimal module system, which is used to load the node # core modules found in lib/*.js. All core modules are compiled into the # node binary, so they can be loaded faster. runInThisContext = (code, options) -> script = new ContextifyScript(code, options) script.runInThisContext() NativeModule = (id) -> @filename = id + ".js" @id = id @exports = {} @loaded = false return @global = this startup.globalVariables = -> global.process = process global.global = global global.GLOBAL = global global.root = global global.Buffer = NativeModule.require("buffer").Buffer process.domain = null process._exiting = false return startup.globalTimeouts = -> global.setTimeout = -> t = NativeModule.require("timers") t.setTimeout.apply this, arguments global.setInterval = -> t = NativeModule.require("timers") t.setInterval.apply this, arguments global.clearTimeout = -> t = NativeModule.require("timers") t.clearTimeout.apply this, arguments global.clearInterval = -> t = NativeModule.require("timers") t.clearInterval.apply this, arguments global.setImmediate = -> t = NativeModule.require("timers") t.setImmediate.apply this, arguments global.clearImmediate = -> t = NativeModule.require("timers") t.clearImmediate.apply this, arguments return startup.globalConsole = -> global.__defineGetter__ "console", -> NativeModule.require "console" return startup._lazyConstants = null startup.lazyConstants = -> startup._lazyConstants = process.binding("constants") unless startup._lazyConstants startup._lazyConstants startup.processFatal = -> process._fatalException = (er) -> caught = undefined caught = process.domain._errorHandler(er) or caught if process.domain and process.domain._errorHandler caught = process.emit("uncaughtException", er) unless caught unless caught try unless process._exiting process._exiting = true process.emit "exit", 1 else NativeModule.require("timers").setImmediate process._tickCallback caught return assert = undefined startup.processAssert = -> assert = process.assert = (x, msg) -> throw new Error(msg or "assertion error") unless x return return startup.processConfig = -> config = NativeModule._source.config delete NativeModule._source.config config = config.split("\n").slice(1).join("\n").replace(/"/g, "\\\"").replace(/'/g, "\"") process.config = JSON.parse(config, (key, value) -> return true if value is "true" return false if value is "false" value ) return startup.processNextTick = -> tickDone = -> if tickInfo[kLength] isnt 0 if tickInfo[kLength] <= tickInfo[kIndex] nextTickQueue = [] tickInfo[kLength] = 0 else nextTickQueue.splice 0, tickInfo[kIndex] tickInfo[kLength] = nextTickQueue.length tickInfo[kIndex] = 0 return scheduleMicrotasks = -> return if microtasksScheduled nextTickQueue.push callback: runMicrotasksCallback domain: null tickInfo[kLength]++ microtasksScheduled = true return runMicrotasksCallback = -> microtasksScheduled = false _runMicrotasks() scheduleMicrotasks() if tickInfo[kIndex] < tickInfo[kLength] return _tickCallback = -> callback = undefined threw = undefined tock = undefined scheduleMicrotasks() while tickInfo[kIndex] < tickInfo[kLength] tock = nextTickQueue[tickInfo[kIndex]++] callback = tock.callback threw = true try callback() threw = false finally tickDone() if threw tickDone() if 1e4 < tickInfo[kIndex] tickDone() return _tickDomainCallback = -> callback = undefined domain = undefined threw = undefined tock = undefined scheduleMicrotasks() while tickInfo[kIndex] < tickInfo[kLength] tock = nextTickQueue[tickInfo[kIndex]++] callback = tock.callback domain = tock.domain domain.enter() if domain threw = true try callback() threw = false finally tickDone() if threw tickDone() if 1e4 < tickInfo[kIndex] domain.exit() if domain tickDone() return nextTick = (callback) -> return if process._exiting obj = callback: callback domain: process.domain or null nextTickQueue.push obj tickInfo[kLength]++ return nextTickQueue = [] microtasksScheduled = false _runMicrotasks = {} tickInfo = {} kIndex = 0 kLength = 1 process.nextTick = nextTick process._tickCallback = _tickCallback process._tickDomainCallback = _tickDomainCallback process._setupNextTick tickInfo, _tickCallback, _runMicrotasks _runMicrotasks = _runMicrotasks.runMicrotasks return startup.processStdio = -> stdin = undefined stdout = undefined stderr = undefined process.__defineGetter__ "stdout", -> return stdout if stdout stdout = createWritableStdioStream(1) stdout.destroy = stdout.destroySoon = (er) -> er = er or new Error("process.stdout cannot be closed.") stdout.emit "error", er return if stdout.isTTY process.on "SIGWINCH", -> stdout._refreshSize() return stdout process.__defineGetter__ "stderr", -> return stderr if stderr stderr = createWritableStdioStream(2) stderr.destroy = stderr.destroySoon = (er) -> er = er or new Error("process.stderr cannot be closed.") stderr.emit "error", er return stderr process.__defineGetter__ "stdin", -> return stdin if stdin tty_wrap = process.binding("tty_wrap") fd = 0 switch tty_wrap.guessHandleType(fd) when "TTY" tty = NativeModule.require("tty") stdin = new tty.ReadStream(fd, highWaterMark: 0 readable: true writable: false ) when "FILE" fs = NativeModule.require("fs") stdin = new fs.ReadStream(null, fd: fd autoClose: false ) when "PIPE", "TCP" net = NativeModule.require("net") if process._channel and process._channel.fd is fd stdin = new net.Socket( handle: process._channel readable: true writable: false ) else stdin = new net.Socket( fd: fd readable: true writable: false ) else throw new Error("Implement me. Unknown stdin file type!") stdin.fd = fd if stdin._handle and stdin._handle.readStop stdin._handle.reading = false stdin._readableState.reading = false stdin._handle.readStop() stdin.on "pause", -> return unless stdin._handle stdin._readableState.reading = false stdin._handle.reading = false stdin._handle.readStop() return stdin process.openStdin = -> process.stdin.resume() process.stdin return startup.processKillAndExit = -> process.exit = (code) -> process.exitCode = code if code or code is 0 unless process._exiting process._exiting = true process.emit "exit", process.exitCode or 0 process.reallyExit process.exitCode or 0 return process.kill = (pid, sig) -> err = undefined throw new TypeError("invalid pid") unless pid is (pid | 0) if 0 is sig err = process._kill(pid, 0) else sig = sig or "SIGTERM" if startup.lazyConstants()[sig] and sig.slice(0, 3) is "SIG" err = process._kill(pid, startup.lazyConstants()[sig]) else throw new Error("Unknown signal: " + sig) if err errnoException = NativeModule.require("util")._errnoException throw errnoException(err, "kill") true return startup.processSignalHandlers = -> isSignal = (event) -> event.slice(0, 3) is "SIG" and startup.lazyConstants().hasOwnProperty(event) signalWraps = {} addListener = process.addListener removeListener = process.removeListener process.on = process.addListener = (type, listener) -> if isSignal(type) and not signalWraps.hasOwnProperty(type) Signal = process.binding("signal_wrap").Signal wrap = new Signal() wrap.unref() wrap.onsignal = -> process.emit type return signum = startup.lazyConstants()[type] err = wrap.start(signum) if err wrap.close() errnoException = NativeModule.require("util")._errnoException throw errnoException(err, "uv_signal_start") signalWraps[type] = wrap addListener.apply this, arguments process.removeListener = (type, listener) -> ret = removeListener.apply(this, arguments) if isSignal(type) assert signalWraps.hasOwnProperty(type) if NativeModule.require("events").listenerCount(this, type) is 0 signalWraps[type].close() delete signalWraps[type] ret return startup.processChannel = -> if process.env.NODE_CHANNEL_FD fd = parseInt(process.env.NODE_CHANNEL_FD, 10) assert fd >= 0 delete process.env.NODE_CHANNEL_FD cp = NativeModule.require("child_process") process.binding "tcp_wrap" cp._forkChild fd assert process.send return startup.processRawDebug = -> format = NativeModule.require("util").format rawDebug = process._rawDebug process._rawDebug = -> rawDebug format.apply(null, arguments) return return startup.resolveArgv0 = -> cwd = process.cwd() isWindows = process.platform is "win32" argv0 = process.argv[0] if not isWindows and argv0.indexOf("/") isnt -1 and argv0.charAt(0) isnt "/" path = NativeModule.require("path") process.argv[0] = path.join(cwd, process.argv[0]) return ContextifyScript = process.binding("contextify").ContextifyScript NativeModule._source = process.binding("natives") NativeModule._cache = {} NativeModule.require = (id) -> return NativeModule if id is "native_module" cached = NativeModule.getCached(id) return cached.exports if cached throw new Error("No such native module " + id) unless NativeModule.exists(id) process.moduleLoadList.push "NativeModule " + id nativeModule = new NativeModule(id) nativeModule.cache() nativeModule.compile() nativeModule.exports NativeModule.getCached = (id) -> NativeModule._cache[id] NativeModule.exists = (id) -> NativeModule._source.hasOwnProperty id NativeModule.getSource = (id) -> NativeModule._source[id] NativeModule.wrap = (script) -> NativeModule.wrapper[0] + script + NativeModule.wrapper[1] NativeModule.wrapper = [ "(function (exports, require, module, __filename, __dirname) { " "\n});" ] NativeModule::compile = -> source = NativeModule.getSource(@id) source = NativeModule.wrap(source) fn = runInThisContext(source, filename: @filename ) fn @exports, NativeModule.require, this, @filename @loaded = true return NativeModule::cache = -> NativeModule._cache[@id] = this return startup() return
122444
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Hello, and welcome to hacking node.js! # # This file is invoked by node::Load in src/node.cc, and responsible for # bootstrapping the node.js core. Special caution is given to the performance # of the startup process, so many dependencies are invoked lazily. "use strict" (process) -> startup = -> EventEmitter = NativeModule.require("events").EventEmitter process.__proto__ = Object.create(EventEmitter::, constructor: value: process.constructor ) EventEmitter.call process process.EventEmitter = EventEmitter # process.EventEmitter is deprecated # do this good and early, since it handles errors. startup.processFatal() startup.globalVariables() startup.globalTimeouts() startup.globalConsole() startup.processAssert() startup.processConfig() startup.processNextTick() startup.processStdio() startup.processKillAndExit() startup.processSignalHandlers() # Do not initialize channel in debugger agent, it deletes env variable # and the main thread won't see it. startup.processChannel() if process.argv[1] isnt "--debug-agent" startup.processRawDebug() startup.resolveArgv0() # There are various modes that Node can run in. The most common two # are running from a script and running the REPL - but there are a few # others like the debugger or running --eval arguments. Here we decide # which mode we run in. if NativeModule.exists("_third_party_main") # To allow people to extend Node in different ways, this hook allows # one to drop a file lib/_third_party_main.js into the build # directory which will be executed instead of Node's normal loading. process.nextTick -> NativeModule.require "_third_party_main" return else if process.argv[1] is "debug" # Start the debugger agent d = NativeModule.require("_debugger") d.start() else if process.argv[1] is "--debug-agent" # Start the debugger agent d = NativeModule.require("_debug_agent") d.start() else if process._eval? # User passed '-e' or '--eval' arguments to Node. evalScript "[eval]" else if process.argv[1] # make process.argv[1] into a full path path = NativeModule.require("path") process.argv[1] = path.resolve(process.argv[1]) # If this is a worker in cluster mode, start up the communication # channel. if process.env.NODE_UNIQUE_ID cluster = NativeModule.require("cluster") cluster._setupWorker() # Make sure it's not accidentally inherited by child processes. delete process.env.NODE_UNIQUE_ID Module = NativeModule.require("module") if global.v8debug and process.execArgv.some((arg) -> arg.match /^--debug-brk(=[0-9]*)?$/ ) # XXX Fix this terrible hack! # # Give the client program a few ticks to connect. # Otherwise, there's a race condition where `node debug foo.js` # will not be able to connect in time to catch the first # breakpoint message on line 1. # # A better fix would be to somehow get a message from the # global.v8debug object about a connection, and runMain when # that occurs. --isaacs debugTimeout = +process.env.NODE_DEBUG_TIMEOUT or 50 setTimeout Module.runMain, debugTimeout else # Main entry point into most programs: Module.runMain() else Module = NativeModule.require("module") # If -i or --interactive were passed, or stdin is a TTY. if process._forceRepl or NativeModule.require("tty").isatty(0) # REPL opts = useGlobal: true ignoreUndefined: false opts.terminal = false if parseInt(process.env["NODE_NO_READLINE"], 10) opts.useColors = false if parseInt(process.env["NODE_DISABLE_COLORS"], 10) repl = Module.requireRepl().start(opts) repl.on "exit", -> process.exit() return else # Read all of stdin - execute it. process.stdin.setEncoding "utf8" code = "" process.stdin.on "data", (d) -> code += d return process.stdin.on "end", -> process._eval = code evalScript "[stdin]" return return # If someone handled it, then great. otherwise, die in C++ land # since that means that we'll exit the process, emit the 'exit' event # nothing to be done about it at this point. # if we handled an error, then make sure any ticks get processed # used for `process.config`, but not a real module # strip the gyp comment line at the beginning # Used to run V8's micro task queue. # This tickInfo thing is used so that the C++ code in src/node.cc # can have easy accesss to our nextTick state, and avoid unnecessary # *Must* match Environment::TickInfo::Fields in src/env.h. # Needs to be accessible from beyond this scope. # Run callbacks that have no domain. # Using domains will cause this to be overridden. # on the way out, don't bother. it won't get fired anyway. evalScript = (name) -> Module = NativeModule.require("module") path = NativeModule.require("path") cwd = process.cwd() module = new Module(name) module.filename = path.join(cwd, name) module.paths = Module._nodeModulePaths(cwd) script = process._eval unless Module._contextLoad body = script script = "global.__filename = " + JSON.stringify(name) + ";\n" + "global.exports = exports;\n" + "global.module = module;\n" + "global.__dirname = __dirname;\n" + "global.require = require;\n" + "return require(\"vm\").runInThisContext(" + JSON.stringify(body) + ", { filename: " + JSON.stringify(name) + " });\n" result = module._compile(script, name + "-wrapper") console.log result if process._print_eval return createWritableStdioStream = (fd) -> stream = undefined tty_wrap = process.binding("tty_wrap") # Note stream._type is used for test-module-load-list.js switch tty_wrap.guessHandleType(fd) when "TTY" tty = NativeModule.require("tty") stream = new tty.WriteStream(fd) stream._type = "tty" # Hack to have stream not keep the event loop alive. # See https://github.com/joyent/node/issues/1726 stream._handle.unref() if stream._handle and stream._handle.unref when "FILE" fs = NativeModule.require("fs") stream = new fs.SyncWriteStream(fd, autoClose: false ) stream._type = "fs" when "PIPE", "TCP" net = NativeModule.require("net") stream = new net.Socket( fd: fd readable: false writable: true ) # FIXME Should probably have an option in net.Socket to create a # stream from an existing fd which is writable only. But for now # we'll just add this hack and set the `readable` member to false. # Test: ./node test/fixtures/echo.js < /etc/passwd stream.readable = false stream.read = null stream._type = "pipe" # FIXME Hack to have stream not keep the event loop alive. # See https://github.com/joyent/node/issues/1726 stream._handle.unref() if stream._handle and stream._handle.unref else # Probably an error on in uv_guess_handle() throw new Error("Implement me. Unknown stream file type!") # For supporting legacy API we put the FD here. stream.fd = fd stream._isStdio = true stream # It could be that process has been started with an IPC channel # sitting on fd=0, in such case the pipe for this fd is already # present and creating a new one will lead to the assertion failure # in libuv. # Probably an error on in uv_guess_handle() # For supporting legacy API we put the FD here. # stdin starts out life in a paused state, but node doesn't # know yet. Explicitly to readStop() it to put it in the # not-reading state. # if the user calls stdin.pause(), then we need to stop reading # immediately, so that the process can close down. # preserve null signal # Load events module in order to access prototype elements on process like # process.addListener. # Wrap addListener for the special signal types # If we were spawned with env NODE_CHANNEL_FD then load that up and # start parsing data from that stream. # Make sure it's not accidentally inherited by child processes. # Load tcp_wrap to avoid situation where we might immediately receive # a message. # FIXME is this really necessary? # Make process.argv[0] into a full path, but only touch argv[0] if it's # not a system $PATH lookup. # TODO: Make this work on Windows as well. Note that "node" might # execute cwd\node.exe, or some %PATH%\node.exe on Windows, # and that every directory has its own cwd, so d:node.exe is valid. # Below you find a minimal module system, which is used to load the node # core modules found in lib/*.js. All core modules are compiled into the # node binary, so they can be loaded faster. runInThisContext = (code, options) -> script = new ContextifyScript(code, options) script.runInThisContext() NativeModule = (id) -> @filename = id + ".js" @id = id @exports = {} @loaded = false return @global = this startup.globalVariables = -> global.process = process global.global = global global.GLOBAL = global global.root = global global.Buffer = NativeModule.require("buffer").Buffer process.domain = null process._exiting = false return startup.globalTimeouts = -> global.setTimeout = -> t = NativeModule.require("timers") t.setTimeout.apply this, arguments global.setInterval = -> t = NativeModule.require("timers") t.setInterval.apply this, arguments global.clearTimeout = -> t = NativeModule.require("timers") t.clearTimeout.apply this, arguments global.clearInterval = -> t = NativeModule.require("timers") t.clearInterval.apply this, arguments global.setImmediate = -> t = NativeModule.require("timers") t.setImmediate.apply this, arguments global.clearImmediate = -> t = NativeModule.require("timers") t.clearImmediate.apply this, arguments return startup.globalConsole = -> global.__defineGetter__ "console", -> NativeModule.require "console" return startup._lazyConstants = null startup.lazyConstants = -> startup._lazyConstants = process.binding("constants") unless startup._lazyConstants startup._lazyConstants startup.processFatal = -> process._fatalException = (er) -> caught = undefined caught = process.domain._errorHandler(er) or caught if process.domain and process.domain._errorHandler caught = process.emit("uncaughtException", er) unless caught unless caught try unless process._exiting process._exiting = true process.emit "exit", 1 else NativeModule.require("timers").setImmediate process._tickCallback caught return assert = undefined startup.processAssert = -> assert = process.assert = (x, msg) -> throw new Error(msg or "assertion error") unless x return return startup.processConfig = -> config = NativeModule._source.config delete NativeModule._source.config config = config.split("\n").slice(1).join("\n").replace(/"/g, "\\\"").replace(/'/g, "\"") process.config = JSON.parse(config, (key, value) -> return true if value is "true" return false if value is "false" value ) return startup.processNextTick = -> tickDone = -> if tickInfo[kLength] isnt 0 if tickInfo[kLength] <= tickInfo[kIndex] nextTickQueue = [] tickInfo[kLength] = 0 else nextTickQueue.splice 0, tickInfo[kIndex] tickInfo[kLength] = nextTickQueue.length tickInfo[kIndex] = 0 return scheduleMicrotasks = -> return if microtasksScheduled nextTickQueue.push callback: runMicrotasksCallback domain: null tickInfo[kLength]++ microtasksScheduled = true return runMicrotasksCallback = -> microtasksScheduled = false _runMicrotasks() scheduleMicrotasks() if tickInfo[kIndex] < tickInfo[kLength] return _tickCallback = -> callback = undefined threw = undefined tock = undefined scheduleMicrotasks() while tickInfo[kIndex] < tickInfo[kLength] tock = nextTickQueue[tickInfo[kIndex]++] callback = tock.callback threw = true try callback() threw = false finally tickDone() if threw tickDone() if 1e4 < tickInfo[kIndex] tickDone() return _tickDomainCallback = -> callback = undefined domain = undefined threw = undefined tock = undefined scheduleMicrotasks() while tickInfo[kIndex] < tickInfo[kLength] tock = nextTickQueue[tickInfo[kIndex]++] callback = tock.callback domain = tock.domain domain.enter() if domain threw = true try callback() threw = false finally tickDone() if threw tickDone() if 1e4 < tickInfo[kIndex] domain.exit() if domain tickDone() return nextTick = (callback) -> return if process._exiting obj = callback: callback domain: process.domain or null nextTickQueue.push obj tickInfo[kLength]++ return nextTickQueue = [] microtasksScheduled = false _runMicrotasks = {} tickInfo = {} kIndex = 0 kLength = 1 process.nextTick = nextTick process._tickCallback = _tickCallback process._tickDomainCallback = _tickDomainCallback process._setupNextTick tickInfo, _tickCallback, _runMicrotasks _runMicrotasks = _runMicrotasks.runMicrotasks return startup.processStdio = -> stdin = undefined stdout = undefined stderr = undefined process.__defineGetter__ "stdout", -> return stdout if stdout stdout = createWritableStdioStream(1) stdout.destroy = stdout.destroySoon = (er) -> er = er or new Error("process.stdout cannot be closed.") stdout.emit "error", er return if stdout.isTTY process.on "SIGWINCH", -> stdout._refreshSize() return stdout process.__defineGetter__ "stderr", -> return stderr if stderr stderr = createWritableStdioStream(2) stderr.destroy = stderr.destroySoon = (er) -> er = er or new Error("process.stderr cannot be closed.") stderr.emit "error", er return stderr process.__defineGetter__ "stdin", -> return stdin if stdin tty_wrap = process.binding("tty_wrap") fd = 0 switch tty_wrap.guessHandleType(fd) when "TTY" tty = NativeModule.require("tty") stdin = new tty.ReadStream(fd, highWaterMark: 0 readable: true writable: false ) when "FILE" fs = NativeModule.require("fs") stdin = new fs.ReadStream(null, fd: fd autoClose: false ) when "PIPE", "TCP" net = NativeModule.require("net") if process._channel and process._channel.fd is fd stdin = new net.Socket( handle: process._channel readable: true writable: false ) else stdin = new net.Socket( fd: fd readable: true writable: false ) else throw new Error("Implement me. Unknown stdin file type!") stdin.fd = fd if stdin._handle and stdin._handle.readStop stdin._handle.reading = false stdin._readableState.reading = false stdin._handle.readStop() stdin.on "pause", -> return unless stdin._handle stdin._readableState.reading = false stdin._handle.reading = false stdin._handle.readStop() return stdin process.openStdin = -> process.stdin.resume() process.stdin return startup.processKillAndExit = -> process.exit = (code) -> process.exitCode = code if code or code is 0 unless process._exiting process._exiting = true process.emit "exit", process.exitCode or 0 process.reallyExit process.exitCode or 0 return process.kill = (pid, sig) -> err = undefined throw new TypeError("invalid pid") unless pid is (pid | 0) if 0 is sig err = process._kill(pid, 0) else sig = sig or "SIGTERM" if startup.lazyConstants()[sig] and sig.slice(0, 3) is "SIG" err = process._kill(pid, startup.lazyConstants()[sig]) else throw new Error("Unknown signal: " + sig) if err errnoException = NativeModule.require("util")._errnoException throw errnoException(err, "kill") true return startup.processSignalHandlers = -> isSignal = (event) -> event.slice(0, 3) is "SIG" and startup.lazyConstants().hasOwnProperty(event) signalWraps = {} addListener = process.addListener removeListener = process.removeListener process.on = process.addListener = (type, listener) -> if isSignal(type) and not signalWraps.hasOwnProperty(type) Signal = process.binding("signal_wrap").Signal wrap = new Signal() wrap.unref() wrap.onsignal = -> process.emit type return signum = startup.lazyConstants()[type] err = wrap.start(signum) if err wrap.close() errnoException = NativeModule.require("util")._errnoException throw errnoException(err, "uv_signal_start") signalWraps[type] = wrap addListener.apply this, arguments process.removeListener = (type, listener) -> ret = removeListener.apply(this, arguments) if isSignal(type) assert signalWraps.hasOwnProperty(type) if NativeModule.require("events").listenerCount(this, type) is 0 signalWraps[type].close() delete signalWraps[type] ret return startup.processChannel = -> if process.env.NODE_CHANNEL_FD fd = parseInt(process.env.NODE_CHANNEL_FD, 10) assert fd >= 0 delete process.env.NODE_CHANNEL_FD cp = NativeModule.require("child_process") process.binding "tcp_wrap" cp._forkChild fd assert process.send return startup.processRawDebug = -> format = NativeModule.require("util").format rawDebug = process._rawDebug process._rawDebug = -> rawDebug format.apply(null, arguments) return return startup.resolveArgv0 = -> cwd = process.cwd() isWindows = process.platform is "win32" argv0 = process.argv[0] if not isWindows and argv0.indexOf("/") isnt -1 and argv0.charAt(0) isnt "/" path = NativeModule.require("path") process.argv[0] = path.join(cwd, process.argv[0]) return ContextifyScript = process.binding("contextify").ContextifyScript NativeModule._source = process.binding("natives") NativeModule._cache = {} NativeModule.require = (id) -> return NativeModule if id is "native_module" cached = NativeModule.getCached(id) return cached.exports if cached throw new Error("No such native module " + id) unless NativeModule.exists(id) process.moduleLoadList.push "NativeModule " + id nativeModule = new NativeModule(id) nativeModule.cache() nativeModule.compile() nativeModule.exports NativeModule.getCached = (id) -> NativeModule._cache[id] NativeModule.exists = (id) -> NativeModule._source.hasOwnProperty id NativeModule.getSource = (id) -> NativeModule._source[id] NativeModule.wrap = (script) -> NativeModule.wrapper[0] + script + NativeModule.wrapper[1] NativeModule.wrapper = [ "(function (exports, require, module, __filename, __dirname) { " "\n});" ] NativeModule::compile = -> source = NativeModule.getSource(@id) source = NativeModule.wrap(source) fn = runInThisContext(source, filename: @filename ) fn @exports, NativeModule.require, this, @filename @loaded = true return NativeModule::cache = -> NativeModule._cache[@id] = this return startup() return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Hello, and welcome to hacking node.js! # # This file is invoked by node::Load in src/node.cc, and responsible for # bootstrapping the node.js core. Special caution is given to the performance # of the startup process, so many dependencies are invoked lazily. "use strict" (process) -> startup = -> EventEmitter = NativeModule.require("events").EventEmitter process.__proto__ = Object.create(EventEmitter::, constructor: value: process.constructor ) EventEmitter.call process process.EventEmitter = EventEmitter # process.EventEmitter is deprecated # do this good and early, since it handles errors. startup.processFatal() startup.globalVariables() startup.globalTimeouts() startup.globalConsole() startup.processAssert() startup.processConfig() startup.processNextTick() startup.processStdio() startup.processKillAndExit() startup.processSignalHandlers() # Do not initialize channel in debugger agent, it deletes env variable # and the main thread won't see it. startup.processChannel() if process.argv[1] isnt "--debug-agent" startup.processRawDebug() startup.resolveArgv0() # There are various modes that Node can run in. The most common two # are running from a script and running the REPL - but there are a few # others like the debugger or running --eval arguments. Here we decide # which mode we run in. if NativeModule.exists("_third_party_main") # To allow people to extend Node in different ways, this hook allows # one to drop a file lib/_third_party_main.js into the build # directory which will be executed instead of Node's normal loading. process.nextTick -> NativeModule.require "_third_party_main" return else if process.argv[1] is "debug" # Start the debugger agent d = NativeModule.require("_debugger") d.start() else if process.argv[1] is "--debug-agent" # Start the debugger agent d = NativeModule.require("_debug_agent") d.start() else if process._eval? # User passed '-e' or '--eval' arguments to Node. evalScript "[eval]" else if process.argv[1] # make process.argv[1] into a full path path = NativeModule.require("path") process.argv[1] = path.resolve(process.argv[1]) # If this is a worker in cluster mode, start up the communication # channel. if process.env.NODE_UNIQUE_ID cluster = NativeModule.require("cluster") cluster._setupWorker() # Make sure it's not accidentally inherited by child processes. delete process.env.NODE_UNIQUE_ID Module = NativeModule.require("module") if global.v8debug and process.execArgv.some((arg) -> arg.match /^--debug-brk(=[0-9]*)?$/ ) # XXX Fix this terrible hack! # # Give the client program a few ticks to connect. # Otherwise, there's a race condition where `node debug foo.js` # will not be able to connect in time to catch the first # breakpoint message on line 1. # # A better fix would be to somehow get a message from the # global.v8debug object about a connection, and runMain when # that occurs. --isaacs debugTimeout = +process.env.NODE_DEBUG_TIMEOUT or 50 setTimeout Module.runMain, debugTimeout else # Main entry point into most programs: Module.runMain() else Module = NativeModule.require("module") # If -i or --interactive were passed, or stdin is a TTY. if process._forceRepl or NativeModule.require("tty").isatty(0) # REPL opts = useGlobal: true ignoreUndefined: false opts.terminal = false if parseInt(process.env["NODE_NO_READLINE"], 10) opts.useColors = false if parseInt(process.env["NODE_DISABLE_COLORS"], 10) repl = Module.requireRepl().start(opts) repl.on "exit", -> process.exit() return else # Read all of stdin - execute it. process.stdin.setEncoding "utf8" code = "" process.stdin.on "data", (d) -> code += d return process.stdin.on "end", -> process._eval = code evalScript "[stdin]" return return # If someone handled it, then great. otherwise, die in C++ land # since that means that we'll exit the process, emit the 'exit' event # nothing to be done about it at this point. # if we handled an error, then make sure any ticks get processed # used for `process.config`, but not a real module # strip the gyp comment line at the beginning # Used to run V8's micro task queue. # This tickInfo thing is used so that the C++ code in src/node.cc # can have easy accesss to our nextTick state, and avoid unnecessary # *Must* match Environment::TickInfo::Fields in src/env.h. # Needs to be accessible from beyond this scope. # Run callbacks that have no domain. # Using domains will cause this to be overridden. # on the way out, don't bother. it won't get fired anyway. evalScript = (name) -> Module = NativeModule.require("module") path = NativeModule.require("path") cwd = process.cwd() module = new Module(name) module.filename = path.join(cwd, name) module.paths = Module._nodeModulePaths(cwd) script = process._eval unless Module._contextLoad body = script script = "global.__filename = " + JSON.stringify(name) + ";\n" + "global.exports = exports;\n" + "global.module = module;\n" + "global.__dirname = __dirname;\n" + "global.require = require;\n" + "return require(\"vm\").runInThisContext(" + JSON.stringify(body) + ", { filename: " + JSON.stringify(name) + " });\n" result = module._compile(script, name + "-wrapper") console.log result if process._print_eval return createWritableStdioStream = (fd) -> stream = undefined tty_wrap = process.binding("tty_wrap") # Note stream._type is used for test-module-load-list.js switch tty_wrap.guessHandleType(fd) when "TTY" tty = NativeModule.require("tty") stream = new tty.WriteStream(fd) stream._type = "tty" # Hack to have stream not keep the event loop alive. # See https://github.com/joyent/node/issues/1726 stream._handle.unref() if stream._handle and stream._handle.unref when "FILE" fs = NativeModule.require("fs") stream = new fs.SyncWriteStream(fd, autoClose: false ) stream._type = "fs" when "PIPE", "TCP" net = NativeModule.require("net") stream = new net.Socket( fd: fd readable: false writable: true ) # FIXME Should probably have an option in net.Socket to create a # stream from an existing fd which is writable only. But for now # we'll just add this hack and set the `readable` member to false. # Test: ./node test/fixtures/echo.js < /etc/passwd stream.readable = false stream.read = null stream._type = "pipe" # FIXME Hack to have stream not keep the event loop alive. # See https://github.com/joyent/node/issues/1726 stream._handle.unref() if stream._handle and stream._handle.unref else # Probably an error on in uv_guess_handle() throw new Error("Implement me. Unknown stream file type!") # For supporting legacy API we put the FD here. stream.fd = fd stream._isStdio = true stream # It could be that process has been started with an IPC channel # sitting on fd=0, in such case the pipe for this fd is already # present and creating a new one will lead to the assertion failure # in libuv. # Probably an error on in uv_guess_handle() # For supporting legacy API we put the FD here. # stdin starts out life in a paused state, but node doesn't # know yet. Explicitly to readStop() it to put it in the # not-reading state. # if the user calls stdin.pause(), then we need to stop reading # immediately, so that the process can close down. # preserve null signal # Load events module in order to access prototype elements on process like # process.addListener. # Wrap addListener for the special signal types # If we were spawned with env NODE_CHANNEL_FD then load that up and # start parsing data from that stream. # Make sure it's not accidentally inherited by child processes. # Load tcp_wrap to avoid situation where we might immediately receive # a message. # FIXME is this really necessary? # Make process.argv[0] into a full path, but only touch argv[0] if it's # not a system $PATH lookup. # TODO: Make this work on Windows as well. Note that "node" might # execute cwd\node.exe, or some %PATH%\node.exe on Windows, # and that every directory has its own cwd, so d:node.exe is valid. # Below you find a minimal module system, which is used to load the node # core modules found in lib/*.js. All core modules are compiled into the # node binary, so they can be loaded faster. runInThisContext = (code, options) -> script = new ContextifyScript(code, options) script.runInThisContext() NativeModule = (id) -> @filename = id + ".js" @id = id @exports = {} @loaded = false return @global = this startup.globalVariables = -> global.process = process global.global = global global.GLOBAL = global global.root = global global.Buffer = NativeModule.require("buffer").Buffer process.domain = null process._exiting = false return startup.globalTimeouts = -> global.setTimeout = -> t = NativeModule.require("timers") t.setTimeout.apply this, arguments global.setInterval = -> t = NativeModule.require("timers") t.setInterval.apply this, arguments global.clearTimeout = -> t = NativeModule.require("timers") t.clearTimeout.apply this, arguments global.clearInterval = -> t = NativeModule.require("timers") t.clearInterval.apply this, arguments global.setImmediate = -> t = NativeModule.require("timers") t.setImmediate.apply this, arguments global.clearImmediate = -> t = NativeModule.require("timers") t.clearImmediate.apply this, arguments return startup.globalConsole = -> global.__defineGetter__ "console", -> NativeModule.require "console" return startup._lazyConstants = null startup.lazyConstants = -> startup._lazyConstants = process.binding("constants") unless startup._lazyConstants startup._lazyConstants startup.processFatal = -> process._fatalException = (er) -> caught = undefined caught = process.domain._errorHandler(er) or caught if process.domain and process.domain._errorHandler caught = process.emit("uncaughtException", er) unless caught unless caught try unless process._exiting process._exiting = true process.emit "exit", 1 else NativeModule.require("timers").setImmediate process._tickCallback caught return assert = undefined startup.processAssert = -> assert = process.assert = (x, msg) -> throw new Error(msg or "assertion error") unless x return return startup.processConfig = -> config = NativeModule._source.config delete NativeModule._source.config config = config.split("\n").slice(1).join("\n").replace(/"/g, "\\\"").replace(/'/g, "\"") process.config = JSON.parse(config, (key, value) -> return true if value is "true" return false if value is "false" value ) return startup.processNextTick = -> tickDone = -> if tickInfo[kLength] isnt 0 if tickInfo[kLength] <= tickInfo[kIndex] nextTickQueue = [] tickInfo[kLength] = 0 else nextTickQueue.splice 0, tickInfo[kIndex] tickInfo[kLength] = nextTickQueue.length tickInfo[kIndex] = 0 return scheduleMicrotasks = -> return if microtasksScheduled nextTickQueue.push callback: runMicrotasksCallback domain: null tickInfo[kLength]++ microtasksScheduled = true return runMicrotasksCallback = -> microtasksScheduled = false _runMicrotasks() scheduleMicrotasks() if tickInfo[kIndex] < tickInfo[kLength] return _tickCallback = -> callback = undefined threw = undefined tock = undefined scheduleMicrotasks() while tickInfo[kIndex] < tickInfo[kLength] tock = nextTickQueue[tickInfo[kIndex]++] callback = tock.callback threw = true try callback() threw = false finally tickDone() if threw tickDone() if 1e4 < tickInfo[kIndex] tickDone() return _tickDomainCallback = -> callback = undefined domain = undefined threw = undefined tock = undefined scheduleMicrotasks() while tickInfo[kIndex] < tickInfo[kLength] tock = nextTickQueue[tickInfo[kIndex]++] callback = tock.callback domain = tock.domain domain.enter() if domain threw = true try callback() threw = false finally tickDone() if threw tickDone() if 1e4 < tickInfo[kIndex] domain.exit() if domain tickDone() return nextTick = (callback) -> return if process._exiting obj = callback: callback domain: process.domain or null nextTickQueue.push obj tickInfo[kLength]++ return nextTickQueue = [] microtasksScheduled = false _runMicrotasks = {} tickInfo = {} kIndex = 0 kLength = 1 process.nextTick = nextTick process._tickCallback = _tickCallback process._tickDomainCallback = _tickDomainCallback process._setupNextTick tickInfo, _tickCallback, _runMicrotasks _runMicrotasks = _runMicrotasks.runMicrotasks return startup.processStdio = -> stdin = undefined stdout = undefined stderr = undefined process.__defineGetter__ "stdout", -> return stdout if stdout stdout = createWritableStdioStream(1) stdout.destroy = stdout.destroySoon = (er) -> er = er or new Error("process.stdout cannot be closed.") stdout.emit "error", er return if stdout.isTTY process.on "SIGWINCH", -> stdout._refreshSize() return stdout process.__defineGetter__ "stderr", -> return stderr if stderr stderr = createWritableStdioStream(2) stderr.destroy = stderr.destroySoon = (er) -> er = er or new Error("process.stderr cannot be closed.") stderr.emit "error", er return stderr process.__defineGetter__ "stdin", -> return stdin if stdin tty_wrap = process.binding("tty_wrap") fd = 0 switch tty_wrap.guessHandleType(fd) when "TTY" tty = NativeModule.require("tty") stdin = new tty.ReadStream(fd, highWaterMark: 0 readable: true writable: false ) when "FILE" fs = NativeModule.require("fs") stdin = new fs.ReadStream(null, fd: fd autoClose: false ) when "PIPE", "TCP" net = NativeModule.require("net") if process._channel and process._channel.fd is fd stdin = new net.Socket( handle: process._channel readable: true writable: false ) else stdin = new net.Socket( fd: fd readable: true writable: false ) else throw new Error("Implement me. Unknown stdin file type!") stdin.fd = fd if stdin._handle and stdin._handle.readStop stdin._handle.reading = false stdin._readableState.reading = false stdin._handle.readStop() stdin.on "pause", -> return unless stdin._handle stdin._readableState.reading = false stdin._handle.reading = false stdin._handle.readStop() return stdin process.openStdin = -> process.stdin.resume() process.stdin return startup.processKillAndExit = -> process.exit = (code) -> process.exitCode = code if code or code is 0 unless process._exiting process._exiting = true process.emit "exit", process.exitCode or 0 process.reallyExit process.exitCode or 0 return process.kill = (pid, sig) -> err = undefined throw new TypeError("invalid pid") unless pid is (pid | 0) if 0 is sig err = process._kill(pid, 0) else sig = sig or "SIGTERM" if startup.lazyConstants()[sig] and sig.slice(0, 3) is "SIG" err = process._kill(pid, startup.lazyConstants()[sig]) else throw new Error("Unknown signal: " + sig) if err errnoException = NativeModule.require("util")._errnoException throw errnoException(err, "kill") true return startup.processSignalHandlers = -> isSignal = (event) -> event.slice(0, 3) is "SIG" and startup.lazyConstants().hasOwnProperty(event) signalWraps = {} addListener = process.addListener removeListener = process.removeListener process.on = process.addListener = (type, listener) -> if isSignal(type) and not signalWraps.hasOwnProperty(type) Signal = process.binding("signal_wrap").Signal wrap = new Signal() wrap.unref() wrap.onsignal = -> process.emit type return signum = startup.lazyConstants()[type] err = wrap.start(signum) if err wrap.close() errnoException = NativeModule.require("util")._errnoException throw errnoException(err, "uv_signal_start") signalWraps[type] = wrap addListener.apply this, arguments process.removeListener = (type, listener) -> ret = removeListener.apply(this, arguments) if isSignal(type) assert signalWraps.hasOwnProperty(type) if NativeModule.require("events").listenerCount(this, type) is 0 signalWraps[type].close() delete signalWraps[type] ret return startup.processChannel = -> if process.env.NODE_CHANNEL_FD fd = parseInt(process.env.NODE_CHANNEL_FD, 10) assert fd >= 0 delete process.env.NODE_CHANNEL_FD cp = NativeModule.require("child_process") process.binding "tcp_wrap" cp._forkChild fd assert process.send return startup.processRawDebug = -> format = NativeModule.require("util").format rawDebug = process._rawDebug process._rawDebug = -> rawDebug format.apply(null, arguments) return return startup.resolveArgv0 = -> cwd = process.cwd() isWindows = process.platform is "win32" argv0 = process.argv[0] if not isWindows and argv0.indexOf("/") isnt -1 and argv0.charAt(0) isnt "/" path = NativeModule.require("path") process.argv[0] = path.join(cwd, process.argv[0]) return ContextifyScript = process.binding("contextify").ContextifyScript NativeModule._source = process.binding("natives") NativeModule._cache = {} NativeModule.require = (id) -> return NativeModule if id is "native_module" cached = NativeModule.getCached(id) return cached.exports if cached throw new Error("No such native module " + id) unless NativeModule.exists(id) process.moduleLoadList.push "NativeModule " + id nativeModule = new NativeModule(id) nativeModule.cache() nativeModule.compile() nativeModule.exports NativeModule.getCached = (id) -> NativeModule._cache[id] NativeModule.exists = (id) -> NativeModule._source.hasOwnProperty id NativeModule.getSource = (id) -> NativeModule._source[id] NativeModule.wrap = (script) -> NativeModule.wrapper[0] + script + NativeModule.wrapper[1] NativeModule.wrapper = [ "(function (exports, require, module, __filename, __dirname) { " "\n});" ] NativeModule::compile = -> source = NativeModule.getSource(@id) source = NativeModule.wrap(source) fn = runInThisContext(source, filename: @filename ) fn @exports, NativeModule.require, this, @filename @loaded = true return NativeModule::cache = -> NativeModule._cache[@id] = this return startup() return
[ { "context": "e: \"Gmail\"\n auth: {user : email, pass : password}\n\n options.from = email\n\n smtpTrans", "end": 1444, "score": 0.9983733892440796, "start": 1436, "tag": "PASSWORD", "value": "password" } ]
src/api/util.coffee
bladepan/cloudbrowser
0
Nodemailer = require("nodemailer") cloudbrowserError = require("../shared/cloudbrowser_error") ###* @class Util @param {object} emailerConfig ### class Util _pvts = [] _instance = null constructor : (emailerConfig) -> # Singleton if _pvts.length then return _instance else _instance = this # Defining @_idx as a read-only property Object.defineProperty this, "_idx", value : _pvts.length # Setting private properties _pvts.push emailerConfig : emailerConfig Object.freeze(this.__proto__) Object.freeze(this) ###* Sends an email to the specified user. @static @method sendEmail @memberOf Util @param {Object} options @param {String} options.to @param {String} options.subject @param {String} options.html @param {errorCallback} callback ### sendEmail : (options) -> {callback} = options if not _pvts[@_idx].emailerConfig callback?(cloudbrowserError('NO_EMAIL_CONFIG')) return {email, password} = _pvts[@_idx].emailerConfig if not (email and password) callback?(cloudbrowserError('NO_EMAIL_CONFIG')) return smtpTransport = Nodemailer.createTransport "SMTP", service: "Gmail" auth: {user : email, pass : password} options.from = email smtpTransport.sendMail options, (err, response) -> smtpTransport.close() callback?(err) module.exports = Util
216270
Nodemailer = require("nodemailer") cloudbrowserError = require("../shared/cloudbrowser_error") ###* @class Util @param {object} emailerConfig ### class Util _pvts = [] _instance = null constructor : (emailerConfig) -> # Singleton if _pvts.length then return _instance else _instance = this # Defining @_idx as a read-only property Object.defineProperty this, "_idx", value : _pvts.length # Setting private properties _pvts.push emailerConfig : emailerConfig Object.freeze(this.__proto__) Object.freeze(this) ###* Sends an email to the specified user. @static @method sendEmail @memberOf Util @param {Object} options @param {String} options.to @param {String} options.subject @param {String} options.html @param {errorCallback} callback ### sendEmail : (options) -> {callback} = options if not _pvts[@_idx].emailerConfig callback?(cloudbrowserError('NO_EMAIL_CONFIG')) return {email, password} = _pvts[@_idx].emailerConfig if not (email and password) callback?(cloudbrowserError('NO_EMAIL_CONFIG')) return smtpTransport = Nodemailer.createTransport "SMTP", service: "Gmail" auth: {user : email, pass : <PASSWORD>} options.from = email smtpTransport.sendMail options, (err, response) -> smtpTransport.close() callback?(err) module.exports = Util
true
Nodemailer = require("nodemailer") cloudbrowserError = require("../shared/cloudbrowser_error") ###* @class Util @param {object} emailerConfig ### class Util _pvts = [] _instance = null constructor : (emailerConfig) -> # Singleton if _pvts.length then return _instance else _instance = this # Defining @_idx as a read-only property Object.defineProperty this, "_idx", value : _pvts.length # Setting private properties _pvts.push emailerConfig : emailerConfig Object.freeze(this.__proto__) Object.freeze(this) ###* Sends an email to the specified user. @static @method sendEmail @memberOf Util @param {Object} options @param {String} options.to @param {String} options.subject @param {String} options.html @param {errorCallback} callback ### sendEmail : (options) -> {callback} = options if not _pvts[@_idx].emailerConfig callback?(cloudbrowserError('NO_EMAIL_CONFIG')) return {email, password} = _pvts[@_idx].emailerConfig if not (email and password) callback?(cloudbrowserError('NO_EMAIL_CONFIG')) return smtpTransport = Nodemailer.createTransport "SMTP", service: "Gmail" auth: {user : email, pass : PI:PASSWORD:<PASSWORD>END_PI} options.from = email smtpTransport.sendMail options, (err, response) -> smtpTransport.close() callback?(err) module.exports = Util
[ { "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.9999200105667114, "start": 178, "tag": "EMAIL", "value": "info@chaibio.com" } ]
frontend/javascripts/app/controllers/settings_ctrl.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.App.controller 'SettingsCtrl', [ '$scope' 'User' 'Device' ($scope, User, Device) -> $scope.isBeta = true $scope.anotherExperimentInProgress = false $scope.checked = false $scope.$on 'status:data:updated', (e, data, oldData) -> return if !data return if !data.experiment_controller $scope.state = data.experiment_controller.machine.state if $scope.state isnt 'idle' $scope.anotherExperimentInProgress = true else $scope.anotherExperimentInProgress = false Device.getVersion(true).then (resp) -> $scope.has_serial_number = resp.serial_number User.getCurrent().then (resp) -> $scope.user = resp.data.user Device.getVersion().then (data) -> console.log data if data.software_release_variant == "beta" $scope.isBeta = true Device.isDualChannel() .then (resp) -> $scope.checked = true $scope.is_dual_channel = resp backdrop = $('.maintainance-backdrop') backdrop.css('height', $('.wizards-container').height()) ]
121406
### 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.App.controller 'SettingsCtrl', [ '$scope' 'User' 'Device' ($scope, User, Device) -> $scope.isBeta = true $scope.anotherExperimentInProgress = false $scope.checked = false $scope.$on 'status:data:updated', (e, data, oldData) -> return if !data return if !data.experiment_controller $scope.state = data.experiment_controller.machine.state if $scope.state isnt 'idle' $scope.anotherExperimentInProgress = true else $scope.anotherExperimentInProgress = false Device.getVersion(true).then (resp) -> $scope.has_serial_number = resp.serial_number User.getCurrent().then (resp) -> $scope.user = resp.data.user Device.getVersion().then (data) -> console.log data if data.software_release_variant == "beta" $scope.isBeta = true Device.isDualChannel() .then (resp) -> $scope.checked = true $scope.is_dual_channel = resp backdrop = $('.maintainance-backdrop') backdrop.css('height', $('.wizards-container').height()) ]
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.App.controller 'SettingsCtrl', [ '$scope' 'User' 'Device' ($scope, User, Device) -> $scope.isBeta = true $scope.anotherExperimentInProgress = false $scope.checked = false $scope.$on 'status:data:updated', (e, data, oldData) -> return if !data return if !data.experiment_controller $scope.state = data.experiment_controller.machine.state if $scope.state isnt 'idle' $scope.anotherExperimentInProgress = true else $scope.anotherExperimentInProgress = false Device.getVersion(true).then (resp) -> $scope.has_serial_number = resp.serial_number User.getCurrent().then (resp) -> $scope.user = resp.data.user Device.getVersion().then (data) -> console.log data if data.software_release_variant == "beta" $scope.isBeta = true Device.isDualChannel() .then (resp) -> $scope.checked = true $scope.is_dual_channel = resp backdrop = $('.maintainance-backdrop') backdrop.css('height', $('.wizards-container').height()) ]
[ { "context": "eoverview Tests for no-empty-class rule.\n# @author Ian Christian Myers\n###\n\n'use strict'\n\n#-----------------------------", "end": 81, "score": 0.9997540712356567, "start": 62, "tag": "NAME", "value": "Ian Christian Myers" } ]
src/tests/rules/no-empty-character-class.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for no-empty-class rule. # @author Ian Christian Myers ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-empty-character-class' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ### eslint-disable ### ruleTester.run 'no-empty-character-class', rule, valid: [ 'foo = /^abc[a-zA-Z]/' 'regExp = new RegExp("^abc[]")' 'foo = /^abc/' 'foo = /[\\[]/' 'foo = /[\\]]/' 'foo = /[a-zA-Z\\[]/' 'foo = /[[]/' 'foo = /[\\[a-z[]]/' 'foo = /[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\^\\$\\|]/g' 'foo = /\\s*:\\s*/gim' 'foo = /[\\]]/uy' 'foo = /[\\]]/s' 'foo = /\\[]/' ''' foo = /// x # [] /// ''' ''' foo = /// x # [] #{b []} /// ''' ''' ///#{a}\\
/// ''' ] invalid: [ code: 'foo = /^abc[]/' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'foo = ///^abc[]///' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'foo = /foo[]bar/' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'if foo.match(/^abc[]/) then yes' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'if /^abc[]/.test(foo) then yes' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'foo = /[]]/' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'foo = /\\[[]/' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'foo = /\\[\\[\\]a-z[]/' errors: [messageId: 'unexpected', type: 'Literal'] , code: ''' foo = /// x [] /// ''' errors: [messageId: 'unexpected', type: 'Literal'] , # eslint-disable-next-line coffee/no-template-curly-in-string code: ''' foo = /// x [] #{b []} /// ''' errors: [messageId: 'unexpected', type: 'InterpolatedRegExpLiteral'] ]
165824
###* # @fileoverview Tests for no-empty-class rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-empty-character-class' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ### eslint-disable ### ruleTester.run 'no-empty-character-class', rule, valid: [ 'foo = /^abc[a-zA-Z]/' 'regExp = new RegExp("^abc[]")' 'foo = /^abc/' 'foo = /[\\[]/' 'foo = /[\\]]/' 'foo = /[a-zA-Z\\[]/' 'foo = /[[]/' 'foo = /[\\[a-z[]]/' 'foo = /[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\^\\$\\|]/g' 'foo = /\\s*:\\s*/gim' 'foo = /[\\]]/uy' 'foo = /[\\]]/s' 'foo = /\\[]/' ''' foo = /// x # [] /// ''' ''' foo = /// x # [] #{b []} /// ''' ''' ///#{a}\\
/// ''' ] invalid: [ code: 'foo = /^abc[]/' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'foo = ///^abc[]///' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'foo = /foo[]bar/' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'if foo.match(/^abc[]/) then yes' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'if /^abc[]/.test(foo) then yes' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'foo = /[]]/' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'foo = /\\[[]/' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'foo = /\\[\\[\\]a-z[]/' errors: [messageId: 'unexpected', type: 'Literal'] , code: ''' foo = /// x [] /// ''' errors: [messageId: 'unexpected', type: 'Literal'] , # eslint-disable-next-line coffee/no-template-curly-in-string code: ''' foo = /// x [] #{b []} /// ''' errors: [messageId: 'unexpected', type: 'InterpolatedRegExpLiteral'] ]
true
###* # @fileoverview Tests for no-empty-class rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-empty-character-class' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ### eslint-disable ### ruleTester.run 'no-empty-character-class', rule, valid: [ 'foo = /^abc[a-zA-Z]/' 'regExp = new RegExp("^abc[]")' 'foo = /^abc/' 'foo = /[\\[]/' 'foo = /[\\]]/' 'foo = /[a-zA-Z\\[]/' 'foo = /[[]/' 'foo = /[\\[a-z[]]/' 'foo = /[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\^\\$\\|]/g' 'foo = /\\s*:\\s*/gim' 'foo = /[\\]]/uy' 'foo = /[\\]]/s' 'foo = /\\[]/' ''' foo = /// x # [] /// ''' ''' foo = /// x # [] #{b []} /// ''' ''' ///#{a}\\
/// ''' ] invalid: [ code: 'foo = /^abc[]/' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'foo = ///^abc[]///' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'foo = /foo[]bar/' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'if foo.match(/^abc[]/) then yes' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'if /^abc[]/.test(foo) then yes' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'foo = /[]]/' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'foo = /\\[[]/' errors: [messageId: 'unexpected', type: 'Literal'] , code: 'foo = /\\[\\[\\]a-z[]/' errors: [messageId: 'unexpected', type: 'Literal'] , code: ''' foo = /// x [] /// ''' errors: [messageId: 'unexpected', type: 'Literal'] , # eslint-disable-next-line coffee/no-template-curly-in-string code: ''' foo = /// x [] #{b []} /// ''' errors: [messageId: 'unexpected', type: 'InterpolatedRegExpLiteral'] ]
[ { "context": "# Copyright 2015, Christopher Joakim <christopher.joakim@gmail.com>\n\ndescribe 'Age', -", "end": 36, "score": 0.9998866319656372, "start": 18, "tag": "NAME", "value": "Christopher Joakim" }, { "context": "# Copyright 2015, Christopher Joakim <christopher.joakim@gmail.com>\n\ndescribe 'Age', ->\n\n it \"should construct with", "end": 66, "score": 0.9999334216117859, "start": 38, "tag": "EMAIL", "value": "christopher.joakim@gmail.com" } ]
m26-js/test-src/m26_age_spec.coffee
cjoakim/oss
0
# Copyright 2015, Christopher Joakim <christopher.joakim@gmail.com> describe 'Age', -> it "should construct with either a String or Number arg", -> a1 = new Age(44.4) a2 = new Age('55.5') expect(a1.val()).isWithin(0.0000000001, 44.4) expect(a2.val()).isWithin(0.0000000001, 55.5) it "should calculate max_pulse", -> a16 = new Age(16) a20 = new Age('20') a21 = new Age(21) a36 = new Age(36) a57 = new Age('57') expect(a16.max_pulse()).isWithin(0.0000000001, 200.0) expect(a20.max_pulse()).isWithin(0.0000000001, 200.0) expect(a21.max_pulse()).isWithin(0.0000000001, 199.0) expect(a36.max_pulse()).isWithin(0.0000000001, 184.0) expect(a57.max_pulse()).isWithin(0.0000000001, 163.0) it "should add and subtract", -> a16 = new Age(16.9) a57 = new Age(57.1) sum = a57.add(a16) diff = a57.subtract(a16) expect(sum).isWithin(0.0000000001, 74.0) expect(diff).isWithin(0.0000000001, 40.2) it "should calculate heart-rate training-zones", -> a57 = new Age(57.1) zones = a57.training_zones() # console.log(JSON.stringify(zones, null, 2)) expect(zones.length).toBe(5) z1 = zones[0] z5 = zones[4] expect(z1.zone).toBe(1) expect(z1.pulse).toBe(155) expect(z1.age).isWithin(0.001, 57.1) expect(z1.pct_max).isWithin(0.001, 0.95) expect(z1.max).isWithin(0.001, 162.9) expect(z5.zone).toBe(5) expect(z5.pulse).toBe(122) expect(z5.age).isWithin(0.001, 57.1) expect(z5.pct_max).isWithin(0.001, 0.75) expect(z5.max).isWithin(0.001, 162.9)
155255
# Copyright 2015, <NAME> <<EMAIL>> describe 'Age', -> it "should construct with either a String or Number arg", -> a1 = new Age(44.4) a2 = new Age('55.5') expect(a1.val()).isWithin(0.0000000001, 44.4) expect(a2.val()).isWithin(0.0000000001, 55.5) it "should calculate max_pulse", -> a16 = new Age(16) a20 = new Age('20') a21 = new Age(21) a36 = new Age(36) a57 = new Age('57') expect(a16.max_pulse()).isWithin(0.0000000001, 200.0) expect(a20.max_pulse()).isWithin(0.0000000001, 200.0) expect(a21.max_pulse()).isWithin(0.0000000001, 199.0) expect(a36.max_pulse()).isWithin(0.0000000001, 184.0) expect(a57.max_pulse()).isWithin(0.0000000001, 163.0) it "should add and subtract", -> a16 = new Age(16.9) a57 = new Age(57.1) sum = a57.add(a16) diff = a57.subtract(a16) expect(sum).isWithin(0.0000000001, 74.0) expect(diff).isWithin(0.0000000001, 40.2) it "should calculate heart-rate training-zones", -> a57 = new Age(57.1) zones = a57.training_zones() # console.log(JSON.stringify(zones, null, 2)) expect(zones.length).toBe(5) z1 = zones[0] z5 = zones[4] expect(z1.zone).toBe(1) expect(z1.pulse).toBe(155) expect(z1.age).isWithin(0.001, 57.1) expect(z1.pct_max).isWithin(0.001, 0.95) expect(z1.max).isWithin(0.001, 162.9) expect(z5.zone).toBe(5) expect(z5.pulse).toBe(122) expect(z5.age).isWithin(0.001, 57.1) expect(z5.pct_max).isWithin(0.001, 0.75) expect(z5.max).isWithin(0.001, 162.9)
true
# Copyright 2015, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> describe 'Age', -> it "should construct with either a String or Number arg", -> a1 = new Age(44.4) a2 = new Age('55.5') expect(a1.val()).isWithin(0.0000000001, 44.4) expect(a2.val()).isWithin(0.0000000001, 55.5) it "should calculate max_pulse", -> a16 = new Age(16) a20 = new Age('20') a21 = new Age(21) a36 = new Age(36) a57 = new Age('57') expect(a16.max_pulse()).isWithin(0.0000000001, 200.0) expect(a20.max_pulse()).isWithin(0.0000000001, 200.0) expect(a21.max_pulse()).isWithin(0.0000000001, 199.0) expect(a36.max_pulse()).isWithin(0.0000000001, 184.0) expect(a57.max_pulse()).isWithin(0.0000000001, 163.0) it "should add and subtract", -> a16 = new Age(16.9) a57 = new Age(57.1) sum = a57.add(a16) diff = a57.subtract(a16) expect(sum).isWithin(0.0000000001, 74.0) expect(diff).isWithin(0.0000000001, 40.2) it "should calculate heart-rate training-zones", -> a57 = new Age(57.1) zones = a57.training_zones() # console.log(JSON.stringify(zones, null, 2)) expect(zones.length).toBe(5) z1 = zones[0] z5 = zones[4] expect(z1.zone).toBe(1) expect(z1.pulse).toBe(155) expect(z1.age).isWithin(0.001, 57.1) expect(z1.pct_max).isWithin(0.001, 0.95) expect(z1.max).isWithin(0.001, 162.9) expect(z5.zone).toBe(5) expect(z5.pulse).toBe(122) expect(z5.age).isWithin(0.001, 57.1) expect(z5.pct_max).isWithin(0.001, 0.75) expect(z5.max).isWithin(0.001, 162.9)
[ { "context": "# Backbone.CollectionSubset\n# https://github.com/anthonyshort/backbone.collectionsubset\n#\n# Copyright (c) 2012 ", "end": 61, "score": 0.9994368553161621, "start": 49, "tag": "USERNAME", "value": "anthonyshort" }, { "context": "t/backbone.collectionsubset\n#\n# Copyright (c) 2012 Anthony Short\n# Licensed under the MIT license.\n\n# This allows ", "end": 124, "score": 0.9998605847358704, "start": 111, "tag": "NAME", "value": "Anthony Short" } ]
src/backbone.collectionsubset.coffee
anthonyshort/backbone.collectionsubset
10
# Backbone.CollectionSubset # https://github.com/anthonyshort/backbone.collectionsubset # # Copyright (c) 2012 Anthony Short # Licensed under the MIT license. # This allows you to create a subset of a collection based # on a filter function. This new collection will stay in sync # with the main collection. When a model is added to the main # collection it will automatically be added to the child collection # if it matches a filter. # # Triggers can be set that will allow the child collection to # only update when particular attributes are changed. This should # be set for every subset. # # The subset will be autoamtically disposed when either the parent # or the child collection is disposed. If the parent collection is # disposed of then the child collection will also be disposed of. class Backbone.CollectionSubset # Borrow the extend method @extend: Backbone.Model.extend _.extend @::, Backbone.Events constructor: (options = {})-> options = _.defaults options, refresh: true triggers: null filter: -> true name: null child: null parent: null @triggers = if options.triggers then options.triggers.split(' ') else [] options.child = new options.parent.constructor unless options.child @setParent(options.parent) @setChild(options.child) @setFilter(options.filter) @child.model = options.model if options.model @refresh() if options.refresh @name = options.name # Set the parent collection. This attached a number of # event handlers to the collection. It also removed any # event handlers that this collection may have already # added to the parent. setParent: (collection) -> @parent?.off(null,null,@) @parent = collection @parent.on 'add', @_onParentAdd, @ @parent.on 'remove', @_onParentRemove, @ @parent.on 'reset', @_onParentReset, @ @parent.on 'change', @_onParentChange, @ @parent.on 'dispose', @dispose, @ @parent.on 'loading', (=> @child.trigger('loading')), @ @parent.on 'ready', (=> @child.trigger('ready')), @ # Set the child collection. This attached a number of event # handlers to the child and removed any events that were # previously created by this subset. It is possible to access # the subset from the child collection via .filterer and the parent # collection via .parent. The child URL is automatically set # to the parents URL as with the model. setChild: (collection) -> @child?.off(null,null,@) @child = collection @child.on 'add', @_onChildAdd, @ @child.on 'reset', @_onChildReset, @ @child.on 'dispose', @dispose, @ @child.superset = @parent @child.filterer = @ @child.url = @parent.url @child.model = @parent.model # This method must be called to set the filter. It binds the method # to the correct context and fires off any parent filters. This allows you # to have subsets of subsets. setFilter: (fn)-> filter = (model)-> matchesFilter = fn.call @,model matchesParentFilter = if @parent.filterer then @parent.filterer.filter(model) else true return matchesFilter and matchesParentFilter @filter = _.bind(filter, @) # Reset the child collection completely with matching models # from the parent collection and trigger an event. refresh: (options = {})-> models = @parent.filter(@filter) @child.reset(models,{subset:this}) @child.trigger 'refresh' # Replaces a model object on the child with the model object # from the parent. This means they are always using the same # object for models. _replaceChildModel: (parentModel)-> childModel = @_getByCid(@child, parentModel.cid) return if childModel is parentModel if _.isUndefined(childModel) @child.add(parentModel,subset:this) else index = @child.indexOf(childModel) @child.remove(childModel) @child.add(parentModel,{at:index,subset:this}) # When a model is added to the parent collection # Add it to the child if it matches the filter. _onParentAdd: (model,collection,options)-> return if options && options.subset is this if @filter(model) @_replaceChildModel(model) # When a model is removed from the parent # remove it from the child _onParentRemove: (model,collection,options)-> @child.remove(model,options) # When the parent is reset refrehs the child _onParentReset: (collection,options)-> @refresh() # When a model changes in the parent, check to see # if the attribute changed was one of the triggers. # if so, then add or remove from to the child _onParentChange: (model,changes)-> return unless @triggerMatched(model) if @filter(model) @child.add(model) else @child.remove(model) # When a model is added to the child # If the parent has the model replace the one just added to the child _onChildAdd: (model,collection,options)-> return if options && options.subset is this @parent.add(model) parentModel = @_getByCid(@parent, model.cid) return unless parentModel if @filter(parentModel) @_replaceChildModel(parentModel) else @child.remove(model) # After the child fetches we need to get all the models # from the child, add them to the parent, and then # reset the child with the models from the parent # so they use the same model references _onChildReset: (collection,options)-> return if options && options.subset is this @parent.add(@child.models) @refresh() # Get a model by it's cid. Backbone 0.9.9 removes getByCid as # get now handles cid transparently. _getByCid: (model, cid) -> fn = model.getByCid || model.get fn.apply(model, [cid]) # Determine if a trigger attribute was changed triggerMatched: (model)-> return true if @triggers.length is 0 return false unless model.hasChanged() changedAttrs = _.keys(model.changedAttributes()) _.intersection(@triggers,changedAttrs).length > 0 # Remove all event handlers for the subset from both the # parent and the child. Remove the child collection. dispose: -> return if @disposed @trigger 'dispose', this @parent.off null,null,@ @child.off null,null,@ @child.dispose?() @off() delete this[prop] for prop in ['parent','child','options'] @disposed = true Backbone.Collection::subcollection = (options = {}) -> _.defaults options, child: new this.constructor parent: this subset = new Backbone.CollectionSubset(options) subset.child module?.exports = Backbone.CollectionSubset
49537
# Backbone.CollectionSubset # https://github.com/anthonyshort/backbone.collectionsubset # # Copyright (c) 2012 <NAME> # Licensed under the MIT license. # This allows you to create a subset of a collection based # on a filter function. This new collection will stay in sync # with the main collection. When a model is added to the main # collection it will automatically be added to the child collection # if it matches a filter. # # Triggers can be set that will allow the child collection to # only update when particular attributes are changed. This should # be set for every subset. # # The subset will be autoamtically disposed when either the parent # or the child collection is disposed. If the parent collection is # disposed of then the child collection will also be disposed of. class Backbone.CollectionSubset # Borrow the extend method @extend: Backbone.Model.extend _.extend @::, Backbone.Events constructor: (options = {})-> options = _.defaults options, refresh: true triggers: null filter: -> true name: null child: null parent: null @triggers = if options.triggers then options.triggers.split(' ') else [] options.child = new options.parent.constructor unless options.child @setParent(options.parent) @setChild(options.child) @setFilter(options.filter) @child.model = options.model if options.model @refresh() if options.refresh @name = options.name # Set the parent collection. This attached a number of # event handlers to the collection. It also removed any # event handlers that this collection may have already # added to the parent. setParent: (collection) -> @parent?.off(null,null,@) @parent = collection @parent.on 'add', @_onParentAdd, @ @parent.on 'remove', @_onParentRemove, @ @parent.on 'reset', @_onParentReset, @ @parent.on 'change', @_onParentChange, @ @parent.on 'dispose', @dispose, @ @parent.on 'loading', (=> @child.trigger('loading')), @ @parent.on 'ready', (=> @child.trigger('ready')), @ # Set the child collection. This attached a number of event # handlers to the child and removed any events that were # previously created by this subset. It is possible to access # the subset from the child collection via .filterer and the parent # collection via .parent. The child URL is automatically set # to the parents URL as with the model. setChild: (collection) -> @child?.off(null,null,@) @child = collection @child.on 'add', @_onChildAdd, @ @child.on 'reset', @_onChildReset, @ @child.on 'dispose', @dispose, @ @child.superset = @parent @child.filterer = @ @child.url = @parent.url @child.model = @parent.model # This method must be called to set the filter. It binds the method # to the correct context and fires off any parent filters. This allows you # to have subsets of subsets. setFilter: (fn)-> filter = (model)-> matchesFilter = fn.call @,model matchesParentFilter = if @parent.filterer then @parent.filterer.filter(model) else true return matchesFilter and matchesParentFilter @filter = _.bind(filter, @) # Reset the child collection completely with matching models # from the parent collection and trigger an event. refresh: (options = {})-> models = @parent.filter(@filter) @child.reset(models,{subset:this}) @child.trigger 'refresh' # Replaces a model object on the child with the model object # from the parent. This means they are always using the same # object for models. _replaceChildModel: (parentModel)-> childModel = @_getByCid(@child, parentModel.cid) return if childModel is parentModel if _.isUndefined(childModel) @child.add(parentModel,subset:this) else index = @child.indexOf(childModel) @child.remove(childModel) @child.add(parentModel,{at:index,subset:this}) # When a model is added to the parent collection # Add it to the child if it matches the filter. _onParentAdd: (model,collection,options)-> return if options && options.subset is this if @filter(model) @_replaceChildModel(model) # When a model is removed from the parent # remove it from the child _onParentRemove: (model,collection,options)-> @child.remove(model,options) # When the parent is reset refrehs the child _onParentReset: (collection,options)-> @refresh() # When a model changes in the parent, check to see # if the attribute changed was one of the triggers. # if so, then add or remove from to the child _onParentChange: (model,changes)-> return unless @triggerMatched(model) if @filter(model) @child.add(model) else @child.remove(model) # When a model is added to the child # If the parent has the model replace the one just added to the child _onChildAdd: (model,collection,options)-> return if options && options.subset is this @parent.add(model) parentModel = @_getByCid(@parent, model.cid) return unless parentModel if @filter(parentModel) @_replaceChildModel(parentModel) else @child.remove(model) # After the child fetches we need to get all the models # from the child, add them to the parent, and then # reset the child with the models from the parent # so they use the same model references _onChildReset: (collection,options)-> return if options && options.subset is this @parent.add(@child.models) @refresh() # Get a model by it's cid. Backbone 0.9.9 removes getByCid as # get now handles cid transparently. _getByCid: (model, cid) -> fn = model.getByCid || model.get fn.apply(model, [cid]) # Determine if a trigger attribute was changed triggerMatched: (model)-> return true if @triggers.length is 0 return false unless model.hasChanged() changedAttrs = _.keys(model.changedAttributes()) _.intersection(@triggers,changedAttrs).length > 0 # Remove all event handlers for the subset from both the # parent and the child. Remove the child collection. dispose: -> return if @disposed @trigger 'dispose', this @parent.off null,null,@ @child.off null,null,@ @child.dispose?() @off() delete this[prop] for prop in ['parent','child','options'] @disposed = true Backbone.Collection::subcollection = (options = {}) -> _.defaults options, child: new this.constructor parent: this subset = new Backbone.CollectionSubset(options) subset.child module?.exports = Backbone.CollectionSubset
true
# Backbone.CollectionSubset # https://github.com/anthonyshort/backbone.collectionsubset # # Copyright (c) 2012 PI:NAME:<NAME>END_PI # Licensed under the MIT license. # This allows you to create a subset of a collection based # on a filter function. This new collection will stay in sync # with the main collection. When a model is added to the main # collection it will automatically be added to the child collection # if it matches a filter. # # Triggers can be set that will allow the child collection to # only update when particular attributes are changed. This should # be set for every subset. # # The subset will be autoamtically disposed when either the parent # or the child collection is disposed. If the parent collection is # disposed of then the child collection will also be disposed of. class Backbone.CollectionSubset # Borrow the extend method @extend: Backbone.Model.extend _.extend @::, Backbone.Events constructor: (options = {})-> options = _.defaults options, refresh: true triggers: null filter: -> true name: null child: null parent: null @triggers = if options.triggers then options.triggers.split(' ') else [] options.child = new options.parent.constructor unless options.child @setParent(options.parent) @setChild(options.child) @setFilter(options.filter) @child.model = options.model if options.model @refresh() if options.refresh @name = options.name # Set the parent collection. This attached a number of # event handlers to the collection. It also removed any # event handlers that this collection may have already # added to the parent. setParent: (collection) -> @parent?.off(null,null,@) @parent = collection @parent.on 'add', @_onParentAdd, @ @parent.on 'remove', @_onParentRemove, @ @parent.on 'reset', @_onParentReset, @ @parent.on 'change', @_onParentChange, @ @parent.on 'dispose', @dispose, @ @parent.on 'loading', (=> @child.trigger('loading')), @ @parent.on 'ready', (=> @child.trigger('ready')), @ # Set the child collection. This attached a number of event # handlers to the child and removed any events that were # previously created by this subset. It is possible to access # the subset from the child collection via .filterer and the parent # collection via .parent. The child URL is automatically set # to the parents URL as with the model. setChild: (collection) -> @child?.off(null,null,@) @child = collection @child.on 'add', @_onChildAdd, @ @child.on 'reset', @_onChildReset, @ @child.on 'dispose', @dispose, @ @child.superset = @parent @child.filterer = @ @child.url = @parent.url @child.model = @parent.model # This method must be called to set the filter. It binds the method # to the correct context and fires off any parent filters. This allows you # to have subsets of subsets. setFilter: (fn)-> filter = (model)-> matchesFilter = fn.call @,model matchesParentFilter = if @parent.filterer then @parent.filterer.filter(model) else true return matchesFilter and matchesParentFilter @filter = _.bind(filter, @) # Reset the child collection completely with matching models # from the parent collection and trigger an event. refresh: (options = {})-> models = @parent.filter(@filter) @child.reset(models,{subset:this}) @child.trigger 'refresh' # Replaces a model object on the child with the model object # from the parent. This means they are always using the same # object for models. _replaceChildModel: (parentModel)-> childModel = @_getByCid(@child, parentModel.cid) return if childModel is parentModel if _.isUndefined(childModel) @child.add(parentModel,subset:this) else index = @child.indexOf(childModel) @child.remove(childModel) @child.add(parentModel,{at:index,subset:this}) # When a model is added to the parent collection # Add it to the child if it matches the filter. _onParentAdd: (model,collection,options)-> return if options && options.subset is this if @filter(model) @_replaceChildModel(model) # When a model is removed from the parent # remove it from the child _onParentRemove: (model,collection,options)-> @child.remove(model,options) # When the parent is reset refrehs the child _onParentReset: (collection,options)-> @refresh() # When a model changes in the parent, check to see # if the attribute changed was one of the triggers. # if so, then add or remove from to the child _onParentChange: (model,changes)-> return unless @triggerMatched(model) if @filter(model) @child.add(model) else @child.remove(model) # When a model is added to the child # If the parent has the model replace the one just added to the child _onChildAdd: (model,collection,options)-> return if options && options.subset is this @parent.add(model) parentModel = @_getByCid(@parent, model.cid) return unless parentModel if @filter(parentModel) @_replaceChildModel(parentModel) else @child.remove(model) # After the child fetches we need to get all the models # from the child, add them to the parent, and then # reset the child with the models from the parent # so they use the same model references _onChildReset: (collection,options)-> return if options && options.subset is this @parent.add(@child.models) @refresh() # Get a model by it's cid. Backbone 0.9.9 removes getByCid as # get now handles cid transparently. _getByCid: (model, cid) -> fn = model.getByCid || model.get fn.apply(model, [cid]) # Determine if a trigger attribute was changed triggerMatched: (model)-> return true if @triggers.length is 0 return false unless model.hasChanged() changedAttrs = _.keys(model.changedAttributes()) _.intersection(@triggers,changedAttrs).length > 0 # Remove all event handlers for the subset from both the # parent and the child. Remove the child collection. dispose: -> return if @disposed @trigger 'dispose', this @parent.off null,null,@ @child.off null,null,@ @child.dispose?() @off() delete this[prop] for prop in ['parent','child','options'] @disposed = true Backbone.Collection::subcollection = (options = {}) -> _.defaults options, child: new this.constructor parent: this subset = new Backbone.CollectionSubset(options) subset.child module?.exports = Backbone.CollectionSubset
[ { "context": "# Copyright (c) 2013 Taher Haveliwala\n# All Rights Reserved\n#\n# util.coffee\n#\n# See LIC", "end": 37, "score": 0.999867856502533, "start": 21, "tag": "NAME", "value": "Taher Haveliwala" } ]
src/coffeescript/util.coffee
taherh/Astro
0
# Copyright (c) 2013 Taher Haveliwala # All Rights Reserved # # util.coffee # # See LICENSE for licensing # window.Asteroids = {} if not window.Asteroids util = Asteroids.util = {} util.sign = (x) -> return if x > 0 then 1 else if x < 0 then -1 else 0 util.cap = (val, max) -> if Math.abs(val) >= max return util.sign(val) * max else return max util.toRad = (degrees) -> return degrees * (Math.PI / 180) util.toDeg = (radians) -> return radians * (180 / Math.PI) util.getAngle = (y, x) -> angle = Math.atan2(y, x) if angle >= 0 return angle else return angle + 2*Math.PI util.remove = (list, obj) -> list.splice(list.indexOf(obj), 1)
89432
# Copyright (c) 2013 <NAME> # All Rights Reserved # # util.coffee # # See LICENSE for licensing # window.Asteroids = {} if not window.Asteroids util = Asteroids.util = {} util.sign = (x) -> return if x > 0 then 1 else if x < 0 then -1 else 0 util.cap = (val, max) -> if Math.abs(val) >= max return util.sign(val) * max else return max util.toRad = (degrees) -> return degrees * (Math.PI / 180) util.toDeg = (radians) -> return radians * (180 / Math.PI) util.getAngle = (y, x) -> angle = Math.atan2(y, x) if angle >= 0 return angle else return angle + 2*Math.PI util.remove = (list, obj) -> list.splice(list.indexOf(obj), 1)
true
# Copyright (c) 2013 PI:NAME:<NAME>END_PI # All Rights Reserved # # util.coffee # # See LICENSE for licensing # window.Asteroids = {} if not window.Asteroids util = Asteroids.util = {} util.sign = (x) -> return if x > 0 then 1 else if x < 0 then -1 else 0 util.cap = (val, max) -> if Math.abs(val) >= max return util.sign(val) * max else return max util.toRad = (degrees) -> return degrees * (Math.PI / 180) util.toDeg = (radians) -> return radians * (180 / Math.PI) util.getAngle = (y, x) -> angle = Math.atan2(y, x) if angle >= 0 return angle else return angle + 2*Math.PI util.remove = (list, obj) -> list.splice(list.indexOf(obj), 1)
[ { "context": " 2015\n# The MIT License (MIT)\n# Copyright (c) 2015 Dustin Dowell\n# github.com/dustindowell22/drop-down\n# =========", "end": 98, "score": 0.9998379945755005, "start": 85, "tag": "NAME", "value": "Dustin Dowell" }, { "context": ")\n# Copyright (c) 2015 Dustin Dowell\n# github.com/dustindowell22/drop-down\n# =====================================", "end": 126, "score": 0.9928282499313354, "start": 112, "tag": "USERNAME", "value": "dustindowell22" } ]
jquery.drop-down.coffee
dustin-archive/drop-down
2
# Drop Down - 1.0.4 # September 2, 2015 # The MIT License (MIT) # Copyright (c) 2015 Dustin Dowell # github.com/dustindowell22/drop-down # ============================================== (($) -> $.fn.dropDown = (toggleClass = 'toggled') -> # Cache this object $this = $(this) # $ul = $this.find('ul') $li = $this.find('li') $a = $this.find('a') # $button = $ul.siblings($a) # Buttons are anchors that are siblings to an unordered-list $parent = $a.closest($li) # Parents are list-items that are parents to anchors $drawer = $a.siblings($ul) # Drawers are unordered-lists that are siblings to anchors $link = $a.not($button) # Links are anchors that are not buttons $listItem = $li.has($a) # List-items contain anchors # $button.click (event) -> event.preventDefault() # Cached object names in this function are preceded by a 'c' $cButton = $(this) $cParent = $cButton.parent() $cUncle = $cParent.siblings() $cCousin = $cUncle.find($li) $cDrawer = $cButton.siblings($ul) $cDrawerListItem = $cDrawer.find($listItem) # These variable names kinda suck $cNestedDrawer = $cDrawer.find($drawer) # These variable names kinda suck # if $cParent.hasClass(toggleClass) $cParent.removeClass(toggleClass) $cDrawer.css('height', '') else $cParent.addClass(toggleClass) # Reset children if $cDrawerListItem.hasClass(toggleClass) $cDrawerListItem.removeClass(toggleClass) $cNestedDrawer.css('height', '') # Reset uncles if $cUncle.hasClass(toggleClass) $cUncle.removeClass(toggleClass) $cUncle.children($drawer).css('height', '') # Reset cousins if $cCousin.hasClass(toggleClass) $cCousin.removeClass(toggleClass) $cCousin.children($drawer).css('height', '') # Animate auto $drawer.update().reverse().each -> # Cached object names in this function are preceded by an 'a' $aDrawer = $(this) $aParent = $aDrawer.parent() if $aParent.hasClass(toggleClass) $aClone = $aDrawer.clone().css('display', 'none').appendTo($aParent) height = $aClone.css('height', 'auto').outerHeight() + 'px' $aClone.remove() $aDrawer.css('height', '').css('height', height) # closeMenu = -> if $parent.hasClass(toggleClass) $parent.removeClass(toggleClass) $drawer.css('height', '') # $link.click -> closeMenu() # $(document).on 'click focusin', (event) -> if not $(event.target).closest($button.parent()).length closeMenu() # Allow chaining return this ) jQuery
10419
# Drop Down - 1.0.4 # September 2, 2015 # The MIT License (MIT) # Copyright (c) 2015 <NAME> # github.com/dustindowell22/drop-down # ============================================== (($) -> $.fn.dropDown = (toggleClass = 'toggled') -> # Cache this object $this = $(this) # $ul = $this.find('ul') $li = $this.find('li') $a = $this.find('a') # $button = $ul.siblings($a) # Buttons are anchors that are siblings to an unordered-list $parent = $a.closest($li) # Parents are list-items that are parents to anchors $drawer = $a.siblings($ul) # Drawers are unordered-lists that are siblings to anchors $link = $a.not($button) # Links are anchors that are not buttons $listItem = $li.has($a) # List-items contain anchors # $button.click (event) -> event.preventDefault() # Cached object names in this function are preceded by a 'c' $cButton = $(this) $cParent = $cButton.parent() $cUncle = $cParent.siblings() $cCousin = $cUncle.find($li) $cDrawer = $cButton.siblings($ul) $cDrawerListItem = $cDrawer.find($listItem) # These variable names kinda suck $cNestedDrawer = $cDrawer.find($drawer) # These variable names kinda suck # if $cParent.hasClass(toggleClass) $cParent.removeClass(toggleClass) $cDrawer.css('height', '') else $cParent.addClass(toggleClass) # Reset children if $cDrawerListItem.hasClass(toggleClass) $cDrawerListItem.removeClass(toggleClass) $cNestedDrawer.css('height', '') # Reset uncles if $cUncle.hasClass(toggleClass) $cUncle.removeClass(toggleClass) $cUncle.children($drawer).css('height', '') # Reset cousins if $cCousin.hasClass(toggleClass) $cCousin.removeClass(toggleClass) $cCousin.children($drawer).css('height', '') # Animate auto $drawer.update().reverse().each -> # Cached object names in this function are preceded by an 'a' $aDrawer = $(this) $aParent = $aDrawer.parent() if $aParent.hasClass(toggleClass) $aClone = $aDrawer.clone().css('display', 'none').appendTo($aParent) height = $aClone.css('height', 'auto').outerHeight() + 'px' $aClone.remove() $aDrawer.css('height', '').css('height', height) # closeMenu = -> if $parent.hasClass(toggleClass) $parent.removeClass(toggleClass) $drawer.css('height', '') # $link.click -> closeMenu() # $(document).on 'click focusin', (event) -> if not $(event.target).closest($button.parent()).length closeMenu() # Allow chaining return this ) jQuery
true
# Drop Down - 1.0.4 # September 2, 2015 # The MIT License (MIT) # Copyright (c) 2015 PI:NAME:<NAME>END_PI # github.com/dustindowell22/drop-down # ============================================== (($) -> $.fn.dropDown = (toggleClass = 'toggled') -> # Cache this object $this = $(this) # $ul = $this.find('ul') $li = $this.find('li') $a = $this.find('a') # $button = $ul.siblings($a) # Buttons are anchors that are siblings to an unordered-list $parent = $a.closest($li) # Parents are list-items that are parents to anchors $drawer = $a.siblings($ul) # Drawers are unordered-lists that are siblings to anchors $link = $a.not($button) # Links are anchors that are not buttons $listItem = $li.has($a) # List-items contain anchors # $button.click (event) -> event.preventDefault() # Cached object names in this function are preceded by a 'c' $cButton = $(this) $cParent = $cButton.parent() $cUncle = $cParent.siblings() $cCousin = $cUncle.find($li) $cDrawer = $cButton.siblings($ul) $cDrawerListItem = $cDrawer.find($listItem) # These variable names kinda suck $cNestedDrawer = $cDrawer.find($drawer) # These variable names kinda suck # if $cParent.hasClass(toggleClass) $cParent.removeClass(toggleClass) $cDrawer.css('height', '') else $cParent.addClass(toggleClass) # Reset children if $cDrawerListItem.hasClass(toggleClass) $cDrawerListItem.removeClass(toggleClass) $cNestedDrawer.css('height', '') # Reset uncles if $cUncle.hasClass(toggleClass) $cUncle.removeClass(toggleClass) $cUncle.children($drawer).css('height', '') # Reset cousins if $cCousin.hasClass(toggleClass) $cCousin.removeClass(toggleClass) $cCousin.children($drawer).css('height', '') # Animate auto $drawer.update().reverse().each -> # Cached object names in this function are preceded by an 'a' $aDrawer = $(this) $aParent = $aDrawer.parent() if $aParent.hasClass(toggleClass) $aClone = $aDrawer.clone().css('display', 'none').appendTo($aParent) height = $aClone.css('height', 'auto').outerHeight() + 'px' $aClone.remove() $aDrawer.css('height', '').css('height', height) # closeMenu = -> if $parent.hasClass(toggleClass) $parent.removeClass(toggleClass) $drawer.css('height', '') # $link.click -> closeMenu() # $(document).on 'click focusin', (event) -> if not $(event.target).closest($button.parent()).length closeMenu() # Allow chaining return this ) jQuery
[ { "context": ".0-pre'\ndescription: 'A npb seed project.'\nauthor: ':FooTearth <footearth@gmail.com>'\n# main: ''\nlicense: 'MIT'\n", "end": 108, "score": 0.9923355579376221, "start": 97, "tag": "USERNAME", "value": "':FooTearth" }, { "context": "ption: 'A npb seed project.'\nauthor: ':FooTearth <footearth@gmail.com>'\n# main: ''\nlicense: 'MIT'\nrepository:\n type: '", "end": 129, "score": 0.999927818775177, "start": 110, "tag": "EMAIL", "value": "footearth@gmail.com" }, { "context": "ository:\n type: 'git'\n url: 'https://github.com/Mooxe000/npb-seed.git'\nbugs:\n url: 'https://github.com/Mo", "end": 219, "score": 0.9993723034858704, "start": 211, "tag": "USERNAME", "value": "Mooxe000" }, { "context": "00/npb-seed.git'\nbugs:\n url: 'https://github.com/Mooxe000/npb-seed/issues'\nhomepage: 'https://github.com/Mo", "end": 275, "score": 0.9994401931762695, "start": 267, "tag": "USERNAME", "value": "Mooxe000" }, { "context": "00/npb-seed/issues'\nhomepage: 'https://github.com/Mooxe000/npb-seed'\nKeywords: [\n 'npb'\n 'seed'\n 'example", "end": 331, "score": 0.9989583492279053, "start": 323, "tag": "USERNAME", "value": "Mooxe000" } ]
npb.cson
Mooxe000/npb-seed
0
# PUBLIC CONFIG name: 'npb-seed' version: '0.0.0-pre' description: 'A npb seed project.' author: ':FooTearth <footearth@gmail.com>' # main: '' license: 'MIT' repository: type: 'git' url: 'https://github.com/Mooxe000/npb-seed.git' bugs: url: 'https://github.com/Mooxe000/npb-seed/issues' homepage: 'https://github.com/Mooxe000/npb-seed' Keywords: [ 'npb' 'seed' 'example' 'coffee' ] # BOWER CONFIG bower: dependencies: 'angularjs': 'angular.js' 'bootstrap' : [ 'dist/css/bootstrap.css' 'dist/fonts/glyphicons-halflings-regular.eot' 'dist/fonts/glyphicons-halflings-regular.svg' 'dist/fonts/glyphicons-halflings-regular.ttf' 'dist/fonts/glyphicons-halflings-regular.woff' ] 'jquery': 'dist/jquery.js' 'angular-route': 'angular-route.js' 'angular-resource': 'angular-resource.js' 'angular-animate': 'angular-animate.js' devDependencies: [] # NPM CONFIG npm: bin: {} scripts: test: '' dependencies: [] devDependencies: [ 'coffee-script' 'npb-coffee' 'lodash' 'del' gulp: [ # dev 'gulp-filter' 'gulp-coffee' 'gulp-jade' 'gulp-stylus' 'gulp-tap' 'gulp-watch' 'browser-sync' # dist 'gulp-inline-angular-templates' 'gulp-usemin' 'gulp-useref' 'gulp-minify-html' 'gulp-minify-css' 'gulp-csso' 'gulp-uglify' 'gulp-rev' 'gulp-rev-replace' ] ] # NPB CONFIG npb: # bower: # root_allow: true npm: commander: 'npm' # default # commander: 'cnpm' # -- build tools -- # build: 'gulp' # default # build: 'grunt'
49379
# PUBLIC CONFIG name: 'npb-seed' version: '0.0.0-pre' description: 'A npb seed project.' author: ':FooTearth <<EMAIL>>' # main: '' license: 'MIT' repository: type: 'git' url: 'https://github.com/Mooxe000/npb-seed.git' bugs: url: 'https://github.com/Mooxe000/npb-seed/issues' homepage: 'https://github.com/Mooxe000/npb-seed' Keywords: [ 'npb' 'seed' 'example' 'coffee' ] # BOWER CONFIG bower: dependencies: 'angularjs': 'angular.js' 'bootstrap' : [ 'dist/css/bootstrap.css' 'dist/fonts/glyphicons-halflings-regular.eot' 'dist/fonts/glyphicons-halflings-regular.svg' 'dist/fonts/glyphicons-halflings-regular.ttf' 'dist/fonts/glyphicons-halflings-regular.woff' ] 'jquery': 'dist/jquery.js' 'angular-route': 'angular-route.js' 'angular-resource': 'angular-resource.js' 'angular-animate': 'angular-animate.js' devDependencies: [] # NPM CONFIG npm: bin: {} scripts: test: '' dependencies: [] devDependencies: [ 'coffee-script' 'npb-coffee' 'lodash' 'del' gulp: [ # dev 'gulp-filter' 'gulp-coffee' 'gulp-jade' 'gulp-stylus' 'gulp-tap' 'gulp-watch' 'browser-sync' # dist 'gulp-inline-angular-templates' 'gulp-usemin' 'gulp-useref' 'gulp-minify-html' 'gulp-minify-css' 'gulp-csso' 'gulp-uglify' 'gulp-rev' 'gulp-rev-replace' ] ] # NPB CONFIG npb: # bower: # root_allow: true npm: commander: 'npm' # default # commander: 'cnpm' # -- build tools -- # build: 'gulp' # default # build: 'grunt'
true
# PUBLIC CONFIG name: 'npb-seed' version: '0.0.0-pre' description: 'A npb seed project.' author: ':FooTearth <PI:EMAIL:<EMAIL>END_PI>' # main: '' license: 'MIT' repository: type: 'git' url: 'https://github.com/Mooxe000/npb-seed.git' bugs: url: 'https://github.com/Mooxe000/npb-seed/issues' homepage: 'https://github.com/Mooxe000/npb-seed' Keywords: [ 'npb' 'seed' 'example' 'coffee' ] # BOWER CONFIG bower: dependencies: 'angularjs': 'angular.js' 'bootstrap' : [ 'dist/css/bootstrap.css' 'dist/fonts/glyphicons-halflings-regular.eot' 'dist/fonts/glyphicons-halflings-regular.svg' 'dist/fonts/glyphicons-halflings-regular.ttf' 'dist/fonts/glyphicons-halflings-regular.woff' ] 'jquery': 'dist/jquery.js' 'angular-route': 'angular-route.js' 'angular-resource': 'angular-resource.js' 'angular-animate': 'angular-animate.js' devDependencies: [] # NPM CONFIG npm: bin: {} scripts: test: '' dependencies: [] devDependencies: [ 'coffee-script' 'npb-coffee' 'lodash' 'del' gulp: [ # dev 'gulp-filter' 'gulp-coffee' 'gulp-jade' 'gulp-stylus' 'gulp-tap' 'gulp-watch' 'browser-sync' # dist 'gulp-inline-angular-templates' 'gulp-usemin' 'gulp-useref' 'gulp-minify-html' 'gulp-minify-css' 'gulp-csso' 'gulp-uglify' 'gulp-rev' 'gulp-rev-replace' ] ] # NPB CONFIG npb: # bower: # root_allow: true npm: commander: 'npm' # default # commander: 'cnpm' # -- build tools -- # build: 'gulp' # default # build: 'grunt'
[ { "context": " row[key] = parseFloat val if key isnt 'NEIGHBORHOOD'\n row\n out[years[index]] = data\n ", "end": 5553, "score": 0.540743887424469, "start": 5543, "tag": "KEY", "value": "IGHBORHOOD" } ]
source/javascripts/all.coffee
gruppopam/portland-census
0
#= require mappings years = [2000, 2010] width = 900 height = 680 vis = null places = null neighborhoods = null directory = null format = d3.format ',' colors = [ '#0aafed' '#3bbff1' '#6ccff4' '#9ddff8' '#ceeffb' '#fff' ] intensity = d3.scale.quantile() projection = d3.geo.albers().rotate [120] path = d3.geo.path().projection projection tip = d3.tip().attr('class', 'tip').offset([-3, 0]).html (d) -> "<h3>#{d.name} <span>#{d.subject}</span></h3> <table> <tr> <th>2000</th> <th>2010</th> <th>% Change</th> <th>+/-</th> </tr> <tr> <td>#{format d.data[0]}</td> <td>#{format d.data[1]}</td> <td>#{d.data[3]}</td> <td>#{format d.data[2]}</td> </tr> </table> " d3.json 'data/neighborhoods.json', (pdx) -> neighborhoods = topojson.feature pdx, pdx.objects.neighborhoods projection.scale(1).translate [0, 0] b = path.bounds(neighborhoods) s = .99 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height) t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2] projection.scale(s).translate(t) loadCensusData(mapDataToNeighborhoods) vis.append('pattern') .attr('id', 'hatch') .attr('patternUnits', 'userSpaceOnUse') .attr('width', 4) .attr('height', 4) .append('path') .style('stroke', '#777') .style('stroke-width', 0.5) .style('shape-rendering', 'crispedges') .attr('d', 'M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2') vis.selectAll('.neighborhood') .data(neighborhoods.features) .enter().append('path') .attr('class', (d) -> "neighborhood #{d.properties.name.toLowerCase().replace(/\s+/, '-')}") .classed('unclaimed', (d) -> d.properties.name.toLowerCase().indexOf('unclaimed') != -1) .classed('shared', (d) -> d.properties.shared) .attr('d', path) $ -> width = $('.js-map').outerWidth() vis = d3.select('.js-map').append('svg') .attr('width', width) .attr('height', height) .call(tip) directory = d3.select '.js-entries' menu = d3.select('.js-menu-subject').on 'change', (d) -> filters = getFilterParams() highlight filters.subject, filters.type d3.selectAll('.js-sort').on 'click', -> event = d3.event event.preventDefault() params = d3.select(this).attr('href') .substr(1) .split('&') .map (val) -> val.split '=' filters = getFilterParams() sort = params.filter((p) -> p[0] == 'dir')[0] type = params.filter((p) -> p[0] == 'prop')[0] type = if type[1] is 'change' 3 else if filters.type is '2010' then 1 else 0 query = [] for param in params [key, val] = param val = (if val is 'asc' then 'desc' else 'asc') if key == 'dir' query.push "#{key}=#{val}" d3.select(this).attr 'href', "?#{query.join('&')}" updateInfo filters.subject, type, __mappings[filters.subject], sort[1] d3.select('.js-menu-type').on 'change', (d) -> filters = getFilterParams() highlight filters.subject, filters.type for key of __mappings menu.append('option') .attr('value', key) .text(key) # Highlight a specific census category # # subject - Name of the census mapping # type - Index of type (2000, 2010, total change, % growth) highlight = (subject, type) -> colorRange = __mappings[subject][2] ?= colors values = places.map((d) -> parseFloat(d.value[subject][type])) .sort (a, b) -> d3.ascending(a, b) # Discard larges and smallest numbers min = values[1] max = values[values.length - 2] updateInfo subject, type, __mappings[subject] intensity.domain([min, max]).range colorRange vis.selectAll('.neighborhood:not(.shared):not(.unclaimed)') .style('fill', (d) -> name = d.properties.name place = places.filter((p) -> p.key == name)[0] count = place.value[subject][type] intensity(count)) .style('stroke', (d) -> name = d.properties.name place = places.filter((p) -> p.key == name)[0] count = place.value[subject][type] intensity(count)) .on('mouseover', (d) -> name = d.properties.name place = places.filter((p) -> p.key == name)[0] tip.show name: name, subject: subject, data: place.value[subject]) .on 'mouseout', tip.hide # Map topojson neighborhood data to census data mappings specified in mappings.coffee # # data - Census topojson data # mapDataToNeighborhoods = (data) -> nhoods = {} for hood in neighborhoods.features name = hood.properties.name current = nhoods[name] = {} current[2010] = data[2010].filter((d) -> d.NEIGHBORHOOD == name)[0] current[2000] = data[2000].filter((d) -> d.NEIGHBORHOOD == name)[0] for key, ids of window.__mappings try from = d3.sum(ids[0].map (id) -> current[2000][id]) to = d3.sum(ids[1].map (id) -> current[2010][id]) change = to - from growth = parseFloat ((change / from) * 100).toFixed(1) growth = 100 if !isFinite growth current[key] = [from, to, change, growth] catch e console.log "ERROR!!!! #{e} #{name} #{key}" delete current[2000] delete current[2010] places = d3.entries(nhoods).filter (nh) -> !shouldExcludeNeighborhood(nh.key) highlight 'Total Population', 0 # Load census data csv files loadCensusData = (callback) -> out = {} index = 0 for year in years d3.csv "data/#{year}-census.csv", (data) -> data.map (row) -> for key, val of row row[key] = parseFloat val if key isnt 'NEIGHBORHOOD' row out[years[index]] = data callback(out) if index == 1 index += 1 updateInfo = (subject, type, data, sort = 'desc') -> sortFunc = if sort == 'desc' then d3.descending else d3.ascending nhoods = places.map((place) -> name: place.key, value: place.value[subject]) .sort((a, b) -> sortFunc a.value[type], b.value[type]) #[0..19] [min, max] = d3.extent nhoods, (d) -> d.value[type] directory.selectAll('.entry').remove() directory.selectAll('.entry') .data(nhoods, (d) -> d.name) .enter().append('tr') .html((d, i) -> change = d.value[3] changeClass = if change < 0 then 'down' else 'up' changeClass = null if change is 0 "<tr> <td class='rank'>#{i + 1}.</td> <td>#{d.name}</td> <td class='val'>#{format(d.value[type])}</td> <td class='change #{changeClass}'>#{format(change)}%</td> </tr> ").attr('class', 'entry') getFilterParams = -> subjectMenu = d3.select '.js-menu-subject' typeMenu = d3.select '.js-menu-type' subjectIndex = subjectMenu.node().selectedIndex typeIndex = typeMenu.node().selectedIndex subject = d3.select(subjectMenu.node().options[subjectIndex]).attr 'value' type = typeIndex {subject, type} # Should we exclude a neighoborhood from being highlighted. # Sometimes we want to draw a neighborhood, but not highlight it with others. # For example, Portland has a lot of MC Unclaimed areas and overlapping # neighborhood boundaries. shouldExcludeNeighborhood = (name) -> name = name.toLowerCase() name.indexOf('unclaimed') != -1 or name == 'roseway/madison south'
98479
#= require mappings years = [2000, 2010] width = 900 height = 680 vis = null places = null neighborhoods = null directory = null format = d3.format ',' colors = [ '#0aafed' '#3bbff1' '#6ccff4' '#9ddff8' '#ceeffb' '#fff' ] intensity = d3.scale.quantile() projection = d3.geo.albers().rotate [120] path = d3.geo.path().projection projection tip = d3.tip().attr('class', 'tip').offset([-3, 0]).html (d) -> "<h3>#{d.name} <span>#{d.subject}</span></h3> <table> <tr> <th>2000</th> <th>2010</th> <th>% Change</th> <th>+/-</th> </tr> <tr> <td>#{format d.data[0]}</td> <td>#{format d.data[1]}</td> <td>#{d.data[3]}</td> <td>#{format d.data[2]}</td> </tr> </table> " d3.json 'data/neighborhoods.json', (pdx) -> neighborhoods = topojson.feature pdx, pdx.objects.neighborhoods projection.scale(1).translate [0, 0] b = path.bounds(neighborhoods) s = .99 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height) t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2] projection.scale(s).translate(t) loadCensusData(mapDataToNeighborhoods) vis.append('pattern') .attr('id', 'hatch') .attr('patternUnits', 'userSpaceOnUse') .attr('width', 4) .attr('height', 4) .append('path') .style('stroke', '#777') .style('stroke-width', 0.5) .style('shape-rendering', 'crispedges') .attr('d', 'M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2') vis.selectAll('.neighborhood') .data(neighborhoods.features) .enter().append('path') .attr('class', (d) -> "neighborhood #{d.properties.name.toLowerCase().replace(/\s+/, '-')}") .classed('unclaimed', (d) -> d.properties.name.toLowerCase().indexOf('unclaimed') != -1) .classed('shared', (d) -> d.properties.shared) .attr('d', path) $ -> width = $('.js-map').outerWidth() vis = d3.select('.js-map').append('svg') .attr('width', width) .attr('height', height) .call(tip) directory = d3.select '.js-entries' menu = d3.select('.js-menu-subject').on 'change', (d) -> filters = getFilterParams() highlight filters.subject, filters.type d3.selectAll('.js-sort').on 'click', -> event = d3.event event.preventDefault() params = d3.select(this).attr('href') .substr(1) .split('&') .map (val) -> val.split '=' filters = getFilterParams() sort = params.filter((p) -> p[0] == 'dir')[0] type = params.filter((p) -> p[0] == 'prop')[0] type = if type[1] is 'change' 3 else if filters.type is '2010' then 1 else 0 query = [] for param in params [key, val] = param val = (if val is 'asc' then 'desc' else 'asc') if key == 'dir' query.push "#{key}=#{val}" d3.select(this).attr 'href', "?#{query.join('&')}" updateInfo filters.subject, type, __mappings[filters.subject], sort[1] d3.select('.js-menu-type').on 'change', (d) -> filters = getFilterParams() highlight filters.subject, filters.type for key of __mappings menu.append('option') .attr('value', key) .text(key) # Highlight a specific census category # # subject - Name of the census mapping # type - Index of type (2000, 2010, total change, % growth) highlight = (subject, type) -> colorRange = __mappings[subject][2] ?= colors values = places.map((d) -> parseFloat(d.value[subject][type])) .sort (a, b) -> d3.ascending(a, b) # Discard larges and smallest numbers min = values[1] max = values[values.length - 2] updateInfo subject, type, __mappings[subject] intensity.domain([min, max]).range colorRange vis.selectAll('.neighborhood:not(.shared):not(.unclaimed)') .style('fill', (d) -> name = d.properties.name place = places.filter((p) -> p.key == name)[0] count = place.value[subject][type] intensity(count)) .style('stroke', (d) -> name = d.properties.name place = places.filter((p) -> p.key == name)[0] count = place.value[subject][type] intensity(count)) .on('mouseover', (d) -> name = d.properties.name place = places.filter((p) -> p.key == name)[0] tip.show name: name, subject: subject, data: place.value[subject]) .on 'mouseout', tip.hide # Map topojson neighborhood data to census data mappings specified in mappings.coffee # # data - Census topojson data # mapDataToNeighborhoods = (data) -> nhoods = {} for hood in neighborhoods.features name = hood.properties.name current = nhoods[name] = {} current[2010] = data[2010].filter((d) -> d.NEIGHBORHOOD == name)[0] current[2000] = data[2000].filter((d) -> d.NEIGHBORHOOD == name)[0] for key, ids of window.__mappings try from = d3.sum(ids[0].map (id) -> current[2000][id]) to = d3.sum(ids[1].map (id) -> current[2010][id]) change = to - from growth = parseFloat ((change / from) * 100).toFixed(1) growth = 100 if !isFinite growth current[key] = [from, to, change, growth] catch e console.log "ERROR!!!! #{e} #{name} #{key}" delete current[2000] delete current[2010] places = d3.entries(nhoods).filter (nh) -> !shouldExcludeNeighborhood(nh.key) highlight 'Total Population', 0 # Load census data csv files loadCensusData = (callback) -> out = {} index = 0 for year in years d3.csv "data/#{year}-census.csv", (data) -> data.map (row) -> for key, val of row row[key] = parseFloat val if key isnt 'NE<KEY>' row out[years[index]] = data callback(out) if index == 1 index += 1 updateInfo = (subject, type, data, sort = 'desc') -> sortFunc = if sort == 'desc' then d3.descending else d3.ascending nhoods = places.map((place) -> name: place.key, value: place.value[subject]) .sort((a, b) -> sortFunc a.value[type], b.value[type]) #[0..19] [min, max] = d3.extent nhoods, (d) -> d.value[type] directory.selectAll('.entry').remove() directory.selectAll('.entry') .data(nhoods, (d) -> d.name) .enter().append('tr') .html((d, i) -> change = d.value[3] changeClass = if change < 0 then 'down' else 'up' changeClass = null if change is 0 "<tr> <td class='rank'>#{i + 1}.</td> <td>#{d.name}</td> <td class='val'>#{format(d.value[type])}</td> <td class='change #{changeClass}'>#{format(change)}%</td> </tr> ").attr('class', 'entry') getFilterParams = -> subjectMenu = d3.select '.js-menu-subject' typeMenu = d3.select '.js-menu-type' subjectIndex = subjectMenu.node().selectedIndex typeIndex = typeMenu.node().selectedIndex subject = d3.select(subjectMenu.node().options[subjectIndex]).attr 'value' type = typeIndex {subject, type} # Should we exclude a neighoborhood from being highlighted. # Sometimes we want to draw a neighborhood, but not highlight it with others. # For example, Portland has a lot of MC Unclaimed areas and overlapping # neighborhood boundaries. shouldExcludeNeighborhood = (name) -> name = name.toLowerCase() name.indexOf('unclaimed') != -1 or name == 'roseway/madison south'
true
#= require mappings years = [2000, 2010] width = 900 height = 680 vis = null places = null neighborhoods = null directory = null format = d3.format ',' colors = [ '#0aafed' '#3bbff1' '#6ccff4' '#9ddff8' '#ceeffb' '#fff' ] intensity = d3.scale.quantile() projection = d3.geo.albers().rotate [120] path = d3.geo.path().projection projection tip = d3.tip().attr('class', 'tip').offset([-3, 0]).html (d) -> "<h3>#{d.name} <span>#{d.subject}</span></h3> <table> <tr> <th>2000</th> <th>2010</th> <th>% Change</th> <th>+/-</th> </tr> <tr> <td>#{format d.data[0]}</td> <td>#{format d.data[1]}</td> <td>#{d.data[3]}</td> <td>#{format d.data[2]}</td> </tr> </table> " d3.json 'data/neighborhoods.json', (pdx) -> neighborhoods = topojson.feature pdx, pdx.objects.neighborhoods projection.scale(1).translate [0, 0] b = path.bounds(neighborhoods) s = .99 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height) t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2] projection.scale(s).translate(t) loadCensusData(mapDataToNeighborhoods) vis.append('pattern') .attr('id', 'hatch') .attr('patternUnits', 'userSpaceOnUse') .attr('width', 4) .attr('height', 4) .append('path') .style('stroke', '#777') .style('stroke-width', 0.5) .style('shape-rendering', 'crispedges') .attr('d', 'M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2') vis.selectAll('.neighborhood') .data(neighborhoods.features) .enter().append('path') .attr('class', (d) -> "neighborhood #{d.properties.name.toLowerCase().replace(/\s+/, '-')}") .classed('unclaimed', (d) -> d.properties.name.toLowerCase().indexOf('unclaimed') != -1) .classed('shared', (d) -> d.properties.shared) .attr('d', path) $ -> width = $('.js-map').outerWidth() vis = d3.select('.js-map').append('svg') .attr('width', width) .attr('height', height) .call(tip) directory = d3.select '.js-entries' menu = d3.select('.js-menu-subject').on 'change', (d) -> filters = getFilterParams() highlight filters.subject, filters.type d3.selectAll('.js-sort').on 'click', -> event = d3.event event.preventDefault() params = d3.select(this).attr('href') .substr(1) .split('&') .map (val) -> val.split '=' filters = getFilterParams() sort = params.filter((p) -> p[0] == 'dir')[0] type = params.filter((p) -> p[0] == 'prop')[0] type = if type[1] is 'change' 3 else if filters.type is '2010' then 1 else 0 query = [] for param in params [key, val] = param val = (if val is 'asc' then 'desc' else 'asc') if key == 'dir' query.push "#{key}=#{val}" d3.select(this).attr 'href', "?#{query.join('&')}" updateInfo filters.subject, type, __mappings[filters.subject], sort[1] d3.select('.js-menu-type').on 'change', (d) -> filters = getFilterParams() highlight filters.subject, filters.type for key of __mappings menu.append('option') .attr('value', key) .text(key) # Highlight a specific census category # # subject - Name of the census mapping # type - Index of type (2000, 2010, total change, % growth) highlight = (subject, type) -> colorRange = __mappings[subject][2] ?= colors values = places.map((d) -> parseFloat(d.value[subject][type])) .sort (a, b) -> d3.ascending(a, b) # Discard larges and smallest numbers min = values[1] max = values[values.length - 2] updateInfo subject, type, __mappings[subject] intensity.domain([min, max]).range colorRange vis.selectAll('.neighborhood:not(.shared):not(.unclaimed)') .style('fill', (d) -> name = d.properties.name place = places.filter((p) -> p.key == name)[0] count = place.value[subject][type] intensity(count)) .style('stroke', (d) -> name = d.properties.name place = places.filter((p) -> p.key == name)[0] count = place.value[subject][type] intensity(count)) .on('mouseover', (d) -> name = d.properties.name place = places.filter((p) -> p.key == name)[0] tip.show name: name, subject: subject, data: place.value[subject]) .on 'mouseout', tip.hide # Map topojson neighborhood data to census data mappings specified in mappings.coffee # # data - Census topojson data # mapDataToNeighborhoods = (data) -> nhoods = {} for hood in neighborhoods.features name = hood.properties.name current = nhoods[name] = {} current[2010] = data[2010].filter((d) -> d.NEIGHBORHOOD == name)[0] current[2000] = data[2000].filter((d) -> d.NEIGHBORHOOD == name)[0] for key, ids of window.__mappings try from = d3.sum(ids[0].map (id) -> current[2000][id]) to = d3.sum(ids[1].map (id) -> current[2010][id]) change = to - from growth = parseFloat ((change / from) * 100).toFixed(1) growth = 100 if !isFinite growth current[key] = [from, to, change, growth] catch e console.log "ERROR!!!! #{e} #{name} #{key}" delete current[2000] delete current[2010] places = d3.entries(nhoods).filter (nh) -> !shouldExcludeNeighborhood(nh.key) highlight 'Total Population', 0 # Load census data csv files loadCensusData = (callback) -> out = {} index = 0 for year in years d3.csv "data/#{year}-census.csv", (data) -> data.map (row) -> for key, val of row row[key] = parseFloat val if key isnt 'NEPI:KEY:<KEY>END_PI' row out[years[index]] = data callback(out) if index == 1 index += 1 updateInfo = (subject, type, data, sort = 'desc') -> sortFunc = if sort == 'desc' then d3.descending else d3.ascending nhoods = places.map((place) -> name: place.key, value: place.value[subject]) .sort((a, b) -> sortFunc a.value[type], b.value[type]) #[0..19] [min, max] = d3.extent nhoods, (d) -> d.value[type] directory.selectAll('.entry').remove() directory.selectAll('.entry') .data(nhoods, (d) -> d.name) .enter().append('tr') .html((d, i) -> change = d.value[3] changeClass = if change < 0 then 'down' else 'up' changeClass = null if change is 0 "<tr> <td class='rank'>#{i + 1}.</td> <td>#{d.name}</td> <td class='val'>#{format(d.value[type])}</td> <td class='change #{changeClass}'>#{format(change)}%</td> </tr> ").attr('class', 'entry') getFilterParams = -> subjectMenu = d3.select '.js-menu-subject' typeMenu = d3.select '.js-menu-type' subjectIndex = subjectMenu.node().selectedIndex typeIndex = typeMenu.node().selectedIndex subject = d3.select(subjectMenu.node().options[subjectIndex]).attr 'value' type = typeIndex {subject, type} # Should we exclude a neighoborhood from being highlighted. # Sometimes we want to draw a neighborhood, but not highlight it with others. # For example, Portland has a lot of MC Unclaimed areas and overlapping # neighborhood boundaries. shouldExcludeNeighborhood = (name) -> name = name.toLowerCase() name.indexOf('unclaimed') != -1 or name == 'roseway/madison south'
[ { "context": "-890'\n\n\t\tit 'email', () ->\n\t\t\torg = 'info@hogehoge.com';\n\t\t\tcnv = nvalidr(org).email().s\n\t\t\tassert cnv =", "end": 6399, "score": 0.8046162128448486, "start": 6396, "tag": "EMAIL", "value": "com" }, { "context": "\t\t\tcnv = nvalidr(org).email().s\n\t\t\tassert cnv == 'info@hogehoge.com'\n\n\t\tit 'zipcode', () ->\n\t\t\torg = '543ー0021';\n\t\t\tc", "end": 6469, "score": 0.999900758266449, "start": 6452, "tag": "EMAIL", "value": "info@hogehoge.com" } ]
test/main.coffee
yuka2py/nvalidr.js
2
nvalidr = require '../lib/nvalidr.js' assert = require 'power-assert' describe 'nvalidr/', () -> describe 'type/', () -> it 'toInt', () -> org = '1234.5'; dst = nvalidr(org).toInt(); assert dst == 1234 it 'toFloat', () -> org = '1234.5'; dst = nvalidr(org).toFloat(); assert dst == 1234.5 it 'toNumber', () -> org = '1234.5'; dst = nvalidr(org).toNumber(); assert dst == 1234.5 describe 'trim/', () -> it 'trim', () -> org = ' aa a \n\r   '; dst = nvalidr(org).trim().s; assert dst == 'aa a' it 'rtrim', () -> org = ' aa a \n\r   '; dst = nvalidr(org).rtrim().s; assert(dst == ' aa a') it 'ltrim', () -> org = ' aa a \n\r   '; dst = nvalidr(org).ltrim().s; assert dst == 'aa a \n\r   ' describe 'date/', () -> it 'invalid date string', () -> org = 'あいう'; errmsg = null nvalidr(org).date () -> errmsg = '日付じゃありません' assert errmsg == '日付じゃありません' it 'valid date string YYYY-MM-DD', () -> org = '2015/8/12'; dst = nvalidr(org).date().s assert dst == '2015-08-12' it 'valid date string MM-DD', () -> org = '8/12'; dst = nvalidr(org).date().s assert dst == new Date().getFullYear() + '-08-12' it 'with format', () -> org = '2222/8/12'; dst = nvalidr(org).date({format:'YYYY/MM/DD'}).s assert dst == '2222/08/12' it 'with patterns', () -> org = '8/12/2222'; dst = nvalidr(org).date({patterns:'MM/DD/YYYY'}).s assert dst == '2222-08-12' it 'wit options and error', () -> org = 'あいう'; err = null nvalidr(org).date {format:'YYYY/MM/DD'}, () -> err = '日付じゃありません' assert err == '日付じゃありません' describe 'time/', () -> it 'invalid time string', () -> org = 'あいう'; errmsg = null nvalidr(org).time () -> errmsg = '時刻じゃありません' assert errmsg == '時刻じゃありません' it 'valid time string HH:mm', () -> org = '15:28'; dst = nvalidr(org).time().s assert dst == '15:28' it 'valid time string ', () -> org = '16:32'; dst = nvalidr(org).time().s assert dst == '16:32' it 'with format', () -> org = '14:22'; dst = nvalidr(org).time({format:'HH-mm'}).s assert dst == '14-22' it 'with patterns', () -> org = '14:22'; dst = nvalidr(org).time({patterns:'HH-mm'}).s assert dst == '14:22' it 'wit options and error', () -> org = 'あいう'; err = null nvalidr(org).time {format:'YYYY/MM/DD'}, () -> err = '時刻じゃありません' assert err == '時刻じゃありません' describe 'filter/', () -> it 'filter', () -> org = 'あいうえお' dst = nvalidr(org).filter((value) -> value.replace('い', 'あ') ).s assert dst == 'ああうえお' describe 'replace/', () -> it 'map of array', () -> org = 'あいうえお' dst = nvalidr(org).replace([['い','あ'],['う','あ']]).s assert dst == 'あああえお' it 'map of array with the from of RegExp', () -> org = 'あいうえお' dst = nvalidr(org).replace([[/[あいうえお]/g, 'あ'],[/(あ{3})(あ{2})/, '$1-$2']]).s assert dst == 'あああ-ああ' it '全角かたかな => 全角ひらがな', () -> org = 'アイウエオカサタナハマヤラワン' cnv = nvalidr(org).replace(nvalidr.KATA2HIRA).s assert cnv == 'あいうえおかさたなはまやらわん' it '全角かたかな => 半角かたかな', () -> org = 'アイウエオカサタナハマヤラワンガプ' cnv = nvalidr(org).replace(nvalidr.H_KATA).s assert cnv == 'アイウエオカサタナハマヤラワンガプ' it '全角ひらがな => 全角かたかな', () -> org = 'あいうえおかさたなはまやらわん' cnv = nvalidr(org).replace(nvalidr.HIRA2KATA).s assert cnv == 'アイウエオカサタナハマヤラワン' it '全角ひらがな => 半角かたかな', () -> org = 'あいうえおかさたなはまやらわんがぷ' cnv = nvalidr(org).replace(nvalidr.HIRA2KATA, nvalidr.H_KATA).s assert cnv == 'アイウエオカサタナハマヤラワンガプ' it '全角アルファベット => 半角アルファベット', () -> org = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' cnv = nvalidr(org).replace(nvalidr.H_ALPHA).s assert cnv == 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' it '全角数字 => 半角数字', () -> org = '0123456789' cnv = nvalidr(org).replace(nvalidr.H_NUM).s assert cnv == '0123456789' it '全角記号 => 半角記号', () -> org = '.,!?”’‘@_:;#$%&()=*+-/<>[¥]^{|}~、。「」・ー' cnv = nvalidr(org).replace(nvalidr.H_KIGO).s assert cnv == '.,!?"\'`@_:;#$%&()=*+-/<>[¥]^{|}~、。「」・ー' it '半角アルファベット => 全角アルファベット', () -> org = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' cnv = nvalidr(org).replace(nvalidr.Z_ALPHA).s assert cnv == 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' it '半角数字 => 全角数字', () -> org = '0123456789' cnv = nvalidr(org).replace(nvalidr.Z_NUM).s assert cnv == '0123456789' it '半角記号 => 全角記号', () -> org = '.,!?"\'`@_:;#$%&()=*+-/<>[¥]^{|}~、。「」・ー' cnv = nvalidr(org).replace(nvalidr.Z_KIGO).s assert cnv == '.,!?”’‘@_:;#$%&()=*+-/<>[¥]^{|}~、。「」・ー' it '半角スペース => 全角スペース', () -> org = ' ' cnv = nvalidr(org).replace(nvalidr.Z_SPACE).s assert cnv == ' ' it '全角スペース => 半角スペース', () -> org = ' ' cnv = nvalidr(org).replace(nvalidr.H_SPACE).s assert cnv == ' ' it 'skip chars', () -> org = '0123456789' cnv = nvalidr(org).replace(nvalidr.H_NUM, { skip:'78' }).s assert cnv == '0123456789' it 'extra chars', () -> org = '01234567.89' cnv = nvalidr(org).replace(nvalidr.H_NUM, { extra:[['.','.']] }).s assert cnv == '01234567.89' describe 'validation/', () -> it 'normtext', () -> org = 'カラバイヨあかさたな松本伊代0234ABC、。「」' cnv = nvalidr(org).normtext().s assert cnv == 'カラバイヨあかさたな松本伊代0234ABC、。「」' it 'hiragana', () -> org = 'カラバイヨばーすロッテ' cnv = nvalidr(org).hiragana().s assert cnv == 'からばいよばーすろって' it 'hiragana => failed', () -> err = null nvalidr('カラバイヨ漢字ばーすロッテ').hiragana () -> err = 'ひらがなで入力してください。' assert err == 'ひらがなで入力してください。' it 'katakana', () -> org = 'カラバイヨばーすロッテ' cnv = nvalidr(org).katakana().s assert cnv == 'カラバイヨバースロッテ' it 'number', () -> org = '0123472' cnv = nvalidr(org).number().s assert cnv == '0123472' it 'int', () -> org = '-012,347' cnv = nvalidr(org).int().s assert cnv == '-012347' it 'float', () -> org = '-012,347.2' cnv = nvalidr(org).float().s assert cnv == '-012347.2' it 'alpha', () -> org = 'abcdefgHIJKLMN' cnv = nvalidr(org).alpha().s assert cnv == 'abcdefgHIJKLMN' it 'alphanum', () -> org = '0123ABXYZ789' cnv = nvalidr(org).alphanum().s assert cnv == '0123ABXYZ789' it 'phone', () -> org = '0123−4567ー890漢字' cnv = nvalidr(org).phone().s assert cnv == '0123-4567-890' it 'email', () -> org = 'info@hogehoge.com'; cnv = nvalidr(org).email().s assert cnv == 'info@hogehoge.com' it 'zipcode', () -> org = '543ー0021'; cnv = nvalidr(org).zipcode().s assert cnv == '543-0021' it 'maxlen => success', () -> errmsg = null; nvalidr('1234567').maxlen(7, () -> errmsg = '7文字以内で入力してください。' ).s assert errmsg == null; it 'maxlen => fail', () -> errmsg = null; nvalidr('12345678').maxlen(7, () -> errmsg = '7文字以内で入力してください。' ).s assert errmsg == '7文字以内で入力してください。' it 'minlen => success', () -> errmsg = null; nvalidr('1234567').minlen(7, () -> errmsg = '7文字以内で入力してください。' ).s assert errmsg == null; it 'minlen => fail', () -> errmsg = null; nvalidr('123456').minlen(7, () -> errmsg = '7文字以上で入力してください。' ).s assert errmsg == '7文字以上で入力してください。'; it 'length => success', () -> errmsg = null; nvalidr('12345678').length(4, 8, () -> errmsg = '7文字以内で入力してください。' ).s assert errmsg == null; it 'length => fail', () -> errmsg = null; nvalidr('123').length(4, 8, () -> errmsg = '4〜8文字で入力してください。' ).s assert errmsg == '4〜8文字で入力してください。'; it 'max => fail', () -> errmsg = null; nvalidr(21).max(20, () -> errmsg = '20以下の数値で指定してください。' ).s assert errmsg == '20以下の数値で指定してください。'; it 'min => fail', () -> errmsg = null; nvalidr('19').min(20, () -> errmsg = '20以上の数値で指定してください。' ).s assert errmsg == '20以上の数値で指定してください。'; it 'range => fail', () -> errmsg = null; nvalidr('19').range(20, 40, () -> errmsg = '20〜40の数値で指定してください。' ).s assert errmsg == '20〜40の数値で指定してください。'; it 'presence => fail', () -> errmsg = null; nvalidr('').presence(() -> errmsg = '値を入力してください。' ).s assert errmsg == '値を入力してください。';
9584
nvalidr = require '../lib/nvalidr.js' assert = require 'power-assert' describe 'nvalidr/', () -> describe 'type/', () -> it 'toInt', () -> org = '1234.5'; dst = nvalidr(org).toInt(); assert dst == 1234 it 'toFloat', () -> org = '1234.5'; dst = nvalidr(org).toFloat(); assert dst == 1234.5 it 'toNumber', () -> org = '1234.5'; dst = nvalidr(org).toNumber(); assert dst == 1234.5 describe 'trim/', () -> it 'trim', () -> org = ' aa a \n\r   '; dst = nvalidr(org).trim().s; assert dst == 'aa a' it 'rtrim', () -> org = ' aa a \n\r   '; dst = nvalidr(org).rtrim().s; assert(dst == ' aa a') it 'ltrim', () -> org = ' aa a \n\r   '; dst = nvalidr(org).ltrim().s; assert dst == 'aa a \n\r   ' describe 'date/', () -> it 'invalid date string', () -> org = 'あいう'; errmsg = null nvalidr(org).date () -> errmsg = '日付じゃありません' assert errmsg == '日付じゃありません' it 'valid date string YYYY-MM-DD', () -> org = '2015/8/12'; dst = nvalidr(org).date().s assert dst == '2015-08-12' it 'valid date string MM-DD', () -> org = '8/12'; dst = nvalidr(org).date().s assert dst == new Date().getFullYear() + '-08-12' it 'with format', () -> org = '2222/8/12'; dst = nvalidr(org).date({format:'YYYY/MM/DD'}).s assert dst == '2222/08/12' it 'with patterns', () -> org = '8/12/2222'; dst = nvalidr(org).date({patterns:'MM/DD/YYYY'}).s assert dst == '2222-08-12' it 'wit options and error', () -> org = 'あいう'; err = null nvalidr(org).date {format:'YYYY/MM/DD'}, () -> err = '日付じゃありません' assert err == '日付じゃありません' describe 'time/', () -> it 'invalid time string', () -> org = 'あいう'; errmsg = null nvalidr(org).time () -> errmsg = '時刻じゃありません' assert errmsg == '時刻じゃありません' it 'valid time string HH:mm', () -> org = '15:28'; dst = nvalidr(org).time().s assert dst == '15:28' it 'valid time string ', () -> org = '16:32'; dst = nvalidr(org).time().s assert dst == '16:32' it 'with format', () -> org = '14:22'; dst = nvalidr(org).time({format:'HH-mm'}).s assert dst == '14-22' it 'with patterns', () -> org = '14:22'; dst = nvalidr(org).time({patterns:'HH-mm'}).s assert dst == '14:22' it 'wit options and error', () -> org = 'あいう'; err = null nvalidr(org).time {format:'YYYY/MM/DD'}, () -> err = '時刻じゃありません' assert err == '時刻じゃありません' describe 'filter/', () -> it 'filter', () -> org = 'あいうえお' dst = nvalidr(org).filter((value) -> value.replace('い', 'あ') ).s assert dst == 'ああうえお' describe 'replace/', () -> it 'map of array', () -> org = 'あいうえお' dst = nvalidr(org).replace([['い','あ'],['う','あ']]).s assert dst == 'あああえお' it 'map of array with the from of RegExp', () -> org = 'あいうえお' dst = nvalidr(org).replace([[/[あいうえお]/g, 'あ'],[/(あ{3})(あ{2})/, '$1-$2']]).s assert dst == 'あああ-ああ' it '全角かたかな => 全角ひらがな', () -> org = 'アイウエオカサタナハマヤラワン' cnv = nvalidr(org).replace(nvalidr.KATA2HIRA).s assert cnv == 'あいうえおかさたなはまやらわん' it '全角かたかな => 半角かたかな', () -> org = 'アイウエオカサタナハマヤラワンガプ' cnv = nvalidr(org).replace(nvalidr.H_KATA).s assert cnv == 'アイウエオカサタナハマヤラワンガプ' it '全角ひらがな => 全角かたかな', () -> org = 'あいうえおかさたなはまやらわん' cnv = nvalidr(org).replace(nvalidr.HIRA2KATA).s assert cnv == 'アイウエオカサタナハマヤラワン' it '全角ひらがな => 半角かたかな', () -> org = 'あいうえおかさたなはまやらわんがぷ' cnv = nvalidr(org).replace(nvalidr.HIRA2KATA, nvalidr.H_KATA).s assert cnv == 'アイウエオカサタナハマヤラワンガプ' it '全角アルファベット => 半角アルファベット', () -> org = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' cnv = nvalidr(org).replace(nvalidr.H_ALPHA).s assert cnv == 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' it '全角数字 => 半角数字', () -> org = '0123456789' cnv = nvalidr(org).replace(nvalidr.H_NUM).s assert cnv == '0123456789' it '全角記号 => 半角記号', () -> org = '.,!?”’‘@_:;#$%&()=*+-/<>[¥]^{|}~、。「」・ー' cnv = nvalidr(org).replace(nvalidr.H_KIGO).s assert cnv == '.,!?"\'`@_:;#$%&()=*+-/<>[¥]^{|}~、。「」・ー' it '半角アルファベット => 全角アルファベット', () -> org = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' cnv = nvalidr(org).replace(nvalidr.Z_ALPHA).s assert cnv == 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' it '半角数字 => 全角数字', () -> org = '0123456789' cnv = nvalidr(org).replace(nvalidr.Z_NUM).s assert cnv == '0123456789' it '半角記号 => 全角記号', () -> org = '.,!?"\'`@_:;#$%&()=*+-/<>[¥]^{|}~、。「」・ー' cnv = nvalidr(org).replace(nvalidr.Z_KIGO).s assert cnv == '.,!?”’‘@_:;#$%&()=*+-/<>[¥]^{|}~、。「」・ー' it '半角スペース => 全角スペース', () -> org = ' ' cnv = nvalidr(org).replace(nvalidr.Z_SPACE).s assert cnv == ' ' it '全角スペース => 半角スペース', () -> org = ' ' cnv = nvalidr(org).replace(nvalidr.H_SPACE).s assert cnv == ' ' it 'skip chars', () -> org = '0123456789' cnv = nvalidr(org).replace(nvalidr.H_NUM, { skip:'78' }).s assert cnv == '0123456789' it 'extra chars', () -> org = '01234567.89' cnv = nvalidr(org).replace(nvalidr.H_NUM, { extra:[['.','.']] }).s assert cnv == '01234567.89' describe 'validation/', () -> it 'normtext', () -> org = 'カラバイヨあかさたな松本伊代0234ABC、。「」' cnv = nvalidr(org).normtext().s assert cnv == 'カラバイヨあかさたな松本伊代0234ABC、。「」' it 'hiragana', () -> org = 'カラバイヨばーすロッテ' cnv = nvalidr(org).hiragana().s assert cnv == 'からばいよばーすろって' it 'hiragana => failed', () -> err = null nvalidr('カラバイヨ漢字ばーすロッテ').hiragana () -> err = 'ひらがなで入力してください。' assert err == 'ひらがなで入力してください。' it 'katakana', () -> org = 'カラバイヨばーすロッテ' cnv = nvalidr(org).katakana().s assert cnv == 'カラバイヨバースロッテ' it 'number', () -> org = '0123472' cnv = nvalidr(org).number().s assert cnv == '0123472' it 'int', () -> org = '-012,347' cnv = nvalidr(org).int().s assert cnv == '-012347' it 'float', () -> org = '-012,347.2' cnv = nvalidr(org).float().s assert cnv == '-012347.2' it 'alpha', () -> org = 'abcdefgHIJKLMN' cnv = nvalidr(org).alpha().s assert cnv == 'abcdefgHIJKLMN' it 'alphanum', () -> org = '0123ABXYZ789' cnv = nvalidr(org).alphanum().s assert cnv == '0123ABXYZ789' it 'phone', () -> org = '0123−4567ー890漢字' cnv = nvalidr(org).phone().s assert cnv == '0123-4567-890' it 'email', () -> org = 'info@hogehoge.<EMAIL>'; cnv = nvalidr(org).email().s assert cnv == '<EMAIL>' it 'zipcode', () -> org = '543ー0021'; cnv = nvalidr(org).zipcode().s assert cnv == '543-0021' it 'maxlen => success', () -> errmsg = null; nvalidr('1234567').maxlen(7, () -> errmsg = '7文字以内で入力してください。' ).s assert errmsg == null; it 'maxlen => fail', () -> errmsg = null; nvalidr('12345678').maxlen(7, () -> errmsg = '7文字以内で入力してください。' ).s assert errmsg == '7文字以内で入力してください。' it 'minlen => success', () -> errmsg = null; nvalidr('1234567').minlen(7, () -> errmsg = '7文字以内で入力してください。' ).s assert errmsg == null; it 'minlen => fail', () -> errmsg = null; nvalidr('123456').minlen(7, () -> errmsg = '7文字以上で入力してください。' ).s assert errmsg == '7文字以上で入力してください。'; it 'length => success', () -> errmsg = null; nvalidr('12345678').length(4, 8, () -> errmsg = '7文字以内で入力してください。' ).s assert errmsg == null; it 'length => fail', () -> errmsg = null; nvalidr('123').length(4, 8, () -> errmsg = '4〜8文字で入力してください。' ).s assert errmsg == '4〜8文字で入力してください。'; it 'max => fail', () -> errmsg = null; nvalidr(21).max(20, () -> errmsg = '20以下の数値で指定してください。' ).s assert errmsg == '20以下の数値で指定してください。'; it 'min => fail', () -> errmsg = null; nvalidr('19').min(20, () -> errmsg = '20以上の数値で指定してください。' ).s assert errmsg == '20以上の数値で指定してください。'; it 'range => fail', () -> errmsg = null; nvalidr('19').range(20, 40, () -> errmsg = '20〜40の数値で指定してください。' ).s assert errmsg == '20〜40の数値で指定してください。'; it 'presence => fail', () -> errmsg = null; nvalidr('').presence(() -> errmsg = '値を入力してください。' ).s assert errmsg == '値を入力してください。';
true
nvalidr = require '../lib/nvalidr.js' assert = require 'power-assert' describe 'nvalidr/', () -> describe 'type/', () -> it 'toInt', () -> org = '1234.5'; dst = nvalidr(org).toInt(); assert dst == 1234 it 'toFloat', () -> org = '1234.5'; dst = nvalidr(org).toFloat(); assert dst == 1234.5 it 'toNumber', () -> org = '1234.5'; dst = nvalidr(org).toNumber(); assert dst == 1234.5 describe 'trim/', () -> it 'trim', () -> org = ' aa a \n\r   '; dst = nvalidr(org).trim().s; assert dst == 'aa a' it 'rtrim', () -> org = ' aa a \n\r   '; dst = nvalidr(org).rtrim().s; assert(dst == ' aa a') it 'ltrim', () -> org = ' aa a \n\r   '; dst = nvalidr(org).ltrim().s; assert dst == 'aa a \n\r   ' describe 'date/', () -> it 'invalid date string', () -> org = 'あいう'; errmsg = null nvalidr(org).date () -> errmsg = '日付じゃありません' assert errmsg == '日付じゃありません' it 'valid date string YYYY-MM-DD', () -> org = '2015/8/12'; dst = nvalidr(org).date().s assert dst == '2015-08-12' it 'valid date string MM-DD', () -> org = '8/12'; dst = nvalidr(org).date().s assert dst == new Date().getFullYear() + '-08-12' it 'with format', () -> org = '2222/8/12'; dst = nvalidr(org).date({format:'YYYY/MM/DD'}).s assert dst == '2222/08/12' it 'with patterns', () -> org = '8/12/2222'; dst = nvalidr(org).date({patterns:'MM/DD/YYYY'}).s assert dst == '2222-08-12' it 'wit options and error', () -> org = 'あいう'; err = null nvalidr(org).date {format:'YYYY/MM/DD'}, () -> err = '日付じゃありません' assert err == '日付じゃありません' describe 'time/', () -> it 'invalid time string', () -> org = 'あいう'; errmsg = null nvalidr(org).time () -> errmsg = '時刻じゃありません' assert errmsg == '時刻じゃありません' it 'valid time string HH:mm', () -> org = '15:28'; dst = nvalidr(org).time().s assert dst == '15:28' it 'valid time string ', () -> org = '16:32'; dst = nvalidr(org).time().s assert dst == '16:32' it 'with format', () -> org = '14:22'; dst = nvalidr(org).time({format:'HH-mm'}).s assert dst == '14-22' it 'with patterns', () -> org = '14:22'; dst = nvalidr(org).time({patterns:'HH-mm'}).s assert dst == '14:22' it 'wit options and error', () -> org = 'あいう'; err = null nvalidr(org).time {format:'YYYY/MM/DD'}, () -> err = '時刻じゃありません' assert err == '時刻じゃありません' describe 'filter/', () -> it 'filter', () -> org = 'あいうえお' dst = nvalidr(org).filter((value) -> value.replace('い', 'あ') ).s assert dst == 'ああうえお' describe 'replace/', () -> it 'map of array', () -> org = 'あいうえお' dst = nvalidr(org).replace([['い','あ'],['う','あ']]).s assert dst == 'あああえお' it 'map of array with the from of RegExp', () -> org = 'あいうえお' dst = nvalidr(org).replace([[/[あいうえお]/g, 'あ'],[/(あ{3})(あ{2})/, '$1-$2']]).s assert dst == 'あああ-ああ' it '全角かたかな => 全角ひらがな', () -> org = 'アイウエオカサタナハマヤラワン' cnv = nvalidr(org).replace(nvalidr.KATA2HIRA).s assert cnv == 'あいうえおかさたなはまやらわん' it '全角かたかな => 半角かたかな', () -> org = 'アイウエオカサタナハマヤラワンガプ' cnv = nvalidr(org).replace(nvalidr.H_KATA).s assert cnv == 'アイウエオカサタナハマヤラワンガプ' it '全角ひらがな => 全角かたかな', () -> org = 'あいうえおかさたなはまやらわん' cnv = nvalidr(org).replace(nvalidr.HIRA2KATA).s assert cnv == 'アイウエオカサタナハマヤラワン' it '全角ひらがな => 半角かたかな', () -> org = 'あいうえおかさたなはまやらわんがぷ' cnv = nvalidr(org).replace(nvalidr.HIRA2KATA, nvalidr.H_KATA).s assert cnv == 'アイウエオカサタナハマヤラワンガプ' it '全角アルファベット => 半角アルファベット', () -> org = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' cnv = nvalidr(org).replace(nvalidr.H_ALPHA).s assert cnv == 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' it '全角数字 => 半角数字', () -> org = '0123456789' cnv = nvalidr(org).replace(nvalidr.H_NUM).s assert cnv == '0123456789' it '全角記号 => 半角記号', () -> org = '.,!?”’‘@_:;#$%&()=*+-/<>[¥]^{|}~、。「」・ー' cnv = nvalidr(org).replace(nvalidr.H_KIGO).s assert cnv == '.,!?"\'`@_:;#$%&()=*+-/<>[¥]^{|}~、。「」・ー' it '半角アルファベット => 全角アルファベット', () -> org = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' cnv = nvalidr(org).replace(nvalidr.Z_ALPHA).s assert cnv == 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' it '半角数字 => 全角数字', () -> org = '0123456789' cnv = nvalidr(org).replace(nvalidr.Z_NUM).s assert cnv == '0123456789' it '半角記号 => 全角記号', () -> org = '.,!?"\'`@_:;#$%&()=*+-/<>[¥]^{|}~、。「」・ー' cnv = nvalidr(org).replace(nvalidr.Z_KIGO).s assert cnv == '.,!?”’‘@_:;#$%&()=*+-/<>[¥]^{|}~、。「」・ー' it '半角スペース => 全角スペース', () -> org = ' ' cnv = nvalidr(org).replace(nvalidr.Z_SPACE).s assert cnv == ' ' it '全角スペース => 半角スペース', () -> org = ' ' cnv = nvalidr(org).replace(nvalidr.H_SPACE).s assert cnv == ' ' it 'skip chars', () -> org = '0123456789' cnv = nvalidr(org).replace(nvalidr.H_NUM, { skip:'78' }).s assert cnv == '0123456789' it 'extra chars', () -> org = '01234567.89' cnv = nvalidr(org).replace(nvalidr.H_NUM, { extra:[['.','.']] }).s assert cnv == '01234567.89' describe 'validation/', () -> it 'normtext', () -> org = 'カラバイヨあかさたな松本伊代0234ABC、。「」' cnv = nvalidr(org).normtext().s assert cnv == 'カラバイヨあかさたな松本伊代0234ABC、。「」' it 'hiragana', () -> org = 'カラバイヨばーすロッテ' cnv = nvalidr(org).hiragana().s assert cnv == 'からばいよばーすろって' it 'hiragana => failed', () -> err = null nvalidr('カラバイヨ漢字ばーすロッテ').hiragana () -> err = 'ひらがなで入力してください。' assert err == 'ひらがなで入力してください。' it 'katakana', () -> org = 'カラバイヨばーすロッテ' cnv = nvalidr(org).katakana().s assert cnv == 'カラバイヨバースロッテ' it 'number', () -> org = '0123472' cnv = nvalidr(org).number().s assert cnv == '0123472' it 'int', () -> org = '-012,347' cnv = nvalidr(org).int().s assert cnv == '-012347' it 'float', () -> org = '-012,347.2' cnv = nvalidr(org).float().s assert cnv == '-012347.2' it 'alpha', () -> org = 'abcdefgHIJKLMN' cnv = nvalidr(org).alpha().s assert cnv == 'abcdefgHIJKLMN' it 'alphanum', () -> org = '0123ABXYZ789' cnv = nvalidr(org).alphanum().s assert cnv == '0123ABXYZ789' it 'phone', () -> org = '0123−4567ー890漢字' cnv = nvalidr(org).phone().s assert cnv == '0123-4567-890' it 'email', () -> org = 'info@hogehoge.PI:EMAIL:<EMAIL>END_PI'; cnv = nvalidr(org).email().s assert cnv == 'PI:EMAIL:<EMAIL>END_PI' it 'zipcode', () -> org = '543ー0021'; cnv = nvalidr(org).zipcode().s assert cnv == '543-0021' it 'maxlen => success', () -> errmsg = null; nvalidr('1234567').maxlen(7, () -> errmsg = '7文字以内で入力してください。' ).s assert errmsg == null; it 'maxlen => fail', () -> errmsg = null; nvalidr('12345678').maxlen(7, () -> errmsg = '7文字以内で入力してください。' ).s assert errmsg == '7文字以内で入力してください。' it 'minlen => success', () -> errmsg = null; nvalidr('1234567').minlen(7, () -> errmsg = '7文字以内で入力してください。' ).s assert errmsg == null; it 'minlen => fail', () -> errmsg = null; nvalidr('123456').minlen(7, () -> errmsg = '7文字以上で入力してください。' ).s assert errmsg == '7文字以上で入力してください。'; it 'length => success', () -> errmsg = null; nvalidr('12345678').length(4, 8, () -> errmsg = '7文字以内で入力してください。' ).s assert errmsg == null; it 'length => fail', () -> errmsg = null; nvalidr('123').length(4, 8, () -> errmsg = '4〜8文字で入力してください。' ).s assert errmsg == '4〜8文字で入力してください。'; it 'max => fail', () -> errmsg = null; nvalidr(21).max(20, () -> errmsg = '20以下の数値で指定してください。' ).s assert errmsg == '20以下の数値で指定してください。'; it 'min => fail', () -> errmsg = null; nvalidr('19').min(20, () -> errmsg = '20以上の数値で指定してください。' ).s assert errmsg == '20以上の数値で指定してください。'; it 'range => fail', () -> errmsg = null; nvalidr('19').range(20, 40, () -> errmsg = '20〜40の数値で指定してください。' ).s assert errmsg == '20〜40の数値で指定してください。'; it 'presence => fail', () -> errmsg = null; nvalidr('').presence(() -> errmsg = '値を入力してください。' ).s assert errmsg == '値を入力してください。';
[ { "context": " log \"adminmodule.apply\"\n try\n token = appState.token()\n langTag = pwaContent.languageTag\n ", "end": 7536, "score": 0.6908311247825623, "start": 7522, "tag": "KEY", "value": "appState.token" } ]
source/adminmodule/adminmodule.coffee
JhonnyJason/admin-tester-admin-interface-sources
0
adminmodule = {name: "adminmodule"} ############################################################ #region printLogFunctions log = (arg) -> if adminModules.debugmodule.modulesToDebug["adminmodule"]? then console.log "[adminmodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ #region modulesFromEnvironment mustache = require "mustache" ############################################################ mustachekeys = null templatepreparation = null network = null adminpanel = null appState = null contentHandler = null bottomPanel = null bigPanel = null imageManagement = null listManagement = null linkManagement = null auth = null #endregion ############################################################ #region internalProperties currentEditTextFallback = "" ############################################################ typingSecret = false loggingIn = false token = "" panelVisible = true showingEditables = false #endregion ############################################################ adminmodule.initialize = () -> log "adminmodule.initialize" mustachekeys = adminModules.mustachekeysmodule templatepreparation = adminModules.templatepreparationmodule network = adminModules.networkmodule adminpanel = adminModules.adminpanelmodule appState = adminModules.appstatemodule auth = adminModules.authmodule contentHandler = adminModules.contenthandlermodule bigPanel = adminModules.bigpanelmodule imageManagement = adminModules.imagemanagementmodule listManagement = adminModules.listmanagementmodule linkManagement = adminModules.linkmanagementmodule bottomPanel = adminModules.bottompanelmodule return ############################################################ renderProcess = -> log "renderProcess" content = contentHandler.content() mustachekeys.createMustacheKeys() mustacheTemplate = template(pwaMustacheKeymap) # log mustacheTemplate shadowBody = document.createElement("body") shadowBody.innerHTML = mustacheTemplate templatepreparation.prepareBody(shadowBody) preparedTemplate = shadowBody.innerHTML # log preparedTemplate htmlResult = mustache.render(preparedTemplate, content) # log htmlResult newBody = document.createElement("body") newBody.innerHTML = htmlResult adminpanel.attachPanelToBody(newBody) document.body = newBody addAdministrativeEventListeners() bigPanel.prepare() return ############################################################ #region stuffForEditing addAdministrativeEventListeners = -> log "addAdministrativeEventListeners" allEditableTexts = document.querySelectorAll("[text-content-key]") for editable in allEditableTexts editable.addEventListener("keydown", editKeyPressed) editable.addEventListener("focusin", startedEditing) editable.addEventListener("focusout", stoppedEditing) allEditableImages = document.querySelectorAll("[image-content-key]") for editable in allEditableImages editable.addEventListener("click", editableImageClicked) return ############################################################ #region eventListeners editableImageClicked = (event) -> log "editableImageClicked" imageLabel = event.target.getAttribute("image-content-key") bigPanel.activateEdit("images", imageLabel) bottomPanel.applyUIState() return editKeyPressed = (event) -> log "editKeyPressed" key = event.keyCode if (key == 27) #escape this.textContent = currentEditTextFallback document.activeElement.blur() return startedEditing = (event) -> log "startedEditing" element = event.target element.classList.add("editing") currentEditTextFallback = element.textContent return stoppedEditing = (event) -> log "stoppedEditing" element = event.target element.classList.remove("editing") return if element.textContent == currentEditTextFallback contentKeyString = element.getAttribute("text-content-key") newContentText(contentKeyString, element.textContent) return #endregion ############################################################ newContentText = (contentKeyString, content) -> log "newContentText" log contentKeyString log content token = appState.token() langTag = pwaContent.languageTag path = window.location.pathname documentName = path.split("/").pop() updateObject = {langTag, documentName, contentKeyString, content, token} oldContent = currentEditTextFallback try response = await network.scicall("update", updateObject) edits = {} edits[contentKeyString] = content contentHandler.reflectEdits(edits) updateSuccess(response) catch err then revertEdit(contentKeyString, oldContent) return ############################################################ revertEdit = (contentKeyString, oldText) -> log "revertEdit" bottomPanel.setErrorMessage("Veränderung konnte nicht angenommen werden!") selector = "[text-content-key='"+contentKeyString+"']" element = document.querySelector(selector) element.textContent = oldText return setCleanState = -> log "setCleanState" appState.setClean() bottomPanel.applyUIState() return setDirtyState = -> log "setDirtyState" appState.setDirty() bottomPanel.applyUIState() return ############################################################ updateSuccess = (response) -> log "updateSuccess" setDirtyState() bottomPanel.setSuccessMessage("Veränderung angenommen") return prepareImages = -> log "prepareImages" content = contentHandler.content() imageManagement.setImages(content.images) return handleDataState = (response) -> log "handleDataState" olog response await contentHandler.prepareOriginal(response.contentHash) prepareImages() contentHandler.reflectEdits(response.edits) if Object.keys(response.edits).length > 0 then setDirtyState() else setCleanState() renderProcess() return dataStateRequestError = -> log "dataStateRequestError" auth.logout() return ############################################################ adminmodule.noticeContentChange = -> setDirtyState() adminmodule.noticeAuthorizationSuccess = -> log "adminmodule.noticeAuthorization" token = appState.token() langTag = pwaContent.languageTag path = window.location.pathname documentName = path.split("/").pop(); communicationObject = {langTag, documentName, token} try response = await network.scicall("getDataState", communicationObject) await handleDataState(response) catch err then dataStateRequestError() return adminmodule.noticeAuthorizationFail = -> log "adminmodule.noticeAuthorizationFail" return adminmodule.discard = -> log "adminmodule.discard" try langTag = pwaContent.languageTag await network.scicall("discard", {langTag, token}) contentHandler.reflectEdits({}) setCleanState() bottomPanel.setSuccessMessage("Alle Änderungen wurden verworfen") renderProcess() catch err bottomPanel.setErrorMessage("Keine Änderungen wurden verworfen!") return adminmodule.apply = -> log "adminmodule.apply" try token = appState.token() langTag = pwaContent.languageTag path = window.location.pathname documentName = path.split("/").pop(); communicationObject = {langTag, documentName, token} await network.scicall("apply", {langTag, token}) response = await network.scicall("getDataState", communicationObject) await handleDataState(response) bottomPanel.setSuccessMessage("Alle Änderungen wurden übernommen") catch err bottomPanel.setErrorMessage("Keine Änderungen wurden übernommen!") return adminmodule.start = -> log "adminmodule.start" prepareImages() renderProcess() return module.exports = adminmodule
128813
adminmodule = {name: "adminmodule"} ############################################################ #region printLogFunctions log = (arg) -> if adminModules.debugmodule.modulesToDebug["adminmodule"]? then console.log "[adminmodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ #region modulesFromEnvironment mustache = require "mustache" ############################################################ mustachekeys = null templatepreparation = null network = null adminpanel = null appState = null contentHandler = null bottomPanel = null bigPanel = null imageManagement = null listManagement = null linkManagement = null auth = null #endregion ############################################################ #region internalProperties currentEditTextFallback = "" ############################################################ typingSecret = false loggingIn = false token = "" panelVisible = true showingEditables = false #endregion ############################################################ adminmodule.initialize = () -> log "adminmodule.initialize" mustachekeys = adminModules.mustachekeysmodule templatepreparation = adminModules.templatepreparationmodule network = adminModules.networkmodule adminpanel = adminModules.adminpanelmodule appState = adminModules.appstatemodule auth = adminModules.authmodule contentHandler = adminModules.contenthandlermodule bigPanel = adminModules.bigpanelmodule imageManagement = adminModules.imagemanagementmodule listManagement = adminModules.listmanagementmodule linkManagement = adminModules.linkmanagementmodule bottomPanel = adminModules.bottompanelmodule return ############################################################ renderProcess = -> log "renderProcess" content = contentHandler.content() mustachekeys.createMustacheKeys() mustacheTemplate = template(pwaMustacheKeymap) # log mustacheTemplate shadowBody = document.createElement("body") shadowBody.innerHTML = mustacheTemplate templatepreparation.prepareBody(shadowBody) preparedTemplate = shadowBody.innerHTML # log preparedTemplate htmlResult = mustache.render(preparedTemplate, content) # log htmlResult newBody = document.createElement("body") newBody.innerHTML = htmlResult adminpanel.attachPanelToBody(newBody) document.body = newBody addAdministrativeEventListeners() bigPanel.prepare() return ############################################################ #region stuffForEditing addAdministrativeEventListeners = -> log "addAdministrativeEventListeners" allEditableTexts = document.querySelectorAll("[text-content-key]") for editable in allEditableTexts editable.addEventListener("keydown", editKeyPressed) editable.addEventListener("focusin", startedEditing) editable.addEventListener("focusout", stoppedEditing) allEditableImages = document.querySelectorAll("[image-content-key]") for editable in allEditableImages editable.addEventListener("click", editableImageClicked) return ############################################################ #region eventListeners editableImageClicked = (event) -> log "editableImageClicked" imageLabel = event.target.getAttribute("image-content-key") bigPanel.activateEdit("images", imageLabel) bottomPanel.applyUIState() return editKeyPressed = (event) -> log "editKeyPressed" key = event.keyCode if (key == 27) #escape this.textContent = currentEditTextFallback document.activeElement.blur() return startedEditing = (event) -> log "startedEditing" element = event.target element.classList.add("editing") currentEditTextFallback = element.textContent return stoppedEditing = (event) -> log "stoppedEditing" element = event.target element.classList.remove("editing") return if element.textContent == currentEditTextFallback contentKeyString = element.getAttribute("text-content-key") newContentText(contentKeyString, element.textContent) return #endregion ############################################################ newContentText = (contentKeyString, content) -> log "newContentText" log contentKeyString log content token = appState.token() langTag = pwaContent.languageTag path = window.location.pathname documentName = path.split("/").pop() updateObject = {langTag, documentName, contentKeyString, content, token} oldContent = currentEditTextFallback try response = await network.scicall("update", updateObject) edits = {} edits[contentKeyString] = content contentHandler.reflectEdits(edits) updateSuccess(response) catch err then revertEdit(contentKeyString, oldContent) return ############################################################ revertEdit = (contentKeyString, oldText) -> log "revertEdit" bottomPanel.setErrorMessage("Veränderung konnte nicht angenommen werden!") selector = "[text-content-key='"+contentKeyString+"']" element = document.querySelector(selector) element.textContent = oldText return setCleanState = -> log "setCleanState" appState.setClean() bottomPanel.applyUIState() return setDirtyState = -> log "setDirtyState" appState.setDirty() bottomPanel.applyUIState() return ############################################################ updateSuccess = (response) -> log "updateSuccess" setDirtyState() bottomPanel.setSuccessMessage("Veränderung angenommen") return prepareImages = -> log "prepareImages" content = contentHandler.content() imageManagement.setImages(content.images) return handleDataState = (response) -> log "handleDataState" olog response await contentHandler.prepareOriginal(response.contentHash) prepareImages() contentHandler.reflectEdits(response.edits) if Object.keys(response.edits).length > 0 then setDirtyState() else setCleanState() renderProcess() return dataStateRequestError = -> log "dataStateRequestError" auth.logout() return ############################################################ adminmodule.noticeContentChange = -> setDirtyState() adminmodule.noticeAuthorizationSuccess = -> log "adminmodule.noticeAuthorization" token = appState.token() langTag = pwaContent.languageTag path = window.location.pathname documentName = path.split("/").pop(); communicationObject = {langTag, documentName, token} try response = await network.scicall("getDataState", communicationObject) await handleDataState(response) catch err then dataStateRequestError() return adminmodule.noticeAuthorizationFail = -> log "adminmodule.noticeAuthorizationFail" return adminmodule.discard = -> log "adminmodule.discard" try langTag = pwaContent.languageTag await network.scicall("discard", {langTag, token}) contentHandler.reflectEdits({}) setCleanState() bottomPanel.setSuccessMessage("Alle Änderungen wurden verworfen") renderProcess() catch err bottomPanel.setErrorMessage("Keine Änderungen wurden verworfen!") return adminmodule.apply = -> log "adminmodule.apply" try token = <KEY>() langTag = pwaContent.languageTag path = window.location.pathname documentName = path.split("/").pop(); communicationObject = {langTag, documentName, token} await network.scicall("apply", {langTag, token}) response = await network.scicall("getDataState", communicationObject) await handleDataState(response) bottomPanel.setSuccessMessage("Alle Änderungen wurden übernommen") catch err bottomPanel.setErrorMessage("Keine Änderungen wurden übernommen!") return adminmodule.start = -> log "adminmodule.start" prepareImages() renderProcess() return module.exports = adminmodule
true
adminmodule = {name: "adminmodule"} ############################################################ #region printLogFunctions log = (arg) -> if adminModules.debugmodule.modulesToDebug["adminmodule"]? then console.log "[adminmodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ #region modulesFromEnvironment mustache = require "mustache" ############################################################ mustachekeys = null templatepreparation = null network = null adminpanel = null appState = null contentHandler = null bottomPanel = null bigPanel = null imageManagement = null listManagement = null linkManagement = null auth = null #endregion ############################################################ #region internalProperties currentEditTextFallback = "" ############################################################ typingSecret = false loggingIn = false token = "" panelVisible = true showingEditables = false #endregion ############################################################ adminmodule.initialize = () -> log "adminmodule.initialize" mustachekeys = adminModules.mustachekeysmodule templatepreparation = adminModules.templatepreparationmodule network = adminModules.networkmodule adminpanel = adminModules.adminpanelmodule appState = adminModules.appstatemodule auth = adminModules.authmodule contentHandler = adminModules.contenthandlermodule bigPanel = adminModules.bigpanelmodule imageManagement = adminModules.imagemanagementmodule listManagement = adminModules.listmanagementmodule linkManagement = adminModules.linkmanagementmodule bottomPanel = adminModules.bottompanelmodule return ############################################################ renderProcess = -> log "renderProcess" content = contentHandler.content() mustachekeys.createMustacheKeys() mustacheTemplate = template(pwaMustacheKeymap) # log mustacheTemplate shadowBody = document.createElement("body") shadowBody.innerHTML = mustacheTemplate templatepreparation.prepareBody(shadowBody) preparedTemplate = shadowBody.innerHTML # log preparedTemplate htmlResult = mustache.render(preparedTemplate, content) # log htmlResult newBody = document.createElement("body") newBody.innerHTML = htmlResult adminpanel.attachPanelToBody(newBody) document.body = newBody addAdministrativeEventListeners() bigPanel.prepare() return ############################################################ #region stuffForEditing addAdministrativeEventListeners = -> log "addAdministrativeEventListeners" allEditableTexts = document.querySelectorAll("[text-content-key]") for editable in allEditableTexts editable.addEventListener("keydown", editKeyPressed) editable.addEventListener("focusin", startedEditing) editable.addEventListener("focusout", stoppedEditing) allEditableImages = document.querySelectorAll("[image-content-key]") for editable in allEditableImages editable.addEventListener("click", editableImageClicked) return ############################################################ #region eventListeners editableImageClicked = (event) -> log "editableImageClicked" imageLabel = event.target.getAttribute("image-content-key") bigPanel.activateEdit("images", imageLabel) bottomPanel.applyUIState() return editKeyPressed = (event) -> log "editKeyPressed" key = event.keyCode if (key == 27) #escape this.textContent = currentEditTextFallback document.activeElement.blur() return startedEditing = (event) -> log "startedEditing" element = event.target element.classList.add("editing") currentEditTextFallback = element.textContent return stoppedEditing = (event) -> log "stoppedEditing" element = event.target element.classList.remove("editing") return if element.textContent == currentEditTextFallback contentKeyString = element.getAttribute("text-content-key") newContentText(contentKeyString, element.textContent) return #endregion ############################################################ newContentText = (contentKeyString, content) -> log "newContentText" log contentKeyString log content token = appState.token() langTag = pwaContent.languageTag path = window.location.pathname documentName = path.split("/").pop() updateObject = {langTag, documentName, contentKeyString, content, token} oldContent = currentEditTextFallback try response = await network.scicall("update", updateObject) edits = {} edits[contentKeyString] = content contentHandler.reflectEdits(edits) updateSuccess(response) catch err then revertEdit(contentKeyString, oldContent) return ############################################################ revertEdit = (contentKeyString, oldText) -> log "revertEdit" bottomPanel.setErrorMessage("Veränderung konnte nicht angenommen werden!") selector = "[text-content-key='"+contentKeyString+"']" element = document.querySelector(selector) element.textContent = oldText return setCleanState = -> log "setCleanState" appState.setClean() bottomPanel.applyUIState() return setDirtyState = -> log "setDirtyState" appState.setDirty() bottomPanel.applyUIState() return ############################################################ updateSuccess = (response) -> log "updateSuccess" setDirtyState() bottomPanel.setSuccessMessage("Veränderung angenommen") return prepareImages = -> log "prepareImages" content = contentHandler.content() imageManagement.setImages(content.images) return handleDataState = (response) -> log "handleDataState" olog response await contentHandler.prepareOriginal(response.contentHash) prepareImages() contentHandler.reflectEdits(response.edits) if Object.keys(response.edits).length > 0 then setDirtyState() else setCleanState() renderProcess() return dataStateRequestError = -> log "dataStateRequestError" auth.logout() return ############################################################ adminmodule.noticeContentChange = -> setDirtyState() adminmodule.noticeAuthorizationSuccess = -> log "adminmodule.noticeAuthorization" token = appState.token() langTag = pwaContent.languageTag path = window.location.pathname documentName = path.split("/").pop(); communicationObject = {langTag, documentName, token} try response = await network.scicall("getDataState", communicationObject) await handleDataState(response) catch err then dataStateRequestError() return adminmodule.noticeAuthorizationFail = -> log "adminmodule.noticeAuthorizationFail" return adminmodule.discard = -> log "adminmodule.discard" try langTag = pwaContent.languageTag await network.scicall("discard", {langTag, token}) contentHandler.reflectEdits({}) setCleanState() bottomPanel.setSuccessMessage("Alle Änderungen wurden verworfen") renderProcess() catch err bottomPanel.setErrorMessage("Keine Änderungen wurden verworfen!") return adminmodule.apply = -> log "adminmodule.apply" try token = PI:KEY:<KEY>END_PI() langTag = pwaContent.languageTag path = window.location.pathname documentName = path.split("/").pop(); communicationObject = {langTag, documentName, token} await network.scicall("apply", {langTag, token}) response = await network.scicall("getDataState", communicationObject) await handleDataState(response) bottomPanel.setSuccessMessage("Alle Änderungen wurden übernommen") catch err bottomPanel.setErrorMessage("Keine Änderungen wurden übernommen!") return adminmodule.start = -> log "adminmodule.start" prepareImages() renderProcess() return module.exports = adminmodule
[ { "context": "rom.reject()\n prom.promise\n\n email = 'wrong@email.here'\n password = 'wrongpassword'\n\n @control", "end": 2337, "score": 0.9999063611030579, "start": 2321, "tag": "EMAIL", "value": "wrong@email.here" }, { "context": " email = 'wrong@email.here'\n password = 'wrongpassword'\n\n @controller.email = email\n @controll", "end": 2370, "score": 0.999234676361084, "start": 2357, "tag": "PASSWORD", "value": "wrongpassword" }, { "context": "troller.email = email\n @controller.password = password\n @controller.signIn()\n\n @$rootScope.$di", "end": 2442, "score": 0.99907386302948, "start": 2434, "tag": "PASSWORD", "value": "password" }, { "context": "om.resolve()\n prom.promise\n\n email = 'correct@email.here'\n password = 'correct password'\n\n @cont", "end": 3146, "score": 0.9999104738235474, "start": 3128, "tag": "EMAIL", "value": "correct@email.here" }, { "context": " email = 'correct@email.here'\n password = 'correct password'\n\n @controller.email = email\n @controll", "end": 3182, "score": 0.999274730682373, "start": 3166, "tag": "PASSWORD", "value": "correct password" }, { "context": "troller.email = email\n @controller.password = password\n @controller.signIn()\n\n @$rootScope.$di", "end": 3254, "score": 0.9990382194519043, "start": 3246, "tag": "PASSWORD", "value": "password" } ]
src/app/layout/layout.navigation.spec.coffee
pavelkuchin/tracktrains-ui
0
describe 'LayoutNavigationCtrl', () -> beforeEach(module('trackSeatsApp')) beforeEach(inject((@$rootScope, $controller, $httpBackend, @$q, @ALERTS_TYPE, @NAVIGATION) => $httpBackend.when('GET', '/v1/user/session/').respond({}) $httpBackend.when('GET', 'app/pages/landing/pages.landing.template.html') .respond({}) @emptySessionStub = authorized: false user: {} @stubState = jasmine.createSpyObj('$state', ['go']) @stubAlertsService = jasmine.createSpyObj('AlertsService', ['showAlert']) @stubAlertsService.TYPE = @ALERTS_TYPE @stubAuthService = jasmine.createSpyObj('AuthService', [ 'checkAuthentication' 'signIn' 'signOut' ]) @stubAuthService.checkAuthentication.and.returnValue(@$q.when(@emptySessionStub)) @scope = $rootScope.$new() @controller = $controller('LayoutNavigationCtrl', $scope: @scope AuthService: @stubAuthService AlertsService: @stubAlertsService $state: @stubState ) @$rootScope.$digest() )) describe 'controller.session', () => it 'session equals to session object from @authService.checkAuthentication() call', () => expect(@controller.session).toEqual({authorized: false, user: {}}) describe 'controller.navCollapsed', () => it 'navCollapsed is true when initialized', () => expect(@controller.navCollapsed).toEqual(true) it 'navCollapsed is changed by controller.toggleNavCollapsed()', () => @controller.toggleNavCollapsed() expect(@controller.navCollapsed).toEqual(false) @controller.toggleNavCollapsed() expect(@controller.navCollapsed).toEqual(true) describe 'controller.signIn', () => it 'if email or/and password are empty then message should be displayed', () => @controller.email = '' @controller.password = '' @controller.signIn() expect(@stubAlertsService.showAlert) .toHaveBeenCalledWith( "Please enter email and password.", @ALERTS_TYPE.ERROR, 3000 ) it 'if email or/and password are invalid then message should be displayed and email/password cleared', () => @stubAuthService.signIn.and.callFake () => prom = @$q.defer() prom.reject() prom.promise email = 'wrong@email.here' password = 'wrongpassword' @controller.email = email @controller.password = password @controller.signIn() @$rootScope.$digest() expect(@stubAuthService.signIn) .toHaveBeenCalledWith(email, password) expect(@stubAlertsService.showAlert).toHaveBeenCalledWith( "User with this email/password has not been found.", @ALERTS_TYPE.ERROR, 3000) expect(@controller.email).toEqual('') expect(@controller.password).toEqual('') it 'if email and password are correct then state should be changed to AUTHENTICATED_DEFAULT_STATE and email/password cleared', () => @stubAuthService.signIn.and.callFake () => prom = @$q.defer() prom.resolve() prom.promise email = 'correct@email.here' password = 'correct password' @controller.email = email @controller.password = password @controller.signIn() @$rootScope.$digest() expect(@stubAuthService.signIn) .toHaveBeenCalledWith(email, password) expect(@stubState.go) .toHaveBeenCalledWith(@NAVIGATION.AUTHENTICATED_DEFAULT_STATE) expect(@controller.email).toEqual('') expect(@controller.password).toEqual('') describe 'controller.signOut', () => it 'Should call authService.signOut and then go to UNAUTHENTICATED_DEFAULT_STATE', () => @controller.signOut() expect(@stubAuthService.signOut).toHaveBeenCalled() expect(@stubState.go) .toHaveBeenCalledWith(@NAVIGATION.UNAUTHENTICATED_DEFAULT_STATE)
124024
describe 'LayoutNavigationCtrl', () -> beforeEach(module('trackSeatsApp')) beforeEach(inject((@$rootScope, $controller, $httpBackend, @$q, @ALERTS_TYPE, @NAVIGATION) => $httpBackend.when('GET', '/v1/user/session/').respond({}) $httpBackend.when('GET', 'app/pages/landing/pages.landing.template.html') .respond({}) @emptySessionStub = authorized: false user: {} @stubState = jasmine.createSpyObj('$state', ['go']) @stubAlertsService = jasmine.createSpyObj('AlertsService', ['showAlert']) @stubAlertsService.TYPE = @ALERTS_TYPE @stubAuthService = jasmine.createSpyObj('AuthService', [ 'checkAuthentication' 'signIn' 'signOut' ]) @stubAuthService.checkAuthentication.and.returnValue(@$q.when(@emptySessionStub)) @scope = $rootScope.$new() @controller = $controller('LayoutNavigationCtrl', $scope: @scope AuthService: @stubAuthService AlertsService: @stubAlertsService $state: @stubState ) @$rootScope.$digest() )) describe 'controller.session', () => it 'session equals to session object from @authService.checkAuthentication() call', () => expect(@controller.session).toEqual({authorized: false, user: {}}) describe 'controller.navCollapsed', () => it 'navCollapsed is true when initialized', () => expect(@controller.navCollapsed).toEqual(true) it 'navCollapsed is changed by controller.toggleNavCollapsed()', () => @controller.toggleNavCollapsed() expect(@controller.navCollapsed).toEqual(false) @controller.toggleNavCollapsed() expect(@controller.navCollapsed).toEqual(true) describe 'controller.signIn', () => it 'if email or/and password are empty then message should be displayed', () => @controller.email = '' @controller.password = '' @controller.signIn() expect(@stubAlertsService.showAlert) .toHaveBeenCalledWith( "Please enter email and password.", @ALERTS_TYPE.ERROR, 3000 ) it 'if email or/and password are invalid then message should be displayed and email/password cleared', () => @stubAuthService.signIn.and.callFake () => prom = @$q.defer() prom.reject() prom.promise email = '<EMAIL>' password = '<PASSWORD>' @controller.email = email @controller.password = <PASSWORD> @controller.signIn() @$rootScope.$digest() expect(@stubAuthService.signIn) .toHaveBeenCalledWith(email, password) expect(@stubAlertsService.showAlert).toHaveBeenCalledWith( "User with this email/password has not been found.", @ALERTS_TYPE.ERROR, 3000) expect(@controller.email).toEqual('') expect(@controller.password).toEqual('') it 'if email and password are correct then state should be changed to AUTHENTICATED_DEFAULT_STATE and email/password cleared', () => @stubAuthService.signIn.and.callFake () => prom = @$q.defer() prom.resolve() prom.promise email = '<EMAIL>' password = '<PASSWORD>' @controller.email = email @controller.password = <PASSWORD> @controller.signIn() @$rootScope.$digest() expect(@stubAuthService.signIn) .toHaveBeenCalledWith(email, password) expect(@stubState.go) .toHaveBeenCalledWith(@NAVIGATION.AUTHENTICATED_DEFAULT_STATE) expect(@controller.email).toEqual('') expect(@controller.password).toEqual('') describe 'controller.signOut', () => it 'Should call authService.signOut and then go to UNAUTHENTICATED_DEFAULT_STATE', () => @controller.signOut() expect(@stubAuthService.signOut).toHaveBeenCalled() expect(@stubState.go) .toHaveBeenCalledWith(@NAVIGATION.UNAUTHENTICATED_DEFAULT_STATE)
true
describe 'LayoutNavigationCtrl', () -> beforeEach(module('trackSeatsApp')) beforeEach(inject((@$rootScope, $controller, $httpBackend, @$q, @ALERTS_TYPE, @NAVIGATION) => $httpBackend.when('GET', '/v1/user/session/').respond({}) $httpBackend.when('GET', 'app/pages/landing/pages.landing.template.html') .respond({}) @emptySessionStub = authorized: false user: {} @stubState = jasmine.createSpyObj('$state', ['go']) @stubAlertsService = jasmine.createSpyObj('AlertsService', ['showAlert']) @stubAlertsService.TYPE = @ALERTS_TYPE @stubAuthService = jasmine.createSpyObj('AuthService', [ 'checkAuthentication' 'signIn' 'signOut' ]) @stubAuthService.checkAuthentication.and.returnValue(@$q.when(@emptySessionStub)) @scope = $rootScope.$new() @controller = $controller('LayoutNavigationCtrl', $scope: @scope AuthService: @stubAuthService AlertsService: @stubAlertsService $state: @stubState ) @$rootScope.$digest() )) describe 'controller.session', () => it 'session equals to session object from @authService.checkAuthentication() call', () => expect(@controller.session).toEqual({authorized: false, user: {}}) describe 'controller.navCollapsed', () => it 'navCollapsed is true when initialized', () => expect(@controller.navCollapsed).toEqual(true) it 'navCollapsed is changed by controller.toggleNavCollapsed()', () => @controller.toggleNavCollapsed() expect(@controller.navCollapsed).toEqual(false) @controller.toggleNavCollapsed() expect(@controller.navCollapsed).toEqual(true) describe 'controller.signIn', () => it 'if email or/and password are empty then message should be displayed', () => @controller.email = '' @controller.password = '' @controller.signIn() expect(@stubAlertsService.showAlert) .toHaveBeenCalledWith( "Please enter email and password.", @ALERTS_TYPE.ERROR, 3000 ) it 'if email or/and password are invalid then message should be displayed and email/password cleared', () => @stubAuthService.signIn.and.callFake () => prom = @$q.defer() prom.reject() prom.promise email = 'PI:EMAIL:<EMAIL>END_PI' password = 'PI:PASSWORD:<PASSWORD>END_PI' @controller.email = email @controller.password = PI:PASSWORD:<PASSWORD>END_PI @controller.signIn() @$rootScope.$digest() expect(@stubAuthService.signIn) .toHaveBeenCalledWith(email, password) expect(@stubAlertsService.showAlert).toHaveBeenCalledWith( "User with this email/password has not been found.", @ALERTS_TYPE.ERROR, 3000) expect(@controller.email).toEqual('') expect(@controller.password).toEqual('') it 'if email and password are correct then state should be changed to AUTHENTICATED_DEFAULT_STATE and email/password cleared', () => @stubAuthService.signIn.and.callFake () => prom = @$q.defer() prom.resolve() prom.promise email = 'PI:EMAIL:<EMAIL>END_PI' password = 'PI:PASSWORD:<PASSWORD>END_PI' @controller.email = email @controller.password = PI:PASSWORD:<PASSWORD>END_PI @controller.signIn() @$rootScope.$digest() expect(@stubAuthService.signIn) .toHaveBeenCalledWith(email, password) expect(@stubState.go) .toHaveBeenCalledWith(@NAVIGATION.AUTHENTICATED_DEFAULT_STATE) expect(@controller.email).toEqual('') expect(@controller.password).toEqual('') describe 'controller.signOut', () => it 'Should call authService.signOut and then go to UNAUTHENTICATED_DEFAULT_STATE', () => @controller.signOut() expect(@stubAuthService.signOut).toHaveBeenCalled() expect(@stubState.go) .toHaveBeenCalledWith(@NAVIGATION.UNAUTHENTICATED_DEFAULT_STATE)
[ { "context": "#\n# Just The Date widget for Übersicht\n# Ruurd Pels\n# github.com/ruurd/justthedate\n#\n\n#\n# Adjust the ", "end": 51, "score": 0.999901533126831, "start": 41, "tag": "NAME", "value": "Ruurd Pels" }, { "context": "te widget for Übersicht\n# Ruurd Pels\n# github.com/ruurd/justthedate\n#\n\n#\n# Adjust the styles as you like\n", "end": 70, "score": 0.9995002150535583, "start": 65, "tag": "USERNAME", "value": "ruurd" } ]
index.coffee
ruurd/simpledate
0
# # Just The Date widget for Übersicht # Ruurd Pels # github.com/ruurd/justthedate # # # Adjust the styles as you like # style = # Define the maximum width of the widget. width: "45%" # Define the position, where to display the date. # Set properties you don't need to "auto" position: top: "1%" bottom: "auto" left: "auto" right: "1%" # Font properties font: "'Helvetica Neue', sans-serif" font_color: "#F5F5F5" font_size: "50px" font_weight: "100" letter_spacing: "0.025em" line_height: ".9em" # Misc text_align: "right" text_transform: "uppercase" # Do the command - never mind in this case command: "echo hello date" # Lower the frequency for more accuracy. refreshFrequency: (1000 * 60) # (1000 * n) seconds render: (o) -> """ <div id="content"> <span id="date"></span> </div> """ update: (output, dom) -> date = new Date(); d = date.getDate(); m = date.getMonth() + 1; y = date.getFullYear(); time_str = ("0" + d).slice(-2) + '-' + ("0" + m).slice(-2) + '-' + y; $(dom).find("#date").html(time_str) style: """ top: #{style.position.top} bottom: #{style.position.bottom} right: #{style.position.right} left: #{style.position.left} width: #{style.width} font-family: #{style.font} color: #{style.font_color} font-weight: #{style.font_weight} text-align: #{style.text_align} text-transform: #{style.text_transform} font-size: #{style.font_size} letter-spacing: #{style.letter_spacing} font-smoothing: antialiased line-height: #{style.line_height} """
76902
# # Just The Date widget for Übersicht # <NAME> # github.com/ruurd/justthedate # # # Adjust the styles as you like # style = # Define the maximum width of the widget. width: "45%" # Define the position, where to display the date. # Set properties you don't need to "auto" position: top: "1%" bottom: "auto" left: "auto" right: "1%" # Font properties font: "'Helvetica Neue', sans-serif" font_color: "#F5F5F5" font_size: "50px" font_weight: "100" letter_spacing: "0.025em" line_height: ".9em" # Misc text_align: "right" text_transform: "uppercase" # Do the command - never mind in this case command: "echo hello date" # Lower the frequency for more accuracy. refreshFrequency: (1000 * 60) # (1000 * n) seconds render: (o) -> """ <div id="content"> <span id="date"></span> </div> """ update: (output, dom) -> date = new Date(); d = date.getDate(); m = date.getMonth() + 1; y = date.getFullYear(); time_str = ("0" + d).slice(-2) + '-' + ("0" + m).slice(-2) + '-' + y; $(dom).find("#date").html(time_str) style: """ top: #{style.position.top} bottom: #{style.position.bottom} right: #{style.position.right} left: #{style.position.left} width: #{style.width} font-family: #{style.font} color: #{style.font_color} font-weight: #{style.font_weight} text-align: #{style.text_align} text-transform: #{style.text_transform} font-size: #{style.font_size} letter-spacing: #{style.letter_spacing} font-smoothing: antialiased line-height: #{style.line_height} """
true
# # Just The Date widget for Übersicht # PI:NAME:<NAME>END_PI # github.com/ruurd/justthedate # # # Adjust the styles as you like # style = # Define the maximum width of the widget. width: "45%" # Define the position, where to display the date. # Set properties you don't need to "auto" position: top: "1%" bottom: "auto" left: "auto" right: "1%" # Font properties font: "'Helvetica Neue', sans-serif" font_color: "#F5F5F5" font_size: "50px" font_weight: "100" letter_spacing: "0.025em" line_height: ".9em" # Misc text_align: "right" text_transform: "uppercase" # Do the command - never mind in this case command: "echo hello date" # Lower the frequency for more accuracy. refreshFrequency: (1000 * 60) # (1000 * n) seconds render: (o) -> """ <div id="content"> <span id="date"></span> </div> """ update: (output, dom) -> date = new Date(); d = date.getDate(); m = date.getMonth() + 1; y = date.getFullYear(); time_str = ("0" + d).slice(-2) + '-' + ("0" + m).slice(-2) + '-' + y; $(dom).find("#date").html(time_str) style: """ top: #{style.position.top} bottom: #{style.position.bottom} right: #{style.position.right} left: #{style.position.left} width: #{style.width} font-family: #{style.font} color: #{style.font_color} font-weight: #{style.font_weight} text-align: #{style.text_align} text-transform: #{style.text_transform} font-size: #{style.font_size} letter-spacing: #{style.letter_spacing} font-smoothing: antialiased line-height: #{style.line_height} """
[ { "context": "_user =\n\t\t\tname: null\n\t\t\temail: email\n\t\t\tpassword: passwordcypt\n\t\t@get email, \"email\", ( err, user )=>\n\t\t\tif err ", "end": 1318, "score": 0.9986447691917419, "start": 1306, "tag": "PASSWORD", "value": "passwordcypt" }, { "context": " err )\n\n\t\t\tif user?\n\t\t\t\t@update user.id, password: passwordcypt, ( err, dbUser )=>\n\t\t\t\t\tif err\n\t\t\t\t\t\tcb( err )\n\t\t", "end": 1467, "score": 0.9992641806602478, "start": 1455, "tag": "PASSWORD", "value": "passwordcypt" } ]
_src/test/dummy_userstore.coffee
mpneuried/tcs_node_auth
1
_ = require( "lodash" )._ class DummyDB constructor: ( @coll )-> return # Dummy db methods has: ( query, cb )=> if _.some( @coll, query ) cb( null, true ) else cb( null, false ) return filter: ( query, cb )=> _result = _.filter( @coll, query ) cb( null, _result ) return create: ( data, cb )=> newID = _.max( @coll, "id" ).id + 1 data.id = newID @coll.push( data ) cb( null, data ) return get: => [ args..., cb ] = arguments [ crit, key ] = args _query = {} _query[ key or "id" ] = crit @filter _query, ( err, users )=> if not users?.length cb( new Error( "not-found" ) ) return cb( null, users[ 0 ] ) return return update: ( id, data, cb )=> @get id, ( err, user )=> if err cb( err ) return cb( null, _.extend( user, data ) ) return return class DefektUserStore extends DummyDB # UserStore methods getUserCredentials: ( email, cb )=> @filter email: email, ( err, users )=> if not users?.length cb( new Error( "not-found" ) ) return cb( err, users[ 0 ].password, users[ 0 ] ) return return checkUserEmail: ( email, options, cb )=> @has( email: email, cb ) return setUserCredentials: ( email, passwordcypt, isRegister, cb )=> _user = name: null email: email password: passwordcypt @get email, "email", ( err, user )=> if err and err?.name is "not-found" cb( err ) if user? @update user.id, password: passwordcypt, ( err, dbUser )=> if err cb( err ) return cb( null, dbUser ) return else @create _user, ( err, dbUser )=> if err cb( err ) return cb( null, dbUser ) return return return setUserMail: ( current_email, new_email, cb )=> @get current_email, "email", ( err, user )=> if err cb( err ) return @update user.id, email: new_email, ( err, dbUser )=> if err cb( err ) return cb( null, dbUser ) return return return class DummyUserStore extends DefektUserStore getMailContent: ( type ,tokenOrNewmail, options, cb )=> switch type when "register" then mailData = { subject: "Test activation" } when "forgot" then mailData = { subject: "Test password forgot" } when "changemail" then mailData = { subject: "Test change mail" } when "notifyoldmail" then mailData = { subject: "Test notify old mail" } if type is "notifyoldmail" mailData.body = "Your mail has changed to `#{tokenOrNewmail}`." else if options?.testMissingLink? mailData.body = "Body without token should cause an error." else mailData.body = "Follow http://www.test.com/#{tokenOrNewmail} to set your password." cb( null, mailData ) return class NotFunctionUserStore extends DefektUserStore getActivationMail: 123 module.exports = main: new DummyUserStore( require( "./dummydata" ) ) notfunction: new NotFunctionUserStore( require( "./dummydata" ) ) missingmethod: new DefektUserStore( require( "./dummydata" ) )
49948
_ = require( "lodash" )._ class DummyDB constructor: ( @coll )-> return # Dummy db methods has: ( query, cb )=> if _.some( @coll, query ) cb( null, true ) else cb( null, false ) return filter: ( query, cb )=> _result = _.filter( @coll, query ) cb( null, _result ) return create: ( data, cb )=> newID = _.max( @coll, "id" ).id + 1 data.id = newID @coll.push( data ) cb( null, data ) return get: => [ args..., cb ] = arguments [ crit, key ] = args _query = {} _query[ key or "id" ] = crit @filter _query, ( err, users )=> if not users?.length cb( new Error( "not-found" ) ) return cb( null, users[ 0 ] ) return return update: ( id, data, cb )=> @get id, ( err, user )=> if err cb( err ) return cb( null, _.extend( user, data ) ) return return class DefektUserStore extends DummyDB # UserStore methods getUserCredentials: ( email, cb )=> @filter email: email, ( err, users )=> if not users?.length cb( new Error( "not-found" ) ) return cb( err, users[ 0 ].password, users[ 0 ] ) return return checkUserEmail: ( email, options, cb )=> @has( email: email, cb ) return setUserCredentials: ( email, passwordcypt, isRegister, cb )=> _user = name: null email: email password: <PASSWORD> @get email, "email", ( err, user )=> if err and err?.name is "not-found" cb( err ) if user? @update user.id, password: <PASSWORD>, ( err, dbUser )=> if err cb( err ) return cb( null, dbUser ) return else @create _user, ( err, dbUser )=> if err cb( err ) return cb( null, dbUser ) return return return setUserMail: ( current_email, new_email, cb )=> @get current_email, "email", ( err, user )=> if err cb( err ) return @update user.id, email: new_email, ( err, dbUser )=> if err cb( err ) return cb( null, dbUser ) return return return class DummyUserStore extends DefektUserStore getMailContent: ( type ,tokenOrNewmail, options, cb )=> switch type when "register" then mailData = { subject: "Test activation" } when "forgot" then mailData = { subject: "Test password forgot" } when "changemail" then mailData = { subject: "Test change mail" } when "notifyoldmail" then mailData = { subject: "Test notify old mail" } if type is "notifyoldmail" mailData.body = "Your mail has changed to `#{tokenOrNewmail}`." else if options?.testMissingLink? mailData.body = "Body without token should cause an error." else mailData.body = "Follow http://www.test.com/#{tokenOrNewmail} to set your password." cb( null, mailData ) return class NotFunctionUserStore extends DefektUserStore getActivationMail: 123 module.exports = main: new DummyUserStore( require( "./dummydata" ) ) notfunction: new NotFunctionUserStore( require( "./dummydata" ) ) missingmethod: new DefektUserStore( require( "./dummydata" ) )
true
_ = require( "lodash" )._ class DummyDB constructor: ( @coll )-> return # Dummy db methods has: ( query, cb )=> if _.some( @coll, query ) cb( null, true ) else cb( null, false ) return filter: ( query, cb )=> _result = _.filter( @coll, query ) cb( null, _result ) return create: ( data, cb )=> newID = _.max( @coll, "id" ).id + 1 data.id = newID @coll.push( data ) cb( null, data ) return get: => [ args..., cb ] = arguments [ crit, key ] = args _query = {} _query[ key or "id" ] = crit @filter _query, ( err, users )=> if not users?.length cb( new Error( "not-found" ) ) return cb( null, users[ 0 ] ) return return update: ( id, data, cb )=> @get id, ( err, user )=> if err cb( err ) return cb( null, _.extend( user, data ) ) return return class DefektUserStore extends DummyDB # UserStore methods getUserCredentials: ( email, cb )=> @filter email: email, ( err, users )=> if not users?.length cb( new Error( "not-found" ) ) return cb( err, users[ 0 ].password, users[ 0 ] ) return return checkUserEmail: ( email, options, cb )=> @has( email: email, cb ) return setUserCredentials: ( email, passwordcypt, isRegister, cb )=> _user = name: null email: email password: PI:PASSWORD:<PASSWORD>END_PI @get email, "email", ( err, user )=> if err and err?.name is "not-found" cb( err ) if user? @update user.id, password: PI:PASSWORD:<PASSWORD>END_PI, ( err, dbUser )=> if err cb( err ) return cb( null, dbUser ) return else @create _user, ( err, dbUser )=> if err cb( err ) return cb( null, dbUser ) return return return setUserMail: ( current_email, new_email, cb )=> @get current_email, "email", ( err, user )=> if err cb( err ) return @update user.id, email: new_email, ( err, dbUser )=> if err cb( err ) return cb( null, dbUser ) return return return class DummyUserStore extends DefektUserStore getMailContent: ( type ,tokenOrNewmail, options, cb )=> switch type when "register" then mailData = { subject: "Test activation" } when "forgot" then mailData = { subject: "Test password forgot" } when "changemail" then mailData = { subject: "Test change mail" } when "notifyoldmail" then mailData = { subject: "Test notify old mail" } if type is "notifyoldmail" mailData.body = "Your mail has changed to `#{tokenOrNewmail}`." else if options?.testMissingLink? mailData.body = "Body without token should cause an error." else mailData.body = "Follow http://www.test.com/#{tokenOrNewmail} to set your password." cb( null, mailData ) return class NotFunctionUserStore extends DefektUserStore getActivationMail: 123 module.exports = main: new DummyUserStore( require( "./dummydata" ) ) notfunction: new NotFunctionUserStore( require( "./dummydata" ) ) missingmethod: new DefektUserStore( require( "./dummydata" ) )
[ { "context": " ip: '1.2.3.4',\n ssh_key: 'overcast.key',\n ssh_port: '22',\n use", "end": 317, "score": 0.986060619354248, "start": 305, "tag": "KEY", "value": "overcast.key" }, { "context": " ssh_port: '22',\n user: 'root'\n }\n }\n }\n })\n ", "end": 375, "score": 0.7418826818466187, "start": 371, "tag": "USERNAME", "value": "root" } ]
test/unit/completions.spec.coffee
skmezanul/overcast
238
cli = require('../../modules/cli') utils = require('../../modules/utils') describe 'completions', -> beforeEach -> spyOn(utils, 'getClusters').andReturn({ default: { instances: { vm01: { name: 'vm01', ip: '1.2.3.4', ssh_key: 'overcast.key', ssh_port: '22', user: 'root' } } } }) spyOn(console, 'log') it 'should return a list of commands, clusters and instances', -> cli.execute('completions') stdout = console.log.mostRecentCall.args[0] expect(stdout).toContain 'overcast' expect(stdout).toContain 'aliases' expect(stdout).toContain 'default' expect(stdout).toContain 'vm01'
9371
cli = require('../../modules/cli') utils = require('../../modules/utils') describe 'completions', -> beforeEach -> spyOn(utils, 'getClusters').andReturn({ default: { instances: { vm01: { name: 'vm01', ip: '1.2.3.4', ssh_key: '<KEY>', ssh_port: '22', user: 'root' } } } }) spyOn(console, 'log') it 'should return a list of commands, clusters and instances', -> cli.execute('completions') stdout = console.log.mostRecentCall.args[0] expect(stdout).toContain 'overcast' expect(stdout).toContain 'aliases' expect(stdout).toContain 'default' expect(stdout).toContain 'vm01'
true
cli = require('../../modules/cli') utils = require('../../modules/utils') describe 'completions', -> beforeEach -> spyOn(utils, 'getClusters').andReturn({ default: { instances: { vm01: { name: 'vm01', ip: '1.2.3.4', ssh_key: 'PI:KEY:<KEY>END_PI', ssh_port: '22', user: 'root' } } } }) spyOn(console, 'log') it 'should return a list of commands, clusters and instances', -> cli.execute('completions') stdout = console.log.mostRecentCall.args[0] expect(stdout).toContain 'overcast' expect(stdout).toContain 'aliases' expect(stdout).toContain 'default' expect(stdout).toContain 'vm01'
[ { "context": "cribe 'Placebo', ->\n\n settings.linode_api_key = 'fakeapikey'\n settings.config_path = 'test/class'\n\n it 'can", "end": 222, "score": 0.9869097471237183, "start": 212, "tag": "KEY", "value": "fakeapikey" } ]
test/placebo.coffee
scraperwiki/lithium
0
# Placebo and its Mocha tests. should = require 'should' _ = require 'underscore' Placebo = require '../code/placebo' settings = require 'settings' describe 'Placebo', -> settings.linode_api_key = 'fakeapikey' settings.config_path = 'test/class' it 'can create a placebo instance with a config', -> instance = Placebo.create 'boxecutor' instance.should.be.an.instanceof Placebo instance.config.name.should.equal 'boxecutor' Placebo.list().should.include instance Placebo.destroy instance describe 'when two instances exist', -> l = null before -> (_ 2).times -> Placebo.create 'vanilla' l = Placebo.list() it 'can list created instances', -> l.should.be.an.instanceof Array l.length.should.equal 2 l[0].should.be.an.instanceof Placebo l[1].should.be.an.instanceof Placebo it 'can destroy a placebo instance, given its name', -> Placebo.destroy Placebo.list()[0] Placebo.list().length.should.equal 1 describe 'a new placebo instance', -> placebo = null before -> placebo = new Placebo 'boxecutor' it 'has a start method', -> should.exist placebo.start it 'has a stop method', -> should.exist placebo.stop it 'has a sh method', -> should.exist placebo.sh
53989
# Placebo and its Mocha tests. should = require 'should' _ = require 'underscore' Placebo = require '../code/placebo' settings = require 'settings' describe 'Placebo', -> settings.linode_api_key = '<KEY>' settings.config_path = 'test/class' it 'can create a placebo instance with a config', -> instance = Placebo.create 'boxecutor' instance.should.be.an.instanceof Placebo instance.config.name.should.equal 'boxecutor' Placebo.list().should.include instance Placebo.destroy instance describe 'when two instances exist', -> l = null before -> (_ 2).times -> Placebo.create 'vanilla' l = Placebo.list() it 'can list created instances', -> l.should.be.an.instanceof Array l.length.should.equal 2 l[0].should.be.an.instanceof Placebo l[1].should.be.an.instanceof Placebo it 'can destroy a placebo instance, given its name', -> Placebo.destroy Placebo.list()[0] Placebo.list().length.should.equal 1 describe 'a new placebo instance', -> placebo = null before -> placebo = new Placebo 'boxecutor' it 'has a start method', -> should.exist placebo.start it 'has a stop method', -> should.exist placebo.stop it 'has a sh method', -> should.exist placebo.sh
true
# Placebo and its Mocha tests. should = require 'should' _ = require 'underscore' Placebo = require '../code/placebo' settings = require 'settings' describe 'Placebo', -> settings.linode_api_key = 'PI:KEY:<KEY>END_PI' settings.config_path = 'test/class' it 'can create a placebo instance with a config', -> instance = Placebo.create 'boxecutor' instance.should.be.an.instanceof Placebo instance.config.name.should.equal 'boxecutor' Placebo.list().should.include instance Placebo.destroy instance describe 'when two instances exist', -> l = null before -> (_ 2).times -> Placebo.create 'vanilla' l = Placebo.list() it 'can list created instances', -> l.should.be.an.instanceof Array l.length.should.equal 2 l[0].should.be.an.instanceof Placebo l[1].should.be.an.instanceof Placebo it 'can destroy a placebo instance, given its name', -> Placebo.destroy Placebo.list()[0] Placebo.list().length.should.equal 1 describe 'a new placebo instance', -> placebo = null before -> placebo = new Placebo 'boxecutor' it 'has a start method', -> should.exist placebo.start it 'has a stop method', -> should.exist placebo.stop it 'has a sh method', -> should.exist placebo.sh
[ { "context": "est (or response), concatenated by dots.\n key = null\n entry = {}\n\n for i in [0..@path.length]\n ", "end": 2571, "score": 0.9840342402458191, "start": 2567, "tag": "KEY", "value": "null" } ]
src/detect-transaction-examples.coffee
cranieri/dredd-transactions-extended
0
traverse = require('traverse') detectTransactionExamples = (transition) -> # Index of requests and responses within given *transition*, sorted by # their position in the original API Blueprint document. index = createIndex(transition) # No transaction examples, handling as a special case. if not index.length transition.attributes ?= {} transition.attributes.examples = 0 return # Iterating over requests and responses in the index, keeping track of in # which block we currently are (block of requests: 'req', block # of responses: 'res'). In case there's change 'res' -> 'req', we raise # the example number. The example number is then attached to every # transaction as a Refract attribute 'example'. The total number of examples # gets attached to the transition as a Refract attribute 'examples'. example = 1 state = 'req' for {type, transaction} in index if type is 'httpRequest' example += 1 if state is 'res' state = 'req' else # 'httpResponse' state = 'res' transaction.attributes ?= {} transaction.attributes.example = example transition.attributes ?= {} transition.attributes.examples = example return # 'in situ' function # Provides index of requests and responses within given *transition*, sorted by # their position in the original API Blueprint document (from first to last). # # [ # { # 'type': 'httpResponse', # 'transaction': {'element': 'httpTransaction', ...}, # 'position': 85, # }, # ... # ] # # ## Index Entry (object) # # - type: httpRequest, httpResponse (enum) # - transaction (object) - Parent transaction element. # - position (number) - Position of the first character relevant to # the request (or response) within the original API Blueprint document. createIndex = (transition) -> mapping = {} traversal = traverse(transition) traversal.forEach((node) -> # Process just sourceMap elements. return unless node?.element is 'sourceMap' # Ignore sourceMap elements for request's HTTP method. Method is # often on a different place in the document than the actual # request is, so it's sourceMap is misleading for our purpose. return if 'method' in @path # Iterate over parents of the source map element and find # corresponding request (or response) and transaction elements. # # Key is a string representing one request or response in the index. # It is a path of the request (or response), concatenated by dots. key = null entry = {} for i in [0..@path.length] path = @path[0..i] parentNode = traversal.get(path) switch parentNode.element when 'httpRequest', 'httpResponse' key = path.join('.') entry.type = parentNode.element when 'httpTransaction' entry.transaction = parentNode # Process just sourceMap elements inside requests and responses. # # If we were not able to determine all necessary information (e.g. because # given source map isn't inside request or response, but somewhere else # in the transition's Refract tree), ignore the node. return unless key and entry.type and entry.transaction # Take positions of the first character for each continuous code block # in the source map. # # At the end we'll take the lowest number from the array as # a representation of the beginning of the whole request (or response) # within the original document. positions = (charBlock[0] for charBlock in node.content) if mapping[key] # If entry for given request (or response) already exists, add # also its current position to the array. This allows us to take the # lowest number among all source maps for given request (or response). positions.push(mapping[key].position) else # If the entry isn't in the mapping yet, create a new one. mapping[key] ?= entry # Now set the lowest position from all positions found for # the request (or response). This way at the end of this traversal # the 'position' attribute should contain position of the first # character relevant for the whole request (or response). mapping[key].position = Math.min.apply(null, positions) return # needed for 'traverse' to work properly in CoffeeScript ) # Turn the mapping into an index, i.e. an array sorted by position. index = (entry for own key, entry of mapping) index.sort((entry1, entry2) -> entry1.position - entry2.position) return index module.exports = detectTransactionExamples
111100
traverse = require('traverse') detectTransactionExamples = (transition) -> # Index of requests and responses within given *transition*, sorted by # their position in the original API Blueprint document. index = createIndex(transition) # No transaction examples, handling as a special case. if not index.length transition.attributes ?= {} transition.attributes.examples = 0 return # Iterating over requests and responses in the index, keeping track of in # which block we currently are (block of requests: 'req', block # of responses: 'res'). In case there's change 'res' -> 'req', we raise # the example number. The example number is then attached to every # transaction as a Refract attribute 'example'. The total number of examples # gets attached to the transition as a Refract attribute 'examples'. example = 1 state = 'req' for {type, transaction} in index if type is 'httpRequest' example += 1 if state is 'res' state = 'req' else # 'httpResponse' state = 'res' transaction.attributes ?= {} transaction.attributes.example = example transition.attributes ?= {} transition.attributes.examples = example return # 'in situ' function # Provides index of requests and responses within given *transition*, sorted by # their position in the original API Blueprint document (from first to last). # # [ # { # 'type': 'httpResponse', # 'transaction': {'element': 'httpTransaction', ...}, # 'position': 85, # }, # ... # ] # # ## Index Entry (object) # # - type: httpRequest, httpResponse (enum) # - transaction (object) - Parent transaction element. # - position (number) - Position of the first character relevant to # the request (or response) within the original API Blueprint document. createIndex = (transition) -> mapping = {} traversal = traverse(transition) traversal.forEach((node) -> # Process just sourceMap elements. return unless node?.element is 'sourceMap' # Ignore sourceMap elements for request's HTTP method. Method is # often on a different place in the document than the actual # request is, so it's sourceMap is misleading for our purpose. return if 'method' in @path # Iterate over parents of the source map element and find # corresponding request (or response) and transaction elements. # # Key is a string representing one request or response in the index. # It is a path of the request (or response), concatenated by dots. key = <KEY> entry = {} for i in [0..@path.length] path = @path[0..i] parentNode = traversal.get(path) switch parentNode.element when 'httpRequest', 'httpResponse' key = path.join('.') entry.type = parentNode.element when 'httpTransaction' entry.transaction = parentNode # Process just sourceMap elements inside requests and responses. # # If we were not able to determine all necessary information (e.g. because # given source map isn't inside request or response, but somewhere else # in the transition's Refract tree), ignore the node. return unless key and entry.type and entry.transaction # Take positions of the first character for each continuous code block # in the source map. # # At the end we'll take the lowest number from the array as # a representation of the beginning of the whole request (or response) # within the original document. positions = (charBlock[0] for charBlock in node.content) if mapping[key] # If entry for given request (or response) already exists, add # also its current position to the array. This allows us to take the # lowest number among all source maps for given request (or response). positions.push(mapping[key].position) else # If the entry isn't in the mapping yet, create a new one. mapping[key] ?= entry # Now set the lowest position from all positions found for # the request (or response). This way at the end of this traversal # the 'position' attribute should contain position of the first # character relevant for the whole request (or response). mapping[key].position = Math.min.apply(null, positions) return # needed for 'traverse' to work properly in CoffeeScript ) # Turn the mapping into an index, i.e. an array sorted by position. index = (entry for own key, entry of mapping) index.sort((entry1, entry2) -> entry1.position - entry2.position) return index module.exports = detectTransactionExamples
true
traverse = require('traverse') detectTransactionExamples = (transition) -> # Index of requests and responses within given *transition*, sorted by # their position in the original API Blueprint document. index = createIndex(transition) # No transaction examples, handling as a special case. if not index.length transition.attributes ?= {} transition.attributes.examples = 0 return # Iterating over requests and responses in the index, keeping track of in # which block we currently are (block of requests: 'req', block # of responses: 'res'). In case there's change 'res' -> 'req', we raise # the example number. The example number is then attached to every # transaction as a Refract attribute 'example'. The total number of examples # gets attached to the transition as a Refract attribute 'examples'. example = 1 state = 'req' for {type, transaction} in index if type is 'httpRequest' example += 1 if state is 'res' state = 'req' else # 'httpResponse' state = 'res' transaction.attributes ?= {} transaction.attributes.example = example transition.attributes ?= {} transition.attributes.examples = example return # 'in situ' function # Provides index of requests and responses within given *transition*, sorted by # their position in the original API Blueprint document (from first to last). # # [ # { # 'type': 'httpResponse', # 'transaction': {'element': 'httpTransaction', ...}, # 'position': 85, # }, # ... # ] # # ## Index Entry (object) # # - type: httpRequest, httpResponse (enum) # - transaction (object) - Parent transaction element. # - position (number) - Position of the first character relevant to # the request (or response) within the original API Blueprint document. createIndex = (transition) -> mapping = {} traversal = traverse(transition) traversal.forEach((node) -> # Process just sourceMap elements. return unless node?.element is 'sourceMap' # Ignore sourceMap elements for request's HTTP method. Method is # often on a different place in the document than the actual # request is, so it's sourceMap is misleading for our purpose. return if 'method' in @path # Iterate over parents of the source map element and find # corresponding request (or response) and transaction elements. # # Key is a string representing one request or response in the index. # It is a path of the request (or response), concatenated by dots. key = PI:KEY:<KEY>END_PI entry = {} for i in [0..@path.length] path = @path[0..i] parentNode = traversal.get(path) switch parentNode.element when 'httpRequest', 'httpResponse' key = path.join('.') entry.type = parentNode.element when 'httpTransaction' entry.transaction = parentNode # Process just sourceMap elements inside requests and responses. # # If we were not able to determine all necessary information (e.g. because # given source map isn't inside request or response, but somewhere else # in the transition's Refract tree), ignore the node. return unless key and entry.type and entry.transaction # Take positions of the first character for each continuous code block # in the source map. # # At the end we'll take the lowest number from the array as # a representation of the beginning of the whole request (or response) # within the original document. positions = (charBlock[0] for charBlock in node.content) if mapping[key] # If entry for given request (or response) already exists, add # also its current position to the array. This allows us to take the # lowest number among all source maps for given request (or response). positions.push(mapping[key].position) else # If the entry isn't in the mapping yet, create a new one. mapping[key] ?= entry # Now set the lowest position from all positions found for # the request (or response). This way at the end of this traversal # the 'position' attribute should contain position of the first # character relevant for the whole request (or response). mapping[key].position = Math.min.apply(null, positions) return # needed for 'traverse' to work properly in CoffeeScript ) # Turn the mapping into an index, i.e. an array sorted by position. index = (entry for own key, entry of mapping) index.sort((entry1, entry2) -> entry1.position - entry2.position) return index module.exports = detectTransactionExamples
[ { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri", "end": 42, "score": 0.9998443126678467, "start": 24, "tag": "NAME", "value": "Alexander Cherniuk" }, { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistribution and use in ", "end": 60, "score": 0.9999300837516785, "start": 44, "tag": "EMAIL", "value": "ts33kr@gmail.com" } ]
library/nucleus/scanner.coffee
ts33kr/granite
6
### Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" chokidar = require "chokidar" asciify = require "asciify" connect = require "connect" logger = require "winston" colors = require "colors" assert = require "assert" async = require "async" nconf = require "nconf" paths = require "path" https = require "https" http = require "http" util = require "util" fs = require "fs" {Zombie} = require "./zombie" {Archetype} = require "./arche" # The module scanner is a brand new module scanning facility. Is # built on top of the service architecture and itself is a zombie. # It takes care of scanning the supplied directories for new modules. # When new modules are discobered, the toolkit scans a module content # to see if there are any service to be attached. The toolkit is also # taking care of monitoring when a module changes and handling that. module.exports.ModuleScanner = class ModuleScanner extends Zombie # This defines the set of filename extensions that this service # should interpret as valid system modules, and therefore do the # fully fledged procssing of those. That is, require the module # when it is discovered, scan for available services there and # continue monitoring the module to see when there are changes. # Default values will be processing JavaScript and CoffeeScript. @MODULE_EXTENSIONS: [".js", ".coffee"] # This method is being fired off once some directory changes. # When that happens, this mehod will see if all the approriate # conditions are met, and if so - invoke the instance rebooting # sequence. It will also ensure that if there are multiple (lot) # of changes at once, nothing bad happens and a reboot sequence # will be upheld and properly executed, if configured to do so. directoryChanged: (path) -> assert located = "Changes located at %s".cyan msg = "Going to reboot the kernel in %s millisec" reason = "Rebooting the kernel due to the changes" forever = "not launched under Forever environment" assert relative = paths.relative process.cwd(), path return no unless reboot = nconf.get "scanner:reboot" return no if (reboot is false) or (reboot is null) assert _.isNumber(reboot), "reboot should be an int" refuse = (w) -> logger.warn "Cease rebooting: %s", w return refuse forever unless (try nconf.get "forever") return yes unless _.isEmpty @rebooting or undefined timer = (millisec, fnx) -> setTimeout fnx, millisec logger.warn msg.toString().red, reboot or undefined logger.warn located, relative.toString().underline killer = (exp) => @kernel.shutdownKernel exp, false return @rebooting = timer reboot, => killer reason send = => hst.emit arguments... for hst in hosting assert try _.all hosting = [this, @kernel] or null return send "directory-changed", this, path # This method is being fired off once a new module discovered. # When that happens, this method will fire up all a necessary # routine. This involves loading the module, if it has not been # loaded yet, bailing out if an error happens during that one. # If everything is okay, the method then transfers control to # the routine the internal routine - `extractServiceObjects`. candidateDiscovered: (path) -> fail = "could not resolve to the absolute path" assert current = process.cwd(), "a CWD get fail" assert modules = @constructor.MODULE_EXTENSIONS assert absolute = fs.realpathSync(path) or fail assert extension = paths.extname absolute or null return false unless extension in (modules or []) assert resolved = require.resolve absolute or null return false if resolved is require.main.filename addition = "Discover module at %s".cyan.toString() assert relative = r = paths.relative current, path logger.info addition, relative.underline.toString() handle = (err) -> logger.error fail.red, err.stack try require resolved catch error then handle error ss = this.extractServiceObjects(resolved) or null send = => hst.emit arguments... for hst in hosting assert try _.all hosting = [this, @kernel] or null return send "candidate-discovered", this, path # Once a module has been discovered, resolved and successfully # loaded, this routine is being involved on it. What it does is # it scans the `exports` namespace in the module and then checks # every single value there if it is a module that can be loaded. # Such module are ebery subclasses of `Service` that are final. # Meaning not abstract or otherwise marked as not for loading. extractServiceObjects: (resolved) -> cacheErr = "could not find discovery in a cache" assert service = require "./service" # no cycles assert cached = require.cache[resolved], cacheErr assert queue = try this.allocateOperationsQueue() assert exports = (cached or {}).exports or Object() assert exports = _.values(exports) or new Array() proto = (sv) -> _.isObject(sv) and sv.prototype servc = (sv) -> try sv.derives service.Service typed = (sv) -> return proto(sv) and servc(sv) final = (sv) -> typed(sv) and not sv.abstract() notmk = (sv) -> not sv.STOP_AUTO_DISCOVERY or 0 assert services = _.filter exports or [], final assert services = _.filter services or [], notmk assert services = _.unique(services or Array()) service.origin = cached for service in services queue.push _.map(services, (s) -> service: s) send = => h.emit arguments... for h in hosting assert try _.all hosting = [this, @kernel] or 0 send "extr-services", this, resolved, services return services.length or 0 # services found # Obtain an operations queue of this scanner instance. This queue # is responsible for processing either a service registration or # a service unregistration. The queueing mechanism is necessary in # order to make sure of correct sequencing of all the operations. # It aids is avoiding the race conditions during modules changes. # Consult with the `queue` member of the `async` packing/module. allocateOperationsQueue: -> return this.queue if _.isObject this.queue identify = @constructor.identify().underline assert _.isObject router = this.kernel.router assert register = router.register.bind router assert unregister = router.unregister.bind router missingOperation = "specify an operation to exec" collides = "use either register or unregister op" created = "Create seuquence operation queue at %s" try logger.debug created.yellow, identify.toString() patch = (q) => q.drain = (=> this.emit "drain", q); q sequential = (fn) => patch @queue = async.queue fn, 1 throttle = (fn) -> _.debounce fn, 50 # 50 millisecs return sequential throttle (operation, callback) => acknowledge = -> return callback.apply this applicate = (inp) -> register inp, acknowledge opService = try operation.service or undefined opDestroy = try operation.destroy or undefined assert opService or opDestroy, missingOperation assert not (opService and opDestroy), collides opService.spawn @kernel, applicate if opService unregister opDestroy, acknowledge if opDestroy # Register the supplied directory to be monitored by the module # scanner. The directory will be automatically resolved in the # relation to the current working directory (CWD) of a process. # New modules will be discovered off this directory. When the # directory changes, the scanner will reboot the kernel, if # it is configured this way. Please reference source coding. monitorDirectory: (directory) -> notString = "the directory is not a valud string" notExists = "Dir %s does not exist, no monitoring" chokidarOff = "the Chokidar library malfunctions" monitoring = "Monitoring %s directory for modules" assert _.isString(directory or null), notString exists = fs.existsSync directory.toString() or 0 relative = paths.relative process.cwd(), directory assert _.isFunction esync = fs.realpathSync or 0 return if abs = esync(relative) in @tracks ?= [] this.tracks.push abs unless abs in @tracks ?= [] formats = [notExists.red, relative.underline] return try logger.warn formats... unless exists logger.info monitoring.blue, relative.underline assert _.isFunction chokidar.watch, chokidarOff send = => h.emit arguments... for h in hosting assert try _.all hosting = [this, @kernel] or 0 assert monitor = chokidar.watch directory or 0 monitor.on "unlink", @directoryChanged.bind @ monitor.on "change", @directoryChanged.bind @ monitor.on "add", @candidateDiscovered.bind @ send "monitor-dir", this, directory, monitor
108294
### Copyright (c) 2013, <NAME> <<EMAIL>> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" chokidar = require "chokidar" asciify = require "asciify" connect = require "connect" logger = require "winston" colors = require "colors" assert = require "assert" async = require "async" nconf = require "nconf" paths = require "path" https = require "https" http = require "http" util = require "util" fs = require "fs" {Zombie} = require "./zombie" {Archetype} = require "./arche" # The module scanner is a brand new module scanning facility. Is # built on top of the service architecture and itself is a zombie. # It takes care of scanning the supplied directories for new modules. # When new modules are discobered, the toolkit scans a module content # to see if there are any service to be attached. The toolkit is also # taking care of monitoring when a module changes and handling that. module.exports.ModuleScanner = class ModuleScanner extends Zombie # This defines the set of filename extensions that this service # should interpret as valid system modules, and therefore do the # fully fledged procssing of those. That is, require the module # when it is discovered, scan for available services there and # continue monitoring the module to see when there are changes. # Default values will be processing JavaScript and CoffeeScript. @MODULE_EXTENSIONS: [".js", ".coffee"] # This method is being fired off once some directory changes. # When that happens, this mehod will see if all the approriate # conditions are met, and if so - invoke the instance rebooting # sequence. It will also ensure that if there are multiple (lot) # of changes at once, nothing bad happens and a reboot sequence # will be upheld and properly executed, if configured to do so. directoryChanged: (path) -> assert located = "Changes located at %s".cyan msg = "Going to reboot the kernel in %s millisec" reason = "Rebooting the kernel due to the changes" forever = "not launched under Forever environment" assert relative = paths.relative process.cwd(), path return no unless reboot = nconf.get "scanner:reboot" return no if (reboot is false) or (reboot is null) assert _.isNumber(reboot), "reboot should be an int" refuse = (w) -> logger.warn "Cease rebooting: %s", w return refuse forever unless (try nconf.get "forever") return yes unless _.isEmpty @rebooting or undefined timer = (millisec, fnx) -> setTimeout fnx, millisec logger.warn msg.toString().red, reboot or undefined logger.warn located, relative.toString().underline killer = (exp) => @kernel.shutdownKernel exp, false return @rebooting = timer reboot, => killer reason send = => hst.emit arguments... for hst in hosting assert try _.all hosting = [this, @kernel] or null return send "directory-changed", this, path # This method is being fired off once a new module discovered. # When that happens, this method will fire up all a necessary # routine. This involves loading the module, if it has not been # loaded yet, bailing out if an error happens during that one. # If everything is okay, the method then transfers control to # the routine the internal routine - `extractServiceObjects`. candidateDiscovered: (path) -> fail = "could not resolve to the absolute path" assert current = process.cwd(), "a CWD get fail" assert modules = @constructor.MODULE_EXTENSIONS assert absolute = fs.realpathSync(path) or fail assert extension = paths.extname absolute or null return false unless extension in (modules or []) assert resolved = require.resolve absolute or null return false if resolved is require.main.filename addition = "Discover module at %s".cyan.toString() assert relative = r = paths.relative current, path logger.info addition, relative.underline.toString() handle = (err) -> logger.error fail.red, err.stack try require resolved catch error then handle error ss = this.extractServiceObjects(resolved) or null send = => hst.emit arguments... for hst in hosting assert try _.all hosting = [this, @kernel] or null return send "candidate-discovered", this, path # Once a module has been discovered, resolved and successfully # loaded, this routine is being involved on it. What it does is # it scans the `exports` namespace in the module and then checks # every single value there if it is a module that can be loaded. # Such module are ebery subclasses of `Service` that are final. # Meaning not abstract or otherwise marked as not for loading. extractServiceObjects: (resolved) -> cacheErr = "could not find discovery in a cache" assert service = require "./service" # no cycles assert cached = require.cache[resolved], cacheErr assert queue = try this.allocateOperationsQueue() assert exports = (cached or {}).exports or Object() assert exports = _.values(exports) or new Array() proto = (sv) -> _.isObject(sv) and sv.prototype servc = (sv) -> try sv.derives service.Service typed = (sv) -> return proto(sv) and servc(sv) final = (sv) -> typed(sv) and not sv.abstract() notmk = (sv) -> not sv.STOP_AUTO_DISCOVERY or 0 assert services = _.filter exports or [], final assert services = _.filter services or [], notmk assert services = _.unique(services or Array()) service.origin = cached for service in services queue.push _.map(services, (s) -> service: s) send = => h.emit arguments... for h in hosting assert try _.all hosting = [this, @kernel] or 0 send "extr-services", this, resolved, services return services.length or 0 # services found # Obtain an operations queue of this scanner instance. This queue # is responsible for processing either a service registration or # a service unregistration. The queueing mechanism is necessary in # order to make sure of correct sequencing of all the operations. # It aids is avoiding the race conditions during modules changes. # Consult with the `queue` member of the `async` packing/module. allocateOperationsQueue: -> return this.queue if _.isObject this.queue identify = @constructor.identify().underline assert _.isObject router = this.kernel.router assert register = router.register.bind router assert unregister = router.unregister.bind router missingOperation = "specify an operation to exec" collides = "use either register or unregister op" created = "Create seuquence operation queue at %s" try logger.debug created.yellow, identify.toString() patch = (q) => q.drain = (=> this.emit "drain", q); q sequential = (fn) => patch @queue = async.queue fn, 1 throttle = (fn) -> _.debounce fn, 50 # 50 millisecs return sequential throttle (operation, callback) => acknowledge = -> return callback.apply this applicate = (inp) -> register inp, acknowledge opService = try operation.service or undefined opDestroy = try operation.destroy or undefined assert opService or opDestroy, missingOperation assert not (opService and opDestroy), collides opService.spawn @kernel, applicate if opService unregister opDestroy, acknowledge if opDestroy # Register the supplied directory to be monitored by the module # scanner. The directory will be automatically resolved in the # relation to the current working directory (CWD) of a process. # New modules will be discovered off this directory. When the # directory changes, the scanner will reboot the kernel, if # it is configured this way. Please reference source coding. monitorDirectory: (directory) -> notString = "the directory is not a valud string" notExists = "Dir %s does not exist, no monitoring" chokidarOff = "the Chokidar library malfunctions" monitoring = "Monitoring %s directory for modules" assert _.isString(directory or null), notString exists = fs.existsSync directory.toString() or 0 relative = paths.relative process.cwd(), directory assert _.isFunction esync = fs.realpathSync or 0 return if abs = esync(relative) in @tracks ?= [] this.tracks.push abs unless abs in @tracks ?= [] formats = [notExists.red, relative.underline] return try logger.warn formats... unless exists logger.info monitoring.blue, relative.underline assert _.isFunction chokidar.watch, chokidarOff send = => h.emit arguments... for h in hosting assert try _.all hosting = [this, @kernel] or 0 assert monitor = chokidar.watch directory or 0 monitor.on "unlink", @directoryChanged.bind @ monitor.on "change", @directoryChanged.bind @ monitor.on "add", @candidateDiscovered.bind @ send "monitor-dir", this, directory, monitor
true
### Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" chokidar = require "chokidar" asciify = require "asciify" connect = require "connect" logger = require "winston" colors = require "colors" assert = require "assert" async = require "async" nconf = require "nconf" paths = require "path" https = require "https" http = require "http" util = require "util" fs = require "fs" {Zombie} = require "./zombie" {Archetype} = require "./arche" # The module scanner is a brand new module scanning facility. Is # built on top of the service architecture and itself is a zombie. # It takes care of scanning the supplied directories for new modules. # When new modules are discobered, the toolkit scans a module content # to see if there are any service to be attached. The toolkit is also # taking care of monitoring when a module changes and handling that. module.exports.ModuleScanner = class ModuleScanner extends Zombie # This defines the set of filename extensions that this service # should interpret as valid system modules, and therefore do the # fully fledged procssing of those. That is, require the module # when it is discovered, scan for available services there and # continue monitoring the module to see when there are changes. # Default values will be processing JavaScript and CoffeeScript. @MODULE_EXTENSIONS: [".js", ".coffee"] # This method is being fired off once some directory changes. # When that happens, this mehod will see if all the approriate # conditions are met, and if so - invoke the instance rebooting # sequence. It will also ensure that if there are multiple (lot) # of changes at once, nothing bad happens and a reboot sequence # will be upheld and properly executed, if configured to do so. directoryChanged: (path) -> assert located = "Changes located at %s".cyan msg = "Going to reboot the kernel in %s millisec" reason = "Rebooting the kernel due to the changes" forever = "not launched under Forever environment" assert relative = paths.relative process.cwd(), path return no unless reboot = nconf.get "scanner:reboot" return no if (reboot is false) or (reboot is null) assert _.isNumber(reboot), "reboot should be an int" refuse = (w) -> logger.warn "Cease rebooting: %s", w return refuse forever unless (try nconf.get "forever") return yes unless _.isEmpty @rebooting or undefined timer = (millisec, fnx) -> setTimeout fnx, millisec logger.warn msg.toString().red, reboot or undefined logger.warn located, relative.toString().underline killer = (exp) => @kernel.shutdownKernel exp, false return @rebooting = timer reboot, => killer reason send = => hst.emit arguments... for hst in hosting assert try _.all hosting = [this, @kernel] or null return send "directory-changed", this, path # This method is being fired off once a new module discovered. # When that happens, this method will fire up all a necessary # routine. This involves loading the module, if it has not been # loaded yet, bailing out if an error happens during that one. # If everything is okay, the method then transfers control to # the routine the internal routine - `extractServiceObjects`. candidateDiscovered: (path) -> fail = "could not resolve to the absolute path" assert current = process.cwd(), "a CWD get fail" assert modules = @constructor.MODULE_EXTENSIONS assert absolute = fs.realpathSync(path) or fail assert extension = paths.extname absolute or null return false unless extension in (modules or []) assert resolved = require.resolve absolute or null return false if resolved is require.main.filename addition = "Discover module at %s".cyan.toString() assert relative = r = paths.relative current, path logger.info addition, relative.underline.toString() handle = (err) -> logger.error fail.red, err.stack try require resolved catch error then handle error ss = this.extractServiceObjects(resolved) or null send = => hst.emit arguments... for hst in hosting assert try _.all hosting = [this, @kernel] or null return send "candidate-discovered", this, path # Once a module has been discovered, resolved and successfully # loaded, this routine is being involved on it. What it does is # it scans the `exports` namespace in the module and then checks # every single value there if it is a module that can be loaded. # Such module are ebery subclasses of `Service` that are final. # Meaning not abstract or otherwise marked as not for loading. extractServiceObjects: (resolved) -> cacheErr = "could not find discovery in a cache" assert service = require "./service" # no cycles assert cached = require.cache[resolved], cacheErr assert queue = try this.allocateOperationsQueue() assert exports = (cached or {}).exports or Object() assert exports = _.values(exports) or new Array() proto = (sv) -> _.isObject(sv) and sv.prototype servc = (sv) -> try sv.derives service.Service typed = (sv) -> return proto(sv) and servc(sv) final = (sv) -> typed(sv) and not sv.abstract() notmk = (sv) -> not sv.STOP_AUTO_DISCOVERY or 0 assert services = _.filter exports or [], final assert services = _.filter services or [], notmk assert services = _.unique(services or Array()) service.origin = cached for service in services queue.push _.map(services, (s) -> service: s) send = => h.emit arguments... for h in hosting assert try _.all hosting = [this, @kernel] or 0 send "extr-services", this, resolved, services return services.length or 0 # services found # Obtain an operations queue of this scanner instance. This queue # is responsible for processing either a service registration or # a service unregistration. The queueing mechanism is necessary in # order to make sure of correct sequencing of all the operations. # It aids is avoiding the race conditions during modules changes. # Consult with the `queue` member of the `async` packing/module. allocateOperationsQueue: -> return this.queue if _.isObject this.queue identify = @constructor.identify().underline assert _.isObject router = this.kernel.router assert register = router.register.bind router assert unregister = router.unregister.bind router missingOperation = "specify an operation to exec" collides = "use either register or unregister op" created = "Create seuquence operation queue at %s" try logger.debug created.yellow, identify.toString() patch = (q) => q.drain = (=> this.emit "drain", q); q sequential = (fn) => patch @queue = async.queue fn, 1 throttle = (fn) -> _.debounce fn, 50 # 50 millisecs return sequential throttle (operation, callback) => acknowledge = -> return callback.apply this applicate = (inp) -> register inp, acknowledge opService = try operation.service or undefined opDestroy = try operation.destroy or undefined assert opService or opDestroy, missingOperation assert not (opService and opDestroy), collides opService.spawn @kernel, applicate if opService unregister opDestroy, acknowledge if opDestroy # Register the supplied directory to be monitored by the module # scanner. The directory will be automatically resolved in the # relation to the current working directory (CWD) of a process. # New modules will be discovered off this directory. When the # directory changes, the scanner will reboot the kernel, if # it is configured this way. Please reference source coding. monitorDirectory: (directory) -> notString = "the directory is not a valud string" notExists = "Dir %s does not exist, no monitoring" chokidarOff = "the Chokidar library malfunctions" monitoring = "Monitoring %s directory for modules" assert _.isString(directory or null), notString exists = fs.existsSync directory.toString() or 0 relative = paths.relative process.cwd(), directory assert _.isFunction esync = fs.realpathSync or 0 return if abs = esync(relative) in @tracks ?= [] this.tracks.push abs unless abs in @tracks ?= [] formats = [notExists.red, relative.underline] return try logger.warn formats... unless exists logger.info monitoring.blue, relative.underline assert _.isFunction chokidar.watch, chokidarOff send = => h.emit arguments... for h in hosting assert try _.all hosting = [this, @kernel] or 0 assert monitor = chokidar.watch directory or 0 monitor.on "unlink", @directoryChanged.bind @ monitor.on "change", @directoryChanged.bind @ monitor.on "add", @candidateDiscovered.bind @ send "monitor-dir", this, directory, monitor
[ { "context": "sername : API_KEY\n password : 'thisdoesntmatter'\n sendImmediately : false\n form ", "end": 411, "score": 0.9993555545806885, "start": 395, "tag": "PASSWORD", "value": "thisdoesntmatter" } ]
servers/lib/server/handlers/wufooproxy.coffee
lionheart1022/koding
0
request = require 'request' { wufoo } = require 'koding-config-manager' API_KEY = wufoo module.exports = (req, res, next) -> { identifier } = req.params formURI = "https://koding.wufoo.com/api/v3/forms/#{identifier}/entries.json" request uri : formURI method : 'POST' auth : username : API_KEY password : 'thisdoesntmatter' sendImmediately : false form : req.body , (err, response, body) -> return res.status(500).send 'an error occured' if err or not body try body = JSON.parse body catch e return res.status(500).send 'an error occured' { Success, ErrorText, FieldErrors, RedirectUrl } = body return res.status(400).send { ErrorText, FieldErrors } unless Success return res.status(200).send { Success, RedirectUrl }
164025
request = require 'request' { wufoo } = require 'koding-config-manager' API_KEY = wufoo module.exports = (req, res, next) -> { identifier } = req.params formURI = "https://koding.wufoo.com/api/v3/forms/#{identifier}/entries.json" request uri : formURI method : 'POST' auth : username : API_KEY password : '<PASSWORD>' sendImmediately : false form : req.body , (err, response, body) -> return res.status(500).send 'an error occured' if err or not body try body = JSON.parse body catch e return res.status(500).send 'an error occured' { Success, ErrorText, FieldErrors, RedirectUrl } = body return res.status(400).send { ErrorText, FieldErrors } unless Success return res.status(200).send { Success, RedirectUrl }
true
request = require 'request' { wufoo } = require 'koding-config-manager' API_KEY = wufoo module.exports = (req, res, next) -> { identifier } = req.params formURI = "https://koding.wufoo.com/api/v3/forms/#{identifier}/entries.json" request uri : formURI method : 'POST' auth : username : API_KEY password : 'PI:PASSWORD:<PASSWORD>END_PI' sendImmediately : false form : req.body , (err, response, body) -> return res.status(500).send 'an error occured' if err or not body try body = JSON.parse body catch e return res.status(500).send 'an error occured' { Success, ErrorText, FieldErrors, RedirectUrl } = body return res.status(400).send { ErrorText, FieldErrors } unless Success return res.status(200).send { Success, RedirectUrl }
[ { "context": "ng went wrong. Please contact our <a href=\"mailto:support@swarmcorp.com\">support team</a>.'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\toption.co", "end": 4448, "score": 0.9999232888221741, "start": 4427, "tag": "EMAIL", "value": "support@swarmcorp.com" } ]
js/directives/sidebar/da-sidebar-voting.coffee
SwarmCorp/razzledazzle
0
window.app.directive 'daSidebarVoting', ($modal, Wallet, User, Voting, Counterparty) -> restrict: 'A' templateUrl: 'partials/app/blocks/sidebar-voting.html' replace: true link: (scope) -> bitcore = require 'bitcore' scope.secredAccepted = false || window.daDebug?.votingSecretAccepted scope.voting = null scope.$watch (-> User.info), (newValue) -> scope.userInfo = User.info if newValue.loaded scope.$watch (-> User.info.privateKey), (newValue) -> scope.secredAccepted = User.info.privateKey if newValue scope.$watch (-> scope.secredAccepted), (newValue) -> if newValue Voting.getVotings() .then (votings) -> scope.votings = votings .then null, ()-> scope.votings = null scope.loading = false scope.checkSecret = -> secretField = scope.form.secret.accessSecret secret = secretField.$viewValue || '' if secret.indexOf(' ') >= 0 publicKey = Wallet.fromPassphrase(secret)?.public privateKeyWIF = Wallet.fromPassphrase(secret)?.private else if secret.length == 52 then privateKey = bitcore.PrivateKey.fromWIF secret publicKey = privateKey?.toAddress().toString() privateKeyWIF = secret if publicKey secretField.$setValidity 'incorrect', true if publicKey != User.info.wallet secretField.$setValidity 'incorrect', false secretField.errorMessage = 'Private key or passphrase is correct, but isn\'t paired with current user account. Please contact support.' else angular.extend User.info, {privateKey: privateKeyWIF} else secretField.$setValidity 'incorrect', false secretField.customError = true secretField.errorMessage = 'Invalid private key or passphrase.' scope.backToVotes = -> scope.voting = null scope.selectVoting = (voting) -> scope.loading = true multipleOptions = voting.multiple inviteesLength = -> size = 0 for id, invitee of voting.invitees size++ return size asset = voting.asset votingOptions = voting.options do checkOptions = -> votedOptions = 0 scope.$watch (-> (multipleOptions == 1 && voting.invitees[User.info.id].voted) || votedOptions >= multipleOptions), (newValue)-> if newValue voting.votingDone = true else voting.votingDone = false for option of votingOptions if votingOptions[option].votes?[User.info.id] voting.options[option].voted = true votedOptions++ Voting.getVotesCount option, asset, true .then (data) -> if data.balance if multipleOptions > 1 percent = (data.balance * 100 ) / ( multipleOptions * inviteesLength() ) votingOptions[data.address].votesCount = Math.round(percent*100)/100 else percent = data.balance / inviteesLength() * 100 votingOptions[data.address].votesCount = Math.round(percent*100)/100 else votingOptions[data.address].votesCount = 0 if (multipleOptions == 1 && voting.invitees[User.info.id].voted) || votedOptions >= multipleOptions voting.votingDone = true scope.title = voting.title scope.voting = voting scope.loading = false else User.getAsset voting.asset .then (balance)-> scope.title = voting.title scope.voting = voting scope.canVote = balance > 0 scope.loading = false .then null, ()-> scope.canVote = false scope.loading = false voting.$watch (newValue)-> checkOptions() if newValue scope.vote = (option) -> return false if option.voted || scope.voting.votingDone if option.confirmVote scope.loading = true # Mark user as voted even before transaction is made to prevent 'double vote' UI bug Voting.markUserAsVoted User.info.id, scope.voting.$id new Counterparty(User.info.privateKey).sendAsset { destination: option.address asset: scope.voting.asset quantity: 1 } .then -> Voting.markOptionAsVoted User.info.id, scope.voting.$id, option.address .then ()-> Voting.markUserAsVoted User.info.id, scope.voting.$id .then ()-> scope.selectVoting(scope.voting) scope.loading = false .then null, ()-> Voting.markUserAsNotVoted User.info.id, scope.voting.$id $modal.open templateUrl: 'partials/app/modal/notification.html', controller: 'modalNotificationController', resolve: { notificationData: -> { text: 'Something went wrong. Please contact our <a href="mailto:support@swarmcorp.com">support team</a>.' } } option.confirmVote = false option.voted = true else votingOptions = scope.voting.options for votingOption of votingOptions votingOptions[votingOption].confirmVote = false option.confirmVote = true scope.toggleOptionAddress = (option) -> option.addressVisible = !option.addressVisible
119899
window.app.directive 'daSidebarVoting', ($modal, Wallet, User, Voting, Counterparty) -> restrict: 'A' templateUrl: 'partials/app/blocks/sidebar-voting.html' replace: true link: (scope) -> bitcore = require 'bitcore' scope.secredAccepted = false || window.daDebug?.votingSecretAccepted scope.voting = null scope.$watch (-> User.info), (newValue) -> scope.userInfo = User.info if newValue.loaded scope.$watch (-> User.info.privateKey), (newValue) -> scope.secredAccepted = User.info.privateKey if newValue scope.$watch (-> scope.secredAccepted), (newValue) -> if newValue Voting.getVotings() .then (votings) -> scope.votings = votings .then null, ()-> scope.votings = null scope.loading = false scope.checkSecret = -> secretField = scope.form.secret.accessSecret secret = secretField.$viewValue || '' if secret.indexOf(' ') >= 0 publicKey = Wallet.fromPassphrase(secret)?.public privateKeyWIF = Wallet.fromPassphrase(secret)?.private else if secret.length == 52 then privateKey = bitcore.PrivateKey.fromWIF secret publicKey = privateKey?.toAddress().toString() privateKeyWIF = secret if publicKey secretField.$setValidity 'incorrect', true if publicKey != User.info.wallet secretField.$setValidity 'incorrect', false secretField.errorMessage = 'Private key or passphrase is correct, but isn\'t paired with current user account. Please contact support.' else angular.extend User.info, {privateKey: privateKeyWIF} else secretField.$setValidity 'incorrect', false secretField.customError = true secretField.errorMessage = 'Invalid private key or passphrase.' scope.backToVotes = -> scope.voting = null scope.selectVoting = (voting) -> scope.loading = true multipleOptions = voting.multiple inviteesLength = -> size = 0 for id, invitee of voting.invitees size++ return size asset = voting.asset votingOptions = voting.options do checkOptions = -> votedOptions = 0 scope.$watch (-> (multipleOptions == 1 && voting.invitees[User.info.id].voted) || votedOptions >= multipleOptions), (newValue)-> if newValue voting.votingDone = true else voting.votingDone = false for option of votingOptions if votingOptions[option].votes?[User.info.id] voting.options[option].voted = true votedOptions++ Voting.getVotesCount option, asset, true .then (data) -> if data.balance if multipleOptions > 1 percent = (data.balance * 100 ) / ( multipleOptions * inviteesLength() ) votingOptions[data.address].votesCount = Math.round(percent*100)/100 else percent = data.balance / inviteesLength() * 100 votingOptions[data.address].votesCount = Math.round(percent*100)/100 else votingOptions[data.address].votesCount = 0 if (multipleOptions == 1 && voting.invitees[User.info.id].voted) || votedOptions >= multipleOptions voting.votingDone = true scope.title = voting.title scope.voting = voting scope.loading = false else User.getAsset voting.asset .then (balance)-> scope.title = voting.title scope.voting = voting scope.canVote = balance > 0 scope.loading = false .then null, ()-> scope.canVote = false scope.loading = false voting.$watch (newValue)-> checkOptions() if newValue scope.vote = (option) -> return false if option.voted || scope.voting.votingDone if option.confirmVote scope.loading = true # Mark user as voted even before transaction is made to prevent 'double vote' UI bug Voting.markUserAsVoted User.info.id, scope.voting.$id new Counterparty(User.info.privateKey).sendAsset { destination: option.address asset: scope.voting.asset quantity: 1 } .then -> Voting.markOptionAsVoted User.info.id, scope.voting.$id, option.address .then ()-> Voting.markUserAsVoted User.info.id, scope.voting.$id .then ()-> scope.selectVoting(scope.voting) scope.loading = false .then null, ()-> Voting.markUserAsNotVoted User.info.id, scope.voting.$id $modal.open templateUrl: 'partials/app/modal/notification.html', controller: 'modalNotificationController', resolve: { notificationData: -> { text: 'Something went wrong. Please contact our <a href="mailto:<EMAIL>">support team</a>.' } } option.confirmVote = false option.voted = true else votingOptions = scope.voting.options for votingOption of votingOptions votingOptions[votingOption].confirmVote = false option.confirmVote = true scope.toggleOptionAddress = (option) -> option.addressVisible = !option.addressVisible
true
window.app.directive 'daSidebarVoting', ($modal, Wallet, User, Voting, Counterparty) -> restrict: 'A' templateUrl: 'partials/app/blocks/sidebar-voting.html' replace: true link: (scope) -> bitcore = require 'bitcore' scope.secredAccepted = false || window.daDebug?.votingSecretAccepted scope.voting = null scope.$watch (-> User.info), (newValue) -> scope.userInfo = User.info if newValue.loaded scope.$watch (-> User.info.privateKey), (newValue) -> scope.secredAccepted = User.info.privateKey if newValue scope.$watch (-> scope.secredAccepted), (newValue) -> if newValue Voting.getVotings() .then (votings) -> scope.votings = votings .then null, ()-> scope.votings = null scope.loading = false scope.checkSecret = -> secretField = scope.form.secret.accessSecret secret = secretField.$viewValue || '' if secret.indexOf(' ') >= 0 publicKey = Wallet.fromPassphrase(secret)?.public privateKeyWIF = Wallet.fromPassphrase(secret)?.private else if secret.length == 52 then privateKey = bitcore.PrivateKey.fromWIF secret publicKey = privateKey?.toAddress().toString() privateKeyWIF = secret if publicKey secretField.$setValidity 'incorrect', true if publicKey != User.info.wallet secretField.$setValidity 'incorrect', false secretField.errorMessage = 'Private key or passphrase is correct, but isn\'t paired with current user account. Please contact support.' else angular.extend User.info, {privateKey: privateKeyWIF} else secretField.$setValidity 'incorrect', false secretField.customError = true secretField.errorMessage = 'Invalid private key or passphrase.' scope.backToVotes = -> scope.voting = null scope.selectVoting = (voting) -> scope.loading = true multipleOptions = voting.multiple inviteesLength = -> size = 0 for id, invitee of voting.invitees size++ return size asset = voting.asset votingOptions = voting.options do checkOptions = -> votedOptions = 0 scope.$watch (-> (multipleOptions == 1 && voting.invitees[User.info.id].voted) || votedOptions >= multipleOptions), (newValue)-> if newValue voting.votingDone = true else voting.votingDone = false for option of votingOptions if votingOptions[option].votes?[User.info.id] voting.options[option].voted = true votedOptions++ Voting.getVotesCount option, asset, true .then (data) -> if data.balance if multipleOptions > 1 percent = (data.balance * 100 ) / ( multipleOptions * inviteesLength() ) votingOptions[data.address].votesCount = Math.round(percent*100)/100 else percent = data.balance / inviteesLength() * 100 votingOptions[data.address].votesCount = Math.round(percent*100)/100 else votingOptions[data.address].votesCount = 0 if (multipleOptions == 1 && voting.invitees[User.info.id].voted) || votedOptions >= multipleOptions voting.votingDone = true scope.title = voting.title scope.voting = voting scope.loading = false else User.getAsset voting.asset .then (balance)-> scope.title = voting.title scope.voting = voting scope.canVote = balance > 0 scope.loading = false .then null, ()-> scope.canVote = false scope.loading = false voting.$watch (newValue)-> checkOptions() if newValue scope.vote = (option) -> return false if option.voted || scope.voting.votingDone if option.confirmVote scope.loading = true # Mark user as voted even before transaction is made to prevent 'double vote' UI bug Voting.markUserAsVoted User.info.id, scope.voting.$id new Counterparty(User.info.privateKey).sendAsset { destination: option.address asset: scope.voting.asset quantity: 1 } .then -> Voting.markOptionAsVoted User.info.id, scope.voting.$id, option.address .then ()-> Voting.markUserAsVoted User.info.id, scope.voting.$id .then ()-> scope.selectVoting(scope.voting) scope.loading = false .then null, ()-> Voting.markUserAsNotVoted User.info.id, scope.voting.$id $modal.open templateUrl: 'partials/app/modal/notification.html', controller: 'modalNotificationController', resolve: { notificationData: -> { text: 'Something went wrong. Please contact our <a href="mailto:PI:EMAIL:<EMAIL>END_PI">support team</a>.' } } option.confirmVote = false option.voted = true else votingOptions = scope.voting.options for votingOption of votingOptions votingOptions[votingOption].confirmVote = false option.confirmVote = true scope.toggleOptionAddress = (option) -> option.addressVisible = !option.addressVisible