entities
listlengths
1
8.61k
max_stars_repo_path
stringlengths
7
172
max_stars_repo_name
stringlengths
5
89
max_stars_count
int64
0
82k
content
stringlengths
14
1.05M
id
stringlengths
2
6
new_content
stringlengths
15
1.05M
modified
bool
1 class
references
stringlengths
29
1.05M
[ { "context": "るとエラー\", ->\n process.env.REDIS_URL = 'redis://127.0.0.1:6379'\n process.env.SALESFORCE_CLIENT_ID = 'A", "end": 1039, "score": 0.999587893486023, "start": 1030, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "AA'\n process.env.SALESFORCE_CLIENT...
test/index.coffee
co-meeting/botdock-helper
0
chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' expect = chai.expect chai.use sinonChai BotDockHelper = require '../src/index' fixture = require './fixture' jsforce = require 'jsforce' describe "botdock-helper", -> beforeEach -> # join時のレスポンス @JOIN_RESPONSE = fixture.join_response() # 通常のテキスト投稿のレスポンス @TEXT_RESPONSE = fixture.text_response() @robot = fixture.robot() afterEach -> # 環境変数を削除 REQUIRED_ENVS = [ 'REDIS_URL' 'SALESFORCE_CLIENT_ID' 'SALESFORCE_CLIENT_SECRET' 'SALESFORCE_REDIRECT_URI' 'SALESFORCE_ORG_ID' ] for env in REQUIRED_ENVS delete process.env[env] describe "コンストラクタ", -> it "環境変数が設定されていないとエラー", -> constructor = -> new BotDockHelper(@robot) expect(constructor).to.throw 'REDIS_URL, SALESFORCE_CLIENT_ID, SALESFORCE_CLIENT_SECRET, SALESFORCE_REDIRECT_URI, SALESFORCE_ORG_ID must be specified.' it "環境変数が不足しているとエラー", -> process.env.REDIS_URL = 'redis://127.0.0.1:6379' process.env.SALESFORCE_CLIENT_ID = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' process.env.SALESFORCE_CLIENT_SECRET = '11111111110000' constructor = -> new BotDockHelper(@robot) expect(constructor).to.throw 'SALESFORCE_REDIRECT_URI, SALESFORCE_ORG_ID must be specified.' it "環境変数が設定されているとエラーにならない", -> process.env.REDIS_URL = 'redis://127.0.0.1:6379' process.env.SALESFORCE_CLIENT_ID = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' process.env.SALESFORCE_CLIENT_SECRET = '11111111110000' process.env.SALESFORCE_REDIRECT_URI = 'http://localhost:8888' process.env.SALESFORCE_ORG_ID = '*' constructor = -> new BotDockHelper(@robot) expect(constructor).not.to.throw /.*/ describe "インスタンスメソッド", -> beforeEach -> process.env.REDIS_URL = 'redis://127.0.0.1:6379' process.env.SALESFORCE_CLIENT_ID = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' process.env.SALESFORCE_CLIENT_SECRET = '11111111110000' process.env.SALESFORCE_REDIRECT_URI = 'http://localhost:8888' process.env.SALESFORCE_ORG_ID = '*' @botdock = new BotDockHelper(@robot) describe "_generateSessionId" , -> it "33文字のランダムな文字列が生成される", -> id1 = @botdock._generateSessionId() id2 = @botdock._generateSessionId() expect(id1.length).to.eq 33 expect(id2.length).to.eq 33 expect(id1).to.not.eq id2 describe "_getUserIdOnJoin", -> it "joinメッセージのときuserIdが取得できる", -> expect(@botdock._getUserIdOnJoin(@JOIN_RESPONSE)).to.eq '_11111111_-1111111111' describe "_getDomainId", -> it "ドメインIDが取得できる", -> expect(@botdock._getDomainId(@JOIN_RESPONSE)).to.eq '_12345678_12345678' expect(@botdock._getDomainId(@TEXT_RESPONSE)).to.eq '_12345678_12345678' describe "_getRobotId", -> it "BotのユーザIDが取得できる", -> expect(@botdock._getRobotId()).to.eq '_99999999_-9999999999' describe "_findDB", -> beforeEach -> @botdock.client = connected: true multi: -> select: -> get: -> exec: -> @client = @botdock.client sinon.stub(@client, 'multi').returns(@client) sinon.stub(@client, 'select').returns(@client) sinon.stub(@client, 'get').returns(@client) it "キャッシュ済みだったらそのDBインデックスを返す", -> @botdock.redisDBMap['_12345678_12345678'] = 3 @botdock._findDB(@TEXT_RESPONSE).then (result) -> expect(result).to.eq 3 it "DBインデックスが1000以上だったらエラーになる", -> @botdock._findDB(@TEXT_RESPONSE, 1000) .then (result) -> expect(true).to.be.false .catch (err) -> expect(true).to.be.true it "Redisがダウン中はその旨のメッセージを表示", -> @botdock.client.connected = false @botdock._findDB(@TEXT_RESPONSE) .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eql {code:"REDIS_DOWN", message:"Redis is down."} expect(@TEXT_RESPONSE.send).to.have.been.calledWith " 現在メンテナンス中です。大変ご不便をおかけいたしますが、今しばらくお待ちください。" it "Redisの処理でエラーが起きると、rejectする", -> sinon.stub @client, 'exec', (callback) -> callback 'error!', {} @botdock._findDB(@TEXT_RESPONSE) .then (result) -> expect(true).to.be.false .catch (err) -> expect(err).to.eq 'error!' it "初回アクセスで該当する組織IDが取得できると1を返す", -> sinon.stub @client, 'exec', (callback) -> callback false, [1, '_12345678_12345678'] @botdock._findDB(@TEXT_RESPONSE) .then (result) -> expect(result).to.eq 1 .catch (err) -> expect(true).to.be.false it "3回目のアクセスで該当する組織IDが取得できると3を返す", -> execStub = sinon.stub() sinon.stub @client, 'exec', (callback) -> callback false, execStub() execStub.onCall(0).returns [1, 'xxxxx'] execStub.onCall(1).returns [1, 'xxxxx'] execStub.returns [1, '_12345678_12345678'] @botdock._findDB(@TEXT_RESPONSE) .then (result) -> expect(result).to.eq 3 .catch (err) -> expect(true).to.be.false describe "sendAuthorizationUrl", -> beforeEach -> @botdock._findDB = sinon.stub().returns(Promise.resolve(3)) @botdock.client0 = connected: true multi: -> hmset: -> expire: -> exec: -> @client0 = @botdock.client0 sinon.stub(@client0, 'multi').returns(@client0) sinon.stub(@client0, 'hmset').returns(@client0) sinon.stub(@client0, 'expire').returns(@client0) it "resにユーザIDが含まれていない場合エラー", -> delete @TEXT_RESPONSE.message.user.id @botdock.sendAuthorizationUrl(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith "不正な操作です。" it "グループトークの場合にログインできない旨のメッセージを表示", -> @TEXT_RESPONSE.message.roomType = 2 @botdock.sendAuthorizationUrl(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith "#{@TEXT_RESPONSE.message.user.name}さん\n まだSalesforceへの認証ができていないため、ご利用いただけません。\n まずペアトークで私に話しかけて認証をしてからご利用ください。" it "Redisがダウン中はその旨のメッセージを表示", -> @botdock.client0.connected = false @botdock.sendAuthorizationUrl(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith " 現在メンテナンス中です。大変ご不便をおかけいたしますが、今しばらくお待ちください。" it "Redisへ正しいデータを保存すること", -> @botdock._generateSessionId = sinon.stub().returns('abcdefg') @botdock.sendAuthorizationUrl(@TEXT_RESPONSE).then => expect(@client0.hmset).to.have.been.calledWithMatch 'abcdefg', { userId: '_11111111_-1111111111' db: 3 orgId: '_12345678_12345678' sfOrgId: '*' } it "Redisへの保存処理が成功したら、ログインURLを表示", -> sinon.stub @client0, 'exec', (callback) -> callback false, [1, 1, 1] @oauth2 = @botdock.oauth2 sinon.stub(@oauth2, 'getAuthorizationUrl').returns('http://login.example.com/') @botdock.sendAuthorizationUrl(@TEXT_RESPONSE).then => expect(@TEXT_RESPONSE.send).to.have.been.calledWith " このBotを利用するには、Salesforceにログインする必要があります。\n 以下のURLからSalesforceにログインしてください。\n http://login.example.com/" it "Redisへの保存処理が失敗したら、その旨を表示", -> sinon.stub @client0, 'exec', (callback) -> callback 'error!', [1, 1, 1] @oauth2 = @botdock.oauth2 sinon.stub(@oauth2, 'getAuthorizationUrl').returns('http://login.example.com/') @botdock.sendAuthorizationUrl(@TEXT_RESPONSE).then => expect(@TEXT_RESPONSE.send).to.have.been.calledWith "ログインURLの生成に失敗しました。" describe "getJsforceConnection", -> beforeEach -> @botdock._findDB = sinon.stub().returns(Promise.resolve(3)) @botdock.client = connected: true multi: -> select: -> hgetall: -> exec: -> @client = @botdock.client sinon.stub(@client, 'multi').returns(@client) sinon.stub(@client, 'select').returns(@client) sinon.stub(@client, 'hgetall').returns(@client) it "resにユーザIDが含まれていない場合エラー", -> delete @TEXT_RESPONSE.message.user.id @botdock.getJsforceConnection(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith "不正な操作です。" it "Redisがダウン中はその旨のメッセージを表示", -> @botdock.client.connected = false @botdock.getJsforceConnection(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith " 現在メンテナンス中です。大変ご不便をおかけいたしますが、今しばらくお待ちください。" it "Redisへの保存処理が失敗したらreject", -> sinon.stub @client, 'exec', (callback) -> callback 'error!', [1, {}] @botdock.getJsforceConnection(@TEXT_RESPONSE) .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eq 'error!' it "OAuth情報が取得できなかったらreject", -> sinon.stub @client, 'exec', (callback) -> callback false, [1, null] @botdock.sendAuthorizationUrl = sinon.spy() @botdock.getJsforceConnection(@TEXT_RESPONSE) .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eql {code:"NO_AUTH", message:"認証していません"} expect(@botdock.sendAuthorizationUrl).to.have.been.calledWith @TEXT_RESPONSE it "OAuth情報が取得できたらjsforce.Connectionを返す", -> sinon.stub @client, 'exec', (callback) -> callback false, [ 1, { instanceUrl: 'http://ap.example.com' accessToken: 'ACCESS' refreshToken: 'REFRESH' } ] @botdock.getJsforceConnection(@TEXT_RESPONSE) .then (result) => expect(result).to.be.an.instanceof(jsforce.Connection) expect(result.instanceUrl).to.eq 'http://ap.example.com' expect(result.accessToken).to.eq 'ACCESS' expect(result.refreshToken).to.eq 'REFRESH' expect(result.oauth2).to.eq @botdock.oauth2 .catch (err) => expect(true).to.be.false describe "checkAuthenticationOnJoin", -> it "_getUserIdOnJoinで取得したユーザIDがgetJsConnectionに渡される", -> @botdock._getUserIdOnJoin = sinon.stub().returns('USERID') @botdock.getJsforceConnection = sinon.spy() @botdock.checkAuthenticationOnJoin(@TEXT_RESPONSE) expect(@botdock.getJsforceConnection).to.have.been.calledWithMatch @TEXT_RESPONSE, { userId: 'USERID' skipGroupTalkHelp:true } describe "logout", -> beforeEach -> @botdock._findDB = sinon.stub().returns(Promise.resolve(3)) @botdock.client = connected: true multi: -> select: -> del: -> exec: -> @client = @botdock.client sinon.stub(@client, 'multi').returns(@client) sinon.stub(@client, 'select').returns(@client) sinon.stub(@client, 'del').returns(@client) it "グループトークの場合にログインできない旨のメッセージを表示", -> @TEXT_RESPONSE.message.roomType = 2 @botdock.logout(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith "グループトークではログアウトできません。" it "resにユーザIDが含まれていない場合エラー", -> delete @TEXT_RESPONSE.message.user.id @botdock.logout(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith "不正な操作です。" it "Redisがダウン中はその旨のメッセージを表示", -> @botdock.client.connected = false @botdock.logout(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith " 現在メンテナンス中です。大変ご不便をおかけいたしますが、今しばらくお待ちください。" it "Redisの削除処理が失敗したらエラーを表示", -> sinon.stub @client, 'exec', (callback) -> callback 'error!', [1, 1] @botdock.logout(@TEXT_RESPONSE) .then (result) => expect(@TEXT_RESPONSE.send).to.have.been.calledWith "ログアウトに失敗しました。" .catch (err) => expect(true).to.be.false it "Redisの削除処理が成功したらログアウトした旨を表示", -> sinon.stub @client, 'exec', (callback) -> callback false, [1, 1] @botdock.getJsforceConnection = sinon.spy() @botdock.logout(@TEXT_RESPONSE) .then (result) => expect(@TEXT_RESPONSE.send).to.have.been.calledWith "ログアウトしました。" expect(@botdock.getJsforceConnection).to.have.been.calledWith @TEXT_RESPONSE .catch (err) => expect(true).to.be.false describe "setData", -> beforeEach -> @botdock._findDB = sinon.stub().returns(Promise.resolve(3)) @botdock.client = connected: true multi: -> select: -> hset: -> exec: -> @client = @botdock.client sinon.stub(@client, 'multi').returns(@client) sinon.stub(@client, 'select').returns(@client) sinon.stub(@client, 'hset').returns(@client) @data = a:1 arr: [1,2,3] hash: a: 1 b: 2 it "_findDBでエラーが起きると、rejectする", -> @botdock._findDB.returns(Promise.reject('error!')) @botdock.setData(@TEXT_RESPONSE, 'key1', @data) .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eq 'error!' it "Redisの処理でエラーが起きると、rejectする", -> sinon.stub @client, 'exec', (callback) => callback 'error!', [] @botdock.setData(@TEXT_RESPONSE, 'key1', @data) .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eq 'error!' it "途中でエラーが起きなかった場合、正しくhsetが呼ばれる", -> sinon.stub @client, 'exec', (callback) => callback false, [0, 1] @botdock.setData(@TEXT_RESPONSE, 'key1', @data) .then (result) => expect(result).to.eq 1 expect(@client.hset).to.have.been.calledWith '_99999999_-9999999999', 'key1', JSON.stringify(@data) .catch (err) => expect(true).to.be.false describe "getData", -> beforeEach -> @botdock._findDB = sinon.stub().returns(Promise.resolve(3)) @botdock.client = connected: true multi: -> select: -> hget: -> exec: -> @client = @botdock.client sinon.stub(@client, 'multi').returns(@client) sinon.stub(@client, 'select').returns(@client) sinon.stub(@client, 'hget').returns(@client) @data = a:1 arr: [1,2,3] hash: a: 1 b: 2 it "_findDBでエラーが起きると、rejectする", -> @botdock._findDB.returns(Promise.reject('error!')) @botdock.getData(@TEXT_RESPONSE, 'key1') .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eq 'error!' it "Redisの処理でエラーが起きると、rejectする", -> sinon.stub @client, 'exec', (callback) => callback 'error!', [] @botdock.getData(@TEXT_RESPONSE, 'key1') .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eq 'error!' it "途中でエラーが起きなかった場合、正しくhgetが呼ばれ、その結果を取得できる", -> sinon.stub @client, 'exec', (callback) => callback false, [0, JSON.stringify(@data)] @botdock.getData(@TEXT_RESPONSE, 'key1') .then (result) => expect(@client.hget).to.have.been.calledWith '_99999999_-9999999999', 'key1' expect(result).to.eql @data .catch (err) => expect(true).to.be.false it "hgetがnullを返した場合、nullを取得できる", -> sinon.stub @client, 'exec', (callback) => callback false, [0, null] @botdock.getData(@TEXT_RESPONSE, 'key1') .then (result) => expect(@client.hget).to.have.been.calledWith '_99999999_-9999999999', 'key1' expect(result).to.eq null .catch (err) => expect(true).to.be.false
152084
chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' expect = chai.expect chai.use sinonChai BotDockHelper = require '../src/index' fixture = require './fixture' jsforce = require 'jsforce' describe "botdock-helper", -> beforeEach -> # join時のレスポンス @JOIN_RESPONSE = fixture.join_response() # 通常のテキスト投稿のレスポンス @TEXT_RESPONSE = fixture.text_response() @robot = fixture.robot() afterEach -> # 環境変数を削除 REQUIRED_ENVS = [ 'REDIS_URL' 'SALESFORCE_CLIENT_ID' 'SALESFORCE_CLIENT_SECRET' 'SALESFORCE_REDIRECT_URI' 'SALESFORCE_ORG_ID' ] for env in REQUIRED_ENVS delete process.env[env] describe "コンストラクタ", -> it "環境変数が設定されていないとエラー", -> constructor = -> new BotDockHelper(@robot) expect(constructor).to.throw 'REDIS_URL, SALESFORCE_CLIENT_ID, SALESFORCE_CLIENT_SECRET, SALESFORCE_REDIRECT_URI, SALESFORCE_ORG_ID must be specified.' it "環境変数が不足しているとエラー", -> process.env.REDIS_URL = 'redis://127.0.0.1:6379' process.env.SALESFORCE_CLIENT_ID = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' process.env.SALESFORCE_CLIENT_SECRET = '<KEY>' constructor = -> new BotDockHelper(@robot) expect(constructor).to.throw 'SALESFORCE_REDIRECT_URI, SALESFORCE_ORG_ID must be specified.' it "環境変数が設定されているとエラーにならない", -> process.env.REDIS_URL = 'redis://127.0.0.1:6379' process.env.SALESFORCE_CLIENT_ID = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' process.env.SALESFORCE_CLIENT_SECRET = '<KEY>111111110000' process.env.SALESFORCE_REDIRECT_URI = 'http://localhost:8888' process.env.SALESFORCE_ORG_ID = '*' constructor = -> new BotDockHelper(@robot) expect(constructor).not.to.throw /.*/ describe "インスタンスメソッド", -> beforeEach -> process.env.REDIS_URL = 'redis://127.0.0.1:6379' process.env.SALESFORCE_CLIENT_ID = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' process.env.SALESFORCE_CLIENT_SECRET = '11111111110000' process.env.SALESFORCE_REDIRECT_URI = 'http://localhost:8888' process.env.SALESFORCE_ORG_ID = '*' @botdock = new BotDockHelper(@robot) describe "_generateSessionId" , -> it "33文字のランダムな文字列が生成される", -> id1 = @botdock._generateSessionId() id2 = @botdock._generateSessionId() expect(id1.length).to.eq 33 expect(id2.length).to.eq 33 expect(id1).to.not.eq id2 describe "_getUserIdOnJoin", -> it "joinメッセージのときuserIdが取得できる", -> expect(@botdock._getUserIdOnJoin(@JOIN_RESPONSE)).to.eq '_11111111_-1111111111' describe "_getDomainId", -> it "ドメインIDが取得できる", -> expect(@botdock._getDomainId(@JOIN_RESPONSE)).to.eq '_12345678_12345678' expect(@botdock._getDomainId(@TEXT_RESPONSE)).to.eq '_12345678_12345678' describe "_getRobotId", -> it "BotのユーザIDが取得できる", -> expect(@botdock._getRobotId()).to.eq '_99999999_-9999999999' describe "_findDB", -> beforeEach -> @botdock.client = connected: true multi: -> select: -> get: -> exec: -> @client = @botdock.client sinon.stub(@client, 'multi').returns(@client) sinon.stub(@client, 'select').returns(@client) sinon.stub(@client, 'get').returns(@client) it "キャッシュ済みだったらそのDBインデックスを返す", -> @botdock.redisDBMap['_12345678_12345678'] = 3 @botdock._findDB(@TEXT_RESPONSE).then (result) -> expect(result).to.eq 3 it "DBインデックスが1000以上だったらエラーになる", -> @botdock._findDB(@TEXT_RESPONSE, 1000) .then (result) -> expect(true).to.be.false .catch (err) -> expect(true).to.be.true it "Redisがダウン中はその旨のメッセージを表示", -> @botdock.client.connected = false @botdock._findDB(@TEXT_RESPONSE) .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eql {code:"REDIS_DOWN", message:"Redis is down."} expect(@TEXT_RESPONSE.send).to.have.been.calledWith " 現在メンテナンス中です。大変ご不便をおかけいたしますが、今しばらくお待ちください。" it "Redisの処理でエラーが起きると、rejectする", -> sinon.stub @client, 'exec', (callback) -> callback 'error!', {} @botdock._findDB(@TEXT_RESPONSE) .then (result) -> expect(true).to.be.false .catch (err) -> expect(err).to.eq 'error!' it "初回アクセスで該当する組織IDが取得できると1を返す", -> sinon.stub @client, 'exec', (callback) -> callback false, [1, '_12345678_12345678'] @botdock._findDB(@TEXT_RESPONSE) .then (result) -> expect(result).to.eq 1 .catch (err) -> expect(true).to.be.false it "3回目のアクセスで該当する組織IDが取得できると3を返す", -> execStub = sinon.stub() sinon.stub @client, 'exec', (callback) -> callback false, execStub() execStub.onCall(0).returns [1, 'xxxxx'] execStub.onCall(1).returns [1, 'xxxxx'] execStub.returns [1, '_12345678_12345678'] @botdock._findDB(@TEXT_RESPONSE) .then (result) -> expect(result).to.eq 3 .catch (err) -> expect(true).to.be.false describe "sendAuthorizationUrl", -> beforeEach -> @botdock._findDB = sinon.stub().returns(Promise.resolve(3)) @botdock.client0 = connected: true multi: -> hmset: -> expire: -> exec: -> @client0 = @botdock.client0 sinon.stub(@client0, 'multi').returns(@client0) sinon.stub(@client0, 'hmset').returns(@client0) sinon.stub(@client0, 'expire').returns(@client0) it "resにユーザIDが含まれていない場合エラー", -> delete @TEXT_RESPONSE.message.user.id @botdock.sendAuthorizationUrl(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith "不正な操作です。" it "グループトークの場合にログインできない旨のメッセージを表示", -> @TEXT_RESPONSE.message.roomType = 2 @botdock.sendAuthorizationUrl(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith "#{@TEXT_RESPONSE.message.user.name}さん\n まだSalesforceへの認証ができていないため、ご利用いただけません。\n まずペアトークで私に話しかけて認証をしてからご利用ください。" it "Redisがダウン中はその旨のメッセージを表示", -> @botdock.client0.connected = false @botdock.sendAuthorizationUrl(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith " 現在メンテナンス中です。大変ご不便をおかけいたしますが、今しばらくお待ちください。" it "Redisへ正しいデータを保存すること", -> @botdock._generateSessionId = sinon.stub().returns('abcdefg') @botdock.sendAuthorizationUrl(@TEXT_RESPONSE).then => expect(@client0.hmset).to.have.been.calledWithMatch 'abcdefg', { userId: '_11111111_-1111111111' db: 3 orgId: '_12345678_12345678' sfOrgId: '*' } it "Redisへの保存処理が成功したら、ログインURLを表示", -> sinon.stub @client0, 'exec', (callback) -> callback false, [1, 1, 1] @oauth2 = @botdock.oauth2 sinon.stub(@oauth2, 'getAuthorizationUrl').returns('http://login.example.com/') @botdock.sendAuthorizationUrl(@TEXT_RESPONSE).then => expect(@TEXT_RESPONSE.send).to.have.been.calledWith " このBotを利用するには、Salesforceにログインする必要があります。\n 以下のURLからSalesforceにログインしてください。\n http://login.example.com/" it "Redisへの保存処理が失敗したら、その旨を表示", -> sinon.stub @client0, 'exec', (callback) -> callback 'error!', [1, 1, 1] @oauth2 = @botdock.oauth2 sinon.stub(@oauth2, 'getAuthorizationUrl').returns('http://login.example.com/') @botdock.sendAuthorizationUrl(@TEXT_RESPONSE).then => expect(@TEXT_RESPONSE.send).to.have.been.calledWith "ログインURLの生成に失敗しました。" describe "getJsforceConnection", -> beforeEach -> @botdock._findDB = sinon.stub().returns(Promise.resolve(3)) @botdock.client = connected: true multi: -> select: -> hgetall: -> exec: -> @client = @botdock.client sinon.stub(@client, 'multi').returns(@client) sinon.stub(@client, 'select').returns(@client) sinon.stub(@client, 'hgetall').returns(@client) it "resにユーザIDが含まれていない場合エラー", -> delete @TEXT_RESPONSE.message.user.id @botdock.getJsforceConnection(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith "不正な操作です。" it "Redisがダウン中はその旨のメッセージを表示", -> @botdock.client.connected = false @botdock.getJsforceConnection(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith " 現在メンテナンス中です。大変ご不便をおかけいたしますが、今しばらくお待ちください。" it "Redisへの保存処理が失敗したらreject", -> sinon.stub @client, 'exec', (callback) -> callback 'error!', [1, {}] @botdock.getJsforceConnection(@TEXT_RESPONSE) .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eq 'error!' it "OAuth情報が取得できなかったらreject", -> sinon.stub @client, 'exec', (callback) -> callback false, [1, null] @botdock.sendAuthorizationUrl = sinon.spy() @botdock.getJsforceConnection(@TEXT_RESPONSE) .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eql {code:"NO_AUTH", message:"認証していません"} expect(@botdock.sendAuthorizationUrl).to.have.been.calledWith @TEXT_RESPONSE it "OAuth情報が取得できたらjsforce.Connectionを返す", -> sinon.stub @client, 'exec', (callback) -> callback false, [ 1, { instanceUrl: 'http://ap.example.com' accessToken: '<KEY>' refreshToken: '<KEY>' } ] @botdock.getJsforceConnection(@TEXT_RESPONSE) .then (result) => expect(result).to.be.an.instanceof(jsforce.Connection) expect(result.instanceUrl).to.eq 'http://ap.example.com' expect(result.accessToken).to.eq 'ACCESS' expect(result.refreshToken).to.eq '<KEY>' expect(result.oauth2).to.eq @botdock.oauth2 .catch (err) => expect(true).to.be.false describe "checkAuthenticationOnJoin", -> it "_getUserIdOnJoinで取得したユーザIDがgetJsConnectionに渡される", -> @botdock._getUserIdOnJoin = sinon.stub().returns('USERID') @botdock.getJsforceConnection = sinon.spy() @botdock.checkAuthenticationOnJoin(@TEXT_RESPONSE) expect(@botdock.getJsforceConnection).to.have.been.calledWithMatch @TEXT_RESPONSE, { userId: 'USERID' skipGroupTalkHelp:true } describe "logout", -> beforeEach -> @botdock._findDB = sinon.stub().returns(Promise.resolve(3)) @botdock.client = connected: true multi: -> select: -> del: -> exec: -> @client = @botdock.client sinon.stub(@client, 'multi').returns(@client) sinon.stub(@client, 'select').returns(@client) sinon.stub(@client, 'del').returns(@client) it "グループトークの場合にログインできない旨のメッセージを表示", -> @TEXT_RESPONSE.message.roomType = 2 @botdock.logout(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith "グループトークではログアウトできません。" it "resにユーザIDが含まれていない場合エラー", -> delete @TEXT_RESPONSE.message.user.id @botdock.logout(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith "不正な操作です。" it "Redisがダウン中はその旨のメッセージを表示", -> @botdock.client.connected = false @botdock.logout(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith " 現在メンテナンス中です。大変ご不便をおかけいたしますが、今しばらくお待ちください。" it "Redisの削除処理が失敗したらエラーを表示", -> sinon.stub @client, 'exec', (callback) -> callback 'error!', [1, 1] @botdock.logout(@TEXT_RESPONSE) .then (result) => expect(@TEXT_RESPONSE.send).to.have.been.calledWith "ログアウトに失敗しました。" .catch (err) => expect(true).to.be.false it "Redisの削除処理が成功したらログアウトした旨を表示", -> sinon.stub @client, 'exec', (callback) -> callback false, [1, 1] @botdock.getJsforceConnection = sinon.spy() @botdock.logout(@TEXT_RESPONSE) .then (result) => expect(@TEXT_RESPONSE.send).to.have.been.calledWith "ログアウトしました。" expect(@botdock.getJsforceConnection).to.have.been.calledWith @TEXT_RESPONSE .catch (err) => expect(true).to.be.false describe "setData", -> beforeEach -> @botdock._findDB = sinon.stub().returns(Promise.resolve(3)) @botdock.client = connected: true multi: -> select: -> hset: -> exec: -> @client = @botdock.client sinon.stub(@client, 'multi').returns(@client) sinon.stub(@client, 'select').returns(@client) sinon.stub(@client, 'hset').returns(@client) @data = a:1 arr: [1,2,3] hash: a: 1 b: 2 it "_findDBでエラーが起きると、rejectする", -> @botdock._findDB.returns(Promise.reject('error!')) @botdock.setData(@TEXT_RESPONSE, 'key1', @data) .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eq 'error!' it "Redisの処理でエラーが起きると、rejectする", -> sinon.stub @client, 'exec', (callback) => callback 'error!', [] @botdock.setData(@TEXT_RESPONSE, 'key1', @data) .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eq 'error!' it "途中でエラーが起きなかった場合、正しくhsetが呼ばれる", -> sinon.stub @client, 'exec', (callback) => callback false, [0, 1] @botdock.setData(@TEXT_RESPONSE, 'key1', @data) .then (result) => expect(result).to.eq 1 expect(@client.hset).to.have.been.calledWith '_99999999_-9999999999', 'key1', JSON.stringify(@data) .catch (err) => expect(true).to.be.false describe "getData", -> beforeEach -> @botdock._findDB = sinon.stub().returns(Promise.resolve(3)) @botdock.client = connected: true multi: -> select: -> hget: -> exec: -> @client = @botdock.client sinon.stub(@client, 'multi').returns(@client) sinon.stub(@client, 'select').returns(@client) sinon.stub(@client, 'hget').returns(@client) @data = a:1 arr: [1,2,3] hash: a: 1 b: 2 it "_findDBでエラーが起きると、rejectする", -> @botdock._findDB.returns(Promise.reject('error!')) @botdock.getData(@TEXT_RESPONSE, 'key1') .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eq 'error!' it "Redisの処理でエラーが起きると、rejectする", -> sinon.stub @client, 'exec', (callback) => callback 'error!', [] @botdock.getData(@TEXT_RESPONSE, 'key1') .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eq 'error!' it "途中でエラーが起きなかった場合、正しくhgetが呼ばれ、その結果を取得できる", -> sinon.stub @client, 'exec', (callback) => callback false, [0, JSON.stringify(@data)] @botdock.getData(@TEXT_RESPONSE, 'key1') .then (result) => expect(@client.hget).to.have.been.calledWith '_99999999_-9999999999', 'key1' expect(result).to.eql @data .catch (err) => expect(true).to.be.false it "hgetがnullを返した場合、nullを取得できる", -> sinon.stub @client, 'exec', (callback) => callback false, [0, null] @botdock.getData(@TEXT_RESPONSE, 'key1') .then (result) => expect(@client.hget).to.have.been.calledWith '_99999999_-9999999999', 'key1' expect(result).to.eq null .catch (err) => expect(true).to.be.false
true
chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' expect = chai.expect chai.use sinonChai BotDockHelper = require '../src/index' fixture = require './fixture' jsforce = require 'jsforce' describe "botdock-helper", -> beforeEach -> # join時のレスポンス @JOIN_RESPONSE = fixture.join_response() # 通常のテキスト投稿のレスポンス @TEXT_RESPONSE = fixture.text_response() @robot = fixture.robot() afterEach -> # 環境変数を削除 REQUIRED_ENVS = [ 'REDIS_URL' 'SALESFORCE_CLIENT_ID' 'SALESFORCE_CLIENT_SECRET' 'SALESFORCE_REDIRECT_URI' 'SALESFORCE_ORG_ID' ] for env in REQUIRED_ENVS delete process.env[env] describe "コンストラクタ", -> it "環境変数が設定されていないとエラー", -> constructor = -> new BotDockHelper(@robot) expect(constructor).to.throw 'REDIS_URL, SALESFORCE_CLIENT_ID, SALESFORCE_CLIENT_SECRET, SALESFORCE_REDIRECT_URI, SALESFORCE_ORG_ID must be specified.' it "環境変数が不足しているとエラー", -> process.env.REDIS_URL = 'redis://127.0.0.1:6379' process.env.SALESFORCE_CLIENT_ID = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' process.env.SALESFORCE_CLIENT_SECRET = 'PI:KEY:<KEY>END_PI' constructor = -> new BotDockHelper(@robot) expect(constructor).to.throw 'SALESFORCE_REDIRECT_URI, SALESFORCE_ORG_ID must be specified.' it "環境変数が設定されているとエラーにならない", -> process.env.REDIS_URL = 'redis://127.0.0.1:6379' process.env.SALESFORCE_CLIENT_ID = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' process.env.SALESFORCE_CLIENT_SECRET = 'PI:KEY:<KEY>END_PI111111110000' process.env.SALESFORCE_REDIRECT_URI = 'http://localhost:8888' process.env.SALESFORCE_ORG_ID = '*' constructor = -> new BotDockHelper(@robot) expect(constructor).not.to.throw /.*/ describe "インスタンスメソッド", -> beforeEach -> process.env.REDIS_URL = 'redis://127.0.0.1:6379' process.env.SALESFORCE_CLIENT_ID = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' process.env.SALESFORCE_CLIENT_SECRET = '11111111110000' process.env.SALESFORCE_REDIRECT_URI = 'http://localhost:8888' process.env.SALESFORCE_ORG_ID = '*' @botdock = new BotDockHelper(@robot) describe "_generateSessionId" , -> it "33文字のランダムな文字列が生成される", -> id1 = @botdock._generateSessionId() id2 = @botdock._generateSessionId() expect(id1.length).to.eq 33 expect(id2.length).to.eq 33 expect(id1).to.not.eq id2 describe "_getUserIdOnJoin", -> it "joinメッセージのときuserIdが取得できる", -> expect(@botdock._getUserIdOnJoin(@JOIN_RESPONSE)).to.eq '_11111111_-1111111111' describe "_getDomainId", -> it "ドメインIDが取得できる", -> expect(@botdock._getDomainId(@JOIN_RESPONSE)).to.eq '_12345678_12345678' expect(@botdock._getDomainId(@TEXT_RESPONSE)).to.eq '_12345678_12345678' describe "_getRobotId", -> it "BotのユーザIDが取得できる", -> expect(@botdock._getRobotId()).to.eq '_99999999_-9999999999' describe "_findDB", -> beforeEach -> @botdock.client = connected: true multi: -> select: -> get: -> exec: -> @client = @botdock.client sinon.stub(@client, 'multi').returns(@client) sinon.stub(@client, 'select').returns(@client) sinon.stub(@client, 'get').returns(@client) it "キャッシュ済みだったらそのDBインデックスを返す", -> @botdock.redisDBMap['_12345678_12345678'] = 3 @botdock._findDB(@TEXT_RESPONSE).then (result) -> expect(result).to.eq 3 it "DBインデックスが1000以上だったらエラーになる", -> @botdock._findDB(@TEXT_RESPONSE, 1000) .then (result) -> expect(true).to.be.false .catch (err) -> expect(true).to.be.true it "Redisがダウン中はその旨のメッセージを表示", -> @botdock.client.connected = false @botdock._findDB(@TEXT_RESPONSE) .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eql {code:"REDIS_DOWN", message:"Redis is down."} expect(@TEXT_RESPONSE.send).to.have.been.calledWith " 現在メンテナンス中です。大変ご不便をおかけいたしますが、今しばらくお待ちください。" it "Redisの処理でエラーが起きると、rejectする", -> sinon.stub @client, 'exec', (callback) -> callback 'error!', {} @botdock._findDB(@TEXT_RESPONSE) .then (result) -> expect(true).to.be.false .catch (err) -> expect(err).to.eq 'error!' it "初回アクセスで該当する組織IDが取得できると1を返す", -> sinon.stub @client, 'exec', (callback) -> callback false, [1, '_12345678_12345678'] @botdock._findDB(@TEXT_RESPONSE) .then (result) -> expect(result).to.eq 1 .catch (err) -> expect(true).to.be.false it "3回目のアクセスで該当する組織IDが取得できると3を返す", -> execStub = sinon.stub() sinon.stub @client, 'exec', (callback) -> callback false, execStub() execStub.onCall(0).returns [1, 'xxxxx'] execStub.onCall(1).returns [1, 'xxxxx'] execStub.returns [1, '_12345678_12345678'] @botdock._findDB(@TEXT_RESPONSE) .then (result) -> expect(result).to.eq 3 .catch (err) -> expect(true).to.be.false describe "sendAuthorizationUrl", -> beforeEach -> @botdock._findDB = sinon.stub().returns(Promise.resolve(3)) @botdock.client0 = connected: true multi: -> hmset: -> expire: -> exec: -> @client0 = @botdock.client0 sinon.stub(@client0, 'multi').returns(@client0) sinon.stub(@client0, 'hmset').returns(@client0) sinon.stub(@client0, 'expire').returns(@client0) it "resにユーザIDが含まれていない場合エラー", -> delete @TEXT_RESPONSE.message.user.id @botdock.sendAuthorizationUrl(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith "不正な操作です。" it "グループトークの場合にログインできない旨のメッセージを表示", -> @TEXT_RESPONSE.message.roomType = 2 @botdock.sendAuthorizationUrl(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith "#{@TEXT_RESPONSE.message.user.name}さん\n まだSalesforceへの認証ができていないため、ご利用いただけません。\n まずペアトークで私に話しかけて認証をしてからご利用ください。" it "Redisがダウン中はその旨のメッセージを表示", -> @botdock.client0.connected = false @botdock.sendAuthorizationUrl(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith " 現在メンテナンス中です。大変ご不便をおかけいたしますが、今しばらくお待ちください。" it "Redisへ正しいデータを保存すること", -> @botdock._generateSessionId = sinon.stub().returns('abcdefg') @botdock.sendAuthorizationUrl(@TEXT_RESPONSE).then => expect(@client0.hmset).to.have.been.calledWithMatch 'abcdefg', { userId: '_11111111_-1111111111' db: 3 orgId: '_12345678_12345678' sfOrgId: '*' } it "Redisへの保存処理が成功したら、ログインURLを表示", -> sinon.stub @client0, 'exec', (callback) -> callback false, [1, 1, 1] @oauth2 = @botdock.oauth2 sinon.stub(@oauth2, 'getAuthorizationUrl').returns('http://login.example.com/') @botdock.sendAuthorizationUrl(@TEXT_RESPONSE).then => expect(@TEXT_RESPONSE.send).to.have.been.calledWith " このBotを利用するには、Salesforceにログインする必要があります。\n 以下のURLからSalesforceにログインしてください。\n http://login.example.com/" it "Redisへの保存処理が失敗したら、その旨を表示", -> sinon.stub @client0, 'exec', (callback) -> callback 'error!', [1, 1, 1] @oauth2 = @botdock.oauth2 sinon.stub(@oauth2, 'getAuthorizationUrl').returns('http://login.example.com/') @botdock.sendAuthorizationUrl(@TEXT_RESPONSE).then => expect(@TEXT_RESPONSE.send).to.have.been.calledWith "ログインURLの生成に失敗しました。" describe "getJsforceConnection", -> beforeEach -> @botdock._findDB = sinon.stub().returns(Promise.resolve(3)) @botdock.client = connected: true multi: -> select: -> hgetall: -> exec: -> @client = @botdock.client sinon.stub(@client, 'multi').returns(@client) sinon.stub(@client, 'select').returns(@client) sinon.stub(@client, 'hgetall').returns(@client) it "resにユーザIDが含まれていない場合エラー", -> delete @TEXT_RESPONSE.message.user.id @botdock.getJsforceConnection(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith "不正な操作です。" it "Redisがダウン中はその旨のメッセージを表示", -> @botdock.client.connected = false @botdock.getJsforceConnection(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith " 現在メンテナンス中です。大変ご不便をおかけいたしますが、今しばらくお待ちください。" it "Redisへの保存処理が失敗したらreject", -> sinon.stub @client, 'exec', (callback) -> callback 'error!', [1, {}] @botdock.getJsforceConnection(@TEXT_RESPONSE) .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eq 'error!' it "OAuth情報が取得できなかったらreject", -> sinon.stub @client, 'exec', (callback) -> callback false, [1, null] @botdock.sendAuthorizationUrl = sinon.spy() @botdock.getJsforceConnection(@TEXT_RESPONSE) .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eql {code:"NO_AUTH", message:"認証していません"} expect(@botdock.sendAuthorizationUrl).to.have.been.calledWith @TEXT_RESPONSE it "OAuth情報が取得できたらjsforce.Connectionを返す", -> sinon.stub @client, 'exec', (callback) -> callback false, [ 1, { instanceUrl: 'http://ap.example.com' accessToken: 'PI:KEY:<KEY>END_PI' refreshToken: 'PI:KEY:<KEY>END_PI' } ] @botdock.getJsforceConnection(@TEXT_RESPONSE) .then (result) => expect(result).to.be.an.instanceof(jsforce.Connection) expect(result.instanceUrl).to.eq 'http://ap.example.com' expect(result.accessToken).to.eq 'ACCESS' expect(result.refreshToken).to.eq 'PI:KEY:<KEY>END_PI' expect(result.oauth2).to.eq @botdock.oauth2 .catch (err) => expect(true).to.be.false describe "checkAuthenticationOnJoin", -> it "_getUserIdOnJoinで取得したユーザIDがgetJsConnectionに渡される", -> @botdock._getUserIdOnJoin = sinon.stub().returns('USERID') @botdock.getJsforceConnection = sinon.spy() @botdock.checkAuthenticationOnJoin(@TEXT_RESPONSE) expect(@botdock.getJsforceConnection).to.have.been.calledWithMatch @TEXT_RESPONSE, { userId: 'USERID' skipGroupTalkHelp:true } describe "logout", -> beforeEach -> @botdock._findDB = sinon.stub().returns(Promise.resolve(3)) @botdock.client = connected: true multi: -> select: -> del: -> exec: -> @client = @botdock.client sinon.stub(@client, 'multi').returns(@client) sinon.stub(@client, 'select').returns(@client) sinon.stub(@client, 'del').returns(@client) it "グループトークの場合にログインできない旨のメッセージを表示", -> @TEXT_RESPONSE.message.roomType = 2 @botdock.logout(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith "グループトークではログアウトできません。" it "resにユーザIDが含まれていない場合エラー", -> delete @TEXT_RESPONSE.message.user.id @botdock.logout(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith "不正な操作です。" it "Redisがダウン中はその旨のメッセージを表示", -> @botdock.client.connected = false @botdock.logout(@TEXT_RESPONSE) expect(@TEXT_RESPONSE.send).to.have.been.calledWith " 現在メンテナンス中です。大変ご不便をおかけいたしますが、今しばらくお待ちください。" it "Redisの削除処理が失敗したらエラーを表示", -> sinon.stub @client, 'exec', (callback) -> callback 'error!', [1, 1] @botdock.logout(@TEXT_RESPONSE) .then (result) => expect(@TEXT_RESPONSE.send).to.have.been.calledWith "ログアウトに失敗しました。" .catch (err) => expect(true).to.be.false it "Redisの削除処理が成功したらログアウトした旨を表示", -> sinon.stub @client, 'exec', (callback) -> callback false, [1, 1] @botdock.getJsforceConnection = sinon.spy() @botdock.logout(@TEXT_RESPONSE) .then (result) => expect(@TEXT_RESPONSE.send).to.have.been.calledWith "ログアウトしました。" expect(@botdock.getJsforceConnection).to.have.been.calledWith @TEXT_RESPONSE .catch (err) => expect(true).to.be.false describe "setData", -> beforeEach -> @botdock._findDB = sinon.stub().returns(Promise.resolve(3)) @botdock.client = connected: true multi: -> select: -> hset: -> exec: -> @client = @botdock.client sinon.stub(@client, 'multi').returns(@client) sinon.stub(@client, 'select').returns(@client) sinon.stub(@client, 'hset').returns(@client) @data = a:1 arr: [1,2,3] hash: a: 1 b: 2 it "_findDBでエラーが起きると、rejectする", -> @botdock._findDB.returns(Promise.reject('error!')) @botdock.setData(@TEXT_RESPONSE, 'key1', @data) .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eq 'error!' it "Redisの処理でエラーが起きると、rejectする", -> sinon.stub @client, 'exec', (callback) => callback 'error!', [] @botdock.setData(@TEXT_RESPONSE, 'key1', @data) .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eq 'error!' it "途中でエラーが起きなかった場合、正しくhsetが呼ばれる", -> sinon.stub @client, 'exec', (callback) => callback false, [0, 1] @botdock.setData(@TEXT_RESPONSE, 'key1', @data) .then (result) => expect(result).to.eq 1 expect(@client.hset).to.have.been.calledWith '_99999999_-9999999999', 'key1', JSON.stringify(@data) .catch (err) => expect(true).to.be.false describe "getData", -> beforeEach -> @botdock._findDB = sinon.stub().returns(Promise.resolve(3)) @botdock.client = connected: true multi: -> select: -> hget: -> exec: -> @client = @botdock.client sinon.stub(@client, 'multi').returns(@client) sinon.stub(@client, 'select').returns(@client) sinon.stub(@client, 'hget').returns(@client) @data = a:1 arr: [1,2,3] hash: a: 1 b: 2 it "_findDBでエラーが起きると、rejectする", -> @botdock._findDB.returns(Promise.reject('error!')) @botdock.getData(@TEXT_RESPONSE, 'key1') .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eq 'error!' it "Redisの処理でエラーが起きると、rejectする", -> sinon.stub @client, 'exec', (callback) => callback 'error!', [] @botdock.getData(@TEXT_RESPONSE, 'key1') .then (result) => expect(true).to.be.false .catch (err) => expect(err).to.eq 'error!' it "途中でエラーが起きなかった場合、正しくhgetが呼ばれ、その結果を取得できる", -> sinon.stub @client, 'exec', (callback) => callback false, [0, JSON.stringify(@data)] @botdock.getData(@TEXT_RESPONSE, 'key1') .then (result) => expect(@client.hget).to.have.been.calledWith '_99999999_-9999999999', 'key1' expect(result).to.eql @data .catch (err) => expect(true).to.be.false it "hgetがnullを返した場合、nullを取得できる", -> sinon.stub @client, 'exec', (callback) => callback false, [0, null] @botdock.getData(@TEXT_RESPONSE, 'key1') .then (result) => expect(@client.hget).to.have.been.calledWith '_99999999_-9999999999', 'key1' expect(result).to.eq null .catch (err) => expect(true).to.be.false
[ { "context": " \"tmp_gpg.trustdb\"\n keys :\n merkle : [\n \"03E146CDAF8136680AD566912A32340CEC8C9492\"\n ]\n testing_keys :\n # for testing purpose", "end": 739, "score": 0.9922549724578857, "start": 699, "tag": "KEY", "value": "03E146CDAF8136680AD566912A32340CEC8C9492" },...
src/constants.iced
substack/keybase-client
1
exports.constants = constants = version : 1 api_version : "1.0" canonical_host : "keybase.io" client_name : "keybase.io node.js client" user_agent : main : "Keybase-CLI" details : "#{process.platform}; node.js #{process.versions.node}" server : host : "api.keybase.io" port : 443 no_tls : false filenames : config_dir : ".keybase" config_file : "config.json" session_file : "session.json" db_file : "keybase.idb" nedb_file : "keybase.nedb" tmp_keyring_dir : "tmp_keyrings" tmp_gpg : sec_keyring : "tmp_gpg.sec.keyring" pub_keyring : "tmp_gpg.pub.keyring" trustdb : "tmp_gpg.trustdb" keys : merkle : [ "03E146CDAF8136680AD566912A32340CEC8C9492" ] testing_keys : # for testing purposes, not needed in production merkle : [ "A05161510EE696601BA0EC7B3FD53B4871528CEF" ] loopback_port_range : [ 56000, 56100 ] security: pwh : derived_key_bytes : 32 openpgp : derived_key_bytes : 12 triplesec : version : 3 permissions : dir : 0o700 file : 0o600 lookups : username : 1 local_track : 2 key_id_64_to_user : 3 key_fingerprint_to_user : 4 merkle_root : 5 ids : sig_chain_link : "e0" local_track : "e1" merkle_root : "e2" import_state : NONE : 0 TEMPORARY : 1 FINAL : 2 CANCELED : 3 REMOVED : 4 proof_state : NONE : 0 OK : 1 TEMP_FAILURE : 2 PERM_FAILURE : 3 LOOKING : 4 SUPERSEDED : 5 POSTED : 6 REVOKED : 7 signature_types : NONE : 0 SELF_SIG : 1 REMOTE_PROOF : 2 TRACK : 3 UNTRACK : 4 REVOKE : 5 CRYPTOCURRENCY : 6 cryptocurrencies : bitcoin : 0 bitcoin_mutli : 5 allowed_cryptocurrency_types : [0,5] skip : NONE : 0 LOCAL : 1 REMOTE : 2 time : remote_proof_recheck_interval : 60 * 60 * 24 # check remote proofs every day keygen : expire : "10y" master : bits : 4096 subkey : bits : 4096 constants.server.api_uri_prefix = "/_/api/" + constants.api_version
152668
exports.constants = constants = version : 1 api_version : "1.0" canonical_host : "keybase.io" client_name : "keybase.io node.js client" user_agent : main : "Keybase-CLI" details : "#{process.platform}; node.js #{process.versions.node}" server : host : "api.keybase.io" port : 443 no_tls : false filenames : config_dir : ".keybase" config_file : "config.json" session_file : "session.json" db_file : "keybase.idb" nedb_file : "keybase.nedb" tmp_keyring_dir : "tmp_keyrings" tmp_gpg : sec_keyring : "tmp_gpg.sec.keyring" pub_keyring : "tmp_gpg.pub.keyring" trustdb : "tmp_gpg.trustdb" keys : merkle : [ "<KEY>" ] testing_keys : # for testing purposes, not needed in production merkle : [ "<KEY>" ] loopback_port_range : [ 56000, 56100 ] security: pwh : derived_key_bytes : 32 openpgp : derived_key_bytes : 12 triplesec : version : 3 permissions : dir : 0o700 file : 0o600 lookups : username : 1 local_track : 2 key_id_64_to_user : 3 key_fingerprint_to_user : 4 merkle_root : 5 ids : sig_chain_link : "e0" local_track : "e1" merkle_root : "e2" import_state : NONE : 0 TEMPORARY : 1 FINAL : 2 CANCELED : 3 REMOVED : 4 proof_state : NONE : 0 OK : 1 TEMP_FAILURE : 2 PERM_FAILURE : 3 LOOKING : 4 SUPERSEDED : 5 POSTED : 6 REVOKED : 7 signature_types : NONE : 0 SELF_SIG : 1 REMOTE_PROOF : 2 TRACK : 3 UNTRACK : 4 REVOKE : 5 CRYPTOCURRENCY : 6 cryptocurrencies : bitcoin : 0 bitcoin_mutli : 5 allowed_cryptocurrency_types : [0,5] skip : NONE : 0 LOCAL : 1 REMOTE : 2 time : remote_proof_recheck_interval : 60 * 60 * 24 # check remote proofs every day keygen : expire : "10y" master : bits : 4096 subkey : bits : 4096 constants.server.api_uri_prefix = "/_/api/" + constants.api_version
true
exports.constants = constants = version : 1 api_version : "1.0" canonical_host : "keybase.io" client_name : "keybase.io node.js client" user_agent : main : "Keybase-CLI" details : "#{process.platform}; node.js #{process.versions.node}" server : host : "api.keybase.io" port : 443 no_tls : false filenames : config_dir : ".keybase" config_file : "config.json" session_file : "session.json" db_file : "keybase.idb" nedb_file : "keybase.nedb" tmp_keyring_dir : "tmp_keyrings" tmp_gpg : sec_keyring : "tmp_gpg.sec.keyring" pub_keyring : "tmp_gpg.pub.keyring" trustdb : "tmp_gpg.trustdb" keys : merkle : [ "PI:KEY:<KEY>END_PI" ] testing_keys : # for testing purposes, not needed in production merkle : [ "PI:KEY:<KEY>END_PI" ] loopback_port_range : [ 56000, 56100 ] security: pwh : derived_key_bytes : 32 openpgp : derived_key_bytes : 12 triplesec : version : 3 permissions : dir : 0o700 file : 0o600 lookups : username : 1 local_track : 2 key_id_64_to_user : 3 key_fingerprint_to_user : 4 merkle_root : 5 ids : sig_chain_link : "e0" local_track : "e1" merkle_root : "e2" import_state : NONE : 0 TEMPORARY : 1 FINAL : 2 CANCELED : 3 REMOVED : 4 proof_state : NONE : 0 OK : 1 TEMP_FAILURE : 2 PERM_FAILURE : 3 LOOKING : 4 SUPERSEDED : 5 POSTED : 6 REVOKED : 7 signature_types : NONE : 0 SELF_SIG : 1 REMOTE_PROOF : 2 TRACK : 3 UNTRACK : 4 REVOKE : 5 CRYPTOCURRENCY : 6 cryptocurrencies : bitcoin : 0 bitcoin_mutli : 5 allowed_cryptocurrency_types : [0,5] skip : NONE : 0 LOCAL : 1 REMOTE : 2 time : remote_proof_recheck_interval : 60 * 60 * 24 # check remote proofs every day keygen : expire : "10y" master : bits : 4096 subkey : bits : 4096 constants.server.api_uri_prefix = "/_/api/" + constants.api_version
[ { "context": "s\n if c.id == id\n c.name = name\n equal = true\n break\n ", "end": 1933, "score": 0.9910433292388916, "start": 1929, "tag": "NAME", "value": "name" }, { "context": "ses.push(\n id: id\n name:...
src/coffee/moodle.coffee
regisfaria/original-dashboard
0
### # moodle: moodle data ### class Moodle constructor: (options) -> if options options = @parse(options) if typeof options == 'string' && options.length for key, value of options @[key] = value console.log('Moodle:', @) syncTitle: (response) -> $.ajax( url: @url success: (data) => parser = new DOMParser() doc = parser.parseFromString(data, 'text/html') @title = $($('*[class="tree_item branch"] *[title]', doc)[0]) .attr('title')?.trim() unless @title @title = $('title', doc).text()?.trim() response(Moodle.response().success) ) @ sync: (response) -> # default = /my, cafeead moodle = /disciplinas $.ajax( url: @url + '/disciplinas' type: 'HEAD' success: => @syncCourses(response, 'disciplinas') error: => @syncCourses(response) ) @ syncCourses: (response, path = 'my') -> $.ajax( url: @url + '/' + path data: mynumber: -2 success: (data) => parser = new DOMParser() doc = parser.parseFromString(data, 'text/html') courses = $('h2 > a[href*="course/view.php?id="]', doc) unless courses.length courses = $('h4 > a[href*="course/view.php?id="]', doc) unless courses.length courses = $('li > a[href*="course/view.php?id="]', doc) unless courses.length return response( Moodle.response().sync_no_courses, Moodle.response().sync_courses ) unless @courses console.log '--> syncCourses: entrou no unless @courses' @courses = [] courses.each((i, course) => id = parseInt(/[\\?&]id=([^&#]*)/.exec($(course).prop('href'))[1]) name = $(course).text().trim() equal = false for c in @courses if c.id == id c.name = name equal = true break unless equal @courses.push( id: id name: name selected: false users: [] errors: [] ) ) @courses.sort((a, b) -> if a.id > b.id return -1 if a.id < b.id return 1 return 0 ) @courses[0].selected = true; for course in @courses @syncUsers(course, response) response( Moodle.response().success, Moodle.response().sync_courses ) error: -> response( Moodle.response().sync_no_moodle_access, Moodle.response().sync_courses ) ) @ ''' por algum motivo a função abaixo não está sendo criada por enquanto vou deixar ela ai, caso eu precise eventualmente, mas caso desnecessario, vou excluir ''' regexMoodle: -> regexList = [] # Here we'll add possible moodle paths for futher maintence ufsc = new RegExp(/ufsc/) ufpel = new RegExp(/ufpel/) regexList.push(ufsc) regexList.push(ufpel) for regex in regexList if @url.match(regex) actual_moodle = @url.match(regex) return actual_moodle[0] #[ ] need to fix some problems(??) in this function syncUsers: (course, response) -> $.ajax( url: @url + '/user/index.php?perpage=100&id=' + course.id type: 'GET' success: (data) => parser = new DOMParser() doc = parser.parseFromString(data, 'text/html') list = $('div > table > tbody > tr', doc) ''' Problema1: a estrutura do htlm é a mesma na UFPEL e na UFSC, Entretanto, a posição das 'cell' são organizadas diferentes. É preciso saber onde se esta trabalhando e criar uma rotina baseado no moodle utilizado. Resolução do P1: Criei uma regex para saber onde estamos, caso novos moodles tenham problemas a solução vai ser alterar essa parte da regex, pegar a peculiaridade do html dele e adicionar ao um elif, criando as variaveis daquele if com os mesmo nomes, para que na frente o codigo funcione. Problema2: Não é em todo moodle que tem a role do professor dentro de um <tr>, então vou tentar excluir a role do código(já que agora o upload é local e só professores tem acesso a os logs.). ''' regexList = [] # Here we'll add possible moodle paths for futher maintence ufsc = new RegExp(/ufsc/) ufpel = new RegExp(/ufpel/) regexList.push(ufsc) regexList.push(ufpel) for regex in regexList if @url.match(regex) actual_moodle = @url.match(regex) break # NOTE: use actual_moodle[0] to get the regex return if actual_moodle[0] == "ufpel" picture = $('*[class="cell c1"] a', list) name = $('*[class="cell c2"]', list) email = $('*[class="cell c3"]', list) else picture = $('*[class="cell c1"] a', list) name = $('*[class="cell c1"]', list) email = $('*[class="cell c2"]', list) ''' # COMENTADO PELO MOMENTO - trata o erro do html não retornar usuarios, mas tá bugado. unless list.length console.log '--> syncUsers: returned in the first unless line 109' return response( Moodle.response().sync_no_users, Moodle.response().sync_users ) ''' #a = $('*[class*="picture"] a', list) #b = $('*[class*="name"]', list) #c = $('*[class*="email"]', list) #d = $('*[class*="roles"]', list) unless picture.length || name.length || email.length return response( Moodle.response().sync_no_users, Moodle.response().sync_users ) #[ ] CONCERTAR A PARTIR DAQUI - NOTA: apaguei algumas coisas. list.each((i) => ''' Nota: A seguinte regex: .match(/\d+/) retorna um numero composto. p.e: 1548 ''' ''' roles = [] $('*[class^="role"]', d[i]).each((i_r, role) -> id = 0 value = [] if $(role).attr('rel') value = $(role).attr('rel').match(/\d+/) unless value.length value = $(role).attr('class').match(/\d+/) if value.length id = parseInt(value[0]) roles.push( id: id role: $(role).text().trim() ) ) unless roles.length roles.push( id: 0 role: 'Participant' ) ''' ''' for role in roles ur = course.users.filter((user) => user.id == role.id) if ur.length user = ur[0] else p = course.users.push( id: role.id role: role.role list: [] selected: false ) - 1 user = course.users[p] ''' # a linha abaixo tem que estar dentro de um for usr = id: parseInt(/[\\?&]id=([^&#]*)/.exec($(picture[i]).prop('href'))[1]) picture: $('img', picture[i]).prop('src') name: $(name[i]).text().replace(/\s\s/g, ' ').trim() email: $(email[i]).text().trim() selected: true names = usr.name.toLowerCase().split(/\s/) usr.firstname = names[0].replace(/\S/, (e) -> e.toUpperCase() ) if names.length > 1 usr.lastname = names[names.length - 1].replace(/\S/, (e) -> e.toUpperCase() ) equal = false ''' for u in user.list if u.id == usr.id u.picture = usr.picture u.name = usr.name u.firstname = usr.firstname u.lastname = usr.lastname u.email = usr.email equal = true break ''' user.list.push(usr) user.list.sort((a, b) -> x = a.name.toLowerCase() y = b.name.toLowerCase() if x < y return -1 if x > y return 1 return 0 ) ) course.users.sort((a, b) -> if a.list.length > b.list.length return -1 if a.list.length < b.list.length return 1 return 0 ) course.users[0].selected = true @upLastAccess() console.log '--> syncUsers: mostrando usuarios json: ' + JSON.stringify(course.users) response( Moodle.response().success, Moodle.response().sync_users ) error: => console.log '--> syncUsers: ajax error' response( console.log '--> syncUsers: ajax error' Moodle.response().sync_no_moodle_access Moodle.response().sync_users ) ) @ syncDates: (response) -> unless @hasCourses() return response( console.log 'problema no hasCourses' Moodle.response().sync_no_courses, Moodle.response().sync_dates ) unless @hasUsers() return response( console.log 'problema no hasUsers' Moodle.response().sync_no_users, Moodle.response().sync_dates ) course = @getCourse() $.ajax( url: @url + '/report/log/' data: id: course.id success: (data) => parser = new DOMParser() doc = parser.parseFromString(data, 'text/html') list = $('select[name="date"] option', doc) timelist = [] list.each((i, e) => if $(e).val() timelist.push(parseInt($(e).val())) ) unless timelist.length return response( console.log 'problema na timelist do syncDates' Moodle.response().sync_no_dates, Moodle.response().sync_dates ) timelist.sort((a, b) -> if a < b return -1 if a > b return 1 return 0 ) first = timelist[0] * 1000 last = timelist[timelist.length - 1] * 1000 if course.dates old = @clone(course.dates) timelist = timelist[timelist.indexOf(old.max.value / 1000)..] course.dates.max.value = last if old.max.selected == old.max.value course.dates.max.selected = last if old.min.selected != old.min.value dif = last - old.max.value if dif > 0 course.dates.min.selected += dif if course.dates.min.selected < course.dates.min.value course.dates.min.selected = course.dates.min.value else course.dates = min: value: first selected: first max: value: last selected: last course.users_not_found = {} console.log('timelist:', timelist, course.errors) timelist = timelist.concat(course.errors) course.errors = [] for time in timelist @syncData(course, time, response) response( Moodle.response().success, Moodle.response().sync_dates, timelist.length ) error: -> response( console.log 'erro no ajax da syncDates' Moodle.response().sync_no_moodle_access, Moodle.response().sync_dates ) ) @ # Analisar esta função - download csv syncData: (course, time, response) -> ''' Acho que oq posso fazer aqui é achar o curso equivalente que foi chamado com a função e em seguida procurar no html da pagina o .csv que foi submetido localmente ''' # Criar um parser que vai encontrar os cursos que foram achados na sessão atual console.log 'entrou na syncData' parser = new DOMParser() doc = parser.parseFromString(@html, 'text/html') coursesCrawled = $('ul > li > label', doc) for item in coursesCrawled # []preciso saber oq é esse course para comparar os nomes if item.textContent == course.course # preciso achar o .csv e jogar para dentro da data data = @processRaw(course, time, data, 'csv') else console.log '404 - not found' ''' $.ajax( url: @url + '/report/log/' data: id: course.id date: time chooselog: 1 logformat: 'downloadascsv' download: 'csv' lang: 'en' success: (data, textStatus, request) => type = request.getResponseHeader('content-type') if /application\/download/.test(type) @processRaw(course, time, data, 'tsv') else if /text\/tab-separated-values/.test(type) if data.length > 0 @processRaw(course, time, data, 'tsv') else if /text\/csv/.test(type) if data.length > 0 @processRaw(course, time, data, 'csv') else if data.length > 0 course.errors.push(time) return response( Moodle.response().sync_no_moodle_access, Moodle.response().sync_data ) response( Moodle.response().success, Moodle.response().sync_data ) error: (request) -> if request.status >= 400 return response( Moodle.response().success, Moodle.response().sync_data ); course.errors.push(time) response( Moodle.response().sync_no_moodle_access, Moodle.response().sync_data ) ) @ ''' # [ ] Arranjar uma maneira de trazer os logs para esta funçao processRaw: (course, time, data, type) -> realtime = time * 1000 console.log 'AAAAA: Testando: ' + course + ' -- AND --> ' + course.course logs = data.replace(/\"Saved\sat\:(.+)\s/, '') unless course.logs course.logs = {} course.logs[realtime] = d3[type].parse(logs) users = {} # aqui pra baixo já tem os logs for row in course.logs[realtime] username = (row['User full name'] || row['Nome completo']).trim() unless users[username] users[username] = [] users[username].push(row) for user, rows of users es = @getUser(course, user) if es.length for e in es unless e.data e.data = {} e.data[realtime] = @processRow(rows, realtime) else course.users_not_found[user] = Date.now() @ processRow: (rows, realtime) -> data = {} for row in rows action = (row['Event name'] || row['Action'] || row['Nome do evento']) eventname = action.split(/\s\(/)?[0].trim() eventcontext = ( row['Event context'] || row['Contexto do Evento'] || action.split(/\s\(/)?[1].slice(0, -1) ).trim() component = (row['Component'] || row['Componente'] || action.split(/\s/)?[0]).trim() if component.toLowerCase() == 'logs' continue description = (row['Description'] || row['Information'] || row['Descrição']) if description description = description.trim() hour = /([0-9]{1,2}:[0-9]{1,2})(\s(A|P)M)?/.exec((row['Time'] || row['Hora']).toUpperCase())[0] date = new Date(realtime).toISOString().split(/T/)[0] time = Date.parse(date + ' ' + hour) - Date.parse(date) unless data[component] data[component] = {} unless data[component][eventname] data[component][eventname] = {} unless data[component][eventname][eventcontext] data[component][eventname][eventcontext] = {} unless data[component][eventname][eventcontext][description] data[component][eventname][eventcontext][description] = {} unless data[component][eventname][eventcontext][description][time] data[component][eventname][eventcontext][description][time] = 0 data[component][eventname][eventcontext][description][time]++ data setDefaultLang: -> $.ajax( url: @url data: lang: @lang method: 'HEAD' ) @ getSessKey: (response) -> $.ajax( url: @url success: (data, textStatus, request) -> parser = new DOMParser() doc = parser.parseFromString(data, 'text/html') sesskey = /"sesskey":"([^"]*)/.exec($('head', doc).html()) if sesskey && sesskey.length > 1 && sesskey[1] return response(sesskey[1]) response() error: -> response() ) @ sendMessageToUser: (user, message, sesskey, response) -> $.ajax( url: @url + '/message/index.php' data: id: user message: message sesskey: sesskey _qf__send_form: 1 submitbutton: 'send' method: 'POST' success: (data, textStatus, request) -> response() error: -> response() ) @ getCourseIndex: (name) -> for course, i in @courses if name == course.name return i setCourse: (id) -> for course, i in @courses course.selected = (i == id) @ setUser: (role, user, selected) -> users = @getCourse().users[role].list users[user].selected = selected @ setUsersAll: (role) -> users = @getCourse().users[role].list for user in users user.selected = true @ setUsersInvert: (role) -> users = @getCourse().users[role].list for user in users user.selected = !user.selected @ setDates: (dates) -> @getCourse().dates = dates @ upLastAccess: -> @last_sync = Date.now() @ upLastSync: -> @getCourse().last_sync = Date.now() @ select: (url) -> @selected = @equals(url) && @hasUsers() @ ''' $('#thefile').change (e) -> if e.target.files != undefined reader = new FileReader reader.onload = (e) -> $('#text').text e.target.result return reader.readAsText e.target.files.item(0) false ''' ''' getLocalLogs: (course) -> continue ''' getActivities: (role) -> unless @hasData() return course = @getCourse() data = {} for user, userid in course.users[role].list if user.data for day, components of user.data for component, eventnames of components for eventname, eventcontexts of eventnames for eventcontext, descriptions of eventcontexts for description, hours of descriptions page = eventcontext if /^http/.test(page) page = description event = eventname + ' (' + eventcontext + ')' unless data[event] data[event] = page: page event: eventname data getAssignments: () -> unless @hasData() return course = @getCourse() data = {} assings = {} for role, roleid in course.users for user, userid in role.list if user.data for day, components of user.data for component, eventnames of components for eventname, eventcontexts of eventnames for eventcontext, descriptions of eventcontexts for description, hours of descriptions page = eventcontext if /^http/.test(page) page = description if /^assign/.test(eventname) || /^assign/.test(page.toLowerCase()) unless data[roleid] data[roleid] = data: [] events: {} unless data[roleid].events[eventname] data[roleid].events[eventname] = 0 data[roleid].events[eventname]++ data[roleid].data.push( user: user.name page: page event: eventname context: eventcontext description: description component: component ) data getLogs: -> course = @getCourse() # [ ] checar se este unless vai bugar com a remoção da sync console.log 'rodando funçao getLogs' unless course.logs && Object.keys(course.logs).length console.log 'entrou no unless do getLOGS' return days = Object.keys(course.logs).sort((a, b) -> a = parseInt(a) b = parseInt(b) if a > b return -1 if a < b return 1 return 0 ) logs = [] for day in days logs = logs.concat(course.logs[day]) logs getCourseData: -> unless @hasData() return @getCourse() getTitle: -> @title getURL: -> @url # retorna o objeto curso que foi clicado no dashborad getCourse: -> for course in @courses if course.selected return course getCourseList: -> for course in @courses name: course.name selected: course.selected getRoles: -> for role in @getCourse().users console.log '--> getRoles: a role é: ' + role console.log '--> getRoles: a role.role é: ' + role.role name: role.role getUser: (course, username) -> list = [] for role in course.users for user in role.list if user.name == username list.push(user) list getUsers: -> roles = @getRoles() for role, i in roles console.log '--> getUsers(moodle): entrou no for de roles' role.users = [] for user in @getCourse().users[i].list console.log '--> getUsers(moodle): entrou no for de users' role.users.push( id: user.id picture: user.picture email: user.email name: user.name firstname: user.firstname lastname: user.lastname selected: user.selected ) roles getUsersNotFound: -> course = @getCourse() if course.users_not_found Object.keys(course.users_not_found) else [] getDates: -> @getCourse().dates getLastAccess: -> @last_sync || 0 getLastSync: -> @getCourse().last_sync || 0 hasCourses: -> @courses? hasUsers: -> unless @hasCourses() return false @getCourse().users.length > 0 hasDates: -> unless @hasCourses() console.log '--> hasDates: retornou false' return false #no final de dates tinha um sinal de ?, tirei pois não sabia oq faz @getCourse().dates hasErrors: -> unless @hasCourses() return false @getCourse().errors.length > 0 hasData: -> #old code below #@hasDates() && @getLastSync() > 0 @hasDates() > 0 isSelected: -> @selected equals: (url) -> @url == url toString: -> JSON.stringify(@) parse: (str) -> JSON.parse(str) clone: (obj) -> JSON.parse(JSON.stringify(obj)) @response: -> success: 'SUCCESS' sync_no_moodle_access: 'SYNC_NO_MOODLE_ACCESS' sync_no_courses: 'SYNC_NO_COURSES' sync_no_users: 'SYNC_NO_USERS' sync_no_dates: 'SYNC_NO_DATES' sync_no_data: 'SYNC_NO_DATA' sync_courses: 'SYNC_COURSES' sync_users: 'SYNC_USERS' sync_dates: 'SYNC_DATES' sync_data: 'SYNC_DATA' @Moodle = Moodle
88481
### # moodle: moodle data ### class Moodle constructor: (options) -> if options options = @parse(options) if typeof options == 'string' && options.length for key, value of options @[key] = value console.log('Moodle:', @) syncTitle: (response) -> $.ajax( url: @url success: (data) => parser = new DOMParser() doc = parser.parseFromString(data, 'text/html') @title = $($('*[class="tree_item branch"] *[title]', doc)[0]) .attr('title')?.trim() unless @title @title = $('title', doc).text()?.trim() response(Moodle.response().success) ) @ sync: (response) -> # default = /my, cafeead moodle = /disciplinas $.ajax( url: @url + '/disciplinas' type: 'HEAD' success: => @syncCourses(response, 'disciplinas') error: => @syncCourses(response) ) @ syncCourses: (response, path = 'my') -> $.ajax( url: @url + '/' + path data: mynumber: -2 success: (data) => parser = new DOMParser() doc = parser.parseFromString(data, 'text/html') courses = $('h2 > a[href*="course/view.php?id="]', doc) unless courses.length courses = $('h4 > a[href*="course/view.php?id="]', doc) unless courses.length courses = $('li > a[href*="course/view.php?id="]', doc) unless courses.length return response( Moodle.response().sync_no_courses, Moodle.response().sync_courses ) unless @courses console.log '--> syncCourses: entrou no unless @courses' @courses = [] courses.each((i, course) => id = parseInt(/[\\?&]id=([^&#]*)/.exec($(course).prop('href'))[1]) name = $(course).text().trim() equal = false for c in @courses if c.id == id c.name = <NAME> equal = true break unless equal @courses.push( id: id name: <NAME> selected: false users: [] errors: [] ) ) @courses.sort((a, b) -> if a.id > b.id return -1 if a.id < b.id return 1 return 0 ) @courses[0].selected = true; for course in @courses @syncUsers(course, response) response( Moodle.response().success, Moodle.response().sync_courses ) error: -> response( Moodle.response().sync_no_moodle_access, Moodle.response().sync_courses ) ) @ ''' por algum motivo a função abaixo não está sendo criada por enquanto vou deixar ela ai, caso eu precise eventualmente, mas caso desnecessario, vou excluir ''' regexMoodle: -> regexList = [] # Here we'll add possible moodle paths for futher maintence ufsc = new RegExp(/ufsc/) ufpel = new RegExp(/ufpel/) regexList.push(ufsc) regexList.push(ufpel) for regex in regexList if @url.match(regex) actual_moodle = @url.match(regex) return actual_moodle[0] #[ ] need to fix some problems(??) in this function syncUsers: (course, response) -> $.ajax( url: @url + '/user/index.php?perpage=100&id=' + course.id type: 'GET' success: (data) => parser = new DOMParser() doc = parser.parseFromString(data, 'text/html') list = $('div > table > tbody > tr', doc) ''' Problema1: a estrutura do htlm é a mesma na UFPEL e na UFSC, Entretanto, a posição das 'cell' são organizadas diferentes. É preciso saber onde se esta trabalhando e criar uma rotina baseado no moodle utilizado. Resolução do P1: Criei uma regex para saber onde estamos, caso novos moodles tenham problemas a solução vai ser alterar essa parte da regex, pegar a peculiaridade do html dele e adicionar ao um elif, criando as variaveis daquele if com os mesmo nomes, para que na frente o codigo funcione. Problema2: Não é em todo moodle que tem a role do professor dentro de um <tr>, então vou tentar excluir a role do código(já que agora o upload é local e só professores tem acesso a os logs.). ''' regexList = [] # Here we'll add possible moodle paths for futher maintence ufsc = new RegExp(/ufsc/) ufpel = new RegExp(/ufpel/) regexList.push(ufsc) regexList.push(ufpel) for regex in regexList if @url.match(regex) actual_moodle = @url.match(regex) break # NOTE: use actual_moodle[0] to get the regex return if actual_moodle[0] == "ufpel" picture = $('*[class="cell c1"] a', list) name = $('*[class="cell c2"]', list) email = $('*[class="cell c3"]', list) else picture = $('*[class="cell c1"] a', list) name = $('*[class="cell c1"]', list) email = $('*[class="cell c2"]', list) ''' # COMENTADO PELO MOMENTO - trata o erro do html não retornar usuarios, mas tá bugado. unless list.length console.log '--> syncUsers: returned in the first unless line 109' return response( Moodle.response().sync_no_users, Moodle.response().sync_users ) ''' #a = $('*[class*="picture"] a', list) #b = $('*[class*="name"]', list) #c = $('*[class*="email"]', list) #d = $('*[class*="roles"]', list) unless picture.length || name.length || email.length return response( Moodle.response().sync_no_users, Moodle.response().sync_users ) #[ ] CONCERTAR A PARTIR DAQUI - NOTA: apaguei algumas coisas. list.each((i) => ''' Nota: A seguinte regex: .match(/\d+/) retorna um numero composto. p.e: 1548 ''' ''' roles = [] $('*[class^="role"]', d[i]).each((i_r, role) -> id = 0 value = [] if $(role).attr('rel') value = $(role).attr('rel').match(/\d+/) unless value.length value = $(role).attr('class').match(/\d+/) if value.length id = parseInt(value[0]) roles.push( id: id role: $(role).text().trim() ) ) unless roles.length roles.push( id: 0 role: 'Participant' ) ''' ''' for role in roles ur = course.users.filter((user) => user.id == role.id) if ur.length user = ur[0] else p = course.users.push( id: role.id role: role.role list: [] selected: false ) - 1 user = course.users[p] ''' # a linha abaixo tem que estar dentro de um for usr = id: parseInt(/[\\?&]id=([^&#]*)/.exec($(picture[i]).prop('href'))[1]) picture: $('img', picture[i]).prop('src') name: $(name[i]).text().replace(/\s\s/g, ' ').trim() email: $(email[i]).text().trim() selected: true names = usr.name.toLowerCase().split(/\s/) usr.firstname = names[0].replace(/\S/, (e) -> e.toUpperCase() ) if names.length > 1 usr.lastname = names[names.length - 1].replace(/\S/, (e) -> e.toUpperCase() ) equal = false ''' for u in user.list if u.id == usr.id u.picture = usr.picture u.name = usr.name u.firstname = usr.firstname u.lastname = usr.lastname u.email = usr.email equal = true break ''' user.list.push(usr) user.list.sort((a, b) -> x = a.name.toLowerCase() y = b.name.toLowerCase() if x < y return -1 if x > y return 1 return 0 ) ) course.users.sort((a, b) -> if a.list.length > b.list.length return -1 if a.list.length < b.list.length return 1 return 0 ) course.users[0].selected = true @upLastAccess() console.log '--> syncUsers: mostrando usuarios json: ' + JSON.stringify(course.users) response( Moodle.response().success, Moodle.response().sync_users ) error: => console.log '--> syncUsers: ajax error' response( console.log '--> syncUsers: ajax error' Moodle.response().sync_no_moodle_access Moodle.response().sync_users ) ) @ syncDates: (response) -> unless @hasCourses() return response( console.log 'problema no hasCourses' Moodle.response().sync_no_courses, Moodle.response().sync_dates ) unless @hasUsers() return response( console.log 'problema no hasUsers' Moodle.response().sync_no_users, Moodle.response().sync_dates ) course = @getCourse() $.ajax( url: @url + '/report/log/' data: id: course.id success: (data) => parser = new DOMParser() doc = parser.parseFromString(data, 'text/html') list = $('select[name="date"] option', doc) timelist = [] list.each((i, e) => if $(e).val() timelist.push(parseInt($(e).val())) ) unless timelist.length return response( console.log 'problema na timelist do syncDates' Moodle.response().sync_no_dates, Moodle.response().sync_dates ) timelist.sort((a, b) -> if a < b return -1 if a > b return 1 return 0 ) first = timelist[0] * 1000 last = timelist[timelist.length - 1] * 1000 if course.dates old = @clone(course.dates) timelist = timelist[timelist.indexOf(old.max.value / 1000)..] course.dates.max.value = last if old.max.selected == old.max.value course.dates.max.selected = last if old.min.selected != old.min.value dif = last - old.max.value if dif > 0 course.dates.min.selected += dif if course.dates.min.selected < course.dates.min.value course.dates.min.selected = course.dates.min.value else course.dates = min: value: first selected: first max: value: last selected: last course.users_not_found = {} console.log('timelist:', timelist, course.errors) timelist = timelist.concat(course.errors) course.errors = [] for time in timelist @syncData(course, time, response) response( Moodle.response().success, Moodle.response().sync_dates, timelist.length ) error: -> response( console.log 'erro no ajax da syncDates' Moodle.response().sync_no_moodle_access, Moodle.response().sync_dates ) ) @ # Analisar esta função - download csv syncData: (course, time, response) -> ''' Acho que oq posso fazer aqui é achar o curso equivalente que foi chamado com a função e em seguida procurar no html da pagina o .csv que foi submetido localmente ''' # Criar um parser que vai encontrar os cursos que foram achados na sessão atual console.log 'entrou na syncData' parser = new DOMParser() doc = parser.parseFromString(@html, 'text/html') coursesCrawled = $('ul > li > label', doc) for item in coursesCrawled # []preciso saber oq é esse course para comparar os nomes if item.textContent == course.course # preciso achar o .csv e jogar para dentro da data data = @processRaw(course, time, data, 'csv') else console.log '404 - not found' ''' $.ajax( url: @url + '/report/log/' data: id: course.id date: time chooselog: 1 logformat: 'downloadascsv' download: 'csv' lang: 'en' success: (data, textStatus, request) => type = request.getResponseHeader('content-type') if /application\/download/.test(type) @processRaw(course, time, data, 'tsv') else if /text\/tab-separated-values/.test(type) if data.length > 0 @processRaw(course, time, data, 'tsv') else if /text\/csv/.test(type) if data.length > 0 @processRaw(course, time, data, 'csv') else if data.length > 0 course.errors.push(time) return response( Moodle.response().sync_no_moodle_access, Moodle.response().sync_data ) response( Moodle.response().success, Moodle.response().sync_data ) error: (request) -> if request.status >= 400 return response( Moodle.response().success, Moodle.response().sync_data ); course.errors.push(time) response( Moodle.response().sync_no_moodle_access, Moodle.response().sync_data ) ) @ ''' # [ ] Arranjar uma maneira de trazer os logs para esta funçao processRaw: (course, time, data, type) -> realtime = time * 1000 console.log 'AAAAA: Testando: ' + course + ' -- AND --> ' + course.course logs = data.replace(/\"Saved\sat\:(.+)\s/, '') unless course.logs course.logs = {} course.logs[realtime] = d3[type].parse(logs) users = {} # aqui pra baixo já tem os logs for row in course.logs[realtime] username = (row['User full name'] || row['Nome completo']).trim() unless users[username] users[username] = [] users[username].push(row) for user, rows of users es = @getUser(course, user) if es.length for e in es unless e.data e.data = {} e.data[realtime] = @processRow(rows, realtime) else course.users_not_found[user] = Date.now() @ processRow: (rows, realtime) -> data = {} for row in rows action = (row['Event name'] || row['Action'] || row['Nome do evento']) eventname = action.split(/\s\(/)?[0].trim() eventcontext = ( row['Event context'] || row['Contexto do Evento'] || action.split(/\s\(/)?[1].slice(0, -1) ).trim() component = (row['Component'] || row['Componente'] || action.split(/\s/)?[0]).trim() if component.toLowerCase() == 'logs' continue description = (row['Description'] || row['Information'] || row['Descrição']) if description description = description.trim() hour = /([0-9]{1,2}:[0-9]{1,2})(\s(A|P)M)?/.exec((row['Time'] || row['Hora']).toUpperCase())[0] date = new Date(realtime).toISOString().split(/T/)[0] time = Date.parse(date + ' ' + hour) - Date.parse(date) unless data[component] data[component] = {} unless data[component][eventname] data[component][eventname] = {} unless data[component][eventname][eventcontext] data[component][eventname][eventcontext] = {} unless data[component][eventname][eventcontext][description] data[component][eventname][eventcontext][description] = {} unless data[component][eventname][eventcontext][description][time] data[component][eventname][eventcontext][description][time] = 0 data[component][eventname][eventcontext][description][time]++ data setDefaultLang: -> $.ajax( url: @url data: lang: @lang method: 'HEAD' ) @ getSessKey: (response) -> $.ajax( url: @url success: (data, textStatus, request) -> parser = new DOMParser() doc = parser.parseFromString(data, 'text/html') sesskey = /"sesskey":"([^"]*)/.exec($('head', doc).html()) if sesskey && sesskey.length > 1 && sesskey[1] return response(sesskey[1]) response() error: -> response() ) @ sendMessageToUser: (user, message, sesskey, response) -> $.ajax( url: @url + '/message/index.php' data: id: user message: message sesskey: sesskey _qf__send_form: 1 submitbutton: 'send' method: 'POST' success: (data, textStatus, request) -> response() error: -> response() ) @ getCourseIndex: (name) -> for course, i in @courses if name == course.name return i setCourse: (id) -> for course, i in @courses course.selected = (i == id) @ setUser: (role, user, selected) -> users = @getCourse().users[role].list users[user].selected = selected @ setUsersAll: (role) -> users = @getCourse().users[role].list for user in users user.selected = true @ setUsersInvert: (role) -> users = @getCourse().users[role].list for user in users user.selected = !user.selected @ setDates: (dates) -> @getCourse().dates = dates @ upLastAccess: -> @last_sync = Date.now() @ upLastSync: -> @getCourse().last_sync = Date.now() @ select: (url) -> @selected = @equals(url) && @hasUsers() @ ''' $('#thefile').change (e) -> if e.target.files != undefined reader = new FileReader reader.onload = (e) -> $('#text').text e.target.result return reader.readAsText e.target.files.item(0) false ''' ''' getLocalLogs: (course) -> continue ''' getActivities: (role) -> unless @hasData() return course = @getCourse() data = {} for user, userid in course.users[role].list if user.data for day, components of user.data for component, eventnames of components for eventname, eventcontexts of eventnames for eventcontext, descriptions of eventcontexts for description, hours of descriptions page = eventcontext if /^http/.test(page) page = description event = eventname + ' (' + eventcontext + ')' unless data[event] data[event] = page: page event: eventname data getAssignments: () -> unless @hasData() return course = @getCourse() data = {} assings = {} for role, roleid in course.users for user, userid in role.list if user.data for day, components of user.data for component, eventnames of components for eventname, eventcontexts of eventnames for eventcontext, descriptions of eventcontexts for description, hours of descriptions page = eventcontext if /^http/.test(page) page = description if /^assign/.test(eventname) || /^assign/.test(page.toLowerCase()) unless data[roleid] data[roleid] = data: [] events: {} unless data[roleid].events[eventname] data[roleid].events[eventname] = 0 data[roleid].events[eventname]++ data[roleid].data.push( user: user.name page: page event: eventname context: eventcontext description: description component: component ) data getLogs: -> course = @getCourse() # [ ] checar se este unless vai bugar com a remoção da sync console.log 'rodando funçao getLogs' unless course.logs && Object.keys(course.logs).length console.log 'entrou no unless do getLOGS' return days = Object.keys(course.logs).sort((a, b) -> a = parseInt(a) b = parseInt(b) if a > b return -1 if a < b return 1 return 0 ) logs = [] for day in days logs = logs.concat(course.logs[day]) logs getCourseData: -> unless @hasData() return @getCourse() getTitle: -> @title getURL: -> @url # retorna o objeto curso que foi clicado no dashborad getCourse: -> for course in @courses if course.selected return course getCourseList: -> for course in @courses name: course.name selected: course.selected getRoles: -> for role in @getCourse().users console.log '--> getRoles: a role é: ' + role console.log '--> getRoles: a role.role é: ' + role.role name: role.role getUser: (course, username) -> list = [] for role in course.users for user in role.list if user.name == username list.push(user) list getUsers: -> roles = @getRoles() for role, i in roles console.log '--> getUsers(moodle): entrou no for de roles' role.users = [] for user in @getCourse().users[i].list console.log '--> getUsers(moodle): entrou no for de users' role.users.push( id: user.id picture: user.picture email: user.email name: <NAME>.name firstname: user.firstname lastname: user.lastname selected: user.selected ) roles getUsersNotFound: -> course = @getCourse() if course.users_not_found Object.keys(course.users_not_found) else [] getDates: -> @getCourse().dates getLastAccess: -> @last_sync || 0 getLastSync: -> @getCourse().last_sync || 0 hasCourses: -> @courses? hasUsers: -> unless @hasCourses() return false @getCourse().users.length > 0 hasDates: -> unless @hasCourses() console.log '--> hasDates: retornou false' return false #no final de dates tinha um sinal de ?, tirei pois não sabia oq faz @getCourse().dates hasErrors: -> unless @hasCourses() return false @getCourse().errors.length > 0 hasData: -> #old code below #@hasDates() && @getLastSync() > 0 @hasDates() > 0 isSelected: -> @selected equals: (url) -> @url == url toString: -> JSON.stringify(@) parse: (str) -> JSON.parse(str) clone: (obj) -> JSON.parse(JSON.stringify(obj)) @response: -> success: 'SUCCESS' sync_no_moodle_access: 'SYNC_NO_MOODLE_ACCESS' sync_no_courses: 'SYNC_NO_COURSES' sync_no_users: 'SYNC_NO_USERS' sync_no_dates: 'SYNC_NO_DATES' sync_no_data: 'SYNC_NO_DATA' sync_courses: 'SYNC_COURSES' sync_users: 'SYNC_USERS' sync_dates: 'SYNC_DATES' sync_data: 'SYNC_DATA' @Moodle = Moodle
true
### # moodle: moodle data ### class Moodle constructor: (options) -> if options options = @parse(options) if typeof options == 'string' && options.length for key, value of options @[key] = value console.log('Moodle:', @) syncTitle: (response) -> $.ajax( url: @url success: (data) => parser = new DOMParser() doc = parser.parseFromString(data, 'text/html') @title = $($('*[class="tree_item branch"] *[title]', doc)[0]) .attr('title')?.trim() unless @title @title = $('title', doc).text()?.trim() response(Moodle.response().success) ) @ sync: (response) -> # default = /my, cafeead moodle = /disciplinas $.ajax( url: @url + '/disciplinas' type: 'HEAD' success: => @syncCourses(response, 'disciplinas') error: => @syncCourses(response) ) @ syncCourses: (response, path = 'my') -> $.ajax( url: @url + '/' + path data: mynumber: -2 success: (data) => parser = new DOMParser() doc = parser.parseFromString(data, 'text/html') courses = $('h2 > a[href*="course/view.php?id="]', doc) unless courses.length courses = $('h4 > a[href*="course/view.php?id="]', doc) unless courses.length courses = $('li > a[href*="course/view.php?id="]', doc) unless courses.length return response( Moodle.response().sync_no_courses, Moodle.response().sync_courses ) unless @courses console.log '--> syncCourses: entrou no unless @courses' @courses = [] courses.each((i, course) => id = parseInt(/[\\?&]id=([^&#]*)/.exec($(course).prop('href'))[1]) name = $(course).text().trim() equal = false for c in @courses if c.id == id c.name = PI:NAME:<NAME>END_PI equal = true break unless equal @courses.push( id: id name: PI:NAME:<NAME>END_PI selected: false users: [] errors: [] ) ) @courses.sort((a, b) -> if a.id > b.id return -1 if a.id < b.id return 1 return 0 ) @courses[0].selected = true; for course in @courses @syncUsers(course, response) response( Moodle.response().success, Moodle.response().sync_courses ) error: -> response( Moodle.response().sync_no_moodle_access, Moodle.response().sync_courses ) ) @ ''' por algum motivo a função abaixo não está sendo criada por enquanto vou deixar ela ai, caso eu precise eventualmente, mas caso desnecessario, vou excluir ''' regexMoodle: -> regexList = [] # Here we'll add possible moodle paths for futher maintence ufsc = new RegExp(/ufsc/) ufpel = new RegExp(/ufpel/) regexList.push(ufsc) regexList.push(ufpel) for regex in regexList if @url.match(regex) actual_moodle = @url.match(regex) return actual_moodle[0] #[ ] need to fix some problems(??) in this function syncUsers: (course, response) -> $.ajax( url: @url + '/user/index.php?perpage=100&id=' + course.id type: 'GET' success: (data) => parser = new DOMParser() doc = parser.parseFromString(data, 'text/html') list = $('div > table > tbody > tr', doc) ''' Problema1: a estrutura do htlm é a mesma na UFPEL e na UFSC, Entretanto, a posição das 'cell' são organizadas diferentes. É preciso saber onde se esta trabalhando e criar uma rotina baseado no moodle utilizado. Resolução do P1: Criei uma regex para saber onde estamos, caso novos moodles tenham problemas a solução vai ser alterar essa parte da regex, pegar a peculiaridade do html dele e adicionar ao um elif, criando as variaveis daquele if com os mesmo nomes, para que na frente o codigo funcione. Problema2: Não é em todo moodle que tem a role do professor dentro de um <tr>, então vou tentar excluir a role do código(já que agora o upload é local e só professores tem acesso a os logs.). ''' regexList = [] # Here we'll add possible moodle paths for futher maintence ufsc = new RegExp(/ufsc/) ufpel = new RegExp(/ufpel/) regexList.push(ufsc) regexList.push(ufpel) for regex in regexList if @url.match(regex) actual_moodle = @url.match(regex) break # NOTE: use actual_moodle[0] to get the regex return if actual_moodle[0] == "ufpel" picture = $('*[class="cell c1"] a', list) name = $('*[class="cell c2"]', list) email = $('*[class="cell c3"]', list) else picture = $('*[class="cell c1"] a', list) name = $('*[class="cell c1"]', list) email = $('*[class="cell c2"]', list) ''' # COMENTADO PELO MOMENTO - trata o erro do html não retornar usuarios, mas tá bugado. unless list.length console.log '--> syncUsers: returned in the first unless line 109' return response( Moodle.response().sync_no_users, Moodle.response().sync_users ) ''' #a = $('*[class*="picture"] a', list) #b = $('*[class*="name"]', list) #c = $('*[class*="email"]', list) #d = $('*[class*="roles"]', list) unless picture.length || name.length || email.length return response( Moodle.response().sync_no_users, Moodle.response().sync_users ) #[ ] CONCERTAR A PARTIR DAQUI - NOTA: apaguei algumas coisas. list.each((i) => ''' Nota: A seguinte regex: .match(/\d+/) retorna um numero composto. p.e: 1548 ''' ''' roles = [] $('*[class^="role"]', d[i]).each((i_r, role) -> id = 0 value = [] if $(role).attr('rel') value = $(role).attr('rel').match(/\d+/) unless value.length value = $(role).attr('class').match(/\d+/) if value.length id = parseInt(value[0]) roles.push( id: id role: $(role).text().trim() ) ) unless roles.length roles.push( id: 0 role: 'Participant' ) ''' ''' for role in roles ur = course.users.filter((user) => user.id == role.id) if ur.length user = ur[0] else p = course.users.push( id: role.id role: role.role list: [] selected: false ) - 1 user = course.users[p] ''' # a linha abaixo tem que estar dentro de um for usr = id: parseInt(/[\\?&]id=([^&#]*)/.exec($(picture[i]).prop('href'))[1]) picture: $('img', picture[i]).prop('src') name: $(name[i]).text().replace(/\s\s/g, ' ').trim() email: $(email[i]).text().trim() selected: true names = usr.name.toLowerCase().split(/\s/) usr.firstname = names[0].replace(/\S/, (e) -> e.toUpperCase() ) if names.length > 1 usr.lastname = names[names.length - 1].replace(/\S/, (e) -> e.toUpperCase() ) equal = false ''' for u in user.list if u.id == usr.id u.picture = usr.picture u.name = usr.name u.firstname = usr.firstname u.lastname = usr.lastname u.email = usr.email equal = true break ''' user.list.push(usr) user.list.sort((a, b) -> x = a.name.toLowerCase() y = b.name.toLowerCase() if x < y return -1 if x > y return 1 return 0 ) ) course.users.sort((a, b) -> if a.list.length > b.list.length return -1 if a.list.length < b.list.length return 1 return 0 ) course.users[0].selected = true @upLastAccess() console.log '--> syncUsers: mostrando usuarios json: ' + JSON.stringify(course.users) response( Moodle.response().success, Moodle.response().sync_users ) error: => console.log '--> syncUsers: ajax error' response( console.log '--> syncUsers: ajax error' Moodle.response().sync_no_moodle_access Moodle.response().sync_users ) ) @ syncDates: (response) -> unless @hasCourses() return response( console.log 'problema no hasCourses' Moodle.response().sync_no_courses, Moodle.response().sync_dates ) unless @hasUsers() return response( console.log 'problema no hasUsers' Moodle.response().sync_no_users, Moodle.response().sync_dates ) course = @getCourse() $.ajax( url: @url + '/report/log/' data: id: course.id success: (data) => parser = new DOMParser() doc = parser.parseFromString(data, 'text/html') list = $('select[name="date"] option', doc) timelist = [] list.each((i, e) => if $(e).val() timelist.push(parseInt($(e).val())) ) unless timelist.length return response( console.log 'problema na timelist do syncDates' Moodle.response().sync_no_dates, Moodle.response().sync_dates ) timelist.sort((a, b) -> if a < b return -1 if a > b return 1 return 0 ) first = timelist[0] * 1000 last = timelist[timelist.length - 1] * 1000 if course.dates old = @clone(course.dates) timelist = timelist[timelist.indexOf(old.max.value / 1000)..] course.dates.max.value = last if old.max.selected == old.max.value course.dates.max.selected = last if old.min.selected != old.min.value dif = last - old.max.value if dif > 0 course.dates.min.selected += dif if course.dates.min.selected < course.dates.min.value course.dates.min.selected = course.dates.min.value else course.dates = min: value: first selected: first max: value: last selected: last course.users_not_found = {} console.log('timelist:', timelist, course.errors) timelist = timelist.concat(course.errors) course.errors = [] for time in timelist @syncData(course, time, response) response( Moodle.response().success, Moodle.response().sync_dates, timelist.length ) error: -> response( console.log 'erro no ajax da syncDates' Moodle.response().sync_no_moodle_access, Moodle.response().sync_dates ) ) @ # Analisar esta função - download csv syncData: (course, time, response) -> ''' Acho que oq posso fazer aqui é achar o curso equivalente que foi chamado com a função e em seguida procurar no html da pagina o .csv que foi submetido localmente ''' # Criar um parser que vai encontrar os cursos que foram achados na sessão atual console.log 'entrou na syncData' parser = new DOMParser() doc = parser.parseFromString(@html, 'text/html') coursesCrawled = $('ul > li > label', doc) for item in coursesCrawled # []preciso saber oq é esse course para comparar os nomes if item.textContent == course.course # preciso achar o .csv e jogar para dentro da data data = @processRaw(course, time, data, 'csv') else console.log '404 - not found' ''' $.ajax( url: @url + '/report/log/' data: id: course.id date: time chooselog: 1 logformat: 'downloadascsv' download: 'csv' lang: 'en' success: (data, textStatus, request) => type = request.getResponseHeader('content-type') if /application\/download/.test(type) @processRaw(course, time, data, 'tsv') else if /text\/tab-separated-values/.test(type) if data.length > 0 @processRaw(course, time, data, 'tsv') else if /text\/csv/.test(type) if data.length > 0 @processRaw(course, time, data, 'csv') else if data.length > 0 course.errors.push(time) return response( Moodle.response().sync_no_moodle_access, Moodle.response().sync_data ) response( Moodle.response().success, Moodle.response().sync_data ) error: (request) -> if request.status >= 400 return response( Moodle.response().success, Moodle.response().sync_data ); course.errors.push(time) response( Moodle.response().sync_no_moodle_access, Moodle.response().sync_data ) ) @ ''' # [ ] Arranjar uma maneira de trazer os logs para esta funçao processRaw: (course, time, data, type) -> realtime = time * 1000 console.log 'AAAAA: Testando: ' + course + ' -- AND --> ' + course.course logs = data.replace(/\"Saved\sat\:(.+)\s/, '') unless course.logs course.logs = {} course.logs[realtime] = d3[type].parse(logs) users = {} # aqui pra baixo já tem os logs for row in course.logs[realtime] username = (row['User full name'] || row['Nome completo']).trim() unless users[username] users[username] = [] users[username].push(row) for user, rows of users es = @getUser(course, user) if es.length for e in es unless e.data e.data = {} e.data[realtime] = @processRow(rows, realtime) else course.users_not_found[user] = Date.now() @ processRow: (rows, realtime) -> data = {} for row in rows action = (row['Event name'] || row['Action'] || row['Nome do evento']) eventname = action.split(/\s\(/)?[0].trim() eventcontext = ( row['Event context'] || row['Contexto do Evento'] || action.split(/\s\(/)?[1].slice(0, -1) ).trim() component = (row['Component'] || row['Componente'] || action.split(/\s/)?[0]).trim() if component.toLowerCase() == 'logs' continue description = (row['Description'] || row['Information'] || row['Descrição']) if description description = description.trim() hour = /([0-9]{1,2}:[0-9]{1,2})(\s(A|P)M)?/.exec((row['Time'] || row['Hora']).toUpperCase())[0] date = new Date(realtime).toISOString().split(/T/)[0] time = Date.parse(date + ' ' + hour) - Date.parse(date) unless data[component] data[component] = {} unless data[component][eventname] data[component][eventname] = {} unless data[component][eventname][eventcontext] data[component][eventname][eventcontext] = {} unless data[component][eventname][eventcontext][description] data[component][eventname][eventcontext][description] = {} unless data[component][eventname][eventcontext][description][time] data[component][eventname][eventcontext][description][time] = 0 data[component][eventname][eventcontext][description][time]++ data setDefaultLang: -> $.ajax( url: @url data: lang: @lang method: 'HEAD' ) @ getSessKey: (response) -> $.ajax( url: @url success: (data, textStatus, request) -> parser = new DOMParser() doc = parser.parseFromString(data, 'text/html') sesskey = /"sesskey":"([^"]*)/.exec($('head', doc).html()) if sesskey && sesskey.length > 1 && sesskey[1] return response(sesskey[1]) response() error: -> response() ) @ sendMessageToUser: (user, message, sesskey, response) -> $.ajax( url: @url + '/message/index.php' data: id: user message: message sesskey: sesskey _qf__send_form: 1 submitbutton: 'send' method: 'POST' success: (data, textStatus, request) -> response() error: -> response() ) @ getCourseIndex: (name) -> for course, i in @courses if name == course.name return i setCourse: (id) -> for course, i in @courses course.selected = (i == id) @ setUser: (role, user, selected) -> users = @getCourse().users[role].list users[user].selected = selected @ setUsersAll: (role) -> users = @getCourse().users[role].list for user in users user.selected = true @ setUsersInvert: (role) -> users = @getCourse().users[role].list for user in users user.selected = !user.selected @ setDates: (dates) -> @getCourse().dates = dates @ upLastAccess: -> @last_sync = Date.now() @ upLastSync: -> @getCourse().last_sync = Date.now() @ select: (url) -> @selected = @equals(url) && @hasUsers() @ ''' $('#thefile').change (e) -> if e.target.files != undefined reader = new FileReader reader.onload = (e) -> $('#text').text e.target.result return reader.readAsText e.target.files.item(0) false ''' ''' getLocalLogs: (course) -> continue ''' getActivities: (role) -> unless @hasData() return course = @getCourse() data = {} for user, userid in course.users[role].list if user.data for day, components of user.data for component, eventnames of components for eventname, eventcontexts of eventnames for eventcontext, descriptions of eventcontexts for description, hours of descriptions page = eventcontext if /^http/.test(page) page = description event = eventname + ' (' + eventcontext + ')' unless data[event] data[event] = page: page event: eventname data getAssignments: () -> unless @hasData() return course = @getCourse() data = {} assings = {} for role, roleid in course.users for user, userid in role.list if user.data for day, components of user.data for component, eventnames of components for eventname, eventcontexts of eventnames for eventcontext, descriptions of eventcontexts for description, hours of descriptions page = eventcontext if /^http/.test(page) page = description if /^assign/.test(eventname) || /^assign/.test(page.toLowerCase()) unless data[roleid] data[roleid] = data: [] events: {} unless data[roleid].events[eventname] data[roleid].events[eventname] = 0 data[roleid].events[eventname]++ data[roleid].data.push( user: user.name page: page event: eventname context: eventcontext description: description component: component ) data getLogs: -> course = @getCourse() # [ ] checar se este unless vai bugar com a remoção da sync console.log 'rodando funçao getLogs' unless course.logs && Object.keys(course.logs).length console.log 'entrou no unless do getLOGS' return days = Object.keys(course.logs).sort((a, b) -> a = parseInt(a) b = parseInt(b) if a > b return -1 if a < b return 1 return 0 ) logs = [] for day in days logs = logs.concat(course.logs[day]) logs getCourseData: -> unless @hasData() return @getCourse() getTitle: -> @title getURL: -> @url # retorna o objeto curso que foi clicado no dashborad getCourse: -> for course in @courses if course.selected return course getCourseList: -> for course in @courses name: course.name selected: course.selected getRoles: -> for role in @getCourse().users console.log '--> getRoles: a role é: ' + role console.log '--> getRoles: a role.role é: ' + role.role name: role.role getUser: (course, username) -> list = [] for role in course.users for user in role.list if user.name == username list.push(user) list getUsers: -> roles = @getRoles() for role, i in roles console.log '--> getUsers(moodle): entrou no for de roles' role.users = [] for user in @getCourse().users[i].list console.log '--> getUsers(moodle): entrou no for de users' role.users.push( id: user.id picture: user.picture email: user.email name: PI:NAME:<NAME>END_PI.name firstname: user.firstname lastname: user.lastname selected: user.selected ) roles getUsersNotFound: -> course = @getCourse() if course.users_not_found Object.keys(course.users_not_found) else [] getDates: -> @getCourse().dates getLastAccess: -> @last_sync || 0 getLastSync: -> @getCourse().last_sync || 0 hasCourses: -> @courses? hasUsers: -> unless @hasCourses() return false @getCourse().users.length > 0 hasDates: -> unless @hasCourses() console.log '--> hasDates: retornou false' return false #no final de dates tinha um sinal de ?, tirei pois não sabia oq faz @getCourse().dates hasErrors: -> unless @hasCourses() return false @getCourse().errors.length > 0 hasData: -> #old code below #@hasDates() && @getLastSync() > 0 @hasDates() > 0 isSelected: -> @selected equals: (url) -> @url == url toString: -> JSON.stringify(@) parse: (str) -> JSON.parse(str) clone: (obj) -> JSON.parse(JSON.stringify(obj)) @response: -> success: 'SUCCESS' sync_no_moodle_access: 'SYNC_NO_MOODLE_ACCESS' sync_no_courses: 'SYNC_NO_COURSES' sync_no_users: 'SYNC_NO_USERS' sync_no_dates: 'SYNC_NO_DATES' sync_no_data: 'SYNC_NO_DATA' sync_courses: 'SYNC_COURSES' sync_users: 'SYNC_USERS' sync_dates: 'SYNC_DATES' sync_data: 'SYNC_DATA' @Moodle = Moodle
[ { "context": "rap: true\n \"exception-reporting\":\n userId: \"ff26a91b-7a0f-442f-bb67-1e3ac881f968\"\n \"linter-ui-default\":\n panelHeight: 81\n \"tr", "end": 450, "score": 0.5744253396987915, "start": 416, "tag": "PASSWORD", "value": "26a91b-7a0f-442f-bb67-1e3ac881f968" } ]
atom/config.cson
rashedInt32/dotfiles
0
"*": "autocomplete-python": useKite: false core: disabledPackages: [ "autocomplete-paths" "rainbow-tree" ] telemetryConsent: "no" themes: [ "atom-material-ui" "one-dark-syntax" ] editor: fontFamily: "Dank Mono" fontSize: 17 scrollPastEnd: true showLineNumbers: false softTabs: false softWrap: true "exception-reporting": userId: "ff26a91b-7a0f-442f-bb67-1e3ac881f968" "linter-ui-default": panelHeight: 81 "tree-view": {} "vim-mode-plus": {} welcome: showOnStartup: false
107303
"*": "autocomplete-python": useKite: false core: disabledPackages: [ "autocomplete-paths" "rainbow-tree" ] telemetryConsent: "no" themes: [ "atom-material-ui" "one-dark-syntax" ] editor: fontFamily: "Dank Mono" fontSize: 17 scrollPastEnd: true showLineNumbers: false softTabs: false softWrap: true "exception-reporting": userId: "ff<PASSWORD>" "linter-ui-default": panelHeight: 81 "tree-view": {} "vim-mode-plus": {} welcome: showOnStartup: false
true
"*": "autocomplete-python": useKite: false core: disabledPackages: [ "autocomplete-paths" "rainbow-tree" ] telemetryConsent: "no" themes: [ "atom-material-ui" "one-dark-syntax" ] editor: fontFamily: "Dank Mono" fontSize: 17 scrollPastEnd: true showLineNumbers: false softTabs: false softWrap: true "exception-reporting": userId: "ffPI:PASSWORD:<PASSWORD>END_PI" "linter-ui-default": panelHeight: 81 "tree-view": {} "vim-mode-plus": {} welcome: showOnStartup: false
[ { "context": "# @Author: Grégoire Puget <gregoirepuget>\n# @Date: 2017-02-10T11:04:04+01", "end": 25, "score": 0.9998684525489807, "start": 11, "tag": "NAME", "value": "Grégoire Puget" }, { "context": "# @Author: Grégoire Puget <gregoirepuget>\n# @Date: 2017-02-10T11:04:04+01:00\...
snippets/snippets.cson
gregoirepuget/36pixelspackage
0
# @Author: Grégoire Puget <gregoirepuget> # @Date: 2017-02-10T11:04:04+01:00 # @Email: gregoire@36pixels.fr # @Project: firstpixel # @Filename: snippets.cson # @Last modified by: gregoirepuget # @Last modified time: 2017-10-05T01:35:53+02:00 # @Copyright: All rights reserved 36 Pixels # Your snippets # # Atom snippets allow you to enter a simple prefix in the editor and hit tab to # expand the prefix into a larger code block with templated values. # # You can create a new snippet in this file by typing "snip" and then hitting # tab. # # An example CoffeeScript snippet to expand log to console.log: # # '.source.coffee': # 'Console log': # 'prefix': 'log' # 'body': 'console.log $1' # # Each scope (e.g. '.source.coffee' above) can only be declared once. # # This file uses CoffeeScript Object Notation (CSON). # If you are unfamiliar with CSON, you can read more about it in the # Atom Flight Manual: # http://flight-manual.atom.io/using-atom/sections/basic-customization/#_cson '.source.css': 'WordPress Create Theme': 'prefix': 'fp_create_theme' 'body' : ' /*\n Theme Name: $1\n Author: $2\n Author URI: $3\n Description: $4\n */' '.text.php': 'WordPress create header.php': 'prefix': 'fp_header.php' 'body': """ <!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( \'charset\' ); ?>" /> <!-- Appel du fichier style.css de notre thème --> <link rel="stylesheet" href="<?php bloginfo(\'stylesheet_url\'); ?>"> <!-- Tout le contenu de la partie head de mon site --> <!-- Execution de la fonction wp_head() obligatoire ! --> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <header id="header"> <!-- Tout le contenu de l entête de mon site --> </header>""" 'WordPress create footer.php': 'prefix': 'fp_footer.php' 'body': """ <footer id="footer"> <!-- Tout le contenu de la partie head de mon site --> </footer> <!-- Execution de la fonction wp_footer() obligatoire ! --> <?php wp_footer(); ?> </body> </html> """ 'WordPress create index.php': 'prefix': 'fp_index.php' 'body': """ <?php get_header(); //appel du template header.php ?> <div id="content"> <h1>Contenu Principal</h1> <?php // boucle WordPress if (have_posts()){ while (have_posts()){ the_post(); ?> <h1><?php the_title(); ?></h1> <h2>Posté le <?php the_time('F jS, Y') ?></h2> <p><?php the_content(); ?></p> <?php } } else { ?> Nous n'avons pas trouvé d'article répondant à votre recherche <?php } ?> </div> <!-- /content --> <?php get_footer(); //appel du template footer.php ?> """ 'WordPress create basic loop': 'prefix': 'fp_loop_basic' 'body': """ <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <div class="post"> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <small><?php the_time('F jS, Y'); ?></small> <div class="entry"> <?php the_content(); ?> </div> <p class="postmetadata">Posted in <?php the_category(', '); ?></p> </div> <!-- fin du premier bloc div --> <?php endwhile; else: ?> <p>Sorry, no posts matched your criteria.</p> <?php endif; ?>""" 'WordPress create hook': 'prefix': 'fp_hook' 'body': """ add_action('$1', '$2',$3); function $2(){ echo '<!-- Je suis un commentaire -->'; }"""
182875
# @Author: <NAME> <gregoirepuget> # @Date: 2017-02-10T11:04:04+01:00 # @Email: <EMAIL> # @Project: firstpixel # @Filename: snippets.cson # @Last modified by: gregoirepuget # @Last modified time: 2017-10-05T01:35:53+02:00 # @Copyright: All rights reserved 36 Pixels # Your snippets # # Atom snippets allow you to enter a simple prefix in the editor and hit tab to # expand the prefix into a larger code block with templated values. # # You can create a new snippet in this file by typing "snip" and then hitting # tab. # # An example CoffeeScript snippet to expand log to console.log: # # '.source.coffee': # 'Console log': # 'prefix': 'log' # 'body': 'console.log $1' # # Each scope (e.g. '.source.coffee' above) can only be declared once. # # This file uses CoffeeScript Object Notation (CSON). # If you are unfamiliar with CSON, you can read more about it in the # Atom Flight Manual: # http://flight-manual.atom.io/using-atom/sections/basic-customization/#_cson '.source.css': 'WordPress Create Theme': 'prefix': 'fp_create_theme' 'body' : ' /*\n Theme Name: $1\n Author: $2\n Author URI: $3\n Description: $4\n */' '.text.php': 'WordPress create header.php': 'prefix': 'fp_header.php' 'body': """ <!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( \'charset\' ); ?>" /> <!-- Appel du fichier style.css de notre thème --> <link rel="stylesheet" href="<?php bloginfo(\'stylesheet_url\'); ?>"> <!-- Tout le contenu de la partie head de mon site --> <!-- Execution de la fonction wp_head() obligatoire ! --> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <header id="header"> <!-- Tout le contenu de l entête de mon site --> </header>""" 'WordPress create footer.php': 'prefix': 'fp_footer.php' 'body': """ <footer id="footer"> <!-- Tout le contenu de la partie head de mon site --> </footer> <!-- Execution de la fonction wp_footer() obligatoire ! --> <?php wp_footer(); ?> </body> </html> """ 'WordPress create index.php': 'prefix': 'fp_index.php' 'body': """ <?php get_header(); //appel du template header.php ?> <div id="content"> <h1>Contenu Principal</h1> <?php // boucle WordPress if (have_posts()){ while (have_posts()){ the_post(); ?> <h1><?php the_title(); ?></h1> <h2>Posté le <?php the_time('F jS, Y') ?></h2> <p><?php the_content(); ?></p> <?php } } else { ?> Nous n'avons pas trouvé d'article répondant à votre recherche <?php } ?> </div> <!-- /content --> <?php get_footer(); //appel du template footer.php ?> """ 'WordPress create basic loop': 'prefix': 'fp_loop_basic' 'body': """ <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <div class="post"> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <small><?php the_time('F jS, Y'); ?></small> <div class="entry"> <?php the_content(); ?> </div> <p class="postmetadata">Posted in <?php the_category(', '); ?></p> </div> <!-- fin du premier bloc div --> <?php endwhile; else: ?> <p>Sorry, no posts matched your criteria.</p> <?php endif; ?>""" 'WordPress create hook': 'prefix': 'fp_hook' 'body': """ add_action('$1', '$2',$3); function $2(){ echo '<!-- Je suis un commentaire -->'; }"""
true
# @Author: PI:NAME:<NAME>END_PI <gregoirepuget> # @Date: 2017-02-10T11:04:04+01:00 # @Email: PI:EMAIL:<EMAIL>END_PI # @Project: firstpixel # @Filename: snippets.cson # @Last modified by: gregoirepuget # @Last modified time: 2017-10-05T01:35:53+02:00 # @Copyright: All rights reserved 36 Pixels # Your snippets # # Atom snippets allow you to enter a simple prefix in the editor and hit tab to # expand the prefix into a larger code block with templated values. # # You can create a new snippet in this file by typing "snip" and then hitting # tab. # # An example CoffeeScript snippet to expand log to console.log: # # '.source.coffee': # 'Console log': # 'prefix': 'log' # 'body': 'console.log $1' # # Each scope (e.g. '.source.coffee' above) can only be declared once. # # This file uses CoffeeScript Object Notation (CSON). # If you are unfamiliar with CSON, you can read more about it in the # Atom Flight Manual: # http://flight-manual.atom.io/using-atom/sections/basic-customization/#_cson '.source.css': 'WordPress Create Theme': 'prefix': 'fp_create_theme' 'body' : ' /*\n Theme Name: $1\n Author: $2\n Author URI: $3\n Description: $4\n */' '.text.php': 'WordPress create header.php': 'prefix': 'fp_header.php' 'body': """ <!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( \'charset\' ); ?>" /> <!-- Appel du fichier style.css de notre thème --> <link rel="stylesheet" href="<?php bloginfo(\'stylesheet_url\'); ?>"> <!-- Tout le contenu de la partie head de mon site --> <!-- Execution de la fonction wp_head() obligatoire ! --> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <header id="header"> <!-- Tout le contenu de l entête de mon site --> </header>""" 'WordPress create footer.php': 'prefix': 'fp_footer.php' 'body': """ <footer id="footer"> <!-- Tout le contenu de la partie head de mon site --> </footer> <!-- Execution de la fonction wp_footer() obligatoire ! --> <?php wp_footer(); ?> </body> </html> """ 'WordPress create index.php': 'prefix': 'fp_index.php' 'body': """ <?php get_header(); //appel du template header.php ?> <div id="content"> <h1>Contenu Principal</h1> <?php // boucle WordPress if (have_posts()){ while (have_posts()){ the_post(); ?> <h1><?php the_title(); ?></h1> <h2>Posté le <?php the_time('F jS, Y') ?></h2> <p><?php the_content(); ?></p> <?php } } else { ?> Nous n'avons pas trouvé d'article répondant à votre recherche <?php } ?> </div> <!-- /content --> <?php get_footer(); //appel du template footer.php ?> """ 'WordPress create basic loop': 'prefix': 'fp_loop_basic' 'body': """ <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <div class="post"> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <small><?php the_time('F jS, Y'); ?></small> <div class="entry"> <?php the_content(); ?> </div> <p class="postmetadata">Posted in <?php the_category(', '); ?></p> </div> <!-- fin du premier bloc div --> <?php endwhile; else: ?> <p>Sorry, no posts matched your criteria.</p> <?php endif; ?>""" 'WordPress create hook': 'prefix': 'fp_hook' 'body': """ add_action('$1', '$2',$3); function $2(){ echo '<!-- Je suis un commentaire -->'; }"""
[ { "context": "Test', (t) =>\n await t\n .typeText(nameInput, 'Peter')\n .typeText(nameInput, 'Paker', { replace: tr", "end": 232, "score": 0.9995134472846985, "start": 227, "tag": "NAME", "value": "Peter" }, { "context": "ext(nameInput, 'Peter')\n .typeText(nameInput, 'Pake...
test/fixture8.coffee
1600133971/testcafe-template
0
import { Selector } from 'testcafe' config = require('../config.json'); fixture `CoffeeScript Example` .page `${config.url}` nameInput = Selector '#developer-name' test 'Test', (t) => await t .typeText(nameInput, 'Peter') .typeText(nameInput, 'Paker', { replace: true }) .typeText(nameInput, 'r', { caretPos: 2 }) .expect(nameInput.value).eql 'Parker';
179950
import { Selector } from 'testcafe' config = require('../config.json'); fixture `CoffeeScript Example` .page `${config.url}` nameInput = Selector '#developer-name' test 'Test', (t) => await t .typeText(nameInput, '<NAME>') .typeText(nameInput, '<NAME>', { replace: true }) .typeText(nameInput, 'r', { caretPos: 2 }) .expect(nameInput.value).eql '<NAME>';
true
import { Selector } from 'testcafe' config = require('../config.json'); fixture `CoffeeScript Example` .page `${config.url}` nameInput = Selector '#developer-name' test 'Test', (t) => await t .typeText(nameInput, 'PI:NAME:<NAME>END_PI') .typeText(nameInput, 'PI:NAME:<NAME>END_PI', { replace: true }) .typeText(nameInput, 'r', { caretPos: 2 }) .expect(nameInput.value).eql 'PI:NAME:<NAME>END_PI';
[ { "context": "###\n Author Nick McCready\n Intersection of Objects if the arrays have so", "end": 28, "score": 0.9997189044952393, "start": 15, "tag": "NAME", "value": "Nick McCready" } ]
bower_components/angular-google-maps-init/src/coffee/extensions/lodash.coffee
aditioan/naturapass
2
### Author Nick McCready Intersection of Objects if the arrays have something in common each intersecting object will be returned in an new array. ### _.intersectionObjects = (array1, array2, comparison = undefined) -> res = _.map array1, (obj1) => _.find array2, (obj2) => if comparison? comparison(obj1, obj2) else _.isEqual(obj1, obj2) _.filter res, (o) -> o? # Determine if the array or object contains a given value (using `===`). #Aliased as `include`. _.containsObject = _.includeObject = (obj, target, comparison = undefined) -> if (obj == null) return false # if (nativeIndexOf && obj.indexOf == nativeIndexOf) # return obj.indexOf(target) != -1 _.any obj, (value) => if comparison? comparison value, target else _.isEqual value, target _.differenceObjects = (array1, array2, comparison = undefined) -> _.filter array1, (value) -> !_.containsObject array2, value, comparison #alias to differenceObjects _.withoutObjects = _.differenceObjects _.indexOfObject = (array, item, comparison, isSorted) -> return -1 unless array? i = 0 length = array.length if isSorted if typeof isSorted is "number" i = ((if isSorted < 0 then Math.max(0, length + isSorted) else isSorted)) else i = _.sortedIndex(array, item) return (if array[i] is item then i else -1) while i < length if comparison? return i if comparison array[i], item else return i if _.isEqual array[i], item i++ -1 #to easily inherit multiple objects _.extends=(arrayOfObjectsToCombine)-> _.reduce arrayOfObjectsToCombine,(combined,toAdd)-> _.extend(combined,toAdd) ,{}#starting point empty object _.isNullOrUndefined = (thing) -> _.isNull thing or _.isUndefined thing
115231
### Author <NAME> Intersection of Objects if the arrays have something in common each intersecting object will be returned in an new array. ### _.intersectionObjects = (array1, array2, comparison = undefined) -> res = _.map array1, (obj1) => _.find array2, (obj2) => if comparison? comparison(obj1, obj2) else _.isEqual(obj1, obj2) _.filter res, (o) -> o? # Determine if the array or object contains a given value (using `===`). #Aliased as `include`. _.containsObject = _.includeObject = (obj, target, comparison = undefined) -> if (obj == null) return false # if (nativeIndexOf && obj.indexOf == nativeIndexOf) # return obj.indexOf(target) != -1 _.any obj, (value) => if comparison? comparison value, target else _.isEqual value, target _.differenceObjects = (array1, array2, comparison = undefined) -> _.filter array1, (value) -> !_.containsObject array2, value, comparison #alias to differenceObjects _.withoutObjects = _.differenceObjects _.indexOfObject = (array, item, comparison, isSorted) -> return -1 unless array? i = 0 length = array.length if isSorted if typeof isSorted is "number" i = ((if isSorted < 0 then Math.max(0, length + isSorted) else isSorted)) else i = _.sortedIndex(array, item) return (if array[i] is item then i else -1) while i < length if comparison? return i if comparison array[i], item else return i if _.isEqual array[i], item i++ -1 #to easily inherit multiple objects _.extends=(arrayOfObjectsToCombine)-> _.reduce arrayOfObjectsToCombine,(combined,toAdd)-> _.extend(combined,toAdd) ,{}#starting point empty object _.isNullOrUndefined = (thing) -> _.isNull thing or _.isUndefined thing
true
### Author PI:NAME:<NAME>END_PI Intersection of Objects if the arrays have something in common each intersecting object will be returned in an new array. ### _.intersectionObjects = (array1, array2, comparison = undefined) -> res = _.map array1, (obj1) => _.find array2, (obj2) => if comparison? comparison(obj1, obj2) else _.isEqual(obj1, obj2) _.filter res, (o) -> o? # Determine if the array or object contains a given value (using `===`). #Aliased as `include`. _.containsObject = _.includeObject = (obj, target, comparison = undefined) -> if (obj == null) return false # if (nativeIndexOf && obj.indexOf == nativeIndexOf) # return obj.indexOf(target) != -1 _.any obj, (value) => if comparison? comparison value, target else _.isEqual value, target _.differenceObjects = (array1, array2, comparison = undefined) -> _.filter array1, (value) -> !_.containsObject array2, value, comparison #alias to differenceObjects _.withoutObjects = _.differenceObjects _.indexOfObject = (array, item, comparison, isSorted) -> return -1 unless array? i = 0 length = array.length if isSorted if typeof isSorted is "number" i = ((if isSorted < 0 then Math.max(0, length + isSorted) else isSorted)) else i = _.sortedIndex(array, item) return (if array[i] is item then i else -1) while i < length if comparison? return i if comparison array[i], item else return i if _.isEqual array[i], item i++ -1 #to easily inherit multiple objects _.extends=(arrayOfObjectsToCombine)-> _.reduce arrayOfObjectsToCombine,(combined,toAdd)-> _.extend(combined,toAdd) ,{}#starting point empty object _.isNullOrUndefined = (thing) -> _.isNull thing or _.isUndefined thing
[ { "context": "rage.getLocalStorageKeys()\n if key.indexOf('koding-editor') > -1\n delete global.localStorage[k", "end": 4577, "score": 0.6113534569740295, "start": 4571, "tag": "KEY", "value": "oding-" } ]
client/app/lib/localsynccontroller.coffee
ezgikaysi/koding
1
kd = require 'kd' async = require 'async' KDController = kd.Controller remote = require('./remote').getInstance() showError = require './util/showError' FSHelper = require './util/fs/fshelper' module.exports = class LocalSyncController extends KDController constructor: -> super @storage = kd.singletons.localStorageController.storage 'editor' @filesToSave = @storage.getValue('saveRequestedFiles') or [] @openedFiles = @storage.getValue('openedFiles') or [] # if @filesToSave.length > 0 # @syncLocalContentIfDiffExists (res)-> log "Synced" @initializeListeners() initializeListeners: -> remote.on 'reconnected', => return if @synStarted @synStarted = yes # @syncLocalContentIfDiffExists (err)=> # @synStarted = no # showError err if err syncLocalContentIfDiffExists: (callback) -> queue = @filesToSave.map (key) => (fin) => fsfile = FSHelper.createFileInstance { path: key } @patchFileIfDiffExist fsfile, @storage.getValue("OE-#{key}"), (res) -> fin() async.parallel queue, callback addToSaveArray: (file) -> fileName = FSHelper.getFullPath file index = @filesToSave.indexOf fileName @filesToSave.push fileName if index is -1 @storage.setValue 'saveRequestedFiles', @filesToSave @addSaveRequestTime file @initializeListeners() addSaveRequestTime: (file) -> path = FSHelper.getFullPath file @storage.setValue "#{path}-savetime", Date.now() isFileVersionOk: (file, lastUpdate) -> path = FSHelper.getFullPath file localTime = @storage.getValue "#{path}-savetime" dt = new Date lastUpdate if localTime > dt.getTime() return yes else @removeFileContentFromLocalStorage file @removeFromSaveArray file @storage.unsetKey "#{path}-savetime" return no removeFromSaveArray: (file) -> fileName = FSHelper.getFullPath file index = @filesToSave.indexOf fileName return unless index > -1 @filesToSave.splice index, 1 @storage.setValue 'saveRequestedFiles', @filesToSave patchFileIfDiffExist: (file, localContent, cb, callCounter = 0) -> kd.singletons.vmController.info file.vmName, kd.utils.getTimedOutCallback (err, vm, info) => return cb err unless info.state is 'RUNNING' FSHelper.getInfo file.path, file.vmName, (err, info) => return showError err if err return unless @isFileVersionOk file, info.time file.fetchContents (err, content) => if content and not err unless content is localContent file.save localContent, (err, res) => return cb err if err @removeFromSaveArray file @removeFileContentFromLocalStorage file @updateEditorStatus file, localContent @emit 'LocalContentSynced', file cb null, file else @removeFromSaveArray file cb null, file , => ++callCounter if callCounter > 5 @emit 'LocalContentCouldntSynced', file else @patchFileIfDiffExist file, localContent, cb, callCounter updateFileContentOnLocalStorage: (file, content) -> fileName = FSHelper.getFullPath file @storage.setValue "OE-#{fileName}", content removeFileContentFromLocalStorage: (file) -> fileName = FSHelper.getFullPath file @storage.unsetKey "OE-#{fileName}" addToOpenedFiles: (fileName) -> machineUid = FSHelper.getUidFromPath fileName index = @openedFiles.indexOf fileName if index is -1 and machineUid @openedFiles.push fileName @storage.setValue 'openedFiles', @openedFiles removeFromOpenedFiles: (file) -> fileName = FSHelper.getFullPath file index = @openedFiles.indexOf fileName return if index is -1 @openedFiles.splice index, 1 @storage.setValue 'openedFiles', @openedFiles @removeFromSaveArray file @removeFileContentFromLocalStorage file getRecentOpenedFiles: -> @openedFiles updateEditorStatus: (file, lastSavedContent) -> fileName = FSHelper.getFullPath file # get current AceViews aceAppView = kd.singletons.appManager.get('Ace').getView() { ace } = aceAppView.aceViews[fileName] ace.lastSavedContents = lastSavedContent unless ace.getContents() is lastSavedContent ace.emit 'FileContentChanged' else ace.emit 'FileContentRestored' removeLocalContents: -> for key in @storage.getLocalStorageKeys() if key.indexOf('koding-editor') > -1 delete global.localStorage[key]
12362
kd = require 'kd' async = require 'async' KDController = kd.Controller remote = require('./remote').getInstance() showError = require './util/showError' FSHelper = require './util/fs/fshelper' module.exports = class LocalSyncController extends KDController constructor: -> super @storage = kd.singletons.localStorageController.storage 'editor' @filesToSave = @storage.getValue('saveRequestedFiles') or [] @openedFiles = @storage.getValue('openedFiles') or [] # if @filesToSave.length > 0 # @syncLocalContentIfDiffExists (res)-> log "Synced" @initializeListeners() initializeListeners: -> remote.on 'reconnected', => return if @synStarted @synStarted = yes # @syncLocalContentIfDiffExists (err)=> # @synStarted = no # showError err if err syncLocalContentIfDiffExists: (callback) -> queue = @filesToSave.map (key) => (fin) => fsfile = FSHelper.createFileInstance { path: key } @patchFileIfDiffExist fsfile, @storage.getValue("OE-#{key}"), (res) -> fin() async.parallel queue, callback addToSaveArray: (file) -> fileName = FSHelper.getFullPath file index = @filesToSave.indexOf fileName @filesToSave.push fileName if index is -1 @storage.setValue 'saveRequestedFiles', @filesToSave @addSaveRequestTime file @initializeListeners() addSaveRequestTime: (file) -> path = FSHelper.getFullPath file @storage.setValue "#{path}-savetime", Date.now() isFileVersionOk: (file, lastUpdate) -> path = FSHelper.getFullPath file localTime = @storage.getValue "#{path}-savetime" dt = new Date lastUpdate if localTime > dt.getTime() return yes else @removeFileContentFromLocalStorage file @removeFromSaveArray file @storage.unsetKey "#{path}-savetime" return no removeFromSaveArray: (file) -> fileName = FSHelper.getFullPath file index = @filesToSave.indexOf fileName return unless index > -1 @filesToSave.splice index, 1 @storage.setValue 'saveRequestedFiles', @filesToSave patchFileIfDiffExist: (file, localContent, cb, callCounter = 0) -> kd.singletons.vmController.info file.vmName, kd.utils.getTimedOutCallback (err, vm, info) => return cb err unless info.state is 'RUNNING' FSHelper.getInfo file.path, file.vmName, (err, info) => return showError err if err return unless @isFileVersionOk file, info.time file.fetchContents (err, content) => if content and not err unless content is localContent file.save localContent, (err, res) => return cb err if err @removeFromSaveArray file @removeFileContentFromLocalStorage file @updateEditorStatus file, localContent @emit 'LocalContentSynced', file cb null, file else @removeFromSaveArray file cb null, file , => ++callCounter if callCounter > 5 @emit 'LocalContentCouldntSynced', file else @patchFileIfDiffExist file, localContent, cb, callCounter updateFileContentOnLocalStorage: (file, content) -> fileName = FSHelper.getFullPath file @storage.setValue "OE-#{fileName}", content removeFileContentFromLocalStorage: (file) -> fileName = FSHelper.getFullPath file @storage.unsetKey "OE-#{fileName}" addToOpenedFiles: (fileName) -> machineUid = FSHelper.getUidFromPath fileName index = @openedFiles.indexOf fileName if index is -1 and machineUid @openedFiles.push fileName @storage.setValue 'openedFiles', @openedFiles removeFromOpenedFiles: (file) -> fileName = FSHelper.getFullPath file index = @openedFiles.indexOf fileName return if index is -1 @openedFiles.splice index, 1 @storage.setValue 'openedFiles', @openedFiles @removeFromSaveArray file @removeFileContentFromLocalStorage file getRecentOpenedFiles: -> @openedFiles updateEditorStatus: (file, lastSavedContent) -> fileName = FSHelper.getFullPath file # get current AceViews aceAppView = kd.singletons.appManager.get('Ace').getView() { ace } = aceAppView.aceViews[fileName] ace.lastSavedContents = lastSavedContent unless ace.getContents() is lastSavedContent ace.emit 'FileContentChanged' else ace.emit 'FileContentRestored' removeLocalContents: -> for key in @storage.getLocalStorageKeys() if key.indexOf('k<KEY>editor') > -1 delete global.localStorage[key]
true
kd = require 'kd' async = require 'async' KDController = kd.Controller remote = require('./remote').getInstance() showError = require './util/showError' FSHelper = require './util/fs/fshelper' module.exports = class LocalSyncController extends KDController constructor: -> super @storage = kd.singletons.localStorageController.storage 'editor' @filesToSave = @storage.getValue('saveRequestedFiles') or [] @openedFiles = @storage.getValue('openedFiles') or [] # if @filesToSave.length > 0 # @syncLocalContentIfDiffExists (res)-> log "Synced" @initializeListeners() initializeListeners: -> remote.on 'reconnected', => return if @synStarted @synStarted = yes # @syncLocalContentIfDiffExists (err)=> # @synStarted = no # showError err if err syncLocalContentIfDiffExists: (callback) -> queue = @filesToSave.map (key) => (fin) => fsfile = FSHelper.createFileInstance { path: key } @patchFileIfDiffExist fsfile, @storage.getValue("OE-#{key}"), (res) -> fin() async.parallel queue, callback addToSaveArray: (file) -> fileName = FSHelper.getFullPath file index = @filesToSave.indexOf fileName @filesToSave.push fileName if index is -1 @storage.setValue 'saveRequestedFiles', @filesToSave @addSaveRequestTime file @initializeListeners() addSaveRequestTime: (file) -> path = FSHelper.getFullPath file @storage.setValue "#{path}-savetime", Date.now() isFileVersionOk: (file, lastUpdate) -> path = FSHelper.getFullPath file localTime = @storage.getValue "#{path}-savetime" dt = new Date lastUpdate if localTime > dt.getTime() return yes else @removeFileContentFromLocalStorage file @removeFromSaveArray file @storage.unsetKey "#{path}-savetime" return no removeFromSaveArray: (file) -> fileName = FSHelper.getFullPath file index = @filesToSave.indexOf fileName return unless index > -1 @filesToSave.splice index, 1 @storage.setValue 'saveRequestedFiles', @filesToSave patchFileIfDiffExist: (file, localContent, cb, callCounter = 0) -> kd.singletons.vmController.info file.vmName, kd.utils.getTimedOutCallback (err, vm, info) => return cb err unless info.state is 'RUNNING' FSHelper.getInfo file.path, file.vmName, (err, info) => return showError err if err return unless @isFileVersionOk file, info.time file.fetchContents (err, content) => if content and not err unless content is localContent file.save localContent, (err, res) => return cb err if err @removeFromSaveArray file @removeFileContentFromLocalStorage file @updateEditorStatus file, localContent @emit 'LocalContentSynced', file cb null, file else @removeFromSaveArray file cb null, file , => ++callCounter if callCounter > 5 @emit 'LocalContentCouldntSynced', file else @patchFileIfDiffExist file, localContent, cb, callCounter updateFileContentOnLocalStorage: (file, content) -> fileName = FSHelper.getFullPath file @storage.setValue "OE-#{fileName}", content removeFileContentFromLocalStorage: (file) -> fileName = FSHelper.getFullPath file @storage.unsetKey "OE-#{fileName}" addToOpenedFiles: (fileName) -> machineUid = FSHelper.getUidFromPath fileName index = @openedFiles.indexOf fileName if index is -1 and machineUid @openedFiles.push fileName @storage.setValue 'openedFiles', @openedFiles removeFromOpenedFiles: (file) -> fileName = FSHelper.getFullPath file index = @openedFiles.indexOf fileName return if index is -1 @openedFiles.splice index, 1 @storage.setValue 'openedFiles', @openedFiles @removeFromSaveArray file @removeFileContentFromLocalStorage file getRecentOpenedFiles: -> @openedFiles updateEditorStatus: (file, lastSavedContent) -> fileName = FSHelper.getFullPath file # get current AceViews aceAppView = kd.singletons.appManager.get('Ace').getView() { ace } = aceAppView.aceViews[fileName] ace.lastSavedContents = lastSavedContent unless ace.getContents() is lastSavedContent ace.emit 'FileContentChanged' else ace.emit 'FileContentRestored' removeLocalContents: -> for key in @storage.getLocalStorageKeys() if key.indexOf('kPI:KEY:<KEY>END_PIeditor') > -1 delete global.localStorage[key]
[ { "context": "4 chars', (done) ->\n\t\t\trs.get {app: app1, token: \"lsdkjfslkfjsldfkj\"}, (err, resp) ->\n\t\t\t\terr.message.should.equal(\"I", "end": 1207, "score": 0.6082313060760498, "start": 1190, "tag": "PASSWORD", "value": "lsdkjfslkfjsldfkj" }, { "context": "4 chars', (done)...
Server/node_modules/redis-sessions/test/test.coffee
jinMaoHuiHui/WhiteBoard
0
_ = require "lodash" should = require "should" async = require "async" RedisSessions = require "../index" describe 'Redis-Sessions Test', -> rs = null app1 = "test" app2 = "TEST" token1 = null token2 = null token3 = null token4 = null bulksessions = [] before (done) -> done() return after (done) -> done() return it 'get a RedisSessions instance', (done) -> rs = new RedisSessions() rs.should.be.an.instanceOf RedisSessions done() return describe 'GET: Part 1', -> it 'Get a Session with invalid app format: no app supplied', (done) -> rs.get {}, (err, resp) -> err.message.should.equal("No app supplied") done() return return it 'Get a Session with invalid app format: too short', (done) -> rs.get {app: "a"}, (err, resp) -> err.message.should.equal("Invalid app format") done() return return it 'Get a Session with invalid token format: no token at all', (done) -> rs.get {app: app1}, (err, resp) -> err.message.should.equal("No token supplied") done() return return it 'Get a Session with invalid token format: token shorter than 64 chars', (done) -> rs.get {app: app1, token: "lsdkjfslkfjsldfkj"}, (err, resp) -> err.message.should.equal("Invalid token format") done() return return it 'Get a Session with invalid token format: token longer than 64 chars', (done) -> rs.get {app: app1, token: "0123456789012345678901234567890123456789012345678901234567890123456789"}, (err, resp) -> err.message.should.equal("Invalid token format") done() return return it 'Get a Session with invalid token format: token with invalid character', (done) -> rs.get {app: app1, token: "!123456789012345678901234567890123456789012345678901234567891234"}, (err, resp) -> err.message.should.equal("Invalid token format") done() return return it 'Get a Session with valid token format but token should not exist', (done) -> rs.get {app: app1, token: "0123456789012345678901234567890123456789012345678901234567891234"}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('id') done() return return return describe 'CREATE: Part 1', -> it 'Create a session with invalid data: no app supplied', (done) -> rs.create {}, (err, resp) -> err.message.should.equal("No app supplied") done() return return it 'Create a session with invalid data: no id supplied', (done) -> rs.create {app: app1}, (err, resp) -> err.message.should.equal("No id supplied") done() return return it 'Create a session with invalid data: no ip supplied', (done) -> rs.create {app: app1, id:"user1"}, (err, resp) -> err.message.should.equal("No ip supplied") done() return return it 'Create a session with invalid data: Longer than 39 chars ip supplied', (done) -> rs.create {app: app1, id:"user1", ip:"1234567890123456789012345678901234567890"}, (err, resp) -> err.message.should.equal("Invalid ip format") done() return return it 'Create a session with invalid data: zero length ip supplied', (done) -> rs.create {app: app1, id:"user1", ip:""}, (err, resp) -> err.message.should.equal("No ip supplied") done() return return it 'Create a session with invalid data: ttl too short', (done) -> rs.create {app: app1, id:"user1", ip: "127.0.0.1", ttl: 4}, (err, resp) -> err.message.should.equal("ttl must be a positive integer >= 10") done() return return it 'Create a session with valid data: should return a token', (done) -> rs.create {app: app1, id:"user1", ip: "127.0.0.1", ttl: 30}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') token1 = resp.token done() return return it 'Activity should show 1 user', (done) -> rs.activity {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(1) done() return return it 'Create another session for user1: should return a token', (done) -> rs.create {app: app1, id:"user1", ip: "127.0.0.2", ttl: 30}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') done() return return it 'Create yet another session for user1 with a `d` object: should return a token', (done) -> rs.create {app: app1, id:"user1", ip: "127.0.0.2", ttl: 30, d:{"foo":"bar","nu":null,"hi":123,"lo":-123,"boo":true,"boo2":false}}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') token4 = resp.token done() return return it 'Create yet another session for user1 with an invalid `d` object: should return a token', (done) -> rs.create {app: app1, id:"user1", ip: "2001:0000:1234:0000:0000:C1C0:ABCD:0876", ttl: 30, d:{"inv":[]}}, (err, resp) -> should.not.exist(resp) should.exist(err) done() return return it 'Create yet another session for user1 with an invalid `d` object: should return a token', (done) -> rs.create {app: app1, id:"user1", ip: "2001:0000:1234:0000:0000:C1C0:ABCD:0876", ttl: 30, d:{}}, (err, resp) -> should.not.exist(resp) should.exist(err) done() return return it 'Activity should STILL show 1 user', (done) -> rs.activity {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(1) done() return return it 'Create another session with valid data: should return a token', (done) -> rs.create {app: app1, id:"user2", ip: "127.0.0.1", ttl: 10}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') token2 = resp.token done() return return it 'Activity should show 2 users', (done) -> rs.activity {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(2) done() return return it 'Sessions of App should return 4 users', (done) -> rs.soapp {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('sessions') resp.sessions.length.should.equal(4) done() return return it 'Create a session for another app with valid data: should return a token', (done) -> rs.create {app: app2, id:"user1", ip: "127.0.0.1", ttl: 30}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') token3 = resp.token done() return return it 'Activity should show 1 user', (done) -> rs.activity {app: app2, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(1) done() return return it 'Create 1000 sessions for app2: succeed', (done) -> pq = [] for i in [0...1000] pq.push({app:app2, id: "bulkuser_" + i, ip:"127.0.0.1"}) async.map pq, rs.create, (err, resp) -> for e in resp e.should.have.keys('token') bulksessions.push(e.token) e.token.length.should.equal(64) done() return return it 'Activity should show 1001 user', (done) -> rs.activity {app: app2, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(1001) done() return return it 'Get 1000 sessions for app2: succeed', (done) -> pq = [] for e,i in bulksessions pq.push({app:app2, token: e}) async.map pq, rs.get, (err, resp) -> resp.length.should.equal(1000) for e,i in resp e.should.have.keys('id','r','w','ttl','idle','ip') e.id.should.equal("bulkuser_" + i) done() return return it 'Create a session for bulkuser_999 with valid data: should return a token', (done) -> rs.create {app: app2, id:"bulkuser_999", ip: "127.0.0.2", ttl: 30}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') done() return return it 'Check if we have 2 sessions for bulkuser_999', (done) -> rs.soid {app: app2, id: "bulkuser_999"}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('sessions') resp.sessions.length.should.equal(2) resp.sessions[0].id.should.equal("bulkuser_999") done() return return it 'Remove those 2 sessions for bulkuser_999', (done) -> rs.killsoid {app: app2, id: "bulkuser_999"}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('kill') resp.kill.should.equal(2) done() return return it 'Check if we have still have sessions for bulkuser_999: should return 0', (done) -> rs.soid {app: app2, id: "bulkuser_999"}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('sessions') resp.sessions.length.should.equal(0) done() return return return describe 'GET: Part 2', -> it 'Get the Session for token1: should work', ( done ) -> rs.get {app: app1, token: token1}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.have.keys('id','r','w','ttl','idle','ip') resp.id.should.equal("user1") resp.ttl.should.equal(30) done() return return it 'Get the Session for token1 again: should work', ( done ) -> rs.get {app: app1, token: token1}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.have.keys('id','r','w','ttl','idle','ip') resp.id.should.equal("user1") resp.ttl.should.equal(30) resp.r.should.equal(2) done() return return it 'Sessions of App should return 4 users', (done) -> rs.soapp {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('sessions') resp.sessions.length.should.equal(4) done() return return it 'Kill the Session for token1: should work', ( done ) -> rs.kill {app: app1, token: token1}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.have.keys('kill') resp.kill.should.equal(1) done() return return it 'Get the Session for token1: should fail', ( done ) -> rs.get {app: app1, token: token1}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('id') done() return return it 'Activity for app1 should show 2 users still', (done) -> rs.activity {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(2) done() return return it 'Get the Session for token2', ( done ) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.have.keys('id','r','w','ttl','idle','ip') resp.id.should.equal("user2") resp.ttl.should.equal(10) done() return return it 'Get the Session for token4', ( done ) -> rs.get {app: app1, token: token4}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.have.keys('id','r','w','ttl','idle','ip','d') resp.id.should.equal("user1") resp.ttl.should.equal(30) resp.d.foo.should.equal("bar") done() return return return describe 'SET', -> it 'Set some params for token1 with no d: should fail', ( done ) -> rs.set {app: app1, token: token1}, (err, resp) -> err.message.should.equal("No d supplied") done() return return it 'Set some params for token1 with d being an array', ( done ) -> rs.set {app: app1, token: token1, d:[12,"bla"]}, (err, resp) -> err.message.should.equal("d must be an object") done() return return it 'Set some params for token1 with d being a string: should fail', ( done ) -> rs.set {app: app1, token: token1, d:"someString"}, (err, resp) -> err.message.should.equal("d must be an object") done() return return it 'Set some params for token1 with forbidden type (array): should fail', ( done ) -> rs.set {app: app1, token: token1, d:{arr:[1,2,3]}}, (err, resp) -> err.message.should.equal("d.arr has a forbidden type. Only strings, numbers, boolean and null are allowed.") done() return return it 'Set some params for token1 with forbidden type (object): should fail', ( done ) -> rs.set {app: app1, token: token1, d:{obj:{bla:1}}}, (err, resp) -> err.message.should.equal("d.obj has a forbidden type. Only strings, numbers, boolean and null are allowed.") done() return return it 'Set some params for token1 with an empty object: should fail', ( done ) -> rs.set {app: app1, token: token1, d:{}}, (err, resp) -> err.message.should.equal("d must containt at least one key.") done() return return it 'Set some params for token1: should fail as token1 was killed', ( done ) -> rs.set {app: app1, token: token1, d:{str:"haha"}}, (err, resp) -> should.not.exist(err) resp.should.not.have.keys('id') done() return return it 'Set some params for token2: should work', ( done ) -> rs.set {app: app1, token: token2, d: {hi: "ho", count: 120, premium: true, nix:null }}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object done() return return it 'Get the session for token2: should work and contain new values', (done) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('hi','count','premium') done() return return it 'Remove a param from token2: should work', ( done ) -> rs.set {app: app1, token: token2, d: {hi: null}}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('count','premium') done() return return it 'Get the session for token2: should work and contain modified values', (done) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('count','premium') done() return return it 'Remove all remaining params from token2: should work', ( done ) -> rs.set {app: app1, token: token2, d: {count: null, premium: null}}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('d') done() return return it 'Get the session for token2: should work and not contain the d key', (done) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('d') done() return return it 'Remove all remaining params from token2 again: should work', ( done ) -> rs.set {app: app1, token: token2, d: {count: null, premium: null}}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('d') done() return return it 'Get the session for token2: should work and not contain the d key', (done) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('d') done() return return it 'Set some params for token2: should work', ( done ) -> rs.set {app: app1, token: token2, d: {a: "sometext", b: 20, c: true, d: false}}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('a','b','c','d') resp.d.a.should.equal("sometext") resp.d.b.should.equal(20) resp.d.c.should.equal(true) resp.d.d.should.equal(false) done() return return it 'Modify some params for token2: should work', ( done ) -> rs.set {app: app1, token: token2, d: {a: false, b: "some_text", c: 20, d: true, e:20.212}}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('a','b','c','d','e') resp.d.a.should.equal(false) resp.d.b.should.equal('some_text') resp.d.c.should.equal(20) resp.d.d.should.equal(true) resp.d.e.should.equal(20.212) done() return return it 'Get the params for token2: should work', ( done ) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('a','b','c','d','e') resp.d.a.should.equal(false) resp.d.b.should.equal('some_text') resp.d.c.should.equal(20) resp.d.d.should.equal(true) resp.d.e.should.equal(20.212) done() return return return describe 'CLEANUP', -> # Kill all tokens it 'Remove all sessions from app1', (done) -> rs.killall {app:app1}, (err, resp) -> should.exist(resp.kill) done() return return it 'Remove all sessions from app2', (done) -> rs.killall {app:app2}, (err, resp) -> should.exist(resp.kill) done() return return it 'Issue the Quit Command.', (done) -> rs.quit() done() return return return
183411
_ = require "lodash" should = require "should" async = require "async" RedisSessions = require "../index" describe 'Redis-Sessions Test', -> rs = null app1 = "test" app2 = "TEST" token1 = null token2 = null token3 = null token4 = null bulksessions = [] before (done) -> done() return after (done) -> done() return it 'get a RedisSessions instance', (done) -> rs = new RedisSessions() rs.should.be.an.instanceOf RedisSessions done() return describe 'GET: Part 1', -> it 'Get a Session with invalid app format: no app supplied', (done) -> rs.get {}, (err, resp) -> err.message.should.equal("No app supplied") done() return return it 'Get a Session with invalid app format: too short', (done) -> rs.get {app: "a"}, (err, resp) -> err.message.should.equal("Invalid app format") done() return return it 'Get a Session with invalid token format: no token at all', (done) -> rs.get {app: app1}, (err, resp) -> err.message.should.equal("No token supplied") done() return return it 'Get a Session with invalid token format: token shorter than 64 chars', (done) -> rs.get {app: app1, token: "<PASSWORD>"}, (err, resp) -> err.message.should.equal("Invalid token format") done() return return it 'Get a Session with invalid token format: token longer than 64 chars', (done) -> rs.get {app: app1, token: "<KEY>"}, (err, resp) -> err.message.should.equal("Invalid token format") done() return return it 'Get a Session with invalid token format: token with invalid character', (done) -> rs.get {app: app1, token: <KEY>"}, (err, resp) -> err.message.should.equal("Invalid token format") done() return return it 'Get a Session with valid token format but token should not exist', (done) -> rs.get {app: app1, token: "<KEY>"}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('id') done() return return return describe 'CREATE: Part 1', -> it 'Create a session with invalid data: no app supplied', (done) -> rs.create {}, (err, resp) -> err.message.should.equal("No app supplied") done() return return it 'Create a session with invalid data: no id supplied', (done) -> rs.create {app: app1}, (err, resp) -> err.message.should.equal("No id supplied") done() return return it 'Create a session with invalid data: no ip supplied', (done) -> rs.create {app: app1, id:"user1"}, (err, resp) -> err.message.should.equal("No ip supplied") done() return return it 'Create a session with invalid data: Longer than 39 chars ip supplied', (done) -> rs.create {app: app1, id:"user1", ip:"1234567890123456789012345678901234567890"}, (err, resp) -> err.message.should.equal("Invalid ip format") done() return return it 'Create a session with invalid data: zero length ip supplied', (done) -> rs.create {app: app1, id:"user1", ip:""}, (err, resp) -> err.message.should.equal("No ip supplied") done() return return it 'Create a session with invalid data: ttl too short', (done) -> rs.create {app: app1, id:"user1", ip: "127.0.0.1", ttl: 4}, (err, resp) -> err.message.should.equal("ttl must be a positive integer >= 10") done() return return it 'Create a session with valid data: should return a token', (done) -> rs.create {app: app1, id:"user1", ip: "127.0.0.1", ttl: 30}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') token1 = resp.token done() return return it 'Activity should show 1 user', (done) -> rs.activity {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(1) done() return return it 'Create another session for user1: should return a token', (done) -> rs.create {app: app1, id:"user1", ip: "127.0.0.2", ttl: 30}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') done() return return it 'Create yet another session for user1 with a `d` object: should return a token', (done) -> rs.create {app: app1, id:"user1", ip: "127.0.0.2", ttl: 30, d:{"foo":"bar","nu":null,"hi":123,"lo":-123,"boo":true,"boo2":false}}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') token4 = resp.token done() return return it 'Create yet another session for user1 with an invalid `d` object: should return a token', (done) -> rs.create {app: app1, id:"user1", ip: "2001:0000:1234:0000:0000:C1C0:ABCD:0876", ttl: 30, d:{"inv":[]}}, (err, resp) -> should.not.exist(resp) should.exist(err) done() return return it 'Create yet another session for user1 with an invalid `d` object: should return a token', (done) -> rs.create {app: app1, id:"user1", ip: "2001:0000:1234:0000:0000:C1C0:ABCD:0876", ttl: 30, d:{}}, (err, resp) -> should.not.exist(resp) should.exist(err) done() return return it 'Activity should STILL show 1 user', (done) -> rs.activity {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(1) done() return return it 'Create another session with valid data: should return a token', (done) -> rs.create {app: app1, id:"user2", ip: "127.0.0.1", ttl: 10}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') token2 = resp.token done() return return it 'Activity should show 2 users', (done) -> rs.activity {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(2) done() return return it 'Sessions of App should return 4 users', (done) -> rs.soapp {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('sessions') resp.sessions.length.should.equal(4) done() return return it 'Create a session for another app with valid data: should return a token', (done) -> rs.create {app: app2, id:"user1", ip: "127.0.0.1", ttl: 30}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') token3 = resp.token done() return return it 'Activity should show 1 user', (done) -> rs.activity {app: app2, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(1) done() return return it 'Create 1000 sessions for app2: succeed', (done) -> pq = [] for i in [0...1000] pq.push({app:app2, id: "bulkuser_" + i, ip:"127.0.0.1"}) async.map pq, rs.create, (err, resp) -> for e in resp e.should.have.keys('token') bulksessions.push(e.token) e.token.length.should.equal(64) done() return return it 'Activity should show 1001 user', (done) -> rs.activity {app: app2, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(1001) done() return return it 'Get 1000 sessions for app2: succeed', (done) -> pq = [] for e,i in bulksessions pq.push({app:app2, token: e}) async.map pq, rs.get, (err, resp) -> resp.length.should.equal(1000) for e,i in resp e.should.have.keys('id','r','w','ttl','idle','ip') e.id.should.equal("bulkuser_" + i) done() return return it 'Create a session for bulkuser_999 with valid data: should return a token', (done) -> rs.create {app: app2, id:"bulkuser_999", ip: "127.0.0.2", ttl: 30}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') done() return return it 'Check if we have 2 sessions for bulkuser_999', (done) -> rs.soid {app: app2, id: "bulkuser_999"}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('sessions') resp.sessions.length.should.equal(2) resp.sessions[0].id.should.equal("bulkuser_999") done() return return it 'Remove those 2 sessions for bulkuser_999', (done) -> rs.killsoid {app: app2, id: "bulkuser_999"}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('kill') resp.kill.should.equal(2) done() return return it 'Check if we have still have sessions for bulkuser_999: should return 0', (done) -> rs.soid {app: app2, id: "bulkuser_999"}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('sessions') resp.sessions.length.should.equal(0) done() return return return describe 'GET: Part 2', -> it 'Get the Session for token1: should work', ( done ) -> rs.get {app: app1, token: token1}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.have.keys('id','r','w','ttl','idle','ip') resp.id.should.equal("user1") resp.ttl.should.equal(30) done() return return it 'Get the Session for token1 again: should work', ( done ) -> rs.get {app: app1, token: token1}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.have.keys('id','r','w','ttl','idle','ip') resp.id.should.equal("user1") resp.ttl.should.equal(30) resp.r.should.equal(2) done() return return it 'Sessions of App should return 4 users', (done) -> rs.soapp {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('sessions') resp.sessions.length.should.equal(4) done() return return it 'Kill the Session for token1: should work', ( done ) -> rs.kill {app: app1, token: token1}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.have.keys('kill') resp.kill.should.equal(1) done() return return it 'Get the Session for token1: should fail', ( done ) -> rs.get {app: app1, token: token1}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('id') done() return return it 'Activity for app1 should show 2 users still', (done) -> rs.activity {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(2) done() return return it 'Get the Session for token2', ( done ) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.have.keys('id','r','w','ttl','idle','ip') resp.id.should.equal("user2") resp.ttl.should.equal(10) done() return return it 'Get the Session for token4', ( done ) -> rs.get {app: app1, token: token4}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.have.keys('id','r','w','ttl','idle','ip','d') resp.id.should.equal("user1") resp.ttl.should.equal(30) resp.d.foo.should.equal("bar") done() return return return describe 'SET', -> it 'Set some params for token1 with no d: should fail', ( done ) -> rs.set {app: app1, token: token1}, (err, resp) -> err.message.should.equal("No d supplied") done() return return it 'Set some params for token1 with d being an array', ( done ) -> rs.set {app: app1, token: token1, d:[12,"bla"]}, (err, resp) -> err.message.should.equal("d must be an object") done() return return it 'Set some params for token1 with d being a string: should fail', ( done ) -> rs.set {app: app1, token: token1, d:"someString"}, (err, resp) -> err.message.should.equal("d must be an object") done() return return it 'Set some params for token1 with forbidden type (array): should fail', ( done ) -> rs.set {app: app1, token: token1, d:{arr:[1,2,3]}}, (err, resp) -> err.message.should.equal("d.arr has a forbidden type. Only strings, numbers, boolean and null are allowed.") done() return return it 'Set some params for token1 with forbidden type (object): should fail', ( done ) -> rs.set {app: app1, token: token1, d:{obj:{bla:1}}}, (err, resp) -> err.message.should.equal("d.obj has a forbidden type. Only strings, numbers, boolean and null are allowed.") done() return return it 'Set some params for token1 with an empty object: should fail', ( done ) -> rs.set {app: app1, token: token1, d:{}}, (err, resp) -> err.message.should.equal("d must containt at least one key.") done() return return it 'Set some params for token1: should fail as token1 was killed', ( done ) -> rs.set {app: app1, token: token1, d:{str:"haha"}}, (err, resp) -> should.not.exist(err) resp.should.not.have.keys('id') done() return return it 'Set some params for token2: should work', ( done ) -> rs.set {app: app1, token: token2, d: {hi: "ho", count: 120, premium: true, nix:null }}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object done() return return it 'Get the session for token2: should work and contain new values', (done) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('hi','count','premium') done() return return it 'Remove a param from token2: should work', ( done ) -> rs.set {app: app1, token: token2, d: {hi: null}}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('count','premium') done() return return it 'Get the session for token2: should work and contain modified values', (done) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('count','premium') done() return return it 'Remove all remaining params from token2: should work', ( done ) -> rs.set {app: app1, token: token2, d: {count: null, premium: null}}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('d') done() return return it 'Get the session for token2: should work and not contain the d key', (done) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('d') done() return return it 'Remove all remaining params from token2 again: should work', ( done ) -> rs.set {app: app1, token: token2, d: {count: null, premium: null}}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('d') done() return return it 'Get the session for token2: should work and not contain the d key', (done) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('d') done() return return it 'Set some params for token2: should work', ( done ) -> rs.set {app: app1, token: token2, d: {a: "sometext", b: 20, c: true, d: false}}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('a','b','c','d') resp.d.a.should.equal("sometext") resp.d.b.should.equal(20) resp.d.c.should.equal(true) resp.d.d.should.equal(false) done() return return it 'Modify some params for token2: should work', ( done ) -> rs.set {app: app1, token: token2, d: {a: false, b: "some_text", c: 20, d: true, e:20.212}}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('a','b','c','d','e') resp.d.a.should.equal(false) resp.d.b.should.equal('some_text') resp.d.c.should.equal(20) resp.d.d.should.equal(true) resp.d.e.should.equal(20.212) done() return return it 'Get the params for token2: should work', ( done ) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('a','b','c','d','e') resp.d.a.should.equal(false) resp.d.b.should.equal('some_text') resp.d.c.should.equal(20) resp.d.d.should.equal(true) resp.d.e.should.equal(20.212) done() return return return describe 'CLEANUP', -> # Kill all tokens it 'Remove all sessions from app1', (done) -> rs.killall {app:app1}, (err, resp) -> should.exist(resp.kill) done() return return it 'Remove all sessions from app2', (done) -> rs.killall {app:app2}, (err, resp) -> should.exist(resp.kill) done() return return it 'Issue the Quit Command.', (done) -> rs.quit() done() return return return
true
_ = require "lodash" should = require "should" async = require "async" RedisSessions = require "../index" describe 'Redis-Sessions Test', -> rs = null app1 = "test" app2 = "TEST" token1 = null token2 = null token3 = null token4 = null bulksessions = [] before (done) -> done() return after (done) -> done() return it 'get a RedisSessions instance', (done) -> rs = new RedisSessions() rs.should.be.an.instanceOf RedisSessions done() return describe 'GET: Part 1', -> it 'Get a Session with invalid app format: no app supplied', (done) -> rs.get {}, (err, resp) -> err.message.should.equal("No app supplied") done() return return it 'Get a Session with invalid app format: too short', (done) -> rs.get {app: "a"}, (err, resp) -> err.message.should.equal("Invalid app format") done() return return it 'Get a Session with invalid token format: no token at all', (done) -> rs.get {app: app1}, (err, resp) -> err.message.should.equal("No token supplied") done() return return it 'Get a Session with invalid token format: token shorter than 64 chars', (done) -> rs.get {app: app1, token: "PI:PASSWORD:<PASSWORD>END_PI"}, (err, resp) -> err.message.should.equal("Invalid token format") done() return return it 'Get a Session with invalid token format: token longer than 64 chars', (done) -> rs.get {app: app1, token: "PI:KEY:<KEY>END_PI"}, (err, resp) -> err.message.should.equal("Invalid token format") done() return return it 'Get a Session with invalid token format: token with invalid character', (done) -> rs.get {app: app1, token: PI:KEY:<KEY>END_PI"}, (err, resp) -> err.message.should.equal("Invalid token format") done() return return it 'Get a Session with valid token format but token should not exist', (done) -> rs.get {app: app1, token: "PI:KEY:<KEY>END_PI"}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('id') done() return return return describe 'CREATE: Part 1', -> it 'Create a session with invalid data: no app supplied', (done) -> rs.create {}, (err, resp) -> err.message.should.equal("No app supplied") done() return return it 'Create a session with invalid data: no id supplied', (done) -> rs.create {app: app1}, (err, resp) -> err.message.should.equal("No id supplied") done() return return it 'Create a session with invalid data: no ip supplied', (done) -> rs.create {app: app1, id:"user1"}, (err, resp) -> err.message.should.equal("No ip supplied") done() return return it 'Create a session with invalid data: Longer than 39 chars ip supplied', (done) -> rs.create {app: app1, id:"user1", ip:"1234567890123456789012345678901234567890"}, (err, resp) -> err.message.should.equal("Invalid ip format") done() return return it 'Create a session with invalid data: zero length ip supplied', (done) -> rs.create {app: app1, id:"user1", ip:""}, (err, resp) -> err.message.should.equal("No ip supplied") done() return return it 'Create a session with invalid data: ttl too short', (done) -> rs.create {app: app1, id:"user1", ip: "127.0.0.1", ttl: 4}, (err, resp) -> err.message.should.equal("ttl must be a positive integer >= 10") done() return return it 'Create a session with valid data: should return a token', (done) -> rs.create {app: app1, id:"user1", ip: "127.0.0.1", ttl: 30}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') token1 = resp.token done() return return it 'Activity should show 1 user', (done) -> rs.activity {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(1) done() return return it 'Create another session for user1: should return a token', (done) -> rs.create {app: app1, id:"user1", ip: "127.0.0.2", ttl: 30}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') done() return return it 'Create yet another session for user1 with a `d` object: should return a token', (done) -> rs.create {app: app1, id:"user1", ip: "127.0.0.2", ttl: 30, d:{"foo":"bar","nu":null,"hi":123,"lo":-123,"boo":true,"boo2":false}}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') token4 = resp.token done() return return it 'Create yet another session for user1 with an invalid `d` object: should return a token', (done) -> rs.create {app: app1, id:"user1", ip: "2001:0000:1234:0000:0000:C1C0:ABCD:0876", ttl: 30, d:{"inv":[]}}, (err, resp) -> should.not.exist(resp) should.exist(err) done() return return it 'Create yet another session for user1 with an invalid `d` object: should return a token', (done) -> rs.create {app: app1, id:"user1", ip: "2001:0000:1234:0000:0000:C1C0:ABCD:0876", ttl: 30, d:{}}, (err, resp) -> should.not.exist(resp) should.exist(err) done() return return it 'Activity should STILL show 1 user', (done) -> rs.activity {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(1) done() return return it 'Create another session with valid data: should return a token', (done) -> rs.create {app: app1, id:"user2", ip: "127.0.0.1", ttl: 10}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') token2 = resp.token done() return return it 'Activity should show 2 users', (done) -> rs.activity {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(2) done() return return it 'Sessions of App should return 4 users', (done) -> rs.soapp {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('sessions') resp.sessions.length.should.equal(4) done() return return it 'Create a session for another app with valid data: should return a token', (done) -> rs.create {app: app2, id:"user1", ip: "127.0.0.1", ttl: 30}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') token3 = resp.token done() return return it 'Activity should show 1 user', (done) -> rs.activity {app: app2, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(1) done() return return it 'Create 1000 sessions for app2: succeed', (done) -> pq = [] for i in [0...1000] pq.push({app:app2, id: "bulkuser_" + i, ip:"127.0.0.1"}) async.map pq, rs.create, (err, resp) -> for e in resp e.should.have.keys('token') bulksessions.push(e.token) e.token.length.should.equal(64) done() return return it 'Activity should show 1001 user', (done) -> rs.activity {app: app2, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(1001) done() return return it 'Get 1000 sessions for app2: succeed', (done) -> pq = [] for e,i in bulksessions pq.push({app:app2, token: e}) async.map pq, rs.get, (err, resp) -> resp.length.should.equal(1000) for e,i in resp e.should.have.keys('id','r','w','ttl','idle','ip') e.id.should.equal("bulkuser_" + i) done() return return it 'Create a session for bulkuser_999 with valid data: should return a token', (done) -> rs.create {app: app2, id:"bulkuser_999", ip: "127.0.0.2", ttl: 30}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('token') done() return return it 'Check if we have 2 sessions for bulkuser_999', (done) -> rs.soid {app: app2, id: "bulkuser_999"}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('sessions') resp.sessions.length.should.equal(2) resp.sessions[0].id.should.equal("bulkuser_999") done() return return it 'Remove those 2 sessions for bulkuser_999', (done) -> rs.killsoid {app: app2, id: "bulkuser_999"}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('kill') resp.kill.should.equal(2) done() return return it 'Check if we have still have sessions for bulkuser_999: should return 0', (done) -> rs.soid {app: app2, id: "bulkuser_999"}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('sessions') resp.sessions.length.should.equal(0) done() return return return describe 'GET: Part 2', -> it 'Get the Session for token1: should work', ( done ) -> rs.get {app: app1, token: token1}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.have.keys('id','r','w','ttl','idle','ip') resp.id.should.equal("user1") resp.ttl.should.equal(30) done() return return it 'Get the Session for token1 again: should work', ( done ) -> rs.get {app: app1, token: token1}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.have.keys('id','r','w','ttl','idle','ip') resp.id.should.equal("user1") resp.ttl.should.equal(30) resp.r.should.equal(2) done() return return it 'Sessions of App should return 4 users', (done) -> rs.soapp {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('sessions') resp.sessions.length.should.equal(4) done() return return it 'Kill the Session for token1: should work', ( done ) -> rs.kill {app: app1, token: token1}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.have.keys('kill') resp.kill.should.equal(1) done() return return it 'Get the Session for token1: should fail', ( done ) -> rs.get {app: app1, token: token1}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('id') done() return return it 'Activity for app1 should show 2 users still', (done) -> rs.activity {app: app1, dt: 60}, (err, resp) -> should.not.exist(err) should.exist(resp) resp.should.have.keys('activity') resp.activity.should.equal(2) done() return return it 'Get the Session for token2', ( done ) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.have.keys('id','r','w','ttl','idle','ip') resp.id.should.equal("user2") resp.ttl.should.equal(10) done() return return it 'Get the Session for token4', ( done ) -> rs.get {app: app1, token: token4}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.have.keys('id','r','w','ttl','idle','ip','d') resp.id.should.equal("user1") resp.ttl.should.equal(30) resp.d.foo.should.equal("bar") done() return return return describe 'SET', -> it 'Set some params for token1 with no d: should fail', ( done ) -> rs.set {app: app1, token: token1}, (err, resp) -> err.message.should.equal("No d supplied") done() return return it 'Set some params for token1 with d being an array', ( done ) -> rs.set {app: app1, token: token1, d:[12,"bla"]}, (err, resp) -> err.message.should.equal("d must be an object") done() return return it 'Set some params for token1 with d being a string: should fail', ( done ) -> rs.set {app: app1, token: token1, d:"someString"}, (err, resp) -> err.message.should.equal("d must be an object") done() return return it 'Set some params for token1 with forbidden type (array): should fail', ( done ) -> rs.set {app: app1, token: token1, d:{arr:[1,2,3]}}, (err, resp) -> err.message.should.equal("d.arr has a forbidden type. Only strings, numbers, boolean and null are allowed.") done() return return it 'Set some params for token1 with forbidden type (object): should fail', ( done ) -> rs.set {app: app1, token: token1, d:{obj:{bla:1}}}, (err, resp) -> err.message.should.equal("d.obj has a forbidden type. Only strings, numbers, boolean and null are allowed.") done() return return it 'Set some params for token1 with an empty object: should fail', ( done ) -> rs.set {app: app1, token: token1, d:{}}, (err, resp) -> err.message.should.equal("d must containt at least one key.") done() return return it 'Set some params for token1: should fail as token1 was killed', ( done ) -> rs.set {app: app1, token: token1, d:{str:"haha"}}, (err, resp) -> should.not.exist(err) resp.should.not.have.keys('id') done() return return it 'Set some params for token2: should work', ( done ) -> rs.set {app: app1, token: token2, d: {hi: "ho", count: 120, premium: true, nix:null }}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object done() return return it 'Get the session for token2: should work and contain new values', (done) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('hi','count','premium') done() return return it 'Remove a param from token2: should work', ( done ) -> rs.set {app: app1, token: token2, d: {hi: null}}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('count','premium') done() return return it 'Get the session for token2: should work and contain modified values', (done) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('count','premium') done() return return it 'Remove all remaining params from token2: should work', ( done ) -> rs.set {app: app1, token: token2, d: {count: null, premium: null}}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('d') done() return return it 'Get the session for token2: should work and not contain the d key', (done) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('d') done() return return it 'Remove all remaining params from token2 again: should work', ( done ) -> rs.set {app: app1, token: token2, d: {count: null, premium: null}}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('d') done() return return it 'Get the session for token2: should work and not contain the d key', (done) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.should.not.have.keys('d') done() return return it 'Set some params for token2: should work', ( done ) -> rs.set {app: app1, token: token2, d: {a: "sometext", b: 20, c: true, d: false}}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('a','b','c','d') resp.d.a.should.equal("sometext") resp.d.b.should.equal(20) resp.d.c.should.equal(true) resp.d.d.should.equal(false) done() return return it 'Modify some params for token2: should work', ( done ) -> rs.set {app: app1, token: token2, d: {a: false, b: "some_text", c: 20, d: true, e:20.212}}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('a','b','c','d','e') resp.d.a.should.equal(false) resp.d.b.should.equal('some_text') resp.d.c.should.equal(20) resp.d.d.should.equal(true) resp.d.e.should.equal(20.212) done() return return it 'Get the params for token2: should work', ( done ) -> rs.get {app: app1, token: token2}, (err, resp) -> should.not.exist(err) resp.should.be.an.Object resp.d.should.have.keys('a','b','c','d','e') resp.d.a.should.equal(false) resp.d.b.should.equal('some_text') resp.d.c.should.equal(20) resp.d.d.should.equal(true) resp.d.e.should.equal(20.212) done() return return return describe 'CLEANUP', -> # Kill all tokens it 'Remove all sessions from app1', (done) -> rs.killall {app:app1}, (err, resp) -> should.exist(resp.kill) done() return return it 'Remove all sessions from app2', (done) -> rs.killall {app:app2}, (err, resp) -> should.exist(resp.kill) done() return return it 'Issue the Quit Command.', (done) -> rs.quit() done() return return return
[ { "context": "owner = @store.createRecord \"owner\",\n name: \"test-owner-freddy\"\n ctx.owner.save()\n andThen =>\n owner = ct", "end": 510, "score": 0.9982241988182068, "start": 493, "tag": "USERNAME", "value": "test-owner-freddy" }, { "context": "de an owner\"\n ass...
tests/acceptance/standard-use-test.coffee
foxnewsnetwork/autox
0
`import Ember from 'ember'` `import { test } from 'qunit'` `import moduleForAcceptance from '../../tests/helpers/module-for-acceptance'` moduleForAcceptance 'Acceptance: StandardUse' test 'visiting /', (assert) -> @store = @application.__container__.lookup("service:store") visit '/' ctx = {} andThen => assert.equal currentURL(), '/' assert.equal typeof @store?.createRecord, "function", "we should have the store" ctx.owner = @store.createRecord "owner", name: "test-owner-freddy" ctx.owner.save() andThen => owner = ctx.owner assert.ok owner, "we should have made an owner" assert.equal owner.get("name"), "test-owner-freddy", "it should handle attributes correctly" factory = @store.modelFor "owner" assert.equal owner.constructor, factory, "it should be what we expect" andThen => ctx.shop = @store.createRecord "shop", owner: ctx.owner name: "jackson Davis Shop" location: "nowhere" ctx.shop.save() andThen => {shop} = ctx assert.ok shop assert.equal shop.get("name"), "jackson Davis Shop", "the attributes should match" shop.get("owner") .then (owner) -> assert.equal owner.get("id"), ctx.owner.get("id"), "ok relationship" andThen => ctx.salsa = @store.createRecord "salsa", name: "avocado mild" price: 1.34 ctx.salsa.save() andThen => {shop, salsa} = ctx assert.equal typeof shop.relate, "function", "models should have the relate function" ctx.relation = (relation = shop.relate "salsas") relation.associate salsa relation.set "authorization-key", "x-fire" relation.save() andThen => {shop, salsa} = ctx shop.get("salsas") .then (salsas) -> assert.equal salsas.get("length"), 1, "we should have a salsa at the shop" s = salsas.objectAt(0) assert.equal s.get("id"), salsa.get("id"), "the salsas should match" andThen => {relation} = ctx relation.destroyRecord() andThen => {shop} = ctx shop .get("salsas") .then (salsas) -> salsas.reload() .then (salsas) -> assert.equal salsas.get("length"), 0, "deleting the relation should empty out the relation"
52547
`import Ember from 'ember'` `import { test } from 'qunit'` `import moduleForAcceptance from '../../tests/helpers/module-for-acceptance'` moduleForAcceptance 'Acceptance: StandardUse' test 'visiting /', (assert) -> @store = @application.__container__.lookup("service:store") visit '/' ctx = {} andThen => assert.equal currentURL(), '/' assert.equal typeof @store?.createRecord, "function", "we should have the store" ctx.owner = @store.createRecord "owner", name: "test-owner-freddy" ctx.owner.save() andThen => owner = ctx.owner assert.ok owner, "we should have made an owner" assert.equal owner.get("name"), "test-owner-freddy", "it should handle attributes correctly" factory = @store.modelFor "owner" assert.equal owner.constructor, factory, "it should be what we expect" andThen => ctx.shop = @store.createRecord "shop", owner: ctx.owner name: "<NAME>" location: "nowhere" ctx.shop.save() andThen => {shop} = ctx assert.ok shop assert.equal shop.get("name"), "<NAME> Shop", "the attributes should match" shop.get("owner") .then (owner) -> assert.equal owner.get("id"), ctx.owner.get("id"), "ok relationship" andThen => ctx.salsa = @store.createRecord "salsa", name: "<NAME>" price: 1.34 ctx.salsa.save() andThen => {shop, salsa} = ctx assert.equal typeof shop.relate, "function", "models should have the relate function" ctx.relation = (relation = shop.relate "salsas") relation.associate salsa relation.set "authorization-key", "<KEY>" relation.save() andThen => {shop, salsa} = ctx shop.get("salsas") .then (salsas) -> assert.equal salsas.get("length"), 1, "we should have a salsa at the shop" s = salsas.objectAt(0) assert.equal s.get("id"), salsa.get("id"), "the salsas should match" andThen => {relation} = ctx relation.destroyRecord() andThen => {shop} = ctx shop .get("salsas") .then (salsas) -> salsas.reload() .then (salsas) -> assert.equal salsas.get("length"), 0, "deleting the relation should empty out the relation"
true
`import Ember from 'ember'` `import { test } from 'qunit'` `import moduleForAcceptance from '../../tests/helpers/module-for-acceptance'` moduleForAcceptance 'Acceptance: StandardUse' test 'visiting /', (assert) -> @store = @application.__container__.lookup("service:store") visit '/' ctx = {} andThen => assert.equal currentURL(), '/' assert.equal typeof @store?.createRecord, "function", "we should have the store" ctx.owner = @store.createRecord "owner", name: "test-owner-freddy" ctx.owner.save() andThen => owner = ctx.owner assert.ok owner, "we should have made an owner" assert.equal owner.get("name"), "test-owner-freddy", "it should handle attributes correctly" factory = @store.modelFor "owner" assert.equal owner.constructor, factory, "it should be what we expect" andThen => ctx.shop = @store.createRecord "shop", owner: ctx.owner name: "PI:NAME:<NAME>END_PI" location: "nowhere" ctx.shop.save() andThen => {shop} = ctx assert.ok shop assert.equal shop.get("name"), "PI:NAME:<NAME>END_PI Shop", "the attributes should match" shop.get("owner") .then (owner) -> assert.equal owner.get("id"), ctx.owner.get("id"), "ok relationship" andThen => ctx.salsa = @store.createRecord "salsa", name: "PI:NAME:<NAME>END_PI" price: 1.34 ctx.salsa.save() andThen => {shop, salsa} = ctx assert.equal typeof shop.relate, "function", "models should have the relate function" ctx.relation = (relation = shop.relate "salsas") relation.associate salsa relation.set "authorization-key", "PI:KEY:<KEY>END_PI" relation.save() andThen => {shop, salsa} = ctx shop.get("salsas") .then (salsas) -> assert.equal salsas.get("length"), 1, "we should have a salsa at the shop" s = salsas.objectAt(0) assert.equal s.get("id"), salsa.get("id"), "the salsas should match" andThen => {relation} = ctx relation.destroyRecord() andThen => {shop} = ctx shop .get("salsas") .then (salsas) -> salsas.reload() .then (salsas) -> assert.equal salsas.get("length"), 0, "deleting the relation should empty out the relation"
[ { "context": " text page.title\n a href:'https://github.com/georgeOsdDev', target:'_blank', ->\n img style:'position", "end": 491, "score": 0.9994896650314331, "start": 479, "tag": "USERNAME", "value": "georgeOsdDev" }, { "context": "\n text \"'s\"\n a href:'htt...
src/layouts/page.html.coffee
georgeOsdDev/slidepad
7
--- layout: default style: 'bootstrap' --- div '.navbar.navbar-fixed-top', -> div '.navbar-inner', -> div '.container', -> a '.brand', href:'/', -> text "slidepad" ul '.nav', -> @getCollection('navmenus').toJSON().forEach (page) => li typeof:'sioc:Page', about:page.url, ".#{'active' if @document.url is page.url}", -> a href:page.url ,property:'dc:title', -> text page.title a href:'https://github.com/georgeOsdDev', target:'_blank', -> img style:'position: absolute; top: 0; right: 0; border: 0;', src: 'https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png', alt:"Fork me on GitHub" div '.container', -> text @content hr '.soften-nomargin' footer id:'footer', -> p -> text "This website was created with" a href:'http://bevry.me', target:'_blank', title:'Visit Website', -> text 'Bevry' text "'s" a href:'https://github.com/bevry/docpad', target:'_blank', title:'Visit on GitHub', -> text 'DocPad' text " Powerd by " a href:'http://nodejs.org/', target:'_blank', title:'Node.js', -> text 'Node.js' br -> text "Slidepad is created and maintained by" a href:'http://about.me/takeharu.oshida', target:'_blank', title:'about me', -> text "Takeharu.Oshida" p -> "Last updated at #{@site.date.toISOString()}" # Include scripts text @getBlock('scripts').add([ '/vendor/log.js' '/vendor/jquery.js' '/vendor/modernizr.js' '/vendor/prettify.js' '/scripts/script.js' ]).toHTML()
195528
--- layout: default style: 'bootstrap' --- div '.navbar.navbar-fixed-top', -> div '.navbar-inner', -> div '.container', -> a '.brand', href:'/', -> text "slidepad" ul '.nav', -> @getCollection('navmenus').toJSON().forEach (page) => li typeof:'sioc:Page', about:page.url, ".#{'active' if @document.url is page.url}", -> a href:page.url ,property:'dc:title', -> text page.title a href:'https://github.com/georgeOsdDev', target:'_blank', -> img style:'position: absolute; top: 0; right: 0; border: 0;', src: 'https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png', alt:"Fork me on GitHub" div '.container', -> text @content hr '.soften-nomargin' footer id:'footer', -> p -> text "This website was created with" a href:'http://bevry.me', target:'_blank', title:'Visit Website', -> text 'Bevry' text "'s" a href:'https://github.com/bevry/docpad', target:'_blank', title:'Visit on GitHub', -> text 'DocPad' text " Powerd by " a href:'http://nodejs.org/', target:'_blank', title:'Node.js', -> text 'Node.js' br -> text "Slidepad is created and maintained by" a href:'http://about.me/takeharu.oshida', target:'_blank', title:'about me', -> text "<NAME>" p -> "Last updated at #{@site.date.toISOString()}" # Include scripts text @getBlock('scripts').add([ '/vendor/log.js' '/vendor/jquery.js' '/vendor/modernizr.js' '/vendor/prettify.js' '/scripts/script.js' ]).toHTML()
true
--- layout: default style: 'bootstrap' --- div '.navbar.navbar-fixed-top', -> div '.navbar-inner', -> div '.container', -> a '.brand', href:'/', -> text "slidepad" ul '.nav', -> @getCollection('navmenus').toJSON().forEach (page) => li typeof:'sioc:Page', about:page.url, ".#{'active' if @document.url is page.url}", -> a href:page.url ,property:'dc:title', -> text page.title a href:'https://github.com/georgeOsdDev', target:'_blank', -> img style:'position: absolute; top: 0; right: 0; border: 0;', src: 'https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png', alt:"Fork me on GitHub" div '.container', -> text @content hr '.soften-nomargin' footer id:'footer', -> p -> text "This website was created with" a href:'http://bevry.me', target:'_blank', title:'Visit Website', -> text 'Bevry' text "'s" a href:'https://github.com/bevry/docpad', target:'_blank', title:'Visit on GitHub', -> text 'DocPad' text " Powerd by " a href:'http://nodejs.org/', target:'_blank', title:'Node.js', -> text 'Node.js' br -> text "Slidepad is created and maintained by" a href:'http://about.me/takeharu.oshida', target:'_blank', title:'about me', -> text "PI:NAME:<NAME>END_PI" p -> "Last updated at #{@site.date.toISOString()}" # Include scripts text @getBlock('scripts').add([ '/vendor/log.js' '/vendor/jquery.js' '/vendor/modernizr.js' '/vendor/prettify.js' '/scripts/script.js' ]).toHTML()
[ { "context": "tions =\n\tlayout: false\n\nsessionParams =\n\tsecret: '4159J3v6V4rX6y1O6BN3ASuG2aDN7q'\n\nroutes = () ->\n\t@use '/admin', adminController.", "end": 672, "score": 0.9997336268424988, "start": 642, "tag": "KEY", "value": "4159J3v6V4rX6y1O6BN3ASuG2aDN7q" } ]
init/application.coffee
winnlab/Optimeal
0
http = require 'http' express = require 'express' async = require 'async' passport = require 'passport' roles = require 'roles' _ = require 'underscore' cookieParser = require 'cookie-parser' bodyParser = require 'body-parser' session = require 'express-session' methodOverride = require 'method-override' multer = require 'multer' Crypto = require '../utils/crypto' Cache = require '../lib/cache' View = require '../lib/view' Auth = require '../lib/auth' Ajax = require '../lib/ajax' adminController = require '../controllers/admin' userController = require '../controllers/user' jadeOptions = layout: false sessionParams = secret: '4159J3v6V4rX6y1O6BN3ASuG2aDN7q' routes = () -> @use '/admin', adminController.Router @use '/', userController.Router @use '/:lang(uk|en)', userController.Router configure = () -> @set 'views', "#{__dirname}/../views" @set 'view engine', 'jade' @set 'view options', jadeOptions @use express.static "#{__dirname}/../public" @use multer dest: './public/uploads/', rename: (fieldname, filename) -> return Crypto.md5 filename + Date.now() @use Cache.requestCache @use bodyParser.json(limit: '50mb') @use bodyParser.urlencoded({limit: '50mb', extended: true}) @use cookieParser 'LmAK3VNuA6' @use session sessionParams @use passport.initialize() @use passport.session() @use '/admin', Auth.isAuth @use methodOverride() @use View.globals @use (req, res, next) -> Ajax.isAjax req, res, {admin: adminController.layoutPage, user: userController.layoutPage}, next exports.init = (callback) -> exports.express = app = express() exports.server = http.Server app configure.apply app routes.apply app callback null exports.listen = (port, callback) -> exports.server.listen port, callback
31661
http = require 'http' express = require 'express' async = require 'async' passport = require 'passport' roles = require 'roles' _ = require 'underscore' cookieParser = require 'cookie-parser' bodyParser = require 'body-parser' session = require 'express-session' methodOverride = require 'method-override' multer = require 'multer' Crypto = require '../utils/crypto' Cache = require '../lib/cache' View = require '../lib/view' Auth = require '../lib/auth' Ajax = require '../lib/ajax' adminController = require '../controllers/admin' userController = require '../controllers/user' jadeOptions = layout: false sessionParams = secret: '<KEY>' routes = () -> @use '/admin', adminController.Router @use '/', userController.Router @use '/:lang(uk|en)', userController.Router configure = () -> @set 'views', "#{__dirname}/../views" @set 'view engine', 'jade' @set 'view options', jadeOptions @use express.static "#{__dirname}/../public" @use multer dest: './public/uploads/', rename: (fieldname, filename) -> return Crypto.md5 filename + Date.now() @use Cache.requestCache @use bodyParser.json(limit: '50mb') @use bodyParser.urlencoded({limit: '50mb', extended: true}) @use cookieParser 'LmAK3VNuA6' @use session sessionParams @use passport.initialize() @use passport.session() @use '/admin', Auth.isAuth @use methodOverride() @use View.globals @use (req, res, next) -> Ajax.isAjax req, res, {admin: adminController.layoutPage, user: userController.layoutPage}, next exports.init = (callback) -> exports.express = app = express() exports.server = http.Server app configure.apply app routes.apply app callback null exports.listen = (port, callback) -> exports.server.listen port, callback
true
http = require 'http' express = require 'express' async = require 'async' passport = require 'passport' roles = require 'roles' _ = require 'underscore' cookieParser = require 'cookie-parser' bodyParser = require 'body-parser' session = require 'express-session' methodOverride = require 'method-override' multer = require 'multer' Crypto = require '../utils/crypto' Cache = require '../lib/cache' View = require '../lib/view' Auth = require '../lib/auth' Ajax = require '../lib/ajax' adminController = require '../controllers/admin' userController = require '../controllers/user' jadeOptions = layout: false sessionParams = secret: 'PI:KEY:<KEY>END_PI' routes = () -> @use '/admin', adminController.Router @use '/', userController.Router @use '/:lang(uk|en)', userController.Router configure = () -> @set 'views', "#{__dirname}/../views" @set 'view engine', 'jade' @set 'view options', jadeOptions @use express.static "#{__dirname}/../public" @use multer dest: './public/uploads/', rename: (fieldname, filename) -> return Crypto.md5 filename + Date.now() @use Cache.requestCache @use bodyParser.json(limit: '50mb') @use bodyParser.urlencoded({limit: '50mb', extended: true}) @use cookieParser 'LmAK3VNuA6' @use session sessionParams @use passport.initialize() @use passport.session() @use '/admin', Auth.isAuth @use methodOverride() @use View.globals @use (req, res, next) -> Ajax.isAjax req, res, {admin: adminController.layoutPage, user: userController.layoutPage}, next exports.init = (callback) -> exports.express = app = express() exports.server = http.Server app configure.apply app routes.apply app callback null exports.listen = (port, callback) -> exports.server.listen port, callback
[ { "context": "st' ])\n@SECRET_KEY = (process.env.SECRET_KEY || 'v secure imo')\n", "end": 114, "score": 0.4898149371147156, "start": 108, "tag": "KEY", "value": "secure" } ]
server/config.coffee
sarenji/pokebattle-sim
5
@IS_LOCAL = (process.env.NODE_ENV in [ 'development', 'test' ]) @SECRET_KEY = (process.env.SECRET_KEY || 'v secure imo')
87880
@IS_LOCAL = (process.env.NODE_ENV in [ 'development', 'test' ]) @SECRET_KEY = (process.env.SECRET_KEY || 'v <KEY> imo')
true
@IS_LOCAL = (process.env.NODE_ENV in [ 'development', 'test' ]) @SECRET_KEY = (process.env.SECRET_KEY || 'v PI:KEY:<KEY>END_PI imo')
[ { "context": "ON', ->\n before ->\n value = '{\"key\": \"Brand New\"}'\n\n after ->\n value = null\n\n it", "end": 2264, "score": 0.9976201057434082, "start": 2255, "tag": "KEY", "value": "Brand New" }, { "context": "e\n expect(result).to.have.prop...
lib/utils.spec.coffee
kpunith8/gringotts
0
import Chaplin from 'chaplin' import deadDeferred from './dead-deferred' import {keys, openURL, getLocation, setLocation, reloadLocation, urlJoin, tagBuilder, parseJSON, toBrowserDate, toServerDate, mix, waitUntil, abortable, disposable, excludeUrlParam, excludeUrlParams, compress, superValue} from './utils' describe 'Utils lib', -> context 'urlJoin', -> it 'should correctly combine urls with protocol', -> url = urlJoin 'https://somedomain.com/', '', null, '/foo' expect(url).to.equal 'https://somedomain.com/foo' it 'should correctly combine regular urls', -> url = urlJoin 'moo', '', null, '/foo', 'oops' expect(url).to.equal 'moo/foo/oops' url = urlJoin '/a', 'b/', '/c' expect(url).to.equal '/a/b/c' url = urlJoin 'd', 'e', 'f/' expect(url).to.equal 'd/e/f/' url = urlJoin 'one', 44, false, null, 'two' expect(url).to.equal 'one/44/two' it 'should correctly combine weird urls', -> url = urlJoin '', '/foo' expect(url).to.equal '/foo' url = urlJoin '/', undefined, '/foo' expect(url).to.equal '/foo' url = urlJoin '/', 'foo' expect(url).to.equal '/foo' context 'openURL', -> it 'should open URLs', -> sinon.stub window, 'open' openURL 'fum' expect(window.open).to.be.calledOnce expect(window.open).to.be.calledWith 'fum' window.open.restore() context 'tagBuilder', -> $el = null beforeEach -> $el = $ tagBuilder 'a', 'Everything is awesome!', href: '#' it 'should create the correct tag', -> expect($el).to.match 'a' it 'should contain the correct content', -> expect($el).to.contain 'Everything is awesome!' it 'should have the correct attributes', -> expect($el).to.have.attr 'href', '#' it 'should insert HTML', -> $myEl = $ tagBuilder 'p', '<strong>Live!</strong>', null, no expect($myEl).to.have.html '<strong>Live!</strong>' context 'parseJSON', -> result = null value = null beforeEach -> window.Raven = captureException: sinon.spy() result = parseJSON value afterEach -> delete window.Raven context 'with valid JSON', -> before -> value = '{"key": "Brand New"}' after -> value = null it 'should return the json', -> expect(result).to.not.be.false expect(result).to.have.property 'key', 'Brand New' context 'with invalid JSON', -> before -> value = 'invalid' after -> value = null it 'should log an exception to Raven', -> expect(result).to.be.false expect(window.Raven.captureException).to.have.been.called it 'should pass the string that failed to parse', -> secondArg = window.Raven.captureException.lastCall.args[1] expect(secondArg).to.eql tags: str: 'invalid' context 'with empty string', -> before -> value = '' after -> value = null it 'should pass the string that failed to parse', -> secondArg = window.Raven.captureException.lastCall.args[1] expect(secondArg).to.eql tags: str: 'Empty string' context 'with undefined', -> before -> value = undefined after -> value = null it 'should pass the string that failed to parse', -> secondArg = window.Raven.captureException.lastCall.args[1] expect(secondArg).to.eql tags: str: 'undefined' context 'toBrowserDate', -> it 'should convert data to HTML5 date', -> date = toBrowserDate '2016-07-18' expect(date).to.equal '2016-07-18' context 'toServerDate', -> it 'should parse a number', -> date = toServerDate '2016-07-18' expect(date).to.match /^2016-07-18T([0-9\.\:])+Z$/ context 'abortable', -> xhr = null beforeEach -> xhr = $.Deferred() xhr.abort = sinon.spy -> xhr.reject() return context 'regular handlers', -> progressSpy = null thenSpy = null catchSpy = null promise = null beforeEach -> promise = abortable xhr, progress: progressSpy = sinon.spy() then: thenSpy = sinon.spy() catch: catchSpy = sinon.spy() return context 'on nofity', -> beforeEach -> xhr.notify(5).resolve() promise it 'should pass progress to promise', -> expect(progressSpy).to.have.been.calledWith 5 context 'on resolve', -> beforeEach -> xhr.resolve 6 promise it 'should pass resolved value to promise', -> expect(thenSpy).to.have.been.calledWith 6 context 'on reject', -> beforeEach -> xhr.reject 7 promise it 'should pass rejected value to promise', -> expect(catchSpy).to.have.been.calledWith 7 context 'on abort', -> beforeEach -> promise.abort() it 'should abort xhr', -> expect(xhr.abort).to.have.been.calledOnce context 'all handler', -> promise = null allSpy = null beforeEach -> promise = abortable xhr, all: allSpy = sinon.spy() return context 'on nofity', -> beforeEach -> xhr.notify(5).resolve() promise it 'should pass progress to promise', -> expect(allSpy).to.have.been.calledWith 5 context 'on resolve', -> beforeEach -> xhr.resolve 6 promise it 'should pass resolved value to promise', -> expect(allSpy).to.have.been.calledWith 6 context 'on reject', -> beforeEach -> xhr.reject 7 promise it 'should pass rejected value to promise', -> expect(allSpy).to.have.been.calledWith 7 context 'disposable', -> expectCallback = (key, response, type) -> context key, -> sandbox = null promise = null callback = null disposed = null beforeEach -> sandbox = sinon.createSandbox useFakeServer: yes sandbox.server.respondWith response sandbox.stub(deadDeferred, 'create').callsFake -> $.Deferred().reject 'disposed' model = new Chaplin.Model() model.url = '/foo' promise = disposable model.fetch(), -> model.disposed promise[key] callback = sinon.spy() model.dispose() if disposed promise.catch ($xhr) -> $xhr unless $xhr is 'disposed' or $xhr.status is 500 afterEach -> sandbox.restore() it 'should invoke promise callback', -> if type is 'success' expect(callback).to.be.calledWith [], sinon.match.string, sinon.match.has 'status', 200 else expect(callback).to.be.calledWith sinon.match.has('status', 500), sinon.match.string, sinon.match.string context 'if disposed', -> before -> disposed = yes after -> disposed = null it 'should not invoke promise callback', -> if key in ['done', 'then'] expect(callback).to.not.be.calledOnce else expect(callback).to.be.calledWith 'disposed' expectCallback 'done', '[]', 'success' expectCallback 'fail', [500, {}, '{}'], 'fail' expectCallback 'always', '[]', 'success' expectCallback 'then', '[]', 'success' expectCallback 'catch', [500, {}, '{}'], 'fail' context 'waitUntil', -> beforeEach (done) -> i = 0 waitUntil condition: -> i++ > 5 then: done it 'should wait and then finish test', -> expect(true).to.be.true context 'excludeUrlParams', -> params = null result = null beforeEach -> result = excludeUrlParams 'some/url?a=b&c=d&e=f&g=h', params context 'one param', -> before -> params = 'e' it 'should return proper url', -> expect(result).to.equal 'some/url?a=b&c=d&g=h' context 'many params', -> before -> params = ['a', 'c', 'g'] it 'should return proper url', -> expect(result).to.equal 'some/url?e=f' context 'compress', -> context 'passing undefined', -> it 'should return undefined', -> expect(compress undefined).to.be.undefined context 'passing single element array', -> it 'should return the element', -> expect(compress [5]).to.equal 5 context 'passing multiple elements array', -> it 'should return the array', -> expect(compress [6, 7]).to.eql [6, 7]
145048
import Chaplin from 'chaplin' import deadDeferred from './dead-deferred' import {keys, openURL, getLocation, setLocation, reloadLocation, urlJoin, tagBuilder, parseJSON, toBrowserDate, toServerDate, mix, waitUntil, abortable, disposable, excludeUrlParam, excludeUrlParams, compress, superValue} from './utils' describe 'Utils lib', -> context 'urlJoin', -> it 'should correctly combine urls with protocol', -> url = urlJoin 'https://somedomain.com/', '', null, '/foo' expect(url).to.equal 'https://somedomain.com/foo' it 'should correctly combine regular urls', -> url = urlJoin 'moo', '', null, '/foo', 'oops' expect(url).to.equal 'moo/foo/oops' url = urlJoin '/a', 'b/', '/c' expect(url).to.equal '/a/b/c' url = urlJoin 'd', 'e', 'f/' expect(url).to.equal 'd/e/f/' url = urlJoin 'one', 44, false, null, 'two' expect(url).to.equal 'one/44/two' it 'should correctly combine weird urls', -> url = urlJoin '', '/foo' expect(url).to.equal '/foo' url = urlJoin '/', undefined, '/foo' expect(url).to.equal '/foo' url = urlJoin '/', 'foo' expect(url).to.equal '/foo' context 'openURL', -> it 'should open URLs', -> sinon.stub window, 'open' openURL 'fum' expect(window.open).to.be.calledOnce expect(window.open).to.be.calledWith 'fum' window.open.restore() context 'tagBuilder', -> $el = null beforeEach -> $el = $ tagBuilder 'a', 'Everything is awesome!', href: '#' it 'should create the correct tag', -> expect($el).to.match 'a' it 'should contain the correct content', -> expect($el).to.contain 'Everything is awesome!' it 'should have the correct attributes', -> expect($el).to.have.attr 'href', '#' it 'should insert HTML', -> $myEl = $ tagBuilder 'p', '<strong>Live!</strong>', null, no expect($myEl).to.have.html '<strong>Live!</strong>' context 'parseJSON', -> result = null value = null beforeEach -> window.Raven = captureException: sinon.spy() result = parseJSON value afterEach -> delete window.Raven context 'with valid JSON', -> before -> value = '{"key": "<KEY>"}' after -> value = null it 'should return the json', -> expect(result).to.not.be.false expect(result).to.have.property 'key', '<KEY>' context 'with invalid JSON', -> before -> value = 'invalid' after -> value = null it 'should log an exception to Raven', -> expect(result).to.be.false expect(window.Raven.captureException).to.have.been.called it 'should pass the string that failed to parse', -> secondArg = window.Raven.captureException.lastCall.args[1] expect(secondArg).to.eql tags: str: 'invalid' context 'with empty string', -> before -> value = '' after -> value = null it 'should pass the string that failed to parse', -> secondArg = window.Raven.captureException.lastCall.args[1] expect(secondArg).to.eql tags: str: 'Empty string' context 'with undefined', -> before -> value = undefined after -> value = null it 'should pass the string that failed to parse', -> secondArg = window.Raven.captureException.lastCall.args[1] expect(secondArg).to.eql tags: str: 'undefined' context 'toBrowserDate', -> it 'should convert data to HTML5 date', -> date = toBrowserDate '2016-07-18' expect(date).to.equal '2016-07-18' context 'toServerDate', -> it 'should parse a number', -> date = toServerDate '2016-07-18' expect(date).to.match /^2016-07-18T([0-9\.\:])+Z$/ context 'abortable', -> xhr = null beforeEach -> xhr = $.Deferred() xhr.abort = sinon.spy -> xhr.reject() return context 'regular handlers', -> progressSpy = null thenSpy = null catchSpy = null promise = null beforeEach -> promise = abortable xhr, progress: progressSpy = sinon.spy() then: thenSpy = sinon.spy() catch: catchSpy = sinon.spy() return context 'on nofity', -> beforeEach -> xhr.notify(5).resolve() promise it 'should pass progress to promise', -> expect(progressSpy).to.have.been.calledWith 5 context 'on resolve', -> beforeEach -> xhr.resolve 6 promise it 'should pass resolved value to promise', -> expect(thenSpy).to.have.been.calledWith 6 context 'on reject', -> beforeEach -> xhr.reject 7 promise it 'should pass rejected value to promise', -> expect(catchSpy).to.have.been.calledWith 7 context 'on abort', -> beforeEach -> promise.abort() it 'should abort xhr', -> expect(xhr.abort).to.have.been.calledOnce context 'all handler', -> promise = null allSpy = null beforeEach -> promise = abortable xhr, all: allSpy = sinon.spy() return context 'on nofity', -> beforeEach -> xhr.notify(5).resolve() promise it 'should pass progress to promise', -> expect(allSpy).to.have.been.calledWith 5 context 'on resolve', -> beforeEach -> xhr.resolve 6 promise it 'should pass resolved value to promise', -> expect(allSpy).to.have.been.calledWith 6 context 'on reject', -> beforeEach -> xhr.reject 7 promise it 'should pass rejected value to promise', -> expect(allSpy).to.have.been.calledWith 7 context 'disposable', -> expectCallback = (key, response, type) -> context key, -> sandbox = null promise = null callback = null disposed = null beforeEach -> sandbox = sinon.createSandbox useFakeServer: yes sandbox.server.respondWith response sandbox.stub(deadDeferred, 'create').callsFake -> $.Deferred().reject 'disposed' model = new Chaplin.Model() model.url = '/foo' promise = disposable model.fetch(), -> model.disposed promise[key] callback = sinon.spy() model.dispose() if disposed promise.catch ($xhr) -> $xhr unless $xhr is 'disposed' or $xhr.status is 500 afterEach -> sandbox.restore() it 'should invoke promise callback', -> if type is 'success' expect(callback).to.be.calledWith [], sinon.match.string, sinon.match.has 'status', 200 else expect(callback).to.be.calledWith sinon.match.has('status', 500), sinon.match.string, sinon.match.string context 'if disposed', -> before -> disposed = yes after -> disposed = null it 'should not invoke promise callback', -> if key in ['done', 'then'] expect(callback).to.not.be.calledOnce else expect(callback).to.be.calledWith 'disposed' expectCallback 'done', '[]', 'success' expectCallback 'fail', [500, {}, '{}'], 'fail' expectCallback 'always', '[]', 'success' expectCallback 'then', '[]', 'success' expectCallback 'catch', [500, {}, '{}'], 'fail' context 'waitUntil', -> beforeEach (done) -> i = 0 waitUntil condition: -> i++ > 5 then: done it 'should wait and then finish test', -> expect(true).to.be.true context 'excludeUrlParams', -> params = null result = null beforeEach -> result = excludeUrlParams 'some/url?a=b&c=d&e=f&g=h', params context 'one param', -> before -> params = 'e' it 'should return proper url', -> expect(result).to.equal 'some/url?a=b&c=d&g=h' context 'many params', -> before -> params = ['a', 'c', 'g'] it 'should return proper url', -> expect(result).to.equal 'some/url?e=f' context 'compress', -> context 'passing undefined', -> it 'should return undefined', -> expect(compress undefined).to.be.undefined context 'passing single element array', -> it 'should return the element', -> expect(compress [5]).to.equal 5 context 'passing multiple elements array', -> it 'should return the array', -> expect(compress [6, 7]).to.eql [6, 7]
true
import Chaplin from 'chaplin' import deadDeferred from './dead-deferred' import {keys, openURL, getLocation, setLocation, reloadLocation, urlJoin, tagBuilder, parseJSON, toBrowserDate, toServerDate, mix, waitUntil, abortable, disposable, excludeUrlParam, excludeUrlParams, compress, superValue} from './utils' describe 'Utils lib', -> context 'urlJoin', -> it 'should correctly combine urls with protocol', -> url = urlJoin 'https://somedomain.com/', '', null, '/foo' expect(url).to.equal 'https://somedomain.com/foo' it 'should correctly combine regular urls', -> url = urlJoin 'moo', '', null, '/foo', 'oops' expect(url).to.equal 'moo/foo/oops' url = urlJoin '/a', 'b/', '/c' expect(url).to.equal '/a/b/c' url = urlJoin 'd', 'e', 'f/' expect(url).to.equal 'd/e/f/' url = urlJoin 'one', 44, false, null, 'two' expect(url).to.equal 'one/44/two' it 'should correctly combine weird urls', -> url = urlJoin '', '/foo' expect(url).to.equal '/foo' url = urlJoin '/', undefined, '/foo' expect(url).to.equal '/foo' url = urlJoin '/', 'foo' expect(url).to.equal '/foo' context 'openURL', -> it 'should open URLs', -> sinon.stub window, 'open' openURL 'fum' expect(window.open).to.be.calledOnce expect(window.open).to.be.calledWith 'fum' window.open.restore() context 'tagBuilder', -> $el = null beforeEach -> $el = $ tagBuilder 'a', 'Everything is awesome!', href: '#' it 'should create the correct tag', -> expect($el).to.match 'a' it 'should contain the correct content', -> expect($el).to.contain 'Everything is awesome!' it 'should have the correct attributes', -> expect($el).to.have.attr 'href', '#' it 'should insert HTML', -> $myEl = $ tagBuilder 'p', '<strong>Live!</strong>', null, no expect($myEl).to.have.html '<strong>Live!</strong>' context 'parseJSON', -> result = null value = null beforeEach -> window.Raven = captureException: sinon.spy() result = parseJSON value afterEach -> delete window.Raven context 'with valid JSON', -> before -> value = '{"key": "PI:KEY:<KEY>END_PI"}' after -> value = null it 'should return the json', -> expect(result).to.not.be.false expect(result).to.have.property 'key', 'PI:KEY:<KEY>END_PI' context 'with invalid JSON', -> before -> value = 'invalid' after -> value = null it 'should log an exception to Raven', -> expect(result).to.be.false expect(window.Raven.captureException).to.have.been.called it 'should pass the string that failed to parse', -> secondArg = window.Raven.captureException.lastCall.args[1] expect(secondArg).to.eql tags: str: 'invalid' context 'with empty string', -> before -> value = '' after -> value = null it 'should pass the string that failed to parse', -> secondArg = window.Raven.captureException.lastCall.args[1] expect(secondArg).to.eql tags: str: 'Empty string' context 'with undefined', -> before -> value = undefined after -> value = null it 'should pass the string that failed to parse', -> secondArg = window.Raven.captureException.lastCall.args[1] expect(secondArg).to.eql tags: str: 'undefined' context 'toBrowserDate', -> it 'should convert data to HTML5 date', -> date = toBrowserDate '2016-07-18' expect(date).to.equal '2016-07-18' context 'toServerDate', -> it 'should parse a number', -> date = toServerDate '2016-07-18' expect(date).to.match /^2016-07-18T([0-9\.\:])+Z$/ context 'abortable', -> xhr = null beforeEach -> xhr = $.Deferred() xhr.abort = sinon.spy -> xhr.reject() return context 'regular handlers', -> progressSpy = null thenSpy = null catchSpy = null promise = null beforeEach -> promise = abortable xhr, progress: progressSpy = sinon.spy() then: thenSpy = sinon.spy() catch: catchSpy = sinon.spy() return context 'on nofity', -> beforeEach -> xhr.notify(5).resolve() promise it 'should pass progress to promise', -> expect(progressSpy).to.have.been.calledWith 5 context 'on resolve', -> beforeEach -> xhr.resolve 6 promise it 'should pass resolved value to promise', -> expect(thenSpy).to.have.been.calledWith 6 context 'on reject', -> beforeEach -> xhr.reject 7 promise it 'should pass rejected value to promise', -> expect(catchSpy).to.have.been.calledWith 7 context 'on abort', -> beforeEach -> promise.abort() it 'should abort xhr', -> expect(xhr.abort).to.have.been.calledOnce context 'all handler', -> promise = null allSpy = null beforeEach -> promise = abortable xhr, all: allSpy = sinon.spy() return context 'on nofity', -> beforeEach -> xhr.notify(5).resolve() promise it 'should pass progress to promise', -> expect(allSpy).to.have.been.calledWith 5 context 'on resolve', -> beforeEach -> xhr.resolve 6 promise it 'should pass resolved value to promise', -> expect(allSpy).to.have.been.calledWith 6 context 'on reject', -> beforeEach -> xhr.reject 7 promise it 'should pass rejected value to promise', -> expect(allSpy).to.have.been.calledWith 7 context 'disposable', -> expectCallback = (key, response, type) -> context key, -> sandbox = null promise = null callback = null disposed = null beforeEach -> sandbox = sinon.createSandbox useFakeServer: yes sandbox.server.respondWith response sandbox.stub(deadDeferred, 'create').callsFake -> $.Deferred().reject 'disposed' model = new Chaplin.Model() model.url = '/foo' promise = disposable model.fetch(), -> model.disposed promise[key] callback = sinon.spy() model.dispose() if disposed promise.catch ($xhr) -> $xhr unless $xhr is 'disposed' or $xhr.status is 500 afterEach -> sandbox.restore() it 'should invoke promise callback', -> if type is 'success' expect(callback).to.be.calledWith [], sinon.match.string, sinon.match.has 'status', 200 else expect(callback).to.be.calledWith sinon.match.has('status', 500), sinon.match.string, sinon.match.string context 'if disposed', -> before -> disposed = yes after -> disposed = null it 'should not invoke promise callback', -> if key in ['done', 'then'] expect(callback).to.not.be.calledOnce else expect(callback).to.be.calledWith 'disposed' expectCallback 'done', '[]', 'success' expectCallback 'fail', [500, {}, '{}'], 'fail' expectCallback 'always', '[]', 'success' expectCallback 'then', '[]', 'success' expectCallback 'catch', [500, {}, '{}'], 'fail' context 'waitUntil', -> beforeEach (done) -> i = 0 waitUntil condition: -> i++ > 5 then: done it 'should wait and then finish test', -> expect(true).to.be.true context 'excludeUrlParams', -> params = null result = null beforeEach -> result = excludeUrlParams 'some/url?a=b&c=d&e=f&g=h', params context 'one param', -> before -> params = 'e' it 'should return proper url', -> expect(result).to.equal 'some/url?a=b&c=d&g=h' context 'many params', -> before -> params = ['a', 'c', 'g'] it 'should return proper url', -> expect(result).to.equal 'some/url?e=f' context 'compress', -> context 'passing undefined', -> it 'should return undefined', -> expect(compress undefined).to.be.undefined context 'passing single element array', -> it 'should return the element', -> expect(compress [5]).to.equal 5 context 'passing multiple elements array', -> it 'should return the array', -> expect(compress [6, 7]).to.eql [6, 7]
[ { "context": "tfix comprehension is wrapped in parens.\n# @author Julian Rosse\n###\n'use strict'\n\n#------------------------------", "end": 132, "score": 0.9998494982719421, "start": 120, "tag": "NAME", "value": "Julian Rosse" } ]
src/rules/postfix-comprehension-assign-parens.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Enforces that an assignment as the body of a postfix comprehension is wrapped in parens. # @author Julian Rosse ### 'use strict' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ isSingleAssignmentBlock = (block) -> return no unless block?.type is 'BlockStatement' return no unless block.body.length is 1 [singleStatement] = block.body return no unless singleStatement.type is 'ExpressionStatement' {expression} = singleStatement return no unless expression.type is 'AssignmentExpression' expression #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce parentheses around an assignment as the body of a postfix comprehension' category: 'Stylistic Issues' recommended: no # url: 'https://eslint.org/docs/rules/object-curly-spacing' schema: [] fixable: 'code' messages: missingParens: 'Add parentheses around the assignment to avoid confusion about the comprehension’s structure.' create: (context) -> sourceCode = context.getSourceCode() isWrappedInParens = (expression) -> nextToken = sourceCode.getTokenAfter expression nextToken.value is ')' #-------------------------------------------------------------------------- # Public #-------------------------------------------------------------------------- For: ({postfix, body}) -> return unless postfix return unless assignment = isSingleAssignmentBlock body return if isWrappedInParens assignment context.report node: assignment messageId: 'missingParens' fix: (fixer) -> fixer.replaceText assignment, "(#{sourceCode.getText assignment})"
13084
###* # @fileoverview Enforces that an assignment as the body of a postfix comprehension is wrapped in parens. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ isSingleAssignmentBlock = (block) -> return no unless block?.type is 'BlockStatement' return no unless block.body.length is 1 [singleStatement] = block.body return no unless singleStatement.type is 'ExpressionStatement' {expression} = singleStatement return no unless expression.type is 'AssignmentExpression' expression #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce parentheses around an assignment as the body of a postfix comprehension' category: 'Stylistic Issues' recommended: no # url: 'https://eslint.org/docs/rules/object-curly-spacing' schema: [] fixable: 'code' messages: missingParens: 'Add parentheses around the assignment to avoid confusion about the comprehension’s structure.' create: (context) -> sourceCode = context.getSourceCode() isWrappedInParens = (expression) -> nextToken = sourceCode.getTokenAfter expression nextToken.value is ')' #-------------------------------------------------------------------------- # Public #-------------------------------------------------------------------------- For: ({postfix, body}) -> return unless postfix return unless assignment = isSingleAssignmentBlock body return if isWrappedInParens assignment context.report node: assignment messageId: 'missingParens' fix: (fixer) -> fixer.replaceText assignment, "(#{sourceCode.getText assignment})"
true
###* # @fileoverview Enforces that an assignment as the body of a postfix comprehension is wrapped in parens. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ isSingleAssignmentBlock = (block) -> return no unless block?.type is 'BlockStatement' return no unless block.body.length is 1 [singleStatement] = block.body return no unless singleStatement.type is 'ExpressionStatement' {expression} = singleStatement return no unless expression.type is 'AssignmentExpression' expression #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce parentheses around an assignment as the body of a postfix comprehension' category: 'Stylistic Issues' recommended: no # url: 'https://eslint.org/docs/rules/object-curly-spacing' schema: [] fixable: 'code' messages: missingParens: 'Add parentheses around the assignment to avoid confusion about the comprehension’s structure.' create: (context) -> sourceCode = context.getSourceCode() isWrappedInParens = (expression) -> nextToken = sourceCode.getTokenAfter expression nextToken.value is ')' #-------------------------------------------------------------------------- # Public #-------------------------------------------------------------------------- For: ({postfix, body}) -> return unless postfix return unless assignment = isSingleAssignmentBlock body return if isWrappedInParens assignment context.report node: assignment messageId: 'missingParens' fix: (fixer) -> fixer.replaceText assignment, "(#{sourceCode.getText assignment})"
[ { "context": "nitializeFacebookSDK = ->\n FB.init\n appId : '663494370449454'\n version : 'v2.4'\n xfbml : true\n", "end": 909, "score": 0.7797020077705383, "start": 894, "tag": "KEY", "value": "663494370449454" } ]
app/assets/javascripts/articles.coffee
NUSComputingITCell/nuscomputing.com
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/ $ -> loadFacebookSDK() bindFacebookEvents() unless window.fbEventsBound bindFacebookEvents = -> $(document) .on('page:fetch', saveFacebookRoot) .on('page:change', restoreFacebookRoot) .on('page:load', -> FB?.XFBML.parse() ) @fbEventsBound = true saveFacebookRoot = -> if $('#fb-root').length @fbRoot = $('#fb-root').detach() restoreFacebookRoot = -> if @fbRoot? if $('#fb-root').length $('#fb-root').replaceWith @fbRoot else $('body').append @fbRoot loadFacebookSDK = -> window.fbAsyncInit = initializeFacebookSDK $.getScript("//connect.facebook.net/en_US/sdk.js") initializeFacebookSDK = -> FB.init appId : '663494370449454' version : 'v2.4' xfbml : true
70701
# 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/ $ -> loadFacebookSDK() bindFacebookEvents() unless window.fbEventsBound bindFacebookEvents = -> $(document) .on('page:fetch', saveFacebookRoot) .on('page:change', restoreFacebookRoot) .on('page:load', -> FB?.XFBML.parse() ) @fbEventsBound = true saveFacebookRoot = -> if $('#fb-root').length @fbRoot = $('#fb-root').detach() restoreFacebookRoot = -> if @fbRoot? if $('#fb-root').length $('#fb-root').replaceWith @fbRoot else $('body').append @fbRoot loadFacebookSDK = -> window.fbAsyncInit = initializeFacebookSDK $.getScript("//connect.facebook.net/en_US/sdk.js") initializeFacebookSDK = -> FB.init appId : '<KEY>' version : 'v2.4' xfbml : true
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/ $ -> loadFacebookSDK() bindFacebookEvents() unless window.fbEventsBound bindFacebookEvents = -> $(document) .on('page:fetch', saveFacebookRoot) .on('page:change', restoreFacebookRoot) .on('page:load', -> FB?.XFBML.parse() ) @fbEventsBound = true saveFacebookRoot = -> if $('#fb-root').length @fbRoot = $('#fb-root').detach() restoreFacebookRoot = -> if @fbRoot? if $('#fb-root').length $('#fb-root').replaceWith @fbRoot else $('body').append @fbRoot loadFacebookSDK = -> window.fbAsyncInit = initializeFacebookSDK $.getScript("//connect.facebook.net/en_US/sdk.js") initializeFacebookSDK = -> FB.init appId : 'PI:KEY:<KEY>END_PI' version : 'v2.4' xfbml : true
[ { "context": "\n# JSLocationManager - get location API\n# Coded by kouichi.sakazaki 2013.09.25\n#*************************************", "end": 109, "score": 0.9980325698852539, "start": 93, "tag": "NAME", "value": "kouichi.sakazaki" } ]
JSKit/frameworks/JSCoreLocation.framework/JSLocationManager.coffee
digitarhythm/codeJS
0
#***************************************** # JSLocationManager - get location API # Coded by kouichi.sakazaki 2013.09.25 #***************************************** class JSLocationManager extends JSObject constructor:-> super() @_location = new JSLocation() @_oldcoord = new JSLocation() @_calcelID = null @delegate = @_self locationServicesEnabled:-> ret = navigator.geolocation if (ret) return true else return false startUpdatingLocation:-> position_options = enableHighAccuracy: true timeout: 60000 maximumAge: 0 @_cancelID = navigator.geolocation.watchPosition(@successCallback, @errorCallback, position_options) stopUpdatingLocation:-> if (@_cancelID != null) navigator.geolocation.clearWatch(@_cancelID) @_cancelID = null successCallback:(event)=> if (@_cancelID == null) return if (typeof @delegate.didUpdateToLocation == 'function') lat = event.coords.latitude lng = event.coords.longitude @_oldcoord._latitude = @_location._latitude @_oldcoord._longitude = @_location._longitude @_location._latitude = lat @_location._longitude = lng @delegate.didUpdateToLocation(@_oldcoord, @_location) errorCallback:(err)=> if (typeof @delegate.didFailWithError == 'function') @delegate.didFailWithError(err)
188910
#***************************************** # JSLocationManager - get location API # Coded by <NAME> 2013.09.25 #***************************************** class JSLocationManager extends JSObject constructor:-> super() @_location = new JSLocation() @_oldcoord = new JSLocation() @_calcelID = null @delegate = @_self locationServicesEnabled:-> ret = navigator.geolocation if (ret) return true else return false startUpdatingLocation:-> position_options = enableHighAccuracy: true timeout: 60000 maximumAge: 0 @_cancelID = navigator.geolocation.watchPosition(@successCallback, @errorCallback, position_options) stopUpdatingLocation:-> if (@_cancelID != null) navigator.geolocation.clearWatch(@_cancelID) @_cancelID = null successCallback:(event)=> if (@_cancelID == null) return if (typeof @delegate.didUpdateToLocation == 'function') lat = event.coords.latitude lng = event.coords.longitude @_oldcoord._latitude = @_location._latitude @_oldcoord._longitude = @_location._longitude @_location._latitude = lat @_location._longitude = lng @delegate.didUpdateToLocation(@_oldcoord, @_location) errorCallback:(err)=> if (typeof @delegate.didFailWithError == 'function') @delegate.didFailWithError(err)
true
#***************************************** # JSLocationManager - get location API # Coded by PI:NAME:<NAME>END_PI 2013.09.25 #***************************************** class JSLocationManager extends JSObject constructor:-> super() @_location = new JSLocation() @_oldcoord = new JSLocation() @_calcelID = null @delegate = @_self locationServicesEnabled:-> ret = navigator.geolocation if (ret) return true else return false startUpdatingLocation:-> position_options = enableHighAccuracy: true timeout: 60000 maximumAge: 0 @_cancelID = navigator.geolocation.watchPosition(@successCallback, @errorCallback, position_options) stopUpdatingLocation:-> if (@_cancelID != null) navigator.geolocation.clearWatch(@_cancelID) @_cancelID = null successCallback:(event)=> if (@_cancelID == null) return if (typeof @delegate.didUpdateToLocation == 'function') lat = event.coords.latitude lng = event.coords.longitude @_oldcoord._latitude = @_location._latitude @_oldcoord._longitude = @_location._longitude @_location._latitude = lat @_location._longitude = lng @delegate.didUpdateToLocation(@_oldcoord, @_location) errorCallback:(err)=> if (typeof @delegate.didFailWithError == 'function') @delegate.didFailWithError(err)
[ { "context": "ew Backpack.Component { \n name: 'test'\n , parent: '#test'\n ", "end": 986, "score": 0.9986598491668701, "start": 982, "tag": "NAME", "value": "test" }, { "context": " }).options\n expect(options.name).toEqual('test')...
spec/src/ComponentSpec.coffee
isabella232/backpack
119
describe "Backpack.Component", -> beforeEach -> @component = new Backpack.Component({hide: true}) describe "#initialize", -> it "should create a <div>", -> nodeName = @component.el.nodeName expect(nodeName).toEqual('DIV') it "should have a 'backpack-component' class", -> hasClass = @component.$el.hasClass('backpack-component') expect(hasClass).toBeTruthy() it "should define @$parent", -> expect(@component.$parent).toBeDefined() it "should have no items (children)", -> expect(@component._items.length).toEqual(0) describe "options", -> beforeEach -> @options = @component.options it "should have a blank default content", -> expect(@options._content).toBeUndefined() it "should have 'body' as a default $parent", -> expect(@options.parent).toEqual('body') it "should set options", -> options = (new Backpack.Component { name: 'test' , parent: '#test' , hide: true , content: '' }).options expect(options.name).toEqual('test') expect(options.parent).toEqual('#test') expect(options.content).toEqual('') describe "events", -> beforeEach -> @events = @component.events it "should have no events", -> expect(@events).toBeUndefined() describe "#render", -> it "should append the component to it's parent", -> parent = $('<div>') @component.parent(parent) @component.render() expect(parent.children().length).toEqual(1) it "should return the component for chaining", -> parent = $('<div>') @component.parent(parent) expect(@component.render()).toEqual(@component) it "should call the parents #append", -> @component.parent('<div>') spy = sinon.spy(@component.$parent, 'append') @component.render() expect(spy).toHaveBeenCalled() @component.$parent.append.restore() describe "#addClass", -> it "should add a class to the component", -> @component.addClass("test") expect(@component.$el.hasClass("test")).toBeTruthy() it "should do nothing if passed nothing", -> className = @component.$el.className @component.addClass() expect(@component.$el.className).toEqual(className) describe "#removeClass", -> it "should remove a class to the component", -> @component.addClass("test").removeClass('test') expect(@component.$el.hasClass("test")).toBeFalsy() it "should do nothing if passed nothing", -> className = @component.$el.className @component.removeClass() expect(@component.$el.className).toEqual(className) describe "#parent", -> it "should set the component's parent", -> parent1 = $('<div>') @component.parent(parent1) expect(@component.$parent).toEqual(parent1) parent2 = $('<ul>') @component.parent(parent2) expect(@component.$parent).toEqual(parent2) it "should do nothing if passed nothing", -> parent = @component.$parent @component.parent() expect(@component.$parent).toEqual(parent) describe "#hide", -> it "should add the hide class to the component", -> @component.show() expect(@component.$el.hasClass('hide')).toBeFalsy() @component.hide() expect(@component.$el.hasClass('hide')).toBeTruthy() it "should call #undelegateEvents", -> spy = sinon.spy(@component, 'undelegateEvents') @component.hide() expect(spy).toHaveBeenCalled() @component.undelegateEvents.restore() it "should call #addClass", -> spy = sinon.spy(@component.$el, 'addClass') @component.hide() expect(spy).toHaveBeenCalled() @component.$el.addClass.restore() describe "#show", -> it "should remove the hide class from the component", -> @component.hide() expect(@component.$el.hasClass('hide')).toBeTruthy() @component.show() expect(@component.$el.hasClass('hide')).toBeFalsy() it "should call #delegateEvents", -> spy = sinon.spy(@component, 'delegateEvents') @component.show() expect(spy).toHaveBeenCalled() @component.delegateEvents.restore() it "should call #removeClass", -> spy = sinon.spy(@component.$el, 'removeClass') @component.show() expect(spy).toHaveBeenCalled() @component.$el.removeClass.restore() describe "#close", -> it "should call #hide", -> spy = sinon.spy(@component, 'hide') @component.close() expect(spy).toHaveBeenCalled() @component.hide.restore() it "should call #remove", -> spy = sinon.spy(@component, 'remove') @component.close() expect(spy).toHaveBeenCalled() @component.remove.restore() describe "#append", -> it "should call $.append", -> spy = sinon.spy(@component.$el, 'append') @component.append('') expect(spy).toHaveBeenCalled() @component.$el.append.restore() it "should call #setContent", -> spy = sinon.spy(@component, 'setContent') @component.append('') expect(spy).toHaveBeenCalled() @component.setContent.restore() it "should do nothing if passed nothing", -> testContent = @component.content @component.setContent() expect(@component.content).toEqual(testContent) describe "#prepend", -> it "should call $.prepend", -> spy = sinon.spy(@component.$el, 'prepend') @component.prepend('') expect(spy).toHaveBeenCalled() @component.$el.prepend.restore() it "should call #setContent", -> spy = sinon.spy(@component, 'setContent') @component.append('') expect(spy).toHaveBeenCalled() @component.setContent.restore() it "should do nothing if passed nothing", -> testContent = @component.content @component.setContent() expect(@component.content).toEqual(testContent) describe "#before", -> it "should call $.before", -> spy = sinon.spy(@component.$el, 'before') @component.before('') expect(spy).toHaveBeenCalled() @component.$el.before.restore() it "should call #setContent", -> spy = sinon.spy(@component, 'setContent') @component.append('') expect(spy).toHaveBeenCalled() @component.setContent.restore() it "should do nothing if passed nothing", -> @component.content = 'lkja' @component.setContent() expect(@component.content).toEqual('lkja') describe "#after", -> it "should call $.after", -> spy = sinon.spy(@component.$el, 'after') @component.after('') expect(spy).toHaveBeenCalled() @component.$el.after.restore() it "should call #setContent", -> spy = sinon.spy(@component, 'setContent') @component.append('') expect(spy).toHaveBeenCalled() @component.setContent.restore() it "should do nothing if passed nothing", -> testContent = @component.content @component.setContent() expect(@component.content).toEqual(testContent) describe "#content", -> it "should do nothing if passed nothing", -> testContent = '' @component.content(testContent) @component.content() expect(@component._content).toEqual(testContent) it "should return content if content isn't a View", -> testContent = '' @component.content(testContent) expect(@component._content).toEqual(testContent) it "should return content.render().el if it's a View", -> testContent = new Backbone.View({ hide: true }) spy = sinon.spy(testContent, 'render') @component.content(testContent) expect(spy).toHaveBeenCalled() expect(@component._content).toEqual(testContent.render().el) testContent.render.restore() it "should return content.el if content.render doesn't exist", -> testContent = { el: document.createElement('div') } @component.content(testContent) expect(@component._content).toEqual(testContent.el) it "should call #setContent", -> spy = sinon.spy(@component, 'setContent') @component.content('') expect(spy).toHaveBeenCalled() describe "#getItems", -> it "should return the component's items", -> @component.items('testy', {test: 'test'}) item = @component.getItems() expect(item[0]).toBe('testy') expect(item[1]['test']).toBe('test')
20482
describe "Backpack.Component", -> beforeEach -> @component = new Backpack.Component({hide: true}) describe "#initialize", -> it "should create a <div>", -> nodeName = @component.el.nodeName expect(nodeName).toEqual('DIV') it "should have a 'backpack-component' class", -> hasClass = @component.$el.hasClass('backpack-component') expect(hasClass).toBeTruthy() it "should define @$parent", -> expect(@component.$parent).toBeDefined() it "should have no items (children)", -> expect(@component._items.length).toEqual(0) describe "options", -> beforeEach -> @options = @component.options it "should have a blank default content", -> expect(@options._content).toBeUndefined() it "should have 'body' as a default $parent", -> expect(@options.parent).toEqual('body') it "should set options", -> options = (new Backpack.Component { name: '<NAME>' , parent: '#test' , hide: true , content: '' }).options expect(options.name).toEqual('<NAME>') expect(options.parent).toEqual('#test') expect(options.content).toEqual('') describe "events", -> beforeEach -> @events = @component.events it "should have no events", -> expect(@events).toBeUndefined() describe "#render", -> it "should append the component to it's parent", -> parent = $('<div>') @component.parent(parent) @component.render() expect(parent.children().length).toEqual(1) it "should return the component for chaining", -> parent = $('<div>') @component.parent(parent) expect(@component.render()).toEqual(@component) it "should call the parents #append", -> @component.parent('<div>') spy = sinon.spy(@component.$parent, 'append') @component.render() expect(spy).toHaveBeenCalled() @component.$parent.append.restore() describe "#addClass", -> it "should add a class to the component", -> @component.addClass("test") expect(@component.$el.hasClass("test")).toBeTruthy() it "should do nothing if passed nothing", -> className = @component.$el.className @component.addClass() expect(@component.$el.className).toEqual(className) describe "#removeClass", -> it "should remove a class to the component", -> @component.addClass("test").removeClass('test') expect(@component.$el.hasClass("test")).toBeFalsy() it "should do nothing if passed nothing", -> className = @component.$el.className @component.removeClass() expect(@component.$el.className).toEqual(className) describe "#parent", -> it "should set the component's parent", -> parent1 = $('<div>') @component.parent(parent1) expect(@component.$parent).toEqual(parent1) parent2 = $('<ul>') @component.parent(parent2) expect(@component.$parent).toEqual(parent2) it "should do nothing if passed nothing", -> parent = @component.$parent @component.parent() expect(@component.$parent).toEqual(parent) describe "#hide", -> it "should add the hide class to the component", -> @component.show() expect(@component.$el.hasClass('hide')).toBeFalsy() @component.hide() expect(@component.$el.hasClass('hide')).toBeTruthy() it "should call #undelegateEvents", -> spy = sinon.spy(@component, 'undelegateEvents') @component.hide() expect(spy).toHaveBeenCalled() @component.undelegateEvents.restore() it "should call #addClass", -> spy = sinon.spy(@component.$el, 'addClass') @component.hide() expect(spy).toHaveBeenCalled() @component.$el.addClass.restore() describe "#show", -> it "should remove the hide class from the component", -> @component.hide() expect(@component.$el.hasClass('hide')).toBeTruthy() @component.show() expect(@component.$el.hasClass('hide')).toBeFalsy() it "should call #delegateEvents", -> spy = sinon.spy(@component, 'delegateEvents') @component.show() expect(spy).toHaveBeenCalled() @component.delegateEvents.restore() it "should call #removeClass", -> spy = sinon.spy(@component.$el, 'removeClass') @component.show() expect(spy).toHaveBeenCalled() @component.$el.removeClass.restore() describe "#close", -> it "should call #hide", -> spy = sinon.spy(@component, 'hide') @component.close() expect(spy).toHaveBeenCalled() @component.hide.restore() it "should call #remove", -> spy = sinon.spy(@component, 'remove') @component.close() expect(spy).toHaveBeenCalled() @component.remove.restore() describe "#append", -> it "should call $.append", -> spy = sinon.spy(@component.$el, 'append') @component.append('') expect(spy).toHaveBeenCalled() @component.$el.append.restore() it "should call #setContent", -> spy = sinon.spy(@component, 'setContent') @component.append('') expect(spy).toHaveBeenCalled() @component.setContent.restore() it "should do nothing if passed nothing", -> testContent = @component.content @component.setContent() expect(@component.content).toEqual(testContent) describe "#prepend", -> it "should call $.prepend", -> spy = sinon.spy(@component.$el, 'prepend') @component.prepend('') expect(spy).toHaveBeenCalled() @component.$el.prepend.restore() it "should call #setContent", -> spy = sinon.spy(@component, 'setContent') @component.append('') expect(spy).toHaveBeenCalled() @component.setContent.restore() it "should do nothing if passed nothing", -> testContent = @component.content @component.setContent() expect(@component.content).toEqual(testContent) describe "#before", -> it "should call $.before", -> spy = sinon.spy(@component.$el, 'before') @component.before('') expect(spy).toHaveBeenCalled() @component.$el.before.restore() it "should call #setContent", -> spy = sinon.spy(@component, 'setContent') @component.append('') expect(spy).toHaveBeenCalled() @component.setContent.restore() it "should do nothing if passed nothing", -> @component.content = 'lkja' @component.setContent() expect(@component.content).toEqual('lkja') describe "#after", -> it "should call $.after", -> spy = sinon.spy(@component.$el, 'after') @component.after('') expect(spy).toHaveBeenCalled() @component.$el.after.restore() it "should call #setContent", -> spy = sinon.spy(@component, 'setContent') @component.append('') expect(spy).toHaveBeenCalled() @component.setContent.restore() it "should do nothing if passed nothing", -> testContent = @component.content @component.setContent() expect(@component.content).toEqual(testContent) describe "#content", -> it "should do nothing if passed nothing", -> testContent = '' @component.content(testContent) @component.content() expect(@component._content).toEqual(testContent) it "should return content if content isn't a View", -> testContent = '' @component.content(testContent) expect(@component._content).toEqual(testContent) it "should return content.render().el if it's a View", -> testContent = new Backbone.View({ hide: true }) spy = sinon.spy(testContent, 'render') @component.content(testContent) expect(spy).toHaveBeenCalled() expect(@component._content).toEqual(testContent.render().el) testContent.render.restore() it "should return content.el if content.render doesn't exist", -> testContent = { el: document.createElement('div') } @component.content(testContent) expect(@component._content).toEqual(testContent.el) it "should call #setContent", -> spy = sinon.spy(@component, 'setContent') @component.content('') expect(spy).toHaveBeenCalled() describe "#getItems", -> it "should return the component's items", -> @component.items('testy', {test: 'test'}) item = @component.getItems() expect(item[0]).toBe('testy') expect(item[1]['test']).toBe('test')
true
describe "Backpack.Component", -> beforeEach -> @component = new Backpack.Component({hide: true}) describe "#initialize", -> it "should create a <div>", -> nodeName = @component.el.nodeName expect(nodeName).toEqual('DIV') it "should have a 'backpack-component' class", -> hasClass = @component.$el.hasClass('backpack-component') expect(hasClass).toBeTruthy() it "should define @$parent", -> expect(@component.$parent).toBeDefined() it "should have no items (children)", -> expect(@component._items.length).toEqual(0) describe "options", -> beforeEach -> @options = @component.options it "should have a blank default content", -> expect(@options._content).toBeUndefined() it "should have 'body' as a default $parent", -> expect(@options.parent).toEqual('body') it "should set options", -> options = (new Backpack.Component { name: 'PI:NAME:<NAME>END_PI' , parent: '#test' , hide: true , content: '' }).options expect(options.name).toEqual('PI:NAME:<NAME>END_PI') expect(options.parent).toEqual('#test') expect(options.content).toEqual('') describe "events", -> beforeEach -> @events = @component.events it "should have no events", -> expect(@events).toBeUndefined() describe "#render", -> it "should append the component to it's parent", -> parent = $('<div>') @component.parent(parent) @component.render() expect(parent.children().length).toEqual(1) it "should return the component for chaining", -> parent = $('<div>') @component.parent(parent) expect(@component.render()).toEqual(@component) it "should call the parents #append", -> @component.parent('<div>') spy = sinon.spy(@component.$parent, 'append') @component.render() expect(spy).toHaveBeenCalled() @component.$parent.append.restore() describe "#addClass", -> it "should add a class to the component", -> @component.addClass("test") expect(@component.$el.hasClass("test")).toBeTruthy() it "should do nothing if passed nothing", -> className = @component.$el.className @component.addClass() expect(@component.$el.className).toEqual(className) describe "#removeClass", -> it "should remove a class to the component", -> @component.addClass("test").removeClass('test') expect(@component.$el.hasClass("test")).toBeFalsy() it "should do nothing if passed nothing", -> className = @component.$el.className @component.removeClass() expect(@component.$el.className).toEqual(className) describe "#parent", -> it "should set the component's parent", -> parent1 = $('<div>') @component.parent(parent1) expect(@component.$parent).toEqual(parent1) parent2 = $('<ul>') @component.parent(parent2) expect(@component.$parent).toEqual(parent2) it "should do nothing if passed nothing", -> parent = @component.$parent @component.parent() expect(@component.$parent).toEqual(parent) describe "#hide", -> it "should add the hide class to the component", -> @component.show() expect(@component.$el.hasClass('hide')).toBeFalsy() @component.hide() expect(@component.$el.hasClass('hide')).toBeTruthy() it "should call #undelegateEvents", -> spy = sinon.spy(@component, 'undelegateEvents') @component.hide() expect(spy).toHaveBeenCalled() @component.undelegateEvents.restore() it "should call #addClass", -> spy = sinon.spy(@component.$el, 'addClass') @component.hide() expect(spy).toHaveBeenCalled() @component.$el.addClass.restore() describe "#show", -> it "should remove the hide class from the component", -> @component.hide() expect(@component.$el.hasClass('hide')).toBeTruthy() @component.show() expect(@component.$el.hasClass('hide')).toBeFalsy() it "should call #delegateEvents", -> spy = sinon.spy(@component, 'delegateEvents') @component.show() expect(spy).toHaveBeenCalled() @component.delegateEvents.restore() it "should call #removeClass", -> spy = sinon.spy(@component.$el, 'removeClass') @component.show() expect(spy).toHaveBeenCalled() @component.$el.removeClass.restore() describe "#close", -> it "should call #hide", -> spy = sinon.spy(@component, 'hide') @component.close() expect(spy).toHaveBeenCalled() @component.hide.restore() it "should call #remove", -> spy = sinon.spy(@component, 'remove') @component.close() expect(spy).toHaveBeenCalled() @component.remove.restore() describe "#append", -> it "should call $.append", -> spy = sinon.spy(@component.$el, 'append') @component.append('') expect(spy).toHaveBeenCalled() @component.$el.append.restore() it "should call #setContent", -> spy = sinon.spy(@component, 'setContent') @component.append('') expect(spy).toHaveBeenCalled() @component.setContent.restore() it "should do nothing if passed nothing", -> testContent = @component.content @component.setContent() expect(@component.content).toEqual(testContent) describe "#prepend", -> it "should call $.prepend", -> spy = sinon.spy(@component.$el, 'prepend') @component.prepend('') expect(spy).toHaveBeenCalled() @component.$el.prepend.restore() it "should call #setContent", -> spy = sinon.spy(@component, 'setContent') @component.append('') expect(spy).toHaveBeenCalled() @component.setContent.restore() it "should do nothing if passed nothing", -> testContent = @component.content @component.setContent() expect(@component.content).toEqual(testContent) describe "#before", -> it "should call $.before", -> spy = sinon.spy(@component.$el, 'before') @component.before('') expect(spy).toHaveBeenCalled() @component.$el.before.restore() it "should call #setContent", -> spy = sinon.spy(@component, 'setContent') @component.append('') expect(spy).toHaveBeenCalled() @component.setContent.restore() it "should do nothing if passed nothing", -> @component.content = 'lkja' @component.setContent() expect(@component.content).toEqual('lkja') describe "#after", -> it "should call $.after", -> spy = sinon.spy(@component.$el, 'after') @component.after('') expect(spy).toHaveBeenCalled() @component.$el.after.restore() it "should call #setContent", -> spy = sinon.spy(@component, 'setContent') @component.append('') expect(spy).toHaveBeenCalled() @component.setContent.restore() it "should do nothing if passed nothing", -> testContent = @component.content @component.setContent() expect(@component.content).toEqual(testContent) describe "#content", -> it "should do nothing if passed nothing", -> testContent = '' @component.content(testContent) @component.content() expect(@component._content).toEqual(testContent) it "should return content if content isn't a View", -> testContent = '' @component.content(testContent) expect(@component._content).toEqual(testContent) it "should return content.render().el if it's a View", -> testContent = new Backbone.View({ hide: true }) spy = sinon.spy(testContent, 'render') @component.content(testContent) expect(spy).toHaveBeenCalled() expect(@component._content).toEqual(testContent.render().el) testContent.render.restore() it "should return content.el if content.render doesn't exist", -> testContent = { el: document.createElement('div') } @component.content(testContent) expect(@component._content).toEqual(testContent.el) it "should call #setContent", -> spy = sinon.spy(@component, 'setContent') @component.content('') expect(spy).toHaveBeenCalled() describe "#getItems", -> it "should return the component's items", -> @component.items('testy', {test: 'test'}) item = @component.getItems() expect(item[0]).toBe('testy') expect(item[1]['test']).toBe('test')
[ { "context": "###\nmonome\nhttps://github.com/charlesholbrow/node-monome\n\nCopyright (c) 2013 Charles Holbrow\nL", "end": 44, "score": 0.9996158480644226, "start": 30, "tag": "USERNAME", "value": "charlesholbrow" }, { "context": "com/charlesholbrow/node-monome\n\nCopyright (c) 2013 ...
src/lib/monome.coffee
CharlesHolbrow/monode
13
### monome https://github.com/charlesholbrow/node-monome Copyright (c) 2013 Charles Holbrow Licensed under the MIT license. ### 'use strict' events = require 'events' makeGrid = require './grid' osc = require './osc' monome = undefined PORT = 45450 module.exports = -> if monome then return monome listen = null monome = new events.EventEmitter() monome.devices = devices = {} serialosc = osc.Client 12002 osc.Server PORT, (error, _listen)-> listen = _listen if error throw new Error('Failed to open main server: ' + error) if listen.port != PORT throw new Error('Failed to listen on udp port ' + PORT + '. Is node-monome already running?') # listen to serialosc listen.on 'message', (msg, info)-> # receive device info if msg[0] == '/serialosc/device' or msg[0] == '/serialosc/add' id = msg[1] type = msg[2] port = msg[3] unless devices[id] console.log 'Connect:', msg, '\n' device = makeGrid port, type devices[id] = device device.once 'ready', -> monome.emit 'device', device # store newly added devices in convenience properties if type.match /monome arc \d+/ monome.arc = device else monome.grid = device monome.emit 'connect', device # device was removed if msg[0] == '/serialosc/remove' id = msg[1] device = devices[id] if device console.log 'Disconnect:', msg, '\n' monome.emit 'disconnect', device device.close() delete devices[id] # we need to request notification again if msg[0] == '/serialosc/add' or msg[0] == '/serialosc/remove' serialosc.send '/serialosc/notify', '127.0.0.1', PORT # get a list of all the connected devices serialosc.send '/serialosc/list', '127.0.0.1', PORT serialosc.send '/serialosc/notify', '127.0.0.1', PORT return monome
116158
### monome https://github.com/charlesholbrow/node-monome Copyright (c) 2013 <NAME> Licensed under the MIT license. ### 'use strict' events = require 'events' makeGrid = require './grid' osc = require './osc' monome = undefined PORT = 45450 module.exports = -> if monome then return monome listen = null monome = new events.EventEmitter() monome.devices = devices = {} serialosc = osc.Client 12002 osc.Server PORT, (error, _listen)-> listen = _listen if error throw new Error('Failed to open main server: ' + error) if listen.port != PORT throw new Error('Failed to listen on udp port ' + PORT + '. Is node-monome already running?') # listen to serialosc listen.on 'message', (msg, info)-> # receive device info if msg[0] == '/serialosc/device' or msg[0] == '/serialosc/add' id = msg[1] type = msg[2] port = msg[3] unless devices[id] console.log 'Connect:', msg, '\n' device = makeGrid port, type devices[id] = device device.once 'ready', -> monome.emit 'device', device # store newly added devices in convenience properties if type.match /monome arc \d+/ monome.arc = device else monome.grid = device monome.emit 'connect', device # device was removed if msg[0] == '/serialosc/remove' id = msg[1] device = devices[id] if device console.log 'Disconnect:', msg, '\n' monome.emit 'disconnect', device device.close() delete devices[id] # we need to request notification again if msg[0] == '/serialosc/add' or msg[0] == '/serialosc/remove' serialosc.send '/serialosc/notify', '127.0.0.1', PORT # get a list of all the connected devices serialosc.send '/serialosc/list', '127.0.0.1', PORT serialosc.send '/serialosc/notify', '127.0.0.1', PORT return monome
true
### monome https://github.com/charlesholbrow/node-monome Copyright (c) 2013 PI:NAME:<NAME>END_PI Licensed under the MIT license. ### 'use strict' events = require 'events' makeGrid = require './grid' osc = require './osc' monome = undefined PORT = 45450 module.exports = -> if monome then return monome listen = null monome = new events.EventEmitter() monome.devices = devices = {} serialosc = osc.Client 12002 osc.Server PORT, (error, _listen)-> listen = _listen if error throw new Error('Failed to open main server: ' + error) if listen.port != PORT throw new Error('Failed to listen on udp port ' + PORT + '. Is node-monome already running?') # listen to serialosc listen.on 'message', (msg, info)-> # receive device info if msg[0] == '/serialosc/device' or msg[0] == '/serialosc/add' id = msg[1] type = msg[2] port = msg[3] unless devices[id] console.log 'Connect:', msg, '\n' device = makeGrid port, type devices[id] = device device.once 'ready', -> monome.emit 'device', device # store newly added devices in convenience properties if type.match /monome arc \d+/ monome.arc = device else monome.grid = device monome.emit 'connect', device # device was removed if msg[0] == '/serialosc/remove' id = msg[1] device = devices[id] if device console.log 'Disconnect:', msg, '\n' monome.emit 'disconnect', device device.close() delete devices[id] # we need to request notification again if msg[0] == '/serialosc/add' or msg[0] == '/serialosc/remove' serialosc.send '/serialosc/notify', '127.0.0.1', PORT # get a list of all the connected devices serialosc.send '/serialosc/list', '127.0.0.1', PORT serialosc.send '/serialosc/notify', '127.0.0.1', PORT return monome
[ { "context": "# * freshbooks-cli-invoice\n# * https://github.com/logankoester/freshbooks-cli-invoice\n# *\n# * Copyright (c) 2013", "end": 64, "score": 0.9995073080062866, "start": 52, "tag": "USERNAME", "value": "logankoester" }, { "context": "/freshbooks-cli-invoice\n# *\n# * Copyr...
Gruntfile.coffee
logankoester/freshbooks-cli-invoice
1
# # * freshbooks-cli-invoice # * https://github.com/logankoester/freshbooks-cli-invoice # * # * Copyright (c) 2013 Logan Koester # * Licensed under the MIT license. # path = require 'path' module.exports = (grunt) -> # # Project configuration. grunt.initConfig pkg: grunt.file.readJSON 'package.json' # Coffeescript coffee: src: expand: true cwd: 'src/' src: '**/*.coffee' dest: '.' ext: '.js' copy: src: expand: true cwd: 'src/tests' src: 'config_file' dest: 'tests/' clean: lib: ['lib/', 'tests/', 'man/'] watch: all: files: [ 'src/**/*.coffee', 'bin/**/*.coffee', 'Gruntfile.coffee', 'readme/**/*.md' ] tasks: ['default'] nodeunit: all: ['tests/**/*_test.js'] readme_generator: help: options: output: 'freshbooks-invoice.md' table_of_contents: false generate_footer: false has_travis: false package_title: 'freshbooks-invoice' package_name: 'freshbooks-invoice' order: 'usage.md': 'Usage' 'examples.md': 'Examples' readme: options: github_username: 'logankoester' generate_footer: false table_of_contents: false order: 'overview.md': 'Overview' 'usage.md': 'Usage' 'examples.md': 'Examples' 'contributing.md': 'Contributing' 'license.md': 'License' bump: options: commit: true commitMessage: 'Release v%VERSION%' commitFiles: ['package.json'] createTag: true tagName: 'v%VERSION%' tagMessage: 'Version %VERSION%' push: false # These plugins provide necessary tasks. grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadNpmTasks 'grunt-contrib-coffee' grunt.loadNpmTasks 'grunt-contrib-watch' grunt.loadNpmTasks 'grunt-contrib-copy' grunt.loadNpmTasks 'grunt-contrib-nodeunit' grunt.loadNpmTasks 'grunt-readme-generator' grunt.loadNpmTasks 'grunt-bump' grunt.registerTask 'marked-man', -> done = @async() grunt.util.spawn cmd: './marked-man' args: [path.join(__dirname, 'freshbooks-invoice.md')] opts: cwd: path.join(__dirname, 'node_modules', 'marked-man', 'bin') , (error, result, code) -> throw error if error out = path.join __dirname, 'man', 'freshbooks-invoice.1' grunt.file.write out, result.stdout done() grunt.registerTask 'build', ['clean', 'coffee', 'copy', 'readme_generator', 'marked-man'] grunt.registerTask 'test', ['nodeunit'] grunt.registerTask 'default', ['build', 'test']
102595
# # * freshbooks-cli-invoice # * https://github.com/logankoester/freshbooks-cli-invoice # * # * Copyright (c) 2013 <NAME> # * Licensed under the MIT license. # path = require 'path' module.exports = (grunt) -> # # Project configuration. grunt.initConfig pkg: grunt.file.readJSON 'package.json' # Coffeescript coffee: src: expand: true cwd: 'src/' src: '**/*.coffee' dest: '.' ext: '.js' copy: src: expand: true cwd: 'src/tests' src: 'config_file' dest: 'tests/' clean: lib: ['lib/', 'tests/', 'man/'] watch: all: files: [ 'src/**/*.coffee', 'bin/**/*.coffee', 'Gruntfile.coffee', 'readme/**/*.md' ] tasks: ['default'] nodeunit: all: ['tests/**/*_test.js'] readme_generator: help: options: output: 'freshbooks-invoice.md' table_of_contents: false generate_footer: false has_travis: false package_title: 'freshbooks-invoice' package_name: 'freshbooks-invoice' order: 'usage.md': 'Usage' 'examples.md': 'Examples' readme: options: github_username: 'logankoester' generate_footer: false table_of_contents: false order: 'overview.md': 'Overview' 'usage.md': 'Usage' 'examples.md': 'Examples' 'contributing.md': 'Contributing' 'license.md': 'License' bump: options: commit: true commitMessage: 'Release v%VERSION%' commitFiles: ['package.json'] createTag: true tagName: 'v%VERSION%' tagMessage: 'Version %VERSION%' push: false # These plugins provide necessary tasks. grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadNpmTasks 'grunt-contrib-coffee' grunt.loadNpmTasks 'grunt-contrib-watch' grunt.loadNpmTasks 'grunt-contrib-copy' grunt.loadNpmTasks 'grunt-contrib-nodeunit' grunt.loadNpmTasks 'grunt-readme-generator' grunt.loadNpmTasks 'grunt-bump' grunt.registerTask 'marked-man', -> done = @async() grunt.util.spawn cmd: './marked-man' args: [path.join(__dirname, 'freshbooks-invoice.md')] opts: cwd: path.join(__dirname, 'node_modules', 'marked-man', 'bin') , (error, result, code) -> throw error if error out = path.join __dirname, 'man', 'freshbooks-invoice.1' grunt.file.write out, result.stdout done() grunt.registerTask 'build', ['clean', 'coffee', 'copy', 'readme_generator', 'marked-man'] grunt.registerTask 'test', ['nodeunit'] grunt.registerTask 'default', ['build', 'test']
true
# # * freshbooks-cli-invoice # * https://github.com/logankoester/freshbooks-cli-invoice # * # * Copyright (c) 2013 PI:NAME:<NAME>END_PI # * Licensed under the MIT license. # path = require 'path' module.exports = (grunt) -> # # Project configuration. grunt.initConfig pkg: grunt.file.readJSON 'package.json' # Coffeescript coffee: src: expand: true cwd: 'src/' src: '**/*.coffee' dest: '.' ext: '.js' copy: src: expand: true cwd: 'src/tests' src: 'config_file' dest: 'tests/' clean: lib: ['lib/', 'tests/', 'man/'] watch: all: files: [ 'src/**/*.coffee', 'bin/**/*.coffee', 'Gruntfile.coffee', 'readme/**/*.md' ] tasks: ['default'] nodeunit: all: ['tests/**/*_test.js'] readme_generator: help: options: output: 'freshbooks-invoice.md' table_of_contents: false generate_footer: false has_travis: false package_title: 'freshbooks-invoice' package_name: 'freshbooks-invoice' order: 'usage.md': 'Usage' 'examples.md': 'Examples' readme: options: github_username: 'logankoester' generate_footer: false table_of_contents: false order: 'overview.md': 'Overview' 'usage.md': 'Usage' 'examples.md': 'Examples' 'contributing.md': 'Contributing' 'license.md': 'License' bump: options: commit: true commitMessage: 'Release v%VERSION%' commitFiles: ['package.json'] createTag: true tagName: 'v%VERSION%' tagMessage: 'Version %VERSION%' push: false # These plugins provide necessary tasks. grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadNpmTasks 'grunt-contrib-coffee' grunt.loadNpmTasks 'grunt-contrib-watch' grunt.loadNpmTasks 'grunt-contrib-copy' grunt.loadNpmTasks 'grunt-contrib-nodeunit' grunt.loadNpmTasks 'grunt-readme-generator' grunt.loadNpmTasks 'grunt-bump' grunt.registerTask 'marked-man', -> done = @async() grunt.util.spawn cmd: './marked-man' args: [path.join(__dirname, 'freshbooks-invoice.md')] opts: cwd: path.join(__dirname, 'node_modules', 'marked-man', 'bin') , (error, result, code) -> throw error if error out = path.join __dirname, 'man', 'freshbooks-invoice.1' grunt.file.write out, result.stdout done() grunt.registerTask 'build', ['clean', 'coffee', 'copy', 'readme_generator', 'marked-man'] grunt.registerTask 'test', ['nodeunit'] grunt.registerTask 'default', ['build', 'test']
[ { "context": "cher resync', ->\n\n getNock = ->\n nock 'http://127.0.0.1:4001'\n\n it 'should resync if index is outdated a", "end": 3037, "score": 0.9994025826454163, "start": 3028, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "e:\n key: \"/key\"\n ...
node_modules/node-etcd/test/watcher.coffee
bugsysBugs/cote-workshop-secured
0
should = require 'should' nock = require 'nock' Etcd = require '../src/index' Watcher = require '../src/watcher.coffee' class FakeEtcd constructor: -> @stopped = false @cb = -> abort: -> {abort: => @stopped = true} watch: (key, options, cb) -> key.should.equal 'key' @cb = cb return @abort() watchIndex: (key, index, options, cb) -> key.should.equal 'key' @cb = cb return @abort() change: (err, val, header = {}) -> @cb err, val, header describe 'Watcher', -> it 'should emit change on watch change', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'change', (val) -> val.should.containEql { node: { modifiedIndex: 0 } } done() etcd.change null, { node: { modifiedIndex: 0 } } it 'should emit reconnect event on error', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'reconnect', (err) -> err.should.containEql { error: "error" } done() etcd.change "error", null it 'should emit error if received content is invalid', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'error', -> done() etcd.change null, 'invalid content', {} it 'should emit error object on error', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'error', (err) -> err.should.be.an.instanceOf Error done() etcd.change null, 'invalid content', {} it 'should use provided options', (done) -> etcd = new FakeEtcd etcd.watch = (key, opt, cb) -> opt.should.containEql { recursive: true } done() w = new Watcher etcd, 'key', null, { recursive: true } it 'should emit action on event', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'set', (res) -> done() etcd.change null, { action: 'set', node: { key: '/key', value: 'value', modifiedIndex: 1, createdIndex: 1 } } it 'should reconnect (call watch again) on error', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' etcd.watch = (key, cb) -> w.retryAttempts.should.equal 1 done() etcd.change "error", null it 'should reconnect (watch again) on empty body (etcd timeout)', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'reconnect', () -> done() etcd.change null, null, {'x-etcd-index': 123} it 'should call watch on next index after getting change', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' i = 5 etcd.watchIndex = (key, index, cb) -> index.should.equal i + 1 done() etcd.change null, { node: { modifiedIndex: i } } it 'should abort request when stop is called', -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.stop() etcd.stopped.should.be.true it 'should emit stop when stopped', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'stop', -> done() w.stop() describe 'Watcher resync', -> getNock = -> nock 'http://127.0.0.1:4001' it 'should resync if index is outdated and cleared', (done) -> getNock() .get('/v2/keys/key?waitIndex=0&wait=true') .reply(401, { errorCode: 401 message: "The event in requested index is outdated and cleared" cause: "the requested history has been cleared [1007/4]" index: 2006 }) .get('/v2/keys/key?waitIndex=2006&wait=true') .reply(200, { action:"set" node: key: "/key" value: "banan" modifiedIndex: 2013 createdIndex: 2013 prevNode: key: "/key" value: "2" modifiedIndex: 5 createdIndex: 5 }) .get('/v2/keys/key?waitIndex=2014&wait=true').reply(200,{}) w = new Watcher (new Etcd), 'key', 0 w.on 'change', (res) -> res.node.value.should.equal 'banan' w.stop() done()
104889
should = require 'should' nock = require 'nock' Etcd = require '../src/index' Watcher = require '../src/watcher.coffee' class FakeEtcd constructor: -> @stopped = false @cb = -> abort: -> {abort: => @stopped = true} watch: (key, options, cb) -> key.should.equal 'key' @cb = cb return @abort() watchIndex: (key, index, options, cb) -> key.should.equal 'key' @cb = cb return @abort() change: (err, val, header = {}) -> @cb err, val, header describe 'Watcher', -> it 'should emit change on watch change', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'change', (val) -> val.should.containEql { node: { modifiedIndex: 0 } } done() etcd.change null, { node: { modifiedIndex: 0 } } it 'should emit reconnect event on error', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'reconnect', (err) -> err.should.containEql { error: "error" } done() etcd.change "error", null it 'should emit error if received content is invalid', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'error', -> done() etcd.change null, 'invalid content', {} it 'should emit error object on error', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'error', (err) -> err.should.be.an.instanceOf Error done() etcd.change null, 'invalid content', {} it 'should use provided options', (done) -> etcd = new FakeEtcd etcd.watch = (key, opt, cb) -> opt.should.containEql { recursive: true } done() w = new Watcher etcd, 'key', null, { recursive: true } it 'should emit action on event', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'set', (res) -> done() etcd.change null, { action: 'set', node: { key: '/key', value: 'value', modifiedIndex: 1, createdIndex: 1 } } it 'should reconnect (call watch again) on error', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' etcd.watch = (key, cb) -> w.retryAttempts.should.equal 1 done() etcd.change "error", null it 'should reconnect (watch again) on empty body (etcd timeout)', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'reconnect', () -> done() etcd.change null, null, {'x-etcd-index': 123} it 'should call watch on next index after getting change', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' i = 5 etcd.watchIndex = (key, index, cb) -> index.should.equal i + 1 done() etcd.change null, { node: { modifiedIndex: i } } it 'should abort request when stop is called', -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.stop() etcd.stopped.should.be.true it 'should emit stop when stopped', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'stop', -> done() w.stop() describe 'Watcher resync', -> getNock = -> nock 'http://127.0.0.1:4001' it 'should resync if index is outdated and cleared', (done) -> getNock() .get('/v2/keys/key?waitIndex=0&wait=true') .reply(401, { errorCode: 401 message: "The event in requested index is outdated and cleared" cause: "the requested history has been cleared [1007/4]" index: 2006 }) .get('/v2/keys/key?waitIndex=2006&wait=true') .reply(200, { action:"set" node: key: "/key" value: "ban<NAME>" modifiedIndex: 2013 createdIndex: 2013 prevNode: key: "/key" value: "2" modifiedIndex: 5 createdIndex: 5 }) .get('/v2/keys/key?waitIndex=2014&wait=true').reply(200,{}) w = new Watcher (new Etcd), 'key', 0 w.on 'change', (res) -> res.node.value.should.equal 'banan' w.stop() done()
true
should = require 'should' nock = require 'nock' Etcd = require '../src/index' Watcher = require '../src/watcher.coffee' class FakeEtcd constructor: -> @stopped = false @cb = -> abort: -> {abort: => @stopped = true} watch: (key, options, cb) -> key.should.equal 'key' @cb = cb return @abort() watchIndex: (key, index, options, cb) -> key.should.equal 'key' @cb = cb return @abort() change: (err, val, header = {}) -> @cb err, val, header describe 'Watcher', -> it 'should emit change on watch change', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'change', (val) -> val.should.containEql { node: { modifiedIndex: 0 } } done() etcd.change null, { node: { modifiedIndex: 0 } } it 'should emit reconnect event on error', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'reconnect', (err) -> err.should.containEql { error: "error" } done() etcd.change "error", null it 'should emit error if received content is invalid', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'error', -> done() etcd.change null, 'invalid content', {} it 'should emit error object on error', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'error', (err) -> err.should.be.an.instanceOf Error done() etcd.change null, 'invalid content', {} it 'should use provided options', (done) -> etcd = new FakeEtcd etcd.watch = (key, opt, cb) -> opt.should.containEql { recursive: true } done() w = new Watcher etcd, 'key', null, { recursive: true } it 'should emit action on event', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'set', (res) -> done() etcd.change null, { action: 'set', node: { key: '/key', value: 'value', modifiedIndex: 1, createdIndex: 1 } } it 'should reconnect (call watch again) on error', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' etcd.watch = (key, cb) -> w.retryAttempts.should.equal 1 done() etcd.change "error", null it 'should reconnect (watch again) on empty body (etcd timeout)', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'reconnect', () -> done() etcd.change null, null, {'x-etcd-index': 123} it 'should call watch on next index after getting change', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' i = 5 etcd.watchIndex = (key, index, cb) -> index.should.equal i + 1 done() etcd.change null, { node: { modifiedIndex: i } } it 'should abort request when stop is called', -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.stop() etcd.stopped.should.be.true it 'should emit stop when stopped', (done) -> etcd = new FakeEtcd w = new Watcher etcd, 'key' w.on 'stop', -> done() w.stop() describe 'Watcher resync', -> getNock = -> nock 'http://127.0.0.1:4001' it 'should resync if index is outdated and cleared', (done) -> getNock() .get('/v2/keys/key?waitIndex=0&wait=true') .reply(401, { errorCode: 401 message: "The event in requested index is outdated and cleared" cause: "the requested history has been cleared [1007/4]" index: 2006 }) .get('/v2/keys/key?waitIndex=2006&wait=true') .reply(200, { action:"set" node: key: "/key" value: "banPI:NAME:<NAME>END_PI" modifiedIndex: 2013 createdIndex: 2013 prevNode: key: "/key" value: "2" modifiedIndex: 5 createdIndex: 5 }) .get('/v2/keys/key?waitIndex=2014&wait=true').reply(200,{}) w = new Watcher (new Etcd), 'key', 0 w.on 'change', (res) -> res.node.value.should.equal 'banan' w.stop() done()
[ { "context": "name: \"Tom Adams\"\njob_title: \"Senior Content Designer\"\ngrade: 7\nsa", "end": 16, "score": 0.9998745322227478, "start": 7, "tag": "NAME", "value": "Tom Adams" }, { "context": "\"Business Transformation Group\"\nmanager:\n name: \"Ben Holliday\"\n phone: \"0789 12...
app/data/users/tom.cson
dwpdigitaltech/DWPwelcome
0
name: "Tom Adams" job_title: "Senior Content Designer" grade: 7 salary: "£50,000" pay_date: "29 February 2016" annual_leave: 25 section: "User Experience and Design" directorate: "Business Transformation Group" manager: name: "Ben Holliday" phone: "0789 123 4567" office: "Leeds, ONE" role: [ "As a senior content designer you're expected to create content to support the DWP's digital portfolio of services and DWP content on GOV.UK." "You'll be assigned to specific services and work as part of an agile team in each service you work on." "Your work will involve line managing 3 staff." ]
64433
name: "<NAME>" job_title: "Senior Content Designer" grade: 7 salary: "£50,000" pay_date: "29 February 2016" annual_leave: 25 section: "User Experience and Design" directorate: "Business Transformation Group" manager: name: "<NAME>" phone: "0789 123 4567" office: "Leeds, ONE" role: [ "As a senior content designer you're expected to create content to support the DWP's digital portfolio of services and DWP content on GOV.UK." "You'll be assigned to specific services and work as part of an agile team in each service you work on." "Your work will involve line managing 3 staff." ]
true
name: "PI:NAME:<NAME>END_PI" job_title: "Senior Content Designer" grade: 7 salary: "£50,000" pay_date: "29 February 2016" annual_leave: 25 section: "User Experience and Design" directorate: "Business Transformation Group" manager: name: "PI:NAME:<NAME>END_PI" phone: "0789 123 4567" office: "Leeds, ONE" role: [ "As a senior content designer you're expected to create content to support the DWP's digital portfolio of services and DWP content on GOV.UK." "You'll be assigned to specific services and work as part of an agile team in each service you work on." "Your work will involve line managing 3 staff." ]
[ { "context": " # Hubot.Robot instance\n robot:\n name: 'Kitt'\n\n # Express request object\n request: ->\n ", "end": 592, "score": 0.7301884889602661, "start": 588, "tag": "NAME", "value": "Kitt" }, { "context": "iable', ->\n process.env.HUBOT_SLACK_BOTNAME = 'Lon...
node_modules/hubot-slack/test/slack.coffee
goodship11/hubot-on-slack
0
################################################################### # Setup the tests ################################################################### should = require 'should' # Import our hero. Noop logging so that we don't clutter the test output {Slack} = require '../src/slack' Slack::log = -> # Stub a few interfaces to grease the skids for tests. These are intentionally # as minimal as possible and only provide enough to make the tests possible. # Stubs are recreated before each test. stubs = null beforeEach -> stubs = # Hubot.Robot instance robot: name: 'Kitt' # Express request object request: -> data: {} param: (key) -> @data[key] # Generate a new slack instance for each test. slack = null beforeEach -> slack = new Slack stubs.robot ################################################################### # Start the tests ################################################################### describe 'Adapter', -> it 'Should initialize with a robot', -> slack.robot.name.should.eql stubs.robot.name describe '(Un)escaping strings', -> # Generate strings with multiple replacement characters makeTestString = (character) -> "Hello #{character} world and #{character} again" escapeChars = [ {before: '&', after: '&amp;', name: 'ampersands'} {before: '>', after: '&gt;', name: 'greater than signs'} {before: '<', after: '&lt;', name: 'less than signs'} ] for character in escapeChars it "Should escape #{character.name}", -> escaped = slack.escapeHtml(makeTestString(character.before)) escaped.should.eql makeTestString(character.after) it "Should unescape #{character.name}", -> unescaped = slack.unescapeHtml(makeTestString(character.after)) unescaped.should.eql makeTestString(character.before) describe 'Getting the user from params', -> it 'Should support old Hubot syntax', -> # Old syntax does not have a `user` property oldParams = reply_to: 'Your friend' slack.userFromParams(oldParams).should.have.property 'reply_to', 'Your friend' it 'Should support new Hubot syntax', -> params = user: reply_to: 'Your new friend' slack.userFromParams(params).should.have.property 'reply_to', 'Your new friend' it 'Should fall back to room value for reply_to', -> roomParams = room: 'The real reply to' slack.userFromParams(roomParams).should.have.property 'reply_to', 'The real reply to' describe 'Sending a message', -> it 'Should JSON-ify args', -> # Shim the post() methd to grab its args value slack.post = (path, args) -> (-> JSON.parse args).should.not.throw() params = reply_to: 'A fake room' args = slack.send params, 'Hello, fake world' describe 'Parsing options', -> it 'Should default to the name "slackbot"', -> slack.parseOptions() slack.options.name.should.equal 'slackbot' it 'Should default to the "blacklist" channel mode', -> slack.parseOptions() slack.options.mode.should.equal 'blacklist' it 'Should default to [] for channel list', -> slack.parseOptions() slack.options.channels.should.be.instanceof(Array).and.have.lengthOf(0); it 'Should default to null for missing environment variables', -> slack.parseOptions() should.not.exist slack.options.token should.not.exist slack.options.team it 'Should use HUBOT_SLACK_TOKEN environment variable', -> process.env.HUBOT_SLACK_TOKEN = 'insecure token' slack.parseOptions() slack.options.token.should.eql 'insecure token' delete process.env.HUBOT_SLACK_TOKEN it 'Should use HUBOT_SLACK_TEAM environment variable', -> process.env.HUBOT_SLACK_TEAM = 'fake team' slack.parseOptions() slack.options.team.should.eql 'fake team' delete process.env.HUBOT_SLACK_TEAM it 'Should use HUBOT_SLACK_BOTNAME environment variable', -> process.env.HUBOT_SLACK_BOTNAME = 'Lonely Bot' slack.parseOptions() slack.options.name.should.eql 'Lonely Bot' delete process.env.HUBOT_SLACK_BOTNAME it 'Should use HUBOT_SLACK_CHANNELMODE environment variable', -> process.env.HUBOT_SLACK_CHANNELMODE = 'a channel mode' slack.parseOptions() slack.options.mode.should.eql 'a channel mode' delete process.env.HUBOT_SLACK_CHANNELMODE it 'Should use HUBOT_SLACK_CHANNELS environment variable', -> process.env.HUBOT_SLACK_CHANNELS = 'a,list,of,channels' slack.parseOptions() slack.options.channels.should.eql ['a', 'list', 'of', 'channels'] delete process.env.HUBOT_SLACK_CHANNELS describe 'Parsing the request', -> it 'Should get the message', -> slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data.text = requestText slack.getMessageFromRequest(req).should.eql requestText it 'Should return null if the message is missing', -> slack.parseOptions() message = slack.getMessageFromRequest stubs.request() should.not.exist message it 'Should get the author', -> req = stubs.request() req.data = user_id: 37 user_name: 'Luke' channel_id: 760 channel_name: 'Home' author = slack.getAuthorFromRequest req author.should.include id: 37 name: 'Luke' it 'Should ignore blacklisted rooms', -> process.env.HUBOT_SLACK_CHANNELMODE = 'blacklist' process.env.HUBOT_SLACK_CHANNELS = 'test' slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data = channel_name: 'test' text: requestText message = slack.getMessageFromRequest req should.not.exist message delete process.env.HUBOT_SLACK_CHANNELMODE delete process.env.HUBOT_SLACK_CHANNELS it 'Should strip leading hashes from blacklisted room names', -> process.env.HUBOT_SLACK_CHANNELMODE = 'blacklist' process.env.HUBOT_SLACK_CHANNELS = '#foo,#test' slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data = channel_name: 'test' text: requestText message = slack.getMessageFromRequest req should.not.exist message delete process.env.HUBOT_SLACK_CHANNELMODE delete process.env.HUBOT_SLACK_CHANNELS it 'Should not ignore not blacklisted rooms', -> process.env.HUBOT_SLACK_CHANNELMODE = 'blacklist' process.env.HUBOT_SLACK_CHANNELS = 'test' slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data = channel_name: 'not-test' text: requestText slack.getMessageFromRequest(req).should.eql requestText delete process.env.HUBOT_SLACK_CHANNELMODE delete process.env.HUBOT_SLACK_CHANNELS it 'Should not ignore whitelisted rooms', -> process.env.HUBOT_SLACK_CHANNELMODE = 'whitelist' process.env.HUBOT_SLACK_CHANNELS = 'test' slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data = channel_name: 'test' text: requestText slack.getMessageFromRequest(req).should.eql requestText delete process.env.HUBOT_SLACK_CHANNELMODE delete process.env.HUBOT_SLACK_CHANNELS it 'Should ignore not whitelisted rooms', -> process.env.HUBOT_SLACK_CHANNELMODE = 'whitelist' process.env.HUBOT_SLACK_CHANNELS = 'test' slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data = channel_name: 'not-test' text: requestText message = slack.getMessageFromRequest req should.not.exist message delete process.env.HUBOT_SLACK_CHANNELMODE delete process.env.HUBOT_SLACK_CHANNELS
157213
################################################################### # Setup the tests ################################################################### should = require 'should' # Import our hero. Noop logging so that we don't clutter the test output {Slack} = require '../src/slack' Slack::log = -> # Stub a few interfaces to grease the skids for tests. These are intentionally # as minimal as possible and only provide enough to make the tests possible. # Stubs are recreated before each test. stubs = null beforeEach -> stubs = # Hubot.Robot instance robot: name: '<NAME>' # Express request object request: -> data: {} param: (key) -> @data[key] # Generate a new slack instance for each test. slack = null beforeEach -> slack = new Slack stubs.robot ################################################################### # Start the tests ################################################################### describe 'Adapter', -> it 'Should initialize with a robot', -> slack.robot.name.should.eql stubs.robot.name describe '(Un)escaping strings', -> # Generate strings with multiple replacement characters makeTestString = (character) -> "Hello #{character} world and #{character} again" escapeChars = [ {before: '&', after: '&amp;', name: 'ampersands'} {before: '>', after: '&gt;', name: 'greater than signs'} {before: '<', after: '&lt;', name: 'less than signs'} ] for character in escapeChars it "Should escape #{character.name}", -> escaped = slack.escapeHtml(makeTestString(character.before)) escaped.should.eql makeTestString(character.after) it "Should unescape #{character.name}", -> unescaped = slack.unescapeHtml(makeTestString(character.after)) unescaped.should.eql makeTestString(character.before) describe 'Getting the user from params', -> it 'Should support old Hubot syntax', -> # Old syntax does not have a `user` property oldParams = reply_to: 'Your friend' slack.userFromParams(oldParams).should.have.property 'reply_to', 'Your friend' it 'Should support new Hubot syntax', -> params = user: reply_to: 'Your new friend' slack.userFromParams(params).should.have.property 'reply_to', 'Your new friend' it 'Should fall back to room value for reply_to', -> roomParams = room: 'The real reply to' slack.userFromParams(roomParams).should.have.property 'reply_to', 'The real reply to' describe 'Sending a message', -> it 'Should JSON-ify args', -> # Shim the post() methd to grab its args value slack.post = (path, args) -> (-> JSON.parse args).should.not.throw() params = reply_to: 'A fake room' args = slack.send params, 'Hello, fake world' describe 'Parsing options', -> it 'Should default to the name "slackbot"', -> slack.parseOptions() slack.options.name.should.equal 'slackbot' it 'Should default to the "blacklist" channel mode', -> slack.parseOptions() slack.options.mode.should.equal 'blacklist' it 'Should default to [] for channel list', -> slack.parseOptions() slack.options.channels.should.be.instanceof(Array).and.have.lengthOf(0); it 'Should default to null for missing environment variables', -> slack.parseOptions() should.not.exist slack.options.token should.not.exist slack.options.team it 'Should use HUBOT_SLACK_TOKEN environment variable', -> process.env.HUBOT_SLACK_TOKEN = 'insecure token' slack.parseOptions() slack.options.token.should.eql 'insecure token' delete process.env.HUBOT_SLACK_TOKEN it 'Should use HUBOT_SLACK_TEAM environment variable', -> process.env.HUBOT_SLACK_TEAM = 'fake team' slack.parseOptions() slack.options.team.should.eql 'fake team' delete process.env.HUBOT_SLACK_TEAM it 'Should use HUBOT_SLACK_BOTNAME environment variable', -> process.env.HUBOT_SLACK_BOTNAME = 'Lonely Bot' slack.parseOptions() slack.options.name.should.eql 'Lonely Bot' delete process.env.HUBOT_SLACK_BOTNAME it 'Should use HUBOT_SLACK_CHANNELMODE environment variable', -> process.env.HUBOT_SLACK_CHANNELMODE = 'a channel mode' slack.parseOptions() slack.options.mode.should.eql 'a channel mode' delete process.env.HUBOT_SLACK_CHANNELMODE it 'Should use HUBOT_SLACK_CHANNELS environment variable', -> process.env.HUBOT_SLACK_CHANNELS = 'a,list,of,channels' slack.parseOptions() slack.options.channels.should.eql ['a', 'list', 'of', 'channels'] delete process.env.HUBOT_SLACK_CHANNELS describe 'Parsing the request', -> it 'Should get the message', -> slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data.text = requestText slack.getMessageFromRequest(req).should.eql requestText it 'Should return null if the message is missing', -> slack.parseOptions() message = slack.getMessageFromRequest stubs.request() should.not.exist message it 'Should get the author', -> req = stubs.request() req.data = user_id: 37 user_name: 'Luke' channel_id: 760 channel_name: 'Home' author = slack.getAuthorFromRequest req author.should.include id: 37 name: '<NAME>' it 'Should ignore blacklisted rooms', -> process.env.HUBOT_SLACK_CHANNELMODE = 'blacklist' process.env.HUBOT_SLACK_CHANNELS = 'test' slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data = channel_name: 'test' text: requestText message = slack.getMessageFromRequest req should.not.exist message delete process.env.HUBOT_SLACK_CHANNELMODE delete process.env.HUBOT_SLACK_CHANNELS it 'Should strip leading hashes from blacklisted room names', -> process.env.HUBOT_SLACK_CHANNELMODE = 'blacklist' process.env.HUBOT_SLACK_CHANNELS = '#foo,#test' slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data = channel_name: 'test' text: requestText message = slack.getMessageFromRequest req should.not.exist message delete process.env.HUBOT_SLACK_CHANNELMODE delete process.env.HUBOT_SLACK_CHANNELS it 'Should not ignore not blacklisted rooms', -> process.env.HUBOT_SLACK_CHANNELMODE = 'blacklist' process.env.HUBOT_SLACK_CHANNELS = 'test' slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data = channel_name: 'not-test' text: requestText slack.getMessageFromRequest(req).should.eql requestText delete process.env.HUBOT_SLACK_CHANNELMODE delete process.env.HUBOT_SLACK_CHANNELS it 'Should not ignore whitelisted rooms', -> process.env.HUBOT_SLACK_CHANNELMODE = 'whitelist' process.env.HUBOT_SLACK_CHANNELS = 'test' slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data = channel_name: 'test' text: requestText slack.getMessageFromRequest(req).should.eql requestText delete process.env.HUBOT_SLACK_CHANNELMODE delete process.env.HUBOT_SLACK_CHANNELS it 'Should ignore not whitelisted rooms', -> process.env.HUBOT_SLACK_CHANNELMODE = 'whitelist' process.env.HUBOT_SLACK_CHANNELS = 'test' slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data = channel_name: 'not-test' text: requestText message = slack.getMessageFromRequest req should.not.exist message delete process.env.HUBOT_SLACK_CHANNELMODE delete process.env.HUBOT_SLACK_CHANNELS
true
################################################################### # Setup the tests ################################################################### should = require 'should' # Import our hero. Noop logging so that we don't clutter the test output {Slack} = require '../src/slack' Slack::log = -> # Stub a few interfaces to grease the skids for tests. These are intentionally # as minimal as possible and only provide enough to make the tests possible. # Stubs are recreated before each test. stubs = null beforeEach -> stubs = # Hubot.Robot instance robot: name: 'PI:NAME:<NAME>END_PI' # Express request object request: -> data: {} param: (key) -> @data[key] # Generate a new slack instance for each test. slack = null beforeEach -> slack = new Slack stubs.robot ################################################################### # Start the tests ################################################################### describe 'Adapter', -> it 'Should initialize with a robot', -> slack.robot.name.should.eql stubs.robot.name describe '(Un)escaping strings', -> # Generate strings with multiple replacement characters makeTestString = (character) -> "Hello #{character} world and #{character} again" escapeChars = [ {before: '&', after: '&amp;', name: 'ampersands'} {before: '>', after: '&gt;', name: 'greater than signs'} {before: '<', after: '&lt;', name: 'less than signs'} ] for character in escapeChars it "Should escape #{character.name}", -> escaped = slack.escapeHtml(makeTestString(character.before)) escaped.should.eql makeTestString(character.after) it "Should unescape #{character.name}", -> unescaped = slack.unescapeHtml(makeTestString(character.after)) unescaped.should.eql makeTestString(character.before) describe 'Getting the user from params', -> it 'Should support old Hubot syntax', -> # Old syntax does not have a `user` property oldParams = reply_to: 'Your friend' slack.userFromParams(oldParams).should.have.property 'reply_to', 'Your friend' it 'Should support new Hubot syntax', -> params = user: reply_to: 'Your new friend' slack.userFromParams(params).should.have.property 'reply_to', 'Your new friend' it 'Should fall back to room value for reply_to', -> roomParams = room: 'The real reply to' slack.userFromParams(roomParams).should.have.property 'reply_to', 'The real reply to' describe 'Sending a message', -> it 'Should JSON-ify args', -> # Shim the post() methd to grab its args value slack.post = (path, args) -> (-> JSON.parse args).should.not.throw() params = reply_to: 'A fake room' args = slack.send params, 'Hello, fake world' describe 'Parsing options', -> it 'Should default to the name "slackbot"', -> slack.parseOptions() slack.options.name.should.equal 'slackbot' it 'Should default to the "blacklist" channel mode', -> slack.parseOptions() slack.options.mode.should.equal 'blacklist' it 'Should default to [] for channel list', -> slack.parseOptions() slack.options.channels.should.be.instanceof(Array).and.have.lengthOf(0); it 'Should default to null for missing environment variables', -> slack.parseOptions() should.not.exist slack.options.token should.not.exist slack.options.team it 'Should use HUBOT_SLACK_TOKEN environment variable', -> process.env.HUBOT_SLACK_TOKEN = 'insecure token' slack.parseOptions() slack.options.token.should.eql 'insecure token' delete process.env.HUBOT_SLACK_TOKEN it 'Should use HUBOT_SLACK_TEAM environment variable', -> process.env.HUBOT_SLACK_TEAM = 'fake team' slack.parseOptions() slack.options.team.should.eql 'fake team' delete process.env.HUBOT_SLACK_TEAM it 'Should use HUBOT_SLACK_BOTNAME environment variable', -> process.env.HUBOT_SLACK_BOTNAME = 'Lonely Bot' slack.parseOptions() slack.options.name.should.eql 'Lonely Bot' delete process.env.HUBOT_SLACK_BOTNAME it 'Should use HUBOT_SLACK_CHANNELMODE environment variable', -> process.env.HUBOT_SLACK_CHANNELMODE = 'a channel mode' slack.parseOptions() slack.options.mode.should.eql 'a channel mode' delete process.env.HUBOT_SLACK_CHANNELMODE it 'Should use HUBOT_SLACK_CHANNELS environment variable', -> process.env.HUBOT_SLACK_CHANNELS = 'a,list,of,channels' slack.parseOptions() slack.options.channels.should.eql ['a', 'list', 'of', 'channels'] delete process.env.HUBOT_SLACK_CHANNELS describe 'Parsing the request', -> it 'Should get the message', -> slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data.text = requestText slack.getMessageFromRequest(req).should.eql requestText it 'Should return null if the message is missing', -> slack.parseOptions() message = slack.getMessageFromRequest stubs.request() should.not.exist message it 'Should get the author', -> req = stubs.request() req.data = user_id: 37 user_name: 'Luke' channel_id: 760 channel_name: 'Home' author = slack.getAuthorFromRequest req author.should.include id: 37 name: 'PI:NAME:<NAME>END_PI' it 'Should ignore blacklisted rooms', -> process.env.HUBOT_SLACK_CHANNELMODE = 'blacklist' process.env.HUBOT_SLACK_CHANNELS = 'test' slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data = channel_name: 'test' text: requestText message = slack.getMessageFromRequest req should.not.exist message delete process.env.HUBOT_SLACK_CHANNELMODE delete process.env.HUBOT_SLACK_CHANNELS it 'Should strip leading hashes from blacklisted room names', -> process.env.HUBOT_SLACK_CHANNELMODE = 'blacklist' process.env.HUBOT_SLACK_CHANNELS = '#foo,#test' slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data = channel_name: 'test' text: requestText message = slack.getMessageFromRequest req should.not.exist message delete process.env.HUBOT_SLACK_CHANNELMODE delete process.env.HUBOT_SLACK_CHANNELS it 'Should not ignore not blacklisted rooms', -> process.env.HUBOT_SLACK_CHANNELMODE = 'blacklist' process.env.HUBOT_SLACK_CHANNELS = 'test' slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data = channel_name: 'not-test' text: requestText slack.getMessageFromRequest(req).should.eql requestText delete process.env.HUBOT_SLACK_CHANNELMODE delete process.env.HUBOT_SLACK_CHANNELS it 'Should not ignore whitelisted rooms', -> process.env.HUBOT_SLACK_CHANNELMODE = 'whitelist' process.env.HUBOT_SLACK_CHANNELS = 'test' slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data = channel_name: 'test' text: requestText slack.getMessageFromRequest(req).should.eql requestText delete process.env.HUBOT_SLACK_CHANNELMODE delete process.env.HUBOT_SLACK_CHANNELS it 'Should ignore not whitelisted rooms', -> process.env.HUBOT_SLACK_CHANNELMODE = 'whitelist' process.env.HUBOT_SLACK_CHANNELS = 'test' slack.parseOptions() requestText = 'The message from the request' req = stubs.request() req.data = channel_name: 'not-test' text: requestText message = slack.getMessageFromRequest req should.not.exist message delete process.env.HUBOT_SLACK_CHANNELMODE delete process.env.HUBOT_SLACK_CHANNELS
[ { "context": "dit> [limit] - Lookup reddit topic\n#\n# Author:\n# EnriqueVidal\n\nSelect = require( \"soupselect\" ).select\n\nlo", "end": 199, "score": 0.7938445806503296, "start": 187, "tag": "NAME", "value": "EnriqueVidal" } ]
src/scripts/reddit.coffee
contolini/hubot-scripts
1,450
# Description: # None # # Dependencies: # "soupselect: "0.2.0" # # Configuration: # None # # Commands: # hubot reddit (me) <reddit> [limit] - Lookup reddit topic # # Author: # EnriqueVidal Select = require( "soupselect" ).select lookup_site = "http://www.reddit.com/" module.exports = (robot)-> robot.respond /reddit( me)? ([a-z0-9\-_\.]+\/?[a-z0-9\-_\.]+)( [0-9]+)?/i, (message)-> lookup_reddit message, (text)-> message.send text lookup_reddit = (message, response_handler)-> top = parseInt message.match[3] reddit = "r/" + message.match[2] + ".json" location = lookup_site + reddit message.http( location ).get() (error, response, body)-> return response_handler "Sorry, something went wrong" if error return response_handler "Reddit doesn't know what you're talking about" if response.statusCode == 404 return response_handler "Reddit doesn't want anyone to go there any more." if response.statusCode == 403 list = JSON.parse( body ).data.children count = 0 for item in list count++ text = ( item.data.title || item.data.link_title ) + " - " + ( item.data.url || item.data.body ) response_handler text break if count == top
198052
# Description: # None # # Dependencies: # "soupselect: "0.2.0" # # Configuration: # None # # Commands: # hubot reddit (me) <reddit> [limit] - Lookup reddit topic # # Author: # <NAME> Select = require( "soupselect" ).select lookup_site = "http://www.reddit.com/" module.exports = (robot)-> robot.respond /reddit( me)? ([a-z0-9\-_\.]+\/?[a-z0-9\-_\.]+)( [0-9]+)?/i, (message)-> lookup_reddit message, (text)-> message.send text lookup_reddit = (message, response_handler)-> top = parseInt message.match[3] reddit = "r/" + message.match[2] + ".json" location = lookup_site + reddit message.http( location ).get() (error, response, body)-> return response_handler "Sorry, something went wrong" if error return response_handler "Reddit doesn't know what you're talking about" if response.statusCode == 404 return response_handler "Reddit doesn't want anyone to go there any more." if response.statusCode == 403 list = JSON.parse( body ).data.children count = 0 for item in list count++ text = ( item.data.title || item.data.link_title ) + " - " + ( item.data.url || item.data.body ) response_handler text break if count == top
true
# Description: # None # # Dependencies: # "soupselect: "0.2.0" # # Configuration: # None # # Commands: # hubot reddit (me) <reddit> [limit] - Lookup reddit topic # # Author: # PI:NAME:<NAME>END_PI Select = require( "soupselect" ).select lookup_site = "http://www.reddit.com/" module.exports = (robot)-> robot.respond /reddit( me)? ([a-z0-9\-_\.]+\/?[a-z0-9\-_\.]+)( [0-9]+)?/i, (message)-> lookup_reddit message, (text)-> message.send text lookup_reddit = (message, response_handler)-> top = parseInt message.match[3] reddit = "r/" + message.match[2] + ".json" location = lookup_site + reddit message.http( location ).get() (error, response, body)-> return response_handler "Sorry, something went wrong" if error return response_handler "Reddit doesn't know what you're talking about" if response.statusCode == 404 return response_handler "Reddit doesn't want anyone to go there any more." if response.statusCode == 403 list = JSON.parse( body ).data.children count = 0 for item in list count++ text = ( item.data.title || item.data.link_title ) + " - " + ( item.data.url || item.data.body ) response_handler text break if count == top
[ { "context": "ithout_inner_key =\n \"1\":\n id: \"1\",\n name: \"one\"\n \"2\":\n id: \"2\",\n name: \"two\"\n\nexpected_wi", "end": 150, "score": 0.960171639919281, "start": 147, "tag": "NAME", "value": "one" }, { "context": "\",\n name: \"one\"\n \"2\":\n id: \...
test/slack.coffee
sdslabs/slack-utils
2
require '../loadenv.coffee' slack = require "../api.coffee" assert = require "assert" expected_without_inner_key = "1": id: "1", name: "one" "2": id: "2", name: "two" expected_with_inner_key = "1": "one" "2": "two" list = "list": [ id: "1", name: "one" , id: "2", name: "two" ] it 'should parse lists with inner key', ()-> assert.deepEqual expected_with_inner_key, slack().listToHash list , "list", "name" it 'should parse lists without inner key', ()-> assert.deepEqual expected_without_inner_key, slack().listToHash list , "list"
17649
require '../loadenv.coffee' slack = require "../api.coffee" assert = require "assert" expected_without_inner_key = "1": id: "1", name: "<NAME>" "2": id: "2", name: "<NAME>" expected_with_inner_key = "1": "<NAME>" "2": "<NAME>" list = "list": [ id: "1", name: "<NAME>" , id: "2", name: "<NAME>" ] it 'should parse lists with inner key', ()-> assert.deepEqual expected_with_inner_key, slack().listToHash list , "list", "name" it 'should parse lists without inner key', ()-> assert.deepEqual expected_without_inner_key, slack().listToHash list , "list"
true
require '../loadenv.coffee' slack = require "../api.coffee" assert = require "assert" expected_without_inner_key = "1": id: "1", name: "PI:NAME:<NAME>END_PI" "2": id: "2", name: "PI:NAME:<NAME>END_PI" expected_with_inner_key = "1": "PI:KEY:<NAME>END_PI" "2": "PI:KEY:<NAME>END_PI" list = "list": [ id: "1", name: "PI:NAME:<NAME>END_PI" , id: "2", name: "PI:NAME:<NAME>END_PI" ] it 'should parse lists with inner key', ()-> assert.deepEqual expected_with_inner_key, slack().listToHash list , "list", "name" it 'should parse lists without inner key', ()-> assert.deepEqual expected_without_inner_key, slack().listToHash list , "list"
[ { "context": "es are known as bulls.\n '''\n\n scientificName: '(Loxodonta africana)'\n mainImage: 'assets/fieldguide-content/mammals", "end": 693, "score": 0.9594764709472656, "start": 675, "tag": "NAME", "value": "Loxodonta africana" } ]
app/lib/field-guide-content/elephant.coffee
zooniverse/snapshot-wisconsin
0
module.exports = label: 'African elephant' description: ''' African elephants are the largest land animals on earth. The trunk, a muscular extension of the upper lip and nose, contains the nostrils and has two opposing extensions at its end that are used for communication and handling objects including food. African elephants have huge ears, up to 2 x 1.5 m, which allow them to radiate excess heat. Both males and females have tusks—large, modified incisors that continuously grow throughout an elephant’s lifetime. Their skin is gray to brownish, wrinkled, and nearly hairless. Females are known as cows while males are known as bulls. ''' scientificName: '(Loxodonta africana)' mainImage: 'assets/fieldguide-content/mammals/elephant/elephant-feature.jpg' conservationStatus: 'Vulnerable' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well. information: [{ label: 'Length' value: '6.8-7.5 m' }, { label: 'Height' value: '2.5-3.3 m' }, { label: 'Weight' value: '3,000-6,000 kg' }, { label: 'Lifespan' value: '' }, { label: 'Gestation' value: '60-70 years' }, { label: 'Avg. number of offspring' value: '1' }] sections: [{ title: 'Habitat' content: 'African elephants live in almost any habitat that offers food and water.' }, { title: 'Diet' content: 'African elephants mainly eat leaves and branches of bushes and trees, but they also eat grasses, fruit, and bark.' }, { title: 'Predators' content: 'Humans, lions' }, { title: 'Behavior' content: ''' <p>African elephants have a complex social structure that takes the form of a matriarchal clan society. The basic social unit consists of a mother and her dependent offspring and grown daughters with their offspring. Each cow herd is typically made up of 9 to 11 elephants. Larger herds will often split into two or three units, but will remain within a mile of each other and communicate through rumbling calls so low in frequency they cannot be heard by humans. The matriarch sets the herd’s direction and pace, and the rest of the herd follows. When threatened, elephants will group around young calves. Males leave the cow herds at puberty at around 12 years of age. They live alone or in bachelor herds and are only seen near cow herds during the mating season. African elephants are not territorial, so male mating success depends largely on body size and tusk size.</p> ''' }, { title: 'Breeding' content: ''' African elephants give birth to one calf after a gestation period of 22 months. There is a four- to nine-year interval between calves. Bulls start to compete for females around 25, but bulls over 35 typically monopolize matings. The onset of musth, a state of heightened aggression and sexual activity, attracts cows in heat. ''' }, { title: 'Fun Facts' style: 'focus-box' content: ''' <ol> <li>African elephants use sounds well below the range of human hearing to communicate over long distances.</li> <li>The skull of the African elephant makes up 25% of its body weight.</li> </ol> ''' },{ title: 'Distribution' content: '<img src="assets/fieldguide-content/mammals/elephant/elephant-map.jpg"/>' }]
136303
module.exports = label: 'African elephant' description: ''' African elephants are the largest land animals on earth. The trunk, a muscular extension of the upper lip and nose, contains the nostrils and has two opposing extensions at its end that are used for communication and handling objects including food. African elephants have huge ears, up to 2 x 1.5 m, which allow them to radiate excess heat. Both males and females have tusks—large, modified incisors that continuously grow throughout an elephant’s lifetime. Their skin is gray to brownish, wrinkled, and nearly hairless. Females are known as cows while males are known as bulls. ''' scientificName: '(<NAME>)' mainImage: 'assets/fieldguide-content/mammals/elephant/elephant-feature.jpg' conservationStatus: 'Vulnerable' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well. information: [{ label: 'Length' value: '6.8-7.5 m' }, { label: 'Height' value: '2.5-3.3 m' }, { label: 'Weight' value: '3,000-6,000 kg' }, { label: 'Lifespan' value: '' }, { label: 'Gestation' value: '60-70 years' }, { label: 'Avg. number of offspring' value: '1' }] sections: [{ title: 'Habitat' content: 'African elephants live in almost any habitat that offers food and water.' }, { title: 'Diet' content: 'African elephants mainly eat leaves and branches of bushes and trees, but they also eat grasses, fruit, and bark.' }, { title: 'Predators' content: 'Humans, lions' }, { title: 'Behavior' content: ''' <p>African elephants have a complex social structure that takes the form of a matriarchal clan society. The basic social unit consists of a mother and her dependent offspring and grown daughters with their offspring. Each cow herd is typically made up of 9 to 11 elephants. Larger herds will often split into two or three units, but will remain within a mile of each other and communicate through rumbling calls so low in frequency they cannot be heard by humans. The matriarch sets the herd’s direction and pace, and the rest of the herd follows. When threatened, elephants will group around young calves. Males leave the cow herds at puberty at around 12 years of age. They live alone or in bachelor herds and are only seen near cow herds during the mating season. African elephants are not territorial, so male mating success depends largely on body size and tusk size.</p> ''' }, { title: 'Breeding' content: ''' African elephants give birth to one calf after a gestation period of 22 months. There is a four- to nine-year interval between calves. Bulls start to compete for females around 25, but bulls over 35 typically monopolize matings. The onset of musth, a state of heightened aggression and sexual activity, attracts cows in heat. ''' }, { title: 'Fun Facts' style: 'focus-box' content: ''' <ol> <li>African elephants use sounds well below the range of human hearing to communicate over long distances.</li> <li>The skull of the African elephant makes up 25% of its body weight.</li> </ol> ''' },{ title: 'Distribution' content: '<img src="assets/fieldguide-content/mammals/elephant/elephant-map.jpg"/>' }]
true
module.exports = label: 'African elephant' description: ''' African elephants are the largest land animals on earth. The trunk, a muscular extension of the upper lip and nose, contains the nostrils and has two opposing extensions at its end that are used for communication and handling objects including food. African elephants have huge ears, up to 2 x 1.5 m, which allow them to radiate excess heat. Both males and females have tusks—large, modified incisors that continuously grow throughout an elephant’s lifetime. Their skin is gray to brownish, wrinkled, and nearly hairless. Females are known as cows while males are known as bulls. ''' scientificName: '(PI:NAME:<NAME>END_PI)' mainImage: 'assets/fieldguide-content/mammals/elephant/elephant-feature.jpg' conservationStatus: 'Vulnerable' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well. information: [{ label: 'Length' value: '6.8-7.5 m' }, { label: 'Height' value: '2.5-3.3 m' }, { label: 'Weight' value: '3,000-6,000 kg' }, { label: 'Lifespan' value: '' }, { label: 'Gestation' value: '60-70 years' }, { label: 'Avg. number of offspring' value: '1' }] sections: [{ title: 'Habitat' content: 'African elephants live in almost any habitat that offers food and water.' }, { title: 'Diet' content: 'African elephants mainly eat leaves and branches of bushes and trees, but they also eat grasses, fruit, and bark.' }, { title: 'Predators' content: 'Humans, lions' }, { title: 'Behavior' content: ''' <p>African elephants have a complex social structure that takes the form of a matriarchal clan society. The basic social unit consists of a mother and her dependent offspring and grown daughters with their offspring. Each cow herd is typically made up of 9 to 11 elephants. Larger herds will often split into two or three units, but will remain within a mile of each other and communicate through rumbling calls so low in frequency they cannot be heard by humans. The matriarch sets the herd’s direction and pace, and the rest of the herd follows. When threatened, elephants will group around young calves. Males leave the cow herds at puberty at around 12 years of age. They live alone or in bachelor herds and are only seen near cow herds during the mating season. African elephants are not territorial, so male mating success depends largely on body size and tusk size.</p> ''' }, { title: 'Breeding' content: ''' African elephants give birth to one calf after a gestation period of 22 months. There is a four- to nine-year interval between calves. Bulls start to compete for females around 25, but bulls over 35 typically monopolize matings. The onset of musth, a state of heightened aggression and sexual activity, attracts cows in heat. ''' }, { title: 'Fun Facts' style: 'focus-box' content: ''' <ol> <li>African elephants use sounds well below the range of human hearing to communicate over long distances.</li> <li>The skull of the African elephant makes up 25% of its body weight.</li> </ol> ''' },{ title: 'Distribution' content: '<img src="assets/fieldguide-content/mammals/elephant/elephant-map.jpg"/>' }]
[ { "context": "#\t> File Name: discuss.coffee\n#\t> Author: LY\n#\t> Mail: ly.franky@gmail.com\n#\t> Created Time: T", "end": 44, "score": 0.9974496364593506, "start": 42, "tag": "USERNAME", "value": "LY" }, { "context": "File Name: discuss.coffee\n#\t> Author: LY\n#\t> Mail: ly.frank...
server/db/models/discuss.coffee
wiiliamking/miac-website
0
# > File Name: discuss.coffee # > Author: LY # > Mail: ly.franky@gmail.com # > Created Time: Thursday, December 04, 2014 PM02:11:09 CST mongoose = require 'mongoose' Schema = mongoose.Schema ObjectId = Schema.Types.ObjectId DiscussionSchema = new Schema type: String title: String content: String up: Number down: Number viewsCount: Number createdBy: ObjectId createdAt: { type: Date, default: Date.now } votedUsers: [ObjectId] answerTo: ObjectId userVoteForUp: [ObjectId] DiscussionModel = mongoose.model 'DiscussionModel', DiscussionSchema ### * create a discussion in DiscussionModel with type, title, content, user's id and answerTo * @param type: discussion's type * @param title: discussion's title * @param content: discussion's content * @param createdBy: user's id, to memorize who create the discussion * @param answerTo: the discussion's id that the answer reply to if this is a answer, else answerTo is ' * @param callback: the callback function that would execute when function ended ### DiscussionModel.createDiscussion = (type, title, content, createdBy, answerTo, callback)-> DiscussionModel.create type: type title: title if title isnt '' content: content up: 0 down: 0 viewsCount: 0 createdBy: createdBy answerTo: answerTo if answerTo isnt '' , (err)-> if err console.log err else callback() ### * find a discussion with discussionId * add 1 to up and save * @param discussionId: the id of the discussion to add up * @param createdBy: the user's id to memorize who votes for it * @param callback: the callback function that would execute when function ended ### DiscussionModel.up = (discussionId, createdBy, callback)-> DiscussionModel.findOne { _id: discussionId }, (err, discussion)-> if err console.log err else discussion.up++ discussion.votedUsers.push createdBy discussion.userVoteForUp.push createdBy discussion.save -> callback() ### * find a discussion with discussionId * add 1 to down and save * @param discussionId: the id of the discussion to add down * @param createdBy: the user's id to memorize who votes for it * @param callback: the callback function that would execute when function ended ### DiscussionModel.down = (discussionId, createdBy, callback)-> DiscussionModel.findOne { _id: discussionId }, (err, discussion)-> if err console.log err else discussion.down++ discussion.votedUsers.push createdBy discussion.save -> callback() ### * remove user's vote * @param removeUp: it is a boolean, whether removeUp, or remove down * @param discussionId: the id of the discussion to remove vote * @param createdBy: the user's id to memorize who is removing vote * @param callback: the callback function that would execute when function ended ### DiscussionModel.removeVote = (removeUp, discussionId, createdBy, callback)-> DiscussionModel.findOne { _id: discussionId }, (err, discussion)-> if err console.log err else index = 0 while index < discussion.votedUsers.length if discussion.votedUsers[index].toString() is createdBy discussion.votedUsers.splice(index, 1) break index++ if removeUp index = 0 while index < discussion.userVoteForUp.length if discussion.userVoteForUp[index].toString() is createdBy discussion.userVoteForUp.splice(index, 1) break index++ discussion.up-- else discussion.down-- discussion.save -> callback() ### * find a discussion by discussionId * add 1 to viewsCount * @param: discussionId: the id of the discussion to add views' count * @param callback: the callback function that would execute when function ended ### DiscussionModel.addViewsCount = (discussionId, callback)-> DiscussionModel.findOne { _id: discussionId }, (err, discussion)-> if err console.log err else discussion.viewsCount++ discussion.save -> callback() ### * drop all the discussions in DiscussionModel * @param callback: the callback function that would execute when function ended ### DiscussionModel.drop = (callback)-> DiscussionModel.remove {}, -> callback() module.exports = DiscussionModel
107938
# > File Name: discuss.coffee # > Author: LY # > Mail: <EMAIL> # > Created Time: Thursday, December 04, 2014 PM02:11:09 CST mongoose = require 'mongoose' Schema = mongoose.Schema ObjectId = Schema.Types.ObjectId DiscussionSchema = new Schema type: String title: String content: String up: Number down: Number viewsCount: Number createdBy: ObjectId createdAt: { type: Date, default: Date.now } votedUsers: [ObjectId] answerTo: ObjectId userVoteForUp: [ObjectId] DiscussionModel = mongoose.model 'DiscussionModel', DiscussionSchema ### * create a discussion in DiscussionModel with type, title, content, user's id and answerTo * @param type: discussion's type * @param title: discussion's title * @param content: discussion's content * @param createdBy: user's id, to memorize who create the discussion * @param answerTo: the discussion's id that the answer reply to if this is a answer, else answerTo is ' * @param callback: the callback function that would execute when function ended ### DiscussionModel.createDiscussion = (type, title, content, createdBy, answerTo, callback)-> DiscussionModel.create type: type title: title if title isnt '' content: content up: 0 down: 0 viewsCount: 0 createdBy: createdBy answerTo: answerTo if answerTo isnt '' , (err)-> if err console.log err else callback() ### * find a discussion with discussionId * add 1 to up and save * @param discussionId: the id of the discussion to add up * @param createdBy: the user's id to memorize who votes for it * @param callback: the callback function that would execute when function ended ### DiscussionModel.up = (discussionId, createdBy, callback)-> DiscussionModel.findOne { _id: discussionId }, (err, discussion)-> if err console.log err else discussion.up++ discussion.votedUsers.push createdBy discussion.userVoteForUp.push createdBy discussion.save -> callback() ### * find a discussion with discussionId * add 1 to down and save * @param discussionId: the id of the discussion to add down * @param createdBy: the user's id to memorize who votes for it * @param callback: the callback function that would execute when function ended ### DiscussionModel.down = (discussionId, createdBy, callback)-> DiscussionModel.findOne { _id: discussionId }, (err, discussion)-> if err console.log err else discussion.down++ discussion.votedUsers.push createdBy discussion.save -> callback() ### * remove user's vote * @param removeUp: it is a boolean, whether removeUp, or remove down * @param discussionId: the id of the discussion to remove vote * @param createdBy: the user's id to memorize who is removing vote * @param callback: the callback function that would execute when function ended ### DiscussionModel.removeVote = (removeUp, discussionId, createdBy, callback)-> DiscussionModel.findOne { _id: discussionId }, (err, discussion)-> if err console.log err else index = 0 while index < discussion.votedUsers.length if discussion.votedUsers[index].toString() is createdBy discussion.votedUsers.splice(index, 1) break index++ if removeUp index = 0 while index < discussion.userVoteForUp.length if discussion.userVoteForUp[index].toString() is createdBy discussion.userVoteForUp.splice(index, 1) break index++ discussion.up-- else discussion.down-- discussion.save -> callback() ### * find a discussion by discussionId * add 1 to viewsCount * @param: discussionId: the id of the discussion to add views' count * @param callback: the callback function that would execute when function ended ### DiscussionModel.addViewsCount = (discussionId, callback)-> DiscussionModel.findOne { _id: discussionId }, (err, discussion)-> if err console.log err else discussion.viewsCount++ discussion.save -> callback() ### * drop all the discussions in DiscussionModel * @param callback: the callback function that would execute when function ended ### DiscussionModel.drop = (callback)-> DiscussionModel.remove {}, -> callback() module.exports = DiscussionModel
true
# > File Name: discuss.coffee # > Author: LY # > Mail: PI:EMAIL:<EMAIL>END_PI # > Created Time: Thursday, December 04, 2014 PM02:11:09 CST mongoose = require 'mongoose' Schema = mongoose.Schema ObjectId = Schema.Types.ObjectId DiscussionSchema = new Schema type: String title: String content: String up: Number down: Number viewsCount: Number createdBy: ObjectId createdAt: { type: Date, default: Date.now } votedUsers: [ObjectId] answerTo: ObjectId userVoteForUp: [ObjectId] DiscussionModel = mongoose.model 'DiscussionModel', DiscussionSchema ### * create a discussion in DiscussionModel with type, title, content, user's id and answerTo * @param type: discussion's type * @param title: discussion's title * @param content: discussion's content * @param createdBy: user's id, to memorize who create the discussion * @param answerTo: the discussion's id that the answer reply to if this is a answer, else answerTo is ' * @param callback: the callback function that would execute when function ended ### DiscussionModel.createDiscussion = (type, title, content, createdBy, answerTo, callback)-> DiscussionModel.create type: type title: title if title isnt '' content: content up: 0 down: 0 viewsCount: 0 createdBy: createdBy answerTo: answerTo if answerTo isnt '' , (err)-> if err console.log err else callback() ### * find a discussion with discussionId * add 1 to up and save * @param discussionId: the id of the discussion to add up * @param createdBy: the user's id to memorize who votes for it * @param callback: the callback function that would execute when function ended ### DiscussionModel.up = (discussionId, createdBy, callback)-> DiscussionModel.findOne { _id: discussionId }, (err, discussion)-> if err console.log err else discussion.up++ discussion.votedUsers.push createdBy discussion.userVoteForUp.push createdBy discussion.save -> callback() ### * find a discussion with discussionId * add 1 to down and save * @param discussionId: the id of the discussion to add down * @param createdBy: the user's id to memorize who votes for it * @param callback: the callback function that would execute when function ended ### DiscussionModel.down = (discussionId, createdBy, callback)-> DiscussionModel.findOne { _id: discussionId }, (err, discussion)-> if err console.log err else discussion.down++ discussion.votedUsers.push createdBy discussion.save -> callback() ### * remove user's vote * @param removeUp: it is a boolean, whether removeUp, or remove down * @param discussionId: the id of the discussion to remove vote * @param createdBy: the user's id to memorize who is removing vote * @param callback: the callback function that would execute when function ended ### DiscussionModel.removeVote = (removeUp, discussionId, createdBy, callback)-> DiscussionModel.findOne { _id: discussionId }, (err, discussion)-> if err console.log err else index = 0 while index < discussion.votedUsers.length if discussion.votedUsers[index].toString() is createdBy discussion.votedUsers.splice(index, 1) break index++ if removeUp index = 0 while index < discussion.userVoteForUp.length if discussion.userVoteForUp[index].toString() is createdBy discussion.userVoteForUp.splice(index, 1) break index++ discussion.up-- else discussion.down-- discussion.save -> callback() ### * find a discussion by discussionId * add 1 to viewsCount * @param: discussionId: the id of the discussion to add views' count * @param callback: the callback function that would execute when function ended ### DiscussionModel.addViewsCount = (discussionId, callback)-> DiscussionModel.findOne { _id: discussionId }, (err, discussion)-> if err console.log err else discussion.viewsCount++ discussion.save -> callback() ### * drop all the discussions in DiscussionModel * @param callback: the callback function that would execute when function ended ### DiscussionModel.drop = (callback)-> DiscussionModel.remove {}, -> callback() module.exports = DiscussionModel
[ { "context": " user:\n data: [\n id: 1\n name: \"Bob\"\n primes: [1, 2, 3, 5, 7]\n ]\n \nd", "end": 238, "score": 0.9992029070854187, "start": 235, "tag": "NAME", "value": "Bob" }, { "context": " user = User.find(1)\n expect(user.name).toBe(\"B...
test/spec_coffee/model_populate_with_non_knows_about_spec.coffee
kirkbowers/mvcoffee
0
MVCoffee = require("../lib/mvcoffee") theUser = class User extends MVCoffee.Model store = new MVCoffee.ModelStore user: User store.load mvcoffee_version: "1.0.0" models: user: data: [ id: 1 name: "Bob" primes: [1, 2, 3, 5, 7] ] describe "models with hierarchical data that isn't known about", -> it "should have a simple array for non-known about complex property", -> user = User.find(1) expect(user.name).toBe("Bob") expect(user.primes.length).toBe(5) expect(user.primes[0]).toBe(1) expect(user.primes[1]).toBe(2) expect(user.primes[2]).toBe(3) expect(user.primes[3]).toBe(5) expect(user.primes[4]).toBe(7)
172462
MVCoffee = require("../lib/mvcoffee") theUser = class User extends MVCoffee.Model store = new MVCoffee.ModelStore user: User store.load mvcoffee_version: "1.0.0" models: user: data: [ id: 1 name: "<NAME>" primes: [1, 2, 3, 5, 7] ] describe "models with hierarchical data that isn't known about", -> it "should have a simple array for non-known about complex property", -> user = User.find(1) expect(user.name).toBe("<NAME>") expect(user.primes.length).toBe(5) expect(user.primes[0]).toBe(1) expect(user.primes[1]).toBe(2) expect(user.primes[2]).toBe(3) expect(user.primes[3]).toBe(5) expect(user.primes[4]).toBe(7)
true
MVCoffee = require("../lib/mvcoffee") theUser = class User extends MVCoffee.Model store = new MVCoffee.ModelStore user: User store.load mvcoffee_version: "1.0.0" models: user: data: [ id: 1 name: "PI:NAME:<NAME>END_PI" primes: [1, 2, 3, 5, 7] ] describe "models with hierarchical data that isn't known about", -> it "should have a simple array for non-known about complex property", -> user = User.find(1) expect(user.name).toBe("PI:NAME:<NAME>END_PI") expect(user.primes.length).toBe(5) expect(user.primes[0]).toBe(1) expect(user.primes[1]).toBe(2) expect(user.primes[2]).toBe(3) expect(user.primes[3]).toBe(5) expect(user.primes[4]).toBe(7)
[ { "context": " from Facebook on your timeline\n// @author Vadorequest\n// @supportURL https://github.com/Vadorequest", "end": 234, "score": 0.7881900668144226, "start": 223, "tag": "NAME", "value": "Vadorequest" }, { "context": "Vadorequest\n// @supportURL https://git...
src/index.coffee
Vadorequest/fb-adblock-sponsored-chrome-extension
0
### // ==UserScript== // @name Facebook AdBlock for your Timeline // @namespace http://tampermonkey.net/ // @version 1.0.2 // @description Hide ads from Facebook on your timeline // @author Vadorequest // @supportURL https://github.com/Vadorequest/fb-adblock-timeline/issues // @include https://www.facebook.com/* // @include https://facebook.com/* // @include http://www.facebook.com/* // @include http://facebook.com/* // @version 1.12 // ==/UserScript== ### class App constructor: -> @debug = false # Display logs. @appName = "Facebook AdBlock" # Used in logs. console.log "#{@appName} - Starting" if @debug @delay = 3000 # Delay between two attempts to delete a fracking ad. @adClass = 'userContentWrapper' # Class used by facebook to identify a <div> container. Used as a way to check we are deleting the right thing. # Texts to look for. Currently, there are only 2 different texts used by facebook. # TODO Handle I18n. Or just put a big array with all possibilities. (may be complicated to check the user language settings?) @texts = [ # EN 'Suggested Post' 'Sponsored' # FR 'Publication suggérée' 'Sponsorisé' ] # Run recursively. console.log "#{@appName} - Starting recursive search of ads" if @debug @run(true) find: (text) => @result = document.evaluate( "//*[text()='#{text}']" document null XPathResult.ORDERED_NODE_SNAPSHOT_TYPE ).snapshotItem(0) console.log "#{@appName} - Found an ad for '#{text}'" if @debug and @result removeAds: => if @result? # Get the container and deletes it. # XXX This depends upon the css class facebook relies on and may change in the future. container = @findParentClassLike(@result) container.remove() if container? console.log "#{@appName} - Ad deleted, looking for another", container if @debug and container # TODO Do something smart about this. It basically means we haven't found a proper container. Many possible reasons: # 1. FB has changed the container class name (most likely) # 2. There must be more reasons for this to fail, haven't found them yet! console.log "#{@appName} - Couldn't find the container of the ad" if @debug and not container # Look for another one right away in case of there would be several at once (ie: fast scroll). @run() # Main program. For each text, tries to find a result. If so, deletes it. Additionally run recursively. run: (recursive = false) => setTimeout => @texts.map (text) => @find(text) @removeAds() # Make it recursive. @run(@delay) if recursive , @delay # Try to find a parent <div> containing the class we're looking for. (In order to identify the ad container) findParentClassLike: (el) => while el.parentNode el = el.parentNode if el.className?.startsWith @adClass return el null # TRACK AND KILL THEM ALL! App = new App()
117998
### // ==UserScript== // @name Facebook AdBlock for your Timeline // @namespace http://tampermonkey.net/ // @version 1.0.2 // @description Hide ads from Facebook on your timeline // @author <NAME> // @supportURL https://github.com/Vadorequest/fb-adblock-timeline/issues // @include https://www.facebook.com/* // @include https://facebook.com/* // @include http://www.facebook.com/* // @include http://facebook.com/* // @version 1.12 // ==/UserScript== ### class App constructor: -> @debug = false # Display logs. @appName = "Facebook AdBlock" # Used in logs. console.log "#{@appName} - Starting" if @debug @delay = 3000 # Delay between two attempts to delete a fracking ad. @adClass = 'userContentWrapper' # Class used by facebook to identify a <div> container. Used as a way to check we are deleting the right thing. # Texts to look for. Currently, there are only 2 different texts used by facebook. # TODO Handle I18n. Or just put a big array with all possibilities. (may be complicated to check the user language settings?) @texts = [ # EN 'Suggested Post' 'Sponsored' # FR 'Publication suggérée' 'Sponsorisé' ] # Run recursively. console.log "#{@appName} - Starting recursive search of ads" if @debug @run(true) find: (text) => @result = document.evaluate( "//*[text()='#{text}']" document null XPathResult.ORDERED_NODE_SNAPSHOT_TYPE ).snapshotItem(0) console.log "#{@appName} - Found an ad for '#{text}'" if @debug and @result removeAds: => if @result? # Get the container and deletes it. # XXX This depends upon the css class facebook relies on and may change in the future. container = @findParentClassLike(@result) container.remove() if container? console.log "#{@appName} - Ad deleted, looking for another", container if @debug and container # TODO Do something smart about this. It basically means we haven't found a proper container. Many possible reasons: # 1. FB has changed the container class name (most likely) # 2. There must be more reasons for this to fail, haven't found them yet! console.log "#{@appName} - Couldn't find the container of the ad" if @debug and not container # Look for another one right away in case of there would be several at once (ie: fast scroll). @run() # Main program. For each text, tries to find a result. If so, deletes it. Additionally run recursively. run: (recursive = false) => setTimeout => @texts.map (text) => @find(text) @removeAds() # Make it recursive. @run(@delay) if recursive , @delay # Try to find a parent <div> containing the class we're looking for. (In order to identify the ad container) findParentClassLike: (el) => while el.parentNode el = el.parentNode if el.className?.startsWith @adClass return el null # TRACK AND KILL THEM ALL! App = new App()
true
### // ==UserScript== // @name Facebook AdBlock for your Timeline // @namespace http://tampermonkey.net/ // @version 1.0.2 // @description Hide ads from Facebook on your timeline // @author PI:NAME:<NAME>END_PI // @supportURL https://github.com/Vadorequest/fb-adblock-timeline/issues // @include https://www.facebook.com/* // @include https://facebook.com/* // @include http://www.facebook.com/* // @include http://facebook.com/* // @version 1.12 // ==/UserScript== ### class App constructor: -> @debug = false # Display logs. @appName = "Facebook AdBlock" # Used in logs. console.log "#{@appName} - Starting" if @debug @delay = 3000 # Delay between two attempts to delete a fracking ad. @adClass = 'userContentWrapper' # Class used by facebook to identify a <div> container. Used as a way to check we are deleting the right thing. # Texts to look for. Currently, there are only 2 different texts used by facebook. # TODO Handle I18n. Or just put a big array with all possibilities. (may be complicated to check the user language settings?) @texts = [ # EN 'Suggested Post' 'Sponsored' # FR 'Publication suggérée' 'Sponsorisé' ] # Run recursively. console.log "#{@appName} - Starting recursive search of ads" if @debug @run(true) find: (text) => @result = document.evaluate( "//*[text()='#{text}']" document null XPathResult.ORDERED_NODE_SNAPSHOT_TYPE ).snapshotItem(0) console.log "#{@appName} - Found an ad for '#{text}'" if @debug and @result removeAds: => if @result? # Get the container and deletes it. # XXX This depends upon the css class facebook relies on and may change in the future. container = @findParentClassLike(@result) container.remove() if container? console.log "#{@appName} - Ad deleted, looking for another", container if @debug and container # TODO Do something smart about this. It basically means we haven't found a proper container. Many possible reasons: # 1. FB has changed the container class name (most likely) # 2. There must be more reasons for this to fail, haven't found them yet! console.log "#{@appName} - Couldn't find the container of the ad" if @debug and not container # Look for another one right away in case of there would be several at once (ie: fast scroll). @run() # Main program. For each text, tries to find a result. If so, deletes it. Additionally run recursively. run: (recursive = false) => setTimeout => @texts.map (text) => @find(text) @removeAds() # Make it recursive. @run(@delay) if recursive , @delay # Try to find a parent <div> containing the class we're looking for. (In order to identify the ad container) findParentClassLike: (el) => while el.parentNode el = el.parentNode if el.className?.startsWith @adClass return el null # TRACK AND KILL THEM ALL! App = new App()
[ { "context": "a blank per team key encryption kid\"\n\nusers: {\n \"herb\": {}\n \"basil\": {}\n \"rose\": {}\n}\n\nteams: {\n \"ca", "end": 78, "score": 0.987602949142456, "start": 74, "tag": "USERNAME", "value": "herb" }, { "context": "eam key encryption kid\"\n\nusers: {\n \"...
teamchains/inputs/ptk_missing_enc_kid.iced
keybase/keybase-test-vectors
4
description: "Chain has a blank per team key encryption kid" users: { "herb": {} "basil": {} "rose": {} } teams: { "cabal": { links: [ type: "root" signer: "herb" members: owner: ["herb"] writer: ["basil"] corruptors: per_team_key: (section) -> delete section.encryption_kid section ] } } sessions: [ loads: [ error: true error_substr: "invalid per-team-key encryption KID" ] ]
41671
description: "Chain has a blank per team key encryption kid" users: { "herb": {} "bas<NAME>": {} "<NAME>": {} } teams: { "cabal": { links: [ type: "root" signer: "herb" members: owner: ["herb"] writer: ["<NAME>"] corruptors: per_team_key: (section) -> delete section.encryption_kid section ] } } sessions: [ loads: [ error: true error_substr: "invalid per-team-key encryption KID" ] ]
true
description: "Chain has a blank per team key encryption kid" users: { "herb": {} "basPI:NAME:<NAME>END_PI": {} "PI:NAME:<NAME>END_PI": {} } teams: { "cabal": { links: [ type: "root" signer: "herb" members: owner: ["herb"] writer: ["PI:NAME:<NAME>END_PI"] corruptors: per_team_key: (section) -> delete section.encryption_kid section ] } } sessions: [ loads: [ error: true error_substr: "invalid per-team-key encryption KID" ] ]
[ { "context": "form of the big five, the bfi-s or bfi-soep\n# see: Lang, F. R., John, D., Luedtke, O., Schupp, J., & Wagner, G. G", "end": 1876, "score": 0.9992592334747314, "start": 1866, "tag": "NAME", "value": "Lang, F. R" }, { "context": "ig five, the bfi-s or bfi-soep\n# see: Lan...
both/2_utils/personality/big_five.coffee
MooqitaSFH/worklearn
0
############################################################################### @big_five_40 = ["is the life of the party", "feels little concern for others", "is always prepared", "gets stressed out easily", "has a rich vocabulary", "does not talk a lot", "is interested in people", "leaves my belongings around", "is relaxed most of the time", "has difficulty understanding abstract ideas", "feels comfortable around people", "insults people", "pays attention to details", "worries about things", "has a vivid imagination", "keeps in the background", "sympathizes with others' feelings", "makes a mess of things", "seldom feel blue", "is not interested in abstract ideas", "starts conversations", "is not interested in other people's problems", "gets chores done right away", "is easily disturbed", "has excellent ideas", "has little to say", "has a soft heart", "often forgets to put things back in their proper place", "gets upset easily", "does not have a good imagination", "talks to a lot of different people at parties", "is not really interested in others", "likes order", "changes their mood a lot", "is quick to understand things", "doesn't like to draw attention to myself", "takes time out for others", "shirk their duties", "has frequent mood swings", "uses difficult words", "does't mind being the center of attention", "feels others' emotions", "follows a schedule", "gets irritated easily", "spends time reflecting on things", "is quiet around strangers", "makes people feel at ease", "is exacting in their work", "often feels blue", "is full of ideas"] # items below implement a well-validated short form of the big five, the bfi-s or bfi-soep # see: Lang, F. R., John, D., Luedtke, O., Schupp, J., & Wagner, G. G. (2011). Short assessment of the Big Five: robust across survey methods except telephone interviewing. Behavior Research Methods, 43(2), 548–567. https://doi.org/10.3758/s13428-011-0066-z ############################################################################### @big_five_15 = ["does a thorough job", "is talkative", "is sometimes rude to others", "is original, comes up with new ideas", "worries a lot", "has a forgiving nature", "tends to be lazy", "is outgoing, sociable", "values artistic, aesthetic experiences", "gets nervous easily", "does things efficiently", "is reserved", "is considerate and kind to almost everyone", "has an active imagination", "remains calm in tense situations" ] ############################################################################### @big_5_mean = Extroversion: m: 3.27 sd: 0.89 Agreeableness: m: 3.73 sd: 0.69 Conscientiousness: m: 3.63 sd: 0.71 Stability: m: 3.22 sd: 0.84 Openness: m: 3.92 sd: 0.67 ############################################################################### @calculate_trait_40 = (trait, answers) -> v = (i) -> q = big_five_40[i-1] n = answers[q] return Number(n) switch trait when "Extroversion" then return 20 + v(1) - v(6) + v(11) - v(16) + v(21) - v(26) + v(31) - v(36) + v(41) - v(46) when "Agreeableness" then return 14 - v(2) + v(7) - v(12) + v(17) - v(22) + v(27) - v(32) + v(37) + v(42) + v(47) when "Conscientiousness" then return 14 + v(3) - v(8) + v(13) - v(18) + v(23) - v(28) + v(33) - v(38) + v(43) + v(48) when "Stability" then return 2 + v(4) - v(9) + v(14) - v(19) + v(24) + v(29) + v(34) + v(39) + v(44) + v(49) when "Openness" then return 8 + v(5) - v(10) + v(15) - v(20) + v(25) - v(30) + v(35) + v(40) + v(45) + v(50) ############################################################################### @calculate_trait_15 = (trait, answers) -> v = (i) -> q = big_five_15[i-1] n = answers[q] return Number(n) scale_to_40 = 8 / 3 switch trait when "Extroversion" then return Math.round((v(2) + v(8) + (6 - v(12))) * scale_to_40) when "Agreeableness" then return Math.round(((6 - v(3)) + v(6) + v(13)) * scale_to_40) when "Conscientiousness" then return Math.round((v(1) + (6 - v(7)) + v(11)) * scale_to_40) when "Stability" then return Math.round((v(5) + v(10) + (6 - v(15))) * scale_to_40) when "Openness" then return Math.round((v(4) + v(9) + v(14)) * scale_to_40) ############################################################################### @calculate_trait = (trait, answers) -> l = Object.keys(answers).length switch when l == 15 then return calculate_trait_15(trait, answers) when l == 16 then return calculate_trait_15(trait, answers) when l == 50 then return calculate_trait_40(trait, answers) when l == 51 then return calculate_trait_40(trait, answers) console.log "length of test: " + l ############################################################################### @calculate_persona = (answers) -> C = calculate_trait "Conscientiousness", answers A = calculate_trait "Agreeableness", answers E = calculate_trait "Extroversion", answers S = calculate_trait "Stability", answers O = calculate_trait "Openness", answers persona = [ { label: "Stability", value: S }, { label: "Openness", value: O }, { label: "Agreeableness", value: A }, { label: "Extroversion", value: E }, { label: "Conscientiousness", value: C } ] return persona ############################################################################### @randomize_big_five = (questions) -> answers = {} for q in questions answers[q] = Math.round(Random.fraction() * 4) + 1 return answers
8331
############################################################################### @big_five_40 = ["is the life of the party", "feels little concern for others", "is always prepared", "gets stressed out easily", "has a rich vocabulary", "does not talk a lot", "is interested in people", "leaves my belongings around", "is relaxed most of the time", "has difficulty understanding abstract ideas", "feels comfortable around people", "insults people", "pays attention to details", "worries about things", "has a vivid imagination", "keeps in the background", "sympathizes with others' feelings", "makes a mess of things", "seldom feel blue", "is not interested in abstract ideas", "starts conversations", "is not interested in other people's problems", "gets chores done right away", "is easily disturbed", "has excellent ideas", "has little to say", "has a soft heart", "often forgets to put things back in their proper place", "gets upset easily", "does not have a good imagination", "talks to a lot of different people at parties", "is not really interested in others", "likes order", "changes their mood a lot", "is quick to understand things", "doesn't like to draw attention to myself", "takes time out for others", "shirk their duties", "has frequent mood swings", "uses difficult words", "does't mind being the center of attention", "feels others' emotions", "follows a schedule", "gets irritated easily", "spends time reflecting on things", "is quiet around strangers", "makes people feel at ease", "is exacting in their work", "often feels blue", "is full of ideas"] # items below implement a well-validated short form of the big five, the bfi-s or bfi-soep # see: <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2011). Short assessment of the Big Five: robust across survey methods except telephone interviewing. Behavior Research Methods, 43(2), 548–567. https://doi.org/10.3758/s13428-011-0066-z ############################################################################### @big_five_15 = ["does a thorough job", "is talkative", "is sometimes rude to others", "is original, comes up with new ideas", "worries a lot", "has a forgiving nature", "tends to be lazy", "is outgoing, sociable", "values artistic, aesthetic experiences", "gets nervous easily", "does things efficiently", "is reserved", "is considerate and kind to almost everyone", "has an active imagination", "remains calm in tense situations" ] ############################################################################### @big_5_mean = Extroversion: m: 3.27 sd: 0.89 Agreeableness: m: 3.73 sd: 0.69 Conscientiousness: m: 3.63 sd: 0.71 Stability: m: 3.22 sd: 0.84 Openness: m: 3.92 sd: 0.67 ############################################################################### @calculate_trait_40 = (trait, answers) -> v = (i) -> q = big_five_40[i-1] n = answers[q] return Number(n) switch trait when "Extroversion" then return 20 + v(1) - v(6) + v(11) - v(16) + v(21) - v(26) + v(31) - v(36) + v(41) - v(46) when "Agreeableness" then return 14 - v(2) + v(7) - v(12) + v(17) - v(22) + v(27) - v(32) + v(37) + v(42) + v(47) when "Conscientiousness" then return 14 + v(3) - v(8) + v(13) - v(18) + v(23) - v(28) + v(33) - v(38) + v(43) + v(48) when "Stability" then return 2 + v(4) - v(9) + v(14) - v(19) + v(24) + v(29) + v(34) + v(39) + v(44) + v(49) when "Openness" then return 8 + v(5) - v(10) + v(15) - v(20) + v(25) - v(30) + v(35) + v(40) + v(45) + v(50) ############################################################################### @calculate_trait_15 = (trait, answers) -> v = (i) -> q = big_five_15[i-1] n = answers[q] return Number(n) scale_to_40 = 8 / 3 switch trait when "Extroversion" then return Math.round((v(2) + v(8) + (6 - v(12))) * scale_to_40) when "Agreeableness" then return Math.round(((6 - v(3)) + v(6) + v(13)) * scale_to_40) when "Conscientiousness" then return Math.round((v(1) + (6 - v(7)) + v(11)) * scale_to_40) when "Stability" then return Math.round((v(5) + v(10) + (6 - v(15))) * scale_to_40) when "Openness" then return Math.round((v(4) + v(9) + v(14)) * scale_to_40) ############################################################################### @calculate_trait = (trait, answers) -> l = Object.keys(answers).length switch when l == 15 then return calculate_trait_15(trait, answers) when l == 16 then return calculate_trait_15(trait, answers) when l == 50 then return calculate_trait_40(trait, answers) when l == 51 then return calculate_trait_40(trait, answers) console.log "length of test: " + l ############################################################################### @calculate_persona = (answers) -> C = calculate_trait "Conscientiousness", answers A = calculate_trait "Agreeableness", answers E = calculate_trait "Extroversion", answers S = calculate_trait "Stability", answers O = calculate_trait "Openness", answers persona = [ { label: "Stability", value: S }, { label: "Openness", value: O }, { label: "Agreeableness", value: A }, { label: "Extroversion", value: E }, { label: "Conscientiousness", value: C } ] return persona ############################################################################### @randomize_big_five = (questions) -> answers = {} for q in questions answers[q] = Math.round(Random.fraction() * 4) + 1 return answers
true
############################################################################### @big_five_40 = ["is the life of the party", "feels little concern for others", "is always prepared", "gets stressed out easily", "has a rich vocabulary", "does not talk a lot", "is interested in people", "leaves my belongings around", "is relaxed most of the time", "has difficulty understanding abstract ideas", "feels comfortable around people", "insults people", "pays attention to details", "worries about things", "has a vivid imagination", "keeps in the background", "sympathizes with others' feelings", "makes a mess of things", "seldom feel blue", "is not interested in abstract ideas", "starts conversations", "is not interested in other people's problems", "gets chores done right away", "is easily disturbed", "has excellent ideas", "has little to say", "has a soft heart", "often forgets to put things back in their proper place", "gets upset easily", "does not have a good imagination", "talks to a lot of different people at parties", "is not really interested in others", "likes order", "changes their mood a lot", "is quick to understand things", "doesn't like to draw attention to myself", "takes time out for others", "shirk their duties", "has frequent mood swings", "uses difficult words", "does't mind being the center of attention", "feels others' emotions", "follows a schedule", "gets irritated easily", "spends time reflecting on things", "is quiet around strangers", "makes people feel at ease", "is exacting in their work", "often feels blue", "is full of ideas"] # items below implement a well-validated short form of the big five, the bfi-s or bfi-soep # see: PI:NAME:<NAME>END_PI., PI:NAME:<NAME>END_PI., PI:NAME:<NAME>END_PI., PI:NAME:<NAME>END_PI., & PI:NAME:<NAME>END_PI. (2011). Short assessment of the Big Five: robust across survey methods except telephone interviewing. Behavior Research Methods, 43(2), 548–567. https://doi.org/10.3758/s13428-011-0066-z ############################################################################### @big_five_15 = ["does a thorough job", "is talkative", "is sometimes rude to others", "is original, comes up with new ideas", "worries a lot", "has a forgiving nature", "tends to be lazy", "is outgoing, sociable", "values artistic, aesthetic experiences", "gets nervous easily", "does things efficiently", "is reserved", "is considerate and kind to almost everyone", "has an active imagination", "remains calm in tense situations" ] ############################################################################### @big_5_mean = Extroversion: m: 3.27 sd: 0.89 Agreeableness: m: 3.73 sd: 0.69 Conscientiousness: m: 3.63 sd: 0.71 Stability: m: 3.22 sd: 0.84 Openness: m: 3.92 sd: 0.67 ############################################################################### @calculate_trait_40 = (trait, answers) -> v = (i) -> q = big_five_40[i-1] n = answers[q] return Number(n) switch trait when "Extroversion" then return 20 + v(1) - v(6) + v(11) - v(16) + v(21) - v(26) + v(31) - v(36) + v(41) - v(46) when "Agreeableness" then return 14 - v(2) + v(7) - v(12) + v(17) - v(22) + v(27) - v(32) + v(37) + v(42) + v(47) when "Conscientiousness" then return 14 + v(3) - v(8) + v(13) - v(18) + v(23) - v(28) + v(33) - v(38) + v(43) + v(48) when "Stability" then return 2 + v(4) - v(9) + v(14) - v(19) + v(24) + v(29) + v(34) + v(39) + v(44) + v(49) when "Openness" then return 8 + v(5) - v(10) + v(15) - v(20) + v(25) - v(30) + v(35) + v(40) + v(45) + v(50) ############################################################################### @calculate_trait_15 = (trait, answers) -> v = (i) -> q = big_five_15[i-1] n = answers[q] return Number(n) scale_to_40 = 8 / 3 switch trait when "Extroversion" then return Math.round((v(2) + v(8) + (6 - v(12))) * scale_to_40) when "Agreeableness" then return Math.round(((6 - v(3)) + v(6) + v(13)) * scale_to_40) when "Conscientiousness" then return Math.round((v(1) + (6 - v(7)) + v(11)) * scale_to_40) when "Stability" then return Math.round((v(5) + v(10) + (6 - v(15))) * scale_to_40) when "Openness" then return Math.round((v(4) + v(9) + v(14)) * scale_to_40) ############################################################################### @calculate_trait = (trait, answers) -> l = Object.keys(answers).length switch when l == 15 then return calculate_trait_15(trait, answers) when l == 16 then return calculate_trait_15(trait, answers) when l == 50 then return calculate_trait_40(trait, answers) when l == 51 then return calculate_trait_40(trait, answers) console.log "length of test: " + l ############################################################################### @calculate_persona = (answers) -> C = calculate_trait "Conscientiousness", answers A = calculate_trait "Agreeableness", answers E = calculate_trait "Extroversion", answers S = calculate_trait "Stability", answers O = calculate_trait "Openness", answers persona = [ { label: "Stability", value: S }, { label: "Openness", value: O }, { label: "Agreeableness", value: A }, { label: "Extroversion", value: E }, { label: "Conscientiousness", value: C } ] return persona ############################################################################### @randomize_big_five = (questions) -> answers = {} for q in questions answers[q] = Math.round(Random.fraction() * 4) + 1 return answers
[ { "context": "t_800_38a__f_5_5 = (T, cb) ->\n tv =\n key : [ '603deb1015ca71be2b73aef0857d7781'\n '1f352c073b6108d72d9810a30914dff4' ]", "end": 329, "score": 0.9997491836547852, "start": 297, "tag": "KEY", "value": "603deb1015ca71be2b73aef0857d7781" }, { "context": "[ ...
test/files/aes_ctr.iced
CyberFlameGO/triplesec
274
{WordArray} = require '../../lib/wordarray' {AES} = require '../../lib/aes' ctr = require '../../lib/ctr' test_vec__nist_sp_800_38a__f_5_5 = # See http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf # Section F5.5 exports.sp_nist_800_38a__f_5_5 = (T, cb) -> tv = key : [ '603deb1015ca71be2b73aef0857d7781' '1f352c073b6108d72d9810a30914dff4' ].join('') iv : 'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff' pt : [ "6bc1bee22e409f96e93d7e117393172a", "ae2d8a571e03ac9c9eb76fac45af8e51", "30c81c46a35ce411e5fbc1191a0a52ef", "f69f2445df4f9b17ad2b417be66c3710" ].join('') ct : [ "601ec313775789a5b7a7f504bbf3d228" "f443e3ca4d62b59aca84e990cacaf5c5" "2b0930daa23de94ce87017ba2d84988d" "dfc9c58db67aada613c2dd08457941a6" ].join("") E = (input, cb) -> ctr.bulk_encrypt { block_cipher : new AES(WordArray.from_hex tv.key) iv : WordArray.from_hex tv.iv input : input }, cb pt = WordArray.from_hex tv.pt await E pt, defer out T.equal out.to_hex(), tv.ct, "Cipher text match" await E out, defer out T.equal out.to_hex(), tv.pt, "Plaintext decryption match" cb()
135838
{WordArray} = require '../../lib/wordarray' {AES} = require '../../lib/aes' ctr = require '../../lib/ctr' test_vec__nist_sp_800_38a__f_5_5 = # See http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf # Section F5.5 exports.sp_nist_800_38a__f_5_5 = (T, cb) -> tv = key : [ '<KEY>' '<KEY>' ].join('') iv : 'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff' pt : [ "6<KEY>", "ae2d8a571e03ac9c9eb76fac<KEY>af8e51", "30c81c46a35ce411e5fbc1191a0a52ef", "f69f2445df4f9b17ad2b417be66c3710" ].join('') ct : [ "6<KEY>8" "f443e3ca4d62b59aca84e990cacaf5c5" "2b0930daa23de94ce87017ba2d84988d" "dfc<KEY>c<KEY>67aada6<KEY>c<KEY>08<KEY>" ].join("") E = (input, cb) -> ctr.bulk_encrypt { block_cipher : new AES(WordArray.from_hex tv.key) iv : WordArray.from_hex tv.iv input : input }, cb pt = WordArray.from_hex tv.pt await E pt, defer out T.equal out.to_hex(), tv.ct, "Cipher text match" await E out, defer out T.equal out.to_hex(), tv.pt, "Plaintext decryption match" cb()
true
{WordArray} = require '../../lib/wordarray' {AES} = require '../../lib/aes' ctr = require '../../lib/ctr' test_vec__nist_sp_800_38a__f_5_5 = # See http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf # Section F5.5 exports.sp_nist_800_38a__f_5_5 = (T, cb) -> tv = key : [ 'PI:KEY:<KEY>END_PI' 'PI:KEY:<KEY>END_PI' ].join('') iv : 'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff' pt : [ "6PI:KEY:<KEY>END_PI", "ae2d8a571e03ac9c9eb76facPI:KEY:<KEY>END_PIaf8e51", "30c81c46a35ce411e5fbc1191a0a52ef", "f69f2445df4f9b17ad2b417be66c3710" ].join('') ct : [ "6PI:KEY:<KEY>END_PI8" "f443e3ca4d62b59aca84e990cacaf5c5" "2b0930daa23de94ce87017ba2d84988d" "dfcPI:KEY:<KEY>END_PIcPI:KEY:<KEY>END_PI67aada6PI:KEY:<KEY>END_PIcPI:KEY:<KEY>END_PI08PI:KEY:<KEY>END_PI" ].join("") E = (input, cb) -> ctr.bulk_encrypt { block_cipher : new AES(WordArray.from_hex tv.key) iv : WordArray.from_hex tv.iv input : input }, cb pt = WordArray.from_hex tv.pt await E pt, defer out T.equal out.to_hex(), tv.ct, "Cipher text match" await E out, defer out T.equal out.to_hex(), tv.pt, "Plaintext decryption match" cb()
[ { "context": "xt.qualifier\n Description: \"Auto created by Litexa\"\n FunctionVersion: \"$LATEST\"\n lambdaC", "end": 14582, "score": 0.8764393925666809, "start": 14576, "tag": "NAME", "value": "Litexa" }, { "context": "text.qualifier\n Description: \"Auto cr...
packages/litexa-deploy-aws/src/lambda.coffee
fboerncke/litexa
1
### # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ### fs = require 'fs' path = require 'path' mkdirp = require 'mkdirp' rimraf = require 'rimraf' util = require 'util' crypto = require 'crypto' AWS = require 'aws-sdk' uuid = require 'uuid' debug = require('debug')('litexa-deploy-lambda') writeFilePromise = util.promisify fs.writeFile readFilePromise = util.promisify fs.readFile SupportedOS = LINUX: 'linux', OSX: 'darwin', WIN: 'win32' writeFileIfDifferent = (filename, contents) -> readFilePromise filename, 'utf8' .catch (err) -> # fine if we can't read it, we'll assume we have to write return Promise.resolve() .then (fileContents) -> if contents == fileContents return Promise.resolve(false) else return writeFilePromise(filename, contents, 'utf8').then(-> Promise.resolve(true)) # TODO: Used for unit testing. Can remove when refactoring code to be more modular and test friendly # as eval does reduce runtime performance, but this should mainly be in the build process exports.unitTestHelper = (funcName) -> args = Array.prototype.slice.call arguments eval funcName .apply this, args[1..] exports.deploy = (context, logger) -> logger.log "deploying lambda" context.lambdaDeployStart = new Date lambdaContext = codeRoot: path.join context.deployRoot, 'lambda' litexaRoot: path.join context.projectRoot, 'litexa' call = (func) -> func context, logger, lambdaContext call preamble .then -> # all of this can happen at the same time step1 = [ call writeReadme call writeSkillJS call copyNodeModules call ensureDynamoTable ] Promise.all(step1) .then -> call packZipFile .then -> call createZipSHA256 .then -> call getLambdaConfig .then -> call updateLambdaConfig .then -> call updateLambdaCode .catch (err) -> if err.code != 'ResourceNotFoundException' throw err # doesn't exist, make it call createLambda .then -> call checkLambdaQualifier .then -> call checkLambdaPermissions .then -> call changeCloudwatchRetentionPolicy .then -> call endLambdaDeployment .catch (err) -> logger.error "lambda deployment failed" throw err preamble = (context, logger, lambdaContext) -> new Promise (resolve, reject) -> try require('./aws-config')(context, logger, AWS) mkdirp.sync lambdaContext.codeRoot lambdaContext.lambda = new AWS.Lambda context.lambdaName = [ context.projectInfo.name context.projectInfo.variant "litexa" "handler" ].join('_') # the alias we're going to deploy to lambdaContext.qualifier = "release-" + context.artifacts.currentVersion catch err return reject(err) resolve() writeReadme = (context, logger, lambdaContext) -> # readme readme = """ This lambda was generated by the litexa package and uploaded using the @litexa/deploy-aws package """ filename = path.join(lambdaContext.codeRoot,'readme.md') writeFileIfDifferent filename, readme .then (wrote) -> if wrote logger.log "wrote readme" writeSkillJS = (context, logger, lambdaContext) -> code = context.skill.toLambda() filename = path.join(lambdaContext.codeRoot,'index.js') writeFileIfDifferent filename, code .then (wrote) -> if wrote logger.log "wrote index.js" copyNodeModules = (context, logger, lambdaContext) -> sourceDir = path.join context.skill.projectInfo.litexaRoot, 'node_modules' targetDir = path.join lambdaContext.codeRoot modulesCache = path.join context.deployRoot, "modules.cache" logger.log "considering node_modules" # check to see if any files appear to be modified since the last time # we did this msSinceLastCopy = context.localCache.millisecondsSince 'copiedNodeModules' needsCopy = (location) -> unless fs.existsSync modulesCache return true unless msSinceLastCopy? return true secondInMillis = 1000 secondsSinceLastCopy = Math.ceil msSinceLastCopy / secondInMillis if process.platform == SupportedOS.WIN # WINCOMPAT - find the first thing that has changed since the last copy. Could use a faster # algorithm to find the last modified file more quickly. fileList = fs.readdirSync(sourceDir) .map (v) -> return { name: v, time: fs.statSync(path.join sourceDir, v).mtime.getTime() } # Grabs the timestamp of the most recently modified file from folder reducer = (prev, curr) -> return if prev.time > curr.time then prev else curr lastModifiedTime = fileList.reduce reducer, 0 .time return lastModifiedTime > ((new Date).getTime() - (secondsSinceLastCopy * secondInMillis)) else { execSync } = require('child_process') result = execSync "find -L #{sourceDir} -type f -atime -#{secondsSinceLastCopy}s | head -n 1" return result.length > 0 unless needsCopy sourceDir logger.log "node modules appear to be up to date" return Promise.resolve() packageJSONPath = path.join context.skill.projectInfo.litexaRoot, 'package.json' unless fs.existsSync packageJSONPath logger.log "no package.json found at #{packageJSONPath}, skipping node_modules" return Promise.resolve() nodeModulesPath = path.join context.skill.projectInfo.litexaRoot, 'node_modules' unless fs.existsSync nodeModulesPath throw new Error "no node_modules found at #{nodeModulesPath}, but we did see #{packageJSONPath}. Aborting for now. Did you perhaps miss running `npm install` from your litexa directory?" return Promise.resolve() new Promise (resolve, reject) -> startTime = new Date { exec } = require('child_process') execCmd = "rsync -crt --copy-links --delete --exclude '*.git' #{sourceDir} #{targetDir}" if process.platform == SupportedOS.WIN # WINCOMPAT - Windows uses robocopy in place of rsync to ensure files get replicated to destination execCmd = "robocopy #{sourceDir} #{targetDir} /mir /copy:DAT /sl /xf \"*.git\" /r:3 /w:4" exec execCmd, (err, stdout, stderr) -> logger.log "rsync: \n" + stdout if stdout deltaTime = (new Date) - startTime fs.writeFileSync modulesCache, '' logger.log "synchronized node_modules in #{deltaTime}ms" if err? reject(err) else if stderr logger.log stderr reject(err) else context.localCache.saveTimestamp 'copiedNodeModules' resolve() packZipFile = (context, logger, lambdaContext) -> new Promise (resolve, reject) -> logger.log "beginning zip archive" zipStart = new Date lambdaContext.zipFilename = path.join context.deployRoot, 'lambda.zip' lambdaSource = path.join(context.deployRoot,'lambda') debug "source directory: #{lambdaSource}" { exec } = require('child_process') zipFileCreationLogging = (err, stdout, stderr) -> logger.log "Platform: #{process.platform}" if process.platform == SupportedOS.WIN # WINCOMPAT - deletes old zip and creates new zip. There may be a faster way to zip on Windows zip = require 'adm-zip' zipper = new zip zipper.addLocalFolder lambdaSource zipper.writeZip lambdaContext.zipFilename zipLog = path.join context.deployRoot, 'zip.out.log' fs.writeFileSync zipLog, stdout zipLog = path.join context.deployRoot, 'zip.err.log' fs.writeFileSync zipLog, "" + err + stderr if err? logger.error err throw "failed to zip lambda" deltaTime = (new Date) - zipStart logger.log "zip archiving complete in #{deltaTime}ms" return resolve() if process.platform == SupportedOS.WIN # WINCOMPAT - using rimraf instead of rm -f for compatability rimraf '../data.zip', zipFileCreationLogging else exec "rm -f ../data.zip && zip -rX ../lambda.zip *", { cwd: lambdaSource maxBuffer: 1024 * 500 }, zipFileCreationLogging createZipSHA256 = (context, logger, lambdaContext) -> new Promise (resolve, reject) -> shasum = crypto.createHash('sha256') fs.createReadStream lambdaContext.zipFilename .on "data", (chunk) -> shasum.update chunk .on "end", -> lambdaContext.zipSHA256 = shasum.digest('base64') logger.log "zip SHA: #{lambdaContext.zipSHA256}" resolve() .on "error", (err) -> reject err getLambdaConfig = (context, logger, lambdaContext) -> if context.localCache.lessThanSince 'lambdaUpdated', 30 # it's ok to skip this during iteration, so do it every half hour lambdaContext.deployedSHA256 = context.localCache.getHash 'lambdaSHA256' logger.log "skipping Lambda #{context.lambdaName} configuration check" return Promise.resolve() logger.log "fetching Lambda #{context.lambdaName} configuration" params = FunctionName: context.lambdaName lambdaContext.lambda.getFunctionConfiguration(params).promise() .then (data) -> logger.log "fetched Lambda configuration" lambdaContext.deployedSHA256 = data.CodeSha256 lambdaContext.deployedLambdaConfig = data setLambdaARN context, lambdaContext, data.FunctionArn Promise.resolve data setLambdaARN = (context, lambdaContext, newARN) -> aliasedARN = "#{newARN}:#{lambdaContext.qualifier}" lambdaContext.baseARN = newARN context.lambdaARN = aliasedARN context.artifacts.save 'lambdaARN', aliasedARN makeLambdaConfiguration = (context, logger) -> require('./iam-roles').ensureLambdaIAMRole(context, logger) .then -> loggingLevel = if context.projectInfo.variant in ['alpha', 'beta', 'gamma'] undefined else 'terse' loggingLevel = 'terse' config = Description: "Litexa skill handler for project #{context.projectInfo.name}" Handler: "index.handler" # exports.handler in index.js MemorySize: 256 # megabytes, mainly because this also means dedicated CPU Role: context.lambdaIAMRoleARN Runtime: "nodejs8.10" Timeout: 10 # seconds Environment: Variables: variant: context.projectInfo.variant loggingLevel: loggingLevel dynamoTableName: context.dynamoTableName assetsRoot: context.artifacts.get 'assets-root' if context.deploymentOptions.lambdaConfiguration? # if this option is present, merge that object into the config, key by key mergeValue = ( target, key, value, stringify ) -> if key of target if typeof(target[key]) == 'object' # recurse into objects unless typeof(value) == 'object' throw "value of key #{key} was expected to be an object in lambdaConfiguration, but was instead #{JSON.stringify value}" for k, v of value # variable value must be strings, so switch here if k == 'Variables' stringify = true mergeValue target[key], k, v, stringify return if stringify target[key] = '' + value else target[key] = value for k, v of context.deploymentOptions.lambdaConfiguration mergeValue config, k, v, false debug "Lambda config: " + JSON.stringify config, null, 2 return config createLambda = (context, logger, lambdaContext) -> logger.log "creating Lambda function #{context.lambdaName}" params = Code: ZipFile: fs.readFileSync(lambdaContext.zipFilename) FunctionName: context.lambdaName Publish: true, VpcConfig: {} makeLambdaConfiguration(context, logger) .then (lambdaConfig) -> for k, v of lambdaConfig params[k] = v lambdaContext.lambda.createFunction(params).promise() .then (data) -> logger.verbose 'create-function', data logger.log "creating LIVE alias for Lambda function #{context.lambdaName}" lambdaContext.deployedSHA256 = data.CodeSha256 setLambdaARN context, lambdaContext, data.FunctionArn # create the live alias, to support easy # console based rollbacks in emergencies params = FunctionName: context.lambdaName FunctionVersion: '$LATEST' Name: 'LIVE' Description: 'Current live version, used to refer to this lambda by the Alexa skill. In an emergency, you can point this to an older version of the code.' lambdaContext.lambda.createAlias(params).promise() updateLambdaConfig = (context, logger, lambdaContext) -> needsUpdating = false matchObject = (a, b) -> unless b? return needsUpdating = true for k, v of a if typeof(v) == 'object' matchObject v, b[k] else if v? and b[k] != v logger.log "lambda configuration mismatch: #{k}:#{b[k]} should be #{v}" needsUpdating = true makeLambdaConfiguration context, logger .then (lambdaConfig) -> matchObject lambdaConfig, lambdaContext.deployedLambdaConfig unless needsUpdating return Promise.resolve() logger.log "patching Lambda configuration" params = FunctionName: context.lambdaName for k, v of lambdaConfig params[k] = v lambdaContext.lambda.updateFunctionConfiguration(params).promise() updateLambdaCode = (context, logger, lambdaContext) -> # todo: with node_modules it's much easier to get bigger than # updateFunctionCode supports... will have to go through S3 then? if lambdaContext.deployedSHA256 == lambdaContext.zipSHA256 logger.log "Lambda function #{context.lambdaName} code already up to date" return Promise.resolve() logger.log "updating code for Lambda function #{context.lambdaName}" params = FunctionName: context.lambdaName Publish: true ZipFile: fs.readFileSync(lambdaContext.zipFilename) lambdaContext.lambda.updateFunctionCode(params).promise() .then (data) -> context.localCache.storeHash 'lambdaSHA256', data.CodeSha256 checkLambdaQualifier = (context, logger, lambdaContext) -> params = FunctionName: context.lambdaName Name: lambdaContext.qualifier lambdaContext.lambda.getAlias(params).promise() .catch (err) -> if err.code == "ResourceNotFoundException" # not found is fine, we'll make it params = FunctionName: context.lambdaName Name: lambdaContext.qualifier Description: "Auto created by Litexa" FunctionVersion: "$LATEST" lambdaContext.lambda.createAlias(params).promise() .catch (err) -> logger.error err throw "Failed to create alias #{lambdaContext.qualifier}" throw new Error "Failed to create alias #{lambdaContext.qualifier}" .then (data) -> logger.verbose 'createAlias', data Promise.resolve(data) else logger.error err throw "Failed to fetch alias for lambda #{context.lambdaName}, #{lambdaContext.qualifier}" Promise.resolve() .then (data) -> # the development head should always be latest if data.FunctionVersion == '$LATEST' return Promise.resolve() params = RevisionId: data.RevisionId FunctionName: context.lambdaName Name: lambdaContext.qualifier Description: "Auto created by Litexa" FunctionVersion: "$LATEST" lambdaContext.lambda.updateAlias(params).promise() checkLambdaPermissions = (context, logger, lambdaContext) -> if context.localCache.timestampExists "lambdaPermissionsChecked-#{lambdaContext.qualifier}" return Promise.resolve() addPolicy = (cache) -> logger.log "adding policies to Lambda #{context.lambdaName}" params = FunctionName: context.lambdaName Action: 'lambda:InvokeFunction' StatementId: 'lc-' + uuid.v4() Principal: 'alexa-appkit.amazon.com' Qualifier: lambdaContext.qualifier lambdaContext.lambda.addPermission(params).promise() .catch (err) -> logger.error "Failed to add permissions to lambda: #{err}" .then (data) -> logger.verbose "addPermission: #{JSON.stringify(data, null, 2)}" removePolicy = (statement) -> logger.log "removing policy #{statement.Sid} from lambda #{context.lambdaName}" params = FunctionName: context.lambdaName StatementId: statement.Sid Qualifier: lambdaContext.qualifier lambdaContext.lambda.removePermission(params).promise() .catch (err) -> logger.error err throw "failed to remove bad lambda permission" logger.log "pulling existing policies" params = FunctionName: context.lambdaName Qualifier: lambdaContext.qualifier lambdaContext.lambda.getPolicy(params).promise() .catch (err) -> # ResourceNotFoundException is fine, might not have a policy if err.code != "ResourceNotFoundException" logger.error err throw "Failed to fetch policies for lambda #{context.lambdaName}" .then (data) -> promises = [] foundCorrectPolicy = false if data? logger.log "reconciling policies against existing data" # analyze the existing one policy = JSON.parse(data.Policy) for statement in policy.Statement # is this the ask statement? continue unless statement.Principal?.Service == "alexa-appkit.amazon.com" # still the right contents? lambdaARN = context.artifacts.get 'lambdaARN' if lambdaARN? and statement.Resource == lambdaARN and statement.Effect == 'Allow' and statement.Action == 'lambda:InvokeFunction' foundCorrectPolicy = true else promises.push removePolicy(statement) unless foundCorrectPolicy promises.push addPolicy() Promise.all(promises) .then -> context.localCache.saveTimestamp "lambdaPermissionsChecked-#{lambdaContext.qualifier}" endLambdaDeployment = (context, logger, lambdaContext) -> deltaTime = (new Date) - context.lambdaDeployStart logger.log "lambda deployment complete in #{deltaTime}ms" context.localCache.saveTimestamp 'lambdaUpdated' ensureDynamoTable = (context, logger, lambdaContext) -> context.dynamoTableName = [ context.projectInfo.name context.projectInfo.variant "litexa_handler_state" ].join '_' # if its existence is already verified, no need to do so anymore if context.localCache.timestampExists 'ensuredDynamoTable' return Promise.resolve() dynamo = new AWS.DynamoDB { params: TableName: context.dynamoTableName } logger.log "fetching dynamoDB information" dynamo.describeTable({}).promise() .catch (err) -> if err.code != 'ResourceNotFoundException' logger.error err throw "failed to ensure dynamoDB table exists" logger.log "dynamoDB table not found, creating #{context.dynamoTableName}" params = AttributeDefinitions: [ { AttributeName: "userId" AttributeType: "S" } ], KeySchema: [ { AttributeName: "userId" KeyType: "HASH" } ] ProvisionedThroughput: ReadCapacityUnits: 10, WriteCapacityUnits: 10 dynamo.createTable(params).promise() .then -> context.localCache.saveTimestamp 'createdDynamoTable' dynamo.describeTable({}).promise() .then (data) -> logger.log "verified dynamoDB table exists" context.dynamoTableARN = data.Table.TableArn context.artifacts.save 'dynamoDBARN', data.Table.TableArn context.localCache.saveTimestamp 'ensuredDynamoTable' # only modify the retention policy if it's creating an new log group changeCloudwatchRetentionPolicy = (context, logger, lambdaContext) -> if context.localCache.timestampExists 'ensuredCloudwatchLogGroup' return Promise.resolve() logGroupName = "/aws/lambda/#{context.lambdaName}" cloudwatch = new AWS.CloudWatchLogs() params = { logGroupNamePrefix: logGroupName } cloudwatch.describeLogGroups(params).promise() .then (data) -> logGroupExists = false for logGroup in data.logGroups if logGroup.logGroupName == logGroupName logGroupExists = true break if logGroupExists context.localCache.saveTimestamp 'ensuredCloudwatchLogGroup' return Promise.resolve() params = { logGroupName } cloudwatch.createLogGroup(params).promise() .then -> logger.log "Created Cloudwatch log group for lambda" params = { logGroupName: logGroupName retentionInDays: 30 } context.localCache.saveTimestamp 'ensuredCloudwatchLogGroup' cloudwatch.putRetentionPolicy(params).promise() .then -> logger.log "Updated CloudWatch retention policy to 30 days" context.localCache.saveTimestamp 'appliedLogRetentionPolicy' return Promise.resolve()
83608
### # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ### fs = require 'fs' path = require 'path' mkdirp = require 'mkdirp' rimraf = require 'rimraf' util = require 'util' crypto = require 'crypto' AWS = require 'aws-sdk' uuid = require 'uuid' debug = require('debug')('litexa-deploy-lambda') writeFilePromise = util.promisify fs.writeFile readFilePromise = util.promisify fs.readFile SupportedOS = LINUX: 'linux', OSX: 'darwin', WIN: 'win32' writeFileIfDifferent = (filename, contents) -> readFilePromise filename, 'utf8' .catch (err) -> # fine if we can't read it, we'll assume we have to write return Promise.resolve() .then (fileContents) -> if contents == fileContents return Promise.resolve(false) else return writeFilePromise(filename, contents, 'utf8').then(-> Promise.resolve(true)) # TODO: Used for unit testing. Can remove when refactoring code to be more modular and test friendly # as eval does reduce runtime performance, but this should mainly be in the build process exports.unitTestHelper = (funcName) -> args = Array.prototype.slice.call arguments eval funcName .apply this, args[1..] exports.deploy = (context, logger) -> logger.log "deploying lambda" context.lambdaDeployStart = new Date lambdaContext = codeRoot: path.join context.deployRoot, 'lambda' litexaRoot: path.join context.projectRoot, 'litexa' call = (func) -> func context, logger, lambdaContext call preamble .then -> # all of this can happen at the same time step1 = [ call writeReadme call writeSkillJS call copyNodeModules call ensureDynamoTable ] Promise.all(step1) .then -> call packZipFile .then -> call createZipSHA256 .then -> call getLambdaConfig .then -> call updateLambdaConfig .then -> call updateLambdaCode .catch (err) -> if err.code != 'ResourceNotFoundException' throw err # doesn't exist, make it call createLambda .then -> call checkLambdaQualifier .then -> call checkLambdaPermissions .then -> call changeCloudwatchRetentionPolicy .then -> call endLambdaDeployment .catch (err) -> logger.error "lambda deployment failed" throw err preamble = (context, logger, lambdaContext) -> new Promise (resolve, reject) -> try require('./aws-config')(context, logger, AWS) mkdirp.sync lambdaContext.codeRoot lambdaContext.lambda = new AWS.Lambda context.lambdaName = [ context.projectInfo.name context.projectInfo.variant "litexa" "handler" ].join('_') # the alias we're going to deploy to lambdaContext.qualifier = "release-" + context.artifacts.currentVersion catch err return reject(err) resolve() writeReadme = (context, logger, lambdaContext) -> # readme readme = """ This lambda was generated by the litexa package and uploaded using the @litexa/deploy-aws package """ filename = path.join(lambdaContext.codeRoot,'readme.md') writeFileIfDifferent filename, readme .then (wrote) -> if wrote logger.log "wrote readme" writeSkillJS = (context, logger, lambdaContext) -> code = context.skill.toLambda() filename = path.join(lambdaContext.codeRoot,'index.js') writeFileIfDifferent filename, code .then (wrote) -> if wrote logger.log "wrote index.js" copyNodeModules = (context, logger, lambdaContext) -> sourceDir = path.join context.skill.projectInfo.litexaRoot, 'node_modules' targetDir = path.join lambdaContext.codeRoot modulesCache = path.join context.deployRoot, "modules.cache" logger.log "considering node_modules" # check to see if any files appear to be modified since the last time # we did this msSinceLastCopy = context.localCache.millisecondsSince 'copiedNodeModules' needsCopy = (location) -> unless fs.existsSync modulesCache return true unless msSinceLastCopy? return true secondInMillis = 1000 secondsSinceLastCopy = Math.ceil msSinceLastCopy / secondInMillis if process.platform == SupportedOS.WIN # WINCOMPAT - find the first thing that has changed since the last copy. Could use a faster # algorithm to find the last modified file more quickly. fileList = fs.readdirSync(sourceDir) .map (v) -> return { name: v, time: fs.statSync(path.join sourceDir, v).mtime.getTime() } # Grabs the timestamp of the most recently modified file from folder reducer = (prev, curr) -> return if prev.time > curr.time then prev else curr lastModifiedTime = fileList.reduce reducer, 0 .time return lastModifiedTime > ((new Date).getTime() - (secondsSinceLastCopy * secondInMillis)) else { execSync } = require('child_process') result = execSync "find -L #{sourceDir} -type f -atime -#{secondsSinceLastCopy}s | head -n 1" return result.length > 0 unless needsCopy sourceDir logger.log "node modules appear to be up to date" return Promise.resolve() packageJSONPath = path.join context.skill.projectInfo.litexaRoot, 'package.json' unless fs.existsSync packageJSONPath logger.log "no package.json found at #{packageJSONPath}, skipping node_modules" return Promise.resolve() nodeModulesPath = path.join context.skill.projectInfo.litexaRoot, 'node_modules' unless fs.existsSync nodeModulesPath throw new Error "no node_modules found at #{nodeModulesPath}, but we did see #{packageJSONPath}. Aborting for now. Did you perhaps miss running `npm install` from your litexa directory?" return Promise.resolve() new Promise (resolve, reject) -> startTime = new Date { exec } = require('child_process') execCmd = "rsync -crt --copy-links --delete --exclude '*.git' #{sourceDir} #{targetDir}" if process.platform == SupportedOS.WIN # WINCOMPAT - Windows uses robocopy in place of rsync to ensure files get replicated to destination execCmd = "robocopy #{sourceDir} #{targetDir} /mir /copy:DAT /sl /xf \"*.git\" /r:3 /w:4" exec execCmd, (err, stdout, stderr) -> logger.log "rsync: \n" + stdout if stdout deltaTime = (new Date) - startTime fs.writeFileSync modulesCache, '' logger.log "synchronized node_modules in #{deltaTime}ms" if err? reject(err) else if stderr logger.log stderr reject(err) else context.localCache.saveTimestamp 'copiedNodeModules' resolve() packZipFile = (context, logger, lambdaContext) -> new Promise (resolve, reject) -> logger.log "beginning zip archive" zipStart = new Date lambdaContext.zipFilename = path.join context.deployRoot, 'lambda.zip' lambdaSource = path.join(context.deployRoot,'lambda') debug "source directory: #{lambdaSource}" { exec } = require('child_process') zipFileCreationLogging = (err, stdout, stderr) -> logger.log "Platform: #{process.platform}" if process.platform == SupportedOS.WIN # WINCOMPAT - deletes old zip and creates new zip. There may be a faster way to zip on Windows zip = require 'adm-zip' zipper = new zip zipper.addLocalFolder lambdaSource zipper.writeZip lambdaContext.zipFilename zipLog = path.join context.deployRoot, 'zip.out.log' fs.writeFileSync zipLog, stdout zipLog = path.join context.deployRoot, 'zip.err.log' fs.writeFileSync zipLog, "" + err + stderr if err? logger.error err throw "failed to zip lambda" deltaTime = (new Date) - zipStart logger.log "zip archiving complete in #{deltaTime}ms" return resolve() if process.platform == SupportedOS.WIN # WINCOMPAT - using rimraf instead of rm -f for compatability rimraf '../data.zip', zipFileCreationLogging else exec "rm -f ../data.zip && zip -rX ../lambda.zip *", { cwd: lambdaSource maxBuffer: 1024 * 500 }, zipFileCreationLogging createZipSHA256 = (context, logger, lambdaContext) -> new Promise (resolve, reject) -> shasum = crypto.createHash('sha256') fs.createReadStream lambdaContext.zipFilename .on "data", (chunk) -> shasum.update chunk .on "end", -> lambdaContext.zipSHA256 = shasum.digest('base64') logger.log "zip SHA: #{lambdaContext.zipSHA256}" resolve() .on "error", (err) -> reject err getLambdaConfig = (context, logger, lambdaContext) -> if context.localCache.lessThanSince 'lambdaUpdated', 30 # it's ok to skip this during iteration, so do it every half hour lambdaContext.deployedSHA256 = context.localCache.getHash 'lambdaSHA256' logger.log "skipping Lambda #{context.lambdaName} configuration check" return Promise.resolve() logger.log "fetching Lambda #{context.lambdaName} configuration" params = FunctionName: context.lambdaName lambdaContext.lambda.getFunctionConfiguration(params).promise() .then (data) -> logger.log "fetched Lambda configuration" lambdaContext.deployedSHA256 = data.CodeSha256 lambdaContext.deployedLambdaConfig = data setLambdaARN context, lambdaContext, data.FunctionArn Promise.resolve data setLambdaARN = (context, lambdaContext, newARN) -> aliasedARN = "#{newARN}:#{lambdaContext.qualifier}" lambdaContext.baseARN = newARN context.lambdaARN = aliasedARN context.artifacts.save 'lambdaARN', aliasedARN makeLambdaConfiguration = (context, logger) -> require('./iam-roles').ensureLambdaIAMRole(context, logger) .then -> loggingLevel = if context.projectInfo.variant in ['alpha', 'beta', 'gamma'] undefined else 'terse' loggingLevel = 'terse' config = Description: "Litexa skill handler for project #{context.projectInfo.name}" Handler: "index.handler" # exports.handler in index.js MemorySize: 256 # megabytes, mainly because this also means dedicated CPU Role: context.lambdaIAMRoleARN Runtime: "nodejs8.10" Timeout: 10 # seconds Environment: Variables: variant: context.projectInfo.variant loggingLevel: loggingLevel dynamoTableName: context.dynamoTableName assetsRoot: context.artifacts.get 'assets-root' if context.deploymentOptions.lambdaConfiguration? # if this option is present, merge that object into the config, key by key mergeValue = ( target, key, value, stringify ) -> if key of target if typeof(target[key]) == 'object' # recurse into objects unless typeof(value) == 'object' throw "value of key #{key} was expected to be an object in lambdaConfiguration, but was instead #{JSON.stringify value}" for k, v of value # variable value must be strings, so switch here if k == 'Variables' stringify = true mergeValue target[key], k, v, stringify return if stringify target[key] = '' + value else target[key] = value for k, v of context.deploymentOptions.lambdaConfiguration mergeValue config, k, v, false debug "Lambda config: " + JSON.stringify config, null, 2 return config createLambda = (context, logger, lambdaContext) -> logger.log "creating Lambda function #{context.lambdaName}" params = Code: ZipFile: fs.readFileSync(lambdaContext.zipFilename) FunctionName: context.lambdaName Publish: true, VpcConfig: {} makeLambdaConfiguration(context, logger) .then (lambdaConfig) -> for k, v of lambdaConfig params[k] = v lambdaContext.lambda.createFunction(params).promise() .then (data) -> logger.verbose 'create-function', data logger.log "creating LIVE alias for Lambda function #{context.lambdaName}" lambdaContext.deployedSHA256 = data.CodeSha256 setLambdaARN context, lambdaContext, data.FunctionArn # create the live alias, to support easy # console based rollbacks in emergencies params = FunctionName: context.lambdaName FunctionVersion: '$LATEST' Name: 'LIVE' Description: 'Current live version, used to refer to this lambda by the Alexa skill. In an emergency, you can point this to an older version of the code.' lambdaContext.lambda.createAlias(params).promise() updateLambdaConfig = (context, logger, lambdaContext) -> needsUpdating = false matchObject = (a, b) -> unless b? return needsUpdating = true for k, v of a if typeof(v) == 'object' matchObject v, b[k] else if v? and b[k] != v logger.log "lambda configuration mismatch: #{k}:#{b[k]} should be #{v}" needsUpdating = true makeLambdaConfiguration context, logger .then (lambdaConfig) -> matchObject lambdaConfig, lambdaContext.deployedLambdaConfig unless needsUpdating return Promise.resolve() logger.log "patching Lambda configuration" params = FunctionName: context.lambdaName for k, v of lambdaConfig params[k] = v lambdaContext.lambda.updateFunctionConfiguration(params).promise() updateLambdaCode = (context, logger, lambdaContext) -> # todo: with node_modules it's much easier to get bigger than # updateFunctionCode supports... will have to go through S3 then? if lambdaContext.deployedSHA256 == lambdaContext.zipSHA256 logger.log "Lambda function #{context.lambdaName} code already up to date" return Promise.resolve() logger.log "updating code for Lambda function #{context.lambdaName}" params = FunctionName: context.lambdaName Publish: true ZipFile: fs.readFileSync(lambdaContext.zipFilename) lambdaContext.lambda.updateFunctionCode(params).promise() .then (data) -> context.localCache.storeHash 'lambdaSHA256', data.CodeSha256 checkLambdaQualifier = (context, logger, lambdaContext) -> params = FunctionName: context.lambdaName Name: lambdaContext.qualifier lambdaContext.lambda.getAlias(params).promise() .catch (err) -> if err.code == "ResourceNotFoundException" # not found is fine, we'll make it params = FunctionName: context.lambdaName Name: lambdaContext.qualifier Description: "Auto created by <NAME>" FunctionVersion: "$LATEST" lambdaContext.lambda.createAlias(params).promise() .catch (err) -> logger.error err throw "Failed to create alias #{lambdaContext.qualifier}" throw new Error "Failed to create alias #{lambdaContext.qualifier}" .then (data) -> logger.verbose 'createAlias', data Promise.resolve(data) else logger.error err throw "Failed to fetch alias for lambda #{context.lambdaName}, #{lambdaContext.qualifier}" Promise.resolve() .then (data) -> # the development head should always be latest if data.FunctionVersion == '$LATEST' return Promise.resolve() params = RevisionId: data.RevisionId FunctionName: context.lambdaName Name: lambdaContext.qualifier Description: "Auto created by <NAME>" FunctionVersion: "$LATEST" lambdaContext.lambda.updateAlias(params).promise() checkLambdaPermissions = (context, logger, lambdaContext) -> if context.localCache.timestampExists "lambdaPermissionsChecked-#{lambdaContext.qualifier}" return Promise.resolve() addPolicy = (cache) -> logger.log "adding policies to Lambda #{context.lambdaName}" params = FunctionName: context.lambdaName Action: 'lambda:InvokeFunction' StatementId: 'lc-' + uuid.v4() Principal: 'alexa-appkit.amazon.com' Qualifier: lambdaContext.qualifier lambdaContext.lambda.addPermission(params).promise() .catch (err) -> logger.error "Failed to add permissions to lambda: #{err}" .then (data) -> logger.verbose "addPermission: #{JSON.stringify(data, null, 2)}" removePolicy = (statement) -> logger.log "removing policy #{statement.Sid} from lambda #{context.lambdaName}" params = FunctionName: context.lambdaName StatementId: statement.Sid Qualifier: lambdaContext.qualifier lambdaContext.lambda.removePermission(params).promise() .catch (err) -> logger.error err throw "failed to remove bad lambda permission" logger.log "pulling existing policies" params = FunctionName: context.lambdaName Qualifier: lambdaContext.qualifier lambdaContext.lambda.getPolicy(params).promise() .catch (err) -> # ResourceNotFoundException is fine, might not have a policy if err.code != "ResourceNotFoundException" logger.error err throw "Failed to fetch policies for lambda #{context.lambdaName}" .then (data) -> promises = [] foundCorrectPolicy = false if data? logger.log "reconciling policies against existing data" # analyze the existing one policy = JSON.parse(data.Policy) for statement in policy.Statement # is this the ask statement? continue unless statement.Principal?.Service == "alexa-appkit.amazon.com" # still the right contents? lambdaARN = context.artifacts.get 'lambdaARN' if lambdaARN? and statement.Resource == lambdaARN and statement.Effect == 'Allow' and statement.Action == 'lambda:InvokeFunction' foundCorrectPolicy = true else promises.push removePolicy(statement) unless foundCorrectPolicy promises.push addPolicy() Promise.all(promises) .then -> context.localCache.saveTimestamp "lambdaPermissionsChecked-#{lambdaContext.qualifier}" endLambdaDeployment = (context, logger, lambdaContext) -> deltaTime = (new Date) - context.lambdaDeployStart logger.log "lambda deployment complete in #{deltaTime}ms" context.localCache.saveTimestamp 'lambdaUpdated' ensureDynamoTable = (context, logger, lambdaContext) -> context.dynamoTableName = [ context.projectInfo.name context.projectInfo.variant "litexa_handler_state" ].join '_' # if its existence is already verified, no need to do so anymore if context.localCache.timestampExists 'ensuredDynamoTable' return Promise.resolve() dynamo = new AWS.DynamoDB { params: TableName: context.dynamoTableName } logger.log "fetching dynamoDB information" dynamo.describeTable({}).promise() .catch (err) -> if err.code != 'ResourceNotFoundException' logger.error err throw "failed to ensure dynamoDB table exists" logger.log "dynamoDB table not found, creating #{context.dynamoTableName}" params = AttributeDefinitions: [ { AttributeName: "userId" AttributeType: "S" } ], KeySchema: [ { AttributeName: "<KEY>" KeyType: "HASH" } ] ProvisionedThroughput: ReadCapacityUnits: 10, WriteCapacityUnits: 10 dynamo.createTable(params).promise() .then -> context.localCache.saveTimestamp 'createdDynamoTable' dynamo.describeTable({}).promise() .then (data) -> logger.log "verified dynamoDB table exists" context.dynamoTableARN = data.Table.TableArn context.artifacts.save 'dynamoDBARN', data.Table.TableArn context.localCache.saveTimestamp 'ensuredDynamoTable' # only modify the retention policy if it's creating an new log group changeCloudwatchRetentionPolicy = (context, logger, lambdaContext) -> if context.localCache.timestampExists 'ensuredCloudwatchLogGroup' return Promise.resolve() logGroupName = "/aws/lambda/#{context.lambdaName}" cloudwatch = new AWS.CloudWatchLogs() params = { logGroupNamePrefix: logGroupName } cloudwatch.describeLogGroups(params).promise() .then (data) -> logGroupExists = false for logGroup in data.logGroups if logGroup.logGroupName == logGroupName logGroupExists = true break if logGroupExists context.localCache.saveTimestamp 'ensuredCloudwatchLogGroup' return Promise.resolve() params = { logGroupName } cloudwatch.createLogGroup(params).promise() .then -> logger.log "Created Cloudwatch log group for lambda" params = { logGroupName: logGroupName retentionInDays: 30 } context.localCache.saveTimestamp 'ensuredCloudwatchLogGroup' cloudwatch.putRetentionPolicy(params).promise() .then -> logger.log "Updated CloudWatch retention policy to 30 days" context.localCache.saveTimestamp 'appliedLogRetentionPolicy' return Promise.resolve()
true
### # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ### fs = require 'fs' path = require 'path' mkdirp = require 'mkdirp' rimraf = require 'rimraf' util = require 'util' crypto = require 'crypto' AWS = require 'aws-sdk' uuid = require 'uuid' debug = require('debug')('litexa-deploy-lambda') writeFilePromise = util.promisify fs.writeFile readFilePromise = util.promisify fs.readFile SupportedOS = LINUX: 'linux', OSX: 'darwin', WIN: 'win32' writeFileIfDifferent = (filename, contents) -> readFilePromise filename, 'utf8' .catch (err) -> # fine if we can't read it, we'll assume we have to write return Promise.resolve() .then (fileContents) -> if contents == fileContents return Promise.resolve(false) else return writeFilePromise(filename, contents, 'utf8').then(-> Promise.resolve(true)) # TODO: Used for unit testing. Can remove when refactoring code to be more modular and test friendly # as eval does reduce runtime performance, but this should mainly be in the build process exports.unitTestHelper = (funcName) -> args = Array.prototype.slice.call arguments eval funcName .apply this, args[1..] exports.deploy = (context, logger) -> logger.log "deploying lambda" context.lambdaDeployStart = new Date lambdaContext = codeRoot: path.join context.deployRoot, 'lambda' litexaRoot: path.join context.projectRoot, 'litexa' call = (func) -> func context, logger, lambdaContext call preamble .then -> # all of this can happen at the same time step1 = [ call writeReadme call writeSkillJS call copyNodeModules call ensureDynamoTable ] Promise.all(step1) .then -> call packZipFile .then -> call createZipSHA256 .then -> call getLambdaConfig .then -> call updateLambdaConfig .then -> call updateLambdaCode .catch (err) -> if err.code != 'ResourceNotFoundException' throw err # doesn't exist, make it call createLambda .then -> call checkLambdaQualifier .then -> call checkLambdaPermissions .then -> call changeCloudwatchRetentionPolicy .then -> call endLambdaDeployment .catch (err) -> logger.error "lambda deployment failed" throw err preamble = (context, logger, lambdaContext) -> new Promise (resolve, reject) -> try require('./aws-config')(context, logger, AWS) mkdirp.sync lambdaContext.codeRoot lambdaContext.lambda = new AWS.Lambda context.lambdaName = [ context.projectInfo.name context.projectInfo.variant "litexa" "handler" ].join('_') # the alias we're going to deploy to lambdaContext.qualifier = "release-" + context.artifacts.currentVersion catch err return reject(err) resolve() writeReadme = (context, logger, lambdaContext) -> # readme readme = """ This lambda was generated by the litexa package and uploaded using the @litexa/deploy-aws package """ filename = path.join(lambdaContext.codeRoot,'readme.md') writeFileIfDifferent filename, readme .then (wrote) -> if wrote logger.log "wrote readme" writeSkillJS = (context, logger, lambdaContext) -> code = context.skill.toLambda() filename = path.join(lambdaContext.codeRoot,'index.js') writeFileIfDifferent filename, code .then (wrote) -> if wrote logger.log "wrote index.js" copyNodeModules = (context, logger, lambdaContext) -> sourceDir = path.join context.skill.projectInfo.litexaRoot, 'node_modules' targetDir = path.join lambdaContext.codeRoot modulesCache = path.join context.deployRoot, "modules.cache" logger.log "considering node_modules" # check to see if any files appear to be modified since the last time # we did this msSinceLastCopy = context.localCache.millisecondsSince 'copiedNodeModules' needsCopy = (location) -> unless fs.existsSync modulesCache return true unless msSinceLastCopy? return true secondInMillis = 1000 secondsSinceLastCopy = Math.ceil msSinceLastCopy / secondInMillis if process.platform == SupportedOS.WIN # WINCOMPAT - find the first thing that has changed since the last copy. Could use a faster # algorithm to find the last modified file more quickly. fileList = fs.readdirSync(sourceDir) .map (v) -> return { name: v, time: fs.statSync(path.join sourceDir, v).mtime.getTime() } # Grabs the timestamp of the most recently modified file from folder reducer = (prev, curr) -> return if prev.time > curr.time then prev else curr lastModifiedTime = fileList.reduce reducer, 0 .time return lastModifiedTime > ((new Date).getTime() - (secondsSinceLastCopy * secondInMillis)) else { execSync } = require('child_process') result = execSync "find -L #{sourceDir} -type f -atime -#{secondsSinceLastCopy}s | head -n 1" return result.length > 0 unless needsCopy sourceDir logger.log "node modules appear to be up to date" return Promise.resolve() packageJSONPath = path.join context.skill.projectInfo.litexaRoot, 'package.json' unless fs.existsSync packageJSONPath logger.log "no package.json found at #{packageJSONPath}, skipping node_modules" return Promise.resolve() nodeModulesPath = path.join context.skill.projectInfo.litexaRoot, 'node_modules' unless fs.existsSync nodeModulesPath throw new Error "no node_modules found at #{nodeModulesPath}, but we did see #{packageJSONPath}. Aborting for now. Did you perhaps miss running `npm install` from your litexa directory?" return Promise.resolve() new Promise (resolve, reject) -> startTime = new Date { exec } = require('child_process') execCmd = "rsync -crt --copy-links --delete --exclude '*.git' #{sourceDir} #{targetDir}" if process.platform == SupportedOS.WIN # WINCOMPAT - Windows uses robocopy in place of rsync to ensure files get replicated to destination execCmd = "robocopy #{sourceDir} #{targetDir} /mir /copy:DAT /sl /xf \"*.git\" /r:3 /w:4" exec execCmd, (err, stdout, stderr) -> logger.log "rsync: \n" + stdout if stdout deltaTime = (new Date) - startTime fs.writeFileSync modulesCache, '' logger.log "synchronized node_modules in #{deltaTime}ms" if err? reject(err) else if stderr logger.log stderr reject(err) else context.localCache.saveTimestamp 'copiedNodeModules' resolve() packZipFile = (context, logger, lambdaContext) -> new Promise (resolve, reject) -> logger.log "beginning zip archive" zipStart = new Date lambdaContext.zipFilename = path.join context.deployRoot, 'lambda.zip' lambdaSource = path.join(context.deployRoot,'lambda') debug "source directory: #{lambdaSource}" { exec } = require('child_process') zipFileCreationLogging = (err, stdout, stderr) -> logger.log "Platform: #{process.platform}" if process.platform == SupportedOS.WIN # WINCOMPAT - deletes old zip and creates new zip. There may be a faster way to zip on Windows zip = require 'adm-zip' zipper = new zip zipper.addLocalFolder lambdaSource zipper.writeZip lambdaContext.zipFilename zipLog = path.join context.deployRoot, 'zip.out.log' fs.writeFileSync zipLog, stdout zipLog = path.join context.deployRoot, 'zip.err.log' fs.writeFileSync zipLog, "" + err + stderr if err? logger.error err throw "failed to zip lambda" deltaTime = (new Date) - zipStart logger.log "zip archiving complete in #{deltaTime}ms" return resolve() if process.platform == SupportedOS.WIN # WINCOMPAT - using rimraf instead of rm -f for compatability rimraf '../data.zip', zipFileCreationLogging else exec "rm -f ../data.zip && zip -rX ../lambda.zip *", { cwd: lambdaSource maxBuffer: 1024 * 500 }, zipFileCreationLogging createZipSHA256 = (context, logger, lambdaContext) -> new Promise (resolve, reject) -> shasum = crypto.createHash('sha256') fs.createReadStream lambdaContext.zipFilename .on "data", (chunk) -> shasum.update chunk .on "end", -> lambdaContext.zipSHA256 = shasum.digest('base64') logger.log "zip SHA: #{lambdaContext.zipSHA256}" resolve() .on "error", (err) -> reject err getLambdaConfig = (context, logger, lambdaContext) -> if context.localCache.lessThanSince 'lambdaUpdated', 30 # it's ok to skip this during iteration, so do it every half hour lambdaContext.deployedSHA256 = context.localCache.getHash 'lambdaSHA256' logger.log "skipping Lambda #{context.lambdaName} configuration check" return Promise.resolve() logger.log "fetching Lambda #{context.lambdaName} configuration" params = FunctionName: context.lambdaName lambdaContext.lambda.getFunctionConfiguration(params).promise() .then (data) -> logger.log "fetched Lambda configuration" lambdaContext.deployedSHA256 = data.CodeSha256 lambdaContext.deployedLambdaConfig = data setLambdaARN context, lambdaContext, data.FunctionArn Promise.resolve data setLambdaARN = (context, lambdaContext, newARN) -> aliasedARN = "#{newARN}:#{lambdaContext.qualifier}" lambdaContext.baseARN = newARN context.lambdaARN = aliasedARN context.artifacts.save 'lambdaARN', aliasedARN makeLambdaConfiguration = (context, logger) -> require('./iam-roles').ensureLambdaIAMRole(context, logger) .then -> loggingLevel = if context.projectInfo.variant in ['alpha', 'beta', 'gamma'] undefined else 'terse' loggingLevel = 'terse' config = Description: "Litexa skill handler for project #{context.projectInfo.name}" Handler: "index.handler" # exports.handler in index.js MemorySize: 256 # megabytes, mainly because this also means dedicated CPU Role: context.lambdaIAMRoleARN Runtime: "nodejs8.10" Timeout: 10 # seconds Environment: Variables: variant: context.projectInfo.variant loggingLevel: loggingLevel dynamoTableName: context.dynamoTableName assetsRoot: context.artifacts.get 'assets-root' if context.deploymentOptions.lambdaConfiguration? # if this option is present, merge that object into the config, key by key mergeValue = ( target, key, value, stringify ) -> if key of target if typeof(target[key]) == 'object' # recurse into objects unless typeof(value) == 'object' throw "value of key #{key} was expected to be an object in lambdaConfiguration, but was instead #{JSON.stringify value}" for k, v of value # variable value must be strings, so switch here if k == 'Variables' stringify = true mergeValue target[key], k, v, stringify return if stringify target[key] = '' + value else target[key] = value for k, v of context.deploymentOptions.lambdaConfiguration mergeValue config, k, v, false debug "Lambda config: " + JSON.stringify config, null, 2 return config createLambda = (context, logger, lambdaContext) -> logger.log "creating Lambda function #{context.lambdaName}" params = Code: ZipFile: fs.readFileSync(lambdaContext.zipFilename) FunctionName: context.lambdaName Publish: true, VpcConfig: {} makeLambdaConfiguration(context, logger) .then (lambdaConfig) -> for k, v of lambdaConfig params[k] = v lambdaContext.lambda.createFunction(params).promise() .then (data) -> logger.verbose 'create-function', data logger.log "creating LIVE alias for Lambda function #{context.lambdaName}" lambdaContext.deployedSHA256 = data.CodeSha256 setLambdaARN context, lambdaContext, data.FunctionArn # create the live alias, to support easy # console based rollbacks in emergencies params = FunctionName: context.lambdaName FunctionVersion: '$LATEST' Name: 'LIVE' Description: 'Current live version, used to refer to this lambda by the Alexa skill. In an emergency, you can point this to an older version of the code.' lambdaContext.lambda.createAlias(params).promise() updateLambdaConfig = (context, logger, lambdaContext) -> needsUpdating = false matchObject = (a, b) -> unless b? return needsUpdating = true for k, v of a if typeof(v) == 'object' matchObject v, b[k] else if v? and b[k] != v logger.log "lambda configuration mismatch: #{k}:#{b[k]} should be #{v}" needsUpdating = true makeLambdaConfiguration context, logger .then (lambdaConfig) -> matchObject lambdaConfig, lambdaContext.deployedLambdaConfig unless needsUpdating return Promise.resolve() logger.log "patching Lambda configuration" params = FunctionName: context.lambdaName for k, v of lambdaConfig params[k] = v lambdaContext.lambda.updateFunctionConfiguration(params).promise() updateLambdaCode = (context, logger, lambdaContext) -> # todo: with node_modules it's much easier to get bigger than # updateFunctionCode supports... will have to go through S3 then? if lambdaContext.deployedSHA256 == lambdaContext.zipSHA256 logger.log "Lambda function #{context.lambdaName} code already up to date" return Promise.resolve() logger.log "updating code for Lambda function #{context.lambdaName}" params = FunctionName: context.lambdaName Publish: true ZipFile: fs.readFileSync(lambdaContext.zipFilename) lambdaContext.lambda.updateFunctionCode(params).promise() .then (data) -> context.localCache.storeHash 'lambdaSHA256', data.CodeSha256 checkLambdaQualifier = (context, logger, lambdaContext) -> params = FunctionName: context.lambdaName Name: lambdaContext.qualifier lambdaContext.lambda.getAlias(params).promise() .catch (err) -> if err.code == "ResourceNotFoundException" # not found is fine, we'll make it params = FunctionName: context.lambdaName Name: lambdaContext.qualifier Description: "Auto created by PI:NAME:<NAME>END_PI" FunctionVersion: "$LATEST" lambdaContext.lambda.createAlias(params).promise() .catch (err) -> logger.error err throw "Failed to create alias #{lambdaContext.qualifier}" throw new Error "Failed to create alias #{lambdaContext.qualifier}" .then (data) -> logger.verbose 'createAlias', data Promise.resolve(data) else logger.error err throw "Failed to fetch alias for lambda #{context.lambdaName}, #{lambdaContext.qualifier}" Promise.resolve() .then (data) -> # the development head should always be latest if data.FunctionVersion == '$LATEST' return Promise.resolve() params = RevisionId: data.RevisionId FunctionName: context.lambdaName Name: lambdaContext.qualifier Description: "Auto created by PI:NAME:<NAME>END_PI" FunctionVersion: "$LATEST" lambdaContext.lambda.updateAlias(params).promise() checkLambdaPermissions = (context, logger, lambdaContext) -> if context.localCache.timestampExists "lambdaPermissionsChecked-#{lambdaContext.qualifier}" return Promise.resolve() addPolicy = (cache) -> logger.log "adding policies to Lambda #{context.lambdaName}" params = FunctionName: context.lambdaName Action: 'lambda:InvokeFunction' StatementId: 'lc-' + uuid.v4() Principal: 'alexa-appkit.amazon.com' Qualifier: lambdaContext.qualifier lambdaContext.lambda.addPermission(params).promise() .catch (err) -> logger.error "Failed to add permissions to lambda: #{err}" .then (data) -> logger.verbose "addPermission: #{JSON.stringify(data, null, 2)}" removePolicy = (statement) -> logger.log "removing policy #{statement.Sid} from lambda #{context.lambdaName}" params = FunctionName: context.lambdaName StatementId: statement.Sid Qualifier: lambdaContext.qualifier lambdaContext.lambda.removePermission(params).promise() .catch (err) -> logger.error err throw "failed to remove bad lambda permission" logger.log "pulling existing policies" params = FunctionName: context.lambdaName Qualifier: lambdaContext.qualifier lambdaContext.lambda.getPolicy(params).promise() .catch (err) -> # ResourceNotFoundException is fine, might not have a policy if err.code != "ResourceNotFoundException" logger.error err throw "Failed to fetch policies for lambda #{context.lambdaName}" .then (data) -> promises = [] foundCorrectPolicy = false if data? logger.log "reconciling policies against existing data" # analyze the existing one policy = JSON.parse(data.Policy) for statement in policy.Statement # is this the ask statement? continue unless statement.Principal?.Service == "alexa-appkit.amazon.com" # still the right contents? lambdaARN = context.artifacts.get 'lambdaARN' if lambdaARN? and statement.Resource == lambdaARN and statement.Effect == 'Allow' and statement.Action == 'lambda:InvokeFunction' foundCorrectPolicy = true else promises.push removePolicy(statement) unless foundCorrectPolicy promises.push addPolicy() Promise.all(promises) .then -> context.localCache.saveTimestamp "lambdaPermissionsChecked-#{lambdaContext.qualifier}" endLambdaDeployment = (context, logger, lambdaContext) -> deltaTime = (new Date) - context.lambdaDeployStart logger.log "lambda deployment complete in #{deltaTime}ms" context.localCache.saveTimestamp 'lambdaUpdated' ensureDynamoTable = (context, logger, lambdaContext) -> context.dynamoTableName = [ context.projectInfo.name context.projectInfo.variant "litexa_handler_state" ].join '_' # if its existence is already verified, no need to do so anymore if context.localCache.timestampExists 'ensuredDynamoTable' return Promise.resolve() dynamo = new AWS.DynamoDB { params: TableName: context.dynamoTableName } logger.log "fetching dynamoDB information" dynamo.describeTable({}).promise() .catch (err) -> if err.code != 'ResourceNotFoundException' logger.error err throw "failed to ensure dynamoDB table exists" logger.log "dynamoDB table not found, creating #{context.dynamoTableName}" params = AttributeDefinitions: [ { AttributeName: "userId" AttributeType: "S" } ], KeySchema: [ { AttributeName: "PI:KEY:<KEY>END_PI" KeyType: "HASH" } ] ProvisionedThroughput: ReadCapacityUnits: 10, WriteCapacityUnits: 10 dynamo.createTable(params).promise() .then -> context.localCache.saveTimestamp 'createdDynamoTable' dynamo.describeTable({}).promise() .then (data) -> logger.log "verified dynamoDB table exists" context.dynamoTableARN = data.Table.TableArn context.artifacts.save 'dynamoDBARN', data.Table.TableArn context.localCache.saveTimestamp 'ensuredDynamoTable' # only modify the retention policy if it's creating an new log group changeCloudwatchRetentionPolicy = (context, logger, lambdaContext) -> if context.localCache.timestampExists 'ensuredCloudwatchLogGroup' return Promise.resolve() logGroupName = "/aws/lambda/#{context.lambdaName}" cloudwatch = new AWS.CloudWatchLogs() params = { logGroupNamePrefix: logGroupName } cloudwatch.describeLogGroups(params).promise() .then (data) -> logGroupExists = false for logGroup in data.logGroups if logGroup.logGroupName == logGroupName logGroupExists = true break if logGroupExists context.localCache.saveTimestamp 'ensuredCloudwatchLogGroup' return Promise.resolve() params = { logGroupName } cloudwatch.createLogGroup(params).promise() .then -> logger.log "Created Cloudwatch log group for lambda" params = { logGroupName: logGroupName retentionInDays: 30 } context.localCache.saveTimestamp 'ensuredCloudwatchLogGroup' cloudwatch.putRetentionPolicy(params).promise() .then -> logger.log "Updated CloudWatch retention policy to 30 days" context.localCache.saveTimestamp 'appliedLogRetentionPolicy' return Promise.resolve()
[ { "context": "#\n# Copyright 2015 Volcra\n#\n# Licensed under the Apache License, Version 2.", "end": 25, "score": 0.9996169209480286, "start": 19, "tag": "NAME", "value": "Volcra" } ]
gulpfile.coffee
volcra/react-foundation
0
# # Copyright 2015 Volcra # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # $ = require('gulp-load-plugins')() browserSync = require 'browser-sync' del = require 'del' gulp = require 'gulp' reload = browserSync.reload runSequence = require 'run-sequence' # React gulp.task 'react', -> gulp.src ['src/**/*.jsx'] .pipe $.react() .pipe $.concat 'all.js' .pipe gulp.dest 'build' # Webpack gulp.task 'webpack', -> gulp.src '' .pipe $.webpack require './webpack.config.coffee' .pipe gulp.dest 'build' # Serve gulp.task 'serve', ['webpack'], -> browserSync notify: false logPrefix: 'VC' server: ['build', 'foundation'] gulp.watch ['src/**/*.{jsx,js,coffee}'], ['webpack', reload] gulp.watch ['foundation/index.html'], reload # Clean gulp.task 'clean', del.bind null, ['build'], dot: true # Default gulp.task 'default', ['clean'], (cb) -> runSequence 'webpack', cb
136221
# # Copyright 2015 <NAME> # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # $ = require('gulp-load-plugins')() browserSync = require 'browser-sync' del = require 'del' gulp = require 'gulp' reload = browserSync.reload runSequence = require 'run-sequence' # React gulp.task 'react', -> gulp.src ['src/**/*.jsx'] .pipe $.react() .pipe $.concat 'all.js' .pipe gulp.dest 'build' # Webpack gulp.task 'webpack', -> gulp.src '' .pipe $.webpack require './webpack.config.coffee' .pipe gulp.dest 'build' # Serve gulp.task 'serve', ['webpack'], -> browserSync notify: false logPrefix: 'VC' server: ['build', 'foundation'] gulp.watch ['src/**/*.{jsx,js,coffee}'], ['webpack', reload] gulp.watch ['foundation/index.html'], reload # Clean gulp.task 'clean', del.bind null, ['build'], dot: true # Default gulp.task 'default', ['clean'], (cb) -> runSequence 'webpack', cb
true
# # Copyright 2015 PI:NAME:<NAME>END_PI # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # $ = require('gulp-load-plugins')() browserSync = require 'browser-sync' del = require 'del' gulp = require 'gulp' reload = browserSync.reload runSequence = require 'run-sequence' # React gulp.task 'react', -> gulp.src ['src/**/*.jsx'] .pipe $.react() .pipe $.concat 'all.js' .pipe gulp.dest 'build' # Webpack gulp.task 'webpack', -> gulp.src '' .pipe $.webpack require './webpack.config.coffee' .pipe gulp.dest 'build' # Serve gulp.task 'serve', ['webpack'], -> browserSync notify: false logPrefix: 'VC' server: ['build', 'foundation'] gulp.watch ['src/**/*.{jsx,js,coffee}'], ['webpack', reload] gulp.watch ['foundation/index.html'], reload # Clean gulp.task 'clean', del.bind null, ['build'], dot: true # Default gulp.task 'default', ['clean'], (cb) -> runSequence 'webpack', cb
[ { "context": "= (device) =>\n return unless device.name == 'Lyrebird'\n device.known = !!@knownDevices.get(device.", "end": 1023, "score": 0.8602724671363831, "start": 1015, "tag": "NAME", "value": "Lyrebird" } ]
client/mobile/app/coffee/modules/device/service.coffee
aeksco/ble-key
0
DeviceCollection = require './collection' # # # # # # DeviceService class definition # Defines a Marionette.Service class to store # Bluetooth devices found during scans class DeviceService extends Marionette.Service radioRequests: 'device model': 'model' 'device collection': 'collection' radioEvents: 'device refresh': 'refresh' initialize: -> # Gets currently known devices Backbone.Radio.channel('known:device').request('collection') .then (knownDevices) => @knownDevices = knownDevices # Caches collection instance @collectionCache = new DeviceCollection() # Re-scans refresh: -> # Throttles multiple calls to refresh return if @scanning # Resets collection # TODO - this isn't a reliable solution # Instead we must rescan for devices and reset the collection # with the union of its models and the scan result @collectionCache.reset([]) # Success callback onDeviceFound = (device) => return unless device.name == 'Lyrebird' device.known = !!@knownDevices.get(device.id) @collectionCache.add device # Error callback onScanError = () -> console.log 'ERROR FETCHING DEVICES' # TODO - throw error return # Starts scan ble.startScan([], onDeviceFound, onScanError) # Callbacks onScanComplete = => @scanning = false onStopFail = => console.log 'StopScan failure' # Stops scan after 5 seconds @scanning = true setTimeout(ble.stopScan, 5000, onScanComplete, onStopFail) model: (id) -> return new Promise (resolve,reject) => resolve(@collectionCache.get(id)) # TODO - a lot of this should be abstracted into the bluetooth service collection: -> return new Promise (resolve,reject) => # Invokes refresh with respect to this collection @refresh() # Returns collection, async return resolve(@collectionCache) # # # # # # Exports instance of DeviceService module.exports = new DeviceService()
124690
DeviceCollection = require './collection' # # # # # # DeviceService class definition # Defines a Marionette.Service class to store # Bluetooth devices found during scans class DeviceService extends Marionette.Service radioRequests: 'device model': 'model' 'device collection': 'collection' radioEvents: 'device refresh': 'refresh' initialize: -> # Gets currently known devices Backbone.Radio.channel('known:device').request('collection') .then (knownDevices) => @knownDevices = knownDevices # Caches collection instance @collectionCache = new DeviceCollection() # Re-scans refresh: -> # Throttles multiple calls to refresh return if @scanning # Resets collection # TODO - this isn't a reliable solution # Instead we must rescan for devices and reset the collection # with the union of its models and the scan result @collectionCache.reset([]) # Success callback onDeviceFound = (device) => return unless device.name == '<NAME>' device.known = !!@knownDevices.get(device.id) @collectionCache.add device # Error callback onScanError = () -> console.log 'ERROR FETCHING DEVICES' # TODO - throw error return # Starts scan ble.startScan([], onDeviceFound, onScanError) # Callbacks onScanComplete = => @scanning = false onStopFail = => console.log 'StopScan failure' # Stops scan after 5 seconds @scanning = true setTimeout(ble.stopScan, 5000, onScanComplete, onStopFail) model: (id) -> return new Promise (resolve,reject) => resolve(@collectionCache.get(id)) # TODO - a lot of this should be abstracted into the bluetooth service collection: -> return new Promise (resolve,reject) => # Invokes refresh with respect to this collection @refresh() # Returns collection, async return resolve(@collectionCache) # # # # # # Exports instance of DeviceService module.exports = new DeviceService()
true
DeviceCollection = require './collection' # # # # # # DeviceService class definition # Defines a Marionette.Service class to store # Bluetooth devices found during scans class DeviceService extends Marionette.Service radioRequests: 'device model': 'model' 'device collection': 'collection' radioEvents: 'device refresh': 'refresh' initialize: -> # Gets currently known devices Backbone.Radio.channel('known:device').request('collection') .then (knownDevices) => @knownDevices = knownDevices # Caches collection instance @collectionCache = new DeviceCollection() # Re-scans refresh: -> # Throttles multiple calls to refresh return if @scanning # Resets collection # TODO - this isn't a reliable solution # Instead we must rescan for devices and reset the collection # with the union of its models and the scan result @collectionCache.reset([]) # Success callback onDeviceFound = (device) => return unless device.name == 'PI:NAME:<NAME>END_PI' device.known = !!@knownDevices.get(device.id) @collectionCache.add device # Error callback onScanError = () -> console.log 'ERROR FETCHING DEVICES' # TODO - throw error return # Starts scan ble.startScan([], onDeviceFound, onScanError) # Callbacks onScanComplete = => @scanning = false onStopFail = => console.log 'StopScan failure' # Stops scan after 5 seconds @scanning = true setTimeout(ble.stopScan, 5000, onScanComplete, onStopFail) model: (id) -> return new Promise (resolve,reject) => resolve(@collectionCache.get(id)) # TODO - a lot of this should be abstracted into the bluetooth service collection: -> return new Promise (resolve,reject) => # Invokes refresh with respect to this collection @refresh() # Returns collection, async return resolve(@collectionCache) # # # # # # Exports instance of DeviceService module.exports = new DeviceService()
[ { "context": "# Author: 易晓峰\n# E-mail: wvv8oo@gmail.com\n# Date: 6/8/15 1", "end": 16, "score": 0.9986716508865356, "start": 13, "tag": "NAME", "value": "易晓峰" }, { "context": "# Author: 易晓峰\n# E-mail: wvv8oo@gmail.com\n# Date: 6/8/15 11:48 AM\n# Description: 用户的活...
src/redis/stream.coffee
kiteam/kiteam
0
# Author: 易晓峰 # E-mail: wvv8oo@gmail.com # Date: 6/8/15 11:48 AM # Description: 用户的活动 _async = require 'async' _ = require 'lodash' _common = require '../common' _connect = require './connect' _config = _common.config #获取成员活动的key getKey = (member_id)-> "#{_config.redis.unique}:member_stream:#{member_id}" #添加活动 exports.append = (sender, receiver, eventName, data, cb)-> return if not (sender and receiver) key = getKey receiver.id redis = _connect.redis activity = eventName: eventName data: data sender_id: sender.id sender: sender.realname timestamp: new Date().valueOf() #每个用户只保存99条活动 redis.lpush key, JSON.stringify(activity), (err)-> redis.ltrim key, 0, 1000, (err)-> cb? null #根据用户的ID来获取工作流 exports.getStream = (member_id, cb)-> key = getKey member_id redis = _connect.redis redis.lrange key, 0, 99, (err, result)-> result = _.map result, (current)-> JSON.parse(current) cb err, result
13786
# Author: <NAME> # E-mail: <EMAIL> # Date: 6/8/15 11:48 AM # Description: 用户的活动 _async = require 'async' _ = require 'lodash' _common = require '../common' _connect = require './connect' _config = _common.config #获取成员活动的key getKey = (member_id)-> "#{_config.redis.unique}:member_stream:#{member_id}" #添加活动 exports.append = (sender, receiver, eventName, data, cb)-> return if not (sender and receiver) key = getKey receiver.id redis = _connect.redis activity = eventName: eventName data: data sender_id: sender.id sender: sender.realname timestamp: new Date().valueOf() #每个用户只保存99条活动 redis.lpush key, JSON.stringify(activity), (err)-> redis.ltrim key, 0, 1000, (err)-> cb? null #根据用户的ID来获取工作流 exports.getStream = (member_id, cb)-> key = getKey member_id redis = _connect.redis redis.lrange key, 0, 99, (err, result)-> result = _.map result, (current)-> JSON.parse(current) cb err, result
true
# Author: PI:NAME:<NAME>END_PI # E-mail: PI:EMAIL:<EMAIL>END_PI # Date: 6/8/15 11:48 AM # Description: 用户的活动 _async = require 'async' _ = require 'lodash' _common = require '../common' _connect = require './connect' _config = _common.config #获取成员活动的key getKey = (member_id)-> "#{_config.redis.unique}:member_stream:#{member_id}" #添加活动 exports.append = (sender, receiver, eventName, data, cb)-> return if not (sender and receiver) key = getKey receiver.id redis = _connect.redis activity = eventName: eventName data: data sender_id: sender.id sender: sender.realname timestamp: new Date().valueOf() #每个用户只保存99条活动 redis.lpush key, JSON.stringify(activity), (err)-> redis.ltrim key, 0, 1000, (err)-> cb? null #根据用户的ID来获取工作流 exports.getStream = (member_id, cb)-> key = getKey member_id redis = _connect.redis redis.lrange key, 0, 99, (err, result)-> result = _.map result, (current)-> JSON.parse(current) cb err, result
[ { "context": "# Proc.coffee\n#\n#\t© 2013 Dave Goehrig <dave@dloh.org>\n#\n\npgproc = require 'pgproc'\nquer", "end": 37, "score": 0.9998895525932312, "start": 25, "tag": "NAME", "value": "Dave Goehrig" }, { "context": "# Proc.coffee\n#\n#\t© 2013 Dave Goehrig <dave@dloh.org>\n#\n\np...
lib/Proc.coffee
cthulhuology/opifex.pgproc
1
# Proc.coffee # # © 2013 Dave Goehrig <dave@dloh.org> # pgproc = require 'pgproc' querystring = require 'querystring' Proc = () -> this["connect"] = (database,schema) -> pgproc(database,schema) this.send { connect: "ok" } this["*"] = (method,args...) -> args = args.map( querystring.unescape ) args.push( (row) => this.send row, this.dest, this.key ) global[method].apply(global,args) module.exports = Proc
144498
# Proc.coffee # # © 2013 <NAME> <<EMAIL>> # pgproc = require 'pgproc' querystring = require 'querystring' Proc = () -> this["connect"] = (database,schema) -> pgproc(database,schema) this.send { connect: "ok" } this["*"] = (method,args...) -> args = args.map( querystring.unescape ) args.push( (row) => this.send row, this.dest, this.key ) global[method].apply(global,args) module.exports = Proc
true
# Proc.coffee # # © 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # pgproc = require 'pgproc' querystring = require 'querystring' Proc = () -> this["connect"] = (database,schema) -> pgproc(database,schema) this.send { connect: "ok" } this["*"] = (method,args...) -> args = args.map( querystring.unescape ) args.push( (row) => this.send row, this.dest, this.key ) global[method].apply(global,args) module.exports = Proc
[ { "context": "eleased under the MIT License.\n# It's developed by Darius Morawiec. 2013-2016\n#\n# https://github.com/nok/onedollar-c", "end": 105, "score": 0.9998461008071899, "start": 90, "tag": "NAME", "value": "Darius Morawiec" }, { "context": "Darius Morawiec. 2013-2016\n#\n# ht...
src/onedollar.coffee
nok/onedollar-unistroke-coffee
20
# The library is Open Source Software released under the MIT License. # It's developed by Darius Morawiec. 2013-2016 # # https://github.com/nok/onedollar-coffeescript # # --- # # The $1 Gesture Recognizer is a research project by Wobbrock, Wilson and Li of # the University of Washington and Microsoft Research. It describes a simple # algorithm for accurate and fast recognition of drawn gestures. # # Gestures can be recognised at any position, scale, and under any rotation. # The system requires little training, achieving a 97% recognition rate with # only one template for each gesture. # # http://depts.washington.edu/aimgroup/proj/dollar/ class OneDollar # Math constants: PHI = 0.5 * (-1.0 + Math.sqrt(5.0)) # Prepared inner variables: SIZE = HALF = ANGLE = STEP = null # Internal data handlers: _options = {} _templates = {} _binds = {} _hasBinds = false _candidates = [] # The constructor of the algorithm. # # @param {[object]} options The options of the algorithm. # # @return OneDollar constructor: (options = {}) -> _options = options # Threshold in percent of callbacks: if !('score' of _options) _options['score'] = 80 if !('parts' of _options) _options['parts'] = 64 if !('angle' of _options) _options['angle'] = 45 ANGLE = ___radians _options.angle if !('step' of _options) _options['step'] = 2 STEP = ___radians _options.step # Size of bounding box: if !('size' of _options) _options['size'] = 250.0 SIZE = _options.size HALF = 0.5 * Math.sqrt(SIZE * SIZE + SIZE * SIZE) return @ # Add a new template. # # @param {String} name The name of the template. # @param {Array} points The points of the gesture. # # @return OneDollar add: (name, points) -> if points.length > 0 _templates[name] = _transform points return @ # Remove a template. # # @param {String} name The name of the template. # # @return OneDollar remove: (name) -> if _templates[name] isnt undefined delete _templates[name] return @ # Bind callback for chosen templates. # # @param {String} name The name of the template. # @param {function} fn The callback function. # # @return OneDollar on: (name, fn) -> names = [] if name == "*" for name, template of _templates names.push name else names = name.split ' ' for name in names if _templates[name] isnt undefined _binds[name] = fn _hasBinds = true else throw new Error "The template '" + name + "' isn't defined." return @ # Unbind callback for chosen templates. # # @param {String} name The name of the template. # # @return OneDollar off: (name) -> if _binds[name] isnt undefined delete _binds[name] _hasBinds = false for name, bind of _binds if _templates.hasOwnProperty name _hasBinds = true break return @ # Get information about the algorithm. # # @return Object Return options, templates and binds. toObject: -> return { options: _options templates: _templates binds: _binds } # Create a new gesture candidate. # # @param {Integer} id The unique ID of the candidate. # @param {Array} point The start position of the candidate. # # @return OneDollar start: (id, point) -> if typeof(id) is 'object' and typeof(point) is 'undefined' point = id id = -1 _candidates[id] = [] @update id, point return @ # Add a new position to a created candidate. # # @param {Integer} id The unique ID of the candidate. # @param {Array} point The new position of the candidate. # # @return OneDollar update: (id, point) -> if typeof(id) is 'object' and typeof(point) is 'undefined' point = id id = -1 _candidates[id].push point return @ # Close a new gesture candidate and trigger the gesture recognition. # # @param {Integer} id The unique ID of the candidate. # @param {Array} point The last position of the candidate. # # @return OneDollar end: (id, point) -> if typeof(id) is 'object' and typeof(point) is 'undefined' point = id id = -1 @update id, point result = @check _candidates[id] delete _candidates[id] return result # Run the gesture recognition. # # @param {Array} candidate The candidate gesture. # # @return {boolean|Object} The result object. check: (candidate) -> args = false points = candidate.length if points < 3 return args path = start: [candidate[0][0], candidate[0][1]] end: [candidate[points - 1][0], candidate[points - 1][1]] centroid: if points > 1 then ___centroid candidate else path.start candidate = _transform candidate ranking = [] bestDist = +Infinity bestName = null for name, template of _templates if _hasBinds == false or _binds[name] isnt undefined distance = _findBestMatch candidate, template score = parseFloat(((1.0 - distance / HALF) * 100).toFixed(2)) if isNaN score score = 0.0 ranking.push name: name score: score if distance < bestDist bestDist = distance bestName = name if ranking.length > 0 # Sorting: if ranking.length > 1 ranking.sort (a, b) -> return if a.score < b.score then 1 else -1 idx = candidate.length - 1 args = name: ranking[0].name score: ranking[0].score recognized: false path: path ranking: ranking if ranking[0].score >= _options.score args.recognized = true if _hasBinds _binds[ranking[0].name].apply @, [args] return args # Transform the data to a comparable format. # # @param {Array} points The raw candidate gesture. # # @return Array The transformed candidate. _transform = (points) -> # Algorithm step: points = __resample points # (1) points = __rotateToZero points # (2) points = __scaleToSquare points # (3) points = __translateToOrigin points # (4) return points # Find the best match between a candidate and template. # # @param {Array} candidate The candidate gesture. # @param {Array} template The template gesture. # # @return Float The computed smallest distance. _findBestMatch = (candidate, template) -> rt = ANGLE lt = -ANGLE centroid = ___centroid candidate x1 = PHI * lt + (1.0 - PHI) * rt f1 = __distanceAtAngle candidate, template, x1, centroid x2 = (1.0 - PHI) * lt + PHI * rt f2 = __distanceAtAngle candidate, template, x2, centroid while (Math.abs(rt - lt) > STEP) if f1 < f2 rt = x2 x2 = x1 f2 = f1 x1 = PHI * lt + (1.0 - PHI) * rt f1 = __distanceAtAngle candidate, template, x1, centroid else lt = x1 x1 = x2 f1 = f2 x2 = (1.0 - PHI) * lt + PHI * rt f2 = __distanceAtAngle candidate, template, x2, centroid return Math.min(f1, f2) # 1: Resampling of a gesture. # # @param {Array} points The points of a move. # # @return Array The resampled gesture. __resample = (points) -> seperator = (___length points) / (_options.parts - 1) distance = 0.0 resampled = [] resampled.push [points[0][0], points[0][1]] idx = 1 while idx < points.length prev = points[idx - 1] point = points[idx] space = ___distance(prev, point) if (distance + space) >= seperator x = prev[0] + ((seperator - distance) / space) * (point[0] - prev[0]) y = prev[1] + ((seperator - distance) / space) * (point[1] - prev[1]) resampled.push [x, y] points.splice idx, 0, [x, y] distance = 0.0 else distance += space idx += 1 while resampled.length < _options.parts resampled.push [points[points.length-1][0], points[points.length-1][1]] return resampled # 2: Rotation of the gesture. # # @param {Array} points The points of a move. # # @return Array The rotated gesture. __rotateToZero = (points) -> centroid = ___centroid points theta = Math.atan2(centroid[1] - points[0][1], centroid[0] - points[0][0]) return ___rotate points, -theta, centroid # 3: Scaling of a gesture. # # @param {Array} points The points of a move. # # @return Array The scaled gesture. __scaleToSquare = (points) -> minX = minY = +Infinity maxX = maxY = -Infinity for point in points minX = Math.min(point[0], minX) maxX = Math.max(point[0], maxX) minY = Math.min(point[1], minY) maxY = Math.max(point[1], maxY) deltaX = maxX - minX deltaY = maxY - minY offset = [SIZE / deltaX, SIZE / deltaY] return ___scale points, offset # 4: Translation of a gesture. # # @param {Array} points The points of a move. # # @return Array The translated gesture. __translateToOrigin = (points) -> centroid = ___centroid points centroid[0] *= -1 centroid[1] *= -1 return ___translate points, centroid # Compute the delta space between two sets of points at a specific angle. # # @param {Array} points1 The points of a move. # @param {Array} points2 The points of a move. # @param {Float} radians The radian value. # # @return Float The computed distance. __distanceAtAngle = (points1, points2, radians, centroid) -> _points1 = ___rotate points1, radians, centroid result = ___delta _points1, points2 return result # Compute the delta space between two sets of points. # # @param {Array} points1 The points of a move. # @param {Array} points2 The points of a move. # # @return Float The computed distance. ___delta = (points1, points2) -> delta = 0.0 for point, idx in points1 delta += ___distance(points1[idx], points2[idx]) return delta / points1.length # Compute the distance of a gesture. # # @param {Array} points The points of a move. # # @return Float The computed distance. ___length = (points) -> length = 0.0 prev = null for point in points if prev isnt null length += ___distance(prev, point) prev = point return length # Compute the euclidean distance between two points. # # @param {Array} p1 The first two dimensional point. # @param {Array} p2 The second two dimensional point. # # @return Float The computed euclidean distance. ___distance = (p1, p2) -> x = Math.pow(p1[0] - p2[0], 2) y = Math.pow(p1[1] - p2[1], 2) return Math.sqrt(x + y) # Compute the centroid of a set of points. # # @param {Array} points1 The points of a move. # # @return Array The centroid object. ___centroid = (points) -> x = 0.0 y = 0.0 for point in points x += point[0] y += point[1] x /= points.length y /= points.length return [x, y] # Rotate a gesture. # # @param {Array} points The points of a move. # @param {Float} radians The rotation angle. # @param {Array} pivot The pivot of the rotation. # # @return Array The rotated gesture. ___rotate = (points, radians, pivot) -> sin = Math.sin(radians) cos = Math.cos(radians) neew = [] for point, idx in points deltaX = points[idx][0] - pivot[0] deltaY = points[idx][1] - pivot[1] points[idx][0] = deltaX * cos - deltaY * sin + pivot[0] points[idx][1] = deltaX * sin + deltaY * cos + pivot[1] return points # Scale a gesture. # # @param {Array} points The points of a move. # @param {Array} offset The scalar values. # # @return Array The scaled gesture. ___scale = (points, offset) -> for point, idx in points points[idx][0] *= offset[0] points[idx][1] *= offset[1] return points # Translate a gesture. # # @param {Array} points The points of a move. # @param {Array} offset The translation values. # # @return Array The translated gesture. ___translate = (points, offset) -> for point, idx in points points[idx][0] += offset[0] points[idx][1] += offset[1] return points # Compute the radians from degrees. # # @param {Float} degrees The degree value. # # @return Float The computed radian value. ___radians = (degrees) -> return degrees * Math.PI / 180.0 # Environment and testing: if typeof exports isnt 'undefined' exports.OneDollar = OneDollar
63802
# The library is Open Source Software released under the MIT License. # It's developed by <NAME>. 2013-2016 # # https://github.com/nok/onedollar-coffeescript # # --- # # The $1 Gesture Recognizer is a research project by <NAME>, <NAME> <NAME> of # the University of Washington and Microsoft Research. It describes a simple # algorithm for accurate and fast recognition of drawn gestures. # # Gestures can be recognised at any position, scale, and under any rotation. # The system requires little training, achieving a 97% recognition rate with # only one template for each gesture. # # http://depts.washington.edu/aimgroup/proj/dollar/ class OneDollar # Math constants: PHI = 0.5 * (-1.0 + Math.sqrt(5.0)) # Prepared inner variables: SIZE = HALF = ANGLE = STEP = null # Internal data handlers: _options = {} _templates = {} _binds = {} _hasBinds = false _candidates = [] # The constructor of the algorithm. # # @param {[object]} options The options of the algorithm. # # @return OneDollar constructor: (options = {}) -> _options = options # Threshold in percent of callbacks: if !('score' of _options) _options['score'] = 80 if !('parts' of _options) _options['parts'] = 64 if !('angle' of _options) _options['angle'] = 45 ANGLE = ___radians _options.angle if !('step' of _options) _options['step'] = 2 STEP = ___radians _options.step # Size of bounding box: if !('size' of _options) _options['size'] = 250.0 SIZE = _options.size HALF = 0.5 * Math.sqrt(SIZE * SIZE + SIZE * SIZE) return @ # Add a new template. # # @param {String} name The name of the template. # @param {Array} points The points of the gesture. # # @return OneDollar add: (name, points) -> if points.length > 0 _templates[name] = _transform points return @ # Remove a template. # # @param {String} name The name of the template. # # @return OneDollar remove: (name) -> if _templates[name] isnt undefined delete _templates[name] return @ # Bind callback for chosen templates. # # @param {String} name The name of the template. # @param {function} fn The callback function. # # @return OneDollar on: (name, fn) -> names = [] if name == "*" for name, template of _templates names.push name else names = name.split ' ' for name in names if _templates[name] isnt undefined _binds[name] = fn _hasBinds = true else throw new Error "The template '" + name + "' isn't defined." return @ # Unbind callback for chosen templates. # # @param {String} name The name of the template. # # @return OneDollar off: (name) -> if _binds[name] isnt undefined delete _binds[name] _hasBinds = false for name, bind of _binds if _templates.hasOwnProperty name _hasBinds = true break return @ # Get information about the algorithm. # # @return Object Return options, templates and binds. toObject: -> return { options: _options templates: _templates binds: _binds } # Create a new gesture candidate. # # @param {Integer} id The unique ID of the candidate. # @param {Array} point The start position of the candidate. # # @return OneDollar start: (id, point) -> if typeof(id) is 'object' and typeof(point) is 'undefined' point = id id = -1 _candidates[id] = [] @update id, point return @ # Add a new position to a created candidate. # # @param {Integer} id The unique ID of the candidate. # @param {Array} point The new position of the candidate. # # @return OneDollar update: (id, point) -> if typeof(id) is 'object' and typeof(point) is 'undefined' point = id id = -1 _candidates[id].push point return @ # Close a new gesture candidate and trigger the gesture recognition. # # @param {Integer} id The unique ID of the candidate. # @param {Array} point The last position of the candidate. # # @return OneDollar end: (id, point) -> if typeof(id) is 'object' and typeof(point) is 'undefined' point = id id = -1 @update id, point result = @check _candidates[id] delete _candidates[id] return result # Run the gesture recognition. # # @param {Array} candidate The candidate gesture. # # @return {boolean|Object} The result object. check: (candidate) -> args = false points = candidate.length if points < 3 return args path = start: [candidate[0][0], candidate[0][1]] end: [candidate[points - 1][0], candidate[points - 1][1]] centroid: if points > 1 then ___centroid candidate else path.start candidate = _transform candidate ranking = [] bestDist = +Infinity bestName = null for name, template of _templates if _hasBinds == false or _binds[name] isnt undefined distance = _findBestMatch candidate, template score = parseFloat(((1.0 - distance / HALF) * 100).toFixed(2)) if isNaN score score = 0.0 ranking.push name: name score: score if distance < bestDist bestDist = distance bestName = name if ranking.length > 0 # Sorting: if ranking.length > 1 ranking.sort (a, b) -> return if a.score < b.score then 1 else -1 idx = candidate.length - 1 args = name: ranking[0].name score: ranking[0].score recognized: false path: path ranking: ranking if ranking[0].score >= _options.score args.recognized = true if _hasBinds _binds[ranking[0].name].apply @, [args] return args # Transform the data to a comparable format. # # @param {Array} points The raw candidate gesture. # # @return Array The transformed candidate. _transform = (points) -> # Algorithm step: points = __resample points # (1) points = __rotateToZero points # (2) points = __scaleToSquare points # (3) points = __translateToOrigin points # (4) return points # Find the best match between a candidate and template. # # @param {Array} candidate The candidate gesture. # @param {Array} template The template gesture. # # @return Float The computed smallest distance. _findBestMatch = (candidate, template) -> rt = ANGLE lt = -ANGLE centroid = ___centroid candidate x1 = PHI * lt + (1.0 - PHI) * rt f1 = __distanceAtAngle candidate, template, x1, centroid x2 = (1.0 - PHI) * lt + PHI * rt f2 = __distanceAtAngle candidate, template, x2, centroid while (Math.abs(rt - lt) > STEP) if f1 < f2 rt = x2 x2 = x1 f2 = f1 x1 = PHI * lt + (1.0 - PHI) * rt f1 = __distanceAtAngle candidate, template, x1, centroid else lt = x1 x1 = x2 f1 = f2 x2 = (1.0 - PHI) * lt + PHI * rt f2 = __distanceAtAngle candidate, template, x2, centroid return Math.min(f1, f2) # 1: Resampling of a gesture. # # @param {Array} points The points of a move. # # @return Array The resampled gesture. __resample = (points) -> seperator = (___length points) / (_options.parts - 1) distance = 0.0 resampled = [] resampled.push [points[0][0], points[0][1]] idx = 1 while idx < points.length prev = points[idx - 1] point = points[idx] space = ___distance(prev, point) if (distance + space) >= seperator x = prev[0] + ((seperator - distance) / space) * (point[0] - prev[0]) y = prev[1] + ((seperator - distance) / space) * (point[1] - prev[1]) resampled.push [x, y] points.splice idx, 0, [x, y] distance = 0.0 else distance += space idx += 1 while resampled.length < _options.parts resampled.push [points[points.length-1][0], points[points.length-1][1]] return resampled # 2: Rotation of the gesture. # # @param {Array} points The points of a move. # # @return Array The rotated gesture. __rotateToZero = (points) -> centroid = ___centroid points theta = Math.atan2(centroid[1] - points[0][1], centroid[0] - points[0][0]) return ___rotate points, -theta, centroid # 3: Scaling of a gesture. # # @param {Array} points The points of a move. # # @return Array The scaled gesture. __scaleToSquare = (points) -> minX = minY = +Infinity maxX = maxY = -Infinity for point in points minX = Math.min(point[0], minX) maxX = Math.max(point[0], maxX) minY = Math.min(point[1], minY) maxY = Math.max(point[1], maxY) deltaX = maxX - minX deltaY = maxY - minY offset = [SIZE / deltaX, SIZE / deltaY] return ___scale points, offset # 4: Translation of a gesture. # # @param {Array} points The points of a move. # # @return Array The translated gesture. __translateToOrigin = (points) -> centroid = ___centroid points centroid[0] *= -1 centroid[1] *= -1 return ___translate points, centroid # Compute the delta space between two sets of points at a specific angle. # # @param {Array} points1 The points of a move. # @param {Array} points2 The points of a move. # @param {Float} radians The radian value. # # @return Float The computed distance. __distanceAtAngle = (points1, points2, radians, centroid) -> _points1 = ___rotate points1, radians, centroid result = ___delta _points1, points2 return result # Compute the delta space between two sets of points. # # @param {Array} points1 The points of a move. # @param {Array} points2 The points of a move. # # @return Float The computed distance. ___delta = (points1, points2) -> delta = 0.0 for point, idx in points1 delta += ___distance(points1[idx], points2[idx]) return delta / points1.length # Compute the distance of a gesture. # # @param {Array} points The points of a move. # # @return Float The computed distance. ___length = (points) -> length = 0.0 prev = null for point in points if prev isnt null length += ___distance(prev, point) prev = point return length # Compute the euclidean distance between two points. # # @param {Array} p1 The first two dimensional point. # @param {Array} p2 The second two dimensional point. # # @return Float The computed euclidean distance. ___distance = (p1, p2) -> x = Math.pow(p1[0] - p2[0], 2) y = Math.pow(p1[1] - p2[1], 2) return Math.sqrt(x + y) # Compute the centroid of a set of points. # # @param {Array} points1 The points of a move. # # @return Array The centroid object. ___centroid = (points) -> x = 0.0 y = 0.0 for point in points x += point[0] y += point[1] x /= points.length y /= points.length return [x, y] # Rotate a gesture. # # @param {Array} points The points of a move. # @param {Float} radians The rotation angle. # @param {Array} pivot The pivot of the rotation. # # @return Array The rotated gesture. ___rotate = (points, radians, pivot) -> sin = Math.sin(radians) cos = Math.cos(radians) neew = [] for point, idx in points deltaX = points[idx][0] - pivot[0] deltaY = points[idx][1] - pivot[1] points[idx][0] = deltaX * cos - deltaY * sin + pivot[0] points[idx][1] = deltaX * sin + deltaY * cos + pivot[1] return points # Scale a gesture. # # @param {Array} points The points of a move. # @param {Array} offset The scalar values. # # @return Array The scaled gesture. ___scale = (points, offset) -> for point, idx in points points[idx][0] *= offset[0] points[idx][1] *= offset[1] return points # Translate a gesture. # # @param {Array} points The points of a move. # @param {Array} offset The translation values. # # @return Array The translated gesture. ___translate = (points, offset) -> for point, idx in points points[idx][0] += offset[0] points[idx][1] += offset[1] return points # Compute the radians from degrees. # # @param {Float} degrees The degree value. # # @return Float The computed radian value. ___radians = (degrees) -> return degrees * Math.PI / 180.0 # Environment and testing: if typeof exports isnt 'undefined' exports.OneDollar = OneDollar
true
# The library is Open Source Software released under the MIT License. # It's developed by PI:NAME:<NAME>END_PI. 2013-2016 # # https://github.com/nok/onedollar-coffeescript # # --- # # The $1 Gesture Recognizer is a research project by PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI of # the University of Washington and Microsoft Research. It describes a simple # algorithm for accurate and fast recognition of drawn gestures. # # Gestures can be recognised at any position, scale, and under any rotation. # The system requires little training, achieving a 97% recognition rate with # only one template for each gesture. # # http://depts.washington.edu/aimgroup/proj/dollar/ class OneDollar # Math constants: PHI = 0.5 * (-1.0 + Math.sqrt(5.0)) # Prepared inner variables: SIZE = HALF = ANGLE = STEP = null # Internal data handlers: _options = {} _templates = {} _binds = {} _hasBinds = false _candidates = [] # The constructor of the algorithm. # # @param {[object]} options The options of the algorithm. # # @return OneDollar constructor: (options = {}) -> _options = options # Threshold in percent of callbacks: if !('score' of _options) _options['score'] = 80 if !('parts' of _options) _options['parts'] = 64 if !('angle' of _options) _options['angle'] = 45 ANGLE = ___radians _options.angle if !('step' of _options) _options['step'] = 2 STEP = ___radians _options.step # Size of bounding box: if !('size' of _options) _options['size'] = 250.0 SIZE = _options.size HALF = 0.5 * Math.sqrt(SIZE * SIZE + SIZE * SIZE) return @ # Add a new template. # # @param {String} name The name of the template. # @param {Array} points The points of the gesture. # # @return OneDollar add: (name, points) -> if points.length > 0 _templates[name] = _transform points return @ # Remove a template. # # @param {String} name The name of the template. # # @return OneDollar remove: (name) -> if _templates[name] isnt undefined delete _templates[name] return @ # Bind callback for chosen templates. # # @param {String} name The name of the template. # @param {function} fn The callback function. # # @return OneDollar on: (name, fn) -> names = [] if name == "*" for name, template of _templates names.push name else names = name.split ' ' for name in names if _templates[name] isnt undefined _binds[name] = fn _hasBinds = true else throw new Error "The template '" + name + "' isn't defined." return @ # Unbind callback for chosen templates. # # @param {String} name The name of the template. # # @return OneDollar off: (name) -> if _binds[name] isnt undefined delete _binds[name] _hasBinds = false for name, bind of _binds if _templates.hasOwnProperty name _hasBinds = true break return @ # Get information about the algorithm. # # @return Object Return options, templates and binds. toObject: -> return { options: _options templates: _templates binds: _binds } # Create a new gesture candidate. # # @param {Integer} id The unique ID of the candidate. # @param {Array} point The start position of the candidate. # # @return OneDollar start: (id, point) -> if typeof(id) is 'object' and typeof(point) is 'undefined' point = id id = -1 _candidates[id] = [] @update id, point return @ # Add a new position to a created candidate. # # @param {Integer} id The unique ID of the candidate. # @param {Array} point The new position of the candidate. # # @return OneDollar update: (id, point) -> if typeof(id) is 'object' and typeof(point) is 'undefined' point = id id = -1 _candidates[id].push point return @ # Close a new gesture candidate and trigger the gesture recognition. # # @param {Integer} id The unique ID of the candidate. # @param {Array} point The last position of the candidate. # # @return OneDollar end: (id, point) -> if typeof(id) is 'object' and typeof(point) is 'undefined' point = id id = -1 @update id, point result = @check _candidates[id] delete _candidates[id] return result # Run the gesture recognition. # # @param {Array} candidate The candidate gesture. # # @return {boolean|Object} The result object. check: (candidate) -> args = false points = candidate.length if points < 3 return args path = start: [candidate[0][0], candidate[0][1]] end: [candidate[points - 1][0], candidate[points - 1][1]] centroid: if points > 1 then ___centroid candidate else path.start candidate = _transform candidate ranking = [] bestDist = +Infinity bestName = null for name, template of _templates if _hasBinds == false or _binds[name] isnt undefined distance = _findBestMatch candidate, template score = parseFloat(((1.0 - distance / HALF) * 100).toFixed(2)) if isNaN score score = 0.0 ranking.push name: name score: score if distance < bestDist bestDist = distance bestName = name if ranking.length > 0 # Sorting: if ranking.length > 1 ranking.sort (a, b) -> return if a.score < b.score then 1 else -1 idx = candidate.length - 1 args = name: ranking[0].name score: ranking[0].score recognized: false path: path ranking: ranking if ranking[0].score >= _options.score args.recognized = true if _hasBinds _binds[ranking[0].name].apply @, [args] return args # Transform the data to a comparable format. # # @param {Array} points The raw candidate gesture. # # @return Array The transformed candidate. _transform = (points) -> # Algorithm step: points = __resample points # (1) points = __rotateToZero points # (2) points = __scaleToSquare points # (3) points = __translateToOrigin points # (4) return points # Find the best match between a candidate and template. # # @param {Array} candidate The candidate gesture. # @param {Array} template The template gesture. # # @return Float The computed smallest distance. _findBestMatch = (candidate, template) -> rt = ANGLE lt = -ANGLE centroid = ___centroid candidate x1 = PHI * lt + (1.0 - PHI) * rt f1 = __distanceAtAngle candidate, template, x1, centroid x2 = (1.0 - PHI) * lt + PHI * rt f2 = __distanceAtAngle candidate, template, x2, centroid while (Math.abs(rt - lt) > STEP) if f1 < f2 rt = x2 x2 = x1 f2 = f1 x1 = PHI * lt + (1.0 - PHI) * rt f1 = __distanceAtAngle candidate, template, x1, centroid else lt = x1 x1 = x2 f1 = f2 x2 = (1.0 - PHI) * lt + PHI * rt f2 = __distanceAtAngle candidate, template, x2, centroid return Math.min(f1, f2) # 1: Resampling of a gesture. # # @param {Array} points The points of a move. # # @return Array The resampled gesture. __resample = (points) -> seperator = (___length points) / (_options.parts - 1) distance = 0.0 resampled = [] resampled.push [points[0][0], points[0][1]] idx = 1 while idx < points.length prev = points[idx - 1] point = points[idx] space = ___distance(prev, point) if (distance + space) >= seperator x = prev[0] + ((seperator - distance) / space) * (point[0] - prev[0]) y = prev[1] + ((seperator - distance) / space) * (point[1] - prev[1]) resampled.push [x, y] points.splice idx, 0, [x, y] distance = 0.0 else distance += space idx += 1 while resampled.length < _options.parts resampled.push [points[points.length-1][0], points[points.length-1][1]] return resampled # 2: Rotation of the gesture. # # @param {Array} points The points of a move. # # @return Array The rotated gesture. __rotateToZero = (points) -> centroid = ___centroid points theta = Math.atan2(centroid[1] - points[0][1], centroid[0] - points[0][0]) return ___rotate points, -theta, centroid # 3: Scaling of a gesture. # # @param {Array} points The points of a move. # # @return Array The scaled gesture. __scaleToSquare = (points) -> minX = minY = +Infinity maxX = maxY = -Infinity for point in points minX = Math.min(point[0], minX) maxX = Math.max(point[0], maxX) minY = Math.min(point[1], minY) maxY = Math.max(point[1], maxY) deltaX = maxX - minX deltaY = maxY - minY offset = [SIZE / deltaX, SIZE / deltaY] return ___scale points, offset # 4: Translation of a gesture. # # @param {Array} points The points of a move. # # @return Array The translated gesture. __translateToOrigin = (points) -> centroid = ___centroid points centroid[0] *= -1 centroid[1] *= -1 return ___translate points, centroid # Compute the delta space between two sets of points at a specific angle. # # @param {Array} points1 The points of a move. # @param {Array} points2 The points of a move. # @param {Float} radians The radian value. # # @return Float The computed distance. __distanceAtAngle = (points1, points2, radians, centroid) -> _points1 = ___rotate points1, radians, centroid result = ___delta _points1, points2 return result # Compute the delta space between two sets of points. # # @param {Array} points1 The points of a move. # @param {Array} points2 The points of a move. # # @return Float The computed distance. ___delta = (points1, points2) -> delta = 0.0 for point, idx in points1 delta += ___distance(points1[idx], points2[idx]) return delta / points1.length # Compute the distance of a gesture. # # @param {Array} points The points of a move. # # @return Float The computed distance. ___length = (points) -> length = 0.0 prev = null for point in points if prev isnt null length += ___distance(prev, point) prev = point return length # Compute the euclidean distance between two points. # # @param {Array} p1 The first two dimensional point. # @param {Array} p2 The second two dimensional point. # # @return Float The computed euclidean distance. ___distance = (p1, p2) -> x = Math.pow(p1[0] - p2[0], 2) y = Math.pow(p1[1] - p2[1], 2) return Math.sqrt(x + y) # Compute the centroid of a set of points. # # @param {Array} points1 The points of a move. # # @return Array The centroid object. ___centroid = (points) -> x = 0.0 y = 0.0 for point in points x += point[0] y += point[1] x /= points.length y /= points.length return [x, y] # Rotate a gesture. # # @param {Array} points The points of a move. # @param {Float} radians The rotation angle. # @param {Array} pivot The pivot of the rotation. # # @return Array The rotated gesture. ___rotate = (points, radians, pivot) -> sin = Math.sin(radians) cos = Math.cos(radians) neew = [] for point, idx in points deltaX = points[idx][0] - pivot[0] deltaY = points[idx][1] - pivot[1] points[idx][0] = deltaX * cos - deltaY * sin + pivot[0] points[idx][1] = deltaX * sin + deltaY * cos + pivot[1] return points # Scale a gesture. # # @param {Array} points The points of a move. # @param {Array} offset The scalar values. # # @return Array The scaled gesture. ___scale = (points, offset) -> for point, idx in points points[idx][0] *= offset[0] points[idx][1] *= offset[1] return points # Translate a gesture. # # @param {Array} points The points of a move. # @param {Array} offset The translation values. # # @return Array The translated gesture. ___translate = (points, offset) -> for point, idx in points points[idx][0] += offset[0] points[idx][1] += offset[1] return points # Compute the radians from degrees. # # @param {Float} degrees The degree value. # # @return Float The computed radian value. ___radians = (degrees) -> return degrees * Math.PI / 180.0 # Environment and testing: if typeof exports isnt 'undefined' exports.OneDollar = OneDollar
[ { "context": "if), mobile true olsun\n # https://github.com/blueimp/jQuery-File-Upload/wiki/Options -> to see options", "end": 2605, "score": 0.8986756801605225, "start": 2598, "tag": "USERNAME", "value": "blueimp" }, { "context": "ique_id = password\n # file2.unique_...
app/assets/javascripts/s3_direct_upload.js.coffee
fatihtas/s3_direct_upload_customized
2
#= require jquery-fileupload/basic #= require jquery-fileupload/vendor/tmpl $ = jQuery $isOpera = !!window.opr && !!opr.addons || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0 $isChrome = !!window.chrome && (!!window.chrome.webstore) $isFirefox = typeof InstallTrigger != 'undefined' console.log('isFirefox: ' +$isFirefox) $isSafari = /constructor/i.test(window.HTMLElement) || ((p) -> p.toString() == '[object SafariRemoteNotification]' )(!window['safari'] || typeof safari != 'undefined' && safari.pushNotification) $isIE = false || !!document.documentMode $isEdge = !$isIE && !!window.StyleMedia $isEdgeChromium = $isChrome && navigator.userAgent.indexOf('Edg') != -1 $isBlink = ($isChrome or $isOpera) and !!window.CSS $.fn.S3Uploader = (options) -> # support multiple elements if @length > 1 @each -> $(this).S3Uploader options return this $uploadForm = this settings = path: '' additional_data: null before_add: null remove_completed_progress_bar: true remove_failed_progress_bar: false progress_bar_target: null click_submit_target: null allow_multiple_files: true $.extend settings, options current_files = [] forms_for_submit = [] if settings.click_submit_target settings.click_submit_target.click -> form.submit() for form in forms_for_submit false setUploadForm = -> ## image duplication in different sizes: $.blueimp.fileupload::processActions.duplicateImage = (data, options) -> if data.canvas data.files.push data.files[data.index] data $uploadForm.fileupload( previewMaxWidth: 236 previewMaxHeight: 236 # forceIframeTransport: false ## default # singleFileUploads: true ## default # prependFiles: true # By default(false), files are appended to the files container. Set this option to true, to prepend files instead. # maxNumberOfFiles: 10 # Not working, probably this is indeed: # of data.files maxFileSize: 20000000 imageQuality: 80 imageMaxWidth: 1600 # 1600 imageMaxHeight: 1600 # 1600 imageCrop: false #previewCrop: true #sequentialUploads: false #disableImageMetaDataLoad: true #!($isFirefox || $isSafari || $isIE || $isEdge) #!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent) # masaustu dogru (exif almadik) mobilde (exif aliyoruz) yanlis olsun imageOrientation: true #!($isFirefox || $isSafari || $isIE || $isEdge) # masaustu false(cunku en bastan almadik exif), mobile true olsun # https://github.com/blueimp/jQuery-File-Upload/wiki/Options -> to see options (1-8),or (boolean) disableImageMetaDataSave: true #!($isFirefox || $isSafari || $isIE || $isEdge) # !/iPhone|iPad|iPod|Android/i.test(navigator.userAgent) #Disables saving the image meta data into the resized images (masaustu true olmali sanki, mobile false). #default false -> # bunu dene #Otherwise orientation is broken on iOS Safari #/Android(?!.*Chrome)|Opera/.test(window.navigator && navigator.userAgent) disableImageResize: false #($isFirefox || $isSafari || $isIE || $isEdge) # masaustu false mobilde true olsun #/Android(?!.*Chrome)|Opera/.test(window.navigator && navigator.userAgent) imageForceResize: true image_library: 0 #previewOrientation: 0 acceptFileTypes: /(\.|\/)(gif|jpe?g|png|webp|tiff|tif)$/i #### resize photos for S3 ... # processQueue: [ # { # action: 'loadImage' # fileTypes: /^image\/(gif|jpeg|png)$/ # maxFileSize: 20000000 # } # { # action: 'resizeImage' # maxWidth: 800 # maxHeight: 800 # # jpeg_quality: 100 # } # { action: 'saveImage' } # { action: 'duplicateImage' } # { # action: 'resizeImage' # maxWidth: 400 # maxHeight: 400 # # jpeg_quality: 100 # } # { action: 'saveImage' } # { action: 'duplicateImage' } # { # action: 'resizeImage' # maxWidth: 200 # maxHeight: 200 # # jpeg_quality: 100 # # crop: true # } # { action: 'saveImage' } # ] add: (e, data) -> # callback for the file upload request queue. It is invoked as soon as files are added current_data = $(this) data.process(-> return current_data.fileupload('process', data) ).done(-> #### From this line below, I tried to send resized photos to S3 as well.. #### Couldn't succeed to re-ignite. (lack of forms, lack of re-initiation during 1st process) # file1 = data.files[0] # file2 = data.files[1] # file3 = data.files[2] # # bu isimlendirmede hata oluyo, kucuk dosya gelince, olusturulmuyo o size'in altindakiler. # # ++ small'mu, medium'mu onu da bilemeyiz aslinda. bu durumda. belki de medium'da oluyo. hepsi yani ayni dosya olmali. # file1.unique_id = password # file2.unique_id = password # file3.unique_id = password # file1.name = file1.name.replace(/(\.[\w\d_-]+)$/i, '_small$1') # file2.name = file2.name.replace(/(\.[\w\d_-]+)$/i, '_large$1') # file3.name = file3.name.replace(/(\.[\w\d_-]+)$/i, '_medium$1'); # # leave only 1 file in data.files. # data.files.splice(2,1) # data.files.splice(0,1) file = data.files[0] password = Math.random().toString(36).substr(2,16) file.unique_id = password #### abort button koyuyoruz. # abortBtn = $('<a/>').attr('href', 'javascript:void(0)').addClass('btn btn-default').append('Abort').click(-> # data.abort() # data.context.remove() # $(this).remove() # return # ) # data.context = $('<div/>').appendTo('#abort_container') # data.context.append abortBtn #### abort button koyuyoruz. unless settings.before_add and not settings.before_add(file) current_files.push data if $('#template-upload').length > 0 data.context = $($.trim(tmpl("template-upload", file))) $(data.context).appendTo(settings.progress_bar_target || $uploadForm) else if !settings.allow_multiple_files data.context = settings.progress_bar_target if settings.click_submit_target if settings.allow_multiple_files forms_for_submit.push data else forms_for_submit = [data] else data.submit() ) start: (e) -> # Callback for uploads start $uploadForm.trigger("s3_uploads_start", [e]) progress: (e, data) -> #C allback for upload progress events. if data.context progress = parseInt(data.loaded / data.total * 100, 10) data.context.find('.bar').css('width', progress + '%') done: (e, data) -> #Callback for successful upload requests. # here you can perform an ajax call to get your documents to display on the screen. # $('#your_documents').load("/documents?for_item=1234"); content = build_content_object $uploadForm, data.files[0], data.result callback_url = $uploadForm.data('callback-url') if callback_url content[$uploadForm.data('callback-param')] = content.url # S3'ten gelen cevap sonrasi db'ye yollamak icin bunu hazirliyoz. $.ajax type: $uploadForm.data('callback-method') url: callback_url data: content beforeSend: ( xhr, settings ) -> event = $.Event('ajax:beforeSend') $uploadForm.trigger(event, [xhr, settings]) return event.result complete: ( xhr, status ) -> event = $.Event('ajax:complete') $uploadForm.trigger(event, [xhr, status]) return event.result success: ( data, status, xhr ) -> event = $.Event('ajax:success') $uploadForm.trigger(event, [data, status, xhr]) return event.result error: ( xhr, status, error ) -> event = $.Event('ajax:error') $uploadForm.trigger(event, [xhr, status, error]) return event.result data.context.remove() if data.context && settings.remove_completed_progress_bar # remove progress bar $uploadForm.trigger("s3_upload_complete", [content]) current_files.splice($.inArray(data, current_files), 1) # remove that element from the array $uploadForm.trigger("s3_uploads_complete", [content]) unless current_files.length fail: (e, data) -> # Callback for failed (abort or error) upload requests content = build_content_object $uploadForm, data.files[0], data.result content.error_thrown = data.errorThrown data.context.remove() if data.context && settings.remove_failed_progress_bar # remove progress bar $uploadForm.trigger("s3_upload_failed", [content]) #### CALLBACKS #### # submit: (e, data) -> # Callback for the submit event of each file upload. # send: (e, data) -> # Callback for the start of each file upload request. # always: (e, data) -> # Callback for completed (success, abort or error) upload requests # progressall: (e,data ) -> #Callback for global upload progress events. # stop: (e, data) -> # Callback for uploads stop # change: (e, data) -> # Callback for change events of the fileInput collection # paste: (e, data) -> # Callback for paste events to the dropZone collection # drop: (e, data) -> # Callback for drop events of the dropZone collection # dragover: (e, data)-> #Callback for dragover events of the dropZone collection. formData: (form) -> data = form.serializeArray() fileType = "" if "type" of @files[0] fileType = @files[0].type data.push name: "content-type" value: fileType key = $uploadForm.data("key") .replace('{timestamp}', new Date().getTime()) .replace('{unique_id}', @files[0].unique_id) .replace('{extension}', @files[0].name.split('.').pop()) # substitute upload timestamp and unique_id into key key_field = $.grep data, (n) -> n if n.name == "key" if key_field.length > 0 key_field[0].value = settings.path + key # IE <= 9 doesn't have XHR2 hence it can't use formData # replace 'key' field to submit form unless 'FormData' of window $uploadForm.find("input[name='key']").val(settings.path + key) data ).bind 'fileuploadprocessalways', (e, data) -> canvas = data.files[0].preview if canvas dataURL = canvas.toDataURL() $("#preview-image").removeClass('hidden').attr("src", dataURL) build_content_object = ($uploadForm, file, result) -> content = {} if result # Use the S3 response to set the URL to avoid character encodings bugs content.url = $(result).find("Location").text() content.filepath = $('<a />').attr('href', content.url)[0].pathname else # IE <= 9 retu rn a null result object so we use the file object instead domain = $uploadForm.attr('action') content.filepath = $uploadForm.find('input[name=key]').val().replace('/${filename}', '') content.url = domain + content.filepath + '/' + encodeURIComponent(file.name) content.filename = file.name content.filesize = file.size if 'size' of file content.lastModifiedDate = file.lastModifiedDate if 'lastModifiedDate' of file content.filetype = file.type if 'type' of file content.unique_id = file.unique_id if 'unique_id' of file content.relativePath = build_relativePath(file) if has_relativePath(file) content = $.extend content, settings.additional_data if settings.additional_data content has_relativePath = (file) -> file.relativePath || file.webkitRelativePath build_relativePath = (file) -> file.relativePath || (file.webkitRelativePath.split("/")[0..-2].join("/") + "/" if file.webkitRelativePath) #public methods @initialize = -> # Save key for IE9 Fix $uploadForm.data("key", $uploadForm.find("input[name='key']").val()) setUploadForm() this @path = (new_path) -> settings.path = new_path @additional_data = (new_data) -> settings.additional_data = new_data @initialize()
58528
#= require jquery-fileupload/basic #= require jquery-fileupload/vendor/tmpl $ = jQuery $isOpera = !!window.opr && !!opr.addons || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0 $isChrome = !!window.chrome && (!!window.chrome.webstore) $isFirefox = typeof InstallTrigger != 'undefined' console.log('isFirefox: ' +$isFirefox) $isSafari = /constructor/i.test(window.HTMLElement) || ((p) -> p.toString() == '[object SafariRemoteNotification]' )(!window['safari'] || typeof safari != 'undefined' && safari.pushNotification) $isIE = false || !!document.documentMode $isEdge = !$isIE && !!window.StyleMedia $isEdgeChromium = $isChrome && navigator.userAgent.indexOf('Edg') != -1 $isBlink = ($isChrome or $isOpera) and !!window.CSS $.fn.S3Uploader = (options) -> # support multiple elements if @length > 1 @each -> $(this).S3Uploader options return this $uploadForm = this settings = path: '' additional_data: null before_add: null remove_completed_progress_bar: true remove_failed_progress_bar: false progress_bar_target: null click_submit_target: null allow_multiple_files: true $.extend settings, options current_files = [] forms_for_submit = [] if settings.click_submit_target settings.click_submit_target.click -> form.submit() for form in forms_for_submit false setUploadForm = -> ## image duplication in different sizes: $.blueimp.fileupload::processActions.duplicateImage = (data, options) -> if data.canvas data.files.push data.files[data.index] data $uploadForm.fileupload( previewMaxWidth: 236 previewMaxHeight: 236 # forceIframeTransport: false ## default # singleFileUploads: true ## default # prependFiles: true # By default(false), files are appended to the files container. Set this option to true, to prepend files instead. # maxNumberOfFiles: 10 # Not working, probably this is indeed: # of data.files maxFileSize: 20000000 imageQuality: 80 imageMaxWidth: 1600 # 1600 imageMaxHeight: 1600 # 1600 imageCrop: false #previewCrop: true #sequentialUploads: false #disableImageMetaDataLoad: true #!($isFirefox || $isSafari || $isIE || $isEdge) #!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent) # masaustu dogru (exif almadik) mobilde (exif aliyoruz) yanlis olsun imageOrientation: true #!($isFirefox || $isSafari || $isIE || $isEdge) # masaustu false(cunku en bastan almadik exif), mobile true olsun # https://github.com/blueimp/jQuery-File-Upload/wiki/Options -> to see options (1-8),or (boolean) disableImageMetaDataSave: true #!($isFirefox || $isSafari || $isIE || $isEdge) # !/iPhone|iPad|iPod|Android/i.test(navigator.userAgent) #Disables saving the image meta data into the resized images (masaustu true olmali sanki, mobile false). #default false -> # bunu dene #Otherwise orientation is broken on iOS Safari #/Android(?!.*Chrome)|Opera/.test(window.navigator && navigator.userAgent) disableImageResize: false #($isFirefox || $isSafari || $isIE || $isEdge) # masaustu false mobilde true olsun #/Android(?!.*Chrome)|Opera/.test(window.navigator && navigator.userAgent) imageForceResize: true image_library: 0 #previewOrientation: 0 acceptFileTypes: /(\.|\/)(gif|jpe?g|png|webp|tiff|tif)$/i #### resize photos for S3 ... # processQueue: [ # { # action: 'loadImage' # fileTypes: /^image\/(gif|jpeg|png)$/ # maxFileSize: 20000000 # } # { # action: 'resizeImage' # maxWidth: 800 # maxHeight: 800 # # jpeg_quality: 100 # } # { action: 'saveImage' } # { action: 'duplicateImage' } # { # action: 'resizeImage' # maxWidth: 400 # maxHeight: 400 # # jpeg_quality: 100 # } # { action: 'saveImage' } # { action: 'duplicateImage' } # { # action: 'resizeImage' # maxWidth: 200 # maxHeight: 200 # # jpeg_quality: 100 # # crop: true # } # { action: 'saveImage' } # ] add: (e, data) -> # callback for the file upload request queue. It is invoked as soon as files are added current_data = $(this) data.process(-> return current_data.fileupload('process', data) ).done(-> #### From this line below, I tried to send resized photos to S3 as well.. #### Couldn't succeed to re-ignite. (lack of forms, lack of re-initiation during 1st process) # file1 = data.files[0] # file2 = data.files[1] # file3 = data.files[2] # # bu isimlendirmede hata oluyo, kucuk dosya gelince, olusturulmuyo o size'in altindakiler. # # ++ small'mu, medium'mu onu da bilemeyiz aslinda. bu durumda. belki de medium'da oluyo. hepsi yani ayni dosya olmali. # file1.unique_id = password # file2.unique_id = <PASSWORD> # file3.unique_id = password # file1.name = file1.name.replace(/(\.[\w\d_-]+)$/i, '_small$1') # file2.name = file2.name.replace(/(\.[\w\d_-]+)$/i, '_large$1') # file3.name = file3.name.replace(/(\.[\w\d_-]+)$/i, '_medium$1'); # # leave only 1 file in data.files. # data.files.splice(2,1) # data.files.splice(0,1) file = data.files[0] password = Math.random().toString(36).substr(2,16) file.unique_id = password #### abort button koyuyoruz. # abortBtn = $('<a/>').attr('href', 'javascript:void(0)').addClass('btn btn-default').append('Abort').click(-> # data.abort() # data.context.remove() # $(this).remove() # return # ) # data.context = $('<div/>').appendTo('#abort_container') # data.context.append abortBtn #### abort button koyuyoruz. unless settings.before_add and not settings.before_add(file) current_files.push data if $('#template-upload').length > 0 data.context = $($.trim(tmpl("template-upload", file))) $(data.context).appendTo(settings.progress_bar_target || $uploadForm) else if !settings.allow_multiple_files data.context = settings.progress_bar_target if settings.click_submit_target if settings.allow_multiple_files forms_for_submit.push data else forms_for_submit = [data] else data.submit() ) start: (e) -> # Callback for uploads start $uploadForm.trigger("s3_uploads_start", [e]) progress: (e, data) -> #C allback for upload progress events. if data.context progress = parseInt(data.loaded / data.total * 100, 10) data.context.find('.bar').css('width', progress + '%') done: (e, data) -> #Callback for successful upload requests. # here you can perform an ajax call to get your documents to display on the screen. # $('#your_documents').load("/documents?for_item=1234"); content = build_content_object $uploadForm, data.files[0], data.result callback_url = $uploadForm.data('callback-url') if callback_url content[$uploadForm.data('callback-param')] = content.url # S3'ten gelen cevap sonrasi db'ye yollamak icin bunu hazirliyoz. $.ajax type: $uploadForm.data('callback-method') url: callback_url data: content beforeSend: ( xhr, settings ) -> event = $.Event('ajax:beforeSend') $uploadForm.trigger(event, [xhr, settings]) return event.result complete: ( xhr, status ) -> event = $.Event('ajax:complete') $uploadForm.trigger(event, [xhr, status]) return event.result success: ( data, status, xhr ) -> event = $.Event('ajax:success') $uploadForm.trigger(event, [data, status, xhr]) return event.result error: ( xhr, status, error ) -> event = $.Event('ajax:error') $uploadForm.trigger(event, [xhr, status, error]) return event.result data.context.remove() if data.context && settings.remove_completed_progress_bar # remove progress bar $uploadForm.trigger("s3_upload_complete", [content]) current_files.splice($.inArray(data, current_files), 1) # remove that element from the array $uploadForm.trigger("s3_uploads_complete", [content]) unless current_files.length fail: (e, data) -> # Callback for failed (abort or error) upload requests content = build_content_object $uploadForm, data.files[0], data.result content.error_thrown = data.errorThrown data.context.remove() if data.context && settings.remove_failed_progress_bar # remove progress bar $uploadForm.trigger("s3_upload_failed", [content]) #### CALLBACKS #### # submit: (e, data) -> # Callback for the submit event of each file upload. # send: (e, data) -> # Callback for the start of each file upload request. # always: (e, data) -> # Callback for completed (success, abort or error) upload requests # progressall: (e,data ) -> #Callback for global upload progress events. # stop: (e, data) -> # Callback for uploads stop # change: (e, data) -> # Callback for change events of the fileInput collection # paste: (e, data) -> # Callback for paste events to the dropZone collection # drop: (e, data) -> # Callback for drop events of the dropZone collection # dragover: (e, data)-> #Callback for dragover events of the dropZone collection. formData: (form) -> data = form.serializeArray() fileType = "" if "type" of @files[0] fileType = @files[0].type data.push name: "content-type" value: fileType key = $uploadForm.data("key") .replace('{timestamp}', new Date().getTime()) .replace('{unique_id}', @files[0].unique_id) .replace('{extension}', @files[0].name.split('.').pop()) # substitute upload timestamp and unique_id into key key_field = $.grep data, (n) -> n if n.name == "key" if key_field.length > 0 key_field[0].value = settings.path + key # IE <= 9 doesn't have XHR2 hence it can't use formData # replace 'key' field to submit form unless 'FormData' of window $uploadForm.find("input[name='key']").val(settings.path + key) data ).bind 'fileuploadprocessalways', (e, data) -> canvas = data.files[0].preview if canvas dataURL = canvas.toDataURL() $("#preview-image").removeClass('hidden').attr("src", dataURL) build_content_object = ($uploadForm, file, result) -> content = {} if result # Use the S3 response to set the URL to avoid character encodings bugs content.url = $(result).find("Location").text() content.filepath = $('<a />').attr('href', content.url)[0].pathname else # IE <= 9 retu rn a null result object so we use the file object instead domain = $uploadForm.attr('action') content.filepath = $uploadForm.find('input[name=key]').val().replace('/${filename}', '') content.url = domain + content.filepath + '/' + encodeURIComponent(file.name) content.filename = file.name content.filesize = file.size if 'size' of file content.lastModifiedDate = file.lastModifiedDate if 'lastModifiedDate' of file content.filetype = file.type if 'type' of file content.unique_id = file.unique_id if 'unique_id' of file content.relativePath = build_relativePath(file) if has_relativePath(file) content = $.extend content, settings.additional_data if settings.additional_data content has_relativePath = (file) -> file.relativePath || file.webkitRelativePath build_relativePath = (file) -> file.relativePath || (file.webkitRelativePath.split("/")[0..-2].join("/") + "/" if file.webkitRelativePath) #public methods @initialize = -> # Save key for IE9 Fix $uploadForm.data("key", $uploadForm.find("input[name='key']").val()) setUploadForm() this @path = (new_path) -> settings.path = new_path @additional_data = (new_data) -> settings.additional_data = new_data @initialize()
true
#= require jquery-fileupload/basic #= require jquery-fileupload/vendor/tmpl $ = jQuery $isOpera = !!window.opr && !!opr.addons || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0 $isChrome = !!window.chrome && (!!window.chrome.webstore) $isFirefox = typeof InstallTrigger != 'undefined' console.log('isFirefox: ' +$isFirefox) $isSafari = /constructor/i.test(window.HTMLElement) || ((p) -> p.toString() == '[object SafariRemoteNotification]' )(!window['safari'] || typeof safari != 'undefined' && safari.pushNotification) $isIE = false || !!document.documentMode $isEdge = !$isIE && !!window.StyleMedia $isEdgeChromium = $isChrome && navigator.userAgent.indexOf('Edg') != -1 $isBlink = ($isChrome or $isOpera) and !!window.CSS $.fn.S3Uploader = (options) -> # support multiple elements if @length > 1 @each -> $(this).S3Uploader options return this $uploadForm = this settings = path: '' additional_data: null before_add: null remove_completed_progress_bar: true remove_failed_progress_bar: false progress_bar_target: null click_submit_target: null allow_multiple_files: true $.extend settings, options current_files = [] forms_for_submit = [] if settings.click_submit_target settings.click_submit_target.click -> form.submit() for form in forms_for_submit false setUploadForm = -> ## image duplication in different sizes: $.blueimp.fileupload::processActions.duplicateImage = (data, options) -> if data.canvas data.files.push data.files[data.index] data $uploadForm.fileupload( previewMaxWidth: 236 previewMaxHeight: 236 # forceIframeTransport: false ## default # singleFileUploads: true ## default # prependFiles: true # By default(false), files are appended to the files container. Set this option to true, to prepend files instead. # maxNumberOfFiles: 10 # Not working, probably this is indeed: # of data.files maxFileSize: 20000000 imageQuality: 80 imageMaxWidth: 1600 # 1600 imageMaxHeight: 1600 # 1600 imageCrop: false #previewCrop: true #sequentialUploads: false #disableImageMetaDataLoad: true #!($isFirefox || $isSafari || $isIE || $isEdge) #!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent) # masaustu dogru (exif almadik) mobilde (exif aliyoruz) yanlis olsun imageOrientation: true #!($isFirefox || $isSafari || $isIE || $isEdge) # masaustu false(cunku en bastan almadik exif), mobile true olsun # https://github.com/blueimp/jQuery-File-Upload/wiki/Options -> to see options (1-8),or (boolean) disableImageMetaDataSave: true #!($isFirefox || $isSafari || $isIE || $isEdge) # !/iPhone|iPad|iPod|Android/i.test(navigator.userAgent) #Disables saving the image meta data into the resized images (masaustu true olmali sanki, mobile false). #default false -> # bunu dene #Otherwise orientation is broken on iOS Safari #/Android(?!.*Chrome)|Opera/.test(window.navigator && navigator.userAgent) disableImageResize: false #($isFirefox || $isSafari || $isIE || $isEdge) # masaustu false mobilde true olsun #/Android(?!.*Chrome)|Opera/.test(window.navigator && navigator.userAgent) imageForceResize: true image_library: 0 #previewOrientation: 0 acceptFileTypes: /(\.|\/)(gif|jpe?g|png|webp|tiff|tif)$/i #### resize photos for S3 ... # processQueue: [ # { # action: 'loadImage' # fileTypes: /^image\/(gif|jpeg|png)$/ # maxFileSize: 20000000 # } # { # action: 'resizeImage' # maxWidth: 800 # maxHeight: 800 # # jpeg_quality: 100 # } # { action: 'saveImage' } # { action: 'duplicateImage' } # { # action: 'resizeImage' # maxWidth: 400 # maxHeight: 400 # # jpeg_quality: 100 # } # { action: 'saveImage' } # { action: 'duplicateImage' } # { # action: 'resizeImage' # maxWidth: 200 # maxHeight: 200 # # jpeg_quality: 100 # # crop: true # } # { action: 'saveImage' } # ] add: (e, data) -> # callback for the file upload request queue. It is invoked as soon as files are added current_data = $(this) data.process(-> return current_data.fileupload('process', data) ).done(-> #### From this line below, I tried to send resized photos to S3 as well.. #### Couldn't succeed to re-ignite. (lack of forms, lack of re-initiation during 1st process) # file1 = data.files[0] # file2 = data.files[1] # file3 = data.files[2] # # bu isimlendirmede hata oluyo, kucuk dosya gelince, olusturulmuyo o size'in altindakiler. # # ++ small'mu, medium'mu onu da bilemeyiz aslinda. bu durumda. belki de medium'da oluyo. hepsi yani ayni dosya olmali. # file1.unique_id = password # file2.unique_id = PI:PASSWORD:<PASSWORD>END_PI # file3.unique_id = password # file1.name = file1.name.replace(/(\.[\w\d_-]+)$/i, '_small$1') # file2.name = file2.name.replace(/(\.[\w\d_-]+)$/i, '_large$1') # file3.name = file3.name.replace(/(\.[\w\d_-]+)$/i, '_medium$1'); # # leave only 1 file in data.files. # data.files.splice(2,1) # data.files.splice(0,1) file = data.files[0] password = Math.random().toString(36).substr(2,16) file.unique_id = password #### abort button koyuyoruz. # abortBtn = $('<a/>').attr('href', 'javascript:void(0)').addClass('btn btn-default').append('Abort').click(-> # data.abort() # data.context.remove() # $(this).remove() # return # ) # data.context = $('<div/>').appendTo('#abort_container') # data.context.append abortBtn #### abort button koyuyoruz. unless settings.before_add and not settings.before_add(file) current_files.push data if $('#template-upload').length > 0 data.context = $($.trim(tmpl("template-upload", file))) $(data.context).appendTo(settings.progress_bar_target || $uploadForm) else if !settings.allow_multiple_files data.context = settings.progress_bar_target if settings.click_submit_target if settings.allow_multiple_files forms_for_submit.push data else forms_for_submit = [data] else data.submit() ) start: (e) -> # Callback for uploads start $uploadForm.trigger("s3_uploads_start", [e]) progress: (e, data) -> #C allback for upload progress events. if data.context progress = parseInt(data.loaded / data.total * 100, 10) data.context.find('.bar').css('width', progress + '%') done: (e, data) -> #Callback for successful upload requests. # here you can perform an ajax call to get your documents to display on the screen. # $('#your_documents').load("/documents?for_item=1234"); content = build_content_object $uploadForm, data.files[0], data.result callback_url = $uploadForm.data('callback-url') if callback_url content[$uploadForm.data('callback-param')] = content.url # S3'ten gelen cevap sonrasi db'ye yollamak icin bunu hazirliyoz. $.ajax type: $uploadForm.data('callback-method') url: callback_url data: content beforeSend: ( xhr, settings ) -> event = $.Event('ajax:beforeSend') $uploadForm.trigger(event, [xhr, settings]) return event.result complete: ( xhr, status ) -> event = $.Event('ajax:complete') $uploadForm.trigger(event, [xhr, status]) return event.result success: ( data, status, xhr ) -> event = $.Event('ajax:success') $uploadForm.trigger(event, [data, status, xhr]) return event.result error: ( xhr, status, error ) -> event = $.Event('ajax:error') $uploadForm.trigger(event, [xhr, status, error]) return event.result data.context.remove() if data.context && settings.remove_completed_progress_bar # remove progress bar $uploadForm.trigger("s3_upload_complete", [content]) current_files.splice($.inArray(data, current_files), 1) # remove that element from the array $uploadForm.trigger("s3_uploads_complete", [content]) unless current_files.length fail: (e, data) -> # Callback for failed (abort or error) upload requests content = build_content_object $uploadForm, data.files[0], data.result content.error_thrown = data.errorThrown data.context.remove() if data.context && settings.remove_failed_progress_bar # remove progress bar $uploadForm.trigger("s3_upload_failed", [content]) #### CALLBACKS #### # submit: (e, data) -> # Callback for the submit event of each file upload. # send: (e, data) -> # Callback for the start of each file upload request. # always: (e, data) -> # Callback for completed (success, abort or error) upload requests # progressall: (e,data ) -> #Callback for global upload progress events. # stop: (e, data) -> # Callback for uploads stop # change: (e, data) -> # Callback for change events of the fileInput collection # paste: (e, data) -> # Callback for paste events to the dropZone collection # drop: (e, data) -> # Callback for drop events of the dropZone collection # dragover: (e, data)-> #Callback for dragover events of the dropZone collection. formData: (form) -> data = form.serializeArray() fileType = "" if "type" of @files[0] fileType = @files[0].type data.push name: "content-type" value: fileType key = $uploadForm.data("key") .replace('{timestamp}', new Date().getTime()) .replace('{unique_id}', @files[0].unique_id) .replace('{extension}', @files[0].name.split('.').pop()) # substitute upload timestamp and unique_id into key key_field = $.grep data, (n) -> n if n.name == "key" if key_field.length > 0 key_field[0].value = settings.path + key # IE <= 9 doesn't have XHR2 hence it can't use formData # replace 'key' field to submit form unless 'FormData' of window $uploadForm.find("input[name='key']").val(settings.path + key) data ).bind 'fileuploadprocessalways', (e, data) -> canvas = data.files[0].preview if canvas dataURL = canvas.toDataURL() $("#preview-image").removeClass('hidden').attr("src", dataURL) build_content_object = ($uploadForm, file, result) -> content = {} if result # Use the S3 response to set the URL to avoid character encodings bugs content.url = $(result).find("Location").text() content.filepath = $('<a />').attr('href', content.url)[0].pathname else # IE <= 9 retu rn a null result object so we use the file object instead domain = $uploadForm.attr('action') content.filepath = $uploadForm.find('input[name=key]').val().replace('/${filename}', '') content.url = domain + content.filepath + '/' + encodeURIComponent(file.name) content.filename = file.name content.filesize = file.size if 'size' of file content.lastModifiedDate = file.lastModifiedDate if 'lastModifiedDate' of file content.filetype = file.type if 'type' of file content.unique_id = file.unique_id if 'unique_id' of file content.relativePath = build_relativePath(file) if has_relativePath(file) content = $.extend content, settings.additional_data if settings.additional_data content has_relativePath = (file) -> file.relativePath || file.webkitRelativePath build_relativePath = (file) -> file.relativePath || (file.webkitRelativePath.split("/")[0..-2].join("/") + "/" if file.webkitRelativePath) #public methods @initialize = -> # Save key for IE9 Fix $uploadForm.data("key", $uploadForm.find("input[name='key']").val()) setUploadForm() this @path = (new_path) -> settings.path = new_path @additional_data = (new_data) -> settings.additional_data = new_data @initialize()
[ { "context": "s file is part of the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyrig", "end": 74, "score": 0.9998769760131836, "start": 61, "tag": "NAME", "value": "Jessym Reziga" }, { "context": "f the Konsserto package.\n *\n * (c) Je...
node_modules/konsserto/lib/src/Konsserto/Bundle/FrameworkBundle/Command/AssetsInstallCommand.coffee
konsserto/konsserto
2
### * This file is part of the Konsserto package. * * (c) Jessym Reziga <jessym@konsserto.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### cc = use('cli-color') filesystem = use('fs') path = use('path') Table = use('cli-table'); Command = use('@Konsserto/Component/Console/Command') Filesystem = use('@Konsserto/Component/Filesystem/Filesystem') InputArgument = use('@Konsserto/Component/Console/Input/InputArgument') InputOption = use('@Konsserto/Component/Console/Input/InputOption') Tools = use('@Konsserto/Component/Static/Tools'); # # AssetsInstallCommand # # @author Jessym Reziga <jessym@konsserto.com> # class AssetsInstallCommand extends Command create:() -> @setName('assets:install') @setDescription('Manage assets and installs bundles web assets under a public web directory') @setDefinition([new InputArgument('target',InputArgument.OPTIONAL,'The target directory','web')]) @setHelp(' The command %command.name% installs bundle assets into a given directory.\n Example:\n %command.full_name% web') execute:(input) -> target = path.normalize(process.cwd()+'/'+input.getArgument('target')+'/') table = new Table({chars:@getArrayChars()}); table.push(['Konsserto Assets Installation']) @write('\n\n'+table.toString()+'\n') if (filesystem.existsSync(target)) target = target + 'bundles/' Filesystem.mkdir(target,755,true) for name,bundle of @getContainer().get('Application').getBundles() bundleTarget = path.normalize(target + Tools.replaceFinalOccurence(bundle.getName().toLowerCase(),'bundle')) bundlePublic = bundle.getPublicPath() if filesystem.existsSync(bundlePublic) Filesystem.mkdir(bundleTarget,755) Filesystem.copytree(bundle.getPublicPath(), bundleTarget) else throw new Error('Directory doesn\'t exists : '+target) return 0 module.exports = AssetsInstallCommand;
33937
### * This file is part of the Konsserto package. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### cc = use('cli-color') filesystem = use('fs') path = use('path') Table = use('cli-table'); Command = use('@Konsserto/Component/Console/Command') Filesystem = use('@Konsserto/Component/Filesystem/Filesystem') InputArgument = use('@Konsserto/Component/Console/Input/InputArgument') InputOption = use('@Konsserto/Component/Console/Input/InputOption') Tools = use('@Konsserto/Component/Static/Tools'); # # AssetsInstallCommand # # @author <NAME> <<EMAIL>> # class AssetsInstallCommand extends Command create:() -> @setName('assets:install') @setDescription('Manage assets and installs bundles web assets under a public web directory') @setDefinition([new InputArgument('target',InputArgument.OPTIONAL,'The target directory','web')]) @setHelp(' The command %command.name% installs bundle assets into a given directory.\n Example:\n %command.full_name% web') execute:(input) -> target = path.normalize(process.cwd()+'/'+input.getArgument('target')+'/') table = new Table({chars:@getArrayChars()}); table.push(['Konsserto Assets Installation']) @write('\n\n'+table.toString()+'\n') if (filesystem.existsSync(target)) target = target + 'bundles/' Filesystem.mkdir(target,755,true) for name,bundle of @getContainer().get('Application').getBundles() bundleTarget = path.normalize(target + Tools.replaceFinalOccurence(bundle.getName().toLowerCase(),'bundle')) bundlePublic = bundle.getPublicPath() if filesystem.existsSync(bundlePublic) Filesystem.mkdir(bundleTarget,755) Filesystem.copytree(bundle.getPublicPath(), bundleTarget) else throw new Error('Directory doesn\'t exists : '+target) return 0 module.exports = AssetsInstallCommand;
true
### * This file is part of the Konsserto package. * * (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### cc = use('cli-color') filesystem = use('fs') path = use('path') Table = use('cli-table'); Command = use('@Konsserto/Component/Console/Command') Filesystem = use('@Konsserto/Component/Filesystem/Filesystem') InputArgument = use('@Konsserto/Component/Console/Input/InputArgument') InputOption = use('@Konsserto/Component/Console/Input/InputOption') Tools = use('@Konsserto/Component/Static/Tools'); # # AssetsInstallCommand # # @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # class AssetsInstallCommand extends Command create:() -> @setName('assets:install') @setDescription('Manage assets and installs bundles web assets under a public web directory') @setDefinition([new InputArgument('target',InputArgument.OPTIONAL,'The target directory','web')]) @setHelp(' The command %command.name% installs bundle assets into a given directory.\n Example:\n %command.full_name% web') execute:(input) -> target = path.normalize(process.cwd()+'/'+input.getArgument('target')+'/') table = new Table({chars:@getArrayChars()}); table.push(['Konsserto Assets Installation']) @write('\n\n'+table.toString()+'\n') if (filesystem.existsSync(target)) target = target + 'bundles/' Filesystem.mkdir(target,755,true) for name,bundle of @getContainer().get('Application').getBundles() bundleTarget = path.normalize(target + Tools.replaceFinalOccurence(bundle.getName().toLowerCase(),'bundle')) bundlePublic = bundle.getPublicPath() if filesystem.existsSync(bundlePublic) Filesystem.mkdir(bundleTarget,755) Filesystem.copytree(bundle.getPublicPath(), bundleTarget) else throw new Error('Directory doesn\'t exists : '+target) return 0 module.exports = AssetsInstallCommand;
[ { "context": "ore likely to be an offensive force.\n *\n * @name Bard\n * @magical\n * @support\n * @hp 50+[level*10]+[", "end": 276, "score": 0.9983078241348267, "start": 272, "tag": "NAME", "value": "Bard" } ]
src/character/classes/Bard.coffee
sadbear-/IdleLands
0
Class = require "./../base/Class" MessageCreator = require "../../system/MessageCreator" `/** * This class is a very supportive class. They sing their songs to buff their allies. * If they have no allies, they are more likely to be an offensive force. * * @name Bard * @magical * @support * @hp 50+[level*10]+[con*6] * @mp 100+[level*3]+[int*5] * @itemScore int*1.4 + wis*1.4 - con*0.8 - str*0.8 * @statPerLevel {str} 1 * @statPerLevel {dex} 1 * @statPerLevel {con} 1 * @statPerLevel {int} 3 * @statPerLevel {wis} 3 * @statPerLevel {agi} 3 * @minDamage 10% * @category Classes * @package Player */` class Bard extends Class baseHp: 50 baseHpPerLevel: 10 baseHpPerCon: 6 baseMp: 100 baseMpPerLevel: 3 baseMpPerInt: 5 baseConPerLevel: 1 baseDexPerLevel: 1 baseAgiPerLevel: 3 baseStrPerLevel: 1 baseIntPerLevel: 3 baseWisPerLevel: 3 baseGoldGainPerCombat: 1000 itemScore: (player, item) -> item.int*1.4 + item.wis*1.4 - item.con*0.8 - item.str*0.8 physicalAttackChance: (player) -> if player.party and player.party.players.length > 1 then -20 else 20 minDamage: (player) -> player.calc.damage()*0.10 events: {} module.exports = exports = Bard
166439
Class = require "./../base/Class" MessageCreator = require "../../system/MessageCreator" `/** * This class is a very supportive class. They sing their songs to buff their allies. * If they have no allies, they are more likely to be an offensive force. * * @name <NAME> * @magical * @support * @hp 50+[level*10]+[con*6] * @mp 100+[level*3]+[int*5] * @itemScore int*1.4 + wis*1.4 - con*0.8 - str*0.8 * @statPerLevel {str} 1 * @statPerLevel {dex} 1 * @statPerLevel {con} 1 * @statPerLevel {int} 3 * @statPerLevel {wis} 3 * @statPerLevel {agi} 3 * @minDamage 10% * @category Classes * @package Player */` class Bard extends Class baseHp: 50 baseHpPerLevel: 10 baseHpPerCon: 6 baseMp: 100 baseMpPerLevel: 3 baseMpPerInt: 5 baseConPerLevel: 1 baseDexPerLevel: 1 baseAgiPerLevel: 3 baseStrPerLevel: 1 baseIntPerLevel: 3 baseWisPerLevel: 3 baseGoldGainPerCombat: 1000 itemScore: (player, item) -> item.int*1.4 + item.wis*1.4 - item.con*0.8 - item.str*0.8 physicalAttackChance: (player) -> if player.party and player.party.players.length > 1 then -20 else 20 minDamage: (player) -> player.calc.damage()*0.10 events: {} module.exports = exports = Bard
true
Class = require "./../base/Class" MessageCreator = require "../../system/MessageCreator" `/** * This class is a very supportive class. They sing their songs to buff their allies. * If they have no allies, they are more likely to be an offensive force. * * @name PI:NAME:<NAME>END_PI * @magical * @support * @hp 50+[level*10]+[con*6] * @mp 100+[level*3]+[int*5] * @itemScore int*1.4 + wis*1.4 - con*0.8 - str*0.8 * @statPerLevel {str} 1 * @statPerLevel {dex} 1 * @statPerLevel {con} 1 * @statPerLevel {int} 3 * @statPerLevel {wis} 3 * @statPerLevel {agi} 3 * @minDamage 10% * @category Classes * @package Player */` class Bard extends Class baseHp: 50 baseHpPerLevel: 10 baseHpPerCon: 6 baseMp: 100 baseMpPerLevel: 3 baseMpPerInt: 5 baseConPerLevel: 1 baseDexPerLevel: 1 baseAgiPerLevel: 3 baseStrPerLevel: 1 baseIntPerLevel: 3 baseWisPerLevel: 3 baseGoldGainPerCombat: 1000 itemScore: (player, item) -> item.int*1.4 + item.wis*1.4 - item.con*0.8 - item.str*0.8 physicalAttackChance: (player) -> if player.party and player.party.players.length > 1 then -20 else 20 minDamage: (player) -> player.calc.damage()*0.10 events: {} module.exports = exports = Bard
[ { "context": "ew Delta(10, 10, [new RetainOp(0, 10, {authorId: 'Gandalf'})])\n console.assert(delta.isIdentity() == tru", "end": 1309, "score": 0.9037235379219055, "start": 1302, "tag": "NAME", "value": "Gandalf" }, { "context": "new Delta(10, 10, [new RetainOp(0, 5, {authorId: 'G...
tests/isIdentity.coffee
tandem/tandem-core
2
# Copyright (c) 2012, Salesforce.com, Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. Redistributions in binary # form must reproduce the above copyright notice, this list of conditions and # the following disclaimer in the documentation and/or other materials provided # with the distribution. Neither the name of Salesforce.com nor the names of # its contributors may be used to endorse or promote products derived from this # software without specific prior written permission. assert = require('chai').assert Tandem = require('../index') Delta = Tandem.Delta InsertOp = Tandem.InsertOp RetainOp = Tandem.RetainOp describe('isIdentity', -> it('should accept the identity with no attributes', -> delta = new Delta(10, 10, [new RetainOp(0, 10)]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should accept the identity with an author attribute', -> delta = new Delta(10, 10, [new RetainOp(0, 10, {authorId: 'Gandalf'})]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should accept the noncompacted identity', -> delta = new Delta(10, 10, [new RetainOp(0, 5), new RetainOp(5, 10)]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should accept the noncompacted identity with complete author attributes', -> delta = new Delta(10, 10, [new RetainOp(0, 5, {authorId: 'Gandalf'}), new RetainOp(5, 10, {authorId: 'Frodo'})]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should accept the noncompacted identity with partial author attribution', -> delta = new Delta(10, 10, [new RetainOp(0, 5), new RetainOp(5, 10, {authorId: 'Frodo'})]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should accept the noncompacted identity with partial author attribution', -> delta = new Delta(10, 10, [new RetainOp(0, 5, {authorId: 'Frodo'}), new RetainOp(5, 10)]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should reject the complete retain of a document if it contains non-author attr', -> delta = new Delta(10, 10, [new RetainOp(0, 10, {bold: true})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} not to be the identity, but delta.isIdentity() says it is") ) it('should reject the complete retain of a document if it contains non-author attr', -> delta = new Delta(10, 10, [new RetainOp(0, 5, {bold: true}), new RetainOp(5, 10, {authorId: 'Frodo'})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} to not be the identity, but delta.isIdentity() says it is") ) it('should reject the complete retain of a document if it contains non-author attr', -> delta = new Delta(10, 10, [new RetainOp(0, 5, {bold: true}), new RetainOp(5, 10, {bold: null})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} to not be the identity, but delta.isIdentity() says it is") ) it('should reject the complete retain of a document if it contains non-author attr', -> delta = new Delta(10, 10, [new RetainOp(0, 5), new RetainOp(5, 10, {bold: true})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} not to be the identity, but delta.isIdentity() says it is") ) it('should reject the complete retain of a document if it contains non-author attr', -> delta = new Delta(10, 10, [new RetainOp(0, 10, {authorId: 'Gandalf', bold: true})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} not to be the identity, but delta.isIdentity() says it is") ) it('should reject any delta containing an InsertOp', -> delta = new Delta(10, 10, [new RetainOp(0, 4), new InsertOp("a"), new RetainOp(5, 10, {authorId: 'Frodo'})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} to not be the identity, but delta.isIdentity() says it is") ) )
12239
# Copyright (c) 2012, Salesforce.com, Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. Redistributions in binary # form must reproduce the above copyright notice, this list of conditions and # the following disclaimer in the documentation and/or other materials provided # with the distribution. Neither the name of Salesforce.com nor the names of # its contributors may be used to endorse or promote products derived from this # software without specific prior written permission. assert = require('chai').assert Tandem = require('../index') Delta = Tandem.Delta InsertOp = Tandem.InsertOp RetainOp = Tandem.RetainOp describe('isIdentity', -> it('should accept the identity with no attributes', -> delta = new Delta(10, 10, [new RetainOp(0, 10)]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should accept the identity with an author attribute', -> delta = new Delta(10, 10, [new RetainOp(0, 10, {authorId: '<NAME>'})]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should accept the noncompacted identity', -> delta = new Delta(10, 10, [new RetainOp(0, 5), new RetainOp(5, 10)]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should accept the noncompacted identity with complete author attributes', -> delta = new Delta(10, 10, [new RetainOp(0, 5, {authorId: '<NAME>andalf'}), new RetainOp(5, 10, {authorId: 'Frodo'})]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should accept the noncompacted identity with partial author attribution', -> delta = new Delta(10, 10, [new RetainOp(0, 5), new RetainOp(5, 10, {authorId: 'Frodo'})]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should accept the noncompacted identity with partial author attribution', -> delta = new Delta(10, 10, [new RetainOp(0, 5, {authorId: 'Frodo'}), new RetainOp(5, 10)]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should reject the complete retain of a document if it contains non-author attr', -> delta = new Delta(10, 10, [new RetainOp(0, 10, {bold: true})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} not to be the identity, but delta.isIdentity() says it is") ) it('should reject the complete retain of a document if it contains non-author attr', -> delta = new Delta(10, 10, [new RetainOp(0, 5, {bold: true}), new RetainOp(5, 10, {authorId: 'Frodo'})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} to not be the identity, but delta.isIdentity() says it is") ) it('should reject the complete retain of a document if it contains non-author attr', -> delta = new Delta(10, 10, [new RetainOp(0, 5, {bold: true}), new RetainOp(5, 10, {bold: null})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} to not be the identity, but delta.isIdentity() says it is") ) it('should reject the complete retain of a document if it contains non-author attr', -> delta = new Delta(10, 10, [new RetainOp(0, 5), new RetainOp(5, 10, {bold: true})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} not to be the identity, but delta.isIdentity() says it is") ) it('should reject the complete retain of a document if it contains non-author attr', -> delta = new Delta(10, 10, [new RetainOp(0, 10, {authorId: 'Gandalf', bold: true})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} not to be the identity, but delta.isIdentity() says it is") ) it('should reject any delta containing an InsertOp', -> delta = new Delta(10, 10, [new RetainOp(0, 4), new InsertOp("a"), new RetainOp(5, 10, {authorId: 'Frodo'})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} to not be the identity, but delta.isIdentity() says it is") ) )
true
# Copyright (c) 2012, Salesforce.com, Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. Redistributions in binary # form must reproduce the above copyright notice, this list of conditions and # the following disclaimer in the documentation and/or other materials provided # with the distribution. Neither the name of Salesforce.com nor the names of # its contributors may be used to endorse or promote products derived from this # software without specific prior written permission. assert = require('chai').assert Tandem = require('../index') Delta = Tandem.Delta InsertOp = Tandem.InsertOp RetainOp = Tandem.RetainOp describe('isIdentity', -> it('should accept the identity with no attributes', -> delta = new Delta(10, 10, [new RetainOp(0, 10)]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should accept the identity with an author attribute', -> delta = new Delta(10, 10, [new RetainOp(0, 10, {authorId: 'PI:NAME:<NAME>END_PI'})]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should accept the noncompacted identity', -> delta = new Delta(10, 10, [new RetainOp(0, 5), new RetainOp(5, 10)]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should accept the noncompacted identity with complete author attributes', -> delta = new Delta(10, 10, [new RetainOp(0, 5, {authorId: 'PI:NAME:<NAME>END_PIandalf'}), new RetainOp(5, 10, {authorId: 'Frodo'})]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should accept the noncompacted identity with partial author attribution', -> delta = new Delta(10, 10, [new RetainOp(0, 5), new RetainOp(5, 10, {authorId: 'Frodo'})]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should accept the noncompacted identity with partial author attribution', -> delta = new Delta(10, 10, [new RetainOp(0, 5, {authorId: 'Frodo'}), new RetainOp(5, 10)]) console.assert(delta.isIdentity() == true, "Expected delta #{delta.toString()} to be the identity, but delta.isIdentity() says its not") ) it('should reject the complete retain of a document if it contains non-author attr', -> delta = new Delta(10, 10, [new RetainOp(0, 10, {bold: true})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} not to be the identity, but delta.isIdentity() says it is") ) it('should reject the complete retain of a document if it contains non-author attr', -> delta = new Delta(10, 10, [new RetainOp(0, 5, {bold: true}), new RetainOp(5, 10, {authorId: 'Frodo'})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} to not be the identity, but delta.isIdentity() says it is") ) it('should reject the complete retain of a document if it contains non-author attr', -> delta = new Delta(10, 10, [new RetainOp(0, 5, {bold: true}), new RetainOp(5, 10, {bold: null})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} to not be the identity, but delta.isIdentity() says it is") ) it('should reject the complete retain of a document if it contains non-author attr', -> delta = new Delta(10, 10, [new RetainOp(0, 5), new RetainOp(5, 10, {bold: true})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} not to be the identity, but delta.isIdentity() says it is") ) it('should reject the complete retain of a document if it contains non-author attr', -> delta = new Delta(10, 10, [new RetainOp(0, 10, {authorId: 'Gandalf', bold: true})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} not to be the identity, but delta.isIdentity() says it is") ) it('should reject any delta containing an InsertOp', -> delta = new Delta(10, 10, [new RetainOp(0, 4), new InsertOp("a"), new RetainOp(5, 10, {authorId: 'Frodo'})]) console.assert(delta.isIdentity() == false, "Expected delta #{delta.toString()} to not be the identity, but delta.isIdentity() says it is") ) )
[ { "context": "name = \"Joseph\"\nif name.length > 1 \n console.log \"Hello, #{name", "end": 14, "score": 0.9998114705085754, "start": 8, "tag": "NAME", "value": "Joseph" } ]
ch04/04-coffee/indent.coffee
gogosub77/node-webscraping
0
name = "Joseph" if name.length > 1 console.log "Hello, #{name}!" else console.log "empty name"
55104
name = "<NAME>" if name.length > 1 console.log "Hello, #{name}!" else console.log "empty name"
true
name = "PI:NAME:<NAME>END_PI" if name.length > 1 console.log "Hello, #{name}!" else console.log "empty name"
[ { "context": "e, version, worker) ->\n @tasks.push\n name: name\n version: version\n worker: worker\n\nmodu", "end": 3211, "score": 0.8930861949920654, "start": 3207, "tag": "NAME", "value": "name" } ]
index.coffee
RootPanel/Mallard
1
semver = require 'semver' async = require 'async' fs = require 'fs' _ = require 'underscore' logger = -> args = _.toArray arguments args.unshift '[Assort]' console.log.apply @, args versionFromFile = (filename = '.version', name = 'version') -> return { name: name readVersion: (callback) -> fs.exists filename, (exists) -> if exists fs.readFile filename, (err, body) -> if err callback err else callback err, JSON.parse(body.toString())[name] else callback null, null saveVersion: (version, callback) -> writeVersion = (config) -> config ?= {} config[name] = version fs.writeFile filename, JSON.stringify(config), callback fs.exists filename, (exists) -> if exists fs.readFile filename, (err, body) -> if err callback err else writeVersion JSON.parse body.toString() else writeVersion() } versionFromMongoDB = (uri, collection = '_version', name = 'version') -> {MongoClient} = require 'mongodb' return { name: name readVersion: (callback) -> MongoClient.connect uri, (err, db) -> return callback err if err db.collection(collection).findOne name: name , (err, doc) -> if err callback err else if doc callback err, doc?.version else callback err, null saveVersion: (version, callback) -> MongoClient.connect uri, (err, db) -> return callback err if err db.collection(collection).update name: name , $set: version: version , upsert: true , (err, doc) -> if err callback err else if doc callback err, doc?[name] else callback err, null } class Assort tasks: [] # storage: readVersion(callback(err)), saveVersion(version, callback(err)) constructor: (storage) -> _.extend @, storage: storage # callback(err) migrate: (latest_version, resource, callback) -> {storage, tasks} = @ unless latest_version return callback 'missing latest_version' logger "start migrate: #{storage.name}, latest_version: #{latest_version}" storage.readVersion (err, current_version) -> return callback err if err logger "read version, current_version: #{current_version}" async.eachSeries tasks, (task, callback) -> if current_version and task.version and !semver.satisfies(current_version, task.version) logger "skip task #{task.name}(#{task.version})" return callback() logger "run task #{task.name}(#{task.version}) ..." task.worker resource, callback , (err) -> if err logger 'migrate error', err callback err else logger "save version, current_version: #{latest_version}" storage.saveVersion latest_version, callback # worker(resource, callback(err)) task: (name, version, worker) -> @tasks.push name: name version: version worker: worker module.exports = _.extend Assort, fromFile: versionFromFile fromMongoDB: versionFromMongoDB
152646
semver = require 'semver' async = require 'async' fs = require 'fs' _ = require 'underscore' logger = -> args = _.toArray arguments args.unshift '[Assort]' console.log.apply @, args versionFromFile = (filename = '.version', name = 'version') -> return { name: name readVersion: (callback) -> fs.exists filename, (exists) -> if exists fs.readFile filename, (err, body) -> if err callback err else callback err, JSON.parse(body.toString())[name] else callback null, null saveVersion: (version, callback) -> writeVersion = (config) -> config ?= {} config[name] = version fs.writeFile filename, JSON.stringify(config), callback fs.exists filename, (exists) -> if exists fs.readFile filename, (err, body) -> if err callback err else writeVersion JSON.parse body.toString() else writeVersion() } versionFromMongoDB = (uri, collection = '_version', name = 'version') -> {MongoClient} = require 'mongodb' return { name: name readVersion: (callback) -> MongoClient.connect uri, (err, db) -> return callback err if err db.collection(collection).findOne name: name , (err, doc) -> if err callback err else if doc callback err, doc?.version else callback err, null saveVersion: (version, callback) -> MongoClient.connect uri, (err, db) -> return callback err if err db.collection(collection).update name: name , $set: version: version , upsert: true , (err, doc) -> if err callback err else if doc callback err, doc?[name] else callback err, null } class Assort tasks: [] # storage: readVersion(callback(err)), saveVersion(version, callback(err)) constructor: (storage) -> _.extend @, storage: storage # callback(err) migrate: (latest_version, resource, callback) -> {storage, tasks} = @ unless latest_version return callback 'missing latest_version' logger "start migrate: #{storage.name}, latest_version: #{latest_version}" storage.readVersion (err, current_version) -> return callback err if err logger "read version, current_version: #{current_version}" async.eachSeries tasks, (task, callback) -> if current_version and task.version and !semver.satisfies(current_version, task.version) logger "skip task #{task.name}(#{task.version})" return callback() logger "run task #{task.name}(#{task.version}) ..." task.worker resource, callback , (err) -> if err logger 'migrate error', err callback err else logger "save version, current_version: #{latest_version}" storage.saveVersion latest_version, callback # worker(resource, callback(err)) task: (name, version, worker) -> @tasks.push name: <NAME> version: version worker: worker module.exports = _.extend Assort, fromFile: versionFromFile fromMongoDB: versionFromMongoDB
true
semver = require 'semver' async = require 'async' fs = require 'fs' _ = require 'underscore' logger = -> args = _.toArray arguments args.unshift '[Assort]' console.log.apply @, args versionFromFile = (filename = '.version', name = 'version') -> return { name: name readVersion: (callback) -> fs.exists filename, (exists) -> if exists fs.readFile filename, (err, body) -> if err callback err else callback err, JSON.parse(body.toString())[name] else callback null, null saveVersion: (version, callback) -> writeVersion = (config) -> config ?= {} config[name] = version fs.writeFile filename, JSON.stringify(config), callback fs.exists filename, (exists) -> if exists fs.readFile filename, (err, body) -> if err callback err else writeVersion JSON.parse body.toString() else writeVersion() } versionFromMongoDB = (uri, collection = '_version', name = 'version') -> {MongoClient} = require 'mongodb' return { name: name readVersion: (callback) -> MongoClient.connect uri, (err, db) -> return callback err if err db.collection(collection).findOne name: name , (err, doc) -> if err callback err else if doc callback err, doc?.version else callback err, null saveVersion: (version, callback) -> MongoClient.connect uri, (err, db) -> return callback err if err db.collection(collection).update name: name , $set: version: version , upsert: true , (err, doc) -> if err callback err else if doc callback err, doc?[name] else callback err, null } class Assort tasks: [] # storage: readVersion(callback(err)), saveVersion(version, callback(err)) constructor: (storage) -> _.extend @, storage: storage # callback(err) migrate: (latest_version, resource, callback) -> {storage, tasks} = @ unless latest_version return callback 'missing latest_version' logger "start migrate: #{storage.name}, latest_version: #{latest_version}" storage.readVersion (err, current_version) -> return callback err if err logger "read version, current_version: #{current_version}" async.eachSeries tasks, (task, callback) -> if current_version and task.version and !semver.satisfies(current_version, task.version) logger "skip task #{task.name}(#{task.version})" return callback() logger "run task #{task.name}(#{task.version}) ..." task.worker resource, callback , (err) -> if err logger 'migrate error', err callback err else logger "save version, current_version: #{latest_version}" storage.saveVersion latest_version, callback # worker(resource, callback(err)) task: (name, version, worker) -> @tasks.push name: PI:NAME:<NAME>END_PI version: version worker: worker module.exports = _.extend Assort, fromFile: versionFromFile fromMongoDB: versionFromMongoDB
[ { "context": "e.js\", ->\n js.should.include \"(c) 2009-2012 Jeremy Ashkenas\"\n \n describe \"dont include jQuery\", ->\n ", "end": 1144, "score": 0.999893844127655, "start": 1129, "tag": "NAME", "value": "Jeremy Ashkenas" } ]
test/build.test.coffee
stratuseditor/fractus
1
should = require 'should' bundle = require 'stratus-bundle' bundle.testDir() build = require '../src/build' buildFractus = -> return build(langs: ["Ruby"], theme: "Idlefingers") describe "build", -> describe "()", -> it "sets a default theme", -> build(langs: ["Ruby"]).theme.should.eql "Idlefingers" it "includes extended languages", -> build(langs: ["Ruby.Rails.Model"]).langs.should.include "Ruby" #it "includes required languages", -> # build(langs: ["HTML"]).langs.should.include "CSS" describe "#js", -> describe "without a file", -> js = buildFractus().js() it "is a string", -> js.should.be.a "string" js.should.include "fractus" it "includes the given bundles", -> js.should.include "Ruby" js.should.include "sentientwaffle" it "does not include other bundles", -> js.should.not.include "Ruby.Rails" it "includes jQuery", -> js.should.include "jquery.org/license" it "includes Underscore.js", -> js.should.include "(c) 2009-2012 Jeremy Ashkenas" describe "dont include jQuery", -> fractus = build langs: ["Ruby"] jquery: false it "excludes jQuery", -> fractus.js().should.not.include "jquery.org/license" describe "#css", -> describe "without a file", -> css = null before (done) -> buildFractus().css (err, _css) -> throw err if err css = _css done() it "is a string", -> css.should.be.a "string" it "includes the Fractus css", -> css.should.include ".fractus" it "includes the theme", -> css.should.include ".hi-keyword"
212017
should = require 'should' bundle = require 'stratus-bundle' bundle.testDir() build = require '../src/build' buildFractus = -> return build(langs: ["Ruby"], theme: "Idlefingers") describe "build", -> describe "()", -> it "sets a default theme", -> build(langs: ["Ruby"]).theme.should.eql "Idlefingers" it "includes extended languages", -> build(langs: ["Ruby.Rails.Model"]).langs.should.include "Ruby" #it "includes required languages", -> # build(langs: ["HTML"]).langs.should.include "CSS" describe "#js", -> describe "without a file", -> js = buildFractus().js() it "is a string", -> js.should.be.a "string" js.should.include "fractus" it "includes the given bundles", -> js.should.include "Ruby" js.should.include "sentientwaffle" it "does not include other bundles", -> js.should.not.include "Ruby.Rails" it "includes jQuery", -> js.should.include "jquery.org/license" it "includes Underscore.js", -> js.should.include "(c) 2009-2012 <NAME>" describe "dont include jQuery", -> fractus = build langs: ["Ruby"] jquery: false it "excludes jQuery", -> fractus.js().should.not.include "jquery.org/license" describe "#css", -> describe "without a file", -> css = null before (done) -> buildFractus().css (err, _css) -> throw err if err css = _css done() it "is a string", -> css.should.be.a "string" it "includes the Fractus css", -> css.should.include ".fractus" it "includes the theme", -> css.should.include ".hi-keyword"
true
should = require 'should' bundle = require 'stratus-bundle' bundle.testDir() build = require '../src/build' buildFractus = -> return build(langs: ["Ruby"], theme: "Idlefingers") describe "build", -> describe "()", -> it "sets a default theme", -> build(langs: ["Ruby"]).theme.should.eql "Idlefingers" it "includes extended languages", -> build(langs: ["Ruby.Rails.Model"]).langs.should.include "Ruby" #it "includes required languages", -> # build(langs: ["HTML"]).langs.should.include "CSS" describe "#js", -> describe "without a file", -> js = buildFractus().js() it "is a string", -> js.should.be.a "string" js.should.include "fractus" it "includes the given bundles", -> js.should.include "Ruby" js.should.include "sentientwaffle" it "does not include other bundles", -> js.should.not.include "Ruby.Rails" it "includes jQuery", -> js.should.include "jquery.org/license" it "includes Underscore.js", -> js.should.include "(c) 2009-2012 PI:NAME:<NAME>END_PI" describe "dont include jQuery", -> fractus = build langs: ["Ruby"] jquery: false it "excludes jQuery", -> fractus.js().should.not.include "jquery.org/license" describe "#css", -> describe "without a file", -> css = null before (done) -> buildFractus().css (err, _css) -> throw err if err css = _css done() it "is a string", -> css.should.be.a "string" it "includes the Fractus css", -> css.should.include ".fractus" it "includes the theme", -> css.should.include ".hi-keyword"
[ { "context": "e'\n\n###\nPackage documentation: https://github.com/mysqljs/mysql\n###\n\nPool = mysql.createPool(\n connectionL", "end": 119, "score": 0.9994539022445679, "start": 112, "tag": "USERNAME", "value": "mysqljs" }, { "context": "mysql.server\n user: config.mysql.user\n ...
src/services/database.coffee
underc0de/korex-server
0
mysql = require 'mysql' config = require '../../config/database' ### Package documentation: https://github.com/mysqljs/mysql ### Pool = mysql.createPool( connectionLimit: 10 host: config.mysql.server user: config.mysql.user password: config.mysql.password database: config.mysql.database ) module.exports = # Ping database initialize: (cb) -> Pool.getConnection (err) -> cb err # Query execution exec: (sql, values) -> new Promise((resolve, reject) -> Pool.getConnection (err, connection) -> reject(err) if err values = values || [] connection.query(sql, values, (err, rows) -> connection.release() if err then reject(err) else resolve(rows) ) )
119988
mysql = require 'mysql' config = require '../../config/database' ### Package documentation: https://github.com/mysqljs/mysql ### Pool = mysql.createPool( connectionLimit: 10 host: config.mysql.server user: config.mysql.user password: <PASSWORD> database: config.mysql.database ) module.exports = # Ping database initialize: (cb) -> Pool.getConnection (err) -> cb err # Query execution exec: (sql, values) -> new Promise((resolve, reject) -> Pool.getConnection (err, connection) -> reject(err) if err values = values || [] connection.query(sql, values, (err, rows) -> connection.release() if err then reject(err) else resolve(rows) ) )
true
mysql = require 'mysql' config = require '../../config/database' ### Package documentation: https://github.com/mysqljs/mysql ### Pool = mysql.createPool( connectionLimit: 10 host: config.mysql.server user: config.mysql.user password: PI:PASSWORD:<PASSWORD>END_PI database: config.mysql.database ) module.exports = # Ping database initialize: (cb) -> Pool.getConnection (err) -> cb err # Query execution exec: (sql, values) -> new Promise((resolve, reject) -> Pool.getConnection (err, connection) -> reject(err) if err values = values || [] connection.query(sql, values, (err, rows) -> connection.release() if err then reject(err) else resolve(rows) ) )
[ { "context": " person:\n job:\n name: \"Singer\"\n\n # Act\n result = _.flattenObj(obj)\n\n ", "end": 8600, "score": 0.9998058676719666, "start": 8594, "tag": "NAME", "value": "Singer" }, { "context": " expect(result[\"person.job.name\"]).to....
spec/underscore/underscore-extensions.spec.coffee
vtex/front.utils
6
expect = chai.expect describe 'Underscore extensions', -> describe 'formatCurrency', -> it 'should return the value string with 2 decimals', -> # Assert expect(_.formatCurrency(123)).to.equal('123,00') expect(_.formatCurrency(123.45)).to.equal('123,45') expect(_.formatCurrency(123.451)).to.equal('123,45') expect(_.formatCurrency(-123)).to.equal('-123,00') it 'should return the absolute value when options.absolute is true', -> # Assert expect(_.formatCurrency(-123, absolute: true)).to.equal('123,00') describe '_getCurrency', -> it 'should default to R$ when vtex.i18n is undefined', -> # Arrange window.vtex = undefined # Assert expect(_._getCurrency()).to.equal('R$ ') describe '_getDecimalSeparator', -> it 'should default to . when vtex.i18n is undefined', -> # Arrange window.vtex = undefined # Assert expect(_._getDecimalSeparator()).to.equal(',') describe '_getThousandsSeparator', -> it 'should default to , when vtex.i18n is undefined', -> # Arrange window.vtex = undefined # Assert expect(_._getThousandsSeparator()).to.equal('.') describe '_getDecimalDigits', -> it 'should default to 2 when vtex.i18n is undefined', -> # Arrange window.vtex = undefined # Assert expect(_._getDecimalDigits()).to.equal(2) describe 'pad', -> it 'should not modify strings larger than max', -> # Assert expect(_.pad('123', 2)).to.equal('123') expect(_.pad('abc', 2)).to.equal('abc') it 'should not modify strings that are the same size as max', -> # Assert expect(_.pad('123', 3)).to.equal('123') expect(_.pad('abc', 3)).to.equal('abc') it 'should pad strings with zeroes', -> # Assert expect(_.pad('123', 4)).to.equal('0123') expect(_.pad('123', 5)).to.equal('00123') expect(_.pad('abc', 4)).to.equal('0abc') expect(_.pad('abc', 5)).to.equal('00abc') it 'should pad strings with the given char', -> # Arrange options = char: ' ' # Assert expect(_.pad('123', 4, options)).to.equal(' 123') it 'shoudl pad strings on the right', -> #Arrange options = position: 'right' #Assert expect(_.pad('123', 4, options)).to.equal('1230') describe 'readCookie', -> beforeEach -> # Arrange document.cookie = 'a=123' document.cookie = 'b=456;' it 'should return undefined for an invalid name', -> # Assert expect(_.readCookie('abc')).to.be.undefined it 'should return the corresponding value for a valid name', -> # Assert expect(_.readCookie('a')).to.equal('123') expect(_.readCookie('b')).to.equal('456') describe 'getCookieValue', -> beforeEach -> # Arrange @cook = 'a=b&c=d' it 'should return undefined for an invalid name', -> # Assert expect(_.getCookieValue(@cook, 'abc')).to.be.undefined it 'should return the corresponding value for a valid name', -> # Assert expect(_.getCookieValue(@cook, 'a')).to.equal('b') expect(_.getCookieValue(@cook, 'c')).to.equal('d') describe 'capitalizeWord', -> it 'should capitalize the first character', -> # Assert expect(_.capitalizeWord('hello')).to.equal('Hello') it 'should not trim', -> # Assert expect(_.capitalizeWord(' hello ')).to.equal(' hello ') it 'should not modify other characters', -> # Assert expect(_.capitalizeWord('WorlD!@#$%¨&*()')).to.equal('WorlD!@#$%¨&*()') describe 'capitalizeSentence', -> it 'should call capitalizeWord for every word', -> # Arrange sentence = 'The quick brown fox jumps over the lazy dog' sentenceExp = 'The Quick Brown Fox Jumps Over The Lazy Dog' # Act result = _.capitalizeSentence(sentence) # Assert expect(result).to.equal(sentenceExp) describe 'maskString', -> it 'should receive a raw Brazilian postal code value, a mask and return a masked value', -> # Arrange raw = '22030030' mask = '99999-999' masked = '22030-030' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a raw Brazilian document value, a mask and return a masked value', -> # Arrange raw = '12345678909' mask = '999.999.999-99' masked = '123.456.789-09' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a masked value, a mask and return the same masked value', -> # Arrange raw = '123.456.789-09' mask = '999.999.999-99' masked = '123.456.789-09' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a raw value, a mask smaller than the raw value, and return the masked value preserving the remaining value', -> # Arrange raw = '1234567890912' mask = '999.999.999-99' masked = '123.456.789-0912' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a raw value smaller than the mask, a mask, and return a masked value', -> # Arrange raw = '123456789' mask = '999.999.999-99' masked = '123.456.789' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a half-masked raw value, a mask, and return a masked value', -> # Arrange raw = '4444 33332' mask = '9999 9999 9999 9999' masked = '4444 3333 2' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a numeric raw value not matching mask and return raw value', -> # Arrange raw = '12345' mask = 'AAA-AA' masked = '12345' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a all-letters raw value, a mask and return masked value', -> # Arrange raw = 'ABCDE' mask = 'AAA-AA' masked = 'ABC-DE' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a all-letters raw value not matching mask and return raw value', -> # Arrange raw = 'ABCDE' mask = '999-99' masked = 'ABCDE' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a mixed raw value not matching mask and return raw value', -> # Arrange raw = '1232ABB' mask = '999-AA-99' masked = '1232ABB' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a mixed raw value, a matching mask and return masked value', -> # Arrange raw = '123rj28' mask = '999-AA-99' masked = '123-rj-28' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a mixed raw value with punctuation, a matching mask and return masked value', -> # Arrange raw = '123äéöã28' mask = '999-AAAA-99' masked = '123-äéöã-28' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should ignore mask characters outside of 9 or A', -> # Arrange raw = 'bana99' mask = '123-ABC' masked = 'ban-a99' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should respect user fixedChar parameter', -> # Arrange raw = 'banana' fixedChars = 'X' mask = 'AAAXAAA' masked = 'banXana' # Assert expect(_.maskString(raw,mask,fixedChars)).to.equal(masked) describe 'maskInfo', -> it 'should substitute * for some html', -> # Arrange html = '<span class="masked-info">*</span>' # Assert expect(_.maskInfo('***aaa**a')).to.equal(html+html+html+'aaa'+html+html+'a') describe 'plainChars', -> it 'should planify characters', -> # Assert expect(_.plainChars('ąàáäâãåæćęèéëêìíïîłńòóöôõøśùúüûñçżź')).to.equal('aaaaaaaaceeeeeiiiilnoooooosuuuunczz') it 'should planify even if the characters are repeated', -> # Assert expect(_.plainChars('ąąąąą')).to.equal('aaaaa') it 'should not modify other characters', -> # Assert expect(_.plainChars('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%¨&*()')).to.equal('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%¨&*()') describe 'mapObj', -> it '', -> describe 'flattenObj', -> it 'should flatten an object', -> # Arrange obj = person: job: name: "Singer" # Act result = _.flattenObj(obj) # Assert expect(result["person.job.name"]).to.equal("Singer") describe 'unFlattenObj', -> it 'should unflatten an object', -> # Arrange obj = "person.job.name": "Singer" # Act result = _.unFlattenObj(obj) # Assert expect(result.person.job.name).to.equal("Singer") describe 'padStr', -> it 'should pad left', -> # Arrange number = 1 limit = 2 padding = '00' # Act result = _.padStr(number, limit, padding) # Assert expect(result).to.equal('01') describe 'dateFormat', -> it 'should format', -> # Arrange date = '2014/01/23' # Act result = _.dateFormat(date) # Assert expect(result).to.equal('23/01/2014') describe 'dateFormatUS', -> it 'should format as american date', -> # Arrange date = '2014/01/23' # Act result = _.dateFormatUS(date) # Assert expect(result).to.equal('1/23/2014')
144994
expect = chai.expect describe 'Underscore extensions', -> describe 'formatCurrency', -> it 'should return the value string with 2 decimals', -> # Assert expect(_.formatCurrency(123)).to.equal('123,00') expect(_.formatCurrency(123.45)).to.equal('123,45') expect(_.formatCurrency(123.451)).to.equal('123,45') expect(_.formatCurrency(-123)).to.equal('-123,00') it 'should return the absolute value when options.absolute is true', -> # Assert expect(_.formatCurrency(-123, absolute: true)).to.equal('123,00') describe '_getCurrency', -> it 'should default to R$ when vtex.i18n is undefined', -> # Arrange window.vtex = undefined # Assert expect(_._getCurrency()).to.equal('R$ ') describe '_getDecimalSeparator', -> it 'should default to . when vtex.i18n is undefined', -> # Arrange window.vtex = undefined # Assert expect(_._getDecimalSeparator()).to.equal(',') describe '_getThousandsSeparator', -> it 'should default to , when vtex.i18n is undefined', -> # Arrange window.vtex = undefined # Assert expect(_._getThousandsSeparator()).to.equal('.') describe '_getDecimalDigits', -> it 'should default to 2 when vtex.i18n is undefined', -> # Arrange window.vtex = undefined # Assert expect(_._getDecimalDigits()).to.equal(2) describe 'pad', -> it 'should not modify strings larger than max', -> # Assert expect(_.pad('123', 2)).to.equal('123') expect(_.pad('abc', 2)).to.equal('abc') it 'should not modify strings that are the same size as max', -> # Assert expect(_.pad('123', 3)).to.equal('123') expect(_.pad('abc', 3)).to.equal('abc') it 'should pad strings with zeroes', -> # Assert expect(_.pad('123', 4)).to.equal('0123') expect(_.pad('123', 5)).to.equal('00123') expect(_.pad('abc', 4)).to.equal('0abc') expect(_.pad('abc', 5)).to.equal('00abc') it 'should pad strings with the given char', -> # Arrange options = char: ' ' # Assert expect(_.pad('123', 4, options)).to.equal(' 123') it 'shoudl pad strings on the right', -> #Arrange options = position: 'right' #Assert expect(_.pad('123', 4, options)).to.equal('1230') describe 'readCookie', -> beforeEach -> # Arrange document.cookie = 'a=123' document.cookie = 'b=456;' it 'should return undefined for an invalid name', -> # Assert expect(_.readCookie('abc')).to.be.undefined it 'should return the corresponding value for a valid name', -> # Assert expect(_.readCookie('a')).to.equal('123') expect(_.readCookie('b')).to.equal('456') describe 'getCookieValue', -> beforeEach -> # Arrange @cook = 'a=b&c=d' it 'should return undefined for an invalid name', -> # Assert expect(_.getCookieValue(@cook, 'abc')).to.be.undefined it 'should return the corresponding value for a valid name', -> # Assert expect(_.getCookieValue(@cook, 'a')).to.equal('b') expect(_.getCookieValue(@cook, 'c')).to.equal('d') describe 'capitalizeWord', -> it 'should capitalize the first character', -> # Assert expect(_.capitalizeWord('hello')).to.equal('Hello') it 'should not trim', -> # Assert expect(_.capitalizeWord(' hello ')).to.equal(' hello ') it 'should not modify other characters', -> # Assert expect(_.capitalizeWord('WorlD!@#$%¨&*()')).to.equal('WorlD!@#$%¨&*()') describe 'capitalizeSentence', -> it 'should call capitalizeWord for every word', -> # Arrange sentence = 'The quick brown fox jumps over the lazy dog' sentenceExp = 'The Quick Brown Fox Jumps Over The Lazy Dog' # Act result = _.capitalizeSentence(sentence) # Assert expect(result).to.equal(sentenceExp) describe 'maskString', -> it 'should receive a raw Brazilian postal code value, a mask and return a masked value', -> # Arrange raw = '22030030' mask = '99999-999' masked = '22030-030' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a raw Brazilian document value, a mask and return a masked value', -> # Arrange raw = '12345678909' mask = '999.999.999-99' masked = '123.456.789-09' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a masked value, a mask and return the same masked value', -> # Arrange raw = '123.456.789-09' mask = '999.999.999-99' masked = '123.456.789-09' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a raw value, a mask smaller than the raw value, and return the masked value preserving the remaining value', -> # Arrange raw = '1234567890912' mask = '999.999.999-99' masked = '123.456.789-0912' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a raw value smaller than the mask, a mask, and return a masked value', -> # Arrange raw = '123456789' mask = '999.999.999-99' masked = '123.456.789' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a half-masked raw value, a mask, and return a masked value', -> # Arrange raw = '4444 33332' mask = '9999 9999 9999 9999' masked = '4444 3333 2' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a numeric raw value not matching mask and return raw value', -> # Arrange raw = '12345' mask = 'AAA-AA' masked = '12345' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a all-letters raw value, a mask and return masked value', -> # Arrange raw = 'ABCDE' mask = 'AAA-AA' masked = 'ABC-DE' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a all-letters raw value not matching mask and return raw value', -> # Arrange raw = 'ABCDE' mask = '999-99' masked = 'ABCDE' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a mixed raw value not matching mask and return raw value', -> # Arrange raw = '1232ABB' mask = '999-AA-99' masked = '1232ABB' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a mixed raw value, a matching mask and return masked value', -> # Arrange raw = '123rj28' mask = '999-AA-99' masked = '123-rj-28' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a mixed raw value with punctuation, a matching mask and return masked value', -> # Arrange raw = '123äéöã28' mask = '999-AAAA-99' masked = '123-äéöã-28' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should ignore mask characters outside of 9 or A', -> # Arrange raw = 'bana99' mask = '123-ABC' masked = 'ban-a99' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should respect user fixedChar parameter', -> # Arrange raw = 'banana' fixedChars = 'X' mask = 'AAAXAAA' masked = 'banXana' # Assert expect(_.maskString(raw,mask,fixedChars)).to.equal(masked) describe 'maskInfo', -> it 'should substitute * for some html', -> # Arrange html = '<span class="masked-info">*</span>' # Assert expect(_.maskInfo('***aaa**a')).to.equal(html+html+html+'aaa'+html+html+'a') describe 'plainChars', -> it 'should planify characters', -> # Assert expect(_.plainChars('ąàáäâãåæćęèéëêìíïîłńòóöôõøśùúüûñçżź')).to.equal('aaaaaaaaceeeeeiiiilnoooooosuuuunczz') it 'should planify even if the characters are repeated', -> # Assert expect(_.plainChars('ąąąąą')).to.equal('aaaaa') it 'should not modify other characters', -> # Assert expect(_.plainChars('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%¨&*()')).to.equal('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%¨&*()') describe 'mapObj', -> it '', -> describe 'flattenObj', -> it 'should flatten an object', -> # Arrange obj = person: job: name: "<NAME>" # Act result = _.flattenObj(obj) # Assert expect(result["person.job.name"]).to.equal("<NAME>") describe 'unFlattenObj', -> it 'should unflatten an object', -> # Arrange obj = "person.job.name": "<NAME>" # Act result = _.unFlattenObj(obj) # Assert expect(result.person.job.name).to.equal("<NAME>") describe 'padStr', -> it 'should pad left', -> # Arrange number = 1 limit = 2 padding = '00' # Act result = _.padStr(number, limit, padding) # Assert expect(result).to.equal('01') describe 'dateFormat', -> it 'should format', -> # Arrange date = '2014/01/23' # Act result = _.dateFormat(date) # Assert expect(result).to.equal('23/01/2014') describe 'dateFormatUS', -> it 'should format as american date', -> # Arrange date = '2014/01/23' # Act result = _.dateFormatUS(date) # Assert expect(result).to.equal('1/23/2014')
true
expect = chai.expect describe 'Underscore extensions', -> describe 'formatCurrency', -> it 'should return the value string with 2 decimals', -> # Assert expect(_.formatCurrency(123)).to.equal('123,00') expect(_.formatCurrency(123.45)).to.equal('123,45') expect(_.formatCurrency(123.451)).to.equal('123,45') expect(_.formatCurrency(-123)).to.equal('-123,00') it 'should return the absolute value when options.absolute is true', -> # Assert expect(_.formatCurrency(-123, absolute: true)).to.equal('123,00') describe '_getCurrency', -> it 'should default to R$ when vtex.i18n is undefined', -> # Arrange window.vtex = undefined # Assert expect(_._getCurrency()).to.equal('R$ ') describe '_getDecimalSeparator', -> it 'should default to . when vtex.i18n is undefined', -> # Arrange window.vtex = undefined # Assert expect(_._getDecimalSeparator()).to.equal(',') describe '_getThousandsSeparator', -> it 'should default to , when vtex.i18n is undefined', -> # Arrange window.vtex = undefined # Assert expect(_._getThousandsSeparator()).to.equal('.') describe '_getDecimalDigits', -> it 'should default to 2 when vtex.i18n is undefined', -> # Arrange window.vtex = undefined # Assert expect(_._getDecimalDigits()).to.equal(2) describe 'pad', -> it 'should not modify strings larger than max', -> # Assert expect(_.pad('123', 2)).to.equal('123') expect(_.pad('abc', 2)).to.equal('abc') it 'should not modify strings that are the same size as max', -> # Assert expect(_.pad('123', 3)).to.equal('123') expect(_.pad('abc', 3)).to.equal('abc') it 'should pad strings with zeroes', -> # Assert expect(_.pad('123', 4)).to.equal('0123') expect(_.pad('123', 5)).to.equal('00123') expect(_.pad('abc', 4)).to.equal('0abc') expect(_.pad('abc', 5)).to.equal('00abc') it 'should pad strings with the given char', -> # Arrange options = char: ' ' # Assert expect(_.pad('123', 4, options)).to.equal(' 123') it 'shoudl pad strings on the right', -> #Arrange options = position: 'right' #Assert expect(_.pad('123', 4, options)).to.equal('1230') describe 'readCookie', -> beforeEach -> # Arrange document.cookie = 'a=123' document.cookie = 'b=456;' it 'should return undefined for an invalid name', -> # Assert expect(_.readCookie('abc')).to.be.undefined it 'should return the corresponding value for a valid name', -> # Assert expect(_.readCookie('a')).to.equal('123') expect(_.readCookie('b')).to.equal('456') describe 'getCookieValue', -> beforeEach -> # Arrange @cook = 'a=b&c=d' it 'should return undefined for an invalid name', -> # Assert expect(_.getCookieValue(@cook, 'abc')).to.be.undefined it 'should return the corresponding value for a valid name', -> # Assert expect(_.getCookieValue(@cook, 'a')).to.equal('b') expect(_.getCookieValue(@cook, 'c')).to.equal('d') describe 'capitalizeWord', -> it 'should capitalize the first character', -> # Assert expect(_.capitalizeWord('hello')).to.equal('Hello') it 'should not trim', -> # Assert expect(_.capitalizeWord(' hello ')).to.equal(' hello ') it 'should not modify other characters', -> # Assert expect(_.capitalizeWord('WorlD!@#$%¨&*()')).to.equal('WorlD!@#$%¨&*()') describe 'capitalizeSentence', -> it 'should call capitalizeWord for every word', -> # Arrange sentence = 'The quick brown fox jumps over the lazy dog' sentenceExp = 'The Quick Brown Fox Jumps Over The Lazy Dog' # Act result = _.capitalizeSentence(sentence) # Assert expect(result).to.equal(sentenceExp) describe 'maskString', -> it 'should receive a raw Brazilian postal code value, a mask and return a masked value', -> # Arrange raw = '22030030' mask = '99999-999' masked = '22030-030' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a raw Brazilian document value, a mask and return a masked value', -> # Arrange raw = '12345678909' mask = '999.999.999-99' masked = '123.456.789-09' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a masked value, a mask and return the same masked value', -> # Arrange raw = '123.456.789-09' mask = '999.999.999-99' masked = '123.456.789-09' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a raw value, a mask smaller than the raw value, and return the masked value preserving the remaining value', -> # Arrange raw = '1234567890912' mask = '999.999.999-99' masked = '123.456.789-0912' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a raw value smaller than the mask, a mask, and return a masked value', -> # Arrange raw = '123456789' mask = '999.999.999-99' masked = '123.456.789' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a half-masked raw value, a mask, and return a masked value', -> # Arrange raw = '4444 33332' mask = '9999 9999 9999 9999' masked = '4444 3333 2' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a numeric raw value not matching mask and return raw value', -> # Arrange raw = '12345' mask = 'AAA-AA' masked = '12345' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a all-letters raw value, a mask and return masked value', -> # Arrange raw = 'ABCDE' mask = 'AAA-AA' masked = 'ABC-DE' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a all-letters raw value not matching mask and return raw value', -> # Arrange raw = 'ABCDE' mask = '999-99' masked = 'ABCDE' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a mixed raw value not matching mask and return raw value', -> # Arrange raw = '1232ABB' mask = '999-AA-99' masked = '1232ABB' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a mixed raw value, a matching mask and return masked value', -> # Arrange raw = '123rj28' mask = '999-AA-99' masked = '123-rj-28' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should receive a mixed raw value with punctuation, a matching mask and return masked value', -> # Arrange raw = '123äéöã28' mask = '999-AAAA-99' masked = '123-äéöã-28' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should ignore mask characters outside of 9 or A', -> # Arrange raw = 'bana99' mask = '123-ABC' masked = 'ban-a99' # Assert expect(_.maskString(raw,mask)).to.equal(masked) it 'should respect user fixedChar parameter', -> # Arrange raw = 'banana' fixedChars = 'X' mask = 'AAAXAAA' masked = 'banXana' # Assert expect(_.maskString(raw,mask,fixedChars)).to.equal(masked) describe 'maskInfo', -> it 'should substitute * for some html', -> # Arrange html = '<span class="masked-info">*</span>' # Assert expect(_.maskInfo('***aaa**a')).to.equal(html+html+html+'aaa'+html+html+'a') describe 'plainChars', -> it 'should planify characters', -> # Assert expect(_.plainChars('ąàáäâãåæćęèéëêìíïîłńòóöôõøśùúüûñçżź')).to.equal('aaaaaaaaceeeeeiiiilnoooooosuuuunczz') it 'should planify even if the characters are repeated', -> # Assert expect(_.plainChars('ąąąąą')).to.equal('aaaaa') it 'should not modify other characters', -> # Assert expect(_.plainChars('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%¨&*()')).to.equal('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%¨&*()') describe 'mapObj', -> it '', -> describe 'flattenObj', -> it 'should flatten an object', -> # Arrange obj = person: job: name: "PI:NAME:<NAME>END_PI" # Act result = _.flattenObj(obj) # Assert expect(result["person.job.name"]).to.equal("PI:NAME:<NAME>END_PI") describe 'unFlattenObj', -> it 'should unflatten an object', -> # Arrange obj = "person.job.name": "PI:NAME:<NAME>END_PI" # Act result = _.unFlattenObj(obj) # Assert expect(result.person.job.name).to.equal("PI:NAME:<NAME>END_PI") describe 'padStr', -> it 'should pad left', -> # Arrange number = 1 limit = 2 padding = '00' # Act result = _.padStr(number, limit, padding) # Assert expect(result).to.equal('01') describe 'dateFormat', -> it 'should format', -> # Arrange date = '2014/01/23' # Act result = _.dateFormat(date) # Assert expect(result).to.equal('23/01/2014') describe 'dateFormatUS', -> it 'should format as american date', -> # Arrange date = '2014/01/23' # Act result = _.dateFormatUS(date) # Assert expect(result).to.equal('1/23/2014')
[ { "context": "ave properties', ->\n @wine = new Wine name: 'Test'\n @wine.get('name').should.equal 'Test'\n ", "end": 279, "score": 0.5606542229652405, "start": 275, "tag": "NAME", "value": "Test" }, { "context": " as properties', ->\n @wine = new Wine name: 'DOMAIN...
test/cases/model.coffee
arthur-xavier/diamond.js
0
# test/cases/model.coffee should = require 'should' Wine = require "#{dependencies}/models/wine" Region = require "#{dependencies}/models/region" describe 'Model', -> # describe 'properties', -> # it 'should have properties', -> @wine = new Wine name: 'Test' @wine.get('name').should.equal 'Test' it 'should have default properties', -> @wine.get('description').should.equal '' @wine.get('year').should.equal new Date().getFullYear() it 'should have computed properties', -> @region = new Region name: 'Bordeaux', country: 'France' @region.get('location').should.equal "Bordeaux, France" it 'should have custom methods', -> @region.toString().should.equal "Bordeaux, France" it 'should have other models as properties', -> @wine = new Wine name: 'DOMAINE DU BOUSCAT', region: @region @wine.get('region.location').should.equal "Bordeaux, France" it 'should allow relationships', -> @wine = new Wine name: 'DOMAINE DU BOUSCAT', region: { name: 'Bordeaux', country: 'France' } @wine.get('region.location').should.equal "Bordeaux, France" # describe 'validations', -> # it 'should validate for presence', -> new Wine().validate().region.should.equal true should.not.exist new Wine(region: new Region country: 'France').validate().country it 'should validate for RegExp patterns', -> new Wine(name: "1NV4L1D W1N3").validate().name.should.equal true should.not.exist new Wine(name: 'DOMAINE DU BOUSCAT').validate().name it 'should validate with functions', -> new Wine(year: 1995).validate().name.should.equal true should.not.exist new Wine().validate().year # describe 'storage', -> # it 'finds all', (done) -> Wine.all (err, wines) -> throw err if err wines[0].name.should.equal "CHATEAU DE SAINT COSME" wines[1].name.should.equal "LAN RIOJA CRIANZA" done() it 'counts', (done) -> Wine.count (err, count) -> throw err if err count.should.equal 2 done() it 'finds by query', (done) -> Wine.find year: 2009, (err, wines) -> throw err if err wines[0].name.should.equal "CHATEAU DE SAINT COSME" done() it 'finds by id', -> # works from assertion. Find by query works it 'saves', (done) -> rioja = new Region name: 'Rioja', country: 'Spain' new Wine({ name: "Dinastia Vivanco", year: "2008", region: rioja, description: "Whether enjoying a fine cigar or a nicotine patch, don't pass up a taste of this hearty Rioja, both smooth and robust.", }).save() Wine.find name: "DINASTIA VIVANCO", (err, wines) -> throw err if err wines[0].region.should.equal "Rioja, Spain" done() it 'updates', (done) -> Wine.update {region: "Rioja, Spain"}, {region: "Tuscany, Italy"}, (err) -> throw err if err Wine.find region: "Tuscany, Italy", (err, wines) -> throw err if err wines[0].name.should.equal "LAN RIOJA CRIANZA" wines[1].name.should.equal "DINASTIA VIVANCO" done() it 'removes', (done) -> Wine.remove {region: "Southern Rhone, France"}, (err) -> throw err if err Wine.all (err, wines) -> wines[0].name.should.equal "LAN RIOJA CRIANZA" wines[1].name.should.equal "DINASTIA VIVANCO" done() it 'fetches models', (done) -> verify = (wines) -> wine.region.country.should.equal "Italy" for wine in wines done() Wine.find region: "Tuscany, Italy", (err, wines) -> throw err if err wines.forEach (wine, i) -> Region.find location: wine.region, (err, regions) -> throw err if err wines[i].region = regions[0] verify wines if i == wines.length - 1
95735
# test/cases/model.coffee should = require 'should' Wine = require "#{dependencies}/models/wine" Region = require "#{dependencies}/models/region" describe 'Model', -> # describe 'properties', -> # it 'should have properties', -> @wine = new Wine name: '<NAME>' @wine.get('name').should.equal 'Test' it 'should have default properties', -> @wine.get('description').should.equal '' @wine.get('year').should.equal new Date().getFullYear() it 'should have computed properties', -> @region = new Region name: 'Bordeaux', country: 'France' @region.get('location').should.equal "Bordeaux, France" it 'should have custom methods', -> @region.toString().should.equal "Bordeaux, France" it 'should have other models as properties', -> @wine = new Wine name: '<NAME>', region: @region @wine.get('region.location').should.equal "Bordeaux, France" it 'should allow relationships', -> @wine = new Wine name: '<NAME> D<NAME>', region: { name: 'Bordeaux', country: 'France' } @wine.get('region.location').should.equal "Bordeaux, France" # describe 'validations', -> # it 'should validate for presence', -> new Wine().validate().region.should.equal true should.not.exist new Wine(region: new Region country: 'France').validate().country it 'should validate for RegExp patterns', -> new Wine(name: "1NV4L1D W1N3").validate().name.should.equal true should.not.exist new Wine(name: '<NAME>').validate().name it 'should validate with functions', -> new Wine(year: 1995).validate().name.should.equal true should.not.exist new Wine().validate().year # describe 'storage', -> # it 'finds all', (done) -> Wine.all (err, wines) -> throw err if err wines[0].name.should.equal "<NAME>" wines[1].name.should.equal "<NAME>" done() it 'counts', (done) -> Wine.count (err, count) -> throw err if err count.should.equal 2 done() it 'finds by query', (done) -> Wine.find year: 2009, (err, wines) -> throw err if err wines[0].name.should.equal "<NAME> S<NAME>" done() it 'finds by id', -> # works from assertion. Find by query works it 'saves', (done) -> rioja = new Region name: 'Rioja', country: 'Spain' new Wine({ name: "<NAME>", year: "2008", region: rioja, description: "Whether enjoying a fine cigar or a nicotine patch, don't pass up a taste of this hearty Rioja, both smooth and robust.", }).save() Wine.find name: "<NAME>", (err, wines) -> throw err if err wines[0].region.should.equal "Rioja, Spain" done() it 'updates', (done) -> Wine.update {region: "Rioja, Spain"}, {region: "Tuscany, Italy"}, (err) -> throw err if err Wine.find region: "Tuscany, Italy", (err, wines) -> throw err if err wines[0].name.should.equal "<NAME>" wines[1].name.should.equal "<NAME>" done() it 'removes', (done) -> Wine.remove {region: "Southern Rhone, France"}, (err) -> throw err if err Wine.all (err, wines) -> wines[0].name.should.equal "<NAME>" wines[1].name.should.equal "<NAME>" done() it 'fetches models', (done) -> verify = (wines) -> wine.region.country.should.equal "Italy" for wine in wines done() Wine.find region: "Tuscany, Italy", (err, wines) -> throw err if err wines.forEach (wine, i) -> Region.find location: wine.region, (err, regions) -> throw err if err wines[i].region = regions[0] verify wines if i == wines.length - 1
true
# test/cases/model.coffee should = require 'should' Wine = require "#{dependencies}/models/wine" Region = require "#{dependencies}/models/region" describe 'Model', -> # describe 'properties', -> # it 'should have properties', -> @wine = new Wine name: 'PI:NAME:<NAME>END_PI' @wine.get('name').should.equal 'Test' it 'should have default properties', -> @wine.get('description').should.equal '' @wine.get('year').should.equal new Date().getFullYear() it 'should have computed properties', -> @region = new Region name: 'Bordeaux', country: 'France' @region.get('location').should.equal "Bordeaux, France" it 'should have custom methods', -> @region.toString().should.equal "Bordeaux, France" it 'should have other models as properties', -> @wine = new Wine name: 'PI:NAME:<NAME>END_PI', region: @region @wine.get('region.location').should.equal "Bordeaux, France" it 'should allow relationships', -> @wine = new Wine name: 'PI:NAME:<NAME>END_PI DPI:NAME:<NAME>END_PI', region: { name: 'Bordeaux', country: 'France' } @wine.get('region.location').should.equal "Bordeaux, France" # describe 'validations', -> # it 'should validate for presence', -> new Wine().validate().region.should.equal true should.not.exist new Wine(region: new Region country: 'France').validate().country it 'should validate for RegExp patterns', -> new Wine(name: "1NV4L1D W1N3").validate().name.should.equal true should.not.exist new Wine(name: 'PI:NAME:<NAME>END_PI').validate().name it 'should validate with functions', -> new Wine(year: 1995).validate().name.should.equal true should.not.exist new Wine().validate().year # describe 'storage', -> # it 'finds all', (done) -> Wine.all (err, wines) -> throw err if err wines[0].name.should.equal "PI:NAME:<NAME>END_PI" wines[1].name.should.equal "PI:NAME:<NAME>END_PI" done() it 'counts', (done) -> Wine.count (err, count) -> throw err if err count.should.equal 2 done() it 'finds by query', (done) -> Wine.find year: 2009, (err, wines) -> throw err if err wines[0].name.should.equal "PI:NAME:<NAME>END_PI SPI:NAME:<NAME>END_PI" done() it 'finds by id', -> # works from assertion. Find by query works it 'saves', (done) -> rioja = new Region name: 'Rioja', country: 'Spain' new Wine({ name: "PI:NAME:<NAME>END_PI", year: "2008", region: rioja, description: "Whether enjoying a fine cigar or a nicotine patch, don't pass up a taste of this hearty Rioja, both smooth and robust.", }).save() Wine.find name: "PI:NAME:<NAME>END_PI", (err, wines) -> throw err if err wines[0].region.should.equal "Rioja, Spain" done() it 'updates', (done) -> Wine.update {region: "Rioja, Spain"}, {region: "Tuscany, Italy"}, (err) -> throw err if err Wine.find region: "Tuscany, Italy", (err, wines) -> throw err if err wines[0].name.should.equal "PI:NAME:<NAME>END_PI" wines[1].name.should.equal "PI:NAME:<NAME>END_PI" done() it 'removes', (done) -> Wine.remove {region: "Southern Rhone, France"}, (err) -> throw err if err Wine.all (err, wines) -> wines[0].name.should.equal "PI:NAME:<NAME>END_PI" wines[1].name.should.equal "PI:NAME:<NAME>END_PI" done() it 'fetches models', (done) -> verify = (wines) -> wine.region.country.should.equal "Italy" for wine in wines done() Wine.find region: "Tuscany, Italy", (err, wines) -> throw err if err wines.forEach (wine, i) -> Region.find location: wine.region, (err, regions) -> throw err if err wines[i].region = regions[0] verify wines if i == wines.length - 1
[ { "context": "# Copyright 2013 Andrey Antukh <niwi@niwi.be>\n#\n# Licensed under the Apache Lice", "end": 30, "score": 0.9998828172683716, "start": 17, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "# Copyright 2013 Andrey Antukh <niwi@niwi.be>\n#\n# Licensed under the Apac...
mrfogg-front/app/coffee/plugins/urls.coffee
PIWEEK/mrfogg
0
# Copyright 2013 Andrey Antukh <niwi@niwi.be> # # 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. format = (fmt, obj) -> obj = _.clone(obj) return fmt.replace /%s/g, (match) -> String(obj.shift()) UrlsProvider = -> data = { urls: {} host: {} scheme: {} } setHost = (ns, host, scheme) -> data.host[ns] = host data.scheme[ns] = scheme setUrls = (ns, urls) -> if _.toArray(arguments).length != 2 throw Error("wrong arguments to setUrls") data.urls[ns] = urls service[ns] = -> if _.toArray(arguments).length < 1 throw Error("wrong arguments") args = _.toArray(arguments) name = args.slice(0, 1)[0] url = format(data.urls[ns][name], args.slice(1)) if data.host[ns] return format("%s://%s%s", [data.scheme[ns], data.host[ns], url]) return url service = {} service.data = data service.setUrls = setUrls service.setHost = setHost @.setUrls = setUrls @.setHost = setHost @.$get = -> return service return module = angular.module("gmUrls", []) module.provider('$gmUrls', UrlsProvider)
17690
# Copyright 2013 <NAME> <<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. format = (fmt, obj) -> obj = _.clone(obj) return fmt.replace /%s/g, (match) -> String(obj.shift()) UrlsProvider = -> data = { urls: {} host: {} scheme: {} } setHost = (ns, host, scheme) -> data.host[ns] = host data.scheme[ns] = scheme setUrls = (ns, urls) -> if _.toArray(arguments).length != 2 throw Error("wrong arguments to setUrls") data.urls[ns] = urls service[ns] = -> if _.toArray(arguments).length < 1 throw Error("wrong arguments") args = _.toArray(arguments) name = args.slice(0, 1)[0] url = format(data.urls[ns][name], args.slice(1)) if data.host[ns] return format("%s://%s%s", [data.scheme[ns], data.host[ns], url]) return url service = {} service.data = data service.setUrls = setUrls service.setHost = setHost @.setUrls = setUrls @.setHost = setHost @.$get = -> return service return module = angular.module("gmUrls", []) module.provider('$gmUrls', UrlsProvider)
true
# Copyright 2013 PI:NAME:<NAME>END_PI <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. format = (fmt, obj) -> obj = _.clone(obj) return fmt.replace /%s/g, (match) -> String(obj.shift()) UrlsProvider = -> data = { urls: {} host: {} scheme: {} } setHost = (ns, host, scheme) -> data.host[ns] = host data.scheme[ns] = scheme setUrls = (ns, urls) -> if _.toArray(arguments).length != 2 throw Error("wrong arguments to setUrls") data.urls[ns] = urls service[ns] = -> if _.toArray(arguments).length < 1 throw Error("wrong arguments") args = _.toArray(arguments) name = args.slice(0, 1)[0] url = format(data.urls[ns][name], args.slice(1)) if data.host[ns] return format("%s://%s%s", [data.scheme[ns], data.host[ns], url]) return url service = {} service.data = data service.setUrls = setUrls service.setHost = setHost @.setUrls = setUrls @.setHost = setHost @.$get = -> return service return module = angular.module("gmUrls", []) module.provider('$gmUrls', UrlsProvider)
[ { "context": " '443'\n # Original non-wss relay:\n # host: '192.81.135.242'\n # port: 9902\n\n cookieName: \"snowflake-allow", "end": 185, "score": 0.9997716546058655, "start": 171, "tag": "IP_ADDRESS", "value": "192.81.135.242" } ]
proxy/config.coffee
NullHypothesis/snowflake
0
class Config brokerUrl: 'snowflake-broker.bamsoftware.com' relayAddr: host: 'snowflake.bamsoftware.com' port: '443' # Original non-wss relay: # host: '192.81.135.242' # port: 9902 cookieName: "snowflake-allow" # Bytes per second. Set to undefined to disable limit. rateLimitBytes: undefined minRateLimit: 10 * 1024 rateLimitHistory: 5.0 defaultBrokerPollInterval: 5.0 * 1000 maxNumClients: 1 connectionsPerClient: 1 # TODO: Different ICE servers. pcConfig = { iceServers: [ { urls: ['stun:stun.l.google.com:19302'] } ] }
189602
class Config brokerUrl: 'snowflake-broker.bamsoftware.com' relayAddr: host: 'snowflake.bamsoftware.com' port: '443' # Original non-wss relay: # host: '192.168.3.11' # port: 9902 cookieName: "snowflake-allow" # Bytes per second. Set to undefined to disable limit. rateLimitBytes: undefined minRateLimit: 10 * 1024 rateLimitHistory: 5.0 defaultBrokerPollInterval: 5.0 * 1000 maxNumClients: 1 connectionsPerClient: 1 # TODO: Different ICE servers. pcConfig = { iceServers: [ { urls: ['stun:stun.l.google.com:19302'] } ] }
true
class Config brokerUrl: 'snowflake-broker.bamsoftware.com' relayAddr: host: 'snowflake.bamsoftware.com' port: '443' # Original non-wss relay: # host: 'PI:IP_ADDRESS:192.168.3.11END_PI' # port: 9902 cookieName: "snowflake-allow" # Bytes per second. Set to undefined to disable limit. rateLimitBytes: undefined minRateLimit: 10 * 1024 rateLimitHistory: 5.0 defaultBrokerPollInterval: 5.0 * 1000 maxNumClients: 1 connectionsPerClient: 1 # TODO: Different ICE servers. pcConfig = { iceServers: [ { urls: ['stun:stun.l.google.com:19302'] } ] }
[ { "context": " \n# Copyright 2011 - 2013 Mark Masse (OSS project WRML.org) \n# ", "end": 824, "score": 0.9997768402099609, "start": 814, "tag": "NAME", "value": "Mark Masse" } ]
wrmldoc/js/app/config/marionette/application.coffee
wrml/wrml
47
# # WRML - Web Resource Modeling Language # __ __ ______ __ __ __ # /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \ # \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____ # \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\ # \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/ # # http://www.wrml.org # # Copyright 2011 - 2013 Mark Masse (OSS project WRML.org) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # CoffeeScript do (Backbone) -> _.extend Backbone.Marionette.Application::, navigate: (route, options = {}) -> # route = "#" + route if route.charAt(0) is "/" Backbone.history.navigate route, options getCurrentRoute: -> frag = Backbone.history.fragment if _.isEmpty(frag) then null else frag startHistory: -> if Backbone.history Backbone.history.start() register: (instance, id) -> @_registry ?= {} @_registry[id] = instance unregister: (instance, id) -> delete @_registry[id] resetRegistry: -> oldCount = @getRegistrySize() for key, controller of @_registry controller.region.close() msg = "There were #{oldCount} controllers in the registry, there are now #{@getRegistrySize()}" if @getRegistrySize() > 0 then console.warn(msg, @_registry) else console.log(msg) getRegistrySize: -> _.size @_registry
31923
# # WRML - Web Resource Modeling Language # __ __ ______ __ __ __ # /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \ # \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____ # \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\ # \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/ # # http://www.wrml.org # # Copyright 2011 - 2013 <NAME> (OSS project WRML.org) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # CoffeeScript do (Backbone) -> _.extend Backbone.Marionette.Application::, navigate: (route, options = {}) -> # route = "#" + route if route.charAt(0) is "/" Backbone.history.navigate route, options getCurrentRoute: -> frag = Backbone.history.fragment if _.isEmpty(frag) then null else frag startHistory: -> if Backbone.history Backbone.history.start() register: (instance, id) -> @_registry ?= {} @_registry[id] = instance unregister: (instance, id) -> delete @_registry[id] resetRegistry: -> oldCount = @getRegistrySize() for key, controller of @_registry controller.region.close() msg = "There were #{oldCount} controllers in the registry, there are now #{@getRegistrySize()}" if @getRegistrySize() > 0 then console.warn(msg, @_registry) else console.log(msg) getRegistrySize: -> _.size @_registry
true
# # WRML - Web Resource Modeling Language # __ __ ______ __ __ __ # /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \ # \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____ # \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\ # \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/ # # http://www.wrml.org # # Copyright 2011 - 2013 PI:NAME:<NAME>END_PI (OSS project WRML.org) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # CoffeeScript do (Backbone) -> _.extend Backbone.Marionette.Application::, navigate: (route, options = {}) -> # route = "#" + route if route.charAt(0) is "/" Backbone.history.navigate route, options getCurrentRoute: -> frag = Backbone.history.fragment if _.isEmpty(frag) then null else frag startHistory: -> if Backbone.history Backbone.history.start() register: (instance, id) -> @_registry ?= {} @_registry[id] = instance unregister: (instance, id) -> delete @_registry[id] resetRegistry: -> oldCount = @getRegistrySize() for key, controller of @_registry controller.region.close() msg = "There were #{oldCount} controllers in the registry, there are now #{@getRegistrySize()}" if @getRegistrySize() > 0 then console.warn(msg, @_registry) else console.log(msg) getRegistrySize: -> _.size @_registry
[ { "context": "###\n# grunt-svg2storeicons\n# https://github.com/pem--/grunt-svg2storeicons\n#\n# copyright (c) 2013 pierr", "end": 51, "score": 0.9258320331573486, "start": 48, "tag": "USERNAME", "value": "pem" }, { "context": "/pem--/grunt-svg2storeicons\n#\n# copyright (c) 2013 pie...
test/testDefaultOptions.coffee
gruntjs-updater/grunt-svg2storeicons
0
### # grunt-svg2storeicons # https://github.com/pem--/grunt-svg2storeicons # # copyright (c) 2013 pierre-eric marchandet (pem-- <pemarchandet@gmail.com>) # licensed under the mit licence. ### 'use strict' assert = require 'assert' fs = require 'fs' path = require 'path' EXPECTED_DEST = path.join 'tmp', 'default_options' PROFILES = (require '../lib/profiles') prjName: 'Test' EXPECTED_FILES = [] for key of PROFILES dir = PROFILES[key].dir for icon in PROFILES[key].icons EXPECTED_FILES.push path.join EXPECTED_DEST, dir, icon.name describe 'Default options', -> it 'should create all icons for each default profiles', -> for file in EXPECTED_FILES assert.equal true, (fs.statSync file).isFile()
174247
### # grunt-svg2storeicons # https://github.com/pem--/grunt-svg2storeicons # # copyright (c) 2013 <NAME> (pem-- <<EMAIL>>) # licensed under the mit licence. ### 'use strict' assert = require 'assert' fs = require 'fs' path = require 'path' EXPECTED_DEST = path.join 'tmp', 'default_options' PROFILES = (require '../lib/profiles') prjName: 'Test' EXPECTED_FILES = [] for key of PROFILES dir = PROFILES[key].dir for icon in PROFILES[key].icons EXPECTED_FILES.push path.join EXPECTED_DEST, dir, icon.name describe 'Default options', -> it 'should create all icons for each default profiles', -> for file in EXPECTED_FILES assert.equal true, (fs.statSync file).isFile()
true
### # grunt-svg2storeicons # https://github.com/pem--/grunt-svg2storeicons # # copyright (c) 2013 PI:NAME:<NAME>END_PI (pem-- <PI:EMAIL:<EMAIL>END_PI>) # licensed under the mit licence. ### 'use strict' assert = require 'assert' fs = require 'fs' path = require 'path' EXPECTED_DEST = path.join 'tmp', 'default_options' PROFILES = (require '../lib/profiles') prjName: 'Test' EXPECTED_FILES = [] for key of PROFILES dir = PROFILES[key].dir for icon in PROFILES[key].icons EXPECTED_FILES.push path.join EXPECTED_DEST, dir, icon.name describe 'Default options', -> it 'should create all icons for each default profiles', -> for file in EXPECTED_FILES assert.equal true, (fs.statSync file).isFile()
[ { "context": "name: 'Zelus'\nscopeName: 'source.zelus'\ntype: 'tree-sitter'\npa", "end": 12, "score": 0.765693724155426, "start": 7, "tag": "NAME", "value": "Zelus" } ]
grammars/tree-sitter-zelus.cson
ismailbennani/language-zelus
0
name: 'Zelus' scopeName: 'source.zelus' type: 'tree-sitter' parser: 'tree-sitter-zelus' fileTypes: ["zls", "zli"] comments: start: '(* ' end: ' *)' folds: [ { type: 'comment' } { start: {index: 0, type: '{'} end: {index: -1, type: '}'} } { start: {index: 0, type: '['} end: {index: -1, type: ']'} } { start: {index: 0, type: '('} end: {index: -1, type: ')'} } { type: 'if_expression', start: {type: '"then"'}, end: {type: 'else_expression'} } { type: 'else_expression', start: {type: '"else"'}, } { type: 'let_expression', start: {type: '"="'}, end: {type: '"in"'} } { type: 'reset_expression', start: {type: '"reset"'}, end: {type: '"every"'} } { type: 'automaton_expression', start: {type: '"automaton"'}, end: {type: '"init"'} } { type: 'match_expression', start: {type: '"with"'}, end: {type: '"end"'} } { type: 'present_expression', start: {type: '"->"'}, end: {type: ['"else"', '"end"']} } { type: 'forall_equation', } { type: 'automaton_equation', start: {index: 0, type: '"automaton"'}, end: {type: '"init"'} } { type: 'automaton_equation', start: {index: 0, type: '"automaton"'} } { type: 'match_equation', start: {index: 0, type: '"match"'} } { type: 'present_equation', start: {type: '"->"'}, end: {type: ['"else"', '"end"']} } { type: 'if_equation', } { type: 'else_equation', } { type: 'reset_equation', start: {index: 0, type: '"reset"'}, end: {type: '"every"'} } { type: [ 'eq_equation', 'der_equation', 'next_equation', 'init_equation', 'emit_equation', 'period_equation', 'last_equation', 'let_declaration' ], start: {type: '"="'} } { type: [ 'automaton_handler_equation', 'automaton_handler_expression', 'match_handler_equation', 'match_handler_expression', 'present_handler_equation', 'present_handler_expression', 'der_reset_handler' ], start: {type: '"->"'} } { type: [ 'do_done_block' 'block_equation', 'block_expression', 'block_optional_equation' ], start: {index: 0, type: '"do"'} } { type: 'fun_declaration', start: {type: ['"where"', '"="']}, } { type: 'val_declaration', start: {type: ['":"']}, } { start: {index: 0, type: ['"until"', '"unless"', '"else"']}, end: {type: ['"then"', '"continue"']} } { type: 'one_local', } { type: 'one_let', start: {type: '"="'}, end: {type: '"in"'} } ] scopes: 'ERROR': 'markup.underline.zelus' # debug tree-sitter-zelus 'comment': 'comment.block.zelus' 'integer': 'constant.numeric.zelus' 'float' : 'constant.numeric.zelus' 'string' : 'string.quoted.double.zelus' 'string > escape_sequence': 'constant.character.escape.zelus' 'char' : 'string.quoted.single.zelus' 'bool' : 'constant.language.boolean.zelus' 'kind': 'keyword.control.zelus' 'arrow': 'meta.arrow.zelus' 'constructor': 'meta.class.zelus' # 'entity.name.type.variant.zelus' 'type_var' : 'storage.type.zelus' 'identifier' : 'meta.identifier.zelus' 'fun_name' : 'entity.name.function.zelus' 'ty_name' : 'storage.type.zelus' 'label_expr' : 'meta.label_expr.zelus' 'present_expression' : 'meta.present_expression.zelus' 'match_expression' : 'meta.match_expression.zelus' 'automaton_expression' : 'meta.automaton_expression.zelus' 'reset_expression' : 'meta.reset_expression.zelus' 'every_expression' : 'meta.every_expression.zelus' 'let_expression' : 'meta.let_expression.zelus' 'else_expression' : 'meta.else_expression.zelus' 'if_expression' : 'meta.if_expression.zelus' 'application_expression' : 'meta.application_expression.zelus' 'update_expression' : 'meta.update_expression.zelus' 'record_access_expression' : 'meta.record_access_expression.zelus' 'tuple_expression' : 'meta.tuple_expression.zelus' 'slice_expression' : 'meta.slice_expression.zelus' 'concat_expression' : 'meta.concat_expression.zelus' 'access_expression' : 'meta.access_expression.zelus' 'do_in_expression' : 'meta.do_in_expression.zelus' 'period_expression' : 'meta.period_expression.zelus' 'last_expression' : 'meta.last_expression.zelus' 'reset_equation' : 'meta.reset_equation.zelus' 'present_equation' : 'meta.present_equation.zelus' 'else_equation' : 'meta.else_equation.zelus' 'if_equation' : 'meta.if_equation.zelus' 'match_equation' : 'meta.match_equation.zelus' 'automaton_equation' : 'meta.automaton_equation.zelus' 'forall_equation' : 'meta.forall_equation.zelus' 'forall_index' : 'meta.forall_index.zelus' 'eq_equation' : 'meta.eq_equation.zelus' 'period_equation' : 'meta.period_equation.zelus' 'der_equation' : 'meta.der_equation.zelus' 'next_equation' : 'meta.next_equation.zelus' 'init_equation' : 'meta.init_equation.zelus' 'emit_equation' : 'meta.emit_equation.zelus' 'last_equation' : 'meta.last_equation.zelus' 'do_done_block' : 'meta.do_done_block.zelus' 'block_equation' : 'meta.block_equation.zelus' 'block_expression' : 'meta.block_expression.zelus' 'block_optional_equation' : 'meta.block_optional_equation.zelus' 'automaton_handler_equation' : 'meta.automaton_handler_equation' 'automaton_handler_expression': 'meta.automaton_handler_expression' 'match_handler_equation' : 'meta.match_handler_equation' 'match_handler_expression' : 'meta.match_handler_expression' 'present_handler_equation' : 'meta.present_handler_equation' 'present_handler_expression' : 'meta.present_handler_expression' 'der_reset_handler' : 'meta.der_reset_handler' 'let_declaration' : 'meta.let_declaration.zelus' 'fun_declaration' : 'meta.fun_declaration.zelus' 'val_declaration' : 'meta.val_declaration.zelus' 'pattern': 'meta.pattern.zelus' 'one_local': 'meta.one_local.zelus' 'one_let' : 'meta.one_let.zelus' 'one_local > identifier' : 'entity.name.function.zelus' 'update_expression > identifier:nth-child(1)' : 'entity.name.function.zelus' 'last_expression > identifier:nth-child(1)' : 'entity.name.function.zelus' 'every_expression > identifier:nth-child(1)' : 'entity.name.function.zelus' 'if_expression > identifier:nth-child(1)' : 'entity.name.function.zelus' 'label_expr > identifier:nth-child(0)' : 'entity.name.function.zelus' 'der_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'init_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'emit_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'next_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'last_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'forall_index > identifier:nth-child(0)' : 'entity.name.function.zelus' 'match_expression > identifier:nth-child(1)' : 'entity.name.function.zelus' 'match_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'let_declaration > identifier:nth-child(1)' : 'entity.name.function.zelus' 'val_declaration > identifier:nth-child(1)' : 'entity.name.function.zelus' 'val_declaration > arrow' : 'entity.name.type.variant.zelus' 'present_handler_equation > identifier:nth-child(0)': 'entity.name.function.zelus' 'present_handler_expression > identifier:nth-child(0)': 'entity.name.function.zelus' 'record_access_expression > identifier:nth-child(0)': 'entity.name.variable.zelus' 'der_reset_handler > identifier:nth-child(0)': 'entity.name.function.zelus' # Ugly hack because atom do not support 'pattern identifier' selector, a # selector that should select any descendent of pattern of type identifier. # The only selector available for now is > which only goes down by 1 lvl # in the hierarchy. For now the tuples nested more than 4 times won't be # highlighted ''' eq_equation > pattern:nth-child(0) > identifier , eq_equation > pattern:nth-child(0) > pattern > identifier , eq_equation > pattern:nth-child(0) > pattern > pattern > identifier , eq_equation > pattern:nth-child(0) > pattern > pattern > pattern > identifier , eq_equation > pattern:nth-child(0) > pattern > pattern > pattern > pattern > identifier ''' : "entity.name.function.zelus" ''' match_handler_equation > pattern:nth-child(0) > identifier , match_handler_equation > pattern:nth-child(0) > pattern > identifier , match_handler_equation > pattern:nth-child(0) > pattern > pattern > identifier , match_handler_equation > pattern:nth-child(0) > pattern > pattern > pattern > identifier , match_handler_equation > pattern:nth-child(0) > pattern > pattern > pattern > pattern > identifier ''' : "entity.name.function.zelus" ''' match_handler_expression > pattern:nth-child(0) > identifier , match_handler_expression > pattern:nth-child(0) > pattern > identifier , match_handler_expression > pattern:nth-child(0) > pattern > pattern > identifier , match_handler_expression > pattern:nth-child(0) > pattern > pattern > pattern > identifier , match_handler_expression > pattern:nth-child(0) > pattern > pattern > pattern > pattern > identifier ''' : "entity.name.function.zelus" ''' period_equation > pattern:nth-child(1) > identifier , period_equation > pattern:nth-child(1) > pattern > identifier , period_equation > pattern:nth-child(1) > pattern > pattern > identifier , period_equation > pattern:nth-child(1) > pattern > pattern > pattern > identifier , period_equation > pattern:nth-child(1) > pattern > pattern > pattern > pattern > identifier ''' : "entity.name.function.zelus" # end of ugly hack 'prfx' : 'support.function.zelus' 'infx' : 'support.function.zelus' '"next"' : 'keyword.control.zelus' '"last"' : 'keyword.control.zelus' '"emit"' : 'keyword.control.zelus' '"up"' : 'keyword.control.zelus' '"open"' : 'keyword.control.zelus' '"type"' : 'keyword.control.zelus' '"val"' : 'keyword.control.zelus' '"let"' : 'keyword.control.zelus' '"rec"' : 'keyword.control.zelus' '"in"' : 'keyword.control.zelus' '"out"' : 'keyword.control.zelus' '"on"' : 'keyword.control.zelus' '"as"' : 'keyword.control.zelus' '"of"' : 'keyword.control.zelus' '"before"' : 'keyword.control.zelus' '"and"' : 'keyword.control.zelus' '"static"' : 'keyword.control.zelus' '"atomic"' : 'keyword.control.zelus' '"where"' : 'keyword.control.zelus' '"der"' : 'keyword.control.zelus' '"init"' : 'keyword.control.zelus' '"default"' : 'keyword.control.zelus' '"reset"' : 'keyword.control.zelus' '"every"' : 'keyword.control.zelus' '"present"' : 'keyword.control.zelus' '"period"' : 'keyword.control.zelus' '"local"' : 'keyword.control.zelus' '"do"' : 'keyword.control.zelus' '"done"' : 'keyword.control.zelus' '"forall"' : 'keyword.control.zelus' '"initialize"' : 'keyword.control.zelus' '"match"' : 'keyword.control.zelus' '"with"' : 'keyword.control.zelus' '"end"' : 'keyword.control.zelus' '"automaton"' : 'keyword.control.zelus' '"then"' : 'keyword.control.zelus' '"continue"' : 'keyword.control.zelus' '"until"' : 'keyword.control.zelus' '"unless"' : 'keyword.control.zelus' '"if"' : 'keyword.control.zelus' '"else"' : 'keyword.control.zelus'
148458
name: '<NAME>' scopeName: 'source.zelus' type: 'tree-sitter' parser: 'tree-sitter-zelus' fileTypes: ["zls", "zli"] comments: start: '(* ' end: ' *)' folds: [ { type: 'comment' } { start: {index: 0, type: '{'} end: {index: -1, type: '}'} } { start: {index: 0, type: '['} end: {index: -1, type: ']'} } { start: {index: 0, type: '('} end: {index: -1, type: ')'} } { type: 'if_expression', start: {type: '"then"'}, end: {type: 'else_expression'} } { type: 'else_expression', start: {type: '"else"'}, } { type: 'let_expression', start: {type: '"="'}, end: {type: '"in"'} } { type: 'reset_expression', start: {type: '"reset"'}, end: {type: '"every"'} } { type: 'automaton_expression', start: {type: '"automaton"'}, end: {type: '"init"'} } { type: 'match_expression', start: {type: '"with"'}, end: {type: '"end"'} } { type: 'present_expression', start: {type: '"->"'}, end: {type: ['"else"', '"end"']} } { type: 'forall_equation', } { type: 'automaton_equation', start: {index: 0, type: '"automaton"'}, end: {type: '"init"'} } { type: 'automaton_equation', start: {index: 0, type: '"automaton"'} } { type: 'match_equation', start: {index: 0, type: '"match"'} } { type: 'present_equation', start: {type: '"->"'}, end: {type: ['"else"', '"end"']} } { type: 'if_equation', } { type: 'else_equation', } { type: 'reset_equation', start: {index: 0, type: '"reset"'}, end: {type: '"every"'} } { type: [ 'eq_equation', 'der_equation', 'next_equation', 'init_equation', 'emit_equation', 'period_equation', 'last_equation', 'let_declaration' ], start: {type: '"="'} } { type: [ 'automaton_handler_equation', 'automaton_handler_expression', 'match_handler_equation', 'match_handler_expression', 'present_handler_equation', 'present_handler_expression', 'der_reset_handler' ], start: {type: '"->"'} } { type: [ 'do_done_block' 'block_equation', 'block_expression', 'block_optional_equation' ], start: {index: 0, type: '"do"'} } { type: 'fun_declaration', start: {type: ['"where"', '"="']}, } { type: 'val_declaration', start: {type: ['":"']}, } { start: {index: 0, type: ['"until"', '"unless"', '"else"']}, end: {type: ['"then"', '"continue"']} } { type: 'one_local', } { type: 'one_let', start: {type: '"="'}, end: {type: '"in"'} } ] scopes: 'ERROR': 'markup.underline.zelus' # debug tree-sitter-zelus 'comment': 'comment.block.zelus' 'integer': 'constant.numeric.zelus' 'float' : 'constant.numeric.zelus' 'string' : 'string.quoted.double.zelus' 'string > escape_sequence': 'constant.character.escape.zelus' 'char' : 'string.quoted.single.zelus' 'bool' : 'constant.language.boolean.zelus' 'kind': 'keyword.control.zelus' 'arrow': 'meta.arrow.zelus' 'constructor': 'meta.class.zelus' # 'entity.name.type.variant.zelus' 'type_var' : 'storage.type.zelus' 'identifier' : 'meta.identifier.zelus' 'fun_name' : 'entity.name.function.zelus' 'ty_name' : 'storage.type.zelus' 'label_expr' : 'meta.label_expr.zelus' 'present_expression' : 'meta.present_expression.zelus' 'match_expression' : 'meta.match_expression.zelus' 'automaton_expression' : 'meta.automaton_expression.zelus' 'reset_expression' : 'meta.reset_expression.zelus' 'every_expression' : 'meta.every_expression.zelus' 'let_expression' : 'meta.let_expression.zelus' 'else_expression' : 'meta.else_expression.zelus' 'if_expression' : 'meta.if_expression.zelus' 'application_expression' : 'meta.application_expression.zelus' 'update_expression' : 'meta.update_expression.zelus' 'record_access_expression' : 'meta.record_access_expression.zelus' 'tuple_expression' : 'meta.tuple_expression.zelus' 'slice_expression' : 'meta.slice_expression.zelus' 'concat_expression' : 'meta.concat_expression.zelus' 'access_expression' : 'meta.access_expression.zelus' 'do_in_expression' : 'meta.do_in_expression.zelus' 'period_expression' : 'meta.period_expression.zelus' 'last_expression' : 'meta.last_expression.zelus' 'reset_equation' : 'meta.reset_equation.zelus' 'present_equation' : 'meta.present_equation.zelus' 'else_equation' : 'meta.else_equation.zelus' 'if_equation' : 'meta.if_equation.zelus' 'match_equation' : 'meta.match_equation.zelus' 'automaton_equation' : 'meta.automaton_equation.zelus' 'forall_equation' : 'meta.forall_equation.zelus' 'forall_index' : 'meta.forall_index.zelus' 'eq_equation' : 'meta.eq_equation.zelus' 'period_equation' : 'meta.period_equation.zelus' 'der_equation' : 'meta.der_equation.zelus' 'next_equation' : 'meta.next_equation.zelus' 'init_equation' : 'meta.init_equation.zelus' 'emit_equation' : 'meta.emit_equation.zelus' 'last_equation' : 'meta.last_equation.zelus' 'do_done_block' : 'meta.do_done_block.zelus' 'block_equation' : 'meta.block_equation.zelus' 'block_expression' : 'meta.block_expression.zelus' 'block_optional_equation' : 'meta.block_optional_equation.zelus' 'automaton_handler_equation' : 'meta.automaton_handler_equation' 'automaton_handler_expression': 'meta.automaton_handler_expression' 'match_handler_equation' : 'meta.match_handler_equation' 'match_handler_expression' : 'meta.match_handler_expression' 'present_handler_equation' : 'meta.present_handler_equation' 'present_handler_expression' : 'meta.present_handler_expression' 'der_reset_handler' : 'meta.der_reset_handler' 'let_declaration' : 'meta.let_declaration.zelus' 'fun_declaration' : 'meta.fun_declaration.zelus' 'val_declaration' : 'meta.val_declaration.zelus' 'pattern': 'meta.pattern.zelus' 'one_local': 'meta.one_local.zelus' 'one_let' : 'meta.one_let.zelus' 'one_local > identifier' : 'entity.name.function.zelus' 'update_expression > identifier:nth-child(1)' : 'entity.name.function.zelus' 'last_expression > identifier:nth-child(1)' : 'entity.name.function.zelus' 'every_expression > identifier:nth-child(1)' : 'entity.name.function.zelus' 'if_expression > identifier:nth-child(1)' : 'entity.name.function.zelus' 'label_expr > identifier:nth-child(0)' : 'entity.name.function.zelus' 'der_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'init_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'emit_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'next_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'last_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'forall_index > identifier:nth-child(0)' : 'entity.name.function.zelus' 'match_expression > identifier:nth-child(1)' : 'entity.name.function.zelus' 'match_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'let_declaration > identifier:nth-child(1)' : 'entity.name.function.zelus' 'val_declaration > identifier:nth-child(1)' : 'entity.name.function.zelus' 'val_declaration > arrow' : 'entity.name.type.variant.zelus' 'present_handler_equation > identifier:nth-child(0)': 'entity.name.function.zelus' 'present_handler_expression > identifier:nth-child(0)': 'entity.name.function.zelus' 'record_access_expression > identifier:nth-child(0)': 'entity.name.variable.zelus' 'der_reset_handler > identifier:nth-child(0)': 'entity.name.function.zelus' # Ugly hack because atom do not support 'pattern identifier' selector, a # selector that should select any descendent of pattern of type identifier. # The only selector available for now is > which only goes down by 1 lvl # in the hierarchy. For now the tuples nested more than 4 times won't be # highlighted ''' eq_equation > pattern:nth-child(0) > identifier , eq_equation > pattern:nth-child(0) > pattern > identifier , eq_equation > pattern:nth-child(0) > pattern > pattern > identifier , eq_equation > pattern:nth-child(0) > pattern > pattern > pattern > identifier , eq_equation > pattern:nth-child(0) > pattern > pattern > pattern > pattern > identifier ''' : "entity.name.function.zelus" ''' match_handler_equation > pattern:nth-child(0) > identifier , match_handler_equation > pattern:nth-child(0) > pattern > identifier , match_handler_equation > pattern:nth-child(0) > pattern > pattern > identifier , match_handler_equation > pattern:nth-child(0) > pattern > pattern > pattern > identifier , match_handler_equation > pattern:nth-child(0) > pattern > pattern > pattern > pattern > identifier ''' : "entity.name.function.zelus" ''' match_handler_expression > pattern:nth-child(0) > identifier , match_handler_expression > pattern:nth-child(0) > pattern > identifier , match_handler_expression > pattern:nth-child(0) > pattern > pattern > identifier , match_handler_expression > pattern:nth-child(0) > pattern > pattern > pattern > identifier , match_handler_expression > pattern:nth-child(0) > pattern > pattern > pattern > pattern > identifier ''' : "entity.name.function.zelus" ''' period_equation > pattern:nth-child(1) > identifier , period_equation > pattern:nth-child(1) > pattern > identifier , period_equation > pattern:nth-child(1) > pattern > pattern > identifier , period_equation > pattern:nth-child(1) > pattern > pattern > pattern > identifier , period_equation > pattern:nth-child(1) > pattern > pattern > pattern > pattern > identifier ''' : "entity.name.function.zelus" # end of ugly hack 'prfx' : 'support.function.zelus' 'infx' : 'support.function.zelus' '"next"' : 'keyword.control.zelus' '"last"' : 'keyword.control.zelus' '"emit"' : 'keyword.control.zelus' '"up"' : 'keyword.control.zelus' '"open"' : 'keyword.control.zelus' '"type"' : 'keyword.control.zelus' '"val"' : 'keyword.control.zelus' '"let"' : 'keyword.control.zelus' '"rec"' : 'keyword.control.zelus' '"in"' : 'keyword.control.zelus' '"out"' : 'keyword.control.zelus' '"on"' : 'keyword.control.zelus' '"as"' : 'keyword.control.zelus' '"of"' : 'keyword.control.zelus' '"before"' : 'keyword.control.zelus' '"and"' : 'keyword.control.zelus' '"static"' : 'keyword.control.zelus' '"atomic"' : 'keyword.control.zelus' '"where"' : 'keyword.control.zelus' '"der"' : 'keyword.control.zelus' '"init"' : 'keyword.control.zelus' '"default"' : 'keyword.control.zelus' '"reset"' : 'keyword.control.zelus' '"every"' : 'keyword.control.zelus' '"present"' : 'keyword.control.zelus' '"period"' : 'keyword.control.zelus' '"local"' : 'keyword.control.zelus' '"do"' : 'keyword.control.zelus' '"done"' : 'keyword.control.zelus' '"forall"' : 'keyword.control.zelus' '"initialize"' : 'keyword.control.zelus' '"match"' : 'keyword.control.zelus' '"with"' : 'keyword.control.zelus' '"end"' : 'keyword.control.zelus' '"automaton"' : 'keyword.control.zelus' '"then"' : 'keyword.control.zelus' '"continue"' : 'keyword.control.zelus' '"until"' : 'keyword.control.zelus' '"unless"' : 'keyword.control.zelus' '"if"' : 'keyword.control.zelus' '"else"' : 'keyword.control.zelus'
true
name: 'PI:NAME:<NAME>END_PI' scopeName: 'source.zelus' type: 'tree-sitter' parser: 'tree-sitter-zelus' fileTypes: ["zls", "zli"] comments: start: '(* ' end: ' *)' folds: [ { type: 'comment' } { start: {index: 0, type: '{'} end: {index: -1, type: '}'} } { start: {index: 0, type: '['} end: {index: -1, type: ']'} } { start: {index: 0, type: '('} end: {index: -1, type: ')'} } { type: 'if_expression', start: {type: '"then"'}, end: {type: 'else_expression'} } { type: 'else_expression', start: {type: '"else"'}, } { type: 'let_expression', start: {type: '"="'}, end: {type: '"in"'} } { type: 'reset_expression', start: {type: '"reset"'}, end: {type: '"every"'} } { type: 'automaton_expression', start: {type: '"automaton"'}, end: {type: '"init"'} } { type: 'match_expression', start: {type: '"with"'}, end: {type: '"end"'} } { type: 'present_expression', start: {type: '"->"'}, end: {type: ['"else"', '"end"']} } { type: 'forall_equation', } { type: 'automaton_equation', start: {index: 0, type: '"automaton"'}, end: {type: '"init"'} } { type: 'automaton_equation', start: {index: 0, type: '"automaton"'} } { type: 'match_equation', start: {index: 0, type: '"match"'} } { type: 'present_equation', start: {type: '"->"'}, end: {type: ['"else"', '"end"']} } { type: 'if_equation', } { type: 'else_equation', } { type: 'reset_equation', start: {index: 0, type: '"reset"'}, end: {type: '"every"'} } { type: [ 'eq_equation', 'der_equation', 'next_equation', 'init_equation', 'emit_equation', 'period_equation', 'last_equation', 'let_declaration' ], start: {type: '"="'} } { type: [ 'automaton_handler_equation', 'automaton_handler_expression', 'match_handler_equation', 'match_handler_expression', 'present_handler_equation', 'present_handler_expression', 'der_reset_handler' ], start: {type: '"->"'} } { type: [ 'do_done_block' 'block_equation', 'block_expression', 'block_optional_equation' ], start: {index: 0, type: '"do"'} } { type: 'fun_declaration', start: {type: ['"where"', '"="']}, } { type: 'val_declaration', start: {type: ['":"']}, } { start: {index: 0, type: ['"until"', '"unless"', '"else"']}, end: {type: ['"then"', '"continue"']} } { type: 'one_local', } { type: 'one_let', start: {type: '"="'}, end: {type: '"in"'} } ] scopes: 'ERROR': 'markup.underline.zelus' # debug tree-sitter-zelus 'comment': 'comment.block.zelus' 'integer': 'constant.numeric.zelus' 'float' : 'constant.numeric.zelus' 'string' : 'string.quoted.double.zelus' 'string > escape_sequence': 'constant.character.escape.zelus' 'char' : 'string.quoted.single.zelus' 'bool' : 'constant.language.boolean.zelus' 'kind': 'keyword.control.zelus' 'arrow': 'meta.arrow.zelus' 'constructor': 'meta.class.zelus' # 'entity.name.type.variant.zelus' 'type_var' : 'storage.type.zelus' 'identifier' : 'meta.identifier.zelus' 'fun_name' : 'entity.name.function.zelus' 'ty_name' : 'storage.type.zelus' 'label_expr' : 'meta.label_expr.zelus' 'present_expression' : 'meta.present_expression.zelus' 'match_expression' : 'meta.match_expression.zelus' 'automaton_expression' : 'meta.automaton_expression.zelus' 'reset_expression' : 'meta.reset_expression.zelus' 'every_expression' : 'meta.every_expression.zelus' 'let_expression' : 'meta.let_expression.zelus' 'else_expression' : 'meta.else_expression.zelus' 'if_expression' : 'meta.if_expression.zelus' 'application_expression' : 'meta.application_expression.zelus' 'update_expression' : 'meta.update_expression.zelus' 'record_access_expression' : 'meta.record_access_expression.zelus' 'tuple_expression' : 'meta.tuple_expression.zelus' 'slice_expression' : 'meta.slice_expression.zelus' 'concat_expression' : 'meta.concat_expression.zelus' 'access_expression' : 'meta.access_expression.zelus' 'do_in_expression' : 'meta.do_in_expression.zelus' 'period_expression' : 'meta.period_expression.zelus' 'last_expression' : 'meta.last_expression.zelus' 'reset_equation' : 'meta.reset_equation.zelus' 'present_equation' : 'meta.present_equation.zelus' 'else_equation' : 'meta.else_equation.zelus' 'if_equation' : 'meta.if_equation.zelus' 'match_equation' : 'meta.match_equation.zelus' 'automaton_equation' : 'meta.automaton_equation.zelus' 'forall_equation' : 'meta.forall_equation.zelus' 'forall_index' : 'meta.forall_index.zelus' 'eq_equation' : 'meta.eq_equation.zelus' 'period_equation' : 'meta.period_equation.zelus' 'der_equation' : 'meta.der_equation.zelus' 'next_equation' : 'meta.next_equation.zelus' 'init_equation' : 'meta.init_equation.zelus' 'emit_equation' : 'meta.emit_equation.zelus' 'last_equation' : 'meta.last_equation.zelus' 'do_done_block' : 'meta.do_done_block.zelus' 'block_equation' : 'meta.block_equation.zelus' 'block_expression' : 'meta.block_expression.zelus' 'block_optional_equation' : 'meta.block_optional_equation.zelus' 'automaton_handler_equation' : 'meta.automaton_handler_equation' 'automaton_handler_expression': 'meta.automaton_handler_expression' 'match_handler_equation' : 'meta.match_handler_equation' 'match_handler_expression' : 'meta.match_handler_expression' 'present_handler_equation' : 'meta.present_handler_equation' 'present_handler_expression' : 'meta.present_handler_expression' 'der_reset_handler' : 'meta.der_reset_handler' 'let_declaration' : 'meta.let_declaration.zelus' 'fun_declaration' : 'meta.fun_declaration.zelus' 'val_declaration' : 'meta.val_declaration.zelus' 'pattern': 'meta.pattern.zelus' 'one_local': 'meta.one_local.zelus' 'one_let' : 'meta.one_let.zelus' 'one_local > identifier' : 'entity.name.function.zelus' 'update_expression > identifier:nth-child(1)' : 'entity.name.function.zelus' 'last_expression > identifier:nth-child(1)' : 'entity.name.function.zelus' 'every_expression > identifier:nth-child(1)' : 'entity.name.function.zelus' 'if_expression > identifier:nth-child(1)' : 'entity.name.function.zelus' 'label_expr > identifier:nth-child(0)' : 'entity.name.function.zelus' 'der_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'init_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'emit_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'next_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'last_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'forall_index > identifier:nth-child(0)' : 'entity.name.function.zelus' 'match_expression > identifier:nth-child(1)' : 'entity.name.function.zelus' 'match_equation > identifier:nth-child(1)' : 'entity.name.function.zelus' 'let_declaration > identifier:nth-child(1)' : 'entity.name.function.zelus' 'val_declaration > identifier:nth-child(1)' : 'entity.name.function.zelus' 'val_declaration > arrow' : 'entity.name.type.variant.zelus' 'present_handler_equation > identifier:nth-child(0)': 'entity.name.function.zelus' 'present_handler_expression > identifier:nth-child(0)': 'entity.name.function.zelus' 'record_access_expression > identifier:nth-child(0)': 'entity.name.variable.zelus' 'der_reset_handler > identifier:nth-child(0)': 'entity.name.function.zelus' # Ugly hack because atom do not support 'pattern identifier' selector, a # selector that should select any descendent of pattern of type identifier. # The only selector available for now is > which only goes down by 1 lvl # in the hierarchy. For now the tuples nested more than 4 times won't be # highlighted ''' eq_equation > pattern:nth-child(0) > identifier , eq_equation > pattern:nth-child(0) > pattern > identifier , eq_equation > pattern:nth-child(0) > pattern > pattern > identifier , eq_equation > pattern:nth-child(0) > pattern > pattern > pattern > identifier , eq_equation > pattern:nth-child(0) > pattern > pattern > pattern > pattern > identifier ''' : "entity.name.function.zelus" ''' match_handler_equation > pattern:nth-child(0) > identifier , match_handler_equation > pattern:nth-child(0) > pattern > identifier , match_handler_equation > pattern:nth-child(0) > pattern > pattern > identifier , match_handler_equation > pattern:nth-child(0) > pattern > pattern > pattern > identifier , match_handler_equation > pattern:nth-child(0) > pattern > pattern > pattern > pattern > identifier ''' : "entity.name.function.zelus" ''' match_handler_expression > pattern:nth-child(0) > identifier , match_handler_expression > pattern:nth-child(0) > pattern > identifier , match_handler_expression > pattern:nth-child(0) > pattern > pattern > identifier , match_handler_expression > pattern:nth-child(0) > pattern > pattern > pattern > identifier , match_handler_expression > pattern:nth-child(0) > pattern > pattern > pattern > pattern > identifier ''' : "entity.name.function.zelus" ''' period_equation > pattern:nth-child(1) > identifier , period_equation > pattern:nth-child(1) > pattern > identifier , period_equation > pattern:nth-child(1) > pattern > pattern > identifier , period_equation > pattern:nth-child(1) > pattern > pattern > pattern > identifier , period_equation > pattern:nth-child(1) > pattern > pattern > pattern > pattern > identifier ''' : "entity.name.function.zelus" # end of ugly hack 'prfx' : 'support.function.zelus' 'infx' : 'support.function.zelus' '"next"' : 'keyword.control.zelus' '"last"' : 'keyword.control.zelus' '"emit"' : 'keyword.control.zelus' '"up"' : 'keyword.control.zelus' '"open"' : 'keyword.control.zelus' '"type"' : 'keyword.control.zelus' '"val"' : 'keyword.control.zelus' '"let"' : 'keyword.control.zelus' '"rec"' : 'keyword.control.zelus' '"in"' : 'keyword.control.zelus' '"out"' : 'keyword.control.zelus' '"on"' : 'keyword.control.zelus' '"as"' : 'keyword.control.zelus' '"of"' : 'keyword.control.zelus' '"before"' : 'keyword.control.zelus' '"and"' : 'keyword.control.zelus' '"static"' : 'keyword.control.zelus' '"atomic"' : 'keyword.control.zelus' '"where"' : 'keyword.control.zelus' '"der"' : 'keyword.control.zelus' '"init"' : 'keyword.control.zelus' '"default"' : 'keyword.control.zelus' '"reset"' : 'keyword.control.zelus' '"every"' : 'keyword.control.zelus' '"present"' : 'keyword.control.zelus' '"period"' : 'keyword.control.zelus' '"local"' : 'keyword.control.zelus' '"do"' : 'keyword.control.zelus' '"done"' : 'keyword.control.zelus' '"forall"' : 'keyword.control.zelus' '"initialize"' : 'keyword.control.zelus' '"match"' : 'keyword.control.zelus' '"with"' : 'keyword.control.zelus' '"end"' : 'keyword.control.zelus' '"automaton"' : 'keyword.control.zelus' '"then"' : 'keyword.control.zelus' '"continue"' : 'keyword.control.zelus' '"until"' : 'keyword.control.zelus' '"unless"' : 'keyword.control.zelus' '"if"' : 'keyword.control.zelus' '"else"' : 'keyword.control.zelus'
[ { "context": "xtends LayerInfo\n @shouldParse: (key) -> key is 'iOpa'\n\n constructor: (layer, length) ->\n super(lay", "end": 134, "score": 0.9813748002052307, "start": 130, "tag": "KEY", "value": "iOpa" } ]
lib/psd/layer_info/fill_opacity.coffee
aleczratiu/psd.js
0
LayerInfo = require '../layer_info.coffee' module.exports = class FillOpacity extends LayerInfo @shouldParse: (key) -> key is 'iOpa' constructor: (layer, length) -> super(layer, length) @value = 255 parse: -> @value = @file.readByte() opacity: -> @value
31871
LayerInfo = require '../layer_info.coffee' module.exports = class FillOpacity extends LayerInfo @shouldParse: (key) -> key is '<KEY>' constructor: (layer, length) -> super(layer, length) @value = 255 parse: -> @value = @file.readByte() opacity: -> @value
true
LayerInfo = require '../layer_info.coffee' module.exports = class FillOpacity extends LayerInfo @shouldParse: (key) -> key is 'PI:KEY:<KEY>END_PI' constructor: (layer, length) -> super(layer, length) @value = 255 parse: -> @value = @file.readByte() opacity: -> @value
[ { "context": "ength is 0\n key = keys[0]\n else\n key += \".#{keys[keys.length-1]}\"\n st += \" ? obj.#{key} : void 0\"\n st += \" : ", "end": 1206, "score": 0.9453484416007996, "start": 1181, "tag": "KEY", "value": "\".#{keys[keys.length-1]}\"" } ]
sexprs_logic.coffee
chethiya/sexprs_logic
0
#compile cond s-expression to a test function compile = (cond) -> st = '' gc = 0 dfs = (l, cond, tab) -> oper = undefined isMap = off if (typeof cond is 'object') and (cond instanceof Array) oper = cond[0].trim().toLowerCase() else if typeof cond is 'object' oper = 'and' isMap = on else throw new Error "invalid condition" if oper isnt 'and' and oper isnt 'or' and oper isnt 'not' throw new Error "Invalid binary operation: #{cond[0]}" res = off if oper is 'and' res = on else res = off st += "#{tab}l#{l} = #{res};\n" if isMap is off for i in [1...cond.length] st += "#{tab}if (l#{l} == #{res}) {\n" dfs l+1, cond[i], tab + ' ' st += "#{tab} l#{l} = l#{l+1};\n" st += "#{tab}}\n" else for k, v of cond st += "#{tab}if (l#{l} == #{res}) {\n" # leaf step TABL = tab + ' ' keys = k.split '.' st += "#{TABL}val = void 0;\n" st += "#{TABL}lit = typeof obj !== \"undefined\" && obj !== null" key = '' for i in [0...keys.length-1] key += "." if key.length > 0 key += keys[i] st += " ? obj.#{key} != null" if key.length is 0 key = keys[0] else key += ".#{keys[keys.length-1]}" st += " ? obj.#{key} : void 0" st += " : void 0" for i in [0...keys.length-1] st += ";\n" comp = val = undefined if (typeof v is 'string') or (typeof v is 'number') comp = 'is' val = v else if (typeof v is 'object') and (v instanceof RegExp) comp = 'regex' val = v else if (typeof v is 'object') and (v instanceof Date) comp = 'is' val = v else if (typeof v is 'object') and not (v instanceof Array) comp = v.comp?.trim().toLowerCase() val = v.val vst = '' if typeof val is 'string' val = (val.replace /\\/g, '\\\\').replace /"/g, "\\\"" vst = "var temp = \"#{val}\";\n" else if typeof val is 'number' vst = "var temp = #{val};\n" else if (typeof val is 'object') and (val instanceof Date) vst = "var temp = new Date(#{val.getTime()});\n" else vst = "var temp = #{val};\n" #lit cast if v.type? if v.type is 'date' st += "#{TABL}if (lit !== null){ \n" st += "#{TABL} lit = new Date(lit);\n" st += "#{TABL}}\n" else if v.type is 'int' st += "#{TABL}if (lit !== null){ \n" st += "#{TABL} lit = parseInt(lit);\n" st += "#{TABL}}\n" else throw new Error "Unknown type #{v.type}" #global cast if comp is 'regex' vst += "var global#{gc} = new RegExp(temp);\n" else if v.type? if v.type is 'date' vst += "var global#{gc} = new Date(temp);\n" else if v.type is 'int' vst += "var global#{gc} = parseInt(temp);\n" else vst += "var global#{gc} = temp;\n" st = vst + st if comp is 'is' if v.type is 'date' or val instanceof Date st += "#{TABL}l#{l+1} = (lit instanceof Date && global#{gc} instanceof Date) ? lit.getTime() == global#{gc}.getTime() : false;\n" else st += "#{TABL}l#{l+1} = lit == global#{gc};\n" else if comp is 'gte' st += "#{TABL}l#{l+1} = lit >= global#{gc};\n" else if comp is 'gt' st += "#{TABL}l#{l+1} = lit > global#{gc};\n" else if comp is 'lte' st += "#{TABL}l#{l+1} = lit <= global#{gc};\n" else if comp is'lt' st += "#{TABL}l#{l+1} = lit < global#{gc};\n" else if comp is 'regex' st += "#{TABL}l#{l+1} = global#{gc}.test(lit);\n" else throw new Error "Invalid comparator: #{comp}" st += "#{TABL}l#{l} = l#{l+1};\n" gc++ # leaf step st += "#{tab}}\n" if l is 0 st += "#{tab}return l0;\n" st += "return function(obj) {\n" dfs 0, cond, ' ' st += "}\n" return (new Function '', st)() #compile the condition by binding condition functions compileByBind = (cond) -> cast = (type, val) -> return val unless type? if type is 'date' return new Date val else if type is 'int' return parseInt val else return val keyVal = (obj, keys) -> kval = obj kval = kval?[k] for k in keys return kval #Operations def oper_is = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return @val.getTime() is kval.getTime() return kval is @val oper_isnt = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return @val.getTime() isnt kval.getTime() return kval isnt @val oper_gte = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return kval.getTime() >= @val.getTime() return kval >= @val oper_gt = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return kval.getTime() > @val.getTime() return kval > @val oper_lte = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return kval.getTime() <= @val.getTime() return kval <= @val oper_lt = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return kval.getTime() < @val.getTime() return kval < @val oper_regex = (obj) -> kval = cast @type, keyVal obj, @keys return @val.test kval #Operations def oper_andornot = (obj) -> res = off res = on if @oper is 'and' if @oper is 'not' res = not @funcs[0] obj if @funcs.length > 0 else for f, i in @funcs res = f obj break if (@oper is 'and' and res is off) or (@oper is 'or' and res is on) return res createFunc = (cond) -> if (typeof cond is 'object') and (cond instanceof Array) oper = cond[0]?.trim().toLowerCase() if oper isnt 'and' and oper isnt 'or' and oper isnt 'not' throw new Error "Invalid binary operation: #{cond[0]}" context = oper: oper funcs: [] context.funcs.push createFunc cond[i] for i in [1...cond.length] return oper_andornot.bind context else if typeof cond is 'object' context = oper: 'and' funcs: [] for k, v of cond c = keys: [] val: undefined type: undefined c.keys = k.split '.' if typeof k is 'string' and k.length > 0 comp = undefined if typeof v is 'string' or typeof v is 'number' or typeof v is 'boolean' comp = 'is' c.val = v else if (typeof v is 'object') and (v instanceof RegExp) comp = 'regex' c.val = v else if (typeof v is 'object') and not (v instanceof Array) comp = v.comp?.trim().toLowerCase() c.val = v.val c.type = v.type if v.type? else throw new Error "Invalid comparison object" if comp is 'regex' c.val = new RegExp c.val else if c.type? if c.type is 'date' c.val = new Date c.val else if c.type is 'int' c.val = parseInt c.val if comp is 'is' context.funcs.push oper_is.bind c else if comp is 'isnt' context.funcs.push oper_isnt.bind c else if comp is 'gte' context.funcs.push oper_gte.bind c else if comp is 'gt' context.funcs.push oper_gt.bind c else if comp is 'lte' context.funcs.push oper_lte.bind c else if comp is 'lt' context.funcs.push oper_lt.bind c else if comp is 'regex' context.funcs.push oper_regex.bind c else throw new Error "Invalid operator: #{comp}" return oper_andornot.bind context return createFunc cond #test obj against cond s-expression test = (cond, obj) -> #console.log 'TEST' #console.log cond, obj if (typeof cond is 'object') and (cond instanceof Array) oper = cond[0].trim().toLowerCase() if oper isnt 'and' and oper isnt 'or' and oper isnt 'not' throw new Error "Invalid binary operation: #{cond[0]}" res = off if oper is 'and' res = on else res = off for i in [1...cond.length] if oper is 'and' res = res and test cond[i], obj break if res is off else if oper is 'or' res = res or test cond[i], obj break if oper is on else if oper is 'not' res = not test cond[i], obj break #console.log "RETURN: #{res}" return res else if typeof cond is 'object' res = on for k, v of cond keys = k.split '.' comp = lit = val = undefined lit = obj lit = lit?[key] for key in keys if typeof v is 'string' or typeof v is 'number' or typeof v is 'boolean' comp = 'is' val = v else if (typeof v is 'object') and not (v instanceof Array) comp = v.comp?.trim().toLowerCase() val = v.val if v.type? and lit? and val? if v.type is 'date' lit = new Date lit val = new Date val else if v.type is 'int' lit = parseInt lit val = parseInt val else throw new Error "Invalid comparison object" #console.log "comp: #{comp}, Key literal: #{lit}, val: #{val}" if comp is 'is' if val instanceof Date and lit instanceof Date res = false if val.getTime() isnt lit.getTime() else res = false if lit isnt val else if comp is 'gte' res = false if lit < val else if comp is 'gt' res = false if lit <= val else if comp is 'lte' res = false if lit > val else if comp is'lt' res = false if lit >= val else if comp is 'regex' r = new RegExp val res = false if not r.test lit break if res is off #console.log "RETURN: #{res}" return res else throw new Error "Invalid condition" exports?.compile = compile exports?.compileByBind = compileByBind exports?.test = test window?.SExprsLogic = compile: compile compileByBind: compileByBind test: test
106789
#compile cond s-expression to a test function compile = (cond) -> st = '' gc = 0 dfs = (l, cond, tab) -> oper = undefined isMap = off if (typeof cond is 'object') and (cond instanceof Array) oper = cond[0].trim().toLowerCase() else if typeof cond is 'object' oper = 'and' isMap = on else throw new Error "invalid condition" if oper isnt 'and' and oper isnt 'or' and oper isnt 'not' throw new Error "Invalid binary operation: #{cond[0]}" res = off if oper is 'and' res = on else res = off st += "#{tab}l#{l} = #{res};\n" if isMap is off for i in [1...cond.length] st += "#{tab}if (l#{l} == #{res}) {\n" dfs l+1, cond[i], tab + ' ' st += "#{tab} l#{l} = l#{l+1};\n" st += "#{tab}}\n" else for k, v of cond st += "#{tab}if (l#{l} == #{res}) {\n" # leaf step TABL = tab + ' ' keys = k.split '.' st += "#{TABL}val = void 0;\n" st += "#{TABL}lit = typeof obj !== \"undefined\" && obj !== null" key = '' for i in [0...keys.length-1] key += "." if key.length > 0 key += keys[i] st += " ? obj.#{key} != null" if key.length is 0 key = keys[0] else key += <KEY> st += " ? obj.#{key} : void 0" st += " : void 0" for i in [0...keys.length-1] st += ";\n" comp = val = undefined if (typeof v is 'string') or (typeof v is 'number') comp = 'is' val = v else if (typeof v is 'object') and (v instanceof RegExp) comp = 'regex' val = v else if (typeof v is 'object') and (v instanceof Date) comp = 'is' val = v else if (typeof v is 'object') and not (v instanceof Array) comp = v.comp?.trim().toLowerCase() val = v.val vst = '' if typeof val is 'string' val = (val.replace /\\/g, '\\\\').replace /"/g, "\\\"" vst = "var temp = \"#{val}\";\n" else if typeof val is 'number' vst = "var temp = #{val};\n" else if (typeof val is 'object') and (val instanceof Date) vst = "var temp = new Date(#{val.getTime()});\n" else vst = "var temp = #{val};\n" #lit cast if v.type? if v.type is 'date' st += "#{TABL}if (lit !== null){ \n" st += "#{TABL} lit = new Date(lit);\n" st += "#{TABL}}\n" else if v.type is 'int' st += "#{TABL}if (lit !== null){ \n" st += "#{TABL} lit = parseInt(lit);\n" st += "#{TABL}}\n" else throw new Error "Unknown type #{v.type}" #global cast if comp is 'regex' vst += "var global#{gc} = new RegExp(temp);\n" else if v.type? if v.type is 'date' vst += "var global#{gc} = new Date(temp);\n" else if v.type is 'int' vst += "var global#{gc} = parseInt(temp);\n" else vst += "var global#{gc} = temp;\n" st = vst + st if comp is 'is' if v.type is 'date' or val instanceof Date st += "#{TABL}l#{l+1} = (lit instanceof Date && global#{gc} instanceof Date) ? lit.getTime() == global#{gc}.getTime() : false;\n" else st += "#{TABL}l#{l+1} = lit == global#{gc};\n" else if comp is 'gte' st += "#{TABL}l#{l+1} = lit >= global#{gc};\n" else if comp is 'gt' st += "#{TABL}l#{l+1} = lit > global#{gc};\n" else if comp is 'lte' st += "#{TABL}l#{l+1} = lit <= global#{gc};\n" else if comp is'lt' st += "#{TABL}l#{l+1} = lit < global#{gc};\n" else if comp is 'regex' st += "#{TABL}l#{l+1} = global#{gc}.test(lit);\n" else throw new Error "Invalid comparator: #{comp}" st += "#{TABL}l#{l} = l#{l+1};\n" gc++ # leaf step st += "#{tab}}\n" if l is 0 st += "#{tab}return l0;\n" st += "return function(obj) {\n" dfs 0, cond, ' ' st += "}\n" return (new Function '', st)() #compile the condition by binding condition functions compileByBind = (cond) -> cast = (type, val) -> return val unless type? if type is 'date' return new Date val else if type is 'int' return parseInt val else return val keyVal = (obj, keys) -> kval = obj kval = kval?[k] for k in keys return kval #Operations def oper_is = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return @val.getTime() is kval.getTime() return kval is @val oper_isnt = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return @val.getTime() isnt kval.getTime() return kval isnt @val oper_gte = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return kval.getTime() >= @val.getTime() return kval >= @val oper_gt = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return kval.getTime() > @val.getTime() return kval > @val oper_lte = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return kval.getTime() <= @val.getTime() return kval <= @val oper_lt = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return kval.getTime() < @val.getTime() return kval < @val oper_regex = (obj) -> kval = cast @type, keyVal obj, @keys return @val.test kval #Operations def oper_andornot = (obj) -> res = off res = on if @oper is 'and' if @oper is 'not' res = not @funcs[0] obj if @funcs.length > 0 else for f, i in @funcs res = f obj break if (@oper is 'and' and res is off) or (@oper is 'or' and res is on) return res createFunc = (cond) -> if (typeof cond is 'object') and (cond instanceof Array) oper = cond[0]?.trim().toLowerCase() if oper isnt 'and' and oper isnt 'or' and oper isnt 'not' throw new Error "Invalid binary operation: #{cond[0]}" context = oper: oper funcs: [] context.funcs.push createFunc cond[i] for i in [1...cond.length] return oper_andornot.bind context else if typeof cond is 'object' context = oper: 'and' funcs: [] for k, v of cond c = keys: [] val: undefined type: undefined c.keys = k.split '.' if typeof k is 'string' and k.length > 0 comp = undefined if typeof v is 'string' or typeof v is 'number' or typeof v is 'boolean' comp = 'is' c.val = v else if (typeof v is 'object') and (v instanceof RegExp) comp = 'regex' c.val = v else if (typeof v is 'object') and not (v instanceof Array) comp = v.comp?.trim().toLowerCase() c.val = v.val c.type = v.type if v.type? else throw new Error "Invalid comparison object" if comp is 'regex' c.val = new RegExp c.val else if c.type? if c.type is 'date' c.val = new Date c.val else if c.type is 'int' c.val = parseInt c.val if comp is 'is' context.funcs.push oper_is.bind c else if comp is 'isnt' context.funcs.push oper_isnt.bind c else if comp is 'gte' context.funcs.push oper_gte.bind c else if comp is 'gt' context.funcs.push oper_gt.bind c else if comp is 'lte' context.funcs.push oper_lte.bind c else if comp is 'lt' context.funcs.push oper_lt.bind c else if comp is 'regex' context.funcs.push oper_regex.bind c else throw new Error "Invalid operator: #{comp}" return oper_andornot.bind context return createFunc cond #test obj against cond s-expression test = (cond, obj) -> #console.log 'TEST' #console.log cond, obj if (typeof cond is 'object') and (cond instanceof Array) oper = cond[0].trim().toLowerCase() if oper isnt 'and' and oper isnt 'or' and oper isnt 'not' throw new Error "Invalid binary operation: #{cond[0]}" res = off if oper is 'and' res = on else res = off for i in [1...cond.length] if oper is 'and' res = res and test cond[i], obj break if res is off else if oper is 'or' res = res or test cond[i], obj break if oper is on else if oper is 'not' res = not test cond[i], obj break #console.log "RETURN: #{res}" return res else if typeof cond is 'object' res = on for k, v of cond keys = k.split '.' comp = lit = val = undefined lit = obj lit = lit?[key] for key in keys if typeof v is 'string' or typeof v is 'number' or typeof v is 'boolean' comp = 'is' val = v else if (typeof v is 'object') and not (v instanceof Array) comp = v.comp?.trim().toLowerCase() val = v.val if v.type? and lit? and val? if v.type is 'date' lit = new Date lit val = new Date val else if v.type is 'int' lit = parseInt lit val = parseInt val else throw new Error "Invalid comparison object" #console.log "comp: #{comp}, Key literal: #{lit}, val: #{val}" if comp is 'is' if val instanceof Date and lit instanceof Date res = false if val.getTime() isnt lit.getTime() else res = false if lit isnt val else if comp is 'gte' res = false if lit < val else if comp is 'gt' res = false if lit <= val else if comp is 'lte' res = false if lit > val else if comp is'lt' res = false if lit >= val else if comp is 'regex' r = new RegExp val res = false if not r.test lit break if res is off #console.log "RETURN: #{res}" return res else throw new Error "Invalid condition" exports?.compile = compile exports?.compileByBind = compileByBind exports?.test = test window?.SExprsLogic = compile: compile compileByBind: compileByBind test: test
true
#compile cond s-expression to a test function compile = (cond) -> st = '' gc = 0 dfs = (l, cond, tab) -> oper = undefined isMap = off if (typeof cond is 'object') and (cond instanceof Array) oper = cond[0].trim().toLowerCase() else if typeof cond is 'object' oper = 'and' isMap = on else throw new Error "invalid condition" if oper isnt 'and' and oper isnt 'or' and oper isnt 'not' throw new Error "Invalid binary operation: #{cond[0]}" res = off if oper is 'and' res = on else res = off st += "#{tab}l#{l} = #{res};\n" if isMap is off for i in [1...cond.length] st += "#{tab}if (l#{l} == #{res}) {\n" dfs l+1, cond[i], tab + ' ' st += "#{tab} l#{l} = l#{l+1};\n" st += "#{tab}}\n" else for k, v of cond st += "#{tab}if (l#{l} == #{res}) {\n" # leaf step TABL = tab + ' ' keys = k.split '.' st += "#{TABL}val = void 0;\n" st += "#{TABL}lit = typeof obj !== \"undefined\" && obj !== null" key = '' for i in [0...keys.length-1] key += "." if key.length > 0 key += keys[i] st += " ? obj.#{key} != null" if key.length is 0 key = keys[0] else key += PI:KEY:<KEY>END_PI st += " ? obj.#{key} : void 0" st += " : void 0" for i in [0...keys.length-1] st += ";\n" comp = val = undefined if (typeof v is 'string') or (typeof v is 'number') comp = 'is' val = v else if (typeof v is 'object') and (v instanceof RegExp) comp = 'regex' val = v else if (typeof v is 'object') and (v instanceof Date) comp = 'is' val = v else if (typeof v is 'object') and not (v instanceof Array) comp = v.comp?.trim().toLowerCase() val = v.val vst = '' if typeof val is 'string' val = (val.replace /\\/g, '\\\\').replace /"/g, "\\\"" vst = "var temp = \"#{val}\";\n" else if typeof val is 'number' vst = "var temp = #{val};\n" else if (typeof val is 'object') and (val instanceof Date) vst = "var temp = new Date(#{val.getTime()});\n" else vst = "var temp = #{val};\n" #lit cast if v.type? if v.type is 'date' st += "#{TABL}if (lit !== null){ \n" st += "#{TABL} lit = new Date(lit);\n" st += "#{TABL}}\n" else if v.type is 'int' st += "#{TABL}if (lit !== null){ \n" st += "#{TABL} lit = parseInt(lit);\n" st += "#{TABL}}\n" else throw new Error "Unknown type #{v.type}" #global cast if comp is 'regex' vst += "var global#{gc} = new RegExp(temp);\n" else if v.type? if v.type is 'date' vst += "var global#{gc} = new Date(temp);\n" else if v.type is 'int' vst += "var global#{gc} = parseInt(temp);\n" else vst += "var global#{gc} = temp;\n" st = vst + st if comp is 'is' if v.type is 'date' or val instanceof Date st += "#{TABL}l#{l+1} = (lit instanceof Date && global#{gc} instanceof Date) ? lit.getTime() == global#{gc}.getTime() : false;\n" else st += "#{TABL}l#{l+1} = lit == global#{gc};\n" else if comp is 'gte' st += "#{TABL}l#{l+1} = lit >= global#{gc};\n" else if comp is 'gt' st += "#{TABL}l#{l+1} = lit > global#{gc};\n" else if comp is 'lte' st += "#{TABL}l#{l+1} = lit <= global#{gc};\n" else if comp is'lt' st += "#{TABL}l#{l+1} = lit < global#{gc};\n" else if comp is 'regex' st += "#{TABL}l#{l+1} = global#{gc}.test(lit);\n" else throw new Error "Invalid comparator: #{comp}" st += "#{TABL}l#{l} = l#{l+1};\n" gc++ # leaf step st += "#{tab}}\n" if l is 0 st += "#{tab}return l0;\n" st += "return function(obj) {\n" dfs 0, cond, ' ' st += "}\n" return (new Function '', st)() #compile the condition by binding condition functions compileByBind = (cond) -> cast = (type, val) -> return val unless type? if type is 'date' return new Date val else if type is 'int' return parseInt val else return val keyVal = (obj, keys) -> kval = obj kval = kval?[k] for k in keys return kval #Operations def oper_is = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return @val.getTime() is kval.getTime() return kval is @val oper_isnt = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return @val.getTime() isnt kval.getTime() return kval isnt @val oper_gte = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return kval.getTime() >= @val.getTime() return kval >= @val oper_gt = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return kval.getTime() > @val.getTime() return kval > @val oper_lte = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return kval.getTime() <= @val.getTime() return kval <= @val oper_lt = (obj) -> kval = cast @type, keyVal obj, @keys if @val instanceof Date and kval instanceof Date return kval.getTime() < @val.getTime() return kval < @val oper_regex = (obj) -> kval = cast @type, keyVal obj, @keys return @val.test kval #Operations def oper_andornot = (obj) -> res = off res = on if @oper is 'and' if @oper is 'not' res = not @funcs[0] obj if @funcs.length > 0 else for f, i in @funcs res = f obj break if (@oper is 'and' and res is off) or (@oper is 'or' and res is on) return res createFunc = (cond) -> if (typeof cond is 'object') and (cond instanceof Array) oper = cond[0]?.trim().toLowerCase() if oper isnt 'and' and oper isnt 'or' and oper isnt 'not' throw new Error "Invalid binary operation: #{cond[0]}" context = oper: oper funcs: [] context.funcs.push createFunc cond[i] for i in [1...cond.length] return oper_andornot.bind context else if typeof cond is 'object' context = oper: 'and' funcs: [] for k, v of cond c = keys: [] val: undefined type: undefined c.keys = k.split '.' if typeof k is 'string' and k.length > 0 comp = undefined if typeof v is 'string' or typeof v is 'number' or typeof v is 'boolean' comp = 'is' c.val = v else if (typeof v is 'object') and (v instanceof RegExp) comp = 'regex' c.val = v else if (typeof v is 'object') and not (v instanceof Array) comp = v.comp?.trim().toLowerCase() c.val = v.val c.type = v.type if v.type? else throw new Error "Invalid comparison object" if comp is 'regex' c.val = new RegExp c.val else if c.type? if c.type is 'date' c.val = new Date c.val else if c.type is 'int' c.val = parseInt c.val if comp is 'is' context.funcs.push oper_is.bind c else if comp is 'isnt' context.funcs.push oper_isnt.bind c else if comp is 'gte' context.funcs.push oper_gte.bind c else if comp is 'gt' context.funcs.push oper_gt.bind c else if comp is 'lte' context.funcs.push oper_lte.bind c else if comp is 'lt' context.funcs.push oper_lt.bind c else if comp is 'regex' context.funcs.push oper_regex.bind c else throw new Error "Invalid operator: #{comp}" return oper_andornot.bind context return createFunc cond #test obj against cond s-expression test = (cond, obj) -> #console.log 'TEST' #console.log cond, obj if (typeof cond is 'object') and (cond instanceof Array) oper = cond[0].trim().toLowerCase() if oper isnt 'and' and oper isnt 'or' and oper isnt 'not' throw new Error "Invalid binary operation: #{cond[0]}" res = off if oper is 'and' res = on else res = off for i in [1...cond.length] if oper is 'and' res = res and test cond[i], obj break if res is off else if oper is 'or' res = res or test cond[i], obj break if oper is on else if oper is 'not' res = not test cond[i], obj break #console.log "RETURN: #{res}" return res else if typeof cond is 'object' res = on for k, v of cond keys = k.split '.' comp = lit = val = undefined lit = obj lit = lit?[key] for key in keys if typeof v is 'string' or typeof v is 'number' or typeof v is 'boolean' comp = 'is' val = v else if (typeof v is 'object') and not (v instanceof Array) comp = v.comp?.trim().toLowerCase() val = v.val if v.type? and lit? and val? if v.type is 'date' lit = new Date lit val = new Date val else if v.type is 'int' lit = parseInt lit val = parseInt val else throw new Error "Invalid comparison object" #console.log "comp: #{comp}, Key literal: #{lit}, val: #{val}" if comp is 'is' if val instanceof Date and lit instanceof Date res = false if val.getTime() isnt lit.getTime() else res = false if lit isnt val else if comp is 'gte' res = false if lit < val else if comp is 'gt' res = false if lit <= val else if comp is 'lte' res = false if lit > val else if comp is'lt' res = false if lit >= val else if comp is 'regex' r = new RegExp val res = false if not r.test lit break if res is off #console.log "RETURN: #{res}" return res else throw new Error "Invalid condition" exports?.compile = compile exports?.compileByBind = compileByBind exports?.test = test window?.SExprsLogic = compile: compile compileByBind: compileByBind test: test
[ { "context": " = Ento()\n .attr('name')\n .build(name: \"John\")\n\n expect(JSON.stringify(obj)).be.like '{\"nam", "end": 346, "score": 0.9994021058082581, "start": 342, "tag": "NAME", "value": "John" }, { "context": " expect(JSON.stringify(obj)).be.like '{\"name\":\"...
test/json_test.coffee
rstacruz/ento
11
require './setup' describe 'json', -> it 'ok with extra values', -> obj = Ento().build(a: 1, b: 2) expect(JSON.stringify(obj)).eql '{"a":1,"b":2}' it 'keys', -> obj = Ento().build(a: 1, b: 2) expect(Object.keys(obj)).be.like ['a', 'b'] it 'defined attrs', -> obj = Ento() .attr('name') .build(name: "John") expect(JSON.stringify(obj)).be.like '{"name":"John"}' it 'ISO string dates', -> obj = Ento() .attr('date', Date) .build(date: new Date("2010-01-01Z")) expect(JSON.stringify(obj)).be.like '{"date":"2010-01-01T00:00:00.000Z"}' it 'numbers', -> obj = Ento() .attr('number', Number) .build(number: 0o100) expect(JSON.stringify(obj)).be.like '{"number":64}' it 'boolean', -> obj = Ento() .attr('bool', Boolean) .build(bool: "1") expect(JSON.stringify(obj)).be.like '{"bool":true}' it 'json: false', -> obj = Ento() .attr('name') .attr('age', json: false) .build(name: "John", age: 12) expect(JSON.stringify(obj)).be.like '{"name":"John"}' it 'defined attrs with extra values', -> obj = Ento() .attr('name') .build(age: 12, name: "John") expect(JSON.stringify(obj)).be.like '{"age":12,"name":"John"}' it 'dynamic attrs', -> obj = Ento() .attr('name') .attr('fullname', json: false, -> "Mr. #{@name}") .build(name: "Jones") expect(obj.name).eql "Jones" expect(obj.fullname).eql "Mr. Jones" expect(JSON.stringify(obj)).be.like '{"name":"Jones"}'
137648
require './setup' describe 'json', -> it 'ok with extra values', -> obj = Ento().build(a: 1, b: 2) expect(JSON.stringify(obj)).eql '{"a":1,"b":2}' it 'keys', -> obj = Ento().build(a: 1, b: 2) expect(Object.keys(obj)).be.like ['a', 'b'] it 'defined attrs', -> obj = Ento() .attr('name') .build(name: "<NAME>") expect(JSON.stringify(obj)).be.like '{"name":"<NAME>"}' it 'ISO string dates', -> obj = Ento() .attr('date', Date) .build(date: new Date("2010-01-01Z")) expect(JSON.stringify(obj)).be.like '{"date":"2010-01-01T00:00:00.000Z"}' it 'numbers', -> obj = Ento() .attr('number', Number) .build(number: 0o100) expect(JSON.stringify(obj)).be.like '{"number":64}' it 'boolean', -> obj = Ento() .attr('bool', Boolean) .build(bool: "1") expect(JSON.stringify(obj)).be.like '{"bool":true}' it 'json: false', -> obj = Ento() .attr('name') .attr('age', json: false) .build(name: "<NAME>", age: 12) expect(JSON.stringify(obj)).be.like '{"name":"<NAME>"}' it 'defined attrs with extra values', -> obj = Ento() .attr('name') .build(age: 12, name: "<NAME>") expect(JSON.stringify(obj)).be.like '{"age":12,"name":"<NAME>"}' it 'dynamic attrs', -> obj = Ento() .attr('name') .attr('fullname', json: false, -> "Mr. #{@name}") .build(name: "<NAME>") expect(obj.name).eql "<NAME>" expect(obj.fullname).eql "Mr. <NAME>" expect(JSON.stringify(obj)).be.like '{"name":"<NAME>"}'
true
require './setup' describe 'json', -> it 'ok with extra values', -> obj = Ento().build(a: 1, b: 2) expect(JSON.stringify(obj)).eql '{"a":1,"b":2}' it 'keys', -> obj = Ento().build(a: 1, b: 2) expect(Object.keys(obj)).be.like ['a', 'b'] it 'defined attrs', -> obj = Ento() .attr('name') .build(name: "PI:NAME:<NAME>END_PI") expect(JSON.stringify(obj)).be.like '{"name":"PI:NAME:<NAME>END_PI"}' it 'ISO string dates', -> obj = Ento() .attr('date', Date) .build(date: new Date("2010-01-01Z")) expect(JSON.stringify(obj)).be.like '{"date":"2010-01-01T00:00:00.000Z"}' it 'numbers', -> obj = Ento() .attr('number', Number) .build(number: 0o100) expect(JSON.stringify(obj)).be.like '{"number":64}' it 'boolean', -> obj = Ento() .attr('bool', Boolean) .build(bool: "1") expect(JSON.stringify(obj)).be.like '{"bool":true}' it 'json: false', -> obj = Ento() .attr('name') .attr('age', json: false) .build(name: "PI:NAME:<NAME>END_PI", age: 12) expect(JSON.stringify(obj)).be.like '{"name":"PI:NAME:<NAME>END_PI"}' it 'defined attrs with extra values', -> obj = Ento() .attr('name') .build(age: 12, name: "PI:NAME:<NAME>END_PI") expect(JSON.stringify(obj)).be.like '{"age":12,"name":"PI:NAME:<NAME>END_PI"}' it 'dynamic attrs', -> obj = Ento() .attr('name') .attr('fullname', json: false, -> "Mr. #{@name}") .build(name: "PI:NAME:<NAME>END_PI") expect(obj.name).eql "PI:NAME:<NAME>END_PI" expect(obj.fullname).eql "Mr. PI:NAME:<NAME>END_PI" expect(JSON.stringify(obj)).be.like '{"name":"PI:NAME:<NAME>END_PI"}'
[ { "context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib", "end": 79, "score": 0.999853789806366, "start": 66, "tag": "NAME", "value": "Henri Bergius" } ]
src/plugins/headings.coffee
GerHobbelt/hallo
682
# Hallo - a rich text editing jQuery UI widget # (c) 2011 Henri Bergius, IKS Consortium # Hallo may be freely distributed under the MIT license ((jQuery) -> jQuery.widget "IKS.halloheadings", options: editable: null uuid: '' formatBlocks: ["p", "h1", "h2", "h3"] buttonCssClass: null populateToolbar: (toolbar) -> widget = this buttonset = jQuery "<span class=\"#{widget.widgetName}\"></span>" ie = navigator.appName is 'Microsoft Internet Explorer' command = (if ie then "FormatBlock" else "formatBlock") buttonize = (format) => buttonHolder = jQuery '<span></span>' buttonHolder.hallobutton label: format editable: @options.editable command: command commandValue: (if ie then "<#{format}>" else format) uuid: @options.uuid cssClass: @options.buttonCssClass queryState: (event) -> try value = document.queryCommandValue command if ie map = { p: "normal" } for val in [1,2,3,4,5,6] map["h#{val}"] = val compared = value.match(new RegExp(map[format],"i")) else compared = value.match(new RegExp(format,"i")) result = if compared then true else false buttonHolder.hallobutton('checked', result) catch e return buttonHolder.find('button .ui-button-text').text(format.toUpperCase()) buttonset.append buttonHolder for format in @options.formatBlocks buttonize format buttonset.hallobuttonset() toolbar.append buttonset )(jQuery)
221515
# Hallo - a rich text editing jQuery UI widget # (c) 2011 <NAME>, IKS Consortium # Hallo may be freely distributed under the MIT license ((jQuery) -> jQuery.widget "IKS.halloheadings", options: editable: null uuid: '' formatBlocks: ["p", "h1", "h2", "h3"] buttonCssClass: null populateToolbar: (toolbar) -> widget = this buttonset = jQuery "<span class=\"#{widget.widgetName}\"></span>" ie = navigator.appName is 'Microsoft Internet Explorer' command = (if ie then "FormatBlock" else "formatBlock") buttonize = (format) => buttonHolder = jQuery '<span></span>' buttonHolder.hallobutton label: format editable: @options.editable command: command commandValue: (if ie then "<#{format}>" else format) uuid: @options.uuid cssClass: @options.buttonCssClass queryState: (event) -> try value = document.queryCommandValue command if ie map = { p: "normal" } for val in [1,2,3,4,5,6] map["h#{val}"] = val compared = value.match(new RegExp(map[format],"i")) else compared = value.match(new RegExp(format,"i")) result = if compared then true else false buttonHolder.hallobutton('checked', result) catch e return buttonHolder.find('button .ui-button-text').text(format.toUpperCase()) buttonset.append buttonHolder for format in @options.formatBlocks buttonize format buttonset.hallobuttonset() toolbar.append buttonset )(jQuery)
true
# Hallo - a rich text editing jQuery UI widget # (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium # Hallo may be freely distributed under the MIT license ((jQuery) -> jQuery.widget "IKS.halloheadings", options: editable: null uuid: '' formatBlocks: ["p", "h1", "h2", "h3"] buttonCssClass: null populateToolbar: (toolbar) -> widget = this buttonset = jQuery "<span class=\"#{widget.widgetName}\"></span>" ie = navigator.appName is 'Microsoft Internet Explorer' command = (if ie then "FormatBlock" else "formatBlock") buttonize = (format) => buttonHolder = jQuery '<span></span>' buttonHolder.hallobutton label: format editable: @options.editable command: command commandValue: (if ie then "<#{format}>" else format) uuid: @options.uuid cssClass: @options.buttonCssClass queryState: (event) -> try value = document.queryCommandValue command if ie map = { p: "normal" } for val in [1,2,3,4,5,6] map["h#{val}"] = val compared = value.match(new RegExp(map[format],"i")) else compared = value.match(new RegExp(format,"i")) result = if compared then true else false buttonHolder.hallobutton('checked', result) catch e return buttonHolder.find('button .ui-button-text').text(format.toUpperCase()) buttonset.append buttonHolder for format in @options.formatBlocks buttonize format buttonset.hallobuttonset() toolbar.append buttonset )(jQuery)
[ { "context": "now the door is closed\n#\n# Author:\n# github.com/mattantonelli\n\nKEY = 'is-the-door-open'\n\nmodule.exports = (robo", "end": 433, "score": 0.9996298551559448, "start": 420, "tag": "USERNAME", "value": "mattantonelli" }, { "context": "\n#\n# Author:\n# github.com/...
src/is-the-door-open.coffee
mattantonelli/hubot-is-the-door-open
1
# Description # Keeps track of whether or not the door is open. # # Dependencies: # None # # Configuration: # None # # Commands: # hubot is the door open? - tells you if the door is open # hubot is the door closed? - tells you if the door is closed # hubot the door is open - lets hubot know the door is open # hubot the door is closed - lets hubot know the door is closed # # Author: # github.com/mattantonelli KEY = 'is-the-door-open' module.exports = (robot) -> robot.respond /(?:is the )?door ([^?]+)\?/i, (res) -> status = res.match[1] reply = if isStatus(status) then 'Yes' else 'No' res.send "#{reply}, the door is #{currentStatus()}." robot.respond /(?:the )?door (?:is )?([^?]+)$/i, (res) -> status = res.match[1] update(status) res.send "The door is #{status}." update = (status) -> robot.brain.set(KEY, status) currentStatus = -> robot.brain.get(KEY) isStatus = (status) -> status.toLowerCase() == currentStatus().toLowerCase()
104757
# Description # Keeps track of whether or not the door is open. # # Dependencies: # None # # Configuration: # None # # Commands: # hubot is the door open? - tells you if the door is open # hubot is the door closed? - tells you if the door is closed # hubot the door is open - lets hubot know the door is open # hubot the door is closed - lets hubot know the door is closed # # Author: # github.com/mattantonelli KEY = '<KEY>' module.exports = (robot) -> robot.respond /(?:is the )?door ([^?]+)\?/i, (res) -> status = res.match[1] reply = if isStatus(status) then 'Yes' else 'No' res.send "#{reply}, the door is #{currentStatus()}." robot.respond /(?:the )?door (?:is )?([^?]+)$/i, (res) -> status = res.match[1] update(status) res.send "The door is #{status}." update = (status) -> robot.brain.set(KEY, status) currentStatus = -> robot.brain.get(KEY) isStatus = (status) -> status.toLowerCase() == currentStatus().toLowerCase()
true
# Description # Keeps track of whether or not the door is open. # # Dependencies: # None # # Configuration: # None # # Commands: # hubot is the door open? - tells you if the door is open # hubot is the door closed? - tells you if the door is closed # hubot the door is open - lets hubot know the door is open # hubot the door is closed - lets hubot know the door is closed # # Author: # github.com/mattantonelli KEY = 'PI:KEY:<KEY>END_PI' module.exports = (robot) -> robot.respond /(?:is the )?door ([^?]+)\?/i, (res) -> status = res.match[1] reply = if isStatus(status) then 'Yes' else 'No' res.send "#{reply}, the door is #{currentStatus()}." robot.respond /(?:the )?door (?:is )?([^?]+)$/i, (res) -> status = res.match[1] update(status) res.send "The door is #{status}." update = (status) -> robot.brain.set(KEY, status) currentStatus = -> robot.brain.get(KEY) isStatus = (status) -> status.toLowerCase() == currentStatus().toLowerCase()
[ { "context": "r = new ledger.utils.SecureLogReader('test_key', '1YnMY5FGugkuzJwdmbue9EtfsAFpQXcZy', 2, TEMPORARY)\n slw = new ledger.utils.Secu", "end": 348, "score": 0.9997614026069641, "start": 315, "tag": "KEY", "value": "1YnMY5FGugkuzJwdmbue9EtfsAFpQXcZy" }, { "context": "w ...
app/spec/utils/logger/secure_log_spec.coffee
romanornr/ledger-wallet-crw
173
describe "Secure Log Writer/Reader", -> slw = null slr = null @_errorHandler = (e) -> fail "FileSystem Error. name: #{e.name} // message: #{e.message}" l new Error().stack beforeEach (done) -> ledger.utils.Log.deleteAll TEMPORARY, -> slr = new ledger.utils.SecureLogReader('test_key', '1YnMY5FGugkuzJwdmbue9EtfsAFpQXcZy', 2, TEMPORARY) slw = new ledger.utils.SecureLogWriter('test_key', '1YnMY5FGugkuzJwdmbue9EtfsAFpQXcZy', 2, TEMPORARY) do done it "should write secure in correct order", (done) -> for str in [0...50] line = "date lorem ipsum blabla msg outing to bla - test #{str}" slw.write line slw.getFlushPromise().then -> slr.read (logs) -> for log, i in logs expect(log).toBe("date lorem ipsum blabla msg outing to bla - test #{i}") expect(logs.length).toBe(50) done() it "should encrypt correctly", (done) -> slw.write "date lorem ipsum blabla msg outing to bla - test" slw.write "nawak nawak double nawak bitcoin will spread the world !" slw.getFlushPromise().then -> ledger.utils.Log.getFs(TEMPORARY).then (fs) -> dirReader = fs.root.createReader() dirReader.readEntries (files) => loopFiles = (index, files) => file = (files || [])[index] return done() unless file? file.file (file) -> reader = new FileReader() reader.onloadend = (e) -> res = _.compact reader.result.split('\n') expect(res[0]).toBe("nm44bNrVL0WTwQE/dUSPEkKhhIEA9mtsYa8l1tbCh6wmXCN57tZ0LK6YMC7V4s0DwPF6w4QBPTeI/lLrO6icfQ==") expect(res[1]).toBe("lG47aJGZLlaBzUp2YViPHQ6myI4D7WsnLL4rgtrYmqtoTGph7dZlML3dfGqB89YSyQUMJIBJEYIzZK/y82Y6EbhYLDcVOoYg") loopFiles index + 1, files reader.readAsText(file) loopFiles 0, files
163805
describe "Secure Log Writer/Reader", -> slw = null slr = null @_errorHandler = (e) -> fail "FileSystem Error. name: #{e.name} // message: #{e.message}" l new Error().stack beforeEach (done) -> ledger.utils.Log.deleteAll TEMPORARY, -> slr = new ledger.utils.SecureLogReader('test_key', '<KEY>', 2, TEMPORARY) slw = new ledger.utils.SecureLogWriter('test_key', '<KEY>', 2, TEMPORARY) do done it "should write secure in correct order", (done) -> for str in [0...50] line = "date lorem ipsum blabla msg outing to bla - test #{str}" slw.write line slw.getFlushPromise().then -> slr.read (logs) -> for log, i in logs expect(log).toBe("date lorem ipsum blabla msg outing to bla - test #{i}") expect(logs.length).toBe(50) done() it "should encrypt correctly", (done) -> slw.write "date lorem ipsum blabla msg outing to bla - test" slw.write "nawak nawak double nawak bitcoin will spread the world !" slw.getFlushPromise().then -> ledger.utils.Log.getFs(TEMPORARY).then (fs) -> dirReader = fs.root.createReader() dirReader.readEntries (files) => loopFiles = (index, files) => file = (files || [])[index] return done() unless file? file.file (file) -> reader = new FileReader() reader.onloadend = (e) -> res = _.compact reader.result.split('\n') expect(res[0]).toBe("nm44bNrVL0WTwQE/dUSPEkKhhIEA9mtsYa8l1tbCh6wmXCN57tZ0LK6YMC7V4s0DwPF6w4QBPTeI/lLrO6icfQ==") expect(res[1]).toBe("<KEY>LlaBz<KEY>my<KEY>trY<KEY>ML<KEY>") loopFiles index + 1, files reader.readAsText(file) loopFiles 0, files
true
describe "Secure Log Writer/Reader", -> slw = null slr = null @_errorHandler = (e) -> fail "FileSystem Error. name: #{e.name} // message: #{e.message}" l new Error().stack beforeEach (done) -> ledger.utils.Log.deleteAll TEMPORARY, -> slr = new ledger.utils.SecureLogReader('test_key', 'PI:KEY:<KEY>END_PI', 2, TEMPORARY) slw = new ledger.utils.SecureLogWriter('test_key', 'PI:KEY:<KEY>END_PI', 2, TEMPORARY) do done it "should write secure in correct order", (done) -> for str in [0...50] line = "date lorem ipsum blabla msg outing to bla - test #{str}" slw.write line slw.getFlushPromise().then -> slr.read (logs) -> for log, i in logs expect(log).toBe("date lorem ipsum blabla msg outing to bla - test #{i}") expect(logs.length).toBe(50) done() it "should encrypt correctly", (done) -> slw.write "date lorem ipsum blabla msg outing to bla - test" slw.write "nawak nawak double nawak bitcoin will spread the world !" slw.getFlushPromise().then -> ledger.utils.Log.getFs(TEMPORARY).then (fs) -> dirReader = fs.root.createReader() dirReader.readEntries (files) => loopFiles = (index, files) => file = (files || [])[index] return done() unless file? file.file (file) -> reader = new FileReader() reader.onloadend = (e) -> res = _.compact reader.result.split('\n') expect(res[0]).toBe("nm44bNrVL0WTwQE/dUSPEkKhhIEA9mtsYa8l1tbCh6wmXCN57tZ0LK6YMC7V4s0DwPF6w4QBPTeI/lLrO6icfQ==") expect(res[1]).toBe("PI:KEY:<KEY>END_PILlaBzPI:KEY:<KEY>END_PImyPI:KEY:<KEY>END_PItrYPI:KEY:<KEY>END_PIMLPI:KEY:<KEY>END_PI") loopFiles index + 1, files reader.readAsText(file) loopFiles 0, files
[ { "context": "###\n * grunt-codo\n * https://github.com/frostney/grunt-codo\n *\n * Copyright (c) 2013 Johannes Stei", "end": 48, "score": 0.999344527721405, "start": 40, "tag": "USERNAME", "value": "frostney" }, { "context": "b.com/frostney/grunt-codo\n *\n * Copyright (c) 2013 Joha...
Gruntfile.coffee
mgabrin/grunt-codo
2
### * grunt-codo * https://github.com/frostney/grunt-codo * * Copyright (c) 2013 Johannes Stein * Licensed under the MIT license. ### "use strict" module.exports = ( grunt ) -> require( "matchdep" ).filterDev( "grunt-*" ).forEach grunt.loadNpmTasks grunt.initConfig coffeelint: options: grunt.file.readJSON "coffeelint.json" task: files: src: [ "Gruntfile.coffee", "src/**/*.coffee" ] coffee: options: bare: yes task: files: "tasks/utils/command.js": "src/utils/command.coffee" "tasks/codo.js": "src/codo.coffee" clean: test: [ "test/expected", "doc" ] codo: default: options: {} src: "test/fixtures/default" custom: options: name: "Codo-codo" title: "Codo-codo Documentation" extra: [ "LICENSE-MIT" ] undocumented: yes stats: no src: [ "test/fixtures/default" "test/fixtures/custom/**/*.coffee" ] dest: "test/expected/custom-docs" grunt.loadTasks "tasks" grunt.registerTask "lint", [ "coffeelint" ] grunt.registerTask "default", [ "lint" "coffee" "clean" "codo" ] grunt.registerTask "build", [ "coffeelint" "coffee" ] grunt.registerTask "test", [ "clean" "codo" ]
208275
### * grunt-codo * https://github.com/frostney/grunt-codo * * Copyright (c) 2013 <NAME> * Licensed under the MIT license. ### "use strict" module.exports = ( grunt ) -> require( "matchdep" ).filterDev( "grunt-*" ).forEach grunt.loadNpmTasks grunt.initConfig coffeelint: options: grunt.file.readJSON "coffeelint.json" task: files: src: [ "Gruntfile.coffee", "src/**/*.coffee" ] coffee: options: bare: yes task: files: "tasks/utils/command.js": "src/utils/command.coffee" "tasks/codo.js": "src/codo.coffee" clean: test: [ "test/expected", "doc" ] codo: default: options: {} src: "test/fixtures/default" custom: options: name: "Codo-codo" title: "Codo-codo Documentation" extra: [ "LICENSE-MIT" ] undocumented: yes stats: no src: [ "test/fixtures/default" "test/fixtures/custom/**/*.coffee" ] dest: "test/expected/custom-docs" grunt.loadTasks "tasks" grunt.registerTask "lint", [ "coffeelint" ] grunt.registerTask "default", [ "lint" "coffee" "clean" "codo" ] grunt.registerTask "build", [ "coffeelint" "coffee" ] grunt.registerTask "test", [ "clean" "codo" ]
true
### * grunt-codo * https://github.com/frostney/grunt-codo * * Copyright (c) 2013 PI:NAME:<NAME>END_PI * Licensed under the MIT license. ### "use strict" module.exports = ( grunt ) -> require( "matchdep" ).filterDev( "grunt-*" ).forEach grunt.loadNpmTasks grunt.initConfig coffeelint: options: grunt.file.readJSON "coffeelint.json" task: files: src: [ "Gruntfile.coffee", "src/**/*.coffee" ] coffee: options: bare: yes task: files: "tasks/utils/command.js": "src/utils/command.coffee" "tasks/codo.js": "src/codo.coffee" clean: test: [ "test/expected", "doc" ] codo: default: options: {} src: "test/fixtures/default" custom: options: name: "Codo-codo" title: "Codo-codo Documentation" extra: [ "LICENSE-MIT" ] undocumented: yes stats: no src: [ "test/fixtures/default" "test/fixtures/custom/**/*.coffee" ] dest: "test/expected/custom-docs" grunt.loadTasks "tasks" grunt.registerTask "lint", [ "coffeelint" ] grunt.registerTask "default", [ "lint" "coffee" "clean" "codo" ] grunt.registerTask "build", [ "coffeelint" "coffee" ] grunt.registerTask "test", [ "clean" "codo" ]
[ { "context": "e) ->\n \"#{name}が参加します!\"\n\n robberName: ->\n \"怪盗\"\n\n roleAndName: (name, roleName) ->\n \"#{name}", "end": 585, "score": 0.923904299736023, "start": 583, "tag": "NAME", "value": "怪盗" }, { "context": " \"#{name}は#{roleName}です。\"\n\n seerName: ->\n ...
scripts/japaneseMessageManager.coffee
mpppk/hubot-onenight-werewolf
1
class JapaneseMessageManager constructor: () -> acceptingIsAlreadyFinished: () -> "参加者受付は終了しています。次のゲームをお待ちください。" alreadyGameStarted: () -> "ゲームは既に開始しています。" alreadyJoined: () -> "既に参加中です。" alreadyVoted: () -> "既に投票済みです。" errorOccurred: () -> "エラーが発生しました。ゲームをやり直してください。" finishAccepting: () -> "受付が終了しました。" finishDisucussion: () -> "議論時間が終了しました。投票を行ってください。" finishVoting: () -> "投票が終了しました。" gameDoesNotStart: () -> "ゲームが開始されていません。\n先にゲームを開始してください。" memberJoined: (name) -> "#{name}が参加します!" robberName: -> "怪盗" roleAndName: (name, roleName) -> "#{name}は#{roleName}です。" seerName: -> "占い師" startDiscussion: () -> "議論を開始してください。" startAccepting: (sec) -> "受付開始(残り#{sec}秒)" targetPlayerDoNotExist: (name) -> name ?= "" "指定した名前(#{name})のプレイヤーは存在しません。" terminateGame: () -> "ゲームを中止しました。" villagerName: -> "村人" vote: (name) -> "#{name}に投票しました。" voteIsAlreadyFinished: () -> "投票は既に終了しています。" voteIsNotYetAccepted: () -> "まだ投票は受け付けていません。" votingResult: (targetName, votedMembersName) -> methodName = "JapaneseMessageManager.votingResult()" unless targetName? throw TypeError("targetName is not exist. (in #{methodName})") unless votedMembersName? throw TypeError("votedMembersName is not exist. (in #{methodName})") votesCast = votedMembersName.length message = "#{targetName}の得票数 => #{votesCast}\n投票した人(" for name in votedMembersName message += name + ", " message.slice(0, -2) + ")" hang: (members) -> message = "" for member in members message += member.name + "と" message.slice(0, -1) + "を処刑しました。" winningTeamIs: (teamName) -> switch teamName when "peace" then return "この村に人狼は居ませんでした!" when "lostPeace" then return "この村に人狼は居ませんでしたが、 不必要な犠牲者を生んでしまいました。" when "human" then return "人間チームが勝利しました!" when "werewolf" then return "人狼チームが勝利しました!" "大変申し訳ないのですが、私にも誰が勝ったのか分かりません。 この村に一体何が起きてしまったのでしょう?" werewolfName: -> "人狼" youAre: (name) -> "あなたは#{name}です。" exports.JapaneseMessageManager = JapaneseMessageManager
179841
class JapaneseMessageManager constructor: () -> acceptingIsAlreadyFinished: () -> "参加者受付は終了しています。次のゲームをお待ちください。" alreadyGameStarted: () -> "ゲームは既に開始しています。" alreadyJoined: () -> "既に参加中です。" alreadyVoted: () -> "既に投票済みです。" errorOccurred: () -> "エラーが発生しました。ゲームをやり直してください。" finishAccepting: () -> "受付が終了しました。" finishDisucussion: () -> "議論時間が終了しました。投票を行ってください。" finishVoting: () -> "投票が終了しました。" gameDoesNotStart: () -> "ゲームが開始されていません。\n先にゲームを開始してください。" memberJoined: (name) -> "#{name}が参加します!" robberName: -> "<NAME>" roleAndName: (name, roleName) -> "#{name}は#{roleName}です。" seerName: -> "<NAME>" startDiscussion: () -> "議論を開始してください。" startAccepting: (sec) -> "受付開始(残り#{sec}秒)" targetPlayerDoNotExist: (name) -> name ?= "" "指定した名前(#{name})のプレイヤーは存在しません。" terminateGame: () -> "ゲームを中止しました。" villagerName: -> "村人" vote: (name) -> "#{name}に投票しました。" voteIsAlreadyFinished: () -> "投票は既に終了しています。" voteIsNotYetAccepted: () -> "まだ投票は受け付けていません。" votingResult: (targetName, votedMembersName) -> methodName = "JapaneseMessageManager.votingResult()" unless targetName? throw TypeError("targetName is not exist. (in #{methodName})") unless votedMembersName? throw TypeError("votedMembersName is not exist. (in #{methodName})") votesCast = votedMembersName.length message = "#{targetName}の得票数 => #{votesCast}\n投票した人(" for name in votedMembersName message += name + ", " message.slice(0, -2) + ")" hang: (members) -> message = "" for member in members message += member.name + "と" message.slice(0, -1) + "を処刑しました。" winningTeamIs: (teamName) -> switch teamName when "peace" then return "この村に人狼は居ませんでした!" when "lostPeace" then return "この村に人狼は居ませんでしたが、 不必要な犠牲者を生んでしまいました。" when "human" then return "人間チームが勝利しました!" when "werewolf" then return "人狼チームが勝利しました!" "大変申し訳ないのですが、私にも誰が勝ったのか分かりません。 この村に一体何が起きてしまったのでしょう?" werewolfName: -> "人狼" youAre: (name) -> "あなたは#{name}です。" exports.JapaneseMessageManager = JapaneseMessageManager
true
class JapaneseMessageManager constructor: () -> acceptingIsAlreadyFinished: () -> "参加者受付は終了しています。次のゲームをお待ちください。" alreadyGameStarted: () -> "ゲームは既に開始しています。" alreadyJoined: () -> "既に参加中です。" alreadyVoted: () -> "既に投票済みです。" errorOccurred: () -> "エラーが発生しました。ゲームをやり直してください。" finishAccepting: () -> "受付が終了しました。" finishDisucussion: () -> "議論時間が終了しました。投票を行ってください。" finishVoting: () -> "投票が終了しました。" gameDoesNotStart: () -> "ゲームが開始されていません。\n先にゲームを開始してください。" memberJoined: (name) -> "#{name}が参加します!" robberName: -> "PI:NAME:<NAME>END_PI" roleAndName: (name, roleName) -> "#{name}は#{roleName}です。" seerName: -> "PI:NAME:<NAME>END_PI" startDiscussion: () -> "議論を開始してください。" startAccepting: (sec) -> "受付開始(残り#{sec}秒)" targetPlayerDoNotExist: (name) -> name ?= "" "指定した名前(#{name})のプレイヤーは存在しません。" terminateGame: () -> "ゲームを中止しました。" villagerName: -> "村人" vote: (name) -> "#{name}に投票しました。" voteIsAlreadyFinished: () -> "投票は既に終了しています。" voteIsNotYetAccepted: () -> "まだ投票は受け付けていません。" votingResult: (targetName, votedMembersName) -> methodName = "JapaneseMessageManager.votingResult()" unless targetName? throw TypeError("targetName is not exist. (in #{methodName})") unless votedMembersName? throw TypeError("votedMembersName is not exist. (in #{methodName})") votesCast = votedMembersName.length message = "#{targetName}の得票数 => #{votesCast}\n投票した人(" for name in votedMembersName message += name + ", " message.slice(0, -2) + ")" hang: (members) -> message = "" for member in members message += member.name + "と" message.slice(0, -1) + "を処刑しました。" winningTeamIs: (teamName) -> switch teamName when "peace" then return "この村に人狼は居ませんでした!" when "lostPeace" then return "この村に人狼は居ませんでしたが、 不必要な犠牲者を生んでしまいました。" when "human" then return "人間チームが勝利しました!" when "werewolf" then return "人狼チームが勝利しました!" "大変申し訳ないのですが、私にも誰が勝ったのか分かりません。 この村に一体何が起きてしまったのでしょう?" werewolfName: -> "人狼" youAre: (name) -> "あなたは#{name}です。" exports.JapaneseMessageManager = JapaneseMessageManager
[ { "context": "Bot = require 'telegram-bot-api'\ntoken = \"YOUR_TOKEN_HERE\"\nusername = \"\"\n\n#\n# Modules\n#\nsearchMo", "end": 54, "score": 0.7587089538574219, "start": 50, "tag": "KEY", "value": "YOUR" }, { "context": " = require 'telegram-bot-api'\ntoken = \"YOUR_...
src/index.coffee
BirkhoffLee/quickSearchBot
0
Bot = require 'telegram-bot-api' token = "YOUR_TOKEN_HERE" username = "" # # Modules # searchModules = {} searchModules.wiki = require "./modules/wiki.coffee" searchModules.google = require "./modules/google.coffee" bot = new Bot token: token updates: enabled: true bot.getMe() .then (data) -> username = data.username console.log "Successfully conencted to Telegram API Server." .catch (err) -> if err.name == "RequestError" console.error "Unable to connect to Telegram API Server." else console.error "Unable to get the bot's username." process.exit -1 sendMessageErrorHandler = (err) -> console.error err sendResult = (message, text) -> bot.sendMessage chat_id: message.chat.id reply_to_message_id: message.message_id disable_web_page_preview: "true" parse_mode: "html" text: text .catch sendMessageErrorHandler bot.on 'message', (message) -> if !message.text? return console.log "@#{message.from.username}: #{message.text}" firstPiece = message.text.split(" ")[0] quiet = null switch firstPiece.replace(new RegExp("@#{username}", "i"), "").slice 1 when "wiki", "wikipedia" result = null search = message.text.slice(firstPiece.length + 1).trim() if search == "" sendResult message, "You have to provide the keyword for me!" return searchModules.wiki search .then (result) -> if !result sendResult message, "Sorry, I found nothing about that on Wikipedia." else sendResult message, result .catch (err) -> console.error err if err == 0 sendResult message, "Sorry, I found nothing about that on Wikipedia." else console.error "Error occurred in Wikipedia searching module, code: #{err.toString()}" sendResult message, "Sorry, I ran into an error while searching." when "google" result = null keyword = message.text.slice(firstPiece.length + 1).trim() if keyword == "" sendResult message, "You have to provide the keyword for me!" return searchModules.google keyword .then (results) -> if results.length == 0 sendResult message, "Sorry, I found nothing about that on Google." else sendResult message, results.join("\n\n").trim() .catch (err) -> console.error "Error occurred in Google searching module, code: #{err.toString()}" sendResult message, "Sorry, I ran into an error while searching." when "start", "help" sendResult message, "Available commands:\n/wiki: Search something on Wikipedia.\n/wikipedia: Alias of /wiki.\n/google: Search something on Google." else return
191597
Bot = require 'telegram-bot-api' token = "<KEY>_<KEY>_<KEY>" username = "" # # Modules # searchModules = {} searchModules.wiki = require "./modules/wiki.coffee" searchModules.google = require "./modules/google.coffee" bot = new Bot token: token updates: enabled: true bot.getMe() .then (data) -> username = data.username console.log "Successfully conencted to Telegram API Server." .catch (err) -> if err.name == "RequestError" console.error "Unable to connect to Telegram API Server." else console.error "Unable to get the bot's username." process.exit -1 sendMessageErrorHandler = (err) -> console.error err sendResult = (message, text) -> bot.sendMessage chat_id: message.chat.id reply_to_message_id: message.message_id disable_web_page_preview: "true" parse_mode: "html" text: text .catch sendMessageErrorHandler bot.on 'message', (message) -> if !message.text? return console.log "@#{message.from.username}: #{message.text}" firstPiece = message.text.split(" ")[0] quiet = null switch firstPiece.replace(new RegExp("@#{username}", "i"), "").slice 1 when "wiki", "wikipedia" result = null search = message.text.slice(firstPiece.length + 1).trim() if search == "" sendResult message, "You have to provide the keyword for me!" return searchModules.wiki search .then (result) -> if !result sendResult message, "Sorry, I found nothing about that on Wikipedia." else sendResult message, result .catch (err) -> console.error err if err == 0 sendResult message, "Sorry, I found nothing about that on Wikipedia." else console.error "Error occurred in Wikipedia searching module, code: #{err.toString()}" sendResult message, "Sorry, I ran into an error while searching." when "google" result = null keyword = message.text.slice(firstPiece.length + 1).trim() if keyword == "" sendResult message, "You have to provide the keyword for me!" return searchModules.google keyword .then (results) -> if results.length == 0 sendResult message, "Sorry, I found nothing about that on Google." else sendResult message, results.join("\n\n").trim() .catch (err) -> console.error "Error occurred in Google searching module, code: #{err.toString()}" sendResult message, "Sorry, I ran into an error while searching." when "start", "help" sendResult message, "Available commands:\n/wiki: Search something on Wikipedia.\n/wikipedia: Alias of /wiki.\n/google: Search something on Google." else return
true
Bot = require 'telegram-bot-api' token = "PI:KEY:<KEY>END_PI_PI:KEY:<KEY>END_PI_PI:KEY:<KEY>END_PI" username = "" # # Modules # searchModules = {} searchModules.wiki = require "./modules/wiki.coffee" searchModules.google = require "./modules/google.coffee" bot = new Bot token: token updates: enabled: true bot.getMe() .then (data) -> username = data.username console.log "Successfully conencted to Telegram API Server." .catch (err) -> if err.name == "RequestError" console.error "Unable to connect to Telegram API Server." else console.error "Unable to get the bot's username." process.exit -1 sendMessageErrorHandler = (err) -> console.error err sendResult = (message, text) -> bot.sendMessage chat_id: message.chat.id reply_to_message_id: message.message_id disable_web_page_preview: "true" parse_mode: "html" text: text .catch sendMessageErrorHandler bot.on 'message', (message) -> if !message.text? return console.log "@#{message.from.username}: #{message.text}" firstPiece = message.text.split(" ")[0] quiet = null switch firstPiece.replace(new RegExp("@#{username}", "i"), "").slice 1 when "wiki", "wikipedia" result = null search = message.text.slice(firstPiece.length + 1).trim() if search == "" sendResult message, "You have to provide the keyword for me!" return searchModules.wiki search .then (result) -> if !result sendResult message, "Sorry, I found nothing about that on Wikipedia." else sendResult message, result .catch (err) -> console.error err if err == 0 sendResult message, "Sorry, I found nothing about that on Wikipedia." else console.error "Error occurred in Wikipedia searching module, code: #{err.toString()}" sendResult message, "Sorry, I ran into an error while searching." when "google" result = null keyword = message.text.slice(firstPiece.length + 1).trim() if keyword == "" sendResult message, "You have to provide the keyword for me!" return searchModules.google keyword .then (results) -> if results.length == 0 sendResult message, "Sorry, I found nothing about that on Google." else sendResult message, results.join("\n\n").trim() .catch (err) -> console.error "Error occurred in Google searching module, code: #{err.toString()}" sendResult message, "Sorry, I ran into an error while searching." when "start", "help" sendResult message, "Available commands:\n/wiki: Search something on Wikipedia.\n/wikipedia: Alias of /wiki.\n/google: Search something on Google." else return
[ { "context": "$new()\n product = new Products(id: 123, name: \"foo\")\n\n ctrl = $controller \"products.ShowCtrl\",\n ", "end": 247, "score": 0.8270533680915833, "start": 244, "tag": "NAME", "value": "foo" } ]
client/test/unit/controllers/products/show_ctrl_spec.coffee
lucassus/angular-coffee-seed
2
describe "Controller `products.ShowCtrl`", -> beforeEach module "myApp", -> $scope = null ctrl = null beforeEach inject ($rootScope, $controller, Products) -> $scope = $rootScope.$new() product = new Products(id: 123, name: "foo") ctrl = $controller "products.ShowCtrl", $scope: $scope product: product describe "$scope", -> it "has a product", -> expect($scope.product).to.not.be.undefined expect($scope.product).to.have.property "id", 123 expect($scope.product).to.have.property "name", "foo"
122541
describe "Controller `products.ShowCtrl`", -> beforeEach module "myApp", -> $scope = null ctrl = null beforeEach inject ($rootScope, $controller, Products) -> $scope = $rootScope.$new() product = new Products(id: 123, name: "<NAME>") ctrl = $controller "products.ShowCtrl", $scope: $scope product: product describe "$scope", -> it "has a product", -> expect($scope.product).to.not.be.undefined expect($scope.product).to.have.property "id", 123 expect($scope.product).to.have.property "name", "foo"
true
describe "Controller `products.ShowCtrl`", -> beforeEach module "myApp", -> $scope = null ctrl = null beforeEach inject ($rootScope, $controller, Products) -> $scope = $rootScope.$new() product = new Products(id: 123, name: "PI:NAME:<NAME>END_PI") ctrl = $controller "products.ShowCtrl", $scope: $scope product: product describe "$scope", -> it "has a product", -> expect($scope.product).to.not.be.undefined expect($scope.product).to.have.property "id", 123 expect($scope.product).to.have.property "name", "foo"
[ { "context": "ess.env.DB_USER ? 'postgres'\n password: process.env.DB_PASSWORD\n database: process.env.DB ? 'gc'\n ", "end": 416, "score": 0.9983376264572144, "start": 393, "tag": "PASSWORD", "value": "process.env.DB_PASSWORD" } ]
storage/test/unit-geolog.coffee
foobert/gc
1
fs = require 'fs' Promise = require 'bluebird' {expect} = require 'chai' describe 'geolog', -> @timeout 5000 db = null geologs = null GL00001 = null GL00002 = null before Promise.coroutine -> db = require('../lib/db') host: process.env.DB_PORT_5432_TCP_ADDR ? 'localhost' user: process.env.DB_USER ? 'postgres' password: process.env.DB_PASSWORD database: process.env.DB ? 'gc' yield db.up() geologs = require('../lib/geolog') db GL00001 = JSON.parse fs.readFileSync "#{__dirname}/data/GL00001", 'utf8' GL00002 = JSON.parse fs.readFileSync "#{__dirname}/data/GL00002", 'utf8' beforeEach Promise.coroutine -> [client, done] = yield db.connect() yield client.queryAsync 'DELETE FROM logs' done() get = Promise.coroutine (id) -> [client, done] = yield db.connect() try result = yield client.queryAsync 'SELECT data FROM logs WHERE lower(id) = lower($1)', [id] return result.rows[0]?.data finally done() describe 'upsert', -> it 'should insert a new geolog', Promise.coroutine -> yield geologs.upsert GL00001 gl = yield get 'GL00001' expect(gl).to.deep.equal GL00001 it 'should update an existing geolog', Promise.coroutine -> copy = JSON.parse JSON.stringify GL00001 copy.LogText = 'TYFTC' yield geologs.upsert GL00001 yield geologs.upsert copy gl = yield get 'GL00001' expect(gl.LogText).to.equal 'TYFTC' describe 'latest', -> it 'should return the latest log for a given username', Promise.coroutine -> yield geologs.upsert GL00001 yield geologs.upsert GL00002 latest = yield geologs.latest 'Foobar' expect(latest).to.equal 'GL00001' it 'should return null if no geologs exist', Promise.coroutine -> latest = yield geologs.latest 'nobody' expect(latest).to.not.exist describe 'deleteAll', -> it 'should delete all logs', Promise.coroutine -> yield geologs.upsert GL00001 yield geologs.upsert GL00002 yield geologs.deleteAll() [client, done] = yield db.connect() try result = yield client.queryAsync 'SELECT count(*) FROM logs' expect(result.rows[0].count).to.equal '0' finally done()
183574
fs = require 'fs' Promise = require 'bluebird' {expect} = require 'chai' describe 'geolog', -> @timeout 5000 db = null geologs = null GL00001 = null GL00002 = null before Promise.coroutine -> db = require('../lib/db') host: process.env.DB_PORT_5432_TCP_ADDR ? 'localhost' user: process.env.DB_USER ? 'postgres' password: <PASSWORD> database: process.env.DB ? 'gc' yield db.up() geologs = require('../lib/geolog') db GL00001 = JSON.parse fs.readFileSync "#{__dirname}/data/GL00001", 'utf8' GL00002 = JSON.parse fs.readFileSync "#{__dirname}/data/GL00002", 'utf8' beforeEach Promise.coroutine -> [client, done] = yield db.connect() yield client.queryAsync 'DELETE FROM logs' done() get = Promise.coroutine (id) -> [client, done] = yield db.connect() try result = yield client.queryAsync 'SELECT data FROM logs WHERE lower(id) = lower($1)', [id] return result.rows[0]?.data finally done() describe 'upsert', -> it 'should insert a new geolog', Promise.coroutine -> yield geologs.upsert GL00001 gl = yield get 'GL00001' expect(gl).to.deep.equal GL00001 it 'should update an existing geolog', Promise.coroutine -> copy = JSON.parse JSON.stringify GL00001 copy.LogText = 'TYFTC' yield geologs.upsert GL00001 yield geologs.upsert copy gl = yield get 'GL00001' expect(gl.LogText).to.equal 'TYFTC' describe 'latest', -> it 'should return the latest log for a given username', Promise.coroutine -> yield geologs.upsert GL00001 yield geologs.upsert GL00002 latest = yield geologs.latest 'Foobar' expect(latest).to.equal 'GL00001' it 'should return null if no geologs exist', Promise.coroutine -> latest = yield geologs.latest 'nobody' expect(latest).to.not.exist describe 'deleteAll', -> it 'should delete all logs', Promise.coroutine -> yield geologs.upsert GL00001 yield geologs.upsert GL00002 yield geologs.deleteAll() [client, done] = yield db.connect() try result = yield client.queryAsync 'SELECT count(*) FROM logs' expect(result.rows[0].count).to.equal '0' finally done()
true
fs = require 'fs' Promise = require 'bluebird' {expect} = require 'chai' describe 'geolog', -> @timeout 5000 db = null geologs = null GL00001 = null GL00002 = null before Promise.coroutine -> db = require('../lib/db') host: process.env.DB_PORT_5432_TCP_ADDR ? 'localhost' user: process.env.DB_USER ? 'postgres' password: PI:PASSWORD:<PASSWORD>END_PI database: process.env.DB ? 'gc' yield db.up() geologs = require('../lib/geolog') db GL00001 = JSON.parse fs.readFileSync "#{__dirname}/data/GL00001", 'utf8' GL00002 = JSON.parse fs.readFileSync "#{__dirname}/data/GL00002", 'utf8' beforeEach Promise.coroutine -> [client, done] = yield db.connect() yield client.queryAsync 'DELETE FROM logs' done() get = Promise.coroutine (id) -> [client, done] = yield db.connect() try result = yield client.queryAsync 'SELECT data FROM logs WHERE lower(id) = lower($1)', [id] return result.rows[0]?.data finally done() describe 'upsert', -> it 'should insert a new geolog', Promise.coroutine -> yield geologs.upsert GL00001 gl = yield get 'GL00001' expect(gl).to.deep.equal GL00001 it 'should update an existing geolog', Promise.coroutine -> copy = JSON.parse JSON.stringify GL00001 copy.LogText = 'TYFTC' yield geologs.upsert GL00001 yield geologs.upsert copy gl = yield get 'GL00001' expect(gl.LogText).to.equal 'TYFTC' describe 'latest', -> it 'should return the latest log for a given username', Promise.coroutine -> yield geologs.upsert GL00001 yield geologs.upsert GL00002 latest = yield geologs.latest 'Foobar' expect(latest).to.equal 'GL00001' it 'should return null if no geologs exist', Promise.coroutine -> latest = yield geologs.latest 'nobody' expect(latest).to.not.exist describe 'deleteAll', -> it 'should delete all logs', Promise.coroutine -> yield geologs.upsert GL00001 yield geologs.upsert GL00002 yield geologs.deleteAll() [client, done] = yield db.connect() try result = yield client.queryAsync 'SELECT count(*) FROM logs' expect(result.rows[0].count).to.equal '0' finally done()
[ { "context": " username : null\n password : null\n confirmPassword : null\n email ", "end": 655, "score": 0.985283613204956, "start": 651, "tag": "PASSWORD", "value": "null" }, { "context": " password : null\n confirmPassword : n...
Projects/Web/AngularJS/src/coffee/controllers/general/sign-up/sign-up-controller.coffee
carloshpds/MyOmakase
0
'use strict' # ============================================= # Module # ============================================= angular.module 'MyAngularOmakase.controllers' # ============================================= # SignUpController # ============================================= .controller 'SignUpController', ['$scope', 'SignUpService', '$state', 'MessagesEnumsFactory', ($scope, SignUpService, $state, MessagesEnumsFactor) -> # ============================================= # Atributes # ============================================= $scope.user = username : null password : null confirmPassword : null email : null # ============================================= # Validation # ============================================= $scope.error = username : false userPassword : false userConfirmPassword : false userEmail : false $scope.hasError = true $scope.validInput = (user) => @validateName user.username @validatePassword user.password @validateConfirmPassword user.password, user.confirmPassword @validateEmail user.email lastPropValue = undefined for prop, propValue of $scope.error if lastPropValue is undefined lastPropValue = propValue continue r = lastPropValue | propValue lastPropValue = propValue if lastPropValue isnt true and propValue is true $scope.hasError = false if lastPropValue is false @clickSignUpButtonHandler() if $scope.hasError is false @validateName = (username) -> return username is null or username.length < 2 @validatePassword = (userPassword) -> return userPassword is null or userPassword.length < 6 @validateConfirmPassword = (userPassword, userConfirmPassword) -> return userConfirmPassword is null or userConfirmPassword isnt userPassword @validateEmail = (userEmail) -> return userEmail is null or userEmail.length < 6 # ============================================= # Handlers # ============================================= @clickSignUpButtonHandler = () -> user = angular.copy($scope.user) delete user.confirmPassword promise = SignUpService.signUp user promise.success (data, status) -> $state.go 'login' promise.error (data) -> message = MessagesEnumsFactory.get(data.message) # ============================================= # Methods # ============================================= $scope.goState = (state) -> $state.go state ]
112169
'use strict' # ============================================= # Module # ============================================= angular.module 'MyAngularOmakase.controllers' # ============================================= # SignUpController # ============================================= .controller 'SignUpController', ['$scope', 'SignUpService', '$state', 'MessagesEnumsFactory', ($scope, SignUpService, $state, MessagesEnumsFactor) -> # ============================================= # Atributes # ============================================= $scope.user = username : null password : <PASSWORD> confirmPassword : <PASSWORD> email : null # ============================================= # Validation # ============================================= $scope.error = username : false userPassword : false userConfirmPassword : false userEmail : false $scope.hasError = true $scope.validInput = (user) => @validateName user.username @validatePassword <PASSWORD> @validateConfirmPassword <PASSWORD>, user.<PASSWORD> @validateEmail user.email lastPropValue = undefined for prop, propValue of $scope.error if lastPropValue is undefined lastPropValue = propValue continue r = lastPropValue | propValue lastPropValue = propValue if lastPropValue isnt true and propValue is true $scope.hasError = false if lastPropValue is false @clickSignUpButtonHandler() if $scope.hasError is false @validateName = (username) -> return username is null or username.length < 2 @validatePassword = (userPassword) -> return userPassword is null or userPassword.length < 6 @validateConfirmPassword = (userPassword, userConfirmPassword) -> return userConfirmPassword is null or userConfirmPassword isnt userPassword @validateEmail = (userEmail) -> return userEmail is null or userEmail.length < 6 # ============================================= # Handlers # ============================================= @clickSignUpButtonHandler = () -> user = angular.copy($scope.user) delete user.confirmPassword promise = SignUpService.signUp user promise.success (data, status) -> $state.go 'login' promise.error (data) -> message = MessagesEnumsFactory.get(data.message) # ============================================= # Methods # ============================================= $scope.goState = (state) -> $state.go state ]
true
'use strict' # ============================================= # Module # ============================================= angular.module 'MyAngularOmakase.controllers' # ============================================= # SignUpController # ============================================= .controller 'SignUpController', ['$scope', 'SignUpService', '$state', 'MessagesEnumsFactory', ($scope, SignUpService, $state, MessagesEnumsFactor) -> # ============================================= # Atributes # ============================================= $scope.user = username : null password : PI:PASSWORD:<PASSWORD>END_PI confirmPassword : PI:PASSWORD:<PASSWORD>END_PI email : null # ============================================= # Validation # ============================================= $scope.error = username : false userPassword : false userConfirmPassword : false userEmail : false $scope.hasError = true $scope.validInput = (user) => @validateName user.username @validatePassword PI:PASSWORD:<PASSWORD>END_PI @validateConfirmPassword PI:PASSWORD:<PASSWORD>END_PI, user.PI:PASSWORD:<PASSWORD>END_PI @validateEmail user.email lastPropValue = undefined for prop, propValue of $scope.error if lastPropValue is undefined lastPropValue = propValue continue r = lastPropValue | propValue lastPropValue = propValue if lastPropValue isnt true and propValue is true $scope.hasError = false if lastPropValue is false @clickSignUpButtonHandler() if $scope.hasError is false @validateName = (username) -> return username is null or username.length < 2 @validatePassword = (userPassword) -> return userPassword is null or userPassword.length < 6 @validateConfirmPassword = (userPassword, userConfirmPassword) -> return userConfirmPassword is null or userConfirmPassword isnt userPassword @validateEmail = (userEmail) -> return userEmail is null or userEmail.length < 6 # ============================================= # Handlers # ============================================= @clickSignUpButtonHandler = () -> user = angular.copy($scope.user) delete user.confirmPassword promise = SignUpService.signUp user promise.success (data, status) -> $state.go 'login' promise.error (data) -> message = MessagesEnumsFactory.get(data.message) # ============================================= # Methods # ============================================= $scope.goState = (state) -> $state.go state ]
[ { "context": "Algorithm API for JavaScript\n# https://github.com/kzokm/ga.js\n#\n# Copyright (c) 2014 OKAMURA, Kazuhide\n#\n", "end": 69, "score": 0.9995977878570557, "start": 64, "tag": "USERNAME", "value": "kzokm" }, { "context": "ps://github.com/kzokm/ga.js\n#\n# Copyright (c) 201...
lib/version.coffee
kzokm/ga.js
4
### # Genetic Algorithm API for JavaScript # https://github.com/kzokm/ga.js # # Copyright (c) 2014 OKAMURA, Kazuhide # # This software is released under the MIT License. # http://opensource.org/licenses/mit-license.php ### module.exports = full: '0.5.0' major: 0 minor: 5 dot: 0
11819
### # Genetic Algorithm API for JavaScript # https://github.com/kzokm/ga.js # # Copyright (c) 2014 <NAME>, <NAME> # # This software is released under the MIT License. # http://opensource.org/licenses/mit-license.php ### module.exports = full: '0.5.0' major: 0 minor: 5 dot: 0
true
### # Genetic Algorithm API for JavaScript # https://github.com/kzokm/ga.js # # Copyright (c) 2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI # # This software is released under the MIT License. # http://opensource.org/licenses/mit-license.php ### module.exports = full: '0.5.0' major: 0 minor: 5 dot: 0
[ { "context": "\n#\n# Commands:\n# hubot scrum\n# hubot what is <username> doing today?\n# hubot scrum help\n#\n# Optional E", "end": 318, "score": 0.6556491851806641, "start": 310, "tag": "USERNAME", "value": "username" }, { "context": "um die so we are making this now!\n#\n# A...
src/app.coffee
airbrake/hubot-scrum
3
# Description: # Team members enter their scrum and scrumbot will send a summary. # # Dependencies: # "cron": "", # "time": "" # # Configuration: # HUBOT_SCRUM_ROOM # HUBOT_SCRUM_NOTIFY_AT # HUBOT_SCRUM_CLEAR_AT # TZ # eg. "America/Los_Angeles" # # Commands: # hubot scrum # hubot what is <username> doing today? # hubot scrum help # # Optional Environment Variables: # TIMEZONE # # Notes: # We were sad to see funscrum die so we are making this now! # # Authors: # @jpsilvashy # @mmcdaris ## # What room do you want to post the scrum summary in? ROOM = process.env.HUBOT_SCRUM_ROOM ## # Explain how to use the scrum bot MESSAGE = """ USAGE: hubot scrum # start your scrum hubot what is <username> doing today? # look up other team member scrum activity hubot scrum help # displays help message """ ## # Set to local timezone TIMEZONE = process.env.TZ ## # Default scrum reminder time REMIND_AT = process.env.HUBOT_SCRUM_REMIND_AT || '0 0 6 * * *' # 6am everyday ## # SEND the scrum at 10 am everyday NOTIFY_AT = process.env.HUBOT_SCRUM_NOTIFY_AT || '0 0 10 * * *' # 10am REQUIRED_CATEGORIES = ["today", "yesterday"] ## # Setup cron CronJob = require("cron").CronJob ## # Set up your free mailgun account here: TODO # Setup Mailgun Mailgun = require('mailgun').Mailgun mailgun = new Mailgun(process.env.HUBOT_MAILGUN_APIKEY) FROM_USER = process.env.HUBOT_SCRUM_FROM_USER || "noreply+scrumbot@example.com" ## # Setup Handlebars Handlebars = require('handlebars') # Models # Team = require('./models/team') Player = require('./models/player') Scrum = require('./models/scrum') ## # Robot module.exports = (robot) -> ## # Initialize the scrum scrum = new Scrum(robot) robot.respond /today (.*)/i, (msg) -> player = Player.fromMessage(msg) player.entry("today", msg.match[1]) robot.respond /whoami/i, (msg) -> player = Player.fromMessage(msg) msg.reply "Your name is: #{player.name}" ## # Response section robot.respond /scrum players/i, (msg) -> console.log scrum.players() list = scrum.players().map (player) -> "#{player.name}: #{player.score}" msg.reply list.join("\n") || "Nobody is in the scrum!" robot.respond /scrum prompt @?([\w .\-]+)\?*$/i, (msg) -> name = msg.match[1].trim() msg.reply msg.user player = scrum.player(name) scrum.prompt(player, "yay") ## # Define the schedule schedule = reminder: (time) -> new CronJob(time, -> scrum.remind() return , null, true, TIMEZONE) notify: (time) -> new CronJob(time, -> robot.brain.data.scrum = {} return , null, true, TIMEZONE) # Schedule the Reminder with a direct message so they don't forget # Don't send this if they already sent it in # instead then send good job and leaderboard changes + streak info schedule.reminder REMIND_AT ## # Schedule when the order should be cleared at schedule.notify NOTIFY_AT ## # Messages presented to the channel, via DM, or email status = personal: (user) -> source = """ =------------------------------------------= hey {{user}}, You have {{score}} points. =------------------------------------------= """ template = Handlebars.compile(source) template({ user: user.name, score: user.score }) leaderboard: (users) -> source = """ =------------------------------------------= Hey team, here is the leaderboard: {{#each users}} {{name}}: {{score}} {{/each}} =------------------------------------------= """ template = Handlebars.compile(source) template({ users: users }) summary: (users)-> source = """ =------------------------------------------= Scrum Summary for {{ day }}: {{#each users}} {{name}} today: {{today}} yesterday: {{yesterday}} blockers: {{blockers}} {{/each}} =------------------------------------------= """ template = Handlebars.compile(source) # Users will be users:[{name:"", today:"", yesterday:"", blockers:""}] template({users: users, date: scrum.today()})
93320
# Description: # Team members enter their scrum and scrumbot will send a summary. # # Dependencies: # "cron": "", # "time": "" # # Configuration: # HUBOT_SCRUM_ROOM # HUBOT_SCRUM_NOTIFY_AT # HUBOT_SCRUM_CLEAR_AT # TZ # eg. "America/Los_Angeles" # # Commands: # hubot scrum # hubot what is <username> doing today? # hubot scrum help # # Optional Environment Variables: # TIMEZONE # # Notes: # We were sad to see funscrum die so we are making this now! # # Authors: # @jpsilvashy # @mmcdaris ## # What room do you want to post the scrum summary in? ROOM = process.env.HUBOT_SCRUM_ROOM ## # Explain how to use the scrum bot MESSAGE = """ USAGE: hubot scrum # start your scrum hubot what is <username> doing today? # look up other team member scrum activity hubot scrum help # displays help message """ ## # Set to local timezone TIMEZONE = process.env.TZ ## # Default scrum reminder time REMIND_AT = process.env.HUBOT_SCRUM_REMIND_AT || '0 0 6 * * *' # 6am everyday ## # SEND the scrum at 10 am everyday NOTIFY_AT = process.env.HUBOT_SCRUM_NOTIFY_AT || '0 0 10 * * *' # 10am REQUIRED_CATEGORIES = ["today", "yesterday"] ## # Setup cron CronJob = require("cron").CronJob ## # Set up your free mailgun account here: TODO # Setup Mailgun Mailgun = require('mailgun').Mailgun mailgun = new Mailgun(process.env.HUBOT_MAILGUN_APIKEY) FROM_USER = process.env.HUBOT_SCRUM_FROM_USER || "<EMAIL>" ## # Setup Handlebars Handlebars = require('handlebars') # Models # Team = require('./models/team') Player = require('./models/player') Scrum = require('./models/scrum') ## # Robot module.exports = (robot) -> ## # Initialize the scrum scrum = new Scrum(robot) robot.respond /today (.*)/i, (msg) -> player = Player.fromMessage(msg) player.entry("today", msg.match[1]) robot.respond /whoami/i, (msg) -> player = Player.fromMessage(msg) msg.reply "Your name is: #{player.name}" ## # Response section robot.respond /scrum players/i, (msg) -> console.log scrum.players() list = scrum.players().map (player) -> "#{player.name}: #{player.score}" msg.reply list.join("\n") || "Nobody is in the scrum!" robot.respond /scrum prompt @?([\w .\-]+)\?*$/i, (msg) -> name = msg.match[1].trim() msg.reply msg.user player = scrum.player(name) scrum.prompt(player, "yay") ## # Define the schedule schedule = reminder: (time) -> new CronJob(time, -> scrum.remind() return , null, true, TIMEZONE) notify: (time) -> new CronJob(time, -> robot.brain.data.scrum = {} return , null, true, TIMEZONE) # Schedule the Reminder with a direct message so they don't forget # Don't send this if they already sent it in # instead then send good job and leaderboard changes + streak info schedule.reminder REMIND_AT ## # Schedule when the order should be cleared at schedule.notify NOTIFY_AT ## # Messages presented to the channel, via DM, or email status = personal: (user) -> source = """ =------------------------------------------= hey {{user}}, You have {{score}} points. =------------------------------------------= """ template = Handlebars.compile(source) template({ user: user.name, score: user.score }) leaderboard: (users) -> source = """ =------------------------------------------= Hey team, here is the leaderboard: {{#each users}} {{name}}: {{score}} {{/each}} =------------------------------------------= """ template = Handlebars.compile(source) template({ users: users }) summary: (users)-> source = """ =------------------------------------------= Scrum Summary for {{ day }}: {{#each users}} {{name}} today: {{today}} yesterday: {{yesterday}} blockers: {{blockers}} {{/each}} =------------------------------------------= """ template = Handlebars.compile(source) # Users will be users:[{name:"", today:"", yesterday:"", blockers:""}] template({users: users, date: scrum.today()})
true
# Description: # Team members enter their scrum and scrumbot will send a summary. # # Dependencies: # "cron": "", # "time": "" # # Configuration: # HUBOT_SCRUM_ROOM # HUBOT_SCRUM_NOTIFY_AT # HUBOT_SCRUM_CLEAR_AT # TZ # eg. "America/Los_Angeles" # # Commands: # hubot scrum # hubot what is <username> doing today? # hubot scrum help # # Optional Environment Variables: # TIMEZONE # # Notes: # We were sad to see funscrum die so we are making this now! # # Authors: # @jpsilvashy # @mmcdaris ## # What room do you want to post the scrum summary in? ROOM = process.env.HUBOT_SCRUM_ROOM ## # Explain how to use the scrum bot MESSAGE = """ USAGE: hubot scrum # start your scrum hubot what is <username> doing today? # look up other team member scrum activity hubot scrum help # displays help message """ ## # Set to local timezone TIMEZONE = process.env.TZ ## # Default scrum reminder time REMIND_AT = process.env.HUBOT_SCRUM_REMIND_AT || '0 0 6 * * *' # 6am everyday ## # SEND the scrum at 10 am everyday NOTIFY_AT = process.env.HUBOT_SCRUM_NOTIFY_AT || '0 0 10 * * *' # 10am REQUIRED_CATEGORIES = ["today", "yesterday"] ## # Setup cron CronJob = require("cron").CronJob ## # Set up your free mailgun account here: TODO # Setup Mailgun Mailgun = require('mailgun').Mailgun mailgun = new Mailgun(process.env.HUBOT_MAILGUN_APIKEY) FROM_USER = process.env.HUBOT_SCRUM_FROM_USER || "PI:EMAIL:<EMAIL>END_PI" ## # Setup Handlebars Handlebars = require('handlebars') # Models # Team = require('./models/team') Player = require('./models/player') Scrum = require('./models/scrum') ## # Robot module.exports = (robot) -> ## # Initialize the scrum scrum = new Scrum(robot) robot.respond /today (.*)/i, (msg) -> player = Player.fromMessage(msg) player.entry("today", msg.match[1]) robot.respond /whoami/i, (msg) -> player = Player.fromMessage(msg) msg.reply "Your name is: #{player.name}" ## # Response section robot.respond /scrum players/i, (msg) -> console.log scrum.players() list = scrum.players().map (player) -> "#{player.name}: #{player.score}" msg.reply list.join("\n") || "Nobody is in the scrum!" robot.respond /scrum prompt @?([\w .\-]+)\?*$/i, (msg) -> name = msg.match[1].trim() msg.reply msg.user player = scrum.player(name) scrum.prompt(player, "yay") ## # Define the schedule schedule = reminder: (time) -> new CronJob(time, -> scrum.remind() return , null, true, TIMEZONE) notify: (time) -> new CronJob(time, -> robot.brain.data.scrum = {} return , null, true, TIMEZONE) # Schedule the Reminder with a direct message so they don't forget # Don't send this if they already sent it in # instead then send good job and leaderboard changes + streak info schedule.reminder REMIND_AT ## # Schedule when the order should be cleared at schedule.notify NOTIFY_AT ## # Messages presented to the channel, via DM, or email status = personal: (user) -> source = """ =------------------------------------------= hey {{user}}, You have {{score}} points. =------------------------------------------= """ template = Handlebars.compile(source) template({ user: user.name, score: user.score }) leaderboard: (users) -> source = """ =------------------------------------------= Hey team, here is the leaderboard: {{#each users}} {{name}}: {{score}} {{/each}} =------------------------------------------= """ template = Handlebars.compile(source) template({ users: users }) summary: (users)-> source = """ =------------------------------------------= Scrum Summary for {{ day }}: {{#each users}} {{name}} today: {{today}} yesterday: {{yesterday}} blockers: {{blockers}} {{/each}} =------------------------------------------= """ template = Handlebars.compile(source) # Users will be users:[{name:"", today:"", yesterday:"", blockers:""}] template({users: users, date: scrum.today()})
[ { "context": "re is licensed under the MIT License.\n\n Copyright Fedor Indutny, 2011.\n\n Permission is hereby granted, free of c", "end": 119, "score": 0.9995109438896179, "start": 106, "tag": "NAME", "value": "Fedor Indutny" } ]
node_modules/index/lib/index/file-storage.coffee
beshrkayali/monkey-release-action
12
### File storage for Node Index Module This software is licensed under the MIT License. Copyright Fedor Indutny, 2011. 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. ### utils = require './utils' step = require 'step' fs = require 'fs' path = require 'path' packer = pack: (data) -> data = JSON.stringify data size = Buffer.byteLength data result = new Buffer(size + 4) # Put size result.writeUInt32LE size, 0 # Put data result.write data, 4 # Return result result unpack: (data) -> size = data.readUInt32LE 0 JSON.parse (data.slice 4, (4 + size)).toString() Buffer = require('buffer').Buffer ### Default storage options ### DEFAULT_OPTIONS = filename: '' padding: 8 rootSize: 64 partitionSize: 1024 * 1024 * 1024 flushMinBytes: 4 * 1024 * 1024 ### Class @constructor ### Storage = exports.Storage = (options, callback) -> options = utils.merge DEFAULT_OPTIONS, options unless options.filename return callback 'Filename is required' {@filename, @padding, @partitionSize, @rootSize, @flushMinBytes} = options @_init callback # Return instance of self @ ### Initializes storage May be used not from constructor ### Storage::_init = (callback) -> @files = [] @filesOffset = 0 @buffers = [] @buffersBytes = 0 @buffersHashmap = {} @checkCompaction (err) => if err return callback err @openFile (err) => if err return callback err if @files.length <= 0 # If no files - create one @createFile callback else callback null, @ ### @constructor wrapper ### exports.createStorage = (options, callback) -> return new Storage options, callback ### pos = [ start-offset, length file-index or undefined ] ### Storage::isPosition = isPosition = (pos) -> pos? and Array.isArray(pos) and pos.length is 3 and true ### Adds index to the end of file and return next (unopened) filename ### Storage::nextFilename = (i, filename) -> index = i or @files.length index -= @filesOffset filename = filename or @filename if index > 0 filename + '.' + index else filename ### Check if interrupted compaction is in place ### Storage::checkCompaction = (callback) -> filename = @filename nextFilename = @nextFilename.bind @ path.exists filename, (exists) => path.exists filename + '.compact', (compactExists) => if exists if compactExists # Probably compaction hasn't finished # Delete compaction files @iterateFiles filename + '.compact', (err, i) -> if err throw err if i isnt null compacted = nextFilename i, filename + '.compact' fs.unlink compacted, @parallel() else @parallel() null # Normal db file exists - use it callback null else if compactExists # Ok, compaction has finished # Move files @iterateFiles filename + '.compact', (err, i) -> if err throw err if i isnt null # still iterating compacted = nextFilename i, filename + '.compact' notcompacted = nextFilename i, filename _callback = @parallel() fs.unlink notcompacted, (err) -> if err and (not err.code or err.code isnt 'ENOENT') _callback err else fs.rename compacted, notcompacted, _callback else # finished iterating callback null else callback null ### Iterate through files in descending order filename.N filename.N - 1 ... filename ### Storage::iterateFiles = (filename, callback) -> files = [] next = () => _filename = @nextFilename files.length, filename step -> _callback = @parallel() path.exists _filename, (exists) -> _callback null, exists return , (err, exists) -> unless exists process.nextTick iterate return files.push files.length process.nextTick next iterate = () -> file = files.pop() unless file? file = null step -> @parallel() null, file , callback , (err) -> if err callback err else if file isnt null process.nextTick iterate next() ### Add index to the end of filename, open it if exists and store size ### Storage::openFile = (callback) -> that = @ padding = @padding files = @files filename = @nextFilename() file = {} step -> _callback = @parallel() path.exists filename, (exists) -> _callback null, exists return , (err, exists) -> if err @paralell() err return unless exists @parallel() null return fs.open filename, 'a+', 0666, @parallel() fs.stat filename, @parallel() return , (err, fd, stat) -> if err throw err unless fd and stat @parallel() null return index = files.length file = filename: filename fd: fd size: stat.size index: index if file.size % padding paddBuff = new Buffer padding - file.size % padding fs.write fd, paddBuff, 0, paddBuff.length, null, @parallel() else @parallel() null, 0 @parallel() null, file files.push file return , (err, bytesWritten, file) -> if err throw err if bytesWritten? if file.size % padding if bytesWritten != padding - file.size % padding @parallel() 'Can\'t add padding to db file' return file.size += padding - file.size % padding that.openFile @parallel() else @parallel() null , callback ### Create file ### Storage::createFile = (writeRoot, callback) -> filename = @nextFilename() unless callback? callback = writeRoot writeRoot = true fs.open filename, 'w+', 0666, (err, fd) => if err return callback err file = filename: filename fd: fd size: 0 index: @files.length - @filesOffset @files.push file unless writeRoot return callback null, @ @root_pos = [ '0', '2', '0' ] @root_pos_data = null # Write new root @write [], (err, pos) => if err return callback err @writeRoot pos, (err) => if err return callback err callback null, @ ### Read data from position ### Storage::read = (pos, callback, raw) -> unless isPosition pos return callback 'pos should be a valid position (read)' s = pos[0] l = pos[1] f = pos[2] file = @files[f || 0] buff = new Buffer l if not file return callback 'pos is incorrect' cached = @buffersHashmap[pos.join '-'] if cached try unless raw cached = packer.unpack cached callback null, cached return catch e fs.read file.fd, buff, 0, l, s, (err, bytesRead) -> if err return callback err unless bytesRead == l return callback 'Read less bytes than expected' unless raw try buff = packer.unpack buff err = null catch e err = 'Data is not a valid json' callback err, buff ### Write data and return position ### Storage::write = (data, callback, raw) -> if raw and not Buffer.isBuffer data return callback 'In raw mode data should be a buffer' unless raw data = new Buffer packer.pack data @_fsWrite data, callback ### Read root page ### Storage::readRoot = (callback) -> if @root_pos_data callback null, @root_pos_data return cache_callback = (err, data) => if err return callback err @root_pos_data = data callback null, data return if @root_pos @read @root_pos, cache_callback return @readRootPos (err, pos) => if err return callback err @read pos, cache_callback ### Find last root in files and return it to callback it will be synchronous for now TODO: make it asynchronous ### Storage::readRootPos = (callback) -> iterate = (index, callback) => file = @files[index] unless file return callback 'root not found' buff = new Buffer @rootSize # If file has incorrect size (unpadded) # Substract difference from its size # B/c root can't be in that unpadded area offset = file.size - (file.size % @padding) - @rootSize + @padding while (offset -= @padding) >= 0 bytesRead = fs.readSync file.fd, buff, 0, @rootSize, offset unless bytesRead == @rootSize # Header not found offset = -1 break if data = checkHash buff root = data try root = packer.unpack root catch e # Header is not JSON # Try in previous file offset = -1 break return callback null, root process.nextTick () -> iterate (index - 1), callback checkHash = (buff) -> hash = buff.slice(0, utils.hash.len).toString() rest = buff.slice(utils.hash.len) rest if hash == utils.hash rest iterate (@files.length - 1), callback ### Write root page ### Storage::writeRoot = (root_pos, callback) -> unless isPosition root_pos return callback 'pos should be a valid position (writeRoot)' _root_pos = packer.pack root_pos buff = new Buffer @rootSize _root_pos.copy buff, utils.hash.len hash = utils.hash buff.slice utils.hash.len buff.write hash, 0, 'binary' @_fsBuffer buff, true, (err) => if err return callback err @root_pos = root_pos @root_pos_data = null callback null ### Low-level write buff - is Buffer ### Storage::_fsWrite = (buff, callback) -> file = @currentFile() pos = [ file.size, buff.length, file.index ] file.size += buff.length @buffersHashmap[pos.join '-'] = buff @_fsBuffer buff, false, (err) -> callback err, pos ### Low-level bufferization ### Storage::_fsBuffer = (buff, isRoot, callback) -> file = @currentFile() fd = file.fd buffLen = buff.length if isRoot if file.size % @padding delta = @padding - (file.size % @padding) buffLen += delta @buffers.push new Buffer delta file.size += buffLen @buffers.push buff if (@buffersBytes += buffLen) < @flushMinBytes callback null return @_fsFlush callback ### Flush buffered data to disk ### Storage::_fsFlush = (callback, compacting) -> file = @currentFile() fd = file.fd buffLen = @buffersBytes buff = new Buffer buffLen offset = 0 buffers = @buffers for i in [0...buffers.length] buffers[i].copy buff, offset offset += buffers[i].length @buffers = [] @buffersBytes = 0 @buffersHashmap = {} fs.write fd, buff, 0, buffLen, null, (err, bytesWritten) => if err or (bytesWritten isnt buffLen) @_fsCheckSize (err2) -> callback err2 or err or 'Written less bytes than expected' return if file.size >= @partitionSize and not compacting @createFile false, callback else callback null ### Recheck current file's length ### Storage::_fsCheckSize = (callback)-> file = @currentFile() filename = @nextFilename @file.index fs.stat filename, (err, stat) => if err return callback err file.size = stat.size callback null ### Current file ### Storage::currentFile = -> @files[@files.length - 1] ### Close all fds ### Storage::close = (callback) -> files = @files @_fsFlush (err) -> if err return callback err step () -> group = @group() for i in [0...files.length] if files[i] fs.close files[i].fd, group() , callback ### Compaction flow actions ### Storage::beforeCompact = (callback) -> @filename += '.compact' @filesOffset = @files.length @_fsFlush (err) => if err return callback err @createFile false, callback , true Storage::afterCompact = (callback) -> that = @ filesOffset = @filesOffset files = @files @filename = @filename.replace /\.compact$/, '' @_fsFlush (err) => if err return callback err step () -> for i in [0...files.length] fs.close files[i].fd, @parallel() return , (err) -> if err throw err for i in [0...filesOffset] fs.unlink files[i].filename, @parallel() return , (err) -> if err throw err fnsQueue = [] compactedCount = files.length - filesOffset [0...compactedCount].forEach (i) -> compactedName = files[i + filesOffset].filename normalName = files[i].filename files[i] = files[i + filesOffset] files[i].filename = normalName fnsQueue.unshift (err) -> if err throw err fs.rename compactedName, normalName, @parallel() return fnsQueue.push @parallel() step.apply null, fnsQueue for i in [compactedCount...files.length] files.pop() that.filesOffset = 0 return , (err) -> if err throw err [0...files.length].forEach (i) => file = files[i] fn = @parallel() fs.open file.filename, 'a+', 0666, (err, fd) -> file.fd = fd fn err, file return , (err) -> if err step -> for i in [0...files.length] fs.close files[i].fd, @parallel() return , -> that._init @parallel() return , @parallel() return null , callback
203850
### File storage for Node Index Module This software is licensed under the MIT License. Copyright <NAME>, 2011. 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. ### utils = require './utils' step = require 'step' fs = require 'fs' path = require 'path' packer = pack: (data) -> data = JSON.stringify data size = Buffer.byteLength data result = new Buffer(size + 4) # Put size result.writeUInt32LE size, 0 # Put data result.write data, 4 # Return result result unpack: (data) -> size = data.readUInt32LE 0 JSON.parse (data.slice 4, (4 + size)).toString() Buffer = require('buffer').Buffer ### Default storage options ### DEFAULT_OPTIONS = filename: '' padding: 8 rootSize: 64 partitionSize: 1024 * 1024 * 1024 flushMinBytes: 4 * 1024 * 1024 ### Class @constructor ### Storage = exports.Storage = (options, callback) -> options = utils.merge DEFAULT_OPTIONS, options unless options.filename return callback 'Filename is required' {@filename, @padding, @partitionSize, @rootSize, @flushMinBytes} = options @_init callback # Return instance of self @ ### Initializes storage May be used not from constructor ### Storage::_init = (callback) -> @files = [] @filesOffset = 0 @buffers = [] @buffersBytes = 0 @buffersHashmap = {} @checkCompaction (err) => if err return callback err @openFile (err) => if err return callback err if @files.length <= 0 # If no files - create one @createFile callback else callback null, @ ### @constructor wrapper ### exports.createStorage = (options, callback) -> return new Storage options, callback ### pos = [ start-offset, length file-index or undefined ] ### Storage::isPosition = isPosition = (pos) -> pos? and Array.isArray(pos) and pos.length is 3 and true ### Adds index to the end of file and return next (unopened) filename ### Storage::nextFilename = (i, filename) -> index = i or @files.length index -= @filesOffset filename = filename or @filename if index > 0 filename + '.' + index else filename ### Check if interrupted compaction is in place ### Storage::checkCompaction = (callback) -> filename = @filename nextFilename = @nextFilename.bind @ path.exists filename, (exists) => path.exists filename + '.compact', (compactExists) => if exists if compactExists # Probably compaction hasn't finished # Delete compaction files @iterateFiles filename + '.compact', (err, i) -> if err throw err if i isnt null compacted = nextFilename i, filename + '.compact' fs.unlink compacted, @parallel() else @parallel() null # Normal db file exists - use it callback null else if compactExists # Ok, compaction has finished # Move files @iterateFiles filename + '.compact', (err, i) -> if err throw err if i isnt null # still iterating compacted = nextFilename i, filename + '.compact' notcompacted = nextFilename i, filename _callback = @parallel() fs.unlink notcompacted, (err) -> if err and (not err.code or err.code isnt 'ENOENT') _callback err else fs.rename compacted, notcompacted, _callback else # finished iterating callback null else callback null ### Iterate through files in descending order filename.N filename.N - 1 ... filename ### Storage::iterateFiles = (filename, callback) -> files = [] next = () => _filename = @nextFilename files.length, filename step -> _callback = @parallel() path.exists _filename, (exists) -> _callback null, exists return , (err, exists) -> unless exists process.nextTick iterate return files.push files.length process.nextTick next iterate = () -> file = files.pop() unless file? file = null step -> @parallel() null, file , callback , (err) -> if err callback err else if file isnt null process.nextTick iterate next() ### Add index to the end of filename, open it if exists and store size ### Storage::openFile = (callback) -> that = @ padding = @padding files = @files filename = @nextFilename() file = {} step -> _callback = @parallel() path.exists filename, (exists) -> _callback null, exists return , (err, exists) -> if err @paralell() err return unless exists @parallel() null return fs.open filename, 'a+', 0666, @parallel() fs.stat filename, @parallel() return , (err, fd, stat) -> if err throw err unless fd and stat @parallel() null return index = files.length file = filename: filename fd: fd size: stat.size index: index if file.size % padding paddBuff = new Buffer padding - file.size % padding fs.write fd, paddBuff, 0, paddBuff.length, null, @parallel() else @parallel() null, 0 @parallel() null, file files.push file return , (err, bytesWritten, file) -> if err throw err if bytesWritten? if file.size % padding if bytesWritten != padding - file.size % padding @parallel() 'Can\'t add padding to db file' return file.size += padding - file.size % padding that.openFile @parallel() else @parallel() null , callback ### Create file ### Storage::createFile = (writeRoot, callback) -> filename = @nextFilename() unless callback? callback = writeRoot writeRoot = true fs.open filename, 'w+', 0666, (err, fd) => if err return callback err file = filename: filename fd: fd size: 0 index: @files.length - @filesOffset @files.push file unless writeRoot return callback null, @ @root_pos = [ '0', '2', '0' ] @root_pos_data = null # Write new root @write [], (err, pos) => if err return callback err @writeRoot pos, (err) => if err return callback err callback null, @ ### Read data from position ### Storage::read = (pos, callback, raw) -> unless isPosition pos return callback 'pos should be a valid position (read)' s = pos[0] l = pos[1] f = pos[2] file = @files[f || 0] buff = new Buffer l if not file return callback 'pos is incorrect' cached = @buffersHashmap[pos.join '-'] if cached try unless raw cached = packer.unpack cached callback null, cached return catch e fs.read file.fd, buff, 0, l, s, (err, bytesRead) -> if err return callback err unless bytesRead == l return callback 'Read less bytes than expected' unless raw try buff = packer.unpack buff err = null catch e err = 'Data is not a valid json' callback err, buff ### Write data and return position ### Storage::write = (data, callback, raw) -> if raw and not Buffer.isBuffer data return callback 'In raw mode data should be a buffer' unless raw data = new Buffer packer.pack data @_fsWrite data, callback ### Read root page ### Storage::readRoot = (callback) -> if @root_pos_data callback null, @root_pos_data return cache_callback = (err, data) => if err return callback err @root_pos_data = data callback null, data return if @root_pos @read @root_pos, cache_callback return @readRootPos (err, pos) => if err return callback err @read pos, cache_callback ### Find last root in files and return it to callback it will be synchronous for now TODO: make it asynchronous ### Storage::readRootPos = (callback) -> iterate = (index, callback) => file = @files[index] unless file return callback 'root not found' buff = new Buffer @rootSize # If file has incorrect size (unpadded) # Substract difference from its size # B/c root can't be in that unpadded area offset = file.size - (file.size % @padding) - @rootSize + @padding while (offset -= @padding) >= 0 bytesRead = fs.readSync file.fd, buff, 0, @rootSize, offset unless bytesRead == @rootSize # Header not found offset = -1 break if data = checkHash buff root = data try root = packer.unpack root catch e # Header is not JSON # Try in previous file offset = -1 break return callback null, root process.nextTick () -> iterate (index - 1), callback checkHash = (buff) -> hash = buff.slice(0, utils.hash.len).toString() rest = buff.slice(utils.hash.len) rest if hash == utils.hash rest iterate (@files.length - 1), callback ### Write root page ### Storage::writeRoot = (root_pos, callback) -> unless isPosition root_pos return callback 'pos should be a valid position (writeRoot)' _root_pos = packer.pack root_pos buff = new Buffer @rootSize _root_pos.copy buff, utils.hash.len hash = utils.hash buff.slice utils.hash.len buff.write hash, 0, 'binary' @_fsBuffer buff, true, (err) => if err return callback err @root_pos = root_pos @root_pos_data = null callback null ### Low-level write buff - is Buffer ### Storage::_fsWrite = (buff, callback) -> file = @currentFile() pos = [ file.size, buff.length, file.index ] file.size += buff.length @buffersHashmap[pos.join '-'] = buff @_fsBuffer buff, false, (err) -> callback err, pos ### Low-level bufferization ### Storage::_fsBuffer = (buff, isRoot, callback) -> file = @currentFile() fd = file.fd buffLen = buff.length if isRoot if file.size % @padding delta = @padding - (file.size % @padding) buffLen += delta @buffers.push new Buffer delta file.size += buffLen @buffers.push buff if (@buffersBytes += buffLen) < @flushMinBytes callback null return @_fsFlush callback ### Flush buffered data to disk ### Storage::_fsFlush = (callback, compacting) -> file = @currentFile() fd = file.fd buffLen = @buffersBytes buff = new Buffer buffLen offset = 0 buffers = @buffers for i in [0...buffers.length] buffers[i].copy buff, offset offset += buffers[i].length @buffers = [] @buffersBytes = 0 @buffersHashmap = {} fs.write fd, buff, 0, buffLen, null, (err, bytesWritten) => if err or (bytesWritten isnt buffLen) @_fsCheckSize (err2) -> callback err2 or err or 'Written less bytes than expected' return if file.size >= @partitionSize and not compacting @createFile false, callback else callback null ### Recheck current file's length ### Storage::_fsCheckSize = (callback)-> file = @currentFile() filename = @nextFilename @file.index fs.stat filename, (err, stat) => if err return callback err file.size = stat.size callback null ### Current file ### Storage::currentFile = -> @files[@files.length - 1] ### Close all fds ### Storage::close = (callback) -> files = @files @_fsFlush (err) -> if err return callback err step () -> group = @group() for i in [0...files.length] if files[i] fs.close files[i].fd, group() , callback ### Compaction flow actions ### Storage::beforeCompact = (callback) -> @filename += '.compact' @filesOffset = @files.length @_fsFlush (err) => if err return callback err @createFile false, callback , true Storage::afterCompact = (callback) -> that = @ filesOffset = @filesOffset files = @files @filename = @filename.replace /\.compact$/, '' @_fsFlush (err) => if err return callback err step () -> for i in [0...files.length] fs.close files[i].fd, @parallel() return , (err) -> if err throw err for i in [0...filesOffset] fs.unlink files[i].filename, @parallel() return , (err) -> if err throw err fnsQueue = [] compactedCount = files.length - filesOffset [0...compactedCount].forEach (i) -> compactedName = files[i + filesOffset].filename normalName = files[i].filename files[i] = files[i + filesOffset] files[i].filename = normalName fnsQueue.unshift (err) -> if err throw err fs.rename compactedName, normalName, @parallel() return fnsQueue.push @parallel() step.apply null, fnsQueue for i in [compactedCount...files.length] files.pop() that.filesOffset = 0 return , (err) -> if err throw err [0...files.length].forEach (i) => file = files[i] fn = @parallel() fs.open file.filename, 'a+', 0666, (err, fd) -> file.fd = fd fn err, file return , (err) -> if err step -> for i in [0...files.length] fs.close files[i].fd, @parallel() return , -> that._init @parallel() return , @parallel() return null , callback
true
### File storage for Node Index Module This software is licensed under the MIT License. Copyright PI:NAME:<NAME>END_PI, 2011. 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. ### utils = require './utils' step = require 'step' fs = require 'fs' path = require 'path' packer = pack: (data) -> data = JSON.stringify data size = Buffer.byteLength data result = new Buffer(size + 4) # Put size result.writeUInt32LE size, 0 # Put data result.write data, 4 # Return result result unpack: (data) -> size = data.readUInt32LE 0 JSON.parse (data.slice 4, (4 + size)).toString() Buffer = require('buffer').Buffer ### Default storage options ### DEFAULT_OPTIONS = filename: '' padding: 8 rootSize: 64 partitionSize: 1024 * 1024 * 1024 flushMinBytes: 4 * 1024 * 1024 ### Class @constructor ### Storage = exports.Storage = (options, callback) -> options = utils.merge DEFAULT_OPTIONS, options unless options.filename return callback 'Filename is required' {@filename, @padding, @partitionSize, @rootSize, @flushMinBytes} = options @_init callback # Return instance of self @ ### Initializes storage May be used not from constructor ### Storage::_init = (callback) -> @files = [] @filesOffset = 0 @buffers = [] @buffersBytes = 0 @buffersHashmap = {} @checkCompaction (err) => if err return callback err @openFile (err) => if err return callback err if @files.length <= 0 # If no files - create one @createFile callback else callback null, @ ### @constructor wrapper ### exports.createStorage = (options, callback) -> return new Storage options, callback ### pos = [ start-offset, length file-index or undefined ] ### Storage::isPosition = isPosition = (pos) -> pos? and Array.isArray(pos) and pos.length is 3 and true ### Adds index to the end of file and return next (unopened) filename ### Storage::nextFilename = (i, filename) -> index = i or @files.length index -= @filesOffset filename = filename or @filename if index > 0 filename + '.' + index else filename ### Check if interrupted compaction is in place ### Storage::checkCompaction = (callback) -> filename = @filename nextFilename = @nextFilename.bind @ path.exists filename, (exists) => path.exists filename + '.compact', (compactExists) => if exists if compactExists # Probably compaction hasn't finished # Delete compaction files @iterateFiles filename + '.compact', (err, i) -> if err throw err if i isnt null compacted = nextFilename i, filename + '.compact' fs.unlink compacted, @parallel() else @parallel() null # Normal db file exists - use it callback null else if compactExists # Ok, compaction has finished # Move files @iterateFiles filename + '.compact', (err, i) -> if err throw err if i isnt null # still iterating compacted = nextFilename i, filename + '.compact' notcompacted = nextFilename i, filename _callback = @parallel() fs.unlink notcompacted, (err) -> if err and (not err.code or err.code isnt 'ENOENT') _callback err else fs.rename compacted, notcompacted, _callback else # finished iterating callback null else callback null ### Iterate through files in descending order filename.N filename.N - 1 ... filename ### Storage::iterateFiles = (filename, callback) -> files = [] next = () => _filename = @nextFilename files.length, filename step -> _callback = @parallel() path.exists _filename, (exists) -> _callback null, exists return , (err, exists) -> unless exists process.nextTick iterate return files.push files.length process.nextTick next iterate = () -> file = files.pop() unless file? file = null step -> @parallel() null, file , callback , (err) -> if err callback err else if file isnt null process.nextTick iterate next() ### Add index to the end of filename, open it if exists and store size ### Storage::openFile = (callback) -> that = @ padding = @padding files = @files filename = @nextFilename() file = {} step -> _callback = @parallel() path.exists filename, (exists) -> _callback null, exists return , (err, exists) -> if err @paralell() err return unless exists @parallel() null return fs.open filename, 'a+', 0666, @parallel() fs.stat filename, @parallel() return , (err, fd, stat) -> if err throw err unless fd and stat @parallel() null return index = files.length file = filename: filename fd: fd size: stat.size index: index if file.size % padding paddBuff = new Buffer padding - file.size % padding fs.write fd, paddBuff, 0, paddBuff.length, null, @parallel() else @parallel() null, 0 @parallel() null, file files.push file return , (err, bytesWritten, file) -> if err throw err if bytesWritten? if file.size % padding if bytesWritten != padding - file.size % padding @parallel() 'Can\'t add padding to db file' return file.size += padding - file.size % padding that.openFile @parallel() else @parallel() null , callback ### Create file ### Storage::createFile = (writeRoot, callback) -> filename = @nextFilename() unless callback? callback = writeRoot writeRoot = true fs.open filename, 'w+', 0666, (err, fd) => if err return callback err file = filename: filename fd: fd size: 0 index: @files.length - @filesOffset @files.push file unless writeRoot return callback null, @ @root_pos = [ '0', '2', '0' ] @root_pos_data = null # Write new root @write [], (err, pos) => if err return callback err @writeRoot pos, (err) => if err return callback err callback null, @ ### Read data from position ### Storage::read = (pos, callback, raw) -> unless isPosition pos return callback 'pos should be a valid position (read)' s = pos[0] l = pos[1] f = pos[2] file = @files[f || 0] buff = new Buffer l if not file return callback 'pos is incorrect' cached = @buffersHashmap[pos.join '-'] if cached try unless raw cached = packer.unpack cached callback null, cached return catch e fs.read file.fd, buff, 0, l, s, (err, bytesRead) -> if err return callback err unless bytesRead == l return callback 'Read less bytes than expected' unless raw try buff = packer.unpack buff err = null catch e err = 'Data is not a valid json' callback err, buff ### Write data and return position ### Storage::write = (data, callback, raw) -> if raw and not Buffer.isBuffer data return callback 'In raw mode data should be a buffer' unless raw data = new Buffer packer.pack data @_fsWrite data, callback ### Read root page ### Storage::readRoot = (callback) -> if @root_pos_data callback null, @root_pos_data return cache_callback = (err, data) => if err return callback err @root_pos_data = data callback null, data return if @root_pos @read @root_pos, cache_callback return @readRootPos (err, pos) => if err return callback err @read pos, cache_callback ### Find last root in files and return it to callback it will be synchronous for now TODO: make it asynchronous ### Storage::readRootPos = (callback) -> iterate = (index, callback) => file = @files[index] unless file return callback 'root not found' buff = new Buffer @rootSize # If file has incorrect size (unpadded) # Substract difference from its size # B/c root can't be in that unpadded area offset = file.size - (file.size % @padding) - @rootSize + @padding while (offset -= @padding) >= 0 bytesRead = fs.readSync file.fd, buff, 0, @rootSize, offset unless bytesRead == @rootSize # Header not found offset = -1 break if data = checkHash buff root = data try root = packer.unpack root catch e # Header is not JSON # Try in previous file offset = -1 break return callback null, root process.nextTick () -> iterate (index - 1), callback checkHash = (buff) -> hash = buff.slice(0, utils.hash.len).toString() rest = buff.slice(utils.hash.len) rest if hash == utils.hash rest iterate (@files.length - 1), callback ### Write root page ### Storage::writeRoot = (root_pos, callback) -> unless isPosition root_pos return callback 'pos should be a valid position (writeRoot)' _root_pos = packer.pack root_pos buff = new Buffer @rootSize _root_pos.copy buff, utils.hash.len hash = utils.hash buff.slice utils.hash.len buff.write hash, 0, 'binary' @_fsBuffer buff, true, (err) => if err return callback err @root_pos = root_pos @root_pos_data = null callback null ### Low-level write buff - is Buffer ### Storage::_fsWrite = (buff, callback) -> file = @currentFile() pos = [ file.size, buff.length, file.index ] file.size += buff.length @buffersHashmap[pos.join '-'] = buff @_fsBuffer buff, false, (err) -> callback err, pos ### Low-level bufferization ### Storage::_fsBuffer = (buff, isRoot, callback) -> file = @currentFile() fd = file.fd buffLen = buff.length if isRoot if file.size % @padding delta = @padding - (file.size % @padding) buffLen += delta @buffers.push new Buffer delta file.size += buffLen @buffers.push buff if (@buffersBytes += buffLen) < @flushMinBytes callback null return @_fsFlush callback ### Flush buffered data to disk ### Storage::_fsFlush = (callback, compacting) -> file = @currentFile() fd = file.fd buffLen = @buffersBytes buff = new Buffer buffLen offset = 0 buffers = @buffers for i in [0...buffers.length] buffers[i].copy buff, offset offset += buffers[i].length @buffers = [] @buffersBytes = 0 @buffersHashmap = {} fs.write fd, buff, 0, buffLen, null, (err, bytesWritten) => if err or (bytesWritten isnt buffLen) @_fsCheckSize (err2) -> callback err2 or err or 'Written less bytes than expected' return if file.size >= @partitionSize and not compacting @createFile false, callback else callback null ### Recheck current file's length ### Storage::_fsCheckSize = (callback)-> file = @currentFile() filename = @nextFilename @file.index fs.stat filename, (err, stat) => if err return callback err file.size = stat.size callback null ### Current file ### Storage::currentFile = -> @files[@files.length - 1] ### Close all fds ### Storage::close = (callback) -> files = @files @_fsFlush (err) -> if err return callback err step () -> group = @group() for i in [0...files.length] if files[i] fs.close files[i].fd, group() , callback ### Compaction flow actions ### Storage::beforeCompact = (callback) -> @filename += '.compact' @filesOffset = @files.length @_fsFlush (err) => if err return callback err @createFile false, callback , true Storage::afterCompact = (callback) -> that = @ filesOffset = @filesOffset files = @files @filename = @filename.replace /\.compact$/, '' @_fsFlush (err) => if err return callback err step () -> for i in [0...files.length] fs.close files[i].fd, @parallel() return , (err) -> if err throw err for i in [0...filesOffset] fs.unlink files[i].filename, @parallel() return , (err) -> if err throw err fnsQueue = [] compactedCount = files.length - filesOffset [0...compactedCount].forEach (i) -> compactedName = files[i + filesOffset].filename normalName = files[i].filename files[i] = files[i + filesOffset] files[i].filename = normalName fnsQueue.unshift (err) -> if err throw err fs.rename compactedName, normalName, @parallel() return fnsQueue.push @parallel() step.apply null, fnsQueue for i in [compactedCount...files.length] files.pop() that.filesOffset = 0 return , (err) -> if err throw err [0...files.length].forEach (i) => file = files[i] fn = @parallel() fs.open file.filename, 'a+', 0666, (err, fd) -> file.fd = fd fn err, file return , (err) -> if err step -> for i in [0...files.length] fs.close files[i].fd, @parallel() return , -> that._init @parallel() return , @parallel() return null , callback
[ { "context": "o S3\", (done) ->\n uploader.upload(\n key: \"test.wat\"\n blob: new Blob [\"wat wat wat???\"], type: \"", "end": 240, "score": 0.9990794062614441, "start": 232, "tag": "KEY", "value": "test.wat" } ]
test/test.coffee
distri/s3-uploader
0
Uploader = require "../main" policy = JSON.parse(localStorage.CCASPolicy) uploader = Uploader policy global.Q = require "q" describe "uploader", -> it "should upload some junk to S3", (done) -> uploader.upload( key: "test.wat" blob: new Blob ["wat wat wat???"], type: "text/plain" ).then (url) -> done() , (error) -> console.log error , (progress) -> console.log progress .done() it "should be able to get files", (done) -> uploader.get "test.wat" .then (blob) -> console.log blob done() , (error) -> console.log error , (progress) -> console.log progress .done()
119488
Uploader = require "../main" policy = JSON.parse(localStorage.CCASPolicy) uploader = Uploader policy global.Q = require "q" describe "uploader", -> it "should upload some junk to S3", (done) -> uploader.upload( key: "<KEY>" blob: new Blob ["wat wat wat???"], type: "text/plain" ).then (url) -> done() , (error) -> console.log error , (progress) -> console.log progress .done() it "should be able to get files", (done) -> uploader.get "test.wat" .then (blob) -> console.log blob done() , (error) -> console.log error , (progress) -> console.log progress .done()
true
Uploader = require "../main" policy = JSON.parse(localStorage.CCASPolicy) uploader = Uploader policy global.Q = require "q" describe "uploader", -> it "should upload some junk to S3", (done) -> uploader.upload( key: "PI:KEY:<KEY>END_PI" blob: new Blob ["wat wat wat???"], type: "text/plain" ).then (url) -> done() , (error) -> console.log error , (progress) -> console.log progress .done() it "should be able to get files", (done) -> uploader.get "test.wat" .then (blob) -> console.log blob done() , (error) -> console.log error , (progress) -> console.log progress .done()
[ { "context": "###\n# Copyright 2015 Scott Brady\n# MIT License\n# https://github.com/scottbrady/xhr", "end": 32, "score": 0.9998846054077148, "start": 21, "tag": "NAME", "value": "Scott Brady" }, { "context": "15 Scott Brady\n# MIT License\n# https://github.com/scottbrady/xhr-promise...
src/index.coffee
zeekay/xhr-promise
0
### # Copyright 2015 Scott Brady # MIT License # https://github.com/scottbrady/xhr-promise/blob/master/LICENSE ### import Promise from 'broken' import objectAssign from 'es-object-assign' import parseHeaders from './parse-headers' defaults = method: 'GET' headers: {} data: null username: null password: null async: true ### # Module to wrap an XhrPromise in a promise. ### class XhrPromise @DEFAULT_CONTENT_TYPE: 'application/x-www-form-urlencoded; charset=UTF-8' @Promise: Promise ########################################################################## ## Public methods ####################################################### ######################################################################## ### # XhrPromise.send(options) -> Promise # - options (Object): URL, method, data, etc. # # Create the XHR object and wire up event handlers to use a promise. ### send: (options = {}) -> options = objectAssign {}, defaults, options new Promise (resolve, reject) => unless XMLHttpRequest @_handleError 'browser', reject, null, "browser doesn't support XMLHttpRequest" return if typeof options.url isnt 'string' || options.url.length is 0 @_handleError 'url', reject, null, 'URL is a required parameter' return # XMLHttpRequest is supported by IE 7+ @_xhr = xhr = new XMLHttpRequest() # success handler xhr.onload = => @_detachWindowUnload() try responseText = @_getResponseText() catch @_handleError 'parse', reject, null, 'invalid JSON response' return resolve url: @_getResponseUrl() headers: @_getHeaders() responseText: responseText status: xhr.status statusText: xhr.statusText xhr: xhr # error handlers xhr.onerror = => @_handleError 'error', reject xhr.ontimeout = => @_handleError 'timeout', reject xhr.onabort = => @_handleError 'abort', reject @_attachWindowUnload() xhr.open options.method, options.url, options.async, options.username, options.password if options.data? && !(options.data instanceof FormData) && !options.headers['Content-Type'] options.headers['Content-Type'] = @constructor.DEFAULT_CONTENT_TYPE for header, value of options.headers xhr.setRequestHeader(header, value) try xhr.send(options.data) catch e @_handleError 'send', reject, null, e.toString() ### # XhrPromise.getXHR() -> XhrPromise ### getXHR: -> @_xhr ########################################################################## ## Psuedo-private methods ############################################### ######################################################################## ### # XhrPromise._attachWindowUnload() # # Fix for IE 9 and IE 10 # Internet Explorer freezes when you close a webpage during an XHR request # https://support.microsoft.com/kb/2856746 # ### _attachWindowUnload: -> @_unloadHandler = @_handleWindowUnload.bind(@) window.attachEvent 'onunload', @_unloadHandler if window.attachEvent ### # XhrPromise._detachWindowUnload() ### _detachWindowUnload: -> window.detachEvent 'onunload', @_unloadHandler if window.detachEvent ### # XhrPromise._getHeaders() -> Object ### _getHeaders: -> parseHeaders @_xhr.getAllResponseHeaders() ### # XhrPromise._getResponseText() -> Mixed # # Parses response text JSON if present. ### _getResponseText: -> # Accessing binary-data responseText throws an exception in IE9 responseText = if typeof @_xhr.responseText is 'string' then @_xhr.responseText else '' switch @_xhr.getResponseHeader('Content-Type') when 'application/json', 'text/javascript' # Workaround Android 2.3 failure to string-cast null input responseText = JSON.parse(responseText + '') responseText ### # XhrPromise._getResponseUrl() -> String # # Actual response URL after following redirects. ### _getResponseUrl: -> return @_xhr.responseURL if @_xhr.responseURL? # Avoid security warnings on getResponseHeader when not allowed by CORS return @_xhr.getResponseHeader('X-Request-URL') if /^X-Request-URL:/m.test(@_xhr.getAllResponseHeaders()) '' ### # XhrPromise._handleError(reason, reject, status, statusText) # - reason (String) # - reject (Function) # - status (String) # - statusText (String) ### _handleError: (reason, reject, status, statusText) -> @_detachWindowUnload() reject reason: reason status: status or @_xhr.status statusText: statusText or @_xhr.statusText xhr: @_xhr ### # XhrPromise._handleWindowUnload() ### _handleWindowUnload: -> @_xhr.abort() export default XhrPromise
57110
### # Copyright 2015 <NAME> # MIT License # https://github.com/scottbrady/xhr-promise/blob/master/LICENSE ### import Promise from 'broken' import objectAssign from 'es-object-assign' import parseHeaders from './parse-headers' defaults = method: 'GET' headers: {} data: null username: null password: <PASSWORD> async: true ### # Module to wrap an XhrPromise in a promise. ### class XhrPromise @DEFAULT_CONTENT_TYPE: 'application/x-www-form-urlencoded; charset=UTF-8' @Promise: Promise ########################################################################## ## Public methods ####################################################### ######################################################################## ### # XhrPromise.send(options) -> Promise # - options (Object): URL, method, data, etc. # # Create the XHR object and wire up event handlers to use a promise. ### send: (options = {}) -> options = objectAssign {}, defaults, options new Promise (resolve, reject) => unless XMLHttpRequest @_handleError 'browser', reject, null, "browser doesn't support XMLHttpRequest" return if typeof options.url isnt 'string' || options.url.length is 0 @_handleError 'url', reject, null, 'URL is a required parameter' return # XMLHttpRequest is supported by IE 7+ @_xhr = xhr = new XMLHttpRequest() # success handler xhr.onload = => @_detachWindowUnload() try responseText = @_getResponseText() catch @_handleError 'parse', reject, null, 'invalid JSON response' return resolve url: @_getResponseUrl() headers: @_getHeaders() responseText: responseText status: xhr.status statusText: xhr.statusText xhr: xhr # error handlers xhr.onerror = => @_handleError 'error', reject xhr.ontimeout = => @_handleError 'timeout', reject xhr.onabort = => @_handleError 'abort', reject @_attachWindowUnload() xhr.open options.method, options.url, options.async, options.username, options.password if options.data? && !(options.data instanceof FormData) && !options.headers['Content-Type'] options.headers['Content-Type'] = @constructor.DEFAULT_CONTENT_TYPE for header, value of options.headers xhr.setRequestHeader(header, value) try xhr.send(options.data) catch e @_handleError 'send', reject, null, e.toString() ### # XhrPromise.getXHR() -> XhrPromise ### getXHR: -> @_xhr ########################################################################## ## Psuedo-private methods ############################################### ######################################################################## ### # XhrPromise._attachWindowUnload() # # Fix for IE 9 and IE 10 # Internet Explorer freezes when you close a webpage during an XHR request # https://support.microsoft.com/kb/2856746 # ### _attachWindowUnload: -> @_unloadHandler = @_handleWindowUnload.bind(@) window.attachEvent 'onunload', @_unloadHandler if window.attachEvent ### # XhrPromise._detachWindowUnload() ### _detachWindowUnload: -> window.detachEvent 'onunload', @_unloadHandler if window.detachEvent ### # XhrPromise._getHeaders() -> Object ### _getHeaders: -> parseHeaders @_xhr.getAllResponseHeaders() ### # XhrPromise._getResponseText() -> Mixed # # Parses response text JSON if present. ### _getResponseText: -> # Accessing binary-data responseText throws an exception in IE9 responseText = if typeof @_xhr.responseText is 'string' then @_xhr.responseText else '' switch @_xhr.getResponseHeader('Content-Type') when 'application/json', 'text/javascript' # Workaround Android 2.3 failure to string-cast null input responseText = JSON.parse(responseText + '') responseText ### # XhrPromise._getResponseUrl() -> String # # Actual response URL after following redirects. ### _getResponseUrl: -> return @_xhr.responseURL if @_xhr.responseURL? # Avoid security warnings on getResponseHeader when not allowed by CORS return @_xhr.getResponseHeader('X-Request-URL') if /^X-Request-URL:/m.test(@_xhr.getAllResponseHeaders()) '' ### # XhrPromise._handleError(reason, reject, status, statusText) # - reason (String) # - reject (Function) # - status (String) # - statusText (String) ### _handleError: (reason, reject, status, statusText) -> @_detachWindowUnload() reject reason: reason status: status or @_xhr.status statusText: statusText or @_xhr.statusText xhr: @_xhr ### # XhrPromise._handleWindowUnload() ### _handleWindowUnload: -> @_xhr.abort() export default XhrPromise
true
### # Copyright 2015 PI:NAME:<NAME>END_PI # MIT License # https://github.com/scottbrady/xhr-promise/blob/master/LICENSE ### import Promise from 'broken' import objectAssign from 'es-object-assign' import parseHeaders from './parse-headers' defaults = method: 'GET' headers: {} data: null username: null password: PI:PASSWORD:<PASSWORD>END_PI async: true ### # Module to wrap an XhrPromise in a promise. ### class XhrPromise @DEFAULT_CONTENT_TYPE: 'application/x-www-form-urlencoded; charset=UTF-8' @Promise: Promise ########################################################################## ## Public methods ####################################################### ######################################################################## ### # XhrPromise.send(options) -> Promise # - options (Object): URL, method, data, etc. # # Create the XHR object and wire up event handlers to use a promise. ### send: (options = {}) -> options = objectAssign {}, defaults, options new Promise (resolve, reject) => unless XMLHttpRequest @_handleError 'browser', reject, null, "browser doesn't support XMLHttpRequest" return if typeof options.url isnt 'string' || options.url.length is 0 @_handleError 'url', reject, null, 'URL is a required parameter' return # XMLHttpRequest is supported by IE 7+ @_xhr = xhr = new XMLHttpRequest() # success handler xhr.onload = => @_detachWindowUnload() try responseText = @_getResponseText() catch @_handleError 'parse', reject, null, 'invalid JSON response' return resolve url: @_getResponseUrl() headers: @_getHeaders() responseText: responseText status: xhr.status statusText: xhr.statusText xhr: xhr # error handlers xhr.onerror = => @_handleError 'error', reject xhr.ontimeout = => @_handleError 'timeout', reject xhr.onabort = => @_handleError 'abort', reject @_attachWindowUnload() xhr.open options.method, options.url, options.async, options.username, options.password if options.data? && !(options.data instanceof FormData) && !options.headers['Content-Type'] options.headers['Content-Type'] = @constructor.DEFAULT_CONTENT_TYPE for header, value of options.headers xhr.setRequestHeader(header, value) try xhr.send(options.data) catch e @_handleError 'send', reject, null, e.toString() ### # XhrPromise.getXHR() -> XhrPromise ### getXHR: -> @_xhr ########################################################################## ## Psuedo-private methods ############################################### ######################################################################## ### # XhrPromise._attachWindowUnload() # # Fix for IE 9 and IE 10 # Internet Explorer freezes when you close a webpage during an XHR request # https://support.microsoft.com/kb/2856746 # ### _attachWindowUnload: -> @_unloadHandler = @_handleWindowUnload.bind(@) window.attachEvent 'onunload', @_unloadHandler if window.attachEvent ### # XhrPromise._detachWindowUnload() ### _detachWindowUnload: -> window.detachEvent 'onunload', @_unloadHandler if window.detachEvent ### # XhrPromise._getHeaders() -> Object ### _getHeaders: -> parseHeaders @_xhr.getAllResponseHeaders() ### # XhrPromise._getResponseText() -> Mixed # # Parses response text JSON if present. ### _getResponseText: -> # Accessing binary-data responseText throws an exception in IE9 responseText = if typeof @_xhr.responseText is 'string' then @_xhr.responseText else '' switch @_xhr.getResponseHeader('Content-Type') when 'application/json', 'text/javascript' # Workaround Android 2.3 failure to string-cast null input responseText = JSON.parse(responseText + '') responseText ### # XhrPromise._getResponseUrl() -> String # # Actual response URL after following redirects. ### _getResponseUrl: -> return @_xhr.responseURL if @_xhr.responseURL? # Avoid security warnings on getResponseHeader when not allowed by CORS return @_xhr.getResponseHeader('X-Request-URL') if /^X-Request-URL:/m.test(@_xhr.getAllResponseHeaders()) '' ### # XhrPromise._handleError(reason, reject, status, statusText) # - reason (String) # - reject (Function) # - status (String) # - statusText (String) ### _handleError: (reason, reject, status, statusText) -> @_detachWindowUnload() reject reason: reason status: status or @_xhr.status statusText: statusText or @_xhr.statusText xhr: @_xhr ### # XhrPromise._handleWindowUnload() ### _handleWindowUnload: -> @_xhr.abort() export default XhrPromise
[ { "context": "lbum_key) ->\n if album_key then album_key = \"https://motorbot.io/AlbumArt/\"+album_key+\".png\"\n playlistObj = {\n id:", "end": 6274, "score": 0.8785436749458313, "start": 6243, "tag": "KEY", "value": "https://motorbot.io/AlbumArt/\"+" }, { "context"...
routes/api_routes/playlist.coffee
motorlatitude/MotorBot
4
express = require 'express' router = express.Router() ObjectID = require('mongodb').ObjectID request = require('request') async = require('async') request = require 'request' uid = require('rand-token').uid; async = require 'async' multer = require 'multer' path = require 'path' utilities = require './objects/APIUtilities.coffee' APIUtilities = new utilities() objects = require './objects/APIObjects.coffee' APIObjects = new objects() ### PLAYLIST ENDPOINT https://motorbot.io/api/playlist/ Contains Endpoints: - POST: / - create new playlist - DELETE: /{playlist_id} - delete playlist - PUT: /{playlist_id}/song - add new song from source - GET: /{playlist_id} - get playlist - PATCH: /{playlist_id}/song/{song_id} - add song from song DB - DELETE: /{playlist_id}/song/{song_id} - delete song from playlist Authentication Required: true API Key Required: true ### #API Key & OAuth Checker router.use((req, res, next) -> if !req.query.api_key return res.status(401).send({code: 401, status: "No API Key Supplied"}) else APIAccessCollection = req.app.locals.motorbot.database.collection("apiaccess") APIAccessCollection.find({key: req.query.api_key}).toArray((err, results) -> if err then console.log err if results[0] client_id = results[0].id if req.headers["authorization"] bearerHeader = req.headers["authorization"] if typeof bearerHeader != 'undefined' bearer = bearerHeader.split(" ") bearerToken = bearer[1] accessTokenCollection = req.app.locals.motorbot.database.collection("accessTokens") accessTokenCollection.find({value: bearerToken}).toArray((err, result) -> if err then console.log err if result[0] if client_id == result[0].clientId req.user_id = result[0].userId req.client_id = result[0].clientId return next() else return res.status(401).send({code: 401, status: "Client Unauthorized"}) else return res.status(401).send({code: 401, status: "Unknown Access Token"}) ) else return res.status(401).send({code: 401, status: "No Token Supplied"}) else return res.status(401).send({code: 401, status: "No Token Supplied"}) else return res.status(401).send({code: 401, status: "Unauthorized"}) ) ) insertSongIntoQueue = (req, res, insertionObj, playlist_id) -> songsQueueCollection = req.app.locals.motorbot.database.collection("songQueue") songsQueueCollection.find({status: {$in: ["added","playing"]}}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] addToQueue = false for song in results console.log song if song.playlistId == playlist_id addToQueue = true break; if addToQueue insertionObj.status = "added" insertionObj.songId = insertionObj.id.toString() insertionObj._id = undefined insertionObj.playlistId = playlist_id songsQueueCollection.insert(insertionObj, (err, result) -> if err then console.log err console.log "Added to Song Queue" req.app.locals.motorbot.websocket.broadcast(JSON.stringify(insertionObj)) res.send({added: true}) ) else console.log "Songs in queue don't match altered playlist" req.app.locals.motorbot.websocket.broadcast(JSON.stringify(insertionObj)) res.send({added: true}) else console.log "Queue Empty" req.app.locals.motorbot.websocket.broadcast(JSON.stringify(insertionObj)) res.send({added: true}) ) refreshSpotifyAccessToken = (req, res, next) -> usersCollection = req.app.locals.motorbot.database.collection("users") #this will retrieve my local spotify connection authorization token and get a new token with each request usersCollection.find({id: "95164972807487488"}).toArray((err, result) -> if err then console.log err if result[0].connections if result[0].connections["spotify"] if result[0].connections["spotify"].refresh_token request({ method: "POST", url: "https://accounts.spotify.com/api/token", json: true form: { "grant_type": "refresh_token", "refresh_token": result[0].connections["spotify"].refresh_token }, headers: { "Content-Type": "application/x-www-form-urlencoded" "Authorization": "Basic "+new Buffer("935356234ee749df96a3ab1999e0d659:622b1a10ae054059bd2e5c260d87dabd").toString('base64') } }, (err, httpResponse, body) -> console.log err console.log body if body.access_token usersCollection.find({id: result[0].id}).toArray((err, result) -> if err then console.log err if result[0] usersCollection.update({id: result[0].id},{$set: {"connections.spotify.access_token": body.access_token}}, (err, result) -> if err then console.log err res.locals.spotify_access_token = body.access_token next() ) else console.log "User doesn't exist" res.locals.spotify_access_token = body.access_token next() ) else console.log "No Access Token was returned" next() ) else next() else next() else next() ) router.post("/", (req, res) -> res.type("json") user_id = req.user_id playlistsCollection = req.app.locals.motorbot.database.collection("playlists") usersCollection = req.app.locals.motorbot.database.collection("users") playlist_id = uid(32); if req.body.playlist_name uploadRemainingData = (album_key) -> if album_key then album_key = "https://motorbot.io/AlbumArt/"+album_key+".png" playlistObj = { id: playlist_id name: req.body.playlist_name description: req.body.playlist_description || "" songs: [] creator: user_id create_date: new Date().getTime() followers: [user_id] artwork: album_key || "" private: req.body.private || false collaborative: req.body.collaborative || false } playlistsCollection.insertOne(playlistObj, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) usersCollection.find({id: user_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] playlists = results[0].playlists playlists.push(playlist_id) usersCollection.update({id: user_id},{$set: {playlists: playlists}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) console.log playlistObj res.send(playlistObj) ) ) ) if req.body.playlist_artwork console.log "Album Art Detected" albumart_key = uid(20); req_albumartContent = req.body.playlist_artwork.replace(/^data:([A-Za-z-+/]+);base64,/, '') require("fs").writeFile(path.join(__dirname, '../../static/AlbumArt/')+albumart_key+".png", req_albumartContent, 'base64', (err) -> if err then console.log(err) console.log "Album Art Uploaded" uploadRemainingData(albumart_key) ) else console.log("No Album Art Detected") uploadRemainingData() else res.send({error: "crap", message:"Incorrectly Formatted Requested"}) ) convertTimestampToSeconds = (input) -> reptms = /^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/ hours = 0 minutes = 0 seconds = 0 if reptms.test(input) matches = reptms.exec(input) if (matches[1]) then hours = Number(matches[1]) if (matches[2]) then minutes = Number(matches[2]) if (matches[3]) then seconds = Number(matches[3]) return hours*60*60+minutes*60+seconds; router.put("/:playlist_id/song", refreshSpotifyAccessToken, (req, res) -> #from source so add to Songs DB res.type("json") if req.user_id console.log "PUT new song from source" console.log req.body #vars source = req.body.source video_id = req.body.video_id song_id = req.body.song_id playlist_id = req.params.playlist_id user_id = req.user_id #Collections tracksCollection = req.app.locals.motorbot.database.collection("tracks") playlistsCollection = req.app.locals.motorbot.database.collection("playlists") if source == "ytb" tracksCollection.find({video_id: video_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] #song already in tracksCollection insertionObj = results[0] insertionObj.type = "trackAdded" insertionObj.playlistId = playlist_id song_obj = { id: insertionObj.id date_added: new Date().getTime() play_count: 0 last_played: undefined } playlistsCollection.find({"id":playlist_id, "creator": user_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] playlist = results[0] if playlist.artwork == "" && insertionObj.artwork != "" #update playlist artwork playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}, "$set": {artwork: insertionObj.artwork}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else return res.status(404).send({code: 404, status: "Playlist Not Found"}) ) else #insert song from source console.log("Spotify Authorization Code: "+res.locals.spotify_access_token) request.get({ url: "https://www.googleapis.com/youtube/v3/videos?id="+video_id+"&key=AIzaSyAyoWcB_yzEqESeJm-W_eC5QDcOu5R1M90&part=snippet,contentDetails", json: true }, (err, httpResponse, data) -> if err then return res.status(500).send({code: 500, status: "Youtube API Error", error: err}) if data.items[0] modifiedTitle = data.items[0].snippet.title.replace(/\[((?!.*?Remix))[^\)]*\]/gmi, '').replace(/\(((?!.*?Remix))[^\)]*\)/gmi, '').replace(/\-(\s|)[0-9]*(\s|)\-/g, '').replace(/(\s|)-(\s|)/gmi," ").replace(/(\sI\s|\s:\s)/gmi, " ").replace(/\sFrom\s(.*)\/(|\s)Soundtrack/gmi, "").replace(/(high\squality|\sOST|playlist|\sHD|\sHQ|\s1080p|\s720p|ft\.|feat\.|ft\s|lyrics|official\svideo|\"|official|video|:|\/Soundtrack\sVersion|\/Soundtrack|\||w\/|\/)/gmi, '') modifiedTitle = encodeURIComponent(modifiedTitle.trim()) console.log modifiedTitle request.get({ url: "https://api.spotify.com/v1/search?type=track&q=" + modifiedTitle, json: true, headers: { "Authorization": "Bearer "+res.locals.spotify_access_token } }, (err, httpResponse, body) -> if err then return res.status(500).send({code: 500, status: "Spotify API Error", error: err}) else artist = {} album = {} composer = {} album_artist = {} title = decodeURIComponent(modifiedTitle) genres = [] release_date = undefined track_number = 0 disc_number = 0 artwork = "" explicit = false if body.tracks if body.tracks.items[0] if body.tracks.items[0].artists[0] id = new Buffer(body.tracks.items[0].artists[0].name, 'base64') artist = { name: body.tracks.items[0].artists[0].name, id: id.toString('hex') } if body.tracks.items[0].album id = new Buffer(body.tracks.items[0].album.name, 'base64') album_artwork = "" if body.tracks.items[0].album.images[0] then album_artwork = body.tracks.items[0].album.images[0].url artwork = album_artwork album = { name: body.tracks.items[0].album.name, artwork: album_artwork id: id.toString('hex') } if body.tracks.items[0].album.artists[0] id = new Buffer(body.tracks.items[0].album.artists[0].name, 'base64') album_artist = { name: body.tracks.items[0].album.artists[0].name, id: id.toString('hex') } title = body.tracks.items[0].name.replace(/\[((?!.*?Remix))[^\)]*\]/gmi, '').replace(/\(((?!.*?Remix))[^\)]*\)/gmi, '').replace(/\-(\s|)[0-9]*(\s|)\-/g, '').replace(/(\s|)-(\s|)/gmi," ").replace(/\sFrom\s(.*)\/(|\s)Soundtrack/gmi, "").replace(/(high\squality|\sOST|playlist|\sHD|\sHQ|\s1080p|ft\.|feat\.|ft\s|lyrics|official\svideo|\"|official|video|:|\/Soundtrack\sVersion|\/Soundtrack|\||w\/|\/)/gmi, '') track_number = Number(body.tracks.items[0].track_number) disc_number = Number(body.tracks.items[0].disc_number) explicit = body.tracks.items[0].explicit track_id = uid(32) track_obj = { id: track_id, type: "youtube", video_id: video_id, video_title: data.items[0].snippet.title, title: title, artist: artist, album: album, composer: composer, album_artist: album_artist genres: genres, duration: convertTimestampToSeconds(data.items[0].contentDetails.duration), import_date: new Date().getTime(), release_date: release_date, track_number: track_number, disc_number: disc_number, play_count: 0, artwork: artwork, explicit: explicit lyrics: "", user_id: user_id, } tracksCollection.insertOne(track_obj, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) else insertionObj = track_obj insertionObj.type = "trackAdded" insertionObj.playlistId = playlist_id song_obj = { id: insertionObj.id date_added: new Date().getTime() play_count: 0 last_played: undefined } #add to playlist playlistsCollection.find({"id":playlist_id,"creator":user_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] playlist = results[0] if playlist.artwork == "" && insertionObj.artwork != "" #update playlist artwork playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}, "$set": {artwork: insertionObj.artwork}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else return res.status(404).send({code: 404, status: "Playlist Not Found"}) ) ) ) else return res.status(404).send({code: 404, status: "Youtube API Error", error: "Video Not Found"}) ) ) else if source == "scd" tracksCollection.find({soundcloud_id: video_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] #song already in the database insertionObj = results[0] insertionObj.type = "trackAdded" insertionObj.playlistId = playlist_id song_obj = { id: insertionObj.id date_added: new Date().getTime() play_count: 0 last_played: undefined } playlistsCollection.find({"id":playlist_id, "creator": user_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] playlist = results[0] if playlist.artwork == "" && insertionObj.artwork != "" #update playlist artwork playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}, "$set": {artwork: insertionObj.artwork}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else return res.status(404).send({code: 404, status: "Playlist Not Found"}) ) else #insert song from source ) else return res.status(429).send({code: 429, status: "Unauthorized"}) ) router.patch("/:playlist_id/song/:song_id", (req, res) -> #add song from another playlist or song DB transfer playlist_id = req.params.playlist_id song_id = req.params.song_id playlistCollection = req.app.locals.motorbot.database.collection("playlists") tracksCollection = req.app.locals.motorbot.database.collection("tracks") playlistCollection.find({id: playlist_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] playlist = results[0] tracksCollection.find({id: song_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] song_obj = { id: song_id date_added: new Date().getTime() play_count: 0 last_played: undefined } if playlist.artwork == "" && results[0].artwork != "" playlistCollection.update({id: playlist_id},{$push: {songs: song_obj}, $set: {artwork: results[0].artwork}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) return res.status(200).send({code: 200, status: "OKAY"}) ) else playlistCollection.update({id: playlist_id},{$push: {songs: song_obj}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) return res.status(200).send({code: 200, status: "OKAY"}) ) else return res.status(404).send({code: 404, status: "Unknown Song"}) ) else return res.status(404).send({code: 404, status: "Unknown Playlist"}) ) ) router.delete("/:playlist_id", (req, res) -> playlistsCollection = req.app.locals.motorbot.database.collection("playlists") usersCollection = req.app.locals.motorbot.database.collection("users") user_id = req.user_id playlist_id = req.params.playlist_id playlistsCollection.remove({"id": playlist_id, "creator": user_id}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) else console.log result.result.n if result.result.n == 1 usersCollection.update({}, {"$pull":{"playlists": playlist_id}}, {multi: true}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) else res.send({"status": 200,"message":"OKAY"}) ) else return res.status(404).send({code: 404, status: "Playlist Not Found For User"}) ) ) router.get("/:playlist_id", (req, res) -> if req.user_id filter = APIUtilities.formatFilterForMongo(req.query.filter) APIObjects.playlist(req).playlistById(req.params.playlist_id.toString(), filter).then((playlist) -> async.parallel([ (asyncParallelComplete) -> if playlist.creator APIObjects.user(req).userById(playlist.creator, {username: 1, discriminator: 1}).then((user) -> playlist["owner"] = user asyncParallelComplete() ).catch((error_obj) -> asyncParallelComplete(error_obj) ) else asyncParallelComplete({error: "PLAYLIST_FORMAT", message: "Unknown playlist format, (playlist is missing an owner)"}) ,(asyncParallelComplete) -> if playlist.songs #return complete song objects for the first 50 tracks, further tracks should be retrieved from the /track endpoint songs = playlist.songs.slice(0,100) songIds = [] songsFinal = {} for song in songs songIds.push(song.id) songsFinal[song.id] = song #store user variables delete songsFinal[song.id].id APIObjects.track(req).tracksForIds(songIds, {}).then((tracks) -> tracks_obj = [] for track in tracks t = {} t = songsFinal[track.id] t["track"] = track tracks_obj.push(t) playlist["tracks"] = APIObjects.pagination().paginate("/playlist/"+req.params.playlist_id+"/tracks", tracks_obj, playlist.songs.length, 0, 100) delete playlist.songs asyncParallelComplete() ).catch((error_obj) -> asyncParallelComplete(error_obj) ) else # No songs in this playlist console.log "PLAYLIST_EMPTY: Playlist contains no songs" asyncParallelComplete() ], (error_obj) -> if error_obj res.type("json") res.send(JSON.stringify(error_obj)) else res.type("json") res.send(JSON.stringify(playlist)) ) ).catch((error_obj) -> res.type("json") res.send(JSON.stringify(error_obj)) ) else return res.status(401).send({code: 401, status: "Unauthorized"}) ) router.get("/:playlist_id/tracks", (req, res) -> if req.user_id APIObjects.playlist(req).playlistById(req.params.playlist_id.toString(), {songs: 1}).then((playlist) -> if playlist.songs #return complete song objects for the first 50 tracks, further tracks should be retrieved from the /track endpoint limit = parseInt(req.query.limit) || 100 offset = parseInt(req.query.offset) || 0 if limit < 1 limit = 1 else if limit > 100 limit = 100 songs = playlist.songs.slice(offset,(offset + limit)) songIds = [] songsFinal = {} for song in songs songIds.push(song.id) songsFinal[song.id] = song #store user variables delete songsFinal[song.id].id APIObjects.track(req).tracksForIds(songIds).then((tracks) -> tracks_obj = [] for track in tracks t = {} t = songsFinal[track.id] t["track"] = track tracks_obj.push(t) finalTracks = APIObjects.pagination().paginate("/playlist/"+req.params.playlist_id+"/tracks", tracks_obj, playlist.songs.length, offset, limit) finalTracks = APIUtilities.filterResponse(finalTracks,req.query.filter) res.type("json") res.send(JSON.stringify(finalTracks)) ).catch((error_obj) -> ) else # No songs in this playlist console.log "PLAYLIST_EMPTY: Playlist contains no songs" ).catch((error_obj) -> res.type("json") res.send(JSON.stringify(error_obj)) ) else return res.status(401).send({code: 401, status: "Unauthorized"}) ) router.delete("/:playlist_id/song/:song_id", (req, res) -> playlistCollection = req.app.locals.motorbot.database.collection("playlists") tracksCollection = req.app.locals.motorbot.database.collection("tracks") songQueueCollection = req.app.locals.motorbot.database.collection("songQueue") playlist_id = req.params.playlist_id song_id = req.params.song_id user_id = req.user_id res.type("json") if user_id playlistCollection.find({id: playlist_id, creator: user_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) if results[0] playlist = results[0] tracksCollection.find({id: song_id}).toArray((err, result) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) else if result[0].artwork == playlist.artwork new_albumart = "" tracksCollection.find({id: {$in: playlist.songs}}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) for song in results if song.id.toString() != song_id.toString() && song.artwork != "" new_albumart = song.artwork break; console.log "New Album Art Set: "+new_albumart playlistCollection.update({id: playlist_id},{$pull: {songs: {id: song_id}}, $set: {artwork: new_albumart}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) res.status(200).send({code: 200, status: "OKAY"}) req.app.locals.motorbot.websocket.broadcast(JSON.stringify({type: 'trackDelete', songId: song_id, playlistId: playlist_id, newAlbumArt: new_albumart})) songQueueCollection.remove({songId: song_id.toString(), playlistId: playlist_id}, (err, results) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) #wss event for queue ) ) ) else playlistCollection.update({id: playlist_id},{$pull: {songs: {id: song_id}}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) res.status(200).send({code: 200, status: "OKAY"}) req.app.locals.motorbot.websocket.broadcast(JSON.stringify({type: 'trackDelete', songId: song_id, playlistId: playlist_id})) songQueueCollection.remove({songId: song_id.toString(), playlistId: playlist_id}, (err, results) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) #wss event for queue ) ) ) else return res.status(404).send({code: 404, status: "Playlist Not Found"}) ) else return res.status(429).send({code: 429, status: "Unauthorized"}) ) module.exports = router
90057
express = require 'express' router = express.Router() ObjectID = require('mongodb').ObjectID request = require('request') async = require('async') request = require 'request' uid = require('rand-token').uid; async = require 'async' multer = require 'multer' path = require 'path' utilities = require './objects/APIUtilities.coffee' APIUtilities = new utilities() objects = require './objects/APIObjects.coffee' APIObjects = new objects() ### PLAYLIST ENDPOINT https://motorbot.io/api/playlist/ Contains Endpoints: - POST: / - create new playlist - DELETE: /{playlist_id} - delete playlist - PUT: /{playlist_id}/song - add new song from source - GET: /{playlist_id} - get playlist - PATCH: /{playlist_id}/song/{song_id} - add song from song DB - DELETE: /{playlist_id}/song/{song_id} - delete song from playlist Authentication Required: true API Key Required: true ### #API Key & OAuth Checker router.use((req, res, next) -> if !req.query.api_key return res.status(401).send({code: 401, status: "No API Key Supplied"}) else APIAccessCollection = req.app.locals.motorbot.database.collection("apiaccess") APIAccessCollection.find({key: req.query.api_key}).toArray((err, results) -> if err then console.log err if results[0] client_id = results[0].id if req.headers["authorization"] bearerHeader = req.headers["authorization"] if typeof bearerHeader != 'undefined' bearer = bearerHeader.split(" ") bearerToken = bearer[1] accessTokenCollection = req.app.locals.motorbot.database.collection("accessTokens") accessTokenCollection.find({value: bearerToken}).toArray((err, result) -> if err then console.log err if result[0] if client_id == result[0].clientId req.user_id = result[0].userId req.client_id = result[0].clientId return next() else return res.status(401).send({code: 401, status: "Client Unauthorized"}) else return res.status(401).send({code: 401, status: "Unknown Access Token"}) ) else return res.status(401).send({code: 401, status: "No Token Supplied"}) else return res.status(401).send({code: 401, status: "No Token Supplied"}) else return res.status(401).send({code: 401, status: "Unauthorized"}) ) ) insertSongIntoQueue = (req, res, insertionObj, playlist_id) -> songsQueueCollection = req.app.locals.motorbot.database.collection("songQueue") songsQueueCollection.find({status: {$in: ["added","playing"]}}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] addToQueue = false for song in results console.log song if song.playlistId == playlist_id addToQueue = true break; if addToQueue insertionObj.status = "added" insertionObj.songId = insertionObj.id.toString() insertionObj._id = undefined insertionObj.playlistId = playlist_id songsQueueCollection.insert(insertionObj, (err, result) -> if err then console.log err console.log "Added to Song Queue" req.app.locals.motorbot.websocket.broadcast(JSON.stringify(insertionObj)) res.send({added: true}) ) else console.log "Songs in queue don't match altered playlist" req.app.locals.motorbot.websocket.broadcast(JSON.stringify(insertionObj)) res.send({added: true}) else console.log "Queue Empty" req.app.locals.motorbot.websocket.broadcast(JSON.stringify(insertionObj)) res.send({added: true}) ) refreshSpotifyAccessToken = (req, res, next) -> usersCollection = req.app.locals.motorbot.database.collection("users") #this will retrieve my local spotify connection authorization token and get a new token with each request usersCollection.find({id: "95164972807487488"}).toArray((err, result) -> if err then console.log err if result[0].connections if result[0].connections["spotify"] if result[0].connections["spotify"].refresh_token request({ method: "POST", url: "https://accounts.spotify.com/api/token", json: true form: { "grant_type": "refresh_token", "refresh_token": result[0].connections["spotify"].refresh_token }, headers: { "Content-Type": "application/x-www-form-urlencoded" "Authorization": "Basic "+new Buffer("935356234ee749df96a3ab1999e0d659:622b1a10ae054059bd2e5c260d87dabd").toString('base64') } }, (err, httpResponse, body) -> console.log err console.log body if body.access_token usersCollection.find({id: result[0].id}).toArray((err, result) -> if err then console.log err if result[0] usersCollection.update({id: result[0].id},{$set: {"connections.spotify.access_token": body.access_token}}, (err, result) -> if err then console.log err res.locals.spotify_access_token = body.access_token next() ) else console.log "User doesn't exist" res.locals.spotify_access_token = body.access_token next() ) else console.log "No Access Token was returned" next() ) else next() else next() else next() ) router.post("/", (req, res) -> res.type("json") user_id = req.user_id playlistsCollection = req.app.locals.motorbot.database.collection("playlists") usersCollection = req.app.locals.motorbot.database.collection("users") playlist_id = uid(32); if req.body.playlist_name uploadRemainingData = (album_key) -> if album_key then album_key = "<KEY>album_key+".<KEY>" playlistObj = { id: playlist_id name: req.body.playlist_name description: req.body.playlist_description || "" songs: [] creator: user_id create_date: new Date().getTime() followers: [user_id] artwork: album_key || "" private: req.body.private || false collaborative: req.body.collaborative || false } playlistsCollection.insertOne(playlistObj, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) usersCollection.find({id: user_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] playlists = results[0].playlists playlists.push(playlist_id) usersCollection.update({id: user_id},{$set: {playlists: playlists}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) console.log playlistObj res.send(playlistObj) ) ) ) if req.body.playlist_artwork console.log "Album Art Detected" albumart_key = <KEY>); req_albumartContent = req.body.playlist_artwork.replace(/^data:([A-Za-z-+/]+);base64,/, '') require("fs").writeFile(path.join(__dirname, '../../static/AlbumArt/')+albumart_key+".png", req_albumartContent, 'base64', (err) -> if err then console.log(err) console.log "Album Art Uploaded" uploadRemainingData(albumart_key) ) else console.log("No Album Art Detected") uploadRemainingData() else res.send({error: "crap", message:"Incorrectly Formatted Requested"}) ) convertTimestampToSeconds = (input) -> reptms = /^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/ hours = 0 minutes = 0 seconds = 0 if reptms.test(input) matches = reptms.exec(input) if (matches[1]) then hours = Number(matches[1]) if (matches[2]) then minutes = Number(matches[2]) if (matches[3]) then seconds = Number(matches[3]) return hours*60*60+minutes*60+seconds; router.put("/:playlist_id/song", refreshSpotifyAccessToken, (req, res) -> #from source so add to Songs DB res.type("json") if req.user_id console.log "PUT new song from source" console.log req.body #vars source = req.body.source video_id = req.body.video_id song_id = req.body.song_id playlist_id = req.params.playlist_id user_id = req.user_id #Collections tracksCollection = req.app.locals.motorbot.database.collection("tracks") playlistsCollection = req.app.locals.motorbot.database.collection("playlists") if source == "ytb" tracksCollection.find({video_id: video_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] #song already in tracksCollection insertionObj = results[0] insertionObj.type = "trackAdded" insertionObj.playlistId = playlist_id song_obj = { id: insertionObj.id date_added: new Date().getTime() play_count: 0 last_played: undefined } playlistsCollection.find({"id":playlist_id, "creator": user_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] playlist = results[0] if playlist.artwork == "" && insertionObj.artwork != "" #update playlist artwork playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}, "$set": {artwork: insertionObj.artwork}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else return res.status(404).send({code: 404, status: "Playlist Not Found"}) ) else #insert song from source console.log("Spotify Authorization Code: "+res.locals.spotify_access_token) request.get({ url: "https://www.googleapis.com/youtube/v3/videos?id="+video_id+"&key=<KEY>&part=snippet,contentDetails", json: true }, (err, httpResponse, data) -> if err then return res.status(500).send({code: 500, status: "Youtube API Error", error: err}) if data.items[0] modifiedTitle = data.items[0].snippet.title.replace(/\[((?!.*?Remix))[^\)]*\]/gmi, '').replace(/\(((?!.*?Remix))[^\)]*\)/gmi, '').replace(/\-(\s|)[0-9]*(\s|)\-/g, '').replace(/(\s|)-(\s|)/gmi," ").replace(/(\sI\s|\s:\s)/gmi, " ").replace(/\sFrom\s(.*)\/(|\s)Soundtrack/gmi, "").replace(/(high\squality|\sOST|playlist|\sHD|\sHQ|\s1080p|\s720p|ft\.|feat\.|ft\s|lyrics|official\svideo|\"|official|video|:|\/Soundtrack\sVersion|\/Soundtrack|\||w\/|\/)/gmi, '') modifiedTitle = encodeURIComponent(modifiedTitle.trim()) console.log modifiedTitle request.get({ url: "https://api.spotify.com/v1/search?type=track&q=" + modifiedTitle, json: true, headers: { "Authorization": "Bearer "+res.locals.spotify_access_token } }, (err, httpResponse, body) -> if err then return res.status(500).send({code: 500, status: "Spotify API Error", error: err}) else artist = {} album = {} composer = {} album_artist = {} title = decodeURIComponent(modifiedTitle) genres = [] release_date = undefined track_number = 0 disc_number = 0 artwork = "" explicit = false if body.tracks if body.tracks.items[0] if body.tracks.items[0].artists[0] id = new Buffer(body.tracks.items[0].artists[0].name, 'base64') artist = { name: body.tracks.items[0].artists[0].name, id: id.toString('hex') } if body.tracks.items[0].album id = new Buffer(body.tracks.items[0].album.name, 'base64') album_artwork = "" if body.tracks.items[0].album.images[0] then album_artwork = body.tracks.items[0].album.images[0].url artwork = album_artwork album = { name: body.tracks.items[0].album.name, artwork: album_artwork id: id.toString('hex') } if body.tracks.items[0].album.artists[0] id = new Buffer(body.tracks.items[0].album.artists[0].name, 'base64') album_artist = { name: body.tracks.items[0].album.artists[0].name, id: id.toString('hex') } title = body.tracks.items[0].name.replace(/\[((?!.*?Remix))[^\)]*\]/gmi, '').replace(/\(((?!.*?Remix))[^\)]*\)/gmi, '').replace(/\-(\s|)[0-9]*(\s|)\-/g, '').replace(/(\s|)-(\s|)/gmi," ").replace(/\sFrom\s(.*)\/(|\s)Soundtrack/gmi, "").replace(/(high\squality|\sOST|playlist|\sHD|\sHQ|\s1080p|ft\.|feat\.|ft\s|lyrics|official\svideo|\"|official|video|:|\/Soundtrack\sVersion|\/Soundtrack|\||w\/|\/)/gmi, '') track_number = Number(body.tracks.items[0].track_number) disc_number = Number(body.tracks.items[0].disc_number) explicit = body.tracks.items[0].explicit track_id = uid(32) track_obj = { id: track_id, type: "youtube", video_id: video_id, video_title: data.items[0].snippet.title, title: title, artist: artist, album: album, composer: composer, album_artist: album_artist genres: genres, duration: convertTimestampToSeconds(data.items[0].contentDetails.duration), import_date: new Date().getTime(), release_date: release_date, track_number: track_number, disc_number: disc_number, play_count: 0, artwork: artwork, explicit: explicit lyrics: "", user_id: user_id, } tracksCollection.insertOne(track_obj, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) else insertionObj = track_obj insertionObj.type = "trackAdded" insertionObj.playlistId = playlist_id song_obj = { id: insertionObj.id date_added: new Date().getTime() play_count: 0 last_played: undefined } #add to playlist playlistsCollection.find({"id":playlist_id,"creator":user_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] playlist = results[0] if playlist.artwork == "" && insertionObj.artwork != "" #update playlist artwork playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}, "$set": {artwork: insertionObj.artwork}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else return res.status(404).send({code: 404, status: "Playlist Not Found"}) ) ) ) else return res.status(404).send({code: 404, status: "Youtube API Error", error: "Video Not Found"}) ) ) else if source == "scd" tracksCollection.find({soundcloud_id: video_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] #song already in the database insertionObj = results[0] insertionObj.type = "trackAdded" insertionObj.playlistId = playlist_id song_obj = { id: insertionObj.id date_added: new Date().getTime() play_count: 0 last_played: undefined } playlistsCollection.find({"id":playlist_id, "creator": user_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] playlist = results[0] if playlist.artwork == "" && insertionObj.artwork != "" #update playlist artwork playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}, "$set": {artwork: insertionObj.artwork}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else return res.status(404).send({code: 404, status: "Playlist Not Found"}) ) else #insert song from source ) else return res.status(429).send({code: 429, status: "Unauthorized"}) ) router.patch("/:playlist_id/song/:song_id", (req, res) -> #add song from another playlist or song DB transfer playlist_id = req.params.playlist_id song_id = req.params.song_id playlistCollection = req.app.locals.motorbot.database.collection("playlists") tracksCollection = req.app.locals.motorbot.database.collection("tracks") playlistCollection.find({id: playlist_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] playlist = results[0] tracksCollection.find({id: song_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] song_obj = { id: song_id date_added: new Date().getTime() play_count: 0 last_played: undefined } if playlist.artwork == "" && results[0].artwork != "" playlistCollection.update({id: playlist_id},{$push: {songs: song_obj}, $set: {artwork: results[0].artwork}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) return res.status(200).send({code: 200, status: "OKAY"}) ) else playlistCollection.update({id: playlist_id},{$push: {songs: song_obj}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) return res.status(200).send({code: 200, status: "OKAY"}) ) else return res.status(404).send({code: 404, status: "Unknown Song"}) ) else return res.status(404).send({code: 404, status: "Unknown Playlist"}) ) ) router.delete("/:playlist_id", (req, res) -> playlistsCollection = req.app.locals.motorbot.database.collection("playlists") usersCollection = req.app.locals.motorbot.database.collection("users") user_id = req.user_id playlist_id = req.params.playlist_id playlistsCollection.remove({"id": playlist_id, "creator": user_id}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) else console.log result.result.n if result.result.n == 1 usersCollection.update({}, {"$pull":{"playlists": playlist_id}}, {multi: true}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) else res.send({"status": 200,"message":"OKAY"}) ) else return res.status(404).send({code: 404, status: "Playlist Not Found For User"}) ) ) router.get("/:playlist_id", (req, res) -> if req.user_id filter = APIUtilities.formatFilterForMongo(req.query.filter) APIObjects.playlist(req).playlistById(req.params.playlist_id.toString(), filter).then((playlist) -> async.parallel([ (asyncParallelComplete) -> if playlist.creator APIObjects.user(req).userById(playlist.creator, {username: 1, discriminator: 1}).then((user) -> playlist["owner"] = user asyncParallelComplete() ).catch((error_obj) -> asyncParallelComplete(error_obj) ) else asyncParallelComplete({error: "PLAYLIST_FORMAT", message: "Unknown playlist format, (playlist is missing an owner)"}) ,(asyncParallelComplete) -> if playlist.songs #return complete song objects for the first 50 tracks, further tracks should be retrieved from the /track endpoint songs = playlist.songs.slice(0,100) songIds = [] songsFinal = {} for song in songs songIds.push(song.id) songsFinal[song.id] = song #store user variables delete songsFinal[song.id].id APIObjects.track(req).tracksForIds(songIds, {}).then((tracks) -> tracks_obj = [] for track in tracks t = {} t = songsFinal[track.id] t["track"] = track tracks_obj.push(t) playlist["tracks"] = APIObjects.pagination().paginate("/playlist/"+req.params.playlist_id+"/tracks", tracks_obj, playlist.songs.length, 0, 100) delete playlist.songs asyncParallelComplete() ).catch((error_obj) -> asyncParallelComplete(error_obj) ) else # No songs in this playlist console.log "PLAYLIST_EMPTY: Playlist contains no songs" asyncParallelComplete() ], (error_obj) -> if error_obj res.type("json") res.send(JSON.stringify(error_obj)) else res.type("json") res.send(JSON.stringify(playlist)) ) ).catch((error_obj) -> res.type("json") res.send(JSON.stringify(error_obj)) ) else return res.status(401).send({code: 401, status: "Unauthorized"}) ) router.get("/:playlist_id/tracks", (req, res) -> if req.user_id APIObjects.playlist(req).playlistById(req.params.playlist_id.toString(), {songs: 1}).then((playlist) -> if playlist.songs #return complete song objects for the first 50 tracks, further tracks should be retrieved from the /track endpoint limit = parseInt(req.query.limit) || 100 offset = parseInt(req.query.offset) || 0 if limit < 1 limit = 1 else if limit > 100 limit = 100 songs = playlist.songs.slice(offset,(offset + limit)) songIds = [] songsFinal = {} for song in songs songIds.push(song.id) songsFinal[song.id] = song #store user variables delete songsFinal[song.id].id APIObjects.track(req).tracksForIds(songIds).then((tracks) -> tracks_obj = [] for track in tracks t = {} t = songsFinal[track.id] t["track"] = track tracks_obj.push(t) finalTracks = APIObjects.pagination().paginate("/playlist/"+req.params.playlist_id+"/tracks", tracks_obj, playlist.songs.length, offset, limit) finalTracks = APIUtilities.filterResponse(finalTracks,req.query.filter) res.type("json") res.send(JSON.stringify(finalTracks)) ).catch((error_obj) -> ) else # No songs in this playlist console.log "PLAYLIST_EMPTY: Playlist contains no songs" ).catch((error_obj) -> res.type("json") res.send(JSON.stringify(error_obj)) ) else return res.status(401).send({code: 401, status: "Unauthorized"}) ) router.delete("/:playlist_id/song/:song_id", (req, res) -> playlistCollection = req.app.locals.motorbot.database.collection("playlists") tracksCollection = req.app.locals.motorbot.database.collection("tracks") songQueueCollection = req.app.locals.motorbot.database.collection("songQueue") playlist_id = req.params.playlist_id song_id = req.params.song_id user_id = req.user_id res.type("json") if user_id playlistCollection.find({id: playlist_id, creator: user_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) if results[0] playlist = results[0] tracksCollection.find({id: song_id}).toArray((err, result) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) else if result[0].artwork == playlist.artwork new_albumart = "" tracksCollection.find({id: {$in: playlist.songs}}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) for song in results if song.id.toString() != song_id.toString() && song.artwork != "" new_albumart = song.artwork break; console.log "New Album Art Set: "+new_albumart playlistCollection.update({id: playlist_id},{$pull: {songs: {id: song_id}}, $set: {artwork: new_albumart}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) res.status(200).send({code: 200, status: "OKAY"}) req.app.locals.motorbot.websocket.broadcast(JSON.stringify({type: 'trackDelete', songId: song_id, playlistId: playlist_id, newAlbumArt: new_albumart})) songQueueCollection.remove({songId: song_id.toString(), playlistId: playlist_id}, (err, results) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) #wss event for queue ) ) ) else playlistCollection.update({id: playlist_id},{$pull: {songs: {id: song_id}}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) res.status(200).send({code: 200, status: "OKAY"}) req.app.locals.motorbot.websocket.broadcast(JSON.stringify({type: 'trackDelete', songId: song_id, playlistId: playlist_id})) songQueueCollection.remove({songId: song_id.toString(), playlistId: playlist_id}, (err, results) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) #wss event for queue ) ) ) else return res.status(404).send({code: 404, status: "Playlist Not Found"}) ) else return res.status(429).send({code: 429, status: "Unauthorized"}) ) module.exports = router
true
express = require 'express' router = express.Router() ObjectID = require('mongodb').ObjectID request = require('request') async = require('async') request = require 'request' uid = require('rand-token').uid; async = require 'async' multer = require 'multer' path = require 'path' utilities = require './objects/APIUtilities.coffee' APIUtilities = new utilities() objects = require './objects/APIObjects.coffee' APIObjects = new objects() ### PLAYLIST ENDPOINT https://motorbot.io/api/playlist/ Contains Endpoints: - POST: / - create new playlist - DELETE: /{playlist_id} - delete playlist - PUT: /{playlist_id}/song - add new song from source - GET: /{playlist_id} - get playlist - PATCH: /{playlist_id}/song/{song_id} - add song from song DB - DELETE: /{playlist_id}/song/{song_id} - delete song from playlist Authentication Required: true API Key Required: true ### #API Key & OAuth Checker router.use((req, res, next) -> if !req.query.api_key return res.status(401).send({code: 401, status: "No API Key Supplied"}) else APIAccessCollection = req.app.locals.motorbot.database.collection("apiaccess") APIAccessCollection.find({key: req.query.api_key}).toArray((err, results) -> if err then console.log err if results[0] client_id = results[0].id if req.headers["authorization"] bearerHeader = req.headers["authorization"] if typeof bearerHeader != 'undefined' bearer = bearerHeader.split(" ") bearerToken = bearer[1] accessTokenCollection = req.app.locals.motorbot.database.collection("accessTokens") accessTokenCollection.find({value: bearerToken}).toArray((err, result) -> if err then console.log err if result[0] if client_id == result[0].clientId req.user_id = result[0].userId req.client_id = result[0].clientId return next() else return res.status(401).send({code: 401, status: "Client Unauthorized"}) else return res.status(401).send({code: 401, status: "Unknown Access Token"}) ) else return res.status(401).send({code: 401, status: "No Token Supplied"}) else return res.status(401).send({code: 401, status: "No Token Supplied"}) else return res.status(401).send({code: 401, status: "Unauthorized"}) ) ) insertSongIntoQueue = (req, res, insertionObj, playlist_id) -> songsQueueCollection = req.app.locals.motorbot.database.collection("songQueue") songsQueueCollection.find({status: {$in: ["added","playing"]}}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] addToQueue = false for song in results console.log song if song.playlistId == playlist_id addToQueue = true break; if addToQueue insertionObj.status = "added" insertionObj.songId = insertionObj.id.toString() insertionObj._id = undefined insertionObj.playlistId = playlist_id songsQueueCollection.insert(insertionObj, (err, result) -> if err then console.log err console.log "Added to Song Queue" req.app.locals.motorbot.websocket.broadcast(JSON.stringify(insertionObj)) res.send({added: true}) ) else console.log "Songs in queue don't match altered playlist" req.app.locals.motorbot.websocket.broadcast(JSON.stringify(insertionObj)) res.send({added: true}) else console.log "Queue Empty" req.app.locals.motorbot.websocket.broadcast(JSON.stringify(insertionObj)) res.send({added: true}) ) refreshSpotifyAccessToken = (req, res, next) -> usersCollection = req.app.locals.motorbot.database.collection("users") #this will retrieve my local spotify connection authorization token and get a new token with each request usersCollection.find({id: "95164972807487488"}).toArray((err, result) -> if err then console.log err if result[0].connections if result[0].connections["spotify"] if result[0].connections["spotify"].refresh_token request({ method: "POST", url: "https://accounts.spotify.com/api/token", json: true form: { "grant_type": "refresh_token", "refresh_token": result[0].connections["spotify"].refresh_token }, headers: { "Content-Type": "application/x-www-form-urlencoded" "Authorization": "Basic "+new Buffer("935356234ee749df96a3ab1999e0d659:622b1a10ae054059bd2e5c260d87dabd").toString('base64') } }, (err, httpResponse, body) -> console.log err console.log body if body.access_token usersCollection.find({id: result[0].id}).toArray((err, result) -> if err then console.log err if result[0] usersCollection.update({id: result[0].id},{$set: {"connections.spotify.access_token": body.access_token}}, (err, result) -> if err then console.log err res.locals.spotify_access_token = body.access_token next() ) else console.log "User doesn't exist" res.locals.spotify_access_token = body.access_token next() ) else console.log "No Access Token was returned" next() ) else next() else next() else next() ) router.post("/", (req, res) -> res.type("json") user_id = req.user_id playlistsCollection = req.app.locals.motorbot.database.collection("playlists") usersCollection = req.app.locals.motorbot.database.collection("users") playlist_id = uid(32); if req.body.playlist_name uploadRemainingData = (album_key) -> if album_key then album_key = "PI:KEY:<KEY>END_PIalbum_key+".PI:KEY:<KEY>END_PI" playlistObj = { id: playlist_id name: req.body.playlist_name description: req.body.playlist_description || "" songs: [] creator: user_id create_date: new Date().getTime() followers: [user_id] artwork: album_key || "" private: req.body.private || false collaborative: req.body.collaborative || false } playlistsCollection.insertOne(playlistObj, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) usersCollection.find({id: user_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] playlists = results[0].playlists playlists.push(playlist_id) usersCollection.update({id: user_id},{$set: {playlists: playlists}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) console.log playlistObj res.send(playlistObj) ) ) ) if req.body.playlist_artwork console.log "Album Art Detected" albumart_key = PI:KEY:<KEY>END_PI); req_albumartContent = req.body.playlist_artwork.replace(/^data:([A-Za-z-+/]+);base64,/, '') require("fs").writeFile(path.join(__dirname, '../../static/AlbumArt/')+albumart_key+".png", req_albumartContent, 'base64', (err) -> if err then console.log(err) console.log "Album Art Uploaded" uploadRemainingData(albumart_key) ) else console.log("No Album Art Detected") uploadRemainingData() else res.send({error: "crap", message:"Incorrectly Formatted Requested"}) ) convertTimestampToSeconds = (input) -> reptms = /^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/ hours = 0 minutes = 0 seconds = 0 if reptms.test(input) matches = reptms.exec(input) if (matches[1]) then hours = Number(matches[1]) if (matches[2]) then minutes = Number(matches[2]) if (matches[3]) then seconds = Number(matches[3]) return hours*60*60+minutes*60+seconds; router.put("/:playlist_id/song", refreshSpotifyAccessToken, (req, res) -> #from source so add to Songs DB res.type("json") if req.user_id console.log "PUT new song from source" console.log req.body #vars source = req.body.source video_id = req.body.video_id song_id = req.body.song_id playlist_id = req.params.playlist_id user_id = req.user_id #Collections tracksCollection = req.app.locals.motorbot.database.collection("tracks") playlistsCollection = req.app.locals.motorbot.database.collection("playlists") if source == "ytb" tracksCollection.find({video_id: video_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] #song already in tracksCollection insertionObj = results[0] insertionObj.type = "trackAdded" insertionObj.playlistId = playlist_id song_obj = { id: insertionObj.id date_added: new Date().getTime() play_count: 0 last_played: undefined } playlistsCollection.find({"id":playlist_id, "creator": user_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] playlist = results[0] if playlist.artwork == "" && insertionObj.artwork != "" #update playlist artwork playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}, "$set": {artwork: insertionObj.artwork}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else return res.status(404).send({code: 404, status: "Playlist Not Found"}) ) else #insert song from source console.log("Spotify Authorization Code: "+res.locals.spotify_access_token) request.get({ url: "https://www.googleapis.com/youtube/v3/videos?id="+video_id+"&key=PI:KEY:<KEY>END_PI&part=snippet,contentDetails", json: true }, (err, httpResponse, data) -> if err then return res.status(500).send({code: 500, status: "Youtube API Error", error: err}) if data.items[0] modifiedTitle = data.items[0].snippet.title.replace(/\[((?!.*?Remix))[^\)]*\]/gmi, '').replace(/\(((?!.*?Remix))[^\)]*\)/gmi, '').replace(/\-(\s|)[0-9]*(\s|)\-/g, '').replace(/(\s|)-(\s|)/gmi," ").replace(/(\sI\s|\s:\s)/gmi, " ").replace(/\sFrom\s(.*)\/(|\s)Soundtrack/gmi, "").replace(/(high\squality|\sOST|playlist|\sHD|\sHQ|\s1080p|\s720p|ft\.|feat\.|ft\s|lyrics|official\svideo|\"|official|video|:|\/Soundtrack\sVersion|\/Soundtrack|\||w\/|\/)/gmi, '') modifiedTitle = encodeURIComponent(modifiedTitle.trim()) console.log modifiedTitle request.get({ url: "https://api.spotify.com/v1/search?type=track&q=" + modifiedTitle, json: true, headers: { "Authorization": "Bearer "+res.locals.spotify_access_token } }, (err, httpResponse, body) -> if err then return res.status(500).send({code: 500, status: "Spotify API Error", error: err}) else artist = {} album = {} composer = {} album_artist = {} title = decodeURIComponent(modifiedTitle) genres = [] release_date = undefined track_number = 0 disc_number = 0 artwork = "" explicit = false if body.tracks if body.tracks.items[0] if body.tracks.items[0].artists[0] id = new Buffer(body.tracks.items[0].artists[0].name, 'base64') artist = { name: body.tracks.items[0].artists[0].name, id: id.toString('hex') } if body.tracks.items[0].album id = new Buffer(body.tracks.items[0].album.name, 'base64') album_artwork = "" if body.tracks.items[0].album.images[0] then album_artwork = body.tracks.items[0].album.images[0].url artwork = album_artwork album = { name: body.tracks.items[0].album.name, artwork: album_artwork id: id.toString('hex') } if body.tracks.items[0].album.artists[0] id = new Buffer(body.tracks.items[0].album.artists[0].name, 'base64') album_artist = { name: body.tracks.items[0].album.artists[0].name, id: id.toString('hex') } title = body.tracks.items[0].name.replace(/\[((?!.*?Remix))[^\)]*\]/gmi, '').replace(/\(((?!.*?Remix))[^\)]*\)/gmi, '').replace(/\-(\s|)[0-9]*(\s|)\-/g, '').replace(/(\s|)-(\s|)/gmi," ").replace(/\sFrom\s(.*)\/(|\s)Soundtrack/gmi, "").replace(/(high\squality|\sOST|playlist|\sHD|\sHQ|\s1080p|ft\.|feat\.|ft\s|lyrics|official\svideo|\"|official|video|:|\/Soundtrack\sVersion|\/Soundtrack|\||w\/|\/)/gmi, '') track_number = Number(body.tracks.items[0].track_number) disc_number = Number(body.tracks.items[0].disc_number) explicit = body.tracks.items[0].explicit track_id = uid(32) track_obj = { id: track_id, type: "youtube", video_id: video_id, video_title: data.items[0].snippet.title, title: title, artist: artist, album: album, composer: composer, album_artist: album_artist genres: genres, duration: convertTimestampToSeconds(data.items[0].contentDetails.duration), import_date: new Date().getTime(), release_date: release_date, track_number: track_number, disc_number: disc_number, play_count: 0, artwork: artwork, explicit: explicit lyrics: "", user_id: user_id, } tracksCollection.insertOne(track_obj, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) else insertionObj = track_obj insertionObj.type = "trackAdded" insertionObj.playlistId = playlist_id song_obj = { id: insertionObj.id date_added: new Date().getTime() play_count: 0 last_played: undefined } #add to playlist playlistsCollection.find({"id":playlist_id,"creator":user_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] playlist = results[0] if playlist.artwork == "" && insertionObj.artwork != "" #update playlist artwork playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}, "$set": {artwork: insertionObj.artwork}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else return res.status(404).send({code: 404, status: "Playlist Not Found"}) ) ) ) else return res.status(404).send({code: 404, status: "Youtube API Error", error: "Video Not Found"}) ) ) else if source == "scd" tracksCollection.find({soundcloud_id: video_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] #song already in the database insertionObj = results[0] insertionObj.type = "trackAdded" insertionObj.playlistId = playlist_id song_obj = { id: insertionObj.id date_added: new Date().getTime() play_count: 0 last_played: undefined } playlistsCollection.find({"id":playlist_id, "creator": user_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] playlist = results[0] if playlist.artwork == "" && insertionObj.artwork != "" #update playlist artwork playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}, "$set": {artwork: insertionObj.artwork}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else playlistsCollection.update({"id":playlist_id,"creator":user_id},{"$push": {songs: song_obj}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) #insert into song queue if active queue insertSongIntoQueue(req, res, insertionObj, playlist_id) ) else return res.status(404).send({code: 404, status: "Playlist Not Found"}) ) else #insert song from source ) else return res.status(429).send({code: 429, status: "Unauthorized"}) ) router.patch("/:playlist_id/song/:song_id", (req, res) -> #add song from another playlist or song DB transfer playlist_id = req.params.playlist_id song_id = req.params.song_id playlistCollection = req.app.locals.motorbot.database.collection("playlists") tracksCollection = req.app.locals.motorbot.database.collection("tracks") playlistCollection.find({id: playlist_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] playlist = results[0] tracksCollection.find({id: song_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) if results[0] song_obj = { id: song_id date_added: new Date().getTime() play_count: 0 last_played: undefined } if playlist.artwork == "" && results[0].artwork != "" playlistCollection.update({id: playlist_id},{$push: {songs: song_obj}, $set: {artwork: results[0].artwork}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) return res.status(200).send({code: 200, status: "OKAY"}) ) else playlistCollection.update({id: playlist_id},{$push: {songs: song_obj}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) return res.status(200).send({code: 200, status: "OKAY"}) ) else return res.status(404).send({code: 404, status: "Unknown Song"}) ) else return res.status(404).send({code: 404, status: "Unknown Playlist"}) ) ) router.delete("/:playlist_id", (req, res) -> playlistsCollection = req.app.locals.motorbot.database.collection("playlists") usersCollection = req.app.locals.motorbot.database.collection("users") user_id = req.user_id playlist_id = req.params.playlist_id playlistsCollection.remove({"id": playlist_id, "creator": user_id}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) else console.log result.result.n if result.result.n == 1 usersCollection.update({}, {"$pull":{"playlists": playlist_id}}, {multi: true}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Database Error", error: err}) else res.send({"status": 200,"message":"OKAY"}) ) else return res.status(404).send({code: 404, status: "Playlist Not Found For User"}) ) ) router.get("/:playlist_id", (req, res) -> if req.user_id filter = APIUtilities.formatFilterForMongo(req.query.filter) APIObjects.playlist(req).playlistById(req.params.playlist_id.toString(), filter).then((playlist) -> async.parallel([ (asyncParallelComplete) -> if playlist.creator APIObjects.user(req).userById(playlist.creator, {username: 1, discriminator: 1}).then((user) -> playlist["owner"] = user asyncParallelComplete() ).catch((error_obj) -> asyncParallelComplete(error_obj) ) else asyncParallelComplete({error: "PLAYLIST_FORMAT", message: "Unknown playlist format, (playlist is missing an owner)"}) ,(asyncParallelComplete) -> if playlist.songs #return complete song objects for the first 50 tracks, further tracks should be retrieved from the /track endpoint songs = playlist.songs.slice(0,100) songIds = [] songsFinal = {} for song in songs songIds.push(song.id) songsFinal[song.id] = song #store user variables delete songsFinal[song.id].id APIObjects.track(req).tracksForIds(songIds, {}).then((tracks) -> tracks_obj = [] for track in tracks t = {} t = songsFinal[track.id] t["track"] = track tracks_obj.push(t) playlist["tracks"] = APIObjects.pagination().paginate("/playlist/"+req.params.playlist_id+"/tracks", tracks_obj, playlist.songs.length, 0, 100) delete playlist.songs asyncParallelComplete() ).catch((error_obj) -> asyncParallelComplete(error_obj) ) else # No songs in this playlist console.log "PLAYLIST_EMPTY: Playlist contains no songs" asyncParallelComplete() ], (error_obj) -> if error_obj res.type("json") res.send(JSON.stringify(error_obj)) else res.type("json") res.send(JSON.stringify(playlist)) ) ).catch((error_obj) -> res.type("json") res.send(JSON.stringify(error_obj)) ) else return res.status(401).send({code: 401, status: "Unauthorized"}) ) router.get("/:playlist_id/tracks", (req, res) -> if req.user_id APIObjects.playlist(req).playlistById(req.params.playlist_id.toString(), {songs: 1}).then((playlist) -> if playlist.songs #return complete song objects for the first 50 tracks, further tracks should be retrieved from the /track endpoint limit = parseInt(req.query.limit) || 100 offset = parseInt(req.query.offset) || 0 if limit < 1 limit = 1 else if limit > 100 limit = 100 songs = playlist.songs.slice(offset,(offset + limit)) songIds = [] songsFinal = {} for song in songs songIds.push(song.id) songsFinal[song.id] = song #store user variables delete songsFinal[song.id].id APIObjects.track(req).tracksForIds(songIds).then((tracks) -> tracks_obj = [] for track in tracks t = {} t = songsFinal[track.id] t["track"] = track tracks_obj.push(t) finalTracks = APIObjects.pagination().paginate("/playlist/"+req.params.playlist_id+"/tracks", tracks_obj, playlist.songs.length, offset, limit) finalTracks = APIUtilities.filterResponse(finalTracks,req.query.filter) res.type("json") res.send(JSON.stringify(finalTracks)) ).catch((error_obj) -> ) else # No songs in this playlist console.log "PLAYLIST_EMPTY: Playlist contains no songs" ).catch((error_obj) -> res.type("json") res.send(JSON.stringify(error_obj)) ) else return res.status(401).send({code: 401, status: "Unauthorized"}) ) router.delete("/:playlist_id/song/:song_id", (req, res) -> playlistCollection = req.app.locals.motorbot.database.collection("playlists") tracksCollection = req.app.locals.motorbot.database.collection("tracks") songQueueCollection = req.app.locals.motorbot.database.collection("songQueue") playlist_id = req.params.playlist_id song_id = req.params.song_id user_id = req.user_id res.type("json") if user_id playlistCollection.find({id: playlist_id, creator: user_id}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) if results[0] playlist = results[0] tracksCollection.find({id: song_id}).toArray((err, result) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) else if result[0].artwork == playlist.artwork new_albumart = "" tracksCollection.find({id: {$in: playlist.songs}}).toArray((err, results) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) for song in results if song.id.toString() != song_id.toString() && song.artwork != "" new_albumart = song.artwork break; console.log "New Album Art Set: "+new_albumart playlistCollection.update({id: playlist_id},{$pull: {songs: {id: song_id}}, $set: {artwork: new_albumart}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) res.status(200).send({code: 200, status: "OKAY"}) req.app.locals.motorbot.websocket.broadcast(JSON.stringify({type: 'trackDelete', songId: song_id, playlistId: playlist_id, newAlbumArt: new_albumart})) songQueueCollection.remove({songId: song_id.toString(), playlistId: playlist_id}, (err, results) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) #wss event for queue ) ) ) else playlistCollection.update({id: playlist_id},{$pull: {songs: {id: song_id}}}, (err, result) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) res.status(200).send({code: 200, status: "OKAY"}) req.app.locals.motorbot.websocket.broadcast(JSON.stringify({type: 'trackDelete', songId: song_id, playlistId: playlist_id})) songQueueCollection.remove({songId: song_id.toString(), playlistId: playlist_id}, (err, results) -> if err then return res.status(500).send({code: 500, status: "Internal Server Error", reason: err}) #wss event for queue ) ) ) else return res.status(404).send({code: 404, status: "Playlist Not Found"}) ) else return res.status(429).send({code: 429, status: "Unauthorized"}) ) module.exports = router
[ { "context": "cess hits: [\n fabricate 'artwork', title: \"Andy Foobar's Finger Painting\"\n ]\n $('body').html()", "end": 1380, "score": 0.8068517446517944, "start": 1369, "tag": "NAME", "value": "Andy Foobar" }, { "context": "][2].success [\n fabricate 'arti...
src/mobile/apps/artist/test/client.view.coffee
kanaabe/force
0
_ = require 'underscore' Backbone = require 'backbone' Artist = require '../../../models/artist' Artworks = require '../../../collections/artworks' FollowArtist = require '../../../models/follow_artist' CurrentUser = require '../../../models/current_user' { fabricate } = require 'antigravity' sinon = require 'sinon' benv = require 'benv' { resolve } = require 'path' describe 'ArtistPageView', -> beforeEach (done) -> benv.setup => @_location = global.location global.location = { search: '' } benv.expose { $: benv.require 'jquery' } Backbone.$ = $ sinon.stub Backbone, 'sync' $.fn.error = sinon.stub() benv.render resolve(__dirname, '../templates/page.jade'), { artist: new Artist(fabricate 'artist'), sd: {} asset: (->) }, => ArtistPageView = benv.requireWithJadeify resolve(__dirname, '../client/view'), ['artworksTemplate', 'articlesTemplate', 'suggestedArtists'] ArtistPageView.__set__ 'ShareView', @ShareView = sinon.stub() @view = new ArtistPageView model: new Artist(fabricate 'artist') done() afterEach -> global.location = @_location benv.teardown() Backbone.sync.restore() describe '#initialize', -> it 'renders artworks', -> Backbone.sync.args[0][2].success hits: [ fabricate 'artwork', title: "Andy Foobar's Finger Painting" ] $('body').html().should.containEql "Andy Foobar's Finger Painting" it 'renders suggested artists', -> Backbone.sync.args[1][2].success [ fabricate 'artist', name: "The Andy Foobar" ] $('body').html().should.containEql "The Andy Foobar" it 'renders on add', -> spy = sinon.spy @view, 'renderArtworks' @view.initialize({user: null}) @view.artworks.trigger 'add' spy.called.should.be.ok() it 'sets the sort params if visiting the right url', -> location.search = 'sort=-published_at' @view.initialize({}) @view.artworkParams.sort.should.equal '-published_at' describe '#swapArtworks', -> it 'fetches the for sale works if that button is clicked', -> @view.swapArtworks target: $ "<button class='artist-page-artworks-tab-for-sale'>" _.last(Backbone.sync.args)[2].data.should.containEql 'for_sale=true' it 'renders the fetched artworks', -> @view.swapArtworks target: $ "<button class='artist-page-artworks-tab-for-sale'>" _.last(Backbone.sync.args)[2].success hits: [fabricate 'artwork', title: 'Foobaraza'] $('#artist-page-artworks-list').html().should.containEql 'Foobaraza' describe '#renderArtworks', -> it 'hides the see more if reached max', -> @view.model.set published_artworks_count: 0 @view.artworks = new Artworks [fabricate('artwork'), fabricate('artwork')] @view.renderArtworks() @view.$('.artist-page-artwork-see-more-container').css('display').should.equal 'none' describe '#seeMoreArtworks', -> it 'fetches more artworks and adds them to the collection', -> @view.seeMoreArtworks() _.last(Backbone.sync.args)[2].data.should.containEql 'page=2' _.last(Backbone.sync.args)[2].success hits: [fabricate('artwork'), fabricate('artwork')] @view.artworks.length.should.be.above 1 describe '#followArtist', -> beforeEach -> @e = $.Event('click') it 'should render init button state', -> @view.$('.artist-follow').data('state').should.equal 'follow' describe 'with a user', -> beforeEach -> @view.followButtonView.isLoggedIn = true @spyFollow = sinon.spy @view.followArtists, 'follow' @spyUnfollow = sinon.spy @view.followArtists, 'unfollow' afterEach -> @spyFollow.restore() @spyUnfollow.restore() it 'should follow the artist', -> @view.followButtonView.onToggle(@e) _.last(Backbone.sync.args)[2].success { id: 123, artist: @view.model.attributes } @spyFollow.calledOnce.should.be.true() it 'should toggle button state', -> @view.$('.artist-follow').data('state').should.equal 'follow' @view.followButtonView.onToggle(@e) _.last(Backbone.sync.args)[2].success { id: 123, artist: @view.model.attributes } @view.$('.artist-follow').attr('data-state').should.equal 'following' # Note: See followButtonView tests describe 'without a user', -> it 'should redirect to log in', -> spy = sinon.spy @view.followArtists, 'follow' @view.followButtonView.onToggle(@e) spy.called.should.be.false() @view.followArtists.follow.restore() location.href.should.containEql "/log_in?redirect-to=" describe '#resetArtworks', -> it 'fetches the artworks with the params', -> @view.artworkParams.sort = 'title' @view.resetArtworks() _.last(Backbone.sync.args)[2].data.should.containEql 'sort=title' describe '#sortArtworks', -> it 'sorts the artworks based on the select value', -> @view.$('#artist-page-sort select').val '-published_at' @view.sortArtworks() _.last(Backbone.sync.args)[2].data.should.containEql '-published_at'
66782
_ = require 'underscore' Backbone = require 'backbone' Artist = require '../../../models/artist' Artworks = require '../../../collections/artworks' FollowArtist = require '../../../models/follow_artist' CurrentUser = require '../../../models/current_user' { fabricate } = require 'antigravity' sinon = require 'sinon' benv = require 'benv' { resolve } = require 'path' describe 'ArtistPageView', -> beforeEach (done) -> benv.setup => @_location = global.location global.location = { search: '' } benv.expose { $: benv.require 'jquery' } Backbone.$ = $ sinon.stub Backbone, 'sync' $.fn.error = sinon.stub() benv.render resolve(__dirname, '../templates/page.jade'), { artist: new Artist(fabricate 'artist'), sd: {} asset: (->) }, => ArtistPageView = benv.requireWithJadeify resolve(__dirname, '../client/view'), ['artworksTemplate', 'articlesTemplate', 'suggestedArtists'] ArtistPageView.__set__ 'ShareView', @ShareView = sinon.stub() @view = new ArtistPageView model: new Artist(fabricate 'artist') done() afterEach -> global.location = @_location benv.teardown() Backbone.sync.restore() describe '#initialize', -> it 'renders artworks', -> Backbone.sync.args[0][2].success hits: [ fabricate 'artwork', title: "<NAME>'s Finger Painting" ] $('body').html().should.containEql "Andy Foobar's Finger Painting" it 'renders suggested artists', -> Backbone.sync.args[1][2].success [ fabricate 'artist', name: "<NAME>" ] $('body').html().should.containEql "The Andy Foobar" it 'renders on add', -> spy = sinon.spy @view, 'renderArtworks' @view.initialize({user: null}) @view.artworks.trigger 'add' spy.called.should.be.ok() it 'sets the sort params if visiting the right url', -> location.search = 'sort=-published_at' @view.initialize({}) @view.artworkParams.sort.should.equal '-published_at' describe '#swapArtworks', -> it 'fetches the for sale works if that button is clicked', -> @view.swapArtworks target: $ "<button class='artist-page-artworks-tab-for-sale'>" _.last(Backbone.sync.args)[2].data.should.containEql 'for_sale=true' it 'renders the fetched artworks', -> @view.swapArtworks target: $ "<button class='artist-page-artworks-tab-for-sale'>" _.last(Backbone.sync.args)[2].success hits: [fabricate 'artwork', title: 'Foobaraza'] $('#artist-page-artworks-list').html().should.containEql 'Foobaraza' describe '#renderArtworks', -> it 'hides the see more if reached max', -> @view.model.set published_artworks_count: 0 @view.artworks = new Artworks [fabricate('artwork'), fabricate('artwork')] @view.renderArtworks() @view.$('.artist-page-artwork-see-more-container').css('display').should.equal 'none' describe '#seeMoreArtworks', -> it 'fetches more artworks and adds them to the collection', -> @view.seeMoreArtworks() _.last(Backbone.sync.args)[2].data.should.containEql 'page=2' _.last(Backbone.sync.args)[2].success hits: [fabricate('artwork'), fabricate('artwork')] @view.artworks.length.should.be.above 1 describe '#followArtist', -> beforeEach -> @e = $.Event('click') it 'should render init button state', -> @view.$('.artist-follow').data('state').should.equal 'follow' describe 'with a user', -> beforeEach -> @view.followButtonView.isLoggedIn = true @spyFollow = sinon.spy @view.followArtists, 'follow' @spyUnfollow = sinon.spy @view.followArtists, 'unfollow' afterEach -> @spyFollow.restore() @spyUnfollow.restore() it 'should follow the artist', -> @view.followButtonView.onToggle(@e) _.last(Backbone.sync.args)[2].success { id: 123, artist: @view.model.attributes } @spyFollow.calledOnce.should.be.true() it 'should toggle button state', -> @view.$('.artist-follow').data('state').should.equal 'follow' @view.followButtonView.onToggle(@e) _.last(Backbone.sync.args)[2].success { id: 123, artist: @view.model.attributes } @view.$('.artist-follow').attr('data-state').should.equal 'following' # Note: See followButtonView tests describe 'without a user', -> it 'should redirect to log in', -> spy = sinon.spy @view.followArtists, 'follow' @view.followButtonView.onToggle(@e) spy.called.should.be.false() @view.followArtists.follow.restore() location.href.should.containEql "/log_in?redirect-to=" describe '#resetArtworks', -> it 'fetches the artworks with the params', -> @view.artworkParams.sort = 'title' @view.resetArtworks() _.last(Backbone.sync.args)[2].data.should.containEql 'sort=title' describe '#sortArtworks', -> it 'sorts the artworks based on the select value', -> @view.$('#artist-page-sort select').val '-published_at' @view.sortArtworks() _.last(Backbone.sync.args)[2].data.should.containEql '-published_at'
true
_ = require 'underscore' Backbone = require 'backbone' Artist = require '../../../models/artist' Artworks = require '../../../collections/artworks' FollowArtist = require '../../../models/follow_artist' CurrentUser = require '../../../models/current_user' { fabricate } = require 'antigravity' sinon = require 'sinon' benv = require 'benv' { resolve } = require 'path' describe 'ArtistPageView', -> beforeEach (done) -> benv.setup => @_location = global.location global.location = { search: '' } benv.expose { $: benv.require 'jquery' } Backbone.$ = $ sinon.stub Backbone, 'sync' $.fn.error = sinon.stub() benv.render resolve(__dirname, '../templates/page.jade'), { artist: new Artist(fabricate 'artist'), sd: {} asset: (->) }, => ArtistPageView = benv.requireWithJadeify resolve(__dirname, '../client/view'), ['artworksTemplate', 'articlesTemplate', 'suggestedArtists'] ArtistPageView.__set__ 'ShareView', @ShareView = sinon.stub() @view = new ArtistPageView model: new Artist(fabricate 'artist') done() afterEach -> global.location = @_location benv.teardown() Backbone.sync.restore() describe '#initialize', -> it 'renders artworks', -> Backbone.sync.args[0][2].success hits: [ fabricate 'artwork', title: "PI:NAME:<NAME>END_PI's Finger Painting" ] $('body').html().should.containEql "Andy Foobar's Finger Painting" it 'renders suggested artists', -> Backbone.sync.args[1][2].success [ fabricate 'artist', name: "PI:NAME:<NAME>END_PI" ] $('body').html().should.containEql "The Andy Foobar" it 'renders on add', -> spy = sinon.spy @view, 'renderArtworks' @view.initialize({user: null}) @view.artworks.trigger 'add' spy.called.should.be.ok() it 'sets the sort params if visiting the right url', -> location.search = 'sort=-published_at' @view.initialize({}) @view.artworkParams.sort.should.equal '-published_at' describe '#swapArtworks', -> it 'fetches the for sale works if that button is clicked', -> @view.swapArtworks target: $ "<button class='artist-page-artworks-tab-for-sale'>" _.last(Backbone.sync.args)[2].data.should.containEql 'for_sale=true' it 'renders the fetched artworks', -> @view.swapArtworks target: $ "<button class='artist-page-artworks-tab-for-sale'>" _.last(Backbone.sync.args)[2].success hits: [fabricate 'artwork', title: 'Foobaraza'] $('#artist-page-artworks-list').html().should.containEql 'Foobaraza' describe '#renderArtworks', -> it 'hides the see more if reached max', -> @view.model.set published_artworks_count: 0 @view.artworks = new Artworks [fabricate('artwork'), fabricate('artwork')] @view.renderArtworks() @view.$('.artist-page-artwork-see-more-container').css('display').should.equal 'none' describe '#seeMoreArtworks', -> it 'fetches more artworks and adds them to the collection', -> @view.seeMoreArtworks() _.last(Backbone.sync.args)[2].data.should.containEql 'page=2' _.last(Backbone.sync.args)[2].success hits: [fabricate('artwork'), fabricate('artwork')] @view.artworks.length.should.be.above 1 describe '#followArtist', -> beforeEach -> @e = $.Event('click') it 'should render init button state', -> @view.$('.artist-follow').data('state').should.equal 'follow' describe 'with a user', -> beforeEach -> @view.followButtonView.isLoggedIn = true @spyFollow = sinon.spy @view.followArtists, 'follow' @spyUnfollow = sinon.spy @view.followArtists, 'unfollow' afterEach -> @spyFollow.restore() @spyUnfollow.restore() it 'should follow the artist', -> @view.followButtonView.onToggle(@e) _.last(Backbone.sync.args)[2].success { id: 123, artist: @view.model.attributes } @spyFollow.calledOnce.should.be.true() it 'should toggle button state', -> @view.$('.artist-follow').data('state').should.equal 'follow' @view.followButtonView.onToggle(@e) _.last(Backbone.sync.args)[2].success { id: 123, artist: @view.model.attributes } @view.$('.artist-follow').attr('data-state').should.equal 'following' # Note: See followButtonView tests describe 'without a user', -> it 'should redirect to log in', -> spy = sinon.spy @view.followArtists, 'follow' @view.followButtonView.onToggle(@e) spy.called.should.be.false() @view.followArtists.follow.restore() location.href.should.containEql "/log_in?redirect-to=" describe '#resetArtworks', -> it 'fetches the artworks with the params', -> @view.artworkParams.sort = 'title' @view.resetArtworks() _.last(Backbone.sync.args)[2].data.should.containEql 'sort=title' describe '#sortArtworks', -> it 'sorts the artworks based on the select value', -> @view.$('#artist-page-sort select').val '-published_at' @view.sortArtworks() _.last(Backbone.sync.args)[2].data.should.containEql '-published_at'
[ { "context": "\n# * Cloned from \"classie.js\"\n# * Copyright © 2014 David DeSandro (\"classie.js\"), Softlayer, an IBM Company\n# * Cod", "end": 157, "score": 0.9998248219490051, "start": 143, "tag": "NAME", "value": "David DeSandro" }, { "context": "s helper functions from bonzo (h...
languages/coffeescript/unclassy.coffee
caleorourke/scrapyard
0
# # * Unclassy # * A library agnostic, extensible DOM utility for class helper functions # * # * Cloned from "classie.js" # * Copyright © 2014 David DeSandro ("classie.js"), Softlayer, an IBM Company # * Code and documentation licensed under MIT # # Usage # 1. unclassy.has( elem, 'my-class' ) -> true/false # 2. unclassy.add( elem, 'my-new-class' ) # 3. unclassy.remove( elem, 'my-unwanted-class' ) # 4. unclassy.toggle( elem, 'my-class' ) ((window) -> # class helper functions from bonzo (https://github.com/ded/bonzo) classReg = (className) -> new RegExp("(^|\\s+)" + className + "(\\s+|$)") # classList support for class management toggleClass = (elem, c) -> fn = (if hasClass(elem, c) then removeClass else addClass) fn elem, c return "use strict" hasClass = undefined addClass = undefined removeClass = undefined if "classList" of document.documentElement hasClass = (elem, c) -> elem.classList.contains c addClass = (elem, c) -> elem.classList.add c return removeClass = (elem, c) -> elem.classList.remove c return else hasClass = (elem, c) -> classReg(c).test elem.className addClass = (elem, c) -> elem.className = elem.className + " " + c unless hasClass(elem, c) return removeClass = (elem, c) -> elem.className = elem.className.replace(classReg(c), " ") return unclassy = # full names hasClass: hasClass addClass: addClass removeClass: removeClass toggleClass: toggleClass # short names has: hasClass add: addClass remove: removeClass toggle: toggleClass # transport if typeof define is "function" and define.amd # AMD define unclassy else if typeof exports is "object" # CommonJS module.exports = unclassy else # browser global window.unclassy = unclassy return ) window
79885
# # * Unclassy # * A library agnostic, extensible DOM utility for class helper functions # * # * Cloned from "classie.js" # * Copyright © 2014 <NAME> ("classie.js"), Softlayer, an IBM Company # * Code and documentation licensed under MIT # # Usage # 1. unclassy.has( elem, 'my-class' ) -> true/false # 2. unclassy.add( elem, 'my-new-class' ) # 3. unclassy.remove( elem, 'my-unwanted-class' ) # 4. unclassy.toggle( elem, 'my-class' ) ((window) -> # class helper functions from bonzo (https://github.com/ded/bonzo) classReg = (className) -> new RegExp("(^|\\s+)" + className + "(\\s+|$)") # classList support for class management toggleClass = (elem, c) -> fn = (if hasClass(elem, c) then removeClass else addClass) fn elem, c return "use strict" hasClass = undefined addClass = undefined removeClass = undefined if "classList" of document.documentElement hasClass = (elem, c) -> elem.classList.contains c addClass = (elem, c) -> elem.classList.add c return removeClass = (elem, c) -> elem.classList.remove c return else hasClass = (elem, c) -> classReg(c).test elem.className addClass = (elem, c) -> elem.className = elem.className + " " + c unless hasClass(elem, c) return removeClass = (elem, c) -> elem.className = elem.className.replace(classReg(c), " ") return unclassy = # full names hasClass: hasClass addClass: addClass removeClass: removeClass toggleClass: toggleClass # short names has: hasClass add: addClass remove: removeClass toggle: toggleClass # transport if typeof define is "function" and define.amd # AMD define unclassy else if typeof exports is "object" # CommonJS module.exports = unclassy else # browser global window.unclassy = unclassy return ) window
true
# # * Unclassy # * A library agnostic, extensible DOM utility for class helper functions # * # * Cloned from "classie.js" # * Copyright © 2014 PI:NAME:<NAME>END_PI ("classie.js"), Softlayer, an IBM Company # * Code and documentation licensed under MIT # # Usage # 1. unclassy.has( elem, 'my-class' ) -> true/false # 2. unclassy.add( elem, 'my-new-class' ) # 3. unclassy.remove( elem, 'my-unwanted-class' ) # 4. unclassy.toggle( elem, 'my-class' ) ((window) -> # class helper functions from bonzo (https://github.com/ded/bonzo) classReg = (className) -> new RegExp("(^|\\s+)" + className + "(\\s+|$)") # classList support for class management toggleClass = (elem, c) -> fn = (if hasClass(elem, c) then removeClass else addClass) fn elem, c return "use strict" hasClass = undefined addClass = undefined removeClass = undefined if "classList" of document.documentElement hasClass = (elem, c) -> elem.classList.contains c addClass = (elem, c) -> elem.classList.add c return removeClass = (elem, c) -> elem.classList.remove c return else hasClass = (elem, c) -> classReg(c).test elem.className addClass = (elem, c) -> elem.className = elem.className + " " + c unless hasClass(elem, c) return removeClass = (elem, c) -> elem.className = elem.className.replace(classReg(c), " ") return unclassy = # full names hasClass: hasClass addClass: addClass removeClass: removeClass toggleClass: toggleClass # short names has: hasClass add: addClass remove: removeClass toggle: toggleClass # transport if typeof define is "function" and define.amd # AMD define unclassy else if typeof exports is "object" # CommonJS module.exports = unclassy else # browser global window.unclassy = unclassy return ) window
[ { "context": "-role` alias to jQuery.\n# Copy from jquery.role by Sasha Koss https://github.com/kossnocorp/role\n\nrewriteSelect", "end": 127, "score": 0.9998255968093872, "start": 117, "tag": "NAME", "value": "Sasha Koss" }, { "context": "from jquery.role by Sasha Koss https://githu...
app/assets/javascripts/base/role.js.coffee
open-cook/ok-2018
0
@by_role = (name) -> $ """[data-role='#{ name }']""" # Add `@data-role` alias to jQuery. # Copy from jquery.role by Sasha Koss https://github.com/kossnocorp/role rewriteSelector = (context, name, pos) -> original = context[name] return unless original context[name] = -> arguments[pos] = arguments[pos].replace(/@@([\w\u00c0-\uFFFF\-]+)/g, "[data-block~=\"$1\"]") arguments[pos] = arguments[pos].replace(/@([\w\u00c0-\uFFFF\-]+)/g, "[data-role~=\"$1\"]") original.apply context, arguments $.extend context[name], original return rewriteSelector $, "find", 0 rewriteSelector $, "multiFilter", 0 rewriteSelector $.find, "matchesSelector", 1 rewriteSelector $.find, "matches", 0
45005
@by_role = (name) -> $ """[data-role='#{ name }']""" # Add `@data-role` alias to jQuery. # Copy from jquery.role by <NAME> https://github.com/kossnocorp/role rewriteSelector = (context, name, pos) -> original = context[name] return unless original context[name] = -> arguments[pos] = arguments[pos].replace(/@@([\w\u00c0-\uFFFF\-]+)/g, "[data-block~=\"$1\"]") arguments[pos] = arguments[pos].replace(/@([\w\u00c0-\uFFFF\-]+)/g, "[data-role~=\"$1\"]") original.apply context, arguments $.extend context[name], original return rewriteSelector $, "find", 0 rewriteSelector $, "multiFilter", 0 rewriteSelector $.find, "matchesSelector", 1 rewriteSelector $.find, "matches", 0
true
@by_role = (name) -> $ """[data-role='#{ name }']""" # Add `@data-role` alias to jQuery. # Copy from jquery.role by PI:NAME:<NAME>END_PI https://github.com/kossnocorp/role rewriteSelector = (context, name, pos) -> original = context[name] return unless original context[name] = -> arguments[pos] = arguments[pos].replace(/@@([\w\u00c0-\uFFFF\-]+)/g, "[data-block~=\"$1\"]") arguments[pos] = arguments[pos].replace(/@([\w\u00c0-\uFFFF\-]+)/g, "[data-role~=\"$1\"]") original.apply context, arguments $.extend context[name], original return rewriteSelector $, "find", 0 rewriteSelector $, "multiFilter", 0 rewriteSelector $.find, "matchesSelector", 1 rewriteSelector $.find, "matches", 0
[ { "context": "er.actual_value\n\n if algorithm.key is 'deeplearning'\n validationFrameParameter = findParamet", "end": 4553, "score": 0.6959859728813171, "start": 4545, "tag": "KEY", "value": "learning" }, { "context": " = columnLabels\n else if algorithm.key i...
h2o-web/src/main/steam/scripts/create-model-dialog.coffee
My-Technical-Architect/h2o-3
1
createTextboxControl = (parameter) -> value = node$ parameter.actual_value kind: 'textbox' name: parameter.name label: parameter.label description: parameter.help required: parameter.required value: value defaultValue: parameter.default_value help: node$ 'Help goes here.' isInvalid: node$ no createDropdownControl = (parameter) -> value = node$ parameter.actual_value kind: 'dropdown' name: parameter.name label: parameter.label description: parameter.help required: parameter.required values: parameter.values value: value defaultValue: parameter.default_value help: node$ 'Help goes here.' isInvalid: node$ no createListControl = (parameter) -> value = node$ parameter.actual_value or [] selection = lift$ value, (values) -> caption = "#{describeCount values.length, 'column'} selected" caption += ": #{values.join ', '}" if values.length > 0 "(#{caption})" kind: 'list' name: parameter.name label: parameter.label description: parameter.help required: parameter.required values: parameter.values value: value selection: selection defaultValue: parameter.default_value help: node$ 'Help goes here.' isInvalid: node$ no createCheckboxControl = (parameter) -> value = node$ parameter.actual_value is 'true' #FIXME clientId: do uniqueId kind: 'checkbox' name: parameter.name label: parameter.label description: parameter.help required: parameter.required value: value defaultValue: parameter.default_value is 'true' help: node$ 'Help goes here.' isInvalid: node$ no createControlFromParameter = (parameter) -> switch parameter.type when 'enum', 'Frame', 'string' createDropdownControl parameter when 'string[]' createListControl parameter when 'boolean' createCheckboxControl parameter when 'Key', 'int', 'long', 'float', 'double', 'int[]', 'long[]', 'float[]', 'double[]' createTextboxControl parameter else console.error 'Invalid field', JSON.stringify parameter, null, 2 null findParameter = (parameters, name) -> find parameters, (parameter) -> parameter.name is name Steam.ModelBuilderForm = (_, _algorithm, _parameters, _go) -> _validationError = node$ null _parametersByLevel = groupBy _parameters, (parameter) -> parameter.level _controls = map [ 'critical', 'secondary', 'expert' ], (type) -> filter (map _parametersByLevel[type], createControlFromParameter), isTruthy [ _criticalControls, _secondaryControls, _expertControls ] = _controls parameterTemplateOf = (control) -> "#{control.kind}-model-parameter" createModel = -> _validationError null parameters = {} for controls in _controls for control in controls if control.defaultValue isnt value = control.value() switch control.kind when 'dropdown' if value parameters[control.name] = value when 'list' if value.length parameters[control.name] = "[#{value.join ','}]" else parameters[control.name] = value _.requestModelBuild _algorithm.key, parameters, (error, result) -> if error _validationError message: error.data.errmsg else _go 'confirm' title: "Configure #{_algorithm.title} Model" criticalControls: _criticalControls secondaryControls: _secondaryControls expertControls: _expertControls validationError: _validationError parameterTemplateOf: parameterTemplateOf createModel: createModel Steam.CreateModelDialog = (_, _frameKey, _sourceModel, _go) -> [ _isAlgorithmSelectionMode, _isModelCreationMode ] = switch$ no, 2 _title = node$ 'New Model' _canChangeAlgorithm = node$ yes _algorithms = nodes$ [] _modelForm = node$ null populateFramesAndColumns = (frameKey, algorithm, parameters, go) -> # Fetch frame list; pick column names from training frame _.requestFrames (error, result) -> if error #TODO handle properly else trainingFrameParameter = findParameter parameters, 'training_frame' #XXX temporary bail out for GLM unless trainingFrameParameter console.error "Model does not have a 'training_frame' parameter!" return go() trainingFrameParameter.values = map result.frames, (frame) -> frame.key.name if frameKey trainingFrameParameter.actual_value = frameKey else frameKey = trainingFrameParameter.actual_value if algorithm.key is 'deeplearning' validationFrameParameter = findParameter parameters, 'validation_frame' responseColumnParameter = findParameter parameters, 'response_column' #TODO HACK hard-coding DL column params for now - rework this when Vec type is supported. #responseColumnParameter.type = 'Vec' ignoredColumnsParameter = findParameter parameters, 'ignored_columns' #TODO HACK hard-coding DL column params for now - rework this when Vec type is supported. #ignoredColumnsParameter.type = 'Vec[]' validationFrameParameter.values = copy trainingFrameParameter.values if trainingFrame = (find result.frames, (frame) -> frame.key.name is frameKey) columnLabels = map trainingFrame.columns, (column) -> column.label sort columnLabels responseColumnParameter.values = columnLabels ignoredColumnsParameter.values = columnLabels else if algorithm.key is 'gbm' #validationFrameParameter = findParameter parameters, 'validation_frame' responseColumnParameter = findParameter parameters, 'response_column' #TODO HACK hard-coding DL column params for now - rework this when Vec type is supported. #responseColumnParameter.type = 'Vec' #ignoredColumnsParameter = findParameter parameters, 'ignored_columns' #TODO HACK hard-coding DL column params for now - rework this when Vec type is supported. #ignoredColumnsParameter.type = 'Vec[]' #validationFrameParameter.values = copy trainingFrameParameter.values if trainingFrame = (find result.frames, (frame) -> frame.key.name is frameKey) columnLabels = map trainingFrame.columns, (column) -> column.label sort columnLabels responseColumnParameter.values = columnLabels #ignoredColumnsParameter.values = columnLabels go() _.requestModelBuilders (error, algorithms) -> algorithms = for algorithm in algorithms key: algorithm title: algorithm # If a source model is specified, we already know the algo, so skip algo selection if _sourceModel _title 'Clone Model' _canChangeAlgorithm no _isModelCreationMode yes selectAlgorithm = noop parameters = _sourceModel.parameters #TODO INSANE SUPERHACK hasRateAnnealing = find _sourceModel.parameters, (parameter) -> parameter.name is 'rate_annealing' algorithm = if hasRateAnnealing find algorithms, (algorithm) -> algorithm.key is 'deeplearning' else find algorithms, (algorithm) -> algorithm.key is 'kmeans' populateFramesAndColumns _frameKey, algorithm, parameters, -> _modelForm Steam.ModelBuilderForm _, algorithm, parameters, _go else _isAlgorithmSelectionMode yes selectAlgorithm = (algorithm) -> _.requestModelBuilder algorithm.key, (error, result) -> if error #TODO handle properly else parameters = result.model_builders[algorithm.key].parameters populateFramesAndColumns _frameKey, algorithm, parameters, -> _modelForm Steam.ModelBuilderForm _, algorithm, parameters, _go _isModelCreationMode yes _algorithms map algorithms, (algorithm) -> self = title: algorithm.title data: algorithm select: -> selectAlgorithm self.data backToAlgorithms = -> _isAlgorithmSelectionMode yes createModel = -> _modelForm().createModel() cancel = -> _go 'cancel' title: _title isAlgorithmSelectionMode: _isAlgorithmSelectionMode isModelCreationMode: _isModelCreationMode algorithms: _algorithms modelForm: _modelForm cancel: cancel canChangeAlgorithm: _canChangeAlgorithm backToAlgorithms: backToAlgorithms createModel: createModel template: 'create-model-dialog'
209563
createTextboxControl = (parameter) -> value = node$ parameter.actual_value kind: 'textbox' name: parameter.name label: parameter.label description: parameter.help required: parameter.required value: value defaultValue: parameter.default_value help: node$ 'Help goes here.' isInvalid: node$ no createDropdownControl = (parameter) -> value = node$ parameter.actual_value kind: 'dropdown' name: parameter.name label: parameter.label description: parameter.help required: parameter.required values: parameter.values value: value defaultValue: parameter.default_value help: node$ 'Help goes here.' isInvalid: node$ no createListControl = (parameter) -> value = node$ parameter.actual_value or [] selection = lift$ value, (values) -> caption = "#{describeCount values.length, 'column'} selected" caption += ": #{values.join ', '}" if values.length > 0 "(#{caption})" kind: 'list' name: parameter.name label: parameter.label description: parameter.help required: parameter.required values: parameter.values value: value selection: selection defaultValue: parameter.default_value help: node$ 'Help goes here.' isInvalid: node$ no createCheckboxControl = (parameter) -> value = node$ parameter.actual_value is 'true' #FIXME clientId: do uniqueId kind: 'checkbox' name: parameter.name label: parameter.label description: parameter.help required: parameter.required value: value defaultValue: parameter.default_value is 'true' help: node$ 'Help goes here.' isInvalid: node$ no createControlFromParameter = (parameter) -> switch parameter.type when 'enum', 'Frame', 'string' createDropdownControl parameter when 'string[]' createListControl parameter when 'boolean' createCheckboxControl parameter when 'Key', 'int', 'long', 'float', 'double', 'int[]', 'long[]', 'float[]', 'double[]' createTextboxControl parameter else console.error 'Invalid field', JSON.stringify parameter, null, 2 null findParameter = (parameters, name) -> find parameters, (parameter) -> parameter.name is name Steam.ModelBuilderForm = (_, _algorithm, _parameters, _go) -> _validationError = node$ null _parametersByLevel = groupBy _parameters, (parameter) -> parameter.level _controls = map [ 'critical', 'secondary', 'expert' ], (type) -> filter (map _parametersByLevel[type], createControlFromParameter), isTruthy [ _criticalControls, _secondaryControls, _expertControls ] = _controls parameterTemplateOf = (control) -> "#{control.kind}-model-parameter" createModel = -> _validationError null parameters = {} for controls in _controls for control in controls if control.defaultValue isnt value = control.value() switch control.kind when 'dropdown' if value parameters[control.name] = value when 'list' if value.length parameters[control.name] = "[#{value.join ','}]" else parameters[control.name] = value _.requestModelBuild _algorithm.key, parameters, (error, result) -> if error _validationError message: error.data.errmsg else _go 'confirm' title: "Configure #{_algorithm.title} Model" criticalControls: _criticalControls secondaryControls: _secondaryControls expertControls: _expertControls validationError: _validationError parameterTemplateOf: parameterTemplateOf createModel: createModel Steam.CreateModelDialog = (_, _frameKey, _sourceModel, _go) -> [ _isAlgorithmSelectionMode, _isModelCreationMode ] = switch$ no, 2 _title = node$ 'New Model' _canChangeAlgorithm = node$ yes _algorithms = nodes$ [] _modelForm = node$ null populateFramesAndColumns = (frameKey, algorithm, parameters, go) -> # Fetch frame list; pick column names from training frame _.requestFrames (error, result) -> if error #TODO handle properly else trainingFrameParameter = findParameter parameters, 'training_frame' #XXX temporary bail out for GLM unless trainingFrameParameter console.error "Model does not have a 'training_frame' parameter!" return go() trainingFrameParameter.values = map result.frames, (frame) -> frame.key.name if frameKey trainingFrameParameter.actual_value = frameKey else frameKey = trainingFrameParameter.actual_value if algorithm.key is 'deep<KEY>' validationFrameParameter = findParameter parameters, 'validation_frame' responseColumnParameter = findParameter parameters, 'response_column' #TODO HACK hard-coding DL column params for now - rework this when Vec type is supported. #responseColumnParameter.type = 'Vec' ignoredColumnsParameter = findParameter parameters, 'ignored_columns' #TODO HACK hard-coding DL column params for now - rework this when Vec type is supported. #ignoredColumnsParameter.type = 'Vec[]' validationFrameParameter.values = copy trainingFrameParameter.values if trainingFrame = (find result.frames, (frame) -> frame.key.name is frameKey) columnLabels = map trainingFrame.columns, (column) -> column.label sort columnLabels responseColumnParameter.values = columnLabels ignoredColumnsParameter.values = columnLabels else if algorithm.key is '<KEY>' #validationFrameParameter = findParameter parameters, 'validation_frame' responseColumnParameter = findParameter parameters, 'response_column' #TODO HACK hard-coding DL column params for now - rework this when Vec type is supported. #responseColumnParameter.type = 'Vec' #ignoredColumnsParameter = findParameter parameters, 'ignored_columns' #TODO HACK hard-coding DL column params for now - rework this when Vec type is supported. #ignoredColumnsParameter.type = 'Vec[]' #validationFrameParameter.values = copy trainingFrameParameter.values if trainingFrame = (find result.frames, (frame) -> frame.key.name is frameKey) columnLabels = map trainingFrame.columns, (column) -> column.label sort columnLabels responseColumnParameter.values = columnLabels #ignoredColumnsParameter.values = columnLabels go() _.requestModelBuilders (error, algorithms) -> algorithms = for algorithm in algorithms key: algorithm title: algorithm # If a source model is specified, we already know the algo, so skip algo selection if _sourceModel _title 'Clone Model' _canChangeAlgorithm no _isModelCreationMode yes selectAlgorithm = noop parameters = _sourceModel.parameters #TODO INSANE SUPERHACK hasRateAnnealing = find _sourceModel.parameters, (parameter) -> parameter.name is 'rate_annealing' algorithm = if hasRateAnnealing find algorithms, (algorithm) -> algorithm.key is '<KEY>' else find algorithms, (algorithm) -> algorithm.key is 'kmeans' populateFramesAndColumns _frameKey, algorithm, parameters, -> _modelForm Steam.ModelBuilderForm _, algorithm, parameters, _go else _isAlgorithmSelectionMode yes selectAlgorithm = (algorithm) -> _.requestModelBuilder algorithm.key, (error, result) -> if error #TODO handle properly else parameters = result.model_builders[algorithm.key].parameters populateFramesAndColumns _frameKey, algorithm, parameters, -> _modelForm Steam.ModelBuilderForm _, algorithm, parameters, _go _isModelCreationMode yes _algorithms map algorithms, (algorithm) -> self = title: algorithm.title data: algorithm select: -> selectAlgorithm self.data backToAlgorithms = -> _isAlgorithmSelectionMode yes createModel = -> _modelForm().createModel() cancel = -> _go 'cancel' title: _title isAlgorithmSelectionMode: _isAlgorithmSelectionMode isModelCreationMode: _isModelCreationMode algorithms: _algorithms modelForm: _modelForm cancel: cancel canChangeAlgorithm: _canChangeAlgorithm backToAlgorithms: backToAlgorithms createModel: createModel template: 'create-model-dialog'
true
createTextboxControl = (parameter) -> value = node$ parameter.actual_value kind: 'textbox' name: parameter.name label: parameter.label description: parameter.help required: parameter.required value: value defaultValue: parameter.default_value help: node$ 'Help goes here.' isInvalid: node$ no createDropdownControl = (parameter) -> value = node$ parameter.actual_value kind: 'dropdown' name: parameter.name label: parameter.label description: parameter.help required: parameter.required values: parameter.values value: value defaultValue: parameter.default_value help: node$ 'Help goes here.' isInvalid: node$ no createListControl = (parameter) -> value = node$ parameter.actual_value or [] selection = lift$ value, (values) -> caption = "#{describeCount values.length, 'column'} selected" caption += ": #{values.join ', '}" if values.length > 0 "(#{caption})" kind: 'list' name: parameter.name label: parameter.label description: parameter.help required: parameter.required values: parameter.values value: value selection: selection defaultValue: parameter.default_value help: node$ 'Help goes here.' isInvalid: node$ no createCheckboxControl = (parameter) -> value = node$ parameter.actual_value is 'true' #FIXME clientId: do uniqueId kind: 'checkbox' name: parameter.name label: parameter.label description: parameter.help required: parameter.required value: value defaultValue: parameter.default_value is 'true' help: node$ 'Help goes here.' isInvalid: node$ no createControlFromParameter = (parameter) -> switch parameter.type when 'enum', 'Frame', 'string' createDropdownControl parameter when 'string[]' createListControl parameter when 'boolean' createCheckboxControl parameter when 'Key', 'int', 'long', 'float', 'double', 'int[]', 'long[]', 'float[]', 'double[]' createTextboxControl parameter else console.error 'Invalid field', JSON.stringify parameter, null, 2 null findParameter = (parameters, name) -> find parameters, (parameter) -> parameter.name is name Steam.ModelBuilderForm = (_, _algorithm, _parameters, _go) -> _validationError = node$ null _parametersByLevel = groupBy _parameters, (parameter) -> parameter.level _controls = map [ 'critical', 'secondary', 'expert' ], (type) -> filter (map _parametersByLevel[type], createControlFromParameter), isTruthy [ _criticalControls, _secondaryControls, _expertControls ] = _controls parameterTemplateOf = (control) -> "#{control.kind}-model-parameter" createModel = -> _validationError null parameters = {} for controls in _controls for control in controls if control.defaultValue isnt value = control.value() switch control.kind when 'dropdown' if value parameters[control.name] = value when 'list' if value.length parameters[control.name] = "[#{value.join ','}]" else parameters[control.name] = value _.requestModelBuild _algorithm.key, parameters, (error, result) -> if error _validationError message: error.data.errmsg else _go 'confirm' title: "Configure #{_algorithm.title} Model" criticalControls: _criticalControls secondaryControls: _secondaryControls expertControls: _expertControls validationError: _validationError parameterTemplateOf: parameterTemplateOf createModel: createModel Steam.CreateModelDialog = (_, _frameKey, _sourceModel, _go) -> [ _isAlgorithmSelectionMode, _isModelCreationMode ] = switch$ no, 2 _title = node$ 'New Model' _canChangeAlgorithm = node$ yes _algorithms = nodes$ [] _modelForm = node$ null populateFramesAndColumns = (frameKey, algorithm, parameters, go) -> # Fetch frame list; pick column names from training frame _.requestFrames (error, result) -> if error #TODO handle properly else trainingFrameParameter = findParameter parameters, 'training_frame' #XXX temporary bail out for GLM unless trainingFrameParameter console.error "Model does not have a 'training_frame' parameter!" return go() trainingFrameParameter.values = map result.frames, (frame) -> frame.key.name if frameKey trainingFrameParameter.actual_value = frameKey else frameKey = trainingFrameParameter.actual_value if algorithm.key is 'deepPI:KEY:<KEY>END_PI' validationFrameParameter = findParameter parameters, 'validation_frame' responseColumnParameter = findParameter parameters, 'response_column' #TODO HACK hard-coding DL column params for now - rework this when Vec type is supported. #responseColumnParameter.type = 'Vec' ignoredColumnsParameter = findParameter parameters, 'ignored_columns' #TODO HACK hard-coding DL column params for now - rework this when Vec type is supported. #ignoredColumnsParameter.type = 'Vec[]' validationFrameParameter.values = copy trainingFrameParameter.values if trainingFrame = (find result.frames, (frame) -> frame.key.name is frameKey) columnLabels = map trainingFrame.columns, (column) -> column.label sort columnLabels responseColumnParameter.values = columnLabels ignoredColumnsParameter.values = columnLabels else if algorithm.key is 'PI:KEY:<KEY>END_PI' #validationFrameParameter = findParameter parameters, 'validation_frame' responseColumnParameter = findParameter parameters, 'response_column' #TODO HACK hard-coding DL column params for now - rework this when Vec type is supported. #responseColumnParameter.type = 'Vec' #ignoredColumnsParameter = findParameter parameters, 'ignored_columns' #TODO HACK hard-coding DL column params for now - rework this when Vec type is supported. #ignoredColumnsParameter.type = 'Vec[]' #validationFrameParameter.values = copy trainingFrameParameter.values if trainingFrame = (find result.frames, (frame) -> frame.key.name is frameKey) columnLabels = map trainingFrame.columns, (column) -> column.label sort columnLabels responseColumnParameter.values = columnLabels #ignoredColumnsParameter.values = columnLabels go() _.requestModelBuilders (error, algorithms) -> algorithms = for algorithm in algorithms key: algorithm title: algorithm # If a source model is specified, we already know the algo, so skip algo selection if _sourceModel _title 'Clone Model' _canChangeAlgorithm no _isModelCreationMode yes selectAlgorithm = noop parameters = _sourceModel.parameters #TODO INSANE SUPERHACK hasRateAnnealing = find _sourceModel.parameters, (parameter) -> parameter.name is 'rate_annealing' algorithm = if hasRateAnnealing find algorithms, (algorithm) -> algorithm.key is 'PI:KEY:<KEY>END_PI' else find algorithms, (algorithm) -> algorithm.key is 'kmeans' populateFramesAndColumns _frameKey, algorithm, parameters, -> _modelForm Steam.ModelBuilderForm _, algorithm, parameters, _go else _isAlgorithmSelectionMode yes selectAlgorithm = (algorithm) -> _.requestModelBuilder algorithm.key, (error, result) -> if error #TODO handle properly else parameters = result.model_builders[algorithm.key].parameters populateFramesAndColumns _frameKey, algorithm, parameters, -> _modelForm Steam.ModelBuilderForm _, algorithm, parameters, _go _isModelCreationMode yes _algorithms map algorithms, (algorithm) -> self = title: algorithm.title data: algorithm select: -> selectAlgorithm self.data backToAlgorithms = -> _isAlgorithmSelectionMode yes createModel = -> _modelForm().createModel() cancel = -> _go 'cancel' title: _title isAlgorithmSelectionMode: _isAlgorithmSelectionMode isModelCreationMode: _isModelCreationMode algorithms: _algorithms modelForm: _modelForm cancel: cancel canChangeAlgorithm: _canChangeAlgorithm backToAlgorithms: backToAlgorithms createModel: createModel template: 'create-model-dialog'
[ { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri", "end": 42, "score": 0.9998452067375183, "start": 24, "tag": "NAME", "value": "Alexander Cherniuk" }, { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmai...
library/membrane/runtime.coffee
ts33kr/granite
6
### Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" asciify = require "asciify" connect = require "connect" logger = require "winston" coffee = require "coffee-script" events = require "eventemitter2" assert = require "assert" colors = require "colors" nconf = require "nconf" https = require "https" http = require "http" util = require "util" # This exports the function whose source codes installs the usual # CoffeeScript runtime definitions. This is necessary to properly # initialize the remote call site, because the source code capture # mechanism is not able to capture these, when emited by compiler. # These definitions should generally be safe, being idempotent. module.exports.coffee = `function () { __slice = [].slice __hasProp = {}.hasOwnProperty __indexOf = [].indexOf || _.indexOf __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }; function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }}; `
39418
### Copyright (c) 2013, <NAME> <<EMAIL>> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" asciify = require "asciify" connect = require "connect" logger = require "winston" coffee = require "coffee-script" events = require "eventemitter2" assert = require "assert" colors = require "colors" nconf = require "nconf" https = require "https" http = require "http" util = require "util" # This exports the function whose source codes installs the usual # CoffeeScript runtime definitions. This is necessary to properly # initialize the remote call site, because the source code capture # mechanism is not able to capture these, when emited by compiler. # These definitions should generally be safe, being idempotent. module.exports.coffee = `function () { __slice = [].slice __hasProp = {}.hasOwnProperty __indexOf = [].indexOf || _.indexOf __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }; function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }}; `
true
### Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" asciify = require "asciify" connect = require "connect" logger = require "winston" coffee = require "coffee-script" events = require "eventemitter2" assert = require "assert" colors = require "colors" nconf = require "nconf" https = require "https" http = require "http" util = require "util" # This exports the function whose source codes installs the usual # CoffeeScript runtime definitions. This is necessary to properly # initialize the remote call site, because the source code capture # mechanism is not able to capture these, when emited by compiler. # These definitions should generally be safe, being idempotent. module.exports.coffee = `function () { __slice = [].slice __hasProp = {}.hasOwnProperty __indexOf = [].indexOf || _.indexOf __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }; function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }}; `
[ { "context": "ull\n\n\n beforeEach ->\n options = { name: 'combo2x' }\n data = [\n { title: 'Fiat', valu", "end": 236, "score": 0.7817550897598267, "start": 234, "tag": "USERNAME", "value": "2x" }, { "context": " with setValue method', ->\n combobox.setValue 'hon...
src/tests/components/combobox/test_combobox.coffee
dashersw/spark
1
goog = goog or goog = require: -> goog.require 'spark.components.ComboBox' goog.require 'goog.ui.MenuItem' describe 'spark.components.ComboBox', -> combobox = null element = null beforeEach -> options = { name: 'combo2x' } data = [ { title: 'Fiat', value: 'fiat' } { title: 'Ford', value: 'ford' } { title: 'Mazda', value: 'mazda' } { title: 'BMW', value: 'bmw' } { title: 'Honda', value: 'honda' } { title: 'Ferrari', value: 'ferrari' } ] combobox = new spark.components.ComboBox options, data element = combobox.getElement() it 'should extends spark.core.View', -> expect(combobox instanceof spark.core.View).toBeTruthy() it 'should have default options', -> combo = new spark.components.ComboBox null expect(combo.getOptions()).toBeDefined() it 'should have items array and its length should be correct', -> items = combobox.getItems() expect(items.length).toBe 6 it 'should appended into element and have correct DOM elements', -> children = element.childNodes expect(children[0].classList.contains('title')).toBeTruthy() expect(children[1].classList.contains('arrow')).toBeTruthy() expect(children[2].classList.contains('goog-menu')).toBeTruthy() it 'should toggle menu when it is clicked', -> menuElement = element.childNodes[element.childNodes.length - 1] expect(menuElement.style.display).toBe 'none' combobox.toggleMenu() expect(menuElement.style.display).toBe '' combobox.toggleMenu() expect(menuElement.style.display).toBe 'none' combobox.emit 'click' expect(menuElement.style.display).toBe '' combobox.emit 'click' expect(menuElement.style.display).toBe 'none' describe 'createItem', -> it 'should create item from data', -> item = combobox.createItem { title: 'hello', value: 'acet' } expect(combobox.getItems().length).toBe 6 it 'should create and append the item', -> item = combobox.createItem { title: 'hello', value: 'acet' }, yes expect(combobox.getItems().length).toBe 7 describe 'addItem', -> it 'should create goog.ui.MenuItem instance and append it to menu', -> data = { title: 'hello', value: 'acet' } combobox.addItem data expect(combobox.getItems().length).toBe 7 it 'should create instance and add it to given index', -> data = { title: 'Spark', value: 'spark' } combobox.addItem data, 4 menuElement = element.childNodes[element.childNodes.length - 1] fourthItem = menuElement.childNodes[4].childNodes[0] expect(fourthItem.innerHTML).toBe 'Spark' it 'should handle not valid parameter for item', -> combobox.addItem 'string' expect(combobox.getItems().length).toBe 6 it 'should remove item', -> item = combobox.getItems()[3] combobox.removeItem item items = combobox.getItems() expect(items.length).toBe 5 expect(items.indexOf(item)).toBe -1 it 'should remove item at given index', -> fourth = combobox.getItemAt 4 fourthData = combobox.getItemData fourth combobox.removeItemAt 4 newFourth = combobox.getItemAt 4 newFourthData = combobox.getItemData newFourth expect(fourthData.title).not.toBe newFourthData.title it 'should return item at given index', -> second = combobox.getItemAt 2 expect(combobox.getItemData(second).title).toBe 'Mazda' it 'should return item with value', -> ferrari = combobox.getItemByValue 'ferrari' ferrariData = combobox.getItemData ferrari expect(ferrariData.title).toBe 'Ferrari' it 'should select item', -> item = combobox.getItemAt 2 combobox.selectItem item expect(combobox.getValue()).toBe 'mazda' it 'should select item at index', -> combobox.selectItemAt 4 expect(combobox.getValue()).toBe 'honda' it 'should select item by value', -> combobox.selectItemByValue 'bmw' expect(combobox.getValue()).toBe 'bmw' it 'should select item with setValue method', -> combobox.setValue 'honda' expect(combobox.getValue()).toBe 'honda' it 'should return selected item', -> expect(combobox.getSelectedItemData()).toBeNull() expect(combobox.getSelectedItem()).toBeNull() combobox.selectItemAt 2 expect(combobox.getSelectedItemData().title).toBe 'Mazda' it 'should emit selected event when an item is selected', -> flag = no data = null combobox.on 'selected', (e) -> flag = yes data = e.data combobox.selectItemAt 2 expect(flag).toBeTruthy() expect(data.value).toBe 'mazda' expect(data.title).toBe 'Mazda' expect(data.data).toBeDefined() it 'should dispatch event with uncompiled code', -> if goog.events?.dispatchEvent? combobox.selectItemAt 1 try goog.events.dispatchEvent combobox.menu_, 'action' it 'should return combobox name or null', -> expect(combobox.getName()).toBe 'combo2x' cb = new spark.components.ComboBox expect(cb.getName()).toBeNull() it 'should select item by value if selectedItemValue passed', -> options = { selectedItemValue: 'item2' } data = [ { title: 'item 1', value: 'item1' } { title: 'item 2', value: 'item2' } { title: 'item 3', value: 'item3' } ] cb = new spark.components.ComboBox options, data selectedData = cb.getSelectedItemData() expect(selectedData.title).toBe 'item 2' expect(selectedData.value).toBe 'item2'
37270
goog = goog or goog = require: -> goog.require 'spark.components.ComboBox' goog.require 'goog.ui.MenuItem' describe 'spark.components.ComboBox', -> combobox = null element = null beforeEach -> options = { name: 'combo2x' } data = [ { title: 'Fiat', value: 'fiat' } { title: 'Ford', value: 'ford' } { title: 'Mazda', value: 'mazda' } { title: 'BMW', value: 'bmw' } { title: 'Honda', value: 'honda' } { title: 'Ferrari', value: 'ferrari' } ] combobox = new spark.components.ComboBox options, data element = combobox.getElement() it 'should extends spark.core.View', -> expect(combobox instanceof spark.core.View).toBeTruthy() it 'should have default options', -> combo = new spark.components.ComboBox null expect(combo.getOptions()).toBeDefined() it 'should have items array and its length should be correct', -> items = combobox.getItems() expect(items.length).toBe 6 it 'should appended into element and have correct DOM elements', -> children = element.childNodes expect(children[0].classList.contains('title')).toBeTruthy() expect(children[1].classList.contains('arrow')).toBeTruthy() expect(children[2].classList.contains('goog-menu')).toBeTruthy() it 'should toggle menu when it is clicked', -> menuElement = element.childNodes[element.childNodes.length - 1] expect(menuElement.style.display).toBe 'none' combobox.toggleMenu() expect(menuElement.style.display).toBe '' combobox.toggleMenu() expect(menuElement.style.display).toBe 'none' combobox.emit 'click' expect(menuElement.style.display).toBe '' combobox.emit 'click' expect(menuElement.style.display).toBe 'none' describe 'createItem', -> it 'should create item from data', -> item = combobox.createItem { title: 'hello', value: 'acet' } expect(combobox.getItems().length).toBe 6 it 'should create and append the item', -> item = combobox.createItem { title: 'hello', value: 'acet' }, yes expect(combobox.getItems().length).toBe 7 describe 'addItem', -> it 'should create goog.ui.MenuItem instance and append it to menu', -> data = { title: 'hello', value: 'acet' } combobox.addItem data expect(combobox.getItems().length).toBe 7 it 'should create instance and add it to given index', -> data = { title: 'Spark', value: 'spark' } combobox.addItem data, 4 menuElement = element.childNodes[element.childNodes.length - 1] fourthItem = menuElement.childNodes[4].childNodes[0] expect(fourthItem.innerHTML).toBe 'Spark' it 'should handle not valid parameter for item', -> combobox.addItem 'string' expect(combobox.getItems().length).toBe 6 it 'should remove item', -> item = combobox.getItems()[3] combobox.removeItem item items = combobox.getItems() expect(items.length).toBe 5 expect(items.indexOf(item)).toBe -1 it 'should remove item at given index', -> fourth = combobox.getItemAt 4 fourthData = combobox.getItemData fourth combobox.removeItemAt 4 newFourth = combobox.getItemAt 4 newFourthData = combobox.getItemData newFourth expect(fourthData.title).not.toBe newFourthData.title it 'should return item at given index', -> second = combobox.getItemAt 2 expect(combobox.getItemData(second).title).toBe 'Mazda' it 'should return item with value', -> ferrari = combobox.getItemByValue 'ferrari' ferrariData = combobox.getItemData ferrari expect(ferrariData.title).toBe 'Ferrari' it 'should select item', -> item = combobox.getItemAt 2 combobox.selectItem item expect(combobox.getValue()).toBe 'mazda' it 'should select item at index', -> combobox.selectItemAt 4 expect(combobox.getValue()).toBe 'honda' it 'should select item by value', -> combobox.selectItemByValue 'bmw' expect(combobox.getValue()).toBe 'bmw' it 'should select item with setValue method', -> combobox.setValue '<NAME>' expect(combobox.getValue()).toBe 'honda' it 'should return selected item', -> expect(combobox.getSelectedItemData()).toBeNull() expect(combobox.getSelectedItem()).toBeNull() combobox.selectItemAt 2 expect(combobox.getSelectedItemData().title).toBe 'Mazda' it 'should emit selected event when an item is selected', -> flag = no data = null combobox.on 'selected', (e) -> flag = yes data = e.data combobox.selectItemAt 2 expect(flag).toBeTruthy() expect(data.value).toBe 'mazda' expect(data.title).toBe 'Mazda' expect(data.data).toBeDefined() it 'should dispatch event with uncompiled code', -> if goog.events?.dispatchEvent? combobox.selectItemAt 1 try goog.events.dispatchEvent combobox.menu_, 'action' it 'should return combobox name or null', -> expect(combobox.getName()).toBe 'combo2x' cb = new spark.components.ComboBox expect(cb.getName()).toBeNull() it 'should select item by value if selectedItemValue passed', -> options = { selectedItemValue: 'item2' } data = [ { title: 'item 1', value: 'item1' } { title: 'item 2', value: 'item2' } { title: 'item 3', value: 'item3' } ] cb = new spark.components.ComboBox options, data selectedData = cb.getSelectedItemData() expect(selectedData.title).toBe 'item 2' expect(selectedData.value).toBe 'item2'
true
goog = goog or goog = require: -> goog.require 'spark.components.ComboBox' goog.require 'goog.ui.MenuItem' describe 'spark.components.ComboBox', -> combobox = null element = null beforeEach -> options = { name: 'combo2x' } data = [ { title: 'Fiat', value: 'fiat' } { title: 'Ford', value: 'ford' } { title: 'Mazda', value: 'mazda' } { title: 'BMW', value: 'bmw' } { title: 'Honda', value: 'honda' } { title: 'Ferrari', value: 'ferrari' } ] combobox = new spark.components.ComboBox options, data element = combobox.getElement() it 'should extends spark.core.View', -> expect(combobox instanceof spark.core.View).toBeTruthy() it 'should have default options', -> combo = new spark.components.ComboBox null expect(combo.getOptions()).toBeDefined() it 'should have items array and its length should be correct', -> items = combobox.getItems() expect(items.length).toBe 6 it 'should appended into element and have correct DOM elements', -> children = element.childNodes expect(children[0].classList.contains('title')).toBeTruthy() expect(children[1].classList.contains('arrow')).toBeTruthy() expect(children[2].classList.contains('goog-menu')).toBeTruthy() it 'should toggle menu when it is clicked', -> menuElement = element.childNodes[element.childNodes.length - 1] expect(menuElement.style.display).toBe 'none' combobox.toggleMenu() expect(menuElement.style.display).toBe '' combobox.toggleMenu() expect(menuElement.style.display).toBe 'none' combobox.emit 'click' expect(menuElement.style.display).toBe '' combobox.emit 'click' expect(menuElement.style.display).toBe 'none' describe 'createItem', -> it 'should create item from data', -> item = combobox.createItem { title: 'hello', value: 'acet' } expect(combobox.getItems().length).toBe 6 it 'should create and append the item', -> item = combobox.createItem { title: 'hello', value: 'acet' }, yes expect(combobox.getItems().length).toBe 7 describe 'addItem', -> it 'should create goog.ui.MenuItem instance and append it to menu', -> data = { title: 'hello', value: 'acet' } combobox.addItem data expect(combobox.getItems().length).toBe 7 it 'should create instance and add it to given index', -> data = { title: 'Spark', value: 'spark' } combobox.addItem data, 4 menuElement = element.childNodes[element.childNodes.length - 1] fourthItem = menuElement.childNodes[4].childNodes[0] expect(fourthItem.innerHTML).toBe 'Spark' it 'should handle not valid parameter for item', -> combobox.addItem 'string' expect(combobox.getItems().length).toBe 6 it 'should remove item', -> item = combobox.getItems()[3] combobox.removeItem item items = combobox.getItems() expect(items.length).toBe 5 expect(items.indexOf(item)).toBe -1 it 'should remove item at given index', -> fourth = combobox.getItemAt 4 fourthData = combobox.getItemData fourth combobox.removeItemAt 4 newFourth = combobox.getItemAt 4 newFourthData = combobox.getItemData newFourth expect(fourthData.title).not.toBe newFourthData.title it 'should return item at given index', -> second = combobox.getItemAt 2 expect(combobox.getItemData(second).title).toBe 'Mazda' it 'should return item with value', -> ferrari = combobox.getItemByValue 'ferrari' ferrariData = combobox.getItemData ferrari expect(ferrariData.title).toBe 'Ferrari' it 'should select item', -> item = combobox.getItemAt 2 combobox.selectItem item expect(combobox.getValue()).toBe 'mazda' it 'should select item at index', -> combobox.selectItemAt 4 expect(combobox.getValue()).toBe 'honda' it 'should select item by value', -> combobox.selectItemByValue 'bmw' expect(combobox.getValue()).toBe 'bmw' it 'should select item with setValue method', -> combobox.setValue 'PI:NAME:<NAME>END_PI' expect(combobox.getValue()).toBe 'honda' it 'should return selected item', -> expect(combobox.getSelectedItemData()).toBeNull() expect(combobox.getSelectedItem()).toBeNull() combobox.selectItemAt 2 expect(combobox.getSelectedItemData().title).toBe 'Mazda' it 'should emit selected event when an item is selected', -> flag = no data = null combobox.on 'selected', (e) -> flag = yes data = e.data combobox.selectItemAt 2 expect(flag).toBeTruthy() expect(data.value).toBe 'mazda' expect(data.title).toBe 'Mazda' expect(data.data).toBeDefined() it 'should dispatch event with uncompiled code', -> if goog.events?.dispatchEvent? combobox.selectItemAt 1 try goog.events.dispatchEvent combobox.menu_, 'action' it 'should return combobox name or null', -> expect(combobox.getName()).toBe 'combo2x' cb = new spark.components.ComboBox expect(cb.getName()).toBeNull() it 'should select item by value if selectedItemValue passed', -> options = { selectedItemValue: 'item2' } data = [ { title: 'item 1', value: 'item1' } { title: 'item 2', value: 'item2' } { title: 'item 3', value: 'item3' } ] cb = new spark.components.ComboBox options, data selectedData = cb.getSelectedItemData() expect(selectedData.title).toBe 'item 2' expect(selectedData.value).toBe 'item2'
[ { "context": "'/login', ->\n authenticated = @req.body.user is 'coffee' and @req.body.pass is 'mate'\n if authenticated\n", "end": 394, "score": 0.922696053981781, "start": 388, "tag": "USERNAME", "value": "coffee" }, { "context": "@req.body.user is 'coffee' and @req.body.pass is '...
examples/simple_auth/app.coffee
kadirpekel/coffeemate
2
mate = require '../../coffeemate' mate.cookieParser() mate.bodyParser() mate.context.authenticate = -> authenticated = @req.cookies.authenticated is 'yes' @redirect '/login' unless authenticated return authenticated mate.get '/', -> @render 'main.eco' if @authenticate() mate.get '/login', -> @render 'login.eco' mate.post '/login', -> authenticated = @req.body.user is 'coffee' and @req.body.pass is 'mate' if authenticated @resp.setHeader("Set-Cookie", ["authenticated=yes"]) @redirect '/' else @redirect '/login' mate.listen 3000
50106
mate = require '../../coffeemate' mate.cookieParser() mate.bodyParser() mate.context.authenticate = -> authenticated = @req.cookies.authenticated is 'yes' @redirect '/login' unless authenticated return authenticated mate.get '/', -> @render 'main.eco' if @authenticate() mate.get '/login', -> @render 'login.eco' mate.post '/login', -> authenticated = @req.body.user is 'coffee' and @req.body.pass is '<PASSWORD>' if authenticated @resp.setHeader("Set-Cookie", ["authenticated=yes"]) @redirect '/' else @redirect '/login' mate.listen 3000
true
mate = require '../../coffeemate' mate.cookieParser() mate.bodyParser() mate.context.authenticate = -> authenticated = @req.cookies.authenticated is 'yes' @redirect '/login' unless authenticated return authenticated mate.get '/', -> @render 'main.eco' if @authenticate() mate.get '/login', -> @render 'login.eco' mate.post '/login', -> authenticated = @req.body.user is 'coffee' and @req.body.pass is 'PI:PASSWORD:<PASSWORD>END_PI' if authenticated @resp.setHeader("Set-Cookie", ["authenticated=yes"]) @redirect '/' else @redirect '/login' mate.listen 3000
[ { "context": "dd inline style\n # refer: https://github.com/Karl33to/jquery.inlineStyler\n # TODO still too much r", "end": 18107, "score": 0.9992672204971313, "start": 18099, "tag": "USERNAME", "value": "Karl33to" }, { "context": "te>'\n\n # make title\n title = ...
app/assets/javascripts/app.coffee
zenja/markever
0
"use strict" markever = angular.module('markever', ['ngResource', 'ui.bootstrap', 'LocalStorageModule', 'angularUUID2']) markever.controller 'EditorController', ['$scope', '$window', '$document', '$http', '$sce', '$interval', 'localStorageService', 'enmlRenderer', 'scrollSyncor', 'apiClient', 'noteManager', 'imageManager', 'dbProvider', 'notifier', 'offlineStateManager', ($scope, $window, $document, $http, $sce, $interval localStorageService, enmlRenderer, scrollSyncor, apiClient, noteManager, imageManager, dbProvider, notifier, offlineStateManager) -> vm = this # ------------------------------------------------------------------------------------------------------------------ # Models # ------------------------------------------------------------------------------------------------------------------ # ------------------------------------------------------------------------------------------------------------------ # Debugging methods # ------------------------------------------------------------------------------------------------------------------ vm._debug_show_current_note = () -> alert(JSON.stringify(vm.note)) vm._debug_close_db = () -> dbProvider.close_db() alert('db closed!') vm._debug_show_current_note_in_db = () -> noteManager.find_note_by_guid(vm.get_guid()).then (note) => alert('current note (' + vm.get_guid() + ') in db is: ' + JSON.stringify(note)) vm._debug_offline_check = -> $window.Offline.check() # ------------------------------------------------------------------------------------------------------------------ # App ready status # ------------------------------------------------------------------------------------------------------------------ vm.all_ready = false # ------------------------------------------------------------------------------------------------------------------ # Document ready # ------------------------------------------------------------------------------------------------------------------ $document.ready -> # init ace editor vm.init_ace_editor() # init ui vm.init_ui() # sync scroll scrollSyncor.syncScroll(vm.ace_editor, $('#md_html_div')) noteManager.init_current_note() # get note list from local noteManager.reload_local_note_list() # get note list from remote if not offlineStateManager.is_offline() noteManager.fetch_note_list() else console.log('offline mode, did not fetch note list from remote') # get notebook list from local noteManager.reload_local_notebook_list() # get notebook list from remote if not offlineStateManager.is_offline() noteManager.fetch_notebook_list() else console.log('offline mode, did not fetch notebook list from remote') # take effect the settings vm.set_keyboard_handler(vm.current_keyboard_handler) vm.set_show_gutter(vm.current_show_gutter) vm.set_ace_theme(vm.current_ace_theme) # reset app status vm.reset_status() # all ready vm.all_ready = true # ------------------------------------------------------------------------------------------------------------------ # UI Logic that has to be made by js # ------------------------------------------------------------------------------------------------------------------ vm.init_ui = -> # when showing note list which is a modal, make the backdrop to be transparent $('#note_list_div').on 'show.bs.modal hidden.bs.modal', () -> $('body').toggleClass('modal-backdrop-transparent') # ------------------------------------------------------------------------------------------------------------------ # ace editor init # ------------------------------------------------------------------------------------------------------------------ vm.init_ace_editor = -> $window.ace.config.set('basePath', '/javascripts/ace') vm.ace_editor = $window.ace.edit("md_editor_div") vm.ace_editor.renderer.setShowGutter(false) vm.ace_editor.setShowPrintMargin(false) vm.ace_editor.getSession().setMode("ace/mode/markdown") vm.ace_editor.getSession().setUseWrapMode(true) vm.ace_editor.setTheme('ace/theme/tomorrow_night_eighties') vm.ace_editor.on 'change', vm.editor_content_changed vm.ace_editor.focus() # ------------------------------------------------------------------------------------------------------------------ # ace editor event handlers # ------------------------------------------------------------------------------------------------------------------ vm.editor_content_changed = (event) -> # render html, since noteManager will not notify back if use editor_content_changed(...) enmlRenderer.render_html($('#md_html_div'), vm.ace_editor.getValue()) noteManager.editor_content_changed(vm.ace_editor.getValue()) # ------------------------------------------------------------------------------------------------------------------ # Operations for notes # ------------------------------------------------------------------------------------------------------------------ vm.load_note = (guid) -> if guid == noteManager.get_current_note_guid() return noteManager.is_note_loadable_locally_promise(guid).then (loadable_locally) -> if not loadable_locally and offlineStateManager.is_offline() notifier.info('Cannot load note in offline mode') else vm.open_loading_modal() noteManager.load_note(guid) vm.sync_up_all_notes = -> if offlineStateManager.is_offline() notifier.info('Cannot sync up notes in offline mode') return if vm.saving_note == false vm.saving_note = true p = noteManager.sync_up_all_notes($('#md_html_div_hidden')).then () => notifier.success('sync_up_all_notes() succeeded for all notes!') vm.saving_note = false p.catch (error) => notifier.error('vm.sync_up_all_notes() failed: ' + error) vm.saving_note = false # ------------------------------------------------------------------------------------------------------------------ # TODO Note Manager Event Handlers # ------------------------------------------------------------------------------------------------------------------ noteManager.on_current_note_md_modified (new_md) -> vm.ace_editor.setValue(new_md) enmlRenderer.render_html($('#md_html_div'), new_md).catch (error) => notifier.error('render error: ' + error) console.log('on_current_note_md_modified()') noteManager.on_current_note_switched (new_note_guid) -> enmlRenderer.render_html($('#md_html_div'), noteManager.get_current_note_md()) noteManager.on_note_load_finished (is_success, guid, error) -> vm.close_loading_modal() if is_success console.log('load note ' + guid + ' succeeded') else notifier.error('load note ' + guid + ' failed: ' + error) noteManager.on_note_synced (is_success, old_guid, new_guid, error) -> noteManager.on_note_list_changed (note_list) -> noteManager.on_notebook_list_changed (notebook_list) -> # ------------------------------------------------------------------------------------------------------------------ # App Status # ------------------------------------------------------------------------------------------------------------------ vm.saving_note = false # reset status vm.reset_status = -> # if the note is in process of saving (syncing) or not vm.saving_note = false # ------------------------------------------------------------------------------------------------------------------ # Editor Settings # ------------------------------------------------------------------------------------------------------------------ # settings name constants vm.SETTINGS_KEY = KEYBOARD_HANDLER: 'settings.keyboard_handler' SHOW_GUTTER: 'settings.show_gutter' ACE_THEME: 'settings.ace_theme' CURRENT_NOTE_GUID: 'settings.current_note.guid' # -------------------------------------------------------- # Editor Keyboard Handler Settings # -------------------------------------------------------- vm.keyboard_handlers = [ {name: 'normal', id: ''} {name: 'vim', id: 'ace/keyboard/vim'} ] # load settings from local storage if localStorageService.get(vm.SETTINGS_KEY.KEYBOARD_HANDLER) != null # N.B. should be set to reference, not value! saved_handler = localStorageService.get(vm.SETTINGS_KEY.KEYBOARD_HANDLER) for handler in vm.keyboard_handlers if saved_handler.name == handler.name vm.current_keyboard_handler = handler break else vm.current_keyboard_handler = vm.keyboard_handlers[0] # "new" keyboard handler used in settings modal # N.B. must by reference, not value # refer: http://jsfiddle.net/qWzTb/ # and: https://docs.angularjs.org/api/ng/directive/select vm.new_keyboard_handler = vm.current_keyboard_handler vm.set_keyboard_handler = (handler) -> vm.ace_editor.setKeyboardHandler(handler.id) vm.current_keyboard_handler = handler localStorageService.set(vm.SETTINGS_KEY.KEYBOARD_HANDLER, JSON.stringify(handler)) # -------------------------------------------------------- # Editor Gutter Settings # -------------------------------------------------------- if localStorageService.get(vm.SETTINGS_KEY.KEYBOARD_HANDLER) != null vm.current_show_gutter = JSON.parse(localStorageService.get(vm.SETTINGS_KEY.SHOW_GUTTER)) else vm.current_show_gutter = false vm.new_show_gutter = vm.show_gutter vm.set_show_gutter = (is_show) -> vm.ace_editor.renderer.setShowGutter(is_show) vm.current_show_gutter = is_show localStorageService.set(vm.SETTINGS_KEY.SHOW_GUTTER, JSON.stringify(is_show)) # -------------------------------------------------------- # Editor Theme Settings # -------------------------------------------------------- vm.ace_themes = [ {name: 'default', id: ''} {name: 'ambiance', id: 'ace/theme/ambiance'} {name: 'chaos', id: 'ace/theme/chaos'} {name: 'chrome', id: 'ace/theme/chrome'} {name: 'clouds', id: 'ace/theme/clouds'} {name: 'clouds_midnight', id: 'ace/theme/clouds_midnight'} {name: 'cobalt', id: 'ace/theme/cobalt'} {name: 'crimson_editor', id: 'ace/theme/crimson_editor'} {name: 'dawn', id: 'ace/theme/dawn'} {name: 'dreamweaver', id: 'ace/theme/dreamweaver'} {name: 'eclipse', id: 'ace/theme/eclipse'} {name: 'github', id: 'ace/theme/github'} {name: 'idle_fingers', id: 'ace/theme/idle_fingers'} {name: 'katzenmilch', id: 'ace/theme/katzenmilch'} {name: 'kr_theme', id: 'ace/theme/kr_theme'} {name: 'kuroir', id: 'ace/theme/kuroir'} {name: 'merbivore', id: 'ace/theme/merbivore'} {name: 'merbivore_soft', id: 'ace/theme/merbivore_soft'} {name: 'mono_industrial', id: 'ace/theme/mono_industrial'} {name: 'monokai', id: 'ace/theme/monokai'} {name: 'pastel_on_dark', id: 'ace/theme/pastel_on_dark'} {name: 'solarized_dark', id: 'ace/theme/solarized_dark'} {name: 'solarized_light', id: 'ace/theme/solarized_light'} {name: 'terminal', id: 'ace/theme/terminal'} {name: 'textmate', id: 'ace/theme/textmate'} {name: 'tomorrow', id: 'ace/theme/tomorrow'} {name: 'tomorrow_night', id: 'ace/theme/tomorrow_night'} {name: 'tomorrow_night_blue', id: 'ace/theme/tomorrow_night_blue'} {name: 'tomorrow_night_bright', id: 'ace/theme/tomorrow_night_bright'} {name: 'tomorrow_night_eighties', id: 'ace/theme/tomorrow_night_eighties'} {name: 'twilight', id: 'ace/theme/twilight'} {name: 'vibrant_ink', id: 'ace/theme/vibrant_ink'} {name: 'xcode', id: 'ace/theme/xcode'} ] if localStorageService.get(vm.SETTINGS_KEY.ACE_THEME) != null # N.B. should be set to reference, not value! saved_ace_theme = localStorageService.get(vm.SETTINGS_KEY.ACE_THEME) for theme in vm.ace_themes if saved_ace_theme.name == theme.name vm.current_ace_theme = theme break else vm.current_ace_theme = vm.ace_themes[0] # "new" ace theme used in settings modal # N.B. same, must by reference, not value vm.new_ace_theme = vm.current_ace_theme vm.set_ace_theme = (theme) -> vm.ace_editor.setTheme(theme.id) vm.current_ace_theme = theme localStorageService.set(vm.SETTINGS_KEY.ACE_THEME, JSON.stringify(theme)) # ------------------------------------------------------------------------------------------------------------------ # on paste # ------------------------------------------------------------------------------------------------------------------ vm.handle_paste = (e) => if not vm.ace_editor.isFocused return false items = (e.clipboardData || e.originalEvent.clipboardData).items console.log(JSON.stringify(items)) if items[0].type.match(/image.*/) blob = items[0].getAsFile() image_uuid = imageManager.load_image_blob(blob) vm.ace_editor.insert('![Alt text](' + image_uuid + ')') # ------------------------------------------------------------------------------------------------------------------ # settings modal # ------------------------------------------------------------------------------------------------------------------ vm.open_settings_modal = -> # reset "new" settings to current settings vm.new_keyboard_handler = vm.current_keyboard_handler vm.new_ace_theme = vm.current_ace_theme vm.new_show_gutter = vm.current_show_gutter # show modal $('#settings-modal').modal({}) # explicit return non-DOM result to avoid warning return true vm.save_settings = -> vm.set_ace_theme(vm.new_ace_theme) vm.set_keyboard_handler(vm.new_keyboard_handler) vm.set_show_gutter(vm.new_show_gutter) # ------------------------------------------------------------------------------------------------------------------ # note list modal # ------------------------------------------------------------------------------------------------------------------ vm.open_note_list_modal = -> # clear search keyword vm.search_note_keyword = '' note_list = noteManager.get_note_list() notebook_list = noteManager.get_notebook_list() notebook_name_map = {} notebook_collapse_map = {} for nb in notebook_list notebook_name_map[nb.guid] = nb.name notebook_collapse_map[nb.guid] = true # key: notebook guid; value: Map{notebook_name: String, note_list: Array} note_group_list = {} for n in note_list if not (n.notebook_guid of note_group_list) if n.notebook_guid.trim() == "" note_group_list[n.notebook_guid] = notebook_name: 'Unspecified Notebook' note_list: [] else note_group_list[n.notebook_guid] = notebook_name: notebook_name_map[n.notebook_guid] note_list: [] note_group_list[n.notebook_guid].note_list.push(n) if not vm.notebook_collapse_map? vm.notebook_collapse_map = notebook_collapse_map vm.note_group_list = note_group_list $('#note_list_div').modal({}) # explicit return non-DOM result to avoid warning return true # ------------------------------------------------------------------------------------------------------------------ # toolbar # ------------------------------------------------------------------------------------------------------------------ # ------------------------------------------------------------------------------------------------------------------ # loading modal # ------------------------------------------------------------------------------------------------------------------ vm.open_loading_modal = -> $('#loading-modal').modal({ backdrop: 'static' keyboard: false }) vm.close_loading_modal = -> $('#loading-modal').modal('hide') # fixme for debug vm.note_manager = noteManager ] # ---------------------------------------------------------------------------------------------------------------------- # Service: enmlRenderer # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'enmlRenderer', ['$window', 'imageManager', 'notifier', ($window, imageManager, notifier) -> render_html = (jq_html_div, md) -> processed_md = _md_pre_process(md) _html_dom = $('<div></div>') _html_dom.html($window.marked(processed_md, {sanitize: true})) return _html_post_process(_html_dom).then( () -> jq_html_div.empty() jq_html_div.append(_html_dom) (error) -> notifier.error('render_html() error: ' + error) ) _md_pre_process = (md) -> # TODO more handling processed_md = md return processed_md # return promise _html_post_process = (jq_tmp_div) -> # code highlighting jq_tmp_div.find('pre code').each (i, block) -> hljs.highlightBlock(block) # render Latex $window.MathJax.Hub.Queue(['Typeset', $window.MathJax.Hub, jq_tmp_div.get(0)]) # change img src to real data url must_finish_promise_list = [] jq_tmp_div.find('img[src]').each (index) -> $img = $(this) uuid = $img.attr('src') p = imageManager.find_image_by_uuid(uuid).then( (image) => if image? console.log('change img src from ' + uuid + ' to its base64 content') $img.attr('longdesc', uuid) $img.attr('src', image.content) (error) => notifier.error('_html_post_process() failed due to failure in imageManager.find_image_by_uuid(' + uuid + '): ' + error) ) must_finish_promise_list.push(p.catch (error) -> notifier.error('image replace failed: ' + error)) return Promise.all(must_finish_promise_list).then () -> return jq_tmp_div get_enml_and_title_promise = (jq_html_div, markdown) -> return render_html(jq_html_div, markdown).then () => # further post process # remove all script tags jq_html_div.find('script').remove() # add inline style # refer: https://github.com/Karl33to/jquery.inlineStyler # TODO still too much redundant styles inline_styler_option = { 'propertyGroups' : { 'font-matters' : ['font-size', 'font-family', 'font-style', 'font-weight'], 'text-matters' : ['text-indent', 'text-align', 'text-transform', 'letter-spacing', 'word-spacing', 'word-wrap', 'white-space', 'line-height', 'direction'], 'display-matters' : ['display'], 'size-matters' : ['width', 'height'], 'color-matters' : ['color', 'background-color'], 'position-matters' : ['margin', 'margin-left', 'margin-right', 'margin-top', 'margin-bottom', 'padding', 'padding-left', 'padding-right', 'padding-top', 'padding-bottom', 'float'], 'border-matters' : ['border', 'border-left', 'border-right', 'border-radius', 'border-top', 'border-right', 'border-color'], }, 'elementGroups' : { # N.B. UPPERCASE tags 'font-matters' : ['DIV', 'BLOCKQUOTE', 'SPAN', 'STRONG', 'EM', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'], 'text-matters' : ['SPAN', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'], 'display-matters' : ['HR', 'PRE', 'SPAN', 'UL', 'OL', 'LI', 'PRE', 'CODE'], 'size-matters' : ['SPAN'], 'color-matters' : ['DIV', 'SPAN', 'PRE', 'CODE', 'BLOCKQUOTE', 'HR'], 'position-matters' : ['DIV', 'PRE', 'BLOCKQUOTE', 'SPAN', 'HR', 'UL', 'OL', 'LI', 'P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'], 'border-matters' : ['HR', 'BLOCKQUOTE', 'SPAN', 'PRE', 'CODE'], } } jq_html_div.inlineStyler(inline_styler_option) # set href to start with 'http' is no protocol assigned jq_html_div.find('a').attr 'href', (i, href) -> if not href.toLowerCase().match('(^http)|(^https)|(^file)') return 'http://' + href else return href # clean the html tags/attributes html_clean_option = { format: true, allowedTags: ['a', 'abbr', 'acronym', 'address', 'area', 'b', 'bdo', 'big', 'blockquote', 'br', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'div', 'dl', 'dt', 'em', 'font', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'map', 'ol', 'p', 'pre', 'q', 's', 'samp', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'title', 'tr', 'tt', 'u', 'ul', 'var', 'xmp',], allowedAttributes: [['href', ['a']], ['longdesc'], ['style']], removeAttrs: ['id', 'class', 'onclick', 'ondblclick', 'accesskey', 'data', 'dynsrc', 'tabindex',], } cleaned_html = $.htmlClean(jq_html_div.html(), html_clean_option); # FIXME hack for strange class attr not removed cleaned_html = cleaned_html.replace(/class='[^']*'/g, '') cleaned_html = cleaned_html.replace(/class="[^"]*"/g, '') # embbed raw markdown content into the html cleaned_html = cleaned_html + '<center style="display:none">' + $('<div />').text(markdown).html() + '</center>' # add XML header & wrap with <en-note></en-note> final_note_xml = '<?xml version="1.0" encoding="utf-8"?>' + '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' + '<en-note>' + cleaned_html + '</en-note>' # make title title = 'New Note - Markever' if jq_html_div.find('h1').size() > 0 text = jq_html_div.find('h1').text() title = text if text.trim().length > 0 else if jq_html_div.find('h2').size() > 0 text = jq_html_div.find('h2').text() title = text if text.trim().length > 0 else if jq_html_div.find('h3').size() > 0 text = jq_html_div.find('h3').text() title = text if text.trim().length > 0 else if jq_html_div.find('p').size() > 0 text = jq_html_div.find('p').text() title = text if text.trim().length > 0 # the return value of result promise return {enml: final_note_xml, title: title} get_title_promise = (jq_html_div, markdown) -> return render_html(jq_html_div, markdown).then () => title = 'New Note - Markever' if jq_html_div.find('h1').size() > 0 text = jq_html_div.find('h1').text() title = text if text.trim().length > 0 else if jq_html_div.find('h2').size() > 0 text = jq_html_div.find('h2').text() title = text if text.trim().length > 0 else if jq_html_div.find('h3').size() > 0 text = jq_html_div.find('h3').text() title = text if text.trim().length > 0 else if jq_html_div.find('p').size() > 0 text = jq_html_div.find('p').text() title = text if text.trim().length > 0 return title return { get_enml_and_title_promise : get_enml_and_title_promise get_title_promise: get_title_promise render_html: render_html } ] # ---------------------------------------------------------------------------------------------------------------------- # Service: enmlRenderer # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'scrollSyncor', -> syncScroll = (ace_editor, jq_div) -> ace_editor.setShowPrintMargin(false) # sync scroll: md -> html editor_scroll_handler = (scroll) => percentage = scroll / (ace_editor.session.getScreenLength() * \ ace_editor.renderer.lineHeight - ($(ace_editor.renderer.getContainerElement()).height())) if percentage > 1 or percentage < 0 then return percentage = Math.floor(percentage * 1000) / 1000; # detach other's scroll handler first jq_div.off('scroll', html_scroll_handler) md_html_div = jq_div.get(0) md_html_div.scrollTop = percentage * (md_html_div.scrollHeight - md_html_div.offsetHeight) # re-attach other's scroll handler at the end, with some delay setTimeout (-> jq_div.scroll(html_scroll_handler)), 10 ace_editor.session.on('changeScrollTop', editor_scroll_handler) # sync scroll: html -> md html_scroll_handler = (e) => md_html_div = jq_div.get(0) percentage = md_html_div.scrollTop / (md_html_div.scrollHeight - md_html_div.offsetHeight) if percentage > 1 or percentage < 0 then return percentage = Math.floor(percentage * 1000) / 1000; # detach other's scroll handler first ace_editor.getSession().removeListener('changeScrollTop', editor_scroll_handler); ace_editor.session.setScrollTop((ace_editor.session.getScreenLength() * \ ace_editor.renderer.lineHeight - $(ace_editor.renderer.getContainerElement()).height()) * percentage) # re-attach other's scroll handler at the end, with some delay setTimeout (-> ace_editor.session.on('changeScrollTop', editor_scroll_handler)), 20 jq_div.scroll(html_scroll_handler) return { syncScroll : syncScroll } # ---------------------------------------------------------------------------------------------------------------------- # Service: apiClient # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'apiClient', ['$resource', ($resource) -> new class APIClient note_resource: $resource('/api/v1/notes/:id', {id: '@id'}, { all: {method : 'GET', params : {id: ''}} note: {method : 'GET', params: {}} newest: {method : 'GET', params : {id: 'newest'}} save: {method : 'POST', params: {id: ''}} }) notebook_resource: $resource('/api/v1/notebooks/:id', {id: '@id'}, { all: {method: 'GET', params: {id: ''}} }) # return promise with all notes get_all_notes: () => return @note_resource.all().$promise.then (data) => return data['notes'] # return promise with the note get_note: (guid) => return @note_resource.note({id: guid}).$promise.then (data) => return data.note # return promise with saved note that is returned from remote save_note: (guid, notebook_guid, title, enml) => _post_data = { guid: guid notebookGuid: notebook_guid title: title enml: enml } return @note_resource.save(_post_data).$promise.then (data) => return data.note get_all_notebooks: () => return @notebook_resource.all().$promise.then (data) => return data['notebooks'] ] # ---------------------------------------------------------------------------------------------------------------------- # Service: notifier # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'notifier', -> new class Notifier success: (msg) -> $.bootstrapGrowl(msg, {type: 'success'}) info: (msg) -> $.bootstrapGrowl(msg, {type: 'info'}) error: (msg) -> $.bootstrapGrowl(msg, {type: 'danger'}) # ---------------------------------------------------------------------------------------------------------------------- # Service: offline state manager # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'offlineStateManager', ['$window', 'notifier', ($window, notifier) -> new class OfflineStateManager constructor: -> @initialized = false @_is_offline = false @_init() $window.Offline.check() _init: => if not @initialized $window.Offline.on 'confirmed-up', () => @_is_offline = false #notifier.success('connection up') $window.Offline.on 'confirmed-down', () => @_is_offline = true #notifier.error('connection down') $window.Offline.on 'up', () => @_is_offline = false notifier.success('connection restored') $window.Offline.on 'down', () => @_is_offline = true notifier.error('connection went down') $window.Offline.on 'reconnect:started', () => #notifier.info('reconnecting started') $window.Offline.on 'reconnect:stopped', () => #notifier.info('reconnecting stopped') $window.Offline.on 'reconnect:failure', () => notifier.error('reconnecting failed') is_offline: => return @_is_offline check_connection: => $window.Offline.check() ] # ---------------------------------------------------------------------------------------------------------------------- # Service: dbProvider # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'dbProvider', -> new class DBProvider constructor: -> @db_server_promise = @init_db() init_db: () => db_open_option = { server: 'markever' version: 1 schema: { notes: { key: {keyPath: 'id', autoIncrement: true}, indexes: { guid: {} title: {} notebook_guid: {} status: {} # no need to index md # md: {} } } images: { key: {keyPath: 'id', autoIncrement: true}, indexes: { uuid: {} # no need to index content # content: {} } } } } # db.js promise is not real promise _false_db_p = db.open(db_open_option) return new Promise (resolve, reject) => resolve(_false_db_p) get_db_server_promise: () => console.log('return real promise @db_server_promise') if @db_server_promise? return @db_server_promise else return @init_db() close_db: () => @db_server_promise.then (server) => server.close() console.log('db closed') # ---------------------------------------------------------------------------------------------------------------------- # Service: imageManager # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'imageManager', ['uuid2', 'dbProvider', (uuid2, dbProvider) -> new class ImageManager constructor: -> dbProvider.get_db_server_promise().then (server) => @db_server = server console.log('DB initialized from ImageManager') # ------------------------------------------------------------ # Return a copy of a image in db with a given uuid # # return: promise containing the image's info: # uuid, content # or null if image does not exist # ------------------------------------------------------------ find_image_by_uuid: (uuid) => p = new Promise (resolve, reject) => resolve(@db_server.images.query().filter('uuid', uuid).execute()) return p.then (images) => if images.length == 0 console.log('find_image_by_uuid(' + uuid + ') returned null') return null else console.log('find_image_by_uuid(' + uuid + ') hit') return images[0] # ------------------------------------------------------------ # Add a image to db # # return: promise # ------------------------------------------------------------ add_image: (uuid, content) => console.log('Adding image to db - uuid: ' + uuid) return new Promise (resolve, reject) => resolve( @db_server.images.add({ uuid: uuid content: content }) ) # return: the uuid of the image (NOT promise) load_image_blob: (blob, extra_handler) => uuid = uuid2.newuuid() reader = new FileReader() reader.onload = (event) => console.log("image result: " + event.target.result) @add_image(uuid, event.target.result) # optional extra_handler if extra_handler extra_handler(event) # start reading blob data, and get result in base64 data URL reader.readAsDataURL(blob) return uuid ] # ---------------------------------------------------------------------------------------------------------------------- # Service: noteManager # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'noteManager', ['$interval', 'uuid2', 'localStorageService', 'dbProvider', 'apiClient', 'imageManager', 'enmlRenderer', 'notifier', 'offlineStateManager', ($interval, uuid2, localStorageService, dbProvider, apiClient, imageManager, enmlRenderer, notifier, offlineStateManager) -> new class NoteManager #--------------------------------------------------------------------------------------------------------------------- # Status of a note: # 1. new: note with a generated guid, not attached to remote # 2. synced_meta: note with metadata fetched to remote. not editable # 3. synced_all: note with all data synced with remote. editable # 4. modified: note attached to remote, but has un-synced modification # # Status transition: # # sync modify # new ------> synced_all ---------> modified # ^ <--------- # | sync # | # | load note data from remote # | # synced_meta ------ #--------------------------------------------------------------------------------------------------------------------- constructor: -> $interval(@save_current_note_to_db, 1000) NOTE_STATUS: NEW: 0 SYNCED_META: 1 SYNCED_ALL: 2 MODIFIED: 3 STORAGE_KEY: CURRENT_NOTE_GUID: 'note_manager.current_note.guid' NOTEBOOK_LIST: 'note_manager.notebook_list' # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Current Note > current_note: guid: '' title: '' status: null md: '' notebook_guid: '' _is_dirty: false # ------------------------------------------------------------ # Public accessor for current_note # ------------------------------------------------------------ get_current_note_guid: => return @current_note.guid get_current_note_title: => return @current_note.title get_current_note_status: => return @current_note.status get_current_note_md: => return @current_note.md get_current_note_notebook_guid: => return @current_note.notebook_guid # ------------------------------------------------------------ # Private accessor for current_note # ------------------------------------------------------------ _is_current_note_dirty: () => return @current_note._is_dirty _set_current_note_dirty: (is_dirty) => @current_note._is_dirty = is_dirty _switch_current_note: (guid, notebook_guid, title, md, status) => console.log('_switch_current_note(...) invoked') @_set_current_note_guid(guid) if notebook_guid? @_set_current_note_notebook_guid(notebook_guid) if title? @_set_current_note_title(title) if md? if @get_current_note_md() != md @_set_current_note_md(md) if status? @_set_current_note_status(status) # notify event after current note changed @current_note_switched(guid) _set_current_note_guid: (guid) => @current_note.guid = guid _set_current_note_title: (title) => @current_note.title = title _set_current_note_md: (md, notify=true) => if @get_current_note_md() != md @current_note.md = md if notify @current_note_md_modified(md) # change note status to MODIFIED if original status is SYNCED_ALL if @get_current_note_status() == @NOTE_STATUS.SYNCED_ALL @_set_current_note_status(@NOTE_STATUS.MODIFIED) _set_current_note_status: (status) => @current_note.status = status @reload_local_note_list() _set_current_note_notebook_guid: (notebook_guid) => @current_note.notebook_guid = notebook_guid @reload_local_note_list() # ------------------------------------------------------------ # Other Operations for Current Note # ------------------------------------------------------------ editor_content_changed: (md) => if @get_current_note_md() != md # update md w/o notifying, otherwise will make loop @_set_current_note_md(md, false) @_set_current_note_dirty(true) save_current_note_to_db: () => if @_is_current_note_dirty() console.log('current note is dirty, saving to db...') # FIXME remove jq element enmlRenderer.get_title_promise($('#md_html_div_hidden'), @get_current_note_md()).then (title) => note_info = guid: @get_current_note_guid() notebook_guid: @get_current_note_notebook_guid() title: title md: @get_current_note_md() status: @get_current_note_status() @update_note(note_info).then( (note) => console.log('dirty note successfully saved to db: ' + JSON.stringify(note) + ', set it to not dirty.') # because title may change, we need to reload note list @reload_local_note_list() @_set_current_note_dirty(false) (error) => notifier.error('update note failed in save_current_note_to_db(): ' + JSON.stringify(error)) ).catch (error) => notifier.error('failed to save current note to db: ' + error) # ------------------------------------------------------------ # load previous note if exists, otherwise make a new note and set it current note # ------------------------------------------------------------ init_current_note: () => previous_note_guid = localStorageService.get(@STORAGE_KEY.CURRENT_NOTE_GUID) if not previous_note_guid? previous_note_guid = "INVALID_GUID" p = @find_note_by_guid(previous_note_guid).then (note) => if note? console.log('got valid previous current note ' + previous_note_guid + '. load...') @load_note(note.guid) else console.log('no valid previous current note found. create new note') @make_new_note().then( (note) => @_switch_current_note(note.guid, note.notebook_guid, note.title, note.md, @NOTE_STATUS.NEW) console.log('New note made: ' + JSON.stringify(note)) (error) => notifier.error('make_new_note() failed: ' + error) ).catch (error) => trace = printStackTrace({e: error}) notifier.error('Error, make new note failed!\n' + 'Message: ' + error.message + '\nStack trace:\n' + trace.join('\n')) p.catch (error) => notifier.error('load previous current note failed: ' + error) # ------------------------------------------------------------ # Load a note by guid as current note # # If note is SYNCED_ALL in local, just load it from local # otherwise fetch the note content from remote # # Return: not used # ------------------------------------------------------------ load_note: (guid) => # check if the note to be loaded is already current note if guid != @get_current_note_guid() p = @find_note_by_guid(guid).then (note) => if note? and (note.status == @NOTE_STATUS.NEW or note.status == @NOTE_STATUS.SYNCED_ALL or note.status == @NOTE_STATUS.MODIFIED) # note in db -> current note console.log('loading note ' + note.guid + ' with status ' + note.status + ' from local DB') @_switch_current_note(note.guid, note.notebook_guid, note.title, note.md, note.status) @note_load_finished(true, note.guid, null) console.log('loading note ' + note.guid + ' finished') if (note? == false) or (note.status == @NOTE_STATUS.SYNCED_META) # remote note -> current note @fetch_remote_note(guid).then( (note) => console.log('loading note ' + note.guid + ' with status ' + note.status + ' from remote') @_switch_current_note(note.guid, note.notebook_guid, note.title, note.md, note.status) @note_load_finished(true, note.guid, null) console.log('loading note ' + note.guid + ' finished') # updating note list @reload_local_note_list() (error) => notifier.error('load note ' + guid + ' failed: ' + JSON.stringify(error)) @note_load_finished(false, guid, new Error('load note ' + guid + ' failed: ' + JSON.stringify(error))) ) p.catch (error) => notifier.error('find_note_by_guid() itself or then() failed in load_note(): ' + JSON.stringify(error)) # ------------------------------------------------------------ # Check if a note is loadable from local # # The logic is consistent with the first part of load_note(guid) # # Return: promise with a boolean value # ------------------------------------------------------------ is_note_loadable_locally_promise: (guid) => if guid == @get_current_note_guid() return new Promise (resolve, reject) => resolve(true) return @find_note_by_guid(guid).then (note) => if note? and (note.status == @NOTE_STATUS.NEW or note.status == @NOTE_STATUS.SYNCED_ALL or note.status == @NOTE_STATUS.MODIFIED) return true else return false # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Note List > note_list: [] get_note_list: => return @note_list _set_note_list: (note_list) => @note_list = note_list @note_list_changed(note_list) # FIXME: delete previous comment when refactor is done fetch_note_list: => @load_remote_notes().then( (notes) => console.log('fetch_note_list() result: ' + JSON.stringify(notes)) @_set_note_list(notes) (error) => notifier.error('fetch_note_list() failed: ' + JSON.stringify(error)) ) reload_local_note_list: () => p = @get_all_notes().then (notes) => @_set_note_list(notes) p.catch (error) => notifier.error('reload_local_note_list() failed:' + error) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Notebook List > notebook_list: [] get_notebook_list: => return @notebook_list _set_notebook_list: (notebook_list) => @notebook_list = notebook_list localStorageService.set(@STORAGE_KEY.NOTEBOOK_LIST, notebook_list) @notebook_list_changed(notebook_list) reload_local_notebook_list: () => @_set_notebook_list(localStorageService.get(@STORAGE_KEY.NOTEBOOK_LIST)) fetch_notebook_list: => @load_remote_notebooks().then( (notebooks) => console.log('fetch_notebook_list() result: ' + JSON.stringify(notebooks)) @_set_notebook_list(notebooks) (error) => notifier.error('fetch_notebook_list() failed: ' + JSON.stringify(error)) ) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Event System > # ------------------------------------------------------------ # Event: current note markdown changed # ------------------------------------------------------------ current_note_md_modified_listeners: [] on_current_note_md_modified: (listener) => @current_note_md_modified_listeners.push(listener) current_note_md_modified: (new_md) => for l in @current_note_md_modified_listeners l(new_md) # ------------------------------------------------------------ # Event: current note switched to another note # ------------------------------------------------------------ current_note_switched_listeners: [] on_current_note_switched: (listener) => @current_note_switched_listeners.push(listener) current_note_switched: (new_note_guid) => localStorageService.set(@STORAGE_KEY.CURRENT_NOTE_GUID, new_note_guid) for l in @current_note_switched_listeners l(new_note_guid) # ------------------------------------------------------------ # Event: current note's guid changed (the note is still the "same" note) # ------------------------------------------------------------ current_note_guid_modified_listeners: [] on_current_note_guid_modified: (listener) => @current_note_guid_modified_listeners.push(listener) current_note_guid_modified: (old_guid, new_guid) => localStorageService.set(@STORAGE_KEY.CURRENT_NOTE_GUID, new_guid) for l in @current_note_guid_modified_listeners l(old_guid, new_guid) # ------------------------------------------------------------ # Event: a note finished synced up # ------------------------------------------------------------ note_synced_listeners: [] on_note_synced: (listener) => @note_synced_listeners.push(listener) note_synced: (is_success, old_guid, new_guid, error) => @reload_local_note_list() for l in @note_synced_listeners l(is_success, old_guid, new_guid, error) # ------------------------------------------------------------ # Event: note list changed # ------------------------------------------------------------ note_list_changed_listeners: [] on_note_list_changed: (listener) => @note_list_changed_listeners.push(listener) note_list_changed: (note_list) => for l in @note_list_changed_listeners l(note_list) # ------------------------------------------------------------ # Event: a note finished loading (either success or fail) # ------------------------------------------------------------ note_load_finished_listeners: [] on_note_load_finished: (listener) => @note_load_finished_listeners.push(listener) note_load_finished: (is_success, guid, error) => for l in @note_load_finished_listeners l(is_success, guid, error) # ------------------------------------------------------------ # Event: a note finished loading (either success or fail) # ------------------------------------------------------------ notebook_list_changed_listeners: [] on_notebook_list_changed: (listener) => @notebook_list_changed_listeners.push(listener) notebook_list_changed: (notebook_list) => for l in @notebook_list_changed_listeners l(notebook_list) # ------------------------------------------------------------ # Event: a note finished loading (either success or fail) # ------------------------------------------------------------ new_note_made_listeners: [] on_new_note_made: (listener) => @new_note_made_listeners.push(listener) new_note_made: () => console.log('refresh local note list due to new note made') @reload_local_note_list() for l in @new_note_made_listeners l() # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Remote Operations > # ------------------------------------------------------------ # Fetch a remote note's all info by guid and update db # # check if note is in local and is SYNCED_ALL first # return: promise containing note's info # ------------------------------------------------------------ fetch_remote_note: (guid) => console.log('fetch_remote_note(' + guid + ') begins to invoke') return @find_note_by_guid(guid).then (note) => console.log('fetch_remote_note(' + guid + ') local note: ' + JSON.stringify(note)) if note != null && note.status == @NOTE_STATUS.SYNCED_ALL console.log('Local note fetch hit: ' + JSON.stringify(note)) return note else console.log('Local note fetch missed, fetch from remote: ' + guid) return apiClient.get_note(guid).then (note) => _note = guid: guid notebook_guid: note.notebook_guid title: note.title md: note.md status: @NOTE_STATUS.SYNCED_ALL resources: note.resources return @update_note(_note) # ------------------------------------------------------------ # Load remote note list (only metadata) to update local notes info # return: promise # ------------------------------------------------------------ load_remote_notes: => # TODO handle failure return apiClient.get_all_notes().then (notes) => @_merge_remote_notes(notes).then( () => console.log('finish merging remote notes') return @get_all_notes() (error) => # TODO pass error on notifier.error('_merge_remote_notes() failed!') ) # ------------------------------------------------------------ # Load remote notebook list (only name and guid) to update local notebooks info # return: promise # ------------------------------------------------------------ load_remote_notebooks: => # TODO handle failure return apiClient.get_all_notebooks().then (notebooks) => return notebooks # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Merge/Sync Operations > # ------------------------------------------------------------ # merge remote note list into local note list db # Possible situations: TODO # ------------------------------------------------------------ _merge_remote_notes: (notes) => guid_list = (note['guid'] for note in notes) console.log('start merging remote notes: ' + JSON.stringify(guid_list)) must_finish_promise_list = [] remote_note_guid_list = [] # Phase one: patch remote notes to local for note_meta in notes remote_note_guid_list.push(note_meta['guid']) do (note_meta) => guid = note_meta['guid'] title = note_meta['title'] notebook_guid = note_meta['notebook_guid'] console.log('Merging note [' + guid + ']') find_p = @find_note_by_guid(guid).then (note) => _find_p_must_finish_promise_list = [] if note == null console.log('About to add note ' + guid) p = @add_note_meta({ guid: guid title: title notebook_guid: notebook_guid }).then () => console.log('note ' + guid + ' metadata added!') _find_p_must_finish_promise_list.push(p) console.log('pushed to _find_p_must_finish_promise_list. TAG: A') else console.log('local note ' + guid + ' exists, updating from remote.') switch note.status when @NOTE_STATUS.NEW console.log('[IMPOSSIBLE] remote note\'s local cache is in status NEW') when @NOTE_STATUS.SYNCED_META # update note title p = @update_note({ guid: guid title: title notebook_guid: notebook_guid }) _find_p_must_finish_promise_list.push(p) console.log('pushed to _find_p_must_finish_promise_list. TAG: B') when @NOTE_STATUS.SYNCED_ALL # fetch the whole note from server and update local console.log('local note ' + guid + ' is SYNCED_ALL, about to fetch from remote for updating') @fetch_remote_note(guid).then( (note) => console.log('note ' + guid + ' (SYNCED_ALL) updated from remote') # maybe FIXME did not add to promise waiting list #_find_p_must_finish_promise_list.push(p) #console.log('pushed to _find_p_must_finish_promise_list. TAG: C') (error) => notifier.error('fetch note ' + guid + ' failed during _merge_remote_notes():' + JSON.stringify(error)) ) when @NOTE_STATUS.MODIFIED # do nothing console.log('do nothing') else notifier.error('IMPOSSIBLE: no correct note status') return Promise.all(_find_p_must_finish_promise_list) must_finish_promise_list.push(find_p) console.log('pushed to must_finish_promise_list. TAG: D') # Phase two: deleted local notes not needed # Notes that should be deleted: # not in remote and status is not new/modified p = @get_all_notes().then (notes) => for n in notes if (n.guid not in remote_note_guid_list) && n.status != @NOTE_STATUS.NEW && n.status != @NOTE_STATUS.MODIFIED _p = @delete_note(n.guid) must_finish_promise_list.push(_p) console.log('pushed to must_finish_promise_list. TAG: E') must_finish_promise_list.push(p) console.log('pushed to must_finish_promise_list. TAG: F') console.log('about to return from _merge_remote_notes(). promise list: ' + JSON.stringify(must_finish_promise_list)) console.log('check if promises in promise list is actually Promises:') for p in must_finish_promise_list if p instanceof Promise console.log('is Promise!') else console.log('is NOT Promise!!') return Promise.all(must_finish_promise_list) # ------------------------------------------------------------ # Params: # jq_div: jQuery div element for rendering # one_note_synced_func: function called whenever a note is successfully synced up # ------------------------------------------------------------ sync_up_all_notes: (jq_div) => p = @get_all_notes().then (notes) => _must_finish_promise_list = [] for note in notes guid = note.guid notebook_guid = note.notebook_guid md = note.md if note.status == @NOTE_STATUS.NEW || note.status == @NOTE_STATUS.MODIFIED is_new_note = (note.status == @NOTE_STATUS.NEW) console.log('note ' + guid + ' sent for sync up') _p = @sync_up_note(is_new_note, guid, notebook_guid, jq_div, md).then( (synced_note) => console.log('sync up note ' + guid + ' succeeded') @note_synced(true, guid, synced_note.guid, null) (error) => notifier.error('sync up note ' + guid + ' failed: ' + JSON.stringify(error)) @note_synced(false, null, null, error) ) _must_finish_promise_list.push(_p) return Promise.all(_must_finish_promise_list) return p.catch (error) => trace = printStackTrace({e: error}) notifier.error('sync_up_all_notes() failed\n' + 'Message: ' + error.message + '\nStack trace:\n' + trace.join('\n')) # ------------------------------------------------------------ # return Promise containing the synced note # ------------------------------------------------------------ sync_up_note: (is_new_note, guid, notebook_guid, jq_div, md) => console.log('enter sync_up_note() for note ' + guid) return enmlRenderer.get_enml_and_title_promise(jq_div, md).then (enml_and_title) => title = enml_and_title.title enml = enml_and_title.enml request_guid = guid if is_new_note request_guid = '' return apiClient.save_note(request_guid, notebook_guid, title, enml).then( (note) => # 1. change note status to SYNCED_ALL, using old guid _modify = guid: guid status: @NOTE_STATUS.SYNCED_ALL # 2. update notebook_guid if it is set a new one from remote if notebook_guid != note.notebook_guid _modify['notebook_guid'] = note.notebook_guid p = @update_note(_modify).then () => # 3. update guid if is new note (when saving new note, tmp guid will be updated to real one) if is_new_note new_guid = note.guid # @update_note_guid will return Promise containing the updated note return @update_note_guid(guid, new_guid) else return @find_note_by_guid(guid) return p console.log('sync_up_note(' + guid + ') succeed') (error) => # set status back notifier.error('sync_up_note() failed: \n' + JSON.stringify(error)) throw error ) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| DB Operations > # db server safe. will get db server itself get_all_notes: () => console.log('get_all_notes() invoked') return dbProvider.get_db_server_promise().then (server) => return server.notes.query().all().execute() # ------------------------------------------------------------ # make a new note to db # # db server safe. will get db server itself # return promise # ------------------------------------------------------------ make_new_note: () => console.log('make_new_note() invoking') return new Promise (resolve, reject) => guid = uuid2.newguid() + '-new' db_server_p = new Promise (resolve, reject) => # db.js does not return real Promise... _false_p = dbProvider.get_db_server_promise().then (server) => server.notes.add({ guid: guid title: 'New Note' md: 'New Note\n==\n' notebook_guid: '' status: @NOTE_STATUS.NEW }) resolve(_false_p) p = db_server_p.then( () => return @find_note_by_guid(guid) (error) => notifier.error('make_new_note() error!') ) resolve(p) # db server safe. will get db server itself delete_note: (guid) => console.log('delete_note(' + guid + ') invoked') return @find_note_by_guid(guid).then( (note) => if note is null console.log('cannot delete note null, aborted') else console.log('about to remove note id ' + note.id) p = dbProvider.get_db_server_promise().then (server) => server.notes.remove(note.id) console.log('local note ' + note.guid + ' deleted. id: ' + note.id) p.catch (error) => notifier.error('delete_note(' + guid + ') failed') (error) => notifier.error('error!') ) # ------------------------------------------------------------ # Return a copy of a note in db with a given guid # # db server safe. will get db server itself # return: promise containing the note's info, # or null if note does not exist # ------------------------------------------------------------ find_note_by_guid: (guid) => # db.js then() does not return a Promise, # need to be wrapper in a real Promise p = dbProvider.get_db_server_promise().then (server) => return new Promise (resolve, reject) => resolve(server.notes.query().filter('guid', guid).execute()) return p.then (notes) => if notes.length == 0 console.log('find_note_by_guid(' + guid + ') returned null') return null else console.log('find_note_by_guid(' + guid + ') hit') return notes[0] # ------------------------------------------------------------ # Add a note's metadata which to db # # db server safe. will get db server itself # return: promise # ------------------------------------------------------------ add_note_meta: (note) -> console.log('Adding note to db - guid: ' + note.guid + ' title: ' + note.title + ' notebook_guid: ' + note.notebook_guid) return dbProvider.get_db_server_promise().then (server) => return new Promise (resolve, reject) => resolve( server.notes.add({ guid: note.guid title: note.title notebook_guid: note.notebook_guid status: @NOTE_STATUS.SYNCED_META }) ) # ------------------------------------------------------------ # Update a note, except for its guid # # db server safe. will get db server itself # If need to update note's guid, please use update_note_guid() # # return: promise # ------------------------------------------------------------ update_note: (note) => console.log('update_note(' + note.guid + ') invoking') if note.guid? == false notifier.error('update_note(): note to be updated must have a guid!') return new Promise (resolve, reject) => reject(new Error('update_note(): note to be updated must have a guid!')) # register resource data into ImageManager if note.resources? for r in note.resources imageManager.add_image(r.uuid, r.data_url).catch (error) => notifier.error('add image failed! uuid: ' + r.uuid) console.log("register uuid: " + r.uuid + " data len: " + r.data_url.length) # update notes db p = new Promise (resolve, reject) => _note_modify = {} if note.title? _note_modify.title = note.title if note.md? _note_modify.md = note.md if note.notebook_guid? _note_modify.notebook_guid = note.notebook_guid if note.status? _note_modify.status = note.status _modify_p = dbProvider.get_db_server_promise().then (server) => return server.notes.query().filter('guid', note.guid).modify(_note_modify).execute() resolve(_modify_p) return p.then( () => console.log('update note ' + note.guid + ' successfully') return @find_note_by_guid(note.guid) (error) => notifier.error('update note ' + note.guid + ' failed!') ) # return promise containing the updated note update_note_guid: (old_guid, new_guid) => p = @find_note_by_guid(old_guid).then (note) => if note? _modify_p = dbProvider.get_db_server_promise().then (server) => _note_modify = {guid: new_guid} return server.notes.query().filter('guid', old_guid).modify(_note_modify).execute() return _modify_p else console.log('update note guid ' + old_guid + ' to new guid ' + new_guid + ' missed!') return p.then( () => console.log('update note guid ' + old_guid + ' to new guid ' + new_guid + ' succeed') # notify current note guid changed if old_guid == @current_note.guid @current_note_guid_modified(old_guid, new_guid) return @find_note_by_guid(new_guid) (error) => notifier.error('update note guid ' + old_guid + ' to new guid ' + new_guid + ' failed: ' + error) ) # ------------------------------------------------------------ # Clear db # # db server safe. will get db server itself # return: promise # ------------------------------------------------------------ clear_all_notes: () -> return dbProvider.get_db_server_promise().then (server) => server.notes.clear() # --------------------------------- tmp operations -------------------------------- ]
93434
"use strict" markever = angular.module('markever', ['ngResource', 'ui.bootstrap', 'LocalStorageModule', 'angularUUID2']) markever.controller 'EditorController', ['$scope', '$window', '$document', '$http', '$sce', '$interval', 'localStorageService', 'enmlRenderer', 'scrollSyncor', 'apiClient', 'noteManager', 'imageManager', 'dbProvider', 'notifier', 'offlineStateManager', ($scope, $window, $document, $http, $sce, $interval localStorageService, enmlRenderer, scrollSyncor, apiClient, noteManager, imageManager, dbProvider, notifier, offlineStateManager) -> vm = this # ------------------------------------------------------------------------------------------------------------------ # Models # ------------------------------------------------------------------------------------------------------------------ # ------------------------------------------------------------------------------------------------------------------ # Debugging methods # ------------------------------------------------------------------------------------------------------------------ vm._debug_show_current_note = () -> alert(JSON.stringify(vm.note)) vm._debug_close_db = () -> dbProvider.close_db() alert('db closed!') vm._debug_show_current_note_in_db = () -> noteManager.find_note_by_guid(vm.get_guid()).then (note) => alert('current note (' + vm.get_guid() + ') in db is: ' + JSON.stringify(note)) vm._debug_offline_check = -> $window.Offline.check() # ------------------------------------------------------------------------------------------------------------------ # App ready status # ------------------------------------------------------------------------------------------------------------------ vm.all_ready = false # ------------------------------------------------------------------------------------------------------------------ # Document ready # ------------------------------------------------------------------------------------------------------------------ $document.ready -> # init ace editor vm.init_ace_editor() # init ui vm.init_ui() # sync scroll scrollSyncor.syncScroll(vm.ace_editor, $('#md_html_div')) noteManager.init_current_note() # get note list from local noteManager.reload_local_note_list() # get note list from remote if not offlineStateManager.is_offline() noteManager.fetch_note_list() else console.log('offline mode, did not fetch note list from remote') # get notebook list from local noteManager.reload_local_notebook_list() # get notebook list from remote if not offlineStateManager.is_offline() noteManager.fetch_notebook_list() else console.log('offline mode, did not fetch notebook list from remote') # take effect the settings vm.set_keyboard_handler(vm.current_keyboard_handler) vm.set_show_gutter(vm.current_show_gutter) vm.set_ace_theme(vm.current_ace_theme) # reset app status vm.reset_status() # all ready vm.all_ready = true # ------------------------------------------------------------------------------------------------------------------ # UI Logic that has to be made by js # ------------------------------------------------------------------------------------------------------------------ vm.init_ui = -> # when showing note list which is a modal, make the backdrop to be transparent $('#note_list_div').on 'show.bs.modal hidden.bs.modal', () -> $('body').toggleClass('modal-backdrop-transparent') # ------------------------------------------------------------------------------------------------------------------ # ace editor init # ------------------------------------------------------------------------------------------------------------------ vm.init_ace_editor = -> $window.ace.config.set('basePath', '/javascripts/ace') vm.ace_editor = $window.ace.edit("md_editor_div") vm.ace_editor.renderer.setShowGutter(false) vm.ace_editor.setShowPrintMargin(false) vm.ace_editor.getSession().setMode("ace/mode/markdown") vm.ace_editor.getSession().setUseWrapMode(true) vm.ace_editor.setTheme('ace/theme/tomorrow_night_eighties') vm.ace_editor.on 'change', vm.editor_content_changed vm.ace_editor.focus() # ------------------------------------------------------------------------------------------------------------------ # ace editor event handlers # ------------------------------------------------------------------------------------------------------------------ vm.editor_content_changed = (event) -> # render html, since noteManager will not notify back if use editor_content_changed(...) enmlRenderer.render_html($('#md_html_div'), vm.ace_editor.getValue()) noteManager.editor_content_changed(vm.ace_editor.getValue()) # ------------------------------------------------------------------------------------------------------------------ # Operations for notes # ------------------------------------------------------------------------------------------------------------------ vm.load_note = (guid) -> if guid == noteManager.get_current_note_guid() return noteManager.is_note_loadable_locally_promise(guid).then (loadable_locally) -> if not loadable_locally and offlineStateManager.is_offline() notifier.info('Cannot load note in offline mode') else vm.open_loading_modal() noteManager.load_note(guid) vm.sync_up_all_notes = -> if offlineStateManager.is_offline() notifier.info('Cannot sync up notes in offline mode') return if vm.saving_note == false vm.saving_note = true p = noteManager.sync_up_all_notes($('#md_html_div_hidden')).then () => notifier.success('sync_up_all_notes() succeeded for all notes!') vm.saving_note = false p.catch (error) => notifier.error('vm.sync_up_all_notes() failed: ' + error) vm.saving_note = false # ------------------------------------------------------------------------------------------------------------------ # TODO Note Manager Event Handlers # ------------------------------------------------------------------------------------------------------------------ noteManager.on_current_note_md_modified (new_md) -> vm.ace_editor.setValue(new_md) enmlRenderer.render_html($('#md_html_div'), new_md).catch (error) => notifier.error('render error: ' + error) console.log('on_current_note_md_modified()') noteManager.on_current_note_switched (new_note_guid) -> enmlRenderer.render_html($('#md_html_div'), noteManager.get_current_note_md()) noteManager.on_note_load_finished (is_success, guid, error) -> vm.close_loading_modal() if is_success console.log('load note ' + guid + ' succeeded') else notifier.error('load note ' + guid + ' failed: ' + error) noteManager.on_note_synced (is_success, old_guid, new_guid, error) -> noteManager.on_note_list_changed (note_list) -> noteManager.on_notebook_list_changed (notebook_list) -> # ------------------------------------------------------------------------------------------------------------------ # App Status # ------------------------------------------------------------------------------------------------------------------ vm.saving_note = false # reset status vm.reset_status = -> # if the note is in process of saving (syncing) or not vm.saving_note = false # ------------------------------------------------------------------------------------------------------------------ # Editor Settings # ------------------------------------------------------------------------------------------------------------------ # settings name constants vm.SETTINGS_KEY = KEYBOARD_HANDLER: 'settings.keyboard_handler' SHOW_GUTTER: 'settings.show_gutter' ACE_THEME: 'settings.ace_theme' CURRENT_NOTE_GUID: 'settings.current_note.guid' # -------------------------------------------------------- # Editor Keyboard Handler Settings # -------------------------------------------------------- vm.keyboard_handlers = [ {name: 'normal', id: ''} {name: 'vim', id: 'ace/keyboard/vim'} ] # load settings from local storage if localStorageService.get(vm.SETTINGS_KEY.KEYBOARD_HANDLER) != null # N.B. should be set to reference, not value! saved_handler = localStorageService.get(vm.SETTINGS_KEY.KEYBOARD_HANDLER) for handler in vm.keyboard_handlers if saved_handler.name == handler.name vm.current_keyboard_handler = handler break else vm.current_keyboard_handler = vm.keyboard_handlers[0] # "new" keyboard handler used in settings modal # N.B. must by reference, not value # refer: http://jsfiddle.net/qWzTb/ # and: https://docs.angularjs.org/api/ng/directive/select vm.new_keyboard_handler = vm.current_keyboard_handler vm.set_keyboard_handler = (handler) -> vm.ace_editor.setKeyboardHandler(handler.id) vm.current_keyboard_handler = handler localStorageService.set(vm.SETTINGS_KEY.KEYBOARD_HANDLER, JSON.stringify(handler)) # -------------------------------------------------------- # Editor Gutter Settings # -------------------------------------------------------- if localStorageService.get(vm.SETTINGS_KEY.KEYBOARD_HANDLER) != null vm.current_show_gutter = JSON.parse(localStorageService.get(vm.SETTINGS_KEY.SHOW_GUTTER)) else vm.current_show_gutter = false vm.new_show_gutter = vm.show_gutter vm.set_show_gutter = (is_show) -> vm.ace_editor.renderer.setShowGutter(is_show) vm.current_show_gutter = is_show localStorageService.set(vm.SETTINGS_KEY.SHOW_GUTTER, JSON.stringify(is_show)) # -------------------------------------------------------- # Editor Theme Settings # -------------------------------------------------------- vm.ace_themes = [ {name: 'default', id: ''} {name: 'ambiance', id: 'ace/theme/ambiance'} {name: 'chaos', id: 'ace/theme/chaos'} {name: 'chrome', id: 'ace/theme/chrome'} {name: 'clouds', id: 'ace/theme/clouds'} {name: 'clouds_midnight', id: 'ace/theme/clouds_midnight'} {name: 'cobalt', id: 'ace/theme/cobalt'} {name: 'crimson_editor', id: 'ace/theme/crimson_editor'} {name: 'dawn', id: 'ace/theme/dawn'} {name: 'dreamweaver', id: 'ace/theme/dreamweaver'} {name: 'eclipse', id: 'ace/theme/eclipse'} {name: 'github', id: 'ace/theme/github'} {name: 'idle_fingers', id: 'ace/theme/idle_fingers'} {name: 'katzenmilch', id: 'ace/theme/katzenmilch'} {name: 'kr_theme', id: 'ace/theme/kr_theme'} {name: 'kuroir', id: 'ace/theme/kuroir'} {name: 'merbivore', id: 'ace/theme/merbivore'} {name: 'merbivore_soft', id: 'ace/theme/merbivore_soft'} {name: 'mono_industrial', id: 'ace/theme/mono_industrial'} {name: 'monokai', id: 'ace/theme/monokai'} {name: 'pastel_on_dark', id: 'ace/theme/pastel_on_dark'} {name: 'solarized_dark', id: 'ace/theme/solarized_dark'} {name: 'solarized_light', id: 'ace/theme/solarized_light'} {name: 'terminal', id: 'ace/theme/terminal'} {name: 'textmate', id: 'ace/theme/textmate'} {name: 'tomorrow', id: 'ace/theme/tomorrow'} {name: 'tomorrow_night', id: 'ace/theme/tomorrow_night'} {name: 'tomorrow_night_blue', id: 'ace/theme/tomorrow_night_blue'} {name: 'tomorrow_night_bright', id: 'ace/theme/tomorrow_night_bright'} {name: 'tomorrow_night_eighties', id: 'ace/theme/tomorrow_night_eighties'} {name: 'twilight', id: 'ace/theme/twilight'} {name: 'vibrant_ink', id: 'ace/theme/vibrant_ink'} {name: 'xcode', id: 'ace/theme/xcode'} ] if localStorageService.get(vm.SETTINGS_KEY.ACE_THEME) != null # N.B. should be set to reference, not value! saved_ace_theme = localStorageService.get(vm.SETTINGS_KEY.ACE_THEME) for theme in vm.ace_themes if saved_ace_theme.name == theme.name vm.current_ace_theme = theme break else vm.current_ace_theme = vm.ace_themes[0] # "new" ace theme used in settings modal # N.B. same, must by reference, not value vm.new_ace_theme = vm.current_ace_theme vm.set_ace_theme = (theme) -> vm.ace_editor.setTheme(theme.id) vm.current_ace_theme = theme localStorageService.set(vm.SETTINGS_KEY.ACE_THEME, JSON.stringify(theme)) # ------------------------------------------------------------------------------------------------------------------ # on paste # ------------------------------------------------------------------------------------------------------------------ vm.handle_paste = (e) => if not vm.ace_editor.isFocused return false items = (e.clipboardData || e.originalEvent.clipboardData).items console.log(JSON.stringify(items)) if items[0].type.match(/image.*/) blob = items[0].getAsFile() image_uuid = imageManager.load_image_blob(blob) vm.ace_editor.insert('![Alt text](' + image_uuid + ')') # ------------------------------------------------------------------------------------------------------------------ # settings modal # ------------------------------------------------------------------------------------------------------------------ vm.open_settings_modal = -> # reset "new" settings to current settings vm.new_keyboard_handler = vm.current_keyboard_handler vm.new_ace_theme = vm.current_ace_theme vm.new_show_gutter = vm.current_show_gutter # show modal $('#settings-modal').modal({}) # explicit return non-DOM result to avoid warning return true vm.save_settings = -> vm.set_ace_theme(vm.new_ace_theme) vm.set_keyboard_handler(vm.new_keyboard_handler) vm.set_show_gutter(vm.new_show_gutter) # ------------------------------------------------------------------------------------------------------------------ # note list modal # ------------------------------------------------------------------------------------------------------------------ vm.open_note_list_modal = -> # clear search keyword vm.search_note_keyword = '' note_list = noteManager.get_note_list() notebook_list = noteManager.get_notebook_list() notebook_name_map = {} notebook_collapse_map = {} for nb in notebook_list notebook_name_map[nb.guid] = nb.name notebook_collapse_map[nb.guid] = true # key: notebook guid; value: Map{notebook_name: String, note_list: Array} note_group_list = {} for n in note_list if not (n.notebook_guid of note_group_list) if n.notebook_guid.trim() == "" note_group_list[n.notebook_guid] = notebook_name: 'Unspecified Notebook' note_list: [] else note_group_list[n.notebook_guid] = notebook_name: notebook_name_map[n.notebook_guid] note_list: [] note_group_list[n.notebook_guid].note_list.push(n) if not vm.notebook_collapse_map? vm.notebook_collapse_map = notebook_collapse_map vm.note_group_list = note_group_list $('#note_list_div').modal({}) # explicit return non-DOM result to avoid warning return true # ------------------------------------------------------------------------------------------------------------------ # toolbar # ------------------------------------------------------------------------------------------------------------------ # ------------------------------------------------------------------------------------------------------------------ # loading modal # ------------------------------------------------------------------------------------------------------------------ vm.open_loading_modal = -> $('#loading-modal').modal({ backdrop: 'static' keyboard: false }) vm.close_loading_modal = -> $('#loading-modal').modal('hide') # fixme for debug vm.note_manager = noteManager ] # ---------------------------------------------------------------------------------------------------------------------- # Service: enmlRenderer # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'enmlRenderer', ['$window', 'imageManager', 'notifier', ($window, imageManager, notifier) -> render_html = (jq_html_div, md) -> processed_md = _md_pre_process(md) _html_dom = $('<div></div>') _html_dom.html($window.marked(processed_md, {sanitize: true})) return _html_post_process(_html_dom).then( () -> jq_html_div.empty() jq_html_div.append(_html_dom) (error) -> notifier.error('render_html() error: ' + error) ) _md_pre_process = (md) -> # TODO more handling processed_md = md return processed_md # return promise _html_post_process = (jq_tmp_div) -> # code highlighting jq_tmp_div.find('pre code').each (i, block) -> hljs.highlightBlock(block) # render Latex $window.MathJax.Hub.Queue(['Typeset', $window.MathJax.Hub, jq_tmp_div.get(0)]) # change img src to real data url must_finish_promise_list = [] jq_tmp_div.find('img[src]').each (index) -> $img = $(this) uuid = $img.attr('src') p = imageManager.find_image_by_uuid(uuid).then( (image) => if image? console.log('change img src from ' + uuid + ' to its base64 content') $img.attr('longdesc', uuid) $img.attr('src', image.content) (error) => notifier.error('_html_post_process() failed due to failure in imageManager.find_image_by_uuid(' + uuid + '): ' + error) ) must_finish_promise_list.push(p.catch (error) -> notifier.error('image replace failed: ' + error)) return Promise.all(must_finish_promise_list).then () -> return jq_tmp_div get_enml_and_title_promise = (jq_html_div, markdown) -> return render_html(jq_html_div, markdown).then () => # further post process # remove all script tags jq_html_div.find('script').remove() # add inline style # refer: https://github.com/Karl33to/jquery.inlineStyler # TODO still too much redundant styles inline_styler_option = { 'propertyGroups' : { 'font-matters' : ['font-size', 'font-family', 'font-style', 'font-weight'], 'text-matters' : ['text-indent', 'text-align', 'text-transform', 'letter-spacing', 'word-spacing', 'word-wrap', 'white-space', 'line-height', 'direction'], 'display-matters' : ['display'], 'size-matters' : ['width', 'height'], 'color-matters' : ['color', 'background-color'], 'position-matters' : ['margin', 'margin-left', 'margin-right', 'margin-top', 'margin-bottom', 'padding', 'padding-left', 'padding-right', 'padding-top', 'padding-bottom', 'float'], 'border-matters' : ['border', 'border-left', 'border-right', 'border-radius', 'border-top', 'border-right', 'border-color'], }, 'elementGroups' : { # N.B. UPPERCASE tags 'font-matters' : ['DIV', 'BLOCKQUOTE', 'SPAN', 'STRONG', 'EM', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'], 'text-matters' : ['SPAN', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'], 'display-matters' : ['HR', 'PRE', 'SPAN', 'UL', 'OL', 'LI', 'PRE', 'CODE'], 'size-matters' : ['SPAN'], 'color-matters' : ['DIV', 'SPAN', 'PRE', 'CODE', 'BLOCKQUOTE', 'HR'], 'position-matters' : ['DIV', 'PRE', 'BLOCKQUOTE', 'SPAN', 'HR', 'UL', 'OL', 'LI', 'P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'], 'border-matters' : ['HR', 'BLOCKQUOTE', 'SPAN', 'PRE', 'CODE'], } } jq_html_div.inlineStyler(inline_styler_option) # set href to start with 'http' is no protocol assigned jq_html_div.find('a').attr 'href', (i, href) -> if not href.toLowerCase().match('(^http)|(^https)|(^file)') return 'http://' + href else return href # clean the html tags/attributes html_clean_option = { format: true, allowedTags: ['a', 'abbr', 'acronym', 'address', 'area', 'b', 'bdo', 'big', 'blockquote', 'br', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'div', 'dl', 'dt', 'em', 'font', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'map', 'ol', 'p', 'pre', 'q', 's', 'samp', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'title', 'tr', 'tt', 'u', 'ul', 'var', 'xmp',], allowedAttributes: [['href', ['a']], ['longdesc'], ['style']], removeAttrs: ['id', 'class', 'onclick', 'ondblclick', 'accesskey', 'data', 'dynsrc', 'tabindex',], } cleaned_html = $.htmlClean(jq_html_div.html(), html_clean_option); # FIXME hack for strange class attr not removed cleaned_html = cleaned_html.replace(/class='[^']*'/g, '') cleaned_html = cleaned_html.replace(/class="[^"]*"/g, '') # embbed raw markdown content into the html cleaned_html = cleaned_html + '<center style="display:none">' + $('<div />').text(markdown).html() + '</center>' # add XML header & wrap with <en-note></en-note> final_note_xml = '<?xml version="1.0" encoding="utf-8"?>' + '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' + '<en-note>' + cleaned_html + '</en-note>' # make title title = 'New Note - <NAME>kever' if jq_html_div.find('h1').size() > 0 text = jq_html_div.find('h1').text() title = text if text.trim().length > 0 else if jq_html_div.find('h2').size() > 0 text = jq_html_div.find('h2').text() title = text if text.trim().length > 0 else if jq_html_div.find('h3').size() > 0 text = jq_html_div.find('h3').text() title = text if text.trim().length > 0 else if jq_html_div.find('p').size() > 0 text = jq_html_div.find('p').text() title = text if text.trim().length > 0 # the return value of result promise return {enml: final_note_xml, title: title} get_title_promise = (jq_html_div, markdown) -> return render_html(jq_html_div, markdown).then () => title = 'New Note - Markever' if jq_html_div.find('h1').size() > 0 text = jq_html_div.find('h1').text() title = text if text.trim().length > 0 else if jq_html_div.find('h2').size() > 0 text = jq_html_div.find('h2').text() title = text if text.trim().length > 0 else if jq_html_div.find('h3').size() > 0 text = jq_html_div.find('h3').text() title = text if text.trim().length > 0 else if jq_html_div.find('p').size() > 0 text = jq_html_div.find('p').text() title = text if text.trim().length > 0 return title return { get_enml_and_title_promise : get_enml_and_title_promise get_title_promise: get_title_promise render_html: render_html } ] # ---------------------------------------------------------------------------------------------------------------------- # Service: enmlRenderer # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'scrollSyncor', -> syncScroll = (ace_editor, jq_div) -> ace_editor.setShowPrintMargin(false) # sync scroll: md -> html editor_scroll_handler = (scroll) => percentage = scroll / (ace_editor.session.getScreenLength() * \ ace_editor.renderer.lineHeight - ($(ace_editor.renderer.getContainerElement()).height())) if percentage > 1 or percentage < 0 then return percentage = Math.floor(percentage * 1000) / 1000; # detach other's scroll handler first jq_div.off('scroll', html_scroll_handler) md_html_div = jq_div.get(0) md_html_div.scrollTop = percentage * (md_html_div.scrollHeight - md_html_div.offsetHeight) # re-attach other's scroll handler at the end, with some delay setTimeout (-> jq_div.scroll(html_scroll_handler)), 10 ace_editor.session.on('changeScrollTop', editor_scroll_handler) # sync scroll: html -> md html_scroll_handler = (e) => md_html_div = jq_div.get(0) percentage = md_html_div.scrollTop / (md_html_div.scrollHeight - md_html_div.offsetHeight) if percentage > 1 or percentage < 0 then return percentage = Math.floor(percentage * 1000) / 1000; # detach other's scroll handler first ace_editor.getSession().removeListener('changeScrollTop', editor_scroll_handler); ace_editor.session.setScrollTop((ace_editor.session.getScreenLength() * \ ace_editor.renderer.lineHeight - $(ace_editor.renderer.getContainerElement()).height()) * percentage) # re-attach other's scroll handler at the end, with some delay setTimeout (-> ace_editor.session.on('changeScrollTop', editor_scroll_handler)), 20 jq_div.scroll(html_scroll_handler) return { syncScroll : syncScroll } # ---------------------------------------------------------------------------------------------------------------------- # Service: apiClient # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'apiClient', ['$resource', ($resource) -> new class APIClient note_resource: $resource('/api/v1/notes/:id', {id: '@id'}, { all: {method : 'GET', params : {id: ''}} note: {method : 'GET', params: {}} newest: {method : 'GET', params : {id: 'newest'}} save: {method : 'POST', params: {id: ''}} }) notebook_resource: $resource('/api/v1/notebooks/:id', {id: '@id'}, { all: {method: 'GET', params: {id: ''}} }) # return promise with all notes get_all_notes: () => return @note_resource.all().$promise.then (data) => return data['notes'] # return promise with the note get_note: (guid) => return @note_resource.note({id: guid}).$promise.then (data) => return data.note # return promise with saved note that is returned from remote save_note: (guid, notebook_guid, title, enml) => _post_data = { guid: guid notebookGuid: notebook_guid title: title enml: enml } return @note_resource.save(_post_data).$promise.then (data) => return data.note get_all_notebooks: () => return @notebook_resource.all().$promise.then (data) => return data['notebooks'] ] # ---------------------------------------------------------------------------------------------------------------------- # Service: notifier # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'notifier', -> new class Notifier success: (msg) -> $.bootstrapGrowl(msg, {type: 'success'}) info: (msg) -> $.bootstrapGrowl(msg, {type: 'info'}) error: (msg) -> $.bootstrapGrowl(msg, {type: 'danger'}) # ---------------------------------------------------------------------------------------------------------------------- # Service: offline state manager # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'offlineStateManager', ['$window', 'notifier', ($window, notifier) -> new class OfflineStateManager constructor: -> @initialized = false @_is_offline = false @_init() $window.Offline.check() _init: => if not @initialized $window.Offline.on 'confirmed-up', () => @_is_offline = false #notifier.success('connection up') $window.Offline.on 'confirmed-down', () => @_is_offline = true #notifier.error('connection down') $window.Offline.on 'up', () => @_is_offline = false notifier.success('connection restored') $window.Offline.on 'down', () => @_is_offline = true notifier.error('connection went down') $window.Offline.on 'reconnect:started', () => #notifier.info('reconnecting started') $window.Offline.on 'reconnect:stopped', () => #notifier.info('reconnecting stopped') $window.Offline.on 'reconnect:failure', () => notifier.error('reconnecting failed') is_offline: => return @_is_offline check_connection: => $window.Offline.check() ] # ---------------------------------------------------------------------------------------------------------------------- # Service: dbProvider # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'dbProvider', -> new class DBProvider constructor: -> @db_server_promise = @init_db() init_db: () => db_open_option = { server: 'markever' version: 1 schema: { notes: { key: {keyPath: 'id', autoIncrement: true}, indexes: { guid: {} title: {} notebook_guid: {} status: {} # no need to index md # md: {} } } images: { key: {keyPath: 'id', autoIncrement: true}, indexes: { uuid: {} # no need to index content # content: {} } } } } # db.js promise is not real promise _false_db_p = db.open(db_open_option) return new Promise (resolve, reject) => resolve(_false_db_p) get_db_server_promise: () => console.log('return real promise @db_server_promise') if @db_server_promise? return @db_server_promise else return @init_db() close_db: () => @db_server_promise.then (server) => server.close() console.log('db closed') # ---------------------------------------------------------------------------------------------------------------------- # Service: imageManager # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'imageManager', ['uuid2', 'dbProvider', (uuid2, dbProvider) -> new class ImageManager constructor: -> dbProvider.get_db_server_promise().then (server) => @db_server = server console.log('DB initialized from ImageManager') # ------------------------------------------------------------ # Return a copy of a image in db with a given uuid # # return: promise containing the image's info: # uuid, content # or null if image does not exist # ------------------------------------------------------------ find_image_by_uuid: (uuid) => p = new Promise (resolve, reject) => resolve(@db_server.images.query().filter('uuid', uuid).execute()) return p.then (images) => if images.length == 0 console.log('find_image_by_uuid(' + uuid + ') returned null') return null else console.log('find_image_by_uuid(' + uuid + ') hit') return images[0] # ------------------------------------------------------------ # Add a image to db # # return: promise # ------------------------------------------------------------ add_image: (uuid, content) => console.log('Adding image to db - uuid: ' + uuid) return new Promise (resolve, reject) => resolve( @db_server.images.add({ uuid: uuid content: content }) ) # return: the uuid of the image (NOT promise) load_image_blob: (blob, extra_handler) => uuid = uuid2.newuuid() reader = new FileReader() reader.onload = (event) => console.log("image result: " + event.target.result) @add_image(uuid, event.target.result) # optional extra_handler if extra_handler extra_handler(event) # start reading blob data, and get result in base64 data URL reader.readAsDataURL(blob) return uuid ] # ---------------------------------------------------------------------------------------------------------------------- # Service: noteManager # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'noteManager', ['$interval', 'uuid2', 'localStorageService', 'dbProvider', 'apiClient', 'imageManager', 'enmlRenderer', 'notifier', 'offlineStateManager', ($interval, uuid2, localStorageService, dbProvider, apiClient, imageManager, enmlRenderer, notifier, offlineStateManager) -> new class NoteManager #--------------------------------------------------------------------------------------------------------------------- # Status of a note: # 1. new: note with a generated guid, not attached to remote # 2. synced_meta: note with metadata fetched to remote. not editable # 3. synced_all: note with all data synced with remote. editable # 4. modified: note attached to remote, but has un-synced modification # # Status transition: # # sync modify # new ------> synced_all ---------> modified # ^ <--------- # | sync # | # | load note data from remote # | # synced_meta ------ #--------------------------------------------------------------------------------------------------------------------- constructor: -> $interval(@save_current_note_to_db, 1000) NOTE_STATUS: NEW: 0 SYNCED_META: 1 SYNCED_ALL: 2 MODIFIED: 3 STORAGE_KEY: CURRENT_NOTE_GUID: 'note_manager.current_note.guid' NOTEBOOK_LIST: 'note_manager.notebook_list' # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Current Note > current_note: guid: '' title: '' status: null md: '' notebook_guid: '' _is_dirty: false # ------------------------------------------------------------ # Public accessor for current_note # ------------------------------------------------------------ get_current_note_guid: => return @current_note.guid get_current_note_title: => return @current_note.title get_current_note_status: => return @current_note.status get_current_note_md: => return @current_note.md get_current_note_notebook_guid: => return @current_note.notebook_guid # ------------------------------------------------------------ # Private accessor for current_note # ------------------------------------------------------------ _is_current_note_dirty: () => return @current_note._is_dirty _set_current_note_dirty: (is_dirty) => @current_note._is_dirty = is_dirty _switch_current_note: (guid, notebook_guid, title, md, status) => console.log('_switch_current_note(...) invoked') @_set_current_note_guid(guid) if notebook_guid? @_set_current_note_notebook_guid(notebook_guid) if title? @_set_current_note_title(title) if md? if @get_current_note_md() != md @_set_current_note_md(md) if status? @_set_current_note_status(status) # notify event after current note changed @current_note_switched(guid) _set_current_note_guid: (guid) => @current_note.guid = guid _set_current_note_title: (title) => @current_note.title = title _set_current_note_md: (md, notify=true) => if @get_current_note_md() != md @current_note.md = md if notify @current_note_md_modified(md) # change note status to MODIFIED if original status is SYNCED_ALL if @get_current_note_status() == @NOTE_STATUS.SYNCED_ALL @_set_current_note_status(@NOTE_STATUS.MODIFIED) _set_current_note_status: (status) => @current_note.status = status @reload_local_note_list() _set_current_note_notebook_guid: (notebook_guid) => @current_note.notebook_guid = notebook_guid @reload_local_note_list() # ------------------------------------------------------------ # Other Operations for Current Note # ------------------------------------------------------------ editor_content_changed: (md) => if @get_current_note_md() != md # update md w/o notifying, otherwise will make loop @_set_current_note_md(md, false) @_set_current_note_dirty(true) save_current_note_to_db: () => if @_is_current_note_dirty() console.log('current note is dirty, saving to db...') # FIXME remove jq element enmlRenderer.get_title_promise($('#md_html_div_hidden'), @get_current_note_md()).then (title) => note_info = guid: @get_current_note_guid() notebook_guid: @get_current_note_notebook_guid() title: title md: @get_current_note_md() status: @get_current_note_status() @update_note(note_info).then( (note) => console.log('dirty note successfully saved to db: ' + JSON.stringify(note) + ', set it to not dirty.') # because title may change, we need to reload note list @reload_local_note_list() @_set_current_note_dirty(false) (error) => notifier.error('update note failed in save_current_note_to_db(): ' + JSON.stringify(error)) ).catch (error) => notifier.error('failed to save current note to db: ' + error) # ------------------------------------------------------------ # load previous note if exists, otherwise make a new note and set it current note # ------------------------------------------------------------ init_current_note: () => previous_note_guid = localStorageService.get(@STORAGE_KEY.CURRENT_NOTE_GUID) if not previous_note_guid? previous_note_guid = "INVALID_GUID" p = @find_note_by_guid(previous_note_guid).then (note) => if note? console.log('got valid previous current note ' + previous_note_guid + '. load...') @load_note(note.guid) else console.log('no valid previous current note found. create new note') @make_new_note().then( (note) => @_switch_current_note(note.guid, note.notebook_guid, note.title, note.md, @NOTE_STATUS.NEW) console.log('New note made: ' + JSON.stringify(note)) (error) => notifier.error('make_new_note() failed: ' + error) ).catch (error) => trace = printStackTrace({e: error}) notifier.error('Error, make new note failed!\n' + 'Message: ' + error.message + '\nStack trace:\n' + trace.join('\n')) p.catch (error) => notifier.error('load previous current note failed: ' + error) # ------------------------------------------------------------ # Load a note by guid as current note # # If note is SYNCED_ALL in local, just load it from local # otherwise fetch the note content from remote # # Return: not used # ------------------------------------------------------------ load_note: (guid) => # check if the note to be loaded is already current note if guid != @get_current_note_guid() p = @find_note_by_guid(guid).then (note) => if note? and (note.status == @NOTE_STATUS.NEW or note.status == @NOTE_STATUS.SYNCED_ALL or note.status == @NOTE_STATUS.MODIFIED) # note in db -> current note console.log('loading note ' + note.guid + ' with status ' + note.status + ' from local DB') @_switch_current_note(note.guid, note.notebook_guid, note.title, note.md, note.status) @note_load_finished(true, note.guid, null) console.log('loading note ' + note.guid + ' finished') if (note? == false) or (note.status == @NOTE_STATUS.SYNCED_META) # remote note -> current note @fetch_remote_note(guid).then( (note) => console.log('loading note ' + note.guid + ' with status ' + note.status + ' from remote') @_switch_current_note(note.guid, note.notebook_guid, note.title, note.md, note.status) @note_load_finished(true, note.guid, null) console.log('loading note ' + note.guid + ' finished') # updating note list @reload_local_note_list() (error) => notifier.error('load note ' + guid + ' failed: ' + JSON.stringify(error)) @note_load_finished(false, guid, new Error('load note ' + guid + ' failed: ' + JSON.stringify(error))) ) p.catch (error) => notifier.error('find_note_by_guid() itself or then() failed in load_note(): ' + JSON.stringify(error)) # ------------------------------------------------------------ # Check if a note is loadable from local # # The logic is consistent with the first part of load_note(guid) # # Return: promise with a boolean value # ------------------------------------------------------------ is_note_loadable_locally_promise: (guid) => if guid == @get_current_note_guid() return new Promise (resolve, reject) => resolve(true) return @find_note_by_guid(guid).then (note) => if note? and (note.status == @NOTE_STATUS.NEW or note.status == @NOTE_STATUS.SYNCED_ALL or note.status == @NOTE_STATUS.MODIFIED) return true else return false # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Note List > note_list: [] get_note_list: => return @note_list _set_note_list: (note_list) => @note_list = note_list @note_list_changed(note_list) # FIXME: delete previous comment when refactor is done fetch_note_list: => @load_remote_notes().then( (notes) => console.log('fetch_note_list() result: ' + JSON.stringify(notes)) @_set_note_list(notes) (error) => notifier.error('fetch_note_list() failed: ' + JSON.stringify(error)) ) reload_local_note_list: () => p = @get_all_notes().then (notes) => @_set_note_list(notes) p.catch (error) => notifier.error('reload_local_note_list() failed:' + error) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Notebook List > notebook_list: [] get_notebook_list: => return @notebook_list _set_notebook_list: (notebook_list) => @notebook_list = notebook_list localStorageService.set(@STORAGE_KEY.NOTEBOOK_LIST, notebook_list) @notebook_list_changed(notebook_list) reload_local_notebook_list: () => @_set_notebook_list(localStorageService.get(@STORAGE_KEY.NOTEBOOK_LIST)) fetch_notebook_list: => @load_remote_notebooks().then( (notebooks) => console.log('fetch_notebook_list() result: ' + JSON.stringify(notebooks)) @_set_notebook_list(notebooks) (error) => notifier.error('fetch_notebook_list() failed: ' + JSON.stringify(error)) ) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Event System > # ------------------------------------------------------------ # Event: current note markdown changed # ------------------------------------------------------------ current_note_md_modified_listeners: [] on_current_note_md_modified: (listener) => @current_note_md_modified_listeners.push(listener) current_note_md_modified: (new_md) => for l in @current_note_md_modified_listeners l(new_md) # ------------------------------------------------------------ # Event: current note switched to another note # ------------------------------------------------------------ current_note_switched_listeners: [] on_current_note_switched: (listener) => @current_note_switched_listeners.push(listener) current_note_switched: (new_note_guid) => localStorageService.set(@STORAGE_KEY.CURRENT_NOTE_GUID, new_note_guid) for l in @current_note_switched_listeners l(new_note_guid) # ------------------------------------------------------------ # Event: current note's guid changed (the note is still the "same" note) # ------------------------------------------------------------ current_note_guid_modified_listeners: [] on_current_note_guid_modified: (listener) => @current_note_guid_modified_listeners.push(listener) current_note_guid_modified: (old_guid, new_guid) => localStorageService.set(@STORAGE_KEY.CURRENT_NOTE_GUID, new_guid) for l in @current_note_guid_modified_listeners l(old_guid, new_guid) # ------------------------------------------------------------ # Event: a note finished synced up # ------------------------------------------------------------ note_synced_listeners: [] on_note_synced: (listener) => @note_synced_listeners.push(listener) note_synced: (is_success, old_guid, new_guid, error) => @reload_local_note_list() for l in @note_synced_listeners l(is_success, old_guid, new_guid, error) # ------------------------------------------------------------ # Event: note list changed # ------------------------------------------------------------ note_list_changed_listeners: [] on_note_list_changed: (listener) => @note_list_changed_listeners.push(listener) note_list_changed: (note_list) => for l in @note_list_changed_listeners l(note_list) # ------------------------------------------------------------ # Event: a note finished loading (either success or fail) # ------------------------------------------------------------ note_load_finished_listeners: [] on_note_load_finished: (listener) => @note_load_finished_listeners.push(listener) note_load_finished: (is_success, guid, error) => for l in @note_load_finished_listeners l(is_success, guid, error) # ------------------------------------------------------------ # Event: a note finished loading (either success or fail) # ------------------------------------------------------------ notebook_list_changed_listeners: [] on_notebook_list_changed: (listener) => @notebook_list_changed_listeners.push(listener) notebook_list_changed: (notebook_list) => for l in @notebook_list_changed_listeners l(notebook_list) # ------------------------------------------------------------ # Event: a note finished loading (either success or fail) # ------------------------------------------------------------ new_note_made_listeners: [] on_new_note_made: (listener) => @new_note_made_listeners.push(listener) new_note_made: () => console.log('refresh local note list due to new note made') @reload_local_note_list() for l in @new_note_made_listeners l() # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Remote Operations > # ------------------------------------------------------------ # Fetch a remote note's all info by guid and update db # # check if note is in local and is SYNCED_ALL first # return: promise containing note's info # ------------------------------------------------------------ fetch_remote_note: (guid) => console.log('fetch_remote_note(' + guid + ') begins to invoke') return @find_note_by_guid(guid).then (note) => console.log('fetch_remote_note(' + guid + ') local note: ' + JSON.stringify(note)) if note != null && note.status == @NOTE_STATUS.SYNCED_ALL console.log('Local note fetch hit: ' + JSON.stringify(note)) return note else console.log('Local note fetch missed, fetch from remote: ' + guid) return apiClient.get_note(guid).then (note) => _note = guid: guid notebook_guid: note.notebook_guid title: note.title md: note.md status: @NOTE_STATUS.SYNCED_ALL resources: note.resources return @update_note(_note) # ------------------------------------------------------------ # Load remote note list (only metadata) to update local notes info # return: promise # ------------------------------------------------------------ load_remote_notes: => # TODO handle failure return apiClient.get_all_notes().then (notes) => @_merge_remote_notes(notes).then( () => console.log('finish merging remote notes') return @get_all_notes() (error) => # TODO pass error on notifier.error('_merge_remote_notes() failed!') ) # ------------------------------------------------------------ # Load remote notebook list (only name and guid) to update local notebooks info # return: promise # ------------------------------------------------------------ load_remote_notebooks: => # TODO handle failure return apiClient.get_all_notebooks().then (notebooks) => return notebooks # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Merge/Sync Operations > # ------------------------------------------------------------ # merge remote note list into local note list db # Possible situations: TODO # ------------------------------------------------------------ _merge_remote_notes: (notes) => guid_list = (note['guid'] for note in notes) console.log('start merging remote notes: ' + JSON.stringify(guid_list)) must_finish_promise_list = [] remote_note_guid_list = [] # Phase one: patch remote notes to local for note_meta in notes remote_note_guid_list.push(note_meta['guid']) do (note_meta) => guid = note_meta['guid'] title = note_meta['title'] notebook_guid = note_meta['notebook_guid'] console.log('Merging note [' + guid + ']') find_p = @find_note_by_guid(guid).then (note) => _find_p_must_finish_promise_list = [] if note == null console.log('About to add note ' + guid) p = @add_note_meta({ guid: guid title: title notebook_guid: notebook_guid }).then () => console.log('note ' + guid + ' metadata added!') _find_p_must_finish_promise_list.push(p) console.log('pushed to _find_p_must_finish_promise_list. TAG: A') else console.log('local note ' + guid + ' exists, updating from remote.') switch note.status when @NOTE_STATUS.NEW console.log('[IMPOSSIBLE] remote note\'s local cache is in status NEW') when @NOTE_STATUS.SYNCED_META # update note title p = @update_note({ guid: guid title: title notebook_guid: notebook_guid }) _find_p_must_finish_promise_list.push(p) console.log('pushed to _find_p_must_finish_promise_list. TAG: B') when @NOTE_STATUS.SYNCED_ALL # fetch the whole note from server and update local console.log('local note ' + guid + ' is SYNCED_ALL, about to fetch from remote for updating') @fetch_remote_note(guid).then( (note) => console.log('note ' + guid + ' (SYNCED_ALL) updated from remote') # maybe FIXME did not add to promise waiting list #_find_p_must_finish_promise_list.push(p) #console.log('pushed to _find_p_must_finish_promise_list. TAG: C') (error) => notifier.error('fetch note ' + guid + ' failed during _merge_remote_notes():' + JSON.stringify(error)) ) when @NOTE_STATUS.MODIFIED # do nothing console.log('do nothing') else notifier.error('IMPOSSIBLE: no correct note status') return Promise.all(_find_p_must_finish_promise_list) must_finish_promise_list.push(find_p) console.log('pushed to must_finish_promise_list. TAG: D') # Phase two: deleted local notes not needed # Notes that should be deleted: # not in remote and status is not new/modified p = @get_all_notes().then (notes) => for n in notes if (n.guid not in remote_note_guid_list) && n.status != @NOTE_STATUS.NEW && n.status != @NOTE_STATUS.MODIFIED _p = @delete_note(n.guid) must_finish_promise_list.push(_p) console.log('pushed to must_finish_promise_list. TAG: E') must_finish_promise_list.push(p) console.log('pushed to must_finish_promise_list. TAG: F') console.log('about to return from _merge_remote_notes(). promise list: ' + JSON.stringify(must_finish_promise_list)) console.log('check if promises in promise list is actually Promises:') for p in must_finish_promise_list if p instanceof Promise console.log('is Promise!') else console.log('is NOT Promise!!') return Promise.all(must_finish_promise_list) # ------------------------------------------------------------ # Params: # jq_div: jQuery div element for rendering # one_note_synced_func: function called whenever a note is successfully synced up # ------------------------------------------------------------ sync_up_all_notes: (jq_div) => p = @get_all_notes().then (notes) => _must_finish_promise_list = [] for note in notes guid = note.guid notebook_guid = note.notebook_guid md = note.md if note.status == @NOTE_STATUS.NEW || note.status == @NOTE_STATUS.MODIFIED is_new_note = (note.status == @NOTE_STATUS.NEW) console.log('note ' + guid + ' sent for sync up') _p = @sync_up_note(is_new_note, guid, notebook_guid, jq_div, md).then( (synced_note) => console.log('sync up note ' + guid + ' succeeded') @note_synced(true, guid, synced_note.guid, null) (error) => notifier.error('sync up note ' + guid + ' failed: ' + JSON.stringify(error)) @note_synced(false, null, null, error) ) _must_finish_promise_list.push(_p) return Promise.all(_must_finish_promise_list) return p.catch (error) => trace = printStackTrace({e: error}) notifier.error('sync_up_all_notes() failed\n' + 'Message: ' + error.message + '\nStack trace:\n' + trace.join('\n')) # ------------------------------------------------------------ # return Promise containing the synced note # ------------------------------------------------------------ sync_up_note: (is_new_note, guid, notebook_guid, jq_div, md) => console.log('enter sync_up_note() for note ' + guid) return enmlRenderer.get_enml_and_title_promise(jq_div, md).then (enml_and_title) => title = enml_and_title.title enml = enml_and_title.enml request_guid = guid if is_new_note request_guid = '' return apiClient.save_note(request_guid, notebook_guid, title, enml).then( (note) => # 1. change note status to SYNCED_ALL, using old guid _modify = guid: guid status: @NOTE_STATUS.SYNCED_ALL # 2. update notebook_guid if it is set a new one from remote if notebook_guid != note.notebook_guid _modify['notebook_guid'] = note.notebook_guid p = @update_note(_modify).then () => # 3. update guid if is new note (when saving new note, tmp guid will be updated to real one) if is_new_note new_guid = note.guid # @update_note_guid will return Promise containing the updated note return @update_note_guid(guid, new_guid) else return @find_note_by_guid(guid) return p console.log('sync_up_note(' + guid + ') succeed') (error) => # set status back notifier.error('sync_up_note() failed: \n' + JSON.stringify(error)) throw error ) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| DB Operations > # db server safe. will get db server itself get_all_notes: () => console.log('get_all_notes() invoked') return dbProvider.get_db_server_promise().then (server) => return server.notes.query().all().execute() # ------------------------------------------------------------ # make a new note to db # # db server safe. will get db server itself # return promise # ------------------------------------------------------------ make_new_note: () => console.log('make_new_note() invoking') return new Promise (resolve, reject) => guid = uuid2.newguid() + '-new' db_server_p = new Promise (resolve, reject) => # db.js does not return real Promise... _false_p = dbProvider.get_db_server_promise().then (server) => server.notes.add({ guid: guid title: 'New Note' md: 'New Note\n==\n' notebook_guid: '' status: @NOTE_STATUS.NEW }) resolve(_false_p) p = db_server_p.then( () => return @find_note_by_guid(guid) (error) => notifier.error('make_new_note() error!') ) resolve(p) # db server safe. will get db server itself delete_note: (guid) => console.log('delete_note(' + guid + ') invoked') return @find_note_by_guid(guid).then( (note) => if note is null console.log('cannot delete note null, aborted') else console.log('about to remove note id ' + note.id) p = dbProvider.get_db_server_promise().then (server) => server.notes.remove(note.id) console.log('local note ' + note.guid + ' deleted. id: ' + note.id) p.catch (error) => notifier.error('delete_note(' + guid + ') failed') (error) => notifier.error('error!') ) # ------------------------------------------------------------ # Return a copy of a note in db with a given guid # # db server safe. will get db server itself # return: promise containing the note's info, # or null if note does not exist # ------------------------------------------------------------ find_note_by_guid: (guid) => # db.js then() does not return a Promise, # need to be wrapper in a real Promise p = dbProvider.get_db_server_promise().then (server) => return new Promise (resolve, reject) => resolve(server.notes.query().filter('guid', guid).execute()) return p.then (notes) => if notes.length == 0 console.log('find_note_by_guid(' + guid + ') returned null') return null else console.log('find_note_by_guid(' + guid + ') hit') return notes[0] # ------------------------------------------------------------ # Add a note's metadata which to db # # db server safe. will get db server itself # return: promise # ------------------------------------------------------------ add_note_meta: (note) -> console.log('Adding note to db - guid: ' + note.guid + ' title: ' + note.title + ' notebook_guid: ' + note.notebook_guid) return dbProvider.get_db_server_promise().then (server) => return new Promise (resolve, reject) => resolve( server.notes.add({ guid: note.guid title: note.title notebook_guid: note.notebook_guid status: @NOTE_STATUS.SYNCED_META }) ) # ------------------------------------------------------------ # Update a note, except for its guid # # db server safe. will get db server itself # If need to update note's guid, please use update_note_guid() # # return: promise # ------------------------------------------------------------ update_note: (note) => console.log('update_note(' + note.guid + ') invoking') if note.guid? == false notifier.error('update_note(): note to be updated must have a guid!') return new Promise (resolve, reject) => reject(new Error('update_note(): note to be updated must have a guid!')) # register resource data into ImageManager if note.resources? for r in note.resources imageManager.add_image(r.uuid, r.data_url).catch (error) => notifier.error('add image failed! uuid: ' + r.uuid) console.log("register uuid: " + r.uuid + " data len: " + r.data_url.length) # update notes db p = new Promise (resolve, reject) => _note_modify = {} if note.title? _note_modify.title = note.title if note.md? _note_modify.md = note.md if note.notebook_guid? _note_modify.notebook_guid = note.notebook_guid if note.status? _note_modify.status = note.status _modify_p = dbProvider.get_db_server_promise().then (server) => return server.notes.query().filter('guid', note.guid).modify(_note_modify).execute() resolve(_modify_p) return p.then( () => console.log('update note ' + note.guid + ' successfully') return @find_note_by_guid(note.guid) (error) => notifier.error('update note ' + note.guid + ' failed!') ) # return promise containing the updated note update_note_guid: (old_guid, new_guid) => p = @find_note_by_guid(old_guid).then (note) => if note? _modify_p = dbProvider.get_db_server_promise().then (server) => _note_modify = {guid: new_guid} return server.notes.query().filter('guid', old_guid).modify(_note_modify).execute() return _modify_p else console.log('update note guid ' + old_guid + ' to new guid ' + new_guid + ' missed!') return p.then( () => console.log('update note guid ' + old_guid + ' to new guid ' + new_guid + ' succeed') # notify current note guid changed if old_guid == @current_note.guid @current_note_guid_modified(old_guid, new_guid) return @find_note_by_guid(new_guid) (error) => notifier.error('update note guid ' + old_guid + ' to new guid ' + new_guid + ' failed: ' + error) ) # ------------------------------------------------------------ # Clear db # # db server safe. will get db server itself # return: promise # ------------------------------------------------------------ clear_all_notes: () -> return dbProvider.get_db_server_promise().then (server) => server.notes.clear() # --------------------------------- tmp operations -------------------------------- ]
true
"use strict" markever = angular.module('markever', ['ngResource', 'ui.bootstrap', 'LocalStorageModule', 'angularUUID2']) markever.controller 'EditorController', ['$scope', '$window', '$document', '$http', '$sce', '$interval', 'localStorageService', 'enmlRenderer', 'scrollSyncor', 'apiClient', 'noteManager', 'imageManager', 'dbProvider', 'notifier', 'offlineStateManager', ($scope, $window, $document, $http, $sce, $interval localStorageService, enmlRenderer, scrollSyncor, apiClient, noteManager, imageManager, dbProvider, notifier, offlineStateManager) -> vm = this # ------------------------------------------------------------------------------------------------------------------ # Models # ------------------------------------------------------------------------------------------------------------------ # ------------------------------------------------------------------------------------------------------------------ # Debugging methods # ------------------------------------------------------------------------------------------------------------------ vm._debug_show_current_note = () -> alert(JSON.stringify(vm.note)) vm._debug_close_db = () -> dbProvider.close_db() alert('db closed!') vm._debug_show_current_note_in_db = () -> noteManager.find_note_by_guid(vm.get_guid()).then (note) => alert('current note (' + vm.get_guid() + ') in db is: ' + JSON.stringify(note)) vm._debug_offline_check = -> $window.Offline.check() # ------------------------------------------------------------------------------------------------------------------ # App ready status # ------------------------------------------------------------------------------------------------------------------ vm.all_ready = false # ------------------------------------------------------------------------------------------------------------------ # Document ready # ------------------------------------------------------------------------------------------------------------------ $document.ready -> # init ace editor vm.init_ace_editor() # init ui vm.init_ui() # sync scroll scrollSyncor.syncScroll(vm.ace_editor, $('#md_html_div')) noteManager.init_current_note() # get note list from local noteManager.reload_local_note_list() # get note list from remote if not offlineStateManager.is_offline() noteManager.fetch_note_list() else console.log('offline mode, did not fetch note list from remote') # get notebook list from local noteManager.reload_local_notebook_list() # get notebook list from remote if not offlineStateManager.is_offline() noteManager.fetch_notebook_list() else console.log('offline mode, did not fetch notebook list from remote') # take effect the settings vm.set_keyboard_handler(vm.current_keyboard_handler) vm.set_show_gutter(vm.current_show_gutter) vm.set_ace_theme(vm.current_ace_theme) # reset app status vm.reset_status() # all ready vm.all_ready = true # ------------------------------------------------------------------------------------------------------------------ # UI Logic that has to be made by js # ------------------------------------------------------------------------------------------------------------------ vm.init_ui = -> # when showing note list which is a modal, make the backdrop to be transparent $('#note_list_div').on 'show.bs.modal hidden.bs.modal', () -> $('body').toggleClass('modal-backdrop-transparent') # ------------------------------------------------------------------------------------------------------------------ # ace editor init # ------------------------------------------------------------------------------------------------------------------ vm.init_ace_editor = -> $window.ace.config.set('basePath', '/javascripts/ace') vm.ace_editor = $window.ace.edit("md_editor_div") vm.ace_editor.renderer.setShowGutter(false) vm.ace_editor.setShowPrintMargin(false) vm.ace_editor.getSession().setMode("ace/mode/markdown") vm.ace_editor.getSession().setUseWrapMode(true) vm.ace_editor.setTheme('ace/theme/tomorrow_night_eighties') vm.ace_editor.on 'change', vm.editor_content_changed vm.ace_editor.focus() # ------------------------------------------------------------------------------------------------------------------ # ace editor event handlers # ------------------------------------------------------------------------------------------------------------------ vm.editor_content_changed = (event) -> # render html, since noteManager will not notify back if use editor_content_changed(...) enmlRenderer.render_html($('#md_html_div'), vm.ace_editor.getValue()) noteManager.editor_content_changed(vm.ace_editor.getValue()) # ------------------------------------------------------------------------------------------------------------------ # Operations for notes # ------------------------------------------------------------------------------------------------------------------ vm.load_note = (guid) -> if guid == noteManager.get_current_note_guid() return noteManager.is_note_loadable_locally_promise(guid).then (loadable_locally) -> if not loadable_locally and offlineStateManager.is_offline() notifier.info('Cannot load note in offline mode') else vm.open_loading_modal() noteManager.load_note(guid) vm.sync_up_all_notes = -> if offlineStateManager.is_offline() notifier.info('Cannot sync up notes in offline mode') return if vm.saving_note == false vm.saving_note = true p = noteManager.sync_up_all_notes($('#md_html_div_hidden')).then () => notifier.success('sync_up_all_notes() succeeded for all notes!') vm.saving_note = false p.catch (error) => notifier.error('vm.sync_up_all_notes() failed: ' + error) vm.saving_note = false # ------------------------------------------------------------------------------------------------------------------ # TODO Note Manager Event Handlers # ------------------------------------------------------------------------------------------------------------------ noteManager.on_current_note_md_modified (new_md) -> vm.ace_editor.setValue(new_md) enmlRenderer.render_html($('#md_html_div'), new_md).catch (error) => notifier.error('render error: ' + error) console.log('on_current_note_md_modified()') noteManager.on_current_note_switched (new_note_guid) -> enmlRenderer.render_html($('#md_html_div'), noteManager.get_current_note_md()) noteManager.on_note_load_finished (is_success, guid, error) -> vm.close_loading_modal() if is_success console.log('load note ' + guid + ' succeeded') else notifier.error('load note ' + guid + ' failed: ' + error) noteManager.on_note_synced (is_success, old_guid, new_guid, error) -> noteManager.on_note_list_changed (note_list) -> noteManager.on_notebook_list_changed (notebook_list) -> # ------------------------------------------------------------------------------------------------------------------ # App Status # ------------------------------------------------------------------------------------------------------------------ vm.saving_note = false # reset status vm.reset_status = -> # if the note is in process of saving (syncing) or not vm.saving_note = false # ------------------------------------------------------------------------------------------------------------------ # Editor Settings # ------------------------------------------------------------------------------------------------------------------ # settings name constants vm.SETTINGS_KEY = KEYBOARD_HANDLER: 'settings.keyboard_handler' SHOW_GUTTER: 'settings.show_gutter' ACE_THEME: 'settings.ace_theme' CURRENT_NOTE_GUID: 'settings.current_note.guid' # -------------------------------------------------------- # Editor Keyboard Handler Settings # -------------------------------------------------------- vm.keyboard_handlers = [ {name: 'normal', id: ''} {name: 'vim', id: 'ace/keyboard/vim'} ] # load settings from local storage if localStorageService.get(vm.SETTINGS_KEY.KEYBOARD_HANDLER) != null # N.B. should be set to reference, not value! saved_handler = localStorageService.get(vm.SETTINGS_KEY.KEYBOARD_HANDLER) for handler in vm.keyboard_handlers if saved_handler.name == handler.name vm.current_keyboard_handler = handler break else vm.current_keyboard_handler = vm.keyboard_handlers[0] # "new" keyboard handler used in settings modal # N.B. must by reference, not value # refer: http://jsfiddle.net/qWzTb/ # and: https://docs.angularjs.org/api/ng/directive/select vm.new_keyboard_handler = vm.current_keyboard_handler vm.set_keyboard_handler = (handler) -> vm.ace_editor.setKeyboardHandler(handler.id) vm.current_keyboard_handler = handler localStorageService.set(vm.SETTINGS_KEY.KEYBOARD_HANDLER, JSON.stringify(handler)) # -------------------------------------------------------- # Editor Gutter Settings # -------------------------------------------------------- if localStorageService.get(vm.SETTINGS_KEY.KEYBOARD_HANDLER) != null vm.current_show_gutter = JSON.parse(localStorageService.get(vm.SETTINGS_KEY.SHOW_GUTTER)) else vm.current_show_gutter = false vm.new_show_gutter = vm.show_gutter vm.set_show_gutter = (is_show) -> vm.ace_editor.renderer.setShowGutter(is_show) vm.current_show_gutter = is_show localStorageService.set(vm.SETTINGS_KEY.SHOW_GUTTER, JSON.stringify(is_show)) # -------------------------------------------------------- # Editor Theme Settings # -------------------------------------------------------- vm.ace_themes = [ {name: 'default', id: ''} {name: 'ambiance', id: 'ace/theme/ambiance'} {name: 'chaos', id: 'ace/theme/chaos'} {name: 'chrome', id: 'ace/theme/chrome'} {name: 'clouds', id: 'ace/theme/clouds'} {name: 'clouds_midnight', id: 'ace/theme/clouds_midnight'} {name: 'cobalt', id: 'ace/theme/cobalt'} {name: 'crimson_editor', id: 'ace/theme/crimson_editor'} {name: 'dawn', id: 'ace/theme/dawn'} {name: 'dreamweaver', id: 'ace/theme/dreamweaver'} {name: 'eclipse', id: 'ace/theme/eclipse'} {name: 'github', id: 'ace/theme/github'} {name: 'idle_fingers', id: 'ace/theme/idle_fingers'} {name: 'katzenmilch', id: 'ace/theme/katzenmilch'} {name: 'kr_theme', id: 'ace/theme/kr_theme'} {name: 'kuroir', id: 'ace/theme/kuroir'} {name: 'merbivore', id: 'ace/theme/merbivore'} {name: 'merbivore_soft', id: 'ace/theme/merbivore_soft'} {name: 'mono_industrial', id: 'ace/theme/mono_industrial'} {name: 'monokai', id: 'ace/theme/monokai'} {name: 'pastel_on_dark', id: 'ace/theme/pastel_on_dark'} {name: 'solarized_dark', id: 'ace/theme/solarized_dark'} {name: 'solarized_light', id: 'ace/theme/solarized_light'} {name: 'terminal', id: 'ace/theme/terminal'} {name: 'textmate', id: 'ace/theme/textmate'} {name: 'tomorrow', id: 'ace/theme/tomorrow'} {name: 'tomorrow_night', id: 'ace/theme/tomorrow_night'} {name: 'tomorrow_night_blue', id: 'ace/theme/tomorrow_night_blue'} {name: 'tomorrow_night_bright', id: 'ace/theme/tomorrow_night_bright'} {name: 'tomorrow_night_eighties', id: 'ace/theme/tomorrow_night_eighties'} {name: 'twilight', id: 'ace/theme/twilight'} {name: 'vibrant_ink', id: 'ace/theme/vibrant_ink'} {name: 'xcode', id: 'ace/theme/xcode'} ] if localStorageService.get(vm.SETTINGS_KEY.ACE_THEME) != null # N.B. should be set to reference, not value! saved_ace_theme = localStorageService.get(vm.SETTINGS_KEY.ACE_THEME) for theme in vm.ace_themes if saved_ace_theme.name == theme.name vm.current_ace_theme = theme break else vm.current_ace_theme = vm.ace_themes[0] # "new" ace theme used in settings modal # N.B. same, must by reference, not value vm.new_ace_theme = vm.current_ace_theme vm.set_ace_theme = (theme) -> vm.ace_editor.setTheme(theme.id) vm.current_ace_theme = theme localStorageService.set(vm.SETTINGS_KEY.ACE_THEME, JSON.stringify(theme)) # ------------------------------------------------------------------------------------------------------------------ # on paste # ------------------------------------------------------------------------------------------------------------------ vm.handle_paste = (e) => if not vm.ace_editor.isFocused return false items = (e.clipboardData || e.originalEvent.clipboardData).items console.log(JSON.stringify(items)) if items[0].type.match(/image.*/) blob = items[0].getAsFile() image_uuid = imageManager.load_image_blob(blob) vm.ace_editor.insert('![Alt text](' + image_uuid + ')') # ------------------------------------------------------------------------------------------------------------------ # settings modal # ------------------------------------------------------------------------------------------------------------------ vm.open_settings_modal = -> # reset "new" settings to current settings vm.new_keyboard_handler = vm.current_keyboard_handler vm.new_ace_theme = vm.current_ace_theme vm.new_show_gutter = vm.current_show_gutter # show modal $('#settings-modal').modal({}) # explicit return non-DOM result to avoid warning return true vm.save_settings = -> vm.set_ace_theme(vm.new_ace_theme) vm.set_keyboard_handler(vm.new_keyboard_handler) vm.set_show_gutter(vm.new_show_gutter) # ------------------------------------------------------------------------------------------------------------------ # note list modal # ------------------------------------------------------------------------------------------------------------------ vm.open_note_list_modal = -> # clear search keyword vm.search_note_keyword = '' note_list = noteManager.get_note_list() notebook_list = noteManager.get_notebook_list() notebook_name_map = {} notebook_collapse_map = {} for nb in notebook_list notebook_name_map[nb.guid] = nb.name notebook_collapse_map[nb.guid] = true # key: notebook guid; value: Map{notebook_name: String, note_list: Array} note_group_list = {} for n in note_list if not (n.notebook_guid of note_group_list) if n.notebook_guid.trim() == "" note_group_list[n.notebook_guid] = notebook_name: 'Unspecified Notebook' note_list: [] else note_group_list[n.notebook_guid] = notebook_name: notebook_name_map[n.notebook_guid] note_list: [] note_group_list[n.notebook_guid].note_list.push(n) if not vm.notebook_collapse_map? vm.notebook_collapse_map = notebook_collapse_map vm.note_group_list = note_group_list $('#note_list_div').modal({}) # explicit return non-DOM result to avoid warning return true # ------------------------------------------------------------------------------------------------------------------ # toolbar # ------------------------------------------------------------------------------------------------------------------ # ------------------------------------------------------------------------------------------------------------------ # loading modal # ------------------------------------------------------------------------------------------------------------------ vm.open_loading_modal = -> $('#loading-modal').modal({ backdrop: 'static' keyboard: false }) vm.close_loading_modal = -> $('#loading-modal').modal('hide') # fixme for debug vm.note_manager = noteManager ] # ---------------------------------------------------------------------------------------------------------------------- # Service: enmlRenderer # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'enmlRenderer', ['$window', 'imageManager', 'notifier', ($window, imageManager, notifier) -> render_html = (jq_html_div, md) -> processed_md = _md_pre_process(md) _html_dom = $('<div></div>') _html_dom.html($window.marked(processed_md, {sanitize: true})) return _html_post_process(_html_dom).then( () -> jq_html_div.empty() jq_html_div.append(_html_dom) (error) -> notifier.error('render_html() error: ' + error) ) _md_pre_process = (md) -> # TODO more handling processed_md = md return processed_md # return promise _html_post_process = (jq_tmp_div) -> # code highlighting jq_tmp_div.find('pre code').each (i, block) -> hljs.highlightBlock(block) # render Latex $window.MathJax.Hub.Queue(['Typeset', $window.MathJax.Hub, jq_tmp_div.get(0)]) # change img src to real data url must_finish_promise_list = [] jq_tmp_div.find('img[src]').each (index) -> $img = $(this) uuid = $img.attr('src') p = imageManager.find_image_by_uuid(uuid).then( (image) => if image? console.log('change img src from ' + uuid + ' to its base64 content') $img.attr('longdesc', uuid) $img.attr('src', image.content) (error) => notifier.error('_html_post_process() failed due to failure in imageManager.find_image_by_uuid(' + uuid + '): ' + error) ) must_finish_promise_list.push(p.catch (error) -> notifier.error('image replace failed: ' + error)) return Promise.all(must_finish_promise_list).then () -> return jq_tmp_div get_enml_and_title_promise = (jq_html_div, markdown) -> return render_html(jq_html_div, markdown).then () => # further post process # remove all script tags jq_html_div.find('script').remove() # add inline style # refer: https://github.com/Karl33to/jquery.inlineStyler # TODO still too much redundant styles inline_styler_option = { 'propertyGroups' : { 'font-matters' : ['font-size', 'font-family', 'font-style', 'font-weight'], 'text-matters' : ['text-indent', 'text-align', 'text-transform', 'letter-spacing', 'word-spacing', 'word-wrap', 'white-space', 'line-height', 'direction'], 'display-matters' : ['display'], 'size-matters' : ['width', 'height'], 'color-matters' : ['color', 'background-color'], 'position-matters' : ['margin', 'margin-left', 'margin-right', 'margin-top', 'margin-bottom', 'padding', 'padding-left', 'padding-right', 'padding-top', 'padding-bottom', 'float'], 'border-matters' : ['border', 'border-left', 'border-right', 'border-radius', 'border-top', 'border-right', 'border-color'], }, 'elementGroups' : { # N.B. UPPERCASE tags 'font-matters' : ['DIV', 'BLOCKQUOTE', 'SPAN', 'STRONG', 'EM', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'], 'text-matters' : ['SPAN', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'], 'display-matters' : ['HR', 'PRE', 'SPAN', 'UL', 'OL', 'LI', 'PRE', 'CODE'], 'size-matters' : ['SPAN'], 'color-matters' : ['DIV', 'SPAN', 'PRE', 'CODE', 'BLOCKQUOTE', 'HR'], 'position-matters' : ['DIV', 'PRE', 'BLOCKQUOTE', 'SPAN', 'HR', 'UL', 'OL', 'LI', 'P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'], 'border-matters' : ['HR', 'BLOCKQUOTE', 'SPAN', 'PRE', 'CODE'], } } jq_html_div.inlineStyler(inline_styler_option) # set href to start with 'http' is no protocol assigned jq_html_div.find('a').attr 'href', (i, href) -> if not href.toLowerCase().match('(^http)|(^https)|(^file)') return 'http://' + href else return href # clean the html tags/attributes html_clean_option = { format: true, allowedTags: ['a', 'abbr', 'acronym', 'address', 'area', 'b', 'bdo', 'big', 'blockquote', 'br', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'div', 'dl', 'dt', 'em', 'font', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'map', 'ol', 'p', 'pre', 'q', 's', 'samp', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'title', 'tr', 'tt', 'u', 'ul', 'var', 'xmp',], allowedAttributes: [['href', ['a']], ['longdesc'], ['style']], removeAttrs: ['id', 'class', 'onclick', 'ondblclick', 'accesskey', 'data', 'dynsrc', 'tabindex',], } cleaned_html = $.htmlClean(jq_html_div.html(), html_clean_option); # FIXME hack for strange class attr not removed cleaned_html = cleaned_html.replace(/class='[^']*'/g, '') cleaned_html = cleaned_html.replace(/class="[^"]*"/g, '') # embbed raw markdown content into the html cleaned_html = cleaned_html + '<center style="display:none">' + $('<div />').text(markdown).html() + '</center>' # add XML header & wrap with <en-note></en-note> final_note_xml = '<?xml version="1.0" encoding="utf-8"?>' + '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' + '<en-note>' + cleaned_html + '</en-note>' # make title title = 'New Note - PI:NAME:<NAME>END_PIkever' if jq_html_div.find('h1').size() > 0 text = jq_html_div.find('h1').text() title = text if text.trim().length > 0 else if jq_html_div.find('h2').size() > 0 text = jq_html_div.find('h2').text() title = text if text.trim().length > 0 else if jq_html_div.find('h3').size() > 0 text = jq_html_div.find('h3').text() title = text if text.trim().length > 0 else if jq_html_div.find('p').size() > 0 text = jq_html_div.find('p').text() title = text if text.trim().length > 0 # the return value of result promise return {enml: final_note_xml, title: title} get_title_promise = (jq_html_div, markdown) -> return render_html(jq_html_div, markdown).then () => title = 'New Note - Markever' if jq_html_div.find('h1').size() > 0 text = jq_html_div.find('h1').text() title = text if text.trim().length > 0 else if jq_html_div.find('h2').size() > 0 text = jq_html_div.find('h2').text() title = text if text.trim().length > 0 else if jq_html_div.find('h3').size() > 0 text = jq_html_div.find('h3').text() title = text if text.trim().length > 0 else if jq_html_div.find('p').size() > 0 text = jq_html_div.find('p').text() title = text if text.trim().length > 0 return title return { get_enml_and_title_promise : get_enml_and_title_promise get_title_promise: get_title_promise render_html: render_html } ] # ---------------------------------------------------------------------------------------------------------------------- # Service: enmlRenderer # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'scrollSyncor', -> syncScroll = (ace_editor, jq_div) -> ace_editor.setShowPrintMargin(false) # sync scroll: md -> html editor_scroll_handler = (scroll) => percentage = scroll / (ace_editor.session.getScreenLength() * \ ace_editor.renderer.lineHeight - ($(ace_editor.renderer.getContainerElement()).height())) if percentage > 1 or percentage < 0 then return percentage = Math.floor(percentage * 1000) / 1000; # detach other's scroll handler first jq_div.off('scroll', html_scroll_handler) md_html_div = jq_div.get(0) md_html_div.scrollTop = percentage * (md_html_div.scrollHeight - md_html_div.offsetHeight) # re-attach other's scroll handler at the end, with some delay setTimeout (-> jq_div.scroll(html_scroll_handler)), 10 ace_editor.session.on('changeScrollTop', editor_scroll_handler) # sync scroll: html -> md html_scroll_handler = (e) => md_html_div = jq_div.get(0) percentage = md_html_div.scrollTop / (md_html_div.scrollHeight - md_html_div.offsetHeight) if percentage > 1 or percentage < 0 then return percentage = Math.floor(percentage * 1000) / 1000; # detach other's scroll handler first ace_editor.getSession().removeListener('changeScrollTop', editor_scroll_handler); ace_editor.session.setScrollTop((ace_editor.session.getScreenLength() * \ ace_editor.renderer.lineHeight - $(ace_editor.renderer.getContainerElement()).height()) * percentage) # re-attach other's scroll handler at the end, with some delay setTimeout (-> ace_editor.session.on('changeScrollTop', editor_scroll_handler)), 20 jq_div.scroll(html_scroll_handler) return { syncScroll : syncScroll } # ---------------------------------------------------------------------------------------------------------------------- # Service: apiClient # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'apiClient', ['$resource', ($resource) -> new class APIClient note_resource: $resource('/api/v1/notes/:id', {id: '@id'}, { all: {method : 'GET', params : {id: ''}} note: {method : 'GET', params: {}} newest: {method : 'GET', params : {id: 'newest'}} save: {method : 'POST', params: {id: ''}} }) notebook_resource: $resource('/api/v1/notebooks/:id', {id: '@id'}, { all: {method: 'GET', params: {id: ''}} }) # return promise with all notes get_all_notes: () => return @note_resource.all().$promise.then (data) => return data['notes'] # return promise with the note get_note: (guid) => return @note_resource.note({id: guid}).$promise.then (data) => return data.note # return promise with saved note that is returned from remote save_note: (guid, notebook_guid, title, enml) => _post_data = { guid: guid notebookGuid: notebook_guid title: title enml: enml } return @note_resource.save(_post_data).$promise.then (data) => return data.note get_all_notebooks: () => return @notebook_resource.all().$promise.then (data) => return data['notebooks'] ] # ---------------------------------------------------------------------------------------------------------------------- # Service: notifier # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'notifier', -> new class Notifier success: (msg) -> $.bootstrapGrowl(msg, {type: 'success'}) info: (msg) -> $.bootstrapGrowl(msg, {type: 'info'}) error: (msg) -> $.bootstrapGrowl(msg, {type: 'danger'}) # ---------------------------------------------------------------------------------------------------------------------- # Service: offline state manager # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'offlineStateManager', ['$window', 'notifier', ($window, notifier) -> new class OfflineStateManager constructor: -> @initialized = false @_is_offline = false @_init() $window.Offline.check() _init: => if not @initialized $window.Offline.on 'confirmed-up', () => @_is_offline = false #notifier.success('connection up') $window.Offline.on 'confirmed-down', () => @_is_offline = true #notifier.error('connection down') $window.Offline.on 'up', () => @_is_offline = false notifier.success('connection restored') $window.Offline.on 'down', () => @_is_offline = true notifier.error('connection went down') $window.Offline.on 'reconnect:started', () => #notifier.info('reconnecting started') $window.Offline.on 'reconnect:stopped', () => #notifier.info('reconnecting stopped') $window.Offline.on 'reconnect:failure', () => notifier.error('reconnecting failed') is_offline: => return @_is_offline check_connection: => $window.Offline.check() ] # ---------------------------------------------------------------------------------------------------------------------- # Service: dbProvider # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'dbProvider', -> new class DBProvider constructor: -> @db_server_promise = @init_db() init_db: () => db_open_option = { server: 'markever' version: 1 schema: { notes: { key: {keyPath: 'id', autoIncrement: true}, indexes: { guid: {} title: {} notebook_guid: {} status: {} # no need to index md # md: {} } } images: { key: {keyPath: 'id', autoIncrement: true}, indexes: { uuid: {} # no need to index content # content: {} } } } } # db.js promise is not real promise _false_db_p = db.open(db_open_option) return new Promise (resolve, reject) => resolve(_false_db_p) get_db_server_promise: () => console.log('return real promise @db_server_promise') if @db_server_promise? return @db_server_promise else return @init_db() close_db: () => @db_server_promise.then (server) => server.close() console.log('db closed') # ---------------------------------------------------------------------------------------------------------------------- # Service: imageManager # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'imageManager', ['uuid2', 'dbProvider', (uuid2, dbProvider) -> new class ImageManager constructor: -> dbProvider.get_db_server_promise().then (server) => @db_server = server console.log('DB initialized from ImageManager') # ------------------------------------------------------------ # Return a copy of a image in db with a given uuid # # return: promise containing the image's info: # uuid, content # or null if image does not exist # ------------------------------------------------------------ find_image_by_uuid: (uuid) => p = new Promise (resolve, reject) => resolve(@db_server.images.query().filter('uuid', uuid).execute()) return p.then (images) => if images.length == 0 console.log('find_image_by_uuid(' + uuid + ') returned null') return null else console.log('find_image_by_uuid(' + uuid + ') hit') return images[0] # ------------------------------------------------------------ # Add a image to db # # return: promise # ------------------------------------------------------------ add_image: (uuid, content) => console.log('Adding image to db - uuid: ' + uuid) return new Promise (resolve, reject) => resolve( @db_server.images.add({ uuid: uuid content: content }) ) # return: the uuid of the image (NOT promise) load_image_blob: (blob, extra_handler) => uuid = uuid2.newuuid() reader = new FileReader() reader.onload = (event) => console.log("image result: " + event.target.result) @add_image(uuid, event.target.result) # optional extra_handler if extra_handler extra_handler(event) # start reading blob data, and get result in base64 data URL reader.readAsDataURL(blob) return uuid ] # ---------------------------------------------------------------------------------------------------------------------- # Service: noteManager # ---------------------------------------------------------------------------------------------------------------------- markever.factory 'noteManager', ['$interval', 'uuid2', 'localStorageService', 'dbProvider', 'apiClient', 'imageManager', 'enmlRenderer', 'notifier', 'offlineStateManager', ($interval, uuid2, localStorageService, dbProvider, apiClient, imageManager, enmlRenderer, notifier, offlineStateManager) -> new class NoteManager #--------------------------------------------------------------------------------------------------------------------- # Status of a note: # 1. new: note with a generated guid, not attached to remote # 2. synced_meta: note with metadata fetched to remote. not editable # 3. synced_all: note with all data synced with remote. editable # 4. modified: note attached to remote, but has un-synced modification # # Status transition: # # sync modify # new ------> synced_all ---------> modified # ^ <--------- # | sync # | # | load note data from remote # | # synced_meta ------ #--------------------------------------------------------------------------------------------------------------------- constructor: -> $interval(@save_current_note_to_db, 1000) NOTE_STATUS: NEW: 0 SYNCED_META: 1 SYNCED_ALL: 2 MODIFIED: 3 STORAGE_KEY: CURRENT_NOTE_GUID: 'note_manager.current_note.guid' NOTEBOOK_LIST: 'note_manager.notebook_list' # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Current Note > current_note: guid: '' title: '' status: null md: '' notebook_guid: '' _is_dirty: false # ------------------------------------------------------------ # Public accessor for current_note # ------------------------------------------------------------ get_current_note_guid: => return @current_note.guid get_current_note_title: => return @current_note.title get_current_note_status: => return @current_note.status get_current_note_md: => return @current_note.md get_current_note_notebook_guid: => return @current_note.notebook_guid # ------------------------------------------------------------ # Private accessor for current_note # ------------------------------------------------------------ _is_current_note_dirty: () => return @current_note._is_dirty _set_current_note_dirty: (is_dirty) => @current_note._is_dirty = is_dirty _switch_current_note: (guid, notebook_guid, title, md, status) => console.log('_switch_current_note(...) invoked') @_set_current_note_guid(guid) if notebook_guid? @_set_current_note_notebook_guid(notebook_guid) if title? @_set_current_note_title(title) if md? if @get_current_note_md() != md @_set_current_note_md(md) if status? @_set_current_note_status(status) # notify event after current note changed @current_note_switched(guid) _set_current_note_guid: (guid) => @current_note.guid = guid _set_current_note_title: (title) => @current_note.title = title _set_current_note_md: (md, notify=true) => if @get_current_note_md() != md @current_note.md = md if notify @current_note_md_modified(md) # change note status to MODIFIED if original status is SYNCED_ALL if @get_current_note_status() == @NOTE_STATUS.SYNCED_ALL @_set_current_note_status(@NOTE_STATUS.MODIFIED) _set_current_note_status: (status) => @current_note.status = status @reload_local_note_list() _set_current_note_notebook_guid: (notebook_guid) => @current_note.notebook_guid = notebook_guid @reload_local_note_list() # ------------------------------------------------------------ # Other Operations for Current Note # ------------------------------------------------------------ editor_content_changed: (md) => if @get_current_note_md() != md # update md w/o notifying, otherwise will make loop @_set_current_note_md(md, false) @_set_current_note_dirty(true) save_current_note_to_db: () => if @_is_current_note_dirty() console.log('current note is dirty, saving to db...') # FIXME remove jq element enmlRenderer.get_title_promise($('#md_html_div_hidden'), @get_current_note_md()).then (title) => note_info = guid: @get_current_note_guid() notebook_guid: @get_current_note_notebook_guid() title: title md: @get_current_note_md() status: @get_current_note_status() @update_note(note_info).then( (note) => console.log('dirty note successfully saved to db: ' + JSON.stringify(note) + ', set it to not dirty.') # because title may change, we need to reload note list @reload_local_note_list() @_set_current_note_dirty(false) (error) => notifier.error('update note failed in save_current_note_to_db(): ' + JSON.stringify(error)) ).catch (error) => notifier.error('failed to save current note to db: ' + error) # ------------------------------------------------------------ # load previous note if exists, otherwise make a new note and set it current note # ------------------------------------------------------------ init_current_note: () => previous_note_guid = localStorageService.get(@STORAGE_KEY.CURRENT_NOTE_GUID) if not previous_note_guid? previous_note_guid = "INVALID_GUID" p = @find_note_by_guid(previous_note_guid).then (note) => if note? console.log('got valid previous current note ' + previous_note_guid + '. load...') @load_note(note.guid) else console.log('no valid previous current note found. create new note') @make_new_note().then( (note) => @_switch_current_note(note.guid, note.notebook_guid, note.title, note.md, @NOTE_STATUS.NEW) console.log('New note made: ' + JSON.stringify(note)) (error) => notifier.error('make_new_note() failed: ' + error) ).catch (error) => trace = printStackTrace({e: error}) notifier.error('Error, make new note failed!\n' + 'Message: ' + error.message + '\nStack trace:\n' + trace.join('\n')) p.catch (error) => notifier.error('load previous current note failed: ' + error) # ------------------------------------------------------------ # Load a note by guid as current note # # If note is SYNCED_ALL in local, just load it from local # otherwise fetch the note content from remote # # Return: not used # ------------------------------------------------------------ load_note: (guid) => # check if the note to be loaded is already current note if guid != @get_current_note_guid() p = @find_note_by_guid(guid).then (note) => if note? and (note.status == @NOTE_STATUS.NEW or note.status == @NOTE_STATUS.SYNCED_ALL or note.status == @NOTE_STATUS.MODIFIED) # note in db -> current note console.log('loading note ' + note.guid + ' with status ' + note.status + ' from local DB') @_switch_current_note(note.guid, note.notebook_guid, note.title, note.md, note.status) @note_load_finished(true, note.guid, null) console.log('loading note ' + note.guid + ' finished') if (note? == false) or (note.status == @NOTE_STATUS.SYNCED_META) # remote note -> current note @fetch_remote_note(guid).then( (note) => console.log('loading note ' + note.guid + ' with status ' + note.status + ' from remote') @_switch_current_note(note.guid, note.notebook_guid, note.title, note.md, note.status) @note_load_finished(true, note.guid, null) console.log('loading note ' + note.guid + ' finished') # updating note list @reload_local_note_list() (error) => notifier.error('load note ' + guid + ' failed: ' + JSON.stringify(error)) @note_load_finished(false, guid, new Error('load note ' + guid + ' failed: ' + JSON.stringify(error))) ) p.catch (error) => notifier.error('find_note_by_guid() itself or then() failed in load_note(): ' + JSON.stringify(error)) # ------------------------------------------------------------ # Check if a note is loadable from local # # The logic is consistent with the first part of load_note(guid) # # Return: promise with a boolean value # ------------------------------------------------------------ is_note_loadable_locally_promise: (guid) => if guid == @get_current_note_guid() return new Promise (resolve, reject) => resolve(true) return @find_note_by_guid(guid).then (note) => if note? and (note.status == @NOTE_STATUS.NEW or note.status == @NOTE_STATUS.SYNCED_ALL or note.status == @NOTE_STATUS.MODIFIED) return true else return false # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Note List > note_list: [] get_note_list: => return @note_list _set_note_list: (note_list) => @note_list = note_list @note_list_changed(note_list) # FIXME: delete previous comment when refactor is done fetch_note_list: => @load_remote_notes().then( (notes) => console.log('fetch_note_list() result: ' + JSON.stringify(notes)) @_set_note_list(notes) (error) => notifier.error('fetch_note_list() failed: ' + JSON.stringify(error)) ) reload_local_note_list: () => p = @get_all_notes().then (notes) => @_set_note_list(notes) p.catch (error) => notifier.error('reload_local_note_list() failed:' + error) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Notebook List > notebook_list: [] get_notebook_list: => return @notebook_list _set_notebook_list: (notebook_list) => @notebook_list = notebook_list localStorageService.set(@STORAGE_KEY.NOTEBOOK_LIST, notebook_list) @notebook_list_changed(notebook_list) reload_local_notebook_list: () => @_set_notebook_list(localStorageService.get(@STORAGE_KEY.NOTEBOOK_LIST)) fetch_notebook_list: => @load_remote_notebooks().then( (notebooks) => console.log('fetch_notebook_list() result: ' + JSON.stringify(notebooks)) @_set_notebook_list(notebooks) (error) => notifier.error('fetch_notebook_list() failed: ' + JSON.stringify(error)) ) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Event System > # ------------------------------------------------------------ # Event: current note markdown changed # ------------------------------------------------------------ current_note_md_modified_listeners: [] on_current_note_md_modified: (listener) => @current_note_md_modified_listeners.push(listener) current_note_md_modified: (new_md) => for l in @current_note_md_modified_listeners l(new_md) # ------------------------------------------------------------ # Event: current note switched to another note # ------------------------------------------------------------ current_note_switched_listeners: [] on_current_note_switched: (listener) => @current_note_switched_listeners.push(listener) current_note_switched: (new_note_guid) => localStorageService.set(@STORAGE_KEY.CURRENT_NOTE_GUID, new_note_guid) for l in @current_note_switched_listeners l(new_note_guid) # ------------------------------------------------------------ # Event: current note's guid changed (the note is still the "same" note) # ------------------------------------------------------------ current_note_guid_modified_listeners: [] on_current_note_guid_modified: (listener) => @current_note_guid_modified_listeners.push(listener) current_note_guid_modified: (old_guid, new_guid) => localStorageService.set(@STORAGE_KEY.CURRENT_NOTE_GUID, new_guid) for l in @current_note_guid_modified_listeners l(old_guid, new_guid) # ------------------------------------------------------------ # Event: a note finished synced up # ------------------------------------------------------------ note_synced_listeners: [] on_note_synced: (listener) => @note_synced_listeners.push(listener) note_synced: (is_success, old_guid, new_guid, error) => @reload_local_note_list() for l in @note_synced_listeners l(is_success, old_guid, new_guid, error) # ------------------------------------------------------------ # Event: note list changed # ------------------------------------------------------------ note_list_changed_listeners: [] on_note_list_changed: (listener) => @note_list_changed_listeners.push(listener) note_list_changed: (note_list) => for l in @note_list_changed_listeners l(note_list) # ------------------------------------------------------------ # Event: a note finished loading (either success or fail) # ------------------------------------------------------------ note_load_finished_listeners: [] on_note_load_finished: (listener) => @note_load_finished_listeners.push(listener) note_load_finished: (is_success, guid, error) => for l in @note_load_finished_listeners l(is_success, guid, error) # ------------------------------------------------------------ # Event: a note finished loading (either success or fail) # ------------------------------------------------------------ notebook_list_changed_listeners: [] on_notebook_list_changed: (listener) => @notebook_list_changed_listeners.push(listener) notebook_list_changed: (notebook_list) => for l in @notebook_list_changed_listeners l(notebook_list) # ------------------------------------------------------------ # Event: a note finished loading (either success or fail) # ------------------------------------------------------------ new_note_made_listeners: [] on_new_note_made: (listener) => @new_note_made_listeners.push(listener) new_note_made: () => console.log('refresh local note list due to new note made') @reload_local_note_list() for l in @new_note_made_listeners l() # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Remote Operations > # ------------------------------------------------------------ # Fetch a remote note's all info by guid and update db # # check if note is in local and is SYNCED_ALL first # return: promise containing note's info # ------------------------------------------------------------ fetch_remote_note: (guid) => console.log('fetch_remote_note(' + guid + ') begins to invoke') return @find_note_by_guid(guid).then (note) => console.log('fetch_remote_note(' + guid + ') local note: ' + JSON.stringify(note)) if note != null && note.status == @NOTE_STATUS.SYNCED_ALL console.log('Local note fetch hit: ' + JSON.stringify(note)) return note else console.log('Local note fetch missed, fetch from remote: ' + guid) return apiClient.get_note(guid).then (note) => _note = guid: guid notebook_guid: note.notebook_guid title: note.title md: note.md status: @NOTE_STATUS.SYNCED_ALL resources: note.resources return @update_note(_note) # ------------------------------------------------------------ # Load remote note list (only metadata) to update local notes info # return: promise # ------------------------------------------------------------ load_remote_notes: => # TODO handle failure return apiClient.get_all_notes().then (notes) => @_merge_remote_notes(notes).then( () => console.log('finish merging remote notes') return @get_all_notes() (error) => # TODO pass error on notifier.error('_merge_remote_notes() failed!') ) # ------------------------------------------------------------ # Load remote notebook list (only name and guid) to update local notebooks info # return: promise # ------------------------------------------------------------ load_remote_notebooks: => # TODO handle failure return apiClient.get_all_notebooks().then (notebooks) => return notebooks # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| Merge/Sync Operations > # ------------------------------------------------------------ # merge remote note list into local note list db # Possible situations: TODO # ------------------------------------------------------------ _merge_remote_notes: (notes) => guid_list = (note['guid'] for note in notes) console.log('start merging remote notes: ' + JSON.stringify(guid_list)) must_finish_promise_list = [] remote_note_guid_list = [] # Phase one: patch remote notes to local for note_meta in notes remote_note_guid_list.push(note_meta['guid']) do (note_meta) => guid = note_meta['guid'] title = note_meta['title'] notebook_guid = note_meta['notebook_guid'] console.log('Merging note [' + guid + ']') find_p = @find_note_by_guid(guid).then (note) => _find_p_must_finish_promise_list = [] if note == null console.log('About to add note ' + guid) p = @add_note_meta({ guid: guid title: title notebook_guid: notebook_guid }).then () => console.log('note ' + guid + ' metadata added!') _find_p_must_finish_promise_list.push(p) console.log('pushed to _find_p_must_finish_promise_list. TAG: A') else console.log('local note ' + guid + ' exists, updating from remote.') switch note.status when @NOTE_STATUS.NEW console.log('[IMPOSSIBLE] remote note\'s local cache is in status NEW') when @NOTE_STATUS.SYNCED_META # update note title p = @update_note({ guid: guid title: title notebook_guid: notebook_guid }) _find_p_must_finish_promise_list.push(p) console.log('pushed to _find_p_must_finish_promise_list. TAG: B') when @NOTE_STATUS.SYNCED_ALL # fetch the whole note from server and update local console.log('local note ' + guid + ' is SYNCED_ALL, about to fetch from remote for updating') @fetch_remote_note(guid).then( (note) => console.log('note ' + guid + ' (SYNCED_ALL) updated from remote') # maybe FIXME did not add to promise waiting list #_find_p_must_finish_promise_list.push(p) #console.log('pushed to _find_p_must_finish_promise_list. TAG: C') (error) => notifier.error('fetch note ' + guid + ' failed during _merge_remote_notes():' + JSON.stringify(error)) ) when @NOTE_STATUS.MODIFIED # do nothing console.log('do nothing') else notifier.error('IMPOSSIBLE: no correct note status') return Promise.all(_find_p_must_finish_promise_list) must_finish_promise_list.push(find_p) console.log('pushed to must_finish_promise_list. TAG: D') # Phase two: deleted local notes not needed # Notes that should be deleted: # not in remote and status is not new/modified p = @get_all_notes().then (notes) => for n in notes if (n.guid not in remote_note_guid_list) && n.status != @NOTE_STATUS.NEW && n.status != @NOTE_STATUS.MODIFIED _p = @delete_note(n.guid) must_finish_promise_list.push(_p) console.log('pushed to must_finish_promise_list. TAG: E') must_finish_promise_list.push(p) console.log('pushed to must_finish_promise_list. TAG: F') console.log('about to return from _merge_remote_notes(). promise list: ' + JSON.stringify(must_finish_promise_list)) console.log('check if promises in promise list is actually Promises:') for p in must_finish_promise_list if p instanceof Promise console.log('is Promise!') else console.log('is NOT Promise!!') return Promise.all(must_finish_promise_list) # ------------------------------------------------------------ # Params: # jq_div: jQuery div element for rendering # one_note_synced_func: function called whenever a note is successfully synced up # ------------------------------------------------------------ sync_up_all_notes: (jq_div) => p = @get_all_notes().then (notes) => _must_finish_promise_list = [] for note in notes guid = note.guid notebook_guid = note.notebook_guid md = note.md if note.status == @NOTE_STATUS.NEW || note.status == @NOTE_STATUS.MODIFIED is_new_note = (note.status == @NOTE_STATUS.NEW) console.log('note ' + guid + ' sent for sync up') _p = @sync_up_note(is_new_note, guid, notebook_guid, jq_div, md).then( (synced_note) => console.log('sync up note ' + guid + ' succeeded') @note_synced(true, guid, synced_note.guid, null) (error) => notifier.error('sync up note ' + guid + ' failed: ' + JSON.stringify(error)) @note_synced(false, null, null, error) ) _must_finish_promise_list.push(_p) return Promise.all(_must_finish_promise_list) return p.catch (error) => trace = printStackTrace({e: error}) notifier.error('sync_up_all_notes() failed\n' + 'Message: ' + error.message + '\nStack trace:\n' + trace.join('\n')) # ------------------------------------------------------------ # return Promise containing the synced note # ------------------------------------------------------------ sync_up_note: (is_new_note, guid, notebook_guid, jq_div, md) => console.log('enter sync_up_note() for note ' + guid) return enmlRenderer.get_enml_and_title_promise(jq_div, md).then (enml_and_title) => title = enml_and_title.title enml = enml_and_title.enml request_guid = guid if is_new_note request_guid = '' return apiClient.save_note(request_guid, notebook_guid, title, enml).then( (note) => # 1. change note status to SYNCED_ALL, using old guid _modify = guid: guid status: @NOTE_STATUS.SYNCED_ALL # 2. update notebook_guid if it is set a new one from remote if notebook_guid != note.notebook_guid _modify['notebook_guid'] = note.notebook_guid p = @update_note(_modify).then () => # 3. update guid if is new note (when saving new note, tmp guid will be updated to real one) if is_new_note new_guid = note.guid # @update_note_guid will return Promise containing the updated note return @update_note_guid(guid, new_guid) else return @find_note_by_guid(guid) return p console.log('sync_up_note(' + guid + ') succeed') (error) => # set status back notifier.error('sync_up_note() failed: \n' + JSON.stringify(error)) throw error ) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| DB Operations > # db server safe. will get db server itself get_all_notes: () => console.log('get_all_notes() invoked') return dbProvider.get_db_server_promise().then (server) => return server.notes.query().all().execute() # ------------------------------------------------------------ # make a new note to db # # db server safe. will get db server itself # return promise # ------------------------------------------------------------ make_new_note: () => console.log('make_new_note() invoking') return new Promise (resolve, reject) => guid = uuid2.newguid() + '-new' db_server_p = new Promise (resolve, reject) => # db.js does not return real Promise... _false_p = dbProvider.get_db_server_promise().then (server) => server.notes.add({ guid: guid title: 'New Note' md: 'New Note\n==\n' notebook_guid: '' status: @NOTE_STATUS.NEW }) resolve(_false_p) p = db_server_p.then( () => return @find_note_by_guid(guid) (error) => notifier.error('make_new_note() error!') ) resolve(p) # db server safe. will get db server itself delete_note: (guid) => console.log('delete_note(' + guid + ') invoked') return @find_note_by_guid(guid).then( (note) => if note is null console.log('cannot delete note null, aborted') else console.log('about to remove note id ' + note.id) p = dbProvider.get_db_server_promise().then (server) => server.notes.remove(note.id) console.log('local note ' + note.guid + ' deleted. id: ' + note.id) p.catch (error) => notifier.error('delete_note(' + guid + ') failed') (error) => notifier.error('error!') ) # ------------------------------------------------------------ # Return a copy of a note in db with a given guid # # db server safe. will get db server itself # return: promise containing the note's info, # or null if note does not exist # ------------------------------------------------------------ find_note_by_guid: (guid) => # db.js then() does not return a Promise, # need to be wrapper in a real Promise p = dbProvider.get_db_server_promise().then (server) => return new Promise (resolve, reject) => resolve(server.notes.query().filter('guid', guid).execute()) return p.then (notes) => if notes.length == 0 console.log('find_note_by_guid(' + guid + ') returned null') return null else console.log('find_note_by_guid(' + guid + ') hit') return notes[0] # ------------------------------------------------------------ # Add a note's metadata which to db # # db server safe. will get db server itself # return: promise # ------------------------------------------------------------ add_note_meta: (note) -> console.log('Adding note to db - guid: ' + note.guid + ' title: ' + note.title + ' notebook_guid: ' + note.notebook_guid) return dbProvider.get_db_server_promise().then (server) => return new Promise (resolve, reject) => resolve( server.notes.add({ guid: note.guid title: note.title notebook_guid: note.notebook_guid status: @NOTE_STATUS.SYNCED_META }) ) # ------------------------------------------------------------ # Update a note, except for its guid # # db server safe. will get db server itself # If need to update note's guid, please use update_note_guid() # # return: promise # ------------------------------------------------------------ update_note: (note) => console.log('update_note(' + note.guid + ') invoking') if note.guid? == false notifier.error('update_note(): note to be updated must have a guid!') return new Promise (resolve, reject) => reject(new Error('update_note(): note to be updated must have a guid!')) # register resource data into ImageManager if note.resources? for r in note.resources imageManager.add_image(r.uuid, r.data_url).catch (error) => notifier.error('add image failed! uuid: ' + r.uuid) console.log("register uuid: " + r.uuid + " data len: " + r.data_url.length) # update notes db p = new Promise (resolve, reject) => _note_modify = {} if note.title? _note_modify.title = note.title if note.md? _note_modify.md = note.md if note.notebook_guid? _note_modify.notebook_guid = note.notebook_guid if note.status? _note_modify.status = note.status _modify_p = dbProvider.get_db_server_promise().then (server) => return server.notes.query().filter('guid', note.guid).modify(_note_modify).execute() resolve(_modify_p) return p.then( () => console.log('update note ' + note.guid + ' successfully') return @find_note_by_guid(note.guid) (error) => notifier.error('update note ' + note.guid + ' failed!') ) # return promise containing the updated note update_note_guid: (old_guid, new_guid) => p = @find_note_by_guid(old_guid).then (note) => if note? _modify_p = dbProvider.get_db_server_promise().then (server) => _note_modify = {guid: new_guid} return server.notes.query().filter('guid', old_guid).modify(_note_modify).execute() return _modify_p else console.log('update note guid ' + old_guid + ' to new guid ' + new_guid + ' missed!') return p.then( () => console.log('update note guid ' + old_guid + ' to new guid ' + new_guid + ' succeed') # notify current note guid changed if old_guid == @current_note.guid @current_note_guid_modified(old_guid, new_guid) return @find_note_by_guid(new_guid) (error) => notifier.error('update note guid ' + old_guid + ' to new guid ' + new_guid + ' failed: ' + error) ) # ------------------------------------------------------------ # Clear db # # db server safe. will get db server itself # return: promise # ------------------------------------------------------------ clear_all_notes: () -> return dbProvider.get_db_server_promise().then (server) => server.notes.clear() # --------------------------------- tmp operations -------------------------------- ]
[ { "context": " backbone-orm.js 0.7.14\n Copyright (c) 2013-2016 Vidigami\n License: MIT (http://www.opensource.org/license", "end": 63, "score": 0.9998787045478821, "start": 55, "tag": "NAME", "value": "Vidigami" }, { "context": "ses/mit-license.php)\n Source: https://github.com/...
src/lib/queue.coffee
dk-dev/backbone-orm
54
### backbone-orm.js 0.7.14 Copyright (c) 2013-2016 Vidigami License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/vidigami/backbone-orm Dependencies: Backbone.js and Underscore.js. ### # TODO: handle double callbacks, to provide promise-like guarantees module.exports = class Queue constructor: (@parallelism) -> @parallelism or= Infinity @tasks = []; @running_count = 0; @error = null @await_callback = null defer: (callback) -> @tasks.push(callback); @_runTasks() await: (callback) -> throw new Error "Awaiting callback was added twice: #{callback}" if @await_callback @await_callback = callback @_callAwaiting() if @error or not (@tasks.length + @running_count) # @nodoc _doneTask: (err) => @running_count--; @error or= err; @_runTasks() # @nodoc _runTasks: -> return @_callAwaiting() if @error or not (@tasks.length + @running_count) while @running_count < @parallelism return unless @tasks.length current = @tasks.shift(); @running_count++ current(@_doneTask) # @nodoc _callAwaiting: -> return if @await_called or not @await_callback @await_called = true; @await_callback(@error)
151972
### backbone-orm.js 0.7.14 Copyright (c) 2013-2016 <NAME> License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/vidigami/backbone-orm Dependencies: Backbone.js and Underscore.js. ### # TODO: handle double callbacks, to provide promise-like guarantees module.exports = class Queue constructor: (@parallelism) -> @parallelism or= Infinity @tasks = []; @running_count = 0; @error = null @await_callback = null defer: (callback) -> @tasks.push(callback); @_runTasks() await: (callback) -> throw new Error "Awaiting callback was added twice: #{callback}" if @await_callback @await_callback = callback @_callAwaiting() if @error or not (@tasks.length + @running_count) # @nodoc _doneTask: (err) => @running_count--; @error or= err; @_runTasks() # @nodoc _runTasks: -> return @_callAwaiting() if @error or not (@tasks.length + @running_count) while @running_count < @parallelism return unless @tasks.length current = @tasks.shift(); @running_count++ current(@_doneTask) # @nodoc _callAwaiting: -> return if @await_called or not @await_callback @await_called = true; @await_callback(@error)
true
### backbone-orm.js 0.7.14 Copyright (c) 2013-2016 PI:NAME:<NAME>END_PI License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/vidigami/backbone-orm Dependencies: Backbone.js and Underscore.js. ### # TODO: handle double callbacks, to provide promise-like guarantees module.exports = class Queue constructor: (@parallelism) -> @parallelism or= Infinity @tasks = []; @running_count = 0; @error = null @await_callback = null defer: (callback) -> @tasks.push(callback); @_runTasks() await: (callback) -> throw new Error "Awaiting callback was added twice: #{callback}" if @await_callback @await_callback = callback @_callAwaiting() if @error or not (@tasks.length + @running_count) # @nodoc _doneTask: (err) => @running_count--; @error or= err; @_runTasks() # @nodoc _runTasks: -> return @_callAwaiting() if @error or not (@tasks.length + @running_count) while @running_count < @parallelism return unless @tasks.length current = @tasks.shift(); @running_count++ current(@_doneTask) # @nodoc _callAwaiting: -> return if @await_called or not @await_callback @await_called = true; @await_callback(@error)
[ { "context": "pedia.org/wiki/UK_railway_stations)\n#\n# Author:\n# JamieMagee\n\nmodule.exports = (robot) ->\n robot.respond /tra", "end": 487, "score": 0.9971726536750793, "start": 477, "tag": "NAME", "value": "JamieMagee" } ]
src/scripts/nationalrail.coffee
ryantomlinson/hubot-scripts
0
# Description: # Get National Rail live departure information # # Dependencies: # None # # Configuration: # HUBOT_DEFAULT_STATION - set the default from station (nearest to your home/office) # # Commands: # hubot: trains <departure station> to <arrival station> # hubot: trains <arrival station> # hubot: trains <departure station> to - lists next 5 departures # # Notes: # Use the station code (https://en.wikipedia.org/wiki/UK_railway_stations) # # Author: # JamieMagee module.exports = (robot) -> robot.respond /trains (\w{3})( (to)*(.*))*/i, (msg) -> trainFrom = if !!msg.match[4] then msg.match[1].toUpperCase() else process.env.HUBOT_DEFAULT_STATION trainTo = if !!msg.match[4] then msg.match[4].toUpperCase() else msg.match[1].toUpperCase() msg.http('http://ojp.nationalrail.co.uk/service/ldb/liveTrainsJson') .query({departing: 'true', liveTrainsFrom: trainFrom, liveTrainsTo: trainTo}) .get() (err, res, body) -> stuff = JSON.parse(body) if stuff.trains.length msg.reply "Next trains from: #{trainFrom} to #{trainTo}" for key, value of stuff.trains if key < 5 info = "#{value}".split "," if !!info[4] msg.send "The #{info[1]} to #{info[2]} at platform #{info[4]} is #{/[^;]*$/.exec(info[3])[0].trim().toLowerCase()}" else msg.send "The #{info[1]} to #{info[2]} is #{/[^;]*$/.exec(info[3])[0].trim().toLowerCase()}" else msg.send "I couldn't find trains from: #{trainFrom} to #{trainTo}. Please make sure and use station codes (https://en.wikipedia.org/wiki/UK_railway_stations)"
84181
# Description: # Get National Rail live departure information # # Dependencies: # None # # Configuration: # HUBOT_DEFAULT_STATION - set the default from station (nearest to your home/office) # # Commands: # hubot: trains <departure station> to <arrival station> # hubot: trains <arrival station> # hubot: trains <departure station> to - lists next 5 departures # # Notes: # Use the station code (https://en.wikipedia.org/wiki/UK_railway_stations) # # Author: # <NAME> module.exports = (robot) -> robot.respond /trains (\w{3})( (to)*(.*))*/i, (msg) -> trainFrom = if !!msg.match[4] then msg.match[1].toUpperCase() else process.env.HUBOT_DEFAULT_STATION trainTo = if !!msg.match[4] then msg.match[4].toUpperCase() else msg.match[1].toUpperCase() msg.http('http://ojp.nationalrail.co.uk/service/ldb/liveTrainsJson') .query({departing: 'true', liveTrainsFrom: trainFrom, liveTrainsTo: trainTo}) .get() (err, res, body) -> stuff = JSON.parse(body) if stuff.trains.length msg.reply "Next trains from: #{trainFrom} to #{trainTo}" for key, value of stuff.trains if key < 5 info = "#{value}".split "," if !!info[4] msg.send "The #{info[1]} to #{info[2]} at platform #{info[4]} is #{/[^;]*$/.exec(info[3])[0].trim().toLowerCase()}" else msg.send "The #{info[1]} to #{info[2]} is #{/[^;]*$/.exec(info[3])[0].trim().toLowerCase()}" else msg.send "I couldn't find trains from: #{trainFrom} to #{trainTo}. Please make sure and use station codes (https://en.wikipedia.org/wiki/UK_railway_stations)"
true
# Description: # Get National Rail live departure information # # Dependencies: # None # # Configuration: # HUBOT_DEFAULT_STATION - set the default from station (nearest to your home/office) # # Commands: # hubot: trains <departure station> to <arrival station> # hubot: trains <arrival station> # hubot: trains <departure station> to - lists next 5 departures # # Notes: # Use the station code (https://en.wikipedia.org/wiki/UK_railway_stations) # # Author: # PI:NAME:<NAME>END_PI module.exports = (robot) -> robot.respond /trains (\w{3})( (to)*(.*))*/i, (msg) -> trainFrom = if !!msg.match[4] then msg.match[1].toUpperCase() else process.env.HUBOT_DEFAULT_STATION trainTo = if !!msg.match[4] then msg.match[4].toUpperCase() else msg.match[1].toUpperCase() msg.http('http://ojp.nationalrail.co.uk/service/ldb/liveTrainsJson') .query({departing: 'true', liveTrainsFrom: trainFrom, liveTrainsTo: trainTo}) .get() (err, res, body) -> stuff = JSON.parse(body) if stuff.trains.length msg.reply "Next trains from: #{trainFrom} to #{trainTo}" for key, value of stuff.trains if key < 5 info = "#{value}".split "," if !!info[4] msg.send "The #{info[1]} to #{info[2]} at platform #{info[4]} is #{/[^;]*$/.exec(info[3])[0].trim().toLowerCase()}" else msg.send "The #{info[1]} to #{info[2]} is #{/[^;]*$/.exec(info[3])[0].trim().toLowerCase()}" else msg.send "I couldn't find trains from: #{trainFrom} to #{trainTo}. Please make sure and use station codes (https://en.wikipedia.org/wiki/UK_railway_stations)"
[ { "context": "offee\"\n\nclass SandwichAlly extends Spell\n name: \"Sandwich Ally\"\n @element = SandwichAlly::element = Spell::Elem", "end": 177, "score": 0.9967519640922546, "start": 164, "tag": "NAME", "value": "Sandwich Ally" }, { "context": "epends on the sandwich made.\n ...
src/character/spells/combat-skills/sandwichArtist/SandwichAlly.coffee
sadbear-/IdleLands
0
Spell = require "../../../base/Spell" SandwichBuff = require "./SandwichBuff.coffee" Cookie = require "./Cookie.coffee" class SandwichAlly extends Spell name: "Sandwich Ally" @element = SandwichAlly::element = Spell::Element.physical @tiers = SandwichAlly::tiers = [ `/** * This skill feeds an ally. As for what that means, that depends on the sandwich made. * * @name Sandwich Ally * @requirement {class} SandwichArtist * @requirement {mp} 200 * @requirement {level} 10 * @element physical * @targets {ally} 1 * @minHeal dex/5 * @minHeal dex/1.5 * @category SandwichArtist * @package Spells */` {name: "Sandwich Ally", spellPower: 1, cost: 200, class: "SandwichArtist", level: 10} ] # Cure group level healing calcDamage: -> minStat = (@caster.calc.stat 'dex')/5 maxStat = (@caster.calc.stat 'dex')/1.5 super() + @minMax minStat, maxStat determineTargets: -> @targetSomeAllies size: @chance.integer({min: 1, max: 2}) cast: (player) -> buff = @game.spellManager.modifySpell new SandwichBuff @game, @caster buff.prepareCast player @name = buff.name damage = @calcDamage() message = "%casterName made %targetName a %spellName and healed %damage HP!" @doDamageTo player, -damage, message if player isnt @caster if @chance.integer({min: 1, max: 10}) < 10 # Rate the sandwich; moderate chance of rating a 5, >50% chance of not doing so rating = @chance.integer({min: 1, max: 7}) if rating < 5 message = "%targetName rated the %spellName a #{rating}. %casterName confiscates his cookie!" @broadcast player, message cookie = @game.spellManager.modifySpell new Cookie @game, @caster cookie.prepareCast @caster else message = "%targetName rated the %spellName a 5, and gets a free cookie!" @broadcast player, message cookie = @game.spellManager.modifySpell new Cookie @game, @caster cookie.prepareCast player constructor: (@game, @caster) -> super @game, @caster @bindings = doSpellCast: @cast module.exports = exports = SandwichAlly
47863
Spell = require "../../../base/Spell" SandwichBuff = require "./SandwichBuff.coffee" Cookie = require "./Cookie.coffee" class SandwichAlly extends Spell name: "<NAME>" @element = SandwichAlly::element = Spell::Element.physical @tiers = SandwichAlly::tiers = [ `/** * This skill feeds an ally. As for what that means, that depends on the sandwich made. * * @name <NAME> * @requirement {class} SandwichArtist * @requirement {mp} 200 * @requirement {level} 10 * @element physical * @targets {ally} 1 * @minHeal dex/5 * @minHeal dex/1.5 * @category SandwichArtist * @package Spells */` {name: "<NAME>", spellPower: 1, cost: 200, class: "SandwichArtist", level: 10} ] # Cure group level healing calcDamage: -> minStat = (@caster.calc.stat 'dex')/5 maxStat = (@caster.calc.stat 'dex')/1.5 super() + @minMax minStat, maxStat determineTargets: -> @targetSomeAllies size: @chance.integer({min: 1, max: 2}) cast: (player) -> buff = @game.spellManager.modifySpell new SandwichBuff @game, @caster buff.prepareCast player @name = buff.name damage = @calcDamage() message = "%casterName made %targetName a %spellName and healed %damage HP!" @doDamageTo player, -damage, message if player isnt @caster if @chance.integer({min: 1, max: 10}) < 10 # Rate the sandwich; moderate chance of rating a 5, >50% chance of not doing so rating = @chance.integer({min: 1, max: 7}) if rating < 5 message = "%targetName rated the %spellName a #{rating}. %casterName confiscates his cookie!" @broadcast player, message cookie = @game.spellManager.modifySpell new Cookie @game, @caster cookie.prepareCast @caster else message = "%targetName rated the %spellName a 5, and gets a free cookie!" @broadcast player, message cookie = @game.spellManager.modifySpell new Cookie @game, @caster cookie.prepareCast player constructor: (@game, @caster) -> super @game, @caster @bindings = doSpellCast: @cast module.exports = exports = SandwichAlly
true
Spell = require "../../../base/Spell" SandwichBuff = require "./SandwichBuff.coffee" Cookie = require "./Cookie.coffee" class SandwichAlly extends Spell name: "PI:NAME:<NAME>END_PI" @element = SandwichAlly::element = Spell::Element.physical @tiers = SandwichAlly::tiers = [ `/** * This skill feeds an ally. As for what that means, that depends on the sandwich made. * * @name PI:NAME:<NAME>END_PI * @requirement {class} SandwichArtist * @requirement {mp} 200 * @requirement {level} 10 * @element physical * @targets {ally} 1 * @minHeal dex/5 * @minHeal dex/1.5 * @category SandwichArtist * @package Spells */` {name: "PI:NAME:<NAME>END_PI", spellPower: 1, cost: 200, class: "SandwichArtist", level: 10} ] # Cure group level healing calcDamage: -> minStat = (@caster.calc.stat 'dex')/5 maxStat = (@caster.calc.stat 'dex')/1.5 super() + @minMax minStat, maxStat determineTargets: -> @targetSomeAllies size: @chance.integer({min: 1, max: 2}) cast: (player) -> buff = @game.spellManager.modifySpell new SandwichBuff @game, @caster buff.prepareCast player @name = buff.name damage = @calcDamage() message = "%casterName made %targetName a %spellName and healed %damage HP!" @doDamageTo player, -damage, message if player isnt @caster if @chance.integer({min: 1, max: 10}) < 10 # Rate the sandwich; moderate chance of rating a 5, >50% chance of not doing so rating = @chance.integer({min: 1, max: 7}) if rating < 5 message = "%targetName rated the %spellName a #{rating}. %casterName confiscates his cookie!" @broadcast player, message cookie = @game.spellManager.modifySpell new Cookie @game, @caster cookie.prepareCast @caster else message = "%targetName rated the %spellName a 5, and gets a free cookie!" @broadcast player, message cookie = @game.spellManager.modifySpell new Cookie @game, @caster cookie.prepareCast player constructor: (@game, @caster) -> super @game, @caster @bindings = doSpellCast: @cast module.exports = exports = SandwichAlly
[ { "context": "# author Alex Robson\n# copyright appendTo, 2012\n#\n# license MIT\n# Crea", "end": 20, "score": 0.9998298287391663, "start": 9, "tag": "NAME", "value": "Alex Robson" }, { "context": "2012\n#\n# license MIT\n# Created February 2, 2012 by Alex Robson\n\namqp = require 'a...
examples/node-to-erlang/rest-api/rabbit.coffee
arobson/vorperl
1
# author Alex Robson # copyright appendTo, 2012 # # license MIT # Created February 2, 2012 by Alex Robson amqp = require 'amqp' class Rabbit constructor: (@server, onReady) -> @defaultExchangeOptions = type: "fanout" autoDelete: true @exchanges = {} @queues = {} @defaultQueueOptions = autoDelete: true console.log "Creating connection..." @connection = amqp.createConnection host: @server, port: 5672 self = @ @connection.on "ready", () -> console.log "Connection is ready" onReady(self) bind: (exchange, queue, key) -> key = if key then key else "" console.log "Binding #{queue} to #{exchange} with topic #{key}" x = @exchanges[exchange] @queues[queue].bind( x, key ) exchange: (exchange, exchangeOpts, callback) -> console.log "Creating #{exchange}" self = @ @connection.exchange exchange, exchangeOpts, (x) -> self.exchanges[exchange] = x callback(x) queue: (queue, queueOpts, callback) -> console.log "Creating #{queue}" self = @ @connection.queue queue, queueOpts, (q) -> self.queues[queue] = q callback(q) send: (exchange, key, message, messageOpts) -> x = @exchanges[exchange] key = if key then key else "" messageOpts.contentType ="application/json" console.log "sending..." #console.log "Publishing #{message} to #{exchange} on channel #{x} with options #{messageOpts}" x.publish key, message, messageOpts subscribe: (queue, handler) -> @queues[queue].subscribe handler #192.168.1.106 exports.broker = (callback) -> new Rabbit( "localhost", callback )
160483
# author <NAME> # copyright appendTo, 2012 # # license MIT # Created February 2, 2012 by <NAME> amqp = require 'amqp' class Rabbit constructor: (@server, onReady) -> @defaultExchangeOptions = type: "fanout" autoDelete: true @exchanges = {} @queues = {} @defaultQueueOptions = autoDelete: true console.log "Creating connection..." @connection = amqp.createConnection host: @server, port: 5672 self = @ @connection.on "ready", () -> console.log "Connection is ready" onReady(self) bind: (exchange, queue, key) -> key = if key then key else "" console.log "Binding #{queue} to #{exchange} with topic #{key}" x = @exchanges[exchange] @queues[queue].bind( x, key ) exchange: (exchange, exchangeOpts, callback) -> console.log "Creating #{exchange}" self = @ @connection.exchange exchange, exchangeOpts, (x) -> self.exchanges[exchange] = x callback(x) queue: (queue, queueOpts, callback) -> console.log "Creating #{queue}" self = @ @connection.queue queue, queueOpts, (q) -> self.queues[queue] = q callback(q) send: (exchange, key, message, messageOpts) -> x = @exchanges[exchange] key = if key then key else "" messageOpts.contentType ="application/json" console.log "sending..." #console.log "Publishing #{message} to #{exchange} on channel #{x} with options #{messageOpts}" x.publish key, message, messageOpts subscribe: (queue, handler) -> @queues[queue].subscribe handler #192.168.1.106 exports.broker = (callback) -> new Rabbit( "localhost", callback )
true
# author PI:NAME:<NAME>END_PI # copyright appendTo, 2012 # # license MIT # Created February 2, 2012 by PI:NAME:<NAME>END_PI amqp = require 'amqp' class Rabbit constructor: (@server, onReady) -> @defaultExchangeOptions = type: "fanout" autoDelete: true @exchanges = {} @queues = {} @defaultQueueOptions = autoDelete: true console.log "Creating connection..." @connection = amqp.createConnection host: @server, port: 5672 self = @ @connection.on "ready", () -> console.log "Connection is ready" onReady(self) bind: (exchange, queue, key) -> key = if key then key else "" console.log "Binding #{queue} to #{exchange} with topic #{key}" x = @exchanges[exchange] @queues[queue].bind( x, key ) exchange: (exchange, exchangeOpts, callback) -> console.log "Creating #{exchange}" self = @ @connection.exchange exchange, exchangeOpts, (x) -> self.exchanges[exchange] = x callback(x) queue: (queue, queueOpts, callback) -> console.log "Creating #{queue}" self = @ @connection.queue queue, queueOpts, (q) -> self.queues[queue] = q callback(q) send: (exchange, key, message, messageOpts) -> x = @exchanges[exchange] key = if key then key else "" messageOpts.contentType ="application/json" console.log "sending..." #console.log "Publishing #{message} to #{exchange} on channel #{x} with options #{messageOpts}" x.publish key, message, messageOpts subscribe: (queue, handler) -> @queues[queue].subscribe handler #192.168.1.106 exports.broker = (callback) -> new Rabbit( "localhost", callback )
[ { "context": "= require 'three'\n #\n # THREE.CSG\n # @author Chandler Prall <chandler.prall@gmail.com> http://chandler.prallf", "end": 93, "score": 0.9999006390571594, "start": 79, "tag": "NAME", "value": "Chandler Prall" }, { "context": "\n #\n # THREE.CSG\n # @author C...
src/app/core/projects/csg/csg.Three.coffee
kaosat-dev/CoffeeSCad
110
define (require) -> THREE = require 'three' # # THREE.CSG # @author Chandler Prall <chandler.prall@gmail.com> http://chandler.prallfamily.com # @modified by Mark Moissette # Wrapper for Evan Wallace's CSG library (https://github.com/evanw/csg.js/) # Provides CSG capabilities for Three.js models. # # Provided under the MIT License # THREE.CSG = toCSG: (three_model, offset, rotation) -> i = undefined geometry = undefined offset = undefined polygons = undefined vertices = undefined rotation_matrix = undefined #if ( !CSG ) { # throw 'CSG library not loaded. Please get a copy from https://github.com/evanw/csg.js'; # } if three_model instanceof THREE.Mesh geometry = three_model.geometry offset = offset or three_model.position rotation = rotation or three_model.rotation else if three_model instanceof THREE.Geometry geometry = three_model offset = offset or new THREE.Vector3(0, 0, 0) rotation = rotation or new THREE.Vector3(0, 0, 0) else throw "Model type not supported." rotation_matrix = new THREE.Matrix4().setRotationFromEuler(rotation) #console.log("geometry"); #console.log(geometry); #FIXME: changed vertices[x].position.clone( ) to vertices[x].clone( ) (as per changes in the geometry class) polygons = [] i = 0 while i < geometry.faces.length if geometry.faces[i] instanceof THREE.Face3 vertices = [] #vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].a].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].b].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].c].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].a].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].b].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].c].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) #console.log("before poly push"); polygons.push new CSG.Polygon(vertices) else if geometry.faces[i] instanceof THREE.Face4 #console.log("4 sided faces"); vertices = [] #vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].a].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].b].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].d].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # #CORRECTED , but clunky v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].a].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].b].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].d].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) polygons.push new CSG.Polygon(vertices) vertices = [] #CORRECTED , but clunky #vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].b].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].c].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].d].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].b].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].c].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].d].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) polygons.push new CSG.Polygon(vertices) else throw "Model contains unsupported face." i++ console.log "THREE.CSG toCSG done" CSG.fromPolygons polygons fromCSG: (csg_model) -> start = new Date().getTime() #need to remove duplicate vertices, keeping the right index csg_model.canonicalize() csg_model.reTesselate() three_geometry = new THREE.Geometry() polygons = csg_model.toPolygons() properties = csg_model.properties opacity = 1 rootPos = csg_model.position #csg_model.position.x,csg_model.position.y,csg_model.position.z verticesIndex= {} fetchVertexIndex = (vertex, index)=> x = vertex.pos.x - rootPos.x #offset to compensate for dual translation: one in geometry space and the other in viewspace y = vertex.pos.y - rootPos.y z = vertex.pos.z - rootPos.z key = "#{x},#{y},#{z}" if not (key of verticesIndex) threeVertex = new THREE.Vector3(vertex.pos._x,vertex.pos._y,vertex.pos._z) result = [index,threeVertex] verticesIndex[key]= result result = [index,threeVertex,false] return result else [index,v] = verticesIndex[key] return [index,v,true] vertexIndex = 0 for polygon, polygonIndex in polygons color = new THREE.Color(0xaaaaaa) try color.r = polygon.shared.color[0] color.g = polygon.shared.color[1] color.b = polygon.shared.color[2] opacity = polygon.shared.color[3] polyVertices = [] for vertex,vindex in polygon.vertices [index,v,found] = fetchVertexIndex(vertex,vertexIndex) polyVertices.push(index) if not found v = v.sub(rootPos) three_geometry.vertices.push(v) vertexIndex+=1 srcNormal = polygon.plane.normal faceNormal = new THREE.Vector3(srcNormal.x,srcNormal.z,srcNormal.y) if polygon.vertices.length == 4 i1 = polyVertices[0] i2 = polyVertices[1] i3 = polyVertices[2] i4 = polyVertices[3] face = new THREE.Face4(i1,i2,i3,i4,faceNormal) face.vertexColors[i] = color for i in [0..3] three_geometry.faces.push face three_geometry.faceVertexUvs[0].push new THREE.Vector2() else for i in [2...polyVertices.length] i1 = polyVertices[0] i2 = polyVertices[i-1] i3 = polyVertices[i] face = new THREE.Face3(i1,i2,i3,faceNormal) face.vertexColors[j] = color for j in [0...3] three_geometry.faces.push face three_geometry.faceVertexUvs[0].push new THREE.Vector2() three_geometry.computeBoundingBox() three_geometry.computeCentroids() three_geometry.computeFaceNormals(); three_geometry.computeBoundingSphere() #three_geometry.computeVertexNormals(); connectors = [] searchForConnectors = (obj)-> for index, prop of obj if (typeof prop) != "function" #console.log prop #console.log "type "+ typeof prop if prop.constructor.name is "Connector" #console.log "connector" connector = {} point = prop.point axisvector = prop.axisvector geometry = new THREE.CubeGeometry(10,10,10) geometry.basePoint = new THREE.Vector3(point.x, point.y, point.z) ### geometry = new THREE.Geometry() geometry.vertices.push(new THREE.Vector3(point.x, point.y, point.z)) end = new THREE.Vector3(point.x+axisvector.x, point.y+axisvector.y, point.z+axisvector.z) end.multiplyScalar(3) geometry.vertices.push(end) ### connectors.push(geometry) ### try if "point" of prop #console.log "haspoint" catch error ### searchForConnectors(prop) #searchForConnectors(properties) three_geometry.connectors = connectors #console.log "resulting three.geometry" #console.log three_geometry end = new Date().getTime() console.log "Conversion to three.geometry time: #{end-start}" three_geometry.tmpPos = new THREE.Vector3(csg_model.position.x,csg_model.position.y,csg_model.position.z) three_geometry.opacity = opacity three_geometry fromCSG_: (csg_model) -> #TODO: fix normals? i = undefined j = undefined vertices = undefined face = undefined three_geometry = new THREE.Geometry() start = new Date().getTime() polygons = csg_model.toPolygons() end = new Date().getTime() console.log "Csg polygon fetch time: #{end-start}" properties = csg_model.properties start = new Date().getTime() i = 0 while i < polygons.length color = new THREE.Color(0xaaaaaa) try poly = polygons[i] color.r = poly.shared.color[0] color.g = poly.shared.color[1] color.b = poly.shared.color[2] # Vertices vertices = [] j = 0 while j < polygons[i].vertices.length vertices.push @getGeometryVertice(three_geometry, polygons[i].vertices[j].pos) j++ vertices.pop() if vertices[0] is vertices[vertices.length - 1] j = 2 while j < vertices.length tmp = new THREE.Vector3().copy(polygons[i].plane.normal) b = tmp[2] tmp[2] = tmp[1] tmp[1] = b face = new THREE.Face3(vertices[0], vertices[j - 1], vertices[j], tmp) face.vertexColors[0] = color face.vertexColors[1] = color face.vertexColors[2] = color three_geometry.faces.push face three_geometry.faceVertexUvs[0].push new THREE.UV() j++ i++ end = new Date().getTime() console.log "Conversion to three.geometry time: #{end-start}" connectors = [] searchForConnectors = (obj)-> for index, prop of obj if (typeof prop) != "function" #console.log prop #console.log "type "+ typeof prop if prop.constructor.name is "Connector" #console.log "connector" connector = {} point = prop.point axisvector = prop.axisvector geometry = new THREE.CubeGeometry(10,10,10) geometry.basePoint = new THREE.Vector3(point.x, point.y, point.z) ### geometry = new THREE.Geometry() geometry.vertices.push(new THREE.Vector3(point.x, point.y, point.z)) end = new THREE.Vector3(point.x+axisvector.x, point.y+axisvector.y, point.z+axisvector.z) end.multiplyScalar(3) geometry.vertices.push(end) ### connectors.push(geometry) ### try if "point" of prop #console.log "haspoint" catch error ### searchForConnectors(prop) #searchForConnectors(properties) #three_geometry.connectors = connectors #three_geometry.computeBoundingBox() three_geometry getGeometryVertice: (geometry, vertice_position) -> i = undefined i = 0 while i < geometry.vertices.length # Vertice already exists return i if geometry.vertices[i].x is vertice_position.x and geometry.vertices[i].y is vertice_position.y and geometry.vertices[i].z is vertice_position.z i++ geometry.vertices.push new THREE.Vector3(vertice_position.x, vertice_position.y, vertice_position.z) geometry.vertices.length - 1 return THREE.CSG
76788
define (require) -> THREE = require 'three' # # THREE.CSG # @author <NAME> <<EMAIL>> http://chandler.prallfamily.com # @modified by <NAME> # Wrapper for Evan Wallace's CSG library (https://github.com/evanw/csg.js/) # Provides CSG capabilities for Three.js models. # # Provided under the MIT License # THREE.CSG = toCSG: (three_model, offset, rotation) -> i = undefined geometry = undefined offset = undefined polygons = undefined vertices = undefined rotation_matrix = undefined #if ( !CSG ) { # throw 'CSG library not loaded. Please get a copy from https://github.com/evanw/csg.js'; # } if three_model instanceof THREE.Mesh geometry = three_model.geometry offset = offset or three_model.position rotation = rotation or three_model.rotation else if three_model instanceof THREE.Geometry geometry = three_model offset = offset or new THREE.Vector3(0, 0, 0) rotation = rotation or new THREE.Vector3(0, 0, 0) else throw "Model type not supported." rotation_matrix = new THREE.Matrix4().setRotationFromEuler(rotation) #console.log("geometry"); #console.log(geometry); #FIXME: changed vertices[x].position.clone( ) to vertices[x].clone( ) (as per changes in the geometry class) polygons = [] i = 0 while i < geometry.faces.length if geometry.faces[i] instanceof THREE.Face3 vertices = [] #vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].a].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].b].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].c].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].a].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].b].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].c].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) #console.log("before poly push"); polygons.push new CSG.Polygon(vertices) else if geometry.faces[i] instanceof THREE.Face4 #console.log("4 sided faces"); vertices = [] #vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].a].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].b].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].d].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # #CORRECTED , but clunky v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].a].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].b].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].d].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) polygons.push new CSG.Polygon(vertices) vertices = [] #CORRECTED , but clunky #vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].b].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].c].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].d].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].b].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].c].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].d].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) polygons.push new CSG.Polygon(vertices) else throw "Model contains unsupported face." i++ console.log "THREE.CSG toCSG done" CSG.fromPolygons polygons fromCSG: (csg_model) -> start = new Date().getTime() #need to remove duplicate vertices, keeping the right index csg_model.canonicalize() csg_model.reTesselate() three_geometry = new THREE.Geometry() polygons = csg_model.toPolygons() properties = csg_model.properties opacity = 1 rootPos = csg_model.position #csg_model.position.x,csg_model.position.y,csg_model.position.z verticesIndex= {} fetchVertexIndex = (vertex, index)=> x = vertex.pos.x - rootPos.x #offset to compensate for dual translation: one in geometry space and the other in viewspace y = vertex.pos.y - rootPos.y z = vertex.pos.z - rootPos.z key = <KEY> if not (key of verticesIndex) threeVertex = new THREE.Vector3(vertex.pos._x,vertex.pos._y,vertex.pos._z) result = [index,threeVertex] verticesIndex[key]= result result = [index,threeVertex,false] return result else [index,v] = verticesIndex[key] return [index,v,true] vertexIndex = 0 for polygon, polygonIndex in polygons color = new THREE.Color(0xaaaaaa) try color.r = polygon.shared.color[0] color.g = polygon.shared.color[1] color.b = polygon.shared.color[2] opacity = polygon.shared.color[3] polyVertices = [] for vertex,vindex in polygon.vertices [index,v,found] = fetchVertexIndex(vertex,vertexIndex) polyVertices.push(index) if not found v = v.sub(rootPos) three_geometry.vertices.push(v) vertexIndex+=1 srcNormal = polygon.plane.normal faceNormal = new THREE.Vector3(srcNormal.x,srcNormal.z,srcNormal.y) if polygon.vertices.length == 4 i1 = polyVertices[0] i2 = polyVertices[1] i3 = polyVertices[2] i4 = polyVertices[3] face = new THREE.Face4(i1,i2,i3,i4,faceNormal) face.vertexColors[i] = color for i in [0..3] three_geometry.faces.push face three_geometry.faceVertexUvs[0].push new THREE.Vector2() else for i in [2...polyVertices.length] i1 = polyVertices[0] i2 = polyVertices[i-1] i3 = polyVertices[i] face = new THREE.Face3(i1,i2,i3,faceNormal) face.vertexColors[j] = color for j in [0...3] three_geometry.faces.push face three_geometry.faceVertexUvs[0].push new THREE.Vector2() three_geometry.computeBoundingBox() three_geometry.computeCentroids() three_geometry.computeFaceNormals(); three_geometry.computeBoundingSphere() #three_geometry.computeVertexNormals(); connectors = [] searchForConnectors = (obj)-> for index, prop of obj if (typeof prop) != "function" #console.log prop #console.log "type "+ typeof prop if prop.constructor.name is "Connector" #console.log "connector" connector = {} point = prop.point axisvector = prop.axisvector geometry = new THREE.CubeGeometry(10,10,10) geometry.basePoint = new THREE.Vector3(point.x, point.y, point.z) ### geometry = new THREE.Geometry() geometry.vertices.push(new THREE.Vector3(point.x, point.y, point.z)) end = new THREE.Vector3(point.x+axisvector.x, point.y+axisvector.y, point.z+axisvector.z) end.multiplyScalar(3) geometry.vertices.push(end) ### connectors.push(geometry) ### try if "point" of prop #console.log "haspoint" catch error ### searchForConnectors(prop) #searchForConnectors(properties) three_geometry.connectors = connectors #console.log "resulting three.geometry" #console.log three_geometry end = new Date().getTime() console.log "Conversion to three.geometry time: #{end-start}" three_geometry.tmpPos = new THREE.Vector3(csg_model.position.x,csg_model.position.y,csg_model.position.z) three_geometry.opacity = opacity three_geometry fromCSG_: (csg_model) -> #TODO: fix normals? i = undefined j = undefined vertices = undefined face = undefined three_geometry = new THREE.Geometry() start = new Date().getTime() polygons = csg_model.toPolygons() end = new Date().getTime() console.log "Csg polygon fetch time: #{end-start}" properties = csg_model.properties start = new Date().getTime() i = 0 while i < polygons.length color = new THREE.Color(0xaaaaaa) try poly = polygons[i] color.r = poly.shared.color[0] color.g = poly.shared.color[1] color.b = poly.shared.color[2] # Vertices vertices = [] j = 0 while j < polygons[i].vertices.length vertices.push @getGeometryVertice(three_geometry, polygons[i].vertices[j].pos) j++ vertices.pop() if vertices[0] is vertices[vertices.length - 1] j = 2 while j < vertices.length tmp = new THREE.Vector3().copy(polygons[i].plane.normal) b = tmp[2] tmp[2] = tmp[1] tmp[1] = b face = new THREE.Face3(vertices[0], vertices[j - 1], vertices[j], tmp) face.vertexColors[0] = color face.vertexColors[1] = color face.vertexColors[2] = color three_geometry.faces.push face three_geometry.faceVertexUvs[0].push new THREE.UV() j++ i++ end = new Date().getTime() console.log "Conversion to three.geometry time: #{end-start}" connectors = [] searchForConnectors = (obj)-> for index, prop of obj if (typeof prop) != "function" #console.log prop #console.log "type "+ typeof prop if prop.constructor.name is "Connector" #console.log "connector" connector = {} point = prop.point axisvector = prop.axisvector geometry = new THREE.CubeGeometry(10,10,10) geometry.basePoint = new THREE.Vector3(point.x, point.y, point.z) ### geometry = new THREE.Geometry() geometry.vertices.push(new THREE.Vector3(point.x, point.y, point.z)) end = new THREE.Vector3(point.x+axisvector.x, point.y+axisvector.y, point.z+axisvector.z) end.multiplyScalar(3) geometry.vertices.push(end) ### connectors.push(geometry) ### try if "point" of prop #console.log "haspoint" catch error ### searchForConnectors(prop) #searchForConnectors(properties) #three_geometry.connectors = connectors #three_geometry.computeBoundingBox() three_geometry getGeometryVertice: (geometry, vertice_position) -> i = undefined i = 0 while i < geometry.vertices.length # Vertice already exists return i if geometry.vertices[i].x is vertice_position.x and geometry.vertices[i].y is vertice_position.y and geometry.vertices[i].z is vertice_position.z i++ geometry.vertices.push new THREE.Vector3(vertice_position.x, vertice_position.y, vertice_position.z) geometry.vertices.length - 1 return THREE.CSG
true
define (require) -> THREE = require 'three' # # THREE.CSG # @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> http://chandler.prallfamily.com # @modified by PI:NAME:<NAME>END_PI # Wrapper for Evan Wallace's CSG library (https://github.com/evanw/csg.js/) # Provides CSG capabilities for Three.js models. # # Provided under the MIT License # THREE.CSG = toCSG: (three_model, offset, rotation) -> i = undefined geometry = undefined offset = undefined polygons = undefined vertices = undefined rotation_matrix = undefined #if ( !CSG ) { # throw 'CSG library not loaded. Please get a copy from https://github.com/evanw/csg.js'; # } if three_model instanceof THREE.Mesh geometry = three_model.geometry offset = offset or three_model.position rotation = rotation or three_model.rotation else if three_model instanceof THREE.Geometry geometry = three_model offset = offset or new THREE.Vector3(0, 0, 0) rotation = rotation or new THREE.Vector3(0, 0, 0) else throw "Model type not supported." rotation_matrix = new THREE.Matrix4().setRotationFromEuler(rotation) #console.log("geometry"); #console.log(geometry); #FIXME: changed vertices[x].position.clone( ) to vertices[x].clone( ) (as per changes in the geometry class) polygons = [] i = 0 while i < geometry.faces.length if geometry.faces[i] instanceof THREE.Face3 vertices = [] #vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].a].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].b].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].c].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].a].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].b].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].c].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) #console.log("before poly push"); polygons.push new CSG.Polygon(vertices) else if geometry.faces[i] instanceof THREE.Face4 #console.log("4 sided faces"); vertices = [] #vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].a].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].b].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].d].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # #CORRECTED , but clunky v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].a].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].b].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].d].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) polygons.push new CSG.Polygon(vertices) vertices = [] #CORRECTED , but clunky #vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].b].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].c].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # vertices.push( new CSG.Vertex( rotation_matrix.multiplyVector3( geometry.vertices[geometry.faces[i].d].clone( ).addSelf( offset ) ), [ geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z ] ) ); # v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].b].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].c].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) v = rotation_matrix.multiplyVector3(geometry.vertices[geometry.faces[i].d].clone().addSelf(offset)) v_cor = new CSG.Vector3D(v.x, v.y, v.z) vertices.push new CSG.Vertex(v_cor, [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]) polygons.push new CSG.Polygon(vertices) else throw "Model contains unsupported face." i++ console.log "THREE.CSG toCSG done" CSG.fromPolygons polygons fromCSG: (csg_model) -> start = new Date().getTime() #need to remove duplicate vertices, keeping the right index csg_model.canonicalize() csg_model.reTesselate() three_geometry = new THREE.Geometry() polygons = csg_model.toPolygons() properties = csg_model.properties opacity = 1 rootPos = csg_model.position #csg_model.position.x,csg_model.position.y,csg_model.position.z verticesIndex= {} fetchVertexIndex = (vertex, index)=> x = vertex.pos.x - rootPos.x #offset to compensate for dual translation: one in geometry space and the other in viewspace y = vertex.pos.y - rootPos.y z = vertex.pos.z - rootPos.z key = PI:KEY:<KEY>END_PI if not (key of verticesIndex) threeVertex = new THREE.Vector3(vertex.pos._x,vertex.pos._y,vertex.pos._z) result = [index,threeVertex] verticesIndex[key]= result result = [index,threeVertex,false] return result else [index,v] = verticesIndex[key] return [index,v,true] vertexIndex = 0 for polygon, polygonIndex in polygons color = new THREE.Color(0xaaaaaa) try color.r = polygon.shared.color[0] color.g = polygon.shared.color[1] color.b = polygon.shared.color[2] opacity = polygon.shared.color[3] polyVertices = [] for vertex,vindex in polygon.vertices [index,v,found] = fetchVertexIndex(vertex,vertexIndex) polyVertices.push(index) if not found v = v.sub(rootPos) three_geometry.vertices.push(v) vertexIndex+=1 srcNormal = polygon.plane.normal faceNormal = new THREE.Vector3(srcNormal.x,srcNormal.z,srcNormal.y) if polygon.vertices.length == 4 i1 = polyVertices[0] i2 = polyVertices[1] i3 = polyVertices[2] i4 = polyVertices[3] face = new THREE.Face4(i1,i2,i3,i4,faceNormal) face.vertexColors[i] = color for i in [0..3] three_geometry.faces.push face three_geometry.faceVertexUvs[0].push new THREE.Vector2() else for i in [2...polyVertices.length] i1 = polyVertices[0] i2 = polyVertices[i-1] i3 = polyVertices[i] face = new THREE.Face3(i1,i2,i3,faceNormal) face.vertexColors[j] = color for j in [0...3] three_geometry.faces.push face three_geometry.faceVertexUvs[0].push new THREE.Vector2() three_geometry.computeBoundingBox() three_geometry.computeCentroids() three_geometry.computeFaceNormals(); three_geometry.computeBoundingSphere() #three_geometry.computeVertexNormals(); connectors = [] searchForConnectors = (obj)-> for index, prop of obj if (typeof prop) != "function" #console.log prop #console.log "type "+ typeof prop if prop.constructor.name is "Connector" #console.log "connector" connector = {} point = prop.point axisvector = prop.axisvector geometry = new THREE.CubeGeometry(10,10,10) geometry.basePoint = new THREE.Vector3(point.x, point.y, point.z) ### geometry = new THREE.Geometry() geometry.vertices.push(new THREE.Vector3(point.x, point.y, point.z)) end = new THREE.Vector3(point.x+axisvector.x, point.y+axisvector.y, point.z+axisvector.z) end.multiplyScalar(3) geometry.vertices.push(end) ### connectors.push(geometry) ### try if "point" of prop #console.log "haspoint" catch error ### searchForConnectors(prop) #searchForConnectors(properties) three_geometry.connectors = connectors #console.log "resulting three.geometry" #console.log three_geometry end = new Date().getTime() console.log "Conversion to three.geometry time: #{end-start}" three_geometry.tmpPos = new THREE.Vector3(csg_model.position.x,csg_model.position.y,csg_model.position.z) three_geometry.opacity = opacity three_geometry fromCSG_: (csg_model) -> #TODO: fix normals? i = undefined j = undefined vertices = undefined face = undefined three_geometry = new THREE.Geometry() start = new Date().getTime() polygons = csg_model.toPolygons() end = new Date().getTime() console.log "Csg polygon fetch time: #{end-start}" properties = csg_model.properties start = new Date().getTime() i = 0 while i < polygons.length color = new THREE.Color(0xaaaaaa) try poly = polygons[i] color.r = poly.shared.color[0] color.g = poly.shared.color[1] color.b = poly.shared.color[2] # Vertices vertices = [] j = 0 while j < polygons[i].vertices.length vertices.push @getGeometryVertice(three_geometry, polygons[i].vertices[j].pos) j++ vertices.pop() if vertices[0] is vertices[vertices.length - 1] j = 2 while j < vertices.length tmp = new THREE.Vector3().copy(polygons[i].plane.normal) b = tmp[2] tmp[2] = tmp[1] tmp[1] = b face = new THREE.Face3(vertices[0], vertices[j - 1], vertices[j], tmp) face.vertexColors[0] = color face.vertexColors[1] = color face.vertexColors[2] = color three_geometry.faces.push face three_geometry.faceVertexUvs[0].push new THREE.UV() j++ i++ end = new Date().getTime() console.log "Conversion to three.geometry time: #{end-start}" connectors = [] searchForConnectors = (obj)-> for index, prop of obj if (typeof prop) != "function" #console.log prop #console.log "type "+ typeof prop if prop.constructor.name is "Connector" #console.log "connector" connector = {} point = prop.point axisvector = prop.axisvector geometry = new THREE.CubeGeometry(10,10,10) geometry.basePoint = new THREE.Vector3(point.x, point.y, point.z) ### geometry = new THREE.Geometry() geometry.vertices.push(new THREE.Vector3(point.x, point.y, point.z)) end = new THREE.Vector3(point.x+axisvector.x, point.y+axisvector.y, point.z+axisvector.z) end.multiplyScalar(3) geometry.vertices.push(end) ### connectors.push(geometry) ### try if "point" of prop #console.log "haspoint" catch error ### searchForConnectors(prop) #searchForConnectors(properties) #three_geometry.connectors = connectors #three_geometry.computeBoundingBox() three_geometry getGeometryVertice: (geometry, vertice_position) -> i = undefined i = 0 while i < geometry.vertices.length # Vertice already exists return i if geometry.vertices[i].x is vertice_position.x and geometry.vertices[i].y is vertice_position.y and geometry.vertices[i].z is vertice_position.z i++ geometry.vertices.push new THREE.Vector3(vertice_position.x, vertice_position.y, vertice_position.z) geometry.vertices.length - 1 return THREE.CSG
[ { "context": "elect Inside Brackets\":\r\n value: \"Përzgjidh Brenda Kllapash\"\r\n \"F&ind\":\r\n value: \"&Gjeni\"\r\n submenu:\r\n", "end": 8153, "score": 0.8077368140220642, "start": 8138, "tag": "NAME", "value": "Brenda Kllapash" }, { "context": "anishme\"\r\n ...
def/sq/menu_linux.cson
erikbs/atom-i18n
76
Menu: "&File": value: "&Kartelë" submenu: "New &Window": value: "&Dritare e Re" "&New File": value: "Karte&lë e Re" "&Open File…": value: "&Hapni Kartelë…" "Open Folder…": value: "Hapni Dosje…" "Add Project Folder…": value: "Shtoni Dosje Projekti…" "Reopen Project": value: "Rihape Projektin" submenu: "Clear Project History": value: "Pastro Historik Projekti" "Reopen Last &Item": value: "Rihap &Objektin e Fundit" "&Save": value: "&Ruaje" "Save &As…": value: "Ruajeni &Si…" "Save A&ll": value: "Ruaji &Krejt" "&Close Tab": value: "&Mbylle Skedën" "Close &Pane": value: "Mbylle K&uadratin" "Clos&e Window": value: "Mbylle &Dritaren" "Quit": value: "Dil" "Close All Tabs": value: "Mbylli Krejt Skedat" "&Edit": value: "&Përpunoni" submenu: "&Undo": value: "&Zhbëje" "&Redo": value: "&Ribëje" "&Cut": value: "&Prije" "C&opy": value: "&Kopjoje" "Copy Pat&h": value: "Kopjoji Shte&gun" "&Paste": value: "&Ngjite" "Select &All": value: "Përzgjidhi &Krejt" "&Toggle Comments": value: "Sh&faqi/Fshihi Komentet" Lines: value: "Rreshta" submenu: "&Indent": value: "&Brendazi" "&Outdent": value: "&Jashtazi" "&Auto Indent": value: "Shmangie &Automatike" "Move Line &Up": value: "Ngjite Rreshtin &Sipër" "Move Line &Down": value: "Zbrite Rreshtin &Poshtë" "Du&plicate Lines": value: "Sh&umëfisho Rreshta" "D&elete Line": value: "&Fshije Rreshtin" "&Join Lines": value: "&Bashkoji Rreshtat" Columns: value: "Shtylla" submenu: "Move Selection &Left": value: "Kaloje Përzgjedhjen &Majtas" "Move Selection &Right": value: "Kaloje Përzgjedhjen &Djathtas" Text: value: "Tekst" submenu: "&Upper Case": value: "Me të &Madhe" "&Lower Case": value: "Me të &Vogël" "Delete to End of &Word": value: "Fshije deri te F&undi i Fjalës" "Delete to Previous Word Boundary": value: "Fshije deri te Kufiri i Fjalës së Mëparshme" "Delete to Next Word Boundary": value: "Fshije deri te Kufiri i Fjalës Pasuese" "&Delete Line": value: "&Fshije Rreshtin" "&Transpose": value: "Ktheji Fjalët Së &Prapthi" Folding: value: "Palosje" submenu: "&Fold": value: "&Palosi" "&Unfold": value: "&Shpalosi" "Fol&d All": value: "Pa&losi Krejt" "Unfold &All": value: "Shpalosi &Krejt" "Fold Level 1": value: "Palos Nivelin 1" "Fold Level 2": value: "Palos Nivelin 2" "Fold Level 3": value: "Palos Nivelin 3" "Fold Level 4": value: "Palos Nivelin 4" "Fold Level 5": value: "Palos Nivelin 5" "Fold Level 6": value: "Palos Nivelin 6" "Fold Level 7": value: "Palos Nivelin 7" "Fold Level 8": value: "Palos Nivelin 8" "Fold Level 9": value: "Palos Nivelin 9" "&Preferences": value: "&Parapëlqime" "Config…": value: "Formësim…" "Init Script…": value: "Programth Init…" "Keymap…": value: "Tastierë…" "Snippets…": value: "Copëza…" "Stylesheet…": value: "Fletëstil…" "Reflow Selection": value: "Reflow Selection" Bookmark: value: "Faqerojtës" submenu: "View All": value: "Shihini Krejt" "Toggle Bookmark": value: "Shfaq/Fshih Faqerojtës" "Jump to Next Bookmark": value: "Hidhu te Faqerojtësi Pasues" "Jump to Previous Bookmark": value: "Hidhu te Faqerojtësi i Mëparshëm" "Select Encoding": value: "Përzgjidhni Kodim" "Go to Line": value: "Shko te Rreshti" "Select Grammar": value: "Përzgjidhni Gramatikë" "&View": value: "&Parje" submenu: "Toggle &Full Screen": value: "Aktivizo/Çaktivizo Mënyrën Sa Krejt &Ekrani" "Toggle Menu Bar": value: "Shfaq/Fshih Shtyllë Menush" Panes: value: "Kuadrate" submenu: "Split Up": value: "Ndaje Për Sipër" "Split Down": value: "Ndaje Për Poshtë" "Split Left": value: "Ndaje Majtas" "Split Right": value: "Ndaje Djathtas" "Focus Next Pane": value: "Fokusi Te Kuadrati Pasues" "Focus Previous Pane": value: "Fokusi Te Kuadrati i Mëparshëm" "Focus Pane Above": value: "Fokusi Te Kuadrati Sipër" "Focus Pane Below": value: "Fokusi Te Kuadrati Poshtë" "Focus Pane On Left": value: "Fokusi Te Kuadrati Në të Majtë" "Focus Pane On Right": value: "Fokusi Te Kuadrati Në të Djathtë" "Close Pane": value: "Mbylle Kuadratin" Developer: value: "Zhvillues" submenu: "Open In &Dev Mode…": value: "Hapeni Nën Mënyrën &Dev…" "&Reload Window": value: "&Ringarkoje Dritaren" "Run Package &Specs": value: "Xhironi &Specifikime Pakete" "Run &Benchmarks": value: "Xhironi Prova &Bankëprove" "Toggle Developer &Tools": value: "Aktivizo/Çaktivizo &Mjete Zhvilluesi" "&Increase Font Size": value: "&Rrite Madhësinë e Shkronjave" "&Decrease Font Size": value: "&Zvogëloje Madhësinë e Shkronjave" "Re&set Font Size": value: "Ktheje Madhësinë e Shkronjave Te &Parazgjedhja" "Toggle Soft &Wrap": value: "Aktivizo/Çaktivizo &Mbështjellje të Butë" "Toggle Command Palette": value: "Aktivizo/Çaktivizo Paletë Urdhrash" # added the following menus, for "Packages"->"GitHub" "Toggle Git Tab": value: "Toggle Git Tab" "Toggle GitHub Tab": value: "Toggle GitHub Tab" "Open Reviews Tab": value: "Open Reviews Tab" # "Toggle Tree View": value: "Aktivizo/Çaktivizo Pamjen Pemë" "&Selection": value: "Për&zgjedhje" submenu: "Add Selection &Above": value: "Shtoje Përzgjedhjen &Sipër" "Add Selection &Below": value: "Shtoje Përzgjedhjen &Poshtë" "S&plit into Lines": value: "Ndaje në &Rreshta" "Single Selection": value: "Përzgjedhje Njëshe" "Select to &Top": value: "Përzgjidh nga aty e &Sipër" "Select to Botto&m": value: "Përzgjidh nga aty e &Poshtë" "Select &Line": value: "Përzgjidh &Rreshtin" "Select &Word": value: "Përzgjidh &Fjalën" "Select to Beginning of W&ord": value: "Përzgjidh nga aty e te Fillimi i Fj&alës" "Select to Beginning of L&ine": value: "Përzgjidh nga aty e te Fillimi i Rr&eshtit" "Select to First &Character of Line": value: "Përzgjidh nga aty e te She&nja e Parë e Rreshtit" "Select to End of Wor&d": value: "Përzgjidh nga aty e te F&undi i Fjalës" "Select to End of Lin&e": value: "Përzgjidh nga aty e te Fun&di i Rreshtit" "Select Inside Brackets": value: "Përzgjidh Brenda Kllapash" "F&ind": value: "&Gjeni" submenu: "Find in Buffer": value: "Gjej në Lëndën e Tanishme" "Replace in Buffer": value: "Zëvendëso në Lëndën e Tanishme" "Select Next": value: "Përzgjidh Pasuesen" "Select All": value: "Përzgjidhi Krejt" "Toggle Find in Buffer": value: "Aktivizo/Çaktivizo Gjetje në Lëndën e Tanishme" "Find in Project": value: "Gjej në Projekt" "Toggle Find in Project": value: "Aktivizo/Çaktivizo Gjetjen në Projekt" "Find All": value: "Gjeji të Tëra" "Find Next": value: "Gjej Pasuesin" "Find Previous": value: "Gjej të Mëparshmin" "Replace Next": value: "Zëvendëso Pasuesin" "Replace All": value: "Zëvendësoji Krejt" "Clear History": value: "Pastroje Historikun" "Find Buffer": value: "Gjeni <em>Buffer</em>" "Find File": value: "Gjeni Kartelë" "Find Modified File": value: "Gjeni Kartelë të Modifikuar" "&Packages": value: "&Paketa" submenu: "Bracket Matcher": value: "Bracket Matcher" submenu: "Go To Matching Bracket": value: "Go To Matching Bracket" "Select Inside Brackets": value: "Select Inside Brackets" "Remove Brackets From Selection": value: "Remove Brackets From Selection" "Close Current Tag": value: "Close Current Tag" "Remove Matching Brackets": value: "Remove Matching Brackets" "Select Matching Brackets": value: "Select Matching Brackets" "Command Palette": value: "Command Palette" submenu: "Toggle": value: "Toggle" "Dev Live Reload": value: "Dev Live Reload" submenu: "Reload All Styles": value: "Reload All Styles" "Git Diff": value: "Git Diff" submenu: "Move to Next Diff": value: "Move to Next Diff" "Move to Previous Diff": value: "Move to Previous Diff" "Toggle Diff List": value: "Toggle Diff List" "GitHub": value: "GitHub" submenu: "Toggle Git Tab": value: "Toggle Git Tab" "Toggle GitHub Tab": value: "Toggle GitHub Tab" "Open Reviews Tab": value: "Open Reviews Tab" "Keybinding Resolver": value: "Keybinding Resolver" submenu: "Toggle": value: "Toggle" "Go To Matching Bracket": value: "Go To Matching Bracket" "Markdown Preview": value: "Markdown Preview" submenu: "Toggle Preview": value: "Toggle Preview" "Toggle Break on Single Newline": value: "Toggle Break on Single Newline" "Toggle GitHub Style": value: "Toggle GitHub Style" "Open On GitHub": value: "Open On GitHub" submenu: "Blame": value: "Blame" "Branch Compare": value: "Branch Compare" "Copy URL": value: "Copy URL" "File": value: "File" "File on Master": value: "File on Master" "History": value: "History" "Issues": value: "Issues" "Pull Requests": value: "Pull Requests" "Repository": value: "Repository" "Package Generator": value: "Package Generator" submenu: "Generate Atom Package": value: "Generate Atom Package" "Generate Atom Syntax Theme": value: "Generate Atom Syntax Theme" "Settings View": value: "Settings View" submenu: "Open": value: "Open" "Show Keybindings": value: "Show Keybindings" "Install Packages/Themes": value: "Install Packages/Themes" "Update Packages/Themes": value: "Update Packages/Themes" "Manage Packages": value: "Manage Packages" "Manage Themes": value: "Manage Themes" "Snippets": value: "Snippets" submenu: "Expand": value: "Expand" "Next Stop": value: "Next Stop" "Previous Stop": value: "Previous Stop" "Available": value: "Available" "Spell Check": value: "Spell Check" submenu: "Toggle": value: "Toggle" "Styleguide": value: "Styleguide" submenu: "Show": value: "Show" "Symbols": value: "Symbols" submenu: "File Symbols": value: "File Symbols" "Project Symbols": value: "File Symbols" "Timecop": value: "Timecop" submenu: "Show": value: "Show" "Tree View": value: "Tree View" submenu: "Focus": value: "Focus" "Toggle": value: "Toggle" "Reveal Active File": value: "Reveal Active File" "Toggle Tree Side": value: "Toggle Tree Side" "Whitespace": value: "Whitespace" submenu: "Remove Trailing Whitespace": value: "Remove Trailing Whitespace" "Save With Trailing Whitespace": value: "Save With Trailing Whitespace" "Save Without Trailing Whitespace": value: "Save Without Trailing Whitespace" "Convert Tabs To Spaces": value: "Convert Tabs To Spaces" "Convert Spaces To Tabs": value: "Convert Spaces To Tabs" "Convert All Tabs To Spaces": value: "Convert All Tabs To Spaces" "&Help": value: "&Ndihmë" submenu: "View &Terms of Use": value: "Shihni &Kushtet e Përdorimit" "View &License": value: "Shihni &Licencën" "&Documentation": value: "&Dokumentim" "Frequently Asked Questions": value: "Pyetje të Bëra Shpesh" "Community Discussions": value: "Diskutime Në Bashkësi" "Report Issue": value: "Njoftoni Një Problem" "Search Issues": value: "Kërkoni Te Problemet" "About Atom": value: "Mbi Atom-in" "Welcome Guide": value: "Turi i Mirëseardhjes"
175351
Menu: "&File": value: "&Kartelë" submenu: "New &Window": value: "&Dritare e Re" "&New File": value: "Karte&lë e Re" "&Open File…": value: "&Hapni Kartelë…" "Open Folder…": value: "Hapni Dosje…" "Add Project Folder…": value: "Shtoni Dosje Projekti…" "Reopen Project": value: "Rihape Projektin" submenu: "Clear Project History": value: "Pastro Historik Projekti" "Reopen Last &Item": value: "Rihap &Objektin e Fundit" "&Save": value: "&Ruaje" "Save &As…": value: "Ruajeni &Si…" "Save A&ll": value: "Ruaji &Krejt" "&Close Tab": value: "&Mbylle Skedën" "Close &Pane": value: "Mbylle K&uadratin" "Clos&e Window": value: "Mbylle &Dritaren" "Quit": value: "Dil" "Close All Tabs": value: "Mbylli Krejt Skedat" "&Edit": value: "&Përpunoni" submenu: "&Undo": value: "&Zhbëje" "&Redo": value: "&Ribëje" "&Cut": value: "&Prije" "C&opy": value: "&Kopjoje" "Copy Pat&h": value: "Kopjoji Shte&gun" "&Paste": value: "&Ngjite" "Select &All": value: "Përzgjidhi &Krejt" "&Toggle Comments": value: "Sh&faqi/Fshihi Komentet" Lines: value: "Rreshta" submenu: "&Indent": value: "&Brendazi" "&Outdent": value: "&Jashtazi" "&Auto Indent": value: "Shmangie &Automatike" "Move Line &Up": value: "Ngjite Rreshtin &Sipër" "Move Line &Down": value: "Zbrite Rreshtin &Poshtë" "Du&plicate Lines": value: "Sh&umëfisho Rreshta" "D&elete Line": value: "&Fshije Rreshtin" "&Join Lines": value: "&Bashkoji Rreshtat" Columns: value: "Shtylla" submenu: "Move Selection &Left": value: "Kaloje Përzgjedhjen &Majtas" "Move Selection &Right": value: "Kaloje Përzgjedhjen &Djathtas" Text: value: "Tekst" submenu: "&Upper Case": value: "Me të &Madhe" "&Lower Case": value: "Me të &Vogël" "Delete to End of &Word": value: "Fshije deri te F&undi i Fjalës" "Delete to Previous Word Boundary": value: "Fshije deri te Kufiri i Fjalës së Mëparshme" "Delete to Next Word Boundary": value: "Fshije deri te Kufiri i Fjalës Pasuese" "&Delete Line": value: "&Fshije Rreshtin" "&Transpose": value: "Ktheji Fjalët Së &Prapthi" Folding: value: "Palosje" submenu: "&Fold": value: "&Palosi" "&Unfold": value: "&Shpalosi" "Fol&d All": value: "Pa&losi Krejt" "Unfold &All": value: "Shpalosi &Krejt" "Fold Level 1": value: "Palos Nivelin 1" "Fold Level 2": value: "Palos Nivelin 2" "Fold Level 3": value: "Palos Nivelin 3" "Fold Level 4": value: "Palos Nivelin 4" "Fold Level 5": value: "Palos Nivelin 5" "Fold Level 6": value: "Palos Nivelin 6" "Fold Level 7": value: "Palos Nivelin 7" "Fold Level 8": value: "Palos Nivelin 8" "Fold Level 9": value: "Palos Nivelin 9" "&Preferences": value: "&Parapëlqime" "Config…": value: "Formësim…" "Init Script…": value: "Programth Init…" "Keymap…": value: "Tastierë…" "Snippets…": value: "Copëza…" "Stylesheet…": value: "Fletëstil…" "Reflow Selection": value: "Reflow Selection" Bookmark: value: "Faqerojtës" submenu: "View All": value: "Shihini Krejt" "Toggle Bookmark": value: "Shfaq/Fshih Faqerojtës" "Jump to Next Bookmark": value: "Hidhu te Faqerojtësi Pasues" "Jump to Previous Bookmark": value: "Hidhu te Faqerojtësi i Mëparshëm" "Select Encoding": value: "Përzgjidhni Kodim" "Go to Line": value: "Shko te Rreshti" "Select Grammar": value: "Përzgjidhni Gramatikë" "&View": value: "&Parje" submenu: "Toggle &Full Screen": value: "Aktivizo/Çaktivizo Mënyrën Sa Krejt &Ekrani" "Toggle Menu Bar": value: "Shfaq/Fshih Shtyllë Menush" Panes: value: "Kuadrate" submenu: "Split Up": value: "Ndaje Për Sipër" "Split Down": value: "Ndaje Për Poshtë" "Split Left": value: "Ndaje Majtas" "Split Right": value: "Ndaje Djathtas" "Focus Next Pane": value: "Fokusi Te Kuadrati Pasues" "Focus Previous Pane": value: "Fokusi Te Kuadrati i Mëparshëm" "Focus Pane Above": value: "Fokusi Te Kuadrati Sipër" "Focus Pane Below": value: "Fokusi Te Kuadrati Poshtë" "Focus Pane On Left": value: "Fokusi Te Kuadrati Në të Majtë" "Focus Pane On Right": value: "Fokusi Te Kuadrati Në të Djathtë" "Close Pane": value: "Mbylle Kuadratin" Developer: value: "Zhvillues" submenu: "Open In &Dev Mode…": value: "Hapeni Nën Mënyrën &Dev…" "&Reload Window": value: "&Ringarkoje Dritaren" "Run Package &Specs": value: "Xhironi &Specifikime Pakete" "Run &Benchmarks": value: "Xhironi Prova &Bankëprove" "Toggle Developer &Tools": value: "Aktivizo/Çaktivizo &Mjete Zhvilluesi" "&Increase Font Size": value: "&Rrite Madhësinë e Shkronjave" "&Decrease Font Size": value: "&Zvogëloje Madhësinë e Shkronjave" "Re&set Font Size": value: "Ktheje Madhësinë e Shkronjave Te &Parazgjedhja" "Toggle Soft &Wrap": value: "Aktivizo/Çaktivizo &Mbështjellje të Butë" "Toggle Command Palette": value: "Aktivizo/Çaktivizo Paletë Urdhrash" # added the following menus, for "Packages"->"GitHub" "Toggle Git Tab": value: "Toggle Git Tab" "Toggle GitHub Tab": value: "Toggle GitHub Tab" "Open Reviews Tab": value: "Open Reviews Tab" # "Toggle Tree View": value: "Aktivizo/Çaktivizo Pamjen Pemë" "&Selection": value: "Për&zgjedhje" submenu: "Add Selection &Above": value: "Shtoje Përzgjedhjen &Sipër" "Add Selection &Below": value: "Shtoje Përzgjedhjen &Poshtë" "S&plit into Lines": value: "Ndaje në &Rreshta" "Single Selection": value: "Përzgjedhje Njëshe" "Select to &Top": value: "Përzgjidh nga aty e &Sipër" "Select to Botto&m": value: "Përzgjidh nga aty e &Poshtë" "Select &Line": value: "Përzgjidh &Rreshtin" "Select &Word": value: "Përzgjidh &Fjalën" "Select to Beginning of W&ord": value: "Përzgjidh nga aty e te Fillimi i Fj&alës" "Select to Beginning of L&ine": value: "Përzgjidh nga aty e te Fillimi i Rr&eshtit" "Select to First &Character of Line": value: "Përzgjidh nga aty e te She&nja e Parë e Rreshtit" "Select to End of Wor&d": value: "Përzgjidh nga aty e te F&undi i Fjalës" "Select to End of Lin&e": value: "Përzgjidh nga aty e te Fun&di i Rreshtit" "Select Inside Brackets": value: "Përzgjidh <NAME>" "F&ind": value: "&Gjeni" submenu: "Find in Buffer": value: "Gjej në Lëndën e Tanishme" "Replace in Buffer": value: "Zëvendëso në Lëndën e Tanishme" "Select Next": value: "Pë<NAME>gj<NAME> Pas<NAME>" "Select All": value: "Përzgjidhi Krejt" "Toggle Find in Buffer": value: "Aktivizo/Çaktivizo Gjetje në Lëndën e Tanishme" "Find in Project": value: "Gjej në Projekt" "Toggle Find in Project": value: "Aktivizo/Çaktivizo Gjetjen në Projekt" "Find All": value: "Gjeji të Tëra" "Find Next": value: "Gjej Pasuesin" "Find Previous": value: "Gjej të Mëparshmin" "Replace Next": value: "Zëvendëso Pasuesin" "Replace All": value: "Zëvendësoji Krejt" "Clear History": value: "Pastroje Historikun" "Find Buffer": value: "Gjeni <em>Buffer</em>" "Find File": value: "Gjeni Kartelë" "Find Modified File": value: "Gjeni Kartelë të Modifikuar" "&Packages": value: "&Paketa" submenu: "Bracket Matcher": value: "Bracket Matcher" submenu: "Go To Matching Bracket": value: "Go To Matching Bracket" "Select Inside Brackets": value: "Select Inside Brackets" "Remove Brackets From Selection": value: "Remove Brackets From Selection" "Close Current Tag": value: "Close Current Tag" "Remove Matching Brackets": value: "Remove Matching Brackets" "Select Matching Brackets": value: "Select Matching Brackets" "Command Palette": value: "Command Palette" submenu: "Toggle": value: "Toggle" "Dev Live Reload": value: "Dev Live Reload" submenu: "Reload All Styles": value: "Reload All Styles" "Git Diff": value: "Git Diff" submenu: "Move to Next Diff": value: "Move to Next Diff" "Move to Previous Diff": value: "Move to Previous Diff" "Toggle Diff List": value: "Toggle Diff List" "GitHub": value: "GitHub" submenu: "Toggle Git Tab": value: "Toggle Git Tab" "Toggle GitHub Tab": value: "Toggle GitHub Tab" "Open Reviews Tab": value: "Open Reviews Tab" "Keybinding Resolver": value: "Keybinding Resolver" submenu: "Toggle": value: "Toggle" "Go To Matching Bracket": value: "Go To Matching Bracket" "Markdown Preview": value: "Markdown Preview" submenu: "Toggle Preview": value: "Toggle Preview" "Toggle Break on Single Newline": value: "Toggle Break on Single Newline" "Toggle GitHub Style": value: "Toggle GitHub Style" "Open On GitHub": value: "Open On GitHub" submenu: "Blame": value: "Blame" "Branch Compare": value: "Branch Compare" "Copy URL": value: "Copy URL" "File": value: "File" "File on Master": value: "File on Master" "History": value: "History" "Issues": value: "Issues" "Pull Requests": value: "Pull Requests" "Repository": value: "Repository" "Package Generator": value: "Package Generator" submenu: "Generate Atom Package": value: "Generate Atom Package" "Generate Atom Syntax Theme": value: "Generate Atom Syntax Theme" "Settings View": value: "Settings View" submenu: "Open": value: "Open" "Show Keybindings": value: "Show Keybindings" "Install Packages/Themes": value: "Install Packages/Themes" "Update Packages/Themes": value: "Update Packages/Themes" "Manage Packages": value: "Manage Packages" "Manage Themes": value: "Manage Themes" "Snippets": value: "Snippets" submenu: "Expand": value: "Expand" "Next Stop": value: "Next Stop" "Previous Stop": value: "Previous Stop" "Available": value: "Available" "Spell Check": value: "Spell Check" submenu: "Toggle": value: "Toggle" "Styleguide": value: "Styleguide" submenu: "Show": value: "Show" "Symbols": value: "Symbols" submenu: "File Symbols": value: "File Symbols" "Project Symbols": value: "File Symbols" "Timecop": value: "Timecop" submenu: "Show": value: "Show" "Tree View": value: "Tree View" submenu: "Focus": value: "Focus" "Toggle": value: "Toggle" "Reveal Active File": value: "Reveal Active File" "Toggle Tree Side": value: "Toggle Tree Side" "Whitespace": value: "Whitespace" submenu: "Remove Trailing Whitespace": value: "Remove Trailing Whitespace" "Save With Trailing Whitespace": value: "Save With Trailing Whitespace" "Save Without Trailing Whitespace": value: "Save Without Trailing Whitespace" "Convert Tabs To Spaces": value: "Convert Tabs To Spaces" "Convert Spaces To Tabs": value: "Convert Spaces To Tabs" "Convert All Tabs To Spaces": value: "Convert All Tabs To Spaces" "&Help": value: "&Ndihmë" submenu: "View &Terms of Use": value: "Shihni &Kushtet e Përdorimit" "View &License": value: "Shihni &Licencën" "&Documentation": value: "&Dokumentim" "Frequently Asked Questions": value: "Pyetje të Bëra Shpesh" "Community Discussions": value: "Diskutime Në Bashkësi" "Report Issue": value: "Njoftoni Një Problem" "Search Issues": value: "Kërkoni Te Problemet" "About Atom": value: "Mbi Atom-in" "Welcome Guide": value: "<NAME> Mir<NAME>"
true
Menu: "&File": value: "&Kartelë" submenu: "New &Window": value: "&Dritare e Re" "&New File": value: "Karte&lë e Re" "&Open File…": value: "&Hapni Kartelë…" "Open Folder…": value: "Hapni Dosje…" "Add Project Folder…": value: "Shtoni Dosje Projekti…" "Reopen Project": value: "Rihape Projektin" submenu: "Clear Project History": value: "Pastro Historik Projekti" "Reopen Last &Item": value: "Rihap &Objektin e Fundit" "&Save": value: "&Ruaje" "Save &As…": value: "Ruajeni &Si…" "Save A&ll": value: "Ruaji &Krejt" "&Close Tab": value: "&Mbylle Skedën" "Close &Pane": value: "Mbylle K&uadratin" "Clos&e Window": value: "Mbylle &Dritaren" "Quit": value: "Dil" "Close All Tabs": value: "Mbylli Krejt Skedat" "&Edit": value: "&Përpunoni" submenu: "&Undo": value: "&Zhbëje" "&Redo": value: "&Ribëje" "&Cut": value: "&Prije" "C&opy": value: "&Kopjoje" "Copy Pat&h": value: "Kopjoji Shte&gun" "&Paste": value: "&Ngjite" "Select &All": value: "Përzgjidhi &Krejt" "&Toggle Comments": value: "Sh&faqi/Fshihi Komentet" Lines: value: "Rreshta" submenu: "&Indent": value: "&Brendazi" "&Outdent": value: "&Jashtazi" "&Auto Indent": value: "Shmangie &Automatike" "Move Line &Up": value: "Ngjite Rreshtin &Sipër" "Move Line &Down": value: "Zbrite Rreshtin &Poshtë" "Du&plicate Lines": value: "Sh&umëfisho Rreshta" "D&elete Line": value: "&Fshije Rreshtin" "&Join Lines": value: "&Bashkoji Rreshtat" Columns: value: "Shtylla" submenu: "Move Selection &Left": value: "Kaloje Përzgjedhjen &Majtas" "Move Selection &Right": value: "Kaloje Përzgjedhjen &Djathtas" Text: value: "Tekst" submenu: "&Upper Case": value: "Me të &Madhe" "&Lower Case": value: "Me të &Vogël" "Delete to End of &Word": value: "Fshije deri te F&undi i Fjalës" "Delete to Previous Word Boundary": value: "Fshije deri te Kufiri i Fjalës së Mëparshme" "Delete to Next Word Boundary": value: "Fshije deri te Kufiri i Fjalës Pasuese" "&Delete Line": value: "&Fshije Rreshtin" "&Transpose": value: "Ktheji Fjalët Së &Prapthi" Folding: value: "Palosje" submenu: "&Fold": value: "&Palosi" "&Unfold": value: "&Shpalosi" "Fol&d All": value: "Pa&losi Krejt" "Unfold &All": value: "Shpalosi &Krejt" "Fold Level 1": value: "Palos Nivelin 1" "Fold Level 2": value: "Palos Nivelin 2" "Fold Level 3": value: "Palos Nivelin 3" "Fold Level 4": value: "Palos Nivelin 4" "Fold Level 5": value: "Palos Nivelin 5" "Fold Level 6": value: "Palos Nivelin 6" "Fold Level 7": value: "Palos Nivelin 7" "Fold Level 8": value: "Palos Nivelin 8" "Fold Level 9": value: "Palos Nivelin 9" "&Preferences": value: "&Parapëlqime" "Config…": value: "Formësim…" "Init Script…": value: "Programth Init…" "Keymap…": value: "Tastierë…" "Snippets…": value: "Copëza…" "Stylesheet…": value: "Fletëstil…" "Reflow Selection": value: "Reflow Selection" Bookmark: value: "Faqerojtës" submenu: "View All": value: "Shihini Krejt" "Toggle Bookmark": value: "Shfaq/Fshih Faqerojtës" "Jump to Next Bookmark": value: "Hidhu te Faqerojtësi Pasues" "Jump to Previous Bookmark": value: "Hidhu te Faqerojtësi i Mëparshëm" "Select Encoding": value: "Përzgjidhni Kodim" "Go to Line": value: "Shko te Rreshti" "Select Grammar": value: "Përzgjidhni Gramatikë" "&View": value: "&Parje" submenu: "Toggle &Full Screen": value: "Aktivizo/Çaktivizo Mënyrën Sa Krejt &Ekrani" "Toggle Menu Bar": value: "Shfaq/Fshih Shtyllë Menush" Panes: value: "Kuadrate" submenu: "Split Up": value: "Ndaje Për Sipër" "Split Down": value: "Ndaje Për Poshtë" "Split Left": value: "Ndaje Majtas" "Split Right": value: "Ndaje Djathtas" "Focus Next Pane": value: "Fokusi Te Kuadrati Pasues" "Focus Previous Pane": value: "Fokusi Te Kuadrati i Mëparshëm" "Focus Pane Above": value: "Fokusi Te Kuadrati Sipër" "Focus Pane Below": value: "Fokusi Te Kuadrati Poshtë" "Focus Pane On Left": value: "Fokusi Te Kuadrati Në të Majtë" "Focus Pane On Right": value: "Fokusi Te Kuadrati Në të Djathtë" "Close Pane": value: "Mbylle Kuadratin" Developer: value: "Zhvillues" submenu: "Open In &Dev Mode…": value: "Hapeni Nën Mënyrën &Dev…" "&Reload Window": value: "&Ringarkoje Dritaren" "Run Package &Specs": value: "Xhironi &Specifikime Pakete" "Run &Benchmarks": value: "Xhironi Prova &Bankëprove" "Toggle Developer &Tools": value: "Aktivizo/Çaktivizo &Mjete Zhvilluesi" "&Increase Font Size": value: "&Rrite Madhësinë e Shkronjave" "&Decrease Font Size": value: "&Zvogëloje Madhësinë e Shkronjave" "Re&set Font Size": value: "Ktheje Madhësinë e Shkronjave Te &Parazgjedhja" "Toggle Soft &Wrap": value: "Aktivizo/Çaktivizo &Mbështjellje të Butë" "Toggle Command Palette": value: "Aktivizo/Çaktivizo Paletë Urdhrash" # added the following menus, for "Packages"->"GitHub" "Toggle Git Tab": value: "Toggle Git Tab" "Toggle GitHub Tab": value: "Toggle GitHub Tab" "Open Reviews Tab": value: "Open Reviews Tab" # "Toggle Tree View": value: "Aktivizo/Çaktivizo Pamjen Pemë" "&Selection": value: "Për&zgjedhje" submenu: "Add Selection &Above": value: "Shtoje Përzgjedhjen &Sipër" "Add Selection &Below": value: "Shtoje Përzgjedhjen &Poshtë" "S&plit into Lines": value: "Ndaje në &Rreshta" "Single Selection": value: "Përzgjedhje Njëshe" "Select to &Top": value: "Përzgjidh nga aty e &Sipër" "Select to Botto&m": value: "Përzgjidh nga aty e &Poshtë" "Select &Line": value: "Përzgjidh &Rreshtin" "Select &Word": value: "Përzgjidh &Fjalën" "Select to Beginning of W&ord": value: "Përzgjidh nga aty e te Fillimi i Fj&alës" "Select to Beginning of L&ine": value: "Përzgjidh nga aty e te Fillimi i Rr&eshtit" "Select to First &Character of Line": value: "Përzgjidh nga aty e te She&nja e Parë e Rreshtit" "Select to End of Wor&d": value: "Përzgjidh nga aty e te F&undi i Fjalës" "Select to End of Lin&e": value: "Përzgjidh nga aty e te Fun&di i Rreshtit" "Select Inside Brackets": value: "Përzgjidh PI:NAME:<NAME>END_PI" "F&ind": value: "&Gjeni" submenu: "Find in Buffer": value: "Gjej në Lëndën e Tanishme" "Replace in Buffer": value: "Zëvendëso në Lëndën e Tanishme" "Select Next": value: "PëPI:NAME:<NAME>END_PIgjPI:NAME:<NAME>END_PI PasPI:NAME:<NAME>END_PI" "Select All": value: "Përzgjidhi Krejt" "Toggle Find in Buffer": value: "Aktivizo/Çaktivizo Gjetje në Lëndën e Tanishme" "Find in Project": value: "Gjej në Projekt" "Toggle Find in Project": value: "Aktivizo/Çaktivizo Gjetjen në Projekt" "Find All": value: "Gjeji të Tëra" "Find Next": value: "Gjej Pasuesin" "Find Previous": value: "Gjej të Mëparshmin" "Replace Next": value: "Zëvendëso Pasuesin" "Replace All": value: "Zëvendësoji Krejt" "Clear History": value: "Pastroje Historikun" "Find Buffer": value: "Gjeni <em>Buffer</em>" "Find File": value: "Gjeni Kartelë" "Find Modified File": value: "Gjeni Kartelë të Modifikuar" "&Packages": value: "&Paketa" submenu: "Bracket Matcher": value: "Bracket Matcher" submenu: "Go To Matching Bracket": value: "Go To Matching Bracket" "Select Inside Brackets": value: "Select Inside Brackets" "Remove Brackets From Selection": value: "Remove Brackets From Selection" "Close Current Tag": value: "Close Current Tag" "Remove Matching Brackets": value: "Remove Matching Brackets" "Select Matching Brackets": value: "Select Matching Brackets" "Command Palette": value: "Command Palette" submenu: "Toggle": value: "Toggle" "Dev Live Reload": value: "Dev Live Reload" submenu: "Reload All Styles": value: "Reload All Styles" "Git Diff": value: "Git Diff" submenu: "Move to Next Diff": value: "Move to Next Diff" "Move to Previous Diff": value: "Move to Previous Diff" "Toggle Diff List": value: "Toggle Diff List" "GitHub": value: "GitHub" submenu: "Toggle Git Tab": value: "Toggle Git Tab" "Toggle GitHub Tab": value: "Toggle GitHub Tab" "Open Reviews Tab": value: "Open Reviews Tab" "Keybinding Resolver": value: "Keybinding Resolver" submenu: "Toggle": value: "Toggle" "Go To Matching Bracket": value: "Go To Matching Bracket" "Markdown Preview": value: "Markdown Preview" submenu: "Toggle Preview": value: "Toggle Preview" "Toggle Break on Single Newline": value: "Toggle Break on Single Newline" "Toggle GitHub Style": value: "Toggle GitHub Style" "Open On GitHub": value: "Open On GitHub" submenu: "Blame": value: "Blame" "Branch Compare": value: "Branch Compare" "Copy URL": value: "Copy URL" "File": value: "File" "File on Master": value: "File on Master" "History": value: "History" "Issues": value: "Issues" "Pull Requests": value: "Pull Requests" "Repository": value: "Repository" "Package Generator": value: "Package Generator" submenu: "Generate Atom Package": value: "Generate Atom Package" "Generate Atom Syntax Theme": value: "Generate Atom Syntax Theme" "Settings View": value: "Settings View" submenu: "Open": value: "Open" "Show Keybindings": value: "Show Keybindings" "Install Packages/Themes": value: "Install Packages/Themes" "Update Packages/Themes": value: "Update Packages/Themes" "Manage Packages": value: "Manage Packages" "Manage Themes": value: "Manage Themes" "Snippets": value: "Snippets" submenu: "Expand": value: "Expand" "Next Stop": value: "Next Stop" "Previous Stop": value: "Previous Stop" "Available": value: "Available" "Spell Check": value: "Spell Check" submenu: "Toggle": value: "Toggle" "Styleguide": value: "Styleguide" submenu: "Show": value: "Show" "Symbols": value: "Symbols" submenu: "File Symbols": value: "File Symbols" "Project Symbols": value: "File Symbols" "Timecop": value: "Timecop" submenu: "Show": value: "Show" "Tree View": value: "Tree View" submenu: "Focus": value: "Focus" "Toggle": value: "Toggle" "Reveal Active File": value: "Reveal Active File" "Toggle Tree Side": value: "Toggle Tree Side" "Whitespace": value: "Whitespace" submenu: "Remove Trailing Whitespace": value: "Remove Trailing Whitespace" "Save With Trailing Whitespace": value: "Save With Trailing Whitespace" "Save Without Trailing Whitespace": value: "Save Without Trailing Whitespace" "Convert Tabs To Spaces": value: "Convert Tabs To Spaces" "Convert Spaces To Tabs": value: "Convert Spaces To Tabs" "Convert All Tabs To Spaces": value: "Convert All Tabs To Spaces" "&Help": value: "&Ndihmë" submenu: "View &Terms of Use": value: "Shihni &Kushtet e Përdorimit" "View &License": value: "Shihni &Licencën" "&Documentation": value: "&Dokumentim" "Frequently Asked Questions": value: "Pyetje të Bëra Shpesh" "Community Discussions": value: "Diskutime Në Bashkësi" "Report Issue": value: "Njoftoni Një Problem" "Search Issues": value: "Kërkoni Te Problemet" "About Atom": value: "Mbi Atom-in" "Welcome Guide": value: "PI:NAME:<NAME>END_PI MirPI:NAME:<NAME>END_PI"
[ { "context": "ever have events happen. In general.\n *\n * @name Sanctified\n * @prerequisite Find a sacred item\n * @effect ", "end": 144, "score": 0.8301213383674622, "start": 134, "tag": "NAME", "value": "Sanctified" } ]
src/character/personalities/Sanctified.coffee
sadbear-/IdleLands
3
Personality = require "../base/Personality" `/** * This personality makes you never have events happen. In general. * * @name Sanctified * @prerequisite Find a sacred item * @effect event probability drastically reduced * @category Personalities * @package Player */` class Sanctified extends Personality constructor: -> eventModifier: -> -10000 @canUse = (player) -> player.permanentAchievements?.hasFoundSacred @desc = "Find a sacred item" module.exports = exports = Sanctified
142416
Personality = require "../base/Personality" `/** * This personality makes you never have events happen. In general. * * @name <NAME> * @prerequisite Find a sacred item * @effect event probability drastically reduced * @category Personalities * @package Player */` class Sanctified extends Personality constructor: -> eventModifier: -> -10000 @canUse = (player) -> player.permanentAchievements?.hasFoundSacred @desc = "Find a sacred item" module.exports = exports = Sanctified
true
Personality = require "../base/Personality" `/** * This personality makes you never have events happen. In general. * * @name PI:NAME:<NAME>END_PI * @prerequisite Find a sacred item * @effect event probability drastically reduced * @category Personalities * @package Player */` class Sanctified extends Personality constructor: -> eventModifier: -> -10000 @canUse = (player) -> player.permanentAchievements?.hasFoundSacred @desc = "Find a sacred item" module.exports = exports = Sanctified
[ { "context": "e == SYSTEM_USER and\n credentials.pass == conf.COUCH_PWD\n )\n req.session or= {}\n req", "end": 411, "score": 0.9611752033233643, "start": 397, "tag": "PASSWORD", "value": "conf.COUCH_PWD" } ]
src/middleware.coffee
cfpb/panthean-helpers
1
basic_auth = require('basic-auth') module.exports = auth: (conf) -> SYSTEM_USER = conf.COUCHDB.SYSTEM_USER (req, resp, next) -> # look for admin credentials in basic auth, and if valid, login user as admin. credentials = basic_auth(req) if conf.DEV or ( credentials and credentials.name == SYSTEM_USER and credentials.pass == conf.COUCH_PWD ) req.session or= {} req.session.user = SYSTEM_USER return next() else return resp.status(401).end(JSON.stringify({error: "unauthorized", msg: "You are not authorized."})) couch: (couch_utils) -> (req, resp, next) -> # add to the request a couch client tied to the logged in user req.couch = couch_utils.nano_user(req.session.user) return next()
14911
basic_auth = require('basic-auth') module.exports = auth: (conf) -> SYSTEM_USER = conf.COUCHDB.SYSTEM_USER (req, resp, next) -> # look for admin credentials in basic auth, and if valid, login user as admin. credentials = basic_auth(req) if conf.DEV or ( credentials and credentials.name == SYSTEM_USER and credentials.pass == <PASSWORD> ) req.session or= {} req.session.user = SYSTEM_USER return next() else return resp.status(401).end(JSON.stringify({error: "unauthorized", msg: "You are not authorized."})) couch: (couch_utils) -> (req, resp, next) -> # add to the request a couch client tied to the logged in user req.couch = couch_utils.nano_user(req.session.user) return next()
true
basic_auth = require('basic-auth') module.exports = auth: (conf) -> SYSTEM_USER = conf.COUCHDB.SYSTEM_USER (req, resp, next) -> # look for admin credentials in basic auth, and if valid, login user as admin. credentials = basic_auth(req) if conf.DEV or ( credentials and credentials.name == SYSTEM_USER and credentials.pass == PI:PASSWORD:<PASSWORD>END_PI ) req.session or= {} req.session.user = SYSTEM_USER return next() else return resp.status(401).end(JSON.stringify({error: "unauthorized", msg: "You are not authorized."})) couch: (couch_utils) -> (req, resp, next) -> # add to the request a couch client tied to the logged in user req.couch = couch_utils.nano_user(req.session.user) return next()
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999103546142578, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/react/profile-page/cover-selection.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import * as React from 'react' import { button, span } from 'react-dom-factories' bn = 'profile-cover-selection' export class CoverSelection extends React.PureComponent render: => button className: osu.classWithModifiers(bn, @props.modifiers) style: backgroundImage: osu.urlPresence(@props.thumbUrl) onClick: @onClick onMouseEnter: @onMouseEnter onMouseLeave: @onMouseLeave if @props.isSelected span className: 'profile-cover-selection__selected', span className: 'far fa-check-circle' onClick: (e) => return if !@props.url? $.publish 'user:cover:upload:state', [true] $.ajax laroute.route('account.cover'), method: 'post' data: cover_id: @props.name dataType: 'json' .always -> $.publish 'user:cover:upload:state', [false] .done (userData) -> $.publish 'user:update', userData .fail osu.emitAjaxError(e.target) onMouseEnter: => return if !@props.url? $.publish 'user:cover:set', @props.url onMouseLeave: -> $.publish 'user:cover:reset'
42607
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import * as React from 'react' import { button, span } from 'react-dom-factories' bn = 'profile-cover-selection' export class CoverSelection extends React.PureComponent render: => button className: osu.classWithModifiers(bn, @props.modifiers) style: backgroundImage: osu.urlPresence(@props.thumbUrl) onClick: @onClick onMouseEnter: @onMouseEnter onMouseLeave: @onMouseLeave if @props.isSelected span className: 'profile-cover-selection__selected', span className: 'far fa-check-circle' onClick: (e) => return if !@props.url? $.publish 'user:cover:upload:state', [true] $.ajax laroute.route('account.cover'), method: 'post' data: cover_id: @props.name dataType: 'json' .always -> $.publish 'user:cover:upload:state', [false] .done (userData) -> $.publish 'user:update', userData .fail osu.emitAjaxError(e.target) onMouseEnter: => return if !@props.url? $.publish 'user:cover:set', @props.url onMouseLeave: -> $.publish 'user:cover:reset'
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import * as React from 'react' import { button, span } from 'react-dom-factories' bn = 'profile-cover-selection' export class CoverSelection extends React.PureComponent render: => button className: osu.classWithModifiers(bn, @props.modifiers) style: backgroundImage: osu.urlPresence(@props.thumbUrl) onClick: @onClick onMouseEnter: @onMouseEnter onMouseLeave: @onMouseLeave if @props.isSelected span className: 'profile-cover-selection__selected', span className: 'far fa-check-circle' onClick: (e) => return if !@props.url? $.publish 'user:cover:upload:state', [true] $.ajax laroute.route('account.cover'), method: 'post' data: cover_id: @props.name dataType: 'json' .always -> $.publish 'user:cover:upload:state', [false] .done (userData) -> $.publish 'user:update', userData .fail osu.emitAjaxError(e.target) onMouseEnter: => return if !@props.url? $.publish 'user:cover:set', @props.url onMouseLeave: -> $.publish 'user:cover:reset'
[ { "context": "\n]\n'firstLineMatch': '^#!.*\\\\bjaeger\\\\b'\n'name': 'Jaeger'\n'repository':\n\t'hex':\n\t\t'patterns': [\n\t\t\t{\n\t\t\t\t#", "end": 105, "score": 0.75380539894104, "start": 99, "tag": "NAME", "value": "Jaeger" } ]
grammars/jaeger.cson
PsichiX/language-jaeger
2
'scopeName': 'source.jaeger' 'fileTypes': [ 'jg' ] 'firstLineMatch': '^#!.*\\bjaeger\\b' 'name': 'Jaeger' 'repository': 'hex': 'patterns': [ { # hex (integer) number 'match': '0x[a-fA-F0-9]+' 'name': 'constant.numeric.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'integer': 'patterns': [ { # integer number 'match': '-?[0-9]+' 'name': 'constant.numeric.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'float': 'patterns': [ { # float number 'match': '-?[0-9]+(\\.[0-9]+)?+' 'name': 'constant.numeric.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'string': 'patterns': [ { # string 'match': '".*?(?=")"' 'name': 'string.quoted.double.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'null': 'patterns': [ { # null 'match': '\\bnull\\b' 'name': 'constant.other.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'false': 'patterns': [ { # false 'match': '\\bfalse\\b' 'name': 'constant.other.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'true': 'patterns': [ { # true 'match': '\\btrue\\b' 'name': 'constant.other.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'variable': 'patterns': [ { # variable 'match': '\\b([_a-zA-Z][_a-zA-Z0-9]*)\\b(\\s*\\.\\s*)?' 'captures': '1': 'name': 'variable.parameter.jaeger' '2': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'field': 'patterns': [ { # field 'match': '(\\<)\\s*([_a-zA-Z][_a-zA-Z0-9]*)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s*(\\>)' 'captures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'variable.parameter.jaeger' '3': 'name': 'storage.type.jaeger' '4': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'block_comment': 'patterns': [ { # block comment 'begin': '###' 'end': '###' 'name': 'comment.block.jaeger' } ] 'line_comment': 'patterns': [ { # line comment 'match': '#.*\\n' 'name': 'comment.line.double-slash.jaeger' } ] 'code_injection': 'patterns': [ { #code injection 'begin': '~~' 'beginCaptures': '0': 'name': 'string.quoted.double.jaeger' 'end': '~~' 'endCaptures': '0': 'name': 'string.quoted.double.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': 'source.intuicio4' } ] } ] 'directive_strict': 'patterns': [ { # directive: strict 'match': '(\\/)\\s*(strict)\\s*(\\/)' 'captures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'directive_import': 'patterns': [ { # directive: use 'begin': '(\\/)\\s*(import)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#string' } ] } ] 'directive_jaegerify': 'patterns': [ { # directive: jaegerify 'begin': '(\\/)\\s*(jaegerify)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\s+(from)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s*(\\/)' 'endCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'storage.type.jaeger' '3': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } { 'match': '\\s+(as)\\s+' 'name': 'keyword.control.directive.jaeger' } { 'include': '#function_definition' } ] } ] 'directive_marshal': 'patterns': [ { # directive: marshal (assembly -> jaeger) 'begin': '(\\/)\\s*(marshal)\\s+(from)\\s+(".*?(?=")")\\s+(to)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s+(with)\\s*' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'keyword.control.directive.jaeger' '4': 'name': 'string.quoted.double.jaeger' '5': 'name': 'keyword.control.directive.jaeger' '6': 'name': 'storage.type.jaeger' '7': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } ] } { # directive: marshal (jaeger -> assembly) 'begin': '(\\/)\\s*(marshal)\\s+(from)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s+(to)\\s+(".*?(?=")")\\s+(with)\\s*' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'keyword.control.directive.jaeger' '4': 'name': 'storage.type.jaeger' '5': 'name': 'keyword.control.directive.jaeger' '6': 'name': 'string.quoted.double.jaeger' '7': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } ] } ] 'directive_start': 'patterns': [ { # directive: start 'match': '(\\/)\\s*(start)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s*(\\/)' 'captures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'entity.name.function.jaeger' '4': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'directive_attribute': 'patterns': [ { # directive: attribute 'match': '(\\/)\\s*(attribute)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s*(\\/)' 'captures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'string.quoted.double.jaeger' '4': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'directive_asm': 'patterns': [ { # directive: asm 'begin': '(\\/)\\s*(asm)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\s*(\\/)' 'endCaptures': '1': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } ] } ] 'directive_return': 'patterns': [ { # directive: return 'match': '(\\/)\\s*(return\\s+placement)\\s*\\/' 'captures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'directive_let': 'patterns': [ { # directive: let 'begin': '(\\/)\\s*(let)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } { 'include': '#field' } ] } ] 'directive_set': 'patterns': [ { # directive: set 'begin': '(\\/)\\s*(set)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'storage.variable.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } ] } ] 'directive_if': 'patterns': [ { # directive: if 'begin': '(\\/)\\s*(if)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#body' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } { 'match': '\\s+(then)\\s+' 'name': 'keyword.control.directive.jaeger' } { 'match': '\\s+(elif)\\s+' 'name': 'keyword.control.directive.jaeger' } { 'match': '\\s+(else)\\s+' 'name': 'keyword.control.directive.jaeger' } ] } ] 'directive_while': 'patterns': [ { # directive: while 'begin': '(\\/)\\s*(while)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#body' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } { 'match': '\\s+(then)\\s+' 'name': 'keyword.control.directive.jaeger' } ] } ] 'directive_yield': 'patterns': [ { 'include': '#directive_yield_value' } { 'include': '#directive_yield_void' } ] 'directive_yield_value': 'patterns': [ { # directive: yield value 'begin': '(\\/)\\s*(yield)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#variable' } ] } ] 'directive_yield_void': 'patterns': [ { # directive: yield void 'match': '(\\/)\\s*(yield)\\s*\\/' 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'structure': 'patterns': [ { # structure 'begin': '(\\{)\\s*([_a-zA-Z][_a-zA-Z0-9]*)\\b' 'beginCaptures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'storage.type.jaeger' 'end': '\\}' 'endCaptures': '0': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } { 'include': '#field' } ] } ] 'function_definition': 'patterns': [ { # function definition 'begin': '(\\[)\\s*([_a-zA-Z][_a-zA-Z0-9]*)(\\s+([_a-zA-Z][_a-zA-Z0-9]*))?\\b' 'beginCaptures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'entity.name.function.jaeger' '4': 'name': 'storage.type.jaeger' 'end': '\\]' 'endCaptures': '0': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#directive_let' } { 'include': '#directive_asm' } { 'include': '#directive_return' } { 'include': '#directive_set' } { 'include': '#directive_if' } { 'include': '#directive_while' } { 'include': '#field' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } ] } ] 'function_call': 'patterns': [ { # function call 'begin': '(\\()\\s*([_a-zA-Z][_a-zA-Z0-9]*)\\b' 'beginCaptures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'entity.name.function.jaeger' 'end': '\\)' 'endCaptures': '0': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } { 'match': '\\s+\\&\\s+' 'name': 'keyword.operator.jaeger' } { 'include': '#function_call' } ] } ] 'body': 'patterns': [ { # body 'begin': '\\[' 'beginCaptures': '0': 'name': 'keyword.operator.jaeger' 'end': '\\]' 'endCaptures': '0': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#directive_asm' } { 'include': '#directive_set' } { 'include': '#directive_if' } { 'include': '#directive_while' } { 'include': '#directive_yield' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } ] } ] 'template': 'patterns': [ { # template 'begin': '(\\[\\<)\\s*(template)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\b' 'beginCaptures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'keyword.control.template.jaeger' '3': 'name': 'storage.type.jaeger' 'end': '\\>\\]' 'endCaptures': '0': 'name': 'keyword.operator.jaeger' 'name': 'string.quoted.double.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'implement': 'patterns': [ { # implement 'match': '(\\[\\<)\\s*(implement)\\s+([_a-zA-Z][_a-zA-Z0-9]*)((\\s+[_a-zA-Z][_a-zA-Z0-9]*)+)\\b(\\>\\])' 'captures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'keyword.control.implement.jaeger' '3': 'name': 'storage.type.jaeger' '4': 'name': 'storage.type.jaeger' '6': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#directive_import' } { 'include': '#directive_jaegerify' } { 'include': '#directive_marshal' } { 'include': '#directive_start' } { 'include': '#directive_strict' } { 'include': '#directive_asm' } { 'include': '#directive_attribute' } { 'include': '#structure' } { 'include': '#function_definition' } { 'include': '#template' } { 'include': '#implement' } ]
102169
'scopeName': 'source.jaeger' 'fileTypes': [ 'jg' ] 'firstLineMatch': '^#!.*\\bjaeger\\b' 'name': '<NAME>' 'repository': 'hex': 'patterns': [ { # hex (integer) number 'match': '0x[a-fA-F0-9]+' 'name': 'constant.numeric.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'integer': 'patterns': [ { # integer number 'match': '-?[0-9]+' 'name': 'constant.numeric.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'float': 'patterns': [ { # float number 'match': '-?[0-9]+(\\.[0-9]+)?+' 'name': 'constant.numeric.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'string': 'patterns': [ { # string 'match': '".*?(?=")"' 'name': 'string.quoted.double.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'null': 'patterns': [ { # null 'match': '\\bnull\\b' 'name': 'constant.other.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'false': 'patterns': [ { # false 'match': '\\bfalse\\b' 'name': 'constant.other.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'true': 'patterns': [ { # true 'match': '\\btrue\\b' 'name': 'constant.other.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'variable': 'patterns': [ { # variable 'match': '\\b([_a-zA-Z][_a-zA-Z0-9]*)\\b(\\s*\\.\\s*)?' 'captures': '1': 'name': 'variable.parameter.jaeger' '2': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'field': 'patterns': [ { # field 'match': '(\\<)\\s*([_a-zA-Z][_a-zA-Z0-9]*)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s*(\\>)' 'captures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'variable.parameter.jaeger' '3': 'name': 'storage.type.jaeger' '4': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'block_comment': 'patterns': [ { # block comment 'begin': '###' 'end': '###' 'name': 'comment.block.jaeger' } ] 'line_comment': 'patterns': [ { # line comment 'match': '#.*\\n' 'name': 'comment.line.double-slash.jaeger' } ] 'code_injection': 'patterns': [ { #code injection 'begin': '~~' 'beginCaptures': '0': 'name': 'string.quoted.double.jaeger' 'end': '~~' 'endCaptures': '0': 'name': 'string.quoted.double.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': 'source.intuicio4' } ] } ] 'directive_strict': 'patterns': [ { # directive: strict 'match': '(\\/)\\s*(strict)\\s*(\\/)' 'captures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'directive_import': 'patterns': [ { # directive: use 'begin': '(\\/)\\s*(import)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#string' } ] } ] 'directive_jaegerify': 'patterns': [ { # directive: jaegerify 'begin': '(\\/)\\s*(jaegerify)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\s+(from)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s*(\\/)' 'endCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'storage.type.jaeger' '3': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } { 'match': '\\s+(as)\\s+' 'name': 'keyword.control.directive.jaeger' } { 'include': '#function_definition' } ] } ] 'directive_marshal': 'patterns': [ { # directive: marshal (assembly -> jaeger) 'begin': '(\\/)\\s*(marshal)\\s+(from)\\s+(".*?(?=")")\\s+(to)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s+(with)\\s*' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'keyword.control.directive.jaeger' '4': 'name': 'string.quoted.double.jaeger' '5': 'name': 'keyword.control.directive.jaeger' '6': 'name': 'storage.type.jaeger' '7': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } ] } { # directive: marshal (jaeger -> assembly) 'begin': '(\\/)\\s*(marshal)\\s+(from)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s+(to)\\s+(".*?(?=")")\\s+(with)\\s*' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'keyword.control.directive.jaeger' '4': 'name': 'storage.type.jaeger' '5': 'name': 'keyword.control.directive.jaeger' '6': 'name': 'string.quoted.double.jaeger' '7': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } ] } ] 'directive_start': 'patterns': [ { # directive: start 'match': '(\\/)\\s*(start)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s*(\\/)' 'captures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'entity.name.function.jaeger' '4': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'directive_attribute': 'patterns': [ { # directive: attribute 'match': '(\\/)\\s*(attribute)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s*(\\/)' 'captures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'string.quoted.double.jaeger' '4': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'directive_asm': 'patterns': [ { # directive: asm 'begin': '(\\/)\\s*(asm)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\s*(\\/)' 'endCaptures': '1': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } ] } ] 'directive_return': 'patterns': [ { # directive: return 'match': '(\\/)\\s*(return\\s+placement)\\s*\\/' 'captures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'directive_let': 'patterns': [ { # directive: let 'begin': '(\\/)\\s*(let)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } { 'include': '#field' } ] } ] 'directive_set': 'patterns': [ { # directive: set 'begin': '(\\/)\\s*(set)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'storage.variable.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } ] } ] 'directive_if': 'patterns': [ { # directive: if 'begin': '(\\/)\\s*(if)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#body' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } { 'match': '\\s+(then)\\s+' 'name': 'keyword.control.directive.jaeger' } { 'match': '\\s+(elif)\\s+' 'name': 'keyword.control.directive.jaeger' } { 'match': '\\s+(else)\\s+' 'name': 'keyword.control.directive.jaeger' } ] } ] 'directive_while': 'patterns': [ { # directive: while 'begin': '(\\/)\\s*(while)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#body' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } { 'match': '\\s+(then)\\s+' 'name': 'keyword.control.directive.jaeger' } ] } ] 'directive_yield': 'patterns': [ { 'include': '#directive_yield_value' } { 'include': '#directive_yield_void' } ] 'directive_yield_value': 'patterns': [ { # directive: yield value 'begin': '(\\/)\\s*(yield)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#variable' } ] } ] 'directive_yield_void': 'patterns': [ { # directive: yield void 'match': '(\\/)\\s*(yield)\\s*\\/' 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'structure': 'patterns': [ { # structure 'begin': '(\\{)\\s*([_a-zA-Z][_a-zA-Z0-9]*)\\b' 'beginCaptures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'storage.type.jaeger' 'end': '\\}' 'endCaptures': '0': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } { 'include': '#field' } ] } ] 'function_definition': 'patterns': [ { # function definition 'begin': '(\\[)\\s*([_a-zA-Z][_a-zA-Z0-9]*)(\\s+([_a-zA-Z][_a-zA-Z0-9]*))?\\b' 'beginCaptures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'entity.name.function.jaeger' '4': 'name': 'storage.type.jaeger' 'end': '\\]' 'endCaptures': '0': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#directive_let' } { 'include': '#directive_asm' } { 'include': '#directive_return' } { 'include': '#directive_set' } { 'include': '#directive_if' } { 'include': '#directive_while' } { 'include': '#field' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } ] } ] 'function_call': 'patterns': [ { # function call 'begin': '(\\()\\s*([_a-zA-Z][_a-zA-Z0-9]*)\\b' 'beginCaptures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'entity.name.function.jaeger' 'end': '\\)' 'endCaptures': '0': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } { 'match': '\\s+\\&\\s+' 'name': 'keyword.operator.jaeger' } { 'include': '#function_call' } ] } ] 'body': 'patterns': [ { # body 'begin': '\\[' 'beginCaptures': '0': 'name': 'keyword.operator.jaeger' 'end': '\\]' 'endCaptures': '0': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#directive_asm' } { 'include': '#directive_set' } { 'include': '#directive_if' } { 'include': '#directive_while' } { 'include': '#directive_yield' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } ] } ] 'template': 'patterns': [ { # template 'begin': '(\\[\\<)\\s*(template)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\b' 'beginCaptures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'keyword.control.template.jaeger' '3': 'name': 'storage.type.jaeger' 'end': '\\>\\]' 'endCaptures': '0': 'name': 'keyword.operator.jaeger' 'name': 'string.quoted.double.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'implement': 'patterns': [ { # implement 'match': '(\\[\\<)\\s*(implement)\\s+([_a-zA-Z][_a-zA-Z0-9]*)((\\s+[_a-zA-Z][_a-zA-Z0-9]*)+)\\b(\\>\\])' 'captures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'keyword.control.implement.jaeger' '3': 'name': 'storage.type.jaeger' '4': 'name': 'storage.type.jaeger' '6': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#directive_import' } { 'include': '#directive_jaegerify' } { 'include': '#directive_marshal' } { 'include': '#directive_start' } { 'include': '#directive_strict' } { 'include': '#directive_asm' } { 'include': '#directive_attribute' } { 'include': '#structure' } { 'include': '#function_definition' } { 'include': '#template' } { 'include': '#implement' } ]
true
'scopeName': 'source.jaeger' 'fileTypes': [ 'jg' ] 'firstLineMatch': '^#!.*\\bjaeger\\b' 'name': 'PI:NAME:<NAME>END_PI' 'repository': 'hex': 'patterns': [ { # hex (integer) number 'match': '0x[a-fA-F0-9]+' 'name': 'constant.numeric.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'integer': 'patterns': [ { # integer number 'match': '-?[0-9]+' 'name': 'constant.numeric.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'float': 'patterns': [ { # float number 'match': '-?[0-9]+(\\.[0-9]+)?+' 'name': 'constant.numeric.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'string': 'patterns': [ { # string 'match': '".*?(?=")"' 'name': 'string.quoted.double.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'null': 'patterns': [ { # null 'match': '\\bnull\\b' 'name': 'constant.other.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'false': 'patterns': [ { # false 'match': '\\bfalse\\b' 'name': 'constant.other.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'true': 'patterns': [ { # true 'match': '\\btrue\\b' 'name': 'constant.other.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'variable': 'patterns': [ { # variable 'match': '\\b([_a-zA-Z][_a-zA-Z0-9]*)\\b(\\s*\\.\\s*)?' 'captures': '1': 'name': 'variable.parameter.jaeger' '2': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'field': 'patterns': [ { # field 'match': '(\\<)\\s*([_a-zA-Z][_a-zA-Z0-9]*)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s*(\\>)' 'captures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'variable.parameter.jaeger' '3': 'name': 'storage.type.jaeger' '4': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'block_comment': 'patterns': [ { # block comment 'begin': '###' 'end': '###' 'name': 'comment.block.jaeger' } ] 'line_comment': 'patterns': [ { # line comment 'match': '#.*\\n' 'name': 'comment.line.double-slash.jaeger' } ] 'code_injection': 'patterns': [ { #code injection 'begin': '~~' 'beginCaptures': '0': 'name': 'string.quoted.double.jaeger' 'end': '~~' 'endCaptures': '0': 'name': 'string.quoted.double.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': 'source.intuicio4' } ] } ] 'directive_strict': 'patterns': [ { # directive: strict 'match': '(\\/)\\s*(strict)\\s*(\\/)' 'captures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'directive_import': 'patterns': [ { # directive: use 'begin': '(\\/)\\s*(import)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#string' } ] } ] 'directive_jaegerify': 'patterns': [ { # directive: jaegerify 'begin': '(\\/)\\s*(jaegerify)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\s+(from)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s*(\\/)' 'endCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'storage.type.jaeger' '3': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } { 'match': '\\s+(as)\\s+' 'name': 'keyword.control.directive.jaeger' } { 'include': '#function_definition' } ] } ] 'directive_marshal': 'patterns': [ { # directive: marshal (assembly -> jaeger) 'begin': '(\\/)\\s*(marshal)\\s+(from)\\s+(".*?(?=")")\\s+(to)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s+(with)\\s*' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'keyword.control.directive.jaeger' '4': 'name': 'string.quoted.double.jaeger' '5': 'name': 'keyword.control.directive.jaeger' '6': 'name': 'storage.type.jaeger' '7': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } ] } { # directive: marshal (jaeger -> assembly) 'begin': '(\\/)\\s*(marshal)\\s+(from)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s+(to)\\s+(".*?(?=")")\\s+(with)\\s*' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'keyword.control.directive.jaeger' '4': 'name': 'storage.type.jaeger' '5': 'name': 'keyword.control.directive.jaeger' '6': 'name': 'string.quoted.double.jaeger' '7': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } ] } ] 'directive_start': 'patterns': [ { # directive: start 'match': '(\\/)\\s*(start)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s*(\\/)' 'captures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'entity.name.function.jaeger' '4': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'directive_attribute': 'patterns': [ { # directive: attribute 'match': '(\\/)\\s*(attribute)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\s*(\\/)' 'captures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'string.quoted.double.jaeger' '4': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'directive_asm': 'patterns': [ { # directive: asm 'begin': '(\\/)\\s*(asm)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\s*(\\/)' 'endCaptures': '1': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } ] } ] 'directive_return': 'patterns': [ { # directive: return 'match': '(\\/)\\s*(return\\s+placement)\\s*\\/' 'captures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'directive_let': 'patterns': [ { # directive: let 'begin': '(\\/)\\s*(let)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } { 'include': '#field' } ] } ] 'directive_set': 'patterns': [ { # directive: set 'begin': '(\\/)\\s*(set)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' '3': 'name': 'storage.variable.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } ] } ] 'directive_if': 'patterns': [ { # directive: if 'begin': '(\\/)\\s*(if)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#body' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } { 'match': '\\s+(then)\\s+' 'name': 'keyword.control.directive.jaeger' } { 'match': '\\s+(elif)\\s+' 'name': 'keyword.control.directive.jaeger' } { 'match': '\\s+(else)\\s+' 'name': 'keyword.control.directive.jaeger' } ] } ] 'directive_while': 'patterns': [ { # directive: while 'begin': '(\\/)\\s*(while)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#body' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } { 'match': '\\s+(then)\\s+' 'name': 'keyword.control.directive.jaeger' } ] } ] 'directive_yield': 'patterns': [ { 'include': '#directive_yield_value' } { 'include': '#directive_yield_void' } ] 'directive_yield_value': 'patterns': [ { # directive: yield value 'begin': '(\\/)\\s*(yield)\\s+' 'beginCaptures': '1': 'name': 'keyword.control.directive.jaeger' '2': 'name': 'keyword.control.directive.jaeger' 'end': '\\/' 'endCaptures': '0': 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#variable' } ] } ] 'directive_yield_void': 'patterns': [ { # directive: yield void 'match': '(\\/)\\s*(yield)\\s*\\/' 'name': 'keyword.control.directive.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'structure': 'patterns': [ { # structure 'begin': '(\\{)\\s*([_a-zA-Z][_a-zA-Z0-9]*)\\b' 'beginCaptures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'storage.type.jaeger' 'end': '\\}' 'endCaptures': '0': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#code_injection' } { 'include': '#field' } ] } ] 'function_definition': 'patterns': [ { # function definition 'begin': '(\\[)\\s*([_a-zA-Z][_a-zA-Z0-9]*)(\\s+([_a-zA-Z][_a-zA-Z0-9]*))?\\b' 'beginCaptures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'entity.name.function.jaeger' '4': 'name': 'storage.type.jaeger' 'end': '\\]' 'endCaptures': '0': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#directive_let' } { 'include': '#directive_asm' } { 'include': '#directive_return' } { 'include': '#directive_set' } { 'include': '#directive_if' } { 'include': '#directive_while' } { 'include': '#field' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } ] } ] 'function_call': 'patterns': [ { # function call 'begin': '(\\()\\s*([_a-zA-Z][_a-zA-Z0-9]*)\\b' 'beginCaptures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'entity.name.function.jaeger' 'end': '\\)' 'endCaptures': '0': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } { 'match': '\\s+\\&\\s+' 'name': 'keyword.operator.jaeger' } { 'include': '#function_call' } ] } ] 'body': 'patterns': [ { # body 'begin': '\\[' 'beginCaptures': '0': 'name': 'keyword.operator.jaeger' 'end': '\\]' 'endCaptures': '0': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#directive_asm' } { 'include': '#directive_set' } { 'include': '#directive_if' } { 'include': '#directive_while' } { 'include': '#directive_yield' } { 'include': '#function_call' } { 'include': '#null' } { 'include': '#false' } { 'include': '#true' } { 'include': '#variable' } { 'include': '#hex' } { 'include': '#integer' } { 'include': '#float' } { 'include': '#string' } ] } ] 'template': 'patterns': [ { # template 'begin': '(\\[\\<)\\s*(template)\\s+([_a-zA-Z][_a-zA-Z0-9]*)\\b' 'beginCaptures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'keyword.control.template.jaeger' '3': 'name': 'storage.type.jaeger' 'end': '\\>\\]' 'endCaptures': '0': 'name': 'keyword.operator.jaeger' 'name': 'string.quoted.double.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'implement': 'patterns': [ { # implement 'match': '(\\[\\<)\\s*(implement)\\s+([_a-zA-Z][_a-zA-Z0-9]*)((\\s+[_a-zA-Z][_a-zA-Z0-9]*)+)\\b(\\>\\])' 'captures': '1': 'name': 'keyword.operator.jaeger' '2': 'name': 'keyword.control.implement.jaeger' '3': 'name': 'storage.type.jaeger' '4': 'name': 'storage.type.jaeger' '6': 'name': 'keyword.operator.jaeger' 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } ] } ] 'patterns': [ { 'include': '#block_comment' } { 'include': '#line_comment' } { 'include': '#directive_import' } { 'include': '#directive_jaegerify' } { 'include': '#directive_marshal' } { 'include': '#directive_start' } { 'include': '#directive_strict' } { 'include': '#directive_asm' } { 'include': '#directive_attribute' } { 'include': '#structure' } { 'include': '#function_definition' } { 'include': '#template' } { 'include': '#implement' } ]
[ { "context": " # Facebook passport bug, see: https://github.com/jaredhanson/passport-facebook/issues/12#issuecomment-5913711\n", "end": 644, "score": 0.9996870160102844, "start": 633, "tag": "USERNAME", "value": "jaredhanson" }, { "context": "ves#galleries-institutions'\n '/artsy.ne...
lib/routers/hardcoded_redirects.coffee
l2succes/force
0
url = require 'url' express = require 'express' router = express.Router() to = require '../to' # Want to permanently redirect a specific route or route pattern? # Put em' here: redirects = '/partners': '/galleries' '/gallery': '/galleries' '/institution': '/institutions' '/filter/artworks': '/browse' '/filter/artworks/*': '/browse' '/genes': '/categories' '/partner-application': '/apply' '/fair-application': '/apply/fair' '/fairs': 'art-fairs' '/feature/art-fairs': 'art-fairs' '/settings': '/user/edit' '/collector/edit': '/profile/edit' '/_=_': '/' # Facebook passport bug, see: https://github.com/jaredhanson/passport-facebook/issues/12#issuecomment-5913711 '/press': '/press/press-releases' '/about/press': '/press/press-releases' '/about/page/press': '/press/press-releases' '/about/page/events': '/press/in-the-media' '/about/jobs': '/jobs' '/lama': '/auction/los-angeles-modern-auctions-march-2015' # HACK: Redirect the "auction" profile to the LAMA auction '/home/featured_works': '/tag/apple/artworks' '/home/featured%20works': '/tag/apple/artworks' '/dev': '/inquiry/development' '/artist': '/artists' '/job/mobile-engineer': '/article/artsy-jobs-mobile-engineer' '/article/jesse-kedy-digital-marketing-manager-organic-growth-06-22-15': '/article/artsy-jobs-associate-director-of-organic-growth' '/feature/artsy-education': '/artsy-education' '/favorites': '/user/saves#saved-artworks' '/following/artists': '/user/saves#artists' '/following/genes': '/user/saves#categories' '/following/profiles': '/user/saves#galleries-institutions' '/artsy.net/artwork/marilyn-minter-miley': '/artwork/marilyn-minter-miley' '/article/artsy-editorial-the-year-in-art-2016': '/2016-year-in-art' for from, path of redirects router.get from, to(path) module.exports = router
30989
url = require 'url' express = require 'express' router = express.Router() to = require '../to' # Want to permanently redirect a specific route or route pattern? # Put em' here: redirects = '/partners': '/galleries' '/gallery': '/galleries' '/institution': '/institutions' '/filter/artworks': '/browse' '/filter/artworks/*': '/browse' '/genes': '/categories' '/partner-application': '/apply' '/fair-application': '/apply/fair' '/fairs': 'art-fairs' '/feature/art-fairs': 'art-fairs' '/settings': '/user/edit' '/collector/edit': '/profile/edit' '/_=_': '/' # Facebook passport bug, see: https://github.com/jaredhanson/passport-facebook/issues/12#issuecomment-5913711 '/press': '/press/press-releases' '/about/press': '/press/press-releases' '/about/page/press': '/press/press-releases' '/about/page/events': '/press/in-the-media' '/about/jobs': '/jobs' '/lama': '/auction/los-angeles-modern-auctions-march-2015' # HACK: Redirect the "auction" profile to the LAMA auction '/home/featured_works': '/tag/apple/artworks' '/home/featured%20works': '/tag/apple/artworks' '/dev': '/inquiry/development' '/artist': '/artists' '/job/mobile-engineer': '/article/artsy-jobs-mobile-engineer' '/article/jesse-kedy-digital-marketing-manager-organic-growth-06-22-15': '/article/artsy-jobs-associate-director-of-organic-growth' '/feature/artsy-education': '/artsy-education' '/favorites': '/user/saves#saved-artworks' '/following/artists': '/user/saves#artists' '/following/genes': '/user/saves#categories' '/following/profiles': '/user/saves#galleries-institutions' '/artsy.net/artwork/<NAME>-<NAME>-<NAME>': '/artwork/<NAME>-<NAME>-<NAME>' '/article/artsy-editorial-the-year-in-art-2016': '/2016-year-in-art' for from, path of redirects router.get from, to(path) module.exports = router
true
url = require 'url' express = require 'express' router = express.Router() to = require '../to' # Want to permanently redirect a specific route or route pattern? # Put em' here: redirects = '/partners': '/galleries' '/gallery': '/galleries' '/institution': '/institutions' '/filter/artworks': '/browse' '/filter/artworks/*': '/browse' '/genes': '/categories' '/partner-application': '/apply' '/fair-application': '/apply/fair' '/fairs': 'art-fairs' '/feature/art-fairs': 'art-fairs' '/settings': '/user/edit' '/collector/edit': '/profile/edit' '/_=_': '/' # Facebook passport bug, see: https://github.com/jaredhanson/passport-facebook/issues/12#issuecomment-5913711 '/press': '/press/press-releases' '/about/press': '/press/press-releases' '/about/page/press': '/press/press-releases' '/about/page/events': '/press/in-the-media' '/about/jobs': '/jobs' '/lama': '/auction/los-angeles-modern-auctions-march-2015' # HACK: Redirect the "auction" profile to the LAMA auction '/home/featured_works': '/tag/apple/artworks' '/home/featured%20works': '/tag/apple/artworks' '/dev': '/inquiry/development' '/artist': '/artists' '/job/mobile-engineer': '/article/artsy-jobs-mobile-engineer' '/article/jesse-kedy-digital-marketing-manager-organic-growth-06-22-15': '/article/artsy-jobs-associate-director-of-organic-growth' '/feature/artsy-education': '/artsy-education' '/favorites': '/user/saves#saved-artworks' '/following/artists': '/user/saves#artists' '/following/genes': '/user/saves#categories' '/following/profiles': '/user/saves#galleries-institutions' '/artsy.net/artwork/PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI': '/artwork/PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI' '/article/artsy-editorial-the-year-in-art-2016': '/2016-year-in-art' for from, path of redirects router.get from, to(path) module.exports = router
[ { "context": "{\n usernameField: 'email',\n passwordField: 'password'\n }, (email, password, done) ->\n UserModel.fi", "end": 444, "score": 0.988252580165863, "start": 436, "tag": "PASSWORD", "value": "password" } ]
src/server/passport.coffee
yournal/YournalProject
1
module.exports = ($app, $injector, UserModel) -> passport = require 'passport' passport.serializeUser (user, done) -> done null, user.id passport.deserializeUser (id, done) -> UserModel.findOne _id: id, '-salt -hashedPassword', (err, user) -> done err, user # Local strategy LocalStrategy = require('passport-local').Strategy passport.use new LocalStrategy({ usernameField: 'email', passwordField: 'password' }, (email, password, done) -> UserModel.findOne(email: email, (err, user) -> if err return done err if not user return done null, false, message: 'Unknown user.' if not user.authenticate password return done null, false, message: 'Invalid password.' return done null, user ) ) # Register passport middleware $app.use passport.initialize() $app.use passport.session() # Auth middleware $injector.register 'auth', -> (roles) -> (req, res, next) -> if !req.isAuthenticated() res.send 401, 'Unauthorized access.' else if roles? authenticated = false if typeof roles is 'object' for role in roles if role in req.user.roles authenticated = true break else if roles in req.user.roles authenticated = true if not authenticated res.send 401, 'Unauthorized access.' else next() else next() return passport
12944
module.exports = ($app, $injector, UserModel) -> passport = require 'passport' passport.serializeUser (user, done) -> done null, user.id passport.deserializeUser (id, done) -> UserModel.findOne _id: id, '-salt -hashedPassword', (err, user) -> done err, user # Local strategy LocalStrategy = require('passport-local').Strategy passport.use new LocalStrategy({ usernameField: 'email', passwordField: '<PASSWORD>' }, (email, password, done) -> UserModel.findOne(email: email, (err, user) -> if err return done err if not user return done null, false, message: 'Unknown user.' if not user.authenticate password return done null, false, message: 'Invalid password.' return done null, user ) ) # Register passport middleware $app.use passport.initialize() $app.use passport.session() # Auth middleware $injector.register 'auth', -> (roles) -> (req, res, next) -> if !req.isAuthenticated() res.send 401, 'Unauthorized access.' else if roles? authenticated = false if typeof roles is 'object' for role in roles if role in req.user.roles authenticated = true break else if roles in req.user.roles authenticated = true if not authenticated res.send 401, 'Unauthorized access.' else next() else next() return passport
true
module.exports = ($app, $injector, UserModel) -> passport = require 'passport' passport.serializeUser (user, done) -> done null, user.id passport.deserializeUser (id, done) -> UserModel.findOne _id: id, '-salt -hashedPassword', (err, user) -> done err, user # Local strategy LocalStrategy = require('passport-local').Strategy passport.use new LocalStrategy({ usernameField: 'email', passwordField: 'PI:PASSWORD:<PASSWORD>END_PI' }, (email, password, done) -> UserModel.findOne(email: email, (err, user) -> if err return done err if not user return done null, false, message: 'Unknown user.' if not user.authenticate password return done null, false, message: 'Invalid password.' return done null, user ) ) # Register passport middleware $app.use passport.initialize() $app.use passport.session() # Auth middleware $injector.register 'auth', -> (roles) -> (req, res, next) -> if !req.isAuthenticated() res.send 401, 'Unauthorized access.' else if roles? authenticated = false if typeof roles is 'object' for role in roles if role in req.user.roles authenticated = true break else if roles in req.user.roles authenticated = true if not authenticated res.send 401, 'Unauthorized access.' else next() else next() return passport
[ { "context": " input value\", ->\n key = AESCrypt.key \"toomanysecrets\"\n base64key = key.toString \"base64\"\n\n e", "end": 214, "score": 0.9830889701843262, "start": 200, "tag": "KEY", "value": "toomanysecrets" }, { "context": "tring \"base64\"\n\n expect...
test/aescrypt.coffee
nextorigin/aescrypt
1
{expect} = require "chai" AESCrypt = require "../src/aescrypt" describe "AESCrypt", -> describe "#key", -> it "should return a hash of the input value", -> key = AESCrypt.key "toomanysecrets" base64key = key.toString "base64" expect(base64key).to.equal "Kz5yjBpdHvoDXDB8IvgOR/hw21eV4veozvWZ31GTp5Y=" describe "#salt", -> it "should return a random value for as many bits as the input", -> for bytes in [4, 8, 16, 32] values = {} for i in [0..100] value = AESCrypt.salt bytes base64value = value.toString "base64" expect(value).to.have.length bytes expect(values[base64value]).to.not.exist values[base64value] = true describe "#decryptWithSalt", -> it "should decrypt the salted+encrypted input value", -> keytext = "toomanysecrets" cleardata = "we have explosive" encrypted = "nm6Ky1J/L7oBmiCont3hBzMwIf7uG9scThAakcokykg=" salt = "C/GzCUNDSjiotRNei17TfQ==" decrypted = AESCrypt.decryptWithSalt keytext, salt, encrypted expect(decrypted).to.equal cleardata it "should return null if failing to decode the salted+encrypted input value", -> keytext = "toomanysecrets" cleardata = "we have explosive" encrypted = "nm6Ky1J/L7oBmiCont3hBzMwIf7cThAakcokykg=" salt = "C/GzCUNDSjiotRNei17TfQ==" decrypted = AESCrypt.decryptWithSalt keytext, salt, encrypted expect(decrypted).to.not.exist describe "#encryptWithSalt", -> it "should return the salted+encrypted input value", -> keytext = "toomanysecrets" cleardata = "we have explosive" {encrypted, salt} = AESCrypt.encryptWithSalt keytext, cleardata expect(encrypted).to.be.a.string expect(encrypted).to.have.length 44 expect(salt).to.be.a.string expect(salt).to.have.length 24 decrypted = AESCrypt.decryptWithSalt keytext, salt, encrypted expect(decrypted).to.equal cleardata
122266
{expect} = require "chai" AESCrypt = require "../src/aescrypt" describe "AESCrypt", -> describe "#key", -> it "should return a hash of the input value", -> key = AESCrypt.key "<KEY>" base64key = key.toString "base64" expect(base64key).to.equal "<KEY> describe "#salt", -> it "should return a random value for as many bits as the input", -> for bytes in [4, 8, 16, 32] values = {} for i in [0..100] value = AESCrypt.salt bytes base64value = value.toString "base64" expect(value).to.have.length bytes expect(values[base64value]).to.not.exist values[base64value] = true describe "#decryptWithSalt", -> it "should decrypt the salted+encrypted input value", -> keytext = "<KEY>" cleardata = "we have explosive" encrypted = "<KEY> salt = "C/GzCUNDSjiotRNei17TfQ==" decrypted = AESCrypt.decryptWithSalt keytext, salt, encrypted expect(decrypted).to.equal cleardata it "should return null if failing to decode the salted+encrypted input value", -> keytext = "<KEY>" cleardata = "we have explosive" encrypted = "<KEY> salt = "C/GzCUNDSjiotRNei17TfQ==" decrypted = AESCrypt.decryptWithSalt keytext, salt, encrypted expect(decrypted).to.not.exist describe "#encryptWithSalt", -> it "should return the salted+encrypted input value", -> keytext = "<KEY>" cleardata = "we have explosive" {encrypted, salt} = AESCrypt.encryptWithSalt keytext, cleardata expect(encrypted).to.be.a.string expect(encrypted).to.have.length 44 expect(salt).to.be.a.string expect(salt).to.have.length 24 decrypted = AESCrypt.decryptWithSalt keytext, salt, encrypted expect(decrypted).to.equal cleardata
true
{expect} = require "chai" AESCrypt = require "../src/aescrypt" describe "AESCrypt", -> describe "#key", -> it "should return a hash of the input value", -> key = AESCrypt.key "PI:KEY:<KEY>END_PI" base64key = key.toString "base64" expect(base64key).to.equal "PI:KEY:<KEY>END_PI describe "#salt", -> it "should return a random value for as many bits as the input", -> for bytes in [4, 8, 16, 32] values = {} for i in [0..100] value = AESCrypt.salt bytes base64value = value.toString "base64" expect(value).to.have.length bytes expect(values[base64value]).to.not.exist values[base64value] = true describe "#decryptWithSalt", -> it "should decrypt the salted+encrypted input value", -> keytext = "PI:KEY:<KEY>END_PI" cleardata = "we have explosive" encrypted = "PI:KEY:<KEY>END_PI salt = "C/GzCUNDSjiotRNei17TfQ==" decrypted = AESCrypt.decryptWithSalt keytext, salt, encrypted expect(decrypted).to.equal cleardata it "should return null if failing to decode the salted+encrypted input value", -> keytext = "PI:KEY:<KEY>END_PI" cleardata = "we have explosive" encrypted = "PI:KEY:<KEY>END_PI salt = "C/GzCUNDSjiotRNei17TfQ==" decrypted = AESCrypt.decryptWithSalt keytext, salt, encrypted expect(decrypted).to.not.exist describe "#encryptWithSalt", -> it "should return the salted+encrypted input value", -> keytext = "PI:KEY:<KEY>END_PI" cleardata = "we have explosive" {encrypted, salt} = AESCrypt.encryptWithSalt keytext, cleardata expect(encrypted).to.be.a.string expect(encrypted).to.have.length 44 expect(salt).to.be.a.string expect(salt).to.have.length 24 decrypted = AESCrypt.decryptWithSalt keytext, salt, encrypted expect(decrypted).to.equal cleardata
[ { "context": "###\n# Copyright jtlebi.fr <admin@jtlebi.fr> and other contributors.", "end": 17, "score": 0.9441618919372559, "start": 16, "tag": "EMAIL", "value": "j" }, { "context": "###\n# Copyright jtlebi.fr <admin@jtlebi.fr> and other contributors.\n#\n# Per", "end": 25, ...
static/js/app/core/router.coffee
yadutaf/Weathermap-archive
1
### # Copyright jtlebi.fr <admin@jtlebi.fr> and other 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. ### #depends on: core ### app router ### createMapChunkRouter = (name, next) -> #if needed, link to next level ChunkRouter = if next Em.LayoutState.extend { next: next nexts: Em.LayoutState.create { viewClass: Em.View.extend {} } } else Em.LayoutState #create instance ChunkRouter.create { route: ':'+name viewClass: Em.View.extend {} enter: (stateManager, transition) -> @_super stateManager, transition chunk = stateManager.getPath 'params.'+name WM[name+'s'].wish chunk } WM.routeManager = Em.RouteManager.create { rootView: WM.main home: Em.LayoutState.create { selector: '.home' viewClass: Em.View.extend { templateName: 'home' } } map: Em.LayoutState.create { route: 'map' selector: '.map' viewClass: Em.View.extend { templateName: 'map' } #map router router: createMapChunkRouter 'group',#group level createMapChunkRouter 'map', #map level createMapChunkRouter 'date', #date level createMapChunkRouter 'time' #time level } } ### Permalink controller ### WM.permalink = Em.Object.create { groupBinding: Em.Binding.oneWay "WM.groups.value" mapBinding: Em.Binding.oneWay "WM.maps.value" dateBinding: Em.Binding.oneWay "WM.dates.value" timeBinding: Em.Binding.oneWay "WM.times.value" selectedBinding: Em.Binding.oneWay "WM.times.selected" _permalinkTimer: null _permalink: -> @_permalinkTimer = null if WM.routeManager.get('location') is null null #avoid first call else group = @get 'group' map = @get 'map' date = @get 'date' time = @get 'time' url = "map" if group url += "/"+group if map url += "/"+map if date url+= "/"+date if time url += "/"+time WM.routeManager.set 'location', url url #urls are both input and output vectors. This timeout #helps preventing url flickering. Better ideas are welcome ! permalink: (-> if @_permalinkTimer clearTimeout @_permalinkTimer @_permalinkTimer = null @_permalinkTimer = setTimeout (=> @_permalink()), 300 ).observes('group', 'map', 'date', 'time') } ### init ### $ -> #start router WM.routeManager.start()
71944
### # Copyright <EMAIL>tlebi.fr <<EMAIL>> and other 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. ### #depends on: core ### app router ### createMapChunkRouter = (name, next) -> #if needed, link to next level ChunkRouter = if next Em.LayoutState.extend { next: next nexts: Em.LayoutState.create { viewClass: Em.View.extend {} } } else Em.LayoutState #create instance ChunkRouter.create { route: ':'+name viewClass: Em.View.extend {} enter: (stateManager, transition) -> @_super stateManager, transition chunk = stateManager.getPath 'params.'+name WM[name+'s'].wish chunk } WM.routeManager = Em.RouteManager.create { rootView: WM.main home: Em.LayoutState.create { selector: '.home' viewClass: Em.View.extend { templateName: 'home' } } map: Em.LayoutState.create { route: 'map' selector: '.map' viewClass: Em.View.extend { templateName: 'map' } #map router router: createMapChunkRouter 'group',#group level createMapChunkRouter 'map', #map level createMapChunkRouter 'date', #date level createMapChunkRouter 'time' #time level } } ### Permalink controller ### WM.permalink = Em.Object.create { groupBinding: Em.Binding.oneWay "WM.groups.value" mapBinding: Em.Binding.oneWay "WM.maps.value" dateBinding: Em.Binding.oneWay "WM.dates.value" timeBinding: Em.Binding.oneWay "WM.times.value" selectedBinding: Em.Binding.oneWay "WM.times.selected" _permalinkTimer: null _permalink: -> @_permalinkTimer = null if WM.routeManager.get('location') is null null #avoid first call else group = @get 'group' map = @get 'map' date = @get 'date' time = @get 'time' url = "map" if group url += "/"+group if map url += "/"+map if date url+= "/"+date if time url += "/"+time WM.routeManager.set 'location', url url #urls are both input and output vectors. This timeout #helps preventing url flickering. Better ideas are welcome ! permalink: (-> if @_permalinkTimer clearTimeout @_permalinkTimer @_permalinkTimer = null @_permalinkTimer = setTimeout (=> @_permalink()), 300 ).observes('group', 'map', 'date', 'time') } ### init ### $ -> #start router WM.routeManager.start()
true
### # Copyright PI:EMAIL:<EMAIL>END_PItlebi.fr <PI:EMAIL:<EMAIL>END_PI> and other 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. ### #depends on: core ### app router ### createMapChunkRouter = (name, next) -> #if needed, link to next level ChunkRouter = if next Em.LayoutState.extend { next: next nexts: Em.LayoutState.create { viewClass: Em.View.extend {} } } else Em.LayoutState #create instance ChunkRouter.create { route: ':'+name viewClass: Em.View.extend {} enter: (stateManager, transition) -> @_super stateManager, transition chunk = stateManager.getPath 'params.'+name WM[name+'s'].wish chunk } WM.routeManager = Em.RouteManager.create { rootView: WM.main home: Em.LayoutState.create { selector: '.home' viewClass: Em.View.extend { templateName: 'home' } } map: Em.LayoutState.create { route: 'map' selector: '.map' viewClass: Em.View.extend { templateName: 'map' } #map router router: createMapChunkRouter 'group',#group level createMapChunkRouter 'map', #map level createMapChunkRouter 'date', #date level createMapChunkRouter 'time' #time level } } ### Permalink controller ### WM.permalink = Em.Object.create { groupBinding: Em.Binding.oneWay "WM.groups.value" mapBinding: Em.Binding.oneWay "WM.maps.value" dateBinding: Em.Binding.oneWay "WM.dates.value" timeBinding: Em.Binding.oneWay "WM.times.value" selectedBinding: Em.Binding.oneWay "WM.times.selected" _permalinkTimer: null _permalink: -> @_permalinkTimer = null if WM.routeManager.get('location') is null null #avoid first call else group = @get 'group' map = @get 'map' date = @get 'date' time = @get 'time' url = "map" if group url += "/"+group if map url += "/"+map if date url+= "/"+date if time url += "/"+time WM.routeManager.set 'location', url url #urls are both input and output vectors. This timeout #helps preventing url flickering. Better ideas are welcome ! permalink: (-> if @_permalinkTimer clearTimeout @_permalinkTimer @_permalinkTimer = null @_permalinkTimer = setTimeout (=> @_permalink()), 300 ).observes('group', 'map', 'date', 'time') } ### init ### $ -> #start router WM.routeManager.start()
[ { "context": "se.com/tutorials/ios-push-notifications\n # @author Michael Lin, Snaphappi Inc.\n###\n\nangular\n.module 'parse.push'", "end": 440, "score": 0.999489426612854, "start": 429, "tag": "NAME", "value": "Michael Lin" }, { "context": "ectId', 'deviceType', 'installationId', '...
app/js/services/push-notify.coffee
mixersoft/ionic-parse-facebook-scaffold
5
'use strict' ###* # @ngdoc service # @name parsePush # @description wrapper for pushNotification plugin, register installation with push server on PARSE # handle push notification events: adds badges, notifications to iOS notification panel # for ParseJs Push configuration details, see: # https://www.parse.com/docs/ios/guide#push-notifications # https://www.parse.com/tutorials/ios-push-notifications # @author Michael Lin, Snaphappi Inc. ### angular .module 'parse.push', [ 'ionic', 'snappi.util' 'parse.backend' 'auth' ] .factory( 'parsePush', [ '$rootScope', '$location', '$q', '$log', '$http' '$cordovaPush', '$cordovaMedia' 'notifyService' 'auth.KEYS', 'deviceReady', 'exportDebug' ($rootScope, $location, $q, $log, $http, $cordovaPush, $cordovaMedia, notify, KEYS, deviceReady, exportDebug)-> # note: serialized during self.initialize() notificationTemplate = { conditions: 'channels': # postData.where 'channels': '$in': ['channel1', 'channel2'] 'ownerId': 'ownerId': null payload: 'example': # postData.data aps: alert: title: 'Hello There' body: "This is a push notification from Parse!" badge: 1 sound: 'default' 'content-available': false target: state: 'app.home' params: null } $rootScope.$on '$cordovaPush:notificationReceived', (event, notification)-> console.log "notification received, JSON="+JSON.stringify notification $log.debug( '$cordovaPush:notificationReceived', notification ) if ionic.Platform.isAndroid() self.handleAndroid( notification ) else if ionic.Platform.isIOS() self.handleIOS( notification ) return _localStorageDevice = null self = { # check existing Parse Installation object ### # @param $localStorageDevice object, place to check for/save existing Parse installation # keys; ['objectId', 'deviceType', 'installationId', 'owner', 'username'] # NOTE: should be saved to $localStorage['device'] ### initialize: ($localStorageDevice)-> return self if deviceReady.device().isBrowser == true _localStorageDevice = $localStorageDevice self.isReady = true console.log "pushNotificationPluginSvc initialized", $localStorageDevice return self registerP: ()-> return $q.when() if deviceReady.device().isBrowser == true if !self.isReady $log.warn("WARNING: attempted to register device before plugin intialization.") return $q.reject("pushNotify plugin not initialized") return Parse._getInstallationId() .then (installationId)-> if _localStorageDevice?['pushInstall']? isOK = true isOK = isOK && $rootScope.parseUser?.id && _localStorageDevice['pushInstall'].ownerId == $rootScope.parseUser.id isOK = isOK && _localStorageDevice['pushInstall'].deviceId == deviceReady.device().id isOK = isOK && _localStorageDevice['pushInstall'].installationId == installationId if isOK console.log "pushInstall unchanged" return $q.when('Parse installation unchanged') # else # console.log "localStorage pushInstall=" + JSON.stringify _localStorageDevice['pushInstall'] # console.log "compare to:" + JSON.stringify [ $rootScope.parseUser.id, deviceReady.device().id, installationId ] else console.log "_localStorageDevice['pushInstall'] is EMPTY" if ionic.Platform.isAndroid() config = { "senderID": "YOUR_GCM_PROJECT_ID" # // REPLACE THIS WITH YOURS FROM GCM CONSOLE - also in the project URL like: https://console.developers.google.com/project/434205989073 } else if ionic.Platform.isIOS() config = { "badge": "true", "sound": "true", "alert": "true" } return $cordovaPush.register(config) .then (result)-> return result if result=='Parse installation unchanged' # $log.debug("Register success " + result) if ionic.Platform.isIOS() self.storeDeviceTokenP { type: 'ios' deviceToken: result } else if ionic.Platform.isAndroid() # ** NOTE: Android regid result comes back in the pushNotificationReceived angular.noop() return true , (err)-> self.isReady = false console.log 'ERROR pushNotify.register(), err=' + JSON.stringify err return $q.reject("pushNotify $cordovaPush register error") handleIOS: (notification)-> # The app was already open but we'll still show the alert # and sound the tone received this way. If you didn't check # for foreground here it would make a sound twice, once when # received in background and upon opening it from clicking # the notification when this code runs (weird). # $log.debug "handleIOS()", notification # looks like: Object # body: "We have your order and are ready for photos. Visit the Uploader to get started." # foreground: "1" # sound: "default" # target: "app.uploader" # title: "Ready for Upload" if notification.foreground == '1' if notification.sound media = $cordovaMedia.newMedia(notification.sound).then ()-> media.play() return , (err)-> $log.error "Play media error", err if notification.badge $cordovaPush.setBadgeNumber(notification.badge).then (result)-> $log.debug "Set badge success", result return , (err)-> $log.error "Set badge error", err else # sound, badge should be set in background by notification Center angular.noop() msg = { target : notification.target } if notification.body? msg['title'] = notification.title msg['message'] = notification.body else msg['message'] = notification.alert notify.message msg,'info', 10000 return if !notification.target # handle state transition if notification.target.state? $rootScope.$state.transitionTo( notification.target.state, notification.target.params ) else $location.path(notification.target) return handleAndroid: (notification)-> # // ** NOTE: ** You could add code for when app is in foreground or not, or coming from coldstart here too # // via the console fields as shown. console.log("In foreground " + notification.foreground + " Coldstart " + notification.coldstart); if notification.event == "registered" self.storeDeviceTokenP { type: 'android' deviceToken: result } else if notification.event == "message" notify.message notification.message $log.debug 'handleAndroid', notification else if notification.event == "error" notify.message notification.message, 'error' $log.error 'Error: handleAndroid', notification return storeDeviceTokenP: (options)-> throw "storeDeviceTokenP(): Error invalid options" if `options==null` return Parse._getInstallationId() .then (installationId)-> postData = { "deviceId": deviceReady.device().id "deviceType": options.type, "deviceToken": options.deviceToken, "installationId" : installationId, "channels": [""] } if $rootScope.parseUser? postData["owner"] = { __type: 'Pointer', className: '_User', objectId: $rootScope.parseUser.id } postData["ownerId"] = $rootScope.parseUser.id postData["username"] = $rootScope.parseUser.get('name') || $rootScope.parseUser.get('username') postData["active"] = true # active installation, for multiple users on same device # TODO: beforeSave set active=false for installationId==installationId else postData["owner"] = null postData["ownerId"] = null postData["username"] = 'guest' postData["active"] = true # active installation, for multiple users on same device # TODO: move to otgParse? xhrOptions = { url: "https://api.parse.com/1/installations", method: "POST", data: postData, headers: "X-Parse-Application-Id": KEYS.parse.APP_ID, "X-Parse-REST-API-Key": KEYS.parse.REST_API_KEY, "Content-Type": "application/json" } return $http(xhrOptions) .then (resp, status)-> _localStorageDevice['pushInstall'] = _.pick resp.data, ['objectId', 'deviceType', 'deviceId', 'installationId', 'ownerId', 'username'] console.log "Parse installation saved, data=" + JSON.stringify _localStorageDevice['pushInstall'] return resp.data , (err)-> console.log "Error: saving Parse installation" + JSON.stringify(err) return $q.reject("pushNotify registerP(), error saving to Parse") sayHelloP: (ownerId)-> if `ownerId==null` return $q.reject('No Parse.User specified') options = { method: 'POST' url: "https://api.parse.com/1/push" headers: 'X-Parse-Application-Id': KEYS.parse.APP_ID 'X-Parse-REST-API-Key': KEYS.parse.REST_API_KEY 'Content-Type': 'application/json' data: '' } postData = { # should be JSON.stringify() where: notificationTemplate.conditions['ownerId'] # should be JSON.stringify() data: notificationTemplate.payload['example'] } postData.where.ownerId = ownerId console.log "options", options options.data = postData return $http( options ).then (resp)-> if resp.data?.result == true return postData return resp.data } exportDebug['parsePush'] = self return self ])
32164
'use strict' ###* # @ngdoc service # @name parsePush # @description wrapper for pushNotification plugin, register installation with push server on PARSE # handle push notification events: adds badges, notifications to iOS notification panel # for ParseJs Push configuration details, see: # https://www.parse.com/docs/ios/guide#push-notifications # https://www.parse.com/tutorials/ios-push-notifications # @author <NAME>, Snaphappi Inc. ### angular .module 'parse.push', [ 'ionic', 'snappi.util' 'parse.backend' 'auth' ] .factory( 'parsePush', [ '$rootScope', '$location', '$q', '$log', '$http' '$cordovaPush', '$cordovaMedia' 'notifyService' 'auth.KEYS', 'deviceReady', 'exportDebug' ($rootScope, $location, $q, $log, $http, $cordovaPush, $cordovaMedia, notify, KEYS, deviceReady, exportDebug)-> # note: serialized during self.initialize() notificationTemplate = { conditions: 'channels': # postData.where 'channels': '$in': ['channel1', 'channel2'] 'ownerId': 'ownerId': null payload: 'example': # postData.data aps: alert: title: 'Hello There' body: "This is a push notification from Parse!" badge: 1 sound: 'default' 'content-available': false target: state: 'app.home' params: null } $rootScope.$on '$cordovaPush:notificationReceived', (event, notification)-> console.log "notification received, JSON="+JSON.stringify notification $log.debug( '$cordovaPush:notificationReceived', notification ) if ionic.Platform.isAndroid() self.handleAndroid( notification ) else if ionic.Platform.isIOS() self.handleIOS( notification ) return _localStorageDevice = null self = { # check existing Parse Installation object ### # @param $localStorageDevice object, place to check for/save existing Parse installation # keys; ['objectId', 'deviceType', 'installationId', 'owner', 'username'] # NOTE: should be saved to $localStorage['device'] ### initialize: ($localStorageDevice)-> return self if deviceReady.device().isBrowser == true _localStorageDevice = $localStorageDevice self.isReady = true console.log "pushNotificationPluginSvc initialized", $localStorageDevice return self registerP: ()-> return $q.when() if deviceReady.device().isBrowser == true if !self.isReady $log.warn("WARNING: attempted to register device before plugin intialization.") return $q.reject("pushNotify plugin not initialized") return Parse._getInstallationId() .then (installationId)-> if _localStorageDevice?['pushInstall']? isOK = true isOK = isOK && $rootScope.parseUser?.id && _localStorageDevice['pushInstall'].ownerId == $rootScope.parseUser.id isOK = isOK && _localStorageDevice['pushInstall'].deviceId == deviceReady.device().id isOK = isOK && _localStorageDevice['pushInstall'].installationId == installationId if isOK console.log "pushInstall unchanged" return $q.when('Parse installation unchanged') # else # console.log "localStorage pushInstall=" + JSON.stringify _localStorageDevice['pushInstall'] # console.log "compare to:" + JSON.stringify [ $rootScope.parseUser.id, deviceReady.device().id, installationId ] else console.log "_localStorageDevice['pushInstall'] is EMPTY" if ionic.Platform.isAndroid() config = { "senderID": "YOUR_GCM_PROJECT_ID" # // REPLACE THIS WITH YOURS FROM GCM CONSOLE - also in the project URL like: https://console.developers.google.com/project/434205989073 } else if ionic.Platform.isIOS() config = { "badge": "true", "sound": "true", "alert": "true" } return $cordovaPush.register(config) .then (result)-> return result if result=='Parse installation unchanged' # $log.debug("Register success " + result) if ionic.Platform.isIOS() self.storeDeviceTokenP { type: 'ios' deviceToken: result } else if ionic.Platform.isAndroid() # ** NOTE: Android regid result comes back in the pushNotificationReceived angular.noop() return true , (err)-> self.isReady = false console.log 'ERROR pushNotify.register(), err=' + JSON.stringify err return $q.reject("pushNotify $cordovaPush register error") handleIOS: (notification)-> # The app was already open but we'll still show the alert # and sound the tone received this way. If you didn't check # for foreground here it would make a sound twice, once when # received in background and upon opening it from clicking # the notification when this code runs (weird). # $log.debug "handleIOS()", notification # looks like: Object # body: "We have your order and are ready for photos. Visit the Uploader to get started." # foreground: "1" # sound: "default" # target: "app.uploader" # title: "Ready for Upload" if notification.foreground == '1' if notification.sound media = $cordovaMedia.newMedia(notification.sound).then ()-> media.play() return , (err)-> $log.error "Play media error", err if notification.badge $cordovaPush.setBadgeNumber(notification.badge).then (result)-> $log.debug "Set badge success", result return , (err)-> $log.error "Set badge error", err else # sound, badge should be set in background by notification Center angular.noop() msg = { target : notification.target } if notification.body? msg['title'] = notification.title msg['message'] = notification.body else msg['message'] = notification.alert notify.message msg,'info', 10000 return if !notification.target # handle state transition if notification.target.state? $rootScope.$state.transitionTo( notification.target.state, notification.target.params ) else $location.path(notification.target) return handleAndroid: (notification)-> # // ** NOTE: ** You could add code for when app is in foreground or not, or coming from coldstart here too # // via the console fields as shown. console.log("In foreground " + notification.foreground + " Coldstart " + notification.coldstart); if notification.event == "registered" self.storeDeviceTokenP { type: 'android' deviceToken: result } else if notification.event == "message" notify.message notification.message $log.debug 'handleAndroid', notification else if notification.event == "error" notify.message notification.message, 'error' $log.error 'Error: handleAndroid', notification return storeDeviceTokenP: (options)-> throw "storeDeviceTokenP(): Error invalid options" if `options==null` return Parse._getInstallationId() .then (installationId)-> postData = { "deviceId": deviceReady.device().id "deviceType": options.type, "deviceToken": options.deviceToken, "installationId" : installationId, "channels": [""] } if $rootScope.parseUser? postData["owner"] = { __type: 'Pointer', className: '_User', objectId: $rootScope.parseUser.id } postData["ownerId"] = $rootScope.parseUser.id postData["username"] = $rootScope.parseUser.get('name') || $rootScope.parseUser.get('username') postData["active"] = true # active installation, for multiple users on same device # TODO: beforeSave set active=false for installationId==installationId else postData["owner"] = null postData["ownerId"] = null postData["username"] = 'guest' postData["active"] = true # active installation, for multiple users on same device # TODO: move to otgParse? xhrOptions = { url: "https://api.parse.com/1/installations", method: "POST", data: postData, headers: "X-Parse-Application-Id": KEYS.parse.APP_ID, "X-Parse-REST-API-Key": KEYS.parse.REST_API_KEY, "Content-Type": "application/json" } return $http(xhrOptions) .then (resp, status)-> _localStorageDevice['pushInstall'] = _.pick resp.data, ['objectId', 'deviceType', 'deviceId', 'installationId', 'ownerId', 'username'] console.log "Parse installation saved, data=" + JSON.stringify _localStorageDevice['pushInstall'] return resp.data , (err)-> console.log "Error: saving Parse installation" + JSON.stringify(err) return $q.reject("pushNotify registerP(), error saving to Parse") sayHelloP: (ownerId)-> if `ownerId==null` return $q.reject('No Parse.User specified') options = { method: 'POST' url: "https://api.parse.com/1/push" headers: 'X-Parse-Application-Id': KEYS.parse.APP_ID 'X-Parse-REST-API-Key': KEYS.parse.REST_API_KEY 'Content-Type': 'application/json' data: '' } postData = { # should be JSON.stringify() where: notificationTemplate.conditions['ownerId'] # should be JSON.stringify() data: notificationTemplate.payload['example'] } postData.where.ownerId = ownerId console.log "options", options options.data = postData return $http( options ).then (resp)-> if resp.data?.result == true return postData return resp.data } exportDebug['parsePush'] = self return self ])
true
'use strict' ###* # @ngdoc service # @name parsePush # @description wrapper for pushNotification plugin, register installation with push server on PARSE # handle push notification events: adds badges, notifications to iOS notification panel # for ParseJs Push configuration details, see: # https://www.parse.com/docs/ios/guide#push-notifications # https://www.parse.com/tutorials/ios-push-notifications # @author PI:NAME:<NAME>END_PI, Snaphappi Inc. ### angular .module 'parse.push', [ 'ionic', 'snappi.util' 'parse.backend' 'auth' ] .factory( 'parsePush', [ '$rootScope', '$location', '$q', '$log', '$http' '$cordovaPush', '$cordovaMedia' 'notifyService' 'auth.KEYS', 'deviceReady', 'exportDebug' ($rootScope, $location, $q, $log, $http, $cordovaPush, $cordovaMedia, notify, KEYS, deviceReady, exportDebug)-> # note: serialized during self.initialize() notificationTemplate = { conditions: 'channels': # postData.where 'channels': '$in': ['channel1', 'channel2'] 'ownerId': 'ownerId': null payload: 'example': # postData.data aps: alert: title: 'Hello There' body: "This is a push notification from Parse!" badge: 1 sound: 'default' 'content-available': false target: state: 'app.home' params: null } $rootScope.$on '$cordovaPush:notificationReceived', (event, notification)-> console.log "notification received, JSON="+JSON.stringify notification $log.debug( '$cordovaPush:notificationReceived', notification ) if ionic.Platform.isAndroid() self.handleAndroid( notification ) else if ionic.Platform.isIOS() self.handleIOS( notification ) return _localStorageDevice = null self = { # check existing Parse Installation object ### # @param $localStorageDevice object, place to check for/save existing Parse installation # keys; ['objectId', 'deviceType', 'installationId', 'owner', 'username'] # NOTE: should be saved to $localStorage['device'] ### initialize: ($localStorageDevice)-> return self if deviceReady.device().isBrowser == true _localStorageDevice = $localStorageDevice self.isReady = true console.log "pushNotificationPluginSvc initialized", $localStorageDevice return self registerP: ()-> return $q.when() if deviceReady.device().isBrowser == true if !self.isReady $log.warn("WARNING: attempted to register device before plugin intialization.") return $q.reject("pushNotify plugin not initialized") return Parse._getInstallationId() .then (installationId)-> if _localStorageDevice?['pushInstall']? isOK = true isOK = isOK && $rootScope.parseUser?.id && _localStorageDevice['pushInstall'].ownerId == $rootScope.parseUser.id isOK = isOK && _localStorageDevice['pushInstall'].deviceId == deviceReady.device().id isOK = isOK && _localStorageDevice['pushInstall'].installationId == installationId if isOK console.log "pushInstall unchanged" return $q.when('Parse installation unchanged') # else # console.log "localStorage pushInstall=" + JSON.stringify _localStorageDevice['pushInstall'] # console.log "compare to:" + JSON.stringify [ $rootScope.parseUser.id, deviceReady.device().id, installationId ] else console.log "_localStorageDevice['pushInstall'] is EMPTY" if ionic.Platform.isAndroid() config = { "senderID": "YOUR_GCM_PROJECT_ID" # // REPLACE THIS WITH YOURS FROM GCM CONSOLE - also in the project URL like: https://console.developers.google.com/project/434205989073 } else if ionic.Platform.isIOS() config = { "badge": "true", "sound": "true", "alert": "true" } return $cordovaPush.register(config) .then (result)-> return result if result=='Parse installation unchanged' # $log.debug("Register success " + result) if ionic.Platform.isIOS() self.storeDeviceTokenP { type: 'ios' deviceToken: result } else if ionic.Platform.isAndroid() # ** NOTE: Android regid result comes back in the pushNotificationReceived angular.noop() return true , (err)-> self.isReady = false console.log 'ERROR pushNotify.register(), err=' + JSON.stringify err return $q.reject("pushNotify $cordovaPush register error") handleIOS: (notification)-> # The app was already open but we'll still show the alert # and sound the tone received this way. If you didn't check # for foreground here it would make a sound twice, once when # received in background and upon opening it from clicking # the notification when this code runs (weird). # $log.debug "handleIOS()", notification # looks like: Object # body: "We have your order and are ready for photos. Visit the Uploader to get started." # foreground: "1" # sound: "default" # target: "app.uploader" # title: "Ready for Upload" if notification.foreground == '1' if notification.sound media = $cordovaMedia.newMedia(notification.sound).then ()-> media.play() return , (err)-> $log.error "Play media error", err if notification.badge $cordovaPush.setBadgeNumber(notification.badge).then (result)-> $log.debug "Set badge success", result return , (err)-> $log.error "Set badge error", err else # sound, badge should be set in background by notification Center angular.noop() msg = { target : notification.target } if notification.body? msg['title'] = notification.title msg['message'] = notification.body else msg['message'] = notification.alert notify.message msg,'info', 10000 return if !notification.target # handle state transition if notification.target.state? $rootScope.$state.transitionTo( notification.target.state, notification.target.params ) else $location.path(notification.target) return handleAndroid: (notification)-> # // ** NOTE: ** You could add code for when app is in foreground or not, or coming from coldstart here too # // via the console fields as shown. console.log("In foreground " + notification.foreground + " Coldstart " + notification.coldstart); if notification.event == "registered" self.storeDeviceTokenP { type: 'android' deviceToken: result } else if notification.event == "message" notify.message notification.message $log.debug 'handleAndroid', notification else if notification.event == "error" notify.message notification.message, 'error' $log.error 'Error: handleAndroid', notification return storeDeviceTokenP: (options)-> throw "storeDeviceTokenP(): Error invalid options" if `options==null` return Parse._getInstallationId() .then (installationId)-> postData = { "deviceId": deviceReady.device().id "deviceType": options.type, "deviceToken": options.deviceToken, "installationId" : installationId, "channels": [""] } if $rootScope.parseUser? postData["owner"] = { __type: 'Pointer', className: '_User', objectId: $rootScope.parseUser.id } postData["ownerId"] = $rootScope.parseUser.id postData["username"] = $rootScope.parseUser.get('name') || $rootScope.parseUser.get('username') postData["active"] = true # active installation, for multiple users on same device # TODO: beforeSave set active=false for installationId==installationId else postData["owner"] = null postData["ownerId"] = null postData["username"] = 'guest' postData["active"] = true # active installation, for multiple users on same device # TODO: move to otgParse? xhrOptions = { url: "https://api.parse.com/1/installations", method: "POST", data: postData, headers: "X-Parse-Application-Id": KEYS.parse.APP_ID, "X-Parse-REST-API-Key": KEYS.parse.REST_API_KEY, "Content-Type": "application/json" } return $http(xhrOptions) .then (resp, status)-> _localStorageDevice['pushInstall'] = _.pick resp.data, ['objectId', 'deviceType', 'deviceId', 'installationId', 'ownerId', 'username'] console.log "Parse installation saved, data=" + JSON.stringify _localStorageDevice['pushInstall'] return resp.data , (err)-> console.log "Error: saving Parse installation" + JSON.stringify(err) return $q.reject("pushNotify registerP(), error saving to Parse") sayHelloP: (ownerId)-> if `ownerId==null` return $q.reject('No Parse.User specified') options = { method: 'POST' url: "https://api.parse.com/1/push" headers: 'X-Parse-Application-Id': KEYS.parse.APP_ID 'X-Parse-REST-API-Key': KEYS.parse.REST_API_KEY 'Content-Type': 'application/json' data: '' } postData = { # should be JSON.stringify() where: notificationTemplate.conditions['ownerId'] # should be JSON.stringify() data: notificationTemplate.payload['example'] } postData.where.ownerId = ownerId console.log "options", options options.data = postData return $http( options ).then (resp)-> if resp.data?.result == true return postData return resp.data } exportDebug['parsePush'] = self return self ])
[ { "context": "et URL'\n\n\t\tuserData =\n\t\t\temail: email\n\t\t\tpassword: pass\n\t\t\tinvitation: invitation\n\n\t\tuserId = Accounts.cr", "end": 861, "score": 0.9970410466194153, "start": 857, "tag": "PASSWORD", "value": "pass" } ]
server/methods/registerUser.coffee
mboozell/rocket-chat-example-package
0
Meteor.methods registerUser: (formData) -> if RocketChat.settings.get('Accounts_RegistrationForm') is 'Disabled' throw new Meteor.Error 'registration-disabled', 'User registration is disabled' {email, pass, name, inviteKey} = formData invitation = email: false if inviteKey invitation = RocketChat.models.Invitations.findOneByKey inviteKey if RocketChat.settings.get 'Invitation_Required' unless invitation.email is email throw new Meteor.Error 'email-invalid', "Invite doesn't match Email" if RocketChat.settings.get('Accounts_RegistrationForm') is 'Secret URL' and (not formData.secretURL or formData.secretURL isnt RocketChat.settings.get('Accounts_RegistrationForm_SecretURL')) throw new Meteor.Error 'registration-disabled', 'User registration is only allowed via Secret URL' userData = email: email password: pass invitation: invitation userId = Accounts.createUser userData RocketChat.models.Users.setName userId, name emailEnabled = RocketChat.settings.get('MAIL_URL') or (RocketChat.settings.get('SMTP_Host') and RocketChat.settings.get('SMTP_Username') and RocketChat.settings.get('SMTP_Password')) if invitation.email RocketChat.models.Users.setEmailVerified userId else if userData.email and emailEnabled Meteor.defer -> Accounts.sendVerificationEmail(userId, email) return userId
138318
Meteor.methods registerUser: (formData) -> if RocketChat.settings.get('Accounts_RegistrationForm') is 'Disabled' throw new Meteor.Error 'registration-disabled', 'User registration is disabled' {email, pass, name, inviteKey} = formData invitation = email: false if inviteKey invitation = RocketChat.models.Invitations.findOneByKey inviteKey if RocketChat.settings.get 'Invitation_Required' unless invitation.email is email throw new Meteor.Error 'email-invalid', "Invite doesn't match Email" if RocketChat.settings.get('Accounts_RegistrationForm') is 'Secret URL' and (not formData.secretURL or formData.secretURL isnt RocketChat.settings.get('Accounts_RegistrationForm_SecretURL')) throw new Meteor.Error 'registration-disabled', 'User registration is only allowed via Secret URL' userData = email: email password: <PASSWORD> invitation: invitation userId = Accounts.createUser userData RocketChat.models.Users.setName userId, name emailEnabled = RocketChat.settings.get('MAIL_URL') or (RocketChat.settings.get('SMTP_Host') and RocketChat.settings.get('SMTP_Username') and RocketChat.settings.get('SMTP_Password')) if invitation.email RocketChat.models.Users.setEmailVerified userId else if userData.email and emailEnabled Meteor.defer -> Accounts.sendVerificationEmail(userId, email) return userId
true
Meteor.methods registerUser: (formData) -> if RocketChat.settings.get('Accounts_RegistrationForm') is 'Disabled' throw new Meteor.Error 'registration-disabled', 'User registration is disabled' {email, pass, name, inviteKey} = formData invitation = email: false if inviteKey invitation = RocketChat.models.Invitations.findOneByKey inviteKey if RocketChat.settings.get 'Invitation_Required' unless invitation.email is email throw new Meteor.Error 'email-invalid', "Invite doesn't match Email" if RocketChat.settings.get('Accounts_RegistrationForm') is 'Secret URL' and (not formData.secretURL or formData.secretURL isnt RocketChat.settings.get('Accounts_RegistrationForm_SecretURL')) throw new Meteor.Error 'registration-disabled', 'User registration is only allowed via Secret URL' userData = email: email password: PI:PASSWORD:<PASSWORD>END_PI invitation: invitation userId = Accounts.createUser userData RocketChat.models.Users.setName userId, name emailEnabled = RocketChat.settings.get('MAIL_URL') or (RocketChat.settings.get('SMTP_Host') and RocketChat.settings.get('SMTP_Username') and RocketChat.settings.get('SMTP_Password')) if invitation.email RocketChat.models.Users.setEmailVerified userId else if userData.email and emailEnabled Meteor.defer -> Accounts.sendVerificationEmail(userId, email) return userId
[ { "context": " Content: smsOptions.contents\n ClientId: 'vradbyxu'\n ClientSecret: 'ypaolptq'\n RegisteredD", "end": 291, "score": 0.9955958127975464, "start": 283, "tag": "USERNAME", "value": "vradbyxu" }, { "context": "s\n ClientId: 'vradbyxu'\n ClientSe...
server/sms.coffee
Innarticles/mypikin
0
Meteor.methods sendMessage: (smsOptions) -> @unblock() console.log 'in sendMessage' try result = HTTP.call('GET', 'https://api.smsgh.com/v3/messages/send?', params: From: smsOptions.From To: smsOptions.phone Content: smsOptions.contents ClientId: 'vradbyxu' ClientSecret: 'ypaolptq' RegisteredDelivery: true) console.log 'tried sending' return true catch e # Got a network error, time-out or HTTP error in the 400 or 500 range. console.log e return false Meteor.methods vodafoneApi: (params) -> @unblock() response = '' try console.log 'in the api' response = HTTP.call 'POST', 'http://testpay.vodafonecash.com.gh', { params: username: '711509' password: 'hackathon2' token: 'abc1234' amount: '2'} return response.content; catch e # Got a network error, time-out or HTTP error in the 400 or 500 range. console.log e return false # Meteor.methods vodafoneApi: (params) -> # @unblock() # response = '' # try # console.log 'in the api' # HTTP.call 'POST', 'http://testpay.vodafonecash.com.gh', { params: # username: '711509' # password: 'hackathon2' # token: 'abc1234' # amount: '2' }, (error, result) -> # if !error # response = result # if error # console.log error # response = error # return response # catch e # # Got a network error, time-out or HTTP error in the 400 or 500 range. # console.log e # return false
9714
Meteor.methods sendMessage: (smsOptions) -> @unblock() console.log 'in sendMessage' try result = HTTP.call('GET', 'https://api.smsgh.com/v3/messages/send?', params: From: smsOptions.From To: smsOptions.phone Content: smsOptions.contents ClientId: 'vradbyxu' ClientSecret: '<KEY>' RegisteredDelivery: true) console.log 'tried sending' return true catch e # Got a network error, time-out or HTTP error in the 400 or 500 range. console.log e return false Meteor.methods vodafoneApi: (params) -> @unblock() response = '' try console.log 'in the api' response = HTTP.call 'POST', 'http://testpay.vodafonecash.com.gh', { params: username: '711509' password: '<PASSWORD>' token: '<KEY>' amount: '2'} return response.content; catch e # Got a network error, time-out or HTTP error in the 400 or 500 range. console.log e return false # Meteor.methods vodafoneApi: (params) -> # @unblock() # response = '' # try # console.log 'in the api' # HTTP.call 'POST', 'http://testpay.vodafonecash.com.gh', { params: # username: '711509' # password: '<PASSWORD>' # token: '<KEY>' # amount: '2' }, (error, result) -> # if !error # response = result # if error # console.log error # response = error # return response # catch e # # Got a network error, time-out or HTTP error in the 400 or 500 range. # console.log e # return false
true
Meteor.methods sendMessage: (smsOptions) -> @unblock() console.log 'in sendMessage' try result = HTTP.call('GET', 'https://api.smsgh.com/v3/messages/send?', params: From: smsOptions.From To: smsOptions.phone Content: smsOptions.contents ClientId: 'vradbyxu' ClientSecret: 'PI:KEY:<KEY>END_PI' RegisteredDelivery: true) console.log 'tried sending' return true catch e # Got a network error, time-out or HTTP error in the 400 or 500 range. console.log e return false Meteor.methods vodafoneApi: (params) -> @unblock() response = '' try console.log 'in the api' response = HTTP.call 'POST', 'http://testpay.vodafonecash.com.gh', { params: username: '711509' password: 'PI:PASSWORD:<PASSWORD>END_PI' token: 'PI:KEY:<KEY>END_PI' amount: '2'} return response.content; catch e # Got a network error, time-out or HTTP error in the 400 or 500 range. console.log e return false # Meteor.methods vodafoneApi: (params) -> # @unblock() # response = '' # try # console.log 'in the api' # HTTP.call 'POST', 'http://testpay.vodafonecash.com.gh', { params: # username: '711509' # password: 'PI:PASSWORD:<PASSWORD>END_PI' # token: 'PI:KEY:<KEY>END_PI' # amount: '2' }, (error, result) -> # if !error # response = result # if error # console.log error # response = error # return response # catch e # # Got a network error, time-out or HTTP error in the 400 or 500 range. # console.log e # return false
[ { "context": "nds] = t\n key = tile_source.tile_xyz_to_key(x, y, z)\n tile = tile_source.tiles[key]\n i", "end": 7385, "score": 0.5308318734169006, "start": 7385, "tag": "KEY", "value": "" }, { "context": "(x, y, z)\n parent_key = tile_source.tile_xyz_to_key(p...
bokehjs/src/coffee/models/tiles/tile_renderer.coffee
chinasaur/bokeh
0
import {ImagePool} from "./image_pool" import {WMTSTileSource} from "./wmts_tile_source" import {Renderer, RendererView} from "../renderers/renderer" import {div} from "core/dom" import * as p from "core/properties" import {isString} from "core/util/types" export class TileRendererView extends RendererView initialize: (options) -> @attributionEl = null super bind_bokeh_events: () -> @listenTo(@model, 'change', @request_render) get_extent: () -> return [@x_range.start, @y_range.start, @x_range.end, @y_range.end] _set_data: () -> @pool = new ImagePool() @map_plot = @plot_model.plot @map_canvas = @plot_view.canvas_view.ctx @map_frame = @plot_model.frame @x_range = @map_plot.x_range @x_mapper = this.map_frame.x_mappers['default'] @y_range = @map_plot.y_range @y_mapper = this.map_frame.y_mappers['default'] @extent = @get_extent() @_last_height = undefined @_last_width = undefined _add_attribution: () => attribution = @model.tile_source.attribution if isString(attribution) and attribution.length > 0 if not @attributionEl? border_width = @map_plot.outline_line_width bottom_offset = @map_plot.min_border_bottom + border_width right_offset = @map_frame.right - @map_frame.width max_width = @map_frame.width - border_width @attributionEl = div({ class: 'bk-tile-attribution' style: { position: 'absolute' bottom: "#{bottom_offset}px" right: "#{right_offset}px" 'max-width': "#{max_width}px" 'background-color': 'rgba(255,255,255,0.8)' 'font-size': '9pt' 'font-family': 'sans-serif' } }) overlays = @plot_view.canvas_view.events_el overlays.appendChild(@attributionEl) @attributionEl.innerHTML = attribution _map_data: () -> @initial_extent = @get_extent() zoom_level = @model.tile_source.get_level_by_extent(@initial_extent, @map_frame.height, @map_frame.width) new_extent = @model.tile_source.snap_to_zoom(@initial_extent, @map_frame.height, @map_frame.width, zoom_level) @x_range.start = new_extent[0] @y_range.start = new_extent[1] @x_range.end = new_extent[2] @y_range.end = new_extent[3] @_add_attribution() _on_tile_load: (e) => tile_data = e.target.tile_data tile_data.img = e.target tile_data.current = true tile_data.loaded = true @request_render() _on_tile_cache_load: (e) => tile_data = e.target.tile_data tile_data.img = e.target tile_data.loaded = true _on_tile_error: (e) => return '' _create_tile: (x, y, z, bounds, cache_only=false) -> normalized_coords = @model.tile_source.normalize_xyz(x, y, z) tile = @pool.pop() if cache_only tile.onload = @_on_tile_cache_load else tile.onload = @_on_tile_load tile.onerror = @_on_tile_error tile.alt = '' tile.tile_data = tile_coords : [x, y, z] normalized_coords : normalized_coords quadkey : @model.tile_source.tile_xyz_to_quadkey(x, y, z) cache_key : @model.tile_source.tile_xyz_to_key(x, y, z) bounds : bounds loaded : false x_coord : bounds[0] y_coord : bounds[3] @model.tile_source.tiles[tile.tile_data.cache_key] = tile.tile_data tile.src = @model.tile_source.get_image_url(normalized_coords...) return tile _enforce_aspect_ratio: () -> # brute force way of handling resize or sizing_mode event ------------------------------------------------------------- if @_last_height != @map_frame.height or @_last_width != @map_frame.width extent = @get_extent() zoom_level = @model.tile_source.get_level_by_extent(extent, @map_frame.height, @map_frame.width) new_extent = @model.tile_source.snap_to_zoom(extent, @map_frame.height, @map_frame.width, zoom_level) @x_range.setv({start:new_extent[0], end: new_extent[2]}) @y_range.setv({start:new_extent[1], end: new_extent[3]}) @extent = new_extent @_last_height = @map_frame.height @_last_width = @map_frame.width return true return false render: (ctx, indices, args) -> if not @map_initialized? @_set_data() @_map_data() @map_initialized = true if @_enforce_aspect_ratio() return @_update() if @prefetch_timer? clearTimeout(@prefetch_timer) @prefetch_timer = setTimeout(@_prefetch_tiles, 500) _draw_tile: (tile_key) -> tile_obj = @model.tile_source.tiles[tile_key] if tile_obj? [sxmin, symin] = @plot_view.frame.map_to_screen([tile_obj.bounds[0]], [tile_obj.bounds[3]], @plot_view.canvas) [sxmax, symax] = @plot_view.frame.map_to_screen([tile_obj.bounds[2]], [tile_obj.bounds[1]], @plot_view.canvas) sxmin = sxmin[0] symin = symin[0] sxmax = sxmax[0] symax = symax[0] sw = sxmax - sxmin sh = symax - symin sx = sxmin sy = symin @map_canvas.drawImage(tile_obj.img, sx, sy, sw, sh) _set_rect:() -> outline_width = @plot_model.plot.properties.outline_line_width.value() l = @plot_view.canvas.vx_to_sx(@map_frame.left) + (outline_width/2) t = @plot_view.canvas.vy_to_sy(@map_frame.top) + (outline_width/2) w = @map_frame.width - outline_width h = @map_frame.height - outline_width @map_canvas.rect(l, t, w, h) @map_canvas.clip() _render_tiles: (tile_keys) -> @map_canvas.save() @_set_rect() @map_canvas.globalAlpha = @model.alpha for tile_key in tile_keys @_draw_tile(tile_key) @map_canvas.restore() _prefetch_tiles: () => tile_source = @model.tile_source extent = @get_extent() h = @map_frame.height w = @map_frame.width zoom_level = @model.tile_source.get_level_by_extent(extent, h, w) tiles = @model.tile_source.get_tiles_by_extent(extent, zoom_level) for t in [0..Math.min(10, tiles.length)] by 1 [x, y, z, bounds] = t children = @model.tile_source.children_by_tile_xyz(x, y, z) for c in children [cx, cy, cz, cbounds] = c if tile_source.tile_xyz_to_key(cx, cy, cz) of tile_source.tiles continue else @_create_tile(cx, cy, cz, cbounds, true) _fetch_tiles:(tiles) -> for t in tiles [x, y, z, bounds] = t @_create_tile(x, y, z, bounds) _update: () => tile_source = @model.tile_source min_zoom = tile_source.min_zoom max_zoom = tile_source.max_zoom tile_source.update() extent = @get_extent() zooming_out = @extent[2] - @extent[0] < extent[2] - extent[0] h = @map_frame.height w = @map_frame.width zoom_level = tile_source.get_level_by_extent(extent, h, w) snap_back = false if zoom_level < min_zoom extent = @extent zoom_level = min_zoom snap_back = true else if zoom_level > max_zoom extent = @extent zoom_level = max_zoom snap_back = true if snap_back @x_range.setv(x_range:{start:extent[0], end: extent[2]}) @y_range.setv({start:extent[1], end: extent[3]}) @extent = extent @extent = extent tiles = tile_source.get_tiles_by_extent(extent, zoom_level) parents = [] need_load = [] cached = [] children = [] for t in tiles [x, y, z, bounds] = t key = tile_source.tile_xyz_to_key(x, y, z) tile = tile_source.tiles[key] if tile? and tile.loaded == true cached.push(key) else if @model.render_parents [px, py, pz] = tile_source.get_closest_parent_by_tile_xyz(x, y, z) parent_key = tile_source.tile_xyz_to_key(px, py, pz) parent_tile = tile_source.tiles[parent_key] if parent_tile? and parent_tile.loaded and parent_key not in parents parents.push(parent_key) if zooming_out children = tile_source.children_by_tile_xyz(x, y, z) for c in children [cx, cy, cz, cbounds] = c child_key = tile_source.tile_xyz_to_key(cx, cy, cz) if child_key of tile_source.tiles children.push(child_key) if not tile? need_load.push(t) # draw stand-in parents ---------- @_render_tiles(parents) @_render_tiles(children) # draw cached ---------- @_render_tiles(cached) for t in cached tile_source.tiles[t].current = true # fetch missing ------- if @render_timer? clearTimeout(@render_timer) @render_timer = setTimeout((=> @_fetch_tiles(need_load)), 65) export class TileRenderer extends Renderer default_view: TileRendererView type: 'TileRenderer' @define { alpha: [ p.Number, 1.0 ] x_range_name: [ p.String, "default" ] y_range_name: [ p.String, "default" ] tile_source: [ p.Instance, () -> new WMTSTileSource() ] render_parents: [ p.Bool, true ] } @override { level: 'underlay' }
76879
import {ImagePool} from "./image_pool" import {WMTSTileSource} from "./wmts_tile_source" import {Renderer, RendererView} from "../renderers/renderer" import {div} from "core/dom" import * as p from "core/properties" import {isString} from "core/util/types" export class TileRendererView extends RendererView initialize: (options) -> @attributionEl = null super bind_bokeh_events: () -> @listenTo(@model, 'change', @request_render) get_extent: () -> return [@x_range.start, @y_range.start, @x_range.end, @y_range.end] _set_data: () -> @pool = new ImagePool() @map_plot = @plot_model.plot @map_canvas = @plot_view.canvas_view.ctx @map_frame = @plot_model.frame @x_range = @map_plot.x_range @x_mapper = this.map_frame.x_mappers['default'] @y_range = @map_plot.y_range @y_mapper = this.map_frame.y_mappers['default'] @extent = @get_extent() @_last_height = undefined @_last_width = undefined _add_attribution: () => attribution = @model.tile_source.attribution if isString(attribution) and attribution.length > 0 if not @attributionEl? border_width = @map_plot.outline_line_width bottom_offset = @map_plot.min_border_bottom + border_width right_offset = @map_frame.right - @map_frame.width max_width = @map_frame.width - border_width @attributionEl = div({ class: 'bk-tile-attribution' style: { position: 'absolute' bottom: "#{bottom_offset}px" right: "#{right_offset}px" 'max-width': "#{max_width}px" 'background-color': 'rgba(255,255,255,0.8)' 'font-size': '9pt' 'font-family': 'sans-serif' } }) overlays = @plot_view.canvas_view.events_el overlays.appendChild(@attributionEl) @attributionEl.innerHTML = attribution _map_data: () -> @initial_extent = @get_extent() zoom_level = @model.tile_source.get_level_by_extent(@initial_extent, @map_frame.height, @map_frame.width) new_extent = @model.tile_source.snap_to_zoom(@initial_extent, @map_frame.height, @map_frame.width, zoom_level) @x_range.start = new_extent[0] @y_range.start = new_extent[1] @x_range.end = new_extent[2] @y_range.end = new_extent[3] @_add_attribution() _on_tile_load: (e) => tile_data = e.target.tile_data tile_data.img = e.target tile_data.current = true tile_data.loaded = true @request_render() _on_tile_cache_load: (e) => tile_data = e.target.tile_data tile_data.img = e.target tile_data.loaded = true _on_tile_error: (e) => return '' _create_tile: (x, y, z, bounds, cache_only=false) -> normalized_coords = @model.tile_source.normalize_xyz(x, y, z) tile = @pool.pop() if cache_only tile.onload = @_on_tile_cache_load else tile.onload = @_on_tile_load tile.onerror = @_on_tile_error tile.alt = '' tile.tile_data = tile_coords : [x, y, z] normalized_coords : normalized_coords quadkey : @model.tile_source.tile_xyz_to_quadkey(x, y, z) cache_key : @model.tile_source.tile_xyz_to_key(x, y, z) bounds : bounds loaded : false x_coord : bounds[0] y_coord : bounds[3] @model.tile_source.tiles[tile.tile_data.cache_key] = tile.tile_data tile.src = @model.tile_source.get_image_url(normalized_coords...) return tile _enforce_aspect_ratio: () -> # brute force way of handling resize or sizing_mode event ------------------------------------------------------------- if @_last_height != @map_frame.height or @_last_width != @map_frame.width extent = @get_extent() zoom_level = @model.tile_source.get_level_by_extent(extent, @map_frame.height, @map_frame.width) new_extent = @model.tile_source.snap_to_zoom(extent, @map_frame.height, @map_frame.width, zoom_level) @x_range.setv({start:new_extent[0], end: new_extent[2]}) @y_range.setv({start:new_extent[1], end: new_extent[3]}) @extent = new_extent @_last_height = @map_frame.height @_last_width = @map_frame.width return true return false render: (ctx, indices, args) -> if not @map_initialized? @_set_data() @_map_data() @map_initialized = true if @_enforce_aspect_ratio() return @_update() if @prefetch_timer? clearTimeout(@prefetch_timer) @prefetch_timer = setTimeout(@_prefetch_tiles, 500) _draw_tile: (tile_key) -> tile_obj = @model.tile_source.tiles[tile_key] if tile_obj? [sxmin, symin] = @plot_view.frame.map_to_screen([tile_obj.bounds[0]], [tile_obj.bounds[3]], @plot_view.canvas) [sxmax, symax] = @plot_view.frame.map_to_screen([tile_obj.bounds[2]], [tile_obj.bounds[1]], @plot_view.canvas) sxmin = sxmin[0] symin = symin[0] sxmax = sxmax[0] symax = symax[0] sw = sxmax - sxmin sh = symax - symin sx = sxmin sy = symin @map_canvas.drawImage(tile_obj.img, sx, sy, sw, sh) _set_rect:() -> outline_width = @plot_model.plot.properties.outline_line_width.value() l = @plot_view.canvas.vx_to_sx(@map_frame.left) + (outline_width/2) t = @plot_view.canvas.vy_to_sy(@map_frame.top) + (outline_width/2) w = @map_frame.width - outline_width h = @map_frame.height - outline_width @map_canvas.rect(l, t, w, h) @map_canvas.clip() _render_tiles: (tile_keys) -> @map_canvas.save() @_set_rect() @map_canvas.globalAlpha = @model.alpha for tile_key in tile_keys @_draw_tile(tile_key) @map_canvas.restore() _prefetch_tiles: () => tile_source = @model.tile_source extent = @get_extent() h = @map_frame.height w = @map_frame.width zoom_level = @model.tile_source.get_level_by_extent(extent, h, w) tiles = @model.tile_source.get_tiles_by_extent(extent, zoom_level) for t in [0..Math.min(10, tiles.length)] by 1 [x, y, z, bounds] = t children = @model.tile_source.children_by_tile_xyz(x, y, z) for c in children [cx, cy, cz, cbounds] = c if tile_source.tile_xyz_to_key(cx, cy, cz) of tile_source.tiles continue else @_create_tile(cx, cy, cz, cbounds, true) _fetch_tiles:(tiles) -> for t in tiles [x, y, z, bounds] = t @_create_tile(x, y, z, bounds) _update: () => tile_source = @model.tile_source min_zoom = tile_source.min_zoom max_zoom = tile_source.max_zoom tile_source.update() extent = @get_extent() zooming_out = @extent[2] - @extent[0] < extent[2] - extent[0] h = @map_frame.height w = @map_frame.width zoom_level = tile_source.get_level_by_extent(extent, h, w) snap_back = false if zoom_level < min_zoom extent = @extent zoom_level = min_zoom snap_back = true else if zoom_level > max_zoom extent = @extent zoom_level = max_zoom snap_back = true if snap_back @x_range.setv(x_range:{start:extent[0], end: extent[2]}) @y_range.setv({start:extent[1], end: extent[3]}) @extent = extent @extent = extent tiles = tile_source.get_tiles_by_extent(extent, zoom_level) parents = [] need_load = [] cached = [] children = [] for t in tiles [x, y, z, bounds] = t key = tile_source.tile_xyz_to_key(x<KEY>, y, z) tile = tile_source.tiles[key] if tile? and tile.loaded == true cached.push(key) else if @model.render_parents [px, py, pz] = tile_source.get_closest_parent_by_tile_xyz(x, y, z) parent_key = tile_source.tile_<KEY>to_key(<KEY>) parent_tile = tile_source.tiles[parent_key] if parent_tile? and parent_tile.loaded and parent_key not in parents parents.push(parent_key) if zooming_out children = tile_source.children_by_tile_xyz(x, y, z) for c in children [cx, cy, cz, cbounds] = c child_key = tile_source.tile_xyz_to_key(<KEY>, <KEY>, cz) if child_key of tile_source.tiles children.push(child_key) if not tile? need_load.push(t) # draw stand-in parents ---------- @_render_tiles(parents) @_render_tiles(children) # draw cached ---------- @_render_tiles(cached) for t in cached tile_source.tiles[t].current = true # fetch missing ------- if @render_timer? clearTimeout(@render_timer) @render_timer = setTimeout((=> @_fetch_tiles(need_load)), 65) export class TileRenderer extends Renderer default_view: TileRendererView type: 'TileRenderer' @define { alpha: [ p.Number, 1.0 ] x_range_name: [ p.String, "default" ] y_range_name: [ p.String, "default" ] tile_source: [ p.Instance, () -> new WMTSTileSource() ] render_parents: [ p.Bool, true ] } @override { level: 'underlay' }
true
import {ImagePool} from "./image_pool" import {WMTSTileSource} from "./wmts_tile_source" import {Renderer, RendererView} from "../renderers/renderer" import {div} from "core/dom" import * as p from "core/properties" import {isString} from "core/util/types" export class TileRendererView extends RendererView initialize: (options) -> @attributionEl = null super bind_bokeh_events: () -> @listenTo(@model, 'change', @request_render) get_extent: () -> return [@x_range.start, @y_range.start, @x_range.end, @y_range.end] _set_data: () -> @pool = new ImagePool() @map_plot = @plot_model.plot @map_canvas = @plot_view.canvas_view.ctx @map_frame = @plot_model.frame @x_range = @map_plot.x_range @x_mapper = this.map_frame.x_mappers['default'] @y_range = @map_plot.y_range @y_mapper = this.map_frame.y_mappers['default'] @extent = @get_extent() @_last_height = undefined @_last_width = undefined _add_attribution: () => attribution = @model.tile_source.attribution if isString(attribution) and attribution.length > 0 if not @attributionEl? border_width = @map_plot.outline_line_width bottom_offset = @map_plot.min_border_bottom + border_width right_offset = @map_frame.right - @map_frame.width max_width = @map_frame.width - border_width @attributionEl = div({ class: 'bk-tile-attribution' style: { position: 'absolute' bottom: "#{bottom_offset}px" right: "#{right_offset}px" 'max-width': "#{max_width}px" 'background-color': 'rgba(255,255,255,0.8)' 'font-size': '9pt' 'font-family': 'sans-serif' } }) overlays = @plot_view.canvas_view.events_el overlays.appendChild(@attributionEl) @attributionEl.innerHTML = attribution _map_data: () -> @initial_extent = @get_extent() zoom_level = @model.tile_source.get_level_by_extent(@initial_extent, @map_frame.height, @map_frame.width) new_extent = @model.tile_source.snap_to_zoom(@initial_extent, @map_frame.height, @map_frame.width, zoom_level) @x_range.start = new_extent[0] @y_range.start = new_extent[1] @x_range.end = new_extent[2] @y_range.end = new_extent[3] @_add_attribution() _on_tile_load: (e) => tile_data = e.target.tile_data tile_data.img = e.target tile_data.current = true tile_data.loaded = true @request_render() _on_tile_cache_load: (e) => tile_data = e.target.tile_data tile_data.img = e.target tile_data.loaded = true _on_tile_error: (e) => return '' _create_tile: (x, y, z, bounds, cache_only=false) -> normalized_coords = @model.tile_source.normalize_xyz(x, y, z) tile = @pool.pop() if cache_only tile.onload = @_on_tile_cache_load else tile.onload = @_on_tile_load tile.onerror = @_on_tile_error tile.alt = '' tile.tile_data = tile_coords : [x, y, z] normalized_coords : normalized_coords quadkey : @model.tile_source.tile_xyz_to_quadkey(x, y, z) cache_key : @model.tile_source.tile_xyz_to_key(x, y, z) bounds : bounds loaded : false x_coord : bounds[0] y_coord : bounds[3] @model.tile_source.tiles[tile.tile_data.cache_key] = tile.tile_data tile.src = @model.tile_source.get_image_url(normalized_coords...) return tile _enforce_aspect_ratio: () -> # brute force way of handling resize or sizing_mode event ------------------------------------------------------------- if @_last_height != @map_frame.height or @_last_width != @map_frame.width extent = @get_extent() zoom_level = @model.tile_source.get_level_by_extent(extent, @map_frame.height, @map_frame.width) new_extent = @model.tile_source.snap_to_zoom(extent, @map_frame.height, @map_frame.width, zoom_level) @x_range.setv({start:new_extent[0], end: new_extent[2]}) @y_range.setv({start:new_extent[1], end: new_extent[3]}) @extent = new_extent @_last_height = @map_frame.height @_last_width = @map_frame.width return true return false render: (ctx, indices, args) -> if not @map_initialized? @_set_data() @_map_data() @map_initialized = true if @_enforce_aspect_ratio() return @_update() if @prefetch_timer? clearTimeout(@prefetch_timer) @prefetch_timer = setTimeout(@_prefetch_tiles, 500) _draw_tile: (tile_key) -> tile_obj = @model.tile_source.tiles[tile_key] if tile_obj? [sxmin, symin] = @plot_view.frame.map_to_screen([tile_obj.bounds[0]], [tile_obj.bounds[3]], @plot_view.canvas) [sxmax, symax] = @plot_view.frame.map_to_screen([tile_obj.bounds[2]], [tile_obj.bounds[1]], @plot_view.canvas) sxmin = sxmin[0] symin = symin[0] sxmax = sxmax[0] symax = symax[0] sw = sxmax - sxmin sh = symax - symin sx = sxmin sy = symin @map_canvas.drawImage(tile_obj.img, sx, sy, sw, sh) _set_rect:() -> outline_width = @plot_model.plot.properties.outline_line_width.value() l = @plot_view.canvas.vx_to_sx(@map_frame.left) + (outline_width/2) t = @plot_view.canvas.vy_to_sy(@map_frame.top) + (outline_width/2) w = @map_frame.width - outline_width h = @map_frame.height - outline_width @map_canvas.rect(l, t, w, h) @map_canvas.clip() _render_tiles: (tile_keys) -> @map_canvas.save() @_set_rect() @map_canvas.globalAlpha = @model.alpha for tile_key in tile_keys @_draw_tile(tile_key) @map_canvas.restore() _prefetch_tiles: () => tile_source = @model.tile_source extent = @get_extent() h = @map_frame.height w = @map_frame.width zoom_level = @model.tile_source.get_level_by_extent(extent, h, w) tiles = @model.tile_source.get_tiles_by_extent(extent, zoom_level) for t in [0..Math.min(10, tiles.length)] by 1 [x, y, z, bounds] = t children = @model.tile_source.children_by_tile_xyz(x, y, z) for c in children [cx, cy, cz, cbounds] = c if tile_source.tile_xyz_to_key(cx, cy, cz) of tile_source.tiles continue else @_create_tile(cx, cy, cz, cbounds, true) _fetch_tiles:(tiles) -> for t in tiles [x, y, z, bounds] = t @_create_tile(x, y, z, bounds) _update: () => tile_source = @model.tile_source min_zoom = tile_source.min_zoom max_zoom = tile_source.max_zoom tile_source.update() extent = @get_extent() zooming_out = @extent[2] - @extent[0] < extent[2] - extent[0] h = @map_frame.height w = @map_frame.width zoom_level = tile_source.get_level_by_extent(extent, h, w) snap_back = false if zoom_level < min_zoom extent = @extent zoom_level = min_zoom snap_back = true else if zoom_level > max_zoom extent = @extent zoom_level = max_zoom snap_back = true if snap_back @x_range.setv(x_range:{start:extent[0], end: extent[2]}) @y_range.setv({start:extent[1], end: extent[3]}) @extent = extent @extent = extent tiles = tile_source.get_tiles_by_extent(extent, zoom_level) parents = [] need_load = [] cached = [] children = [] for t in tiles [x, y, z, bounds] = t key = tile_source.tile_xyz_to_key(xPI:KEY:<KEY>END_PI, y, z) tile = tile_source.tiles[key] if tile? and tile.loaded == true cached.push(key) else if @model.render_parents [px, py, pz] = tile_source.get_closest_parent_by_tile_xyz(x, y, z) parent_key = tile_source.tile_PI:KEY:<KEY>END_PIto_key(PI:KEY:<KEY>END_PI) parent_tile = tile_source.tiles[parent_key] if parent_tile? and parent_tile.loaded and parent_key not in parents parents.push(parent_key) if zooming_out children = tile_source.children_by_tile_xyz(x, y, z) for c in children [cx, cy, cz, cbounds] = c child_key = tile_source.tile_xyz_to_key(PI:KEY:<KEY>END_PI, PI:KEY:<KEY>END_PI, cz) if child_key of tile_source.tiles children.push(child_key) if not tile? need_load.push(t) # draw stand-in parents ---------- @_render_tiles(parents) @_render_tiles(children) # draw cached ---------- @_render_tiles(cached) for t in cached tile_source.tiles[t].current = true # fetch missing ------- if @render_timer? clearTimeout(@render_timer) @render_timer = setTimeout((=> @_fetch_tiles(need_load)), 65) export class TileRenderer extends Renderer default_view: TileRendererView type: 'TileRenderer' @define { alpha: [ p.Number, 1.0 ] x_range_name: [ p.String, "default" ] y_range_name: [ p.String, "default" ] tile_source: [ p.Instance, () -> new WMTSTileSource() ] render_parents: [ p.Bool, true ] } @override { level: 'underlay' }
[ { "context": "find all messages in references\n keys = references.map (mid) -> [mail.accountID, 'mid', mid]\n ", "end": 5264, "score": 0.6124908924102783, "start": 5250, "tag": "KEY", "value": "references.map" }, { "context": "ences\n keys = references...
server/models/message.coffee
gelnior/cozy-emails
0
cozydb = require 'cozydb' # Public: a mail address, used in {Message} schema class MailAdress extends cozydb.Model @schema: name: String address: String class MailAttachment extends cozydb.Model @schema: cozydb.NoSchema # Public: Message module.exports = class Message extends cozydb.CozyModel @docType: 'Message' @schema: accountID : String # account this message belongs to messageID : String # normalized message-id (no <"">) normSubject : String # normalized subject (no Re: ...) conversationID : String # all message in thread have same # conversationID mailboxIDs : cozydb.NoSchema # mailboxes as an hash # {boxID: uid, boxID2 : uid2} hasTwin : [String] # [String] mailboxIDs where this # message has twin twinMailboxIDs : cozydb.NoSchema # mailboxes as an hash of array flags : [String] # [String] flags of the message headers : cozydb.NoSchema # hash of the message headers from : [MailAdress] # array of {name, address} to : [MailAdress] # array of {name, address} cc : [MailAdress] # array of {name, address} bcc : [MailAdress] # array of {name, address} replyTo : [MailAdress] # array of {name, address} subject : String # subject of the message inReplyTo : [String] # array of message-ids references : [String] # array of message-ids text : String # message content as text html : String # message content as html date : Date # message date priority : String # message priority ignoreInCount : Boolean # whether or not to count this message # in account values binary : cozydb.NoSchema attachments : [MailAttachment] alternatives : cozydb.NoSchema # for calendar content # Public: fetch a list of message # # ids - {Array} of {String} message ids # # Returns (callback) {Array} of {Message} the fetched messages in same order @findMultiple: (ids, callback) -> async.mapSeries ids, (id, cb) -> Message.find id, cb , callback # Public: from a list of messages, choses the conversation ID # Take a list of messageid -> conversationID, pick the most used # and updates all messages to have the same. # # rows - [{Object}] key=messageID, value=conversationID # # Returns (callback) {String} the chosen conversation ID @pickConversationID: (rows, callback) -> log.debug "pickConversationID" conversationIDCounts = {} for row in rows conversationIDCounts[row.value] ?= 1 conversationIDCounts[row.value]++ pickedConversationID = null pickedConversationIDCount = 0 # find the most used conversationID for conversationID, count of conversationIDCounts if count > pickedConversationIDCount pickedConversationID = conversationID pickedConversationIDCount = count # if its undefined, we create one (UUID) unless pickedConversationID? and pickedConversationID isnt 'undefined' pickedConversationID = uuid.v4() change = conversationID: pickedConversationID # we update all messages to the new conversationID async.eachSeries rows, (row, cb) -> return cb null if row.value is pickedConversationID Message.find row.id, (err, message) -> log.warn "Cant get message #{row.id}, ignoring" if err if err or message.conversationID is pickedConversationID cb null else message.updateAttributes change, cb , (err) -> return callback err if err callback null, pickedConversationID # Public: get a message conversation ID. # Select the method if the message has references or by subject, # the uses {.pickConversationID} to unify and chose the conversationID # # mail - {Object} the raw node-imap mail # # Returns (callback) {String} the chosen conversation ID @findConversationID: (mail, callback) -> log.debug "findConversationID" # is reply or forward subject = mail.subject isReplyOrForward = subject and mailutils.isReplyOrForward subject # try to find by references references = mail.references or [] references.concat mail.inReplyTo or [] references = references.map mailutils.normalizeMessageID .filter (mid) -> mid # ignore unparsable messageID log.debug "findConversationID", references, mail.normSubject, isReplyOrForward if references.length # find all messages in references keys = references.map (mid) -> [mail.accountID, 'mid', mid] Message.rawRequest 'dedupRequest', {keys}, (err, rows) -> return callback err if err log.debug ' found = ',rows?.length Message.pickConversationID rows, callback # no references, try to find by subject # @TODO : handle the unlikely case where we got a reply # before the original message else if mail.normSubject?.length > 3 and isReplyOrForward key = [mail.accountID, 'subject', mail.normSubject] Message.rawRequest 'dedupRequest', {key}, (err, rows) -> return callback err if err log.debug "found similar", rows.length Message.pickConversationID rows, callback # give it a random uid else callback null, uuid.v4() # Public: get messages in cozy by their uids # # mailboxID - {String} id of the mailbox to check # # Returns (callback) an {Array} of {String} uids in the cozy @UIDsInCozy: (mailboxID, callback) -> # Public: find a message by its message id # # accountID - id of the account to scan # messageID - message-id to search, no need to normalize # # Returns (callback) {Message} the first message with this Message-ID @byMessageID: (accountID, messageID, callback) -> messageID = mailutils.normalizeMessageID messageID Message.rawRequest 'dedupRequest', key: [accountID, 'mid', messageID] include_docs: true , (err, rows) -> return callback err if err message = rows[0]?.doc message = new Message message if message callback null, message # Public: get lengths of multiple conversations # # conversationIDs - [String] id of the conversations # # Returns (callback) an {Object} with conversationsIDs as keys and # counts as values @getConversationLengths: (conversationIDs, callback) -> Message.rawRequest 'byConversationID', keys: conversationIDs group: true reduce: true , (err, rows) -> return callback err if err out = {} out[row.key] = row.value for row in rows callback null, out # Public: find messages by there conversation-id # # conversationID - id of the conversation to fetch # # Returns (callback) an {Array} of {Message} @byConversationID: (conversationID, callback) -> Message.byConversationIDs [conversationID], callback # Public: find messages by multiple conversation-id # # conversationIDs - {Array} of {String} id of the conversations to fetch # # Returns (callback) an {Array} of {Message} @byConversationIDs: (conversationIDs, callback) -> Message.rawRequest 'byConversationID', keys: conversationIDs reduce: false include_docs: true , (err, rows) -> return callback err if err messages = rows.map (row) -> try new Message row.doc catch err log.error "Wrong message", err, row.doc return null callback null, messages # Public: remove a message from a mailbox. # Uses {::removeFromMailbox} # # id - {String} id of the message # box - {Mailbox} mailbox to remove From # # Returns (callback) the updated {Message} @removeFromMailbox: (id, box, callback) -> log.debug "removeFromMailbox", id, box.label Message.find id, (err, message) -> return callback err if err return callback new NotFound "Message #{id}" unless message message.removeFromMailbox box, false, callback # Public: get messages in a box depending on the query params # # mailboxID - {String} the mailbox's ID # params - query's options # callback - Function(err, [{Message}]) # # Returns (callback) an {Object} with properties # :messages - the result of {.getResults} # :count - the result of {.getCount} # :conversationLengths - length of conversations in the result @getResultsAndCount: (mailboxID, params, callback) -> params.flag ?= null if params.descending [params.before, params.after] = [params.after, params.before] async.parallel [ (cb) -> Message.getCount mailboxID, params, cb (cb) -> Message.getResults mailboxID, params, cb ], (err, results) -> return callback err if err [count, messages] = results conversationIDs = _.uniq _.pluck messages, 'conversationID' Message.getConversationLengths conversationIDs, (err, lengths) -> return callback err if err callback null, messages: messages count: count conversationLengths: lengths # Public: get messages in a box depending on the query params # # mailboxID - {String} the mailbox's ID # params - query's options # # Returns (callback) an {Array} of {Message} @getResults: (mailboxID, params, callback) -> {before, after, descending, sortField, flag} = params skip = 0 if sortField is 'from' or sortField is 'dest' if params.resultsAfter? skip = params.resultsAfter startkey = [sortField, mailboxID, flag, before, null] endkey = [sortField, mailboxID, flag, after, null] else if params.resultsAfter? startkey = [sortField, mailboxID, flag, params.resultsAfter] else startkey = [sortField, mailboxID, flag, before] endkey = [sortField, mailboxID, flag, after] requestOptions = descending: descending startkey: startkey endkey: endkey reduce: false skip: skip include_docs: true limit: MSGBYPAGE Message.rawRequest 'byMailboxRequest', requestOptions , (err, rows) -> return callback err if err callback null, rows.map (row) -> new Message row.doc # Public: get number of messages in a box, depending on the query params # # mailboxID - {String} the mailbox's ID # params - query's options # # Returns (callback) {Number} of messages in the search @getCount: (mailboxID, params, callback) -> {before, after, descending, sortField, flag} = params Message.rawRequest 'byMailboxRequest', descending: descending startkey: [sortField, mailboxID, flag, before] endkey: [sortField, mailboxID, flag, after] reduce: true group_level: 2 , (err, rows) -> return callback err if err callback null, rows[0]?.value or 0 # Public: create or update a message # # message - {Message} the mailbox's ID # # Returns (callback) {Message} the updated / created message @updateOrCreate: (message, callback) -> log.debug "create or update" if message.id Message.find message.id, (err, existing) -> log.debug "update" if err callback err else if not existing callback new NotFound "Message #{message.id}" else # prevent overiding of binary message.binary = existing.binary existing.updateAttributes message, callback else log.debug "create" Message.create message, callback # Public: check if a message is already in cozy by its mid. # If it is update it with {::markTwin} or {::addToMailbox}, else fetch it. # # box - {Mailbox} the box to create this message in # msg - {Object} the msg # :mid - {String} Message-id # :uid - {String} the uid # ignoreInCount - {Boolean} mark this message as ignored in counts. # # Returns (callback) {Object} information about what happened # :shouldNotif - {Boolean} whether a new unread message was added # :actuallyAdded - {Boolean} whether a message was actually added @fetchOrUpdate: (box, msg, callback) -> {mid, uid} = msg log.debug "fetchOrUpdate", box.id, mid, uid Message.byMessageID box.accountID, mid, (err, existing) -> return callback err if err if existing and not existing.isInMailbox box log.debug " add" existing.addToMailbox box, uid, callback else if existing # this is the weird case when a message is in the box # under two different UIDs log.debug " twin" existing.markTwin box, uid, callback else log.debug " fetch" Message.fetchOneMail box, uid, callback @fetchOneMail: (box, uid, callback) -> box.doLaterWithBox (imap, imapbox, cb) -> imap.fetchOneMail uid, cb , (err, mail) -> return callback err if err shouldNotif = '\\Seen' in (mail.flags or []) Message.createFromImapMessage mail, box, uid, (err) -> return callback err if err callback null, {shouldNotif: shouldNotif, actuallyAdded: true} # Public: mark a message has having a twin (2 messages with same MID, # but different UID) in the same box so they can be smartly handled at # deletion. # # box - {Mailbox} the mailbox # # Returns (callback) {Object} information about what happened # :shouldNotif - {Boolean} always false # :actuallyAdded - {Boolean} wheter a message was actually added markTwin: (box, uid, callback) -> hasTwin = @hasTwin or [] twinMailboxIDs = @twinMailboxIDs or {} twinMailboxIDsBox = twinMailboxIDs[box.id] or [] if box.id in hasTwin and uid in twinMailboxIDsBox # already noted callback null, {shouldNotif: false, actuallyAdded: false} else if box.id in hasTwin # the message was marked as twin before the introduction of # twinMailboxIDs twinMailboxIDs[box.id] ?= [] twinMailboxIDs[box.id].push uid @updateAttributes {twinMailboxIDs}, (err) -> callback err, {shouldNotif: false, actuallyAdded: true} else hasTwin.push box.id twinMailboxIDs[box.id] ?= [] twinMailboxIDs[box.id].push uid @updateAttributes {hasTwin, twinMailboxIDs}, (err) -> callback err, {shouldNotif: false, actuallyAdded: true} # Public: add the message to a mailbox in the cozy # # box - {Mailbox} to add this message to # uid - {Number} uid of the message in the mailbox # callback - Function(err, {Message} updated) # # Returns (callback) {Object} information about what happened # :shouldNotif - {Boolean} always false # :actuallyAdded - {Boolean} always true addToMailbox: (box, uid, callback) -> log.info "MAIL #{box.path}:#{uid} ADDED TO BOX" mailboxIDs = {} mailboxIDs[key] = value for key, value of @mailboxIDs or {} mailboxIDs[box.id] = uid changes = {mailboxIDs} changes.ignoreInCount = box.ignoreInCount() @updateAttributes changes, (err) -> callback err, {shouldNotif: false, actuallyAdded: true} # Public: helper to check if a message is in a box # # box - {Mailbox} the mailbox # # Returns {Boolean} whether this message is in the box or not isInMailbox: (box) -> return @mailboxIDs[box.id]? and @mailboxIDs[box.id] isnt -1 # Public: remove a message from a mailbox in the cozy # if the message becomes an orphan, we destroy it # # box - {Mailbox} to remove this message from # noDestroy - {Boolean} dont destroy orphan messages # # Returns (callback) the updated {Message} removeFromMailbox: (box, noDestroy = false, callback) -> log.debug ".removeFromMailbox", @id, box.label callback = noDestroy unless callback changes = {} changed = false if box.id of (@mailboxIDs or {}) changes.mailboxIDs = _.omit @mailboxIDs, box.id changed = true if box.id of (@twinMailboxIDs or {}) changes.twinMailboxIDs = _.omit @twinMailboxIDs, box.id changed = true if changed boxes = Object.keys(changes.mailboxIDs or @mailboxIDs) isOrphan = boxes.length is 0 log.debug "REMOVING #{@id}, NOW ORPHAN = ", isOrphan if isOrphan and not noDestroy then @destroy callback else @updateAttributes changes, callback else setImmediate callback # Public: Create a message from a raw imap message. # Handle attachments and normalization of message ids and subjects. # # mail - an node-imap mail {Object} # box - {Mailbox} to create the message in # uid - {Number} UID of the message in the box # # Returns (callback) at completion @createFromImapMessage: (mail, box, uid, callback) -> log.info "createFromImapMessage", box.label, uid log.debug 'flags = ', mail.flags # we store the box & account id mail.accountID = box.accountID mail.ignoreInCount = box.ignoreInCount() mail.mailboxIDs = {} mail.mailboxIDs[box._id] = uid # we store normalized versions of subject & messageID for threading messageID = mail.headers['message-id'] delete mail.messageId # reported bug : if a mail has two messageID, mailparser make it # an array and it crashes the server if messageID and messageID instanceof Array messageID = messageID[0] if messageID mail.messageID = mailutils.normalizeMessageID messageID if mail.subject mail.normSubject = mailutils.normalizeSubject mail.subject # @TODO, find and parse from mail.headers ? mail.replyTo ?= [] mail.cc ?= [] mail.bcc ?= [] mail.to ?= [] mail.from ?= [] if not mail.date? mail.date = new Date().toISOString() # we extract the attachments buffers # @TODO : directly create binaries ? (first step for streaming) attachments = [] if mail.attachments attachments = mail.attachments.map (att) -> buffer = att.content delete att.content return out = name: att.generatedFileName buffer: buffer # pick a method to find the conversation id # if there is a x-gm-thrid, use it # else find the thread using References or Subject Message.findConversationID mail, (err, conversationID) -> return callback err if err mail.conversationID = conversationID Message.create mail, (err, jdbMessage) -> return callback err if err jdbMessage.storeAttachments attachments, callback # Public: Store the node-imap attachment to the cozy message # # attachments - an {Array} of {Object}(name, buffer) # # Returns (callback) at completion storeAttachments: (attachments, callback) -> log.debug "storeAttachments" async.eachSeries attachments, (att, cb) => # WEIRDFIX#1 - some attachments name are broken # WEIRDFIX#2 - some attachments have no buffer # att.name = att.name.replace "\ufffd", "" att.buffer ?= new Buffer 0 @attachBinary att.buffer, name: att.name, cb , callback # Public: get this message formatted for the client. # Generate html & text appropriately and give each # attachment an URL. # # Returns (callback) {Object} the formatted message toClientObject: -> # log.debug "toClientObject" raw = @toObject() raw.attachments?.forEach (file) -> encodedFileName = encodeURIComponent file.generatedFileName file.url = "message/#{raw.id}/attachments/#{encodedFileName}" if raw.html? attachments = raw.attachments or [] raw.html = mailutils.sanitizeHTML raw.html, raw.id, attachments if not raw.text? and raw.html? try raw.text = htmlToText.fromString raw.html, tables: true wordwrap: 80 catch err log.error "Error converting HTML to text", err, raw.html return raw @doGroupedByBox: (messages, iterator, done) -> return done null if messages.length is 0 accountID = messages[0].accountID messagesByBoxID = {} for message in messages for boxID, uid of message.mailboxIDs messagesByBoxID[boxID] ?= [] messagesByBoxID[boxID].push message state = {} async.eachSeries Object.keys(messagesByBoxID), (boxID, next) -> state.box = ramStore.getMailbox boxID state.messagesInBox = messagesByBoxID[boxID] iterator2 = (imap, imapBox, releaseImap) -> state.imapBox = imapBox state.uids = state.messagesInBox.map (msg) -> msg.mailboxIDs[state.box.id] iterator imap, state, releaseImap pool = ramStore.getImapPool(messages[0]) if not pool return done new BadRequest "Pool isn't defined" pool.doASAPWithBox state.box, iterator2, next , done @batchAddFlag: (messages, flag, callback) -> # dont add flag twice messages = messages.filter (msg) -> flag not in msg.flags Message.doGroupedByBox messages, (imap, state, next) -> imap.addFlags state.uids, flag, next , (err) -> return callback err if err async.mapSeries messages, (message, next) -> newflags = message.flags.concat flag message.updateAttributes flags: newflags, (err) -> next err, message , callback @batchRemoveFlag: (messages, flag, callback) -> # dont remove flag if it wasnt messages = messages.filter (msg) -> flag in msg.flags Message.doGroupedByBox messages, (imap, state, next) -> imap.delFlags state.uids, flag, next , (err) -> return callback err if err async.mapSeries messages, (message, next) -> newflags = _.without message.flags, flag message.updateAttributes flags: newflags, (err) -> next err, message , callback cloneMailboxIDs: -> out = {} out[boxID] = uid for boxID, uid of @mailboxIDs return out # Public: wether or not this message # is a draft. Consider a message a draft if it is in Draftbox or has # the \\Draft flag # # Returns {Bollean} is this message a draft ? isDraft: (draftBoxID) -> @mailboxIDs[draftBoxID]? or '\\Draft' in @flags module.exports = Message mailutils = require '../utils/jwz_tools' CONSTANTS = require '../utils/constants' {MSGBYPAGE, LIMIT_DESTROY, CONCURRENT_DESTROY} = CONSTANTS {NotFound, BadRequest, AccountConfigError} = require '../utils/errors' uuid = require 'uuid' _ = require 'lodash' async = require 'async' log = require('../utils/logging')(prefix: 'models:message') htmlToText = require 'html-to-text' require('./model-events').wrapModel Message ramStore = require './store_account_and_boxes'
85063
cozydb = require 'cozydb' # Public: a mail address, used in {Message} schema class MailAdress extends cozydb.Model @schema: name: String address: String class MailAttachment extends cozydb.Model @schema: cozydb.NoSchema # Public: Message module.exports = class Message extends cozydb.CozyModel @docType: 'Message' @schema: accountID : String # account this message belongs to messageID : String # normalized message-id (no <"">) normSubject : String # normalized subject (no Re: ...) conversationID : String # all message in thread have same # conversationID mailboxIDs : cozydb.NoSchema # mailboxes as an hash # {boxID: uid, boxID2 : uid2} hasTwin : [String] # [String] mailboxIDs where this # message has twin twinMailboxIDs : cozydb.NoSchema # mailboxes as an hash of array flags : [String] # [String] flags of the message headers : cozydb.NoSchema # hash of the message headers from : [MailAdress] # array of {name, address} to : [MailAdress] # array of {name, address} cc : [MailAdress] # array of {name, address} bcc : [MailAdress] # array of {name, address} replyTo : [MailAdress] # array of {name, address} subject : String # subject of the message inReplyTo : [String] # array of message-ids references : [String] # array of message-ids text : String # message content as text html : String # message content as html date : Date # message date priority : String # message priority ignoreInCount : Boolean # whether or not to count this message # in account values binary : cozydb.NoSchema attachments : [MailAttachment] alternatives : cozydb.NoSchema # for calendar content # Public: fetch a list of message # # ids - {Array} of {String} message ids # # Returns (callback) {Array} of {Message} the fetched messages in same order @findMultiple: (ids, callback) -> async.mapSeries ids, (id, cb) -> Message.find id, cb , callback # Public: from a list of messages, choses the conversation ID # Take a list of messageid -> conversationID, pick the most used # and updates all messages to have the same. # # rows - [{Object}] key=messageID, value=conversationID # # Returns (callback) {String} the chosen conversation ID @pickConversationID: (rows, callback) -> log.debug "pickConversationID" conversationIDCounts = {} for row in rows conversationIDCounts[row.value] ?= 1 conversationIDCounts[row.value]++ pickedConversationID = null pickedConversationIDCount = 0 # find the most used conversationID for conversationID, count of conversationIDCounts if count > pickedConversationIDCount pickedConversationID = conversationID pickedConversationIDCount = count # if its undefined, we create one (UUID) unless pickedConversationID? and pickedConversationID isnt 'undefined' pickedConversationID = uuid.v4() change = conversationID: pickedConversationID # we update all messages to the new conversationID async.eachSeries rows, (row, cb) -> return cb null if row.value is pickedConversationID Message.find row.id, (err, message) -> log.warn "Cant get message #{row.id}, ignoring" if err if err or message.conversationID is pickedConversationID cb null else message.updateAttributes change, cb , (err) -> return callback err if err callback null, pickedConversationID # Public: get a message conversation ID. # Select the method if the message has references or by subject, # the uses {.pickConversationID} to unify and chose the conversationID # # mail - {Object} the raw node-imap mail # # Returns (callback) {String} the chosen conversation ID @findConversationID: (mail, callback) -> log.debug "findConversationID" # is reply or forward subject = mail.subject isReplyOrForward = subject and mailutils.isReplyOrForward subject # try to find by references references = mail.references or [] references.concat mail.inReplyTo or [] references = references.map mailutils.normalizeMessageID .filter (mid) -> mid # ignore unparsable messageID log.debug "findConversationID", references, mail.normSubject, isReplyOrForward if references.length # find all messages in references keys = <KEY> (mid) -> [<KEY> <KEY> Message.rawRequest 'dedupRequest', {keys}, (err, rows) -> return callback err if err log.debug ' found = ',rows?.length Message.pickConversationID rows, callback # no references, try to find by subject # @TODO : handle the unlikely case where we got a reply # before the original message else if mail.normSubject?.length > 3 and isReplyOrForward key = [mail.<KEY>, 'subject', mail.normSubject] Message.rawRequest 'dedupRequest', {key}, (err, rows) -> return callback err if err log.debug "found similar", rows.length Message.pickConversationID rows, callback # give it a random uid else callback null, uuid.v4() # Public: get messages in cozy by their uids # # mailboxID - {String} id of the mailbox to check # # Returns (callback) an {Array} of {String} uids in the cozy @UIDsInCozy: (mailboxID, callback) -> # Public: find a message by its message id # # accountID - id of the account to scan # messageID - message-id to search, no need to normalize # # Returns (callback) {Message} the first message with this Message-ID @byMessageID: (accountID, messageID, callback) -> messageID = mailutils.normalizeMessageID messageID Message.rawRequest 'dedupRequest', key: [accountID, 'mid', messageID] include_docs: true , (err, rows) -> return callback err if err message = rows[0]?.doc message = new Message message if message callback null, message # Public: get lengths of multiple conversations # # conversationIDs - [String] id of the conversations # # Returns (callback) an {Object} with conversationsIDs as keys and # counts as values @getConversationLengths: (conversationIDs, callback) -> Message.rawRequest 'byConversationID', keys: conversationIDs group: true reduce: true , (err, rows) -> return callback err if err out = {} out[row.key] = row.value for row in rows callback null, out # Public: find messages by there conversation-id # # conversationID - id of the conversation to fetch # # Returns (callback) an {Array} of {Message} @byConversationID: (conversationID, callback) -> Message.byConversationIDs [conversationID], callback # Public: find messages by multiple conversation-id # # conversationIDs - {Array} of {String} id of the conversations to fetch # # Returns (callback) an {Array} of {Message} @byConversationIDs: (conversationIDs, callback) -> Message.rawRequest 'byConversationID', keys: conversationIDs reduce: false include_docs: true , (err, rows) -> return callback err if err messages = rows.map (row) -> try new Message row.doc catch err log.error "Wrong message", err, row.doc return null callback null, messages # Public: remove a message from a mailbox. # Uses {::removeFromMailbox} # # id - {String} id of the message # box - {Mailbox} mailbox to remove From # # Returns (callback) the updated {Message} @removeFromMailbox: (id, box, callback) -> log.debug "removeFromMailbox", id, box.label Message.find id, (err, message) -> return callback err if err return callback new NotFound "Message #{id}" unless message message.removeFromMailbox box, false, callback # Public: get messages in a box depending on the query params # # mailboxID - {String} the mailbox's ID # params - query's options # callback - Function(err, [{Message}]) # # Returns (callback) an {Object} with properties # :messages - the result of {.getResults} # :count - the result of {.getCount} # :conversationLengths - length of conversations in the result @getResultsAndCount: (mailboxID, params, callback) -> params.flag ?= null if params.descending [params.before, params.after] = [params.after, params.before] async.parallel [ (cb) -> Message.getCount mailboxID, params, cb (cb) -> Message.getResults mailboxID, params, cb ], (err, results) -> return callback err if err [count, messages] = results conversationIDs = _.uniq _.pluck messages, 'conversationID' Message.getConversationLengths conversationIDs, (err, lengths) -> return callback err if err callback null, messages: messages count: count conversationLengths: lengths # Public: get messages in a box depending on the query params # # mailboxID - {String} the mailbox's ID # params - query's options # # Returns (callback) an {Array} of {Message} @getResults: (mailboxID, params, callback) -> {before, after, descending, sortField, flag} = params skip = 0 if sortField is 'from' or sortField is 'dest' if params.resultsAfter? skip = params.resultsAfter startkey = [sortField, mailboxID, flag, before, null] endkey = [sortField, mailboxID, flag, after, null] else if params.resultsAfter? startkey = [sortField, mailboxID, flag, params.resultsAfter] else startkey = [sortField, mailboxID, flag, before] endkey = [sortField, mailboxID, flag, after] requestOptions = descending: descending startkey: startkey endkey: endkey reduce: false skip: skip include_docs: true limit: MSGBYPAGE Message.rawRequest 'byMailboxRequest', requestOptions , (err, rows) -> return callback err if err callback null, rows.map (row) -> new Message row.doc # Public: get number of messages in a box, depending on the query params # # mailboxID - {String} the mailbox's ID # params - query's options # # Returns (callback) {Number} of messages in the search @getCount: (mailboxID, params, callback) -> {before, after, descending, sortField, flag} = params Message.rawRequest 'byMailboxRequest', descending: descending startkey: [sortField, mailboxID, flag, before] endkey: [sortField, mailboxID, flag, after] reduce: true group_level: 2 , (err, rows) -> return callback err if err callback null, rows[0]?.value or 0 # Public: create or update a message # # message - {Message} the mailbox's ID # # Returns (callback) {Message} the updated / created message @updateOrCreate: (message, callback) -> log.debug "create or update" if message.id Message.find message.id, (err, existing) -> log.debug "update" if err callback err else if not existing callback new NotFound "Message #{message.id}" else # prevent overiding of binary message.binary = existing.binary existing.updateAttributes message, callback else log.debug "create" Message.create message, callback # Public: check if a message is already in cozy by its mid. # If it is update it with {::markTwin} or {::addToMailbox}, else fetch it. # # box - {Mailbox} the box to create this message in # msg - {Object} the msg # :mid - {String} Message-id # :uid - {String} the uid # ignoreInCount - {Boolean} mark this message as ignored in counts. # # Returns (callback) {Object} information about what happened # :shouldNotif - {Boolean} whether a new unread message was added # :actuallyAdded - {Boolean} whether a message was actually added @fetchOrUpdate: (box, msg, callback) -> {mid, uid} = msg log.debug "fetchOrUpdate", box.id, mid, uid Message.byMessageID box.accountID, mid, (err, existing) -> return callback err if err if existing and not existing.isInMailbox box log.debug " add" existing.addToMailbox box, uid, callback else if existing # this is the weird case when a message is in the box # under two different UIDs log.debug " twin" existing.markTwin box, uid, callback else log.debug " fetch" Message.fetchOneMail box, uid, callback @fetchOneMail: (box, uid, callback) -> box.doLaterWithBox (imap, imapbox, cb) -> imap.fetchOneMail uid, cb , (err, mail) -> return callback err if err shouldNotif = '\\Seen' in (mail.flags or []) Message.createFromImapMessage mail, box, uid, (err) -> return callback err if err callback null, {shouldNotif: shouldNotif, actuallyAdded: true} # Public: mark a message has having a twin (2 messages with same MID, # but different UID) in the same box so they can be smartly handled at # deletion. # # box - {Mailbox} the mailbox # # Returns (callback) {Object} information about what happened # :shouldNotif - {Boolean} always false # :actuallyAdded - {Boolean} wheter a message was actually added markTwin: (box, uid, callback) -> hasTwin = @hasTwin or [] twinMailboxIDs = @twinMailboxIDs or {} twinMailboxIDsBox = twinMailboxIDs[box.id] or [] if box.id in hasTwin and uid in twinMailboxIDsBox # already noted callback null, {shouldNotif: false, actuallyAdded: false} else if box.id in hasTwin # the message was marked as twin before the introduction of # twinMailboxIDs twinMailboxIDs[box.id] ?= [] twinMailboxIDs[box.id].push uid @updateAttributes {twinMailboxIDs}, (err) -> callback err, {shouldNotif: false, actuallyAdded: true} else hasTwin.push box.id twinMailboxIDs[box.id] ?= [] twinMailboxIDs[box.id].push uid @updateAttributes {hasTwin, twinMailboxIDs}, (err) -> callback err, {shouldNotif: false, actuallyAdded: true} # Public: add the message to a mailbox in the cozy # # box - {Mailbox} to add this message to # uid - {Number} uid of the message in the mailbox # callback - Function(err, {Message} updated) # # Returns (callback) {Object} information about what happened # :shouldNotif - {Boolean} always false # :actuallyAdded - {Boolean} always true addToMailbox: (box, uid, callback) -> log.info "MAIL #{box.path}:#{uid} ADDED TO BOX" mailboxIDs = {} mailboxIDs[key] = value for key, value of @mailboxIDs or {} mailboxIDs[box.id] = uid changes = {mailboxIDs} changes.ignoreInCount = box.ignoreInCount() @updateAttributes changes, (err) -> callback err, {shouldNotif: false, actuallyAdded: true} # Public: helper to check if a message is in a box # # box - {Mailbox} the mailbox # # Returns {Boolean} whether this message is in the box or not isInMailbox: (box) -> return @mailboxIDs[box.id]? and @mailboxIDs[box.id] isnt -1 # Public: remove a message from a mailbox in the cozy # if the message becomes an orphan, we destroy it # # box - {Mailbox} to remove this message from # noDestroy - {Boolean} dont destroy orphan messages # # Returns (callback) the updated {Message} removeFromMailbox: (box, noDestroy = false, callback) -> log.debug ".removeFromMailbox", @id, box.label callback = noDestroy unless callback changes = {} changed = false if box.id of (@mailboxIDs or {}) changes.mailboxIDs = _.omit @mailboxIDs, box.id changed = true if box.id of (@twinMailboxIDs or {}) changes.twinMailboxIDs = _.omit @twinMailboxIDs, box.id changed = true if changed boxes = Object.keys(changes.mailboxIDs or @mailboxIDs) isOrphan = boxes.length is 0 log.debug "REMOVING #{@id}, NOW ORPHAN = ", isOrphan if isOrphan and not noDestroy then @destroy callback else @updateAttributes changes, callback else setImmediate callback # Public: Create a message from a raw imap message. # Handle attachments and normalization of message ids and subjects. # # mail - an node-imap mail {Object} # box - {Mailbox} to create the message in # uid - {Number} UID of the message in the box # # Returns (callback) at completion @createFromImapMessage: (mail, box, uid, callback) -> log.info "createFromImapMessage", box.label, uid log.debug 'flags = ', mail.flags # we store the box & account id mail.accountID = box.accountID mail.ignoreInCount = box.ignoreInCount() mail.mailboxIDs = {} mail.mailboxIDs[box._id] = uid # we store normalized versions of subject & messageID for threading messageID = mail.headers['message-id'] delete mail.messageId # reported bug : if a mail has two messageID, mailparser make it # an array and it crashes the server if messageID and messageID instanceof Array messageID = messageID[0] if messageID mail.messageID = mailutils.normalizeMessageID messageID if mail.subject mail.normSubject = mailutils.normalizeSubject mail.subject # @TODO, find and parse from mail.headers ? mail.replyTo ?= [] mail.cc ?= [] mail.bcc ?= [] mail.to ?= [] mail.from ?= [] if not mail.date? mail.date = new Date().toISOString() # we extract the attachments buffers # @TODO : directly create binaries ? (first step for streaming) attachments = [] if mail.attachments attachments = mail.attachments.map (att) -> buffer = att.content delete att.content return out = name: att.generatedFileName buffer: buffer # pick a method to find the conversation id # if there is a x-gm-thrid, use it # else find the thread using References or Subject Message.findConversationID mail, (err, conversationID) -> return callback err if err mail.conversationID = conversationID Message.create mail, (err, jdbMessage) -> return callback err if err jdbMessage.storeAttachments attachments, callback # Public: Store the node-imap attachment to the cozy message # # attachments - an {Array} of {Object}(name, buffer) # # Returns (callback) at completion storeAttachments: (attachments, callback) -> log.debug "storeAttachments" async.eachSeries attachments, (att, cb) => # WEIRDFIX#1 - some attachments name are broken # WEIRDFIX#2 - some attachments have no buffer # att.name = att.name.replace "\ufffd", "" att.buffer ?= new Buffer 0 @attachBinary att.buffer, name: att.name, cb , callback # Public: get this message formatted for the client. # Generate html & text appropriately and give each # attachment an URL. # # Returns (callback) {Object} the formatted message toClientObject: -> # log.debug "toClientObject" raw = @toObject() raw.attachments?.forEach (file) -> encodedFileName = encodeURIComponent file.generatedFileName file.url = "message/#{raw.id}/attachments/#{encodedFileName}" if raw.html? attachments = raw.attachments or [] raw.html = mailutils.sanitizeHTML raw.html, raw.id, attachments if not raw.text? and raw.html? try raw.text = htmlToText.fromString raw.html, tables: true wordwrap: 80 catch err log.error "Error converting HTML to text", err, raw.html return raw @doGroupedByBox: (messages, iterator, done) -> return done null if messages.length is 0 accountID = messages[0].accountID messagesByBoxID = {} for message in messages for boxID, uid of message.mailboxIDs messagesByBoxID[boxID] ?= [] messagesByBoxID[boxID].push message state = {} async.eachSeries Object.keys(messagesByBoxID), (boxID, next) -> state.box = ramStore.getMailbox boxID state.messagesInBox = messagesByBoxID[boxID] iterator2 = (imap, imapBox, releaseImap) -> state.imapBox = imapBox state.uids = state.messagesInBox.map (msg) -> msg.mailboxIDs[state.box.id] iterator imap, state, releaseImap pool = ramStore.getImapPool(messages[0]) if not pool return done new BadRequest "Pool isn't defined" pool.doASAPWithBox state.box, iterator2, next , done @batchAddFlag: (messages, flag, callback) -> # dont add flag twice messages = messages.filter (msg) -> flag not in msg.flags Message.doGroupedByBox messages, (imap, state, next) -> imap.addFlags state.uids, flag, next , (err) -> return callback err if err async.mapSeries messages, (message, next) -> newflags = message.flags.concat flag message.updateAttributes flags: newflags, (err) -> next err, message , callback @batchRemoveFlag: (messages, flag, callback) -> # dont remove flag if it wasnt messages = messages.filter (msg) -> flag in msg.flags Message.doGroupedByBox messages, (imap, state, next) -> imap.delFlags state.uids, flag, next , (err) -> return callback err if err async.mapSeries messages, (message, next) -> newflags = _.without message.flags, flag message.updateAttributes flags: newflags, (err) -> next err, message , callback cloneMailboxIDs: -> out = {} out[boxID] = uid for boxID, uid of @mailboxIDs return out # Public: wether or not this message # is a draft. Consider a message a draft if it is in Draftbox or has # the \\Draft flag # # Returns {Bollean} is this message a draft ? isDraft: (draftBoxID) -> @mailboxIDs[draftBoxID]? or '\\Draft' in @flags module.exports = Message mailutils = require '../utils/jwz_tools' CONSTANTS = require '../utils/constants' {MSGBYPAGE, LIMIT_DESTROY, CONCURRENT_DESTROY} = CONSTANTS {NotFound, BadRequest, AccountConfigError} = require '../utils/errors' uuid = require 'uuid' _ = require 'lodash' async = require 'async' log = require('../utils/logging')(prefix: 'models:message') htmlToText = require 'html-to-text' require('./model-events').wrapModel Message ramStore = require './store_account_and_boxes'
true
cozydb = require 'cozydb' # Public: a mail address, used in {Message} schema class MailAdress extends cozydb.Model @schema: name: String address: String class MailAttachment extends cozydb.Model @schema: cozydb.NoSchema # Public: Message module.exports = class Message extends cozydb.CozyModel @docType: 'Message' @schema: accountID : String # account this message belongs to messageID : String # normalized message-id (no <"">) normSubject : String # normalized subject (no Re: ...) conversationID : String # all message in thread have same # conversationID mailboxIDs : cozydb.NoSchema # mailboxes as an hash # {boxID: uid, boxID2 : uid2} hasTwin : [String] # [String] mailboxIDs where this # message has twin twinMailboxIDs : cozydb.NoSchema # mailboxes as an hash of array flags : [String] # [String] flags of the message headers : cozydb.NoSchema # hash of the message headers from : [MailAdress] # array of {name, address} to : [MailAdress] # array of {name, address} cc : [MailAdress] # array of {name, address} bcc : [MailAdress] # array of {name, address} replyTo : [MailAdress] # array of {name, address} subject : String # subject of the message inReplyTo : [String] # array of message-ids references : [String] # array of message-ids text : String # message content as text html : String # message content as html date : Date # message date priority : String # message priority ignoreInCount : Boolean # whether or not to count this message # in account values binary : cozydb.NoSchema attachments : [MailAttachment] alternatives : cozydb.NoSchema # for calendar content # Public: fetch a list of message # # ids - {Array} of {String} message ids # # Returns (callback) {Array} of {Message} the fetched messages in same order @findMultiple: (ids, callback) -> async.mapSeries ids, (id, cb) -> Message.find id, cb , callback # Public: from a list of messages, choses the conversation ID # Take a list of messageid -> conversationID, pick the most used # and updates all messages to have the same. # # rows - [{Object}] key=messageID, value=conversationID # # Returns (callback) {String} the chosen conversation ID @pickConversationID: (rows, callback) -> log.debug "pickConversationID" conversationIDCounts = {} for row in rows conversationIDCounts[row.value] ?= 1 conversationIDCounts[row.value]++ pickedConversationID = null pickedConversationIDCount = 0 # find the most used conversationID for conversationID, count of conversationIDCounts if count > pickedConversationIDCount pickedConversationID = conversationID pickedConversationIDCount = count # if its undefined, we create one (UUID) unless pickedConversationID? and pickedConversationID isnt 'undefined' pickedConversationID = uuid.v4() change = conversationID: pickedConversationID # we update all messages to the new conversationID async.eachSeries rows, (row, cb) -> return cb null if row.value is pickedConversationID Message.find row.id, (err, message) -> log.warn "Cant get message #{row.id}, ignoring" if err if err or message.conversationID is pickedConversationID cb null else message.updateAttributes change, cb , (err) -> return callback err if err callback null, pickedConversationID # Public: get a message conversation ID. # Select the method if the message has references or by subject, # the uses {.pickConversationID} to unify and chose the conversationID # # mail - {Object} the raw node-imap mail # # Returns (callback) {String} the chosen conversation ID @findConversationID: (mail, callback) -> log.debug "findConversationID" # is reply or forward subject = mail.subject isReplyOrForward = subject and mailutils.isReplyOrForward subject # try to find by references references = mail.references or [] references.concat mail.inReplyTo or [] references = references.map mailutils.normalizeMessageID .filter (mid) -> mid # ignore unparsable messageID log.debug "findConversationID", references, mail.normSubject, isReplyOrForward if references.length # find all messages in references keys = PI:KEY:<KEY>END_PI (mid) -> [PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI Message.rawRequest 'dedupRequest', {keys}, (err, rows) -> return callback err if err log.debug ' found = ',rows?.length Message.pickConversationID rows, callback # no references, try to find by subject # @TODO : handle the unlikely case where we got a reply # before the original message else if mail.normSubject?.length > 3 and isReplyOrForward key = [mail.PI:KEY:<KEY>END_PI, 'subject', mail.normSubject] Message.rawRequest 'dedupRequest', {key}, (err, rows) -> return callback err if err log.debug "found similar", rows.length Message.pickConversationID rows, callback # give it a random uid else callback null, uuid.v4() # Public: get messages in cozy by their uids # # mailboxID - {String} id of the mailbox to check # # Returns (callback) an {Array} of {String} uids in the cozy @UIDsInCozy: (mailboxID, callback) -> # Public: find a message by its message id # # accountID - id of the account to scan # messageID - message-id to search, no need to normalize # # Returns (callback) {Message} the first message with this Message-ID @byMessageID: (accountID, messageID, callback) -> messageID = mailutils.normalizeMessageID messageID Message.rawRequest 'dedupRequest', key: [accountID, 'mid', messageID] include_docs: true , (err, rows) -> return callback err if err message = rows[0]?.doc message = new Message message if message callback null, message # Public: get lengths of multiple conversations # # conversationIDs - [String] id of the conversations # # Returns (callback) an {Object} with conversationsIDs as keys and # counts as values @getConversationLengths: (conversationIDs, callback) -> Message.rawRequest 'byConversationID', keys: conversationIDs group: true reduce: true , (err, rows) -> return callback err if err out = {} out[row.key] = row.value for row in rows callback null, out # Public: find messages by there conversation-id # # conversationID - id of the conversation to fetch # # Returns (callback) an {Array} of {Message} @byConversationID: (conversationID, callback) -> Message.byConversationIDs [conversationID], callback # Public: find messages by multiple conversation-id # # conversationIDs - {Array} of {String} id of the conversations to fetch # # Returns (callback) an {Array} of {Message} @byConversationIDs: (conversationIDs, callback) -> Message.rawRequest 'byConversationID', keys: conversationIDs reduce: false include_docs: true , (err, rows) -> return callback err if err messages = rows.map (row) -> try new Message row.doc catch err log.error "Wrong message", err, row.doc return null callback null, messages # Public: remove a message from a mailbox. # Uses {::removeFromMailbox} # # id - {String} id of the message # box - {Mailbox} mailbox to remove From # # Returns (callback) the updated {Message} @removeFromMailbox: (id, box, callback) -> log.debug "removeFromMailbox", id, box.label Message.find id, (err, message) -> return callback err if err return callback new NotFound "Message #{id}" unless message message.removeFromMailbox box, false, callback # Public: get messages in a box depending on the query params # # mailboxID - {String} the mailbox's ID # params - query's options # callback - Function(err, [{Message}]) # # Returns (callback) an {Object} with properties # :messages - the result of {.getResults} # :count - the result of {.getCount} # :conversationLengths - length of conversations in the result @getResultsAndCount: (mailboxID, params, callback) -> params.flag ?= null if params.descending [params.before, params.after] = [params.after, params.before] async.parallel [ (cb) -> Message.getCount mailboxID, params, cb (cb) -> Message.getResults mailboxID, params, cb ], (err, results) -> return callback err if err [count, messages] = results conversationIDs = _.uniq _.pluck messages, 'conversationID' Message.getConversationLengths conversationIDs, (err, lengths) -> return callback err if err callback null, messages: messages count: count conversationLengths: lengths # Public: get messages in a box depending on the query params # # mailboxID - {String} the mailbox's ID # params - query's options # # Returns (callback) an {Array} of {Message} @getResults: (mailboxID, params, callback) -> {before, after, descending, sortField, flag} = params skip = 0 if sortField is 'from' or sortField is 'dest' if params.resultsAfter? skip = params.resultsAfter startkey = [sortField, mailboxID, flag, before, null] endkey = [sortField, mailboxID, flag, after, null] else if params.resultsAfter? startkey = [sortField, mailboxID, flag, params.resultsAfter] else startkey = [sortField, mailboxID, flag, before] endkey = [sortField, mailboxID, flag, after] requestOptions = descending: descending startkey: startkey endkey: endkey reduce: false skip: skip include_docs: true limit: MSGBYPAGE Message.rawRequest 'byMailboxRequest', requestOptions , (err, rows) -> return callback err if err callback null, rows.map (row) -> new Message row.doc # Public: get number of messages in a box, depending on the query params # # mailboxID - {String} the mailbox's ID # params - query's options # # Returns (callback) {Number} of messages in the search @getCount: (mailboxID, params, callback) -> {before, after, descending, sortField, flag} = params Message.rawRequest 'byMailboxRequest', descending: descending startkey: [sortField, mailboxID, flag, before] endkey: [sortField, mailboxID, flag, after] reduce: true group_level: 2 , (err, rows) -> return callback err if err callback null, rows[0]?.value or 0 # Public: create or update a message # # message - {Message} the mailbox's ID # # Returns (callback) {Message} the updated / created message @updateOrCreate: (message, callback) -> log.debug "create or update" if message.id Message.find message.id, (err, existing) -> log.debug "update" if err callback err else if not existing callback new NotFound "Message #{message.id}" else # prevent overiding of binary message.binary = existing.binary existing.updateAttributes message, callback else log.debug "create" Message.create message, callback # Public: check if a message is already in cozy by its mid. # If it is update it with {::markTwin} or {::addToMailbox}, else fetch it. # # box - {Mailbox} the box to create this message in # msg - {Object} the msg # :mid - {String} Message-id # :uid - {String} the uid # ignoreInCount - {Boolean} mark this message as ignored in counts. # # Returns (callback) {Object} information about what happened # :shouldNotif - {Boolean} whether a new unread message was added # :actuallyAdded - {Boolean} whether a message was actually added @fetchOrUpdate: (box, msg, callback) -> {mid, uid} = msg log.debug "fetchOrUpdate", box.id, mid, uid Message.byMessageID box.accountID, mid, (err, existing) -> return callback err if err if existing and not existing.isInMailbox box log.debug " add" existing.addToMailbox box, uid, callback else if existing # this is the weird case when a message is in the box # under two different UIDs log.debug " twin" existing.markTwin box, uid, callback else log.debug " fetch" Message.fetchOneMail box, uid, callback @fetchOneMail: (box, uid, callback) -> box.doLaterWithBox (imap, imapbox, cb) -> imap.fetchOneMail uid, cb , (err, mail) -> return callback err if err shouldNotif = '\\Seen' in (mail.flags or []) Message.createFromImapMessage mail, box, uid, (err) -> return callback err if err callback null, {shouldNotif: shouldNotif, actuallyAdded: true} # Public: mark a message has having a twin (2 messages with same MID, # but different UID) in the same box so they can be smartly handled at # deletion. # # box - {Mailbox} the mailbox # # Returns (callback) {Object} information about what happened # :shouldNotif - {Boolean} always false # :actuallyAdded - {Boolean} wheter a message was actually added markTwin: (box, uid, callback) -> hasTwin = @hasTwin or [] twinMailboxIDs = @twinMailboxIDs or {} twinMailboxIDsBox = twinMailboxIDs[box.id] or [] if box.id in hasTwin and uid in twinMailboxIDsBox # already noted callback null, {shouldNotif: false, actuallyAdded: false} else if box.id in hasTwin # the message was marked as twin before the introduction of # twinMailboxIDs twinMailboxIDs[box.id] ?= [] twinMailboxIDs[box.id].push uid @updateAttributes {twinMailboxIDs}, (err) -> callback err, {shouldNotif: false, actuallyAdded: true} else hasTwin.push box.id twinMailboxIDs[box.id] ?= [] twinMailboxIDs[box.id].push uid @updateAttributes {hasTwin, twinMailboxIDs}, (err) -> callback err, {shouldNotif: false, actuallyAdded: true} # Public: add the message to a mailbox in the cozy # # box - {Mailbox} to add this message to # uid - {Number} uid of the message in the mailbox # callback - Function(err, {Message} updated) # # Returns (callback) {Object} information about what happened # :shouldNotif - {Boolean} always false # :actuallyAdded - {Boolean} always true addToMailbox: (box, uid, callback) -> log.info "MAIL #{box.path}:#{uid} ADDED TO BOX" mailboxIDs = {} mailboxIDs[key] = value for key, value of @mailboxIDs or {} mailboxIDs[box.id] = uid changes = {mailboxIDs} changes.ignoreInCount = box.ignoreInCount() @updateAttributes changes, (err) -> callback err, {shouldNotif: false, actuallyAdded: true} # Public: helper to check if a message is in a box # # box - {Mailbox} the mailbox # # Returns {Boolean} whether this message is in the box or not isInMailbox: (box) -> return @mailboxIDs[box.id]? and @mailboxIDs[box.id] isnt -1 # Public: remove a message from a mailbox in the cozy # if the message becomes an orphan, we destroy it # # box - {Mailbox} to remove this message from # noDestroy - {Boolean} dont destroy orphan messages # # Returns (callback) the updated {Message} removeFromMailbox: (box, noDestroy = false, callback) -> log.debug ".removeFromMailbox", @id, box.label callback = noDestroy unless callback changes = {} changed = false if box.id of (@mailboxIDs or {}) changes.mailboxIDs = _.omit @mailboxIDs, box.id changed = true if box.id of (@twinMailboxIDs or {}) changes.twinMailboxIDs = _.omit @twinMailboxIDs, box.id changed = true if changed boxes = Object.keys(changes.mailboxIDs or @mailboxIDs) isOrphan = boxes.length is 0 log.debug "REMOVING #{@id}, NOW ORPHAN = ", isOrphan if isOrphan and not noDestroy then @destroy callback else @updateAttributes changes, callback else setImmediate callback # Public: Create a message from a raw imap message. # Handle attachments and normalization of message ids and subjects. # # mail - an node-imap mail {Object} # box - {Mailbox} to create the message in # uid - {Number} UID of the message in the box # # Returns (callback) at completion @createFromImapMessage: (mail, box, uid, callback) -> log.info "createFromImapMessage", box.label, uid log.debug 'flags = ', mail.flags # we store the box & account id mail.accountID = box.accountID mail.ignoreInCount = box.ignoreInCount() mail.mailboxIDs = {} mail.mailboxIDs[box._id] = uid # we store normalized versions of subject & messageID for threading messageID = mail.headers['message-id'] delete mail.messageId # reported bug : if a mail has two messageID, mailparser make it # an array and it crashes the server if messageID and messageID instanceof Array messageID = messageID[0] if messageID mail.messageID = mailutils.normalizeMessageID messageID if mail.subject mail.normSubject = mailutils.normalizeSubject mail.subject # @TODO, find and parse from mail.headers ? mail.replyTo ?= [] mail.cc ?= [] mail.bcc ?= [] mail.to ?= [] mail.from ?= [] if not mail.date? mail.date = new Date().toISOString() # we extract the attachments buffers # @TODO : directly create binaries ? (first step for streaming) attachments = [] if mail.attachments attachments = mail.attachments.map (att) -> buffer = att.content delete att.content return out = name: att.generatedFileName buffer: buffer # pick a method to find the conversation id # if there is a x-gm-thrid, use it # else find the thread using References or Subject Message.findConversationID mail, (err, conversationID) -> return callback err if err mail.conversationID = conversationID Message.create mail, (err, jdbMessage) -> return callback err if err jdbMessage.storeAttachments attachments, callback # Public: Store the node-imap attachment to the cozy message # # attachments - an {Array} of {Object}(name, buffer) # # Returns (callback) at completion storeAttachments: (attachments, callback) -> log.debug "storeAttachments" async.eachSeries attachments, (att, cb) => # WEIRDFIX#1 - some attachments name are broken # WEIRDFIX#2 - some attachments have no buffer # att.name = att.name.replace "\ufffd", "" att.buffer ?= new Buffer 0 @attachBinary att.buffer, name: att.name, cb , callback # Public: get this message formatted for the client. # Generate html & text appropriately and give each # attachment an URL. # # Returns (callback) {Object} the formatted message toClientObject: -> # log.debug "toClientObject" raw = @toObject() raw.attachments?.forEach (file) -> encodedFileName = encodeURIComponent file.generatedFileName file.url = "message/#{raw.id}/attachments/#{encodedFileName}" if raw.html? attachments = raw.attachments or [] raw.html = mailutils.sanitizeHTML raw.html, raw.id, attachments if not raw.text? and raw.html? try raw.text = htmlToText.fromString raw.html, tables: true wordwrap: 80 catch err log.error "Error converting HTML to text", err, raw.html return raw @doGroupedByBox: (messages, iterator, done) -> return done null if messages.length is 0 accountID = messages[0].accountID messagesByBoxID = {} for message in messages for boxID, uid of message.mailboxIDs messagesByBoxID[boxID] ?= [] messagesByBoxID[boxID].push message state = {} async.eachSeries Object.keys(messagesByBoxID), (boxID, next) -> state.box = ramStore.getMailbox boxID state.messagesInBox = messagesByBoxID[boxID] iterator2 = (imap, imapBox, releaseImap) -> state.imapBox = imapBox state.uids = state.messagesInBox.map (msg) -> msg.mailboxIDs[state.box.id] iterator imap, state, releaseImap pool = ramStore.getImapPool(messages[0]) if not pool return done new BadRequest "Pool isn't defined" pool.doASAPWithBox state.box, iterator2, next , done @batchAddFlag: (messages, flag, callback) -> # dont add flag twice messages = messages.filter (msg) -> flag not in msg.flags Message.doGroupedByBox messages, (imap, state, next) -> imap.addFlags state.uids, flag, next , (err) -> return callback err if err async.mapSeries messages, (message, next) -> newflags = message.flags.concat flag message.updateAttributes flags: newflags, (err) -> next err, message , callback @batchRemoveFlag: (messages, flag, callback) -> # dont remove flag if it wasnt messages = messages.filter (msg) -> flag in msg.flags Message.doGroupedByBox messages, (imap, state, next) -> imap.delFlags state.uids, flag, next , (err) -> return callback err if err async.mapSeries messages, (message, next) -> newflags = _.without message.flags, flag message.updateAttributes flags: newflags, (err) -> next err, message , callback cloneMailboxIDs: -> out = {} out[boxID] = uid for boxID, uid of @mailboxIDs return out # Public: wether or not this message # is a draft. Consider a message a draft if it is in Draftbox or has # the \\Draft flag # # Returns {Bollean} is this message a draft ? isDraft: (draftBoxID) -> @mailboxIDs[draftBoxID]? or '\\Draft' in @flags module.exports = Message mailutils = require '../utils/jwz_tools' CONSTANTS = require '../utils/constants' {MSGBYPAGE, LIMIT_DESTROY, CONCURRENT_DESTROY} = CONSTANTS {NotFound, BadRequest, AccountConfigError} = require '../utils/errors' uuid = require 'uuid' _ = require 'lodash' async = require 'async' log = require('../utils/logging')(prefix: 'models:message') htmlToText = require 'html-to-text' require('./model-events').wrapModel Message ramStore = require './store_account_and_boxes'
[ { "context": "=\n mail : req.body.email\n password : req.body.password\n User.connect (client) ->\n User.get_u", "end": 665, "score": 0.9992121458053589, "start": 648, "tag": "PASSWORD", "value": "req.body.password" } ]
src/server/api/user.coffee
mauriciodelrio/lendme
1
User = new (require('../lib/pgconn').User)() Cache = new (require('../lib/cache'))() Session = new (require('../lib/session'))() Mail = new (require('../lib/mail'))() module.exports = () -> all_users: ((req, res) -> User.connect (client) -> User.get_users client, (response) -> res.send status: 'OK', data: response ) user_id: ((req, res) -> User.connect (client) -> User.get_user_by_id client, req.params.user_id, (response) -> res.send status: 'OK', data: response ) signin: ((req, res) -> if req.body?.email and req.body?.password params = mail : req.body.email password : req.body.password User.connect (client) -> User.get_user_by_mail client, params, (user) -> if user[0]?.user_id #limpiar sesiones anteriores acá User.clean_old_sessions client, user[0].user_id, (resp) -> if resp.status is 'OK' and resp.data? console.log resp else console.error resp #Mail.send req.body.email, 'bienvenida', {name: String("#{user[0].user_name or ''} #{user[0].user_lastname or ''}").trim()}, (err, resp) -> #console.log err, resp Session.set user[0].user_id, {}, req, true, (session_id) -> if session_id? console.log "---- Seteo su session ----", session_id Cache.set "user:#{user.user_id}", user[0], (cache_user) -> console.log "---- entro a Cache ----", cache_user res.locals.USER = user[0] res.send status: 'OK', data: user[0] else console.error "EMPTY RESPONSE SESSION" res.send status: 'ERROR', data: "LOGIN ERROR" else console.error user res.send status: 'ERROR', data: "USER NOT FOUND" else console.error "LOGIN_ERROR" )
46047
User = new (require('../lib/pgconn').User)() Cache = new (require('../lib/cache'))() Session = new (require('../lib/session'))() Mail = new (require('../lib/mail'))() module.exports = () -> all_users: ((req, res) -> User.connect (client) -> User.get_users client, (response) -> res.send status: 'OK', data: response ) user_id: ((req, res) -> User.connect (client) -> User.get_user_by_id client, req.params.user_id, (response) -> res.send status: 'OK', data: response ) signin: ((req, res) -> if req.body?.email and req.body?.password params = mail : req.body.email password : <PASSWORD> User.connect (client) -> User.get_user_by_mail client, params, (user) -> if user[0]?.user_id #limpiar sesiones anteriores acá User.clean_old_sessions client, user[0].user_id, (resp) -> if resp.status is 'OK' and resp.data? console.log resp else console.error resp #Mail.send req.body.email, 'bienvenida', {name: String("#{user[0].user_name or ''} #{user[0].user_lastname or ''}").trim()}, (err, resp) -> #console.log err, resp Session.set user[0].user_id, {}, req, true, (session_id) -> if session_id? console.log "---- Seteo su session ----", session_id Cache.set "user:#{user.user_id}", user[0], (cache_user) -> console.log "---- entro a Cache ----", cache_user res.locals.USER = user[0] res.send status: 'OK', data: user[0] else console.error "EMPTY RESPONSE SESSION" res.send status: 'ERROR', data: "LOGIN ERROR" else console.error user res.send status: 'ERROR', data: "USER NOT FOUND" else console.error "LOGIN_ERROR" )
true
User = new (require('../lib/pgconn').User)() Cache = new (require('../lib/cache'))() Session = new (require('../lib/session'))() Mail = new (require('../lib/mail'))() module.exports = () -> all_users: ((req, res) -> User.connect (client) -> User.get_users client, (response) -> res.send status: 'OK', data: response ) user_id: ((req, res) -> User.connect (client) -> User.get_user_by_id client, req.params.user_id, (response) -> res.send status: 'OK', data: response ) signin: ((req, res) -> if req.body?.email and req.body?.password params = mail : req.body.email password : PI:PASSWORD:<PASSWORD>END_PI User.connect (client) -> User.get_user_by_mail client, params, (user) -> if user[0]?.user_id #limpiar sesiones anteriores acá User.clean_old_sessions client, user[0].user_id, (resp) -> if resp.status is 'OK' and resp.data? console.log resp else console.error resp #Mail.send req.body.email, 'bienvenida', {name: String("#{user[0].user_name or ''} #{user[0].user_lastname or ''}").trim()}, (err, resp) -> #console.log err, resp Session.set user[0].user_id, {}, req, true, (session_id) -> if session_id? console.log "---- Seteo su session ----", session_id Cache.set "user:#{user.user_id}", user[0], (cache_user) -> console.log "---- entro a Cache ----", cache_user res.locals.USER = user[0] res.send status: 'OK', data: user[0] else console.error "EMPTY RESPONSE SESSION" res.send status: 'ERROR', data: "LOGIN ERROR" else console.error user res.send status: 'ERROR', data: "USER NOT FOUND" else console.error "LOGIN_ERROR" )
[ { "context": "service:session\")\n @userParams =\n email: \"test@test.test\"\n password: \"password123\"\n Cookies.remove", "end": 526, "score": 0.9998952150344849, "start": 512, "tag": "EMAIL", "value": "test@test.test" }, { "context": " =\n email: \"test@test.t...
tests/acceptance/appointment-creation-test.coffee
simwms/apiv4
2
`import Ember from 'ember'` `import { module, test } from 'qunit'` `import startApp from '../../tests/helpers/start-app'` module 'Acceptance: AppointmentCreation', beforeEach: -> @application = startApp() ### Don't return anything, because QUnit looks for a .then that is present on Ember.Application, but is deprecated. ### @store = @application.__container__.lookup("service:store") @session = @application.__container__.lookup("service:session") @userParams = email: "test@test.test" password: "password123" Cookies.remove "_apiv4_key" Cookies.remove "remember-token" return afterEach: -> Ember.run @application, 'destroy' test 'visiting /appointment-creation', (assert) -> visit "/" andThen => @session.login @userParams andThen => @session .get("model") .get("user") .then (user) => @user = user @user.get("accounts") .then (accounts) => @account = accounts.objectAt(0) andThen => @session.update(account: @account) andThen => @store.findAll "company" .then (companies) => @company = companies.objectAt(0) .then (company) => @appointment = @store.createRecord "appointment", company: company externalReference: "testing-123" description: "this is a test of the appointment creation system" .save() andThen => @appointment .get("histories") .then (histories) => @history = histories.objectAt(0) andThen => assert.ok @history assert.equal @history.get("name"), "appointment-created"
48540
`import Ember from 'ember'` `import { module, test } from 'qunit'` `import startApp from '../../tests/helpers/start-app'` module 'Acceptance: AppointmentCreation', beforeEach: -> @application = startApp() ### Don't return anything, because QUnit looks for a .then that is present on Ember.Application, but is deprecated. ### @store = @application.__container__.lookup("service:store") @session = @application.__container__.lookup("service:session") @userParams = email: "<EMAIL>" password: "<PASSWORD>" Cookies.remove "_apiv4_key" Cookies.remove "remember-token" return afterEach: -> Ember.run @application, 'destroy' test 'visiting /appointment-creation', (assert) -> visit "/" andThen => @session.login @userParams andThen => @session .get("model") .get("user") .then (user) => @user = user @user.get("accounts") .then (accounts) => @account = accounts.objectAt(0) andThen => @session.update(account: @account) andThen => @store.findAll "company" .then (companies) => @company = companies.objectAt(0) .then (company) => @appointment = @store.createRecord "appointment", company: company externalReference: "testing-123" description: "this is a test of the appointment creation system" .save() andThen => @appointment .get("histories") .then (histories) => @history = histories.objectAt(0) andThen => assert.ok @history assert.equal @history.get("name"), "appointment-created"
true
`import Ember from 'ember'` `import { module, test } from 'qunit'` `import startApp from '../../tests/helpers/start-app'` module 'Acceptance: AppointmentCreation', beforeEach: -> @application = startApp() ### Don't return anything, because QUnit looks for a .then that is present on Ember.Application, but is deprecated. ### @store = @application.__container__.lookup("service:store") @session = @application.__container__.lookup("service:session") @userParams = email: "PI:EMAIL:<EMAIL>END_PI" password: "PI:PASSWORD:<PASSWORD>END_PI" Cookies.remove "_apiv4_key" Cookies.remove "remember-token" return afterEach: -> Ember.run @application, 'destroy' test 'visiting /appointment-creation', (assert) -> visit "/" andThen => @session.login @userParams andThen => @session .get("model") .get("user") .then (user) => @user = user @user.get("accounts") .then (accounts) => @account = accounts.objectAt(0) andThen => @session.update(account: @account) andThen => @store.findAll "company" .then (companies) => @company = companies.objectAt(0) .then (company) => @appointment = @store.createRecord "appointment", company: company externalReference: "testing-123" description: "this is a test of the appointment creation system" .save() andThen => @appointment .get("histories") .then (histories) => @history = histories.objectAt(0) andThen => assert.ok @history assert.equal @history.get("name"), "appointment-created"