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 #newsite ${1:0}\n #name ${2:\"Item Name\"}\n #path ${3:0}\n #level ${4",
"end": 2111,
"score": 0.8259885311126709,
"start": 2102,
"tag": "NAME",
"value": "Item Name"
}
] | snippets/snippets.cson | lambda-dom/atom-dominions | 0 | ".source.dominions":
"selectweapon":
prefix: "selectweapon"
body: """
#selectweapon ${1:0}
$2
#end
"""
"newweapon":
prefix: "newweapon"
body: """
#newweapon${1}
#name ${2:"Weapon Name"}
#end
"""
"selectarmor":
prefix: "selectarmor"
body: """
#selectarmor ${1:0}
$2
#end
"""
"newarmor":
prefix: "newarmor"
body: """
#newweapon${1}
#name ${2:"Armor Name"}
#end
"""
"selectmonster":
prefix: "selectmonster"
body: """
#selectmonster ${1:0}
$2
#end
"""
"newmonster":
prefix: "newmonster"
body: """
#newmonster${1}
#name ${2:"Monster Name"}
#descr ${3:"Monster Description"}
#gcost ${4:10000}
#rpcost ${5:0}
#end
"""
"selectspell":
prefix: "selectspell"
body: """
#selectspell ${1:0}
$2
#end
"""
"newspell":
prefix: "newspell"
body: """
#newspell ${1:0}
#name ${2:"Spell Name"}
#descr ${3:"Spell Description"}
#school ${4:-1}
#researchlevel ${5:0}
#path ${6:0} ${7:-1}
#pathlevel ${6:0} ${8:-1}
#end
"""
"selectitem":
prefix: "selectitem"
body: """
#selectitem ${1:0}
$2
#end
"""
"newitem":
prefix: "newitem"
body: """
#newmonster ${1:0}
#name ${2:"Item Name"}
#descr ${3:"Item Description"}
#constlevel ${4:0}
#mainpath ${5:0}
#mainlevel ${6:0}
#end
"""
"selectsite":
prefix: "selectsite"
body: """
#selectsite ${1:0}
$2
#end
"""
"newsite":
prefix: "newsite"
body: """
#newsite ${1:0}
#name ${2:"Item Name"}
#path ${3:0}
#level ${4:0}
#rarity ${5:0}
#loc ${6:223}
#end
"""
"newevent":
prefix: "newevent"
body: """
#newevent
#msg ${1:""}
#end
"""
| 103304 | ".source.dominions":
"selectweapon":
prefix: "selectweapon"
body: """
#selectweapon ${1:0}
$2
#end
"""
"newweapon":
prefix: "newweapon"
body: """
#newweapon${1}
#name ${2:"Weapon Name"}
#end
"""
"selectarmor":
prefix: "selectarmor"
body: """
#selectarmor ${1:0}
$2
#end
"""
"newarmor":
prefix: "newarmor"
body: """
#newweapon${1}
#name ${2:"Armor Name"}
#end
"""
"selectmonster":
prefix: "selectmonster"
body: """
#selectmonster ${1:0}
$2
#end
"""
"newmonster":
prefix: "newmonster"
body: """
#newmonster${1}
#name ${2:"Monster Name"}
#descr ${3:"Monster Description"}
#gcost ${4:10000}
#rpcost ${5:0}
#end
"""
"selectspell":
prefix: "selectspell"
body: """
#selectspell ${1:0}
$2
#end
"""
"newspell":
prefix: "newspell"
body: """
#newspell ${1:0}
#name ${2:"Spell Name"}
#descr ${3:"Spell Description"}
#school ${4:-1}
#researchlevel ${5:0}
#path ${6:0} ${7:-1}
#pathlevel ${6:0} ${8:-1}
#end
"""
"selectitem":
prefix: "selectitem"
body: """
#selectitem ${1:0}
$2
#end
"""
"newitem":
prefix: "newitem"
body: """
#newmonster ${1:0}
#name ${2:"Item Name"}
#descr ${3:"Item Description"}
#constlevel ${4:0}
#mainpath ${5:0}
#mainlevel ${6:0}
#end
"""
"selectsite":
prefix: "selectsite"
body: """
#selectsite ${1:0}
$2
#end
"""
"newsite":
prefix: "newsite"
body: """
#newsite ${1:0}
#name ${2:"<NAME>"}
#path ${3:0}
#level ${4:0}
#rarity ${5:0}
#loc ${6:223}
#end
"""
"newevent":
prefix: "newevent"
body: """
#newevent
#msg ${1:""}
#end
"""
| true | ".source.dominions":
"selectweapon":
prefix: "selectweapon"
body: """
#selectweapon ${1:0}
$2
#end
"""
"newweapon":
prefix: "newweapon"
body: """
#newweapon${1}
#name ${2:"Weapon Name"}
#end
"""
"selectarmor":
prefix: "selectarmor"
body: """
#selectarmor ${1:0}
$2
#end
"""
"newarmor":
prefix: "newarmor"
body: """
#newweapon${1}
#name ${2:"Armor Name"}
#end
"""
"selectmonster":
prefix: "selectmonster"
body: """
#selectmonster ${1:0}
$2
#end
"""
"newmonster":
prefix: "newmonster"
body: """
#newmonster${1}
#name ${2:"Monster Name"}
#descr ${3:"Monster Description"}
#gcost ${4:10000}
#rpcost ${5:0}
#end
"""
"selectspell":
prefix: "selectspell"
body: """
#selectspell ${1:0}
$2
#end
"""
"newspell":
prefix: "newspell"
body: """
#newspell ${1:0}
#name ${2:"Spell Name"}
#descr ${3:"Spell Description"}
#school ${4:-1}
#researchlevel ${5:0}
#path ${6:0} ${7:-1}
#pathlevel ${6:0} ${8:-1}
#end
"""
"selectitem":
prefix: "selectitem"
body: """
#selectitem ${1:0}
$2
#end
"""
"newitem":
prefix: "newitem"
body: """
#newmonster ${1:0}
#name ${2:"Item Name"}
#descr ${3:"Item Description"}
#constlevel ${4:0}
#mainpath ${5:0}
#mainlevel ${6:0}
#end
"""
"selectsite":
prefix: "selectsite"
body: """
#selectsite ${1:0}
$2
#end
"""
"newsite":
prefix: "newsite"
body: """
#newsite ${1:0}
#name ${2:"PI:NAME:<NAME>END_PI"}
#path ${3:0}
#level ${4:0}
#rarity ${5:0}
#loc ${6:223}
#end
"""
"newevent":
prefix: "newevent"
body: """
#newevent
#msg ${1:""}
#end
"""
|
[
{
"context": "}です。\"\n item = Item.create\n id: '1'\n name: \"テストのアイテム\"\n point: 100\n Item.addEventListener 'itemsCha",
"end": 462,
"score": 0.9994842410087585,
"start": 454,
"tag": "NAME",
"value": "テストのアイテム"
}
] | javascripts/model.coffee | moongift/hifive-examples | 0 | $ ->
h5.core.data.createManager 'DatabaseManager', 'db'
Item = db.DatabaseManager.createModel
name: "Item"
schema:
id:
id: true
name:
type: 'string'
point:
type: 'integer'
defaultValue: 0
message:
type: 'string',
depend:
on: ['name', 'point']
calc: (e) ->
"#{@get('name')}は#{@get('point')}です。"
item = Item.create
id: '1'
name: "テストのアイテム"
point: 100
Item.addEventListener 'itemsChange', (e) ->
console.log 'データモデル', 'Change!'
console.log e
item.addEventListener 'change', (e) ->
console.log 'データアイテム', 'Change!'
console.info item
console.info item.get 'name'
item.set 'point', 50
console.info item.get('message')
| 75571 | $ ->
h5.core.data.createManager 'DatabaseManager', 'db'
Item = db.DatabaseManager.createModel
name: "Item"
schema:
id:
id: true
name:
type: 'string'
point:
type: 'integer'
defaultValue: 0
message:
type: 'string',
depend:
on: ['name', 'point']
calc: (e) ->
"#{@get('name')}は#{@get('point')}です。"
item = Item.create
id: '1'
name: "<NAME>"
point: 100
Item.addEventListener 'itemsChange', (e) ->
console.log 'データモデル', 'Change!'
console.log e
item.addEventListener 'change', (e) ->
console.log 'データアイテム', 'Change!'
console.info item
console.info item.get 'name'
item.set 'point', 50
console.info item.get('message')
| true | $ ->
h5.core.data.createManager 'DatabaseManager', 'db'
Item = db.DatabaseManager.createModel
name: "Item"
schema:
id:
id: true
name:
type: 'string'
point:
type: 'integer'
defaultValue: 0
message:
type: 'string',
depend:
on: ['name', 'point']
calc: (e) ->
"#{@get('name')}は#{@get('point')}です。"
item = Item.create
id: '1'
name: "PI:NAME:<NAME>END_PI"
point: 100
Item.addEventListener 'itemsChange', (e) ->
console.log 'データモデル', 'Change!'
console.log e
item.addEventListener 'change', (e) ->
console.log 'データアイテム', 'Change!'
console.info item
console.info item.get 'name'
item.set 'point', 50
console.info item.get('message')
|
[
{
"context": " \n # MongoDB database settings\n db:\n host: \"127.0.0.1\"\n port: 27017\n name: \"justjsblogdemo\"\n\n \n ",
"end": 194,
"score": 0.9997639060020447,
"start": 185,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "\n host: \"127.0.0.1\"\n p... | blog-5/settings.coffee | aishraj/node-learner | 0 | # Settings for our app. The 'require' call in server.js returns
# whatever we assign to 'module.exports' in this file
module.exports =
# MongoDB database settings
db:
host: "127.0.0.1"
port: 27017
name: "justjsblogdemo"
# Port for the webserver to listen on
http:
port: 3000
sessionSecret: '0AAE34BC8DD'
google:
returnURL: 'http://localhost:3000/auth/google/callback',
realm: 'http://localhost:3000/'
posters: 'dahalaishraj+gitcheck@gmail.com'
| 23943 | # Settings for our app. The 'require' call in server.js returns
# whatever we assign to 'module.exports' in this file
module.exports =
# MongoDB database settings
db:
host: "127.0.0.1"
port: 27017
name: "justjsblogdemo"
# Port for the webserver to listen on
http:
port: 3000
sessionSecret: '<KEY>'
google:
returnURL: 'http://localhost:3000/auth/google/callback',
realm: 'http://localhost:3000/'
posters: '<EMAIL>'
| true | # Settings for our app. The 'require' call in server.js returns
# whatever we assign to 'module.exports' in this file
module.exports =
# MongoDB database settings
db:
host: "127.0.0.1"
port: 27017
name: "justjsblogdemo"
# Port for the webserver to listen on
http:
port: 3000
sessionSecret: 'PI:KEY:<KEY>END_PI'
google:
returnURL: 'http://localhost:3000/auth/google/callback',
realm: 'http://localhost:3000/'
posters: 'PI:EMAIL:<EMAIL>END_PI'
|
[
{
"context": "{\n title: 'welcome email for tj',\n to: 'tj@learnboost.com',\n template: 'welcome-email'}).save()\n cb",
"end": 3933,
"score": 0.9999291300773621,
"start": 3916,
"tag": "EMAIL",
"value": "tj@learnboost.com"
}
] | src/server.coffee | caffellatte/undertherules | 2 | # cluster.coffee
# Modules - Модули
_ = require('lodash') # Библиотека Полезных Функций и Операций
fs = require('fs-extra') # Работа с Файловой Системой
os = require('os') # Взаимодействие с Операционной Системой
kue = require('kue') # Автоматизированная Очередь
pug = require('pug') # Перевод из *.pug в *.html
url = require('url') # Форматирование и Парсинг URL ссылок
http = require('http') # HTTP/HTTPS Сервер
shoe = require('shoe') # Прокси
dnode = require('dnode') # Клиент-Сервер для связи с браузером Клиента
level = require('levelup') # База Данных
crypto = require('crypto') # Криптографические функции (хеш-функции)
stylus = require('stylus') # Перевд из *.styl в *.css
natural = require('natural') # Библиотека для обработки текста
cluster = require('cluster') # Управление процессами
request = require('request') # HTTP/HTTPS запросы
coffeeify = require('coffeeify') # Перевод из *.coffee в *.js
browserify = require('browserify') # Загрузчик (транспайлер)
querystring = require('querystring') # Форматирование и Разбор URL-ссылокок
child_process = require('child_process') # Создание дочерних процессов
# Functions - Функции
{exec} = child_process # Функйия для Выполнение команд средствами ОС
{writeFileSync, readFileSync} = fs # Синхронное чтение и запись в файл
{removeSync, mkdirsSync, copySync, ensureDirSync} = fs # Удаление, Создание...
# Environment - Окружение
numCPUs = require('os').cpus().length # Количество Процессорв
# Загрузка значений из файла конфигурации окружения .env (Часть 1)
CORE_DIR = process.env.CORE_DIR
LEVEL_DIR = process.env.LEVEL_DIR
STATIC_DIR = process.env.STATIC_DIR
HTDOCS_DIR = process.env.HTDOCS_DIR
USER_AGENT = process.env.USER_AGENT
KUE_PORT = process.env.KUE_PORT
KUE_HOST = process.env.KUE_HOST
PANEL_PORT = process.env.PANEL_PORT
PANEL_HOST = process.env.PANEL_HOST
IG_COOKIE = process.env.IG_COOKIE
DOMAIN = process.env.DOMAIN
# Загрузка значений из файла конфигурации окружения .env (Часть 2)
KUE_PORT = process.env.KUE_PORT
KUE_HOST = process.env.KUE_HOST
PANEL_PORT = process.env.PANEL_PORT
PANEL_HOST = process.env.PANEL_HOST
IG_COOKIE = process.env.IG_COOKIE
# Files - Файлы
# -- Дирректория для хранения сторонних библиотек для исполнения в браузере -- #
staticJs = "#{STATIC_DIR}/js" # Сторонние библиотеки
staticImg = "#{STATIC_DIR}/img" # Дирректория с Картинками
staticFaviconIco = "#{STATIC_DIR}/favicon.ico" # Иконка для браузера
indexHtml = "#{STATIC_DIR}/index.html" # с помощью pug
styleCss = "#{STATIC_DIR}/style.css" # с помощью stylus
bundleJs = "#{STATIC_DIR}/bundle.js" # coffeeify и browserify
# -------------------------------------------------------------------------- #
# ------------- Исходные Файлы для Генерации Клиентского Кода --------------- #
htdocsJs = "#{HTDOCS_DIR}/js" # Сторонние библиотеки
htdocsImg = "#{HTDOCS_DIR}/img" # Дирректория с Картинками
browserCoffee = "#{HTDOCS_DIR}/client.coffee" # Клиент (Исходник)
htdocsFaviconIco = "#{HTDOCS_DIR}/img/favicon.ico" # Иконка для браузера
templatePug = "#{HTDOCS_DIR}/template.pug" # Исходники для *.html файлов
styleStyl = "#{HTDOCS_DIR}/style.styl" # Исходники для *.css файлов
clusterCoffee = "#{CORE_DIR}/cluster.coffee" # Сервер
# -------------------------------------------------------------------------- #
# Queue - Очередь
queue = kue.createQueue() # Экземпляр (*KUE*) для управления очередью
# Server - Сервер
class Server
# Поиск строки с помощью регулярного выражения и библиотеки natural
@tokenizer:new natural.RegexpTokenizer({pattern:/(https?:\/\/[^\s]+)/g})
@SingUp:(mail, name, pass, cb) => # Регистрация Нового Аккаунта
queue.create('email', {
title: 'welcome email for tj',
to: 'tj@learnboost.com',
template: 'welcome-email'}).save()
cb("mail: #{mail}, name: #{name}, pass: #{pass}")
@SingIn:(user, pass, cb) => # Вход в аккаунт (имя/почта:пароль)
cb("user: #{user}, pass: #{pass}")
@inputMessage:(user_id, msg, cb) => # Входящее сообщение
cb("#{user_id}, #{msg}")
@browserify:(job, done) -> # Клиентский код на coffee преабразуется в js
console.log("PID: #{process.pid}\t@browserify")
{browserCoffee, bundleJs} = job.data # Путь к исходнику и путь для экспорта
bundle = browserify({extensions:['.coffee']}) # Указываем расширение
bundle.transform(coffeeify, {
bare:false # Не оборачивать в анаимную функцию
header:false # Помещаем скрипт в body
})
bundle.add(browserCoffee) # Добавляем файл в экземпляр
bundle.bundle((error, js) -> # Собираем bundle.js
throw error if error? # Проверка на ошибку
writeFileSync(bundleJs, js)
done()
)
@coffeelint:(job, done) -> # Проверка кода (статистический анализ)
console.log("PID: #{process.pid}\t@coffeelint")
{files} = job.data # Список Файлов для Анализа
command = 'coffeelint ' + "#{files.join(' ')}" # Формирем команду
exec(command, (err, stdout, stderr) -> # Выполняем комманду сркдствами ОС
console.log(stdout, stderr) # Выводим результат
done()
)
@pugRender:(job, done) -> # Рендерим HTML шаблон
console.log("PID: #{process.pid}\t@pugRender")
{templatePug, indexHtml} = job.data # Путь к исходнику и путь для экспорта
writeFileSync(indexHtml, pug.renderFile(templatePug, {pretty:true}))
# Записываем результат в файл, выбираем читабельный формат
done()
@static:(job, done) -> # Cоздаем файловую структуру
console.log("PID: #{process.pid}\t@static")
{htdocsFaviconIco, staticFaviconIco, htdocsImg, staticImg} = job.data
mkdirsSync(job.data.STATIC_DIR)
mkdirsSync("#{job.data.STATIC_DIR}/files")
copySync(htdocsJs, staticJs)
copySync(htdocsImg, staticImg)
copySync(htdocsFaviconIco, staticFaviconIco)
done()
@stylusRender:(job, done) ->
console.log("PID: #{process.pid}\t@stylusRender")
{styleStyl, styleCss} = job.data
handler = (err, css) ->
if err then throw err
writeFileSync(styleCss, css)
content = readFileSync(styleStyl, {encoding:'utf8'})
stylus.render(content, handler)
done()
# @email:(job, done ) -> "echo 'test' | mail -aFrom:root@#{DOMAIN} #{mail}"
# console.log("PID: #{process.pid}\t@email")
# {files} = job.data # Список Файлов для Анализа
# command = 'coffeelint ' + "#{files.join(' ')}" # Формирем команду
# exec(command, (err, stdout, stderr) -> # Выполняем комманду сркдствами ОС
# console.log(stdout, stderr) # Выводим результат
# done()
# )
# Master
if cluster.isMaster
## Kue
kue.app.set('title', 'Under The Rules')
kue.app.listen(KUE_PORT, KUE_HOST, ->
console.log("Kue: http://#{KUE_HOST}:#{KUE_PORT}.")
kue.Job.rangeByState('complete', 0, 100000, 'asc', (err, jobs) ->
jobs.forEach((job) ->
job.remove( -> return
)
)
)
)
## Ecstatic is a simple static file server middleware.
ecstatic = require('ecstatic')(STATIC_DIR)
server = http.createServer(ecstatic) # Create a HTTP server.
## Starting Dnode. Using dnode via shoe & Install endpoint
server.listen(PANEL_PORT, PANEL_HOST, ->
console.log("Dnode: http://#{PANEL_HOST}:#{PANEL_PORT}")
)
graph = level(LEVEL_DIR + '/graph', {type:'json'})
sock = shoe((stream) -> # Define API object providing integration vith dnode
d = dnode({
inputMessage:Server.inputMessage,
inputMessage:Server.SingUp
})
d.pipe(stream).pipe(d)
)
sock.install(server, '/dnode')
ensureDirSync(LEVEL_DIR)
## Create Jobs
staticJob = queue.create('static', {
title:'Copy images from HTDOCS_DIR to STATIC_DIR',
STATIC_DIR:STATIC_DIR,
htdocsFaviconIco:htdocsFaviconIco,
staticFaviconIco:staticFaviconIco,
htdocsImg:htdocsImg
staticImg:staticImg
}).save()
staticJob.on('complete', ->
queue.create('pugRender', {
title:'Render (transform) pug template to html',
templatePug:templatePug,
indexHtml:indexHtml
}).delay(1).save()
queue.create('stylusRender', {
title:'Render (transform) stylus template to css',
styleStyl:styleStyl,
styleCss:styleCss
}).delay(1).save()
queue.create('browserify', {
title:'Render (transform) coffee template to js',
browserCoffee:browserCoffee,
bundleJs:bundleJs
}).delay(1).save()
queue.create('coffeelint', {
title:'Link coffee files',
files:[clusterCoffee, browserCoffee]
}).delay(1).save() # browserCoffee
)
## **Clean** job list on exit add to class
exitHandler = (options, err) ->
if err
console.log(err.stack)
if options.exit
process.exit()
return
if options.cleanup
console.log('Buy!')
removeSync(STATIC_DIR)
## Do something when app is closing or ctrl+c event or uncaught exceptions
process.on('exit', exitHandler.bind(null, {cleanup:true}))
process.on('SIGINT', exitHandler.bind(null, {exit:true}))
process.on('uncaughtException', exitHandler.bind(null, {exit:true}))
i = 1
while i < numCPUs
cluster.fork()
i += 1
# Worker
else
queue.process('static', Server.static)
queue.process('pugRender', Server.pugRender)
queue.process('stylusRender', Server.stylusRender)
queue.process('browserify', Server.browserify)
queue.process('coffeelint', Server.coffeelint)
| 158990 | # cluster.coffee
# Modules - Модули
_ = require('lodash') # Библиотека Полезных Функций и Операций
fs = require('fs-extra') # Работа с Файловой Системой
os = require('os') # Взаимодействие с Операционной Системой
kue = require('kue') # Автоматизированная Очередь
pug = require('pug') # Перевод из *.pug в *.html
url = require('url') # Форматирование и Парсинг URL ссылок
http = require('http') # HTTP/HTTPS Сервер
shoe = require('shoe') # Прокси
dnode = require('dnode') # Клиент-Сервер для связи с браузером Клиента
level = require('levelup') # База Данных
crypto = require('crypto') # Криптографические функции (хеш-функции)
stylus = require('stylus') # Перевд из *.styl в *.css
natural = require('natural') # Библиотека для обработки текста
cluster = require('cluster') # Управление процессами
request = require('request') # HTTP/HTTPS запросы
coffeeify = require('coffeeify') # Перевод из *.coffee в *.js
browserify = require('browserify') # Загрузчик (транспайлер)
querystring = require('querystring') # Форматирование и Разбор URL-ссылокок
child_process = require('child_process') # Создание дочерних процессов
# Functions - Функции
{exec} = child_process # Функйия для Выполнение команд средствами ОС
{writeFileSync, readFileSync} = fs # Синхронное чтение и запись в файл
{removeSync, mkdirsSync, copySync, ensureDirSync} = fs # Удаление, Создание...
# Environment - Окружение
numCPUs = require('os').cpus().length # Количество Процессорв
# Загрузка значений из файла конфигурации окружения .env (Часть 1)
CORE_DIR = process.env.CORE_DIR
LEVEL_DIR = process.env.LEVEL_DIR
STATIC_DIR = process.env.STATIC_DIR
HTDOCS_DIR = process.env.HTDOCS_DIR
USER_AGENT = process.env.USER_AGENT
KUE_PORT = process.env.KUE_PORT
KUE_HOST = process.env.KUE_HOST
PANEL_PORT = process.env.PANEL_PORT
PANEL_HOST = process.env.PANEL_HOST
IG_COOKIE = process.env.IG_COOKIE
DOMAIN = process.env.DOMAIN
# Загрузка значений из файла конфигурации окружения .env (Часть 2)
KUE_PORT = process.env.KUE_PORT
KUE_HOST = process.env.KUE_HOST
PANEL_PORT = process.env.PANEL_PORT
PANEL_HOST = process.env.PANEL_HOST
IG_COOKIE = process.env.IG_COOKIE
# Files - Файлы
# -- Дирректория для хранения сторонних библиотек для исполнения в браузере -- #
staticJs = "#{STATIC_DIR}/js" # Сторонние библиотеки
staticImg = "#{STATIC_DIR}/img" # Дирректория с Картинками
staticFaviconIco = "#{STATIC_DIR}/favicon.ico" # Иконка для браузера
indexHtml = "#{STATIC_DIR}/index.html" # с помощью pug
styleCss = "#{STATIC_DIR}/style.css" # с помощью stylus
bundleJs = "#{STATIC_DIR}/bundle.js" # coffeeify и browserify
# -------------------------------------------------------------------------- #
# ------------- Исходные Файлы для Генерации Клиентского Кода --------------- #
htdocsJs = "#{HTDOCS_DIR}/js" # Сторонние библиотеки
htdocsImg = "#{HTDOCS_DIR}/img" # Дирректория с Картинками
browserCoffee = "#{HTDOCS_DIR}/client.coffee" # Клиент (Исходник)
htdocsFaviconIco = "#{HTDOCS_DIR}/img/favicon.ico" # Иконка для браузера
templatePug = "#{HTDOCS_DIR}/template.pug" # Исходники для *.html файлов
styleStyl = "#{HTDOCS_DIR}/style.styl" # Исходники для *.css файлов
clusterCoffee = "#{CORE_DIR}/cluster.coffee" # Сервер
# -------------------------------------------------------------------------- #
# Queue - Очередь
queue = kue.createQueue() # Экземпляр (*KUE*) для управления очередью
# Server - Сервер
class Server
# Поиск строки с помощью регулярного выражения и библиотеки natural
@tokenizer:new natural.RegexpTokenizer({pattern:/(https?:\/\/[^\s]+)/g})
@SingUp:(mail, name, pass, cb) => # Регистрация Нового Аккаунта
queue.create('email', {
title: 'welcome email for tj',
to: '<EMAIL>',
template: 'welcome-email'}).save()
cb("mail: #{mail}, name: #{name}, pass: #{pass}")
@SingIn:(user, pass, cb) => # Вход в аккаунт (имя/почта:пароль)
cb("user: #{user}, pass: #{pass}")
@inputMessage:(user_id, msg, cb) => # Входящее сообщение
cb("#{user_id}, #{msg}")
@browserify:(job, done) -> # Клиентский код на coffee преабразуется в js
console.log("PID: #{process.pid}\t@browserify")
{browserCoffee, bundleJs} = job.data # Путь к исходнику и путь для экспорта
bundle = browserify({extensions:['.coffee']}) # Указываем расширение
bundle.transform(coffeeify, {
bare:false # Не оборачивать в анаимную функцию
header:false # Помещаем скрипт в body
})
bundle.add(browserCoffee) # Добавляем файл в экземпляр
bundle.bundle((error, js) -> # Собираем bundle.js
throw error if error? # Проверка на ошибку
writeFileSync(bundleJs, js)
done()
)
@coffeelint:(job, done) -> # Проверка кода (статистический анализ)
console.log("PID: #{process.pid}\t@coffeelint")
{files} = job.data # Список Файлов для Анализа
command = 'coffeelint ' + "#{files.join(' ')}" # Формирем команду
exec(command, (err, stdout, stderr) -> # Выполняем комманду сркдствами ОС
console.log(stdout, stderr) # Выводим результат
done()
)
@pugRender:(job, done) -> # Рендерим HTML шаблон
console.log("PID: #{process.pid}\t@pugRender")
{templatePug, indexHtml} = job.data # Путь к исходнику и путь для экспорта
writeFileSync(indexHtml, pug.renderFile(templatePug, {pretty:true}))
# Записываем результат в файл, выбираем читабельный формат
done()
@static:(job, done) -> # Cоздаем файловую структуру
console.log("PID: #{process.pid}\t@static")
{htdocsFaviconIco, staticFaviconIco, htdocsImg, staticImg} = job.data
mkdirsSync(job.data.STATIC_DIR)
mkdirsSync("#{job.data.STATIC_DIR}/files")
copySync(htdocsJs, staticJs)
copySync(htdocsImg, staticImg)
copySync(htdocsFaviconIco, staticFaviconIco)
done()
@stylusRender:(job, done) ->
console.log("PID: #{process.pid}\t@stylusRender")
{styleStyl, styleCss} = job.data
handler = (err, css) ->
if err then throw err
writeFileSync(styleCss, css)
content = readFileSync(styleStyl, {encoding:'utf8'})
stylus.render(content, handler)
done()
# @email:(job, done ) -> "echo 'test' | mail -aFrom:root@#{DOMAIN} #{mail}"
# console.log("PID: #{process.pid}\t@email")
# {files} = job.data # Список Файлов для Анализа
# command = 'coffeelint ' + "#{files.join(' ')}" # Формирем команду
# exec(command, (err, stdout, stderr) -> # Выполняем комманду сркдствами ОС
# console.log(stdout, stderr) # Выводим результат
# done()
# )
# Master
if cluster.isMaster
## Kue
kue.app.set('title', 'Under The Rules')
kue.app.listen(KUE_PORT, KUE_HOST, ->
console.log("Kue: http://#{KUE_HOST}:#{KUE_PORT}.")
kue.Job.rangeByState('complete', 0, 100000, 'asc', (err, jobs) ->
jobs.forEach((job) ->
job.remove( -> return
)
)
)
)
## Ecstatic is a simple static file server middleware.
ecstatic = require('ecstatic')(STATIC_DIR)
server = http.createServer(ecstatic) # Create a HTTP server.
## Starting Dnode. Using dnode via shoe & Install endpoint
server.listen(PANEL_PORT, PANEL_HOST, ->
console.log("Dnode: http://#{PANEL_HOST}:#{PANEL_PORT}")
)
graph = level(LEVEL_DIR + '/graph', {type:'json'})
sock = shoe((stream) -> # Define API object providing integration vith dnode
d = dnode({
inputMessage:Server.inputMessage,
inputMessage:Server.SingUp
})
d.pipe(stream).pipe(d)
)
sock.install(server, '/dnode')
ensureDirSync(LEVEL_DIR)
## Create Jobs
staticJob = queue.create('static', {
title:'Copy images from HTDOCS_DIR to STATIC_DIR',
STATIC_DIR:STATIC_DIR,
htdocsFaviconIco:htdocsFaviconIco,
staticFaviconIco:staticFaviconIco,
htdocsImg:htdocsImg
staticImg:staticImg
}).save()
staticJob.on('complete', ->
queue.create('pugRender', {
title:'Render (transform) pug template to html',
templatePug:templatePug,
indexHtml:indexHtml
}).delay(1).save()
queue.create('stylusRender', {
title:'Render (transform) stylus template to css',
styleStyl:styleStyl,
styleCss:styleCss
}).delay(1).save()
queue.create('browserify', {
title:'Render (transform) coffee template to js',
browserCoffee:browserCoffee,
bundleJs:bundleJs
}).delay(1).save()
queue.create('coffeelint', {
title:'Link coffee files',
files:[clusterCoffee, browserCoffee]
}).delay(1).save() # browserCoffee
)
## **Clean** job list on exit add to class
exitHandler = (options, err) ->
if err
console.log(err.stack)
if options.exit
process.exit()
return
if options.cleanup
console.log('Buy!')
removeSync(STATIC_DIR)
## Do something when app is closing or ctrl+c event or uncaught exceptions
process.on('exit', exitHandler.bind(null, {cleanup:true}))
process.on('SIGINT', exitHandler.bind(null, {exit:true}))
process.on('uncaughtException', exitHandler.bind(null, {exit:true}))
i = 1
while i < numCPUs
cluster.fork()
i += 1
# Worker
else
queue.process('static', Server.static)
queue.process('pugRender', Server.pugRender)
queue.process('stylusRender', Server.stylusRender)
queue.process('browserify', Server.browserify)
queue.process('coffeelint', Server.coffeelint)
| true | # cluster.coffee
# Modules - Модули
_ = require('lodash') # Библиотека Полезных Функций и Операций
fs = require('fs-extra') # Работа с Файловой Системой
os = require('os') # Взаимодействие с Операционной Системой
kue = require('kue') # Автоматизированная Очередь
pug = require('pug') # Перевод из *.pug в *.html
url = require('url') # Форматирование и Парсинг URL ссылок
http = require('http') # HTTP/HTTPS Сервер
shoe = require('shoe') # Прокси
dnode = require('dnode') # Клиент-Сервер для связи с браузером Клиента
level = require('levelup') # База Данных
crypto = require('crypto') # Криптографические функции (хеш-функции)
stylus = require('stylus') # Перевд из *.styl в *.css
natural = require('natural') # Библиотека для обработки текста
cluster = require('cluster') # Управление процессами
request = require('request') # HTTP/HTTPS запросы
coffeeify = require('coffeeify') # Перевод из *.coffee в *.js
browserify = require('browserify') # Загрузчик (транспайлер)
querystring = require('querystring') # Форматирование и Разбор URL-ссылокок
child_process = require('child_process') # Создание дочерних процессов
# Functions - Функции
{exec} = child_process # Функйия для Выполнение команд средствами ОС
{writeFileSync, readFileSync} = fs # Синхронное чтение и запись в файл
{removeSync, mkdirsSync, copySync, ensureDirSync} = fs # Удаление, Создание...
# Environment - Окружение
numCPUs = require('os').cpus().length # Количество Процессорв
# Загрузка значений из файла конфигурации окружения .env (Часть 1)
CORE_DIR = process.env.CORE_DIR
LEVEL_DIR = process.env.LEVEL_DIR
STATIC_DIR = process.env.STATIC_DIR
HTDOCS_DIR = process.env.HTDOCS_DIR
USER_AGENT = process.env.USER_AGENT
KUE_PORT = process.env.KUE_PORT
KUE_HOST = process.env.KUE_HOST
PANEL_PORT = process.env.PANEL_PORT
PANEL_HOST = process.env.PANEL_HOST
IG_COOKIE = process.env.IG_COOKIE
DOMAIN = process.env.DOMAIN
# Загрузка значений из файла конфигурации окружения .env (Часть 2)
KUE_PORT = process.env.KUE_PORT
KUE_HOST = process.env.KUE_HOST
PANEL_PORT = process.env.PANEL_PORT
PANEL_HOST = process.env.PANEL_HOST
IG_COOKIE = process.env.IG_COOKIE
# Files - Файлы
# -- Дирректория для хранения сторонних библиотек для исполнения в браузере -- #
staticJs = "#{STATIC_DIR}/js" # Сторонние библиотеки
staticImg = "#{STATIC_DIR}/img" # Дирректория с Картинками
staticFaviconIco = "#{STATIC_DIR}/favicon.ico" # Иконка для браузера
indexHtml = "#{STATIC_DIR}/index.html" # с помощью pug
styleCss = "#{STATIC_DIR}/style.css" # с помощью stylus
bundleJs = "#{STATIC_DIR}/bundle.js" # coffeeify и browserify
# -------------------------------------------------------------------------- #
# ------------- Исходные Файлы для Генерации Клиентского Кода --------------- #
htdocsJs = "#{HTDOCS_DIR}/js" # Сторонние библиотеки
htdocsImg = "#{HTDOCS_DIR}/img" # Дирректория с Картинками
browserCoffee = "#{HTDOCS_DIR}/client.coffee" # Клиент (Исходник)
htdocsFaviconIco = "#{HTDOCS_DIR}/img/favicon.ico" # Иконка для браузера
templatePug = "#{HTDOCS_DIR}/template.pug" # Исходники для *.html файлов
styleStyl = "#{HTDOCS_DIR}/style.styl" # Исходники для *.css файлов
clusterCoffee = "#{CORE_DIR}/cluster.coffee" # Сервер
# -------------------------------------------------------------------------- #
# Queue - Очередь
queue = kue.createQueue() # Экземпляр (*KUE*) для управления очередью
# Server - Сервер
class Server
# Поиск строки с помощью регулярного выражения и библиотеки natural
@tokenizer:new natural.RegexpTokenizer({pattern:/(https?:\/\/[^\s]+)/g})
@SingUp:(mail, name, pass, cb) => # Регистрация Нового Аккаунта
queue.create('email', {
title: 'welcome email for tj',
to: 'PI:EMAIL:<EMAIL>END_PI',
template: 'welcome-email'}).save()
cb("mail: #{mail}, name: #{name}, pass: #{pass}")
@SingIn:(user, pass, cb) => # Вход в аккаунт (имя/почта:пароль)
cb("user: #{user}, pass: #{pass}")
@inputMessage:(user_id, msg, cb) => # Входящее сообщение
cb("#{user_id}, #{msg}")
@browserify:(job, done) -> # Клиентский код на coffee преабразуется в js
console.log("PID: #{process.pid}\t@browserify")
{browserCoffee, bundleJs} = job.data # Путь к исходнику и путь для экспорта
bundle = browserify({extensions:['.coffee']}) # Указываем расширение
bundle.transform(coffeeify, {
bare:false # Не оборачивать в анаимную функцию
header:false # Помещаем скрипт в body
})
bundle.add(browserCoffee) # Добавляем файл в экземпляр
bundle.bundle((error, js) -> # Собираем bundle.js
throw error if error? # Проверка на ошибку
writeFileSync(bundleJs, js)
done()
)
@coffeelint:(job, done) -> # Проверка кода (статистический анализ)
console.log("PID: #{process.pid}\t@coffeelint")
{files} = job.data # Список Файлов для Анализа
command = 'coffeelint ' + "#{files.join(' ')}" # Формирем команду
exec(command, (err, stdout, stderr) -> # Выполняем комманду сркдствами ОС
console.log(stdout, stderr) # Выводим результат
done()
)
@pugRender:(job, done) -> # Рендерим HTML шаблон
console.log("PID: #{process.pid}\t@pugRender")
{templatePug, indexHtml} = job.data # Путь к исходнику и путь для экспорта
writeFileSync(indexHtml, pug.renderFile(templatePug, {pretty:true}))
# Записываем результат в файл, выбираем читабельный формат
done()
@static:(job, done) -> # Cоздаем файловую структуру
console.log("PID: #{process.pid}\t@static")
{htdocsFaviconIco, staticFaviconIco, htdocsImg, staticImg} = job.data
mkdirsSync(job.data.STATIC_DIR)
mkdirsSync("#{job.data.STATIC_DIR}/files")
copySync(htdocsJs, staticJs)
copySync(htdocsImg, staticImg)
copySync(htdocsFaviconIco, staticFaviconIco)
done()
@stylusRender:(job, done) ->
console.log("PID: #{process.pid}\t@stylusRender")
{styleStyl, styleCss} = job.data
handler = (err, css) ->
if err then throw err
writeFileSync(styleCss, css)
content = readFileSync(styleStyl, {encoding:'utf8'})
stylus.render(content, handler)
done()
# @email:(job, done ) -> "echo 'test' | mail -aFrom:root@#{DOMAIN} #{mail}"
# console.log("PID: #{process.pid}\t@email")
# {files} = job.data # Список Файлов для Анализа
# command = 'coffeelint ' + "#{files.join(' ')}" # Формирем команду
# exec(command, (err, stdout, stderr) -> # Выполняем комманду сркдствами ОС
# console.log(stdout, stderr) # Выводим результат
# done()
# )
# Master
if cluster.isMaster
## Kue
kue.app.set('title', 'Under The Rules')
kue.app.listen(KUE_PORT, KUE_HOST, ->
console.log("Kue: http://#{KUE_HOST}:#{KUE_PORT}.")
kue.Job.rangeByState('complete', 0, 100000, 'asc', (err, jobs) ->
jobs.forEach((job) ->
job.remove( -> return
)
)
)
)
## Ecstatic is a simple static file server middleware.
ecstatic = require('ecstatic')(STATIC_DIR)
server = http.createServer(ecstatic) # Create a HTTP server.
## Starting Dnode. Using dnode via shoe & Install endpoint
server.listen(PANEL_PORT, PANEL_HOST, ->
console.log("Dnode: http://#{PANEL_HOST}:#{PANEL_PORT}")
)
graph = level(LEVEL_DIR + '/graph', {type:'json'})
sock = shoe((stream) -> # Define API object providing integration vith dnode
d = dnode({
inputMessage:Server.inputMessage,
inputMessage:Server.SingUp
})
d.pipe(stream).pipe(d)
)
sock.install(server, '/dnode')
ensureDirSync(LEVEL_DIR)
## Create Jobs
staticJob = queue.create('static', {
title:'Copy images from HTDOCS_DIR to STATIC_DIR',
STATIC_DIR:STATIC_DIR,
htdocsFaviconIco:htdocsFaviconIco,
staticFaviconIco:staticFaviconIco,
htdocsImg:htdocsImg
staticImg:staticImg
}).save()
staticJob.on('complete', ->
queue.create('pugRender', {
title:'Render (transform) pug template to html',
templatePug:templatePug,
indexHtml:indexHtml
}).delay(1).save()
queue.create('stylusRender', {
title:'Render (transform) stylus template to css',
styleStyl:styleStyl,
styleCss:styleCss
}).delay(1).save()
queue.create('browserify', {
title:'Render (transform) coffee template to js',
browserCoffee:browserCoffee,
bundleJs:bundleJs
}).delay(1).save()
queue.create('coffeelint', {
title:'Link coffee files',
files:[clusterCoffee, browserCoffee]
}).delay(1).save() # browserCoffee
)
## **Clean** job list on exit add to class
exitHandler = (options, err) ->
if err
console.log(err.stack)
if options.exit
process.exit()
return
if options.cleanup
console.log('Buy!')
removeSync(STATIC_DIR)
## Do something when app is closing or ctrl+c event or uncaught exceptions
process.on('exit', exitHandler.bind(null, {cleanup:true}))
process.on('SIGINT', exitHandler.bind(null, {exit:true}))
process.on('uncaughtException', exitHandler.bind(null, {exit:true}))
i = 1
while i < numCPUs
cluster.fork()
i += 1
# Worker
else
queue.process('static', Server.static)
queue.process('pugRender', Server.pugRender)
queue.process('stylusRender', Server.stylusRender)
queue.process('browserify', Server.browserify)
queue.process('coffeelint', Server.coffeelint)
|
[
{
"context": "//clicklater(\"login_button\");\n break;\n\n case \"ogamer\":\n var k=getParm(\"pos\");\n p=path(\"//span[@t",
"end": 10349,
"score": 0.8817994594573975,
"start": 10343,
"tag": "USERNAME",
"value": "ogamer"
},
{
"context": " e.innerHTML=toHTML(s);\n\t\t\t}\n ... | libgm.coffee | hilbix/gmlib | 0 | #// BE SURE TO EDIT {{{FILENAME}}}
#// Version 0.{{{VERSION}}}
#//
#// Greasemonkey Library
#
# This is just a Hack to update the GM userscript more rapidly
# Returns false for normal script operation,
# true if hack was loaded and hence the script already ran
# (which means, do not continue with the old script)
#
@GM_evilUpdateHack = (url) =>
#
# Little evil downloader (sync!)
# url -> string or undefined on error
#
rq = (u) ->
log "load", u
r = GM_xmlhttpRequest synchronous:true, url:u, method:'GET'
log "code", r.status
if r.status==200 then r.responseText else undefined
#
# If we are on the special purpose URL (given as arg) page
# perform the update
#
log "update hack on", window.location.href
if window.location.href == url
log "update hack, building update"
GM_setValue url, "" # disable hack if it no more works
# alert(dump(GM_info))
# We need @downloadURL in the user script's Meta section (header)
v = GM_info.scriptMetaStr.match /\/\/\s+@downloadURL\s+(\S*)\s/i
if v.length != 2
alert "missing @downloadURL in userscript metadata, cannot update"
return false
#
# Download the new(?) script
#
s = rq(v[1])
if !s
alert "loading failed, cannot update"
return false
# Load the libraries (@require) from the script, too
l = s.match /\/\/\s+@require\s+\S*\s/gi
q = ""
for i in l
t = rq(i.replace(/\s$/, "").replace(/^.*\s/g, ""))
if t
q += t+";\n"
else
log "library failed, continuing anyway" unless t
#
# Remember the hack
# Prepend the libraries
# But invalidate the GM_evilUpdateHack to prevent recoursion
#
GM_setValue url, q+"\nthis.GM_evilUpdateHack = function(){ this.log('update hack worked') };\n"+s
log "loading hack successful"
#
# Nothing to do if no previously remembered hack present
#
hack = @GM_getValue url
return false unless hack
#
# Check if we are up to date with the hack.
# XXX TODO XXX there is a bug if the script became newer than the hack
# For this add some heuristics above: reload the hack if the script revision changes
#
v = hack.match /\/\/\s+@version\s+(\S*)\s/i
if v?.length==2 and GM_info.script.version == v[1]
log "userscript cought up, removing hack version", v[1]
GM_setValue url, ""
return false
#
# Well, we have a hack loaded, use that
#
log "version", GM_info.script.version, "outdated, running hack version", v[1]
eval hack
log "hack succeeded"
return true
#
# DOM path eval
#
class @Path
constructor: (@path, @parent) ->
@xpath = document.evaluate(@path, (if @parent? then @parent.lastNode else document), null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null)
@nr = 0
sub: (path) -> new Path(path, @)
nx: ->
@last = null
return null unless @xpath?
@nr++
@lastNode = @xpath.iterateNext()
next: ->
return null if @nx
@last = this.lastNode?.textContent
has: (s) ->
@last = this.lastNode?.textContent
return false unless @last
return s in @last
# NOT READY YET
###
p.nextIs=function(s)
{
this.nn();
return this.is(s);
}
p.skip=function(s)
{
if (this.nextIs(s))
return;
fatal(s+" is not in "+trim(t.last));
}
p.find=function(s)
{
while (this.nn() && !this.is(s));
return this.last ? true : false;
}
p.el=function(ignore)
{
if (!this.node)
this.next();
l("el ", this.lastNode);
return !ignore || this.lastNode ? this.lastNode : {};
}
p.all=function()
{
var e;
a = [];
while (e=p.nn())
a.push(e);
// l(a);
return a;
}
return p;
}
// OLD STUFF
function oldstuff() {
window.addEventListener("load", function(){load()}, true);
url=""+document.location.href;
function $(e) { return typeof(e)=="object" ? e : document.getElementById(e); }
function el(e) { return typeof(e)=="object" ? e : document.getElementsByName(e)[0]; }
function delay(f,ms) { window.setTimeout(f, ms ? ms : 100); }
function toHTML(s) { return (""+s).replace(/&/,"&").replace(/</,"<").replace(/</,">"); }
function dummyel(e) { return el(e) || {}; }
function noneg(x) { return x<0 ? 0 : x; }
function startsWith(s,v)
{
return v==s.substr(0,v.length);
}
function fatal(what)
{
l("FATAL: ",what);
throw what;
}
// Random number from 0 to x (including)
function rnd(x)
{
var r = Math.floor(Math.random()*(x+1));
// l("rnd ",r);
return r;
}
// Run some function later with a random delay (to lessen load hostspots)
function later(f,ms)
{
if (!ms)
ms=(rnd(10)>9) ? 10000 : 1500;
l("later", f);
ms+=rnd(ms);
var e=$("content");
if (ms>300)
{
e.style.opacity=0.5;
e.style.background=ms >4000 ? "black" : "grey";
}
delay(f, ms);
}
// Change page to some other URL
function goto(u,ms)
{
if (ms)
later(function(){goto(u)},ms);
else
window.location.href = u;
}
// JavaScript hack to get out of the Greasmonkey Sandbox
function exec(s,ms)
{
goto("javascript:"+s,ms);
}
// Do an artificial click
// The mouse variant is the default as it bubbles through the DOM, so it always works.
// The HTML variant only fires the "onclick" event of the given element.
function click(el,html)
{
if (!el)
return;
if (html)
{
var ev = document.createEvent("HTMLEvents");
ev.initEvent("click", true, true);
}
else
{
var ev=document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
}
l("click ",el.nodeName," named ",el.name);
$(el).dispatchEvent(ev);
}
// Do a click delayed
function clicklater(el,ms)
{
l("clicklater ",dump(el));
later(function() { click(el) }, ms);
}
// Data extraction: Fetch formatted integer
// It must not be a floating point.
function fixInt(s)
{
return s ? parseInt(s.replace(/[.,]/g,"")) : null;
}
// Data extraction: Fetch an integer somewhere in the text
// There must not be more than one number.
// It must not be a floating point.
function extractInt(s)
{
return parseInt(s.replace(/[^0-9]/g,""));
}
// Extract
function getParm(p)
{
var r=new RegExp("^[^?]*\?.*\\b"+p+"=");
l(p," at=",url);
return url.replace(r,"").replace(/&.*$/,"");
}
function trim(s)
{
if (typeof(s)!="string")
return s;
return s.replace(/^[[:space:]]*________/,"").replace(/[[:space:]]*$/,"");
}
function gmSetArray(name,a)
{
var s = "";
l("set a[",name,"]=",dump(a));
for (var i in a)
if (a[i]!="")
s += " "+escape(i)+"="+escape(a[i]);
GM_setValue("u"+uni+"a"+name,s);
}
function gmGetArray(name)
{
var s = GM_getValue("u"+uni+"a"+name);
var a = {};
if (s)
{
s = s.split(" ");
for (var i in s)
{
var t=s[i];
if (!t)
continue;
t=t.split("=");
a[unescape(t[0])]=unescape(t[1]);
}
l("get a[",name,"]=",dump(a));
}
return a;
}
function gmSet(k,v)
{
if (!uni || !uniPlanet)
{
l("cannot gmSet(",k,")=",v);
return;
}
l("gmSet(",k,")=",v);
GM_setValue("u"+uni+"l"+uniPlanet+k,v);
}
function gmGet(k)
{
if (!uni || !uniPlanet)
return "";
return GM_getValue("u"+uni+"l"+uniPlanet+k);
}
function planetGetN(p,k)
{
return gmGet("p"+p+"-"+k);
}
function planetGet(k)
{
return planetGetN(planet,k);
}
function planetSetN(p,k,v)
{
gmSet("p"+p+"-"+k, v);
}
function planetSet(k,v)
{
planetSetN(planet, k, v);
}
function lowPlanet()
{
for (var i=maxPlanet+1; --i>=0; )
if (i!=fromPlanet && enabledPlanet(i))
if (planetGetN(i,"trans")<minTrans)
return i;
return -1;
}
// END OF STANDARD LIBRARY
// BEGIN SPECIAL MODULES
// Selections
var sels = document.getElementsByTagName("select");
function selIdx(x)
{
return sels[x] ? sels[x].selectedIndex : -1;
}
function selOpt(x,y)
{
var o;
o = null;
if (sels[x] && sels[x].options)
o = sels[x].options[y];
return o ? o : {};
}
// END OF SPECIAL MODULES
////////////////////////////////////////////////////////////////////////////////
var uniPlanet=null;
function enabledPlanet(i)
{
n=planetName(i);
return n!=KolonieName && !startsWith(n,MondName) && !startsWith(n,"_");
}
function load()
{
if (sels[0])
for (var i=0; i<sels[0].length; i++)
if (enabledPlanet(i))
maxPlanet=i;
l("maxPlanet=",maxPlanet);
planet = selIdx(0);
if (planet>=0)
{
uniPlanet = planetPos(0);
planetSet("pos",planetPos(planet));
planetSet("name",planetName(planet));
}
var page = getParm("page");
l("page=",page," planet=",planet);
var p=path("//table//td[2]/table//tr[3]//td");
metall=fixInt(p.next());
kristall=fixInt(p.next());
deuterium=fixInt(p.next());
dunkle=fixInt(p.next());
energie=fixInt(p.next());
l("metal=",metall," kristall=",kristall," deuterium=",deuterium);
planetSet("m",metall);
planetSet("k",kristall);
planetSet("d",deuterium);
planetSet("e",energie);
deuterium -=500;
if (deuterium<0)
deuterium=0;
dopage(page);
}
// Estimate Treibstoffverbrauch
function fuelUse(a,b)
{
var d;
d = Math.abs(getInt(a[0])-getInt(b[0]));
if (d>0)
return 700*d;
d = Math.abs(getInt(a[1])-getInt(b[1]));
if (d>0)
return 100*d;
d = Math.abs(getInt(a[2])-getInt(b[2]));
if (d>0)
return 40;
return 1;
}
function bestdebris()
{
var debris = gmGetArray("debris");
var salvag = gmGetArray("salvage");
if (!debris)
return ["",0];
var d = uniPlanet.split(":");
var keys = [];
var worth = {};
for (var a in debris)
{
var v = getInt(debris[a]);
if (v==salvag[a])
continue;
if (v>20000)
v = 20000;
v /= fuelUse(a.split(","),d);
if (v<deuteriumToOther)
continue;
l("worth(",a,")=",v);
keys.push(a);
worth[a] = v;
}
if (!keys.length)
return ["",0];
sorted = keys.sort(function (a,b){return worth[b]-worth[a]})
l(sorted[0],"=",debris[sorted[0]]);
return [sorted[0],Math.ceil(debris[sorted[0]]/20000)];
}
function setZiel(coord,at)
{
if (!at)
at=1;
exec("setTarget("+coord.replace(/:/g,",")+","+at+");shortInfo()");
}
function isin(val,arr)
{
for (var i=arr.length; --i>=0; )
if (val.indexOf(arr[i])>=0)
return arr[i];
return "";
}
// The big switch
function dopage(page)
{
var p;
switch (page)
{
case "http://ogame.de/":
// Universum wählen!
//clicklater("login_button");
break;
case "ogamer":
var k=getParm("pos");
p=path("//span[@title]");
// We must fetch all elements in advance,
// as changing the content invalidates the path.
var all=p.all();
for (var i in all)
{
var e=all[i];
var s=GM_getValue(k+e.title);
if (s=='' || s==null)
{
s = GM_getValue(e.title);
if (s==null)
s='';
s = unescape(s);
}
e.innerHTML=toHTML(s);
}
break;
case "flotten1":
p=path("//body/div[4]//form/table//tr");
p.skip("Neuer Auftrag");
p.skip("Schiffsname");
// Fetch interesting ships
var transporters=0;
var recyclers=0;
while (!p.nextIs("Keine Schiffe") && p.last)
if (p.is("Großer Transporter"))
transporters = extractInt(p.last);
else if (p.is("Recycler"))
recyclers = extractInt(p.last);
planetSet("trans", transporters);
planetSet("recycle", recyclers);
// calculate the number of recyclers of interest
var rec = 0;
var bd = null;
if (recyclers)
{
bd = bestdebris();
rec=bd[1];
}
// calculate the number of transporters
var nr = noneg(Math.floor((metall+kristall+deuterium-3000)/25000));
l("transporters ",transporters, " need ",nr, ", recyclers ",recyclers," need ",rec);
// calculate a special transporter target
i = -1;
if (planet==fromPlanet)
{
var i = gmGet("wantp");
if (i>0)
{
i--;
nr = noneg(gmGet("wantm")-planetGetN(i,"m"));
nr += noneg(gmGet("wantk")-planetGetN(i,"k"));
nr += noneg(gmGet("wantd")-planetGetN(i,"d"));
nr = Math.floor((nr+24900-1)/24900); // rule of thumb, must be a little bit more than needed
gmSet("wantt",nr);
}
else if (transporters>=sendTrans && (i=lowPlanet())>=0)
{
nr = sendTrans;
l("planet ",i," has low transporters");
}
}
gmSet("target",i);
// Now do what is to do.
// First, send transporters
if (nr>transporters)
nr = transporters;
dummyel("ship203").value = nr;
gmSet("autotransport",nr);
// If we are in autosweep mode, propagate it
if (gmGet("autosweep")==planet)
{
gmSet("autosweep",planet-1);
gmSet("autonext", 1);
}
// As long as we were in autosweep mode on this planet
// send the transporters
if (gmGet("autonext"))
{
// Successful send
// Do not run the bounce on autorun
// i is the "target" planet, see gmSet above
if (nr>0 && (i>=0 || planet!=fromPlanet) && enabledPlanet(planet))
{
clicklater(path("//body/div[4]//form/table//tr//input[@type='submit' and @value='Weiter']").el());
break;
}
// Nothing to send anymore, we are finished with this planet
gmSet("autonext", 0);
// Atomatic jump to the next one if there is one.
if (planet>0)
{
prevPlanet();
break;
}
}
gmSet("autosweep", -1);
// As there is nothing to do anymore
// do all the other things
// Try to send recyclers
if (rec>0)
{
if (rec>recyclers)
rec = recyclers;
// replace the transporters by recyclers
dummyel("ship203").value = 0;
dummyel("ship209").value = rec;
gmSet("autotransport",rec);
gmSet("automine",bd[0]);
}
break;
case "flotten2":
var inputs = document.getElementsByTagName("input");
var shp = 0;
var inp = "";
for (var i=inputs.length; --i>=0; )
if (inputs[i].name.substr(0,4)=="ship")
{
inp = inp + "," + inputs[i].name;
shp = getInt(inputs[i].value);
}
var at=gmGet("autotransport");
if (shp!=at)
gmSet("autotransport", 0);
gmSet("fleetmode","");
switch (inp)
{
case ",ship203":
var targ=gmGet("target");
gmSet("fleetmode","stat");
if (planet!=fromPlanet)
{
setZiel(planetGetN(fromPlanet,"pos"));
}
else if (targ<0 || (gmGet("wantp") ? shp!=gmGet("wantt") : at!=sendTrans))
{
setZiel(planetGetN(toPlanet,"pos"));
}
else
{
setZiel(planetGetN(targ,"pos"));
if (gmGet("wantp"))
gmSet("fleetmode", "trans");
}
if (at==shp && planet==maxPlanet && window.confirm("Autosweep?"))
gmSet("autosweep",maxPlanet);
break;
case ",ship209":
if (gmGet("automine"))
{
setZiel(gmGet("automine"),2);
gmSet("fleetmode","mine");
}
break;
}
if (at>0 && at==shp)
clicklater(path("//body/div[4]//table//tr//input[@type='submit' and @value='Weiter']").el());
break;
case "flotten3":
p=path("//body/div[4]//table/tbody/tr[2]/th/table//tr");
var at=gmGet("autotransport");
var targ=gmGet("target");
var wantp=gmGet("wantp")-1;
var from=getGSP("thisgalaxy","thissystem","thisplanet");
var to=getGSP("galaxy","system","planet");
// p.nextIn(ARRAY) ???
while (p.next())
{
switch (isin(p.last,["Transport","Stationieren","Abbau"]))
{
default:
continue;
case "Abbau":
if (gmGet("fleetmode")!="mine" || to.replace(/:/g,",")!=gmGet("automine"))
continue;
break;
case "Transport":
if (gmGet("fleetmode")!="trans" || targ!=wantp || to!=planetGetN(wantp,"pos") || at!=gmGet("wantt"))
continue;
gmSet("wantp", 0);
el("resource1").value = noneg(gmGet("wantm")-planetGetN(targ,"m"));
el("resource2").value = noneg(gmGet("wantk")-planetGetN(targ,"k"));
el("resource3").value = noneg(gmGet("wantd")-planetGetN(targ,"d"));
break;
case "Stationieren":
if (gmGet("fleetmode")!="stat")
{
at = 0;
break;
}
//l("from=",from," to=",to," 1=",planetGetN(fromPlanet,"pos")," 2=",planetGetN(toPlanet,"pos"));
if ((from==planetGetN(fromPlanet,"pos") && to==planetGetN(toPlanet,"pos") && (lowPlanet()!=toPlanet || at!=sendTrans)) ||
( to==planetGetN(fromPlanet,"pos")))
{
//el("resource1").value = noneg(planetGetN(targ,"m")-1000);
//el("resource2").value = noneg(planetGetN(targ,"k")-1000);
//el("resource3").value = noneg(-planetGetN(targ,"d")-1000);
exec("maxResources()");
// reduziere Deuterium um 500?
}
else if (targ<0)
at = 0;
break;
}
delay(function(){
p.sub(".//input").el().checked=true;
if (at)
clicklater(path("//body/div[4]//table//tr//input[@type='submit' and @value='Weiter']").el());
});
return;
}
gmSet("fleetmode","");
break;
case "flottenversand":
switch (gmGet("fleetmode"))
{
case "mine":
// Successful salvage
var sal = gmGetArray("salvage");
var to = gmGet("automine");
sal[to]=gmGetArray("debris")[to];
gmSetArray("salvage",sal);
break;
case "stat":
var targ=gmGet("target");
if (targ>=0)
planetSetN(targ,"trans",planetGetN(targ,"trans")+sendTrans);
break;
}
gmSet("target",-1);
gmSet("autotransport",0);
break;
case "messages":
p=path("//body/div[4]//table//tr/td/table//tr");
while (p.nn())
if (p.is("Flottenkommando"))
if (p.is("Stationierung einer Flotte") ||
p.is("Rückkehr einer Flotte") ||
p.is("Erreichen eines Planeten"))
p.sub(".//input").el().checked=true;
break;
case "galaxy":
gal = fixInt(path("//form//input[@name='galaxy']").el().value);
sys = fixInt(path("//form//input[@name='system']").el().value);
l("gal=",gal," sys=",sys);
p=path("//body/div[3]//table//tr/th/a[@title]");
debris = gmGetArray("debris");
salvage = gmGetArray("salvage");
have = new Array();
for (;;)
{
var e=p.nn();
if (!e)
break;
if (e.title.match(/Tr.mmerfeld/))
{
var s = e.title;
res = fixInt(s.replace(/.*M: /,""))+fixInt(s.replace(/.*K: /,""));
pl = fixInt(e.parentNode.textContent);
l("pl=",pl," res=",res);
have[pl]=res;
here=gal+","+sys+","+pl;
if (salvage[here]!=res)
debris[here]=res;
}
}
for (pl=16; --pl>0; )
if (!have[pl])
{
here = gal+","+sys+","+pl;
salvage[here] = "";
debris[here] = "";
}
gmSetArray("debris",debris);
gmSetArray("salvage",salvage);
break;
case "flotten":
case "buildings":
case "techtree":
case "micropayment":
case "statistics":
case "suche":
case "buddy":
case "options":
case "allianzen":
case "overview":
case "resources":
case "infos": // Gebaeudeinfo
case "notizen": // Notizen
case "renameplanet": // Planet umbenennen
case "flottenversand":
case "bericht":
break;
case "b_building": // Gebäude
BuildingMarker();
BuildingData();
break;
default:
alert(page);
}
}
function planetStr(p)
{
return ""+selOpt(0,p).innerHTML;
}
function planetPos(p)
{
return planetStr(p).replace(/^.*\[/g,"").replace(/\].*$/,"");
}
function planetName(p)
{
return trim(planetStr(p).replace(/\[.*$/g,""));
}
// Switch to previous planet
// There's no opposite, as working backwards is just fine.
function prevPlanet()
{
goto(selOpt(0,planet-1).value, 1500);
}
// Fetch Galaxy, System, Planet from hidden form values
// Form the planet location
function getGSP(g,s,p)
{
return el(g).value+":"+el(s).value+":"+el(p).value;
}
function getInt(s)
{
var i = fixInt(s);
return i ? i : 0;
}
function extract(str,what)
{
var i = str.indexOf(what);
if (i<0)
return 0;
var s = str.substr(i).replace(/^[^0-9]*________/,"").replace(/[[:space:]].*________/,"");
// l(what,s);
return getInt(s);
}
function BuildingGetMKD(o)
{
var need=o.innerHTML.replace(/.*<br>Ben.tigt:/,"").replace(/<br>.*________/,"");
// l("click", need);
// Rundungsprobleme in Ogame.
return [ extract(need,"Metall:")+0, extract(need,"Kristall:")+0, extract(need,"Deuterium:")+0 ];
}
function BuildingDest()
{
var mkd=BuildingGetMKD(this.parentNode.previousSibling);
gmSet("wantp", planet==fromPlanet ? 0 : planet+1);
gmSet("wantm", mkd[0]+1);
gmSet("wantk", mkd[1]+1);
gmSet("wantd", mkd[2]+1);
this.setAttribute('color', '#0000ff');
}
function BuildingMarker()
{
if (planet==fromPlanet)
return;
var m=planetGetN(fromPlanet,"m")+planetGetN(planet,"m");
var k=planetGetN(fromPlanet,"k")+planetGetN(planet,"k");
var d=planetGetN(fromPlanet,"d")+planetGetN(planet,"d");
var p=path('//body/div[4]//table//tr/td/table//tr/td[3]/font[@color="#ff0000"]');
var n=p.all();
for (var x in n)
{
var mkd=BuildingGetMKD(n[x].parentNode.previousSibling);
// l("p ",mkd);
if (m>=mkd[0] && k>=mkd[1] && d>=mkd[2])
{
n[x].addEventListener("click",BuildingDest, true);
n[x].setAttribute('color', '#ffff00');
}
}
}
function innerText(o)
{
var s=""+o.innerHTML;
return s.replace(/<[^>]*>/g," ").replace(/ *________/g," ").replace(/^ /,"");
}
function BuildingData()
{
var p=path('//body/div[4]//table//tr/td/table//tr/td[2]');
var n=p.all();
for (var x in n)
{
var mkd=BuildingGetMKD(n[x]);
var s=innerText(n[x]);
var g=s.replace(/ .*________/,"");
s=s.replace(/\).*________/g,"").replace(/.*\(/,"(");
if (startsWith(s,"(Stufe "))
s = s.substr(7);
else
s = "0";
l(mkd," ",g,"#",s);
planetSet("g"+g,s);
}
}
###
| 175094 | #// BE SURE TO EDIT {{{FILENAME}}}
#// Version 0.{{{VERSION}}}
#//
#// Greasemonkey Library
#
# This is just a Hack to update the GM userscript more rapidly
# Returns false for normal script operation,
# true if hack was loaded and hence the script already ran
# (which means, do not continue with the old script)
#
@GM_evilUpdateHack = (url) =>
#
# Little evil downloader (sync!)
# url -> string or undefined on error
#
rq = (u) ->
log "load", u
r = GM_xmlhttpRequest synchronous:true, url:u, method:'GET'
log "code", r.status
if r.status==200 then r.responseText else undefined
#
# If we are on the special purpose URL (given as arg) page
# perform the update
#
log "update hack on", window.location.href
if window.location.href == url
log "update hack, building update"
GM_setValue url, "" # disable hack if it no more works
# alert(dump(GM_info))
# We need @downloadURL in the user script's Meta section (header)
v = GM_info.scriptMetaStr.match /\/\/\s+@downloadURL\s+(\S*)\s/i
if v.length != 2
alert "missing @downloadURL in userscript metadata, cannot update"
return false
#
# Download the new(?) script
#
s = rq(v[1])
if !s
alert "loading failed, cannot update"
return false
# Load the libraries (@require) from the script, too
l = s.match /\/\/\s+@require\s+\S*\s/gi
q = ""
for i in l
t = rq(i.replace(/\s$/, "").replace(/^.*\s/g, ""))
if t
q += t+";\n"
else
log "library failed, continuing anyway" unless t
#
# Remember the hack
# Prepend the libraries
# But invalidate the GM_evilUpdateHack to prevent recoursion
#
GM_setValue url, q+"\nthis.GM_evilUpdateHack = function(){ this.log('update hack worked') };\n"+s
log "loading hack successful"
#
# Nothing to do if no previously remembered hack present
#
hack = @GM_getValue url
return false unless hack
#
# Check if we are up to date with the hack.
# XXX TODO XXX there is a bug if the script became newer than the hack
# For this add some heuristics above: reload the hack if the script revision changes
#
v = hack.match /\/\/\s+@version\s+(\S*)\s/i
if v?.length==2 and GM_info.script.version == v[1]
log "userscript cought up, removing hack version", v[1]
GM_setValue url, ""
return false
#
# Well, we have a hack loaded, use that
#
log "version", GM_info.script.version, "outdated, running hack version", v[1]
eval hack
log "hack succeeded"
return true
#
# DOM path eval
#
class @Path
constructor: (@path, @parent) ->
@xpath = document.evaluate(@path, (if @parent? then @parent.lastNode else document), null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null)
@nr = 0
sub: (path) -> new Path(path, @)
nx: ->
@last = null
return null unless @xpath?
@nr++
@lastNode = @xpath.iterateNext()
next: ->
return null if @nx
@last = this.lastNode?.textContent
has: (s) ->
@last = this.lastNode?.textContent
return false unless @last
return s in @last
# NOT READY YET
###
p.nextIs=function(s)
{
this.nn();
return this.is(s);
}
p.skip=function(s)
{
if (this.nextIs(s))
return;
fatal(s+" is not in "+trim(t.last));
}
p.find=function(s)
{
while (this.nn() && !this.is(s));
return this.last ? true : false;
}
p.el=function(ignore)
{
if (!this.node)
this.next();
l("el ", this.lastNode);
return !ignore || this.lastNode ? this.lastNode : {};
}
p.all=function()
{
var e;
a = [];
while (e=p.nn())
a.push(e);
// l(a);
return a;
}
return p;
}
// OLD STUFF
function oldstuff() {
window.addEventListener("load", function(){load()}, true);
url=""+document.location.href;
function $(e) { return typeof(e)=="object" ? e : document.getElementById(e); }
function el(e) { return typeof(e)=="object" ? e : document.getElementsByName(e)[0]; }
function delay(f,ms) { window.setTimeout(f, ms ? ms : 100); }
function toHTML(s) { return (""+s).replace(/&/,"&").replace(/</,"<").replace(/</,">"); }
function dummyel(e) { return el(e) || {}; }
function noneg(x) { return x<0 ? 0 : x; }
function startsWith(s,v)
{
return v==s.substr(0,v.length);
}
function fatal(what)
{
l("FATAL: ",what);
throw what;
}
// Random number from 0 to x (including)
function rnd(x)
{
var r = Math.floor(Math.random()*(x+1));
// l("rnd ",r);
return r;
}
// Run some function later with a random delay (to lessen load hostspots)
function later(f,ms)
{
if (!ms)
ms=(rnd(10)>9) ? 10000 : 1500;
l("later", f);
ms+=rnd(ms);
var e=$("content");
if (ms>300)
{
e.style.opacity=0.5;
e.style.background=ms >4000 ? "black" : "grey";
}
delay(f, ms);
}
// Change page to some other URL
function goto(u,ms)
{
if (ms)
later(function(){goto(u)},ms);
else
window.location.href = u;
}
// JavaScript hack to get out of the Greasmonkey Sandbox
function exec(s,ms)
{
goto("javascript:"+s,ms);
}
// Do an artificial click
// The mouse variant is the default as it bubbles through the DOM, so it always works.
// The HTML variant only fires the "onclick" event of the given element.
function click(el,html)
{
if (!el)
return;
if (html)
{
var ev = document.createEvent("HTMLEvents");
ev.initEvent("click", true, true);
}
else
{
var ev=document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
}
l("click ",el.nodeName," named ",el.name);
$(el).dispatchEvent(ev);
}
// Do a click delayed
function clicklater(el,ms)
{
l("clicklater ",dump(el));
later(function() { click(el) }, ms);
}
// Data extraction: Fetch formatted integer
// It must not be a floating point.
function fixInt(s)
{
return s ? parseInt(s.replace(/[.,]/g,"")) : null;
}
// Data extraction: Fetch an integer somewhere in the text
// There must not be more than one number.
// It must not be a floating point.
function extractInt(s)
{
return parseInt(s.replace(/[^0-9]/g,""));
}
// Extract
function getParm(p)
{
var r=new RegExp("^[^?]*\?.*\\b"+p+"=");
l(p," at=",url);
return url.replace(r,"").replace(/&.*$/,"");
}
function trim(s)
{
if (typeof(s)!="string")
return s;
return s.replace(/^[[:space:]]*________/,"").replace(/[[:space:]]*$/,"");
}
function gmSetArray(name,a)
{
var s = "";
l("set a[",name,"]=",dump(a));
for (var i in a)
if (a[i]!="")
s += " "+escape(i)+"="+escape(a[i]);
GM_setValue("u"+uni+"a"+name,s);
}
function gmGetArray(name)
{
var s = GM_getValue("u"+uni+"a"+name);
var a = {};
if (s)
{
s = s.split(" ");
for (var i in s)
{
var t=s[i];
if (!t)
continue;
t=t.split("=");
a[unescape(t[0])]=unescape(t[1]);
}
l("get a[",name,"]=",dump(a));
}
return a;
}
function gmSet(k,v)
{
if (!uni || !uniPlanet)
{
l("cannot gmSet(",k,")=",v);
return;
}
l("gmSet(",k,")=",v);
GM_setValue("u"+uni+"l"+uniPlanet+k,v);
}
function gmGet(k)
{
if (!uni || !uniPlanet)
return "";
return GM_getValue("u"+uni+"l"+uniPlanet+k);
}
function planetGetN(p,k)
{
return gmGet("p"+p+"-"+k);
}
function planetGet(k)
{
return planetGetN(planet,k);
}
function planetSetN(p,k,v)
{
gmSet("p"+p+"-"+k, v);
}
function planetSet(k,v)
{
planetSetN(planet, k, v);
}
function lowPlanet()
{
for (var i=maxPlanet+1; --i>=0; )
if (i!=fromPlanet && enabledPlanet(i))
if (planetGetN(i,"trans")<minTrans)
return i;
return -1;
}
// END OF STANDARD LIBRARY
// BEGIN SPECIAL MODULES
// Selections
var sels = document.getElementsByTagName("select");
function selIdx(x)
{
return sels[x] ? sels[x].selectedIndex : -1;
}
function selOpt(x,y)
{
var o;
o = null;
if (sels[x] && sels[x].options)
o = sels[x].options[y];
return o ? o : {};
}
// END OF SPECIAL MODULES
////////////////////////////////////////////////////////////////////////////////
var uniPlanet=null;
function enabledPlanet(i)
{
n=planetName(i);
return n!=KolonieName && !startsWith(n,MondName) && !startsWith(n,"_");
}
function load()
{
if (sels[0])
for (var i=0; i<sels[0].length; i++)
if (enabledPlanet(i))
maxPlanet=i;
l("maxPlanet=",maxPlanet);
planet = selIdx(0);
if (planet>=0)
{
uniPlanet = planetPos(0);
planetSet("pos",planetPos(planet));
planetSet("name",planetName(planet));
}
var page = getParm("page");
l("page=",page," planet=",planet);
var p=path("//table//td[2]/table//tr[3]//td");
metall=fixInt(p.next());
kristall=fixInt(p.next());
deuterium=fixInt(p.next());
dunkle=fixInt(p.next());
energie=fixInt(p.next());
l("metal=",metall," kristall=",kristall," deuterium=",deuterium);
planetSet("m",metall);
planetSet("k",kristall);
planetSet("d",deuterium);
planetSet("e",energie);
deuterium -=500;
if (deuterium<0)
deuterium=0;
dopage(page);
}
// Estimate Treibstoffverbrauch
function fuelUse(a,b)
{
var d;
d = Math.abs(getInt(a[0])-getInt(b[0]));
if (d>0)
return 700*d;
d = Math.abs(getInt(a[1])-getInt(b[1]));
if (d>0)
return 100*d;
d = Math.abs(getInt(a[2])-getInt(b[2]));
if (d>0)
return 40;
return 1;
}
function bestdebris()
{
var debris = gmGetArray("debris");
var salvag = gmGetArray("salvage");
if (!debris)
return ["",0];
var d = uniPlanet.split(":");
var keys = [];
var worth = {};
for (var a in debris)
{
var v = getInt(debris[a]);
if (v==salvag[a])
continue;
if (v>20000)
v = 20000;
v /= fuelUse(a.split(","),d);
if (v<deuteriumToOther)
continue;
l("worth(",a,")=",v);
keys.push(a);
worth[a] = v;
}
if (!keys.length)
return ["",0];
sorted = keys.sort(function (a,b){return worth[b]-worth[a]})
l(sorted[0],"=",debris[sorted[0]]);
return [sorted[0],Math.ceil(debris[sorted[0]]/20000)];
}
function setZiel(coord,at)
{
if (!at)
at=1;
exec("setTarget("+coord.replace(/:/g,",")+","+at+");shortInfo()");
}
function isin(val,arr)
{
for (var i=arr.length; --i>=0; )
if (val.indexOf(arr[i])>=0)
return arr[i];
return "";
}
// The big switch
function dopage(page)
{
var p;
switch (page)
{
case "http://ogame.de/":
// Universum wählen!
//clicklater("login_button");
break;
case "ogamer":
var k=getParm("pos");
p=path("//span[@title]");
// We must fetch all elements in advance,
// as changing the content invalidates the path.
var all=p.all();
for (var i in all)
{
var e=all[i];
var s=GM_getValue(k+e.title);
if (s=='' || s==null)
{
s = GM_getValue(e.title);
if (s==null)
s='';
s = unescape(s);
}
e.innerHTML=toHTML(s);
}
break;
case "flotten1":
p=path("//body/div[4]//form/table//tr");
p.skip("Neuer Auftrag");
p.skip("Schiffsname");
// Fetch interesting ships
var transporters=0;
var recyclers=0;
while (!p.nextIs("Keine Schiffe") && p.last)
if (p.is("Großer Transporter"))
transporters = extractInt(p.last);
else if (p.is("Recycler"))
recyclers = extractInt(p.last);
planetSet("trans", transporters);
planetSet("recycle", recyclers);
// calculate the number of recyclers of interest
var rec = 0;
var bd = null;
if (recyclers)
{
bd = bestdebris();
rec=bd[1];
}
// calculate the number of transporters
var nr = noneg(Math.floor((metall+kristall+deuterium-3000)/25000));
l("transporters ",transporters, " need ",nr, ", recyclers ",recyclers," need ",rec);
// calculate a special transporter target
i = -1;
if (planet==fromPlanet)
{
var i = gmGet("wantp");
if (i>0)
{
i--;
nr = noneg(gmGet("wantm")-planetGetN(i,"m"));
nr += noneg(gmGet("wantk")-planetGetN(i,"k"));
nr += noneg(gmGet("wantd")-planetGetN(i,"d"));
nr = Math.floor((nr+24900-1)/24900); // rule of thumb, must be a little bit more than needed
gmSet("wantt",nr);
}
else if (transporters>=sendTrans && (i=lowPlanet())>=0)
{
nr = sendTrans;
l("planet ",i," has low transporters");
}
}
gmSet("target",i);
// Now do what is to do.
// First, send transporters
if (nr>transporters)
nr = transporters;
dummyel("ship203").value = nr;
gmSet("autotransport",nr);
// If we are in autosweep mode, propagate it
if (gmGet("autosweep")==planet)
{
gmSet("autosweep",planet-1);
gmSet("autonext", 1);
}
// As long as we were in autosweep mode on this planet
// send the transporters
if (gmGet("autonext"))
{
// Successful send
// Do not run the bounce on autorun
// i is the "target" planet, see gmSet above
if (nr>0 && (i>=0 || planet!=fromPlanet) && enabledPlanet(planet))
{
clicklater(path("//body/div[4]//form/table//tr//input[@type='submit' and @value='<NAME>iter']").el());
break;
}
// Nothing to send anymore, we are finished with this planet
gmSet("autonext", 0);
// Atomatic jump to the next one if there is one.
if (planet>0)
{
prevPlanet();
break;
}
}
gmSet("autosweep", -1);
// As there is nothing to do anymore
// do all the other things
// Try to send recyclers
if (rec>0)
{
if (rec>recyclers)
rec = recyclers;
// replace the transporters by recyclers
dummyel("ship203").value = 0;
dummyel("ship209").value = rec;
gmSet("autotransport",rec);
gmSet("automine",bd[0]);
}
break;
case "flotten2":
var inputs = document.getElementsByTagName("input");
var shp = 0;
var inp = "";
for (var i=inputs.length; --i>=0; )
if (inputs[i].name.substr(0,4)=="ship")
{
inp = inp + "," + inputs[i].name;
shp = getInt(inputs[i].value);
}
var at=gmGet("autotransport");
if (shp!=at)
gmSet("autotransport", 0);
gmSet("fleetmode","");
switch (inp)
{
case ",ship203":
var targ=gmGet("target");
gmSet("fleetmode","stat");
if (planet!=fromPlanet)
{
setZiel(planetGetN(fromPlanet,"pos"));
}
else if (targ<0 || (gmGet("wantp") ? shp!=gmGet("wantt") : at!=sendTrans))
{
setZiel(planetGetN(toPlanet,"pos"));
}
else
{
setZiel(planetGetN(targ,"pos"));
if (gmGet("wantp"))
gmSet("fleetmode", "trans");
}
if (at==shp && planet==maxPlanet && window.confirm("Autosweep?"))
gmSet("autosweep",maxPlanet);
break;
case ",ship209":
if (gmGet("automine"))
{
setZiel(gmGet("automine"),2);
gmSet("fleetmode","mine");
}
break;
}
if (at>0 && at==shp)
clicklater(path("//body/div[4]//table//tr//input[@type='submit' and @value='Weiter']").el());
break;
case "flotten3":
p=path("//body/div[4]//table/tbody/tr[2]/th/table//tr");
var at=gmGet("autotransport");
var targ=gmGet("target");
var wantp=gmGet("wantp")-1;
var from=getGSP("thisgalaxy","thissystem","thisplanet");
var to=getGSP("galaxy","system","planet");
// p.nextIn(ARRAY) ???
while (p.next())
{
switch (isin(p.last,["Transport","Stationieren","Abbau"]))
{
default:
continue;
case "Abbau":
if (gmGet("fleetmode")!="mine" || to.replace(/:/g,",")!=gmGet("automine"))
continue;
break;
case "Transport":
if (gmGet("fleetmode")!="trans" || targ!=wantp || to!=planetGetN(wantp,"pos") || at!=gmGet("wantt"))
continue;
gmSet("wantp", 0);
el("resource1").value = noneg(gmGet("wantm")-planetGetN(targ,"m"));
el("resource2").value = noneg(gmGet("wantk")-planetGetN(targ,"k"));
el("resource3").value = noneg(gmGet("wantd")-planetGetN(targ,"d"));
break;
case "Stationieren":
if (gmGet("fleetmode")!="stat")
{
at = 0;
break;
}
//l("from=",from," to=",to," 1=",planetGetN(fromPlanet,"pos")," 2=",planetGetN(toPlanet,"pos"));
if ((from==planetGetN(fromPlanet,"pos") && to==planetGetN(toPlanet,"pos") && (lowPlanet()!=toPlanet || at!=sendTrans)) ||
( to==planetGetN(fromPlanet,"pos")))
{
//el("resource1").value = noneg(planetGetN(targ,"m")-1000);
//el("resource2").value = noneg(planetGetN(targ,"k")-1000);
//el("resource3").value = noneg(-planetGetN(targ,"d")-1000);
exec("maxResources()");
// reduziere Deuterium um 500?
}
else if (targ<0)
at = 0;
break;
}
delay(function(){
p.sub(".//input").el().checked=true;
if (at)
clicklater(path("//body/div[4]//table//tr//input[@type='submit' and @value='<NAME>']").el());
});
return;
}
gmSet("fleetmode","");
break;
case "flottenversand":
switch (gmGet("fleetmode"))
{
case "mine":
// Successful salvage
var sal = gmGetArray("salvage");
var to = gmGet("automine");
sal[to]=gmGetArray("debris")[to];
gmSetArray("salvage",sal);
break;
case "stat":
var targ=gmGet("target");
if (targ>=0)
planetSetN(targ,"trans",planetGetN(targ,"trans")+sendTrans);
break;
}
gmSet("target",-1);
gmSet("autotransport",0);
break;
case "messages":
p=path("//body/div[4]//table//tr/td/table//tr");
while (p.nn())
if (p.is("Flottenkommando"))
if (p.is("Stationierung einer Flotte") ||
p.is("Rückkehr einer Flotte") ||
p.is("Erreichen eines Planeten"))
p.sub(".//input").el().checked=true;
break;
case "galaxy":
gal = fixInt(path("//form//input[@name='galaxy']").el().value);
sys = fixInt(path("//form//input[@name='system']").el().value);
l("gal=",gal," sys=",sys);
p=path("//body/div[3]//table//tr/th/a[@title]");
debris = gmGetArray("debris");
salvage = gmGetArray("salvage");
have = new Array();
for (;;)
{
var e=p.nn();
if (!e)
break;
if (e.title.match(/Tr.mmerfeld/))
{
var s = e.title;
res = fixInt(s.replace(/.*M: /,""))+fixInt(s.replace(/.*K: /,""));
pl = fixInt(e.parentNode.textContent);
l("pl=",pl," res=",res);
have[pl]=res;
here=gal+","+sys+","+pl;
if (salvage[here]!=res)
debris[here]=res;
}
}
for (pl=16; --pl>0; )
if (!have[pl])
{
here = gal+","+sys+","+pl;
salvage[here] = "";
debris[here] = "";
}
gmSetArray("debris",debris);
gmSetArray("salvage",salvage);
break;
case "flotten":
case "buildings":
case "techtree":
case "micropayment":
case "statistics":
case "suche":
case "buddy":
case "options":
case "allianzen":
case "overview":
case "resources":
case "infos": // Gebaeudeinfo
case "notizen": // Notizen
case "renameplanet": // Planet umbenennen
case "flottenversand":
case "bericht":
break;
case "b_building": // Gebäude
BuildingMarker();
BuildingData();
break;
default:
alert(page);
}
}
function planetStr(p)
{
return ""+selOpt(0,p).innerHTML;
}
function planetPos(p)
{
return planetStr(p).replace(/^.*\[/g,"").replace(/\].*$/,"");
}
function planetName(p)
{
return trim(planetStr(p).replace(/\[.*$/g,""));
}
// Switch to previous planet
// There's no opposite, as working backwards is just fine.
function prevPlanet()
{
goto(selOpt(0,planet-1).value, 1500);
}
// Fetch Galaxy, System, Planet from hidden form values
// Form the planet location
function getGSP(g,s,p)
{
return el(g).value+":"+el(s).value+":"+el(p).value;
}
function getInt(s)
{
var i = fixInt(s);
return i ? i : 0;
}
function extract(str,what)
{
var i = str.indexOf(what);
if (i<0)
return 0;
var s = str.substr(i).replace(/^[^0-9]*________/,"").replace(/[[:space:]].*________/,"");
// l(what,s);
return getInt(s);
}
function BuildingGetMKD(o)
{
var need=o.innerHTML.replace(/.*<br>Ben.tigt:/,"").replace(/<br>.*________/,"");
// l("click", need);
// Rundungsprobleme in Ogame.
return [ extract(need,"Metall:")+0, extract(need,"Kristall:")+0, extract(need,"Deuterium:")+0 ];
}
function BuildingDest()
{
var mkd=BuildingGetMKD(this.parentNode.previousSibling);
gmSet("wantp", planet==fromPlanet ? 0 : planet+1);
gmSet("wantm", mkd[0]+1);
gmSet("wantk", mkd[1]+1);
gmSet("wantd", mkd[2]+1);
this.setAttribute('color', '#0000ff');
}
function BuildingMarker()
{
if (planet==fromPlanet)
return;
var m=planetGetN(fromPlanet,"m")+planetGetN(planet,"m");
var k=planetGetN(fromPlanet,"k")+planetGetN(planet,"k");
var d=planetGetN(fromPlanet,"d")+planetGetN(planet,"d");
var p=path('//body/div[4]//table//tr/td/table//tr/td[3]/font[@color="#ff0000"]');
var n=p.all();
for (var x in n)
{
var mkd=BuildingGetMKD(n[x].parentNode.previousSibling);
// l("p ",mkd);
if (m>=mkd[0] && k>=mkd[1] && d>=mkd[2])
{
n[x].addEventListener("click",BuildingDest, true);
n[x].setAttribute('color', '#ffff00');
}
}
}
function innerText(o)
{
var s=""+o.innerHTML;
return s.replace(/<[^>]*>/g," ").replace(/ *________/g," ").replace(/^ /,"");
}
function BuildingData()
{
var p=path('//body/div[4]//table//tr/td/table//tr/td[2]');
var n=p.all();
for (var x in n)
{
var mkd=BuildingGetMKD(n[x]);
var s=innerText(n[x]);
var g=s.replace(/ .*________/,"");
s=s.replace(/\).*________/g,"").replace(/.*\(/,"(");
if (startsWith(s,"(Stufe "))
s = s.substr(7);
else
s = "0";
l(mkd," ",g,"#",s);
planetSet("g"+g,s);
}
}
###
| true | #// BE SURE TO EDIT {{{FILENAME}}}
#// Version 0.{{{VERSION}}}
#//
#// Greasemonkey Library
#
# This is just a Hack to update the GM userscript more rapidly
# Returns false for normal script operation,
# true if hack was loaded and hence the script already ran
# (which means, do not continue with the old script)
#
@GM_evilUpdateHack = (url) =>
#
# Little evil downloader (sync!)
# url -> string or undefined on error
#
rq = (u) ->
log "load", u
r = GM_xmlhttpRequest synchronous:true, url:u, method:'GET'
log "code", r.status
if r.status==200 then r.responseText else undefined
#
# If we are on the special purpose URL (given as arg) page
# perform the update
#
log "update hack on", window.location.href
if window.location.href == url
log "update hack, building update"
GM_setValue url, "" # disable hack if it no more works
# alert(dump(GM_info))
# We need @downloadURL in the user script's Meta section (header)
v = GM_info.scriptMetaStr.match /\/\/\s+@downloadURL\s+(\S*)\s/i
if v.length != 2
alert "missing @downloadURL in userscript metadata, cannot update"
return false
#
# Download the new(?) script
#
s = rq(v[1])
if !s
alert "loading failed, cannot update"
return false
# Load the libraries (@require) from the script, too
l = s.match /\/\/\s+@require\s+\S*\s/gi
q = ""
for i in l
t = rq(i.replace(/\s$/, "").replace(/^.*\s/g, ""))
if t
q += t+";\n"
else
log "library failed, continuing anyway" unless t
#
# Remember the hack
# Prepend the libraries
# But invalidate the GM_evilUpdateHack to prevent recoursion
#
GM_setValue url, q+"\nthis.GM_evilUpdateHack = function(){ this.log('update hack worked') };\n"+s
log "loading hack successful"
#
# Nothing to do if no previously remembered hack present
#
hack = @GM_getValue url
return false unless hack
#
# Check if we are up to date with the hack.
# XXX TODO XXX there is a bug if the script became newer than the hack
# For this add some heuristics above: reload the hack if the script revision changes
#
v = hack.match /\/\/\s+@version\s+(\S*)\s/i
if v?.length==2 and GM_info.script.version == v[1]
log "userscript cought up, removing hack version", v[1]
GM_setValue url, ""
return false
#
# Well, we have a hack loaded, use that
#
log "version", GM_info.script.version, "outdated, running hack version", v[1]
eval hack
log "hack succeeded"
return true
#
# DOM path eval
#
class @Path
constructor: (@path, @parent) ->
@xpath = document.evaluate(@path, (if @parent? then @parent.lastNode else document), null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null)
@nr = 0
sub: (path) -> new Path(path, @)
nx: ->
@last = null
return null unless @xpath?
@nr++
@lastNode = @xpath.iterateNext()
next: ->
return null if @nx
@last = this.lastNode?.textContent
has: (s) ->
@last = this.lastNode?.textContent
return false unless @last
return s in @last
# NOT READY YET
###
p.nextIs=function(s)
{
this.nn();
return this.is(s);
}
p.skip=function(s)
{
if (this.nextIs(s))
return;
fatal(s+" is not in "+trim(t.last));
}
p.find=function(s)
{
while (this.nn() && !this.is(s));
return this.last ? true : false;
}
p.el=function(ignore)
{
if (!this.node)
this.next();
l("el ", this.lastNode);
return !ignore || this.lastNode ? this.lastNode : {};
}
p.all=function()
{
var e;
a = [];
while (e=p.nn())
a.push(e);
// l(a);
return a;
}
return p;
}
// OLD STUFF
function oldstuff() {
window.addEventListener("load", function(){load()}, true);
url=""+document.location.href;
function $(e) { return typeof(e)=="object" ? e : document.getElementById(e); }
function el(e) { return typeof(e)=="object" ? e : document.getElementsByName(e)[0]; }
function delay(f,ms) { window.setTimeout(f, ms ? ms : 100); }
function toHTML(s) { return (""+s).replace(/&/,"&").replace(/</,"<").replace(/</,">"); }
function dummyel(e) { return el(e) || {}; }
function noneg(x) { return x<0 ? 0 : x; }
function startsWith(s,v)
{
return v==s.substr(0,v.length);
}
function fatal(what)
{
l("FATAL: ",what);
throw what;
}
// Random number from 0 to x (including)
function rnd(x)
{
var r = Math.floor(Math.random()*(x+1));
// l("rnd ",r);
return r;
}
// Run some function later with a random delay (to lessen load hostspots)
function later(f,ms)
{
if (!ms)
ms=(rnd(10)>9) ? 10000 : 1500;
l("later", f);
ms+=rnd(ms);
var e=$("content");
if (ms>300)
{
e.style.opacity=0.5;
e.style.background=ms >4000 ? "black" : "grey";
}
delay(f, ms);
}
// Change page to some other URL
function goto(u,ms)
{
if (ms)
later(function(){goto(u)},ms);
else
window.location.href = u;
}
// JavaScript hack to get out of the Greasmonkey Sandbox
function exec(s,ms)
{
goto("javascript:"+s,ms);
}
// Do an artificial click
// The mouse variant is the default as it bubbles through the DOM, so it always works.
// The HTML variant only fires the "onclick" event of the given element.
function click(el,html)
{
if (!el)
return;
if (html)
{
var ev = document.createEvent("HTMLEvents");
ev.initEvent("click", true, true);
}
else
{
var ev=document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
}
l("click ",el.nodeName," named ",el.name);
$(el).dispatchEvent(ev);
}
// Do a click delayed
function clicklater(el,ms)
{
l("clicklater ",dump(el));
later(function() { click(el) }, ms);
}
// Data extraction: Fetch formatted integer
// It must not be a floating point.
function fixInt(s)
{
return s ? parseInt(s.replace(/[.,]/g,"")) : null;
}
// Data extraction: Fetch an integer somewhere in the text
// There must not be more than one number.
// It must not be a floating point.
function extractInt(s)
{
return parseInt(s.replace(/[^0-9]/g,""));
}
// Extract
function getParm(p)
{
var r=new RegExp("^[^?]*\?.*\\b"+p+"=");
l(p," at=",url);
return url.replace(r,"").replace(/&.*$/,"");
}
function trim(s)
{
if (typeof(s)!="string")
return s;
return s.replace(/^[[:space:]]*________/,"").replace(/[[:space:]]*$/,"");
}
function gmSetArray(name,a)
{
var s = "";
l("set a[",name,"]=",dump(a));
for (var i in a)
if (a[i]!="")
s += " "+escape(i)+"="+escape(a[i]);
GM_setValue("u"+uni+"a"+name,s);
}
function gmGetArray(name)
{
var s = GM_getValue("u"+uni+"a"+name);
var a = {};
if (s)
{
s = s.split(" ");
for (var i in s)
{
var t=s[i];
if (!t)
continue;
t=t.split("=");
a[unescape(t[0])]=unescape(t[1]);
}
l("get a[",name,"]=",dump(a));
}
return a;
}
function gmSet(k,v)
{
if (!uni || !uniPlanet)
{
l("cannot gmSet(",k,")=",v);
return;
}
l("gmSet(",k,")=",v);
GM_setValue("u"+uni+"l"+uniPlanet+k,v);
}
function gmGet(k)
{
if (!uni || !uniPlanet)
return "";
return GM_getValue("u"+uni+"l"+uniPlanet+k);
}
function planetGetN(p,k)
{
return gmGet("p"+p+"-"+k);
}
function planetGet(k)
{
return planetGetN(planet,k);
}
function planetSetN(p,k,v)
{
gmSet("p"+p+"-"+k, v);
}
function planetSet(k,v)
{
planetSetN(planet, k, v);
}
function lowPlanet()
{
for (var i=maxPlanet+1; --i>=0; )
if (i!=fromPlanet && enabledPlanet(i))
if (planetGetN(i,"trans")<minTrans)
return i;
return -1;
}
// END OF STANDARD LIBRARY
// BEGIN SPECIAL MODULES
// Selections
var sels = document.getElementsByTagName("select");
function selIdx(x)
{
return sels[x] ? sels[x].selectedIndex : -1;
}
function selOpt(x,y)
{
var o;
o = null;
if (sels[x] && sels[x].options)
o = sels[x].options[y];
return o ? o : {};
}
// END OF SPECIAL MODULES
////////////////////////////////////////////////////////////////////////////////
var uniPlanet=null;
function enabledPlanet(i)
{
n=planetName(i);
return n!=KolonieName && !startsWith(n,MondName) && !startsWith(n,"_");
}
function load()
{
if (sels[0])
for (var i=0; i<sels[0].length; i++)
if (enabledPlanet(i))
maxPlanet=i;
l("maxPlanet=",maxPlanet);
planet = selIdx(0);
if (planet>=0)
{
uniPlanet = planetPos(0);
planetSet("pos",planetPos(planet));
planetSet("name",planetName(planet));
}
var page = getParm("page");
l("page=",page," planet=",planet);
var p=path("//table//td[2]/table//tr[3]//td");
metall=fixInt(p.next());
kristall=fixInt(p.next());
deuterium=fixInt(p.next());
dunkle=fixInt(p.next());
energie=fixInt(p.next());
l("metal=",metall," kristall=",kristall," deuterium=",deuterium);
planetSet("m",metall);
planetSet("k",kristall);
planetSet("d",deuterium);
planetSet("e",energie);
deuterium -=500;
if (deuterium<0)
deuterium=0;
dopage(page);
}
// Estimate Treibstoffverbrauch
function fuelUse(a,b)
{
var d;
d = Math.abs(getInt(a[0])-getInt(b[0]));
if (d>0)
return 700*d;
d = Math.abs(getInt(a[1])-getInt(b[1]));
if (d>0)
return 100*d;
d = Math.abs(getInt(a[2])-getInt(b[2]));
if (d>0)
return 40;
return 1;
}
function bestdebris()
{
var debris = gmGetArray("debris");
var salvag = gmGetArray("salvage");
if (!debris)
return ["",0];
var d = uniPlanet.split(":");
var keys = [];
var worth = {};
for (var a in debris)
{
var v = getInt(debris[a]);
if (v==salvag[a])
continue;
if (v>20000)
v = 20000;
v /= fuelUse(a.split(","),d);
if (v<deuteriumToOther)
continue;
l("worth(",a,")=",v);
keys.push(a);
worth[a] = v;
}
if (!keys.length)
return ["",0];
sorted = keys.sort(function (a,b){return worth[b]-worth[a]})
l(sorted[0],"=",debris[sorted[0]]);
return [sorted[0],Math.ceil(debris[sorted[0]]/20000)];
}
function setZiel(coord,at)
{
if (!at)
at=1;
exec("setTarget("+coord.replace(/:/g,",")+","+at+");shortInfo()");
}
function isin(val,arr)
{
for (var i=arr.length; --i>=0; )
if (val.indexOf(arr[i])>=0)
return arr[i];
return "";
}
// The big switch
function dopage(page)
{
var p;
switch (page)
{
case "http://ogame.de/":
// Universum wählen!
//clicklater("login_button");
break;
case "ogamer":
var k=getParm("pos");
p=path("//span[@title]");
// We must fetch all elements in advance,
// as changing the content invalidates the path.
var all=p.all();
for (var i in all)
{
var e=all[i];
var s=GM_getValue(k+e.title);
if (s=='' || s==null)
{
s = GM_getValue(e.title);
if (s==null)
s='';
s = unescape(s);
}
e.innerHTML=toHTML(s);
}
break;
case "flotten1":
p=path("//body/div[4]//form/table//tr");
p.skip("Neuer Auftrag");
p.skip("Schiffsname");
// Fetch interesting ships
var transporters=0;
var recyclers=0;
while (!p.nextIs("Keine Schiffe") && p.last)
if (p.is("Großer Transporter"))
transporters = extractInt(p.last);
else if (p.is("Recycler"))
recyclers = extractInt(p.last);
planetSet("trans", transporters);
planetSet("recycle", recyclers);
// calculate the number of recyclers of interest
var rec = 0;
var bd = null;
if (recyclers)
{
bd = bestdebris();
rec=bd[1];
}
// calculate the number of transporters
var nr = noneg(Math.floor((metall+kristall+deuterium-3000)/25000));
l("transporters ",transporters, " need ",nr, ", recyclers ",recyclers," need ",rec);
// calculate a special transporter target
i = -1;
if (planet==fromPlanet)
{
var i = gmGet("wantp");
if (i>0)
{
i--;
nr = noneg(gmGet("wantm")-planetGetN(i,"m"));
nr += noneg(gmGet("wantk")-planetGetN(i,"k"));
nr += noneg(gmGet("wantd")-planetGetN(i,"d"));
nr = Math.floor((nr+24900-1)/24900); // rule of thumb, must be a little bit more than needed
gmSet("wantt",nr);
}
else if (transporters>=sendTrans && (i=lowPlanet())>=0)
{
nr = sendTrans;
l("planet ",i," has low transporters");
}
}
gmSet("target",i);
// Now do what is to do.
// First, send transporters
if (nr>transporters)
nr = transporters;
dummyel("ship203").value = nr;
gmSet("autotransport",nr);
// If we are in autosweep mode, propagate it
if (gmGet("autosweep")==planet)
{
gmSet("autosweep",planet-1);
gmSet("autonext", 1);
}
// As long as we were in autosweep mode on this planet
// send the transporters
if (gmGet("autonext"))
{
// Successful send
// Do not run the bounce on autorun
// i is the "target" planet, see gmSet above
if (nr>0 && (i>=0 || planet!=fromPlanet) && enabledPlanet(planet))
{
clicklater(path("//body/div[4]//form/table//tr//input[@type='submit' and @value='PI:NAME:<NAME>END_PIiter']").el());
break;
}
// Nothing to send anymore, we are finished with this planet
gmSet("autonext", 0);
// Atomatic jump to the next one if there is one.
if (planet>0)
{
prevPlanet();
break;
}
}
gmSet("autosweep", -1);
// As there is nothing to do anymore
// do all the other things
// Try to send recyclers
if (rec>0)
{
if (rec>recyclers)
rec = recyclers;
// replace the transporters by recyclers
dummyel("ship203").value = 0;
dummyel("ship209").value = rec;
gmSet("autotransport",rec);
gmSet("automine",bd[0]);
}
break;
case "flotten2":
var inputs = document.getElementsByTagName("input");
var shp = 0;
var inp = "";
for (var i=inputs.length; --i>=0; )
if (inputs[i].name.substr(0,4)=="ship")
{
inp = inp + "," + inputs[i].name;
shp = getInt(inputs[i].value);
}
var at=gmGet("autotransport");
if (shp!=at)
gmSet("autotransport", 0);
gmSet("fleetmode","");
switch (inp)
{
case ",ship203":
var targ=gmGet("target");
gmSet("fleetmode","stat");
if (planet!=fromPlanet)
{
setZiel(planetGetN(fromPlanet,"pos"));
}
else if (targ<0 || (gmGet("wantp") ? shp!=gmGet("wantt") : at!=sendTrans))
{
setZiel(planetGetN(toPlanet,"pos"));
}
else
{
setZiel(planetGetN(targ,"pos"));
if (gmGet("wantp"))
gmSet("fleetmode", "trans");
}
if (at==shp && planet==maxPlanet && window.confirm("Autosweep?"))
gmSet("autosweep",maxPlanet);
break;
case ",ship209":
if (gmGet("automine"))
{
setZiel(gmGet("automine"),2);
gmSet("fleetmode","mine");
}
break;
}
if (at>0 && at==shp)
clicklater(path("//body/div[4]//table//tr//input[@type='submit' and @value='Weiter']").el());
break;
case "flotten3":
p=path("//body/div[4]//table/tbody/tr[2]/th/table//tr");
var at=gmGet("autotransport");
var targ=gmGet("target");
var wantp=gmGet("wantp")-1;
var from=getGSP("thisgalaxy","thissystem","thisplanet");
var to=getGSP("galaxy","system","planet");
// p.nextIn(ARRAY) ???
while (p.next())
{
switch (isin(p.last,["Transport","Stationieren","Abbau"]))
{
default:
continue;
case "Abbau":
if (gmGet("fleetmode")!="mine" || to.replace(/:/g,",")!=gmGet("automine"))
continue;
break;
case "Transport":
if (gmGet("fleetmode")!="trans" || targ!=wantp || to!=planetGetN(wantp,"pos") || at!=gmGet("wantt"))
continue;
gmSet("wantp", 0);
el("resource1").value = noneg(gmGet("wantm")-planetGetN(targ,"m"));
el("resource2").value = noneg(gmGet("wantk")-planetGetN(targ,"k"));
el("resource3").value = noneg(gmGet("wantd")-planetGetN(targ,"d"));
break;
case "Stationieren":
if (gmGet("fleetmode")!="stat")
{
at = 0;
break;
}
//l("from=",from," to=",to," 1=",planetGetN(fromPlanet,"pos")," 2=",planetGetN(toPlanet,"pos"));
if ((from==planetGetN(fromPlanet,"pos") && to==planetGetN(toPlanet,"pos") && (lowPlanet()!=toPlanet || at!=sendTrans)) ||
( to==planetGetN(fromPlanet,"pos")))
{
//el("resource1").value = noneg(planetGetN(targ,"m")-1000);
//el("resource2").value = noneg(planetGetN(targ,"k")-1000);
//el("resource3").value = noneg(-planetGetN(targ,"d")-1000);
exec("maxResources()");
// reduziere Deuterium um 500?
}
else if (targ<0)
at = 0;
break;
}
delay(function(){
p.sub(".//input").el().checked=true;
if (at)
clicklater(path("//body/div[4]//table//tr//input[@type='submit' and @value='PI:NAME:<NAME>END_PI']").el());
});
return;
}
gmSet("fleetmode","");
break;
case "flottenversand":
switch (gmGet("fleetmode"))
{
case "mine":
// Successful salvage
var sal = gmGetArray("salvage");
var to = gmGet("automine");
sal[to]=gmGetArray("debris")[to];
gmSetArray("salvage",sal);
break;
case "stat":
var targ=gmGet("target");
if (targ>=0)
planetSetN(targ,"trans",planetGetN(targ,"trans")+sendTrans);
break;
}
gmSet("target",-1);
gmSet("autotransport",0);
break;
case "messages":
p=path("//body/div[4]//table//tr/td/table//tr");
while (p.nn())
if (p.is("Flottenkommando"))
if (p.is("Stationierung einer Flotte") ||
p.is("Rückkehr einer Flotte") ||
p.is("Erreichen eines Planeten"))
p.sub(".//input").el().checked=true;
break;
case "galaxy":
gal = fixInt(path("//form//input[@name='galaxy']").el().value);
sys = fixInt(path("//form//input[@name='system']").el().value);
l("gal=",gal," sys=",sys);
p=path("//body/div[3]//table//tr/th/a[@title]");
debris = gmGetArray("debris");
salvage = gmGetArray("salvage");
have = new Array();
for (;;)
{
var e=p.nn();
if (!e)
break;
if (e.title.match(/Tr.mmerfeld/))
{
var s = e.title;
res = fixInt(s.replace(/.*M: /,""))+fixInt(s.replace(/.*K: /,""));
pl = fixInt(e.parentNode.textContent);
l("pl=",pl," res=",res);
have[pl]=res;
here=gal+","+sys+","+pl;
if (salvage[here]!=res)
debris[here]=res;
}
}
for (pl=16; --pl>0; )
if (!have[pl])
{
here = gal+","+sys+","+pl;
salvage[here] = "";
debris[here] = "";
}
gmSetArray("debris",debris);
gmSetArray("salvage",salvage);
break;
case "flotten":
case "buildings":
case "techtree":
case "micropayment":
case "statistics":
case "suche":
case "buddy":
case "options":
case "allianzen":
case "overview":
case "resources":
case "infos": // Gebaeudeinfo
case "notizen": // Notizen
case "renameplanet": // Planet umbenennen
case "flottenversand":
case "bericht":
break;
case "b_building": // Gebäude
BuildingMarker();
BuildingData();
break;
default:
alert(page);
}
}
function planetStr(p)
{
return ""+selOpt(0,p).innerHTML;
}
function planetPos(p)
{
return planetStr(p).replace(/^.*\[/g,"").replace(/\].*$/,"");
}
function planetName(p)
{
return trim(planetStr(p).replace(/\[.*$/g,""));
}
// Switch to previous planet
// There's no opposite, as working backwards is just fine.
function prevPlanet()
{
goto(selOpt(0,planet-1).value, 1500);
}
// Fetch Galaxy, System, Planet from hidden form values
// Form the planet location
function getGSP(g,s,p)
{
return el(g).value+":"+el(s).value+":"+el(p).value;
}
function getInt(s)
{
var i = fixInt(s);
return i ? i : 0;
}
function extract(str,what)
{
var i = str.indexOf(what);
if (i<0)
return 0;
var s = str.substr(i).replace(/^[^0-9]*________/,"").replace(/[[:space:]].*________/,"");
// l(what,s);
return getInt(s);
}
function BuildingGetMKD(o)
{
var need=o.innerHTML.replace(/.*<br>Ben.tigt:/,"").replace(/<br>.*________/,"");
// l("click", need);
// Rundungsprobleme in Ogame.
return [ extract(need,"Metall:")+0, extract(need,"Kristall:")+0, extract(need,"Deuterium:")+0 ];
}
function BuildingDest()
{
var mkd=BuildingGetMKD(this.parentNode.previousSibling);
gmSet("wantp", planet==fromPlanet ? 0 : planet+1);
gmSet("wantm", mkd[0]+1);
gmSet("wantk", mkd[1]+1);
gmSet("wantd", mkd[2]+1);
this.setAttribute('color', '#0000ff');
}
function BuildingMarker()
{
if (planet==fromPlanet)
return;
var m=planetGetN(fromPlanet,"m")+planetGetN(planet,"m");
var k=planetGetN(fromPlanet,"k")+planetGetN(planet,"k");
var d=planetGetN(fromPlanet,"d")+planetGetN(planet,"d");
var p=path('//body/div[4]//table//tr/td/table//tr/td[3]/font[@color="#ff0000"]');
var n=p.all();
for (var x in n)
{
var mkd=BuildingGetMKD(n[x].parentNode.previousSibling);
// l("p ",mkd);
if (m>=mkd[0] && k>=mkd[1] && d>=mkd[2])
{
n[x].addEventListener("click",BuildingDest, true);
n[x].setAttribute('color', '#ffff00');
}
}
}
function innerText(o)
{
var s=""+o.innerHTML;
return s.replace(/<[^>]*>/g," ").replace(/ *________/g," ").replace(/^ /,"");
}
function BuildingData()
{
var p=path('//body/div[4]//table//tr/td/table//tr/td[2]');
var n=p.all();
for (var x in n)
{
var mkd=BuildingGetMKD(n[x]);
var s=innerText(n[x]);
var g=s.replace(/ .*________/,"");
s=s.replace(/\).*________/g,"").replace(/.*\(/,"(");
if (startsWith(s,"(Stufe "))
s = s.substr(7);
else
s = "0";
l(mkd," ",g,"#",s);
planetSet("g"+g,s);
}
}
###
|
[
{
"context": "bac446b229838867bf60dd55289213\",\n \"authorName\": \"Bee\",\n \"authorDate\": 1445053404,\n \"message\": \"git-u",
"end": 287,
"score": 0.8132683038711548,
"start": 284,
"tag": "NAME",
"value": "Bee"
},
{
"context": "1c12f2ba8c92eb1100964f98901caa\",\n \"authorName... | spec/test-data/fiveCommitsExpected.coffee | Jeverett3000/git-time-machine | 1,235 | ###
this is the expected data for the first five commits of test-data/fiveCommits.txt.
Only the keys in these objects are tested against the actual first five commits read
from git log
###
module.exports = [{
"id": "4d3547944bbac446b229838867bf60dd55289213",
"authorName": "Bee",
"authorDate": 1445053404,
"message": "git-util-spec: fifth commit of spec/testData/fiveCommits.txt. only deleted a line",
"hash": "4d35479",
"linesAdded": 0,
"linesDeleted": 2
}, {
"id": "fa4aee05281c12f2ba8c92eb1100964f98901caa",
"authorName": "Bee",
"authorDate": 1445053316,
"message": "git-util-spec: forth commit of spec/testData/fiveCommits.txt",
"hash": "fa4aee0",
"linesAdded": 1,
"linesDeleted": 0
}, {
"id": "010f49a2cf4fb08f7117782269ce8ede07e0797a",
"authorName": "Bee",
"authorDate": 1445053277,
"message": "git-util-spec: third commit of spec/testData/fiveCommits.txt",
"hash": "010f49a",
"linesAdded": 2,
"linesDeleted": 1
}, {
"id": "3d03801db29c1f9d92550c8bfed32b21c08ced4c",
"authorName": "Bee",
"authorDate": 1445053179,
"message": "git-util-spec: load correct fully qualified test file name. plus second commit of fiveCommits.txt",
"hash": "3d03801",
"linesAdded": 2,
"linesDeleted": 0
}, {
"id": "bb7b15fc68e681347185003ddb534366465c5b36",
"authorName": "Bee",
"authorDate": 1445052734,
"message": "GitUtils.getFileCommitHistory should return valid data. +new failing test",
"hash": "bb7b15f",
"linesAdded": 7,
"linesDeleted": 0
}]
| 78382 | ###
this is the expected data for the first five commits of test-data/fiveCommits.txt.
Only the keys in these objects are tested against the actual first five commits read
from git log
###
module.exports = [{
"id": "4d3547944bbac446b229838867bf60dd55289213",
"authorName": "<NAME>",
"authorDate": 1445053404,
"message": "git-util-spec: fifth commit of spec/testData/fiveCommits.txt. only deleted a line",
"hash": "4d35479",
"linesAdded": 0,
"linesDeleted": 2
}, {
"id": "fa4aee05281c12f2ba8c92eb1100964f98901caa",
"authorName": "<NAME>",
"authorDate": 1445053316,
"message": "git-util-spec: forth commit of spec/testData/fiveCommits.txt",
"hash": "fa4aee0",
"linesAdded": 1,
"linesDeleted": 0
}, {
"id": "010f49a2cf4fb08f7117782269ce8ede07e0797a",
"authorName": "<NAME>",
"authorDate": 1445053277,
"message": "git-util-spec: third commit of spec/testData/fiveCommits.txt",
"hash": "010f49a",
"linesAdded": 2,
"linesDeleted": 1
}, {
"id": "3d03801db29c1f9d92550c8bfed32b21c08ced4c",
"authorName": "<NAME>",
"authorDate": 1445053179,
"message": "git-util-spec: load correct fully qualified test file name. plus second commit of fiveCommits.txt",
"hash": "3d03801",
"linesAdded": 2,
"linesDeleted": 0
}, {
"id": "bb7b15fc68e681347185003ddb534366465c5b36",
"authorName": "Bee",
"authorDate": 1445052734,
"message": "GitUtils.getFileCommitHistory should return valid data. +new failing test",
"hash": "bb7b15f",
"linesAdded": 7,
"linesDeleted": 0
}]
| true | ###
this is the expected data for the first five commits of test-data/fiveCommits.txt.
Only the keys in these objects are tested against the actual first five commits read
from git log
###
module.exports = [{
"id": "4d3547944bbac446b229838867bf60dd55289213",
"authorName": "PI:NAME:<NAME>END_PI",
"authorDate": 1445053404,
"message": "git-util-spec: fifth commit of spec/testData/fiveCommits.txt. only deleted a line",
"hash": "4d35479",
"linesAdded": 0,
"linesDeleted": 2
}, {
"id": "fa4aee05281c12f2ba8c92eb1100964f98901caa",
"authorName": "PI:NAME:<NAME>END_PI",
"authorDate": 1445053316,
"message": "git-util-spec: forth commit of spec/testData/fiveCommits.txt",
"hash": "fa4aee0",
"linesAdded": 1,
"linesDeleted": 0
}, {
"id": "010f49a2cf4fb08f7117782269ce8ede07e0797a",
"authorName": "PI:NAME:<NAME>END_PI",
"authorDate": 1445053277,
"message": "git-util-spec: third commit of spec/testData/fiveCommits.txt",
"hash": "010f49a",
"linesAdded": 2,
"linesDeleted": 1
}, {
"id": "3d03801db29c1f9d92550c8bfed32b21c08ced4c",
"authorName": "PI:NAME:<NAME>END_PI",
"authorDate": 1445053179,
"message": "git-util-spec: load correct fully qualified test file name. plus second commit of fiveCommits.txt",
"hash": "3d03801",
"linesAdded": 2,
"linesDeleted": 0
}, {
"id": "bb7b15fc68e681347185003ddb534366465c5b36",
"authorName": "Bee",
"authorDate": 1445052734,
"message": "GitUtils.getFileCommitHistory should return valid data. +new failing test",
"hash": "bb7b15f",
"linesAdded": 7,
"linesDeleted": 0
}]
|
[
{
"context": "his.data =\n en:\n name: \"PHUONG LE HOANG\",\n position: \"WEB DEVELOPER\",\n ",
"end": 190,
"score": 0.9998460412025452,
"start": 175,
"tag": "NAME",
"value": "PHUONG LE HOANG"
},
{
"context": "ONTACT ME\"\n vi:\n... | js/main.coffee | lephuongbg/lephuongbg.github.io | 0 | "use strict";
do ->
app = angular.module "vCard", ["ngAnimate"]
app.controller "VCardController", [->
this.data =
en:
name: "PHUONG LE HOANG",
position: "WEB DEVELOPER",
callToAction: "CONTACT ME"
vi:
name: "LÊ HOÀNG PHƯƠNG",
position: "NHÀ PHÁT TRIỂN WEB",
callToAction: "LIÊN HẸ"
ja:
name: "レ ホアン フォン"
position: "ウェブ開発者"
callToAction: "メールを送る"
this.active = "en"
]
app.directive "cardRippleTrigger", [->
restrict: "A"
link: (scope, element) ->
element.on "click", (event) ->
ripple = document.createElement "div"
ripple.className = "ripple"
ripple.style.top = element[0].offsetTop + "px"
ripple.style.left = element[0].offsetLeft + "px"
ripple.addEventListener "animationend", (event) ->
ripple.remove()
angular.element(document.getElementById("card")).append ripple
]
app.animation ".lang-content", ["$animateCss", ($animateCss) ->
enter: (element) ->
parent = element.parent()
sibling = element.siblings()
$animateCss parent,
from:
width: sibling.width()
height: sibling.height()
to:
width: element.width()
height: element.height()
transitionStyle: '.5s cubic-bezier(.55, 0, .1, 1) all'
.start().done ->
parent.css 'width', ''
parent.css 'height', ''
$animateCss element, {event: "enter", structural: true}
leave: (element) ->
$animateCss element, {event: "leave", structural: true}
]
| 224640 | "use strict";
do ->
app = angular.module "vCard", ["ngAnimate"]
app.controller "VCardController", [->
this.data =
en:
name: "<NAME>",
position: "WEB DEVELOPER",
callToAction: "CONTACT ME"
vi:
name: "<NAME>",
position: "NHÀ PHÁT TRIỂN WEB",
callToAction: "LIÊN HẸ"
ja:
name: "<NAME> <NAME>"
position: "ウェブ開発者"
callToAction: "メールを送る"
this.active = "en"
]
app.directive "cardRippleTrigger", [->
restrict: "A"
link: (scope, element) ->
element.on "click", (event) ->
ripple = document.createElement "div"
ripple.className = "ripple"
ripple.style.top = element[0].offsetTop + "px"
ripple.style.left = element[0].offsetLeft + "px"
ripple.addEventListener "animationend", (event) ->
ripple.remove()
angular.element(document.getElementById("card")).append ripple
]
app.animation ".lang-content", ["$animateCss", ($animateCss) ->
enter: (element) ->
parent = element.parent()
sibling = element.siblings()
$animateCss parent,
from:
width: sibling.width()
height: sibling.height()
to:
width: element.width()
height: element.height()
transitionStyle: '.5s cubic-bezier(.55, 0, .1, 1) all'
.start().done ->
parent.css 'width', ''
parent.css 'height', ''
$animateCss element, {event: "enter", structural: true}
leave: (element) ->
$animateCss element, {event: "leave", structural: true}
]
| true | "use strict";
do ->
app = angular.module "vCard", ["ngAnimate"]
app.controller "VCardController", [->
this.data =
en:
name: "PI:NAME:<NAME>END_PI",
position: "WEB DEVELOPER",
callToAction: "CONTACT ME"
vi:
name: "PI:NAME:<NAME>END_PI",
position: "NHÀ PHÁT TRIỂN WEB",
callToAction: "LIÊN HẸ"
ja:
name: "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"
position: "ウェブ開発者"
callToAction: "メールを送る"
this.active = "en"
]
app.directive "cardRippleTrigger", [->
restrict: "A"
link: (scope, element) ->
element.on "click", (event) ->
ripple = document.createElement "div"
ripple.className = "ripple"
ripple.style.top = element[0].offsetTop + "px"
ripple.style.left = element[0].offsetLeft + "px"
ripple.addEventListener "animationend", (event) ->
ripple.remove()
angular.element(document.getElementById("card")).append ripple
]
app.animation ".lang-content", ["$animateCss", ($animateCss) ->
enter: (element) ->
parent = element.parent()
sibling = element.siblings()
$animateCss parent,
from:
width: sibling.width()
height: sibling.height()
to:
width: element.width()
height: element.height()
transitionStyle: '.5s cubic-bezier(.55, 0, .1, 1) all'
.start().done ->
parent.css 'width', ''
parent.css 'height', ''
$animateCss element, {event: "enter", structural: true}
leave: (element) ->
$animateCss element, {event: "leave", structural: true}
]
|
[
{
"context": "iqueid'\n __sync_account_tag_auniqueid_name: 'My Rich Tag'\n __sync_account_tag_auniqueid_color: \"#FF00",
"end": 3583,
"score": 0.9964556694030762,
"start": 3572,
"tag": "NAME",
"value": "My Rich Tag"
},
{
"context": "1, context).get('account_tag').get('name'... | app/spec/database/sync_properties_spec.coffee | romanornr/ledger-wallet-crw | 173 | describe 'Database synchronized properties', ->
store = null
sync = null
db = null
context = null
beforeEach (done) ->
store = new ledger.storage.MemoryStore("local")
sync = new ledger.storage.MemoryStore("sync")
db = new ledger.database.Database('specs', store)
db.load ->
context = new ledger.database.contexts.Context(db, sync)
do done
it 'updates existing objects', (done) ->
onDbSaved = _.after 2, _.once ->
l "Update called"
sync.substore('sync_account_0').set index: 0, name: "My Sync Spec Account", ->
sync.emit 'pulled'
context.on 'update:account', ->
[account] = Account.find(index: 0, context).data()
expect(account.get('name')).toBe("My Sync Spec Account")
do done
context.on 'insert:account', onDbSaved
sync.on 'set', onDbSaved
Account.create({index: 0, name: "My Spec Account"}, context).save()
it 'creates missing objects', (done) ->
sync.substore('sync_account_0').set index: 0, name: "My Sync Spec Account", ->
sync.emit 'pulled'
context.on 'insert:account', ->
[account] = Account.find(index: 0, context).data()
expect(account.get('name')).toBe("My Sync Spec Account")
do done
it 'creates data on sync store when an object is inserted', (done) ->
sync.on 'set', (ev, items) ->
expect(JSON.parse(items['sync.__sync_account_0_index'])).toBe(0)
expect(JSON.parse(items['sync.__sync_account_0_name'])).toBe("My Greatest Account")
do done
Account.create(index: 0, name: "My Greatest Account", context).save()
it 'updates sync store when an object is saved', (done) ->
sync.once 'set', (ev, items) ->
Account.findById(0, context).set('name', "My Whatever Account").save()
sync.once 'set', (ev, items) ->
expect(JSON.parse(items['sync.__sync_account_0_index'])).toBe(0)
expect(JSON.parse(items['sync.__sync_account_0_name'])).toBe("My Whatever Account")
do done
Account.create(index: 0, name: "My Greatest Account", context).save()
it 'deletes data from sync store when an object is deleted', (done) ->
onDbSaved = _.after 2, _.once ->
Account.findById(0, context).delete()
sync.on 'remove', (ev, items...) ->
expect(items).toContain('sync.__sync_account_0_index')
expect(items).toContain('sync.__sync_account_0_name')
do done
context.on 'insert:account', onDbSaved
sync.on 'set', onDbSaved
Account.create(index: 0, name: "My Greatest Account", context).save()
it 'pushes sync relations', (done) ->
afterSave = ->
sync.getAll (data) ->
expect(data['__sync_account_0_name']).toBe('My tagged account')
accountTagId = data['__sync_account_0_account_tag_id']
expect(accountTagId).not.toBeUndefined()
expect(data["__sync_account_tag_#{accountTagId}_name"]).toBe("My accounted tag")
expect(data["__sync_account_tag_#{accountTagId}_color"]).toBe("#FF0000")
do done
sync.on 'set', _.debounce(afterSave, 50)
account = Account.create(index: 0, name: "My tagged account", context).save()
account.set('account_tag', AccountTag.create(name: "My accounted tag", color: "#FF0000", context).save()).save()
it 'restores relationships when data database is empty', (done) ->
sync.set
__sync_account_0_name: "My poor account"
__sync_account_0_index: 1
__sync_account_0_account_tag_id: "auniqueid"
__sync_account_tag_auniqueid_uid: 'auniqueid'
__sync_account_tag_auniqueid_name: 'My Rich Tag'
__sync_account_tag_auniqueid_color: "#FF0000"
, ->
afterSave = _.after 2, _.once ->
expect(Account.findById(1, context).get('account_tag').get('name')).toBe('My Rich Tag')
expect(Account.findById(1, context).get('account_tag').get('color')).toBe("#FF0000")
expect(Account.findById(1, context).get('name')).toBe("My poor account")
do done
context.on 'insert:account insert:account_tag', afterSave
sync.emit 'pulled'
it 'deletes relationships', (done) ->
Account.create(index: 0, name: 'Account 0', context).save()
Account.create(index: 1, name: 'Account 1', context).save()
Account.findById(0, context).set('account_tag', AccountTag.create(name: 'AccountTag', context).save()).save()
afterSave = ->
sync.clear ->
sync.set
__sync_account_1_index: 1
__sync_account_1_name: 'Account 1'
, ->
sync.emit 'pulled'
_.delay ->
expect(Account.all(context).length).toBe(1)
expect(AccountTag.all(context).length).toBe(0)
expect(Account.findById(1, context)).not.toBeUndefined()
expect(Account.findById(1, context).get('name')).toBe('Account 1')
do done
, 50
sync.once 'set', ->
_.delay(afterSave, 50)
| 120121 | describe 'Database synchronized properties', ->
store = null
sync = null
db = null
context = null
beforeEach (done) ->
store = new ledger.storage.MemoryStore("local")
sync = new ledger.storage.MemoryStore("sync")
db = new ledger.database.Database('specs', store)
db.load ->
context = new ledger.database.contexts.Context(db, sync)
do done
it 'updates existing objects', (done) ->
onDbSaved = _.after 2, _.once ->
l "Update called"
sync.substore('sync_account_0').set index: 0, name: "My Sync Spec Account", ->
sync.emit 'pulled'
context.on 'update:account', ->
[account] = Account.find(index: 0, context).data()
expect(account.get('name')).toBe("My Sync Spec Account")
do done
context.on 'insert:account', onDbSaved
sync.on 'set', onDbSaved
Account.create({index: 0, name: "My Spec Account"}, context).save()
it 'creates missing objects', (done) ->
sync.substore('sync_account_0').set index: 0, name: "My Sync Spec Account", ->
sync.emit 'pulled'
context.on 'insert:account', ->
[account] = Account.find(index: 0, context).data()
expect(account.get('name')).toBe("My Sync Spec Account")
do done
it 'creates data on sync store when an object is inserted', (done) ->
sync.on 'set', (ev, items) ->
expect(JSON.parse(items['sync.__sync_account_0_index'])).toBe(0)
expect(JSON.parse(items['sync.__sync_account_0_name'])).toBe("My Greatest Account")
do done
Account.create(index: 0, name: "My Greatest Account", context).save()
it 'updates sync store when an object is saved', (done) ->
sync.once 'set', (ev, items) ->
Account.findById(0, context).set('name', "My Whatever Account").save()
sync.once 'set', (ev, items) ->
expect(JSON.parse(items['sync.__sync_account_0_index'])).toBe(0)
expect(JSON.parse(items['sync.__sync_account_0_name'])).toBe("My Whatever Account")
do done
Account.create(index: 0, name: "My Greatest Account", context).save()
it 'deletes data from sync store when an object is deleted', (done) ->
onDbSaved = _.after 2, _.once ->
Account.findById(0, context).delete()
sync.on 'remove', (ev, items...) ->
expect(items).toContain('sync.__sync_account_0_index')
expect(items).toContain('sync.__sync_account_0_name')
do done
context.on 'insert:account', onDbSaved
sync.on 'set', onDbSaved
Account.create(index: 0, name: "My Greatest Account", context).save()
it 'pushes sync relations', (done) ->
afterSave = ->
sync.getAll (data) ->
expect(data['__sync_account_0_name']).toBe('My tagged account')
accountTagId = data['__sync_account_0_account_tag_id']
expect(accountTagId).not.toBeUndefined()
expect(data["__sync_account_tag_#{accountTagId}_name"]).toBe("My accounted tag")
expect(data["__sync_account_tag_#{accountTagId}_color"]).toBe("#FF0000")
do done
sync.on 'set', _.debounce(afterSave, 50)
account = Account.create(index: 0, name: "My tagged account", context).save()
account.set('account_tag', AccountTag.create(name: "My accounted tag", color: "#FF0000", context).save()).save()
it 'restores relationships when data database is empty', (done) ->
sync.set
__sync_account_0_name: "My poor account"
__sync_account_0_index: 1
__sync_account_0_account_tag_id: "auniqueid"
__sync_account_tag_auniqueid_uid: 'auniqueid'
__sync_account_tag_auniqueid_name: '<NAME>'
__sync_account_tag_auniqueid_color: "#FF0000"
, ->
afterSave = _.after 2, _.once ->
expect(Account.findById(1, context).get('account_tag').get('name')).toBe('<NAME>')
expect(Account.findById(1, context).get('account_tag').get('color')).toBe("#FF0000")
expect(Account.findById(1, context).get('name')).toBe("My poor account")
do done
context.on 'insert:account insert:account_tag', afterSave
sync.emit 'pulled'
it 'deletes relationships', (done) ->
Account.create(index: 0, name: 'Account 0', context).save()
Account.create(index: 1, name: 'Account 1', context).save()
Account.findById(0, context).set('account_tag', AccountTag.create(name: 'AccountTag', context).save()).save()
afterSave = ->
sync.clear ->
sync.set
__sync_account_1_index: 1
__sync_account_1_name: 'Account 1'
, ->
sync.emit 'pulled'
_.delay ->
expect(Account.all(context).length).toBe(1)
expect(AccountTag.all(context).length).toBe(0)
expect(Account.findById(1, context)).not.toBeUndefined()
expect(Account.findById(1, context).get('name')).toBe('Account 1')
do done
, 50
sync.once 'set', ->
_.delay(afterSave, 50)
| true | describe 'Database synchronized properties', ->
store = null
sync = null
db = null
context = null
beforeEach (done) ->
store = new ledger.storage.MemoryStore("local")
sync = new ledger.storage.MemoryStore("sync")
db = new ledger.database.Database('specs', store)
db.load ->
context = new ledger.database.contexts.Context(db, sync)
do done
it 'updates existing objects', (done) ->
onDbSaved = _.after 2, _.once ->
l "Update called"
sync.substore('sync_account_0').set index: 0, name: "My Sync Spec Account", ->
sync.emit 'pulled'
context.on 'update:account', ->
[account] = Account.find(index: 0, context).data()
expect(account.get('name')).toBe("My Sync Spec Account")
do done
context.on 'insert:account', onDbSaved
sync.on 'set', onDbSaved
Account.create({index: 0, name: "My Spec Account"}, context).save()
it 'creates missing objects', (done) ->
sync.substore('sync_account_0').set index: 0, name: "My Sync Spec Account", ->
sync.emit 'pulled'
context.on 'insert:account', ->
[account] = Account.find(index: 0, context).data()
expect(account.get('name')).toBe("My Sync Spec Account")
do done
it 'creates data on sync store when an object is inserted', (done) ->
sync.on 'set', (ev, items) ->
expect(JSON.parse(items['sync.__sync_account_0_index'])).toBe(0)
expect(JSON.parse(items['sync.__sync_account_0_name'])).toBe("My Greatest Account")
do done
Account.create(index: 0, name: "My Greatest Account", context).save()
it 'updates sync store when an object is saved', (done) ->
sync.once 'set', (ev, items) ->
Account.findById(0, context).set('name', "My Whatever Account").save()
sync.once 'set', (ev, items) ->
expect(JSON.parse(items['sync.__sync_account_0_index'])).toBe(0)
expect(JSON.parse(items['sync.__sync_account_0_name'])).toBe("My Whatever Account")
do done
Account.create(index: 0, name: "My Greatest Account", context).save()
it 'deletes data from sync store when an object is deleted', (done) ->
onDbSaved = _.after 2, _.once ->
Account.findById(0, context).delete()
sync.on 'remove', (ev, items...) ->
expect(items).toContain('sync.__sync_account_0_index')
expect(items).toContain('sync.__sync_account_0_name')
do done
context.on 'insert:account', onDbSaved
sync.on 'set', onDbSaved
Account.create(index: 0, name: "My Greatest Account", context).save()
it 'pushes sync relations', (done) ->
afterSave = ->
sync.getAll (data) ->
expect(data['__sync_account_0_name']).toBe('My tagged account')
accountTagId = data['__sync_account_0_account_tag_id']
expect(accountTagId).not.toBeUndefined()
expect(data["__sync_account_tag_#{accountTagId}_name"]).toBe("My accounted tag")
expect(data["__sync_account_tag_#{accountTagId}_color"]).toBe("#FF0000")
do done
sync.on 'set', _.debounce(afterSave, 50)
account = Account.create(index: 0, name: "My tagged account", context).save()
account.set('account_tag', AccountTag.create(name: "My accounted tag", color: "#FF0000", context).save()).save()
it 'restores relationships when data database is empty', (done) ->
sync.set
__sync_account_0_name: "My poor account"
__sync_account_0_index: 1
__sync_account_0_account_tag_id: "auniqueid"
__sync_account_tag_auniqueid_uid: 'auniqueid'
__sync_account_tag_auniqueid_name: 'PI:NAME:<NAME>END_PI'
__sync_account_tag_auniqueid_color: "#FF0000"
, ->
afterSave = _.after 2, _.once ->
expect(Account.findById(1, context).get('account_tag').get('name')).toBe('PI:NAME:<NAME>END_PI')
expect(Account.findById(1, context).get('account_tag').get('color')).toBe("#FF0000")
expect(Account.findById(1, context).get('name')).toBe("My poor account")
do done
context.on 'insert:account insert:account_tag', afterSave
sync.emit 'pulled'
it 'deletes relationships', (done) ->
Account.create(index: 0, name: 'Account 0', context).save()
Account.create(index: 1, name: 'Account 1', context).save()
Account.findById(0, context).set('account_tag', AccountTag.create(name: 'AccountTag', context).save()).save()
afterSave = ->
sync.clear ->
sync.set
__sync_account_1_index: 1
__sync_account_1_name: 'Account 1'
, ->
sync.emit 'pulled'
_.delay ->
expect(Account.all(context).length).toBe(1)
expect(AccountTag.all(context).length).toBe(0)
expect(Account.findById(1, context)).not.toBeUndefined()
expect(Account.findById(1, context).get('name')).toBe('Account 1')
do done
, 50
sync.once 'set', ->
_.delay(afterSave, 50)
|
[
{
"context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.",
"end": 197,
"score": 0.9998795390129089,
"start": 180,
"tag": "NAME",
"value": "Benjamin Blundell"
},
{
"context": " PXL.js\n ... | examples/logo.coffee | OniDaito/pxljs | 1 | ### ABOUT
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
Benjamin Blundell - ben@pxljs.com
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
class Logo
reset_cubes : () ->
for cube in @cube_nodes
cube.matrix.identity()
arrange_cubes : () ->
# P
@cube_nodes[0].matrix.translate( new PXL.Math.Vec3(-4.0,3.0,0.0) )
@cube_nodes[1].matrix.translate( new PXL.Math.Vec3(-4.0,2.0,0.0) )
@cube_nodes[2].matrix.translate( new PXL.Math.Vec3(-4.0,1.0,0.0) )
@cube_nodes[3].matrix.translate( new PXL.Math.Vec3(-4.0,0.0,0.0) )
@cube_nodes[4].matrix.translate( new PXL.Math.Vec3(-4.0,-1.0,0.0) )
@cube_nodes[5].matrix.translate( new PXL.Math.Vec3(-4.0,-2.0,0.0) )
@cube_nodes[6].matrix.translate( new PXL.Math.Vec3(-3.0,3.0,0.0) )
@cube_nodes[7].matrix.translate( new PXL.Math.Vec3(-2.0,3.0,0.0) )
@cube_nodes[8].matrix.translate( new PXL.Math.Vec3(-2.0,2.0,0.0) )
@cube_nodes[9].matrix.translate( new PXL.Math.Vec3(-3.0,1.0,0.0) )
@cube_nodes[10].matrix.translate( new PXL.Math.Vec3(-2.0,1.0,0.0) )
# X
@cube_nodes[11].matrix.translate( new PXL.Math.Vec3(-2.0,0.0,0.0) )
@cube_nodes[12].matrix.translate( new PXL.Math.Vec3(0,0,0) )
@cube_nodes[13].matrix.translate( new PXL.Math.Vec3(-1.0,-1.0,0.0) )
@cube_nodes[14].matrix.translate( new PXL.Math.Vec3(-2.0,-2.0,0.0) )
@cube_nodes[15].matrix.translate( new PXL.Math.Vec3(0.0,-2.0,0.0) )
# L
@cube_nodes[16].matrix.translate( new PXL.Math.Vec3(1.0,3.0,0.0) )
@cube_nodes[17].matrix.translate( new PXL.Math.Vec3(1.0,2.0,0.0) )
@cube_nodes[18].matrix.translate( new PXL.Math.Vec3(1.0,1.0,0.0) )
@cube_nodes[19].matrix.translate( new PXL.Math.Vec3(1.0,0.0,0.0) )
@cube_nodes[20].matrix.translate( new PXL.Math.Vec3(1.0,-1.0,0.0) )
@cube_nodes[21].matrix.translate( new PXL.Math.Vec3(1.0,-2.0,0.0) )
@cube_nodes[22].matrix.translate( new PXL.Math.Vec3(2.0,-2.0,0.0) )
rotate_cubes : (dt) ->
dd = 0
stopped = true
for cube in @cube_nodes
rot = (1.0 + Math.sin(dd))
if cube._rot < 360
cube._rot += rot
cube.matrix.rotate new PXL.Math.Vec3(0,1,0), PXL.Math.degToRad(cube._rot)
stopped = false
dd += 0.1
@time += dt
if not stopped
@pause_time = @time
if stopped
if @time - @pause_time > 5000
for cube in @cube_nodes
cube._rot = 0
@time = 0
@pause_time = 0
init : () ->
@top_node = new PXL.Node()
@camera = new PXL.Camera.PerspCamera new PXL.Math.Vec3(-6.62, -2.15, 7.29), new PXL.Math.Vec3(-1.17, 0.59, -0.64), new PXL.Math.Vec3(-0.16, 0.96, 0.23)
@top_node.add @camera
# Create a cuboid with a basic material
# then translate the cube a little
cube_geometry = new PXL.Geometry.CuboidDup(new PXL.Math.Vec3(1,1,1))
hot_pink = new PXL.Colour.RGB(1.0,0.41,0.7)
spec = new PXL.Colour.RGB(0.0,0.0,0.0)
@top_node.add new PXL.Material.PhongMaterial(hot_pink, hot_pink, spec)
# Create a set of nodes for the logo with the same geometry
@cube_nodes = []
for i in [0..22]
cc = new PXL.Node(cube_geometry)
cc._rot = 0
@cube_nodes.push cc
@top_node.add cc
@ambientlight = new PXL.Light.AmbientLight(new PXL.Colour.RGB(0.1, 0.1, 0.1))
@light = new PXL.Light.PointLight new PXL.Math.Vec3(0.0,2.0,6.0), new PXL.Colour.RGB(0.2,0.2,0.2)
@light2 = new PXL.Light.PointLight new PXL.Math.Vec3(0.0,15.0,5.0), new PXL.Colour.RGB(0.2,0.2,0.2)
@top_node.add @light
@top_node.add @light2
@top_node.add @ambientlight
uber = new PXL.GL.UberShader @top_node
@top_node.add uber
@time = 0
@pause_time = 0
GL.enable(GL.CULL_FACE)
GL.cullFace(GL.BACK)
GL.enable(GL.DEPTH_TEST)
draw : (dt) ->
@reset_cubes()
@arrange_cubes()
@rotate_cubes(dt)
GL.clearColor(1.0, 1.0, 1.0, 1.0)
GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT)
@top_node.draw()
example = new Logo()
params =
canvas : 'webgl-canvas'
context : example
init : example.init
draw : example.draw
debug : true
cgl = new PXL.App params
| 68869 | ### ABOUT
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
<NAME> - <EMAIL>
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
class Logo
reset_cubes : () ->
for cube in @cube_nodes
cube.matrix.identity()
arrange_cubes : () ->
# P
@cube_nodes[0].matrix.translate( new PXL.Math.Vec3(-4.0,3.0,0.0) )
@cube_nodes[1].matrix.translate( new PXL.Math.Vec3(-4.0,2.0,0.0) )
@cube_nodes[2].matrix.translate( new PXL.Math.Vec3(-4.0,1.0,0.0) )
@cube_nodes[3].matrix.translate( new PXL.Math.Vec3(-4.0,0.0,0.0) )
@cube_nodes[4].matrix.translate( new PXL.Math.Vec3(-4.0,-1.0,0.0) )
@cube_nodes[5].matrix.translate( new PXL.Math.Vec3(-4.0,-2.0,0.0) )
@cube_nodes[6].matrix.translate( new PXL.Math.Vec3(-3.0,3.0,0.0) )
@cube_nodes[7].matrix.translate( new PXL.Math.Vec3(-2.0,3.0,0.0) )
@cube_nodes[8].matrix.translate( new PXL.Math.Vec3(-2.0,2.0,0.0) )
@cube_nodes[9].matrix.translate( new PXL.Math.Vec3(-3.0,1.0,0.0) )
@cube_nodes[10].matrix.translate( new PXL.Math.Vec3(-2.0,1.0,0.0) )
# X
@cube_nodes[11].matrix.translate( new PXL.Math.Vec3(-2.0,0.0,0.0) )
@cube_nodes[12].matrix.translate( new PXL.Math.Vec3(0,0,0) )
@cube_nodes[13].matrix.translate( new PXL.Math.Vec3(-1.0,-1.0,0.0) )
@cube_nodes[14].matrix.translate( new PXL.Math.Vec3(-2.0,-2.0,0.0) )
@cube_nodes[15].matrix.translate( new PXL.Math.Vec3(0.0,-2.0,0.0) )
# L
@cube_nodes[16].matrix.translate( new PXL.Math.Vec3(1.0,3.0,0.0) )
@cube_nodes[17].matrix.translate( new PXL.Math.Vec3(1.0,2.0,0.0) )
@cube_nodes[18].matrix.translate( new PXL.Math.Vec3(1.0,1.0,0.0) )
@cube_nodes[19].matrix.translate( new PXL.Math.Vec3(1.0,0.0,0.0) )
@cube_nodes[20].matrix.translate( new PXL.Math.Vec3(1.0,-1.0,0.0) )
@cube_nodes[21].matrix.translate( new PXL.Math.Vec3(1.0,-2.0,0.0) )
@cube_nodes[22].matrix.translate( new PXL.Math.Vec3(2.0,-2.0,0.0) )
rotate_cubes : (dt) ->
dd = 0
stopped = true
for cube in @cube_nodes
rot = (1.0 + Math.sin(dd))
if cube._rot < 360
cube._rot += rot
cube.matrix.rotate new PXL.Math.Vec3(0,1,0), PXL.Math.degToRad(cube._rot)
stopped = false
dd += 0.1
@time += dt
if not stopped
@pause_time = @time
if stopped
if @time - @pause_time > 5000
for cube in @cube_nodes
cube._rot = 0
@time = 0
@pause_time = 0
init : () ->
@top_node = new PXL.Node()
@camera = new PXL.Camera.PerspCamera new PXL.Math.Vec3(-6.62, -2.15, 7.29), new PXL.Math.Vec3(-1.17, 0.59, -0.64), new PXL.Math.Vec3(-0.16, 0.96, 0.23)
@top_node.add @camera
# Create a cuboid with a basic material
# then translate the cube a little
cube_geometry = new PXL.Geometry.CuboidDup(new PXL.Math.Vec3(1,1,1))
hot_pink = new PXL.Colour.RGB(1.0,0.41,0.7)
spec = new PXL.Colour.RGB(0.0,0.0,0.0)
@top_node.add new PXL.Material.PhongMaterial(hot_pink, hot_pink, spec)
# Create a set of nodes for the logo with the same geometry
@cube_nodes = []
for i in [0..22]
cc = new PXL.Node(cube_geometry)
cc._rot = 0
@cube_nodes.push cc
@top_node.add cc
@ambientlight = new PXL.Light.AmbientLight(new PXL.Colour.RGB(0.1, 0.1, 0.1))
@light = new PXL.Light.PointLight new PXL.Math.Vec3(0.0,2.0,6.0), new PXL.Colour.RGB(0.2,0.2,0.2)
@light2 = new PXL.Light.PointLight new PXL.Math.Vec3(0.0,15.0,5.0), new PXL.Colour.RGB(0.2,0.2,0.2)
@top_node.add @light
@top_node.add @light2
@top_node.add @ambientlight
uber = new PXL.GL.UberShader @top_node
@top_node.add uber
@time = 0
@pause_time = 0
GL.enable(GL.CULL_FACE)
GL.cullFace(GL.BACK)
GL.enable(GL.DEPTH_TEST)
draw : (dt) ->
@reset_cubes()
@arrange_cubes()
@rotate_cubes(dt)
GL.clearColor(1.0, 1.0, 1.0, 1.0)
GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT)
@top_node.draw()
example = new Logo()
params =
canvas : 'webgl-canvas'
context : example
init : example.init
draw : example.draw
debug : true
cgl = new PXL.App params
| true | ### ABOUT
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
class Logo
reset_cubes : () ->
for cube in @cube_nodes
cube.matrix.identity()
arrange_cubes : () ->
# P
@cube_nodes[0].matrix.translate( new PXL.Math.Vec3(-4.0,3.0,0.0) )
@cube_nodes[1].matrix.translate( new PXL.Math.Vec3(-4.0,2.0,0.0) )
@cube_nodes[2].matrix.translate( new PXL.Math.Vec3(-4.0,1.0,0.0) )
@cube_nodes[3].matrix.translate( new PXL.Math.Vec3(-4.0,0.0,0.0) )
@cube_nodes[4].matrix.translate( new PXL.Math.Vec3(-4.0,-1.0,0.0) )
@cube_nodes[5].matrix.translate( new PXL.Math.Vec3(-4.0,-2.0,0.0) )
@cube_nodes[6].matrix.translate( new PXL.Math.Vec3(-3.0,3.0,0.0) )
@cube_nodes[7].matrix.translate( new PXL.Math.Vec3(-2.0,3.0,0.0) )
@cube_nodes[8].matrix.translate( new PXL.Math.Vec3(-2.0,2.0,0.0) )
@cube_nodes[9].matrix.translate( new PXL.Math.Vec3(-3.0,1.0,0.0) )
@cube_nodes[10].matrix.translate( new PXL.Math.Vec3(-2.0,1.0,0.0) )
# X
@cube_nodes[11].matrix.translate( new PXL.Math.Vec3(-2.0,0.0,0.0) )
@cube_nodes[12].matrix.translate( new PXL.Math.Vec3(0,0,0) )
@cube_nodes[13].matrix.translate( new PXL.Math.Vec3(-1.0,-1.0,0.0) )
@cube_nodes[14].matrix.translate( new PXL.Math.Vec3(-2.0,-2.0,0.0) )
@cube_nodes[15].matrix.translate( new PXL.Math.Vec3(0.0,-2.0,0.0) )
# L
@cube_nodes[16].matrix.translate( new PXL.Math.Vec3(1.0,3.0,0.0) )
@cube_nodes[17].matrix.translate( new PXL.Math.Vec3(1.0,2.0,0.0) )
@cube_nodes[18].matrix.translate( new PXL.Math.Vec3(1.0,1.0,0.0) )
@cube_nodes[19].matrix.translate( new PXL.Math.Vec3(1.0,0.0,0.0) )
@cube_nodes[20].matrix.translate( new PXL.Math.Vec3(1.0,-1.0,0.0) )
@cube_nodes[21].matrix.translate( new PXL.Math.Vec3(1.0,-2.0,0.0) )
@cube_nodes[22].matrix.translate( new PXL.Math.Vec3(2.0,-2.0,0.0) )
rotate_cubes : (dt) ->
dd = 0
stopped = true
for cube in @cube_nodes
rot = (1.0 + Math.sin(dd))
if cube._rot < 360
cube._rot += rot
cube.matrix.rotate new PXL.Math.Vec3(0,1,0), PXL.Math.degToRad(cube._rot)
stopped = false
dd += 0.1
@time += dt
if not stopped
@pause_time = @time
if stopped
if @time - @pause_time > 5000
for cube in @cube_nodes
cube._rot = 0
@time = 0
@pause_time = 0
init : () ->
@top_node = new PXL.Node()
@camera = new PXL.Camera.PerspCamera new PXL.Math.Vec3(-6.62, -2.15, 7.29), new PXL.Math.Vec3(-1.17, 0.59, -0.64), new PXL.Math.Vec3(-0.16, 0.96, 0.23)
@top_node.add @camera
# Create a cuboid with a basic material
# then translate the cube a little
cube_geometry = new PXL.Geometry.CuboidDup(new PXL.Math.Vec3(1,1,1))
hot_pink = new PXL.Colour.RGB(1.0,0.41,0.7)
spec = new PXL.Colour.RGB(0.0,0.0,0.0)
@top_node.add new PXL.Material.PhongMaterial(hot_pink, hot_pink, spec)
# Create a set of nodes for the logo with the same geometry
@cube_nodes = []
for i in [0..22]
cc = new PXL.Node(cube_geometry)
cc._rot = 0
@cube_nodes.push cc
@top_node.add cc
@ambientlight = new PXL.Light.AmbientLight(new PXL.Colour.RGB(0.1, 0.1, 0.1))
@light = new PXL.Light.PointLight new PXL.Math.Vec3(0.0,2.0,6.0), new PXL.Colour.RGB(0.2,0.2,0.2)
@light2 = new PXL.Light.PointLight new PXL.Math.Vec3(0.0,15.0,5.0), new PXL.Colour.RGB(0.2,0.2,0.2)
@top_node.add @light
@top_node.add @light2
@top_node.add @ambientlight
uber = new PXL.GL.UberShader @top_node
@top_node.add uber
@time = 0
@pause_time = 0
GL.enable(GL.CULL_FACE)
GL.cullFace(GL.BACK)
GL.enable(GL.DEPTH_TEST)
draw : (dt) ->
@reset_cubes()
@arrange_cubes()
@rotate_cubes(dt)
GL.clearColor(1.0, 1.0, 1.0, 1.0)
GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT)
@top_node.draw()
example = new Logo()
params =
canvas : 'webgl-canvas'
context : example
init : example.init
draw : example.draw
debug : true
cgl = new PXL.App params
|
[
{
"context": "igest.authenticateRequest regcontext, rq, {user: '100', password: '1234'} \n sip.send diges",
"end": 873,
"score": 0.9984941482543945,
"start": 870,
"tag": "USERNAME",
"value": "100"
},
{
"context": "eRequest regcontext, rq, {user: '100', password: '1234'} ... | test/digest-server.coffee | kelchy/sip.js | 221 | # digest server code 'unit' test.
#
#
sip = require 'sip'
digest = require 'sip/digest'
randomBytes = (require 'rbytes').randomBytes
rbytes = (n) -> randomBytes(n).toHex()
util = require 'util'
dialogs = {}
makeDialogId = (rq, tag) ->
[rq.headers['call-id'], rq.headers.from.params.tag, rq.headers.to.params.tag || tag].join()
context = {realm: 'test', qop: 'auth-int'}
regcontext = {realm: 'test'}
sip.start {
logger:
send: (rq) -> util.debug "send\n" + util.inspect rq, null, null
recv: (rq) -> util.debug "recv\n" + util.inspect rq, null, null
},
(rq) ->
try
if rq.method != 'REGISTER' && rq.headers.to.params.tag
(dialogs[makeDialogId rq] || (rq) -> sip.send sip.makeResponse rq, 581)(rq)
else
switch rq.method
when 'REGISTER'
if !digest.authenticateRequest regcontext, rq, {user: '100', password: '1234'}
sip.send digest.challenge regcontext, sip.makeResponse rq, 401, 'Authorization Required'
else
rs = sip.makeResponse rq, 200
rs.headers.to.tag = rbytes 16
sip.send digest.signResponse regcontext, rs
when 'INVITE'
if !digest.authenticateRequest context, rq, {user: '100', password: '1234'}
sip.send digest.challenge context, sip.makeResponse rq, 401, 'Authorization Required'
else
tag = rbytes 16
dialogs[makeDialogId rq, tag] = (rq) ->
try
if digest.authenticateRequest context, rq
sip.send digest.challenge context, sip.makeResponse rq, 401, 'Authorization Required'
else
switch rq.method
when 'BYE'
sip.send digest.signResponse context, sip.makeResponse rq, 200
delete dialogs[makeDialogId rq, tag]
else
sip.send digest.signResponse context, sip.makeResponse rq, 400
catch e
util.debug e
rs = sip.makeResponse rq, 200, 'OK'
rs.content =
'''
v=0
o=sip 28908764872 28908764872 IN IP4 127.0.0.1
s=-
c=IN IP4 127.0.0.1
t=0 0
m=audio 0 RTP/AVP 0 8
a=rtpmap:0 PCMU/8000
a=rtpmap:8 PCMA/8000
a=sendonly
'''
rs.headers['content-length'] = rs.content.length
rs.headers.to.params.tag = tag
sip.send digest.signResponse context, rs
else
sip.send sip.makeResponse rq, 400
catch e
util.debug e
util.debug e.stack
| 210144 | # digest server code 'unit' test.
#
#
sip = require 'sip'
digest = require 'sip/digest'
randomBytes = (require 'rbytes').randomBytes
rbytes = (n) -> randomBytes(n).toHex()
util = require 'util'
dialogs = {}
makeDialogId = (rq, tag) ->
[rq.headers['call-id'], rq.headers.from.params.tag, rq.headers.to.params.tag || tag].join()
context = {realm: 'test', qop: 'auth-int'}
regcontext = {realm: 'test'}
sip.start {
logger:
send: (rq) -> util.debug "send\n" + util.inspect rq, null, null
recv: (rq) -> util.debug "recv\n" + util.inspect rq, null, null
},
(rq) ->
try
if rq.method != 'REGISTER' && rq.headers.to.params.tag
(dialogs[makeDialogId rq] || (rq) -> sip.send sip.makeResponse rq, 581)(rq)
else
switch rq.method
when 'REGISTER'
if !digest.authenticateRequest regcontext, rq, {user: '100', password: '<PASSWORD>'}
sip.send digest.challenge regcontext, sip.makeResponse rq, 401, 'Authorization Required'
else
rs = sip.makeResponse rq, 200
rs.headers.to.tag = rbytes 16
sip.send digest.signResponse regcontext, rs
when 'INVITE'
if !digest.authenticateRequest context, rq, {user: '100', password: '<PASSWORD>'}
sip.send digest.challenge context, sip.makeResponse rq, 401, 'Authorization Required'
else
tag = rbytes 16
dialogs[makeDialogId rq, tag] = (rq) ->
try
if digest.authenticateRequest context, rq
sip.send digest.challenge context, sip.makeResponse rq, 401, 'Authorization Required'
else
switch rq.method
when 'BYE'
sip.send digest.signResponse context, sip.makeResponse rq, 200
delete dialogs[makeDialogId rq, tag]
else
sip.send digest.signResponse context, sip.makeResponse rq, 400
catch e
util.debug e
rs = sip.makeResponse rq, 200, 'OK'
rs.content =
'''
v=0
o=sip 28908764872 28908764872 IN IP4 127.0.0.1
s=-
c=IN IP4 127.0.0.1
t=0 0
m=audio 0 RTP/AVP 0 8
a=rtpmap:0 PCMU/8000
a=rtpmap:8 PCMA/8000
a=sendonly
'''
rs.headers['content-length'] = rs.content.length
rs.headers.to.params.tag = tag
sip.send digest.signResponse context, rs
else
sip.send sip.makeResponse rq, 400
catch e
util.debug e
util.debug e.stack
| true | # digest server code 'unit' test.
#
#
sip = require 'sip'
digest = require 'sip/digest'
randomBytes = (require 'rbytes').randomBytes
rbytes = (n) -> randomBytes(n).toHex()
util = require 'util'
dialogs = {}
makeDialogId = (rq, tag) ->
[rq.headers['call-id'], rq.headers.from.params.tag, rq.headers.to.params.tag || tag].join()
context = {realm: 'test', qop: 'auth-int'}
regcontext = {realm: 'test'}
sip.start {
logger:
send: (rq) -> util.debug "send\n" + util.inspect rq, null, null
recv: (rq) -> util.debug "recv\n" + util.inspect rq, null, null
},
(rq) ->
try
if rq.method != 'REGISTER' && rq.headers.to.params.tag
(dialogs[makeDialogId rq] || (rq) -> sip.send sip.makeResponse rq, 581)(rq)
else
switch rq.method
when 'REGISTER'
if !digest.authenticateRequest regcontext, rq, {user: '100', password: 'PI:PASSWORD:<PASSWORD>END_PI'}
sip.send digest.challenge regcontext, sip.makeResponse rq, 401, 'Authorization Required'
else
rs = sip.makeResponse rq, 200
rs.headers.to.tag = rbytes 16
sip.send digest.signResponse regcontext, rs
when 'INVITE'
if !digest.authenticateRequest context, rq, {user: '100', password: 'PI:PASSWORD:<PASSWORD>END_PI'}
sip.send digest.challenge context, sip.makeResponse rq, 401, 'Authorization Required'
else
tag = rbytes 16
dialogs[makeDialogId rq, tag] = (rq) ->
try
if digest.authenticateRequest context, rq
sip.send digest.challenge context, sip.makeResponse rq, 401, 'Authorization Required'
else
switch rq.method
when 'BYE'
sip.send digest.signResponse context, sip.makeResponse rq, 200
delete dialogs[makeDialogId rq, tag]
else
sip.send digest.signResponse context, sip.makeResponse rq, 400
catch e
util.debug e
rs = sip.makeResponse rq, 200, 'OK'
rs.content =
'''
v=0
o=sip 28908764872 28908764872 IN IP4 127.0.0.1
s=-
c=IN IP4 127.0.0.1
t=0 0
m=audio 0 RTP/AVP 0 8
a=rtpmap:0 PCMU/8000
a=rtpmap:8 PCMA/8000
a=sendonly
'''
rs.headers['content-length'] = rs.content.length
rs.headers.to.params.tag = tag
sip.send digest.signResponse context, rs
else
sip.send sip.makeResponse rq, 400
catch e
util.debug e
util.debug e.stack
|
[
{
"context": "#\n# Ethan Mick\n# 2015\n#\nuuid = require 'uuid'\nClient = require '",
"end": 14,
"score": 0.9997172355651855,
"start": 4,
"tag": "NAME",
"value": "Ethan Mick"
}
] | lib/task.coffee | ethanmick/future-client | 0 | #
# Ethan Mick
# 2015
#
uuid = require 'uuid'
Client = require './client'
class Task
constructor: (opts)->
throw Error('"time" is required!') unless opts.time
@name = opts.name or uuid.v4()
@time = opts.time
@opts = opts.opts or null
toObject: ->
{
name: @name
time: @time
opts: @opts
}
schedule: ->
Client.schedule(@toObject())
@inMilliseconds: (ms, opts = {}, autoSchedule = no)->
date = new Date()
date.setMilliseconds(date.getMilliseconds() + ms)
t = new this({
name: opts.name
time: date
opts: opts.opts
})
return t.schedule() if autoSchedule
t
@inSeconds: (seconds, opts, autoSchedule)->
@inMilliseconds(seconds * 1000, opts, autoSchedule)
module.exports = Task
| 96051 | #
# <NAME>
# 2015
#
uuid = require 'uuid'
Client = require './client'
class Task
constructor: (opts)->
throw Error('"time" is required!') unless opts.time
@name = opts.name or uuid.v4()
@time = opts.time
@opts = opts.opts or null
toObject: ->
{
name: @name
time: @time
opts: @opts
}
schedule: ->
Client.schedule(@toObject())
@inMilliseconds: (ms, opts = {}, autoSchedule = no)->
date = new Date()
date.setMilliseconds(date.getMilliseconds() + ms)
t = new this({
name: opts.name
time: date
opts: opts.opts
})
return t.schedule() if autoSchedule
t
@inSeconds: (seconds, opts, autoSchedule)->
@inMilliseconds(seconds * 1000, opts, autoSchedule)
module.exports = Task
| true | #
# PI:NAME:<NAME>END_PI
# 2015
#
uuid = require 'uuid'
Client = require './client'
class Task
constructor: (opts)->
throw Error('"time" is required!') unless opts.time
@name = opts.name or uuid.v4()
@time = opts.time
@opts = opts.opts or null
toObject: ->
{
name: @name
time: @time
opts: @opts
}
schedule: ->
Client.schedule(@toObject())
@inMilliseconds: (ms, opts = {}, autoSchedule = no)->
date = new Date()
date.setMilliseconds(date.getMilliseconds() + ms)
t = new this({
name: opts.name
time: date
opts: opts.opts
})
return t.schedule() if autoSchedule
t
@inSeconds: (seconds, opts, autoSchedule)->
@inMilliseconds(seconds * 1000, opts, autoSchedule)
module.exports = Task
|
[
{
"context": "rvice:user-chan\")\n @userParams =\n email: \"test@test.test\"\n password: \"password123\"\n Cookies.remove",
"end": 651,
"score": 0.9999144673347473,
"start": 637,
"tag": "EMAIL",
"value": "test@test.test"
},
{
"context": " =\n email: \"test@test.t... | tests/acceptance/channel-test.coffee | simwms/apiv4 | 2 | `import Ember from 'ember'`
`import { module, test } from 'qunit'`
`import startApp from '../../tests/helpers/start-app'`
module 'Acceptance: Channel',
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")
@socket = @application.__container__.lookup("service:socket")
@userChan = @application.__container__.lookup("service:user-chan")
@userParams =
email: "test@test.test"
password: "password123"
Cookies.remove "_apiv4_key"
Cookies.remove "remember-token"
return
afterEach: ->
Ember.run @application, 'destroy'
test 'visiting /', (assert) ->
visit '/'
andThen =>
assert.equal currentURL(), '/'
assert.equal @session.get("cookieKey"), "_apiv4_key"
@loginFlag = false
@session.on "login", =>
@loginFlag = true
@connectFlag = false
@socket.on "connect", =>
@connectFlag = true
@session
.login @userParams
.then =>
@socket.get("deferredSocket.promise")
andThen =>
assert.ok @loginFlag, "we should get the callback"
assert.ok @connectFlag, "we should connect"
@session.connect "user"
andThen =>
assert.ok @userChan.get("isConnected"), "user channel should be connected" | 119216 | `import Ember from 'ember'`
`import { module, test } from 'qunit'`
`import startApp from '../../tests/helpers/start-app'`
module 'Acceptance: Channel',
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")
@socket = @application.__container__.lookup("service:socket")
@userChan = @application.__container__.lookup("service:user-chan")
@userParams =
email: "<EMAIL>"
password: "<PASSWORD>"
Cookies.remove "_apiv4_key"
Cookies.remove "remember-token"
return
afterEach: ->
Ember.run @application, 'destroy'
test 'visiting /', (assert) ->
visit '/'
andThen =>
assert.equal currentURL(), '/'
assert.equal @session.get("cookieKey"), "_apiv4_key"
@loginFlag = false
@session.on "login", =>
@loginFlag = true
@connectFlag = false
@socket.on "connect", =>
@connectFlag = true
@session
.login @userParams
.then =>
@socket.get("deferredSocket.promise")
andThen =>
assert.ok @loginFlag, "we should get the callback"
assert.ok @connectFlag, "we should connect"
@session.connect "user"
andThen =>
assert.ok @userChan.get("isConnected"), "user channel should be connected" | true | `import Ember from 'ember'`
`import { module, test } from 'qunit'`
`import startApp from '../../tests/helpers/start-app'`
module 'Acceptance: Channel',
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")
@socket = @application.__container__.lookup("service:socket")
@userChan = @application.__container__.lookup("service:user-chan")
@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 /', (assert) ->
visit '/'
andThen =>
assert.equal currentURL(), '/'
assert.equal @session.get("cookieKey"), "_apiv4_key"
@loginFlag = false
@session.on "login", =>
@loginFlag = true
@connectFlag = false
@socket.on "connect", =>
@connectFlag = true
@session
.login @userParams
.then =>
@socket.get("deferredSocket.promise")
andThen =>
assert.ok @loginFlag, "we should get the callback"
assert.ok @connectFlag, "we should connect"
@session.connect "user"
andThen =>
assert.ok @userChan.get("isConnected"), "user channel should be connected" |
[
{
"context": " email: form.email\n password: form.password\n dataType: \"json\"\n success:",
"end": 817,
"score": 0.9991345405578613,
"start": 804,
"tag": "PASSWORD",
"value": "form.password"
}
] | www/coffee/backbone/models/user.coffee | unepwcmc/BlueCarbonMobile | 0 | window.BlueCarbon ||= {}
window.BlueCarbon.Models ||= {}
class BlueCarbon.Models.User extends Backbone.SyncableModel
schema: ->
"sqlite_id INTEGER PRIMARY KEY, id INTEGER, auth_token TEXT, email TEXT"
# Takes success and error callback options, tries
# to login with model attributes
login: (form, options) ->
# Test for existing login
$.ajax(
type: 'GET'
url: 'http://bluecarbon.unep-wcmc.org/admins/me.json'
success: options.success
error: (data)=>
@set('email', form.email)
if data.error?
# Not logged in, login
$.ajax(
type: 'POST'
url: 'http://bluecarbon.unep-wcmc.org/my/admins/sign_in.json'
data:
admin:
email: form.email
password: form.password
dataType: "json"
success: (data) =>
@set('auth_token', data.auth_token)
@localSave({},
success: (a,b,c)=>
options.success(@)
BlueCarbon.bus.trigger('user:gotAuthToken', data.auth_token)
BlueCarbon.bus.trigger('user:loggedIn', @)
)
error: options.error
)
else
options.error(data)
)
logout: (options) ->
@localDestroy(
success: ->
BlueCarbon.bus.trigger('user:gotAuthToken', '')
options.success()
)
| 126661 | window.BlueCarbon ||= {}
window.BlueCarbon.Models ||= {}
class BlueCarbon.Models.User extends Backbone.SyncableModel
schema: ->
"sqlite_id INTEGER PRIMARY KEY, id INTEGER, auth_token TEXT, email TEXT"
# Takes success and error callback options, tries
# to login with model attributes
login: (form, options) ->
# Test for existing login
$.ajax(
type: 'GET'
url: 'http://bluecarbon.unep-wcmc.org/admins/me.json'
success: options.success
error: (data)=>
@set('email', form.email)
if data.error?
# Not logged in, login
$.ajax(
type: 'POST'
url: 'http://bluecarbon.unep-wcmc.org/my/admins/sign_in.json'
data:
admin:
email: form.email
password: <PASSWORD>
dataType: "json"
success: (data) =>
@set('auth_token', data.auth_token)
@localSave({},
success: (a,b,c)=>
options.success(@)
BlueCarbon.bus.trigger('user:gotAuthToken', data.auth_token)
BlueCarbon.bus.trigger('user:loggedIn', @)
)
error: options.error
)
else
options.error(data)
)
logout: (options) ->
@localDestroy(
success: ->
BlueCarbon.bus.trigger('user:gotAuthToken', '')
options.success()
)
| true | window.BlueCarbon ||= {}
window.BlueCarbon.Models ||= {}
class BlueCarbon.Models.User extends Backbone.SyncableModel
schema: ->
"sqlite_id INTEGER PRIMARY KEY, id INTEGER, auth_token TEXT, email TEXT"
# Takes success and error callback options, tries
# to login with model attributes
login: (form, options) ->
# Test for existing login
$.ajax(
type: 'GET'
url: 'http://bluecarbon.unep-wcmc.org/admins/me.json'
success: options.success
error: (data)=>
@set('email', form.email)
if data.error?
# Not logged in, login
$.ajax(
type: 'POST'
url: 'http://bluecarbon.unep-wcmc.org/my/admins/sign_in.json'
data:
admin:
email: form.email
password: PI:PASSWORD:<PASSWORD>END_PI
dataType: "json"
success: (data) =>
@set('auth_token', data.auth_token)
@localSave({},
success: (a,b,c)=>
options.success(@)
BlueCarbon.bus.trigger('user:gotAuthToken', data.auth_token)
BlueCarbon.bus.trigger('user:loggedIn', @)
)
error: options.error
)
else
options.error(data)
)
logout: (options) ->
@localDestroy(
success: ->
BlueCarbon.bus.trigger('user:gotAuthToken', '')
options.success()
)
|
[
{
"context": "erSlug = 'aws'\n\n @bootstrapKeys = ['key_pair', 'rtb', 'acl']\n\n @sensitiveKeys = ['access_key', 'secr",
"end": 249,
"score": 0.9434806704521179,
"start": 246,
"tag": "KEY",
"value": "rtb"
},
{
"context": " = 'aws'\n\n @bootstrapKeys = ['key_pair', 'rtb', 'acl']\n... | workers/social/lib/social/models/computeproviders/aws.coffee | ezgikaysi/koding | 1 | ProviderInterface = require './providerinterface'
{ updateMachine } = require './helpers'
KodingError = require '../../error'
module.exports = class Aws extends ProviderInterface
@providerSlug = 'aws'
@bootstrapKeys = ['key_pair', 'rtb', 'acl']
@sensitiveKeys = ['access_key', 'secret_key']
@ping = (client, options, callback) ->
callback null, "#{ @providerSlug } rulez #{ client.r.account.profile.nickname }!"
@create = (client, options, callback) ->
{ credential, instanceType, region, ami, storage, label } = options
storage ?= 8
if isNaN storage
return callback new KodingError \
'Requested storage size is not valid.', 'WrongParameter'
meta =
type : @providerSlug
region : region ? 'us-east-1'
instance_type : instanceType ? 't2.nano'
storage_size : storage
assignedLabel : label
if ami?
meta.source_ami = ami
callback null, { meta, credential }
@update = (client, options, callback) ->
{ machineId, alwaysOn } = options
{ r: { group, user, account } } = client
unless machineId? or alwaysOn?
return callback new KodingError \
'A valid machineId and an update option required.', 'WrongParameter'
JMachine = require './machine'
selector = JMachine.getSelectorFor client, { machineId, owner: yes }
selector.provider = @providerSlug
updateMachine { selector, alwaysOn }, callback
| 70978 | ProviderInterface = require './providerinterface'
{ updateMachine } = require './helpers'
KodingError = require '../../error'
module.exports = class Aws extends ProviderInterface
@providerSlug = 'aws'
@bootstrapKeys = ['key_pair', '<KEY>', '<KEY>']
@sensitiveKeys = ['access_key', 'secret_key']
@ping = (client, options, callback) ->
callback null, "#{ @providerSlug } rulez #{ client.r.account.profile.nickname }!"
@create = (client, options, callback) ->
{ credential, instanceType, region, ami, storage, label } = options
storage ?= 8
if isNaN storage
return callback new KodingError \
'Requested storage size is not valid.', 'WrongParameter'
meta =
type : @providerSlug
region : region ? 'us-east-1'
instance_type : instanceType ? 't2.nano'
storage_size : storage
assignedLabel : label
if ami?
meta.source_ami = ami
callback null, { meta, credential }
@update = (client, options, callback) ->
{ machineId, alwaysOn } = options
{ r: { group, user, account } } = client
unless machineId? or alwaysOn?
return callback new KodingError \
'A valid machineId and an update option required.', 'WrongParameter'
JMachine = require './machine'
selector = JMachine.getSelectorFor client, { machineId, owner: yes }
selector.provider = @providerSlug
updateMachine { selector, alwaysOn }, callback
| true | ProviderInterface = require './providerinterface'
{ updateMachine } = require './helpers'
KodingError = require '../../error'
module.exports = class Aws extends ProviderInterface
@providerSlug = 'aws'
@bootstrapKeys = ['key_pair', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI']
@sensitiveKeys = ['access_key', 'secret_key']
@ping = (client, options, callback) ->
callback null, "#{ @providerSlug } rulez #{ client.r.account.profile.nickname }!"
@create = (client, options, callback) ->
{ credential, instanceType, region, ami, storage, label } = options
storage ?= 8
if isNaN storage
return callback new KodingError \
'Requested storage size is not valid.', 'WrongParameter'
meta =
type : @providerSlug
region : region ? 'us-east-1'
instance_type : instanceType ? 't2.nano'
storage_size : storage
assignedLabel : label
if ami?
meta.source_ami = ami
callback null, { meta, credential }
@update = (client, options, callback) ->
{ machineId, alwaysOn } = options
{ r: { group, user, account } } = client
unless machineId? or alwaysOn?
return callback new KodingError \
'A valid machineId and an update option required.', 'WrongParameter'
JMachine = require './machine'
selector = JMachine.getSelectorFor client, { machineId, owner: yes }
selector.provider = @providerSlug
updateMachine { selector, alwaysOn }, callback
|
[
{
"context": "\n \"\"\"\n\n your_model = new Backbone.Model({name: 'Hello', place: 'World!'})\n ko.applyBindings(kb.viewMod",
"end": 1048,
"score": 0.9881125092506409,
"start": 1043,
"tag": "NAME",
"value": "Hello"
},
{
"context": "our_collection = new Backbone.Collection([{name: ... | test/core/test.coffee | kmalakoff/knockback-inspector | 1 | module("knockback-inspector")
# import Underscore (or Lo-Dash with precedence), Backbone, Knockout, and Knockback
Backbone = if not window.Backbone and (typeof(require) != 'undefined') then require('backbone') else window.Backbone
ko = if not window.ko and (typeof(require) != 'undefined') then require('knockout') else window.ko
kb = if not window.kb and (typeof(require) != 'undefined') then require('knockback') else window.kb
kbi = if not window.kbi and (typeof(require) != 'undefined') then require('knockback-inspector') else window.kbi
test("TEST DEPENDENCY MISSING", ->
ok(!!Backbone); ok(!!ko); ok(!!kb); ok(!!kbi)
)
# make kbi global so can be accessed by templates
window.kbi = kbi
# set the template engine so Knockout can find 'kbi_model_node' and 'kbi_collection_node' templates
ko.setTemplateEngine(new kbi.TemplateEngine())
test("Backbone.Model", ->
html = """
<ul id='model' data-bind="template: {name: 'kbi_model_node', data: kbi.nvm('root', true, $data)}"></ul>
"""
your_model = new Backbone.Model({name: 'Hello', place: 'World!'})
ko.applyBindings(kb.viewModel(your_model), $(html)[0])
ok(true)
)
test("Backbone.Collection", ->
html = """
<ul id='collection' data-bind="template: {name: 'kbi_collection_node', data: kbi.nvm('root', true, $data)}"></ul>
"""
your_collection = new Backbone.Collection([{name: 'Hello', place: 'World!'}, {name: 'Goodbye', place: 'Samsara!'}])
ko.applyBindings(kb.collectionObservable(your_collection, {view_model: kb.ViewModel}), $(html)[0]);
ok(true)
) | 178163 | module("knockback-inspector")
# import Underscore (or Lo-Dash with precedence), Backbone, Knockout, and Knockback
Backbone = if not window.Backbone and (typeof(require) != 'undefined') then require('backbone') else window.Backbone
ko = if not window.ko and (typeof(require) != 'undefined') then require('knockout') else window.ko
kb = if not window.kb and (typeof(require) != 'undefined') then require('knockback') else window.kb
kbi = if not window.kbi and (typeof(require) != 'undefined') then require('knockback-inspector') else window.kbi
test("TEST DEPENDENCY MISSING", ->
ok(!!Backbone); ok(!!ko); ok(!!kb); ok(!!kbi)
)
# make kbi global so can be accessed by templates
window.kbi = kbi
# set the template engine so Knockout can find 'kbi_model_node' and 'kbi_collection_node' templates
ko.setTemplateEngine(new kbi.TemplateEngine())
test("Backbone.Model", ->
html = """
<ul id='model' data-bind="template: {name: 'kbi_model_node', data: kbi.nvm('root', true, $data)}"></ul>
"""
your_model = new Backbone.Model({name: '<NAME>', place: 'World!'})
ko.applyBindings(kb.viewModel(your_model), $(html)[0])
ok(true)
)
test("Backbone.Collection", ->
html = """
<ul id='collection' data-bind="template: {name: 'kbi_collection_node', data: kbi.nvm('root', true, $data)}"></ul>
"""
your_collection = new Backbone.Collection([{name: '<NAME>', place: 'World!'}, {name: '<NAME>', place: 'Samsara!'}])
ko.applyBindings(kb.collectionObservable(your_collection, {view_model: kb.ViewModel}), $(html)[0]);
ok(true)
) | true | module("knockback-inspector")
# import Underscore (or Lo-Dash with precedence), Backbone, Knockout, and Knockback
Backbone = if not window.Backbone and (typeof(require) != 'undefined') then require('backbone') else window.Backbone
ko = if not window.ko and (typeof(require) != 'undefined') then require('knockout') else window.ko
kb = if not window.kb and (typeof(require) != 'undefined') then require('knockback') else window.kb
kbi = if not window.kbi and (typeof(require) != 'undefined') then require('knockback-inspector') else window.kbi
test("TEST DEPENDENCY MISSING", ->
ok(!!Backbone); ok(!!ko); ok(!!kb); ok(!!kbi)
)
# make kbi global so can be accessed by templates
window.kbi = kbi
# set the template engine so Knockout can find 'kbi_model_node' and 'kbi_collection_node' templates
ko.setTemplateEngine(new kbi.TemplateEngine())
test("Backbone.Model", ->
html = """
<ul id='model' data-bind="template: {name: 'kbi_model_node', data: kbi.nvm('root', true, $data)}"></ul>
"""
your_model = new Backbone.Model({name: 'PI:NAME:<NAME>END_PI', place: 'World!'})
ko.applyBindings(kb.viewModel(your_model), $(html)[0])
ok(true)
)
test("Backbone.Collection", ->
html = """
<ul id='collection' data-bind="template: {name: 'kbi_collection_node', data: kbi.nvm('root', true, $data)}"></ul>
"""
your_collection = new Backbone.Collection([{name: 'PI:NAME:<NAME>END_PI', place: 'World!'}, {name: 'PI:NAME:<NAME>END_PI', place: 'Samsara!'}])
ko.applyBindings(kb.collectionObservable(your_collection, {view_model: kb.ViewModel}), $(html)[0]);
ok(true)
) |
[
{
"context": "Accounts.ui.config {passwordSignupFields: 'USERNAME_ONLY'}\n",
"end": 56,
"score": 0.8269023895263672,
"start": 43,
"tag": "PASSWORD",
"value": "USERNAME_ONLY"
}
] | client/helpers/config.coffee | fniessink/checksome | 0 | Accounts.ui.config {passwordSignupFields: 'USERNAME_ONLY'}
| 17037 | Accounts.ui.config {passwordSignupFields: '<PASSWORD>'}
| true | Accounts.ui.config {passwordSignupFields: 'PI:PASSWORD:<PASSWORD>END_PI'}
|
[
{
"context": "ux/models/account\").default\n\ncontact_1 =\n name: \"Evan Morikawa\"\n email: \"evan@nylas.com\"\n\ndescribe \"Contact\", -",
"end": 223,
"score": 0.9998656511306763,
"start": 210,
"tag": "NAME",
"value": "Evan Morikawa"
},
{
"context": "lt\n\ncontact_1 =\n name: \"... | packages/client-app/spec/models/contact-spec.coffee | cnheider/nylas-mail | 24,369 | Contact = require("../../src/flux/models/contact").default
AccountStore = require("../../src/flux/stores/account-store").default
Account = require("../../src/flux/models/account").default
contact_1 =
name: "Evan Morikawa"
email: "evan@nylas.com"
describe "Contact", ->
beforeEach ->
@account = AccountStore.accounts()[0]
it "can be built via the constructor", ->
c1 = new Contact contact_1
expect(c1.name).toBe "Evan Morikawa"
expect(c1.email).toBe "evan@nylas.com"
it "accepts a JSON response", ->
c1 = (new Contact).fromJSON(contact_1)
expect(c1.name).toBe "Evan Morikawa"
expect(c1.email).toBe "evan@nylas.com"
it "correctly parses first and last names", ->
c1 = new Contact {name: "Evan Morikawa"}
expect(c1.firstName()).toBe "Evan"
expect(c1.lastName()).toBe "Morikawa"
c2 = new Contact {name: "Evan Takashi Morikawa"}
expect(c2.firstName()).toBe "Evan"
expect(c2.lastName()).toBe "Takashi Morikawa"
c3 = new Contact {name: "evan foo last-name"}
expect(c3.firstName()).toBe "evan"
expect(c3.lastName()).toBe "foo last-name"
c4 = new Contact {name: "Prince"}
expect(c4.firstName()).toBe "Prince"
expect(c4.lastName()).toBe ""
c5 = new Contact {name: "Mr. Evan Morikawa"}
expect(c5.firstName()).toBe "Evan"
expect(c5.lastName()).toBe "Morikawa"
c6 = new Contact {name: "Mr Evan morikawa"}
expect(c6.firstName()).toBe "Evan"
expect(c6.lastName()).toBe "morikawa"
c7 = new Contact {name: "Dr. No"}
expect(c7.firstName()).toBe "No"
expect(c7.lastName()).toBe ""
c8 = new Contact {name: "Mr"}
expect(c8.firstName()).toBe "Mr"
expect(c8.lastName()).toBe ""
it "properly parses Mike Kaylor via LinkedIn", ->
c8 = new Contact {name: "Mike Kaylor via LinkedIn"}
expect(c8.firstName()).toBe "Mike"
expect(c8.lastName()).toBe "Kaylor"
c8 = new Contact {name: "Mike Kaylor VIA LinkedIn"}
expect(c8.firstName()).toBe "Mike"
expect(c8.lastName()).toBe "Kaylor"
c8 = new Contact {name: "Mike Viator"}
expect(c8.firstName()).toBe "Mike"
expect(c8.lastName()).toBe "Viator"
c8 = new Contact {name: "Olivia Pope"}
expect(c8.firstName()).toBe "Olivia"
expect(c8.lastName()).toBe "Pope"
it "should not by fancy about the contents of parenthesis (Evan Morikawa)", ->
c8 = new Contact {name: "Evan (Evan Morikawa)"}
expect(c8.firstName()).toBe "Evan"
expect(c8.lastName()).toBe "(Evan Morikawa)"
it "falls back to the first component of the email if name isn't present", ->
c1 = new Contact {name: " Evan Morikawa ", email: "evan@nylas.com"}
expect(c1.displayName()).toBe "Evan Morikawa"
expect(c1.displayName(compact: true)).toBe "Evan"
c2 = new Contact {name: "", email: "evan@nylas.com"}
expect(c2.displayName()).toBe "evan"
expect(c2.displayName(compact: true)).toBe "evan"
c3 = new Contact {name: "", email: ""}
expect(c3.displayName()).toBe ""
expect(c3.displayName(compact: true)).toBe ""
it "properly parses names with @", ->
c1 = new Contact {name: "nyl@s"}
expect(c1.firstName()).toBe "nyl@s"
expect(c1.lastName()).toBe ""
c1 = new Contact {name: "nyl@s@n1"}
expect(c1.firstName()).toBe "nyl@s@n1"
expect(c1.lastName()).toBe ""
c2 = new Contact {name: "nyl@s nyl@s"}
expect(c2.firstName()).toBe "nyl@s"
expect(c2.lastName()).toBe "nyl@s"
c3 = new Contact {name: "nyl@s 2000"}
expect(c3.firstName()).toBe "nyl@s"
expect(c3.lastName()).toBe "2000"
c6 = new Contact {name: "ev@nylas.com", email: "ev@nylas.com"}
expect(c6.firstName()).toBe "ev@nylas.com"
expect(c6.lastName()).toBe ""
c7 = new Contact {name: "evan@nylas.com"}
expect(c7.firstName()).toBe "evan@nylas.com"
expect(c7.lastName()).toBe ""
c8 = new Contact {name: "Mike K@ylor via L@nkedIn"}
expect(c8.firstName()).toBe "Mike"
expect(c8.lastName()).toBe "K@ylor"
it "properly parses names with last, first (description)", ->
c1 = new Contact {name: "Smith, Bob"}
expect(c1.firstName()).toBe "Bob"
expect(c1.lastName()).toBe "Smith"
expect(c1.fullName()).toBe "Bob Smith"
c2 = new Contact {name: "von Smith, Ricky Bobby"}
expect(c2.firstName()).toBe "Ricky Bobby"
expect(c2.lastName()).toBe "von Smith"
expect(c2.fullName()).toBe "Ricky Bobby von Smith"
c3 = new Contact {name: "von Smith, Ricky Bobby (Awesome Employee)"}
expect(c3.firstName()).toBe "Ricky Bobby"
expect(c3.lastName()).toBe "von Smith (Awesome Employee)"
expect(c3.fullName()).toBe "Ricky Bobby von Smith (Awesome Employee)"
it "should properly return `You` as the display name for the current user", ->
c1 = new Contact {name: " Test Monkey", email: @account.emailAddress}
expect(c1.displayName()).toBe "You"
expect(c1.displayName(compact: true)).toBe "You"
describe "isMe", ->
it "returns true if the contact name matches the account email address", ->
c1 = new Contact {email: @account.emailAddress}
expect(c1.isMe()).toBe(true)
c1 = new Contact {email: 'ben@nylas.com'}
expect(c1.isMe()).toBe(false)
it "is case insensitive", ->
c1 = new Contact {email: @account.emailAddress.toUpperCase()}
expect(c1.isMe()).toBe(true)
it "it calls through to accountForEmail", ->
c1 = new Contact {email: @account.emailAddress}
acct = new Account()
spyOn(AccountStore, 'accountForEmail').andReturn(acct)
expect(c1.isMe()).toBe(true)
expect(AccountStore.accountForEmail).toHaveBeenCalled()
describe 'isValid', ->
it "should return true for a variety of valid contacts", ->
expect((new Contact(name: 'Ben', email: 'ben@nylas.com')).isValid()).toBe(true)
expect((new Contact(email: 'ben@nylas.com')).isValid()).toBe(true)
expect((new Contact(email: 'ben+123@nylas.com')).isValid()).toBe(true)
it "should support contacts with unicode characters in domains", ->
expect((new Contact(name: 'Ben', email: 'ben@arıman.com')).isValid()).toBe(true)
it "should return false if the contact has no email", ->
expect((new Contact(name: 'Ben')).isValid()).toBe(false)
it "should return false if the contact has an email that is not valid", ->
expect((new Contact(name: 'Ben', email:'Ben <ben@nylas.com>')).isValid()).toBe(false)
expect((new Contact(name: 'Ben', email:'<ben@nylas.com>')).isValid()).toBe(false)
expect((new Contact(name: 'Ben', email:'"ben@nylas.com"')).isValid()).toBe(false)
it "returns false if the email doesn't satisfy the regex", ->
expect((new Contact(name: "test", email: "foo")).isValid()).toBe false
it "returns false if the email doesn't match", ->
expect((new Contact(name: "test", email: "foo@")).isValid()).toBe false
| 205074 | Contact = require("../../src/flux/models/contact").default
AccountStore = require("../../src/flux/stores/account-store").default
Account = require("../../src/flux/models/account").default
contact_1 =
name: "<NAME>"
email: "<EMAIL>"
describe "Contact", ->
beforeEach ->
@account = AccountStore.accounts()[0]
it "can be built via the constructor", ->
c1 = new Contact contact_1
expect(c1.name).toBe "<NAME>"
expect(c1.email).toBe "<EMAIL>"
it "accepts a JSON response", ->
c1 = (new Contact).fromJSON(contact_1)
expect(c1.name).toBe "<NAME>"
expect(c1.email).toBe "<EMAIL>"
it "correctly parses first and last names", ->
c1 = new Contact {name: "<NAME>"}
expect(c1.firstName()).toBe "<NAME>"
expect(c1.lastName()).toBe "<NAME>"
c2 = new Contact {name: "<NAME>"}
expect(c2.firstName()).toBe "<NAME>"
expect(c2.lastName()).toBe "<NAME>"
c3 = new Contact {name: "<NAME> foo last-name"}
expect(c3.firstName()).toBe "ev<NAME>"
expect(c3.lastName()).toBe "foo last-name"
c4 = new Contact {name: "<NAME>"}
expect(c4.firstName()).toBe "<NAME>"
expect(c4.lastName()).toBe ""
c5 = new Contact {name: "Mr. <NAME>"}
expect(c5.firstName()).toBe "<NAME>"
expect(c5.lastName()).toBe "<NAME>"
c6 = new Contact {name: "Mr <NAME>"}
expect(c6.firstName()).toBe "<NAME>"
expect(c6.lastName()).toBe "<NAME>awa"
c7 = new Contact {name: "Dr. No"}
expect(c7.firstName()).toBe "No"
expect(c7.lastName()).toBe ""
c8 = new Contact {name: "Mr"}
expect(c8.firstName()).toBe "Mr"
expect(c8.lastName()).toBe ""
it "properly parses <NAME> via LinkedIn", ->
c8 = new Contact {name: "<NAME> via LinkedIn"}
expect(c8.firstName()).toBe "<NAME>"
expect(c8.lastName()).toBe "<NAME>"
c8 = new Contact {name: "<NAME> VIA LinkedIn"}
expect(c8.firstName()).toBe "<NAME>"
expect(c8.lastName()).toBe "<NAME>"
c8 = new Contact {name: "<NAME>"}
expect(c8.firstName()).toBe "<NAME>"
expect(c8.lastName()).toBe "<NAME>"
c8 = new Contact {name: "<NAME>"}
expect(c8.firstName()).toBe "<NAME>"
expect(c8.lastName()).toBe "<NAME>"
it "should not by fancy about the contents of parenthesis (<NAME>)", ->
c8 = new Contact {name: "<NAME> (<NAME>)"}
expect(c8.firstName()).toBe "<NAME>"
expect(c8.lastName()).toBe "(<NAME>)"
it "falls back to the first component of the email if name isn't present", ->
c1 = new Contact {name: " <NAME> ", email: "<EMAIL>"}
expect(c1.displayName()).toBe "<NAME>"
expect(c1.displayName(compact: true)).toBe "<NAME>"
c2 = new Contact {name: "", email: "<EMAIL>"}
expect(c2.displayName()).toBe "evan"
expect(c2.displayName(compact: true)).toBe "evan"
c3 = new Contact {name: "", email: ""}
expect(c3.displayName()).toBe ""
expect(c3.displayName(compact: true)).toBe ""
it "properly parses names with @", ->
c1 = new Contact {name: "nyl@s"}
expect(c1.firstName()).toBe "nyl@s"
expect(c1.lastName()).toBe ""
c1 = new Contact {name: "nyl@s@n1"}
expect(c1.firstName()).toBe "nyl@s@n1"
expect(c1.lastName()).toBe ""
c2 = new Contact {name: "nyl@s nyl@s"}
expect(c2.firstName()).toBe "nyl@s"
expect(c2.lastName()).toBe "nyl@s"
c3 = new Contact {name: "nyl@s 2000"}
expect(c3.firstName()).toBe "nyl@s"
expect(c3.lastName()).toBe "2000"
c6 = new Contact {name: "<EMAIL>", email: "<EMAIL>"}
expect(c6.firstName()).toBe "<EMAIL>"
expect(c6.lastName()).toBe ""
c7 = new Contact {name: "<EMAIL>"}
expect(c7.firstName()).toBe "<EMAIL>"
expect(c7.lastName()).toBe ""
c8 = new Contact {name: "<NAME> via L@nkedIn"}
expect(c8.firstName()).toBe "<NAME>"
expect(c8.lastName()).toBe "K@yl<NAME>"
it "properly parses names with last, first (description)", ->
c1 = new Contact {name: "<NAME>, <NAME>"}
expect(c1.firstName()).toBe "<NAME>"
expect(c1.lastName()).toBe "<NAME>"
expect(c1.fullName()).toBe "<NAME>"
c2 = new Contact {name: "<NAME>, <NAME>"}
expect(c2.firstName()).toBe "<NAME>"
expect(c2.lastName()).toBe "<NAME>"
expect(c2.fullName()).toBe "<NAME>"
c3 = new Contact {name: "<NAME>, <NAME> (Awesome Employee)"}
expect(c3.firstName()).toBe "<NAME>"
expect(c3.lastName()).toBe "<NAME> (Awesome Employee)"
expect(c3.fullName()).toBe "<NAME> von <NAME> (Awesome Employee)"
it "should properly return `You` as the display name for the current user", ->
c1 = new Contact {name: " <NAME>", email: @account.emailAddress}
expect(c1.displayName()).toBe "You"
expect(c1.displayName(compact: true)).toBe "You"
describe "isMe", ->
it "returns true if the contact name matches the account email address", ->
c1 = new Contact {email: @account.emailAddress}
expect(c1.isMe()).toBe(true)
c1 = new Contact {email: '<EMAIL>'}
expect(c1.isMe()).toBe(false)
it "is case insensitive", ->
c1 = new Contact {email: @account.emailAddress.toUpperCase()}
expect(c1.isMe()).toBe(true)
it "it calls through to accountForEmail", ->
c1 = new Contact {email: @account.emailAddress}
acct = new Account()
spyOn(AccountStore, 'accountForEmail').andReturn(acct)
expect(c1.isMe()).toBe(true)
expect(AccountStore.accountForEmail).toHaveBeenCalled()
describe 'isValid', ->
it "should return true for a variety of valid contacts", ->
expect((new Contact(name: '<NAME>', email: '<EMAIL>')).isValid()).toBe(true)
expect((new Contact(email: '<EMAIL>')).isValid()).toBe(true)
expect((new Contact(email: '<EMAIL>')).isValid()).toBe(true)
it "should support contacts with unicode characters in domains", ->
expect((new Contact(name: '<NAME>', email: '<EMAIL>')).isValid()).toBe(true)
it "should return false if the contact has no email", ->
expect((new Contact(name: '<NAME>')).isValid()).toBe(false)
it "should return false if the contact has an email that is not valid", ->
expect((new Contact(name: '<NAME>', email:'<NAME> <<EMAIL>>')).isValid()).toBe(false)
expect((new Contact(name: '<NAME>', email:'<<EMAIL>>')).isValid()).toBe(false)
expect((new Contact(name: '<NAME>', email:'"<EMAIL>"')).isValid()).toBe(false)
it "returns false if the email doesn't satisfy the regex", ->
expect((new Contact(name: "<NAME>", email: "foo")).isValid()).toBe false
it "returns false if the email doesn't match", ->
expect((new Contact(name: "<NAME>", email: "foo@")).isValid()).toBe false
| true | Contact = require("../../src/flux/models/contact").default
AccountStore = require("../../src/flux/stores/account-store").default
Account = require("../../src/flux/models/account").default
contact_1 =
name: "PI:NAME:<NAME>END_PI"
email: "PI:EMAIL:<EMAIL>END_PI"
describe "Contact", ->
beforeEach ->
@account = AccountStore.accounts()[0]
it "can be built via the constructor", ->
c1 = new Contact contact_1
expect(c1.name).toBe "PI:NAME:<NAME>END_PI"
expect(c1.email).toBe "PI:EMAIL:<EMAIL>END_PI"
it "accepts a JSON response", ->
c1 = (new Contact).fromJSON(contact_1)
expect(c1.name).toBe "PI:NAME:<NAME>END_PI"
expect(c1.email).toBe "PI:EMAIL:<EMAIL>END_PI"
it "correctly parses first and last names", ->
c1 = new Contact {name: "PI:NAME:<NAME>END_PI"}
expect(c1.firstName()).toBe "PI:NAME:<NAME>END_PI"
expect(c1.lastName()).toBe "PI:NAME:<NAME>END_PI"
c2 = new Contact {name: "PI:NAME:<NAME>END_PI"}
expect(c2.firstName()).toBe "PI:NAME:<NAME>END_PI"
expect(c2.lastName()).toBe "PI:NAME:<NAME>END_PI"
c3 = new Contact {name: "PI:NAME:<NAME>END_PI foo last-name"}
expect(c3.firstName()).toBe "evPI:NAME:<NAME>END_PI"
expect(c3.lastName()).toBe "foo last-name"
c4 = new Contact {name: "PI:NAME:<NAME>END_PI"}
expect(c4.firstName()).toBe "PI:NAME:<NAME>END_PI"
expect(c4.lastName()).toBe ""
c5 = new Contact {name: "Mr. PI:NAME:<NAME>END_PI"}
expect(c5.firstName()).toBe "PI:NAME:<NAME>END_PI"
expect(c5.lastName()).toBe "PI:NAME:<NAME>END_PI"
c6 = new Contact {name: "Mr PI:NAME:<NAME>END_PI"}
expect(c6.firstName()).toBe "PI:NAME:<NAME>END_PI"
expect(c6.lastName()).toBe "PI:NAME:<NAME>END_PIawa"
c7 = new Contact {name: "Dr. No"}
expect(c7.firstName()).toBe "No"
expect(c7.lastName()).toBe ""
c8 = new Contact {name: "Mr"}
expect(c8.firstName()).toBe "Mr"
expect(c8.lastName()).toBe ""
it "properly parses PI:NAME:<NAME>END_PI via LinkedIn", ->
c8 = new Contact {name: "PI:NAME:<NAME>END_PI via LinkedIn"}
expect(c8.firstName()).toBe "PI:NAME:<NAME>END_PI"
expect(c8.lastName()).toBe "PI:NAME:<NAME>END_PI"
c8 = new Contact {name: "PI:NAME:<NAME>END_PI VIA LinkedIn"}
expect(c8.firstName()).toBe "PI:NAME:<NAME>END_PI"
expect(c8.lastName()).toBe "PI:NAME:<NAME>END_PI"
c8 = new Contact {name: "PI:NAME:<NAME>END_PI"}
expect(c8.firstName()).toBe "PI:NAME:<NAME>END_PI"
expect(c8.lastName()).toBe "PI:NAME:<NAME>END_PI"
c8 = new Contact {name: "PI:NAME:<NAME>END_PI"}
expect(c8.firstName()).toBe "PI:NAME:<NAME>END_PI"
expect(c8.lastName()).toBe "PI:NAME:<NAME>END_PI"
it "should not by fancy about the contents of parenthesis (PI:NAME:<NAME>END_PI)", ->
c8 = new Contact {name: "PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)"}
expect(c8.firstName()).toBe "PI:NAME:<NAME>END_PI"
expect(c8.lastName()).toBe "(PI:NAME:<NAME>END_PI)"
it "falls back to the first component of the email if name isn't present", ->
c1 = new Contact {name: " PI:NAME:<NAME>END_PI ", email: "PI:EMAIL:<EMAIL>END_PI"}
expect(c1.displayName()).toBe "PI:NAME:<NAME>END_PI"
expect(c1.displayName(compact: true)).toBe "PI:NAME:<NAME>END_PI"
c2 = new Contact {name: "", email: "PI:EMAIL:<EMAIL>END_PI"}
expect(c2.displayName()).toBe "evan"
expect(c2.displayName(compact: true)).toBe "evan"
c3 = new Contact {name: "", email: ""}
expect(c3.displayName()).toBe ""
expect(c3.displayName(compact: true)).toBe ""
it "properly parses names with @", ->
c1 = new Contact {name: "nyl@s"}
expect(c1.firstName()).toBe "nyl@s"
expect(c1.lastName()).toBe ""
c1 = new Contact {name: "nyl@s@n1"}
expect(c1.firstName()).toBe "nyl@s@n1"
expect(c1.lastName()).toBe ""
c2 = new Contact {name: "nyl@s nyl@s"}
expect(c2.firstName()).toBe "nyl@s"
expect(c2.lastName()).toBe "nyl@s"
c3 = new Contact {name: "nyl@s 2000"}
expect(c3.firstName()).toBe "nyl@s"
expect(c3.lastName()).toBe "2000"
c6 = new Contact {name: "PI:EMAIL:<EMAIL>END_PI", email: "PI:EMAIL:<EMAIL>END_PI"}
expect(c6.firstName()).toBe "PI:EMAIL:<EMAIL>END_PI"
expect(c6.lastName()).toBe ""
c7 = new Contact {name: "PI:EMAIL:<EMAIL>END_PI"}
expect(c7.firstName()).toBe "PI:EMAIL:<EMAIL>END_PI"
expect(c7.lastName()).toBe ""
c8 = new Contact {name: "PI:NAME:<NAME>END_PI via L@nkedIn"}
expect(c8.firstName()).toBe "PI:NAME:<NAME>END_PI"
expect(c8.lastName()).toBe "K@ylPI:NAME:<NAME>END_PI"
it "properly parses names with last, first (description)", ->
c1 = new Contact {name: "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI"}
expect(c1.firstName()).toBe "PI:NAME:<NAME>END_PI"
expect(c1.lastName()).toBe "PI:NAME:<NAME>END_PI"
expect(c1.fullName()).toBe "PI:NAME:<NAME>END_PI"
c2 = new Contact {name: "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI"}
expect(c2.firstName()).toBe "PI:NAME:<NAME>END_PI"
expect(c2.lastName()).toBe "PI:NAME:<NAME>END_PI"
expect(c2.fullName()).toBe "PI:NAME:<NAME>END_PI"
c3 = new Contact {name: "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI (Awesome Employee)"}
expect(c3.firstName()).toBe "PI:NAME:<NAME>END_PI"
expect(c3.lastName()).toBe "PI:NAME:<NAME>END_PI (Awesome Employee)"
expect(c3.fullName()).toBe "PI:NAME:<NAME>END_PI von PI:NAME:<NAME>END_PI (Awesome Employee)"
it "should properly return `You` as the display name for the current user", ->
c1 = new Contact {name: " PI:NAME:<NAME>END_PI", email: @account.emailAddress}
expect(c1.displayName()).toBe "You"
expect(c1.displayName(compact: true)).toBe "You"
describe "isMe", ->
it "returns true if the contact name matches the account email address", ->
c1 = new Contact {email: @account.emailAddress}
expect(c1.isMe()).toBe(true)
c1 = new Contact {email: 'PI:EMAIL:<EMAIL>END_PI'}
expect(c1.isMe()).toBe(false)
it "is case insensitive", ->
c1 = new Contact {email: @account.emailAddress.toUpperCase()}
expect(c1.isMe()).toBe(true)
it "it calls through to accountForEmail", ->
c1 = new Contact {email: @account.emailAddress}
acct = new Account()
spyOn(AccountStore, 'accountForEmail').andReturn(acct)
expect(c1.isMe()).toBe(true)
expect(AccountStore.accountForEmail).toHaveBeenCalled()
describe 'isValid', ->
it "should return true for a variety of valid contacts", ->
expect((new Contact(name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI')).isValid()).toBe(true)
expect((new Contact(email: 'PI:EMAIL:<EMAIL>END_PI')).isValid()).toBe(true)
expect((new Contact(email: 'PI:EMAIL:<EMAIL>END_PI')).isValid()).toBe(true)
it "should support contacts with unicode characters in domains", ->
expect((new Contact(name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI')).isValid()).toBe(true)
it "should return false if the contact has no email", ->
expect((new Contact(name: 'PI:NAME:<NAME>END_PI')).isValid()).toBe(false)
it "should return false if the contact has an email that is not valid", ->
expect((new Contact(name: 'PI:NAME:<NAME>END_PI', email:'PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>')).isValid()).toBe(false)
expect((new Contact(name: 'PI:NAME:<NAME>END_PI', email:'<PI:EMAIL:<EMAIL>END_PI>')).isValid()).toBe(false)
expect((new Contact(name: 'PI:NAME:<NAME>END_PI', email:'"PI:EMAIL:<EMAIL>END_PI"')).isValid()).toBe(false)
it "returns false if the email doesn't satisfy the regex", ->
expect((new Contact(name: "PI:NAME:<NAME>END_PI", email: "foo")).isValid()).toBe false
it "returns false if the email doesn't match", ->
expect((new Contact(name: "PI:NAME:<NAME>END_PI", email: "foo@")).isValid()).toBe false
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999068975448608,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/beatmapset-page/info.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 { BBCodeEditor } from 'bbcode-editor'
import { Modal } from 'modal'
import * as React from 'react'
import { a, button, div, h3, span, i, textarea } from 'react-dom-factories'
import MetadataEditor from 'beatmapsets-show/metadata-editor'
el = React.createElement
export class Info extends React.Component
constructor: (props) ->
super props
@overlay = React.createRef()
@state =
isBusy: false
isEditingDescription: false
isEditingMetadata: false
componentDidMount: ->
@renderChart()
componentDidUpdate: ->
@renderChart()
componentWillUnmount: =>
$(window).off '.beatmapsetPageInfo'
# see Modal#hideModal
dismissEditor: (e) =>
@setState isEditingDescription: false if e.button == 0 &&
e.target == @overlay.current &&
@clickEndTarget == @clickStartTarget
editStart: =>
@setState isEditingDescription: true
handleClickEnd: (e) =>
@clickEndTarget = e.target
handleClickStart: (e) =>
@clickStartTarget = e.target
onEditorChange: (action) =>
switch action.type
when 'save'
if action.hasChanged
@saveDescription(action.value)
else
@setState isEditingDescription: false
when 'cancel'
@setState isEditingDescription: false
onSelectionUpdate: (selection) =>
@setState selection: selection
saveDescription: (value) =>
@setState isBusy: true
$.ajax laroute.route('beatmapsets.update', beatmapset: @props.beatmapset.id),
method: 'PATCH',
data:
description: value
.done (data) =>
@setState
isEditingDescription: false
description: data.description
.fail osu.ajaxError
.always =>
@setState isBusy: false
toggleEditingMetadata: =>
@setState isEditingMetadata: !@state.isEditingMetadata
withEdit: =>
@props.beatmapset.description.bbcode?
withEditMetadata: =>
@props.beatmapset.current_user_attributes?.can_edit_metadata ? false
renderChart: ->
return if !@props.beatmapset.is_scoreable || @props.beatmap.playcount < 1
unless @_failurePointsChart?
options =
scales:
x: d3.scaleLinear()
y: d3.scaleLinear()
modifiers: ['beatmap-success-rate']
@_failurePointsChart = new StackedBarChart @refs.chartArea, options
$(window).on 'throttled-resize.beatmapsetPageInfo', @_failurePointsChart.resize
@_failurePointsChart.loadData @props.beatmap.failtimes
renderEditMetadataButton: =>
div className: 'beatmapset-info__edit-button',
button
type: 'button'
className: 'btn-circle'
onClick: @toggleEditingMetadata
span className: 'btn-circle__content',
i className: 'fas fa-pencil-alt'
renderEditButton: =>
div className: 'beatmapset-info__edit-button',
button
type: 'button'
className: 'btn-circle'
onClick: @editStart
span className: 'btn-circle__content',
i className: 'fas fa-pencil-alt'
render: ->
tags = _(@props.beatmapset.tags)
.split(' ')
.filter((t) -> t? && t != '')
.slice(0, 21)
.value()
if tags.length == 21
tags.pop()
tagsOverload = true
div className: 'beatmapset-info',
if @state.isEditingDescription
div className: 'beatmapset-description-editor',
div
className: 'beatmapset-description-editor__overlay'
onClick: @dismissEditor
onMouseDown: @handleClickStart
onMouseUp: @handleClickEnd
ref: @overlay
div className: 'beatmapset-description-editor__container osu-page',
el BBCodeEditor,
modifiers: ['beatmapset-description-editor']
disabled: @state.isBusy
onChange: @onEditorChange
onSelectionUpdate: @onSelectionUpdate
rawValue: @state.description?.bbcode ? @props.beatmapset.description.bbcode
selection: @state.selection
if @state.isEditingMetadata
el Modal, visible: true, onClose: @toggleEditingMetadata,
el MetadataEditor, onClose: @toggleEditingMetadata, beatmapset: @props.beatmapset
div className: 'beatmapset-info__box beatmapset-info__box--description',
@renderEditButton() if @withEdit()
h3
className: 'beatmapset-info__header'
osu.trans 'beatmapsets.show.info.description'
div className: 'beatmapset-info__description-container u-fancy-scrollbar',
div
className: 'beatmapset-info__description'
dangerouslySetInnerHTML:
__html: @state.description?.description ? @props.beatmapset.description.description
div className: 'beatmapset-info__box beatmapset-info__box--meta',
@renderEditMetadataButton() if @withEditMetadata()
if @props.beatmapset.source
div null,
h3
className: 'beatmapset-info__header'
osu.trans 'beatmapsets.show.info.source'
a
href: laroute.route('beatmapsets.index', q: @props.beatmapset.source)
@props.beatmapset.source
div className: 'beatmapset-info__half-box',
div className: 'beatmapset-info__half-entry',
h3 className: 'beatmapset-info__header',
osu.trans 'beatmapsets.show.info.genre'
a
href: laroute.route('beatmapsets.index', g: @props.beatmapset.genre.id)
@props.beatmapset.genre.name
div className: 'beatmapset-info__half-entry',
h3 className: 'beatmapset-info__header',
osu.trans 'beatmapsets.show.info.language'
a
href: laroute.route('beatmapsets.index', l: @props.beatmapset.language.id)
@props.beatmapset.language.name
if tags.length > 0
div null,
h3
className: 'beatmapset-info__header'
osu.trans 'beatmapsets.show.info.tags'
div null,
for tag in tags
[
a
key: tag
href: laroute.route('beatmapsets.index', q: tag)
tag
span key: "#{tag}-space", ' '
]
'...' if tagsOverload
div className: 'beatmapset-info__box beatmapset-info__box--success-rate',
if !@props.beatmapset.is_scoreable
div className: 'beatmap-success-rate',
div
className: 'beatmap-success-rate__empty'
osu.trans 'beatmapsets.show.info.unranked'
else
if @props.beatmap.playcount > 0
percentage = _.round((@props.beatmap.passcount / @props.beatmap.playcount) * 100, 1)
div className: 'beatmap-success-rate',
h3
className: 'beatmap-success-rate__header'
osu.trans 'beatmapsets.show.info.success-rate'
div className: 'bar bar--beatmap-success-rate',
div
className: 'bar__fill'
style:
width: "#{percentage}%"
div
className: 'beatmap-success-rate__percentage'
title: "#{osu.formatNumber(@props.beatmap.passcount)} / #{osu.formatNumber(@props.beatmap.playcount)}"
'data-tooltip-position': 'bottom center'
style:
marginLeft: "#{percentage}%"
"#{percentage}%"
h3
className: 'beatmap-success-rate__header'
osu.trans 'beatmapsets.show.info.points-of-failure'
div
className: 'beatmap-success-rate__chart'
ref: 'chartArea'
else
div className: 'beatmap-success-rate',
div
className: 'beatmap-success-rate__empty'
osu.trans 'beatmapsets.show.info.no_scores'
| 124376 | # 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 { BBCodeEditor } from 'bbcode-editor'
import { Modal } from 'modal'
import * as React from 'react'
import { a, button, div, h3, span, i, textarea } from 'react-dom-factories'
import MetadataEditor from 'beatmapsets-show/metadata-editor'
el = React.createElement
export class Info extends React.Component
constructor: (props) ->
super props
@overlay = React.createRef()
@state =
isBusy: false
isEditingDescription: false
isEditingMetadata: false
componentDidMount: ->
@renderChart()
componentDidUpdate: ->
@renderChart()
componentWillUnmount: =>
$(window).off '.beatmapsetPageInfo'
# see Modal#hideModal
dismissEditor: (e) =>
@setState isEditingDescription: false if e.button == 0 &&
e.target == @overlay.current &&
@clickEndTarget == @clickStartTarget
editStart: =>
@setState isEditingDescription: true
handleClickEnd: (e) =>
@clickEndTarget = e.target
handleClickStart: (e) =>
@clickStartTarget = e.target
onEditorChange: (action) =>
switch action.type
when 'save'
if action.hasChanged
@saveDescription(action.value)
else
@setState isEditingDescription: false
when 'cancel'
@setState isEditingDescription: false
onSelectionUpdate: (selection) =>
@setState selection: selection
saveDescription: (value) =>
@setState isBusy: true
$.ajax laroute.route('beatmapsets.update', beatmapset: @props.beatmapset.id),
method: 'PATCH',
data:
description: value
.done (data) =>
@setState
isEditingDescription: false
description: data.description
.fail osu.ajaxError
.always =>
@setState isBusy: false
toggleEditingMetadata: =>
@setState isEditingMetadata: !@state.isEditingMetadata
withEdit: =>
@props.beatmapset.description.bbcode?
withEditMetadata: =>
@props.beatmapset.current_user_attributes?.can_edit_metadata ? false
renderChart: ->
return if !@props.beatmapset.is_scoreable || @props.beatmap.playcount < 1
unless @_failurePointsChart?
options =
scales:
x: d3.scaleLinear()
y: d3.scaleLinear()
modifiers: ['beatmap-success-rate']
@_failurePointsChart = new StackedBarChart @refs.chartArea, options
$(window).on 'throttled-resize.beatmapsetPageInfo', @_failurePointsChart.resize
@_failurePointsChart.loadData @props.beatmap.failtimes
renderEditMetadataButton: =>
div className: 'beatmapset-info__edit-button',
button
type: 'button'
className: 'btn-circle'
onClick: @toggleEditingMetadata
span className: 'btn-circle__content',
i className: 'fas fa-pencil-alt'
renderEditButton: =>
div className: 'beatmapset-info__edit-button',
button
type: 'button'
className: 'btn-circle'
onClick: @editStart
span className: 'btn-circle__content',
i className: 'fas fa-pencil-alt'
render: ->
tags = _(@props.beatmapset.tags)
.split(' ')
.filter((t) -> t? && t != '')
.slice(0, 21)
.value()
if tags.length == 21
tags.pop()
tagsOverload = true
div className: 'beatmapset-info',
if @state.isEditingDescription
div className: 'beatmapset-description-editor',
div
className: 'beatmapset-description-editor__overlay'
onClick: @dismissEditor
onMouseDown: @handleClickStart
onMouseUp: @handleClickEnd
ref: @overlay
div className: 'beatmapset-description-editor__container osu-page',
el BBCodeEditor,
modifiers: ['beatmapset-description-editor']
disabled: @state.isBusy
onChange: @onEditorChange
onSelectionUpdate: @onSelectionUpdate
rawValue: @state.description?.bbcode ? @props.beatmapset.description.bbcode
selection: @state.selection
if @state.isEditingMetadata
el Modal, visible: true, onClose: @toggleEditingMetadata,
el MetadataEditor, onClose: @toggleEditingMetadata, beatmapset: @props.beatmapset
div className: 'beatmapset-info__box beatmapset-info__box--description',
@renderEditButton() if @withEdit()
h3
className: 'beatmapset-info__header'
osu.trans 'beatmapsets.show.info.description'
div className: 'beatmapset-info__description-container u-fancy-scrollbar',
div
className: 'beatmapset-info__description'
dangerouslySetInnerHTML:
__html: @state.description?.description ? @props.beatmapset.description.description
div className: 'beatmapset-info__box beatmapset-info__box--meta',
@renderEditMetadataButton() if @withEditMetadata()
if @props.beatmapset.source
div null,
h3
className: 'beatmapset-info__header'
osu.trans 'beatmapsets.show.info.source'
a
href: laroute.route('beatmapsets.index', q: @props.beatmapset.source)
@props.beatmapset.source
div className: 'beatmapset-info__half-box',
div className: 'beatmapset-info__half-entry',
h3 className: 'beatmapset-info__header',
osu.trans 'beatmapsets.show.info.genre'
a
href: laroute.route('beatmapsets.index', g: @props.beatmapset.genre.id)
@props.beatmapset.genre.name
div className: 'beatmapset-info__half-entry',
h3 className: 'beatmapset-info__header',
osu.trans 'beatmapsets.show.info.language'
a
href: laroute.route('beatmapsets.index', l: @props.beatmapset.language.id)
@props.beatmapset.language.name
if tags.length > 0
div null,
h3
className: 'beatmapset-info__header'
osu.trans 'beatmapsets.show.info.tags'
div null,
for tag in tags
[
a
key: tag
href: laroute.route('beatmapsets.index', q: tag)
tag
span key: "#{tag}-space", ' '
]
'...' if tagsOverload
div className: 'beatmapset-info__box beatmapset-info__box--success-rate',
if !@props.beatmapset.is_scoreable
div className: 'beatmap-success-rate',
div
className: 'beatmap-success-rate__empty'
osu.trans 'beatmapsets.show.info.unranked'
else
if @props.beatmap.playcount > 0
percentage = _.round((@props.beatmap.passcount / @props.beatmap.playcount) * 100, 1)
div className: 'beatmap-success-rate',
h3
className: 'beatmap-success-rate__header'
osu.trans 'beatmapsets.show.info.success-rate'
div className: 'bar bar--beatmap-success-rate',
div
className: 'bar__fill'
style:
width: "#{percentage}%"
div
className: 'beatmap-success-rate__percentage'
title: "#{osu.formatNumber(@props.beatmap.passcount)} / #{osu.formatNumber(@props.beatmap.playcount)}"
'data-tooltip-position': 'bottom center'
style:
marginLeft: "#{percentage}%"
"#{percentage}%"
h3
className: 'beatmap-success-rate__header'
osu.trans 'beatmapsets.show.info.points-of-failure'
div
className: 'beatmap-success-rate__chart'
ref: 'chartArea'
else
div className: 'beatmap-success-rate',
div
className: 'beatmap-success-rate__empty'
osu.trans 'beatmapsets.show.info.no_scores'
| 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 { BBCodeEditor } from 'bbcode-editor'
import { Modal } from 'modal'
import * as React from 'react'
import { a, button, div, h3, span, i, textarea } from 'react-dom-factories'
import MetadataEditor from 'beatmapsets-show/metadata-editor'
el = React.createElement
export class Info extends React.Component
constructor: (props) ->
super props
@overlay = React.createRef()
@state =
isBusy: false
isEditingDescription: false
isEditingMetadata: false
componentDidMount: ->
@renderChart()
componentDidUpdate: ->
@renderChart()
componentWillUnmount: =>
$(window).off '.beatmapsetPageInfo'
# see Modal#hideModal
dismissEditor: (e) =>
@setState isEditingDescription: false if e.button == 0 &&
e.target == @overlay.current &&
@clickEndTarget == @clickStartTarget
editStart: =>
@setState isEditingDescription: true
handleClickEnd: (e) =>
@clickEndTarget = e.target
handleClickStart: (e) =>
@clickStartTarget = e.target
onEditorChange: (action) =>
switch action.type
when 'save'
if action.hasChanged
@saveDescription(action.value)
else
@setState isEditingDescription: false
when 'cancel'
@setState isEditingDescription: false
onSelectionUpdate: (selection) =>
@setState selection: selection
saveDescription: (value) =>
@setState isBusy: true
$.ajax laroute.route('beatmapsets.update', beatmapset: @props.beatmapset.id),
method: 'PATCH',
data:
description: value
.done (data) =>
@setState
isEditingDescription: false
description: data.description
.fail osu.ajaxError
.always =>
@setState isBusy: false
toggleEditingMetadata: =>
@setState isEditingMetadata: !@state.isEditingMetadata
withEdit: =>
@props.beatmapset.description.bbcode?
withEditMetadata: =>
@props.beatmapset.current_user_attributes?.can_edit_metadata ? false
renderChart: ->
return if !@props.beatmapset.is_scoreable || @props.beatmap.playcount < 1
unless @_failurePointsChart?
options =
scales:
x: d3.scaleLinear()
y: d3.scaleLinear()
modifiers: ['beatmap-success-rate']
@_failurePointsChart = new StackedBarChart @refs.chartArea, options
$(window).on 'throttled-resize.beatmapsetPageInfo', @_failurePointsChart.resize
@_failurePointsChart.loadData @props.beatmap.failtimes
renderEditMetadataButton: =>
div className: 'beatmapset-info__edit-button',
button
type: 'button'
className: 'btn-circle'
onClick: @toggleEditingMetadata
span className: 'btn-circle__content',
i className: 'fas fa-pencil-alt'
renderEditButton: =>
div className: 'beatmapset-info__edit-button',
button
type: 'button'
className: 'btn-circle'
onClick: @editStart
span className: 'btn-circle__content',
i className: 'fas fa-pencil-alt'
render: ->
tags = _(@props.beatmapset.tags)
.split(' ')
.filter((t) -> t? && t != '')
.slice(0, 21)
.value()
if tags.length == 21
tags.pop()
tagsOverload = true
div className: 'beatmapset-info',
if @state.isEditingDescription
div className: 'beatmapset-description-editor',
div
className: 'beatmapset-description-editor__overlay'
onClick: @dismissEditor
onMouseDown: @handleClickStart
onMouseUp: @handleClickEnd
ref: @overlay
div className: 'beatmapset-description-editor__container osu-page',
el BBCodeEditor,
modifiers: ['beatmapset-description-editor']
disabled: @state.isBusy
onChange: @onEditorChange
onSelectionUpdate: @onSelectionUpdate
rawValue: @state.description?.bbcode ? @props.beatmapset.description.bbcode
selection: @state.selection
if @state.isEditingMetadata
el Modal, visible: true, onClose: @toggleEditingMetadata,
el MetadataEditor, onClose: @toggleEditingMetadata, beatmapset: @props.beatmapset
div className: 'beatmapset-info__box beatmapset-info__box--description',
@renderEditButton() if @withEdit()
h3
className: 'beatmapset-info__header'
osu.trans 'beatmapsets.show.info.description'
div className: 'beatmapset-info__description-container u-fancy-scrollbar',
div
className: 'beatmapset-info__description'
dangerouslySetInnerHTML:
__html: @state.description?.description ? @props.beatmapset.description.description
div className: 'beatmapset-info__box beatmapset-info__box--meta',
@renderEditMetadataButton() if @withEditMetadata()
if @props.beatmapset.source
div null,
h3
className: 'beatmapset-info__header'
osu.trans 'beatmapsets.show.info.source'
a
href: laroute.route('beatmapsets.index', q: @props.beatmapset.source)
@props.beatmapset.source
div className: 'beatmapset-info__half-box',
div className: 'beatmapset-info__half-entry',
h3 className: 'beatmapset-info__header',
osu.trans 'beatmapsets.show.info.genre'
a
href: laroute.route('beatmapsets.index', g: @props.beatmapset.genre.id)
@props.beatmapset.genre.name
div className: 'beatmapset-info__half-entry',
h3 className: 'beatmapset-info__header',
osu.trans 'beatmapsets.show.info.language'
a
href: laroute.route('beatmapsets.index', l: @props.beatmapset.language.id)
@props.beatmapset.language.name
if tags.length > 0
div null,
h3
className: 'beatmapset-info__header'
osu.trans 'beatmapsets.show.info.tags'
div null,
for tag in tags
[
a
key: tag
href: laroute.route('beatmapsets.index', q: tag)
tag
span key: "#{tag}-space", ' '
]
'...' if tagsOverload
div className: 'beatmapset-info__box beatmapset-info__box--success-rate',
if !@props.beatmapset.is_scoreable
div className: 'beatmap-success-rate',
div
className: 'beatmap-success-rate__empty'
osu.trans 'beatmapsets.show.info.unranked'
else
if @props.beatmap.playcount > 0
percentage = _.round((@props.beatmap.passcount / @props.beatmap.playcount) * 100, 1)
div className: 'beatmap-success-rate',
h3
className: 'beatmap-success-rate__header'
osu.trans 'beatmapsets.show.info.success-rate'
div className: 'bar bar--beatmap-success-rate',
div
className: 'bar__fill'
style:
width: "#{percentage}%"
div
className: 'beatmap-success-rate__percentage'
title: "#{osu.formatNumber(@props.beatmap.passcount)} / #{osu.formatNumber(@props.beatmap.playcount)}"
'data-tooltip-position': 'bottom center'
style:
marginLeft: "#{percentage}%"
"#{percentage}%"
h3
className: 'beatmap-success-rate__header'
osu.trans 'beatmapsets.show.info.points-of-failure'
div
className: 'beatmap-success-rate__chart'
ref: 'chartArea'
else
div className: 'beatmap-success-rate',
div
className: 'beatmap-success-rate__empty'
osu.trans 'beatmapsets.show.info.no_scores'
|
[
{
"context": ">\n user = new UserModel\n user.password = user.genPassword password\n email = new EmailModel\n emailAddress",
"end": 2308,
"score": 0.9959909319877625,
"start": 2283,
"tag": "PASSWORD",
"value": "user.genPassword password"
},
{
"context": "user, n... | talk-account/server/apis/email.coffee | ikingye/talk-os | 3,084 | ###*
* 邮箱密码登录/注册接口
###
Err = require 'err1st'
limbo = require 'limbo'
config = require 'config'
Promise = require 'bluebird'
_ = require 'lodash'
app = require '../server'
util = require '../util'
redis = require '../components/redis'
mailer = require '../mailers'
{
UserModel
MobileModel
UserModel
EmailModel
} = limbo.use 'account'
module.exports = emailController = app.controller 'email', ->
@mixin require './mixins/auth'
@mixin require './mixins/cookie'
@ratelimit '20,60 80,300', only: 'bind change signup signin'
# Parse randomCode and verifyCode from verifyToken
@before 'parseVerifyToken', only: 'bind change signinByVerifyCode'
@ensure 'emailAddress', only: 'signup signin unbind'
@ensure 'password', only: 'signup signin'
@ensure 'randomCode verifyCode', only: 'bind change signinByVerifyCode'
@ensure 'newPassword', only: 'resetPassword'
@ensure 'bindCode', only: 'forcebind'
@before 'delay1s', only: 'bind change signup signin' unless config.debug
# Verify account and set the user model
@before 'verifyAccount', only: 'bind change forcebind unbind resetPassword'
@after 'emailToUser', only: 'bind change forcebind signinByVerifyCode'
@after 'setAccountToken', only: 'bind change forcebind signup signin signinByVerifyCode resetPassword'
@after 'setCookie', only: 'bind change forcebind signup signin signinByVerifyCode'
@action 'signin', (req, res, callback) ->
{emailAddress, password} = req.get()
$email = EmailModel.findOne emailAddress: emailAddress
.populate 'user'
.execAsync()
.then (email) ->
throw new Err('LOGIN_VERIFY_FAILED') unless email?.user
throw new Err('NO_PASSWORD') unless email?.user?.password
email
$user = $email.then (email) -> email.user.verifyPasswordAsync password
Promise.all [$user, $email]
.spread (user, email) ->
user.emailAddress = email.emailAddress
user
.nodeify callback
@action 'signup', (req, res, callback) ->
{emailAddress, password} = req.get()
# 检查账号是否存在
$emailExists = EmailModel.findOneAsync emailAddress: emailAddress
.then (email) -> throw new Err('ACCOUNT_EXISTS') if email
# 创建新账号
$user = $emailExists.then ->
user = new UserModel
user.password = user.genPassword password
email = new EmailModel
emailAddress: emailAddress
user: user
Promise.all [user.$save(), email.$save()]
.spread (user, email) ->
user.emailAddress = email.emailAddress
user
$user.nodeify callback
@action 'sendVerifyCode', (req, res, callback) ->
{emailAddress, action} = req.get()
sentVerifyKey = "sentverify:#{emailAddress}"
switch action
when 'resetpassword'
# 需要先判断邮箱存在才能够继续下面的找回密码操作
$check = EmailModel.findOneAsync emailAddress: emailAddress
.then (email) -> throw new Err('ACCOUNT_NOT_EXIST') unless email
when 'bind', 'change'
# Do not check existing email when bind/change email
$check = Promise.resolve()
else
$check = Promise.reject(new Err('INVALID_ACTION'))
# 检查是否频繁发送
$verifyData = $check.then -> redis.getAsync sentVerifyKey
# 保存验证码和邮箱信息到 redis
.then (sent) ->
throw new Err('RESEND_TOO_OFTEN') if sent and not process.env.DEBUG
options = emailAddress: emailAddress
$verifyData = EmailModel.saveVerifyCodeAsync options
# 根据不同的 action 发送特定邮件模板
$sendEmail = $verifyData.then (verifyData) ->
switch action
when 'resetpassword'
resetMailer = mailer.getMailer 'reset-password'
$sent = resetMailer.send verifyData, emailAddress
when 'bind', 'change'
verifyMailer = mailer.getMailer 'verify'
verifyData.action = action
$sent = verifyMailer.send verifyData, emailAddress
else
$sent = Promise.reject(new Err('INVALID_ACTION'))
$sent
# 设置已发送标识
$setSentFlag = $sendEmail.then -> redis.setexAsync sentVerifyKey, 60, 1
# 返回响应结果到客户端
Promise.all [$verifyData, $sendEmail, $setSentFlag]
.spread (verifyData) ->
if config.debug
data = _.pick(verifyData, 'randomCode', 'verifyCode')
else
data = _.pick(verifyData, 'randomCode')
.nodeify callback
# 验证邮箱验证码同时登录
@action 'signinByVerifyCode', (req, res, callback) ->
{verifyCode, randomCode} = req.get()
$emailAddress = EmailModel.verifyAsync randomCode, verifyCode
.then (verifyData) -> verifyData.emailAddress
$email = $emailAddress.then (emailAddress) ->
# 根据邮箱查找老用户
EmailModel.findOne emailAddress: emailAddress
.populate 'user'
.execAsync()
.then (email) ->
return email if email.user
throw new Err('ACCOUNT_NOT_EXIST')
.nodeify callback
@action 'resetPassword', (req, res, callback) ->
{user, newPassword} = req.get()
user.password = user.genPassword newPassword
$user = user.$save()
$user.nodeify callback
@action 'bind', (req, res, callback) ->
{user, randomCode, verifyCode} = req.get()
$emailAddress = EmailModel.verifyAsync randomCode, verifyCode
.then (verifyData) -> verifyData.emailAddress
$email = $emailAddress.then (emailAddress) ->
EmailModel.findOne emailAddress: emailAddress
.populate 'user'
.execAsync()
.then (email) ->
if email?.user
return $bindCode = email.genBindCodeAsync().then (bindCode) ->
err = new Err('BIND_CONFLICT')
err.data =
bindCode: bindCode
showname: emailAddress
throw err
else if email
email.user = user
else
email = new EmailModel
emailAddress: emailAddress
user: user
email.updatedAt = new Date
email
$cleanupOtherEmails = $email.then (email) ->
EmailModel.removeAsync
user: user._id
emailAddress: $ne: email.emailAddress
$email = Promise.all [$email, $cleanupOtherEmails]
.spread (email) -> email.$save()
$email.nodeify callback
@action 'forcebind', (req, res, callback) ->
{user, bindCode} = req.get()
$email = EmailModel.verifyBindCodeAsync bindCode
$email = $email.then (email) ->
email.user = user
email.updatedAt = new Date
email.$save()
$cleanupOtherEmails = $email.then (email) ->
EmailModel.removeAsync
user: user._id
emailAddress: $ne: email.emailAddress
Promise.all [$email, $cleanupOtherEmails]
.spread (email) -> email
.nodeify callback
@action 'change', (req, res, callback) ->
@bind req, res, callback
@action 'unbind', (req, res, callback) ->
{user, emailAddress} = req.get()
$email = EmailModel.findOneAsync
user: user._id
emailAddress: emailAddress
.then (email) ->
if email?.user
email.$remove()
$email.then -> user
.nodeify callback
@action 'preview', (req, res, callback) ->
{template} = req.query
return res.end('Empty template name') unless template
html = mailer.getMailer(template).preview (err, html) ->
if err
return res.status(400).end err.stack
res.status(200).send html
################################# HOOKS #################################
@action 'setAccountToken', (req, res, user, callback) ->
user.accountToken = user.genAccountToken login: 'email'
callback null, user
@action 'emailToUser', (req, res, email, callback) ->
{user} = email
return callback(new Err('LOGIN_FAILED', '未成功绑定用户账号')) unless user
user.emailAddress = email.emailAddress
callback null, user
# Set randomCode and verifyCode from verifyToken
@action 'parseVerifyToken', (req, res, callback) ->
{verifyToken} = req.get()
return callback() unless verifyToken?.length
util.parseVerifyToken verifyToken, (err, verifyData = {}) ->
req.set 'randomCode', verifyData.randomCode
req.set 'verifyCode', verifyData.verifyCode
callback err
| 17653 | ###*
* 邮箱密码登录/注册接口
###
Err = require 'err1st'
limbo = require 'limbo'
config = require 'config'
Promise = require 'bluebird'
_ = require 'lodash'
app = require '../server'
util = require '../util'
redis = require '../components/redis'
mailer = require '../mailers'
{
UserModel
MobileModel
UserModel
EmailModel
} = limbo.use 'account'
module.exports = emailController = app.controller 'email', ->
@mixin require './mixins/auth'
@mixin require './mixins/cookie'
@ratelimit '20,60 80,300', only: 'bind change signup signin'
# Parse randomCode and verifyCode from verifyToken
@before 'parseVerifyToken', only: 'bind change signinByVerifyCode'
@ensure 'emailAddress', only: 'signup signin unbind'
@ensure 'password', only: 'signup signin'
@ensure 'randomCode verifyCode', only: 'bind change signinByVerifyCode'
@ensure 'newPassword', only: 'resetPassword'
@ensure 'bindCode', only: 'forcebind'
@before 'delay1s', only: 'bind change signup signin' unless config.debug
# Verify account and set the user model
@before 'verifyAccount', only: 'bind change forcebind unbind resetPassword'
@after 'emailToUser', only: 'bind change forcebind signinByVerifyCode'
@after 'setAccountToken', only: 'bind change forcebind signup signin signinByVerifyCode resetPassword'
@after 'setCookie', only: 'bind change forcebind signup signin signinByVerifyCode'
@action 'signin', (req, res, callback) ->
{emailAddress, password} = req.get()
$email = EmailModel.findOne emailAddress: emailAddress
.populate 'user'
.execAsync()
.then (email) ->
throw new Err('LOGIN_VERIFY_FAILED') unless email?.user
throw new Err('NO_PASSWORD') unless email?.user?.password
email
$user = $email.then (email) -> email.user.verifyPasswordAsync password
Promise.all [$user, $email]
.spread (user, email) ->
user.emailAddress = email.emailAddress
user
.nodeify callback
@action 'signup', (req, res, callback) ->
{emailAddress, password} = req.get()
# 检查账号是否存在
$emailExists = EmailModel.findOneAsync emailAddress: emailAddress
.then (email) -> throw new Err('ACCOUNT_EXISTS') if email
# 创建新账号
$user = $emailExists.then ->
user = new UserModel
user.password = <PASSWORD>
email = new EmailModel
emailAddress: emailAddress
user: user
Promise.all [user.$save(), email.$save()]
.spread (user, email) ->
user.emailAddress = email.emailAddress
user
$user.nodeify callback
@action 'sendVerifyCode', (req, res, callback) ->
{emailAddress, action} = req.get()
sentVerifyKey = "sentverify:#{emailAddress}"
switch action
when 'resetpassword'
# 需要先判断邮箱存在才能够继续下面的找回密码操作
$check = EmailModel.findOneAsync emailAddress: emailAddress
.then (email) -> throw new Err('ACCOUNT_NOT_EXIST') unless email
when 'bind', 'change'
# Do not check existing email when bind/change email
$check = Promise.resolve()
else
$check = Promise.reject(new Err('INVALID_ACTION'))
# 检查是否频繁发送
$verifyData = $check.then -> redis.getAsync sentVerifyKey
# 保存验证码和邮箱信息到 redis
.then (sent) ->
throw new Err('RESEND_TOO_OFTEN') if sent and not process.env.DEBUG
options = emailAddress: emailAddress
$verifyData = EmailModel.saveVerifyCodeAsync options
# 根据不同的 action 发送特定邮件模板
$sendEmail = $verifyData.then (verifyData) ->
switch action
when 'resetpassword'
resetMailer = mailer.getMailer 'reset-password'
$sent = resetMailer.send verifyData, emailAddress
when 'bind', 'change'
verifyMailer = mailer.getMailer 'verify'
verifyData.action = action
$sent = verifyMailer.send verifyData, emailAddress
else
$sent = Promise.reject(new Err('INVALID_ACTION'))
$sent
# 设置已发送标识
$setSentFlag = $sendEmail.then -> redis.setexAsync sentVerifyKey, 60, 1
# 返回响应结果到客户端
Promise.all [$verifyData, $sendEmail, $setSentFlag]
.spread (verifyData) ->
if config.debug
data = _.pick(verifyData, 'randomCode', 'verifyCode')
else
data = _.pick(verifyData, 'randomCode')
.nodeify callback
# 验证邮箱验证码同时登录
@action 'signinByVerifyCode', (req, res, callback) ->
{verifyCode, randomCode} = req.get()
$emailAddress = EmailModel.verifyAsync randomCode, verifyCode
.then (verifyData) -> verifyData.emailAddress
$email = $emailAddress.then (emailAddress) ->
# 根据邮箱查找老用户
EmailModel.findOne emailAddress: emailAddress
.populate 'user'
.execAsync()
.then (email) ->
return email if email.user
throw new Err('ACCOUNT_NOT_EXIST')
.nodeify callback
@action 'resetPassword', (req, res, callback) ->
{user, newPassword} = req.get()
user.password = <PASSWORD> <PASSWORD>
$user = user.$save()
$user.nodeify callback
@action 'bind', (req, res, callback) ->
{user, randomCode, verifyCode} = req.get()
$emailAddress = EmailModel.verifyAsync randomCode, verifyCode
.then (verifyData) -> verifyData.emailAddress
$email = $emailAddress.then (emailAddress) ->
EmailModel.findOne emailAddress: emailAddress
.populate 'user'
.execAsync()
.then (email) ->
if email?.user
return $bindCode = email.genBindCodeAsync().then (bindCode) ->
err = new Err('BIND_CONFLICT')
err.data =
bindCode: bindCode
showname: emailAddress
throw err
else if email
email.user = user
else
email = new EmailModel
emailAddress: emailAddress
user: user
email.updatedAt = new Date
email
$cleanupOtherEmails = $email.then (email) ->
EmailModel.removeAsync
user: user._id
emailAddress: $ne: email.emailAddress
$email = Promise.all [$email, $cleanupOtherEmails]
.spread (email) -> email.$save()
$email.nodeify callback
@action 'forcebind', (req, res, callback) ->
{user, bindCode} = req.get()
$email = EmailModel.verifyBindCodeAsync bindCode
$email = $email.then (email) ->
email.user = user
email.updatedAt = new Date
email.$save()
$cleanupOtherEmails = $email.then (email) ->
EmailModel.removeAsync
user: user._id
emailAddress: $ne: email.emailAddress
Promise.all [$email, $cleanupOtherEmails]
.spread (email) -> email
.nodeify callback
@action 'change', (req, res, callback) ->
@bind req, res, callback
@action 'unbind', (req, res, callback) ->
{user, emailAddress} = req.get()
$email = EmailModel.findOneAsync
user: user._id
emailAddress: emailAddress
.then (email) ->
if email?.user
email.$remove()
$email.then -> user
.nodeify callback
@action 'preview', (req, res, callback) ->
{template} = req.query
return res.end('Empty template name') unless template
html = mailer.getMailer(template).preview (err, html) ->
if err
return res.status(400).end err.stack
res.status(200).send html
################################# HOOKS #################################
@action 'setAccountToken', (req, res, user, callback) ->
user.accountToken = user.genAccountToken login: 'email'
callback null, user
@action 'emailToUser', (req, res, email, callback) ->
{user} = email
return callback(new Err('LOGIN_FAILED', '未成功绑定用户账号')) unless user
user.emailAddress = email.emailAddress
callback null, user
# Set randomCode and verifyCode from verifyToken
@action 'parseVerifyToken', (req, res, callback) ->
{verifyToken} = req.get()
return callback() unless verifyToken?.length
util.parseVerifyToken verifyToken, (err, verifyData = {}) ->
req.set 'randomCode', verifyData.randomCode
req.set 'verifyCode', verifyData.verifyCode
callback err
| true | ###*
* 邮箱密码登录/注册接口
###
Err = require 'err1st'
limbo = require 'limbo'
config = require 'config'
Promise = require 'bluebird'
_ = require 'lodash'
app = require '../server'
util = require '../util'
redis = require '../components/redis'
mailer = require '../mailers'
{
UserModel
MobileModel
UserModel
EmailModel
} = limbo.use 'account'
module.exports = emailController = app.controller 'email', ->
@mixin require './mixins/auth'
@mixin require './mixins/cookie'
@ratelimit '20,60 80,300', only: 'bind change signup signin'
# Parse randomCode and verifyCode from verifyToken
@before 'parseVerifyToken', only: 'bind change signinByVerifyCode'
@ensure 'emailAddress', only: 'signup signin unbind'
@ensure 'password', only: 'signup signin'
@ensure 'randomCode verifyCode', only: 'bind change signinByVerifyCode'
@ensure 'newPassword', only: 'resetPassword'
@ensure 'bindCode', only: 'forcebind'
@before 'delay1s', only: 'bind change signup signin' unless config.debug
# Verify account and set the user model
@before 'verifyAccount', only: 'bind change forcebind unbind resetPassword'
@after 'emailToUser', only: 'bind change forcebind signinByVerifyCode'
@after 'setAccountToken', only: 'bind change forcebind signup signin signinByVerifyCode resetPassword'
@after 'setCookie', only: 'bind change forcebind signup signin signinByVerifyCode'
@action 'signin', (req, res, callback) ->
{emailAddress, password} = req.get()
$email = EmailModel.findOne emailAddress: emailAddress
.populate 'user'
.execAsync()
.then (email) ->
throw new Err('LOGIN_VERIFY_FAILED') unless email?.user
throw new Err('NO_PASSWORD') unless email?.user?.password
email
$user = $email.then (email) -> email.user.verifyPasswordAsync password
Promise.all [$user, $email]
.spread (user, email) ->
user.emailAddress = email.emailAddress
user
.nodeify callback
@action 'signup', (req, res, callback) ->
{emailAddress, password} = req.get()
# 检查账号是否存在
$emailExists = EmailModel.findOneAsync emailAddress: emailAddress
.then (email) -> throw new Err('ACCOUNT_EXISTS') if email
# 创建新账号
$user = $emailExists.then ->
user = new UserModel
user.password = PI:PASSWORD:<PASSWORD>END_PI
email = new EmailModel
emailAddress: emailAddress
user: user
Promise.all [user.$save(), email.$save()]
.spread (user, email) ->
user.emailAddress = email.emailAddress
user
$user.nodeify callback
@action 'sendVerifyCode', (req, res, callback) ->
{emailAddress, action} = req.get()
sentVerifyKey = "sentverify:#{emailAddress}"
switch action
when 'resetpassword'
# 需要先判断邮箱存在才能够继续下面的找回密码操作
$check = EmailModel.findOneAsync emailAddress: emailAddress
.then (email) -> throw new Err('ACCOUNT_NOT_EXIST') unless email
when 'bind', 'change'
# Do not check existing email when bind/change email
$check = Promise.resolve()
else
$check = Promise.reject(new Err('INVALID_ACTION'))
# 检查是否频繁发送
$verifyData = $check.then -> redis.getAsync sentVerifyKey
# 保存验证码和邮箱信息到 redis
.then (sent) ->
throw new Err('RESEND_TOO_OFTEN') if sent and not process.env.DEBUG
options = emailAddress: emailAddress
$verifyData = EmailModel.saveVerifyCodeAsync options
# 根据不同的 action 发送特定邮件模板
$sendEmail = $verifyData.then (verifyData) ->
switch action
when 'resetpassword'
resetMailer = mailer.getMailer 'reset-password'
$sent = resetMailer.send verifyData, emailAddress
when 'bind', 'change'
verifyMailer = mailer.getMailer 'verify'
verifyData.action = action
$sent = verifyMailer.send verifyData, emailAddress
else
$sent = Promise.reject(new Err('INVALID_ACTION'))
$sent
# 设置已发送标识
$setSentFlag = $sendEmail.then -> redis.setexAsync sentVerifyKey, 60, 1
# 返回响应结果到客户端
Promise.all [$verifyData, $sendEmail, $setSentFlag]
.spread (verifyData) ->
if config.debug
data = _.pick(verifyData, 'randomCode', 'verifyCode')
else
data = _.pick(verifyData, 'randomCode')
.nodeify callback
# 验证邮箱验证码同时登录
@action 'signinByVerifyCode', (req, res, callback) ->
{verifyCode, randomCode} = req.get()
$emailAddress = EmailModel.verifyAsync randomCode, verifyCode
.then (verifyData) -> verifyData.emailAddress
$email = $emailAddress.then (emailAddress) ->
# 根据邮箱查找老用户
EmailModel.findOne emailAddress: emailAddress
.populate 'user'
.execAsync()
.then (email) ->
return email if email.user
throw new Err('ACCOUNT_NOT_EXIST')
.nodeify callback
@action 'resetPassword', (req, res, callback) ->
{user, newPassword} = req.get()
user.password = PI:PASSWORD:<PASSWORD>END_PI PI:PASSWORD:<PASSWORD>END_PI
$user = user.$save()
$user.nodeify callback
@action 'bind', (req, res, callback) ->
{user, randomCode, verifyCode} = req.get()
$emailAddress = EmailModel.verifyAsync randomCode, verifyCode
.then (verifyData) -> verifyData.emailAddress
$email = $emailAddress.then (emailAddress) ->
EmailModel.findOne emailAddress: emailAddress
.populate 'user'
.execAsync()
.then (email) ->
if email?.user
return $bindCode = email.genBindCodeAsync().then (bindCode) ->
err = new Err('BIND_CONFLICT')
err.data =
bindCode: bindCode
showname: emailAddress
throw err
else if email
email.user = user
else
email = new EmailModel
emailAddress: emailAddress
user: user
email.updatedAt = new Date
email
$cleanupOtherEmails = $email.then (email) ->
EmailModel.removeAsync
user: user._id
emailAddress: $ne: email.emailAddress
$email = Promise.all [$email, $cleanupOtherEmails]
.spread (email) -> email.$save()
$email.nodeify callback
@action 'forcebind', (req, res, callback) ->
{user, bindCode} = req.get()
$email = EmailModel.verifyBindCodeAsync bindCode
$email = $email.then (email) ->
email.user = user
email.updatedAt = new Date
email.$save()
$cleanupOtherEmails = $email.then (email) ->
EmailModel.removeAsync
user: user._id
emailAddress: $ne: email.emailAddress
Promise.all [$email, $cleanupOtherEmails]
.spread (email) -> email
.nodeify callback
@action 'change', (req, res, callback) ->
@bind req, res, callback
@action 'unbind', (req, res, callback) ->
{user, emailAddress} = req.get()
$email = EmailModel.findOneAsync
user: user._id
emailAddress: emailAddress
.then (email) ->
if email?.user
email.$remove()
$email.then -> user
.nodeify callback
@action 'preview', (req, res, callback) ->
{template} = req.query
return res.end('Empty template name') unless template
html = mailer.getMailer(template).preview (err, html) ->
if err
return res.status(400).end err.stack
res.status(200).send html
################################# HOOKS #################################
@action 'setAccountToken', (req, res, user, callback) ->
user.accountToken = user.genAccountToken login: 'email'
callback null, user
@action 'emailToUser', (req, res, email, callback) ->
{user} = email
return callback(new Err('LOGIN_FAILED', '未成功绑定用户账号')) unless user
user.emailAddress = email.emailAddress
callback null, user
# Set randomCode and verifyCode from verifyToken
@action 'parseVerifyToken', (req, res, callback) ->
{verifyToken} = req.get()
return callback() unless verifyToken?.length
util.parseVerifyToken verifyToken, (err, verifyData = {}) ->
req.set 'randomCode', verifyData.randomCode
req.set 'verifyCode', verifyData.verifyCode
callback err
|
[
{
"context": " : アクセストークン\n\t# @param access_token_secret : アクセストークンシークレット\n\t##\n\tgetAccessToken: (err, access_token, access_t",
"end": 2627,
"score": 0.920756459236145,
"start": 2613,
"tag": "KEY",
"value": "アクセストークンシークレット"
}
] | src/bin/window.coffee | yuki540net/nicoreen | 41 | class Window
constructor: ->
@Browser = require('electron').BrowserWindow
@config = require '../config/window.json'
@views =
login : null
controller : null
screen : null
@api = null
@fn = null
@req_token = null
@req_token_secret = null
##
# ウィンドウを閉じる
# @param name : window名
##
close: (name) ->
@views[name].close()
@views[name] = null
if name is 'controller'
@views['screen'].close()
@views['screen'] = null
##
# ウィンドウを最小化
# @param name : window名
##
mini: (name) ->
@views[name].minimize()
##
# ipc通信
# @param name : window名
# @param event : イベント名
# @param data : データ
##
send: (name, event, data) ->
@views[name].webContents.send event, data
##
# コントーラ画面
# @param url : URL
##
showController: (url) ->
@views.controller = new @Browser @config.controller
@views.controller.loadURL url
##
# スクリーン
# @param url : URL
##
showScreen: (url) ->
screen = require('electron').screen
display = screen.getPrimaryDisplay().workArea
option = @config.screen
option.width = display.width
option.height = display.height
@views.screen = new @Browser option
@views.screen.loadURL url
@views.screen.setIgnoreMouseEvents true
##
# ログイン画面
# @param ufn : コールバック関数
##
showLogin: (fn) ->
TwitterAPI = require 'node-twitter-api'
credentials = require '../config/credentials.json'
@fn = fn
@api = new TwitterAPI
consumerKey : credentials.consumer_key
consumerSecret : credentials.consumer_secret
callback : 'http://yuki540.com'
# request tokenの取得
@api.getRequestToken @getRequestToken.bind this
##
# リクエストトークンの取得
# @param err : エラー
# @param req_token : リクエストトークン
# @param req_token_secret
##
getRequestToken: (err, req_token, req_token_secret) ->
@req_token = req_token
@req_token_secret = req_token_secret
url = @api.getAuthUrl req_token
@views.login = new @Browser @config.login
@views.login.loadURL url + '&force_login=true'
# will navigate
@views.login.webContents.on 'will-navigate', @willNavigate.bind this
##
# リダイレクト
# @param event : イベント
# @param url : URL
##
willNavigate: (event, url) ->
event.preventDefault()
match = url.match(/\?oauth_token=([^&]*)&oauth_verifier=([^&]*)/)
if not match
@views.login.reload()
return false
# アクセストークンの取得
@api.getAccessToken(
@req_token,
@req_token_secret,
match[2],
@getAccessToken.bind this
)
##
# アクセストークンの取得
# @param err : エラー
# @param access_token : アクセストークン
# @param access_token_secret : アクセストークンシークレット
##
getAccessToken: (err, access_token, access_token_secret) ->
if err
@views.login.reload()
return false
# アカウントの書き込み
Accounts = require './accounts'
Accounts.write access_token, access_token_secret, =>
@fn()
module.exports = new Window() | 119611 | class Window
constructor: ->
@Browser = require('electron').BrowserWindow
@config = require '../config/window.json'
@views =
login : null
controller : null
screen : null
@api = null
@fn = null
@req_token = null
@req_token_secret = null
##
# ウィンドウを閉じる
# @param name : window名
##
close: (name) ->
@views[name].close()
@views[name] = null
if name is 'controller'
@views['screen'].close()
@views['screen'] = null
##
# ウィンドウを最小化
# @param name : window名
##
mini: (name) ->
@views[name].minimize()
##
# ipc通信
# @param name : window名
# @param event : イベント名
# @param data : データ
##
send: (name, event, data) ->
@views[name].webContents.send event, data
##
# コントーラ画面
# @param url : URL
##
showController: (url) ->
@views.controller = new @Browser @config.controller
@views.controller.loadURL url
##
# スクリーン
# @param url : URL
##
showScreen: (url) ->
screen = require('electron').screen
display = screen.getPrimaryDisplay().workArea
option = @config.screen
option.width = display.width
option.height = display.height
@views.screen = new @Browser option
@views.screen.loadURL url
@views.screen.setIgnoreMouseEvents true
##
# ログイン画面
# @param ufn : コールバック関数
##
showLogin: (fn) ->
TwitterAPI = require 'node-twitter-api'
credentials = require '../config/credentials.json'
@fn = fn
@api = new TwitterAPI
consumerKey : credentials.consumer_key
consumerSecret : credentials.consumer_secret
callback : 'http://yuki540.com'
# request tokenの取得
@api.getRequestToken @getRequestToken.bind this
##
# リクエストトークンの取得
# @param err : エラー
# @param req_token : リクエストトークン
# @param req_token_secret
##
getRequestToken: (err, req_token, req_token_secret) ->
@req_token = req_token
@req_token_secret = req_token_secret
url = @api.getAuthUrl req_token
@views.login = new @Browser @config.login
@views.login.loadURL url + '&force_login=true'
# will navigate
@views.login.webContents.on 'will-navigate', @willNavigate.bind this
##
# リダイレクト
# @param event : イベント
# @param url : URL
##
willNavigate: (event, url) ->
event.preventDefault()
match = url.match(/\?oauth_token=([^&]*)&oauth_verifier=([^&]*)/)
if not match
@views.login.reload()
return false
# アクセストークンの取得
@api.getAccessToken(
@req_token,
@req_token_secret,
match[2],
@getAccessToken.bind this
)
##
# アクセストークンの取得
# @param err : エラー
# @param access_token : アクセストークン
# @param access_token_secret : <KEY>
##
getAccessToken: (err, access_token, access_token_secret) ->
if err
@views.login.reload()
return false
# アカウントの書き込み
Accounts = require './accounts'
Accounts.write access_token, access_token_secret, =>
@fn()
module.exports = new Window() | true | class Window
constructor: ->
@Browser = require('electron').BrowserWindow
@config = require '../config/window.json'
@views =
login : null
controller : null
screen : null
@api = null
@fn = null
@req_token = null
@req_token_secret = null
##
# ウィンドウを閉じる
# @param name : window名
##
close: (name) ->
@views[name].close()
@views[name] = null
if name is 'controller'
@views['screen'].close()
@views['screen'] = null
##
# ウィンドウを最小化
# @param name : window名
##
mini: (name) ->
@views[name].minimize()
##
# ipc通信
# @param name : window名
# @param event : イベント名
# @param data : データ
##
send: (name, event, data) ->
@views[name].webContents.send event, data
##
# コントーラ画面
# @param url : URL
##
showController: (url) ->
@views.controller = new @Browser @config.controller
@views.controller.loadURL url
##
# スクリーン
# @param url : URL
##
showScreen: (url) ->
screen = require('electron').screen
display = screen.getPrimaryDisplay().workArea
option = @config.screen
option.width = display.width
option.height = display.height
@views.screen = new @Browser option
@views.screen.loadURL url
@views.screen.setIgnoreMouseEvents true
##
# ログイン画面
# @param ufn : コールバック関数
##
showLogin: (fn) ->
TwitterAPI = require 'node-twitter-api'
credentials = require '../config/credentials.json'
@fn = fn
@api = new TwitterAPI
consumerKey : credentials.consumer_key
consumerSecret : credentials.consumer_secret
callback : 'http://yuki540.com'
# request tokenの取得
@api.getRequestToken @getRequestToken.bind this
##
# リクエストトークンの取得
# @param err : エラー
# @param req_token : リクエストトークン
# @param req_token_secret
##
getRequestToken: (err, req_token, req_token_secret) ->
@req_token = req_token
@req_token_secret = req_token_secret
url = @api.getAuthUrl req_token
@views.login = new @Browser @config.login
@views.login.loadURL url + '&force_login=true'
# will navigate
@views.login.webContents.on 'will-navigate', @willNavigate.bind this
##
# リダイレクト
# @param event : イベント
# @param url : URL
##
willNavigate: (event, url) ->
event.preventDefault()
match = url.match(/\?oauth_token=([^&]*)&oauth_verifier=([^&]*)/)
if not match
@views.login.reload()
return false
# アクセストークンの取得
@api.getAccessToken(
@req_token,
@req_token_secret,
match[2],
@getAccessToken.bind this
)
##
# アクセストークンの取得
# @param err : エラー
# @param access_token : アクセストークン
# @param access_token_secret : PI:KEY:<KEY>END_PI
##
getAccessToken: (err, access_token, access_token_secret) ->
if err
@views.login.reload()
return false
# アカウントの書き込み
Accounts = require './accounts'
Accounts.write access_token, access_token_secret, =>
@fn()
module.exports = new Window() |
[
{
"context": "e\n \n return _phone\n\n # 随机生成邮箱码\n # @example zcn@gg.cc\n # @return {string}\n email: () ->\n _name = c",
"end": 743,
"score": 0.9998188018798828,
"start": 734,
"tag": "EMAIL",
"value": "zcn@gg.cc"
}
] | lib/string.coffee | boiawang/cheat.js | 0 | cheat = require('..')
string = {
# 随机生成名字
# @param {string} link 连接名字
# @return {string}
name: (link = ' ') ->
_firstNum = cheat.number.range(4, 7)
_lastNum = cheat.number.range(4, 10)
return "#{cheat.utils.capitalize(cheat.random.string(_firstNum))}#{link}#{cheat.utils.capitalize(cheat.random.string(_lastNum))}"
# 随机生成手机号
# @example 13657576541
# @param {boolean} isPrefix 是否带前缀
# @return {string}
# @todo 支持国外手机号
phone: (isPrefix = false) ->
secondNum = [3, 5, 7, 8][cheat.number.range(0, 3)]
lastNums = cheat.array.randomIntegers(9, 0, 9).join('')
_phone = "1#{secondNum}#{lastNums}"
if isPrefix
_phone = '86-' + _phone
return _phone
# 随机生成邮箱码
# @example zcn@gg.cc
# @return {string}
email: () ->
_name = cheat.number.range(5, 8)
_host = cheat.number.range(4, 7)
_c = cheat.number.range(2, 4)
return "#{cheat.utils.capitalize(cheat.random.string(_name))}@#{cheat.random.string(_host)}.#{cheat.random.string(_c)}"
# 随机生成guid
# @return {string} 例: 5dbdc8b5-c2b3-54a6-bc8f-6e95e7968d49
# @see http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
guid: () ->
_temp = 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'
return _temp.replace(/[xy]/g, (c) ->
r = Math.random() * 16 | 0
v= if c is 'x' then r else (r & 0x3 | 0x8)
return v.toString(16)
)
}
module.exports = string
| 139539 | cheat = require('..')
string = {
# 随机生成名字
# @param {string} link 连接名字
# @return {string}
name: (link = ' ') ->
_firstNum = cheat.number.range(4, 7)
_lastNum = cheat.number.range(4, 10)
return "#{cheat.utils.capitalize(cheat.random.string(_firstNum))}#{link}#{cheat.utils.capitalize(cheat.random.string(_lastNum))}"
# 随机生成手机号
# @example 13657576541
# @param {boolean} isPrefix 是否带前缀
# @return {string}
# @todo 支持国外手机号
phone: (isPrefix = false) ->
secondNum = [3, 5, 7, 8][cheat.number.range(0, 3)]
lastNums = cheat.array.randomIntegers(9, 0, 9).join('')
_phone = "1#{secondNum}#{lastNums}"
if isPrefix
_phone = '86-' + _phone
return _phone
# 随机生成邮箱码
# @example <EMAIL>
# @return {string}
email: () ->
_name = cheat.number.range(5, 8)
_host = cheat.number.range(4, 7)
_c = cheat.number.range(2, 4)
return "#{cheat.utils.capitalize(cheat.random.string(_name))}@#{cheat.random.string(_host)}.#{cheat.random.string(_c)}"
# 随机生成guid
# @return {string} 例: 5dbdc8b5-c2b3-54a6-bc8f-6e95e7968d49
# @see http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
guid: () ->
_temp = 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'
return _temp.replace(/[xy]/g, (c) ->
r = Math.random() * 16 | 0
v= if c is 'x' then r else (r & 0x3 | 0x8)
return v.toString(16)
)
}
module.exports = string
| true | cheat = require('..')
string = {
# 随机生成名字
# @param {string} link 连接名字
# @return {string}
name: (link = ' ') ->
_firstNum = cheat.number.range(4, 7)
_lastNum = cheat.number.range(4, 10)
return "#{cheat.utils.capitalize(cheat.random.string(_firstNum))}#{link}#{cheat.utils.capitalize(cheat.random.string(_lastNum))}"
# 随机生成手机号
# @example 13657576541
# @param {boolean} isPrefix 是否带前缀
# @return {string}
# @todo 支持国外手机号
phone: (isPrefix = false) ->
secondNum = [3, 5, 7, 8][cheat.number.range(0, 3)]
lastNums = cheat.array.randomIntegers(9, 0, 9).join('')
_phone = "1#{secondNum}#{lastNums}"
if isPrefix
_phone = '86-' + _phone
return _phone
# 随机生成邮箱码
# @example PI:EMAIL:<EMAIL>END_PI
# @return {string}
email: () ->
_name = cheat.number.range(5, 8)
_host = cheat.number.range(4, 7)
_c = cheat.number.range(2, 4)
return "#{cheat.utils.capitalize(cheat.random.string(_name))}@#{cheat.random.string(_host)}.#{cheat.random.string(_c)}"
# 随机生成guid
# @return {string} 例: 5dbdc8b5-c2b3-54a6-bc8f-6e95e7968d49
# @see http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
guid: () ->
_temp = 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'
return _temp.replace(/[xy]/g, (c) ->
r = Math.random() * 16 | 0
v= if c is 'x' then r else (r & 0x3 | 0x8)
return v.toString(16)
)
}
module.exports = string
|
[
{
"context": "gs'\n 'Japan'\n 'Manga'\n 'Anime'\n 'Nintendo'\n 'Mario Bros.'\n 'Commodore 64'\n 'Nostalgia'\n 'Movies'\n 'Olds",
"end": 529,
"score": 0.9675744771957397,
"start": 519,
"tag": "NAME",
"value": "Mario Bros"
}
] | js/sets.coffee | HitoriSensei/home | 0 | professional = [
'Functions'
'Interfaces'
'Algorithms'
'IntelliJ IDEA'
'F#'
'Quality'
'Declarative\nprogramming'
'HTML5'
'Javascript'
'Coffeescript'
'Engineering'
'Immutability'
'Scala'
'Predictability'
'New ideas'
'Optimization'
'Node.js'
'Fixing things'
'Science'
'Protocols'
'Linux'
'Challenges'
'Progress'
]
personal = [
'Games'
'RPGs'
'ZEN'
'Discovery'
'Electronic music'
'Melodic dubstep'
'Ramen'
'Dogs'
'Japan'
'Manga'
'Anime'
'Nintendo'
'Mario Bros.'
'Commodore 64'
'Nostalgia'
'Movies'
'Oldschool'
'Chillout'
'My Girlfriend'
]
module.exports = [
{set: professional, wage: 5}
{set: personal, wage: 2}
] | 24353 | professional = [
'Functions'
'Interfaces'
'Algorithms'
'IntelliJ IDEA'
'F#'
'Quality'
'Declarative\nprogramming'
'HTML5'
'Javascript'
'Coffeescript'
'Engineering'
'Immutability'
'Scala'
'Predictability'
'New ideas'
'Optimization'
'Node.js'
'Fixing things'
'Science'
'Protocols'
'Linux'
'Challenges'
'Progress'
]
personal = [
'Games'
'RPGs'
'ZEN'
'Discovery'
'Electronic music'
'Melodic dubstep'
'Ramen'
'Dogs'
'Japan'
'Manga'
'Anime'
'Nintendo'
'<NAME>.'
'Commodore 64'
'Nostalgia'
'Movies'
'Oldschool'
'Chillout'
'My Girlfriend'
]
module.exports = [
{set: professional, wage: 5}
{set: personal, wage: 2}
] | true | professional = [
'Functions'
'Interfaces'
'Algorithms'
'IntelliJ IDEA'
'F#'
'Quality'
'Declarative\nprogramming'
'HTML5'
'Javascript'
'Coffeescript'
'Engineering'
'Immutability'
'Scala'
'Predictability'
'New ideas'
'Optimization'
'Node.js'
'Fixing things'
'Science'
'Protocols'
'Linux'
'Challenges'
'Progress'
]
personal = [
'Games'
'RPGs'
'ZEN'
'Discovery'
'Electronic music'
'Melodic dubstep'
'Ramen'
'Dogs'
'Japan'
'Manga'
'Anime'
'Nintendo'
'PI:NAME:<NAME>END_PI.'
'Commodore 64'
'Nostalgia'
'Movies'
'Oldschool'
'Chillout'
'My Girlfriend'
]
module.exports = [
{set: professional, wage: 5}
{set: personal, wage: 2}
] |
[
{
"context": "# (c) Antonin Hildebrand, license MIT\n\nfs = require 'fs'\np = require 'path",
"end": 24,
"score": 0.9998939037322998,
"start": 6,
"tag": "NAME",
"value": "Antonin Hildebrand"
},
{
"context": "'fs'\np = require 'path'\n\n# see https://github.com/jashkenas/coffee-script... | util/include.coffee | darwin/terraform | 2 | # (c) Antonin Hildebrand, license MIT
fs = require 'fs'
p = require 'path'
# see https://github.com/jashkenas/coffee-script/wiki/%5BExtensibility%5D-Hooking-into-the-Command-Line-Compiler
#
# note: we cannot just require CoffeeScript here, command.js modifies returned CoffeeScript object which is a bummer,
# because of http://nodejs.org/api/modules.html#modules_module_caching_caveats
# instead try to lookup CoffeeScript object in our parent module (which is command.js)
#
# CoffeeScript = require 'coffee-script'
for m in module.parent.children
path = m.id.split "/"
name = path[path.length-1]
if name == "coffee-script.js"
CoffeeScript = m.exports
break
########################################################################
readSource = (path) ->
fs.readFileSync path, 'utf8'
numberOfLines = (text) ->
text.split("\n").length
resolveIncludePath = (basePath, relativePath) ->
path = p.resolve basePath, relativePath
return path if p.extname path
return path if fs.existsSync path
path + ".coffee"
preprocess = (text, path, linesMap, linesAdded=0) ->
text.replace /^#include ['"](.*?)['"].*$/gm, (m, include, offset, input) =>
includePath = resolveIncludePath p.dirname(path), include
content = readSource includePath
snippet= preprocess content, includePath, linesMap, linesAdded
len = numberOfLines snippet
lineNumber = (numberOfLines input.substring 0, offset) - 1
linesMap.push { path: includePath, start: linesAdded+lineNumber, len: len }
linesAdded -= 1 # we have deleted original #include line
linesAdded += len # we have added bunch of new lines in-place
snippet
lookupLineRewrite = (line, map) ->
for record in map
return record if line >= record.start and line < record.start + record.len
presentLineRewrite = (line, record, basePath) ->
relativeLine = line - record.start
relativePath = p.relative basePath, record.path
"in #{relativePath}:#{relativeLine+1}" # we have 0-based math
patchLineNumbersInReport = (text, lastCompilation) ->
text.replace /on line (\d+)/gm, (m, n) ->
line = parseInt(n, 10) - 1
record = lookupLineRewrite line, lastCompilation.linesMap
return m if not record
presentLineRewrite line, record, lastCompilation.basePath
#-----------------------------------------------------------------------------
lastCompilation =
linesMap: []
basePath: ''
CoffeeScript.on 'compile', (task) ->
lastCompilation =
linesMap: []
basePath: p.dirname task.file
task.input = preprocess task.input, task.file, lastCompilation.linesMap
CoffeeScript.on 'failure', self = (task) ->
CoffeeScript.removeListener 'failure', self # needed for coffeescript to print the failure report as usual
task.message = patchLineNumbersInReport task.message, lastCompilation
| 112480 | # (c) <NAME>, license MIT
fs = require 'fs'
p = require 'path'
# see https://github.com/jashkenas/coffee-script/wiki/%5BExtensibility%5D-Hooking-into-the-Command-Line-Compiler
#
# note: we cannot just require CoffeeScript here, command.js modifies returned CoffeeScript object which is a bummer,
# because of http://nodejs.org/api/modules.html#modules_module_caching_caveats
# instead try to lookup CoffeeScript object in our parent module (which is command.js)
#
# CoffeeScript = require 'coffee-script'
for m in module.parent.children
path = m.id.split "/"
name = path[path.length-1]
if name == "coffee-script.js"
CoffeeScript = m.exports
break
########################################################################
readSource = (path) ->
fs.readFileSync path, 'utf8'
numberOfLines = (text) ->
text.split("\n").length
resolveIncludePath = (basePath, relativePath) ->
path = p.resolve basePath, relativePath
return path if p.extname path
return path if fs.existsSync path
path + ".coffee"
preprocess = (text, path, linesMap, linesAdded=0) ->
text.replace /^#include ['"](.*?)['"].*$/gm, (m, include, offset, input) =>
includePath = resolveIncludePath p.dirname(path), include
content = readSource includePath
snippet= preprocess content, includePath, linesMap, linesAdded
len = numberOfLines snippet
lineNumber = (numberOfLines input.substring 0, offset) - 1
linesMap.push { path: includePath, start: linesAdded+lineNumber, len: len }
linesAdded -= 1 # we have deleted original #include line
linesAdded += len # we have added bunch of new lines in-place
snippet
lookupLineRewrite = (line, map) ->
for record in map
return record if line >= record.start and line < record.start + record.len
presentLineRewrite = (line, record, basePath) ->
relativeLine = line - record.start
relativePath = p.relative basePath, record.path
"in #{relativePath}:#{relativeLine+1}" # we have 0-based math
patchLineNumbersInReport = (text, lastCompilation) ->
text.replace /on line (\d+)/gm, (m, n) ->
line = parseInt(n, 10) - 1
record = lookupLineRewrite line, lastCompilation.linesMap
return m if not record
presentLineRewrite line, record, lastCompilation.basePath
#-----------------------------------------------------------------------------
lastCompilation =
linesMap: []
basePath: ''
CoffeeScript.on 'compile', (task) ->
lastCompilation =
linesMap: []
basePath: p.dirname task.file
task.input = preprocess task.input, task.file, lastCompilation.linesMap
CoffeeScript.on 'failure', self = (task) ->
CoffeeScript.removeListener 'failure', self # needed for coffeescript to print the failure report as usual
task.message = patchLineNumbersInReport task.message, lastCompilation
| true | # (c) PI:NAME:<NAME>END_PI, license MIT
fs = require 'fs'
p = require 'path'
# see https://github.com/jashkenas/coffee-script/wiki/%5BExtensibility%5D-Hooking-into-the-Command-Line-Compiler
#
# note: we cannot just require CoffeeScript here, command.js modifies returned CoffeeScript object which is a bummer,
# because of http://nodejs.org/api/modules.html#modules_module_caching_caveats
# instead try to lookup CoffeeScript object in our parent module (which is command.js)
#
# CoffeeScript = require 'coffee-script'
for m in module.parent.children
path = m.id.split "/"
name = path[path.length-1]
if name == "coffee-script.js"
CoffeeScript = m.exports
break
########################################################################
readSource = (path) ->
fs.readFileSync path, 'utf8'
numberOfLines = (text) ->
text.split("\n").length
resolveIncludePath = (basePath, relativePath) ->
path = p.resolve basePath, relativePath
return path if p.extname path
return path if fs.existsSync path
path + ".coffee"
preprocess = (text, path, linesMap, linesAdded=0) ->
text.replace /^#include ['"](.*?)['"].*$/gm, (m, include, offset, input) =>
includePath = resolveIncludePath p.dirname(path), include
content = readSource includePath
snippet= preprocess content, includePath, linesMap, linesAdded
len = numberOfLines snippet
lineNumber = (numberOfLines input.substring 0, offset) - 1
linesMap.push { path: includePath, start: linesAdded+lineNumber, len: len }
linesAdded -= 1 # we have deleted original #include line
linesAdded += len # we have added bunch of new lines in-place
snippet
lookupLineRewrite = (line, map) ->
for record in map
return record if line >= record.start and line < record.start + record.len
presentLineRewrite = (line, record, basePath) ->
relativeLine = line - record.start
relativePath = p.relative basePath, record.path
"in #{relativePath}:#{relativeLine+1}" # we have 0-based math
patchLineNumbersInReport = (text, lastCompilation) ->
text.replace /on line (\d+)/gm, (m, n) ->
line = parseInt(n, 10) - 1
record = lookupLineRewrite line, lastCompilation.linesMap
return m if not record
presentLineRewrite line, record, lastCompilation.basePath
#-----------------------------------------------------------------------------
lastCompilation =
linesMap: []
basePath: ''
CoffeeScript.on 'compile', (task) ->
lastCompilation =
linesMap: []
basePath: p.dirname task.file
task.input = preprocess task.input, task.file, lastCompilation.linesMap
CoffeeScript.on 'failure', self = (task) ->
CoffeeScript.removeListener 'failure', self # needed for coffeescript to print the failure report as usual
task.message = patchLineNumbersInReport task.message, lastCompilation
|
[
{
"context": "###\n@authors\nNicolas Laplante - https://plus.google.com/108189012221374960701\nN",
"end": 29,
"score": 0.9998883605003357,
"start": 13,
"tag": "NAME",
"value": "Nicolas Laplante"
},
{
"context": "e - https://plus.google.com/108189012221374960701\nNicholas McCready - h... | SafetyNet_Mobile/www/lib/angular-google-maps-master/src/coffee/directives/polygon.coffee | donh/pheonix | 1 | ###
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Rick Huizinga - https://plus.google.com/+RickHuizinga
###
angular.module('uiGmapgoogle-maps').directive 'uiGmapPolygon', ['uiGmapPolygon',
(Polygon) -> new Polygon()]
| 37782 | ###
@authors
<NAME> - https://plus.google.com/108189012221374960701
<NAME> - https://twitter.com/nmccready
<NAME> - https://plus.google.com/+RickHuizinga
###
angular.module('uiGmapgoogle-maps').directive 'uiGmapPolygon', ['uiGmapPolygon',
(Polygon) -> new Polygon()]
| true | ###
@authors
PI:NAME:<NAME>END_PI - https://plus.google.com/108189012221374960701
PI:NAME:<NAME>END_PI - https://twitter.com/nmccready
PI:NAME:<NAME>END_PI - https://plus.google.com/+RickHuizinga
###
angular.module('uiGmapgoogle-maps').directive 'uiGmapPolygon', ['uiGmapPolygon',
(Polygon) -> new Polygon()]
|
[
{
"context": "###\nstate {\n key: 's1',\n route: {\n 'a': 's2',\n 'b': 's",
"end": 24,
"score": 0.9956334233283997,
"start": 22,
"tag": "KEY",
"value": "s1"
}
] | src/common/DFA.coffee | Mutefish0/compiler_practices | 1 | ###
state {
key: 's1',
route: {
'a': 's2',
'b': 's3',
},
accepted: # accepted state, optional, true | false, default false
dead: # dead state, optional, true | false, default false
start: # start state, optional, true | false, default false
}
###
class DFA
constructor: (@states) ->
if !@states.length
throw Error 'No state found'
@_stateMap = new Map()
for state in @states
@_stateMap.set state.key, state
if state.start
@_startState = state
if !@_startState
throw Error 'No starting state found'
accepte: (str) ->
head = @_startState
for char in str
if head.dead
return false
head = @_stateMap.get head.route[char]
!!head.accepted
toString: ->
@states
module.exports = DFA | 150550 | ###
state {
key: '<KEY>',
route: {
'a': 's2',
'b': 's3',
},
accepted: # accepted state, optional, true | false, default false
dead: # dead state, optional, true | false, default false
start: # start state, optional, true | false, default false
}
###
class DFA
constructor: (@states) ->
if !@states.length
throw Error 'No state found'
@_stateMap = new Map()
for state in @states
@_stateMap.set state.key, state
if state.start
@_startState = state
if !@_startState
throw Error 'No starting state found'
accepte: (str) ->
head = @_startState
for char in str
if head.dead
return false
head = @_stateMap.get head.route[char]
!!head.accepted
toString: ->
@states
module.exports = DFA | true | ###
state {
key: 'PI:KEY:<KEY>END_PI',
route: {
'a': 's2',
'b': 's3',
},
accepted: # accepted state, optional, true | false, default false
dead: # dead state, optional, true | false, default false
start: # start state, optional, true | false, default false
}
###
class DFA
constructor: (@states) ->
if !@states.length
throw Error 'No state found'
@_stateMap = new Map()
for state in @states
@_stateMap.set state.key, state
if state.start
@_startState = state
if !@_startState
throw Error 'No starting state found'
accepte: (str) ->
head = @_startState
for char in str
if head.dead
return false
head = @_stateMap.get head.route[char]
!!head.accepted
toString: ->
@states
module.exports = DFA |
[
{
"context": " username: login.username\n password: login.password\n })\n\n # Send OK to frontend if ok else ",
"end": 834,
"score": 0.9984644055366516,
"start": 820,
"tag": "PASSWORD",
"value": "login.password"
},
{
"context": " username: login.usernam... | GOTHAM/Backend/src/Networking/Rooms/GeneralRoom.coffee | perara/gotham | 0 | Room = require './Room.coffee'
###*
# GeneralRoom, Emitters which does not fit in any category but General
# @class GeneralRoom
# @module Backend
# @submodule Backend.Networking
# @extends Room
###
class GeneralRoom extends Room
define: ->
that = @
###*
# Emitter for Login (Defined as class, but is in reality a method inside GeneralRoom)
# @class Emitter_Login
# @submodule Backend.Emitters
###
@addEvent "Login", (login) ->
client = that.getClient @id
that.log.info "[GeneralRoom] Login called: " + login
that.log.info "---- Attempting to login with #{login.username}:#{login.password}"
db_user = Gotham.LocalDatabase.table("User")
# Check if credential is correct
user = db_user.findOne({
username: login.username
password: login.password
})
# Send OK to frontend if ok else 500
if user
client.setUser user
client.authenticate true
client.Socket.emit 'Login', {"status": 200}
else
client.Socket.emit 'Login', {"status": 500}
client.Socket.disconnect()
###*
# Emitter for Reconnect login (Defined as class, but is in reality a method inside GeneralRoom)
# @class Emitter_ReconnectLogin
# @submodule Backend.Emitters
###
@addEvent "ReconnectLogin", (login) ->
client = that.getClient @id
that.log.info "[GeneralRoom] ReconnectLogin called: " + login
that.log.info "---- Attempting to ReconnectLogin with #{login.username}:#{login.password}"
db_user = Gotham.LocalDatabase.table("User")
# Check if credential is correct
user = db_user.findOne({
username: login.username
password: login.password
})
# Send OK to frontend if ok else 500
if user
client.setUser user
client.authenticate true
client.Socket.emit 'ReconnectLogin', {"status": 200}
else
client.Socket.emit 'ReconnectLogin', {"status": 500}
client.Socket.disconnect()
###*
# Emitter for Logout (Defined as class, but is in reality a method inside GeneralRoom)
# @class Emitter_Logout
# @submodule Backend.Emitters
###
@addEvent "Logout", (data) ->
that.log.info "[GeneralRoom] Logout called" + data
client = that.getClient @id
that.removeClient client
client.Socket.emit 'Logout', "OK"
###*
# Emitter for Terminate (Defined as class, but is in reality a method inside GeneralRoom)
# @class Emitter_Terminate
# @submodule Backend.Emitters
###
@addEvent "Terminate", (data) ->
that.log.info "[GeneralRoom] Terminate called" + data
@emit 'Terminate', "OK"
@disconnect()
module.exports = GeneralRoom | 161057 | Room = require './Room.coffee'
###*
# GeneralRoom, Emitters which does not fit in any category but General
# @class GeneralRoom
# @module Backend
# @submodule Backend.Networking
# @extends Room
###
class GeneralRoom extends Room
define: ->
that = @
###*
# Emitter for Login (Defined as class, but is in reality a method inside GeneralRoom)
# @class Emitter_Login
# @submodule Backend.Emitters
###
@addEvent "Login", (login) ->
client = that.getClient @id
that.log.info "[GeneralRoom] Login called: " + login
that.log.info "---- Attempting to login with #{login.username}:#{login.password}"
db_user = Gotham.LocalDatabase.table("User")
# Check if credential is correct
user = db_user.findOne({
username: login.username
password: <PASSWORD>
})
# Send OK to frontend if ok else 500
if user
client.setUser user
client.authenticate true
client.Socket.emit 'Login', {"status": 200}
else
client.Socket.emit 'Login', {"status": 500}
client.Socket.disconnect()
###*
# Emitter for Reconnect login (Defined as class, but is in reality a method inside GeneralRoom)
# @class Emitter_ReconnectLogin
# @submodule Backend.Emitters
###
@addEvent "ReconnectLogin", (login) ->
client = that.getClient @id
that.log.info "[GeneralRoom] ReconnectLogin called: " + login
that.log.info "---- Attempting to ReconnectLogin with #{login.username}:#{login.password}"
db_user = Gotham.LocalDatabase.table("User")
# Check if credential is correct
user = db_user.findOne({
username: login.username
password: <PASSWORD>
})
# Send OK to frontend if ok else 500
if user
client.setUser user
client.authenticate true
client.Socket.emit 'ReconnectLogin', {"status": 200}
else
client.Socket.emit 'ReconnectLogin', {"status": 500}
client.Socket.disconnect()
###*
# Emitter for Logout (Defined as class, but is in reality a method inside GeneralRoom)
# @class Emitter_Logout
# @submodule Backend.Emitters
###
@addEvent "Logout", (data) ->
that.log.info "[GeneralRoom] Logout called" + data
client = that.getClient @id
that.removeClient client
client.Socket.emit 'Logout', "OK"
###*
# Emitter for Terminate (Defined as class, but is in reality a method inside GeneralRoom)
# @class Emitter_Terminate
# @submodule Backend.Emitters
###
@addEvent "Terminate", (data) ->
that.log.info "[GeneralRoom] Terminate called" + data
@emit 'Terminate', "OK"
@disconnect()
module.exports = GeneralRoom | true | Room = require './Room.coffee'
###*
# GeneralRoom, Emitters which does not fit in any category but General
# @class GeneralRoom
# @module Backend
# @submodule Backend.Networking
# @extends Room
###
class GeneralRoom extends Room
define: ->
that = @
###*
# Emitter for Login (Defined as class, but is in reality a method inside GeneralRoom)
# @class Emitter_Login
# @submodule Backend.Emitters
###
@addEvent "Login", (login) ->
client = that.getClient @id
that.log.info "[GeneralRoom] Login called: " + login
that.log.info "---- Attempting to login with #{login.username}:#{login.password}"
db_user = Gotham.LocalDatabase.table("User")
# Check if credential is correct
user = db_user.findOne({
username: login.username
password: PI:PASSWORD:<PASSWORD>END_PI
})
# Send OK to frontend if ok else 500
if user
client.setUser user
client.authenticate true
client.Socket.emit 'Login', {"status": 200}
else
client.Socket.emit 'Login', {"status": 500}
client.Socket.disconnect()
###*
# Emitter for Reconnect login (Defined as class, but is in reality a method inside GeneralRoom)
# @class Emitter_ReconnectLogin
# @submodule Backend.Emitters
###
@addEvent "ReconnectLogin", (login) ->
client = that.getClient @id
that.log.info "[GeneralRoom] ReconnectLogin called: " + login
that.log.info "---- Attempting to ReconnectLogin with #{login.username}:#{login.password}"
db_user = Gotham.LocalDatabase.table("User")
# Check if credential is correct
user = db_user.findOne({
username: login.username
password: PI:PASSWORD:<PASSWORD>END_PI
})
# Send OK to frontend if ok else 500
if user
client.setUser user
client.authenticate true
client.Socket.emit 'ReconnectLogin', {"status": 200}
else
client.Socket.emit 'ReconnectLogin', {"status": 500}
client.Socket.disconnect()
###*
# Emitter for Logout (Defined as class, but is in reality a method inside GeneralRoom)
# @class Emitter_Logout
# @submodule Backend.Emitters
###
@addEvent "Logout", (data) ->
that.log.info "[GeneralRoom] Logout called" + data
client = that.getClient @id
that.removeClient client
client.Socket.emit 'Logout', "OK"
###*
# Emitter for Terminate (Defined as class, but is in reality a method inside GeneralRoom)
# @class Emitter_Terminate
# @submodule Backend.Emitters
###
@addEvent "Terminate", (data) ->
that.log.info "[GeneralRoom] Terminate called" + data
@emit 'Terminate', "OK"
@disconnect()
module.exports = GeneralRoom |
[
{
"context": "id: 0\naka: ['','']\nname: \"Name Of Project\"\ndescription: \"Description of project\"",
"end": 30,
"score": 0.5908448696136475,
"start": 26,
"tag": "NAME",
"value": "Name"
}
] | app/data/projects/defaults.cson | tsmorgan/dwp-ux-work | 0 | id: 0
aka: ['','']
name: "Name Of Project"
description: "Description of project"
theme: "Platforms"
location: "Leeds"
phase: "backlog"
phase_history:
discovery: [
{
label: ""
date: ""
}
{
label: ""
date: ""
}
]
alpha: [
{
label: ""
date: ""
}
{
label: ""
date: ""
}
]
facing: "user"
priority: "medium"
| 222553 | id: 0
aka: ['','']
name: "<NAME> Of Project"
description: "Description of project"
theme: "Platforms"
location: "Leeds"
phase: "backlog"
phase_history:
discovery: [
{
label: ""
date: ""
}
{
label: ""
date: ""
}
]
alpha: [
{
label: ""
date: ""
}
{
label: ""
date: ""
}
]
facing: "user"
priority: "medium"
| true | id: 0
aka: ['','']
name: "PI:NAME:<NAME>END_PI Of Project"
description: "Description of project"
theme: "Platforms"
location: "Leeds"
phase: "backlog"
phase_history:
discovery: [
{
label: ""
date: ""
}
{
label: ""
date: ""
}
]
alpha: [
{
label: ""
date: ""
}
{
label: ""
date: ""
}
]
facing: "user"
priority: "medium"
|
[
{
"context": "mail (err, email) ->\n options = { password: currentPassword, email }\n remote.api.JUser.verifyPassword ",
"end": 8043,
"score": 0.9988513588905334,
"start": 8028,
"tag": "PASSWORD",
"value": "currentPassword"
},
{
"context": "etCurrentGroup()\n\n ... | client/app/lib/flux/teams/actions.coffee | lionheart1022/koding | 0 | $ = require 'jquery'
kd = require 'kd'
async = require 'async'
whoami = require 'app/util/whoami'
actions = require './actiontypes'
remote = require 'app/remote'
toImmutable = require 'app/util/toImmutable'
getters = require './getters'
Promise = require 'bluebird'
immutable = require 'immutable'
Tracker = require 'app/util/tracker'
isKoding = require 'app/util/isKoding'
isEmailValid = require 'app/util/isEmailValid'
s3upload = require 'app/util/s3upload'
kookies = require 'kookies'
Tracker = require 'app/util/tracker'
VerifyPasswordModal = require 'app/commonviews/verifypasswordmodal'
KodingKontrol = require 'app/kite/kodingkontrol'
globals = require 'globals'
loadTeam = ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
reactor.dispatch actions.LOAD_TEAM_SUCCESS, { team }
updateTeam = (dataToUpdate) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
if dataToUpdate.customize
logo = dataToUpdate.customize?.logo
groupsController.emit 'TEAM_LOGO_CHANGED', logo
new Promise (resolve, reject) ->
team.modify dataToUpdate, (err, result) ->
message = 'Team settings has been successfully updated.'
return reject { message: 'Couldn\'t update team settings. Please try again' } if err
reactor.dispatch actions.UPDATE_TEAM_SUCCESS, { dataToUpdate }
resolve { message }
updateInvitationInputValue = (index, inputType, value) ->
{ reactor } = kd.singletons
reactor.dispatch actions.SET_TEAM_INVITE_INPUT_VALUE, { index, inputType, value }
fetchMembers = (options = {}) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
reactor.dispatch actions.LOAD_TEAM_MEMBERS_BEGIN, { team }
team.fetchMembersWithEmail {}, options, (err, users) ->
reactor.dispatch actions.FETCH_TEAM_MEMBERS_SUCCESS, { users }
fetchMembersRole users
fetchMembersRole = (users) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
reactor.dispatch actions.ALL_USERS_LOADED if users.length < 10
myId = whoami().getId()
ids = users.map (user) -> user._id
ids.push myId
team.fetchUserRoles ids, (err, roles) ->
reactor.dispatch actions.FETCH_TEAM_MEMBERS_ROLES_SUCCESS, roles
loadPendingInvitations = ->
{ reactor } = kd.singletons
options = {}
reactor.dispatch actions.LOAD_PENDING_INVITATION_BEGIN
remote.api.JInvitation.some { status: 'pending' }, options, (err, invitations) ->
reactor.dispatch actions.LOAD_PENDING_INVITATION_FAIL if err
reactor.dispatch actions.LOAD_PENDING_INVITATION_SUCCESS, { invitations }
sendInvitations = ->
{ reactor } = kd.singletons
newInvitations = reactor.evaluate getters.newInvitations
invitations = newInvitations
.map (i) -> i.toJS()
.toArray()
pendingInvitations = reactor.evaluate getters.pendingInvitations
new Promise (resolve, reject) ->
remote.api.JInvitation.create { invitations: invitations }, (err) ->
if err
return reject { err }
title = "Invitation is sent to <strong>#{invitations[0].email}</strong>"
if invitations.length > 1 or pendingInvites?.size
title = 'All invitations are sent.'
Tracker.track Tracker.TEAMS_SENT_INVITATION for invite in invitations
loadPendingInvitations()
reactor.dispatch actions.RESET_TEAM_INVITES
resolve { title }
resendInvitations = ->
{ reactor } = kd.singletons
newInvitations = reactor.evaluate getters.newInvitations
resendInvitations = reactor.evaluate getters.resendInvitations
resendInvitations = resendInvitations.toArray()
new Promise (resolve, reject) ->
title = 'Invitation is resent.'
title = 'Invitations are resent.' if resendInvitations.size > 1
queue = resendInvitations.map (invite) -> (next) ->
remote.api.JInvitation.sendInvitationByCode invite.get('code'), (err) ->
if err
next err
reject { err }
else next()
async.series queue, (err) ->
# send invitations if there is new
if newInvitations.size
sendInvitations().then ({ title }) ->
title = 'All invitations are sent'
resolve { title }
.catch ({ title }) ->
reject { title }
else
title = "Invitation is resent to <strong>#{resendInvitations[0].get('email')}</strong>"
title = 'All invitations are resent.' if resendInvitations.size > 1
resolve { title }
reactor.dispatch actions.RESET_TEAM_INVITES
setSearchInputValue = (newValue) ->
{ reactor } = kd.singletons
reactor.dispatch actions.SET_SEARCH_INPUT_VALUE, { newValue }
handleRoleChange = (account, newRole) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
newRoles = [newRole]
if newRole is 'owner'
newRoles.push 'admin'
accountId = account.get '_id'
team.changeMemberRoles accountId, newRoles, (err, response) ->
unless err
team.fetchUserRoles [accountId], (err, roles) ->
unless err
roles = (role.as for role in roles)
account = account.set 'role', roles #send all roles for that user but we save only one
reactor.dispatch actions.UPDATE_TEAM_MEMBER, { account }
handlePendingInvitationUpdate = (account, action) ->
{ reactor } = kd.singletons
if action is 'revoke'
remote.api.JInvitation.revokeInvitation account, (err) ->
title = 'You are not authorized to revoke this invite.'
return new kd.NotificationView { title, duration: 5000 } if err
reactor.dispatch actions.DELETE_PENDING_INVITATION_SUCCESS, { account }
else if action is 'resend'
remote.api.JInvitation.sendInvitationByCode account.get('code'), (err) ->
title = 'Invitation is resent.'
duration = 5000
if err
title = 'Unable to resend the invitation. Please try again.'
return new kd.NotificationView { title, duration }
handleKickMember = (member) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
return if isKoding team
memberId = member.get '_id'
team.kickMember memberId, (err) ->
# handle, what if there is error
unless err
reactor.dispatch actions.DELETE_TEAM_MEMBER, memberId
reactor.dispatch actions.SAVE_DISABLED_TEAM_MEMBER, { member }
uploads3 = ({ name, content, mimeType }) ->
timeout = 3e4
new Promise (resolve, reject) ->
return reject {} unless name or content or mimeType
s3upload { name, content, mimeType, timeout }, (err, url) ->
if err then reject { err } else resolve { url }
loadDisabledUsers = ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
team.fetchBlockedAccountsWithEmail (err, members) ->
reactor.dispatch actions.LOAD_DISABLED_MEMBERS, { members } unless err
handleDisabledUser = (member) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
memberId = member.get '_id'
options =
id: memberId
removeUserFromTeam: no
team.unblockMember options, (err) ->
unless err
fetchMembers().then (members) ->
fetchMembersRole members
reactor.dispatch actions.REMOVE_ENABLED_MEMBER, { memberId }
.catch (err) -> 'error occurred while unblocking member'
handlePermanentlyDeleteMember = (member) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
memberId = member.get '_id'
options =
id: memberId
removeUserFromTeam: yes
team.unblockMember options, (err) ->
reactor.dispatch actions.REMOVE_ENABLED_MEMBER, { memberId }
leaveTeam = (partial) ->
new Promise (resolve, reject) ->
new VerifyPasswordModal 'Confirm', partial, (currentPassword) ->
whoami().fetchEmail (err, email) ->
options = { password: currentPassword, email }
remote.api.JUser.verifyPassword options, (err, confirmed) ->
return reject err.message if err
return reject 'Current password cannot be confirmed' unless confirmed
resolve confirmed
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
team.leave { password: currentPassword }, (err) ->
if err
return new kd.NotificationView { title : err.message }
Tracker.track Tracker.USER_LEFT_TEAM
kookies.expire 'clientId'
global.location.replace '/'
fetchApiTokens = ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
team.fetchApiTokens (err, apiTokens) ->
reactor.dispatch actions.FETCH_API_TOKENS_SUCCESS, { apiTokens } unless err
deleteApiToken = (apiTokenId) ->
{ reactor } = kd.singletons
reactor.dispatch actions.DELETE_API_TOKEN_SUCCESS, { apiTokenId }
addApiToken = (apiToken) ->
{ reactor } = kd.singletons
reactor.dispatch actions.ADD_API_TOKEN_SUCCESS, { apiToken }
disableApiTokens = (state) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
new Promise (resolve, reject) ->
team.modify { isApiEnabled : state }, (err) ->
return reject { err } if err
reactor.dispatch actions.SET_API_ACCESS_STATE, { state }
fetchCurrentStateOfApiAccess = ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
state = team.isApiEnabled is yes
reactor.dispatch actions.SET_API_ACCESS_STATE, { state }
loadOtaToken = ->
{ reactor } = kd.singletons
whoami().fetchOtaToken (err, token) ->
cmd = if err
"<a href='#'>Failed to generate your command, click to try again!</a>"
else
if globals.config.environment in ['dev', 'default', 'sandbox']
"export KONTROLURL=#{KodingKontrol.getKontrolUrl()}; curl -sL https://sandbox.kodi.ng/c/d/kd | bash -s #{token}"
else "curl -sL https://kodi.ng/c/p/kd | bash -s #{token}"
reactor.dispatch actions.LOAD_OTA_TOKEN_SUCCESS, { cmd }
module.exports = {
loadTeam
leaveTeam
updateTeam
updateInvitationInputValue
fetchMembers
fetchMembersRole
loadPendingInvitations
sendInvitations
resendInvitations
setSearchInputValue
handleRoleChange
handlePendingInvitationUpdate
handleKickMember
uploads3
loadDisabledUsers
handleDisabledUser
handlePermanentlyDeleteMember
fetchApiTokens
deleteApiToken
addApiToken
disableApiTokens
fetchCurrentStateOfApiAccess
loadOtaToken
}
| 51178 | $ = require 'jquery'
kd = require 'kd'
async = require 'async'
whoami = require 'app/util/whoami'
actions = require './actiontypes'
remote = require 'app/remote'
toImmutable = require 'app/util/toImmutable'
getters = require './getters'
Promise = require 'bluebird'
immutable = require 'immutable'
Tracker = require 'app/util/tracker'
isKoding = require 'app/util/isKoding'
isEmailValid = require 'app/util/isEmailValid'
s3upload = require 'app/util/s3upload'
kookies = require 'kookies'
Tracker = require 'app/util/tracker'
VerifyPasswordModal = require 'app/commonviews/verifypasswordmodal'
KodingKontrol = require 'app/kite/kodingkontrol'
globals = require 'globals'
loadTeam = ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
reactor.dispatch actions.LOAD_TEAM_SUCCESS, { team }
updateTeam = (dataToUpdate) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
if dataToUpdate.customize
logo = dataToUpdate.customize?.logo
groupsController.emit 'TEAM_LOGO_CHANGED', logo
new Promise (resolve, reject) ->
team.modify dataToUpdate, (err, result) ->
message = 'Team settings has been successfully updated.'
return reject { message: 'Couldn\'t update team settings. Please try again' } if err
reactor.dispatch actions.UPDATE_TEAM_SUCCESS, { dataToUpdate }
resolve { message }
updateInvitationInputValue = (index, inputType, value) ->
{ reactor } = kd.singletons
reactor.dispatch actions.SET_TEAM_INVITE_INPUT_VALUE, { index, inputType, value }
fetchMembers = (options = {}) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
reactor.dispatch actions.LOAD_TEAM_MEMBERS_BEGIN, { team }
team.fetchMembersWithEmail {}, options, (err, users) ->
reactor.dispatch actions.FETCH_TEAM_MEMBERS_SUCCESS, { users }
fetchMembersRole users
fetchMembersRole = (users) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
reactor.dispatch actions.ALL_USERS_LOADED if users.length < 10
myId = whoami().getId()
ids = users.map (user) -> user._id
ids.push myId
team.fetchUserRoles ids, (err, roles) ->
reactor.dispatch actions.FETCH_TEAM_MEMBERS_ROLES_SUCCESS, roles
loadPendingInvitations = ->
{ reactor } = kd.singletons
options = {}
reactor.dispatch actions.LOAD_PENDING_INVITATION_BEGIN
remote.api.JInvitation.some { status: 'pending' }, options, (err, invitations) ->
reactor.dispatch actions.LOAD_PENDING_INVITATION_FAIL if err
reactor.dispatch actions.LOAD_PENDING_INVITATION_SUCCESS, { invitations }
sendInvitations = ->
{ reactor } = kd.singletons
newInvitations = reactor.evaluate getters.newInvitations
invitations = newInvitations
.map (i) -> i.toJS()
.toArray()
pendingInvitations = reactor.evaluate getters.pendingInvitations
new Promise (resolve, reject) ->
remote.api.JInvitation.create { invitations: invitations }, (err) ->
if err
return reject { err }
title = "Invitation is sent to <strong>#{invitations[0].email}</strong>"
if invitations.length > 1 or pendingInvites?.size
title = 'All invitations are sent.'
Tracker.track Tracker.TEAMS_SENT_INVITATION for invite in invitations
loadPendingInvitations()
reactor.dispatch actions.RESET_TEAM_INVITES
resolve { title }
resendInvitations = ->
{ reactor } = kd.singletons
newInvitations = reactor.evaluate getters.newInvitations
resendInvitations = reactor.evaluate getters.resendInvitations
resendInvitations = resendInvitations.toArray()
new Promise (resolve, reject) ->
title = 'Invitation is resent.'
title = 'Invitations are resent.' if resendInvitations.size > 1
queue = resendInvitations.map (invite) -> (next) ->
remote.api.JInvitation.sendInvitationByCode invite.get('code'), (err) ->
if err
next err
reject { err }
else next()
async.series queue, (err) ->
# send invitations if there is new
if newInvitations.size
sendInvitations().then ({ title }) ->
title = 'All invitations are sent'
resolve { title }
.catch ({ title }) ->
reject { title }
else
title = "Invitation is resent to <strong>#{resendInvitations[0].get('email')}</strong>"
title = 'All invitations are resent.' if resendInvitations.size > 1
resolve { title }
reactor.dispatch actions.RESET_TEAM_INVITES
setSearchInputValue = (newValue) ->
{ reactor } = kd.singletons
reactor.dispatch actions.SET_SEARCH_INPUT_VALUE, { newValue }
handleRoleChange = (account, newRole) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
newRoles = [newRole]
if newRole is 'owner'
newRoles.push 'admin'
accountId = account.get '_id'
team.changeMemberRoles accountId, newRoles, (err, response) ->
unless err
team.fetchUserRoles [accountId], (err, roles) ->
unless err
roles = (role.as for role in roles)
account = account.set 'role', roles #send all roles for that user but we save only one
reactor.dispatch actions.UPDATE_TEAM_MEMBER, { account }
handlePendingInvitationUpdate = (account, action) ->
{ reactor } = kd.singletons
if action is 'revoke'
remote.api.JInvitation.revokeInvitation account, (err) ->
title = 'You are not authorized to revoke this invite.'
return new kd.NotificationView { title, duration: 5000 } if err
reactor.dispatch actions.DELETE_PENDING_INVITATION_SUCCESS, { account }
else if action is 'resend'
remote.api.JInvitation.sendInvitationByCode account.get('code'), (err) ->
title = 'Invitation is resent.'
duration = 5000
if err
title = 'Unable to resend the invitation. Please try again.'
return new kd.NotificationView { title, duration }
handleKickMember = (member) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
return if isKoding team
memberId = member.get '_id'
team.kickMember memberId, (err) ->
# handle, what if there is error
unless err
reactor.dispatch actions.DELETE_TEAM_MEMBER, memberId
reactor.dispatch actions.SAVE_DISABLED_TEAM_MEMBER, { member }
uploads3 = ({ name, content, mimeType }) ->
timeout = 3e4
new Promise (resolve, reject) ->
return reject {} unless name or content or mimeType
s3upload { name, content, mimeType, timeout }, (err, url) ->
if err then reject { err } else resolve { url }
loadDisabledUsers = ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
team.fetchBlockedAccountsWithEmail (err, members) ->
reactor.dispatch actions.LOAD_DISABLED_MEMBERS, { members } unless err
handleDisabledUser = (member) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
memberId = member.get '_id'
options =
id: memberId
removeUserFromTeam: no
team.unblockMember options, (err) ->
unless err
fetchMembers().then (members) ->
fetchMembersRole members
reactor.dispatch actions.REMOVE_ENABLED_MEMBER, { memberId }
.catch (err) -> 'error occurred while unblocking member'
handlePermanentlyDeleteMember = (member) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
memberId = member.get '_id'
options =
id: memberId
removeUserFromTeam: yes
team.unblockMember options, (err) ->
reactor.dispatch actions.REMOVE_ENABLED_MEMBER, { memberId }
leaveTeam = (partial) ->
new Promise (resolve, reject) ->
new VerifyPasswordModal 'Confirm', partial, (currentPassword) ->
whoami().fetchEmail (err, email) ->
options = { password: <PASSWORD>, email }
remote.api.JUser.verifyPassword options, (err, confirmed) ->
return reject err.message if err
return reject 'Current password cannot be confirmed' unless confirmed
resolve confirmed
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
team.leave { password: <PASSWORD> }, (err) ->
if err
return new kd.NotificationView { title : err.message }
Tracker.track Tracker.USER_LEFT_TEAM
kookies.expire 'clientId'
global.location.replace '/'
fetchApiTokens = ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
team.fetchApiTokens (err, apiTokens) ->
reactor.dispatch actions.FETCH_API_TOKENS_SUCCESS, { apiTokens } unless err
deleteApiToken = (apiTokenId) ->
{ reactor } = kd.singletons
reactor.dispatch actions.DELETE_API_TOKEN_SUCCESS, { apiTokenId }
addApiToken = (apiToken) ->
{ reactor } = kd.singletons
reactor.dispatch actions.ADD_API_TOKEN_SUCCESS, { apiToken }
disableApiTokens = (state) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
new Promise (resolve, reject) ->
team.modify { isApiEnabled : state }, (err) ->
return reject { err } if err
reactor.dispatch actions.SET_API_ACCESS_STATE, { state }
fetchCurrentStateOfApiAccess = ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
state = team.isApiEnabled is yes
reactor.dispatch actions.SET_API_ACCESS_STATE, { state }
loadOtaToken = ->
{ reactor } = kd.singletons
whoami().fetchOtaToken (err, token) ->
cmd = if err
"<a href='#'>Failed to generate your command, click to try again!</a>"
else
if globals.config.environment in ['dev', 'default', 'sandbox']
"export KONTROLURL=#{KodingKontrol.getKontrolUrl()}; curl -sL https://sandbox.kodi.ng/c/d/kd | bash -s #{token}"
else "curl -sL https://kodi.ng/c/p/kd | bash -s #{token}"
reactor.dispatch actions.LOAD_OTA_TOKEN_SUCCESS, { cmd }
module.exports = {
loadTeam
leaveTeam
updateTeam
updateInvitationInputValue
fetchMembers
fetchMembersRole
loadPendingInvitations
sendInvitations
resendInvitations
setSearchInputValue
handleRoleChange
handlePendingInvitationUpdate
handleKickMember
uploads3
loadDisabledUsers
handleDisabledUser
handlePermanentlyDeleteMember
fetchApiTokens
deleteApiToken
addApiToken
disableApiTokens
fetchCurrentStateOfApiAccess
loadOtaToken
}
| true | $ = require 'jquery'
kd = require 'kd'
async = require 'async'
whoami = require 'app/util/whoami'
actions = require './actiontypes'
remote = require 'app/remote'
toImmutable = require 'app/util/toImmutable'
getters = require './getters'
Promise = require 'bluebird'
immutable = require 'immutable'
Tracker = require 'app/util/tracker'
isKoding = require 'app/util/isKoding'
isEmailValid = require 'app/util/isEmailValid'
s3upload = require 'app/util/s3upload'
kookies = require 'kookies'
Tracker = require 'app/util/tracker'
VerifyPasswordModal = require 'app/commonviews/verifypasswordmodal'
KodingKontrol = require 'app/kite/kodingkontrol'
globals = require 'globals'
loadTeam = ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
reactor.dispatch actions.LOAD_TEAM_SUCCESS, { team }
updateTeam = (dataToUpdate) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
if dataToUpdate.customize
logo = dataToUpdate.customize?.logo
groupsController.emit 'TEAM_LOGO_CHANGED', logo
new Promise (resolve, reject) ->
team.modify dataToUpdate, (err, result) ->
message = 'Team settings has been successfully updated.'
return reject { message: 'Couldn\'t update team settings. Please try again' } if err
reactor.dispatch actions.UPDATE_TEAM_SUCCESS, { dataToUpdate }
resolve { message }
updateInvitationInputValue = (index, inputType, value) ->
{ reactor } = kd.singletons
reactor.dispatch actions.SET_TEAM_INVITE_INPUT_VALUE, { index, inputType, value }
fetchMembers = (options = {}) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
reactor.dispatch actions.LOAD_TEAM_MEMBERS_BEGIN, { team }
team.fetchMembersWithEmail {}, options, (err, users) ->
reactor.dispatch actions.FETCH_TEAM_MEMBERS_SUCCESS, { users }
fetchMembersRole users
fetchMembersRole = (users) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
reactor.dispatch actions.ALL_USERS_LOADED if users.length < 10
myId = whoami().getId()
ids = users.map (user) -> user._id
ids.push myId
team.fetchUserRoles ids, (err, roles) ->
reactor.dispatch actions.FETCH_TEAM_MEMBERS_ROLES_SUCCESS, roles
loadPendingInvitations = ->
{ reactor } = kd.singletons
options = {}
reactor.dispatch actions.LOAD_PENDING_INVITATION_BEGIN
remote.api.JInvitation.some { status: 'pending' }, options, (err, invitations) ->
reactor.dispatch actions.LOAD_PENDING_INVITATION_FAIL if err
reactor.dispatch actions.LOAD_PENDING_INVITATION_SUCCESS, { invitations }
sendInvitations = ->
{ reactor } = kd.singletons
newInvitations = reactor.evaluate getters.newInvitations
invitations = newInvitations
.map (i) -> i.toJS()
.toArray()
pendingInvitations = reactor.evaluate getters.pendingInvitations
new Promise (resolve, reject) ->
remote.api.JInvitation.create { invitations: invitations }, (err) ->
if err
return reject { err }
title = "Invitation is sent to <strong>#{invitations[0].email}</strong>"
if invitations.length > 1 or pendingInvites?.size
title = 'All invitations are sent.'
Tracker.track Tracker.TEAMS_SENT_INVITATION for invite in invitations
loadPendingInvitations()
reactor.dispatch actions.RESET_TEAM_INVITES
resolve { title }
resendInvitations = ->
{ reactor } = kd.singletons
newInvitations = reactor.evaluate getters.newInvitations
resendInvitations = reactor.evaluate getters.resendInvitations
resendInvitations = resendInvitations.toArray()
new Promise (resolve, reject) ->
title = 'Invitation is resent.'
title = 'Invitations are resent.' if resendInvitations.size > 1
queue = resendInvitations.map (invite) -> (next) ->
remote.api.JInvitation.sendInvitationByCode invite.get('code'), (err) ->
if err
next err
reject { err }
else next()
async.series queue, (err) ->
# send invitations if there is new
if newInvitations.size
sendInvitations().then ({ title }) ->
title = 'All invitations are sent'
resolve { title }
.catch ({ title }) ->
reject { title }
else
title = "Invitation is resent to <strong>#{resendInvitations[0].get('email')}</strong>"
title = 'All invitations are resent.' if resendInvitations.size > 1
resolve { title }
reactor.dispatch actions.RESET_TEAM_INVITES
setSearchInputValue = (newValue) ->
{ reactor } = kd.singletons
reactor.dispatch actions.SET_SEARCH_INPUT_VALUE, { newValue }
handleRoleChange = (account, newRole) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
newRoles = [newRole]
if newRole is 'owner'
newRoles.push 'admin'
accountId = account.get '_id'
team.changeMemberRoles accountId, newRoles, (err, response) ->
unless err
team.fetchUserRoles [accountId], (err, roles) ->
unless err
roles = (role.as for role in roles)
account = account.set 'role', roles #send all roles for that user but we save only one
reactor.dispatch actions.UPDATE_TEAM_MEMBER, { account }
handlePendingInvitationUpdate = (account, action) ->
{ reactor } = kd.singletons
if action is 'revoke'
remote.api.JInvitation.revokeInvitation account, (err) ->
title = 'You are not authorized to revoke this invite.'
return new kd.NotificationView { title, duration: 5000 } if err
reactor.dispatch actions.DELETE_PENDING_INVITATION_SUCCESS, { account }
else if action is 'resend'
remote.api.JInvitation.sendInvitationByCode account.get('code'), (err) ->
title = 'Invitation is resent.'
duration = 5000
if err
title = 'Unable to resend the invitation. Please try again.'
return new kd.NotificationView { title, duration }
handleKickMember = (member) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
return if isKoding team
memberId = member.get '_id'
team.kickMember memberId, (err) ->
# handle, what if there is error
unless err
reactor.dispatch actions.DELETE_TEAM_MEMBER, memberId
reactor.dispatch actions.SAVE_DISABLED_TEAM_MEMBER, { member }
uploads3 = ({ name, content, mimeType }) ->
timeout = 3e4
new Promise (resolve, reject) ->
return reject {} unless name or content or mimeType
s3upload { name, content, mimeType, timeout }, (err, url) ->
if err then reject { err } else resolve { url }
loadDisabledUsers = ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
team.fetchBlockedAccountsWithEmail (err, members) ->
reactor.dispatch actions.LOAD_DISABLED_MEMBERS, { members } unless err
handleDisabledUser = (member) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
memberId = member.get '_id'
options =
id: memberId
removeUserFromTeam: no
team.unblockMember options, (err) ->
unless err
fetchMembers().then (members) ->
fetchMembersRole members
reactor.dispatch actions.REMOVE_ENABLED_MEMBER, { memberId }
.catch (err) -> 'error occurred while unblocking member'
handlePermanentlyDeleteMember = (member) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
memberId = member.get '_id'
options =
id: memberId
removeUserFromTeam: yes
team.unblockMember options, (err) ->
reactor.dispatch actions.REMOVE_ENABLED_MEMBER, { memberId }
leaveTeam = (partial) ->
new Promise (resolve, reject) ->
new VerifyPasswordModal 'Confirm', partial, (currentPassword) ->
whoami().fetchEmail (err, email) ->
options = { password: PI:PASSWORD:<PASSWORD>END_PI, email }
remote.api.JUser.verifyPassword options, (err, confirmed) ->
return reject err.message if err
return reject 'Current password cannot be confirmed' unless confirmed
resolve confirmed
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
team.leave { password: PI:PASSWORD:<PASSWORD>END_PI }, (err) ->
if err
return new kd.NotificationView { title : err.message }
Tracker.track Tracker.USER_LEFT_TEAM
kookies.expire 'clientId'
global.location.replace '/'
fetchApiTokens = ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
team.fetchApiTokens (err, apiTokens) ->
reactor.dispatch actions.FETCH_API_TOKENS_SUCCESS, { apiTokens } unless err
deleteApiToken = (apiTokenId) ->
{ reactor } = kd.singletons
reactor.dispatch actions.DELETE_API_TOKEN_SUCCESS, { apiTokenId }
addApiToken = (apiToken) ->
{ reactor } = kd.singletons
reactor.dispatch actions.ADD_API_TOKEN_SUCCESS, { apiToken }
disableApiTokens = (state) ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
new Promise (resolve, reject) ->
team.modify { isApiEnabled : state }, (err) ->
return reject { err } if err
reactor.dispatch actions.SET_API_ACCESS_STATE, { state }
fetchCurrentStateOfApiAccess = ->
{ groupsController, reactor } = kd.singletons
team = groupsController.getCurrentGroup()
state = team.isApiEnabled is yes
reactor.dispatch actions.SET_API_ACCESS_STATE, { state }
loadOtaToken = ->
{ reactor } = kd.singletons
whoami().fetchOtaToken (err, token) ->
cmd = if err
"<a href='#'>Failed to generate your command, click to try again!</a>"
else
if globals.config.environment in ['dev', 'default', 'sandbox']
"export KONTROLURL=#{KodingKontrol.getKontrolUrl()}; curl -sL https://sandbox.kodi.ng/c/d/kd | bash -s #{token}"
else "curl -sL https://kodi.ng/c/p/kd | bash -s #{token}"
reactor.dispatch actions.LOAD_OTA_TOKEN_SUCCESS, { cmd }
module.exports = {
loadTeam
leaveTeam
updateTeam
updateInvitationInputValue
fetchMembers
fetchMembersRole
loadPendingInvitations
sendInvitations
resendInvitations
setSearchInputValue
handleRoleChange
handlePendingInvitationUpdate
handleKickMember
uploads3
loadDisabledUsers
handleDisabledUser
handlePermanentlyDeleteMember
fetchApiTokens
deleteApiToken
addApiToken
disableApiTokens
fetchCurrentStateOfApiAccess
loadOtaToken
}
|
[
{
"context": "cs/#info.info\n\nFramer.Info =\n\ttitle: \"\"\n\tauthor: \"Tony\"\n\ttwitter: \"\"\n\tdescription: \"\"\n\n\nt0 = 0\nt1 = 0\nde",
"end": 146,
"score": 0.9993020296096802,
"start": 142,
"tag": "NAME",
"value": "Tony"
}
] | 61timer.framer/app.coffee | gremjua-forks/100daysofframer | 26 | # Project Info
# This info is presented in a widget when you share.
# http://framerjs.com/docs/#info.info
Framer.Info =
title: ""
author: "Tony"
twitter: ""
description: ""
t0 = 0
t1 = 0
delta = 0
sliderTimeMax = 3.1
animateTime = 0.02
tick = animateTime
bg = new BackgroundLayer backgroundColor: "250319"
dummy = new Layer
size: 0
timeText = new Layer
html: "Animation Time: 0.00", x: Align.center(60), y: Align.center(-100)
width: 500, height: 50, backgroundColor: null
style: textAlign: "left", fontSize: "2.5rem"
slider = new SliderComponent
x: Align.center, y: Align.center
min: animateTime, max: sliderTimeMax
go = new Layer
width: 120, height: 50, html: "GO", borderRadius: 5
backgroundColor: "#27af90", x: Align.center
y: Align.center(90)
style:
textAlign: "center", fontSize: "1.2rem"
lineHeight: "3rem"
slider.on "change:value", ->
bg.backgroundColor = "#250319"
animateTime = this.value
go.onClick ->
t0 = performance.now()
tick = 0
dummy.animate
properties: x: 100
time: animateTime
curve: "lineal"
bg.animate
properties: backgroundColor: "#5790cc"
time: animateTime
bg.onAnimationEnd ->
t1 = performance.now()
delta = t1 - t0
dummy.x = 0
dummy.on "change:x", ->
if Math.round(tick * 100) < 10
timeText.html = "Animation Time: 0.0" + Math.round(tick * 100)
else if Math.round(tick * 100) < 100
timeText.html = "Animation Time: 0." + Math.round(tick * 100)
else if Math.round(tick * 100) < 200
timeText.html = "Animation Time: 1." + Math.round(tick * 100 - 100)
else if Math.round(tick * 100) < 300
timeText.html = "Animation Time: 2." + Math.round(tick * 100 - 200)
else
timeText.html = "Animation Time: 3." + Math.round(tick * 100 - 300)
Utils.interval 0.01, ->
tick += 0.01
| 154308 | # Project Info
# This info is presented in a widget when you share.
# http://framerjs.com/docs/#info.info
Framer.Info =
title: ""
author: "<NAME>"
twitter: ""
description: ""
t0 = 0
t1 = 0
delta = 0
sliderTimeMax = 3.1
animateTime = 0.02
tick = animateTime
bg = new BackgroundLayer backgroundColor: "250319"
dummy = new Layer
size: 0
timeText = new Layer
html: "Animation Time: 0.00", x: Align.center(60), y: Align.center(-100)
width: 500, height: 50, backgroundColor: null
style: textAlign: "left", fontSize: "2.5rem"
slider = new SliderComponent
x: Align.center, y: Align.center
min: animateTime, max: sliderTimeMax
go = new Layer
width: 120, height: 50, html: "GO", borderRadius: 5
backgroundColor: "#27af90", x: Align.center
y: Align.center(90)
style:
textAlign: "center", fontSize: "1.2rem"
lineHeight: "3rem"
slider.on "change:value", ->
bg.backgroundColor = "#250319"
animateTime = this.value
go.onClick ->
t0 = performance.now()
tick = 0
dummy.animate
properties: x: 100
time: animateTime
curve: "lineal"
bg.animate
properties: backgroundColor: "#5790cc"
time: animateTime
bg.onAnimationEnd ->
t1 = performance.now()
delta = t1 - t0
dummy.x = 0
dummy.on "change:x", ->
if Math.round(tick * 100) < 10
timeText.html = "Animation Time: 0.0" + Math.round(tick * 100)
else if Math.round(tick * 100) < 100
timeText.html = "Animation Time: 0." + Math.round(tick * 100)
else if Math.round(tick * 100) < 200
timeText.html = "Animation Time: 1." + Math.round(tick * 100 - 100)
else if Math.round(tick * 100) < 300
timeText.html = "Animation Time: 2." + Math.round(tick * 100 - 200)
else
timeText.html = "Animation Time: 3." + Math.round(tick * 100 - 300)
Utils.interval 0.01, ->
tick += 0.01
| true | # Project Info
# This info is presented in a widget when you share.
# http://framerjs.com/docs/#info.info
Framer.Info =
title: ""
author: "PI:NAME:<NAME>END_PI"
twitter: ""
description: ""
t0 = 0
t1 = 0
delta = 0
sliderTimeMax = 3.1
animateTime = 0.02
tick = animateTime
bg = new BackgroundLayer backgroundColor: "250319"
dummy = new Layer
size: 0
timeText = new Layer
html: "Animation Time: 0.00", x: Align.center(60), y: Align.center(-100)
width: 500, height: 50, backgroundColor: null
style: textAlign: "left", fontSize: "2.5rem"
slider = new SliderComponent
x: Align.center, y: Align.center
min: animateTime, max: sliderTimeMax
go = new Layer
width: 120, height: 50, html: "GO", borderRadius: 5
backgroundColor: "#27af90", x: Align.center
y: Align.center(90)
style:
textAlign: "center", fontSize: "1.2rem"
lineHeight: "3rem"
slider.on "change:value", ->
bg.backgroundColor = "#250319"
animateTime = this.value
go.onClick ->
t0 = performance.now()
tick = 0
dummy.animate
properties: x: 100
time: animateTime
curve: "lineal"
bg.animate
properties: backgroundColor: "#5790cc"
time: animateTime
bg.onAnimationEnd ->
t1 = performance.now()
delta = t1 - t0
dummy.x = 0
dummy.on "change:x", ->
if Math.round(tick * 100) < 10
timeText.html = "Animation Time: 0.0" + Math.round(tick * 100)
else if Math.round(tick * 100) < 100
timeText.html = "Animation Time: 0." + Math.round(tick * 100)
else if Math.round(tick * 100) < 200
timeText.html = "Animation Time: 1." + Math.round(tick * 100 - 100)
else if Math.round(tick * 100) < 300
timeText.html = "Animation Time: 2." + Math.round(tick * 100 - 200)
else
timeText.html = "Animation Time: 3." + Math.round(tick * 100 - 300)
Utils.interval 0.01, ->
tick += 0.01
|
[
{
"context": "l scheduled messages for any rooms\n#\n# Author:\n# matsukaz <matsukaz@gmail.com>\n# ura14h <ishiura@ja2.so-n",
"end": 1429,
"score": 0.9994206428527832,
"start": 1421,
"tag": "USERNAME",
"value": "matsukaz"
},
{
"context": " messages for any rooms\n#\n# Author:\n# ... | src/scripts/schedule.coffee | ura14h/hubot-schedule | 0 | # Description:
# Schedule a message in both cron-style and datetime-based format pattern
#
# Dependencies:
# "node-schedule" : "~1.0.0",
# "cron-parser" : "~1.0.1"
#
# Configuration:
# HUBOT_SCHEDULE_DEBUG - set "1" for debug
# HUBOT_SCHEDULE_DONT_RECEIVE - set "1" if you don't want hubot to be processed by scheduled message
# HUBOT_SCHEDULE_DENY_EXTERNAL_CONTROL - set "1" if you want to deny scheduling from other rooms
# HUBOT_SCHEDULE_LIST_REPLACE_TEXT - set JSON object like '{"@":"[at]"}' to configure text replacement used when listing scheduled messages
#
# Commands:
# hubot schedule add "<datetime pattern>" <message> - Schedule a message that runs on a specific date and time
# hubot schedule add "<cron pattern>" <message> - Schedule a message that runs recurrently
# hubot schedule add #<room> "<datetime pattern>" <message> - Schedule a message to a specific room that runs on a specific date and time
# hubot schedule add #<room> "<cron pattern>" <message> - Schedule a message to a specific room that runs recurrently
# hubot schedule cancel <id> - Cancel the schedule
# hubot schedule update <id> <message> - Update scheduled message
# hubot schedule list - List all scheduled messages for current room
# hubot schedule list #<room> - List all scheduled messages for specified room
# hubot schedule list all - List all scheduled messages for any rooms
#
# Author:
# matsukaz <matsukaz@gmail.com>
# ura14h <ishiura@ja2.so-net.ne.jp>
# configuration settings
config =
debug: process.env.HUBOT_SCHEDULE_DEBUG
dont_receive: process.env.HUBOT_SCHEDULE_DONT_RECEIVE
deny_external_control: process.env.HUBOT_SCHEDULE_DENY_EXTERNAL_CONTROL
list:
replace_text: JSON.parse(process.env.HUBOT_SCHEDULE_LIST_REPLACE_TEXT ? '{"@":"[@]"}')
scheduler = require('node-schedule')
cronParser = require('cron-parser')
{TextMessage} = require('hubot')
JOBS = {}
JOB_MAX_COUNT = 10000
STORE_KEY = 'hubot_schedule'
module.exports = (robot) ->
robot.brain.on 'loaded', =>
syncSchedules robot
if !robot.brain.get(STORE_KEY)
robot.brain.set(STORE_KEY, {})
robot.respond /schedule help$/i, (msg) ->
prefix = msg.robot.name + ' '
if msg.envelope.user.roomType == 'd'
prefix = ''
text = """
ボットスケジュールコマンドは次のとおりです:
> #{prefix}schedule help -- このヘルプ
> #{prefix}schedule help cron -- クロン形式のヘルプ
> #{prefix}schedule help datetime -- 日時形式のヘルプ
> #{prefix}schedule add "<日時形式>" <メッセージ> -- 特定の日時に実行されるメッセージをスケジュールする
> #{prefix}schedule add "<クロン形式>" <メッセージ> -- 繰り返し実行されるメッセージをスケジュールする
"""
if config.deny_external_control isnt '1'
text += "\n"
text += """
> #{prefix}schedule add #<ルーム> "<日時形式>" <メッセージ> -- 特定の日時に実行される特定のルームにメッセージをスケジュールする
> #{prefix}schedule add #<ルーム> "<クロン形式>" <メッセージ> -- 繰り返し実行される特定のルームにメッセージをスケジュールする
"""
text += "\n"
text += """
> #{prefix}schedule cancel <id> -- スケジュールを取り消す
> #{prefix}schedule update <id> <メッセージ> -- スケジュールされたメッセージを更新する
> #{prefix}schedule list -- 現在のルームでスケジュールされているすべてのメッセージを一覧表示
"""
if config.deny_external_control isnt '1'
text += "\n"
text += """
> #{prefix}schedule list #<ルーム> -- 指定されたルームでスケジュールされているすべてのメッセージを一覧表示
> #{prefix}schedule list all -- すべてのスケジュールされたメッセージを一覧表示
"""
msg.send text
robot.respond /schedule help cron$/i, (msg) ->
msg.send """
クロン形式の書式は次の通りです:
> "分 時 日 月 曜日"
書式の各項目は次の通りです:
> 分 -- 0〜59
> 時 -- 0〜23
> 日 -- 1〜31
> 月 -- 1〜12
> 曜日 -- 0〜7 (0 と 7 が日曜日)
数値の代わりにアスタリスク記号(`*`)を指定した場合は毎分、毎時、毎日、毎月などの意味になります。
単純な数値の代わりにカンマ区切りでリスト指定やハイフン区切りで範囲指定することもできます。
詳細な書式は http://crontab.org/ を参照してください。
"""
robot.respond /schedule help datetime$/i, (msg) ->
msg.send """
日時形式の書式は次の通りです:
> "YYYY-MM-DD hh:mm"
書式の各項目は次の通りです:
> YYYY -- 4 桁の年
> MM -- 2 桁の月 (必要に応じて先頭に 0 を付加)
> DD -- 2 桁の日付 (必要に応じて先頭に 0 を付加)
> hh -- 2 桁の時
> mm -- 2 桁の分
"""
robot.respond /schedule add(?: #(.*))? "(.*?)" ((?:.|\s)*)$/i, (msg) ->
target_room = msg.match[1]
if not is_blank(target_room) and isRestrictedRoom(target_room, robot, msg)
return msg.send "他のルームのスケジュール作成は制限されています"
schedule robot, msg, target_room, msg.match[2], msg.match[3]
robot.respond /schedule list(?: (all|#.*))?/i, (msg) ->
target_room = msg.match[1]
room_id = msg.message.user.room
room_name = getRoomName(robot, msg.message.user)
if is_blank(target_room) or config.deny_external_control is '1'
# if target_room is undefined or blank, show schedule for current room
# room is ignored when HUBOT_SCHEDULE_DENY_EXTERNAL_CONTROL is set to 1
rooms = [room_name, msg.message.user.reply_to]
else if target_room == "all"
show_all = true
else
rooms = [target_room[1..]]
# split jobs into date and cron pattern jobs
dateJobs = {}
cronJobs = {}
for id, job of JOBS
# backward compatibility
# hubot-schedule under v0.5.1 holds it's job by room_id instead of room_name
if job.user.room == room_id
job.user.room = room_name
if show_all or job.user.room in rooms
if job.pattern instanceof Date
dateJobs[id] = job
else
cronJobs[id] = job
# sort by date in ascending order
text = ''
for id in (Object.keys(dateJobs).sort (a, b) -> new Date(dateJobs[a].pattern) - new Date(dateJobs[b].pattern))
job = dateJobs[id]
text += "#{id}: [ #{formatDate(new Date(job.pattern))} ] \##{job.user.room} #{job.message} \n"
for id, job of cronJobs
text += "#{id}: [ #{job.pattern} ] \##{job.user.room} #{job.message} \n"
if !!text.length
text = text.replace(///#{org_text}///g, replaced_text) for org_text, replaced_text of config.list.replace_text
msg.send text
else
msg.send 'メッセージはスケジュールされていません'
robot.respond /schedule update (\d+) ((?:.|\s)*)/i, (msg) ->
updateSchedule robot, msg, msg.match[1], msg.match[2]
robot.respond /schedule cancel (\d+)/i, (msg) ->
cancelSchedule robot, msg, msg.match[1]
schedule = (robot, msg, room, pattern, message) ->
if JOB_MAX_COUNT <= Object.keys(JOBS).length
return msg.send "スケジュールされたメッセージが多すぎます"
id = Math.floor(Math.random() * JOB_MAX_COUNT) while !id? || JOBS[id]
try
job = createSchedule robot, id, pattern, msg.message.user, room, message
if job
msg.send "#{id}: スケジュールが作成されました"
else
prefix = msg.robot.name + ' '
if msg.envelope.user.roomType == 'd'
prefix = ''
msg.send """
\"#{pattern}\" は無効なパターンです。
指定できるパターンは次のヘルプで確認できます:
> #{prefix}schedule help cron -- クロン形式のヘルプ
> #{prefix}schedule help datetime -- 日時形式のヘルプ
"""
catch error
return msg.send error.message
createSchedule = (robot, id, pattern, user, room, message) ->
if isCronPattern(pattern)
return createCronSchedule robot, id, pattern, user, room, message
date = Date.parse(pattern)
if !isNaN(date)
if date < Date.now()
throw new Error "\"#{pattern}\" はすでに過去です"
return createDatetimeSchedule robot, id, pattern, user, room, message
createCronSchedule = (robot, id, pattern, user, room, message) ->
startSchedule robot, id, pattern, user, room, message
createDatetimeSchedule = (robot, id, pattern, user, room, message) ->
startSchedule robot, id, new Date(pattern), user, room, message, () ->
delete JOBS[id]
delete robot.brain.get(STORE_KEY)[id]
startSchedule = (robot, id, pattern, user, room, message, cb) ->
if !room
room = getRoomName(robot, user)
job = new Job(id, pattern, user, room, message, cb)
job.start(robot)
JOBS[id] = job
robot.brain.get(STORE_KEY)[id] = job.serialize()
updateSchedule = (robot, msg, id, message) ->
job = JOBS[id]
return msg.send "スケジュール #{id} は見つかりません" if !job
if isRestrictedRoom(job.user.room, robot, msg)
return msg.send "他のルームのスケジュール更新は制限されています"
job.message = message
robot.brain.get(STORE_KEY)[id] = job.serialize()
msg.send "#{id}: スケジュールされたメッセージを更新しました"
cancelSchedule = (robot, msg, id) ->
job = JOBS[id]
return msg.send "#{id}: スケジュールが見つかりません" if !job
if isRestrictedRoom(job.user.room, robot, msg)
return msg.send "他のルームのスケジュール取り消しは制限されています"
job.cancel()
delete JOBS[id]
delete robot.brain.get(STORE_KEY)[id]
msg.send "#{id}: スケジュールは取り消されました"
syncSchedules = (robot) ->
if !robot.brain.get(STORE_KEY)
robot.brain.set(STORE_KEY, {})
nonCachedSchedules = difference(robot.brain.get(STORE_KEY), JOBS)
for own id, job of nonCachedSchedules
scheduleFromBrain robot, id, job...
nonStoredSchedules = difference(JOBS, robot.brain.get(STORE_KEY))
for own id, job of nonStoredSchedules
storeScheduleInBrain robot, id, job
scheduleFromBrain = (robot, id, pattern, user, message) ->
envelope = user: user, room: user.room
try
createSchedule robot, id, pattern, user, user.room, message
catch error
robot.send envelope, "#{id}: データベースから再スケジュールできませんでした. [#{error.message}]" if config.debug is '1'
return delete robot.brain.get(STORE_KEY)[id]
robot.send envelope, "#{id} データベースから再スケジュールしました" if config.debug is '1'
storeScheduleInBrain = (robot, id, job) ->
robot.brain.get(STORE_KEY)[id] = job.serialize()
envelope = user: job.user, room: job.user.room
robot.send envelope, "#{id}: スケジュールはデータベースに非同期的に保存されます" if config.debug is '1'
difference = (obj1 = {}, obj2 = {}) ->
diff = {}
for id, job of obj1
diff[id] = job if id !of obj2
return diff
isCronPattern = (pattern) ->
errors = cronParser.parseString(pattern).errors
return !Object.keys(errors).length
is_blank = (s) -> !s?.trim()
is_empty = (o) -> Object.keys(o).length == 0
isRestrictedRoom = (target_room, robot, msg) ->
if config.deny_external_control is '1'
if target_room not in [getRoomName(robot, msg.message.user), msg.message.user.reply_to]
return true
return false
toTwoDigits = (num) ->
('0' + num).slice(-2)
formatDate = (date) ->
offset = -date.getTimezoneOffset();
sign = ' GMT+'
if offset < 0
offset = -offset
sign = ' GMT-'
[date.getFullYear(), toTwoDigits(date.getMonth()+1), toTwoDigits(date.getDate())].join('-') + ' ' + date.toLocaleTimeString() + sign + toTwoDigits(offset / 60) + ':' + toTwoDigits(offset % 60);
getRoomName = (robot, user) ->
try
# Slack adapter needs to convert from room identifier
# https://slackapi.github.io/hubot-slack/upgrading
return robot.adapter.client.rtm.dataStore.getChannelGroupOrDMById(user.room).name
catch e
return user.room
class Job
constructor: (id, pattern, user, room, message, cb) ->
@id = id
@pattern = pattern
@user = { room: (room || user.room) }
@user[k] = v for k,v of user when k in ['id','team_id','name'] # copy only needed properties
@message = message
@cb = cb
@job
start: (robot) ->
@job = scheduler.scheduleJob(@pattern, =>
envelope = user: @user, room: @user.room
robot.send envelope, @message
robot.adapter.receive new TextMessage(@user, @message) unless config.dont_receive is '1'
@cb?()
)
cancel: ->
scheduler.cancelJob @job if @job
@cb?()
serialize: ->
[@pattern, @user, @message]
| 197127 | # Description:
# Schedule a message in both cron-style and datetime-based format pattern
#
# Dependencies:
# "node-schedule" : "~1.0.0",
# "cron-parser" : "~1.0.1"
#
# Configuration:
# HUBOT_SCHEDULE_DEBUG - set "1" for debug
# HUBOT_SCHEDULE_DONT_RECEIVE - set "1" if you don't want hubot to be processed by scheduled message
# HUBOT_SCHEDULE_DENY_EXTERNAL_CONTROL - set "1" if you want to deny scheduling from other rooms
# HUBOT_SCHEDULE_LIST_REPLACE_TEXT - set JSON object like '{"@":"[at]"}' to configure text replacement used when listing scheduled messages
#
# Commands:
# hubot schedule add "<datetime pattern>" <message> - Schedule a message that runs on a specific date and time
# hubot schedule add "<cron pattern>" <message> - Schedule a message that runs recurrently
# hubot schedule add #<room> "<datetime pattern>" <message> - Schedule a message to a specific room that runs on a specific date and time
# hubot schedule add #<room> "<cron pattern>" <message> - Schedule a message to a specific room that runs recurrently
# hubot schedule cancel <id> - Cancel the schedule
# hubot schedule update <id> <message> - Update scheduled message
# hubot schedule list - List all scheduled messages for current room
# hubot schedule list #<room> - List all scheduled messages for specified room
# hubot schedule list all - List all scheduled messages for any rooms
#
# Author:
# matsukaz <<EMAIL>>
# ura14h <<EMAIL>>
# configuration settings
config =
debug: process.env.HUBOT_SCHEDULE_DEBUG
dont_receive: process.env.HUBOT_SCHEDULE_DONT_RECEIVE
deny_external_control: process.env.HUBOT_SCHEDULE_DENY_EXTERNAL_CONTROL
list:
replace_text: JSON.parse(process.env.HUBOT_SCHEDULE_LIST_REPLACE_TEXT ? '{"@":"[@]"}')
scheduler = require('node-schedule')
cronParser = require('cron-parser')
{TextMessage} = require('hubot')
JOBS = {}
JOB_MAX_COUNT = 10000
STORE_KEY = '<KEY>'
module.exports = (robot) ->
robot.brain.on 'loaded', =>
syncSchedules robot
if !robot.brain.get(STORE_KEY)
robot.brain.set(STORE_KEY, {})
robot.respond /schedule help$/i, (msg) ->
prefix = msg.robot.name + ' '
if msg.envelope.user.roomType == 'd'
prefix = ''
text = """
ボットスケジュールコマンドは次のとおりです:
> #{prefix}schedule help -- このヘルプ
> #{prefix}schedule help cron -- クロン形式のヘルプ
> #{prefix}schedule help datetime -- 日時形式のヘルプ
> #{prefix}schedule add "<日時形式>" <メッセージ> -- 特定の日時に実行されるメッセージをスケジュールする
> #{prefix}schedule add "<クロン形式>" <メッセージ> -- 繰り返し実行されるメッセージをスケジュールする
"""
if config.deny_external_control isnt '1'
text += "\n"
text += """
> #{prefix}schedule add #<ルーム> "<日時形式>" <メッセージ> -- 特定の日時に実行される特定のルームにメッセージをスケジュールする
> #{prefix}schedule add #<ルーム> "<クロン形式>" <メッセージ> -- 繰り返し実行される特定のルームにメッセージをスケジュールする
"""
text += "\n"
text += """
> #{prefix}schedule cancel <id> -- スケジュールを取り消す
> #{prefix}schedule update <id> <メッセージ> -- スケジュールされたメッセージを更新する
> #{prefix}schedule list -- 現在のルームでスケジュールされているすべてのメッセージを一覧表示
"""
if config.deny_external_control isnt '1'
text += "\n"
text += """
> #{prefix}schedule list #<ルーム> -- 指定されたルームでスケジュールされているすべてのメッセージを一覧表示
> #{prefix}schedule list all -- すべてのスケジュールされたメッセージを一覧表示
"""
msg.send text
robot.respond /schedule help cron$/i, (msg) ->
msg.send """
クロン形式の書式は次の通りです:
> "分 時 日 月 曜日"
書式の各項目は次の通りです:
> 分 -- 0〜59
> 時 -- 0〜23
> 日 -- 1〜31
> 月 -- 1〜12
> 曜日 -- 0〜7 (0 と 7 が日曜日)
数値の代わりにアスタリスク記号(`*`)を指定した場合は毎分、毎時、毎日、毎月などの意味になります。
単純な数値の代わりにカンマ区切りでリスト指定やハイフン区切りで範囲指定することもできます。
詳細な書式は http://crontab.org/ を参照してください。
"""
robot.respond /schedule help datetime$/i, (msg) ->
msg.send """
日時形式の書式は次の通りです:
> "YYYY-MM-DD hh:mm"
書式の各項目は次の通りです:
> YYYY -- 4 桁の年
> MM -- 2 桁の月 (必要に応じて先頭に 0 を付加)
> DD -- 2 桁の日付 (必要に応じて先頭に 0 を付加)
> hh -- 2 桁の時
> mm -- 2 桁の分
"""
robot.respond /schedule add(?: #(.*))? "(.*?)" ((?:.|\s)*)$/i, (msg) ->
target_room = msg.match[1]
if not is_blank(target_room) and isRestrictedRoom(target_room, robot, msg)
return msg.send "他のルームのスケジュール作成は制限されています"
schedule robot, msg, target_room, msg.match[2], msg.match[3]
robot.respond /schedule list(?: (all|#.*))?/i, (msg) ->
target_room = msg.match[1]
room_id = msg.message.user.room
room_name = getRoomName(robot, msg.message.user)
if is_blank(target_room) or config.deny_external_control is '1'
# if target_room is undefined or blank, show schedule for current room
# room is ignored when HUBOT_SCHEDULE_DENY_EXTERNAL_CONTROL is set to 1
rooms = [room_name, msg.message.user.reply_to]
else if target_room == "all"
show_all = true
else
rooms = [target_room[1..]]
# split jobs into date and cron pattern jobs
dateJobs = {}
cronJobs = {}
for id, job of JOBS
# backward compatibility
# hubot-schedule under v0.5.1 holds it's job by room_id instead of room_name
if job.user.room == room_id
job.user.room = room_name
if show_all or job.user.room in rooms
if job.pattern instanceof Date
dateJobs[id] = job
else
cronJobs[id] = job
# sort by date in ascending order
text = ''
for id in (Object.keys(dateJobs).sort (a, b) -> new Date(dateJobs[a].pattern) - new Date(dateJobs[b].pattern))
job = dateJobs[id]
text += "#{id}: [ #{formatDate(new Date(job.pattern))} ] \##{job.user.room} #{job.message} \n"
for id, job of cronJobs
text += "#{id}: [ #{job.pattern} ] \##{job.user.room} #{job.message} \n"
if !!text.length
text = text.replace(///#{org_text}///g, replaced_text) for org_text, replaced_text of config.list.replace_text
msg.send text
else
msg.send 'メッセージはスケジュールされていません'
robot.respond /schedule update (\d+) ((?:.|\s)*)/i, (msg) ->
updateSchedule robot, msg, msg.match[1], msg.match[2]
robot.respond /schedule cancel (\d+)/i, (msg) ->
cancelSchedule robot, msg, msg.match[1]
schedule = (robot, msg, room, pattern, message) ->
if JOB_MAX_COUNT <= Object.keys(JOBS).length
return msg.send "スケジュールされたメッセージが多すぎます"
id = Math.floor(Math.random() * JOB_MAX_COUNT) while !id? || JOBS[id]
try
job = createSchedule robot, id, pattern, msg.message.user, room, message
if job
msg.send "#{id}: スケジュールが作成されました"
else
prefix = msg.robot.name + ' '
if msg.envelope.user.roomType == 'd'
prefix = ''
msg.send """
\"#{pattern}\" は無効なパターンです。
指定できるパターンは次のヘルプで確認できます:
> #{prefix}schedule help cron -- クロン形式のヘルプ
> #{prefix}schedule help datetime -- 日時形式のヘルプ
"""
catch error
return msg.send error.message
createSchedule = (robot, id, pattern, user, room, message) ->
if isCronPattern(pattern)
return createCronSchedule robot, id, pattern, user, room, message
date = Date.parse(pattern)
if !isNaN(date)
if date < Date.now()
throw new Error "\"#{pattern}\" はすでに過去です"
return createDatetimeSchedule robot, id, pattern, user, room, message
createCronSchedule = (robot, id, pattern, user, room, message) ->
startSchedule robot, id, pattern, user, room, message
createDatetimeSchedule = (robot, id, pattern, user, room, message) ->
startSchedule robot, id, new Date(pattern), user, room, message, () ->
delete JOBS[id]
delete robot.brain.get(STORE_KEY)[id]
startSchedule = (robot, id, pattern, user, room, message, cb) ->
if !room
room = getRoomName(robot, user)
job = new Job(id, pattern, user, room, message, cb)
job.start(robot)
JOBS[id] = job
robot.brain.get(STORE_KEY)[id] = job.serialize()
updateSchedule = (robot, msg, id, message) ->
job = JOBS[id]
return msg.send "スケジュール #{id} は見つかりません" if !job
if isRestrictedRoom(job.user.room, robot, msg)
return msg.send "他のルームのスケジュール更新は制限されています"
job.message = message
robot.brain.get(STORE_KEY)[id] = job.serialize()
msg.send "#{id}: スケジュールされたメッセージを更新しました"
cancelSchedule = (robot, msg, id) ->
job = JOBS[id]
return msg.send "#{id}: スケジュールが見つかりません" if !job
if isRestrictedRoom(job.user.room, robot, msg)
return msg.send "他のルームのスケジュール取り消しは制限されています"
job.cancel()
delete JOBS[id]
delete robot.brain.get(STORE_KEY)[id]
msg.send "#{id}: スケジュールは取り消されました"
syncSchedules = (robot) ->
if !robot.brain.get(STORE_KEY)
robot.brain.set(STORE_KEY, {})
nonCachedSchedules = difference(robot.brain.get(STORE_KEY), JOBS)
for own id, job of nonCachedSchedules
scheduleFromBrain robot, id, job...
nonStoredSchedules = difference(JOBS, robot.brain.get(STORE_KEY))
for own id, job of nonStoredSchedules
storeScheduleInBrain robot, id, job
scheduleFromBrain = (robot, id, pattern, user, message) ->
envelope = user: user, room: user.room
try
createSchedule robot, id, pattern, user, user.room, message
catch error
robot.send envelope, "#{id}: データベースから再スケジュールできませんでした. [#{error.message}]" if config.debug is '1'
return delete robot.brain.get(STORE_KEY)[id]
robot.send envelope, "#{id} データベースから再スケジュールしました" if config.debug is '1'
storeScheduleInBrain = (robot, id, job) ->
robot.brain.get(STORE_KEY)[id] = job.serialize()
envelope = user: job.user, room: job.user.room
robot.send envelope, "#{id}: スケジュールはデータベースに非同期的に保存されます" if config.debug is '1'
difference = (obj1 = {}, obj2 = {}) ->
diff = {}
for id, job of obj1
diff[id] = job if id !of obj2
return diff
isCronPattern = (pattern) ->
errors = cronParser.parseString(pattern).errors
return !Object.keys(errors).length
is_blank = (s) -> !s?.trim()
is_empty = (o) -> Object.keys(o).length == 0
isRestrictedRoom = (target_room, robot, msg) ->
if config.deny_external_control is '1'
if target_room not in [getRoomName(robot, msg.message.user), msg.message.user.reply_to]
return true
return false
toTwoDigits = (num) ->
('0' + num).slice(-2)
formatDate = (date) ->
offset = -date.getTimezoneOffset();
sign = ' GMT+'
if offset < 0
offset = -offset
sign = ' GMT-'
[date.getFullYear(), toTwoDigits(date.getMonth()+1), toTwoDigits(date.getDate())].join('-') + ' ' + date.toLocaleTimeString() + sign + toTwoDigits(offset / 60) + ':' + toTwoDigits(offset % 60);
getRoomName = (robot, user) ->
try
# Slack adapter needs to convert from room identifier
# https://slackapi.github.io/hubot-slack/upgrading
return robot.adapter.client.rtm.dataStore.getChannelGroupOrDMById(user.room).name
catch e
return user.room
class Job
constructor: (id, pattern, user, room, message, cb) ->
@id = id
@pattern = pattern
@user = { room: (room || user.room) }
@user[k] = v for k,v of user when k in ['id','team_id','name'] # copy only needed properties
@message = message
@cb = cb
@job
start: (robot) ->
@job = scheduler.scheduleJob(@pattern, =>
envelope = user: @user, room: @user.room
robot.send envelope, @message
robot.adapter.receive new TextMessage(@user, @message) unless config.dont_receive is '1'
@cb?()
)
cancel: ->
scheduler.cancelJob @job if @job
@cb?()
serialize: ->
[@pattern, @user, @message]
| true | # Description:
# Schedule a message in both cron-style and datetime-based format pattern
#
# Dependencies:
# "node-schedule" : "~1.0.0",
# "cron-parser" : "~1.0.1"
#
# Configuration:
# HUBOT_SCHEDULE_DEBUG - set "1" for debug
# HUBOT_SCHEDULE_DONT_RECEIVE - set "1" if you don't want hubot to be processed by scheduled message
# HUBOT_SCHEDULE_DENY_EXTERNAL_CONTROL - set "1" if you want to deny scheduling from other rooms
# HUBOT_SCHEDULE_LIST_REPLACE_TEXT - set JSON object like '{"@":"[at]"}' to configure text replacement used when listing scheduled messages
#
# Commands:
# hubot schedule add "<datetime pattern>" <message> - Schedule a message that runs on a specific date and time
# hubot schedule add "<cron pattern>" <message> - Schedule a message that runs recurrently
# hubot schedule add #<room> "<datetime pattern>" <message> - Schedule a message to a specific room that runs on a specific date and time
# hubot schedule add #<room> "<cron pattern>" <message> - Schedule a message to a specific room that runs recurrently
# hubot schedule cancel <id> - Cancel the schedule
# hubot schedule update <id> <message> - Update scheduled message
# hubot schedule list - List all scheduled messages for current room
# hubot schedule list #<room> - List all scheduled messages for specified room
# hubot schedule list all - List all scheduled messages for any rooms
#
# Author:
# matsukaz <PI:EMAIL:<EMAIL>END_PI>
# ura14h <PI:EMAIL:<EMAIL>END_PI>
# configuration settings
config =
debug: process.env.HUBOT_SCHEDULE_DEBUG
dont_receive: process.env.HUBOT_SCHEDULE_DONT_RECEIVE
deny_external_control: process.env.HUBOT_SCHEDULE_DENY_EXTERNAL_CONTROL
list:
replace_text: JSON.parse(process.env.HUBOT_SCHEDULE_LIST_REPLACE_TEXT ? '{"@":"[@]"}')
scheduler = require('node-schedule')
cronParser = require('cron-parser')
{TextMessage} = require('hubot')
JOBS = {}
JOB_MAX_COUNT = 10000
STORE_KEY = 'PI:KEY:<KEY>END_PI'
module.exports = (robot) ->
robot.brain.on 'loaded', =>
syncSchedules robot
if !robot.brain.get(STORE_KEY)
robot.brain.set(STORE_KEY, {})
robot.respond /schedule help$/i, (msg) ->
prefix = msg.robot.name + ' '
if msg.envelope.user.roomType == 'd'
prefix = ''
text = """
ボットスケジュールコマンドは次のとおりです:
> #{prefix}schedule help -- このヘルプ
> #{prefix}schedule help cron -- クロン形式のヘルプ
> #{prefix}schedule help datetime -- 日時形式のヘルプ
> #{prefix}schedule add "<日時形式>" <メッセージ> -- 特定の日時に実行されるメッセージをスケジュールする
> #{prefix}schedule add "<クロン形式>" <メッセージ> -- 繰り返し実行されるメッセージをスケジュールする
"""
if config.deny_external_control isnt '1'
text += "\n"
text += """
> #{prefix}schedule add #<ルーム> "<日時形式>" <メッセージ> -- 特定の日時に実行される特定のルームにメッセージをスケジュールする
> #{prefix}schedule add #<ルーム> "<クロン形式>" <メッセージ> -- 繰り返し実行される特定のルームにメッセージをスケジュールする
"""
text += "\n"
text += """
> #{prefix}schedule cancel <id> -- スケジュールを取り消す
> #{prefix}schedule update <id> <メッセージ> -- スケジュールされたメッセージを更新する
> #{prefix}schedule list -- 現在のルームでスケジュールされているすべてのメッセージを一覧表示
"""
if config.deny_external_control isnt '1'
text += "\n"
text += """
> #{prefix}schedule list #<ルーム> -- 指定されたルームでスケジュールされているすべてのメッセージを一覧表示
> #{prefix}schedule list all -- すべてのスケジュールされたメッセージを一覧表示
"""
msg.send text
robot.respond /schedule help cron$/i, (msg) ->
msg.send """
クロン形式の書式は次の通りです:
> "分 時 日 月 曜日"
書式の各項目は次の通りです:
> 分 -- 0〜59
> 時 -- 0〜23
> 日 -- 1〜31
> 月 -- 1〜12
> 曜日 -- 0〜7 (0 と 7 が日曜日)
数値の代わりにアスタリスク記号(`*`)を指定した場合は毎分、毎時、毎日、毎月などの意味になります。
単純な数値の代わりにカンマ区切りでリスト指定やハイフン区切りで範囲指定することもできます。
詳細な書式は http://crontab.org/ を参照してください。
"""
robot.respond /schedule help datetime$/i, (msg) ->
msg.send """
日時形式の書式は次の通りです:
> "YYYY-MM-DD hh:mm"
書式の各項目は次の通りです:
> YYYY -- 4 桁の年
> MM -- 2 桁の月 (必要に応じて先頭に 0 を付加)
> DD -- 2 桁の日付 (必要に応じて先頭に 0 を付加)
> hh -- 2 桁の時
> mm -- 2 桁の分
"""
robot.respond /schedule add(?: #(.*))? "(.*?)" ((?:.|\s)*)$/i, (msg) ->
target_room = msg.match[1]
if not is_blank(target_room) and isRestrictedRoom(target_room, robot, msg)
return msg.send "他のルームのスケジュール作成は制限されています"
schedule robot, msg, target_room, msg.match[2], msg.match[3]
robot.respond /schedule list(?: (all|#.*))?/i, (msg) ->
target_room = msg.match[1]
room_id = msg.message.user.room
room_name = getRoomName(robot, msg.message.user)
if is_blank(target_room) or config.deny_external_control is '1'
# if target_room is undefined or blank, show schedule for current room
# room is ignored when HUBOT_SCHEDULE_DENY_EXTERNAL_CONTROL is set to 1
rooms = [room_name, msg.message.user.reply_to]
else if target_room == "all"
show_all = true
else
rooms = [target_room[1..]]
# split jobs into date and cron pattern jobs
dateJobs = {}
cronJobs = {}
for id, job of JOBS
# backward compatibility
# hubot-schedule under v0.5.1 holds it's job by room_id instead of room_name
if job.user.room == room_id
job.user.room = room_name
if show_all or job.user.room in rooms
if job.pattern instanceof Date
dateJobs[id] = job
else
cronJobs[id] = job
# sort by date in ascending order
text = ''
for id in (Object.keys(dateJobs).sort (a, b) -> new Date(dateJobs[a].pattern) - new Date(dateJobs[b].pattern))
job = dateJobs[id]
text += "#{id}: [ #{formatDate(new Date(job.pattern))} ] \##{job.user.room} #{job.message} \n"
for id, job of cronJobs
text += "#{id}: [ #{job.pattern} ] \##{job.user.room} #{job.message} \n"
if !!text.length
text = text.replace(///#{org_text}///g, replaced_text) for org_text, replaced_text of config.list.replace_text
msg.send text
else
msg.send 'メッセージはスケジュールされていません'
robot.respond /schedule update (\d+) ((?:.|\s)*)/i, (msg) ->
updateSchedule robot, msg, msg.match[1], msg.match[2]
robot.respond /schedule cancel (\d+)/i, (msg) ->
cancelSchedule robot, msg, msg.match[1]
schedule = (robot, msg, room, pattern, message) ->
if JOB_MAX_COUNT <= Object.keys(JOBS).length
return msg.send "スケジュールされたメッセージが多すぎます"
id = Math.floor(Math.random() * JOB_MAX_COUNT) while !id? || JOBS[id]
try
job = createSchedule robot, id, pattern, msg.message.user, room, message
if job
msg.send "#{id}: スケジュールが作成されました"
else
prefix = msg.robot.name + ' '
if msg.envelope.user.roomType == 'd'
prefix = ''
msg.send """
\"#{pattern}\" は無効なパターンです。
指定できるパターンは次のヘルプで確認できます:
> #{prefix}schedule help cron -- クロン形式のヘルプ
> #{prefix}schedule help datetime -- 日時形式のヘルプ
"""
catch error
return msg.send error.message
createSchedule = (robot, id, pattern, user, room, message) ->
if isCronPattern(pattern)
return createCronSchedule robot, id, pattern, user, room, message
date = Date.parse(pattern)
if !isNaN(date)
if date < Date.now()
throw new Error "\"#{pattern}\" はすでに過去です"
return createDatetimeSchedule robot, id, pattern, user, room, message
createCronSchedule = (robot, id, pattern, user, room, message) ->
startSchedule robot, id, pattern, user, room, message
createDatetimeSchedule = (robot, id, pattern, user, room, message) ->
startSchedule robot, id, new Date(pattern), user, room, message, () ->
delete JOBS[id]
delete robot.brain.get(STORE_KEY)[id]
startSchedule = (robot, id, pattern, user, room, message, cb) ->
if !room
room = getRoomName(robot, user)
job = new Job(id, pattern, user, room, message, cb)
job.start(robot)
JOBS[id] = job
robot.brain.get(STORE_KEY)[id] = job.serialize()
updateSchedule = (robot, msg, id, message) ->
job = JOBS[id]
return msg.send "スケジュール #{id} は見つかりません" if !job
if isRestrictedRoom(job.user.room, robot, msg)
return msg.send "他のルームのスケジュール更新は制限されています"
job.message = message
robot.brain.get(STORE_KEY)[id] = job.serialize()
msg.send "#{id}: スケジュールされたメッセージを更新しました"
cancelSchedule = (robot, msg, id) ->
job = JOBS[id]
return msg.send "#{id}: スケジュールが見つかりません" if !job
if isRestrictedRoom(job.user.room, robot, msg)
return msg.send "他のルームのスケジュール取り消しは制限されています"
job.cancel()
delete JOBS[id]
delete robot.brain.get(STORE_KEY)[id]
msg.send "#{id}: スケジュールは取り消されました"
syncSchedules = (robot) ->
if !robot.brain.get(STORE_KEY)
robot.brain.set(STORE_KEY, {})
nonCachedSchedules = difference(robot.brain.get(STORE_KEY), JOBS)
for own id, job of nonCachedSchedules
scheduleFromBrain robot, id, job...
nonStoredSchedules = difference(JOBS, robot.brain.get(STORE_KEY))
for own id, job of nonStoredSchedules
storeScheduleInBrain robot, id, job
scheduleFromBrain = (robot, id, pattern, user, message) ->
envelope = user: user, room: user.room
try
createSchedule robot, id, pattern, user, user.room, message
catch error
robot.send envelope, "#{id}: データベースから再スケジュールできませんでした. [#{error.message}]" if config.debug is '1'
return delete robot.brain.get(STORE_KEY)[id]
robot.send envelope, "#{id} データベースから再スケジュールしました" if config.debug is '1'
storeScheduleInBrain = (robot, id, job) ->
robot.brain.get(STORE_KEY)[id] = job.serialize()
envelope = user: job.user, room: job.user.room
robot.send envelope, "#{id}: スケジュールはデータベースに非同期的に保存されます" if config.debug is '1'
difference = (obj1 = {}, obj2 = {}) ->
diff = {}
for id, job of obj1
diff[id] = job if id !of obj2
return diff
isCronPattern = (pattern) ->
errors = cronParser.parseString(pattern).errors
return !Object.keys(errors).length
is_blank = (s) -> !s?.trim()
is_empty = (o) -> Object.keys(o).length == 0
isRestrictedRoom = (target_room, robot, msg) ->
if config.deny_external_control is '1'
if target_room not in [getRoomName(robot, msg.message.user), msg.message.user.reply_to]
return true
return false
toTwoDigits = (num) ->
('0' + num).slice(-2)
formatDate = (date) ->
offset = -date.getTimezoneOffset();
sign = ' GMT+'
if offset < 0
offset = -offset
sign = ' GMT-'
[date.getFullYear(), toTwoDigits(date.getMonth()+1), toTwoDigits(date.getDate())].join('-') + ' ' + date.toLocaleTimeString() + sign + toTwoDigits(offset / 60) + ':' + toTwoDigits(offset % 60);
getRoomName = (robot, user) ->
try
# Slack adapter needs to convert from room identifier
# https://slackapi.github.io/hubot-slack/upgrading
return robot.adapter.client.rtm.dataStore.getChannelGroupOrDMById(user.room).name
catch e
return user.room
class Job
constructor: (id, pattern, user, room, message, cb) ->
@id = id
@pattern = pattern
@user = { room: (room || user.room) }
@user[k] = v for k,v of user when k in ['id','team_id','name'] # copy only needed properties
@message = message
@cb = cb
@job
start: (robot) ->
@job = scheduler.scheduleJob(@pattern, =>
envelope = user: @user, room: @user.room
robot.send envelope, @message
robot.adapter.receive new TextMessage(@user, @message) unless config.dont_receive is '1'
@cb?()
)
cancel: ->
scheduler.cancelJob @job if @job
@cb?()
serialize: ->
[@pattern, @user, @message]
|
[
{
"context": "pmTasks 'grunt-protractor-runner'\n\n sauceUser = 'pomerantsevp'\n sauceKey = '497ab04e-f31b-4a7b-9b18-ae3fbe0232",
"end": 363,
"score": 0.9992445111274719,
"start": 351,
"tag": "USERNAME",
"value": "pomerantsevp"
},
{
"context": "nner'\n\n sauceUser = 'pomerantsevp'... | Gruntfile.coffee | erwinverdonk/ngInfiniteScroll | 1 | module.exports = (grunt) ->
grunt.loadNpmTasks 'grunt-coffeelint'
grunt.loadNpmTasks 'grunt-contrib-clean'
grunt.loadNpmTasks 'grunt-contrib-coffee'
grunt.loadNpmTasks 'grunt-contrib-concat'
grunt.loadNpmTasks 'grunt-contrib-connect'
grunt.loadNpmTasks 'grunt-contrib-uglify'
grunt.loadNpmTasks 'grunt-protractor-runner'
sauceUser = 'pomerantsevp'
sauceKey = '497ab04e-f31b-4a7b-9b18-ae3fbe023222'
grunt.initConfig
pkg: grunt.file.readJSON 'package.json'
meta:
banner: '/* <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> */\n'
coffeelint:
src: 'src/**/*.coffee'
options:
max_line_length:
level: 'ignore'
line_endings:
value: 'unix'
level: 'error'
no_stand_alone_at:
level: 'error'
clean:
options:
force: true
build: ["compile/**", "build/**"]
coffee:
compile:
files: [
{
expand: true
cwd: 'src/'
src: '**/*.coffee'
dest: 'compile/'
ext: '.js'
}
],
options:
bare: true
concat:
options:
banner: '<%= meta.banner %>'
dist:
src: 'compile/**/*.js'
dest: 'build/ng-infinite-scroll.js'
uglify:
options:
banner: '<%= meta.banner %>'
dist:
src: ['build/ng-infinite-scroll.js']
dest: 'build/ng-infinite-scroll.min.js'
connect:
testserver:
options:
port: 8000
hostname: '0.0.0.0'
middleware: (connect, options) ->
base = if Array.isArray(options.base) then options.base[options.base.length - 1] else options.base
[connect.static(base)]
protractor:
local:
options:
configFile: 'test/protractor-local.conf.js'
args:
params:
testThrottleValue: 500
travis:
options:
configFile: 'test/protractor-travis.conf.js'
args:
params:
# When using Sauce Connect, we should use a large timeout
# since everything is generally much slower than when testing locally.
testThrottleValue: 10000
sauceUser: sauceUser
sauceKey: sauceKey
grunt.registerTask 'webdriver', () ->
done = this.async()
p = require('child_process').spawn('node', ['node_modules/protractor/bin/webdriver-manager', 'update'])
p.stdout.pipe(process.stdout)
p.stderr.pipe(process.stderr)
p.on 'exit', (code) ->
if code isnt 0 then grunt.fail.warn('Webdriver failed to update')
done()
grunt.registerTask 'sauce-connect', () ->
done = this.async()
require('sauce-connect-launcher')({username: sauceUser, accessKey: sauceKey}, (err, sauceConnectProcess) ->
if err then console.error(err.message)
else done()
)
grunt.registerTask 'default', ['coffeelint', 'clean', 'coffee', 'concat', 'uglify']
grunt.registerTask 'test:protractor-local', [
'default',
'webdriver',
'connect:testserver',
'protractor:local'
]
grunt.registerTask 'test:protractor-travis', [
'connect:testserver',
'sauce-connect',
'protractor:travis'
]
| 201600 | module.exports = (grunt) ->
grunt.loadNpmTasks 'grunt-coffeelint'
grunt.loadNpmTasks 'grunt-contrib-clean'
grunt.loadNpmTasks 'grunt-contrib-coffee'
grunt.loadNpmTasks 'grunt-contrib-concat'
grunt.loadNpmTasks 'grunt-contrib-connect'
grunt.loadNpmTasks 'grunt-contrib-uglify'
grunt.loadNpmTasks 'grunt-protractor-runner'
sauceUser = 'pomerantsevp'
sauceKey = '<KEY>'
grunt.initConfig
pkg: grunt.file.readJSON 'package.json'
meta:
banner: '/* <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> */\n'
coffeelint:
src: 'src/**/*.coffee'
options:
max_line_length:
level: 'ignore'
line_endings:
value: 'unix'
level: 'error'
no_stand_alone_at:
level: 'error'
clean:
options:
force: true
build: ["compile/**", "build/**"]
coffee:
compile:
files: [
{
expand: true
cwd: 'src/'
src: '**/*.coffee'
dest: 'compile/'
ext: '.js'
}
],
options:
bare: true
concat:
options:
banner: '<%= meta.banner %>'
dist:
src: 'compile/**/*.js'
dest: 'build/ng-infinite-scroll.js'
uglify:
options:
banner: '<%= meta.banner %>'
dist:
src: ['build/ng-infinite-scroll.js']
dest: 'build/ng-infinite-scroll.min.js'
connect:
testserver:
options:
port: 8000
hostname: '0.0.0.0'
middleware: (connect, options) ->
base = if Array.isArray(options.base) then options.base[options.base.length - 1] else options.base
[connect.static(base)]
protractor:
local:
options:
configFile: 'test/protractor-local.conf.js'
args:
params:
testThrottleValue: 500
travis:
options:
configFile: 'test/protractor-travis.conf.js'
args:
params:
# When using Sauce Connect, we should use a large timeout
# since everything is generally much slower than when testing locally.
testThrottleValue: 10000
sauceUser: sauceUser
sauceKey: sauceKey
grunt.registerTask 'webdriver', () ->
done = this.async()
p = require('child_process').spawn('node', ['node_modules/protractor/bin/webdriver-manager', 'update'])
p.stdout.pipe(process.stdout)
p.stderr.pipe(process.stderr)
p.on 'exit', (code) ->
if code isnt 0 then grunt.fail.warn('Webdriver failed to update')
done()
grunt.registerTask 'sauce-connect', () ->
done = this.async()
require('sauce-connect-launcher')({username: sauceUser, accessKey: sauceKey}, (err, sauceConnectProcess) ->
if err then console.error(err.message)
else done()
)
grunt.registerTask 'default', ['coffeelint', 'clean', 'coffee', 'concat', 'uglify']
grunt.registerTask 'test:protractor-local', [
'default',
'webdriver',
'connect:testserver',
'protractor:local'
]
grunt.registerTask 'test:protractor-travis', [
'connect:testserver',
'sauce-connect',
'protractor:travis'
]
| true | module.exports = (grunt) ->
grunt.loadNpmTasks 'grunt-coffeelint'
grunt.loadNpmTasks 'grunt-contrib-clean'
grunt.loadNpmTasks 'grunt-contrib-coffee'
grunt.loadNpmTasks 'grunt-contrib-concat'
grunt.loadNpmTasks 'grunt-contrib-connect'
grunt.loadNpmTasks 'grunt-contrib-uglify'
grunt.loadNpmTasks 'grunt-protractor-runner'
sauceUser = 'pomerantsevp'
sauceKey = 'PI:KEY:<KEY>END_PI'
grunt.initConfig
pkg: grunt.file.readJSON 'package.json'
meta:
banner: '/* <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> */\n'
coffeelint:
src: 'src/**/*.coffee'
options:
max_line_length:
level: 'ignore'
line_endings:
value: 'unix'
level: 'error'
no_stand_alone_at:
level: 'error'
clean:
options:
force: true
build: ["compile/**", "build/**"]
coffee:
compile:
files: [
{
expand: true
cwd: 'src/'
src: '**/*.coffee'
dest: 'compile/'
ext: '.js'
}
],
options:
bare: true
concat:
options:
banner: '<%= meta.banner %>'
dist:
src: 'compile/**/*.js'
dest: 'build/ng-infinite-scroll.js'
uglify:
options:
banner: '<%= meta.banner %>'
dist:
src: ['build/ng-infinite-scroll.js']
dest: 'build/ng-infinite-scroll.min.js'
connect:
testserver:
options:
port: 8000
hostname: '0.0.0.0'
middleware: (connect, options) ->
base = if Array.isArray(options.base) then options.base[options.base.length - 1] else options.base
[connect.static(base)]
protractor:
local:
options:
configFile: 'test/protractor-local.conf.js'
args:
params:
testThrottleValue: 500
travis:
options:
configFile: 'test/protractor-travis.conf.js'
args:
params:
# When using Sauce Connect, we should use a large timeout
# since everything is generally much slower than when testing locally.
testThrottleValue: 10000
sauceUser: sauceUser
sauceKey: sauceKey
grunt.registerTask 'webdriver', () ->
done = this.async()
p = require('child_process').spawn('node', ['node_modules/protractor/bin/webdriver-manager', 'update'])
p.stdout.pipe(process.stdout)
p.stderr.pipe(process.stderr)
p.on 'exit', (code) ->
if code isnt 0 then grunt.fail.warn('Webdriver failed to update')
done()
grunt.registerTask 'sauce-connect', () ->
done = this.async()
require('sauce-connect-launcher')({username: sauceUser, accessKey: sauceKey}, (err, sauceConnectProcess) ->
if err then console.error(err.message)
else done()
)
grunt.registerTask 'default', ['coffeelint', 'clean', 'coffee', 'concat', 'uglify']
grunt.registerTask 'test:protractor-local', [
'default',
'webdriver',
'connect:testserver',
'protractor:local'
]
grunt.registerTask 'test:protractor-travis', [
'connect:testserver',
'sauce-connect',
'protractor:travis'
]
|
[
{
"context": "(actor, callback) ->\n # git config user.email \"you@example.com\"\n @git \"config\", {}, [\"user.email\", \"\\\"#{actor",
"end": 1224,
"score": 0.9998420476913452,
"start": 1209,
"tag": "EMAIL",
"value": "you@example.com"
},
{
"context": "callback err if err\n ... | src/repo.coffee | roelofjan-elsinga/gift | 85 | _ = require 'underscore'
cmd = require './git'
Actor = require './actor'
Commit = require './commit'
Config = require './config'
Tree = require './tree'
Diff = require './diff'
Tag = require './tag'
Status = require './status'
{Ref, Head} = require './ref'
module.exports = class Repo
constructor: (@path, @bare, @git_options) ->
if @bare
@dot_git = @path
else
@dot_git = "#{@path}/.git"
@git = cmd @path, @dot_git, @git_options
# Public: Get the commit identity for this repository.
#
# callback - Receives `(err, actor)`, where `actor` is an Actor.
#
identity: (callback) ->
# git config user.email
@git "config", {}, ["user.email"]
, (err, stdout = '') =>
return callback err if err
email = stdout?.trim()
# git config user.name
@git "config", {}, ["user.name"]
, (err, stdout = '') =>
return callback err if err
name = stdout?.trim()
return callback null, new Actor(name, email)
# Public: Set your account's default identity for commits.
#
# actor - An instance of Actor.
# callback - Receives `(err)`.
#
identify: (actor, callback) ->
# git config user.email "you@example.com"
@git "config", {}, ["user.email", "\"#{actor.email}\""], (err) =>
return callback err if err
# git config user.name "Your Name"
@git "config", {}, ["user.name", "\"#{actor.name}\""], (err) =>
return callback err if err
return callback null
# Public: Get a list of commits.
#
# treeish - String (optional).
# limit - Integer (optional).
# skip - Integer (optional).
# callback - Function which receives `(err, commits)`, where `commits` is
# an Array of Commits.
#
# Examples
#
# # Get the 10 most recent commits to master.
# repo.commits (err, commits) ->
#
# # Or to a different tag or branch.
# repo.commits "v0.0.3", (err, commits) ->
#
# # Limit the maximum number of commits returned.
# repo.commits "master", 30, (err, commits) ->
#
# # Skip some (for pagination):
# repo.commits "master", 30, 30, (err, commits) ->
#
# # Do not limit commits amount
# repo.commits "master", -1, (err, commits) ->
#
commits: (start, limit, skip, callback) ->
[skip, callback] = [callback, skip] if !callback
[limit, callback] = [callback, limit] if !callback
[start, callback] = [callback, start] if !callback
throw new Error "a callback is required" if !callback
start ?= "master"
limit ?= 10
skip ?= 0
options = {skip}
if limit != -1
options["max-count"] = limit
Commit.find_all this, start, options, callback
# Internal: Returns current commit id
#
# callback - Receives `(err, id)`.
#
current_commit_id: (callback) ->
@git "rev-parse HEAD", {}, []
, (err, stdout, stderr) =>
return callback err if err
return callback null, _.first stdout.split "\n"
# Public:
#
# callback - Receives `(err, commit)`
#
current_commit: (callback) ->
@current_commit_id (err, commit_id) =>
return callback err if err
Commit.find this, commit_id, callback
# Public: The tree object for the treeish or master.
#
# treeish - String treeish (such as a branch or tag) (optional).
#
# Returns Tree.
tree: (treeish="master") ->
return new Tree this, treeish
# Public: Get the difference between the trees.
#
# commitA - A Commit or String commit id.
# commitB - A Commit or String commit id.
# paths - A list of String paths to restrict the difference to (optional).
# options - An object of options to pass to git diff (optional)
# callback - A Function which receives `(err, diffs)`.
#
# Possible forms of the method:
#
# diff(commitA, commitB, callback)
# diff(commitA, commitB, paths, callback)
# diff(commitA, commitB, options, callback)
# diff(commitA, commitB, paths, options, callback)
#
diff: (commitA, commitB) ->
[paths, options] = [[], {}]
if arguments.length is 3
callback = arguments[2]
else if arguments.length is 4
callback = arguments[3]
if arguments[2] instanceof Array
paths = arguments[2]
else if arguments[2] instanceof Object
options = arguments[2]
else if arguments.length is 5
[paths, options, callback] = Array.prototype.slice.call(arguments, 2)
commitA = commitA.id if _.isObject(commitA)
commitB = commitB.id if _.isObject(commitB)
@git "diff", options, _.flatten([commitA, commitB, "--", paths])
, (err, stdout, stderr) =>
return callback err if err
if _.has(options, 'raw')
return callback err, Diff.parse_raw(this, stdout)
else
return callback err, Diff.parse(this, stdout)
, 'binary'
# Public: Get the repository's remotes.
#
# callback - Receives `(err, remotes)`.
#
remotes: (callback) ->
Ref.find_all this, "remote", Ref, callback
# Public: List the repository's remotes.
#
# callback - Receives `(err, names)`.
#
remote_list: (callback) ->
@git.list_remotes callback
# Public: Add a remote.
#
# name - String name of the remote.
# url - String url of the remote.
# callback - Receives `(err)`
#
remote_add: (name, url, callback) ->
@git "remote", {}, ["add", name, url]
, (err, stdout, stderr) ->
callback err
# Public: Remove a remote.
#
# name - String name of the remote.
# callback - Receives `(err)`
#
remote_remove: (name, callback) ->
@git "remote", {}, ["rm", name]
, (err, stdout, stderr) ->
callback err
# Public: Add a remote URL.
#
# name - String name of the remote.
# url - String url of the remote.
# callback - Receives `(err)`
#
remote_add_url: (name, url, callback) ->
@git "remote set-url", {}, ["--add", name, url]
, (err, stdout, stderr) ->
callback err
# Public: Set a remote URL.
#
# name - String name of the remote.
# url - String url to set in the remote.
# callback - Receives `(err)`.
#
remote_set_url: (name, url, callback) ->
@git "remote set-url", {}, [name, url]
, (err, stdout, stderr) ->
callback err
# Public: Delete a remote URL.
#
# name - String name of the remote.
# url - String url of the remote.
# callback - Receives `(err)`
#
remote_delete_url: (name, url, callback) ->
@git "remote set-url", {}, ["--delete", name, url]
, (err, stdout, stderr) ->
callback err
# Public: `git fetch <name>`.
#
# name - String name of the remote
# callback - Receives `(err)`.
#
remote_fetch: (name, options, callback) ->
[options, callback] = [callback, options] if !callback
@git "fetch", options, name
, (err, stdout, stderr) ->
callback err
# Public: `git push <name>`.
#
# name - String name of the remote
# branch - (optional) Branch to push
# callback - Receives `(err)`.
#
remote_push: (name, branch, options, callback) ->
if !options && !callback
callback = branch
args = name
options = {}
else
if !callback
callback = options
options = {}
args = [name, branch]
@git "push", options, args
, (err, stdout, stderr) ->
callback err
# Public: `git merge <name>`.
#
# name - String name of the source
# callback - Receives `(err)`.
#
merge: (name, options, callback) ->
[options, callback] = [callback, options] if !callback
@git "merge", options, name
, (err, stdout, stderr) ->
callback err
# Public: Get the repository's status (`git status`).
#
# callback - Receives `(err, status)`
#
status: (options, callback) ->
[options, callback] = [callback, options] if !callback;
return Status(this, options, callback)
# Public: Show information about files in the index and the
# working tree.
#
# files - Array of String paths; or a String path (optional).
# options - An Object of command line arguments to pass to
# `git ls-files`.
# callback - Receives `(err,stdout)`.
#
ls_files: (files, options, callback) ->
# support the single arg sig
if arguments.length == 1
callback = files
files = null
# support the old (options, callback) sig
else if arguments.length < 3
[options, callback] = [files, options]
files = null
callback ?= ->
options ?= {}
files ?= ''
files = [files] if _.isString files
@git "ls-files", options, _.flatten(['--', files])
, (err, stdout, stderr) =>
return callback err if err
return callback null, @parse_lsFiles stdout,options
config: (callback) ->
return Config(this, callback)
# Public: Get the repository's tags.
#
# callback - Receives `(err, tags)`.
#
tags: (callback) ->
Tag.find_all this, callback
# Public: Create a tag.
#
# name - String
# options - An Object of command line arguments to pass to
# `git tag` (optional).
# callback - Receives `(err)`.
#
create_tag: (name, options, callback) ->
[options, callback] = [callback, options] if !callback
@git "tag", options, [name], callback
# Public: Delete the tag.
#
# name - String
# callback - Receives `(err)`.
#
delete_tag: (name, callback) ->
@git "tag", {d: name}, callback
# Public: Get a list of branches.
#
# callback - Receives `(err, heads)`.
#
branches: (callback) ->
Head.find_all this, callback
# Public: Create a branch with the given name.
#
# name - String name of the new branch.
# callback - Receives `(err)`.
#
create_branch: (name, callback) ->
@git "branch", {}, name, (err, stdout, stderr) ->
return callback err
# Public: Delete the branch with the given name.
#
# name - String name of the branch to delete.
# force - Force delete if true.
# callback - Receives `(err)`.
#
delete_branch: (name, force, callback) ->
[force, callback] = [false, force] if !callback
opts = {d: true}
opts = {D: true} if force
@git "branch", opts, name, (err, stdout, stderr) ->
return callback err
# Public: Get the Branch with the given name.
#
# name - String (optional). By default, get the current branch.
# callback - Receives `(err, head)`
#
branch: (name, callback) ->
[name, callback] = [callback, name] if !callback
if !name
Head.current this, callback
else
@branches (err, heads) ->
return callback err if err
for head in heads
return callback null, head if head.name == name
return callback new Error "No branch named '#{name}' found"
# Public: Checkout the treeish.
#
# options - The {Object} containing any of the options available to git checkout:
# :b - {Boolean) Creates a branch when it doesn't exist yet.
#
checkout: (treeish, options, callback) ->
[options, callback] = [{}, options] if !callback
@git "checkout", options, treeish, callback
# Public: Clean the git repo by removing untracked files
#
# options - The {Object} containing any of the options available to git clean:
# :force - {Boolean) In the default repo config, clean will not take effect unless this option is given.
# :d - {Boolean) also removes untracked directories
# :n - {Boolean) Dry run - don't actually delete, just report what would be deleted
# :quiet - {Boolean) only report errors
# callback - The {Function} to callback.
#
clean: (options, callback) ->
options ?= {}
@git "clean", options, callback
# Public: Reset the git repo.
#
# treeish - The {String} to reset to.
# options - The {Object} containing one of the following items:
# :soft - {Boolean)
# :mixed - {Boolean) When no other option given git defaults to 'mixed'.
# :hard - {Boolean)
# :merge - {Boolean)
# :keep - {Boolean)
# callback - The {Function} to callback.
#
reset: (treeish, options, callback) ->
[options, callback] = [callback, options] if !callback
[treeish, callback] = [callback, treeish] if !callback
[treeish, options] = [options, treeish] if typeof treeish is 'object'
treeish ?= 'HEAD'
options ?= {}
@git "reset", options, treeish, callback
# Public: Checkout file(s) to the index
#
# files - Array of String paths; or a String path. If you want to
# checkout all files pass '.'.'
# options - Object (optional).
# "force" - Boolean
# callback - Receives `(err)`.
#
checkoutFile: (files, options, callback) ->
[options, callback] = [callback, options] if !callback
[files, callback] = [callback, files] if !callback
[files, options] = [options, files] if typeof files is 'object'
options ?= {}
files ?= '.'
files = [files] if _.isString files
@git "checkout", options, _.flatten(['--', files]), callback
# Public: Commit some code.
#
# message - String
# options - Object (optional).
# "amend" - Boolean
# "all" - Boolean
# "author"- String formated like: A U Thor <author@example.com>
# callback - Receives `(err)`.
#
commit: (message, options, callback) ->
[options, callback] = [callback, options] if !callback
options ?= {}
options = _.extend options, {m: "\"#{message}\""}
# add quotes around author
options.author = "\"#{options.author}\"" if options.author?
@git "commit", options, callback
# Public: Add files to the index.
#
# files - Array of String paths; or a String path.
# options - Object (optional).
# "all" - Boolean
# callback - Receives `(err)`.
#
add: (files, options, callback) ->
[options, callback] = [callback, options] if !callback
options ?= {}
files = [files] if _.isString files
@git "add", options, files, callback
# Public: Remove files from the index.
#
# files - Array of String paths; or a String path.
# options - Object (optional).
# "recursive" - Boolean
# callback - Receives `(err)`.
#
remove: (files, options, callback) ->
[options, callback] = [callback, options] if !callback
options ?= {}
files = [files] if _.isString files
@git "rm", options, files, callback
# Public: Revert the given commit.
revert: (sha, callback) ->
@git "revert", {}, sha, callback
# Public: Sync the current branch with the remote.
#
# Arguments: ([[remote_name, ]branch_name, ]callback)
#
# remote_name - String (optional).
# branch_name - String.
# callback - Receives `(stderr)`.
#
sync: (remote_name, branch_name, callback) ->
# handle 'curried' arguments
[remote, branch] = [remote_name, branch_name] if typeof callback is "function"
[remote, branch, callback] = ["origin", remote_name, branch_name] if typeof branch_name is "function"
[remote, branch, callback] = ["origin", "master", remote_name] if typeof remote_name is "function"
@status (err, status) =>
return callback err if err
@git "stash", {}, ["save", "-u"], (err, stdout, stderr) =>
return callback stderr if err
@git "pull", {}, [remote, branch], (err, stdout, stderr) =>
return callback stderr if err
@git "push", {}, [remote, branch], (err, stdout, stderr) =>
return callback stderr if err
if not status?.clean
@git "stash", {}, ["pop"], (err, stdout, stderr) =>
return callback stderr if err
return callback null
else
return callback null
# Public: Pull the remotes from the master.
#
# Arguments: ([[remote_name, ]branch_name, ]callback)
#
# remote_name - String (optional).
# branch_name - String.
# callback - Receives `(stderr)`.
#
pull: (remote_name, branch_name, callback) ->
# handle 'curried' arguments
[remote, branch] = [remote_name, branch_name] if typeof callback is "function"
[remote, branch, callback] = ["origin", remote_name, branch_name] if typeof branch_name is "function"
[remote, branch, callback] = ["origin", "master", remote_name] if typeof remote_name is "function"
@status (err, status) =>
return callback err if err
@git "pull", {}, [remote, branch], (err, stdout, stderr) =>
return callback stderr if err
return callback null
# Internal: Parse the list of files from `git ls-files`
#
# Return Files[]
parse_lsFiles: (text,options) ->
files = []
if _.has(options,'z')
lines = text.split "\0"
else
lines = text.split "\n"
while lines.length
line = lines.shift().split(" ")
files.push line
while lines[0]? && !lines[0].length
lines.shift()
return files
| 216954 | _ = require 'underscore'
cmd = require './git'
Actor = require './actor'
Commit = require './commit'
Config = require './config'
Tree = require './tree'
Diff = require './diff'
Tag = require './tag'
Status = require './status'
{Ref, Head} = require './ref'
module.exports = class Repo
constructor: (@path, @bare, @git_options) ->
if @bare
@dot_git = @path
else
@dot_git = "#{@path}/.git"
@git = cmd @path, @dot_git, @git_options
# Public: Get the commit identity for this repository.
#
# callback - Receives `(err, actor)`, where `actor` is an Actor.
#
identity: (callback) ->
# git config user.email
@git "config", {}, ["user.email"]
, (err, stdout = '') =>
return callback err if err
email = stdout?.trim()
# git config user.name
@git "config", {}, ["user.name"]
, (err, stdout = '') =>
return callback err if err
name = stdout?.trim()
return callback null, new Actor(name, email)
# Public: Set your account's default identity for commits.
#
# actor - An instance of Actor.
# callback - Receives `(err)`.
#
identify: (actor, callback) ->
# git config user.email "<EMAIL>"
@git "config", {}, ["user.email", "\"#{actor.email}\""], (err) =>
return callback err if err
# git config user.name "<NAME>"
@git "config", {}, ["user.name", "\"#{actor.name}\""], (err) =>
return callback err if err
return callback null
# Public: Get a list of commits.
#
# treeish - String (optional).
# limit - Integer (optional).
# skip - Integer (optional).
# callback - Function which receives `(err, commits)`, where `commits` is
# an Array of Commits.
#
# Examples
#
# # Get the 10 most recent commits to master.
# repo.commits (err, commits) ->
#
# # Or to a different tag or branch.
# repo.commits "v0.0.3", (err, commits) ->
#
# # Limit the maximum number of commits returned.
# repo.commits "master", 30, (err, commits) ->
#
# # Skip some (for pagination):
# repo.commits "master", 30, 30, (err, commits) ->
#
# # Do not limit commits amount
# repo.commits "master", -1, (err, commits) ->
#
commits: (start, limit, skip, callback) ->
[skip, callback] = [callback, skip] if !callback
[limit, callback] = [callback, limit] if !callback
[start, callback] = [callback, start] if !callback
throw new Error "a callback is required" if !callback
start ?= "master"
limit ?= 10
skip ?= 0
options = {skip}
if limit != -1
options["max-count"] = limit
Commit.find_all this, start, options, callback
# Internal: Returns current commit id
#
# callback - Receives `(err, id)`.
#
current_commit_id: (callback) ->
@git "rev-parse HEAD", {}, []
, (err, stdout, stderr) =>
return callback err if err
return callback null, _.first stdout.split "\n"
# Public:
#
# callback - Receives `(err, commit)`
#
current_commit: (callback) ->
@current_commit_id (err, commit_id) =>
return callback err if err
Commit.find this, commit_id, callback
# Public: The tree object for the treeish or master.
#
# treeish - String treeish (such as a branch or tag) (optional).
#
# Returns Tree.
tree: (treeish="master") ->
return new Tree this, treeish
# Public: Get the difference between the trees.
#
# commitA - A Commit or String commit id.
# commitB - A Commit or String commit id.
# paths - A list of String paths to restrict the difference to (optional).
# options - An object of options to pass to git diff (optional)
# callback - A Function which receives `(err, diffs)`.
#
# Possible forms of the method:
#
# diff(commitA, commitB, callback)
# diff(commitA, commitB, paths, callback)
# diff(commitA, commitB, options, callback)
# diff(commitA, commitB, paths, options, callback)
#
diff: (commitA, commitB) ->
[paths, options] = [[], {}]
if arguments.length is 3
callback = arguments[2]
else if arguments.length is 4
callback = arguments[3]
if arguments[2] instanceof Array
paths = arguments[2]
else if arguments[2] instanceof Object
options = arguments[2]
else if arguments.length is 5
[paths, options, callback] = Array.prototype.slice.call(arguments, 2)
commitA = commitA.id if _.isObject(commitA)
commitB = commitB.id if _.isObject(commitB)
@git "diff", options, _.flatten([commitA, commitB, "--", paths])
, (err, stdout, stderr) =>
return callback err if err
if _.has(options, 'raw')
return callback err, Diff.parse_raw(this, stdout)
else
return callback err, Diff.parse(this, stdout)
, 'binary'
# Public: Get the repository's remotes.
#
# callback - Receives `(err, remotes)`.
#
remotes: (callback) ->
Ref.find_all this, "remote", Ref, callback
# Public: List the repository's remotes.
#
# callback - Receives `(err, names)`.
#
remote_list: (callback) ->
@git.list_remotes callback
# Public: Add a remote.
#
# name - String name of the remote.
# url - String url of the remote.
# callback - Receives `(err)`
#
remote_add: (name, url, callback) ->
@git "remote", {}, ["add", name, url]
, (err, stdout, stderr) ->
callback err
# Public: Remove a remote.
#
# name - String name of the remote.
# callback - Receives `(err)`
#
remote_remove: (name, callback) ->
@git "remote", {}, ["rm", name]
, (err, stdout, stderr) ->
callback err
# Public: Add a remote URL.
#
# name - String name of the remote.
# url - String url of the remote.
# callback - Receives `(err)`
#
remote_add_url: (name, url, callback) ->
@git "remote set-url", {}, ["--add", name, url]
, (err, stdout, stderr) ->
callback err
# Public: Set a remote URL.
#
# name - String name of the remote.
# url - String url to set in the remote.
# callback - Receives `(err)`.
#
remote_set_url: (name, url, callback) ->
@git "remote set-url", {}, [name, url]
, (err, stdout, stderr) ->
callback err
# Public: Delete a remote URL.
#
# name - String name of the remote.
# url - String url of the remote.
# callback - Receives `(err)`
#
remote_delete_url: (name, url, callback) ->
@git "remote set-url", {}, ["--delete", name, url]
, (err, stdout, stderr) ->
callback err
# Public: `git fetch <name>`.
#
# name - String name of the remote
# callback - Receives `(err)`.
#
remote_fetch: (name, options, callback) ->
[options, callback] = [callback, options] if !callback
@git "fetch", options, name
, (err, stdout, stderr) ->
callback err
# Public: `git push <name>`.
#
# name - String name of the remote
# branch - (optional) Branch to push
# callback - Receives `(err)`.
#
remote_push: (name, branch, options, callback) ->
if !options && !callback
callback = branch
args = name
options = {}
else
if !callback
callback = options
options = {}
args = [name, branch]
@git "push", options, args
, (err, stdout, stderr) ->
callback err
# Public: `git merge <name>`.
#
# name - String name of the source
# callback - Receives `(err)`.
#
merge: (name, options, callback) ->
[options, callback] = [callback, options] if !callback
@git "merge", options, name
, (err, stdout, stderr) ->
callback err
# Public: Get the repository's status (`git status`).
#
# callback - Receives `(err, status)`
#
status: (options, callback) ->
[options, callback] = [callback, options] if !callback;
return Status(this, options, callback)
# Public: Show information about files in the index and the
# working tree.
#
# files - Array of String paths; or a String path (optional).
# options - An Object of command line arguments to pass to
# `git ls-files`.
# callback - Receives `(err,stdout)`.
#
ls_files: (files, options, callback) ->
# support the single arg sig
if arguments.length == 1
callback = files
files = null
# support the old (options, callback) sig
else if arguments.length < 3
[options, callback] = [files, options]
files = null
callback ?= ->
options ?= {}
files ?= ''
files = [files] if _.isString files
@git "ls-files", options, _.flatten(['--', files])
, (err, stdout, stderr) =>
return callback err if err
return callback null, @parse_lsFiles stdout,options
config: (callback) ->
return Config(this, callback)
# Public: Get the repository's tags.
#
# callback - Receives `(err, tags)`.
#
tags: (callback) ->
Tag.find_all this, callback
# Public: Create a tag.
#
# name - String
# options - An Object of command line arguments to pass to
# `git tag` (optional).
# callback - Receives `(err)`.
#
create_tag: (name, options, callback) ->
[options, callback] = [callback, options] if !callback
@git "tag", options, [name], callback
# Public: Delete the tag.
#
# name - String
# callback - Receives `(err)`.
#
delete_tag: (name, callback) ->
@git "tag", {d: name}, callback
# Public: Get a list of branches.
#
# callback - Receives `(err, heads)`.
#
branches: (callback) ->
Head.find_all this, callback
# Public: Create a branch with the given name.
#
# name - String name of the new branch.
# callback - Receives `(err)`.
#
create_branch: (name, callback) ->
@git "branch", {}, name, (err, stdout, stderr) ->
return callback err
# Public: Delete the branch with the given name.
#
# name - String name of the branch to delete.
# force - Force delete if true.
# callback - Receives `(err)`.
#
delete_branch: (name, force, callback) ->
[force, callback] = [false, force] if !callback
opts = {d: true}
opts = {D: true} if force
@git "branch", opts, name, (err, stdout, stderr) ->
return callback err
# Public: Get the Branch with the given name.
#
# name - String (optional). By default, get the current branch.
# callback - Receives `(err, head)`
#
branch: (name, callback) ->
[name, callback] = [callback, name] if !callback
if !name
Head.current this, callback
else
@branches (err, heads) ->
return callback err if err
for head in heads
return callback null, head if head.name == name
return callback new Error "No branch named '#{name}' found"
# Public: Checkout the treeish.
#
# options - The {Object} containing any of the options available to git checkout:
# :b - {Boolean) Creates a branch when it doesn't exist yet.
#
checkout: (treeish, options, callback) ->
[options, callback] = [{}, options] if !callback
@git "checkout", options, treeish, callback
# Public: Clean the git repo by removing untracked files
#
# options - The {Object} containing any of the options available to git clean:
# :force - {Boolean) In the default repo config, clean will not take effect unless this option is given.
# :d - {Boolean) also removes untracked directories
# :n - {Boolean) Dry run - don't actually delete, just report what would be deleted
# :quiet - {Boolean) only report errors
# callback - The {Function} to callback.
#
clean: (options, callback) ->
options ?= {}
@git "clean", options, callback
# Public: Reset the git repo.
#
# treeish - The {String} to reset to.
# options - The {Object} containing one of the following items:
# :soft - {Boolean)
# :mixed - {Boolean) When no other option given git defaults to 'mixed'.
# :hard - {Boolean)
# :merge - {Boolean)
# :keep - {Boolean)
# callback - The {Function} to callback.
#
reset: (treeish, options, callback) ->
[options, callback] = [callback, options] if !callback
[treeish, callback] = [callback, treeish] if !callback
[treeish, options] = [options, treeish] if typeof treeish is 'object'
treeish ?= 'HEAD'
options ?= {}
@git "reset", options, treeish, callback
# Public: Checkout file(s) to the index
#
# files - Array of String paths; or a String path. If you want to
# checkout all files pass '.'.'
# options - Object (optional).
# "force" - Boolean
# callback - Receives `(err)`.
#
checkoutFile: (files, options, callback) ->
[options, callback] = [callback, options] if !callback
[files, callback] = [callback, files] if !callback
[files, options] = [options, files] if typeof files is 'object'
options ?= {}
files ?= '.'
files = [files] if _.isString files
@git "checkout", options, _.flatten(['--', files]), callback
# Public: Commit some code.
#
# message - String
# options - Object (optional).
# "amend" - Boolean
# "all" - Boolean
# "author"- String formated like: <NAME> <<EMAIL>>
# callback - Receives `(err)`.
#
commit: (message, options, callback) ->
[options, callback] = [callback, options] if !callback
options ?= {}
options = _.extend options, {m: "\"#{message}\""}
# add quotes around author
options.author = "\"#{options.author}\"" if options.author?
@git "commit", options, callback
# Public: Add files to the index.
#
# files - Array of String paths; or a String path.
# options - Object (optional).
# "all" - Boolean
# callback - Receives `(err)`.
#
add: (files, options, callback) ->
[options, callback] = [callback, options] if !callback
options ?= {}
files = [files] if _.isString files
@git "add", options, files, callback
# Public: Remove files from the index.
#
# files - Array of String paths; or a String path.
# options - Object (optional).
# "recursive" - Boolean
# callback - Receives `(err)`.
#
remove: (files, options, callback) ->
[options, callback] = [callback, options] if !callback
options ?= {}
files = [files] if _.isString files
@git "rm", options, files, callback
# Public: Revert the given commit.
revert: (sha, callback) ->
@git "revert", {}, sha, callback
# Public: Sync the current branch with the remote.
#
# Arguments: ([[remote_name, ]branch_name, ]callback)
#
# remote_name - String (optional).
# branch_name - String.
# callback - Receives `(stderr)`.
#
sync: (remote_name, branch_name, callback) ->
# handle 'curried' arguments
[remote, branch] = [remote_name, branch_name] if typeof callback is "function"
[remote, branch, callback] = ["origin", remote_name, branch_name] if typeof branch_name is "function"
[remote, branch, callback] = ["origin", "master", remote_name] if typeof remote_name is "function"
@status (err, status) =>
return callback err if err
@git "stash", {}, ["save", "-u"], (err, stdout, stderr) =>
return callback stderr if err
@git "pull", {}, [remote, branch], (err, stdout, stderr) =>
return callback stderr if err
@git "push", {}, [remote, branch], (err, stdout, stderr) =>
return callback stderr if err
if not status?.clean
@git "stash", {}, ["pop"], (err, stdout, stderr) =>
return callback stderr if err
return callback null
else
return callback null
# Public: Pull the remotes from the master.
#
# Arguments: ([[remote_name, ]branch_name, ]callback)
#
# remote_name - String (optional).
# branch_name - String.
# callback - Receives `(stderr)`.
#
pull: (remote_name, branch_name, callback) ->
# handle 'curried' arguments
[remote, branch] = [remote_name, branch_name] if typeof callback is "function"
[remote, branch, callback] = ["origin", remote_name, branch_name] if typeof branch_name is "function"
[remote, branch, callback] = ["origin", "master", remote_name] if typeof remote_name is "function"
@status (err, status) =>
return callback err if err
@git "pull", {}, [remote, branch], (err, stdout, stderr) =>
return callback stderr if err
return callback null
# Internal: Parse the list of files from `git ls-files`
#
# Return Files[]
parse_lsFiles: (text,options) ->
files = []
if _.has(options,'z')
lines = text.split "\0"
else
lines = text.split "\n"
while lines.length
line = lines.shift().split(" ")
files.push line
while lines[0]? && !lines[0].length
lines.shift()
return files
| true | _ = require 'underscore'
cmd = require './git'
Actor = require './actor'
Commit = require './commit'
Config = require './config'
Tree = require './tree'
Diff = require './diff'
Tag = require './tag'
Status = require './status'
{Ref, Head} = require './ref'
module.exports = class Repo
constructor: (@path, @bare, @git_options) ->
if @bare
@dot_git = @path
else
@dot_git = "#{@path}/.git"
@git = cmd @path, @dot_git, @git_options
# Public: Get the commit identity for this repository.
#
# callback - Receives `(err, actor)`, where `actor` is an Actor.
#
identity: (callback) ->
# git config user.email
@git "config", {}, ["user.email"]
, (err, stdout = '') =>
return callback err if err
email = stdout?.trim()
# git config user.name
@git "config", {}, ["user.name"]
, (err, stdout = '') =>
return callback err if err
name = stdout?.trim()
return callback null, new Actor(name, email)
# Public: Set your account's default identity for commits.
#
# actor - An instance of Actor.
# callback - Receives `(err)`.
#
identify: (actor, callback) ->
# git config user.email "PI:EMAIL:<EMAIL>END_PI"
@git "config", {}, ["user.email", "\"#{actor.email}\""], (err) =>
return callback err if err
# git config user.name "PI:NAME:<NAME>END_PI"
@git "config", {}, ["user.name", "\"#{actor.name}\""], (err) =>
return callback err if err
return callback null
# Public: Get a list of commits.
#
# treeish - String (optional).
# limit - Integer (optional).
# skip - Integer (optional).
# callback - Function which receives `(err, commits)`, where `commits` is
# an Array of Commits.
#
# Examples
#
# # Get the 10 most recent commits to master.
# repo.commits (err, commits) ->
#
# # Or to a different tag or branch.
# repo.commits "v0.0.3", (err, commits) ->
#
# # Limit the maximum number of commits returned.
# repo.commits "master", 30, (err, commits) ->
#
# # Skip some (for pagination):
# repo.commits "master", 30, 30, (err, commits) ->
#
# # Do not limit commits amount
# repo.commits "master", -1, (err, commits) ->
#
commits: (start, limit, skip, callback) ->
[skip, callback] = [callback, skip] if !callback
[limit, callback] = [callback, limit] if !callback
[start, callback] = [callback, start] if !callback
throw new Error "a callback is required" if !callback
start ?= "master"
limit ?= 10
skip ?= 0
options = {skip}
if limit != -1
options["max-count"] = limit
Commit.find_all this, start, options, callback
# Internal: Returns current commit id
#
# callback - Receives `(err, id)`.
#
current_commit_id: (callback) ->
@git "rev-parse HEAD", {}, []
, (err, stdout, stderr) =>
return callback err if err
return callback null, _.first stdout.split "\n"
# Public:
#
# callback - Receives `(err, commit)`
#
current_commit: (callback) ->
@current_commit_id (err, commit_id) =>
return callback err if err
Commit.find this, commit_id, callback
# Public: The tree object for the treeish or master.
#
# treeish - String treeish (such as a branch or tag) (optional).
#
# Returns Tree.
tree: (treeish="master") ->
return new Tree this, treeish
# Public: Get the difference between the trees.
#
# commitA - A Commit or String commit id.
# commitB - A Commit or String commit id.
# paths - A list of String paths to restrict the difference to (optional).
# options - An object of options to pass to git diff (optional)
# callback - A Function which receives `(err, diffs)`.
#
# Possible forms of the method:
#
# diff(commitA, commitB, callback)
# diff(commitA, commitB, paths, callback)
# diff(commitA, commitB, options, callback)
# diff(commitA, commitB, paths, options, callback)
#
diff: (commitA, commitB) ->
[paths, options] = [[], {}]
if arguments.length is 3
callback = arguments[2]
else if arguments.length is 4
callback = arguments[3]
if arguments[2] instanceof Array
paths = arguments[2]
else if arguments[2] instanceof Object
options = arguments[2]
else if arguments.length is 5
[paths, options, callback] = Array.prototype.slice.call(arguments, 2)
commitA = commitA.id if _.isObject(commitA)
commitB = commitB.id if _.isObject(commitB)
@git "diff", options, _.flatten([commitA, commitB, "--", paths])
, (err, stdout, stderr) =>
return callback err if err
if _.has(options, 'raw')
return callback err, Diff.parse_raw(this, stdout)
else
return callback err, Diff.parse(this, stdout)
, 'binary'
# Public: Get the repository's remotes.
#
# callback - Receives `(err, remotes)`.
#
remotes: (callback) ->
Ref.find_all this, "remote", Ref, callback
# Public: List the repository's remotes.
#
# callback - Receives `(err, names)`.
#
remote_list: (callback) ->
@git.list_remotes callback
# Public: Add a remote.
#
# name - String name of the remote.
# url - String url of the remote.
# callback - Receives `(err)`
#
remote_add: (name, url, callback) ->
@git "remote", {}, ["add", name, url]
, (err, stdout, stderr) ->
callback err
# Public: Remove a remote.
#
# name - String name of the remote.
# callback - Receives `(err)`
#
remote_remove: (name, callback) ->
@git "remote", {}, ["rm", name]
, (err, stdout, stderr) ->
callback err
# Public: Add a remote URL.
#
# name - String name of the remote.
# url - String url of the remote.
# callback - Receives `(err)`
#
remote_add_url: (name, url, callback) ->
@git "remote set-url", {}, ["--add", name, url]
, (err, stdout, stderr) ->
callback err
# Public: Set a remote URL.
#
# name - String name of the remote.
# url - String url to set in the remote.
# callback - Receives `(err)`.
#
remote_set_url: (name, url, callback) ->
@git "remote set-url", {}, [name, url]
, (err, stdout, stderr) ->
callback err
# Public: Delete a remote URL.
#
# name - String name of the remote.
# url - String url of the remote.
# callback - Receives `(err)`
#
remote_delete_url: (name, url, callback) ->
@git "remote set-url", {}, ["--delete", name, url]
, (err, stdout, stderr) ->
callback err
# Public: `git fetch <name>`.
#
# name - String name of the remote
# callback - Receives `(err)`.
#
remote_fetch: (name, options, callback) ->
[options, callback] = [callback, options] if !callback
@git "fetch", options, name
, (err, stdout, stderr) ->
callback err
# Public: `git push <name>`.
#
# name - String name of the remote
# branch - (optional) Branch to push
# callback - Receives `(err)`.
#
remote_push: (name, branch, options, callback) ->
if !options && !callback
callback = branch
args = name
options = {}
else
if !callback
callback = options
options = {}
args = [name, branch]
@git "push", options, args
, (err, stdout, stderr) ->
callback err
# Public: `git merge <name>`.
#
# name - String name of the source
# callback - Receives `(err)`.
#
merge: (name, options, callback) ->
[options, callback] = [callback, options] if !callback
@git "merge", options, name
, (err, stdout, stderr) ->
callback err
# Public: Get the repository's status (`git status`).
#
# callback - Receives `(err, status)`
#
status: (options, callback) ->
[options, callback] = [callback, options] if !callback;
return Status(this, options, callback)
# Public: Show information about files in the index and the
# working tree.
#
# files - Array of String paths; or a String path (optional).
# options - An Object of command line arguments to pass to
# `git ls-files`.
# callback - Receives `(err,stdout)`.
#
ls_files: (files, options, callback) ->
# support the single arg sig
if arguments.length == 1
callback = files
files = null
# support the old (options, callback) sig
else if arguments.length < 3
[options, callback] = [files, options]
files = null
callback ?= ->
options ?= {}
files ?= ''
files = [files] if _.isString files
@git "ls-files", options, _.flatten(['--', files])
, (err, stdout, stderr) =>
return callback err if err
return callback null, @parse_lsFiles stdout,options
config: (callback) ->
return Config(this, callback)
# Public: Get the repository's tags.
#
# callback - Receives `(err, tags)`.
#
tags: (callback) ->
Tag.find_all this, callback
# Public: Create a tag.
#
# name - String
# options - An Object of command line arguments to pass to
# `git tag` (optional).
# callback - Receives `(err)`.
#
create_tag: (name, options, callback) ->
[options, callback] = [callback, options] if !callback
@git "tag", options, [name], callback
# Public: Delete the tag.
#
# name - String
# callback - Receives `(err)`.
#
delete_tag: (name, callback) ->
@git "tag", {d: name}, callback
# Public: Get a list of branches.
#
# callback - Receives `(err, heads)`.
#
branches: (callback) ->
Head.find_all this, callback
# Public: Create a branch with the given name.
#
# name - String name of the new branch.
# callback - Receives `(err)`.
#
create_branch: (name, callback) ->
@git "branch", {}, name, (err, stdout, stderr) ->
return callback err
# Public: Delete the branch with the given name.
#
# name - String name of the branch to delete.
# force - Force delete if true.
# callback - Receives `(err)`.
#
delete_branch: (name, force, callback) ->
[force, callback] = [false, force] if !callback
opts = {d: true}
opts = {D: true} if force
@git "branch", opts, name, (err, stdout, stderr) ->
return callback err
# Public: Get the Branch with the given name.
#
# name - String (optional). By default, get the current branch.
# callback - Receives `(err, head)`
#
branch: (name, callback) ->
[name, callback] = [callback, name] if !callback
if !name
Head.current this, callback
else
@branches (err, heads) ->
return callback err if err
for head in heads
return callback null, head if head.name == name
return callback new Error "No branch named '#{name}' found"
# Public: Checkout the treeish.
#
# options - The {Object} containing any of the options available to git checkout:
# :b - {Boolean) Creates a branch when it doesn't exist yet.
#
checkout: (treeish, options, callback) ->
[options, callback] = [{}, options] if !callback
@git "checkout", options, treeish, callback
# Public: Clean the git repo by removing untracked files
#
# options - The {Object} containing any of the options available to git clean:
# :force - {Boolean) In the default repo config, clean will not take effect unless this option is given.
# :d - {Boolean) also removes untracked directories
# :n - {Boolean) Dry run - don't actually delete, just report what would be deleted
# :quiet - {Boolean) only report errors
# callback - The {Function} to callback.
#
clean: (options, callback) ->
options ?= {}
@git "clean", options, callback
# Public: Reset the git repo.
#
# treeish - The {String} to reset to.
# options - The {Object} containing one of the following items:
# :soft - {Boolean)
# :mixed - {Boolean) When no other option given git defaults to 'mixed'.
# :hard - {Boolean)
# :merge - {Boolean)
# :keep - {Boolean)
# callback - The {Function} to callback.
#
reset: (treeish, options, callback) ->
[options, callback] = [callback, options] if !callback
[treeish, callback] = [callback, treeish] if !callback
[treeish, options] = [options, treeish] if typeof treeish is 'object'
treeish ?= 'HEAD'
options ?= {}
@git "reset", options, treeish, callback
# Public: Checkout file(s) to the index
#
# files - Array of String paths; or a String path. If you want to
# checkout all files pass '.'.'
# options - Object (optional).
# "force" - Boolean
# callback - Receives `(err)`.
#
checkoutFile: (files, options, callback) ->
[options, callback] = [callback, options] if !callback
[files, callback] = [callback, files] if !callback
[files, options] = [options, files] if typeof files is 'object'
options ?= {}
files ?= '.'
files = [files] if _.isString files
@git "checkout", options, _.flatten(['--', files]), callback
# Public: Commit some code.
#
# message - String
# options - Object (optional).
# "amend" - Boolean
# "all" - Boolean
# "author"- String formated like: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# callback - Receives `(err)`.
#
commit: (message, options, callback) ->
[options, callback] = [callback, options] if !callback
options ?= {}
options = _.extend options, {m: "\"#{message}\""}
# add quotes around author
options.author = "\"#{options.author}\"" if options.author?
@git "commit", options, callback
# Public: Add files to the index.
#
# files - Array of String paths; or a String path.
# options - Object (optional).
# "all" - Boolean
# callback - Receives `(err)`.
#
add: (files, options, callback) ->
[options, callback] = [callback, options] if !callback
options ?= {}
files = [files] if _.isString files
@git "add", options, files, callback
# Public: Remove files from the index.
#
# files - Array of String paths; or a String path.
# options - Object (optional).
# "recursive" - Boolean
# callback - Receives `(err)`.
#
remove: (files, options, callback) ->
[options, callback] = [callback, options] if !callback
options ?= {}
files = [files] if _.isString files
@git "rm", options, files, callback
# Public: Revert the given commit.
revert: (sha, callback) ->
@git "revert", {}, sha, callback
# Public: Sync the current branch with the remote.
#
# Arguments: ([[remote_name, ]branch_name, ]callback)
#
# remote_name - String (optional).
# branch_name - String.
# callback - Receives `(stderr)`.
#
sync: (remote_name, branch_name, callback) ->
# handle 'curried' arguments
[remote, branch] = [remote_name, branch_name] if typeof callback is "function"
[remote, branch, callback] = ["origin", remote_name, branch_name] if typeof branch_name is "function"
[remote, branch, callback] = ["origin", "master", remote_name] if typeof remote_name is "function"
@status (err, status) =>
return callback err if err
@git "stash", {}, ["save", "-u"], (err, stdout, stderr) =>
return callback stderr if err
@git "pull", {}, [remote, branch], (err, stdout, stderr) =>
return callback stderr if err
@git "push", {}, [remote, branch], (err, stdout, stderr) =>
return callback stderr if err
if not status?.clean
@git "stash", {}, ["pop"], (err, stdout, stderr) =>
return callback stderr if err
return callback null
else
return callback null
# Public: Pull the remotes from the master.
#
# Arguments: ([[remote_name, ]branch_name, ]callback)
#
# remote_name - String (optional).
# branch_name - String.
# callback - Receives `(stderr)`.
#
pull: (remote_name, branch_name, callback) ->
# handle 'curried' arguments
[remote, branch] = [remote_name, branch_name] if typeof callback is "function"
[remote, branch, callback] = ["origin", remote_name, branch_name] if typeof branch_name is "function"
[remote, branch, callback] = ["origin", "master", remote_name] if typeof remote_name is "function"
@status (err, status) =>
return callback err if err
@git "pull", {}, [remote, branch], (err, stdout, stderr) =>
return callback stderr if err
return callback null
# Internal: Parse the list of files from `git ls-files`
#
# Return Files[]
parse_lsFiles: (text,options) ->
files = []
if _.has(options,'z')
lines = text.split "\0"
else
lines = text.split "\n"
while lines.length
line = lines.shift().split(" ")
files.push line
while lines[0]? && !lines[0].length
lines.shift()
return files
|
[
{
"context": "ce.org/licenses/mit-license.php) license.\n\n@author Sebastian Helzle (sebastian@helzle.net)\n###\n\n(((factory) ->\n if t",
"end": 218,
"score": 0.9998744130134583,
"start": 202,
"tag": "NAME",
"value": "Sebastian Helzle"
},
{
"context": "-license.php) license.\n\n@au... | src/coffee/jquery.smallipop.coffee | Sebobo/jquery.smallipop | 15 | ###!
Smallipop (02/27/2015)
Copyright (c) 2011-2015 Small Improvements (http://www.small-improvements.com)
Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
@author Sebastian Helzle (sebastian@helzle.net)
###
(((factory) ->
if typeof define is 'function' and define.amd
define ['jquery'], factory
else
factory jQuery
)(($) ->
# CSS classes
classBase = 'smallipop'
classHint = classBase + '-hint'
classInstance = classBase + '-instance'
classContent = classBase + '-content'
classLeft = classBase + '-left'
classRight = classBase + '-right'
classBottom = classBase + '-bottom'
classAlignLeft = classBase + '-align-left'
classAlignRight = classBase + '-align-right'
classInitialized = classBase + '-initialized'
classTheme = classBase + '-theme-'
classTour = classBase + '-tour'
classTourContent = classTour + '-content'
classTourOverlay = classTour + '-overlay'
classTourFooter = classTour + '-footer'
classTourCloseIcon = classTour + '-close-icon'
classTourProgress = classTour + '-progress'
classTourClose = classTour + '-close'
classTourPrev = classTour + '-prev'
classTourNext = classTour + '-next'
# Event names
eventFocus = 'focus.' + classBase
eventClick = 'click.' + classBase
eventBlur = 'blur.' + classBase
eventMouseOut = 'mouseout.' + classBase
eventMouseOver = 'mouseover.' + classBase
eventTouchEnd = 'touchend.' + classBase
eventResize = 'resize.' + classBase
eventScroll = 'scroll.' + classBase
eventKeyUp = 'keyup.' + classBase
# Data names
dataZIndex = classBase + 'OriginalZIndex'
dataBeingShown = classBase + 'BeingShown'
dataTimerHide = classBase + 'HideDelayTimer'
dataTimerShow = classBase + 'ShowDelayTimer'
dataTriggerHovered = classBase + 'TriggerHovered'
dataPopupHovered = classBase + 'PopupHovered'
dataShown = classBase + 'Shown'
dataPosition = classBase + 'Position'
dataXDistance = classBase + 'XDistance'
dataYDistance = classBase + 'YDistance'
dataIsTour = classBase + 'IsTour'
# Regular expressions
reAlignmentClass = new RegExp classBase + '-(align|bottom)\w*', "g"
reBaseClass = new RegExp classBase + '\w+', "g"
# Global elements
$document = $ document
$window = $ window
$overlay = null
instances = {}
# Tour vars
tours = {}
currentTour = null
# Id vars
lastId = 1 # Counter for new smallipop id's
nextInstanceId = 1 # Counter for new smallipop container id's
# Timing vars
scrollTimer = null
lastScrollCheck = 0
refreshQueueTimer = null
# Templates
popupTemplate = "<div class='#{classInstance}'><div class='#{classContent}'/></div>"
$.smallipop = sip =
version: '0.6.4'
defaults:
autoscrollPadding: 200
contentAnimationSpeed: 150
cssAnimations:
enabled: false
show: 'animated fadeIn'
hide: 'animated fadeOut'
funcEase: 'easeInOutQuad'
handleInputs: true
hideDelay: 500
hideTrigger: false
hideOnPopupClick: true
hideOnTriggerClick: true
infoClass: classHint
invertAnimation: false
popupId: ''
popupOffset: 31
popupYOffset: 0
popupDistance: 20
popupDelay: 100
popupAnimationSpeed: 200
preferredPosition: 'top' # bottom, top, left or right
referencedContent: null
theme: 'default'
touchSupport: true
tourHighlight: false
tourHighlightColor: '#222'
tourHighlightFadeDuration: 200
tourHighlightOpacity: .5
tourHighlightZIndex: 9997
tourNavigationEnabled: true
triggerAnimationSpeed: 150
triggerOnClick: false
onAfterHide: null
onAfterShow: null
onBeforeHide: null
onBeforeShow: null
onTourClose: null
onTourNext: null
onTourPrev: null
windowPadding: 30 # Imaginary padding in viewport
labels:
prev: 'Prev'
next: 'Next'
close: 'Close'
of: 'of'
# Add default easing function for smallipop to jQuery if missing
unless $.easing.easeInOutQuad
$.easing.easeInOutQuad = (x, t, b, c, d) ->
if ((t/=d/2) < 1) then c/2*t*t + b else -c/2 * ((--t)*(t-2) - 1) + b
# Reset z-index for all other triggers in tours
resetTourZIndices = ->
for tour, steps of tours
for step in steps
tourTrigger = step.trigger
if tourTrigger.data dataZIndex
tourTrigger.css 'zIndex', tourTrigger.data(dataZIndex)
touchEnabled = Modernizr?.touch
cssAnimationsEnabled = Modernizr?.cssanimations
getTrigger = (id) ->
$ ".#{classBase + id}"
# Returns the overlay and creates it if necessary
getOverlay = ->
unless $overlay
$overlay = $("<div id='#{classTourOverlay}'/>").appendTo($('body')).fadeOut 0
$overlay
hideTourOverlay = (options) ->
getOverlay().fadeOut options.tourHighlightFadeDuration
resetTourZIndices()
hideSmallipop = (e) ->
clearTimeout scrollTimer
target = if e?.target then $(e.target) else e
for popupId, popup of instances
popupData = popup.data()
continue unless shownId = popupData[dataShown]
trigger = getTrigger shownId
triggerIsTarget = trigger.is target
triggerData = trigger.data(classBase)
triggerOptions = triggerData.options or sip.defaults
continue if (popupData[dataIsTour] or triggerData.isFormElement) \
and not popup.is(target) \
and not (triggerIsTarget and popup.is(triggerOptions.popupInstance))
# Fire close callback
if popupData[dataIsTour]
currentTour = null
trigger.data(classBase)?.options.onTourClose?()
hideTourOverlay triggerOptions
# Do nothing if clicked and hide on click is disabled for this case
ignoreTriggerClick = not triggerOptions.hideOnTriggerClick and triggerIsTarget
ignorePopupClick = not triggerOptions.hideOnPopupClick \
and popup.find(target).length
continue if target and trigger.length and e?.type in ['click', 'touchend'] \
and (ignoreTriggerClick or ignorePopupClick)
# Show trigger if it was hidden
if shownId and triggerOptions.hideTrigger
trigger.stop(true).fadeTo triggerOptions.triggerAnimationSpeed, 1
popup
.data(dataTimerHide, null)
.data(dataBeingShown, false)
if triggerOptions.cssAnimations.enabled
popup
.removeClass(triggerOptions.cssAnimations.show)
.addClass(triggerOptions.cssAnimations.hide)
.data dataShown, ''
if triggerOptions.onAfterHide
window.setTimeout triggerOptions.onAfterHide, triggerOptions.popupAnimationSpeed
else
direction = if triggerOptions.invertAnimation then -1 else 1
xDistance = popupData[dataXDistance] * direction
yDistance = popupData[dataYDistance] * direction
popup
.stop(true)
.animate
top: "-=#{yDistance}"
left: "+=#{xDistance}"
opacity: 0
, triggerOptions.popupAnimationSpeed, triggerOptions.funcEase, ->
# Hide tip if not being shown in the meantime
self = $ @
unless self.data dataBeingShown
self
.css('display', 'none')
.data(dataShown, '')
triggerOptions.onAfterHide?()
showSmallipop= (e) ->
triggerData = $(@).data classBase
return unless triggerData
if triggerData.popupInstance.data(dataShown) isnt triggerData.id \
and not triggerData.type in ['checkbox', 'radio']
e?.preventDefault()
triggerMouseover.call @
killTimers = (popup) ->
clearTimeout popup.data(dataTimerHide)
clearTimeout popup.data(dataTimerShow)
# Queue a refresh to the popups position
queueRefreshPosition = (delay=50) ->
clearTimeout refreshQueueTimer
refreshQueueTimer = setTimeout refreshPosition, delay
# Class filtering helpers
filterClass = (classStr, re) ->
if classStr then (classStr.match(re) or []).join ' '
filterAlignmentClass = (idx, classStr) ->
filterClass classStr, reAlignmentClass
filterBaseClass = (idx, classStr) ->
filterClass classStr, reBaseClass
# Refresh the position for each visible popup
refreshPosition = (resetTheme=true) ->
for popupId, popup of instances
popupData = popup.data()
shownId = popupData[dataShown]
continue unless shownId
trigger = getTrigger shownId
triggerData = trigger.data classBase
options = triggerData.options
# Remove alignment classes
popup.removeClass filterAlignmentClass
# Reset theme class
if resetTheme
themes = classTheme + options.theme.split(' ').join(" " + classTheme)
popup.attr 'class', "#{classInstance} #{themes}"
# Prepare some properties
win = $ window
xDistance = yDistance = options.popupDistance
xOffset = options.popupOffset
yOffset = options.popupYOffset
isFixed = popup.data(dataPosition) is 'fixed'
# Get popup dimensions
popupH = popup.outerHeight()
popupW = popup.outerWidth()
popupCenter = popupW / 2
# Get viewport dimensions and offsets
winWidth = win.width()
winHeight = win.height()
winScrollTop = win.scrollTop()
winScrollLeft = win.scrollLeft()
windowPadding = options.windowPadding
# Get trigger dimensions and offset
offset = trigger.offset()
selfWidth = trigger.outerWidth()
selfHeight = trigger.outerHeight()
selfY = offset.top - winScrollTop
# Compute distances and offsets
popupOffsetLeft = offset.left + selfWidth / 2
popupOffsetTop = offset.top - popupH + yOffset
popupY = popupH + options.popupDistance - yOffset
popupDistanceTop = selfY - popupY
popupDistanceBottom = winHeight - selfY - selfHeight - popupY
popupDistanceLeft = offset.left - popupW - xOffset
popupDistanceRight = winWidth - offset.left - selfWidth - popupW
# Check desired position and try to fit the popup into the viewport
preferredPosition = options.preferredPosition
if preferredPosition in ['left', 'right']
yDistance = 0
popupOffsetTop += selfHeight / 2 + popupH / 2
if (preferredPosition is 'right' and popupDistanceRight > windowPadding) \
or popupDistanceLeft < windowPadding
# Positioned right
popup.addClass classRight
popupOffsetLeft = offset.left + selfWidth + xOffset
else
# Positioned left
popup.addClass classLeft
popupOffsetLeft = offset.left - popupW - xOffset
xDistance = -xDistance
else
xDistance = 0
if popupOffsetLeft + popupCenter > winWidth - windowPadding
# Aligned left
popupOffsetLeft -= popupCenter * 2 - xOffset
popup.addClass classAlignLeft
else if popupOffsetLeft - popupCenter < windowPadding
# Aligned right
popupOffsetLeft -= xOffset
popup.addClass classAlignRight
else
# Centered
popupOffsetLeft -= popupCenter
# Move right if popup would violate left viewport bounds
if popupOffsetLeft < windowPadding
popupOffsetLeft = windowPadding
# Add class if positioned below
if (preferredPosition is 'bottom' and popupDistanceBottom > windowPadding) \
or popupDistanceTop < windowPadding
yDistance = -yDistance
popupOffsetTop += popupH + selfHeight - 2 * yOffset
popup.addClass classBottom
# Move Smallipop vertically if it wouldn't fit in the viewport
if popupH < selfHeight
yOverflow = popupOffsetTop + popupH + windowPadding - yDistance \
+ yOffset - winScrollTop - winHeight
if yOverflow > 0
popupOffsetTop = Math.max popupOffsetTop - yOverflow - windowPadding
, offset.top + yOffset + windowPadding + yDistance
# Move Smallipop horizontally if it wouldn't fit in the viewport
# and it's smaller than the trigger
if popupW < selfWidth
xOverflow = popupOffsetLeft + popupW + windowPadding + xDistance \
+ xOffset - winScrollLeft - winWidth
if xOverflow > 0
popupOffsetLeft = Math.max popupOffsetLeft - xOverflow + windowPadding
, offset.left + xOffset + windowPadding - xDistance
# Hide trigger if defined
if options.hideTrigger
trigger
.stop(true)
.fadeTo options.triggerAnimationSpeed, 0
opacity = 0
# Animate to new position if refresh does nothing
if not popupData[dataBeingShown] or options.cssAnimations.enabled
popupOffsetTop -= yDistance
popupOffsetLeft += xDistance
xDistance = yDistance = 0
opacity = 1
# If the element is fixed, it has to be moved by the current scroll offset
if isFixed
popupOffsetLeft -= winScrollLeft
popupOffsetTop -= winScrollTop
popup
.data(dataXDistance, xDistance)
.data(dataYDistance, yDistance)
.css
top: popupOffsetTop
left: popupOffsetLeft
display: 'block'
opacity: opacity
# Start fade in animation
fadeInPopup popup,
top: "-=#{yDistance}"
left: "+=#{xDistance}"
opacity: 1
forceRefreshPosition = ->
refreshPosition false
fadeInPopup = (popup, animationTarget) ->
options = getTrigger(popup.data(dataShown)).data(classBase)?.options or sip.defaults
if options.cssAnimations.enabled
popup.addClass options.cssAnimations.show
window.setTimeout ->
fadeInPopupFinished popup, options
, options.popupAnimationSpeed
else
popup
.stop(true)
.animate animationTarget, options.popupAnimationSpeed, options.funcEase, ->
fadeInPopupFinished popup, options
fadeInPopupFinished = (popup, options) ->
popupData = popup.data()
if popupData[dataBeingShown]
popup.data dataBeingShown, false
options.onAfterShow? getTrigger(popupData[dataShown])
showPopup = (trigger, content='') ->
# Get smallipop options stored in trigger and popup
triggerData = trigger.data classBase
triggerOptions = triggerData.options
popup = triggerData.popupInstance
return unless popup.data dataTriggerHovered
# Show last trigger if not yet visible
shownId = popup.data dataShown
if shownId
lastTrigger = getTrigger shownId
if lastTrigger.length
lastTriggerOpt = lastTrigger.data(classBase).options or sip.defaults
if lastTriggerOpt.hideTrigger
lastTrigger
.stop(true)
.fadeTo lastTriggerOpt.fadeSpeed, 1
# Display overlay under the trigger when tourHighlight is enabled
if triggerOptions.tourHighlight and triggerOptions.tourIndex
tourOverlay = getOverlay().css
backgroundColor: triggerOptions.tourHighlightColor
zIndex: triggerOptions.tourHighlightZIndex
resetTourZIndices()
# Set position at least to relative if it's static, or z-index won't work
if trigger.css('position') is 'static'
trigger.css 'position', 'relative'
# Trigger should stay on top of the overlay
unless trigger.data dataZIndex
trigger.data dataZIndex, trigger.css 'zIndex'
trigger.css 'zIndex', triggerOptions.tourHighlightZIndex + 1
# Show overlay
tourOverlay
.fadeTo triggerOptions.tourHighlightFadeDuration, triggerOptions.tourHighlightOpacity
else if $overlay
hideTourOverlay triggerOptions
popupContent = content or triggerData.hint
# If referenced content element is defined, use it's content
if triggerOptions.referencedContent and not content
popupContent = $(triggerOptions.referencedContent).clone(true, true) or popupContent
popupPosition = if isElementFixed trigger then 'fixed' else 'absolute'
if shownId isnt triggerData.id
popup.hide 0
# Update tip content and remove all classes
popup
.data(dataBeingShown, true)
.data(dataShown, triggerData.id)
.data(dataPosition, popupPosition)
.find('.' + classContent).empty().append popupContent
# Check if trigger has fixed position
popup.css 'position', popupPosition
# Queue the next refresh
queueRefreshPosition 0
isElementFixed = (element) ->
elemToCheck = element
while elemToCheck.length and elemToCheck[0].nodeName.toUpperCase() isnt 'HTML'
if elemToCheck.css('position') is 'fixed'
return true
elemToCheck = elemToCheck.parent()
false
triggerMouseover = ->
trigger = popup = $ @
isTrigger = trigger.hasClass classInitialized
unless isTrigger
trigger = getTrigger popup.data(dataShown)
return unless trigger.length
triggerData = trigger.data classBase
popup = triggerData.popupInstance
.data (if isTrigger then dataTriggerHovered else dataPopupHovered), true
killTimers popup
shownId = popup.data dataShown
# We should have a valid id and an active trigger by now
if shownId isnt triggerData.id or popup.css('opacity') is 0
triggerData.options.onBeforeShow? trigger
popup
.data dataTimerShow, setTimeout ->
showPopup trigger
, triggerData.options.popupDelay
triggerMouseout = ->
trigger = popup = $ @
isTrigger = trigger.hasClass classInitialized
unless isTrigger
trigger = getTrigger popup.data(dataShown)
return unless trigger.length
triggerData = trigger.data classBase
popup = triggerData.popupInstance
.data (if isTrigger then dataTriggerHovered else dataPopupHovered), false
killTimers popup
# Hide tip after a while
popupData = popup.data()
unless popupData[dataPopupHovered] or popupData[dataTriggerHovered]
triggerData.options.onBeforeHide? trigger
popup
.data dataTimerHide, setTimeout ->
hideSmallipop popup
, triggerData.options.hideDelay
onWindowScroll = (e) ->
clearTimeout scrollTimer
scrollTimer = setTimeout forceRefreshPosition, 250
setContent = (trigger, content) ->
return unless trigger?.length
triggerData = trigger.data classBase
partOfTour = triggerData.tourTitle
if partOfTour
popupContent = triggerData.popupInstance.find('.' + classTourContent)
else
popupContent = triggerData.popupInstance.find('.' + classContent)
if popupContent.html() isnt content
popupContent
.stop(true)
.fadeTo triggerData.options.contentAnimationSpeed, 0, ->
$(@)
.html(content)
.fadeTo triggerData.options.contentAnimationSpeed, 1
refreshPosition()
runTour = (trigger, step) ->
triggerData = trigger.data classBase
tourTitle = triggerData?.tourTitle
return unless tourTitle and tours[tourTitle]
# Sort tour elements before running by their index
tours[tourTitle].sort (a, b) ->
a.index - b.index
# Check if a valid step as array index was provided
unless typeof step is 'number' and step % 1 is 0
step = -1
else
step -= 1
currentTour = tourTitle
currentTourItems = tours[tourTitle]
for i in [0..currentTourItems.length - 1] when \
(step >= 0 and i is step) \
or (step < 0 and currentTourItems[i].id is triggerData.id)
return tourShow tourTitle, i
tourShow = (title, index) ->
currentTourItems = tours[title]
return unless currentTourItems
$trigger = currentTourItems[index].trigger
triggerData = $trigger.data classBase
options = triggerData.options
navigationEnabled = options.tourNavigationEnabled
navigation = ''
if navigationEnabled
navigation += "<div class='#{classTourProgress}'>" +
"#{index + 1} #{options.labels.of} #{currentTourItems.length}</div>"
if index > 0
navigation += "<a href='#' class='#{classTourPrev}'>#{options.labels.prev}</a>"
if index < currentTourItems.length - 1
navigation += "<a href='#' class='#{classTourNext}'>#{options.labels.next}</a>"
if not navigationEnabled or index is currentTourItems.length - 1
navigation += "<a href='#' class='#{classTourClose}'>#{options.labels.close}</a>"
$content = $ "<div class='#{classTourContent}'/>" +
"<a href='#' class='#{classTourCloseIcon}'>Χ</a>" +
"<div class='#{classTourFooter}'>#{navigation}</div>"
# Append hint object to tour content
$content.eq(0).append triggerData.hint
killTimers triggerData.popupInstance
triggerData.popupInstance.data dataTriggerHovered, true
# Scroll to trigger if it isn't visible
showWhenVisible $trigger, $content
showWhenVisible = ($trigger, content) ->
targetPosition = $trigger.offset().top
offset = targetPosition - $document.scrollTop()
windowHeight = $window.height()
triggerOptions = $trigger.data(classBase).options
# First scroll to trigger then show tour
if not isElementFixed($trigger) and (offset < triggerOptions.autoscrollPadding or offset > windowHeight - triggerOptions.autoscrollPadding)
$('html, body').animate
scrollTop: targetPosition - windowHeight / 2
, 800, 'swing', ->
showPopup $trigger, content
else
showPopup $trigger, content
tourNext = (e) ->
e?.preventDefault()
currentTourItems = tours[currentTour]
return unless currentTourItems
# Get currently shown tour item
$popup = currentTourItems[0].popupInstance
shownId = $popup.data(dataShown) or currentTourItems[0].id
for i in [0..currentTourItems.length - 2] when currentTourItems[i].id is shownId
triggerOptions = currentTourItems[i].trigger.data(classBase).options
if triggerOptions.tourNavigationEnabled
triggerOptions.onTourNext?(currentTourItems[i + 1].trigger)
return tourShow currentTour, i + 1
tourPrev = (e) ->
e?.preventDefault()
currentTourItems = tours[currentTour]
return unless currentTourItems
# Get currently shown tour item
$popup = currentTourItems[0].popupInstance
shownId = $popup.data(dataShown) or currentTourItems[0].id
for i in [1..currentTourItems.length - 1] when currentTourItems[i].id is shownId
triggerOptions = currentTourItems[i].trigger.data(classBase).options
if triggerOptions.tourNavigationEnabled
triggerOptions.onTourPrev?(currentTourItems[i - 1].trigger)
return tourShow currentTour, i - 1
tourClose = (e) ->
e?.preventDefault()
$popup = $(e.target).closest ".#{classInstance}"
hideSmallipop $popup
destroy = (instances) ->
instances.each ->
self = $ @
data = self.data classBase
if data
self
.unbind(".#{classBase}")
.data(classBase, {})
.removeClass filterBaseClass
onWindowKeyUp = (e) ->
targetIsInput = e?.target.tagName.toLowerCase() in ['input', 'textarea']
switch e.which
# Escape - close all popups
when 27 then hideSmallipop popup for popupId, popup of instances
# Arrow left
when 37 then tourPrev() unless targetIsInput
# Arrow right
when 39 then tourNext() unless targetIsInput
getInstance = (id='default', isTour=false) ->
return instances[id] if instances[id]
instance = $(popupTemplate)
.css('opacity', 0)
.attr('id', "#{classBase + nextInstanceId++}")
.addClass(classInstance)
.data(dataXDistance, 0)
.data(dataYDistance, 0)
.data(dataIsTour, isTour)
.bind(eventMouseOver, triggerMouseover)
.bind(eventMouseOut, triggerMouseout)
$('body').append instance
# Add some binding to events in the popup
if isTour
instance
.delegate(".#{classTourPrev}", eventClick, tourPrev)
.delegate(".#{classTourNext}", eventClick, tourNext)
.delegate(".#{classTourClose}, .#{classTourCloseIcon}", eventClick, tourClose)
else
instance.delegate('a', eventClick, hideSmallipop)
# Bind some events to the document and window if we created the first smallipop
if nextInstanceId is 2
$document.bind "#{eventClick} #{eventTouchEnd}", hideSmallipop
$window
.bind(eventResize, queueRefreshPosition)
.bind(eventScroll, onWindowScroll)
.bind(eventKeyUp, onWindowKeyUp)
instances[id] = instance
$.fn.smallipop = (options={}, hint='') ->
return @ if @length is 0
# Handle direct method calls
if typeof(options) is 'string'
switch options.toLowerCase()
when 'show' then showSmallipop.call @first().get(0)
when 'hide' then hideSmallipop @first().get(0)
when 'destroy' then destroy @
when 'tour' then runTour @first(), hint
when 'update' then setContent @first(), hint
return @
options = $.extend true, {}, sip.defaults, options
# Check for enabled css animations and disable if modernizr is active and says no
unless cssAnimationsEnabled
options.cssAnimations.enabled = false
# Initialize smallipop on first call
$popup = getInstance options.popupId
return @.each ->
$self = $ @
tagName = $self[0].tagName.toLowerCase()
type = $self.attr 'type'
triggerData = $self.data()
# Get content for the popup
# If it's inline markup, create a deep copy of the hint html
objHint = hint or $self.attr('title')
$objInfo = $ "> .#{options.infoClass}:first", $self
if $objInfo.length
objHint = $objInfo.clone(true, true).removeClass options.infoClass
# Initialize each trigger, create id and bind events
if objHint and not $self.hasClass classInitialized
newId = lastId++
triggerEvents = {}
triggerPopupInstance = $popup
triggerOptions = $.extend true, {}, options
# Check if inline smallipop options are provided as object or single data attributes
if typeof(triggerData[classBase]) is 'object'
$.extend true, triggerOptions, triggerData[classBase]
# Extend the trigger options by options set in data attribute
for option, value of triggerData when option.indexOf(classBase) >= 0
optionName = option.replace classBase, ''
if optionName
optionName = optionName.substr(0, 1).toLowerCase() + optionName.substr(1)
triggerOptions[optionName] = value
isFormElement = triggerOptions.handleInputs \
and tagName in ['input', 'select', 'textarea']
# Add to tours if tourTitle is set
if triggerOptions.tourIndex
tourTitle = triggerOptions.tourTitle or 'defaultTour'
# Disable all trigger events
triggerOptions.hideOnTriggerClick = triggerOptions.hideOnPopupClick = false
triggerPopupInstance = getInstance tourTitle, true
tours[tourTitle] = [] unless tours[tourTitle]
tours[tourTitle].push
index: triggerOptions.tourIndex or 0
id: newId
trigger: $self
popupInstance: triggerPopupInstance
else
touchTrigger = triggerOptions.touchSupport and touchEnabled
# Activate on blur events if used on inputs and disable hide on click
if isFormElement
# Don't hide when trigger is clicked and show when trigger is clicked
triggerOptions.hideOnTriggerClick = false
triggerEvents[eventFocus] = triggerMouseover
triggerEvents[eventBlur] = triggerMouseout
else if not touchTrigger
triggerEvents[eventMouseOut] = triggerMouseout
# Check whether the trigger should activate smallipop by click or hover
if triggerOptions.triggerOnClick or touchTrigger
triggerEvents[eventClick] = showSmallipop
else
triggerEvents[eventClick] = triggerMouseout
triggerEvents[eventMouseOver] = triggerMouseover
# Store parameters for this trigger
$self
.addClass("#{classInitialized} #{classBase}#{newId}")
.attr('title', '') # Remove title to disable browser hint
.data classBase,
id: newId
hint: objHint
options: triggerOptions
tagName: tagName
type: type
tourTitle: tourTitle
popupInstance: triggerPopupInstance
isFormElement: isFormElement
.bind triggerEvents
# Hide popup when links contained in the trigger are clicked
unless triggerOptions.hideOnTriggerClick
$self.delegate 'a', eventClick, hideSmallipop
))
| 129565 | ###!
Smallipop (02/27/2015)
Copyright (c) 2011-2015 Small Improvements (http://www.small-improvements.com)
Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
@author <NAME> (<EMAIL>)
###
(((factory) ->
if typeof define is 'function' and define.amd
define ['jquery'], factory
else
factory jQuery
)(($) ->
# CSS classes
classBase = 'smallipop'
classHint = classBase + '-hint'
classInstance = classBase + '-instance'
classContent = classBase + '-content'
classLeft = classBase + '-left'
classRight = classBase + '-right'
classBottom = classBase + '-bottom'
classAlignLeft = classBase + '-align-left'
classAlignRight = classBase + '-align-right'
classInitialized = classBase + '-initialized'
classTheme = classBase + '-theme-'
classTour = classBase + '-tour'
classTourContent = classTour + '-content'
classTourOverlay = classTour + '-overlay'
classTourFooter = classTour + '-footer'
classTourCloseIcon = classTour + '-close-icon'
classTourProgress = classTour + '-progress'
classTourClose = classTour + '-close'
classTourPrev = classTour + '-prev'
classTourNext = classTour + '-next'
# Event names
eventFocus = 'focus.' + classBase
eventClick = 'click.' + classBase
eventBlur = 'blur.' + classBase
eventMouseOut = 'mouseout.' + classBase
eventMouseOver = 'mouseover.' + classBase
eventTouchEnd = 'touchend.' + classBase
eventResize = 'resize.' + classBase
eventScroll = 'scroll.' + classBase
eventKeyUp = 'keyup.' + classBase
# Data names
dataZIndex = classBase + 'OriginalZIndex'
dataBeingShown = classBase + 'BeingShown'
dataTimerHide = classBase + 'HideDelayTimer'
dataTimerShow = classBase + 'ShowDelayTimer'
dataTriggerHovered = classBase + 'TriggerHovered'
dataPopupHovered = classBase + 'PopupHovered'
dataShown = classBase + 'Shown'
dataPosition = classBase + 'Position'
dataXDistance = classBase + 'XDistance'
dataYDistance = classBase + 'YDistance'
dataIsTour = classBase + 'IsTour'
# Regular expressions
reAlignmentClass = new RegExp classBase + '-(align|bottom)\w*', "g"
reBaseClass = new RegExp classBase + '\w+', "g"
# Global elements
$document = $ document
$window = $ window
$overlay = null
instances = {}
# Tour vars
tours = {}
currentTour = null
# Id vars
lastId = 1 # Counter for new smallipop id's
nextInstanceId = 1 # Counter for new smallipop container id's
# Timing vars
scrollTimer = null
lastScrollCheck = 0
refreshQueueTimer = null
# Templates
popupTemplate = "<div class='#{classInstance}'><div class='#{classContent}'/></div>"
$.smallipop = sip =
version: '0.6.4'
defaults:
autoscrollPadding: 200
contentAnimationSpeed: 150
cssAnimations:
enabled: false
show: 'animated fadeIn'
hide: 'animated fadeOut'
funcEase: 'easeInOutQuad'
handleInputs: true
hideDelay: 500
hideTrigger: false
hideOnPopupClick: true
hideOnTriggerClick: true
infoClass: classHint
invertAnimation: false
popupId: ''
popupOffset: 31
popupYOffset: 0
popupDistance: 20
popupDelay: 100
popupAnimationSpeed: 200
preferredPosition: 'top' # bottom, top, left or right
referencedContent: null
theme: 'default'
touchSupport: true
tourHighlight: false
tourHighlightColor: '#222'
tourHighlightFadeDuration: 200
tourHighlightOpacity: .5
tourHighlightZIndex: 9997
tourNavigationEnabled: true
triggerAnimationSpeed: 150
triggerOnClick: false
onAfterHide: null
onAfterShow: null
onBeforeHide: null
onBeforeShow: null
onTourClose: null
onTourNext: null
onTourPrev: null
windowPadding: 30 # Imaginary padding in viewport
labels:
prev: 'Prev'
next: 'Next'
close: 'Close'
of: 'of'
# Add default easing function for smallipop to jQuery if missing
unless $.easing.easeInOutQuad
$.easing.easeInOutQuad = (x, t, b, c, d) ->
if ((t/=d/2) < 1) then c/2*t*t + b else -c/2 * ((--t)*(t-2) - 1) + b
# Reset z-index for all other triggers in tours
resetTourZIndices = ->
for tour, steps of tours
for step in steps
tourTrigger = step.trigger
if tourTrigger.data dataZIndex
tourTrigger.css 'zIndex', tourTrigger.data(dataZIndex)
touchEnabled = Modernizr?.touch
cssAnimationsEnabled = Modernizr?.cssanimations
getTrigger = (id) ->
$ ".#{classBase + id}"
# Returns the overlay and creates it if necessary
getOverlay = ->
unless $overlay
$overlay = $("<div id='#{classTourOverlay}'/>").appendTo($('body')).fadeOut 0
$overlay
hideTourOverlay = (options) ->
getOverlay().fadeOut options.tourHighlightFadeDuration
resetTourZIndices()
hideSmallipop = (e) ->
clearTimeout scrollTimer
target = if e?.target then $(e.target) else e
for popupId, popup of instances
popupData = popup.data()
continue unless shownId = popupData[dataShown]
trigger = getTrigger shownId
triggerIsTarget = trigger.is target
triggerData = trigger.data(classBase)
triggerOptions = triggerData.options or sip.defaults
continue if (popupData[dataIsTour] or triggerData.isFormElement) \
and not popup.is(target) \
and not (triggerIsTarget and popup.is(triggerOptions.popupInstance))
# Fire close callback
if popupData[dataIsTour]
currentTour = null
trigger.data(classBase)?.options.onTourClose?()
hideTourOverlay triggerOptions
# Do nothing if clicked and hide on click is disabled for this case
ignoreTriggerClick = not triggerOptions.hideOnTriggerClick and triggerIsTarget
ignorePopupClick = not triggerOptions.hideOnPopupClick \
and popup.find(target).length
continue if target and trigger.length and e?.type in ['click', 'touchend'] \
and (ignoreTriggerClick or ignorePopupClick)
# Show trigger if it was hidden
if shownId and triggerOptions.hideTrigger
trigger.stop(true).fadeTo triggerOptions.triggerAnimationSpeed, 1
popup
.data(dataTimerHide, null)
.data(dataBeingShown, false)
if triggerOptions.cssAnimations.enabled
popup
.removeClass(triggerOptions.cssAnimations.show)
.addClass(triggerOptions.cssAnimations.hide)
.data dataShown, ''
if triggerOptions.onAfterHide
window.setTimeout triggerOptions.onAfterHide, triggerOptions.popupAnimationSpeed
else
direction = if triggerOptions.invertAnimation then -1 else 1
xDistance = popupData[dataXDistance] * direction
yDistance = popupData[dataYDistance] * direction
popup
.stop(true)
.animate
top: "-=#{yDistance}"
left: "+=#{xDistance}"
opacity: 0
, triggerOptions.popupAnimationSpeed, triggerOptions.funcEase, ->
# Hide tip if not being shown in the meantime
self = $ @
unless self.data dataBeingShown
self
.css('display', 'none')
.data(dataShown, '')
triggerOptions.onAfterHide?()
showSmallipop= (e) ->
triggerData = $(@).data classBase
return unless triggerData
if triggerData.popupInstance.data(dataShown) isnt triggerData.id \
and not triggerData.type in ['checkbox', 'radio']
e?.preventDefault()
triggerMouseover.call @
killTimers = (popup) ->
clearTimeout popup.data(dataTimerHide)
clearTimeout popup.data(dataTimerShow)
# Queue a refresh to the popups position
queueRefreshPosition = (delay=50) ->
clearTimeout refreshQueueTimer
refreshQueueTimer = setTimeout refreshPosition, delay
# Class filtering helpers
filterClass = (classStr, re) ->
if classStr then (classStr.match(re) or []).join ' '
filterAlignmentClass = (idx, classStr) ->
filterClass classStr, reAlignmentClass
filterBaseClass = (idx, classStr) ->
filterClass classStr, reBaseClass
# Refresh the position for each visible popup
refreshPosition = (resetTheme=true) ->
for popupId, popup of instances
popupData = popup.data()
shownId = popupData[dataShown]
continue unless shownId
trigger = getTrigger shownId
triggerData = trigger.data classBase
options = triggerData.options
# Remove alignment classes
popup.removeClass filterAlignmentClass
# Reset theme class
if resetTheme
themes = classTheme + options.theme.split(' ').join(" " + classTheme)
popup.attr 'class', "#{classInstance} #{themes}"
# Prepare some properties
win = $ window
xDistance = yDistance = options.popupDistance
xOffset = options.popupOffset
yOffset = options.popupYOffset
isFixed = popup.data(dataPosition) is 'fixed'
# Get popup dimensions
popupH = popup.outerHeight()
popupW = popup.outerWidth()
popupCenter = popupW / 2
# Get viewport dimensions and offsets
winWidth = win.width()
winHeight = win.height()
winScrollTop = win.scrollTop()
winScrollLeft = win.scrollLeft()
windowPadding = options.windowPadding
# Get trigger dimensions and offset
offset = trigger.offset()
selfWidth = trigger.outerWidth()
selfHeight = trigger.outerHeight()
selfY = offset.top - winScrollTop
# Compute distances and offsets
popupOffsetLeft = offset.left + selfWidth / 2
popupOffsetTop = offset.top - popupH + yOffset
popupY = popupH + options.popupDistance - yOffset
popupDistanceTop = selfY - popupY
popupDistanceBottom = winHeight - selfY - selfHeight - popupY
popupDistanceLeft = offset.left - popupW - xOffset
popupDistanceRight = winWidth - offset.left - selfWidth - popupW
# Check desired position and try to fit the popup into the viewport
preferredPosition = options.preferredPosition
if preferredPosition in ['left', 'right']
yDistance = 0
popupOffsetTop += selfHeight / 2 + popupH / 2
if (preferredPosition is 'right' and popupDistanceRight > windowPadding) \
or popupDistanceLeft < windowPadding
# Positioned right
popup.addClass classRight
popupOffsetLeft = offset.left + selfWidth + xOffset
else
# Positioned left
popup.addClass classLeft
popupOffsetLeft = offset.left - popupW - xOffset
xDistance = -xDistance
else
xDistance = 0
if popupOffsetLeft + popupCenter > winWidth - windowPadding
# Aligned left
popupOffsetLeft -= popupCenter * 2 - xOffset
popup.addClass classAlignLeft
else if popupOffsetLeft - popupCenter < windowPadding
# Aligned right
popupOffsetLeft -= xOffset
popup.addClass classAlignRight
else
# Centered
popupOffsetLeft -= popupCenter
# Move right if popup would violate left viewport bounds
if popupOffsetLeft < windowPadding
popupOffsetLeft = windowPadding
# Add class if positioned below
if (preferredPosition is 'bottom' and popupDistanceBottom > windowPadding) \
or popupDistanceTop < windowPadding
yDistance = -yDistance
popupOffsetTop += popupH + selfHeight - 2 * yOffset
popup.addClass classBottom
# Move Smallipop vertically if it wouldn't fit in the viewport
if popupH < selfHeight
yOverflow = popupOffsetTop + popupH + windowPadding - yDistance \
+ yOffset - winScrollTop - winHeight
if yOverflow > 0
popupOffsetTop = Math.max popupOffsetTop - yOverflow - windowPadding
, offset.top + yOffset + windowPadding + yDistance
# Move Smallipop horizontally if it wouldn't fit in the viewport
# and it's smaller than the trigger
if popupW < selfWidth
xOverflow = popupOffsetLeft + popupW + windowPadding + xDistance \
+ xOffset - winScrollLeft - winWidth
if xOverflow > 0
popupOffsetLeft = Math.max popupOffsetLeft - xOverflow + windowPadding
, offset.left + xOffset + windowPadding - xDistance
# Hide trigger if defined
if options.hideTrigger
trigger
.stop(true)
.fadeTo options.triggerAnimationSpeed, 0
opacity = 0
# Animate to new position if refresh does nothing
if not popupData[dataBeingShown] or options.cssAnimations.enabled
popupOffsetTop -= yDistance
popupOffsetLeft += xDistance
xDistance = yDistance = 0
opacity = 1
# If the element is fixed, it has to be moved by the current scroll offset
if isFixed
popupOffsetLeft -= winScrollLeft
popupOffsetTop -= winScrollTop
popup
.data(dataXDistance, xDistance)
.data(dataYDistance, yDistance)
.css
top: popupOffsetTop
left: popupOffsetLeft
display: 'block'
opacity: opacity
# Start fade in animation
fadeInPopup popup,
top: "-=#{yDistance}"
left: "+=#{xDistance}"
opacity: 1
forceRefreshPosition = ->
refreshPosition false
fadeInPopup = (popup, animationTarget) ->
options = getTrigger(popup.data(dataShown)).data(classBase)?.options or sip.defaults
if options.cssAnimations.enabled
popup.addClass options.cssAnimations.show
window.setTimeout ->
fadeInPopupFinished popup, options
, options.popupAnimationSpeed
else
popup
.stop(true)
.animate animationTarget, options.popupAnimationSpeed, options.funcEase, ->
fadeInPopupFinished popup, options
fadeInPopupFinished = (popup, options) ->
popupData = popup.data()
if popupData[dataBeingShown]
popup.data dataBeingShown, false
options.onAfterShow? getTrigger(popupData[dataShown])
showPopup = (trigger, content='') ->
# Get smallipop options stored in trigger and popup
triggerData = trigger.data classBase
triggerOptions = triggerData.options
popup = triggerData.popupInstance
return unless popup.data dataTriggerHovered
# Show last trigger if not yet visible
shownId = popup.data dataShown
if shownId
lastTrigger = getTrigger shownId
if lastTrigger.length
lastTriggerOpt = lastTrigger.data(classBase).options or sip.defaults
if lastTriggerOpt.hideTrigger
lastTrigger
.stop(true)
.fadeTo lastTriggerOpt.fadeSpeed, 1
# Display overlay under the trigger when tourHighlight is enabled
if triggerOptions.tourHighlight and triggerOptions.tourIndex
tourOverlay = getOverlay().css
backgroundColor: triggerOptions.tourHighlightColor
zIndex: triggerOptions.tourHighlightZIndex
resetTourZIndices()
# Set position at least to relative if it's static, or z-index won't work
if trigger.css('position') is 'static'
trigger.css 'position', 'relative'
# Trigger should stay on top of the overlay
unless trigger.data dataZIndex
trigger.data dataZIndex, trigger.css 'zIndex'
trigger.css 'zIndex', triggerOptions.tourHighlightZIndex + 1
# Show overlay
tourOverlay
.fadeTo triggerOptions.tourHighlightFadeDuration, triggerOptions.tourHighlightOpacity
else if $overlay
hideTourOverlay triggerOptions
popupContent = content or triggerData.hint
# If referenced content element is defined, use it's content
if triggerOptions.referencedContent and not content
popupContent = $(triggerOptions.referencedContent).clone(true, true) or popupContent
popupPosition = if isElementFixed trigger then 'fixed' else 'absolute'
if shownId isnt triggerData.id
popup.hide 0
# Update tip content and remove all classes
popup
.data(dataBeingShown, true)
.data(dataShown, triggerData.id)
.data(dataPosition, popupPosition)
.find('.' + classContent).empty().append popupContent
# Check if trigger has fixed position
popup.css 'position', popupPosition
# Queue the next refresh
queueRefreshPosition 0
isElementFixed = (element) ->
elemToCheck = element
while elemToCheck.length and elemToCheck[0].nodeName.toUpperCase() isnt 'HTML'
if elemToCheck.css('position') is 'fixed'
return true
elemToCheck = elemToCheck.parent()
false
triggerMouseover = ->
trigger = popup = $ @
isTrigger = trigger.hasClass classInitialized
unless isTrigger
trigger = getTrigger popup.data(dataShown)
return unless trigger.length
triggerData = trigger.data classBase
popup = triggerData.popupInstance
.data (if isTrigger then dataTriggerHovered else dataPopupHovered), true
killTimers popup
shownId = popup.data dataShown
# We should have a valid id and an active trigger by now
if shownId isnt triggerData.id or popup.css('opacity') is 0
triggerData.options.onBeforeShow? trigger
popup
.data dataTimerShow, setTimeout ->
showPopup trigger
, triggerData.options.popupDelay
triggerMouseout = ->
trigger = popup = $ @
isTrigger = trigger.hasClass classInitialized
unless isTrigger
trigger = getTrigger popup.data(dataShown)
return unless trigger.length
triggerData = trigger.data classBase
popup = triggerData.popupInstance
.data (if isTrigger then dataTriggerHovered else dataPopupHovered), false
killTimers popup
# Hide tip after a while
popupData = popup.data()
unless popupData[dataPopupHovered] or popupData[dataTriggerHovered]
triggerData.options.onBeforeHide? trigger
popup
.data dataTimerHide, setTimeout ->
hideSmallipop popup
, triggerData.options.hideDelay
onWindowScroll = (e) ->
clearTimeout scrollTimer
scrollTimer = setTimeout forceRefreshPosition, 250
setContent = (trigger, content) ->
return unless trigger?.length
triggerData = trigger.data classBase
partOfTour = triggerData.tourTitle
if partOfTour
popupContent = triggerData.popupInstance.find('.' + classTourContent)
else
popupContent = triggerData.popupInstance.find('.' + classContent)
if popupContent.html() isnt content
popupContent
.stop(true)
.fadeTo triggerData.options.contentAnimationSpeed, 0, ->
$(@)
.html(content)
.fadeTo triggerData.options.contentAnimationSpeed, 1
refreshPosition()
runTour = (trigger, step) ->
triggerData = trigger.data classBase
tourTitle = triggerData?.tourTitle
return unless tourTitle and tours[tourTitle]
# Sort tour elements before running by their index
tours[tourTitle].sort (a, b) ->
a.index - b.index
# Check if a valid step as array index was provided
unless typeof step is 'number' and step % 1 is 0
step = -1
else
step -= 1
currentTour = tourTitle
currentTourItems = tours[tourTitle]
for i in [0..currentTourItems.length - 1] when \
(step >= 0 and i is step) \
or (step < 0 and currentTourItems[i].id is triggerData.id)
return tourShow tourTitle, i
tourShow = (title, index) ->
currentTourItems = tours[title]
return unless currentTourItems
$trigger = currentTourItems[index].trigger
triggerData = $trigger.data classBase
options = triggerData.options
navigationEnabled = options.tourNavigationEnabled
navigation = ''
if navigationEnabled
navigation += "<div class='#{classTourProgress}'>" +
"#{index + 1} #{options.labels.of} #{currentTourItems.length}</div>"
if index > 0
navigation += "<a href='#' class='#{classTourPrev}'>#{options.labels.prev}</a>"
if index < currentTourItems.length - 1
navigation += "<a href='#' class='#{classTourNext}'>#{options.labels.next}</a>"
if not navigationEnabled or index is currentTourItems.length - 1
navigation += "<a href='#' class='#{classTourClose}'>#{options.labels.close}</a>"
$content = $ "<div class='#{classTourContent}'/>" +
"<a href='#' class='#{classTourCloseIcon}'>Χ</a>" +
"<div class='#{classTourFooter}'>#{navigation}</div>"
# Append hint object to tour content
$content.eq(0).append triggerData.hint
killTimers triggerData.popupInstance
triggerData.popupInstance.data dataTriggerHovered, true
# Scroll to trigger if it isn't visible
showWhenVisible $trigger, $content
showWhenVisible = ($trigger, content) ->
targetPosition = $trigger.offset().top
offset = targetPosition - $document.scrollTop()
windowHeight = $window.height()
triggerOptions = $trigger.data(classBase).options
# First scroll to trigger then show tour
if not isElementFixed($trigger) and (offset < triggerOptions.autoscrollPadding or offset > windowHeight - triggerOptions.autoscrollPadding)
$('html, body').animate
scrollTop: targetPosition - windowHeight / 2
, 800, 'swing', ->
showPopup $trigger, content
else
showPopup $trigger, content
tourNext = (e) ->
e?.preventDefault()
currentTourItems = tours[currentTour]
return unless currentTourItems
# Get currently shown tour item
$popup = currentTourItems[0].popupInstance
shownId = $popup.data(dataShown) or currentTourItems[0].id
for i in [0..currentTourItems.length - 2] when currentTourItems[i].id is shownId
triggerOptions = currentTourItems[i].trigger.data(classBase).options
if triggerOptions.tourNavigationEnabled
triggerOptions.onTourNext?(currentTourItems[i + 1].trigger)
return tourShow currentTour, i + 1
tourPrev = (e) ->
e?.preventDefault()
currentTourItems = tours[currentTour]
return unless currentTourItems
# Get currently shown tour item
$popup = currentTourItems[0].popupInstance
shownId = $popup.data(dataShown) or currentTourItems[0].id
for i in [1..currentTourItems.length - 1] when currentTourItems[i].id is shownId
triggerOptions = currentTourItems[i].trigger.data(classBase).options
if triggerOptions.tourNavigationEnabled
triggerOptions.onTourPrev?(currentTourItems[i - 1].trigger)
return tourShow currentTour, i - 1
tourClose = (e) ->
e?.preventDefault()
$popup = $(e.target).closest ".#{classInstance}"
hideSmallipop $popup
destroy = (instances) ->
instances.each ->
self = $ @
data = self.data classBase
if data
self
.unbind(".#{classBase}")
.data(classBase, {})
.removeClass filterBaseClass
onWindowKeyUp = (e) ->
targetIsInput = e?.target.tagName.toLowerCase() in ['input', 'textarea']
switch e.which
# Escape - close all popups
when 27 then hideSmallipop popup for popupId, popup of instances
# Arrow left
when 37 then tourPrev() unless targetIsInput
# Arrow right
when 39 then tourNext() unless targetIsInput
getInstance = (id='default', isTour=false) ->
return instances[id] if instances[id]
instance = $(popupTemplate)
.css('opacity', 0)
.attr('id', "#{classBase + nextInstanceId++}")
.addClass(classInstance)
.data(dataXDistance, 0)
.data(dataYDistance, 0)
.data(dataIsTour, isTour)
.bind(eventMouseOver, triggerMouseover)
.bind(eventMouseOut, triggerMouseout)
$('body').append instance
# Add some binding to events in the popup
if isTour
instance
.delegate(".#{classTourPrev}", eventClick, tourPrev)
.delegate(".#{classTourNext}", eventClick, tourNext)
.delegate(".#{classTourClose}, .#{classTourCloseIcon}", eventClick, tourClose)
else
instance.delegate('a', eventClick, hideSmallipop)
# Bind some events to the document and window if we created the first smallipop
if nextInstanceId is 2
$document.bind "#{eventClick} #{eventTouchEnd}", hideSmallipop
$window
.bind(eventResize, queueRefreshPosition)
.bind(eventScroll, onWindowScroll)
.bind(eventKeyUp, onWindowKeyUp)
instances[id] = instance
$.fn.smallipop = (options={}, hint='') ->
return @ if @length is 0
# Handle direct method calls
if typeof(options) is 'string'
switch options.toLowerCase()
when 'show' then showSmallipop.call @first().get(0)
when 'hide' then hideSmallipop @first().get(0)
when 'destroy' then destroy @
when 'tour' then runTour @first(), hint
when 'update' then setContent @first(), hint
return @
options = $.extend true, {}, sip.defaults, options
# Check for enabled css animations and disable if modernizr is active and says no
unless cssAnimationsEnabled
options.cssAnimations.enabled = false
# Initialize smallipop on first call
$popup = getInstance options.popupId
return @.each ->
$self = $ @
tagName = $self[0].tagName.toLowerCase()
type = $self.attr 'type'
triggerData = $self.data()
# Get content for the popup
# If it's inline markup, create a deep copy of the hint html
objHint = hint or $self.attr('title')
$objInfo = $ "> .#{options.infoClass}:first", $self
if $objInfo.length
objHint = $objInfo.clone(true, true).removeClass options.infoClass
# Initialize each trigger, create id and bind events
if objHint and not $self.hasClass classInitialized
newId = lastId++
triggerEvents = {}
triggerPopupInstance = $popup
triggerOptions = $.extend true, {}, options
# Check if inline smallipop options are provided as object or single data attributes
if typeof(triggerData[classBase]) is 'object'
$.extend true, triggerOptions, triggerData[classBase]
# Extend the trigger options by options set in data attribute
for option, value of triggerData when option.indexOf(classBase) >= 0
optionName = option.replace classBase, ''
if optionName
optionName = optionName.substr(0, 1).toLowerCase() + optionName.substr(1)
triggerOptions[optionName] = value
isFormElement = triggerOptions.handleInputs \
and tagName in ['input', 'select', 'textarea']
# Add to tours if tourTitle is set
if triggerOptions.tourIndex
tourTitle = triggerOptions.tourTitle or 'defaultTour'
# Disable all trigger events
triggerOptions.hideOnTriggerClick = triggerOptions.hideOnPopupClick = false
triggerPopupInstance = getInstance tourTitle, true
tours[tourTitle] = [] unless tours[tourTitle]
tours[tourTitle].push
index: triggerOptions.tourIndex or 0
id: newId
trigger: $self
popupInstance: triggerPopupInstance
else
touchTrigger = triggerOptions.touchSupport and touchEnabled
# Activate on blur events if used on inputs and disable hide on click
if isFormElement
# Don't hide when trigger is clicked and show when trigger is clicked
triggerOptions.hideOnTriggerClick = false
triggerEvents[eventFocus] = triggerMouseover
triggerEvents[eventBlur] = triggerMouseout
else if not touchTrigger
triggerEvents[eventMouseOut] = triggerMouseout
# Check whether the trigger should activate smallipop by click or hover
if triggerOptions.triggerOnClick or touchTrigger
triggerEvents[eventClick] = showSmallipop
else
triggerEvents[eventClick] = triggerMouseout
triggerEvents[eventMouseOver] = triggerMouseover
# Store parameters for this trigger
$self
.addClass("#{classInitialized} #{classBase}#{newId}")
.attr('title', '') # Remove title to disable browser hint
.data classBase,
id: newId
hint: objHint
options: triggerOptions
tagName: tagName
type: type
tourTitle: tourTitle
popupInstance: triggerPopupInstance
isFormElement: isFormElement
.bind triggerEvents
# Hide popup when links contained in the trigger are clicked
unless triggerOptions.hideOnTriggerClick
$self.delegate 'a', eventClick, hideSmallipop
))
| true | ###!
Smallipop (02/27/2015)
Copyright (c) 2011-2015 Small Improvements (http://www.small-improvements.com)
Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
@author PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
###
(((factory) ->
if typeof define is 'function' and define.amd
define ['jquery'], factory
else
factory jQuery
)(($) ->
# CSS classes
classBase = 'smallipop'
classHint = classBase + '-hint'
classInstance = classBase + '-instance'
classContent = classBase + '-content'
classLeft = classBase + '-left'
classRight = classBase + '-right'
classBottom = classBase + '-bottom'
classAlignLeft = classBase + '-align-left'
classAlignRight = classBase + '-align-right'
classInitialized = classBase + '-initialized'
classTheme = classBase + '-theme-'
classTour = classBase + '-tour'
classTourContent = classTour + '-content'
classTourOverlay = classTour + '-overlay'
classTourFooter = classTour + '-footer'
classTourCloseIcon = classTour + '-close-icon'
classTourProgress = classTour + '-progress'
classTourClose = classTour + '-close'
classTourPrev = classTour + '-prev'
classTourNext = classTour + '-next'
# Event names
eventFocus = 'focus.' + classBase
eventClick = 'click.' + classBase
eventBlur = 'blur.' + classBase
eventMouseOut = 'mouseout.' + classBase
eventMouseOver = 'mouseover.' + classBase
eventTouchEnd = 'touchend.' + classBase
eventResize = 'resize.' + classBase
eventScroll = 'scroll.' + classBase
eventKeyUp = 'keyup.' + classBase
# Data names
dataZIndex = classBase + 'OriginalZIndex'
dataBeingShown = classBase + 'BeingShown'
dataTimerHide = classBase + 'HideDelayTimer'
dataTimerShow = classBase + 'ShowDelayTimer'
dataTriggerHovered = classBase + 'TriggerHovered'
dataPopupHovered = classBase + 'PopupHovered'
dataShown = classBase + 'Shown'
dataPosition = classBase + 'Position'
dataXDistance = classBase + 'XDistance'
dataYDistance = classBase + 'YDistance'
dataIsTour = classBase + 'IsTour'
# Regular expressions
reAlignmentClass = new RegExp classBase + '-(align|bottom)\w*', "g"
reBaseClass = new RegExp classBase + '\w+', "g"
# Global elements
$document = $ document
$window = $ window
$overlay = null
instances = {}
# Tour vars
tours = {}
currentTour = null
# Id vars
lastId = 1 # Counter for new smallipop id's
nextInstanceId = 1 # Counter for new smallipop container id's
# Timing vars
scrollTimer = null
lastScrollCheck = 0
refreshQueueTimer = null
# Templates
popupTemplate = "<div class='#{classInstance}'><div class='#{classContent}'/></div>"
$.smallipop = sip =
version: '0.6.4'
defaults:
autoscrollPadding: 200
contentAnimationSpeed: 150
cssAnimations:
enabled: false
show: 'animated fadeIn'
hide: 'animated fadeOut'
funcEase: 'easeInOutQuad'
handleInputs: true
hideDelay: 500
hideTrigger: false
hideOnPopupClick: true
hideOnTriggerClick: true
infoClass: classHint
invertAnimation: false
popupId: ''
popupOffset: 31
popupYOffset: 0
popupDistance: 20
popupDelay: 100
popupAnimationSpeed: 200
preferredPosition: 'top' # bottom, top, left or right
referencedContent: null
theme: 'default'
touchSupport: true
tourHighlight: false
tourHighlightColor: '#222'
tourHighlightFadeDuration: 200
tourHighlightOpacity: .5
tourHighlightZIndex: 9997
tourNavigationEnabled: true
triggerAnimationSpeed: 150
triggerOnClick: false
onAfterHide: null
onAfterShow: null
onBeforeHide: null
onBeforeShow: null
onTourClose: null
onTourNext: null
onTourPrev: null
windowPadding: 30 # Imaginary padding in viewport
labels:
prev: 'Prev'
next: 'Next'
close: 'Close'
of: 'of'
# Add default easing function for smallipop to jQuery if missing
unless $.easing.easeInOutQuad
$.easing.easeInOutQuad = (x, t, b, c, d) ->
if ((t/=d/2) < 1) then c/2*t*t + b else -c/2 * ((--t)*(t-2) - 1) + b
# Reset z-index for all other triggers in tours
resetTourZIndices = ->
for tour, steps of tours
for step in steps
tourTrigger = step.trigger
if tourTrigger.data dataZIndex
tourTrigger.css 'zIndex', tourTrigger.data(dataZIndex)
touchEnabled = Modernizr?.touch
cssAnimationsEnabled = Modernizr?.cssanimations
getTrigger = (id) ->
$ ".#{classBase + id}"
# Returns the overlay and creates it if necessary
getOverlay = ->
unless $overlay
$overlay = $("<div id='#{classTourOverlay}'/>").appendTo($('body')).fadeOut 0
$overlay
hideTourOverlay = (options) ->
getOverlay().fadeOut options.tourHighlightFadeDuration
resetTourZIndices()
hideSmallipop = (e) ->
clearTimeout scrollTimer
target = if e?.target then $(e.target) else e
for popupId, popup of instances
popupData = popup.data()
continue unless shownId = popupData[dataShown]
trigger = getTrigger shownId
triggerIsTarget = trigger.is target
triggerData = trigger.data(classBase)
triggerOptions = triggerData.options or sip.defaults
continue if (popupData[dataIsTour] or triggerData.isFormElement) \
and not popup.is(target) \
and not (triggerIsTarget and popup.is(triggerOptions.popupInstance))
# Fire close callback
if popupData[dataIsTour]
currentTour = null
trigger.data(classBase)?.options.onTourClose?()
hideTourOverlay triggerOptions
# Do nothing if clicked and hide on click is disabled for this case
ignoreTriggerClick = not triggerOptions.hideOnTriggerClick and triggerIsTarget
ignorePopupClick = not triggerOptions.hideOnPopupClick \
and popup.find(target).length
continue if target and trigger.length and e?.type in ['click', 'touchend'] \
and (ignoreTriggerClick or ignorePopupClick)
# Show trigger if it was hidden
if shownId and triggerOptions.hideTrigger
trigger.stop(true).fadeTo triggerOptions.triggerAnimationSpeed, 1
popup
.data(dataTimerHide, null)
.data(dataBeingShown, false)
if triggerOptions.cssAnimations.enabled
popup
.removeClass(triggerOptions.cssAnimations.show)
.addClass(triggerOptions.cssAnimations.hide)
.data dataShown, ''
if triggerOptions.onAfterHide
window.setTimeout triggerOptions.onAfterHide, triggerOptions.popupAnimationSpeed
else
direction = if triggerOptions.invertAnimation then -1 else 1
xDistance = popupData[dataXDistance] * direction
yDistance = popupData[dataYDistance] * direction
popup
.stop(true)
.animate
top: "-=#{yDistance}"
left: "+=#{xDistance}"
opacity: 0
, triggerOptions.popupAnimationSpeed, triggerOptions.funcEase, ->
# Hide tip if not being shown in the meantime
self = $ @
unless self.data dataBeingShown
self
.css('display', 'none')
.data(dataShown, '')
triggerOptions.onAfterHide?()
showSmallipop= (e) ->
triggerData = $(@).data classBase
return unless triggerData
if triggerData.popupInstance.data(dataShown) isnt triggerData.id \
and not triggerData.type in ['checkbox', 'radio']
e?.preventDefault()
triggerMouseover.call @
killTimers = (popup) ->
clearTimeout popup.data(dataTimerHide)
clearTimeout popup.data(dataTimerShow)
# Queue a refresh to the popups position
queueRefreshPosition = (delay=50) ->
clearTimeout refreshQueueTimer
refreshQueueTimer = setTimeout refreshPosition, delay
# Class filtering helpers
filterClass = (classStr, re) ->
if classStr then (classStr.match(re) or []).join ' '
filterAlignmentClass = (idx, classStr) ->
filterClass classStr, reAlignmentClass
filterBaseClass = (idx, classStr) ->
filterClass classStr, reBaseClass
# Refresh the position for each visible popup
refreshPosition = (resetTheme=true) ->
for popupId, popup of instances
popupData = popup.data()
shownId = popupData[dataShown]
continue unless shownId
trigger = getTrigger shownId
triggerData = trigger.data classBase
options = triggerData.options
# Remove alignment classes
popup.removeClass filterAlignmentClass
# Reset theme class
if resetTheme
themes = classTheme + options.theme.split(' ').join(" " + classTheme)
popup.attr 'class', "#{classInstance} #{themes}"
# Prepare some properties
win = $ window
xDistance = yDistance = options.popupDistance
xOffset = options.popupOffset
yOffset = options.popupYOffset
isFixed = popup.data(dataPosition) is 'fixed'
# Get popup dimensions
popupH = popup.outerHeight()
popupW = popup.outerWidth()
popupCenter = popupW / 2
# Get viewport dimensions and offsets
winWidth = win.width()
winHeight = win.height()
winScrollTop = win.scrollTop()
winScrollLeft = win.scrollLeft()
windowPadding = options.windowPadding
# Get trigger dimensions and offset
offset = trigger.offset()
selfWidth = trigger.outerWidth()
selfHeight = trigger.outerHeight()
selfY = offset.top - winScrollTop
# Compute distances and offsets
popupOffsetLeft = offset.left + selfWidth / 2
popupOffsetTop = offset.top - popupH + yOffset
popupY = popupH + options.popupDistance - yOffset
popupDistanceTop = selfY - popupY
popupDistanceBottom = winHeight - selfY - selfHeight - popupY
popupDistanceLeft = offset.left - popupW - xOffset
popupDistanceRight = winWidth - offset.left - selfWidth - popupW
# Check desired position and try to fit the popup into the viewport
preferredPosition = options.preferredPosition
if preferredPosition in ['left', 'right']
yDistance = 0
popupOffsetTop += selfHeight / 2 + popupH / 2
if (preferredPosition is 'right' and popupDistanceRight > windowPadding) \
or popupDistanceLeft < windowPadding
# Positioned right
popup.addClass classRight
popupOffsetLeft = offset.left + selfWidth + xOffset
else
# Positioned left
popup.addClass classLeft
popupOffsetLeft = offset.left - popupW - xOffset
xDistance = -xDistance
else
xDistance = 0
if popupOffsetLeft + popupCenter > winWidth - windowPadding
# Aligned left
popupOffsetLeft -= popupCenter * 2 - xOffset
popup.addClass classAlignLeft
else if popupOffsetLeft - popupCenter < windowPadding
# Aligned right
popupOffsetLeft -= xOffset
popup.addClass classAlignRight
else
# Centered
popupOffsetLeft -= popupCenter
# Move right if popup would violate left viewport bounds
if popupOffsetLeft < windowPadding
popupOffsetLeft = windowPadding
# Add class if positioned below
if (preferredPosition is 'bottom' and popupDistanceBottom > windowPadding) \
or popupDistanceTop < windowPadding
yDistance = -yDistance
popupOffsetTop += popupH + selfHeight - 2 * yOffset
popup.addClass classBottom
# Move Smallipop vertically if it wouldn't fit in the viewport
if popupH < selfHeight
yOverflow = popupOffsetTop + popupH + windowPadding - yDistance \
+ yOffset - winScrollTop - winHeight
if yOverflow > 0
popupOffsetTop = Math.max popupOffsetTop - yOverflow - windowPadding
, offset.top + yOffset + windowPadding + yDistance
# Move Smallipop horizontally if it wouldn't fit in the viewport
# and it's smaller than the trigger
if popupW < selfWidth
xOverflow = popupOffsetLeft + popupW + windowPadding + xDistance \
+ xOffset - winScrollLeft - winWidth
if xOverflow > 0
popupOffsetLeft = Math.max popupOffsetLeft - xOverflow + windowPadding
, offset.left + xOffset + windowPadding - xDistance
# Hide trigger if defined
if options.hideTrigger
trigger
.stop(true)
.fadeTo options.triggerAnimationSpeed, 0
opacity = 0
# Animate to new position if refresh does nothing
if not popupData[dataBeingShown] or options.cssAnimations.enabled
popupOffsetTop -= yDistance
popupOffsetLeft += xDistance
xDistance = yDistance = 0
opacity = 1
# If the element is fixed, it has to be moved by the current scroll offset
if isFixed
popupOffsetLeft -= winScrollLeft
popupOffsetTop -= winScrollTop
popup
.data(dataXDistance, xDistance)
.data(dataYDistance, yDistance)
.css
top: popupOffsetTop
left: popupOffsetLeft
display: 'block'
opacity: opacity
# Start fade in animation
fadeInPopup popup,
top: "-=#{yDistance}"
left: "+=#{xDistance}"
opacity: 1
forceRefreshPosition = ->
refreshPosition false
fadeInPopup = (popup, animationTarget) ->
options = getTrigger(popup.data(dataShown)).data(classBase)?.options or sip.defaults
if options.cssAnimations.enabled
popup.addClass options.cssAnimations.show
window.setTimeout ->
fadeInPopupFinished popup, options
, options.popupAnimationSpeed
else
popup
.stop(true)
.animate animationTarget, options.popupAnimationSpeed, options.funcEase, ->
fadeInPopupFinished popup, options
fadeInPopupFinished = (popup, options) ->
popupData = popup.data()
if popupData[dataBeingShown]
popup.data dataBeingShown, false
options.onAfterShow? getTrigger(popupData[dataShown])
showPopup = (trigger, content='') ->
# Get smallipop options stored in trigger and popup
triggerData = trigger.data classBase
triggerOptions = triggerData.options
popup = triggerData.popupInstance
return unless popup.data dataTriggerHovered
# Show last trigger if not yet visible
shownId = popup.data dataShown
if shownId
lastTrigger = getTrigger shownId
if lastTrigger.length
lastTriggerOpt = lastTrigger.data(classBase).options or sip.defaults
if lastTriggerOpt.hideTrigger
lastTrigger
.stop(true)
.fadeTo lastTriggerOpt.fadeSpeed, 1
# Display overlay under the trigger when tourHighlight is enabled
if triggerOptions.tourHighlight and triggerOptions.tourIndex
tourOverlay = getOverlay().css
backgroundColor: triggerOptions.tourHighlightColor
zIndex: triggerOptions.tourHighlightZIndex
resetTourZIndices()
# Set position at least to relative if it's static, or z-index won't work
if trigger.css('position') is 'static'
trigger.css 'position', 'relative'
# Trigger should stay on top of the overlay
unless trigger.data dataZIndex
trigger.data dataZIndex, trigger.css 'zIndex'
trigger.css 'zIndex', triggerOptions.tourHighlightZIndex + 1
# Show overlay
tourOverlay
.fadeTo triggerOptions.tourHighlightFadeDuration, triggerOptions.tourHighlightOpacity
else if $overlay
hideTourOverlay triggerOptions
popupContent = content or triggerData.hint
# If referenced content element is defined, use it's content
if triggerOptions.referencedContent and not content
popupContent = $(triggerOptions.referencedContent).clone(true, true) or popupContent
popupPosition = if isElementFixed trigger then 'fixed' else 'absolute'
if shownId isnt triggerData.id
popup.hide 0
# Update tip content and remove all classes
popup
.data(dataBeingShown, true)
.data(dataShown, triggerData.id)
.data(dataPosition, popupPosition)
.find('.' + classContent).empty().append popupContent
# Check if trigger has fixed position
popup.css 'position', popupPosition
# Queue the next refresh
queueRefreshPosition 0
isElementFixed = (element) ->
elemToCheck = element
while elemToCheck.length and elemToCheck[0].nodeName.toUpperCase() isnt 'HTML'
if elemToCheck.css('position') is 'fixed'
return true
elemToCheck = elemToCheck.parent()
false
triggerMouseover = ->
trigger = popup = $ @
isTrigger = trigger.hasClass classInitialized
unless isTrigger
trigger = getTrigger popup.data(dataShown)
return unless trigger.length
triggerData = trigger.data classBase
popup = triggerData.popupInstance
.data (if isTrigger then dataTriggerHovered else dataPopupHovered), true
killTimers popup
shownId = popup.data dataShown
# We should have a valid id and an active trigger by now
if shownId isnt triggerData.id or popup.css('opacity') is 0
triggerData.options.onBeforeShow? trigger
popup
.data dataTimerShow, setTimeout ->
showPopup trigger
, triggerData.options.popupDelay
triggerMouseout = ->
trigger = popup = $ @
isTrigger = trigger.hasClass classInitialized
unless isTrigger
trigger = getTrigger popup.data(dataShown)
return unless trigger.length
triggerData = trigger.data classBase
popup = triggerData.popupInstance
.data (if isTrigger then dataTriggerHovered else dataPopupHovered), false
killTimers popup
# Hide tip after a while
popupData = popup.data()
unless popupData[dataPopupHovered] or popupData[dataTriggerHovered]
triggerData.options.onBeforeHide? trigger
popup
.data dataTimerHide, setTimeout ->
hideSmallipop popup
, triggerData.options.hideDelay
onWindowScroll = (e) ->
clearTimeout scrollTimer
scrollTimer = setTimeout forceRefreshPosition, 250
setContent = (trigger, content) ->
return unless trigger?.length
triggerData = trigger.data classBase
partOfTour = triggerData.tourTitle
if partOfTour
popupContent = triggerData.popupInstance.find('.' + classTourContent)
else
popupContent = triggerData.popupInstance.find('.' + classContent)
if popupContent.html() isnt content
popupContent
.stop(true)
.fadeTo triggerData.options.contentAnimationSpeed, 0, ->
$(@)
.html(content)
.fadeTo triggerData.options.contentAnimationSpeed, 1
refreshPosition()
runTour = (trigger, step) ->
triggerData = trigger.data classBase
tourTitle = triggerData?.tourTitle
return unless tourTitle and tours[tourTitle]
# Sort tour elements before running by their index
tours[tourTitle].sort (a, b) ->
a.index - b.index
# Check if a valid step as array index was provided
unless typeof step is 'number' and step % 1 is 0
step = -1
else
step -= 1
currentTour = tourTitle
currentTourItems = tours[tourTitle]
for i in [0..currentTourItems.length - 1] when \
(step >= 0 and i is step) \
or (step < 0 and currentTourItems[i].id is triggerData.id)
return tourShow tourTitle, i
tourShow = (title, index) ->
currentTourItems = tours[title]
return unless currentTourItems
$trigger = currentTourItems[index].trigger
triggerData = $trigger.data classBase
options = triggerData.options
navigationEnabled = options.tourNavigationEnabled
navigation = ''
if navigationEnabled
navigation += "<div class='#{classTourProgress}'>" +
"#{index + 1} #{options.labels.of} #{currentTourItems.length}</div>"
if index > 0
navigation += "<a href='#' class='#{classTourPrev}'>#{options.labels.prev}</a>"
if index < currentTourItems.length - 1
navigation += "<a href='#' class='#{classTourNext}'>#{options.labels.next}</a>"
if not navigationEnabled or index is currentTourItems.length - 1
navigation += "<a href='#' class='#{classTourClose}'>#{options.labels.close}</a>"
$content = $ "<div class='#{classTourContent}'/>" +
"<a href='#' class='#{classTourCloseIcon}'>Χ</a>" +
"<div class='#{classTourFooter}'>#{navigation}</div>"
# Append hint object to tour content
$content.eq(0).append triggerData.hint
killTimers triggerData.popupInstance
triggerData.popupInstance.data dataTriggerHovered, true
# Scroll to trigger if it isn't visible
showWhenVisible $trigger, $content
showWhenVisible = ($trigger, content) ->
targetPosition = $trigger.offset().top
offset = targetPosition - $document.scrollTop()
windowHeight = $window.height()
triggerOptions = $trigger.data(classBase).options
# First scroll to trigger then show tour
if not isElementFixed($trigger) and (offset < triggerOptions.autoscrollPadding or offset > windowHeight - triggerOptions.autoscrollPadding)
$('html, body').animate
scrollTop: targetPosition - windowHeight / 2
, 800, 'swing', ->
showPopup $trigger, content
else
showPopup $trigger, content
tourNext = (e) ->
e?.preventDefault()
currentTourItems = tours[currentTour]
return unless currentTourItems
# Get currently shown tour item
$popup = currentTourItems[0].popupInstance
shownId = $popup.data(dataShown) or currentTourItems[0].id
for i in [0..currentTourItems.length - 2] when currentTourItems[i].id is shownId
triggerOptions = currentTourItems[i].trigger.data(classBase).options
if triggerOptions.tourNavigationEnabled
triggerOptions.onTourNext?(currentTourItems[i + 1].trigger)
return tourShow currentTour, i + 1
tourPrev = (e) ->
e?.preventDefault()
currentTourItems = tours[currentTour]
return unless currentTourItems
# Get currently shown tour item
$popup = currentTourItems[0].popupInstance
shownId = $popup.data(dataShown) or currentTourItems[0].id
for i in [1..currentTourItems.length - 1] when currentTourItems[i].id is shownId
triggerOptions = currentTourItems[i].trigger.data(classBase).options
if triggerOptions.tourNavigationEnabled
triggerOptions.onTourPrev?(currentTourItems[i - 1].trigger)
return tourShow currentTour, i - 1
tourClose = (e) ->
e?.preventDefault()
$popup = $(e.target).closest ".#{classInstance}"
hideSmallipop $popup
destroy = (instances) ->
instances.each ->
self = $ @
data = self.data classBase
if data
self
.unbind(".#{classBase}")
.data(classBase, {})
.removeClass filterBaseClass
onWindowKeyUp = (e) ->
targetIsInput = e?.target.tagName.toLowerCase() in ['input', 'textarea']
switch e.which
# Escape - close all popups
when 27 then hideSmallipop popup for popupId, popup of instances
# Arrow left
when 37 then tourPrev() unless targetIsInput
# Arrow right
when 39 then tourNext() unless targetIsInput
getInstance = (id='default', isTour=false) ->
return instances[id] if instances[id]
instance = $(popupTemplate)
.css('opacity', 0)
.attr('id', "#{classBase + nextInstanceId++}")
.addClass(classInstance)
.data(dataXDistance, 0)
.data(dataYDistance, 0)
.data(dataIsTour, isTour)
.bind(eventMouseOver, triggerMouseover)
.bind(eventMouseOut, triggerMouseout)
$('body').append instance
# Add some binding to events in the popup
if isTour
instance
.delegate(".#{classTourPrev}", eventClick, tourPrev)
.delegate(".#{classTourNext}", eventClick, tourNext)
.delegate(".#{classTourClose}, .#{classTourCloseIcon}", eventClick, tourClose)
else
instance.delegate('a', eventClick, hideSmallipop)
# Bind some events to the document and window if we created the first smallipop
if nextInstanceId is 2
$document.bind "#{eventClick} #{eventTouchEnd}", hideSmallipop
$window
.bind(eventResize, queueRefreshPosition)
.bind(eventScroll, onWindowScroll)
.bind(eventKeyUp, onWindowKeyUp)
instances[id] = instance
$.fn.smallipop = (options={}, hint='') ->
return @ if @length is 0
# Handle direct method calls
if typeof(options) is 'string'
switch options.toLowerCase()
when 'show' then showSmallipop.call @first().get(0)
when 'hide' then hideSmallipop @first().get(0)
when 'destroy' then destroy @
when 'tour' then runTour @first(), hint
when 'update' then setContent @first(), hint
return @
options = $.extend true, {}, sip.defaults, options
# Check for enabled css animations and disable if modernizr is active and says no
unless cssAnimationsEnabled
options.cssAnimations.enabled = false
# Initialize smallipop on first call
$popup = getInstance options.popupId
return @.each ->
$self = $ @
tagName = $self[0].tagName.toLowerCase()
type = $self.attr 'type'
triggerData = $self.data()
# Get content for the popup
# If it's inline markup, create a deep copy of the hint html
objHint = hint or $self.attr('title')
$objInfo = $ "> .#{options.infoClass}:first", $self
if $objInfo.length
objHint = $objInfo.clone(true, true).removeClass options.infoClass
# Initialize each trigger, create id and bind events
if objHint and not $self.hasClass classInitialized
newId = lastId++
triggerEvents = {}
triggerPopupInstance = $popup
triggerOptions = $.extend true, {}, options
# Check if inline smallipop options are provided as object or single data attributes
if typeof(triggerData[classBase]) is 'object'
$.extend true, triggerOptions, triggerData[classBase]
# Extend the trigger options by options set in data attribute
for option, value of triggerData when option.indexOf(classBase) >= 0
optionName = option.replace classBase, ''
if optionName
optionName = optionName.substr(0, 1).toLowerCase() + optionName.substr(1)
triggerOptions[optionName] = value
isFormElement = triggerOptions.handleInputs \
and tagName in ['input', 'select', 'textarea']
# Add to tours if tourTitle is set
if triggerOptions.tourIndex
tourTitle = triggerOptions.tourTitle or 'defaultTour'
# Disable all trigger events
triggerOptions.hideOnTriggerClick = triggerOptions.hideOnPopupClick = false
triggerPopupInstance = getInstance tourTitle, true
tours[tourTitle] = [] unless tours[tourTitle]
tours[tourTitle].push
index: triggerOptions.tourIndex or 0
id: newId
trigger: $self
popupInstance: triggerPopupInstance
else
touchTrigger = triggerOptions.touchSupport and touchEnabled
# Activate on blur events if used on inputs and disable hide on click
if isFormElement
# Don't hide when trigger is clicked and show when trigger is clicked
triggerOptions.hideOnTriggerClick = false
triggerEvents[eventFocus] = triggerMouseover
triggerEvents[eventBlur] = triggerMouseout
else if not touchTrigger
triggerEvents[eventMouseOut] = triggerMouseout
# Check whether the trigger should activate smallipop by click or hover
if triggerOptions.triggerOnClick or touchTrigger
triggerEvents[eventClick] = showSmallipop
else
triggerEvents[eventClick] = triggerMouseout
triggerEvents[eventMouseOver] = triggerMouseover
# Store parameters for this trigger
$self
.addClass("#{classInitialized} #{classBase}#{newId}")
.attr('title', '') # Remove title to disable browser hint
.data classBase,
id: newId
hint: objHint
options: triggerOptions
tagName: tagName
type: type
tourTitle: tourTitle
popupInstance: triggerPopupInstance
isFormElement: isFormElement
.bind triggerEvents
# Hide popup when links contained in the trigger are clicked
unless triggerOptions.hideOnTriggerClick
$self.delegate 'a', eventClick, hideSmallipop
))
|
[
{
"context": "of the clang related code from https://github.com/yasuyuky/autocomplete-clang\n# Copyright (c) 2014 Yasuyuki ",
"end": 65,
"score": 0.9994970560073853,
"start": 57,
"tag": "USERNAME",
"value": "yasuyuky"
},
{
"context": "m/yasuyuky/autocomplete-clang\n# Copyright (c) 20... | lib/clang-provider.coffee | benogle/autocomplete-clang | 8 | # Some of the clang related code from https://github.com/yasuyuky/autocomplete-clang
# Copyright (c) 2014 Yasuyuki YAMADA under MIT license
{Point, Range, BufferedProcess, TextEditor, CompositeDisposable} = require 'atom'
path = require 'path'
{existsSync} = require 'fs'
module.exports =
class ClangProvider
selector: '.source.cpp, .source.c, .source.objc, .source.objcpp'
inclusionPriority: 1
excludeLowerPriority: true
clangCommand: "clang"
includePaths: [".", ".."]
scopeSource:
'source.cpp': 'c++'
'source.c': 'c'
'source.objc': 'objective-c'
'source.objcpp': 'objective-c++'
getSuggestions: ({editor, scopeDescriptor, bufferPosition}) ->
language = LanguageUtil.getSourceScopeLang(@scopeSource, scopeDescriptor.getScopesArray())
prefix = LanguageUtil.prefixAtPosition(editor, bufferPosition)
symbolPosition = LanguageUtil.nearestSymbolPosition(editor, bufferPosition) ? bufferPosition
# console.log "'#{prefix}'", bufferPosition, language
if language?
@codeCompletionAt(editor, symbolPosition.row, symbolPosition.column, language).then (suggestions) =>
@filterForPrefix(suggestions, prefix)
codeCompletionAt: (editor, row, column, language) ->
command = @clangCommand
args = @buildClangArgs(editor, row, column, language)
options =
cwd: path.dirname(editor.getPath())
input: editor.getText()
new Promise (resolve) =>
allOutput = []
stdout = (output) => allOutput.push(output)
stderr = (output) => console.log output
exit = (output) => resolve(@handleCompletionResult(allOutput.join('\n')))
bufferedProcess = new BufferedProcess({command, args, options, stdout, stderr, exit})
bufferedProcess.process.stdin.setEncoding = 'utf-8';
bufferedProcess.process.stdin.write(editor.getText())
bufferedProcess.process.stdin.end()
filterForPrefix: (suggestions, prefix) ->
res = []
for suggestion in suggestions
if (suggestion.snippet or suggestion.text).startsWith(prefix)
suggestion.replacementPrefix = prefix
res.push(suggestion)
res
lineRe: /COMPLETION: (.+) : (.+)$/
returnTypeRe: /\[#([^#]+)#\]/ig
argumentRe: /\<#([^#]+)#\>/ig
convertCompletionLine: (s) ->
match = s.match(@lineRe)
if match?
[line, completion, pattern] = match
returnType = null
patternNoType = pattern.replace @returnTypeRe, (match, type) ->
returnType = type
''
index = 0
replacement = patternNoType.replace @argumentRe, (match, arg) ->
index++
"${#{index}:#{arg}}"
suggestion = {leftLabel: returnType}
if index > 0
suggestion.snippet = replacement
suggestion.type = 'method'
else
suggestion.text = replacement
suggestion.type = 'property'
suggestion
handleCompletionResult: (result) ->
outputLines = result.trim().split '\n'
completions = (@convertCompletionLine(s) for s, i in outputLines when i < 1000)
(completion for completion in completions when completion?)
buildClangArgs: (editor, row, column, language)->
# pch = [(atom.config.get "autocomplete-clang.pchFilePrefix"), language, "pch"].join '.'
args = ["-fsyntax-only", "-x#{language}", "-Xclang"]
location = "-:#{row + 1}:#{column + 1}"
args.push("-code-completion-at=#{location}")
pchPath = path.join(path.dirname(editor.getPath()), 'test.pch')
args = args.concat ["-include-pch", pchPath] if existsSync pchPath
# std = atom.config.get "autocomplete-clang.std.#{language}"
# args = args.concat ["-std=#{std}"] if std
args = args.concat("-I#{i}" for i in @includePaths)
args.push("-")
args
LanguageUtil =
getSourceScopeLang: (scopeSource, scopesArray) ->
for scope in scopesArray
return scopeSource[scope] if scope of scopeSource
null
prefixAtPosition: (editor, bufferPosition) ->
regex = /[\w0-9_-]+$/ # whatever your prefix regex might be
line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition])
line.match(regex)?[0] or ''
nearestSymbolPosition: (editor, bufferPosition) ->
methodCall = "\\[([\\w_-]+) (?:[\\w_-]+)?"
propertyAccess = "([\\w_-]+)\\.(?:[\\w_-]+)?"
regex = new RegExp("(?:#{propertyAccess})|(?:#{methodCall})$", 'i')
line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition])
matches = line.match(regex)
if matches
symbol = matches[1] ? matches[2]
symbolColumn = matches[0].indexOf(symbol) + symbol.length + (line.length - matches[0].length)
new Point(bufferPosition.row, symbolColumn)
| 11761 | # Some of the clang related code from https://github.com/yasuyuky/autocomplete-clang
# Copyright (c) 2014 <NAME> under MIT license
{Point, Range, BufferedProcess, TextEditor, CompositeDisposable} = require 'atom'
path = require 'path'
{existsSync} = require 'fs'
module.exports =
class ClangProvider
selector: '.source.cpp, .source.c, .source.objc, .source.objcpp'
inclusionPriority: 1
excludeLowerPriority: true
clangCommand: "clang"
includePaths: [".", ".."]
scopeSource:
'source.cpp': 'c++'
'source.c': 'c'
'source.objc': 'objective-c'
'source.objcpp': 'objective-c++'
getSuggestions: ({editor, scopeDescriptor, bufferPosition}) ->
language = LanguageUtil.getSourceScopeLang(@scopeSource, scopeDescriptor.getScopesArray())
prefix = LanguageUtil.prefixAtPosition(editor, bufferPosition)
symbolPosition = LanguageUtil.nearestSymbolPosition(editor, bufferPosition) ? bufferPosition
# console.log "'#{prefix}'", bufferPosition, language
if language?
@codeCompletionAt(editor, symbolPosition.row, symbolPosition.column, language).then (suggestions) =>
@filterForPrefix(suggestions, prefix)
codeCompletionAt: (editor, row, column, language) ->
command = @clangCommand
args = @buildClangArgs(editor, row, column, language)
options =
cwd: path.dirname(editor.getPath())
input: editor.getText()
new Promise (resolve) =>
allOutput = []
stdout = (output) => allOutput.push(output)
stderr = (output) => console.log output
exit = (output) => resolve(@handleCompletionResult(allOutput.join('\n')))
bufferedProcess = new BufferedProcess({command, args, options, stdout, stderr, exit})
bufferedProcess.process.stdin.setEncoding = 'utf-8';
bufferedProcess.process.stdin.write(editor.getText())
bufferedProcess.process.stdin.end()
filterForPrefix: (suggestions, prefix) ->
res = []
for suggestion in suggestions
if (suggestion.snippet or suggestion.text).startsWith(prefix)
suggestion.replacementPrefix = prefix
res.push(suggestion)
res
lineRe: /COMPLETION: (.+) : (.+)$/
returnTypeRe: /\[#([^#]+)#\]/ig
argumentRe: /\<#([^#]+)#\>/ig
convertCompletionLine: (s) ->
match = s.match(@lineRe)
if match?
[line, completion, pattern] = match
returnType = null
patternNoType = pattern.replace @returnTypeRe, (match, type) ->
returnType = type
''
index = 0
replacement = patternNoType.replace @argumentRe, (match, arg) ->
index++
"${#{index}:#{arg}}"
suggestion = {leftLabel: returnType}
if index > 0
suggestion.snippet = replacement
suggestion.type = 'method'
else
suggestion.text = replacement
suggestion.type = 'property'
suggestion
handleCompletionResult: (result) ->
outputLines = result.trim().split '\n'
completions = (@convertCompletionLine(s) for s, i in outputLines when i < 1000)
(completion for completion in completions when completion?)
buildClangArgs: (editor, row, column, language)->
# pch = [(atom.config.get "autocomplete-clang.pchFilePrefix"), language, "pch"].join '.'
args = ["-fsyntax-only", "-x#{language}", "-Xclang"]
location = "-:#{row + 1}:#{column + 1}"
args.push("-code-completion-at=#{location}")
pchPath = path.join(path.dirname(editor.getPath()), 'test.pch')
args = args.concat ["-include-pch", pchPath] if existsSync pchPath
# std = atom.config.get "autocomplete-clang.std.#{language}"
# args = args.concat ["-std=#{std}"] if std
args = args.concat("-I#{i}" for i in @includePaths)
args.push("-")
args
LanguageUtil =
getSourceScopeLang: (scopeSource, scopesArray) ->
for scope in scopesArray
return scopeSource[scope] if scope of scopeSource
null
prefixAtPosition: (editor, bufferPosition) ->
regex = /[\w0-9_-]+$/ # whatever your prefix regex might be
line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition])
line.match(regex)?[0] or ''
nearestSymbolPosition: (editor, bufferPosition) ->
methodCall = "\\[([\\w_-]+) (?:[\\w_-]+)?"
propertyAccess = "([\\w_-]+)\\.(?:[\\w_-]+)?"
regex = new RegExp("(?:#{propertyAccess})|(?:#{methodCall})$", 'i')
line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition])
matches = line.match(regex)
if matches
symbol = matches[1] ? matches[2]
symbolColumn = matches[0].indexOf(symbol) + symbol.length + (line.length - matches[0].length)
new Point(bufferPosition.row, symbolColumn)
| true | # Some of the clang related code from https://github.com/yasuyuky/autocomplete-clang
# Copyright (c) 2014 PI:NAME:<NAME>END_PI under MIT license
{Point, Range, BufferedProcess, TextEditor, CompositeDisposable} = require 'atom'
path = require 'path'
{existsSync} = require 'fs'
module.exports =
class ClangProvider
selector: '.source.cpp, .source.c, .source.objc, .source.objcpp'
inclusionPriority: 1
excludeLowerPriority: true
clangCommand: "clang"
includePaths: [".", ".."]
scopeSource:
'source.cpp': 'c++'
'source.c': 'c'
'source.objc': 'objective-c'
'source.objcpp': 'objective-c++'
getSuggestions: ({editor, scopeDescriptor, bufferPosition}) ->
language = LanguageUtil.getSourceScopeLang(@scopeSource, scopeDescriptor.getScopesArray())
prefix = LanguageUtil.prefixAtPosition(editor, bufferPosition)
symbolPosition = LanguageUtil.nearestSymbolPosition(editor, bufferPosition) ? bufferPosition
# console.log "'#{prefix}'", bufferPosition, language
if language?
@codeCompletionAt(editor, symbolPosition.row, symbolPosition.column, language).then (suggestions) =>
@filterForPrefix(suggestions, prefix)
codeCompletionAt: (editor, row, column, language) ->
command = @clangCommand
args = @buildClangArgs(editor, row, column, language)
options =
cwd: path.dirname(editor.getPath())
input: editor.getText()
new Promise (resolve) =>
allOutput = []
stdout = (output) => allOutput.push(output)
stderr = (output) => console.log output
exit = (output) => resolve(@handleCompletionResult(allOutput.join('\n')))
bufferedProcess = new BufferedProcess({command, args, options, stdout, stderr, exit})
bufferedProcess.process.stdin.setEncoding = 'utf-8';
bufferedProcess.process.stdin.write(editor.getText())
bufferedProcess.process.stdin.end()
filterForPrefix: (suggestions, prefix) ->
res = []
for suggestion in suggestions
if (suggestion.snippet or suggestion.text).startsWith(prefix)
suggestion.replacementPrefix = prefix
res.push(suggestion)
res
lineRe: /COMPLETION: (.+) : (.+)$/
returnTypeRe: /\[#([^#]+)#\]/ig
argumentRe: /\<#([^#]+)#\>/ig
convertCompletionLine: (s) ->
match = s.match(@lineRe)
if match?
[line, completion, pattern] = match
returnType = null
patternNoType = pattern.replace @returnTypeRe, (match, type) ->
returnType = type
''
index = 0
replacement = patternNoType.replace @argumentRe, (match, arg) ->
index++
"${#{index}:#{arg}}"
suggestion = {leftLabel: returnType}
if index > 0
suggestion.snippet = replacement
suggestion.type = 'method'
else
suggestion.text = replacement
suggestion.type = 'property'
suggestion
handleCompletionResult: (result) ->
outputLines = result.trim().split '\n'
completions = (@convertCompletionLine(s) for s, i in outputLines when i < 1000)
(completion for completion in completions when completion?)
buildClangArgs: (editor, row, column, language)->
# pch = [(atom.config.get "autocomplete-clang.pchFilePrefix"), language, "pch"].join '.'
args = ["-fsyntax-only", "-x#{language}", "-Xclang"]
location = "-:#{row + 1}:#{column + 1}"
args.push("-code-completion-at=#{location}")
pchPath = path.join(path.dirname(editor.getPath()), 'test.pch')
args = args.concat ["-include-pch", pchPath] if existsSync pchPath
# std = atom.config.get "autocomplete-clang.std.#{language}"
# args = args.concat ["-std=#{std}"] if std
args = args.concat("-I#{i}" for i in @includePaths)
args.push("-")
args
LanguageUtil =
getSourceScopeLang: (scopeSource, scopesArray) ->
for scope in scopesArray
return scopeSource[scope] if scope of scopeSource
null
prefixAtPosition: (editor, bufferPosition) ->
regex = /[\w0-9_-]+$/ # whatever your prefix regex might be
line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition])
line.match(regex)?[0] or ''
nearestSymbolPosition: (editor, bufferPosition) ->
methodCall = "\\[([\\w_-]+) (?:[\\w_-]+)?"
propertyAccess = "([\\w_-]+)\\.(?:[\\w_-]+)?"
regex = new RegExp("(?:#{propertyAccess})|(?:#{methodCall})$", 'i')
line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition])
matches = line.match(regex)
if matches
symbol = matches[1] ? matches[2]
symbolColumn = matches[0].indexOf(symbol) + symbol.length + (line.length - matches[0].length)
new Point(bufferPosition.row, symbolColumn)
|
[
{
"context": "Configuration:\n# \"hubot-arm\": \"git://github.com/bouzuya/hubot-arm\",\n# \"hubot-request-arm\": \"git://githu",
"end": 170,
"score": 0.9995399117469788,
"start": 163,
"tag": "USERNAME",
"value": "bouzuya"
},
{
"context": "-arm\",\n# \"hubot-request-arm\": \"git... | src/scripts/yahoo-now.coffee | bouzuya/hubot-yahoo-now | 1 | # Description
# A Hubot script that display the latest news in yahoo news feed.
#
# Dependencies:
# None
#
# Configuration:
# "hubot-arm": "git://github.com/bouzuya/hubot-arm",
# "hubot-request-arm": "git://github.com/bouzuya/hubot-request-arm",
# "moment": "^2.8.2",
# "xml2js": "^0.4.4"
#
# Commands:
# hubot yahoo-now - display the latest news in yahoo news feed.
#
# Author:
# bouzuya <m@bouzuya.net>
#
module.exports = (robot) ->
require('hubot-arm') robot
{parseString} = require 'xml2js'
moment = require 'moment'
robot.respond /yahoo-now$/i, (res) ->
res.robot.arm('request')
url: 'http://rss.dailynews.yahoo.co.jp/fc/domestic/rss.xml'
.then (r) ->
parseString r.body, (err, parsed) ->
message = parsed.rss.channel[0].item
.map (i) ->
title: i.title[0]
link: i.link[0]
pubDate: moment(i.pubDate[0])
.map (i) ->
"#{i.pubDate.format()} : #{i.title} : #{i.link}"
.join '\n'
res.send message
, (e) ->
robot.logger.error e
res.send 'yahoo-now: error'
| 165936 | # Description
# A Hubot script that display the latest news in yahoo news feed.
#
# Dependencies:
# None
#
# Configuration:
# "hubot-arm": "git://github.com/bouzuya/hubot-arm",
# "hubot-request-arm": "git://github.com/bouzuya/hubot-request-arm",
# "moment": "^2.8.2",
# "xml2js": "^0.4.4"
#
# Commands:
# hubot yahoo-now - display the latest news in yahoo news feed.
#
# Author:
# bouzuya <<EMAIL>>
#
module.exports = (robot) ->
require('hubot-arm') robot
{parseString} = require 'xml2js'
moment = require 'moment'
robot.respond /yahoo-now$/i, (res) ->
res.robot.arm('request')
url: 'http://rss.dailynews.yahoo.co.jp/fc/domestic/rss.xml'
.then (r) ->
parseString r.body, (err, parsed) ->
message = parsed.rss.channel[0].item
.map (i) ->
title: i.title[0]
link: i.link[0]
pubDate: moment(i.pubDate[0])
.map (i) ->
"#{i.pubDate.format()} : #{i.title} : #{i.link}"
.join '\n'
res.send message
, (e) ->
robot.logger.error e
res.send 'yahoo-now: error'
| true | # Description
# A Hubot script that display the latest news in yahoo news feed.
#
# Dependencies:
# None
#
# Configuration:
# "hubot-arm": "git://github.com/bouzuya/hubot-arm",
# "hubot-request-arm": "git://github.com/bouzuya/hubot-request-arm",
# "moment": "^2.8.2",
# "xml2js": "^0.4.4"
#
# Commands:
# hubot yahoo-now - display the latest news in yahoo news feed.
#
# Author:
# bouzuya <PI:EMAIL:<EMAIL>END_PI>
#
module.exports = (robot) ->
require('hubot-arm') robot
{parseString} = require 'xml2js'
moment = require 'moment'
robot.respond /yahoo-now$/i, (res) ->
res.robot.arm('request')
url: 'http://rss.dailynews.yahoo.co.jp/fc/domestic/rss.xml'
.then (r) ->
parseString r.body, (err, parsed) ->
message = parsed.rss.channel[0].item
.map (i) ->
title: i.title[0]
link: i.link[0]
pubDate: moment(i.pubDate[0])
.map (i) ->
"#{i.pubDate.format()} : #{i.title} : #{i.link}"
.join '\n'
res.send message
, (e) ->
robot.logger.error e
res.send 'yahoo-now: error'
|
[
{
"context": "lusionPriority: 1\n\n provideLinter: ->\n name: 'OCaml Merlin'\n scope: 'file'\n lintsOnChange: a",
"end": 9459,
"score": 0.6139698624610901,
"start": 9457,
"tag": "NAME",
"value": "OC"
}
] | .atom/packages/ocaml-merlin/lib/main.coffee | hill-a/atom-config | 24 | {CompositeDisposable, Disposable} = require 'atom'
languages = ['ocaml', 'ocamllex', 'ocamlyacc', 'reason']
scopes = ['ocaml'].concat languages.map (language) -> "source.#{language}"
selectors = languages.map (language) -> ".source.#{language}"
Merlin = null
Buffer = null
TypeView = null
SelectionView = null
RenameView = null
module.exports =
merlin: null
subscriptions: null
buffers: {}
typeViews: {}
selectionViews: {}
latestType: null
occurrences: null
positions: []
indentRange: null
activate: (state) ->
Merlin = require './merlin'
Buffer = require './buffer'
TypeView = require './type-view'
SelectionView = require './selection-view'
@merlin = new Merlin
@subscriptions = new CompositeDisposable
@subscriptions.add atom.config.onDidChange 'ocaml-merlin.merlinPath', =>
@restartMerlin()
target = scopes.map (scope) ->
"atom-text-editor[data-grammar='#{scope.replace /\./g, ' '}']"
.join ', '
@subscriptions.add atom.commands.add target,
'ocaml-merlin:show-type': => @toggleType()
'ocaml-merlin:toggle-type': => @toggleType()
'ocaml-merlin:shrink-type': => @shrinkType()
'ocaml-merlin:expand-type': => @expandType()
'ocaml-merlin:close-bubble': => @closeType()
'ocaml-merlin:insert-latest-type': => @insertType()
'ocaml-merlin:destruct': => @destruct()
'ocaml-merlin:next-occurrence': => @getOccurrence(1)
'ocaml-merlin:previous-occurrence': => @getOccurrence(-1)
'ocaml-merlin:go-to-declaration': => @goToDeclaration('ml')
'ocaml-merlin:go-to-type-declaration': => @goToDeclaration('mli')
'ocaml-merlin:return-from-declaration': => @returnFromDeclaration()
'ocaml-merlin:shrink-selection': => @shrinkSelection()
'ocaml-merlin:expand-selection': => @expandSelection()
'ocaml-merlin:rename-variable': => @renameVariable()
'ocaml-merlin:restart-merlin': => @restartMerlin()
@subscriptions.add atom.workspace.observeTextEditors (editor) =>
@subscriptions.add editor.observeGrammar (grammar) =>
if scopes.includes grammar.scopeName
@addBuffer editor.getBuffer()
else
@removeBuffer editor.getBuffer()
@subscriptions.add editor.onDidDestroy =>
delete @typeViews[editor.id]
delete @selectionViews[editor.id]
restartMerlin: ->
buffer.setChanged true for _, buffer of @buffers
@merlin.restart()
addBuffer: (textBuffer) ->
bufferId = textBuffer.getId()
return if @buffers[bufferId]?
buffer = new Buffer textBuffer, => delete @buffers[bufferId]
@buffers[bufferId] = buffer
@merlin.project buffer
.then ({merlinFiles, failures}) =>
atom.workspace.notificationManager.addError failures.join '\n' if failures?
return if merlinFiles.length
@merlin.setFlags buffer, atom.config.get 'ocaml-merlin.default.flags'
.then ({failures}) ->
atom.workspace.notificationManager.addError failures.join '\n' if failures?
@merlin.usePackages buffer, atom.config.get 'ocaml-merlin.default.packages'
.then ({failures}) ->
atom.workspace.notificationManager.addError failures.join '\n' if failures?
@merlin.enableExtensions buffer, atom.config.get 'ocaml-merlin.default.extensions'
@merlin.addSourcePaths buffer, atom.config.get 'ocaml-merlin.default.sourcePaths'
@merlin.addBuildPaths buffer, atom.config.get 'ocaml-merlin.default.buildPaths'
removeBuffer: (textBuffer) ->
@buffers[textBuffer.getId()]?.destroy()
getBuffer: (editor) ->
textBuffer = editor.getBuffer()
buffer = @buffers[textBuffer.getId()]
return buffer if buffer?
@addBuffer textBuffer
@buffers[textBuffer.getId()]
toggleType: ->
return unless editor = atom.workspace.getActiveTextEditor()
if @typeViews[editor.id]?.marker?.isValid()
@typeViews[editor.id].destroy()
delete @typeViews[editor.id]
else
@merlin.type @getBuffer(editor), editor.getCursorBufferPosition()
.then (typeList) =>
return unless typeList.length
typeView = new TypeView typeList, editor
@latestType = typeView.show()
@typeViews[editor.id] = typeView
shrinkType: ->
return unless editor = atom.workspace.getActiveTextEditor()
@latestType = @typeViews[editor.id]?.shrink()
expandType: ->
return unless editor = atom.workspace.getActiveTextEditor()
@latestType = @typeViews[editor.id]?.expand()
closeType: ->
return unless editor = atom.workspace.getActiveTextEditor()
@typeViews[editor.id]?.destroy()
delete @typeViews[editor.id]
insertType: ->
return unless @latestType?
return unless editor = atom.workspace.getActiveTextEditor()
editor.insertText @latestType
destruct: ->
return unless editor = atom.workspace.getActiveTextEditor()
@merlin.destruct @getBuffer(editor), editor.getSelectedBufferRange()
.then ({range, content}) =>
editor.transact 100, =>
range = editor.setTextInBufferRange range, content
@indentRange editor, range if @indentRange?
, ({message}) ->
atom.workspace.notificationManager.addError message
getOccurrence: (offset) ->
return unless editor = atom.workspace.getActiveTextEditor()
point = editor.getCursorBufferPosition()
@merlin.occurrences @getBuffer(editor), point
.then (ranges) ->
index = ranges.findIndex (range) -> range.containsPoint point
range = ranges[(index + offset) % ranges.length]
editor.setSelectedBufferRange range
goToDeclaration: (kind) ->
return unless editor = atom.workspace.getActiveTextEditor()
currentPoint = editor.getCursorBufferPosition()
@merlin.locate @getBuffer(editor), currentPoint, kind
.then ({file, point}) =>
@positions.push
file: editor.getPath()
point: currentPoint
if file isnt editor.getPath()
atom.workspace.open file,
initialLine: point.row
initialColumn: point.column
pending: true
searchAllPanes: true
else
editor.setCursorBufferPosition point
, (reason) ->
atom.workspace.notificationManager.addError reason
returnFromDeclaration: ->
return unless position = @positions.pop()
atom.workspace.open position.file,
initialLine: position.point.row
initialColumn: position.point.column
pending: true
searchAllPanes: true
getSelectionView: ->
return unless editor = atom.workspace.getActiveTextEditor()
selectionView = @selectionViews[editor.id]
return Promise.resolve(selectionView) if selectionView?.isAlive()
@merlin.enclosing @getBuffer(editor), editor.getCursorBufferPosition()
.then (ranges) =>
selectionView = new SelectionView editor, ranges
@selectionViews[editor.id] = selectionView
shrinkSelection: ->
@getSelectionView().then (selectionView) -> selectionView.shrink()
expandSelection: ->
@getSelectionView().then (selectionView) -> selectionView.expand()
renameView: (name, callback) ->
RenameView ?= require './rename-view'
new RenameView {name, callback}
renameVariable: ->
return unless editor = atom.workspace.getActiveTextEditor()
@merlin.occurrences @getBuffer(editor), editor.getCursorBufferPosition()
.then (ranges) =>
currentName = editor.getTextInBufferRange ranges[0]
@renameView currentName, (newName) ->
editor.transact ->
ranges.reverse().map (range) ->
editor.setTextInBufferRange range, newName
deactivate: ->
@merlin.close()
@subscriptions.dispose()
buffer.destroy() for _, buffer of @buffers
getPrefix: (editor, point) ->
line = editor.getTextInBufferRange([[point.row, 0], point])
line.match(/[^\s\[\](){}<>,+*\/-]*$/)[0]
provideAutocomplete: ->
minimumWordLength = 1
@subscriptions.add atom.config.observe "autocomplete-plus.minimumWordLength", (value) ->
minimumWordLength = value
completePartialPrefixes = false
@subscriptions.add atom.config.observe "ocaml-merlin.completePartialPrefixes", (value) ->
completePartialPrefixes = value
kindToType =
"Value": "value"
"Variant": "variable"
"Constructor": "class"
"Label": "keyword"
"Module": "method"
"Signature": "type"
"Type": "type"
"Method": "property"
"#": "constant"
"Exn": "keyword"
"Class": "class"
selector: selectors.join ', '
getSuggestions: ({editor, bufferPosition, activatedManually}) =>
prefix = @getPrefix editor, bufferPosition
return [] if prefix.length < (if activatedManually then 1 else minimumWordLength)
if completePartialPrefixes
replacement = prefix
promise = @merlin.expand @getBuffer(editor), bufferPosition, prefix
else
index = prefix.lastIndexOf "."
replacement = prefix.substr(index + 1) if index >= 0
promise = @merlin.complete @getBuffer(editor), bufferPosition, prefix
promise.then (entries) ->
entries.map ({name, kind, desc, info}) ->
text: name
replacementPrefix: replacement
type: kindToType[kind]
leftLabel: kind
rightLabel: desc
description: if info.length then info else desc
disableForSelector: (selectors.map (selector) -> selector + " .comment").join ', '
inclusionPriority: 1
provideLinter: ->
name: 'OCaml Merlin'
scope: 'file'
lintsOnChange: atom.config.get 'ocaml-merlin.lintAsYouType'
grammarScopes: scopes
lint: (editor) =>
return [] unless buffer = @getBuffer(editor)
@merlin.errors buffer
.then (errors) ->
errors.map ({range, type, message}) ->
location:
file: editor.getPath()
position: range
excerpt: if message.match '\n' then type[0].toUpperCase() + type[1..-1] else message
severity: if type is 'warning' then 'warning' else 'error'
description: if message.match '\n' then "```\n#{message}```" else null
solutions: if m = message.match /Hint: Did you mean (.*)\?/ then [
position: range
replaceWith: m[1]
] else []
consumeIndent: ({@indentRange}) ->
new Disposable => @indentRange = null
| 120825 | {CompositeDisposable, Disposable} = require 'atom'
languages = ['ocaml', 'ocamllex', 'ocamlyacc', 'reason']
scopes = ['ocaml'].concat languages.map (language) -> "source.#{language}"
selectors = languages.map (language) -> ".source.#{language}"
Merlin = null
Buffer = null
TypeView = null
SelectionView = null
RenameView = null
module.exports =
merlin: null
subscriptions: null
buffers: {}
typeViews: {}
selectionViews: {}
latestType: null
occurrences: null
positions: []
indentRange: null
activate: (state) ->
Merlin = require './merlin'
Buffer = require './buffer'
TypeView = require './type-view'
SelectionView = require './selection-view'
@merlin = new Merlin
@subscriptions = new CompositeDisposable
@subscriptions.add atom.config.onDidChange 'ocaml-merlin.merlinPath', =>
@restartMerlin()
target = scopes.map (scope) ->
"atom-text-editor[data-grammar='#{scope.replace /\./g, ' '}']"
.join ', '
@subscriptions.add atom.commands.add target,
'ocaml-merlin:show-type': => @toggleType()
'ocaml-merlin:toggle-type': => @toggleType()
'ocaml-merlin:shrink-type': => @shrinkType()
'ocaml-merlin:expand-type': => @expandType()
'ocaml-merlin:close-bubble': => @closeType()
'ocaml-merlin:insert-latest-type': => @insertType()
'ocaml-merlin:destruct': => @destruct()
'ocaml-merlin:next-occurrence': => @getOccurrence(1)
'ocaml-merlin:previous-occurrence': => @getOccurrence(-1)
'ocaml-merlin:go-to-declaration': => @goToDeclaration('ml')
'ocaml-merlin:go-to-type-declaration': => @goToDeclaration('mli')
'ocaml-merlin:return-from-declaration': => @returnFromDeclaration()
'ocaml-merlin:shrink-selection': => @shrinkSelection()
'ocaml-merlin:expand-selection': => @expandSelection()
'ocaml-merlin:rename-variable': => @renameVariable()
'ocaml-merlin:restart-merlin': => @restartMerlin()
@subscriptions.add atom.workspace.observeTextEditors (editor) =>
@subscriptions.add editor.observeGrammar (grammar) =>
if scopes.includes grammar.scopeName
@addBuffer editor.getBuffer()
else
@removeBuffer editor.getBuffer()
@subscriptions.add editor.onDidDestroy =>
delete @typeViews[editor.id]
delete @selectionViews[editor.id]
restartMerlin: ->
buffer.setChanged true for _, buffer of @buffers
@merlin.restart()
addBuffer: (textBuffer) ->
bufferId = textBuffer.getId()
return if @buffers[bufferId]?
buffer = new Buffer textBuffer, => delete @buffers[bufferId]
@buffers[bufferId] = buffer
@merlin.project buffer
.then ({merlinFiles, failures}) =>
atom.workspace.notificationManager.addError failures.join '\n' if failures?
return if merlinFiles.length
@merlin.setFlags buffer, atom.config.get 'ocaml-merlin.default.flags'
.then ({failures}) ->
atom.workspace.notificationManager.addError failures.join '\n' if failures?
@merlin.usePackages buffer, atom.config.get 'ocaml-merlin.default.packages'
.then ({failures}) ->
atom.workspace.notificationManager.addError failures.join '\n' if failures?
@merlin.enableExtensions buffer, atom.config.get 'ocaml-merlin.default.extensions'
@merlin.addSourcePaths buffer, atom.config.get 'ocaml-merlin.default.sourcePaths'
@merlin.addBuildPaths buffer, atom.config.get 'ocaml-merlin.default.buildPaths'
removeBuffer: (textBuffer) ->
@buffers[textBuffer.getId()]?.destroy()
getBuffer: (editor) ->
textBuffer = editor.getBuffer()
buffer = @buffers[textBuffer.getId()]
return buffer if buffer?
@addBuffer textBuffer
@buffers[textBuffer.getId()]
toggleType: ->
return unless editor = atom.workspace.getActiveTextEditor()
if @typeViews[editor.id]?.marker?.isValid()
@typeViews[editor.id].destroy()
delete @typeViews[editor.id]
else
@merlin.type @getBuffer(editor), editor.getCursorBufferPosition()
.then (typeList) =>
return unless typeList.length
typeView = new TypeView typeList, editor
@latestType = typeView.show()
@typeViews[editor.id] = typeView
shrinkType: ->
return unless editor = atom.workspace.getActiveTextEditor()
@latestType = @typeViews[editor.id]?.shrink()
expandType: ->
return unless editor = atom.workspace.getActiveTextEditor()
@latestType = @typeViews[editor.id]?.expand()
closeType: ->
return unless editor = atom.workspace.getActiveTextEditor()
@typeViews[editor.id]?.destroy()
delete @typeViews[editor.id]
insertType: ->
return unless @latestType?
return unless editor = atom.workspace.getActiveTextEditor()
editor.insertText @latestType
destruct: ->
return unless editor = atom.workspace.getActiveTextEditor()
@merlin.destruct @getBuffer(editor), editor.getSelectedBufferRange()
.then ({range, content}) =>
editor.transact 100, =>
range = editor.setTextInBufferRange range, content
@indentRange editor, range if @indentRange?
, ({message}) ->
atom.workspace.notificationManager.addError message
getOccurrence: (offset) ->
return unless editor = atom.workspace.getActiveTextEditor()
point = editor.getCursorBufferPosition()
@merlin.occurrences @getBuffer(editor), point
.then (ranges) ->
index = ranges.findIndex (range) -> range.containsPoint point
range = ranges[(index + offset) % ranges.length]
editor.setSelectedBufferRange range
goToDeclaration: (kind) ->
return unless editor = atom.workspace.getActiveTextEditor()
currentPoint = editor.getCursorBufferPosition()
@merlin.locate @getBuffer(editor), currentPoint, kind
.then ({file, point}) =>
@positions.push
file: editor.getPath()
point: currentPoint
if file isnt editor.getPath()
atom.workspace.open file,
initialLine: point.row
initialColumn: point.column
pending: true
searchAllPanes: true
else
editor.setCursorBufferPosition point
, (reason) ->
atom.workspace.notificationManager.addError reason
returnFromDeclaration: ->
return unless position = @positions.pop()
atom.workspace.open position.file,
initialLine: position.point.row
initialColumn: position.point.column
pending: true
searchAllPanes: true
getSelectionView: ->
return unless editor = atom.workspace.getActiveTextEditor()
selectionView = @selectionViews[editor.id]
return Promise.resolve(selectionView) if selectionView?.isAlive()
@merlin.enclosing @getBuffer(editor), editor.getCursorBufferPosition()
.then (ranges) =>
selectionView = new SelectionView editor, ranges
@selectionViews[editor.id] = selectionView
shrinkSelection: ->
@getSelectionView().then (selectionView) -> selectionView.shrink()
expandSelection: ->
@getSelectionView().then (selectionView) -> selectionView.expand()
renameView: (name, callback) ->
RenameView ?= require './rename-view'
new RenameView {name, callback}
renameVariable: ->
return unless editor = atom.workspace.getActiveTextEditor()
@merlin.occurrences @getBuffer(editor), editor.getCursorBufferPosition()
.then (ranges) =>
currentName = editor.getTextInBufferRange ranges[0]
@renameView currentName, (newName) ->
editor.transact ->
ranges.reverse().map (range) ->
editor.setTextInBufferRange range, newName
deactivate: ->
@merlin.close()
@subscriptions.dispose()
buffer.destroy() for _, buffer of @buffers
getPrefix: (editor, point) ->
line = editor.getTextInBufferRange([[point.row, 0], point])
line.match(/[^\s\[\](){}<>,+*\/-]*$/)[0]
provideAutocomplete: ->
minimumWordLength = 1
@subscriptions.add atom.config.observe "autocomplete-plus.minimumWordLength", (value) ->
minimumWordLength = value
completePartialPrefixes = false
@subscriptions.add atom.config.observe "ocaml-merlin.completePartialPrefixes", (value) ->
completePartialPrefixes = value
kindToType =
"Value": "value"
"Variant": "variable"
"Constructor": "class"
"Label": "keyword"
"Module": "method"
"Signature": "type"
"Type": "type"
"Method": "property"
"#": "constant"
"Exn": "keyword"
"Class": "class"
selector: selectors.join ', '
getSuggestions: ({editor, bufferPosition, activatedManually}) =>
prefix = @getPrefix editor, bufferPosition
return [] if prefix.length < (if activatedManually then 1 else minimumWordLength)
if completePartialPrefixes
replacement = prefix
promise = @merlin.expand @getBuffer(editor), bufferPosition, prefix
else
index = prefix.lastIndexOf "."
replacement = prefix.substr(index + 1) if index >= 0
promise = @merlin.complete @getBuffer(editor), bufferPosition, prefix
promise.then (entries) ->
entries.map ({name, kind, desc, info}) ->
text: name
replacementPrefix: replacement
type: kindToType[kind]
leftLabel: kind
rightLabel: desc
description: if info.length then info else desc
disableForSelector: (selectors.map (selector) -> selector + " .comment").join ', '
inclusionPriority: 1
provideLinter: ->
name: '<NAME>aml Merlin'
scope: 'file'
lintsOnChange: atom.config.get 'ocaml-merlin.lintAsYouType'
grammarScopes: scopes
lint: (editor) =>
return [] unless buffer = @getBuffer(editor)
@merlin.errors buffer
.then (errors) ->
errors.map ({range, type, message}) ->
location:
file: editor.getPath()
position: range
excerpt: if message.match '\n' then type[0].toUpperCase() + type[1..-1] else message
severity: if type is 'warning' then 'warning' else 'error'
description: if message.match '\n' then "```\n#{message}```" else null
solutions: if m = message.match /Hint: Did you mean (.*)\?/ then [
position: range
replaceWith: m[1]
] else []
consumeIndent: ({@indentRange}) ->
new Disposable => @indentRange = null
| true | {CompositeDisposable, Disposable} = require 'atom'
languages = ['ocaml', 'ocamllex', 'ocamlyacc', 'reason']
scopes = ['ocaml'].concat languages.map (language) -> "source.#{language}"
selectors = languages.map (language) -> ".source.#{language}"
Merlin = null
Buffer = null
TypeView = null
SelectionView = null
RenameView = null
module.exports =
merlin: null
subscriptions: null
buffers: {}
typeViews: {}
selectionViews: {}
latestType: null
occurrences: null
positions: []
indentRange: null
activate: (state) ->
Merlin = require './merlin'
Buffer = require './buffer'
TypeView = require './type-view'
SelectionView = require './selection-view'
@merlin = new Merlin
@subscriptions = new CompositeDisposable
@subscriptions.add atom.config.onDidChange 'ocaml-merlin.merlinPath', =>
@restartMerlin()
target = scopes.map (scope) ->
"atom-text-editor[data-grammar='#{scope.replace /\./g, ' '}']"
.join ', '
@subscriptions.add atom.commands.add target,
'ocaml-merlin:show-type': => @toggleType()
'ocaml-merlin:toggle-type': => @toggleType()
'ocaml-merlin:shrink-type': => @shrinkType()
'ocaml-merlin:expand-type': => @expandType()
'ocaml-merlin:close-bubble': => @closeType()
'ocaml-merlin:insert-latest-type': => @insertType()
'ocaml-merlin:destruct': => @destruct()
'ocaml-merlin:next-occurrence': => @getOccurrence(1)
'ocaml-merlin:previous-occurrence': => @getOccurrence(-1)
'ocaml-merlin:go-to-declaration': => @goToDeclaration('ml')
'ocaml-merlin:go-to-type-declaration': => @goToDeclaration('mli')
'ocaml-merlin:return-from-declaration': => @returnFromDeclaration()
'ocaml-merlin:shrink-selection': => @shrinkSelection()
'ocaml-merlin:expand-selection': => @expandSelection()
'ocaml-merlin:rename-variable': => @renameVariable()
'ocaml-merlin:restart-merlin': => @restartMerlin()
@subscriptions.add atom.workspace.observeTextEditors (editor) =>
@subscriptions.add editor.observeGrammar (grammar) =>
if scopes.includes grammar.scopeName
@addBuffer editor.getBuffer()
else
@removeBuffer editor.getBuffer()
@subscriptions.add editor.onDidDestroy =>
delete @typeViews[editor.id]
delete @selectionViews[editor.id]
restartMerlin: ->
buffer.setChanged true for _, buffer of @buffers
@merlin.restart()
addBuffer: (textBuffer) ->
bufferId = textBuffer.getId()
return if @buffers[bufferId]?
buffer = new Buffer textBuffer, => delete @buffers[bufferId]
@buffers[bufferId] = buffer
@merlin.project buffer
.then ({merlinFiles, failures}) =>
atom.workspace.notificationManager.addError failures.join '\n' if failures?
return if merlinFiles.length
@merlin.setFlags buffer, atom.config.get 'ocaml-merlin.default.flags'
.then ({failures}) ->
atom.workspace.notificationManager.addError failures.join '\n' if failures?
@merlin.usePackages buffer, atom.config.get 'ocaml-merlin.default.packages'
.then ({failures}) ->
atom.workspace.notificationManager.addError failures.join '\n' if failures?
@merlin.enableExtensions buffer, atom.config.get 'ocaml-merlin.default.extensions'
@merlin.addSourcePaths buffer, atom.config.get 'ocaml-merlin.default.sourcePaths'
@merlin.addBuildPaths buffer, atom.config.get 'ocaml-merlin.default.buildPaths'
removeBuffer: (textBuffer) ->
@buffers[textBuffer.getId()]?.destroy()
getBuffer: (editor) ->
textBuffer = editor.getBuffer()
buffer = @buffers[textBuffer.getId()]
return buffer if buffer?
@addBuffer textBuffer
@buffers[textBuffer.getId()]
toggleType: ->
return unless editor = atom.workspace.getActiveTextEditor()
if @typeViews[editor.id]?.marker?.isValid()
@typeViews[editor.id].destroy()
delete @typeViews[editor.id]
else
@merlin.type @getBuffer(editor), editor.getCursorBufferPosition()
.then (typeList) =>
return unless typeList.length
typeView = new TypeView typeList, editor
@latestType = typeView.show()
@typeViews[editor.id] = typeView
shrinkType: ->
return unless editor = atom.workspace.getActiveTextEditor()
@latestType = @typeViews[editor.id]?.shrink()
expandType: ->
return unless editor = atom.workspace.getActiveTextEditor()
@latestType = @typeViews[editor.id]?.expand()
closeType: ->
return unless editor = atom.workspace.getActiveTextEditor()
@typeViews[editor.id]?.destroy()
delete @typeViews[editor.id]
insertType: ->
return unless @latestType?
return unless editor = atom.workspace.getActiveTextEditor()
editor.insertText @latestType
destruct: ->
return unless editor = atom.workspace.getActiveTextEditor()
@merlin.destruct @getBuffer(editor), editor.getSelectedBufferRange()
.then ({range, content}) =>
editor.transact 100, =>
range = editor.setTextInBufferRange range, content
@indentRange editor, range if @indentRange?
, ({message}) ->
atom.workspace.notificationManager.addError message
getOccurrence: (offset) ->
return unless editor = atom.workspace.getActiveTextEditor()
point = editor.getCursorBufferPosition()
@merlin.occurrences @getBuffer(editor), point
.then (ranges) ->
index = ranges.findIndex (range) -> range.containsPoint point
range = ranges[(index + offset) % ranges.length]
editor.setSelectedBufferRange range
goToDeclaration: (kind) ->
return unless editor = atom.workspace.getActiveTextEditor()
currentPoint = editor.getCursorBufferPosition()
@merlin.locate @getBuffer(editor), currentPoint, kind
.then ({file, point}) =>
@positions.push
file: editor.getPath()
point: currentPoint
if file isnt editor.getPath()
atom.workspace.open file,
initialLine: point.row
initialColumn: point.column
pending: true
searchAllPanes: true
else
editor.setCursorBufferPosition point
, (reason) ->
atom.workspace.notificationManager.addError reason
returnFromDeclaration: ->
return unless position = @positions.pop()
atom.workspace.open position.file,
initialLine: position.point.row
initialColumn: position.point.column
pending: true
searchAllPanes: true
getSelectionView: ->
return unless editor = atom.workspace.getActiveTextEditor()
selectionView = @selectionViews[editor.id]
return Promise.resolve(selectionView) if selectionView?.isAlive()
@merlin.enclosing @getBuffer(editor), editor.getCursorBufferPosition()
.then (ranges) =>
selectionView = new SelectionView editor, ranges
@selectionViews[editor.id] = selectionView
shrinkSelection: ->
@getSelectionView().then (selectionView) -> selectionView.shrink()
expandSelection: ->
@getSelectionView().then (selectionView) -> selectionView.expand()
renameView: (name, callback) ->
RenameView ?= require './rename-view'
new RenameView {name, callback}
renameVariable: ->
return unless editor = atom.workspace.getActiveTextEditor()
@merlin.occurrences @getBuffer(editor), editor.getCursorBufferPosition()
.then (ranges) =>
currentName = editor.getTextInBufferRange ranges[0]
@renameView currentName, (newName) ->
editor.transact ->
ranges.reverse().map (range) ->
editor.setTextInBufferRange range, newName
deactivate: ->
@merlin.close()
@subscriptions.dispose()
buffer.destroy() for _, buffer of @buffers
getPrefix: (editor, point) ->
line = editor.getTextInBufferRange([[point.row, 0], point])
line.match(/[^\s\[\](){}<>,+*\/-]*$/)[0]
provideAutocomplete: ->
minimumWordLength = 1
@subscriptions.add atom.config.observe "autocomplete-plus.minimumWordLength", (value) ->
minimumWordLength = value
completePartialPrefixes = false
@subscriptions.add atom.config.observe "ocaml-merlin.completePartialPrefixes", (value) ->
completePartialPrefixes = value
kindToType =
"Value": "value"
"Variant": "variable"
"Constructor": "class"
"Label": "keyword"
"Module": "method"
"Signature": "type"
"Type": "type"
"Method": "property"
"#": "constant"
"Exn": "keyword"
"Class": "class"
selector: selectors.join ', '
getSuggestions: ({editor, bufferPosition, activatedManually}) =>
prefix = @getPrefix editor, bufferPosition
return [] if prefix.length < (if activatedManually then 1 else minimumWordLength)
if completePartialPrefixes
replacement = prefix
promise = @merlin.expand @getBuffer(editor), bufferPosition, prefix
else
index = prefix.lastIndexOf "."
replacement = prefix.substr(index + 1) if index >= 0
promise = @merlin.complete @getBuffer(editor), bufferPosition, prefix
promise.then (entries) ->
entries.map ({name, kind, desc, info}) ->
text: name
replacementPrefix: replacement
type: kindToType[kind]
leftLabel: kind
rightLabel: desc
description: if info.length then info else desc
disableForSelector: (selectors.map (selector) -> selector + " .comment").join ', '
inclusionPriority: 1
provideLinter: ->
name: 'PI:NAME:<NAME>END_PIaml Merlin'
scope: 'file'
lintsOnChange: atom.config.get 'ocaml-merlin.lintAsYouType'
grammarScopes: scopes
lint: (editor) =>
return [] unless buffer = @getBuffer(editor)
@merlin.errors buffer
.then (errors) ->
errors.map ({range, type, message}) ->
location:
file: editor.getPath()
position: range
excerpt: if message.match '\n' then type[0].toUpperCase() + type[1..-1] else message
severity: if type is 'warning' then 'warning' else 'error'
description: if message.match '\n' then "```\n#{message}```" else null
solutions: if m = message.match /Hint: Did you mean (.*)\?/ then [
position: range
replaceWith: m[1]
] else []
consumeIndent: ({@indentRange}) ->
new Disposable => @indentRange = null
|
[
{
"context": "\n\nmodule.exports = class AuctionReminders\n key: 'auction-reminders'\n\n expires: 1800 # 30 minutes\n\n attrs: [\n 'i",
"end": 173,
"score": 0.9466074705123901,
"start": 156,
"tag": "KEY",
"value": "auction-reminders"
}
] | src/desktop/components/auction_reminders/fetch.coffee | streamich/force | 1 | Q = require 'bluebird-q'
cache = require '../../lib/cache'
Auctions = require '../../collections/auctions'
module.exports = class AuctionReminders
key: 'auction-reminders'
expires: 1800 # 30 minutes
attrs: [
'id'
'name'
'start_at'
'live_start_at'
'registration_ends_at'
'end_at'
'sale_type'
'is_auction'
'image_versions'
'image_url'
'auction_state'
]
constructor: ->
@auctions = new Auctions
cached: (callback) ->
Q.promise (resolve, reject) =>
set = (data) =>
cache.set @key, JSON.stringify(data), @expires
resolve data
cache.get @key, (err, cached) =>
return reject err if err?
return resolve JSON.parse(cached) if cached?
callback set, reject
fetch: ->
@cached (resolve, reject) =>
@auctions
.fetch
cache: true
data:
live: true
published: true
is_auction: true
.then =>
@auctions.reset @auctions.filter (x) -> x.reminderStatus()
resolve @auctions.invoke('pick', @attrs)
.catch reject
.done()
| 6283 | Q = require 'bluebird-q'
cache = require '../../lib/cache'
Auctions = require '../../collections/auctions'
module.exports = class AuctionReminders
key: '<KEY>'
expires: 1800 # 30 minutes
attrs: [
'id'
'name'
'start_at'
'live_start_at'
'registration_ends_at'
'end_at'
'sale_type'
'is_auction'
'image_versions'
'image_url'
'auction_state'
]
constructor: ->
@auctions = new Auctions
cached: (callback) ->
Q.promise (resolve, reject) =>
set = (data) =>
cache.set @key, JSON.stringify(data), @expires
resolve data
cache.get @key, (err, cached) =>
return reject err if err?
return resolve JSON.parse(cached) if cached?
callback set, reject
fetch: ->
@cached (resolve, reject) =>
@auctions
.fetch
cache: true
data:
live: true
published: true
is_auction: true
.then =>
@auctions.reset @auctions.filter (x) -> x.reminderStatus()
resolve @auctions.invoke('pick', @attrs)
.catch reject
.done()
| true | Q = require 'bluebird-q'
cache = require '../../lib/cache'
Auctions = require '../../collections/auctions'
module.exports = class AuctionReminders
key: 'PI:KEY:<KEY>END_PI'
expires: 1800 # 30 minutes
attrs: [
'id'
'name'
'start_at'
'live_start_at'
'registration_ends_at'
'end_at'
'sale_type'
'is_auction'
'image_versions'
'image_url'
'auction_state'
]
constructor: ->
@auctions = new Auctions
cached: (callback) ->
Q.promise (resolve, reject) =>
set = (data) =>
cache.set @key, JSON.stringify(data), @expires
resolve data
cache.get @key, (err, cached) =>
return reject err if err?
return resolve JSON.parse(cached) if cached?
callback set, reject
fetch: ->
@cached (resolve, reject) =>
@auctions
.fetch
cache: true
data:
live: true
published: true
is_auction: true
.then =>
@auctions.reset @auctions.filter (x) -> x.reminderStatus()
resolve @auctions.invoke('pick', @attrs)
.catch reject
.done()
|
[
{
"context": "le is part of the Mooch package.\n\nCopyright © 2013 Erin Millard\n\nFor the full copyright and license information, ",
"end": 74,
"score": 0.9998162388801575,
"start": 62,
"tag": "NAME",
"value": "Erin Millard"
}
] | src/mooch.coffee | vanwars/twitter-proxy-cors | 19 | ###
This file is part of the Mooch package.
Copyright © 2013 Erin Millard
For the full copyright and license information, please view the LICENSE file
that was distributed with this source code.
###
moment = require 'moment'
os = require 'os'
Server = require './Server'
allow = []
deny = []
if process.env.MOOCH_ALLOW?
allowStrings = JSON.parse process.env.MOOCH_ALLOW
allow.push new RegExp pattern for pattern in allowStrings
if process.env.MOOCH_DENY?
denyStrings = JSON.parse process.env.MOOCH_DENY
deny.push new RegExp pattern for pattern in denyStrings
options =
consumerKey: process.env.MOOCH_CONSUMER_KEY
consumerSecret: process.env.MOOCH_CONSUMER_SECRET
twitterUri: process.env.MOOCH_TWITTER_URI
allow: allow
deny: deny
server = new Server options
server.listen process.env.PORT
| 72725 | ###
This file is part of the Mooch package.
Copyright © 2013 <NAME>
For the full copyright and license information, please view the LICENSE file
that was distributed with this source code.
###
moment = require 'moment'
os = require 'os'
Server = require './Server'
allow = []
deny = []
if process.env.MOOCH_ALLOW?
allowStrings = JSON.parse process.env.MOOCH_ALLOW
allow.push new RegExp pattern for pattern in allowStrings
if process.env.MOOCH_DENY?
denyStrings = JSON.parse process.env.MOOCH_DENY
deny.push new RegExp pattern for pattern in denyStrings
options =
consumerKey: process.env.MOOCH_CONSUMER_KEY
consumerSecret: process.env.MOOCH_CONSUMER_SECRET
twitterUri: process.env.MOOCH_TWITTER_URI
allow: allow
deny: deny
server = new Server options
server.listen process.env.PORT
| true | ###
This file is part of the Mooch package.
Copyright © 2013 PI:NAME:<NAME>END_PI
For the full copyright and license information, please view the LICENSE file
that was distributed with this source code.
###
moment = require 'moment'
os = require 'os'
Server = require './Server'
allow = []
deny = []
if process.env.MOOCH_ALLOW?
allowStrings = JSON.parse process.env.MOOCH_ALLOW
allow.push new RegExp pattern for pattern in allowStrings
if process.env.MOOCH_DENY?
denyStrings = JSON.parse process.env.MOOCH_DENY
deny.push new RegExp pattern for pattern in denyStrings
options =
consumerKey: process.env.MOOCH_CONSUMER_KEY
consumerSecret: process.env.MOOCH_CONSUMER_SECRET
twitterUri: process.env.MOOCH_TWITTER_URI
allow: allow
deny: deny
server = new Server options
server.listen process.env.PORT
|
[
{
"context": "rview Tests for prefer-rest-params rule.\n# @author Toru Nagashima\n###\n\n'use strict'\n\n#-----------------------------",
"end": 80,
"score": 0.9998577237129211,
"start": 66,
"tag": "NAME",
"value": "Toru Nagashima"
}
] | src/tests/rules/prefer-rest-params.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for prefer-rest-params rule.
# @author Toru Nagashima
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/prefer-rest-params'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'prefer-rest-params', rule,
valid: [
'arguments'
'(...args) -> args'
'-> arguments.length'
'-> arguments.callee'
]
invalid: [
code: '-> arguments'
errors: [
type: 'Identifier'
message: "Use the rest parameters instead of 'arguments'."
]
,
code: '-> arguments[0]'
errors: [
type: 'Identifier'
message: "Use the rest parameters instead of 'arguments'."
]
,
code: '-> arguments[1]'
errors: [
type: 'Identifier'
message: "Use the rest parameters instead of 'arguments'."
]
,
code: '-> arguments[Symbol.iterator]'
errors: [
type: 'Identifier'
message: "Use the rest parameters instead of 'arguments'."
]
]
| 222165 | ###*
# @fileoverview Tests for prefer-rest-params rule.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/prefer-rest-params'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'prefer-rest-params', rule,
valid: [
'arguments'
'(...args) -> args'
'-> arguments.length'
'-> arguments.callee'
]
invalid: [
code: '-> arguments'
errors: [
type: 'Identifier'
message: "Use the rest parameters instead of 'arguments'."
]
,
code: '-> arguments[0]'
errors: [
type: 'Identifier'
message: "Use the rest parameters instead of 'arguments'."
]
,
code: '-> arguments[1]'
errors: [
type: 'Identifier'
message: "Use the rest parameters instead of 'arguments'."
]
,
code: '-> arguments[Symbol.iterator]'
errors: [
type: 'Identifier'
message: "Use the rest parameters instead of 'arguments'."
]
]
| true | ###*
# @fileoverview Tests for prefer-rest-params rule.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/prefer-rest-params'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'prefer-rest-params', rule,
valid: [
'arguments'
'(...args) -> args'
'-> arguments.length'
'-> arguments.callee'
]
invalid: [
code: '-> arguments'
errors: [
type: 'Identifier'
message: "Use the rest parameters instead of 'arguments'."
]
,
code: '-> arguments[0]'
errors: [
type: 'Identifier'
message: "Use the rest parameters instead of 'arguments'."
]
,
code: '-> arguments[1]'
errors: [
type: 'Identifier'
message: "Use the rest parameters instead of 'arguments'."
]
,
code: '-> arguments[Symbol.iterator]'
errors: [
type: 'Identifier'
message: "Use the rest parameters instead of 'arguments'."
]
]
|
[
{
"context": "allowed via Secret URL'\n\n\t\tuserData =\n\t\t\tusername: formData.username\n\t\t\temail: formData.email\n\t\t\tpassword: formData.pa",
"end": 544,
"score": 0.9988045692443848,
"start": 527,
"tag": "USERNAME",
"value": "formData.username"
},
{
"context": "ata.username\... | server/methods/registerUser.coffee | ImpressiveSetOfIntelligentStudents/chat | 0 | Meteor.methods
registerUser: (formData) ->
if RocketChat.settings.get('Accounts_RegistrationForm') is 'Disabled'
throw new Meteor.Error 'registration-disabled', 'User registration is disabled'
else 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 =
username: formData.username
email: formData.email
password: formData.pass
userId = Accounts.createUser userData
RocketChat.models.Users.setUserActive userId, true
profile = {}
RocketChat.models.Users.setProfile userId, profile
RocketChat.models.Users.setName userId, formData.username
return userId
| 172959 | Meteor.methods
registerUser: (formData) ->
if RocketChat.settings.get('Accounts_RegistrationForm') is 'Disabled'
throw new Meteor.Error 'registration-disabled', 'User registration is disabled'
else 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 =
username: formData.username
email: formData.email
password: <PASSWORD>
userId = Accounts.createUser userData
RocketChat.models.Users.setUserActive userId, true
profile = {}
RocketChat.models.Users.setProfile userId, profile
RocketChat.models.Users.setName userId, formData.username
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'
else 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 =
username: formData.username
email: formData.email
password: PI:PASSWORD:<PASSWORD>END_PI
userId = Accounts.createUser userData
RocketChat.models.Users.setUserActive userId, true
profile = {}
RocketChat.models.Users.setProfile userId, profile
RocketChat.models.Users.setName userId, formData.username
return userId
|
[
{
"context": "ail: (test) ->\n test.ok(U.isGoogleEmail('abc@gmail.com'))\n test.ok(U.isGoogleEmail('abc@googlem",
"end": 332,
"score": 0.9999037981033325,
"start": 319,
"tag": "EMAIL",
"value": "abc@gmail.com"
},
{
"context": "c@gmail.com'))\n test.ok(U.isG... | src/tests/server/user/test_utils.coffee | LaPingvino/rizzoma | 88 | testCase = require('nodeunit').testCase
U = require('../../../server/user/utils').UserUtils
module.exports =
TestUserUtils: testCase
setUp: (callback) ->
callback()
tearDown: (callback) ->
callback()
testIsGoogleEmail: (test) ->
test.ok(U.isGoogleEmail('abc@gmail.com'))
test.ok(U.isGoogleEmail('abc@googlemail.com'))
test.ok(not U.isGoogleEmail('abc@yandex.ru'))
test.ok(not U.isGoogleEmail('abc@gmail.com.domain.com'))
test.done()
testNormalizeGoogleEmail: (test) ->
test.equal(U._normalizeGoogleEmail('abc@gmail.com'), 'abc@googlemail.com')
test.equal(U._normalizeGoogleEmail('abc@googlemail.com'), 'abc@googlemail.com')
test.equal(U._normalizeGoogleEmail('abc+d123@gmail.com'), 'abc@googlemail.com', 'Removes +part')
test.equal(U._normalizeGoogleEmail('ab.c+d123@gmail.com'), 'abc@googlemail.com', 'Removes . from name')
test.done()
testNormalizeEmail: (test) ->
test.equal(U.normalizeEmail(' UserName@Facebook.com '), 'username@facebook.com', 'Trims and lower cases')
test.equal(U.normalizeEmail('abc@gmail.com'), 'abc@googlemail.com', 'Uses _normalizeGoogleEmail')
test.done()
| 223193 | testCase = require('nodeunit').testCase
U = require('../../../server/user/utils').UserUtils
module.exports =
TestUserUtils: testCase
setUp: (callback) ->
callback()
tearDown: (callback) ->
callback()
testIsGoogleEmail: (test) ->
test.ok(U.isGoogleEmail('<EMAIL>'))
test.ok(U.isGoogleEmail('<EMAIL>'))
test.ok(not U.isGoogleEmail('<EMAIL>'))
test.ok(not U.isGoogleEmail('<EMAIL>'))
test.done()
testNormalizeGoogleEmail: (test) ->
test.equal(U._normalizeGoogleEmail('<EMAIL>'), '<EMAIL>')
test.equal(U._normalizeGoogleEmail('<EMAIL>'), '<EMAIL>')
test.equal(U._normalizeGoogleEmail('<EMAIL>'), '<EMAIL>', 'Removes +part')
test.equal(U._normalizeGoogleEmail('<EMAIL>'), '<EMAIL>', 'Removes . from name')
test.done()
testNormalizeEmail: (test) ->
test.equal(U.normalizeEmail(' <EMAIL> '), '<EMAIL>', 'Trims and lower cases')
test.equal(U.normalizeEmail('<EMAIL>'), '<EMAIL>', 'Uses _normalizeGoogleEmail')
test.done()
| true | testCase = require('nodeunit').testCase
U = require('../../../server/user/utils').UserUtils
module.exports =
TestUserUtils: testCase
setUp: (callback) ->
callback()
tearDown: (callback) ->
callback()
testIsGoogleEmail: (test) ->
test.ok(U.isGoogleEmail('PI:EMAIL:<EMAIL>END_PI'))
test.ok(U.isGoogleEmail('PI:EMAIL:<EMAIL>END_PI'))
test.ok(not U.isGoogleEmail('PI:EMAIL:<EMAIL>END_PI'))
test.ok(not U.isGoogleEmail('PI:EMAIL:<EMAIL>END_PI'))
test.done()
testNormalizeGoogleEmail: (test) ->
test.equal(U._normalizeGoogleEmail('PI:EMAIL:<EMAIL>END_PI'), 'PI:EMAIL:<EMAIL>END_PI')
test.equal(U._normalizeGoogleEmail('PI:EMAIL:<EMAIL>END_PI'), 'PI:EMAIL:<EMAIL>END_PI')
test.equal(U._normalizeGoogleEmail('PI:EMAIL:<EMAIL>END_PI'), 'PI:EMAIL:<EMAIL>END_PI', 'Removes +part')
test.equal(U._normalizeGoogleEmail('PI:EMAIL:<EMAIL>END_PI'), 'PI:EMAIL:<EMAIL>END_PI', 'Removes . from name')
test.done()
testNormalizeEmail: (test) ->
test.equal(U.normalizeEmail(' PI:EMAIL:<EMAIL>END_PI '), 'PI:EMAIL:<EMAIL>END_PI', 'Trims and lower cases')
test.equal(U.normalizeEmail('PI:EMAIL:<EMAIL>END_PI'), 'PI:EMAIL:<EMAIL>END_PI', 'Uses _normalizeGoogleEmail')
test.done()
|
[
{
"context": "sphereClientId: 'some'\n sphereClientSecret: 'stuff'\n sphereProjectKey: 'here'\n msg = ''\n ",
"end": 1394,
"score": 0.956740140914917,
"start": 1389,
"tag": "KEY",
"value": "stuff"
}
] | src/spec/elasticio.spec.coffee | celeste-horgan/sphere-stock-import | 0 | _ = require 'underscore'
Promise = require 'bluebird'
{SphereClient} = require 'sphere-node-sdk'
{ExtendedLogger, ElasticIo} = require 'sphere-node-utils'
package_json = require '../package.json'
Config = require '../config'
elasticio = require '../lib/elasticio'
cleanup = (logger, client) ->
logger.debug 'Deleting old inventory entries...'
client.inventoryEntries.all().fetch()
.then (result) ->
Promise.all _.map result.body.results, (e) ->
client.inventoryEntries.byId(e.id).delete(e.version)
.then (results) ->
logger.debug "#{_.size results} deleted."
Promise.resolve()
describe 'elasticio integration', ->
beforeEach (done) ->
@logger = new ExtendedLogger
additionalFields:
project_key: Config.config.project_key
logConfig:
name: "#{package_json.name}-#{package_json.version}"
streams: [
{ level: 'info', stream: process.stdout }
]
@client = new SphereClient Config
@logger.info 'About to setup...'
cleanup(@logger, @client)
.then -> done()
.catch (err) -> done(err)
, 10000 # 10sec
afterEach (done) ->
@logger.info 'About to cleanup...'
cleanup(@logger, @client)
.then -> done()
.catch (err) -> done(err)
, 10000 # 10sec
it 'should work with no attachments nor body', (done) ->
cfg =
sphereClientId: 'some'
sphereClientSecret: 'stuff'
sphereProjectKey: 'here'
msg = ''
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe '[SphereStockImport] No data found in elastic.io msg.'
done()
describe 'XML file', ->
it 'should import from one file with 2 entries', (done) ->
cfg =
sphereClientId: Config.config.client_id
sphereClientSecret: Config.config.client_secret
sphereProjectKey: Config.config.project_key
xml =
'''
<root>
<row>
<code>e-123</code>
<quantity>-2</quantity>
</row>
<row>
<code>e-xyz</code>
<quantity>0</quantity>
</row>
</root>
'''
enc = Buffer.from(xml).toString('base64')
msg =
attachments:
'stock.xml':
content: enc
spyOn(ElasticIo, 'returnSuccess').andCallThrough()
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
if message is '[SphereStockImport] elastic.io messages sent.'
expect(ElasticIo.returnSuccess.callCount).toBe 3
expectedMessage =
body:
QUANTITY: -2
SKU: 'e-123'
expect(ElasticIo.returnSuccess).toHaveBeenCalledWith(expectedMessage, jasmine.any(Function))
expectedMessage =
body:
QUANTITY: 0
SKU: 'e-xyz'
expect(ElasticIo.returnSuccess).toHaveBeenCalledWith(expectedMessage, jasmine.any(Function))
done()
describe 'CSV file', ->
it 'should import from one file with 3 entries', (done) ->
cfg =
sphereClientId: Config.config.client_id
sphereClientSecret: Config.config.client_secret
sphereProjectKey: Config.config.project_key
csv =
'''
sku,quantityOnStock
c1,1
c2,2
c3,3
'''
enc = Buffer.from(csv).toString('base64')
msg =
attachments:
'stock.csv':
content: enc
spyOn(ElasticIo, 'returnSuccess').andCallThrough()
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
if message is '[SphereStockImport] elastic.io messages sent.'
expect(error).toBe null
expectedMessage =
body:
QUANTITY: 1
SKU: 'c1'
expect(ElasticIo.returnSuccess).toHaveBeenCalledWith(expectedMessage, jasmine.any(Function))
expectedMessage =
body:
QUANTITY: 2
SKU: 'c2'
expect(ElasticIo.returnSuccess).toHaveBeenCalledWith(expectedMessage, jasmine.any(Function))
expectedMessage =
body:
QUANTITY: 3
SKU: 'c3'
expect(ElasticIo.returnSuccess).toHaveBeenCalledWith(expectedMessage, jasmine.any(Function))
done()
describe 'CSV mapping', ->
it 'should import a simple entry', (done) ->
cfg =
sphereClientId: Config.config.client_id
sphereClientSecret: Config.config.client_secret
sphereProjectKey: Config.config.project_key
msg =
attachments: {}
body:
SKU: 'mySKU1'
QUANTITY: 7
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (1 were new and 0 were updates)'
msg.body.QUANTITY = '3'
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (0 were new and 1 were updates)'
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: nothing to do, everything is fine'
done()
, 10000 # 10sec
it 'should import an entry with channel key', (done) ->
cfg =
sphereClientId: Config.config.client_id
sphereClientSecret: Config.config.client_secret
sphereProjectKey: Config.config.project_key
msg =
attachments: {}
body:
SKU: 'mySKU2'
QUANTITY: -3
CHANNEL_KEY: 'channel-key-test'
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (1 were new and 0 were updates)'
msg.body.QUANTITY = '3'
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (0 were new and 1 were updates)'
done()
, 10000 # 10sec
it 'should import an entry with channel id', (done) ->
cfg =
sphereClientId: Config.config.client_id
sphereClientSecret: Config.config.client_secret
sphereProjectKey: Config.config.project_key
@client.channels.ensure('channel-id-test', ['InventorySupply', 'OrderExport', 'OrderImport'])
.then (channel) ->
msg =
attachments: {}
body:
SKU: 'mySKU3'
QUANTITY: 99
CHANNEL_ID: channel.id
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (1 were new and 0 were updates)'
msg.body.QUANTITY = '3'
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (0 were new and 1 were updates)'
done()
, 10000 # 10sec
| 114047 | _ = require 'underscore'
Promise = require 'bluebird'
{SphereClient} = require 'sphere-node-sdk'
{ExtendedLogger, ElasticIo} = require 'sphere-node-utils'
package_json = require '../package.json'
Config = require '../config'
elasticio = require '../lib/elasticio'
cleanup = (logger, client) ->
logger.debug 'Deleting old inventory entries...'
client.inventoryEntries.all().fetch()
.then (result) ->
Promise.all _.map result.body.results, (e) ->
client.inventoryEntries.byId(e.id).delete(e.version)
.then (results) ->
logger.debug "#{_.size results} deleted."
Promise.resolve()
describe 'elasticio integration', ->
beforeEach (done) ->
@logger = new ExtendedLogger
additionalFields:
project_key: Config.config.project_key
logConfig:
name: "#{package_json.name}-#{package_json.version}"
streams: [
{ level: 'info', stream: process.stdout }
]
@client = new SphereClient Config
@logger.info 'About to setup...'
cleanup(@logger, @client)
.then -> done()
.catch (err) -> done(err)
, 10000 # 10sec
afterEach (done) ->
@logger.info 'About to cleanup...'
cleanup(@logger, @client)
.then -> done()
.catch (err) -> done(err)
, 10000 # 10sec
it 'should work with no attachments nor body', (done) ->
cfg =
sphereClientId: 'some'
sphereClientSecret: '<KEY>'
sphereProjectKey: 'here'
msg = ''
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe '[SphereStockImport] No data found in elastic.io msg.'
done()
describe 'XML file', ->
it 'should import from one file with 2 entries', (done) ->
cfg =
sphereClientId: Config.config.client_id
sphereClientSecret: Config.config.client_secret
sphereProjectKey: Config.config.project_key
xml =
'''
<root>
<row>
<code>e-123</code>
<quantity>-2</quantity>
</row>
<row>
<code>e-xyz</code>
<quantity>0</quantity>
</row>
</root>
'''
enc = Buffer.from(xml).toString('base64')
msg =
attachments:
'stock.xml':
content: enc
spyOn(ElasticIo, 'returnSuccess').andCallThrough()
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
if message is '[SphereStockImport] elastic.io messages sent.'
expect(ElasticIo.returnSuccess.callCount).toBe 3
expectedMessage =
body:
QUANTITY: -2
SKU: 'e-123'
expect(ElasticIo.returnSuccess).toHaveBeenCalledWith(expectedMessage, jasmine.any(Function))
expectedMessage =
body:
QUANTITY: 0
SKU: 'e-xyz'
expect(ElasticIo.returnSuccess).toHaveBeenCalledWith(expectedMessage, jasmine.any(Function))
done()
describe 'CSV file', ->
it 'should import from one file with 3 entries', (done) ->
cfg =
sphereClientId: Config.config.client_id
sphereClientSecret: Config.config.client_secret
sphereProjectKey: Config.config.project_key
csv =
'''
sku,quantityOnStock
c1,1
c2,2
c3,3
'''
enc = Buffer.from(csv).toString('base64')
msg =
attachments:
'stock.csv':
content: enc
spyOn(ElasticIo, 'returnSuccess').andCallThrough()
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
if message is '[SphereStockImport] elastic.io messages sent.'
expect(error).toBe null
expectedMessage =
body:
QUANTITY: 1
SKU: 'c1'
expect(ElasticIo.returnSuccess).toHaveBeenCalledWith(expectedMessage, jasmine.any(Function))
expectedMessage =
body:
QUANTITY: 2
SKU: 'c2'
expect(ElasticIo.returnSuccess).toHaveBeenCalledWith(expectedMessage, jasmine.any(Function))
expectedMessage =
body:
QUANTITY: 3
SKU: 'c3'
expect(ElasticIo.returnSuccess).toHaveBeenCalledWith(expectedMessage, jasmine.any(Function))
done()
describe 'CSV mapping', ->
it 'should import a simple entry', (done) ->
cfg =
sphereClientId: Config.config.client_id
sphereClientSecret: Config.config.client_secret
sphereProjectKey: Config.config.project_key
msg =
attachments: {}
body:
SKU: 'mySKU1'
QUANTITY: 7
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (1 were new and 0 were updates)'
msg.body.QUANTITY = '3'
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (0 were new and 1 were updates)'
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: nothing to do, everything is fine'
done()
, 10000 # 10sec
it 'should import an entry with channel key', (done) ->
cfg =
sphereClientId: Config.config.client_id
sphereClientSecret: Config.config.client_secret
sphereProjectKey: Config.config.project_key
msg =
attachments: {}
body:
SKU: 'mySKU2'
QUANTITY: -3
CHANNEL_KEY: 'channel-key-test'
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (1 were new and 0 were updates)'
msg.body.QUANTITY = '3'
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (0 were new and 1 were updates)'
done()
, 10000 # 10sec
it 'should import an entry with channel id', (done) ->
cfg =
sphereClientId: Config.config.client_id
sphereClientSecret: Config.config.client_secret
sphereProjectKey: Config.config.project_key
@client.channels.ensure('channel-id-test', ['InventorySupply', 'OrderExport', 'OrderImport'])
.then (channel) ->
msg =
attachments: {}
body:
SKU: 'mySKU3'
QUANTITY: 99
CHANNEL_ID: channel.id
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (1 were new and 0 were updates)'
msg.body.QUANTITY = '3'
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (0 were new and 1 were updates)'
done()
, 10000 # 10sec
| true | _ = require 'underscore'
Promise = require 'bluebird'
{SphereClient} = require 'sphere-node-sdk'
{ExtendedLogger, ElasticIo} = require 'sphere-node-utils'
package_json = require '../package.json'
Config = require '../config'
elasticio = require '../lib/elasticio'
cleanup = (logger, client) ->
logger.debug 'Deleting old inventory entries...'
client.inventoryEntries.all().fetch()
.then (result) ->
Promise.all _.map result.body.results, (e) ->
client.inventoryEntries.byId(e.id).delete(e.version)
.then (results) ->
logger.debug "#{_.size results} deleted."
Promise.resolve()
describe 'elasticio integration', ->
beforeEach (done) ->
@logger = new ExtendedLogger
additionalFields:
project_key: Config.config.project_key
logConfig:
name: "#{package_json.name}-#{package_json.version}"
streams: [
{ level: 'info', stream: process.stdout }
]
@client = new SphereClient Config
@logger.info 'About to setup...'
cleanup(@logger, @client)
.then -> done()
.catch (err) -> done(err)
, 10000 # 10sec
afterEach (done) ->
@logger.info 'About to cleanup...'
cleanup(@logger, @client)
.then -> done()
.catch (err) -> done(err)
, 10000 # 10sec
it 'should work with no attachments nor body', (done) ->
cfg =
sphereClientId: 'some'
sphereClientSecret: 'PI:KEY:<KEY>END_PI'
sphereProjectKey: 'here'
msg = ''
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe '[SphereStockImport] No data found in elastic.io msg.'
done()
describe 'XML file', ->
it 'should import from one file with 2 entries', (done) ->
cfg =
sphereClientId: Config.config.client_id
sphereClientSecret: Config.config.client_secret
sphereProjectKey: Config.config.project_key
xml =
'''
<root>
<row>
<code>e-123</code>
<quantity>-2</quantity>
</row>
<row>
<code>e-xyz</code>
<quantity>0</quantity>
</row>
</root>
'''
enc = Buffer.from(xml).toString('base64')
msg =
attachments:
'stock.xml':
content: enc
spyOn(ElasticIo, 'returnSuccess').andCallThrough()
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
if message is '[SphereStockImport] elastic.io messages sent.'
expect(ElasticIo.returnSuccess.callCount).toBe 3
expectedMessage =
body:
QUANTITY: -2
SKU: 'e-123'
expect(ElasticIo.returnSuccess).toHaveBeenCalledWith(expectedMessage, jasmine.any(Function))
expectedMessage =
body:
QUANTITY: 0
SKU: 'e-xyz'
expect(ElasticIo.returnSuccess).toHaveBeenCalledWith(expectedMessage, jasmine.any(Function))
done()
describe 'CSV file', ->
it 'should import from one file with 3 entries', (done) ->
cfg =
sphereClientId: Config.config.client_id
sphereClientSecret: Config.config.client_secret
sphereProjectKey: Config.config.project_key
csv =
'''
sku,quantityOnStock
c1,1
c2,2
c3,3
'''
enc = Buffer.from(csv).toString('base64')
msg =
attachments:
'stock.csv':
content: enc
spyOn(ElasticIo, 'returnSuccess').andCallThrough()
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
if message is '[SphereStockImport] elastic.io messages sent.'
expect(error).toBe null
expectedMessage =
body:
QUANTITY: 1
SKU: 'c1'
expect(ElasticIo.returnSuccess).toHaveBeenCalledWith(expectedMessage, jasmine.any(Function))
expectedMessage =
body:
QUANTITY: 2
SKU: 'c2'
expect(ElasticIo.returnSuccess).toHaveBeenCalledWith(expectedMessage, jasmine.any(Function))
expectedMessage =
body:
QUANTITY: 3
SKU: 'c3'
expect(ElasticIo.returnSuccess).toHaveBeenCalledWith(expectedMessage, jasmine.any(Function))
done()
describe 'CSV mapping', ->
it 'should import a simple entry', (done) ->
cfg =
sphereClientId: Config.config.client_id
sphereClientSecret: Config.config.client_secret
sphereProjectKey: Config.config.project_key
msg =
attachments: {}
body:
SKU: 'mySKU1'
QUANTITY: 7
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (1 were new and 0 were updates)'
msg.body.QUANTITY = '3'
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (0 were new and 1 were updates)'
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: nothing to do, everything is fine'
done()
, 10000 # 10sec
it 'should import an entry with channel key', (done) ->
cfg =
sphereClientId: Config.config.client_id
sphereClientSecret: Config.config.client_secret
sphereProjectKey: Config.config.project_key
msg =
attachments: {}
body:
SKU: 'mySKU2'
QUANTITY: -3
CHANNEL_KEY: 'channel-key-test'
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (1 were new and 0 were updates)'
msg.body.QUANTITY = '3'
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (0 were new and 1 were updates)'
done()
, 10000 # 10sec
it 'should import an entry with channel id', (done) ->
cfg =
sphereClientId: Config.config.client_id
sphereClientSecret: Config.config.client_secret
sphereProjectKey: Config.config.project_key
@client.channels.ensure('channel-id-test', ['InventorySupply', 'OrderExport', 'OrderImport'])
.then (channel) ->
msg =
attachments: {}
body:
SKU: 'mySKU3'
QUANTITY: 99
CHANNEL_ID: channel.id
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (1 were new and 0 were updates)'
msg.body.QUANTITY = '3'
elasticio.process msg, cfg, (error, message) ->
expect(error).toBe null
expect(message).toBe 'Summary: there were 1 imported stocks (0 were new and 1 were updates)'
done()
, 10000 # 10sec
|
[
{
"context": "- remove access token of the user.\n#\n# Author:\n# Jirat Ki. (n3tr)\n\ngithub = require 'octonode'\npath = requi",
"end": 499,
"score": 0.9998807907104492,
"start": 491,
"tag": "NAME",
"value": "Jirat Ki"
},
{
"context": "ess token of the user.\n#\n# Author:\n# Jir... | src/gist-me.coffee | n3tr/hubot-gist-me | 1 | # Description:
# Allow you to Create Gist via Hubot
#
# Dependencies:
# "octonode"
#
# Configuration:
# GIST_ACCESS_TOKEN - (optional) Github access token with 'gist' scope.
#
# Commands:
# hubot gistme <code> - Create Gist
# hubot gistme <filename> <code> - Create Gist with filename (eg. hello.js)
# hubot gist-token:set <github_access_token> - set access token for the user, token with 'gist' scope.
# hubot gist-token:reset - remove access token of the user.
#
# Author:
# Jirat Ki. (n3tr)
github = require 'octonode'
path = require 'path'
TokenVerifier = require(path.join(__dirname, "token_verifier")).TokenVerifier
Gist = require(path.join(__dirname, "Gist.coffee")).Gist
DEFAULT_ACCESS_TOKEN = process.env.GIST_ACCESS_TOKEN
module.exports = (robot) ->
robot.respond /gistme (\S*\.\S+)?((.*\s*)+)/i, (msg) ->
name = msg.match[1]
code = msg.match[2]
if !code
return msg.send "Code is missing.";
if code.length < 5
return msg.send "Code is too short, Please try again."
user = robot.brain.userForId msg.envelope.user.id
if user? and user.gistToken?
token = user.gistToken
token ||= DEFAULT_ACCESS_TOKEN
unless token?
msg.reply "Please set GIST_ACCESS_TOKEN or set you own token by `hubot gist-token:set <you_token>`"
return
name ||= 'file1'
gist = new Gist(token,name,code)
gist.create (error, url) ->
if error
return msg.send error
msg.send "Gist created #{name}: #{url}"
#######################################################
################# TOKEN SET - RESET ###################
#######################################################
robot.respond /gist-token:set (.*)/i, (msg) ->
token = msg.match[1]
verifier = new TokenVerifier(token)
verifier.valid (result) ->
if result
msg.reply "Your token is valid. I stored it for future use."
user = robot.brain.userForId msg.envelope.user.id
user.gistToken = verifier.token
else
msg.reply "Your token is invalid, verify that it has 'gist' scope."
robot.respond /gist-token:reset/i, (msg) ->
user = robot.brain.userForId msg.envelope.user.id
delete(user.gistToken)
msg.reply "Your token has been removed."
| 34466 | # Description:
# Allow you to Create Gist via Hubot
#
# Dependencies:
# "octonode"
#
# Configuration:
# GIST_ACCESS_TOKEN - (optional) Github access token with 'gist' scope.
#
# Commands:
# hubot gistme <code> - Create Gist
# hubot gistme <filename> <code> - Create Gist with filename (eg. hello.js)
# hubot gist-token:set <github_access_token> - set access token for the user, token with 'gist' scope.
# hubot gist-token:reset - remove access token of the user.
#
# Author:
# <NAME>. (n3tr)
github = require 'octonode'
path = require 'path'
TokenVerifier = require(path.join(__dirname, "token_verifier")).TokenVerifier
Gist = require(path.join(__dirname, "Gist.coffee")).Gist
DEFAULT_ACCESS_TOKEN = process.env.GIST_ACCESS_TOKEN
module.exports = (robot) ->
robot.respond /gistme (\S*\.\S+)?((.*\s*)+)/i, (msg) ->
name = msg.match[1]
code = msg.match[2]
if !code
return msg.send "Code is missing.";
if code.length < 5
return msg.send "Code is too short, Please try again."
user = robot.brain.userForId msg.envelope.user.id
if user? and user.gistToken?
token = user.gistToken
token ||= DEFAULT_ACCESS_TOKEN
unless token?
msg.reply "Please set GIST_ACCESS_TOKEN or set you own token by `hubot gist-token:set <you_token>`"
return
name ||= 'file1'
gist = new Gist(token,name,code)
gist.create (error, url) ->
if error
return msg.send error
msg.send "Gist created #{name}: #{url}"
#######################################################
################# TOKEN SET - RESET ###################
#######################################################
robot.respond /gist-token:set (.*)/i, (msg) ->
token = msg.match[1]
verifier = new TokenVerifier(token)
verifier.valid (result) ->
if result
msg.reply "Your token is valid. I stored it for future use."
user = robot.brain.userForId msg.envelope.user.id
user.gistToken = verifier.token
else
msg.reply "Your token is invalid, verify that it has 'gist' scope."
robot.respond /gist-token:reset/i, (msg) ->
user = robot.brain.userForId msg.envelope.user.id
delete(user.gistToken)
msg.reply "Your token has been removed."
| true | # Description:
# Allow you to Create Gist via Hubot
#
# Dependencies:
# "octonode"
#
# Configuration:
# GIST_ACCESS_TOKEN - (optional) Github access token with 'gist' scope.
#
# Commands:
# hubot gistme <code> - Create Gist
# hubot gistme <filename> <code> - Create Gist with filename (eg. hello.js)
# hubot gist-token:set <github_access_token> - set access token for the user, token with 'gist' scope.
# hubot gist-token:reset - remove access token of the user.
#
# Author:
# PI:NAME:<NAME>END_PI. (n3tr)
github = require 'octonode'
path = require 'path'
TokenVerifier = require(path.join(__dirname, "token_verifier")).TokenVerifier
Gist = require(path.join(__dirname, "Gist.coffee")).Gist
DEFAULT_ACCESS_TOKEN = process.env.GIST_ACCESS_TOKEN
module.exports = (robot) ->
robot.respond /gistme (\S*\.\S+)?((.*\s*)+)/i, (msg) ->
name = msg.match[1]
code = msg.match[2]
if !code
return msg.send "Code is missing.";
if code.length < 5
return msg.send "Code is too short, Please try again."
user = robot.brain.userForId msg.envelope.user.id
if user? and user.gistToken?
token = user.gistToken
token ||= DEFAULT_ACCESS_TOKEN
unless token?
msg.reply "Please set GIST_ACCESS_TOKEN or set you own token by `hubot gist-token:set <you_token>`"
return
name ||= 'file1'
gist = new Gist(token,name,code)
gist.create (error, url) ->
if error
return msg.send error
msg.send "Gist created #{name}: #{url}"
#######################################################
################# TOKEN SET - RESET ###################
#######################################################
robot.respond /gist-token:set (.*)/i, (msg) ->
token = msg.match[1]
verifier = new TokenVerifier(token)
verifier.valid (result) ->
if result
msg.reply "Your token is valid. I stored it for future use."
user = robot.brain.userForId msg.envelope.user.id
user.gistToken = verifier.token
else
msg.reply "Your token is invalid, verify that it has 'gist' scope."
robot.respond /gist-token:reset/i, (msg) ->
user = robot.brain.userForId msg.envelope.user.id
delete(user.gistToken)
msg.reply "Your token has been removed."
|
[
{
"context": "ender: ->\n React.createElement 'h1', {}, 'Hello Arda'\n\nclass HelloContext extends Arda.Context\n compo",
"end": 212,
"score": 0.9803413152694702,
"start": 208,
"tag": "NAME",
"value": "Arda"
}
] | examples/helloworld/index.coffee | mizchi/orca | 0 | window.React = require 'react'
window.Promise = require 'bluebird'
Arda = require '../../src/'
HelloComponent = React.createClass
mixins: [Arda.mixin]
render: ->
React.createElement 'h1', {}, 'Hello Arda'
class HelloContext extends Arda.Context
component: HelloComponent
window.addEventListener 'DOMContentLoaded', ->
router = new Arda.Router(Arda.DefaultLayout, document.body)
router.pushContext(HelloContext, {})
| 125670 | window.React = require 'react'
window.Promise = require 'bluebird'
Arda = require '../../src/'
HelloComponent = React.createClass
mixins: [Arda.mixin]
render: ->
React.createElement 'h1', {}, 'Hello <NAME>'
class HelloContext extends Arda.Context
component: HelloComponent
window.addEventListener 'DOMContentLoaded', ->
router = new Arda.Router(Arda.DefaultLayout, document.body)
router.pushContext(HelloContext, {})
| true | window.React = require 'react'
window.Promise = require 'bluebird'
Arda = require '../../src/'
HelloComponent = React.createClass
mixins: [Arda.mixin]
render: ->
React.createElement 'h1', {}, 'Hello PI:NAME:<NAME>END_PI'
class HelloContext extends Arda.Context
component: HelloComponent
window.addEventListener 'DOMContentLoaded', ->
router = new Arda.Router(Arda.DefaultLayout, document.body)
router.pushContext(HelloContext, {})
|
[
{
"context": "ldNum: process.env.TRAVIS_BUILD_NUMBER\n# }\n# \"wercker\": nullDetails\n\n# \"unknown\": nullDetails\n# }\n\nge",
"end": 3095,
"score": 0.5783879160881042,
"start": 3088,
"tag": "NAME",
"value": "wercker"
}
] | packages/server/lib/util/ci_provider.coffee | nothingismagick/cypress | 0 | _ = require("lodash")
isCodeship = ->
process.env.CI_NAME and process.env.CI_NAME is "codeship"
isGitlab = ->
process.env.GITLAB_CI or process.env.CI_SERVER_NAME and process.env.CI_SERVER_NAME is "GitLab CI"
isWercker = ->
process.env.WERCKER or process.env.WERCKER_MAIN_PIPELINE_STARTED
providers = {
"appveyor": "APPVEYOR"
"bamboo": "bamboo_planKey"
"buildkite": "BUILDKITE"
"circle": "CIRCLECI"
"codeship": isCodeship
"drone": "DRONE"
"gitlab": isGitlab
"hudson": "HUDSON_URL"
"jenkins": "JENKINS_URL"
"semaphore": "SEMAPHORE"
"shippable": "SHIPPABLE"
"snap": "SNAP_CI"
"teamcity": "TEAMCITY_VERSION"
"teamfoundation": "TF_BUILD"
"travis": "TRAVIS"
"wercker": isWercker
}
buildNums = (provider) -> {
appveyor: process.env.APPVEYOR_BUILD_NUMBER
circle: process.env.CIRCLE_BUILD_NUM
codeship: process.env.CI_BUILD_NUMBER
gitlab: process.env.CI_BUILD_ID
jenkins: process.env.BUILD_NUMBER
travis: process.env.TRAVIS_BUILD_NUMBER
drone: process.env.DRONE_BUILD_NUMBER
}[provider]
groupIds = (provider) -> {
# for CircleCI v2 use workflow id to group builds
circle: process.env.CIRCLE_WORKFLOW_ID
}[provider]
params = (provider) -> {
appveyor: {
accountName: process.env.APPVEYOR_ACCOUNT_NAME
projectSlug: process.env.APPVEYOR_PROJECT_SLUG
buildVersion: process.env.APPVEYOR_BUILD_VERSION
}
circle: {
buildUrl: process.env.CIRCLE_BUILD_URL
}
codeship: {
buildUrl: process.env.CI_BUILD_URL
}
gitlab: {
buildId: process.env.CI_BUILD_ID
projectUrl: process.env.CI_PROJECT_URL
}
jenkins: {
buildUrl: process.env.BUILD_URL
}
travis: {
buildId: process.env.TRAVIS_BUILD_ID
repoSlug: process.env.TRAVIS_REPO_SLUG
}
drone: {
buildUrl: process.env.DRONE_BUILD_LINK
}
}[provider]
# details = {
# "appveyor": -> {
# ciUrl: "https://ci.appveyor.com/project/#{process.env.APPVEYOR_ACCOUNT_NAME}/#{process.env.APPVEYOR_PROJECT_SLUG}/build/#{process.env.APPVEYOR_BUILD_VERSION}"
# buildNum: process.env.APPVEYOR_BUILD_NUMBER
# }
# "bamboo": nullDetails
# "buildkite": nullDetails
# "circle": -> {
# ciUrl: process.env.CIRCLE_BUILD_URL
# buildNum: process.env.CIRCLE_BUILD_NUM
# }
# "codeship": -> {
# ciUrl: process.env.CI_BUILD_URL
# buildNum: process.env.CI_BUILD_NUMBER
# }
# "drone": nullDetails
# "gitlab": -> {
# ciUrl: "#{process.env.CI_PROJECT_URL}/builds/#{process.env.CI_BUILD_ID}"
# buildNum: process.env.CI_BUILD_ID
# }
# "hudson": nullDetails
# "jenkins": -> {
# ciUrl: process.env.BUILD_URL
# buildNum: process.env.BUILD_NUMBER
# }
# "semaphore": nullDetails
# "shippable": nullDetails
# "snap": nullDetails
# "teamcity": nullDetails
# "teamfoundation": nullDetails
# "travis": -> {
# ciUrl: "https://travis-ci.org/#{process.env.TRAVIS_REPO_SLUG}/builds/#{process.env.TRAVIS_BUILD_ID}"
# buildNum: process.env.TRAVIS_BUILD_NUMBER
# }
# "wercker": nullDetails
# "unknown": nullDetails
# }
getProviderName = ->
## return the key of the first provider
## which is truthy
name = _.findKey providers, (value, key) ->
switch
when _.isString(value)
process.env[value]
when _.isFunction(value)
value()
name or "unknown"
module.exports = {
name: ->
getProviderName()
params: ->
params(getProviderName()) ? null
buildNum: ->
buildNums(getProviderName()) ? null
groupId: ->
groupIds(getProviderName()) ? null
}
| 204762 | _ = require("lodash")
isCodeship = ->
process.env.CI_NAME and process.env.CI_NAME is "codeship"
isGitlab = ->
process.env.GITLAB_CI or process.env.CI_SERVER_NAME and process.env.CI_SERVER_NAME is "GitLab CI"
isWercker = ->
process.env.WERCKER or process.env.WERCKER_MAIN_PIPELINE_STARTED
providers = {
"appveyor": "APPVEYOR"
"bamboo": "bamboo_planKey"
"buildkite": "BUILDKITE"
"circle": "CIRCLECI"
"codeship": isCodeship
"drone": "DRONE"
"gitlab": isGitlab
"hudson": "HUDSON_URL"
"jenkins": "JENKINS_URL"
"semaphore": "SEMAPHORE"
"shippable": "SHIPPABLE"
"snap": "SNAP_CI"
"teamcity": "TEAMCITY_VERSION"
"teamfoundation": "TF_BUILD"
"travis": "TRAVIS"
"wercker": isWercker
}
buildNums = (provider) -> {
appveyor: process.env.APPVEYOR_BUILD_NUMBER
circle: process.env.CIRCLE_BUILD_NUM
codeship: process.env.CI_BUILD_NUMBER
gitlab: process.env.CI_BUILD_ID
jenkins: process.env.BUILD_NUMBER
travis: process.env.TRAVIS_BUILD_NUMBER
drone: process.env.DRONE_BUILD_NUMBER
}[provider]
groupIds = (provider) -> {
# for CircleCI v2 use workflow id to group builds
circle: process.env.CIRCLE_WORKFLOW_ID
}[provider]
params = (provider) -> {
appveyor: {
accountName: process.env.APPVEYOR_ACCOUNT_NAME
projectSlug: process.env.APPVEYOR_PROJECT_SLUG
buildVersion: process.env.APPVEYOR_BUILD_VERSION
}
circle: {
buildUrl: process.env.CIRCLE_BUILD_URL
}
codeship: {
buildUrl: process.env.CI_BUILD_URL
}
gitlab: {
buildId: process.env.CI_BUILD_ID
projectUrl: process.env.CI_PROJECT_URL
}
jenkins: {
buildUrl: process.env.BUILD_URL
}
travis: {
buildId: process.env.TRAVIS_BUILD_ID
repoSlug: process.env.TRAVIS_REPO_SLUG
}
drone: {
buildUrl: process.env.DRONE_BUILD_LINK
}
}[provider]
# details = {
# "appveyor": -> {
# ciUrl: "https://ci.appveyor.com/project/#{process.env.APPVEYOR_ACCOUNT_NAME}/#{process.env.APPVEYOR_PROJECT_SLUG}/build/#{process.env.APPVEYOR_BUILD_VERSION}"
# buildNum: process.env.APPVEYOR_BUILD_NUMBER
# }
# "bamboo": nullDetails
# "buildkite": nullDetails
# "circle": -> {
# ciUrl: process.env.CIRCLE_BUILD_URL
# buildNum: process.env.CIRCLE_BUILD_NUM
# }
# "codeship": -> {
# ciUrl: process.env.CI_BUILD_URL
# buildNum: process.env.CI_BUILD_NUMBER
# }
# "drone": nullDetails
# "gitlab": -> {
# ciUrl: "#{process.env.CI_PROJECT_URL}/builds/#{process.env.CI_BUILD_ID}"
# buildNum: process.env.CI_BUILD_ID
# }
# "hudson": nullDetails
# "jenkins": -> {
# ciUrl: process.env.BUILD_URL
# buildNum: process.env.BUILD_NUMBER
# }
# "semaphore": nullDetails
# "shippable": nullDetails
# "snap": nullDetails
# "teamcity": nullDetails
# "teamfoundation": nullDetails
# "travis": -> {
# ciUrl: "https://travis-ci.org/#{process.env.TRAVIS_REPO_SLUG}/builds/#{process.env.TRAVIS_BUILD_ID}"
# buildNum: process.env.TRAVIS_BUILD_NUMBER
# }
# "<NAME>": nullDetails
# "unknown": nullDetails
# }
getProviderName = ->
## return the key of the first provider
## which is truthy
name = _.findKey providers, (value, key) ->
switch
when _.isString(value)
process.env[value]
when _.isFunction(value)
value()
name or "unknown"
module.exports = {
name: ->
getProviderName()
params: ->
params(getProviderName()) ? null
buildNum: ->
buildNums(getProviderName()) ? null
groupId: ->
groupIds(getProviderName()) ? null
}
| true | _ = require("lodash")
isCodeship = ->
process.env.CI_NAME and process.env.CI_NAME is "codeship"
isGitlab = ->
process.env.GITLAB_CI or process.env.CI_SERVER_NAME and process.env.CI_SERVER_NAME is "GitLab CI"
isWercker = ->
process.env.WERCKER or process.env.WERCKER_MAIN_PIPELINE_STARTED
providers = {
"appveyor": "APPVEYOR"
"bamboo": "bamboo_planKey"
"buildkite": "BUILDKITE"
"circle": "CIRCLECI"
"codeship": isCodeship
"drone": "DRONE"
"gitlab": isGitlab
"hudson": "HUDSON_URL"
"jenkins": "JENKINS_URL"
"semaphore": "SEMAPHORE"
"shippable": "SHIPPABLE"
"snap": "SNAP_CI"
"teamcity": "TEAMCITY_VERSION"
"teamfoundation": "TF_BUILD"
"travis": "TRAVIS"
"wercker": isWercker
}
buildNums = (provider) -> {
appveyor: process.env.APPVEYOR_BUILD_NUMBER
circle: process.env.CIRCLE_BUILD_NUM
codeship: process.env.CI_BUILD_NUMBER
gitlab: process.env.CI_BUILD_ID
jenkins: process.env.BUILD_NUMBER
travis: process.env.TRAVIS_BUILD_NUMBER
drone: process.env.DRONE_BUILD_NUMBER
}[provider]
groupIds = (provider) -> {
# for CircleCI v2 use workflow id to group builds
circle: process.env.CIRCLE_WORKFLOW_ID
}[provider]
params = (provider) -> {
appveyor: {
accountName: process.env.APPVEYOR_ACCOUNT_NAME
projectSlug: process.env.APPVEYOR_PROJECT_SLUG
buildVersion: process.env.APPVEYOR_BUILD_VERSION
}
circle: {
buildUrl: process.env.CIRCLE_BUILD_URL
}
codeship: {
buildUrl: process.env.CI_BUILD_URL
}
gitlab: {
buildId: process.env.CI_BUILD_ID
projectUrl: process.env.CI_PROJECT_URL
}
jenkins: {
buildUrl: process.env.BUILD_URL
}
travis: {
buildId: process.env.TRAVIS_BUILD_ID
repoSlug: process.env.TRAVIS_REPO_SLUG
}
drone: {
buildUrl: process.env.DRONE_BUILD_LINK
}
}[provider]
# details = {
# "appveyor": -> {
# ciUrl: "https://ci.appveyor.com/project/#{process.env.APPVEYOR_ACCOUNT_NAME}/#{process.env.APPVEYOR_PROJECT_SLUG}/build/#{process.env.APPVEYOR_BUILD_VERSION}"
# buildNum: process.env.APPVEYOR_BUILD_NUMBER
# }
# "bamboo": nullDetails
# "buildkite": nullDetails
# "circle": -> {
# ciUrl: process.env.CIRCLE_BUILD_URL
# buildNum: process.env.CIRCLE_BUILD_NUM
# }
# "codeship": -> {
# ciUrl: process.env.CI_BUILD_URL
# buildNum: process.env.CI_BUILD_NUMBER
# }
# "drone": nullDetails
# "gitlab": -> {
# ciUrl: "#{process.env.CI_PROJECT_URL}/builds/#{process.env.CI_BUILD_ID}"
# buildNum: process.env.CI_BUILD_ID
# }
# "hudson": nullDetails
# "jenkins": -> {
# ciUrl: process.env.BUILD_URL
# buildNum: process.env.BUILD_NUMBER
# }
# "semaphore": nullDetails
# "shippable": nullDetails
# "snap": nullDetails
# "teamcity": nullDetails
# "teamfoundation": nullDetails
# "travis": -> {
# ciUrl: "https://travis-ci.org/#{process.env.TRAVIS_REPO_SLUG}/builds/#{process.env.TRAVIS_BUILD_ID}"
# buildNum: process.env.TRAVIS_BUILD_NUMBER
# }
# "PI:NAME:<NAME>END_PI": nullDetails
# "unknown": nullDetails
# }
getProviderName = ->
## return the key of the first provider
## which is truthy
name = _.findKey providers, (value, key) ->
switch
when _.isString(value)
process.env[value]
when _.isFunction(value)
value()
name or "unknown"
module.exports = {
name: ->
getProviderName()
params: ->
params(getProviderName()) ? null
buildNum: ->
buildNums(getProviderName()) ? null
groupId: ->
groupIds(getProviderName()) ? null
}
|
[
{
"context": "rn attendee.email\n expectedAtLeast = ['randomgirl@provider.tld', 'randomguy@provider.tld']\n for expec",
"end": 6894,
"score": 0.9999338388442993,
"start": 6871,
"tag": "EMAIL",
"value": "randomgirl@provider.tld"
},
{
"context": " expectedAtLeas... | test/scenarios.coffee | RubenVerborgh/cozy-ical | 25 | path = require 'path'
should = require 'should'
moment = require 'moment-timezone'
{RRule} = require 'rrule'
{ICalParser, VCalendar, VAlarm, VTodo, VEvent} = require '../src/index'
fixturesPath = path.resolve __dirname, 'fixtures/scenarios'
describe "Parse iCal files from scenarios", ->
# This test suite will be applied to iCal files from various sources
# All the expored files should come from the same data set
applyTest = (fileName, organization, title) -> ->
it "shouldn't return an error", (done) ->
parser = new ICalParser()
filePath = "#{fixturesPath}/#{fileName}.ics"
parser.parseFile filePath, (err, result) =>
should.not.exist err
@result = result
done()
it "and all components should validate", ->
validateComponent = (component) ->
component.validate.bind(component).should.not.throw()
for subComponent in component.subComponents
validateComponent subComponent
validateComponent @result
it "and the calendar properties should be correctly set", ->
calendar = @result.model
should.exist calendar.organization
should.exist calendar.title
calendar.organization.should.equal organization
calendar.title.should.equal title
it "and should have the correct numbers of each components", ->
componentsType = @result.subComponents.map (component) ->
return Object.getPrototypeOf(component).name
@byType = {}
componentsType.reduce (previous, current, index) =>
@byType[current] ?= []
@byType[current].push @result.subComponents[index]
, {}
@byType['VEVENT'].length.should.equal 3
it "and the vEvent object for 'Dentist' should be correctly set", ->
testingEvent = null
for event in @byType['VEVENT']
if event.model.summary is 'Dentist'
testingEvent = event
model = testingEvent.model
model.should.have.properties 'uid', 'stampDate'
model.should.have.property 'summary', 'Dentist'
model.should.have.property 'location', 'Dentist office'
model.should.have.properties 'startDate', 'endDate'
expectedStartDate = moment.tz('2014-11-05 14:00:00', 'UTC').toISOString()
expectedEndDate = moment.tz('2014-11-05 15:00:00', 'UTC').toISOString()
model.startDate.toISOString().should.equal expectedStartDate
model.endDate.toISOString().should.equal expectedEndDate
it "and the vEvent object for 'Dentist' should be correctly set", ->
testingEvent = null
for event in @byType['VEVENT']
if event.model.summary is 'Dentist'
testingEvent = event
should.exist testingEvent
model = testingEvent.model
model.should.have.properties 'uid', 'stampDate'
model.should.have.property 'summary', 'Dentist'
model.should.have.property 'location', 'Dentist office'
model.should.have.properties 'startDate', 'endDate'
expectedStartDate = moment.tz('2014-11-05 14:00:00', 'UTC').toISOString()
expectedEndDate = moment.tz('2014-11-05 15:00:00', 'UTC').toISOString()
model.startDate.toISOString().should.equal expectedStartDate
model.endDate.toISOString().should.equal expectedEndDate
model.should.have.property 'timezone', null
it "and the vEvent object for 'Recurring event' should be correctly set", ->
testingEvent = null
for event in @byType['VEVENT']
if event.model.summary is 'Recurring event'
testingEvent = event
should.exist testingEvent
model = testingEvent.model
model.should.have.properties 'uid', 'stampDate'
model.should.have.property 'summary', 'Recurring event'
model.should.have.property 'description', 'Crawling a hidden dungeon'
model.should.have.property 'location', 'Hidden dungeon'
model.should.have.properties 'startDate', 'endDate'
expectedStartDate = moment.tz('2014-11-06 11:00:00', 'UTC').toISOString()
expectedEndDate = moment.tz('2014-11-06 12:00:00', 'UTC').toISOString()
model.startDate.toISOString().should.equal expectedStartDate
model.endDate.toISOString().should.equal expectedEndDate
model.should.have.property 'timezone', 'Europe/Paris'
model.should.have.property 'rrule'
model.rrule.should.have.properties 'freq', 'until'
model.rrule.freq.should.equal RRule.WEEKLY
expectedUntilDate = moment.tz '2015-01-01 11:00:00', 'UTC'
untilDate = moment.tz model.rrule.until, 'UTC'
# we assert that start of the day should be the same because
# each provider does what he wants here
untilDate
.startOf('day').toISOString()
.should.equal expectedUntilDate.startOf('day').toISOString()
it "and the vEvent object for 'Friend's birthday' should be correctly set", ->
testingEvent = null
for event in @byType['VEVENT']
if event.model.summary is "Friend's birthday"
testingEvent = event
should.exist testingEvent
model = testingEvent.model
model.should.have.properties 'uid', 'stampDate'
model.should.have.property 'summary', "Friend's birthday"
model.should.have.property 'description', "Bring a present!"
model.should.have.property 'location', "Friend's appartment"
model.should.have.properties 'startDate', 'endDate', 'allDay'
model.allDay.should.be.ok
expectedStartDate = moment.tz('2014-11-07', 'UTC').toISOString()
expectedEndDate = moment.tz('2014-11-08', 'UTC').toISOString()
model.startDate.toISOString().should.equal expectedStartDate
model.endDate.toISOString().should.equal expectedEndDate
model.should.have.property 'timezone', null
model.should.have.property 'rrule'
model.rrule.should.have.property 'freq'
model.rrule.freq.should.equal RRule.YEARLY
model.should.have.property 'attendees'
# some providers arbitrarily add the organizer in the attendees list
# so we can't fix value here
model.attendees.length.should.be.within 2, 3
mappedAttendes = model.attendees.map (attendee) -> return attendee.email
expectedAtLeast = ['randomgirl@provider.tld', 'randomguy@provider.tld']
for expected in expectedAtLeast
(expected in mappedAttendes).should.be.ok
describe "When an iCal file from Lightning is parsed", applyTest 'lightning', 'Mozilla.org', 'Mozilla Calendar V1.1'
describe "When an iCal file from Apple Calendar is parsed", applyTest 'apple', 'Apple Inc.', 'Mac OS X 10.9.5'
describe "When an iCal file from Google Calendar is parsed", applyTest 'google', 'Google Inc', 'Google Calendar 70.9054'
describe "When an iCal file from Radicale is parsed", applyTest 'radicale', 'Radicale', 'Radicale Server'
describe "When an iCal file from Cozycloud is parsed", applyTest 'cozycloud', 'Cozy Cloud', 'Cozy Agenda'
| 134782 | path = require 'path'
should = require 'should'
moment = require 'moment-timezone'
{RRule} = require 'rrule'
{ICalParser, VCalendar, VAlarm, VTodo, VEvent} = require '../src/index'
fixturesPath = path.resolve __dirname, 'fixtures/scenarios'
describe "Parse iCal files from scenarios", ->
# This test suite will be applied to iCal files from various sources
# All the expored files should come from the same data set
applyTest = (fileName, organization, title) -> ->
it "shouldn't return an error", (done) ->
parser = new ICalParser()
filePath = "#{fixturesPath}/#{fileName}.ics"
parser.parseFile filePath, (err, result) =>
should.not.exist err
@result = result
done()
it "and all components should validate", ->
validateComponent = (component) ->
component.validate.bind(component).should.not.throw()
for subComponent in component.subComponents
validateComponent subComponent
validateComponent @result
it "and the calendar properties should be correctly set", ->
calendar = @result.model
should.exist calendar.organization
should.exist calendar.title
calendar.organization.should.equal organization
calendar.title.should.equal title
it "and should have the correct numbers of each components", ->
componentsType = @result.subComponents.map (component) ->
return Object.getPrototypeOf(component).name
@byType = {}
componentsType.reduce (previous, current, index) =>
@byType[current] ?= []
@byType[current].push @result.subComponents[index]
, {}
@byType['VEVENT'].length.should.equal 3
it "and the vEvent object for 'Dentist' should be correctly set", ->
testingEvent = null
for event in @byType['VEVENT']
if event.model.summary is 'Dentist'
testingEvent = event
model = testingEvent.model
model.should.have.properties 'uid', 'stampDate'
model.should.have.property 'summary', 'Dentist'
model.should.have.property 'location', 'Dentist office'
model.should.have.properties 'startDate', 'endDate'
expectedStartDate = moment.tz('2014-11-05 14:00:00', 'UTC').toISOString()
expectedEndDate = moment.tz('2014-11-05 15:00:00', 'UTC').toISOString()
model.startDate.toISOString().should.equal expectedStartDate
model.endDate.toISOString().should.equal expectedEndDate
it "and the vEvent object for 'Dentist' should be correctly set", ->
testingEvent = null
for event in @byType['VEVENT']
if event.model.summary is 'Dentist'
testingEvent = event
should.exist testingEvent
model = testingEvent.model
model.should.have.properties 'uid', 'stampDate'
model.should.have.property 'summary', 'Dentist'
model.should.have.property 'location', 'Dentist office'
model.should.have.properties 'startDate', 'endDate'
expectedStartDate = moment.tz('2014-11-05 14:00:00', 'UTC').toISOString()
expectedEndDate = moment.tz('2014-11-05 15:00:00', 'UTC').toISOString()
model.startDate.toISOString().should.equal expectedStartDate
model.endDate.toISOString().should.equal expectedEndDate
model.should.have.property 'timezone', null
it "and the vEvent object for 'Recurring event' should be correctly set", ->
testingEvent = null
for event in @byType['VEVENT']
if event.model.summary is 'Recurring event'
testingEvent = event
should.exist testingEvent
model = testingEvent.model
model.should.have.properties 'uid', 'stampDate'
model.should.have.property 'summary', 'Recurring event'
model.should.have.property 'description', 'Crawling a hidden dungeon'
model.should.have.property 'location', 'Hidden dungeon'
model.should.have.properties 'startDate', 'endDate'
expectedStartDate = moment.tz('2014-11-06 11:00:00', 'UTC').toISOString()
expectedEndDate = moment.tz('2014-11-06 12:00:00', 'UTC').toISOString()
model.startDate.toISOString().should.equal expectedStartDate
model.endDate.toISOString().should.equal expectedEndDate
model.should.have.property 'timezone', 'Europe/Paris'
model.should.have.property 'rrule'
model.rrule.should.have.properties 'freq', 'until'
model.rrule.freq.should.equal RRule.WEEKLY
expectedUntilDate = moment.tz '2015-01-01 11:00:00', 'UTC'
untilDate = moment.tz model.rrule.until, 'UTC'
# we assert that start of the day should be the same because
# each provider does what he wants here
untilDate
.startOf('day').toISOString()
.should.equal expectedUntilDate.startOf('day').toISOString()
it "and the vEvent object for 'Friend's birthday' should be correctly set", ->
testingEvent = null
for event in @byType['VEVENT']
if event.model.summary is "Friend's birthday"
testingEvent = event
should.exist testingEvent
model = testingEvent.model
model.should.have.properties 'uid', 'stampDate'
model.should.have.property 'summary', "Friend's birthday"
model.should.have.property 'description', "Bring a present!"
model.should.have.property 'location', "Friend's appartment"
model.should.have.properties 'startDate', 'endDate', 'allDay'
model.allDay.should.be.ok
expectedStartDate = moment.tz('2014-11-07', 'UTC').toISOString()
expectedEndDate = moment.tz('2014-11-08', 'UTC').toISOString()
model.startDate.toISOString().should.equal expectedStartDate
model.endDate.toISOString().should.equal expectedEndDate
model.should.have.property 'timezone', null
model.should.have.property 'rrule'
model.rrule.should.have.property 'freq'
model.rrule.freq.should.equal RRule.YEARLY
model.should.have.property 'attendees'
# some providers arbitrarily add the organizer in the attendees list
# so we can't fix value here
model.attendees.length.should.be.within 2, 3
mappedAttendes = model.attendees.map (attendee) -> return attendee.email
expectedAtLeast = ['<EMAIL>', '<EMAIL>']
for expected in expectedAtLeast
(expected in mappedAttendes).should.be.ok
describe "When an iCal file from Lightning is parsed", applyTest 'lightning', 'Mozilla.org', 'Mozilla Calendar V1.1'
describe "When an iCal file from Apple Calendar is parsed", applyTest 'apple', 'Apple Inc.', 'Mac OS X 10.9.5'
describe "When an iCal file from Google Calendar is parsed", applyTest 'google', 'Google Inc', 'Google Calendar 70.9054'
describe "When an iCal file from Radicale is parsed", applyTest 'radicale', 'Radicale', 'Radicale Server'
describe "When an iCal file from Cozycloud is parsed", applyTest 'cozycloud', 'Cozy Cloud', 'Cozy Agenda'
| true | path = require 'path'
should = require 'should'
moment = require 'moment-timezone'
{RRule} = require 'rrule'
{ICalParser, VCalendar, VAlarm, VTodo, VEvent} = require '../src/index'
fixturesPath = path.resolve __dirname, 'fixtures/scenarios'
describe "Parse iCal files from scenarios", ->
# This test suite will be applied to iCal files from various sources
# All the expored files should come from the same data set
applyTest = (fileName, organization, title) -> ->
it "shouldn't return an error", (done) ->
parser = new ICalParser()
filePath = "#{fixturesPath}/#{fileName}.ics"
parser.parseFile filePath, (err, result) =>
should.not.exist err
@result = result
done()
it "and all components should validate", ->
validateComponent = (component) ->
component.validate.bind(component).should.not.throw()
for subComponent in component.subComponents
validateComponent subComponent
validateComponent @result
it "and the calendar properties should be correctly set", ->
calendar = @result.model
should.exist calendar.organization
should.exist calendar.title
calendar.organization.should.equal organization
calendar.title.should.equal title
it "and should have the correct numbers of each components", ->
componentsType = @result.subComponents.map (component) ->
return Object.getPrototypeOf(component).name
@byType = {}
componentsType.reduce (previous, current, index) =>
@byType[current] ?= []
@byType[current].push @result.subComponents[index]
, {}
@byType['VEVENT'].length.should.equal 3
it "and the vEvent object for 'Dentist' should be correctly set", ->
testingEvent = null
for event in @byType['VEVENT']
if event.model.summary is 'Dentist'
testingEvent = event
model = testingEvent.model
model.should.have.properties 'uid', 'stampDate'
model.should.have.property 'summary', 'Dentist'
model.should.have.property 'location', 'Dentist office'
model.should.have.properties 'startDate', 'endDate'
expectedStartDate = moment.tz('2014-11-05 14:00:00', 'UTC').toISOString()
expectedEndDate = moment.tz('2014-11-05 15:00:00', 'UTC').toISOString()
model.startDate.toISOString().should.equal expectedStartDate
model.endDate.toISOString().should.equal expectedEndDate
it "and the vEvent object for 'Dentist' should be correctly set", ->
testingEvent = null
for event in @byType['VEVENT']
if event.model.summary is 'Dentist'
testingEvent = event
should.exist testingEvent
model = testingEvent.model
model.should.have.properties 'uid', 'stampDate'
model.should.have.property 'summary', 'Dentist'
model.should.have.property 'location', 'Dentist office'
model.should.have.properties 'startDate', 'endDate'
expectedStartDate = moment.tz('2014-11-05 14:00:00', 'UTC').toISOString()
expectedEndDate = moment.tz('2014-11-05 15:00:00', 'UTC').toISOString()
model.startDate.toISOString().should.equal expectedStartDate
model.endDate.toISOString().should.equal expectedEndDate
model.should.have.property 'timezone', null
it "and the vEvent object for 'Recurring event' should be correctly set", ->
testingEvent = null
for event in @byType['VEVENT']
if event.model.summary is 'Recurring event'
testingEvent = event
should.exist testingEvent
model = testingEvent.model
model.should.have.properties 'uid', 'stampDate'
model.should.have.property 'summary', 'Recurring event'
model.should.have.property 'description', 'Crawling a hidden dungeon'
model.should.have.property 'location', 'Hidden dungeon'
model.should.have.properties 'startDate', 'endDate'
expectedStartDate = moment.tz('2014-11-06 11:00:00', 'UTC').toISOString()
expectedEndDate = moment.tz('2014-11-06 12:00:00', 'UTC').toISOString()
model.startDate.toISOString().should.equal expectedStartDate
model.endDate.toISOString().should.equal expectedEndDate
model.should.have.property 'timezone', 'Europe/Paris'
model.should.have.property 'rrule'
model.rrule.should.have.properties 'freq', 'until'
model.rrule.freq.should.equal RRule.WEEKLY
expectedUntilDate = moment.tz '2015-01-01 11:00:00', 'UTC'
untilDate = moment.tz model.rrule.until, 'UTC'
# we assert that start of the day should be the same because
# each provider does what he wants here
untilDate
.startOf('day').toISOString()
.should.equal expectedUntilDate.startOf('day').toISOString()
it "and the vEvent object for 'Friend's birthday' should be correctly set", ->
testingEvent = null
for event in @byType['VEVENT']
if event.model.summary is "Friend's birthday"
testingEvent = event
should.exist testingEvent
model = testingEvent.model
model.should.have.properties 'uid', 'stampDate'
model.should.have.property 'summary', "Friend's birthday"
model.should.have.property 'description', "Bring a present!"
model.should.have.property 'location', "Friend's appartment"
model.should.have.properties 'startDate', 'endDate', 'allDay'
model.allDay.should.be.ok
expectedStartDate = moment.tz('2014-11-07', 'UTC').toISOString()
expectedEndDate = moment.tz('2014-11-08', 'UTC').toISOString()
model.startDate.toISOString().should.equal expectedStartDate
model.endDate.toISOString().should.equal expectedEndDate
model.should.have.property 'timezone', null
model.should.have.property 'rrule'
model.rrule.should.have.property 'freq'
model.rrule.freq.should.equal RRule.YEARLY
model.should.have.property 'attendees'
# some providers arbitrarily add the organizer in the attendees list
# so we can't fix value here
model.attendees.length.should.be.within 2, 3
mappedAttendes = model.attendees.map (attendee) -> return attendee.email
expectedAtLeast = ['PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI']
for expected in expectedAtLeast
(expected in mappedAttendes).should.be.ok
describe "When an iCal file from Lightning is parsed", applyTest 'lightning', 'Mozilla.org', 'Mozilla Calendar V1.1'
describe "When an iCal file from Apple Calendar is parsed", applyTest 'apple', 'Apple Inc.', 'Mac OS X 10.9.5'
describe "When an iCal file from Google Calendar is parsed", applyTest 'google', 'Google Inc', 'Google Calendar 70.9054'
describe "When an iCal file from Radicale is parsed", applyTest 'radicale', 'Radicale', 'Radicale Server'
describe "When an iCal file from Cozycloud is parsed", applyTest 'cozycloud', 'Cozy Cloud', 'Cozy Agenda'
|
[
{
"context": "ed_client_token = decoded_client_token.replace(\"\\\\u0026\", \"&\")\n clientToken = JSON.parse(decoded_cli",
"end": 1680,
"score": 0.9151850938796997,
"start": 1675,
"tag": "KEY",
"value": "u0026"
}
] | spec/integration/braintree/client_token_gateway_spec.coffee | StreamCo/braintree_node | 0 | require('../../spec_helper')
braintree = specHelper.braintree
{Config} = require('../../../lib/braintree/config')
describe "ClientTokenGateway", ->
it "generates an authorization fingerprint that is accepted by the gateway", (done) ->
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({}, (err, result) ->
assert.isTrue(result.success)
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
encodedFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: encodedFingerprint,
sharedCustomerIdentifier: "test-identifier",
sharedCustomerIdentifierType: "testing"
}
myHttp.get("/client_api/v1/payment_methods.json", params, (statusCode) ->
assert.equal(statusCode, 200)
done()
)
)
it "it allows a client token version to be specified", (done) ->
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({version: 1}, (err, result) ->
assert.isTrue(result.success)
clientToken = JSON.parse(result.clientToken)
assert.equal(clientToken.version, 1)
done()
)
it "defaults to version 2", (done) ->
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({}, (err, result) ->
encoded_client_token = result.clientToken
decoded_client_token = new Buffer(encoded_client_token, "base64").toString("utf8")
unescaped_client_token = decoded_client_token.replace("\\u0026", "&")
clientToken = JSON.parse(decoded_client_token)
assert.equal(clientToken.version, 2)
done()
)
it "can pass verifyCard", (done) ->
specHelper.defaultGateway.customer.create({}, (err, result) ->
customerId = result.customer.id
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({
customerId: customerId,
options: {
verifyCard: true
}
}, (err, result) ->
assert.isTrue(result.success)
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: authorizationFingerprint,
sharedCustomerIdentifierType: "testing",
sharedCustomerIdentifier: "testing-identifier",
credit_card: {
number: "4115111111111115",
expiration_month: "11",
expiration_year: "2099"
}
}
myHttp.post("/client_api/v1/payment_methods/credit_cards.json", params, (statusCode) ->
assert.equal(statusCode, 422)
done()
)
)
)
it "can pass makeDefault", (done) ->
specHelper.defaultGateway.customer.create({}, (err, result) ->
customerId = result.customer.id
specHelper.defaultGateway.creditCard.create({
customerId: customerId,
number: "4242424242424242",
expirationDate: "11/2099"
}, (err, result) ->
assert.isTrue(result.success)
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({
customerId: customerId,
options: {
makeDefault: true
}
}, (err,result) ->
assert.isTrue(result.success)
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: authorizationFingerprint,
sharedCustomerIdentifierType: "testing",
sharedCustomerIdentifier: "testing-identifier",
credit_card: {
number: "4111111111111111",
expiration_month: "11",
expiration_year: "2099"
}
}
myHttp.post("/client_api/v1/payment_methods/credit_cards.json", params, (statusCode) ->
assert.equal(statusCode, 201)
specHelper.defaultGateway.customer.find(customerId, (err, customer) ->
assert.equal(2, customer.creditCards.length)
for index, credit_card of customer.creditCards
if credit_card.last4 == "1111"
assert.isTrue(credit_card.default)
done()
)
)
)
)
)
it "can pass failOnDuplicatePaymentMethod", (done) ->
specHelper.defaultGateway.customer.create({}, (err, result) ->
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
customer = result.customer
specHelper.defaultGateway.clientToken.generate({
customerId: customer.id
}, (err, result) ->
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: authorizationFingerprint,
sharedCustomerIdentifierType: "testing",
sharedCustomerIdentifier: "testing-identifier",
credit_card: {
number: "4111111111111111",
expiration_month: "11",
expiration_year: "2099"
}
}
myHttp.post("/client_api/v1/payment_methods/credit_cards.json", params, (statusCode) ->
assert.equal(statusCode, 201)
specHelper.defaultGateway.clientToken.generate({
customerId: customer.id,
options: {
failOnDuplicatePaymentMethod: true
}
}, (err, result) ->
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params.authorizationFingerprint = authorizationFingerprint
myHttp.post("/client_api/v1/payment_methods/credit_cards.json", params, (statusCode) ->
assert.equal(statusCode, 422)
done()
)
)
)
)
)
it "can pass merchantAccountId", (done) ->
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
clientTokenParams = {
merchantAccountId: "my_merchant_account"
}
specHelper.defaultGateway.clientToken.generate(clientTokenParams, (err, result) ->
assert.isTrue(result.success)
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
assert.equal(clientToken.merchantAccountId, "my_merchant_account")
done()
)
it "returns an error when an invalid parameter is supplied", (done) ->
specHelper.defaultGateway.clientToken.generate({
customrId: "1234"
}, (err, result) ->
assert.equal(err.type, "authorizationError")
done()
)
| 5346 | require('../../spec_helper')
braintree = specHelper.braintree
{Config} = require('../../../lib/braintree/config')
describe "ClientTokenGateway", ->
it "generates an authorization fingerprint that is accepted by the gateway", (done) ->
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({}, (err, result) ->
assert.isTrue(result.success)
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
encodedFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: encodedFingerprint,
sharedCustomerIdentifier: "test-identifier",
sharedCustomerIdentifierType: "testing"
}
myHttp.get("/client_api/v1/payment_methods.json", params, (statusCode) ->
assert.equal(statusCode, 200)
done()
)
)
it "it allows a client token version to be specified", (done) ->
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({version: 1}, (err, result) ->
assert.isTrue(result.success)
clientToken = JSON.parse(result.clientToken)
assert.equal(clientToken.version, 1)
done()
)
it "defaults to version 2", (done) ->
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({}, (err, result) ->
encoded_client_token = result.clientToken
decoded_client_token = new Buffer(encoded_client_token, "base64").toString("utf8")
unescaped_client_token = decoded_client_token.replace("\\<KEY>", "&")
clientToken = JSON.parse(decoded_client_token)
assert.equal(clientToken.version, 2)
done()
)
it "can pass verifyCard", (done) ->
specHelper.defaultGateway.customer.create({}, (err, result) ->
customerId = result.customer.id
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({
customerId: customerId,
options: {
verifyCard: true
}
}, (err, result) ->
assert.isTrue(result.success)
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: authorizationFingerprint,
sharedCustomerIdentifierType: "testing",
sharedCustomerIdentifier: "testing-identifier",
credit_card: {
number: "4115111111111115",
expiration_month: "11",
expiration_year: "2099"
}
}
myHttp.post("/client_api/v1/payment_methods/credit_cards.json", params, (statusCode) ->
assert.equal(statusCode, 422)
done()
)
)
)
it "can pass makeDefault", (done) ->
specHelper.defaultGateway.customer.create({}, (err, result) ->
customerId = result.customer.id
specHelper.defaultGateway.creditCard.create({
customerId: customerId,
number: "4242424242424242",
expirationDate: "11/2099"
}, (err, result) ->
assert.isTrue(result.success)
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({
customerId: customerId,
options: {
makeDefault: true
}
}, (err,result) ->
assert.isTrue(result.success)
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: authorizationFingerprint,
sharedCustomerIdentifierType: "testing",
sharedCustomerIdentifier: "testing-identifier",
credit_card: {
number: "4111111111111111",
expiration_month: "11",
expiration_year: "2099"
}
}
myHttp.post("/client_api/v1/payment_methods/credit_cards.json", params, (statusCode) ->
assert.equal(statusCode, 201)
specHelper.defaultGateway.customer.find(customerId, (err, customer) ->
assert.equal(2, customer.creditCards.length)
for index, credit_card of customer.creditCards
if credit_card.last4 == "1111"
assert.isTrue(credit_card.default)
done()
)
)
)
)
)
it "can pass failOnDuplicatePaymentMethod", (done) ->
specHelper.defaultGateway.customer.create({}, (err, result) ->
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
customer = result.customer
specHelper.defaultGateway.clientToken.generate({
customerId: customer.id
}, (err, result) ->
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: authorizationFingerprint,
sharedCustomerIdentifierType: "testing",
sharedCustomerIdentifier: "testing-identifier",
credit_card: {
number: "4111111111111111",
expiration_month: "11",
expiration_year: "2099"
}
}
myHttp.post("/client_api/v1/payment_methods/credit_cards.json", params, (statusCode) ->
assert.equal(statusCode, 201)
specHelper.defaultGateway.clientToken.generate({
customerId: customer.id,
options: {
failOnDuplicatePaymentMethod: true
}
}, (err, result) ->
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params.authorizationFingerprint = authorizationFingerprint
myHttp.post("/client_api/v1/payment_methods/credit_cards.json", params, (statusCode) ->
assert.equal(statusCode, 422)
done()
)
)
)
)
)
it "can pass merchantAccountId", (done) ->
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
clientTokenParams = {
merchantAccountId: "my_merchant_account"
}
specHelper.defaultGateway.clientToken.generate(clientTokenParams, (err, result) ->
assert.isTrue(result.success)
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
assert.equal(clientToken.merchantAccountId, "my_merchant_account")
done()
)
it "returns an error when an invalid parameter is supplied", (done) ->
specHelper.defaultGateway.clientToken.generate({
customrId: "1234"
}, (err, result) ->
assert.equal(err.type, "authorizationError")
done()
)
| true | require('../../spec_helper')
braintree = specHelper.braintree
{Config} = require('../../../lib/braintree/config')
describe "ClientTokenGateway", ->
it "generates an authorization fingerprint that is accepted by the gateway", (done) ->
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({}, (err, result) ->
assert.isTrue(result.success)
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
encodedFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: encodedFingerprint,
sharedCustomerIdentifier: "test-identifier",
sharedCustomerIdentifierType: "testing"
}
myHttp.get("/client_api/v1/payment_methods.json", params, (statusCode) ->
assert.equal(statusCode, 200)
done()
)
)
it "it allows a client token version to be specified", (done) ->
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({version: 1}, (err, result) ->
assert.isTrue(result.success)
clientToken = JSON.parse(result.clientToken)
assert.equal(clientToken.version, 1)
done()
)
it "defaults to version 2", (done) ->
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({}, (err, result) ->
encoded_client_token = result.clientToken
decoded_client_token = new Buffer(encoded_client_token, "base64").toString("utf8")
unescaped_client_token = decoded_client_token.replace("\\PI:KEY:<KEY>END_PI", "&")
clientToken = JSON.parse(decoded_client_token)
assert.equal(clientToken.version, 2)
done()
)
it "can pass verifyCard", (done) ->
specHelper.defaultGateway.customer.create({}, (err, result) ->
customerId = result.customer.id
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({
customerId: customerId,
options: {
verifyCard: true
}
}, (err, result) ->
assert.isTrue(result.success)
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: authorizationFingerprint,
sharedCustomerIdentifierType: "testing",
sharedCustomerIdentifier: "testing-identifier",
credit_card: {
number: "4115111111111115",
expiration_month: "11",
expiration_year: "2099"
}
}
myHttp.post("/client_api/v1/payment_methods/credit_cards.json", params, (statusCode) ->
assert.equal(statusCode, 422)
done()
)
)
)
it "can pass makeDefault", (done) ->
specHelper.defaultGateway.customer.create({}, (err, result) ->
customerId = result.customer.id
specHelper.defaultGateway.creditCard.create({
customerId: customerId,
number: "4242424242424242",
expirationDate: "11/2099"
}, (err, result) ->
assert.isTrue(result.success)
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({
customerId: customerId,
options: {
makeDefault: true
}
}, (err,result) ->
assert.isTrue(result.success)
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: authorizationFingerprint,
sharedCustomerIdentifierType: "testing",
sharedCustomerIdentifier: "testing-identifier",
credit_card: {
number: "4111111111111111",
expiration_month: "11",
expiration_year: "2099"
}
}
myHttp.post("/client_api/v1/payment_methods/credit_cards.json", params, (statusCode) ->
assert.equal(statusCode, 201)
specHelper.defaultGateway.customer.find(customerId, (err, customer) ->
assert.equal(2, customer.creditCards.length)
for index, credit_card of customer.creditCards
if credit_card.last4 == "1111"
assert.isTrue(credit_card.default)
done()
)
)
)
)
)
it "can pass failOnDuplicatePaymentMethod", (done) ->
specHelper.defaultGateway.customer.create({}, (err, result) ->
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
customer = result.customer
specHelper.defaultGateway.clientToken.generate({
customerId: customer.id
}, (err, result) ->
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: authorizationFingerprint,
sharedCustomerIdentifierType: "testing",
sharedCustomerIdentifier: "testing-identifier",
credit_card: {
number: "4111111111111111",
expiration_month: "11",
expiration_year: "2099"
}
}
myHttp.post("/client_api/v1/payment_methods/credit_cards.json", params, (statusCode) ->
assert.equal(statusCode, 201)
specHelper.defaultGateway.clientToken.generate({
customerId: customer.id,
options: {
failOnDuplicatePaymentMethod: true
}
}, (err, result) ->
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params.authorizationFingerprint = authorizationFingerprint
myHttp.post("/client_api/v1/payment_methods/credit_cards.json", params, (statusCode) ->
assert.equal(statusCode, 422)
done()
)
)
)
)
)
it "can pass merchantAccountId", (done) ->
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
clientTokenParams = {
merchantAccountId: "my_merchant_account"
}
specHelper.defaultGateway.clientToken.generate(clientTokenParams, (err, result) ->
assert.isTrue(result.success)
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
assert.equal(clientToken.merchantAccountId, "my_merchant_account")
done()
)
it "returns an error when an invalid parameter is supplied", (done) ->
specHelper.defaultGateway.clientToken.generate({
customrId: "1234"
}, (err, result) ->
assert.equal(err.type, "authorizationError")
done()
)
|
[
{
"context": "\n# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 19,
"score": 0.999434769153595,
"start": 13,
"tag": "NAME",
"value": "Joyent"
}
] | test/message/eval_messages.coffee | lxe/io.coffee | 0 |
# Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
run = (cmd, strict, cb) ->
args = []
args.push "--use_strict" if strict
args.push "-pe", cmd
child = spawn(process.execPath, args)
child.stdout.pipe process.stdout
child.stderr.pipe process.stdout
child.on "close", cb
return
go = ->
c = queue.shift()
return console.log("done") unless c
run c, false, ->
run c, true, go
return
return
common = require("../common")
assert = require("assert")
spawn = require("child_process").spawn
queue = [
"with(this){__filename}"
"42"
"throw new Error(\"hello\")"
"var x = 100; y = x;"
"var ______________________________________________; throw 10"
]
go()
| 94711 |
# Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
run = (cmd, strict, cb) ->
args = []
args.push "--use_strict" if strict
args.push "-pe", cmd
child = spawn(process.execPath, args)
child.stdout.pipe process.stdout
child.stderr.pipe process.stdout
child.on "close", cb
return
go = ->
c = queue.shift()
return console.log("done") unless c
run c, false, ->
run c, true, go
return
return
common = require("../common")
assert = require("assert")
spawn = require("child_process").spawn
queue = [
"with(this){__filename}"
"42"
"throw new Error(\"hello\")"
"var x = 100; y = x;"
"var ______________________________________________; throw 10"
]
go()
| true |
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
run = (cmd, strict, cb) ->
args = []
args.push "--use_strict" if strict
args.push "-pe", cmd
child = spawn(process.execPath, args)
child.stdout.pipe process.stdout
child.stderr.pipe process.stdout
child.on "close", cb
return
go = ->
c = queue.shift()
return console.log("done") unless c
run c, false, ->
run c, true, go
return
return
common = require("../common")
assert = require("assert")
spawn = require("child_process").spawn
queue = [
"with(this){__filename}"
"42"
"throw new Error(\"hello\")"
"var x = 100; y = x;"
"var ______________________________________________; throw 10"
]
go()
|
[
{
"context": "se magic numbers (adapted from https://github.com/danielstjules/buddy.js)\n# @author Vincent Lemeunier\n###\n\n'use s",
"end": 114,
"score": 0.9996586441993713,
"start": 101,
"tag": "USERNAME",
"value": "danielstjules"
},
{
"context": "tps://github.com/danielstjules/bud... | src/rules/no-magic-numbers.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Rule to flag statements that use magic numbers (adapted from https://github.com/danielstjules/buddy.js)
# @author Vincent Lemeunier
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow magic numbers'
category: 'Best Practices'
recommended: no
url: 'https://eslint.org/docs/rules/no-magic-numbers'
schema: [
type: 'object'
properties:
detectObjects: type: 'boolean'
ignore:
type: 'array'
items: type: 'number'
uniqueItems: yes
ignoreArrayIndexes: type: 'boolean'
additionalProperties: no
]
messages:
useConst: "Number constants declarations must use 'const'."
noMagic: 'No magic number: {{raw}}.'
create: (context) ->
config = context.options[0] or {}
detectObjects = !!config.detectObjects
ignore = config.ignore or []
ignoreArrayIndexes = !!config.ignoreArrayIndexes
###*
# Returns whether the node is number literal
# @param {Node} node - the node literal being evaluated
# @returns {boolean} true if the node is a number literal
###
isNumber = (node) -> typeof node.value is 'number'
###*
# Returns whether the number should be ignored
# @param {number} num - the number
# @returns {boolean} true if the number should be ignored
###
shouldIgnoreNumber = (num) -> ignore.indexOf(num) isnt -1
###*
# Returns whether the number should be ignored when used as a radix within parseInt() or Number.parseInt()
# @param {ASTNode} parent - the non-"UnaryExpression" parent
# @param {ASTNode} node - the node literal being evaluated
# @returns {boolean} true if the number should be ignored
###
shouldIgnoreParseInt = (parent, node) ->
parent.type is 'CallExpression' and
node is parent.arguments[1] and
(parent.callee.name is 'parseInt' or
(parent.callee.type is 'MemberExpression' and
parent.callee.object.name is 'Number' and
parent.callee.property.name is 'parseInt'))
###*
# Returns whether the number should be ignored when used to define a JSX prop
# @param {ASTNode} parent - the non-"UnaryExpression" parent
# @returns {boolean} true if the number should be ignored
###
shouldIgnoreJSXNumbers = (parent) -> parent.type.indexOf('JSX') is 0
###*
# Returns whether the number should be ignored when used as an array index with enabled 'ignoreArrayIndexes' option.
# @param {ASTNode} parent - the non-"UnaryExpression" parent.
# @returns {boolean} true if the number should be ignored
###
shouldIgnoreArrayIndexes = (parent) ->
parent.type is 'MemberExpression' and ignoreArrayIndexes
Literal: (node) ->
okTypes =
if detectObjects
[]
else
['ObjectExpression', 'Property', 'AssignmentExpression']
return unless isNumber node
# For negative magic numbers: update the value and parent node
if node.parent.type is 'UnaryExpression' and node.parent.operator is '-'
fullNumberNode = node.parent
{parent} = fullNumberNode
value = -node.value
raw = "-#{node.raw}"
else
fullNumberNode = node
{parent, value, raw} = node
return if (
shouldIgnoreNumber(value) or
shouldIgnoreParseInt(parent, fullNumberNode) or
shouldIgnoreArrayIndexes(parent) or
shouldIgnoreJSXNumbers parent
)
isAssignment =
parent.type is 'AssignmentExpression' and
parent.left.type is 'Identifier'
return if isAssignment and parent.left.declaration
if okTypes.indexOf(parent.type) is -1 or isAssignment
context.report
node: fullNumberNode
messageId: 'noMagic'
data: {raw}
| 59564 | ###*
# @fileoverview Rule to flag statements that use magic numbers (adapted from https://github.com/danielstjules/buddy.js)
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow magic numbers'
category: 'Best Practices'
recommended: no
url: 'https://eslint.org/docs/rules/no-magic-numbers'
schema: [
type: 'object'
properties:
detectObjects: type: 'boolean'
ignore:
type: 'array'
items: type: 'number'
uniqueItems: yes
ignoreArrayIndexes: type: 'boolean'
additionalProperties: no
]
messages:
useConst: "Number constants declarations must use 'const'."
noMagic: 'No magic number: {{raw}}.'
create: (context) ->
config = context.options[0] or {}
detectObjects = !!config.detectObjects
ignore = config.ignore or []
ignoreArrayIndexes = !!config.ignoreArrayIndexes
###*
# Returns whether the node is number literal
# @param {Node} node - the node literal being evaluated
# @returns {boolean} true if the node is a number literal
###
isNumber = (node) -> typeof node.value is 'number'
###*
# Returns whether the number should be ignored
# @param {number} num - the number
# @returns {boolean} true if the number should be ignored
###
shouldIgnoreNumber = (num) -> ignore.indexOf(num) isnt -1
###*
# Returns whether the number should be ignored when used as a radix within parseInt() or Number.parseInt()
# @param {ASTNode} parent - the non-"UnaryExpression" parent
# @param {ASTNode} node - the node literal being evaluated
# @returns {boolean} true if the number should be ignored
###
shouldIgnoreParseInt = (parent, node) ->
parent.type is 'CallExpression' and
node is parent.arguments[1] and
(parent.callee.name is 'parseInt' or
(parent.callee.type is 'MemberExpression' and
parent.callee.object.name is 'Number' and
parent.callee.property.name is 'parseInt'))
###*
# Returns whether the number should be ignored when used to define a JSX prop
# @param {ASTNode} parent - the non-"UnaryExpression" parent
# @returns {boolean} true if the number should be ignored
###
shouldIgnoreJSXNumbers = (parent) -> parent.type.indexOf('JSX') is 0
###*
# Returns whether the number should be ignored when used as an array index with enabled 'ignoreArrayIndexes' option.
# @param {ASTNode} parent - the non-"UnaryExpression" parent.
# @returns {boolean} true if the number should be ignored
###
shouldIgnoreArrayIndexes = (parent) ->
parent.type is 'MemberExpression' and ignoreArrayIndexes
Literal: (node) ->
okTypes =
if detectObjects
[]
else
['ObjectExpression', 'Property', 'AssignmentExpression']
return unless isNumber node
# For negative magic numbers: update the value and parent node
if node.parent.type is 'UnaryExpression' and node.parent.operator is '-'
fullNumberNode = node.parent
{parent} = fullNumberNode
value = -node.value
raw = "-#{node.raw}"
else
fullNumberNode = node
{parent, value, raw} = node
return if (
shouldIgnoreNumber(value) or
shouldIgnoreParseInt(parent, fullNumberNode) or
shouldIgnoreArrayIndexes(parent) or
shouldIgnoreJSXNumbers parent
)
isAssignment =
parent.type is 'AssignmentExpression' and
parent.left.type is 'Identifier'
return if isAssignment and parent.left.declaration
if okTypes.indexOf(parent.type) is -1 or isAssignment
context.report
node: fullNumberNode
messageId: 'noMagic'
data: {raw}
| true | ###*
# @fileoverview Rule to flag statements that use magic numbers (adapted from https://github.com/danielstjules/buddy.js)
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow magic numbers'
category: 'Best Practices'
recommended: no
url: 'https://eslint.org/docs/rules/no-magic-numbers'
schema: [
type: 'object'
properties:
detectObjects: type: 'boolean'
ignore:
type: 'array'
items: type: 'number'
uniqueItems: yes
ignoreArrayIndexes: type: 'boolean'
additionalProperties: no
]
messages:
useConst: "Number constants declarations must use 'const'."
noMagic: 'No magic number: {{raw}}.'
create: (context) ->
config = context.options[0] or {}
detectObjects = !!config.detectObjects
ignore = config.ignore or []
ignoreArrayIndexes = !!config.ignoreArrayIndexes
###*
# Returns whether the node is number literal
# @param {Node} node - the node literal being evaluated
# @returns {boolean} true if the node is a number literal
###
isNumber = (node) -> typeof node.value is 'number'
###*
# Returns whether the number should be ignored
# @param {number} num - the number
# @returns {boolean} true if the number should be ignored
###
shouldIgnoreNumber = (num) -> ignore.indexOf(num) isnt -1
###*
# Returns whether the number should be ignored when used as a radix within parseInt() or Number.parseInt()
# @param {ASTNode} parent - the non-"UnaryExpression" parent
# @param {ASTNode} node - the node literal being evaluated
# @returns {boolean} true if the number should be ignored
###
shouldIgnoreParseInt = (parent, node) ->
parent.type is 'CallExpression' and
node is parent.arguments[1] and
(parent.callee.name is 'parseInt' or
(parent.callee.type is 'MemberExpression' and
parent.callee.object.name is 'Number' and
parent.callee.property.name is 'parseInt'))
###*
# Returns whether the number should be ignored when used to define a JSX prop
# @param {ASTNode} parent - the non-"UnaryExpression" parent
# @returns {boolean} true if the number should be ignored
###
shouldIgnoreJSXNumbers = (parent) -> parent.type.indexOf('JSX') is 0
###*
# Returns whether the number should be ignored when used as an array index with enabled 'ignoreArrayIndexes' option.
# @param {ASTNode} parent - the non-"UnaryExpression" parent.
# @returns {boolean} true if the number should be ignored
###
shouldIgnoreArrayIndexes = (parent) ->
parent.type is 'MemberExpression' and ignoreArrayIndexes
Literal: (node) ->
okTypes =
if detectObjects
[]
else
['ObjectExpression', 'Property', 'AssignmentExpression']
return unless isNumber node
# For negative magic numbers: update the value and parent node
if node.parent.type is 'UnaryExpression' and node.parent.operator is '-'
fullNumberNode = node.parent
{parent} = fullNumberNode
value = -node.value
raw = "-#{node.raw}"
else
fullNumberNode = node
{parent, value, raw} = node
return if (
shouldIgnoreNumber(value) or
shouldIgnoreParseInt(parent, fullNumberNode) or
shouldIgnoreArrayIndexes(parent) or
shouldIgnoreJSXNumbers parent
)
isAssignment =
parent.type is 'AssignmentExpression' and
parent.left.type is 'Identifier'
return if isAssignment and parent.left.declaration
if okTypes.indexOf(parent.type) is -1 or isAssignment
context.report
node: fullNumberNode
messageId: 'noMagic'
data: {raw}
|
[
{
"context": "rent_lang: ['en']\n\n\tmode: 'development'\n\n\ttoken: 'abc'\n\n\tdefault: 'usr/demo_ppt'\n\n}\n",
"end": 104,
"score": 0.9613150358200073,
"start": 101,
"tag": "KEY",
"value": "abc"
}
] | kit/config.example.coffee | scopalaffairs/notell | 0 | NB.conf = {
port: 8013
load_langs: ['en']
current_lang: ['en']
mode: 'development'
token: 'abc'
default: 'usr/demo_ppt'
}
| 48470 | NB.conf = {
port: 8013
load_langs: ['en']
current_lang: ['en']
mode: 'development'
token: '<KEY>'
default: 'usr/demo_ppt'
}
| true | NB.conf = {
port: 8013
load_langs: ['en']
current_lang: ['en']
mode: 'development'
token: 'PI:KEY:<KEY>END_PI'
default: 'usr/demo_ppt'
}
|
[
{
"context": "ShowFilter _.extend {}, @props,\n key: \"filter-#{filter._id}\"\n filter: filter\n DOM.",
"end": 618,
"score": 0.913881242275238,
"start": 609,
"tag": "KEY",
"value": "filter-#{"
},
{
"context": "nd {}, @props,\n key: \"filter-#{fil... | src/components/list.coffee | brianshaler/kerplunk-filters | 0 | _ = require 'lodash'
React = require 'react'
{DOM} = React
ShowFilter = require './showFilter'
module.exports = React.createFactory React.createClass
render: ->
DOM.section
className: 'content'
,
DOM.h3 null, 'Filters'
DOM.div
className: 'clearfix'
,
DOM.a
onClick: @props.pushState
href: '/admin/filters/create'
className: 'btn btn-success'
, 'create new filter'
DOM.div
className: 'clearfix'
,
_.map @props.filters, (filter) =>
ShowFilter _.extend {}, @props,
key: "filter-#{filter._id}"
filter: filter
DOM.div
className: 'clearfix'
,
DOM.a
onClick: @props.pushState
href: '/admin/filters/create'
className: 'btn btn-success'
, 'create new filter'
| 134955 | _ = require 'lodash'
React = require 'react'
{DOM} = React
ShowFilter = require './showFilter'
module.exports = React.createFactory React.createClass
render: ->
DOM.section
className: 'content'
,
DOM.h3 null, 'Filters'
DOM.div
className: 'clearfix'
,
DOM.a
onClick: @props.pushState
href: '/admin/filters/create'
className: 'btn btn-success'
, 'create new filter'
DOM.div
className: 'clearfix'
,
_.map @props.filters, (filter) =>
ShowFilter _.extend {}, @props,
key: "<KEY>filter._<KEY>
filter: filter
DOM.div
className: 'clearfix'
,
DOM.a
onClick: @props.pushState
href: '/admin/filters/create'
className: 'btn btn-success'
, 'create new filter'
| true | _ = require 'lodash'
React = require 'react'
{DOM} = React
ShowFilter = require './showFilter'
module.exports = React.createFactory React.createClass
render: ->
DOM.section
className: 'content'
,
DOM.h3 null, 'Filters'
DOM.div
className: 'clearfix'
,
DOM.a
onClick: @props.pushState
href: '/admin/filters/create'
className: 'btn btn-success'
, 'create new filter'
DOM.div
className: 'clearfix'
,
_.map @props.filters, (filter) =>
ShowFilter _.extend {}, @props,
key: "PI:KEY:<KEY>END_PIfilter._PI:KEY:<KEY>END_PI
filter: filter
DOM.div
className: 'clearfix'
,
DOM.a
onClick: @props.pushState
href: '/admin/filters/create'
className: 'btn btn-success'
, 'create new filter'
|
[
{
"context": "orId: talkai.get '_id'\n body: body\n creator: talkai\n isLocal: true\n isEditable: false\n\nexports.",
"end": 1826,
"score": 0.6849493980407715,
"start": 1820,
"tag": "NAME",
"value": "talkai"
}
] | talk-web/client/util/assemble.coffee | ikingye/talk-os | 3,084 | msgDsl = require 'talk-msg-dsl'
Immutable = require 'immutable'
lang = require '../locales/lang'
fillMessage = (content) ->
content.replace /\{\{__([\w-]+)\}\}/g, (raw, key) ->
text = lang.getText(key)
if text then text else raw
exports.notification = (data, team) ->
contact = data.creator
body = msgDsl.flattern(msgDsl.read(fillMessage(data.body or '')))
if team?
body = "[#{team}]\n#{body}"
if data.attachments.length > 0
attachment = data.attachments[0]
switch attachment.category
when 'snippet'
type = 'category-snippet'
when 'rtf'
type = 'category-post'
when 'quote'
type = 'attachments'
when 'file'
type = 'category-file'
else
type = 'attachments'
body = "#{body}\n[#{lang.getText(type)}]"
title: contact?.name or ''
icon: contact?.avatarUrl or ''
body: body
exports.localMessage = ({_roomId, _storyId, _teamId, alias, receiver, sender, talkai}) ->
params = "&_userId=#{ receiver.get('_id') }"
receiverName = alias or receiver.get('name')
[text1, text2, text3, text4, text5] = lang.getText('you-may-invite').split('%s')
boldName = category: 'bold', model: '', view: " #{receiverName} "
linkText = category: 'link', view: text4, model: "talk://operation?action=invite#{ params }"
content = [text1, sender.get('name'), text2, boldName, text3, linkText, text5]
localMessage =
_roomId: _roomId
_teamId: _teamId
_storyId: _storyId
_creatorId: talkai.get('_id')
body: msgDsl.write content
creator: talkai
isEditable: false
isLocal: true
exports.localTalkMessage = ({body, talkai, _teamId, _roomId, _storyId}) ->
localMessage =
_teamId: _teamId
_roomId: _roomId
_storyId: _storyId
_creatorId: talkai.get '_id'
body: body
creator: talkai
isLocal: true
isEditable: false
exports.allMembers = ->
_id: 'all'
name: lang.getText('all-members')
pinyins: if lang.getLang() is 'zh' then ['suoyou'] else ['all']
avatarUrl: 'https://dn-talk.oss.aliyuncs.com/icons/all-members.png'
exports.storyFile = (data) ->
Immutable.fromJS
fileKey: data.fileKey or ''
fileName: data.fileName or ''
fileSize: data.fileSize or ''
fileType: data.fileType or ''
imageWidth: data.imageWidth or ''
previewUrl: data.previewUrl or ''
downloadUrl: data.downloadUrl or ''
imageHeight: data.imageHeight or ''
fileCategory: data.fileCategory or ''
thumbnailUrl: data.thumbnailUrl or ''
title: data.fileName or ''
exports.storyLink = (data, url) ->
Immutable.fromJS
text: data.text or ''
title: data.title or url
imageUrl: data.imageUrl or ''
faviconUrl: data.faviconUrl or ''
url: data.url or url
exports.draftStory = (_teamId, _id, category) ->
data =
switch category
when 'file'
fileKey: ''
fileName: ''
fileSize: ''
fileType: ''
previewUrl: ''
imageWidth: ''
downloadUrl: ''
imageHeight: ''
fileCategory: ''
thumbnailUrl: ''
when 'link'
url: ''
text: ''
title: ''
imageUrl: ''
faviconUrl: ''
when 'topic'
text: ''
title: ''
else {}
Immutable.fromJS
_teamId: _teamId
_draftId: _id
_memberIds: []
data: data
text: ''
title: ''
members: []
category: category
| 160843 | msgDsl = require 'talk-msg-dsl'
Immutable = require 'immutable'
lang = require '../locales/lang'
fillMessage = (content) ->
content.replace /\{\{__([\w-]+)\}\}/g, (raw, key) ->
text = lang.getText(key)
if text then text else raw
exports.notification = (data, team) ->
contact = data.creator
body = msgDsl.flattern(msgDsl.read(fillMessage(data.body or '')))
if team?
body = "[#{team}]\n#{body}"
if data.attachments.length > 0
attachment = data.attachments[0]
switch attachment.category
when 'snippet'
type = 'category-snippet'
when 'rtf'
type = 'category-post'
when 'quote'
type = 'attachments'
when 'file'
type = 'category-file'
else
type = 'attachments'
body = "#{body}\n[#{lang.getText(type)}]"
title: contact?.name or ''
icon: contact?.avatarUrl or ''
body: body
exports.localMessage = ({_roomId, _storyId, _teamId, alias, receiver, sender, talkai}) ->
params = "&_userId=#{ receiver.get('_id') }"
receiverName = alias or receiver.get('name')
[text1, text2, text3, text4, text5] = lang.getText('you-may-invite').split('%s')
boldName = category: 'bold', model: '', view: " #{receiverName} "
linkText = category: 'link', view: text4, model: "talk://operation?action=invite#{ params }"
content = [text1, sender.get('name'), text2, boldName, text3, linkText, text5]
localMessage =
_roomId: _roomId
_teamId: _teamId
_storyId: _storyId
_creatorId: talkai.get('_id')
body: msgDsl.write content
creator: talkai
isEditable: false
isLocal: true
exports.localTalkMessage = ({body, talkai, _teamId, _roomId, _storyId}) ->
localMessage =
_teamId: _teamId
_roomId: _roomId
_storyId: _storyId
_creatorId: talkai.get '_id'
body: body
creator: <NAME>
isLocal: true
isEditable: false
exports.allMembers = ->
_id: 'all'
name: lang.getText('all-members')
pinyins: if lang.getLang() is 'zh' then ['suoyou'] else ['all']
avatarUrl: 'https://dn-talk.oss.aliyuncs.com/icons/all-members.png'
exports.storyFile = (data) ->
Immutable.fromJS
fileKey: data.fileKey or ''
fileName: data.fileName or ''
fileSize: data.fileSize or ''
fileType: data.fileType or ''
imageWidth: data.imageWidth or ''
previewUrl: data.previewUrl or ''
downloadUrl: data.downloadUrl or ''
imageHeight: data.imageHeight or ''
fileCategory: data.fileCategory or ''
thumbnailUrl: data.thumbnailUrl or ''
title: data.fileName or ''
exports.storyLink = (data, url) ->
Immutable.fromJS
text: data.text or ''
title: data.title or url
imageUrl: data.imageUrl or ''
faviconUrl: data.faviconUrl or ''
url: data.url or url
exports.draftStory = (_teamId, _id, category) ->
data =
switch category
when 'file'
fileKey: ''
fileName: ''
fileSize: ''
fileType: ''
previewUrl: ''
imageWidth: ''
downloadUrl: ''
imageHeight: ''
fileCategory: ''
thumbnailUrl: ''
when 'link'
url: ''
text: ''
title: ''
imageUrl: ''
faviconUrl: ''
when 'topic'
text: ''
title: ''
else {}
Immutable.fromJS
_teamId: _teamId
_draftId: _id
_memberIds: []
data: data
text: ''
title: ''
members: []
category: category
| true | msgDsl = require 'talk-msg-dsl'
Immutable = require 'immutable'
lang = require '../locales/lang'
fillMessage = (content) ->
content.replace /\{\{__([\w-]+)\}\}/g, (raw, key) ->
text = lang.getText(key)
if text then text else raw
exports.notification = (data, team) ->
contact = data.creator
body = msgDsl.flattern(msgDsl.read(fillMessage(data.body or '')))
if team?
body = "[#{team}]\n#{body}"
if data.attachments.length > 0
attachment = data.attachments[0]
switch attachment.category
when 'snippet'
type = 'category-snippet'
when 'rtf'
type = 'category-post'
when 'quote'
type = 'attachments'
when 'file'
type = 'category-file'
else
type = 'attachments'
body = "#{body}\n[#{lang.getText(type)}]"
title: contact?.name or ''
icon: contact?.avatarUrl or ''
body: body
exports.localMessage = ({_roomId, _storyId, _teamId, alias, receiver, sender, talkai}) ->
params = "&_userId=#{ receiver.get('_id') }"
receiverName = alias or receiver.get('name')
[text1, text2, text3, text4, text5] = lang.getText('you-may-invite').split('%s')
boldName = category: 'bold', model: '', view: " #{receiverName} "
linkText = category: 'link', view: text4, model: "talk://operation?action=invite#{ params }"
content = [text1, sender.get('name'), text2, boldName, text3, linkText, text5]
localMessage =
_roomId: _roomId
_teamId: _teamId
_storyId: _storyId
_creatorId: talkai.get('_id')
body: msgDsl.write content
creator: talkai
isEditable: false
isLocal: true
exports.localTalkMessage = ({body, talkai, _teamId, _roomId, _storyId}) ->
localMessage =
_teamId: _teamId
_roomId: _roomId
_storyId: _storyId
_creatorId: talkai.get '_id'
body: body
creator: PI:NAME:<NAME>END_PI
isLocal: true
isEditable: false
exports.allMembers = ->
_id: 'all'
name: lang.getText('all-members')
pinyins: if lang.getLang() is 'zh' then ['suoyou'] else ['all']
avatarUrl: 'https://dn-talk.oss.aliyuncs.com/icons/all-members.png'
exports.storyFile = (data) ->
Immutable.fromJS
fileKey: data.fileKey or ''
fileName: data.fileName or ''
fileSize: data.fileSize or ''
fileType: data.fileType or ''
imageWidth: data.imageWidth or ''
previewUrl: data.previewUrl or ''
downloadUrl: data.downloadUrl or ''
imageHeight: data.imageHeight or ''
fileCategory: data.fileCategory or ''
thumbnailUrl: data.thumbnailUrl or ''
title: data.fileName or ''
exports.storyLink = (data, url) ->
Immutable.fromJS
text: data.text or ''
title: data.title or url
imageUrl: data.imageUrl or ''
faviconUrl: data.faviconUrl or ''
url: data.url or url
exports.draftStory = (_teamId, _id, category) ->
data =
switch category
when 'file'
fileKey: ''
fileName: ''
fileSize: ''
fileType: ''
previewUrl: ''
imageWidth: ''
downloadUrl: ''
imageHeight: ''
fileCategory: ''
thumbnailUrl: ''
when 'link'
url: ''
text: ''
title: ''
imageUrl: ''
faviconUrl: ''
when 'topic'
text: ''
title: ''
else {}
Immutable.fromJS
_teamId: _teamId
_draftId: _id
_memberIds: []
data: data
text: ''
title: ''
members: []
category: category
|
[
{
"context": " (code)=>\n\t\t\t\t@UserDeleter.deleteUser.calledWith(@user_id)\n\t\t\t\tcode.should.equal 200\n\t\t\t\tdone()\n\t\t\t@UserC",
"end": 1881,
"score": 0.8391909003257751,
"start": 1876,
"tag": "USERNAME",
"value": "user_"
},
{
"context": "UserSettings\", ->\n\t\tbeforeEac... | test/UnitTests/coffee/User/UserControllerTests.coffee | max-maag/web-sharelatex | 0 | sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/User/UserController.js"
SandboxedModule = require('sandboxed-module')
events = require "events"
MockResponse = require "../helpers/MockResponse"
MockRequest = require "../helpers/MockRequest"
ObjectId = require("mongojs").ObjectId
assert = require("assert")
describe "UserController", ->
beforeEach ->
@user_id = "323123"
@user =
_id:@user_id
save:sinon.stub().callsArgWith(0)
ace:{}
@UserDeleter =
deleteUser: sinon.stub().callsArgWith(1)
@UserLocator =
findById: sinon.stub().callsArgWith(1, null, @user)
@User =
findById: sinon.stub().callsArgWith(1, null, @user)
@NewsLetterManager =
unsubscribe: sinon.stub().callsArgWith(1)
@UserRegistrationHandler =
registerNewUser: sinon.stub()
@AuthenticationController = {}
@AuthenticationManager =
authenticate: sinon.stub()
setUserPassword: sinon.stub()
@ReferalAllocator =
allocate:sinon.stub()
@UserUpdater =
changeEmailAddress:sinon.stub()
@UserController = SandboxedModule.require modulePath, requires:
"./UserLocator": @UserLocator
"./UserDeleter": @UserDeleter
"./UserUpdater":@UserUpdater
"../../models/User": User:@User
'../Newsletter/NewsletterManager':@NewsLetterManager
"./UserRegistrationHandler":@UserRegistrationHandler
"../Authentication/AuthenticationController": @AuthenticationController
"../Authentication/AuthenticationManager": @AuthenticationManager
"../Referal/ReferalAllocator":@ReferalAllocator
"logger-sharelatex": {log:->}
@req =
session:
destroy:->
user :
_id : @user_id
body:{}
@res = {}
@next = sinon.stub()
describe "deleteUser", ->
it "should delete the user", (done)->
@res.send = (code)=>
@UserDeleter.deleteUser.calledWith(@user_id)
code.should.equal 200
done()
@UserController.deleteUser @req, @res
describe "unsubscribe", ->
it "should send the user to unsubscribe", (done)->
@res.send = (code)=>
@NewsLetterManager.unsubscribe.calledWith(@user).should.equal true
done()
@UserController.unsubscribe @req, @res
describe "updateUserSettings", ->
beforeEach ->
@newEmail = "hello@world.com"
it "should call save", (done)->
@req.body = {}
@res.send = (code)=>
@user.save.called.should.equal true
done()
@UserController.updateUserSettings @req, @res
it "should set the first name", (done)->
@req.body =
first_name: "bobby "
@res.send = (code)=>
@user.first_name.should.equal "bobby"
done()
@UserController.updateUserSettings @req, @res
it "should set the role", (done)->
@req.body =
role: "student"
@res.send = (code)=>
@user.role.should.equal "student"
done()
@UserController.updateUserSettings @req, @res
it "should set the institution", (done)->
@req.body =
institution: "MIT"
@res.send = (code)=>
@user.institution.should.equal "MIT"
done()
@UserController.updateUserSettings @req, @res
it "should set some props on ace", (done)->
@req.body =
theme: "something"
@res.send = (code)=>
@user.ace.theme.should.equal "something"
done()
@UserController.updateUserSettings @req, @res
it "should send an error if the email is 0 len", (done)->
@req.body.email = ""
@res.send = (code)->
code.should.equal 400
done()
@UserController.updateUserSettings @req, @res
it "should send an error if the email does not contain an @", (done)->
@req.body.email = "bob at something dot com"
@res.send = (code)->
code.should.equal 400
done()
@UserController.updateUserSettings @req, @res
it "should call the user updater with the new email and user _id", (done)->
@req.body.email = @newEmail.toUpperCase()
@UserUpdater.changeEmailAddress.callsArgWith(2)
@res.send = (code)=>
code.should.equal 200
@UserUpdater.changeEmailAddress.calledWith(@user_id, @newEmail).should.equal true
done()
@UserController.updateUserSettings @req, @res
describe "logout", ->
it "should destroy the session", (done)->
@req.session.destroy = sinon.stub().callsArgWith(0)
@res.redirect = (url)=>
url.should.equal "/login"
@req.session.destroy.called.should.equal true
done()
@UserController.logout @req, @res
describe "register", ->
it "should ask the UserRegistrationHandler to register user", (done)->
@UserRegistrationHandler.registerNewUser.callsArgWith(1, null, @user)
@res.send = =>
@UserRegistrationHandler.registerNewUser.calledWith(@req.body).should.equal true
done()
@UserController.register @req, @res
it "should try and log the user in if there is an EmailAlreadyRegisterd error", (done)->
@UserRegistrationHandler.registerNewUser.callsArgWith(1, "EmailAlreadyRegisterd")
@AuthenticationController.login = (req, res)=>
assert.deepEqual req, @req
assert.deepEqual res, @res
done()
@UserController.register @req, @res
it "should put the user on the session and mark them as justRegistered", (done)->
@UserRegistrationHandler.registerNewUser.callsArgWith(1, null, @user)
@res.send = =>
assert.deepEqual @user, @req.session.user
assert.equal @req.session.justRegistered, true
done()
@UserController.register @req, @res
it "should redirect to project page", (done)->
@UserRegistrationHandler.registerNewUser.callsArgWith(1, null, @user)
@res.send = (opts)=>
opts.redir.should.equal "/project"
done()
@UserController.register @req, @res
it "should redirect passed redir if it exists", (done)->
@UserRegistrationHandler.registerNewUser.callsArgWith(1, null, @user)
@req.body.redir = "/somewhere"
@res.send = (opts)=>
opts.redir.should.equal "/somewhere"
done()
@UserController.register @req, @res
it "should allocate the referals", (done)->
@req.session =
referal_id : "23123"
referal_source : "email"
referal_medium : "bob"
@UserRegistrationHandler.registerNewUser.callsArgWith(1, null, @user)
@req.body.redir = "/somewhere"
@res.send = (opts)=>
@ReferalAllocator.allocate.calledWith(@req.session.referal_id, @user._id, @req.session.referal_source, @req.session.referal_medium).should.equal true
done()
@UserController.register @req, @res
describe "changePassword", ->
it "should check the old password is the current one at the moment", (done)->
@AuthenticationManager.authenticate.callsArgWith(2)
@req.body =
currentPassword: "oldpasshere"
@res.send = =>
@AuthenticationManager.authenticate.calledWith(_id:@user._id, "oldpasshere").should.equal true
@AuthenticationManager.setUserPassword.called.should.equal false
done()
@UserController.changePassword @req, @res
it "it should not set the new password if they do not match", (done)->
@AuthenticationManager.authenticate.callsArgWith(2, null, {})
@req.body =
newPassword1: "1"
newPassword2: "2"
@res.send = =>
@AuthenticationManager.setUserPassword.called.should.equal false
done()
@UserController.changePassword @req, @res
it "should set the new password if they do match", (done)->
@AuthenticationManager.authenticate.callsArgWith(2, null, @user)
@AuthenticationManager.setUserPassword.callsArgWith(2)
@req.body =
newPassword1: "newpass"
newPassword2: "newpass"
@res.send = =>
@AuthenticationManager.setUserPassword.calledWith(@user._id, "newpass").should.equal true
done()
@UserController.changePassword @req, @res
| 110665 | sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/User/UserController.js"
SandboxedModule = require('sandboxed-module')
events = require "events"
MockResponse = require "../helpers/MockResponse"
MockRequest = require "../helpers/MockRequest"
ObjectId = require("mongojs").ObjectId
assert = require("assert")
describe "UserController", ->
beforeEach ->
@user_id = "323123"
@user =
_id:@user_id
save:sinon.stub().callsArgWith(0)
ace:{}
@UserDeleter =
deleteUser: sinon.stub().callsArgWith(1)
@UserLocator =
findById: sinon.stub().callsArgWith(1, null, @user)
@User =
findById: sinon.stub().callsArgWith(1, null, @user)
@NewsLetterManager =
unsubscribe: sinon.stub().callsArgWith(1)
@UserRegistrationHandler =
registerNewUser: sinon.stub()
@AuthenticationController = {}
@AuthenticationManager =
authenticate: sinon.stub()
setUserPassword: sinon.stub()
@ReferalAllocator =
allocate:sinon.stub()
@UserUpdater =
changeEmailAddress:sinon.stub()
@UserController = SandboxedModule.require modulePath, requires:
"./UserLocator": @UserLocator
"./UserDeleter": @UserDeleter
"./UserUpdater":@UserUpdater
"../../models/User": User:@User
'../Newsletter/NewsletterManager':@NewsLetterManager
"./UserRegistrationHandler":@UserRegistrationHandler
"../Authentication/AuthenticationController": @AuthenticationController
"../Authentication/AuthenticationManager": @AuthenticationManager
"../Referal/ReferalAllocator":@ReferalAllocator
"logger-sharelatex": {log:->}
@req =
session:
destroy:->
user :
_id : @user_id
body:{}
@res = {}
@next = sinon.stub()
describe "deleteUser", ->
it "should delete the user", (done)->
@res.send = (code)=>
@UserDeleter.deleteUser.calledWith(@user_id)
code.should.equal 200
done()
@UserController.deleteUser @req, @res
describe "unsubscribe", ->
it "should send the user to unsubscribe", (done)->
@res.send = (code)=>
@NewsLetterManager.unsubscribe.calledWith(@user).should.equal true
done()
@UserController.unsubscribe @req, @res
describe "updateUserSettings", ->
beforeEach ->
@newEmail = "<EMAIL>"
it "should call save", (done)->
@req.body = {}
@res.send = (code)=>
@user.save.called.should.equal true
done()
@UserController.updateUserSettings @req, @res
it "should set the first name", (done)->
@req.body =
first_name: "<NAME> "
@res.send = (code)=>
@user.first_name.should.equal "<NAME>"
done()
@UserController.updateUserSettings @req, @res
it "should set the role", (done)->
@req.body =
role: "student"
@res.send = (code)=>
@user.role.should.equal "student"
done()
@UserController.updateUserSettings @req, @res
it "should set the institution", (done)->
@req.body =
institution: "MIT"
@res.send = (code)=>
@user.institution.should.equal "MIT"
done()
@UserController.updateUserSettings @req, @res
it "should set some props on ace", (done)->
@req.body =
theme: "something"
@res.send = (code)=>
@user.ace.theme.should.equal "something"
done()
@UserController.updateUserSettings @req, @res
it "should send an error if the email is 0 len", (done)->
@req.body.email = ""
@res.send = (code)->
code.should.equal 400
done()
@UserController.updateUserSettings @req, @res
it "should send an error if the email does not contain an @", (done)->
@req.body.email = "bob at something dot com"
@res.send = (code)->
code.should.equal 400
done()
@UserController.updateUserSettings @req, @res
it "should call the user updater with the new email and user _id", (done)->
@req.body.email = @newEmail.toUpperCase()
@UserUpdater.changeEmailAddress.callsArgWith(2)
@res.send = (code)=>
code.should.equal 200
@UserUpdater.changeEmailAddress.calledWith(@user_id, @newEmail).should.equal true
done()
@UserController.updateUserSettings @req, @res
describe "logout", ->
it "should destroy the session", (done)->
@req.session.destroy = sinon.stub().callsArgWith(0)
@res.redirect = (url)=>
url.should.equal "/login"
@req.session.destroy.called.should.equal true
done()
@UserController.logout @req, @res
describe "register", ->
it "should ask the UserRegistrationHandler to register user", (done)->
@UserRegistrationHandler.registerNewUser.callsArgWith(1, null, @user)
@res.send = =>
@UserRegistrationHandler.registerNewUser.calledWith(@req.body).should.equal true
done()
@UserController.register @req, @res
it "should try and log the user in if there is an EmailAlreadyRegisterd error", (done)->
@UserRegistrationHandler.registerNewUser.callsArgWith(1, "EmailAlreadyRegisterd")
@AuthenticationController.login = (req, res)=>
assert.deepEqual req, @req
assert.deepEqual res, @res
done()
@UserController.register @req, @res
it "should put the user on the session and mark them as justRegistered", (done)->
@UserRegistrationHandler.registerNewUser.callsArgWith(1, null, @user)
@res.send = =>
assert.deepEqual @user, @req.session.user
assert.equal @req.session.justRegistered, true
done()
@UserController.register @req, @res
it "should redirect to project page", (done)->
@UserRegistrationHandler.registerNewUser.callsArgWith(1, null, @user)
@res.send = (opts)=>
opts.redir.should.equal "/project"
done()
@UserController.register @req, @res
it "should redirect passed redir if it exists", (done)->
@UserRegistrationHandler.registerNewUser.callsArgWith(1, null, @user)
@req.body.redir = "/somewhere"
@res.send = (opts)=>
opts.redir.should.equal "/somewhere"
done()
@UserController.register @req, @res
it "should allocate the referals", (done)->
@req.session =
referal_id : "23123"
referal_source : "email"
referal_medium : "bob"
@UserRegistrationHandler.registerNewUser.callsArgWith(1, null, @user)
@req.body.redir = "/somewhere"
@res.send = (opts)=>
@ReferalAllocator.allocate.calledWith(@req.session.referal_id, @user._id, @req.session.referal_source, @req.session.referal_medium).should.equal true
done()
@UserController.register @req, @res
describe "changePassword", ->
it "should check the old password is the current one at the moment", (done)->
@AuthenticationManager.authenticate.callsArgWith(2)
@req.body =
currentPassword: "<PASSWORD>"
@res.send = =>
@AuthenticationManager.authenticate.calledWith(_id:@user._id, "oldpasshere").should.equal true
@AuthenticationManager.setUserPassword.called.should.equal false
done()
@UserController.changePassword @req, @res
it "it should not set the new password if they do not match", (done)->
@AuthenticationManager.authenticate.callsArgWith(2, null, {})
@req.body =
newPassword1: "<PASSWORD>"
newPassword2: "<PASSWORD>"
@res.send = =>
@AuthenticationManager.setUserPassword.called.should.equal false
done()
@UserController.changePassword @req, @res
it "should set the new password if they do match", (done)->
@AuthenticationManager.authenticate.callsArgWith(2, null, @user)
@AuthenticationManager.setUserPassword.callsArgWith(2)
@req.body =
newPassword1: "<PASSWORD>"
newPassword2: "<PASSWORD>"
@res.send = =>
@AuthenticationManager.setUserPassword.calledWith(@user._id, "<PASSWORD>").should.equal true
done()
@UserController.changePassword @req, @res
| true | sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/User/UserController.js"
SandboxedModule = require('sandboxed-module')
events = require "events"
MockResponse = require "../helpers/MockResponse"
MockRequest = require "../helpers/MockRequest"
ObjectId = require("mongojs").ObjectId
assert = require("assert")
describe "UserController", ->
beforeEach ->
@user_id = "323123"
@user =
_id:@user_id
save:sinon.stub().callsArgWith(0)
ace:{}
@UserDeleter =
deleteUser: sinon.stub().callsArgWith(1)
@UserLocator =
findById: sinon.stub().callsArgWith(1, null, @user)
@User =
findById: sinon.stub().callsArgWith(1, null, @user)
@NewsLetterManager =
unsubscribe: sinon.stub().callsArgWith(1)
@UserRegistrationHandler =
registerNewUser: sinon.stub()
@AuthenticationController = {}
@AuthenticationManager =
authenticate: sinon.stub()
setUserPassword: sinon.stub()
@ReferalAllocator =
allocate:sinon.stub()
@UserUpdater =
changeEmailAddress:sinon.stub()
@UserController = SandboxedModule.require modulePath, requires:
"./UserLocator": @UserLocator
"./UserDeleter": @UserDeleter
"./UserUpdater":@UserUpdater
"../../models/User": User:@User
'../Newsletter/NewsletterManager':@NewsLetterManager
"./UserRegistrationHandler":@UserRegistrationHandler
"../Authentication/AuthenticationController": @AuthenticationController
"../Authentication/AuthenticationManager": @AuthenticationManager
"../Referal/ReferalAllocator":@ReferalAllocator
"logger-sharelatex": {log:->}
@req =
session:
destroy:->
user :
_id : @user_id
body:{}
@res = {}
@next = sinon.stub()
describe "deleteUser", ->
it "should delete the user", (done)->
@res.send = (code)=>
@UserDeleter.deleteUser.calledWith(@user_id)
code.should.equal 200
done()
@UserController.deleteUser @req, @res
describe "unsubscribe", ->
it "should send the user to unsubscribe", (done)->
@res.send = (code)=>
@NewsLetterManager.unsubscribe.calledWith(@user).should.equal true
done()
@UserController.unsubscribe @req, @res
describe "updateUserSettings", ->
beforeEach ->
@newEmail = "PI:EMAIL:<EMAIL>END_PI"
it "should call save", (done)->
@req.body = {}
@res.send = (code)=>
@user.save.called.should.equal true
done()
@UserController.updateUserSettings @req, @res
it "should set the first name", (done)->
@req.body =
first_name: "PI:NAME:<NAME>END_PI "
@res.send = (code)=>
@user.first_name.should.equal "PI:NAME:<NAME>END_PI"
done()
@UserController.updateUserSettings @req, @res
it "should set the role", (done)->
@req.body =
role: "student"
@res.send = (code)=>
@user.role.should.equal "student"
done()
@UserController.updateUserSettings @req, @res
it "should set the institution", (done)->
@req.body =
institution: "MIT"
@res.send = (code)=>
@user.institution.should.equal "MIT"
done()
@UserController.updateUserSettings @req, @res
it "should set some props on ace", (done)->
@req.body =
theme: "something"
@res.send = (code)=>
@user.ace.theme.should.equal "something"
done()
@UserController.updateUserSettings @req, @res
it "should send an error if the email is 0 len", (done)->
@req.body.email = ""
@res.send = (code)->
code.should.equal 400
done()
@UserController.updateUserSettings @req, @res
it "should send an error if the email does not contain an @", (done)->
@req.body.email = "bob at something dot com"
@res.send = (code)->
code.should.equal 400
done()
@UserController.updateUserSettings @req, @res
it "should call the user updater with the new email and user _id", (done)->
@req.body.email = @newEmail.toUpperCase()
@UserUpdater.changeEmailAddress.callsArgWith(2)
@res.send = (code)=>
code.should.equal 200
@UserUpdater.changeEmailAddress.calledWith(@user_id, @newEmail).should.equal true
done()
@UserController.updateUserSettings @req, @res
describe "logout", ->
it "should destroy the session", (done)->
@req.session.destroy = sinon.stub().callsArgWith(0)
@res.redirect = (url)=>
url.should.equal "/login"
@req.session.destroy.called.should.equal true
done()
@UserController.logout @req, @res
describe "register", ->
it "should ask the UserRegistrationHandler to register user", (done)->
@UserRegistrationHandler.registerNewUser.callsArgWith(1, null, @user)
@res.send = =>
@UserRegistrationHandler.registerNewUser.calledWith(@req.body).should.equal true
done()
@UserController.register @req, @res
it "should try and log the user in if there is an EmailAlreadyRegisterd error", (done)->
@UserRegistrationHandler.registerNewUser.callsArgWith(1, "EmailAlreadyRegisterd")
@AuthenticationController.login = (req, res)=>
assert.deepEqual req, @req
assert.deepEqual res, @res
done()
@UserController.register @req, @res
it "should put the user on the session and mark them as justRegistered", (done)->
@UserRegistrationHandler.registerNewUser.callsArgWith(1, null, @user)
@res.send = =>
assert.deepEqual @user, @req.session.user
assert.equal @req.session.justRegistered, true
done()
@UserController.register @req, @res
it "should redirect to project page", (done)->
@UserRegistrationHandler.registerNewUser.callsArgWith(1, null, @user)
@res.send = (opts)=>
opts.redir.should.equal "/project"
done()
@UserController.register @req, @res
it "should redirect passed redir if it exists", (done)->
@UserRegistrationHandler.registerNewUser.callsArgWith(1, null, @user)
@req.body.redir = "/somewhere"
@res.send = (opts)=>
opts.redir.should.equal "/somewhere"
done()
@UserController.register @req, @res
it "should allocate the referals", (done)->
@req.session =
referal_id : "23123"
referal_source : "email"
referal_medium : "bob"
@UserRegistrationHandler.registerNewUser.callsArgWith(1, null, @user)
@req.body.redir = "/somewhere"
@res.send = (opts)=>
@ReferalAllocator.allocate.calledWith(@req.session.referal_id, @user._id, @req.session.referal_source, @req.session.referal_medium).should.equal true
done()
@UserController.register @req, @res
describe "changePassword", ->
it "should check the old password is the current one at the moment", (done)->
@AuthenticationManager.authenticate.callsArgWith(2)
@req.body =
currentPassword: "PI:PASSWORD:<PASSWORD>END_PI"
@res.send = =>
@AuthenticationManager.authenticate.calledWith(_id:@user._id, "oldpasshere").should.equal true
@AuthenticationManager.setUserPassword.called.should.equal false
done()
@UserController.changePassword @req, @res
it "it should not set the new password if they do not match", (done)->
@AuthenticationManager.authenticate.callsArgWith(2, null, {})
@req.body =
newPassword1: "PI:PASSWORD:<PASSWORD>END_PI"
newPassword2: "PI:PASSWORD:<PASSWORD>END_PI"
@res.send = =>
@AuthenticationManager.setUserPassword.called.should.equal false
done()
@UserController.changePassword @req, @res
it "should set the new password if they do match", (done)->
@AuthenticationManager.authenticate.callsArgWith(2, null, @user)
@AuthenticationManager.setUserPassword.callsArgWith(2)
@req.body =
newPassword1: "PI:PASSWORD:<PASSWORD>END_PI"
newPassword2: "PI:PASSWORD:<PASSWORD>END_PI"
@res.send = =>
@AuthenticationManager.setUserPassword.calledWith(@user._id, "PI:PASSWORD:<PASSWORD>END_PI").should.equal true
done()
@UserController.changePassword @req, @res
|
[
{
"context": "Application\n constructor: ->\n @user = new User(@parseUser())\n @user.save()\n\n # User and friends\n @",
"end": 67,
"score": 0.9890419840812683,
"start": 57,
"tag": "USERNAME",
"value": "@parseUser"
},
{
"context": "essage)\n \n # peer.js key\n pee... | app/routers/application.coffee | bnolan/dispersion | 3 | class Application
constructor: ->
@user = new User(@parseUser())
@user.save()
# User and friends
@users = new UserCollection
# All posts by all users
@posts = new PostCollection
# WebRTC service using peer.js cloud services
@peer = new Peer @user.get('name'), { key: @peerKey(), debug : true }
@peer.on 'connection', @onConnection
# Keep a list of peers
@inboundConnections = {}
@outboundConnections = {}
resetSession: ->
delete localStorage['user']
# A client to connected to us
onConnection: (conn) =>
@inboundConnections[conn.peer] = conn
@users.add(new User { name : conn.peer })
message = JSON.stringify {
model : 'User'
attributes : app.user.toAttributes()
}
conn.send(message)
conn.on 'data', (data) =>
console.log('Got data:', data, 'from: ', conn.peer)
# Connect to someone else
connectToUser: (name) ->
conn = app.peer.connect(name)
@outboundConnections[name] = conn
@users.add(new User { name : name })
conn.on 'open', ->
# say who we are
# conn.send(JSON.stringify({ hello : 'world!', user : app.user.get('name') }))
conn.on 'data', (data) =>
obj = {}
try
obj = JSON.parse(data)
catch e
console.log "bad message:", data
return
if obj.model == 'Post'
post = new Post(obj.attributes)
@users.getByName(post.get('user')).newPost(post)
@posts.add(post)
return
if obj.model == 'User'
app.users.add(new User(obj.attributes))
return
console.log('Got data:', data, 'from: ', conn.peer)
postModel: (model) ->
message = JSON.stringify {
model : 'Post'
attributes : model.toAttributes()
}
for name, peer of @inboundConnections
peer.send(message)
# peer.js key
peerKey: ->
"uazd6lgkwi3yds4i"
# the authentication and contact search url
getBrokerUrl: ->
"http://example.com"
parseUser: ->
if localStorage['user']
JSON.parse(localStorage['user'])
else
name = prompt("Please enter a username, no spaces")
{
name : name
posts : [
{ content : 'hello world', created_at : new Date().toISOString(), user : name }
]
}
# todo - maybe replace with a permanent collection and add posts to this collection
# when a new user is added.
# getPosts: ->
# @posts
#
# for post in @user.getPosts().models
# posts.add(post)
#
# for user in @users.models
# for post in user.getPosts().models
# posts.add(post)
#
# posts
start: ->
console.log 'App started'
# Create your controllers here...
new PostsRouter
# Then start backbone
Backbone.history.start()
@Application = Application
| 145770 | class Application
constructor: ->
@user = new User(@parseUser())
@user.save()
# User and friends
@users = new UserCollection
# All posts by all users
@posts = new PostCollection
# WebRTC service using peer.js cloud services
@peer = new Peer @user.get('name'), { key: @peerKey(), debug : true }
@peer.on 'connection', @onConnection
# Keep a list of peers
@inboundConnections = {}
@outboundConnections = {}
resetSession: ->
delete localStorage['user']
# A client to connected to us
onConnection: (conn) =>
@inboundConnections[conn.peer] = conn
@users.add(new User { name : conn.peer })
message = JSON.stringify {
model : 'User'
attributes : app.user.toAttributes()
}
conn.send(message)
conn.on 'data', (data) =>
console.log('Got data:', data, 'from: ', conn.peer)
# Connect to someone else
connectToUser: (name) ->
conn = app.peer.connect(name)
@outboundConnections[name] = conn
@users.add(new User { name : name })
conn.on 'open', ->
# say who we are
# conn.send(JSON.stringify({ hello : 'world!', user : app.user.get('name') }))
conn.on 'data', (data) =>
obj = {}
try
obj = JSON.parse(data)
catch e
console.log "bad message:", data
return
if obj.model == 'Post'
post = new Post(obj.attributes)
@users.getByName(post.get('user')).newPost(post)
@posts.add(post)
return
if obj.model == 'User'
app.users.add(new User(obj.attributes))
return
console.log('Got data:', data, 'from: ', conn.peer)
postModel: (model) ->
message = JSON.stringify {
model : 'Post'
attributes : model.toAttributes()
}
for name, peer of @inboundConnections
peer.send(message)
# peer.js key
peerKey: ->
"<KEY>kw<PASSWORD>"
# the authentication and contact search url
getBrokerUrl: ->
"http://example.com"
parseUser: ->
if localStorage['user']
JSON.parse(localStorage['user'])
else
name = prompt("Please enter a username, no spaces")
{
name : name
posts : [
{ content : 'hello world', created_at : new Date().toISOString(), user : name }
]
}
# todo - maybe replace with a permanent collection and add posts to this collection
# when a new user is added.
# getPosts: ->
# @posts
#
# for post in @user.getPosts().models
# posts.add(post)
#
# for user in @users.models
# for post in user.getPosts().models
# posts.add(post)
#
# posts
start: ->
console.log 'App started'
# Create your controllers here...
new PostsRouter
# Then start backbone
Backbone.history.start()
@Application = Application
| true | class Application
constructor: ->
@user = new User(@parseUser())
@user.save()
# User and friends
@users = new UserCollection
# All posts by all users
@posts = new PostCollection
# WebRTC service using peer.js cloud services
@peer = new Peer @user.get('name'), { key: @peerKey(), debug : true }
@peer.on 'connection', @onConnection
# Keep a list of peers
@inboundConnections = {}
@outboundConnections = {}
resetSession: ->
delete localStorage['user']
# A client to connected to us
onConnection: (conn) =>
@inboundConnections[conn.peer] = conn
@users.add(new User { name : conn.peer })
message = JSON.stringify {
model : 'User'
attributes : app.user.toAttributes()
}
conn.send(message)
conn.on 'data', (data) =>
console.log('Got data:', data, 'from: ', conn.peer)
# Connect to someone else
connectToUser: (name) ->
conn = app.peer.connect(name)
@outboundConnections[name] = conn
@users.add(new User { name : name })
conn.on 'open', ->
# say who we are
# conn.send(JSON.stringify({ hello : 'world!', user : app.user.get('name') }))
conn.on 'data', (data) =>
obj = {}
try
obj = JSON.parse(data)
catch e
console.log "bad message:", data
return
if obj.model == 'Post'
post = new Post(obj.attributes)
@users.getByName(post.get('user')).newPost(post)
@posts.add(post)
return
if obj.model == 'User'
app.users.add(new User(obj.attributes))
return
console.log('Got data:', data, 'from: ', conn.peer)
postModel: (model) ->
message = JSON.stringify {
model : 'Post'
attributes : model.toAttributes()
}
for name, peer of @inboundConnections
peer.send(message)
# peer.js key
peerKey: ->
"PI:KEY:<KEY>END_PIkwPI:PASSWORD:<PASSWORD>END_PI"
# the authentication and contact search url
getBrokerUrl: ->
"http://example.com"
parseUser: ->
if localStorage['user']
JSON.parse(localStorage['user'])
else
name = prompt("Please enter a username, no spaces")
{
name : name
posts : [
{ content : 'hello world', created_at : new Date().toISOString(), user : name }
]
}
# todo - maybe replace with a permanent collection and add posts to this collection
# when a new user is added.
# getPosts: ->
# @posts
#
# for post in @user.getPosts().models
# posts.add(post)
#
# for user in @users.models
# for post in user.getPosts().models
# posts.add(post)
#
# posts
start: ->
console.log 'App started'
# Create your controllers here...
new PostsRouter
# Then start backbone
Backbone.history.start()
@Application = Application
|
[
{
"context": "cars = [\n {\n \"value\": \"asto\",\n \"displayName\": \"Aston Martin\"\n }\n {\n \"",
"end": 31,
"score": 0.999214768409729,
"start": 27,
"tag": "NAME",
"value": "asto"
},
{
"context": " = [\n {\n \"value\": \"asto\",\n \"displayName\": \"Aston Marti... | docs/src/coffee/docs.coffee | callum-hart/Sift.js | 2 | cars = [
{
"value": "asto",
"displayName": "Aston Martin"
}
{
"value": "lamb",
"displayName": "Lamborghini"
}
{
"value": "pors",
"displayName": "Porsche"
}
{
"value": "mcla",
"displayName": "McLaren"
}
{
"value": "ferr",
"displayName": "Ferrari"
}
{
"value": "bron",
"displayName": "Bugatti Veyron"
}
{
"value": "koen",
"displayName": "Koenigsegg"
}
]
# Example One
exampleOne = new Sift "#example-one",
displayName: "Car manufacturers"
type: "checkbox"
filters: cars
activeFilter: ["asto", "pors"]
onFilterApplied: (activeFilter) ->
console.log "Car manufacturers: #{activeFilter}"
# Example Two
exampleTwo = new Sift "#example-two",
displayName: "Car manufacturer"
type: "radio"
filters: cars
activeFilter: "asto"
onFilterApplied: (activeFilter) ->
console.log "Car manufacturer: #{activeFilter}"
# Example Three
exampleThree = new Sift "#example-three",
type: "calendar"
displayName: "Made on"
calendarOptions:
minDate: new Date(2015, 7, 20)
maxDate: new Date(2017, 7, 20)
existingDate: new Date(2016, 7, 20)
dragSelection: no
onFilterApplied: (singleDate) ->
console.log "Made on: #{singleDate}"
# Example Four
exampleFour = new Sift "#example-four",
type: "calendar"
displayName: "Made"
calendarOptions:
existingDateRange: [new Date(2015, 0, 1), new Date(2015, 0, 10)]
onFilterApplied: (startDate, endDate) ->
if endDate
console.log "Made between: #{startDate} – #{endDate}"
else
console.log "Made on: #{startDate}"
# Example Five
exampleFive = new Sift "#example-five",
type: "multi_calendar"
displayName: "Made between"
calendarOptions:
existingDateRange: [new Date(2015, 0, 1), new Date(2015, 11, 25)]
onFilterApplied: (startDate, endDate) ->
console.log "Made between: #{startDate} – #{endDate}"
| 7007 | cars = [
{
"value": "<NAME>",
"displayName": "<NAME>"
}
{
"value": "<NAME>",
"displayName": "<NAME>"
}
{
"value": "<NAME>",
"displayName": "<NAME>"
}
{
"value": "<NAME>",
"displayName": "<NAME>"
}
{
"value": "<NAME>",
"displayName": "<NAME>"
}
{
"value": "<NAME>",
"displayName": "<NAME>"
}
{
"value": "<NAME>",
"displayName": "<NAME>"
}
]
# Example One
exampleOne = new Sift "#example-one",
displayName: "Car manufacturers"
type: "checkbox"
filters: cars
activeFilter: ["asto", "pors"]
onFilterApplied: (activeFilter) ->
console.log "Car manufacturers: #{activeFilter}"
# Example Two
exampleTwo = new Sift "#example-two",
displayName: "Car manufacturer"
type: "radio"
filters: cars
activeFilter: "asto"
onFilterApplied: (activeFilter) ->
console.log "Car manufacturer: #{activeFilter}"
# Example Three
exampleThree = new Sift "#example-three",
type: "calendar"
displayName: "Made on"
calendarOptions:
minDate: new Date(2015, 7, 20)
maxDate: new Date(2017, 7, 20)
existingDate: new Date(2016, 7, 20)
dragSelection: no
onFilterApplied: (singleDate) ->
console.log "Made on: #{singleDate}"
# Example Four
exampleFour = new Sift "#example-four",
type: "calendar"
displayName: "Made"
calendarOptions:
existingDateRange: [new Date(2015, 0, 1), new Date(2015, 0, 10)]
onFilterApplied: (startDate, endDate) ->
if endDate
console.log "Made between: #{startDate} – #{endDate}"
else
console.log "Made on: #{startDate}"
# Example Five
exampleFive = new Sift "#example-five",
type: "multi_calendar"
displayName: "Made between"
calendarOptions:
existingDateRange: [new Date(2015, 0, 1), new Date(2015, 11, 25)]
onFilterApplied: (startDate, endDate) ->
console.log "Made between: #{startDate} – #{endDate}"
| true | cars = [
{
"value": "PI:NAME:<NAME>END_PI",
"displayName": "PI:NAME:<NAME>END_PI"
}
{
"value": "PI:NAME:<NAME>END_PI",
"displayName": "PI:NAME:<NAME>END_PI"
}
{
"value": "PI:NAME:<NAME>END_PI",
"displayName": "PI:NAME:<NAME>END_PI"
}
{
"value": "PI:NAME:<NAME>END_PI",
"displayName": "PI:NAME:<NAME>END_PI"
}
{
"value": "PI:NAME:<NAME>END_PI",
"displayName": "PI:NAME:<NAME>END_PI"
}
{
"value": "PI:NAME:<NAME>END_PI",
"displayName": "PI:NAME:<NAME>END_PI"
}
{
"value": "PI:NAME:<NAME>END_PI",
"displayName": "PI:NAME:<NAME>END_PI"
}
]
# Example One
exampleOne = new Sift "#example-one",
displayName: "Car manufacturers"
type: "checkbox"
filters: cars
activeFilter: ["asto", "pors"]
onFilterApplied: (activeFilter) ->
console.log "Car manufacturers: #{activeFilter}"
# Example Two
exampleTwo = new Sift "#example-two",
displayName: "Car manufacturer"
type: "radio"
filters: cars
activeFilter: "asto"
onFilterApplied: (activeFilter) ->
console.log "Car manufacturer: #{activeFilter}"
# Example Three
exampleThree = new Sift "#example-three",
type: "calendar"
displayName: "Made on"
calendarOptions:
minDate: new Date(2015, 7, 20)
maxDate: new Date(2017, 7, 20)
existingDate: new Date(2016, 7, 20)
dragSelection: no
onFilterApplied: (singleDate) ->
console.log "Made on: #{singleDate}"
# Example Four
exampleFour = new Sift "#example-four",
type: "calendar"
displayName: "Made"
calendarOptions:
existingDateRange: [new Date(2015, 0, 1), new Date(2015, 0, 10)]
onFilterApplied: (startDate, endDate) ->
if endDate
console.log "Made between: #{startDate} – #{endDate}"
else
console.log "Made on: #{startDate}"
# Example Five
exampleFive = new Sift "#example-five",
type: "multi_calendar"
displayName: "Made between"
calendarOptions:
existingDateRange: [new Date(2015, 0, 1), new Date(2015, 11, 25)]
onFilterApplied: (startDate, endDate) ->
console.log "Made between: #{startDate} – #{endDate}"
|
[
{
"context": "m Twitter (requires configuration)\n#\n# Author:\n# stephenyeargin\n\nhockey_teams = require './teams.json'\n\nmoment = ",
"end": 575,
"score": 0.9995701909065247,
"start": 561,
"tag": "USERNAME",
"value": "stephenyeargin"
},
{
"context": "/#{game.gamePk}\",\n ... | src/hockey.coffee | stephenyeargin/hubot-hockey | 0 | # Description
# Get the latest hockey playoff odds for your team.
#
# Configuration:
# HUBOT_TWITTER_CONSUMER_KEY - Optional; Twitter consumer key
# HUBOT_TWITTER_CONSUMER_SECRET - Optional; Twitter consumer secret
# HUBOT_TWITTER_ACCESS_TOKEN - Optional; Twitter access token
# HUBOT_TWITTER_ACCESS_TOKEN_SECRET - Optional; Twitter access token secret
#
# Commands:
# hubot <team or city> - Get the lastest playoff odds from MoneyPuck.com
# hubot <team or city> twitter - Get the latest news from Twitter (requires configuration)
#
# Author:
# stephenyeargin
hockey_teams = require './teams.json'
moment = require 'moment-timezone'
parse = require 'csv-parse'
AsciiTable = require 'ascii-table'
# Twitter
Twitter = require 'twitter'
twitter_client = new Twitter
consumer_key: process.env.HUBOT_TWITTER_CONSUMER_KEY
consumer_secret: process.env.HUBOT_TWITTER_CONSUMER_SECRET
access_token_key: process.env.HUBOT_TWITTER_ACCESS_TOKEN
access_token_secret: process.env.HUBOT_TWITTER_ACCESS_TOKEN_SECRET
module.exports = (robot) ->
registerDefaultListener = (team) ->
statsregex = '_team_regex_$'
robot.respond new RegExp(statsregex.replace('_team_regex_', team.regex), 'i'), (msg) ->
getNhlStatsData team, msg, ->
getMoneyPuckData team, msg
registerTweetListener = (team) ->
twitterregex = '_team_regex_ (tweet|twitter)$'
robot.respond new RegExp(twitterregex.replace('_team_regex_', team.regex), 'i'), (msg) ->
showLatestTweet(team, msg)
getNhlStatsData = (team, msg, cb) ->
msg.http('https://statsapi.web.nhl.com/api/v1/schedule')
.query({
teamId: team.nhl_stats_api_id,
startDate: moment().tz('America/Los_Angeles').format('YYYY-MM-DD'),
endDate: moment().tz('America/Los_Angeles').add(90, 'd').format('YYYY-MM-DD'),
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.get() (err, res, body) ->
if err
robot.logger.error err
return
json = JSON.parse(body)
if !json || json.dates.length == 0 || json.dates[0].games.length == 0
msg.send "No games scheduled."
return
date = json.dates[0].date
game = json.dates[0].games[0]
if game.status.abstractGameState == 'Final'
gameStatus = 'Final'
else if game.status.abstractGameState == 'Live'
gameStatus = "#{game.linescore.currentPeriodTimeRemaining} #{game.linescore.currentPeriodOrdinal}"
else if game.status.detailedState == 'Scheduled' && game.status.startTimeTBD == false
gameStatus = "#{moment(game.gameDate).tz(team.time_zone).format('h:mm a z')}"
else
gameStatus = game.status.detailedState
if game.status.abstractGameState == 'Final' && game.linescore.currentPeriodOrdinal != '3rd'
gameStatus += "/#{game.linescore.currentPeriodOrdinal}"
if game.gameType == 'PR'
gameStatus = gameStatus + ' - Preseason'
if game.gameType == 'P'
gameStatus = gameStatus + " - #{game.seriesSummary.seriesStatus}"
table = new AsciiTable()
if game.teams.away.leagueRecord.ot? or game.teams.home.leagueRecord.ot?
table.addRow "#{game.teams.away.team.name} (#{game.teams.away.leagueRecord.wins}-#{game.teams.away.leagueRecord.losses}-#{game.teams.away.leagueRecord.ot})", "#{game.teams.away.score}"
table.addRow "#{game.teams.home.team.name} (#{game.teams.home.leagueRecord.wins}-#{game.teams.home.leagueRecord.losses}-#{game.teams.home.leagueRecord.ot})", "#{game.teams.home.score}"
else
table.addRow "#{game.teams.away.team.name} (#{game.teams.away.leagueRecord.wins}-#{game.teams.away.leagueRecord.losses})", "#{game.teams.away.score}"
table.addRow "#{game.teams.home.team.name} (#{game.teams.home.leagueRecord.wins}-#{game.teams.home.leagueRecord.losses})", "#{game.teams.home.score}"
table.removeBorder()
howToWatch = game.venue.name
if game.status.abstractGameState != 'Final' and game.broadcasts and game.broadcasts.length > 0
networks = []
for broadcast in game.broadcasts
networks.push "#{broadcast.name} (#{broadcast.type})"
howToWatch = howToWatch + "; TV: " + networks.join(' | ')
# Say it
switch robot.adapterName
when 'slack'
msg.send {
attachments: [
{
fallback: "#{moment(date).format('l')} - #{game.teams.away.team.name} #{game.teams.away.score}, #{game.teams.home.team.name} #{game.teams.home.score} (#{gameStatus})",
title_link: "https://www.nhl.com/gamecenter/#{game.gamePk}",
author_name: "NHL.com",
author_link: "https://nhl.com",
author_icon: "https://github.com/nhl.png",
color: team.primary_color,
title: "#{moment(date).format('l')} - #{gameStatus}",
text: "```\n" + table.toString() + "\n```"
footer: "#{howToWatch}",
mrkdwn_in: ["text", "pretext"]
}
]
}
else
msg.send "#{moment(date).format('l')} - #{howToWatch}"
msg.send table.toString()
msg.send "#{gameStatus} - https://www.nhl.com/gamecenter/#{game.gamePk}"
if typeof cb == 'function'
cb()
getMoneyPuckData = (team, msg, cb) ->
robot.logger.debug team
msg.http('https://moneypuck.com/moneypuck/simulations/simulations_recent.csv')
.get() (err, res, body) ->
# Catch errors
if err || res.statusCode != 200
msg.send "Cannot get your playoff odds right now."
return
# Parse the CSV file into lines
parse body, {}, (err, output) ->
if err
msg.send err
return
# Extract only appropriate row (all odds for given team)
odds = []
for row in output
odds = row if row[0] is 'ALL' and row[1] is team.abbreviation
if !odds
msg.send "Could not find your odds for team #{team.abbreviation}"
return
# Extract relevant columns
make_playoffs = odds[output[0].indexOf('madePlayoffs')] * 100
win_cup = odds[output[0].indexOf('wonCup')] * 100
oddsParts = []
slackFields = []
if make_playoffs > 0 and make_playoffs < 100
oddsParts.push("Make Playoffs: #{make_playoffs.toFixed(1)}%")
slackFields.push({
title: "Make Playoffs",
value: "#{make_playoffs.toFixed(1)}%",
short: false
})
if win_cup > 0 and win_cup < 100
oddsParts.push("Win Stanley Cup: #{win_cup.toFixed(1)}%")
slackFields.push({
title: "Win Stanley Cup",
value: "#{win_cup.toFixed(1)}%",
short: false
})
# Bail if odds are irrelevant
if oddsParts.length == 0
robot.logger.debug 'No reason to show the odds.'
return
fallback = "Odds to " + oddsParts.join(" / ")
# Say it
switch robot.adapterName
when 'slack'
msg.send {
attachments: [
{
author_icon: "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
author_link: "https://moneypuck.com",
author_name: "MoneyPuck.com",
fallback: fallback,
thumb_url: "http://peter-tanner.com/moneypuck/logos/#{team.abbreviation}.png",
title: team.name,
color: team.primary_color,
fields: slackFields
}
]
}
else
msg.send fallback
if typeof cb == 'function'
cb()
showLatestTweet = (team, msg) ->
# Skip if no client configured
return if missingEnvironmentForTwitterApi(msg)
params =
screen_name: team.twitter_handle
# Retrieve data using credentials
twitter_client.get 'statuses/user_timeline', params, (error, tweets, response) ->
# Return if error
if error || tweets.length == 0
robot.logger.error error
msg.send "Failed to retrieve tweets"
return
# Send first tweet
robot.logger.debug tweets
tweet = tweets[0]
switch robot.adapterName
when 'slack'
msg.send {
"text": "<https://twitter.com/#{tweet.user.screen_name}/status/#{tweet.id_str}>",
"unfurl_links": true
}
else
msg.send "<#{tweet.user.screen_name}> #{tweet.text} - #{tweet.created_at}"
strCapitalize = (str) ->
return str.charAt(0).toUpperCase() + str.substring(1)
# Check for Twitter config
missingEnvironmentForTwitterApi = (msg) ->
missingAnything = false
unless process.env.HUBOT_TWITTER_CONSUMER_KEY?
msg.send "Twitter API Client ID is missing: Ensure that HUBOT_TWITTER_CONSUMER_KEY is set."
missingAnything |= true
unless process.env.HUBOT_TWITTER_CONSUMER_SECRET?
msg.send "Twitter API Client Secret is missing: Ensure that HUBOT_TWITTER_CONSUMER_SECRET is set."
missingAnything |= true
unless process.env.HUBOT_TWITTER_ACCESS_TOKEN?
msg.send "Twitter API Access Token is missing: Ensure that HUBOT_TWITTER_ACCESS_TOKEN is set."
missingAnything |= true
unless process.env.HUBOT_TWITTER_ACCESS_TOKEN_SECRET?
msg.send "Twitter API Access Token Secret is missing: Ensure that HUBOT_TWITTER_ACCESS_TOKEN_SECRET is set."
missingAnything |= true
missingAnything
# Loop through teams and create multiple listeners
for team_item in hockey_teams
registerDefaultListener team_item
registerTweetListener team_item
| 61547 | # Description
# Get the latest hockey playoff odds for your team.
#
# Configuration:
# HUBOT_TWITTER_CONSUMER_KEY - Optional; Twitter consumer key
# HUBOT_TWITTER_CONSUMER_SECRET - Optional; Twitter consumer secret
# HUBOT_TWITTER_ACCESS_TOKEN - Optional; Twitter access token
# HUBOT_TWITTER_ACCESS_TOKEN_SECRET - Optional; Twitter access token secret
#
# Commands:
# hubot <team or city> - Get the lastest playoff odds from MoneyPuck.com
# hubot <team or city> twitter - Get the latest news from Twitter (requires configuration)
#
# Author:
# stephenyeargin
hockey_teams = require './teams.json'
moment = require 'moment-timezone'
parse = require 'csv-parse'
AsciiTable = require 'ascii-table'
# Twitter
Twitter = require 'twitter'
twitter_client = new Twitter
consumer_key: process.env.HUBOT_TWITTER_CONSUMER_KEY
consumer_secret: process.env.HUBOT_TWITTER_CONSUMER_SECRET
access_token_key: process.env.HUBOT_TWITTER_ACCESS_TOKEN
access_token_secret: process.env.HUBOT_TWITTER_ACCESS_TOKEN_SECRET
module.exports = (robot) ->
registerDefaultListener = (team) ->
statsregex = '_team_regex_$'
robot.respond new RegExp(statsregex.replace('_team_regex_', team.regex), 'i'), (msg) ->
getNhlStatsData team, msg, ->
getMoneyPuckData team, msg
registerTweetListener = (team) ->
twitterregex = '_team_regex_ (tweet|twitter)$'
robot.respond new RegExp(twitterregex.replace('_team_regex_', team.regex), 'i'), (msg) ->
showLatestTweet(team, msg)
getNhlStatsData = (team, msg, cb) ->
msg.http('https://statsapi.web.nhl.com/api/v1/schedule')
.query({
teamId: team.nhl_stats_api_id,
startDate: moment().tz('America/Los_Angeles').format('YYYY-MM-DD'),
endDate: moment().tz('America/Los_Angeles').add(90, 'd').format('YYYY-MM-DD'),
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.get() (err, res, body) ->
if err
robot.logger.error err
return
json = JSON.parse(body)
if !json || json.dates.length == 0 || json.dates[0].games.length == 0
msg.send "No games scheduled."
return
date = json.dates[0].date
game = json.dates[0].games[0]
if game.status.abstractGameState == 'Final'
gameStatus = 'Final'
else if game.status.abstractGameState == 'Live'
gameStatus = "#{game.linescore.currentPeriodTimeRemaining} #{game.linescore.currentPeriodOrdinal}"
else if game.status.detailedState == 'Scheduled' && game.status.startTimeTBD == false
gameStatus = "#{moment(game.gameDate).tz(team.time_zone).format('h:mm a z')}"
else
gameStatus = game.status.detailedState
if game.status.abstractGameState == 'Final' && game.linescore.currentPeriodOrdinal != '3rd'
gameStatus += "/#{game.linescore.currentPeriodOrdinal}"
if game.gameType == 'PR'
gameStatus = gameStatus + ' - Preseason'
if game.gameType == 'P'
gameStatus = gameStatus + " - #{game.seriesSummary.seriesStatus}"
table = new AsciiTable()
if game.teams.away.leagueRecord.ot? or game.teams.home.leagueRecord.ot?
table.addRow "#{game.teams.away.team.name} (#{game.teams.away.leagueRecord.wins}-#{game.teams.away.leagueRecord.losses}-#{game.teams.away.leagueRecord.ot})", "#{game.teams.away.score}"
table.addRow "#{game.teams.home.team.name} (#{game.teams.home.leagueRecord.wins}-#{game.teams.home.leagueRecord.losses}-#{game.teams.home.leagueRecord.ot})", "#{game.teams.home.score}"
else
table.addRow "#{game.teams.away.team.name} (#{game.teams.away.leagueRecord.wins}-#{game.teams.away.leagueRecord.losses})", "#{game.teams.away.score}"
table.addRow "#{game.teams.home.team.name} (#{game.teams.home.leagueRecord.wins}-#{game.teams.home.leagueRecord.losses})", "#{game.teams.home.score}"
table.removeBorder()
howToWatch = game.venue.name
if game.status.abstractGameState != 'Final' and game.broadcasts and game.broadcasts.length > 0
networks = []
for broadcast in game.broadcasts
networks.push "#{broadcast.name} (#{broadcast.type})"
howToWatch = howToWatch + "; TV: " + networks.join(' | ')
# Say it
switch robot.adapterName
when 'slack'
msg.send {
attachments: [
{
fallback: "#{moment(date).format('l')} - #{game.teams.away.team.name} #{game.teams.away.score}, #{game.teams.home.team.name} #{game.teams.home.score} (#{gameStatus})",
title_link: "https://www.nhl.com/gamecenter/#{game.gamePk}",
author_name: "NHL.com",
author_link: "https://nhl.com",
author_icon: "https://github.com/nhl.png",
color: team.primary_color,
title: "#{moment(date).format('l')} - #{gameStatus}",
text: "```\n" + table.toString() + "\n```"
footer: "#{howToWatch}",
mrkdwn_in: ["text", "pretext"]
}
]
}
else
msg.send "#{moment(date).format('l')} - #{howToWatch}"
msg.send table.toString()
msg.send "#{gameStatus} - https://www.nhl.com/gamecenter/#{game.gamePk}"
if typeof cb == 'function'
cb()
getMoneyPuckData = (team, msg, cb) ->
robot.logger.debug team
msg.http('https://moneypuck.com/moneypuck/simulations/simulations_recent.csv')
.get() (err, res, body) ->
# Catch errors
if err || res.statusCode != 200
msg.send "Cannot get your playoff odds right now."
return
# Parse the CSV file into lines
parse body, {}, (err, output) ->
if err
msg.send err
return
# Extract only appropriate row (all odds for given team)
odds = []
for row in output
odds = row if row[0] is 'ALL' and row[1] is team.abbreviation
if !odds
msg.send "Could not find your odds for team #{team.abbreviation}"
return
# Extract relevant columns
make_playoffs = odds[output[0].indexOf('madePlayoffs')] * 100
win_cup = odds[output[0].indexOf('wonCup')] * 100
oddsParts = []
slackFields = []
if make_playoffs > 0 and make_playoffs < 100
oddsParts.push("Make Playoffs: #{make_playoffs.toFixed(1)}%")
slackFields.push({
title: "Make Playoffs",
value: "#{make_playoffs.toFixed(1)}%",
short: false
})
if win_cup > 0 and win_cup < 100
oddsParts.push("Win Stanley Cup: #{win_cup.toFixed(1)}%")
slackFields.push({
title: "Win Stanley Cup",
value: "#{win_cup.toFixed(1)}%",
short: false
})
# Bail if odds are irrelevant
if oddsParts.length == 0
robot.logger.debug 'No reason to show the odds.'
return
fallback = "Odds to " + oddsParts.join(" / ")
# Say it
switch robot.adapterName
when 'slack'
msg.send {
attachments: [
{
author_icon: "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
author_link: "https://moneypuck.com",
author_name: "<EMAIL>",
fallback: fallback,
thumb_url: "http://peter-tanner.com/moneypuck/logos/#{team.abbreviation}.png",
title: team.name,
color: team.primary_color,
fields: slackFields
}
]
}
else
msg.send fallback
if typeof cb == 'function'
cb()
showLatestTweet = (team, msg) ->
# Skip if no client configured
return if missingEnvironmentForTwitterApi(msg)
params =
screen_name: team.twitter_handle
# Retrieve data using credentials
twitter_client.get 'statuses/user_timeline', params, (error, tweets, response) ->
# Return if error
if error || tweets.length == 0
robot.logger.error error
msg.send "Failed to retrieve tweets"
return
# Send first tweet
robot.logger.debug tweets
tweet = tweets[0]
switch robot.adapterName
when 'slack'
msg.send {
"text": "<https://twitter.com/#{tweet.user.screen_name}/status/#{tweet.id_str}>",
"unfurl_links": true
}
else
msg.send "<#{tweet.user.screen_name}> #{tweet.text} - #{tweet.created_at}"
strCapitalize = (str) ->
return str.charAt(0).toUpperCase() + str.substring(1)
# Check for Twitter config
missingEnvironmentForTwitterApi = (msg) ->
missingAnything = false
unless process.env.HUBOT_TWITTER_CONSUMER_KEY?
msg.send "Twitter API Client ID is missing: Ensure that HUBOT_TWITTER_CONSUMER_KEY is set."
missingAnything |= true
unless process.env.HUBOT_TWITTER_CONSUMER_SECRET?
msg.send "Twitter API Client Secret is missing: Ensure that HUBOT_TWITTER_CONSUMER_SECRET is set."
missingAnything |= true
unless process.env.HUBOT_TWITTER_ACCESS_TOKEN?
msg.send "Twitter API Access Token is missing: Ensure that HUBOT_TWITTER_ACCESS_TOKEN is set."
missingAnything |= true
unless process.env.HUBOT_TWITTER_ACCESS_TOKEN_SECRET?
msg.send "Twitter API Access Token Secret is missing: Ensure that HUBOT_TWITTER_ACCESS_TOKEN_SECRET is set."
missingAnything |= true
missingAnything
# Loop through teams and create multiple listeners
for team_item in hockey_teams
registerDefaultListener team_item
registerTweetListener team_item
| true | # Description
# Get the latest hockey playoff odds for your team.
#
# Configuration:
# HUBOT_TWITTER_CONSUMER_KEY - Optional; Twitter consumer key
# HUBOT_TWITTER_CONSUMER_SECRET - Optional; Twitter consumer secret
# HUBOT_TWITTER_ACCESS_TOKEN - Optional; Twitter access token
# HUBOT_TWITTER_ACCESS_TOKEN_SECRET - Optional; Twitter access token secret
#
# Commands:
# hubot <team or city> - Get the lastest playoff odds from MoneyPuck.com
# hubot <team or city> twitter - Get the latest news from Twitter (requires configuration)
#
# Author:
# stephenyeargin
hockey_teams = require './teams.json'
moment = require 'moment-timezone'
parse = require 'csv-parse'
AsciiTable = require 'ascii-table'
# Twitter
Twitter = require 'twitter'
twitter_client = new Twitter
consumer_key: process.env.HUBOT_TWITTER_CONSUMER_KEY
consumer_secret: process.env.HUBOT_TWITTER_CONSUMER_SECRET
access_token_key: process.env.HUBOT_TWITTER_ACCESS_TOKEN
access_token_secret: process.env.HUBOT_TWITTER_ACCESS_TOKEN_SECRET
module.exports = (robot) ->
registerDefaultListener = (team) ->
statsregex = '_team_regex_$'
robot.respond new RegExp(statsregex.replace('_team_regex_', team.regex), 'i'), (msg) ->
getNhlStatsData team, msg, ->
getMoneyPuckData team, msg
registerTweetListener = (team) ->
twitterregex = '_team_regex_ (tweet|twitter)$'
robot.respond new RegExp(twitterregex.replace('_team_regex_', team.regex), 'i'), (msg) ->
showLatestTweet(team, msg)
getNhlStatsData = (team, msg, cb) ->
msg.http('https://statsapi.web.nhl.com/api/v1/schedule')
.query({
teamId: team.nhl_stats_api_id,
startDate: moment().tz('America/Los_Angeles').format('YYYY-MM-DD'),
endDate: moment().tz('America/Los_Angeles').add(90, 'd').format('YYYY-MM-DD'),
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.get() (err, res, body) ->
if err
robot.logger.error err
return
json = JSON.parse(body)
if !json || json.dates.length == 0 || json.dates[0].games.length == 0
msg.send "No games scheduled."
return
date = json.dates[0].date
game = json.dates[0].games[0]
if game.status.abstractGameState == 'Final'
gameStatus = 'Final'
else if game.status.abstractGameState == 'Live'
gameStatus = "#{game.linescore.currentPeriodTimeRemaining} #{game.linescore.currentPeriodOrdinal}"
else if game.status.detailedState == 'Scheduled' && game.status.startTimeTBD == false
gameStatus = "#{moment(game.gameDate).tz(team.time_zone).format('h:mm a z')}"
else
gameStatus = game.status.detailedState
if game.status.abstractGameState == 'Final' && game.linescore.currentPeriodOrdinal != '3rd'
gameStatus += "/#{game.linescore.currentPeriodOrdinal}"
if game.gameType == 'PR'
gameStatus = gameStatus + ' - Preseason'
if game.gameType == 'P'
gameStatus = gameStatus + " - #{game.seriesSummary.seriesStatus}"
table = new AsciiTable()
if game.teams.away.leagueRecord.ot? or game.teams.home.leagueRecord.ot?
table.addRow "#{game.teams.away.team.name} (#{game.teams.away.leagueRecord.wins}-#{game.teams.away.leagueRecord.losses}-#{game.teams.away.leagueRecord.ot})", "#{game.teams.away.score}"
table.addRow "#{game.teams.home.team.name} (#{game.teams.home.leagueRecord.wins}-#{game.teams.home.leagueRecord.losses}-#{game.teams.home.leagueRecord.ot})", "#{game.teams.home.score}"
else
table.addRow "#{game.teams.away.team.name} (#{game.teams.away.leagueRecord.wins}-#{game.teams.away.leagueRecord.losses})", "#{game.teams.away.score}"
table.addRow "#{game.teams.home.team.name} (#{game.teams.home.leagueRecord.wins}-#{game.teams.home.leagueRecord.losses})", "#{game.teams.home.score}"
table.removeBorder()
howToWatch = game.venue.name
if game.status.abstractGameState != 'Final' and game.broadcasts and game.broadcasts.length > 0
networks = []
for broadcast in game.broadcasts
networks.push "#{broadcast.name} (#{broadcast.type})"
howToWatch = howToWatch + "; TV: " + networks.join(' | ')
# Say it
switch robot.adapterName
when 'slack'
msg.send {
attachments: [
{
fallback: "#{moment(date).format('l')} - #{game.teams.away.team.name} #{game.teams.away.score}, #{game.teams.home.team.name} #{game.teams.home.score} (#{gameStatus})",
title_link: "https://www.nhl.com/gamecenter/#{game.gamePk}",
author_name: "NHL.com",
author_link: "https://nhl.com",
author_icon: "https://github.com/nhl.png",
color: team.primary_color,
title: "#{moment(date).format('l')} - #{gameStatus}",
text: "```\n" + table.toString() + "\n```"
footer: "#{howToWatch}",
mrkdwn_in: ["text", "pretext"]
}
]
}
else
msg.send "#{moment(date).format('l')} - #{howToWatch}"
msg.send table.toString()
msg.send "#{gameStatus} - https://www.nhl.com/gamecenter/#{game.gamePk}"
if typeof cb == 'function'
cb()
getMoneyPuckData = (team, msg, cb) ->
robot.logger.debug team
msg.http('https://moneypuck.com/moneypuck/simulations/simulations_recent.csv')
.get() (err, res, body) ->
# Catch errors
if err || res.statusCode != 200
msg.send "Cannot get your playoff odds right now."
return
# Parse the CSV file into lines
parse body, {}, (err, output) ->
if err
msg.send err
return
# Extract only appropriate row (all odds for given team)
odds = []
for row in output
odds = row if row[0] is 'ALL' and row[1] is team.abbreviation
if !odds
msg.send "Could not find your odds for team #{team.abbreviation}"
return
# Extract relevant columns
make_playoffs = odds[output[0].indexOf('madePlayoffs')] * 100
win_cup = odds[output[0].indexOf('wonCup')] * 100
oddsParts = []
slackFields = []
if make_playoffs > 0 and make_playoffs < 100
oddsParts.push("Make Playoffs: #{make_playoffs.toFixed(1)}%")
slackFields.push({
title: "Make Playoffs",
value: "#{make_playoffs.toFixed(1)}%",
short: false
})
if win_cup > 0 and win_cup < 100
oddsParts.push("Win Stanley Cup: #{win_cup.toFixed(1)}%")
slackFields.push({
title: "Win Stanley Cup",
value: "#{win_cup.toFixed(1)}%",
short: false
})
# Bail if odds are irrelevant
if oddsParts.length == 0
robot.logger.debug 'No reason to show the odds.'
return
fallback = "Odds to " + oddsParts.join(" / ")
# Say it
switch robot.adapterName
when 'slack'
msg.send {
attachments: [
{
author_icon: "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
author_link: "https://moneypuck.com",
author_name: "PI:EMAIL:<EMAIL>END_PI",
fallback: fallback,
thumb_url: "http://peter-tanner.com/moneypuck/logos/#{team.abbreviation}.png",
title: team.name,
color: team.primary_color,
fields: slackFields
}
]
}
else
msg.send fallback
if typeof cb == 'function'
cb()
showLatestTweet = (team, msg) ->
# Skip if no client configured
return if missingEnvironmentForTwitterApi(msg)
params =
screen_name: team.twitter_handle
# Retrieve data using credentials
twitter_client.get 'statuses/user_timeline', params, (error, tweets, response) ->
# Return if error
if error || tweets.length == 0
robot.logger.error error
msg.send "Failed to retrieve tweets"
return
# Send first tweet
robot.logger.debug tweets
tweet = tweets[0]
switch robot.adapterName
when 'slack'
msg.send {
"text": "<https://twitter.com/#{tweet.user.screen_name}/status/#{tweet.id_str}>",
"unfurl_links": true
}
else
msg.send "<#{tweet.user.screen_name}> #{tweet.text} - #{tweet.created_at}"
strCapitalize = (str) ->
return str.charAt(0).toUpperCase() + str.substring(1)
# Check for Twitter config
missingEnvironmentForTwitterApi = (msg) ->
missingAnything = false
unless process.env.HUBOT_TWITTER_CONSUMER_KEY?
msg.send "Twitter API Client ID is missing: Ensure that HUBOT_TWITTER_CONSUMER_KEY is set."
missingAnything |= true
unless process.env.HUBOT_TWITTER_CONSUMER_SECRET?
msg.send "Twitter API Client Secret is missing: Ensure that HUBOT_TWITTER_CONSUMER_SECRET is set."
missingAnything |= true
unless process.env.HUBOT_TWITTER_ACCESS_TOKEN?
msg.send "Twitter API Access Token is missing: Ensure that HUBOT_TWITTER_ACCESS_TOKEN is set."
missingAnything |= true
unless process.env.HUBOT_TWITTER_ACCESS_TOKEN_SECRET?
msg.send "Twitter API Access Token Secret is missing: Ensure that HUBOT_TWITTER_ACCESS_TOKEN_SECRET is set."
missingAnything |= true
missingAnything
# Loop through teams and create multiple listeners
for team_item in hockey_teams
registerDefaultListener team_item
registerTweetListener team_item
|
[
{
"context": " ]\n -[\n 80\n 40\n ]\n ])\n name: \"testLine1\"\n)\nsatLayer = new ol.layer.Tile(source: new ol.so",
"end": 266,
"score": 0.6728804111480713,
"start": 257,
"tag": "NAME",
"value": "testLine1"
},
{
"context": "lPoint: new ol.geom.Point(labelCoords),\... | app/assets/javascripts/tracking_home/tracking_home.js.coffee | lnigra/PusherProblemTest | 1 | map = undefined
satLayer = undefined
startPoint = undefined
streetLayer = undefined
zoomSlider = undefined
featureList1 = new ol.Feature(
geometry: new ol.geom.LineString([
[
-81.62
41.88
]
-[
80
40
]
])
name: "testLine1"
)
satLayer = new ol.layer.Tile(source: new ol.source.MapQuest(layer: "sat"))
streetLayer = new ol.layer.Tile(source: new ol.source.MapQuest(layer: "osm"))
#projection:new ol.proj.EPSG4326(),
featuresLayer1 = new ol.layer.Vector(source: new ol.source.Vector(features: featureList1)) #this array is defined above
map = new ol.Map(
interactions: ol.interaction.defaults().extend([new ol.interaction.Select(style: new ol.style.Style(image: new ol.style.Circle(
radius: 5
fill: new ol.style.Fill(color: "#FF0000")
)))])
target: "map"
layers: [
satLayer
streetLayer
]
view: new ol.View(
center: ol.proj.transform([
37.41
8.82
], "EPSG:4326", "EPSG:3857")
zoom: 4
)
)
map.addLayer satLayer #remember to capitalize the L's!
map.addLayer streetLayer
map.addLayer featuresLayer1
#Styles:
blueStyle = [new ol.style.Style(
fill: new ol.style.Fill(color: "blue")
stroke: new ol.style.Stroke(
color: "blue"
width: 3
)
)]
greenStyle = [new ol.style.Style(
fill: new ol.style.Fill(color: "#00FF00")
stroke: new ol.style.Stroke(
color: "#00FF00"
width: 3
)
)]
redStyle = [new ol.style.Style(
fill: new ol.style.Fill(color: "#FF0000")
stroke: new ol.style.Stroke(
color: "#FF0000"
width: 3
)
)]
markStyle = [new ol.style.Style({})]
#ol3 API docs has only has a title, but nothing in the body for styles
#pass for now
#there are actually functions to get and trace location of the mobile device (probably with GPS enabled) on map with setTracking(), and stuff like getAltitude(
#The following zoom slider actually works!
zoomSlider = new ol.control.ZoomSlider()
map.addControl zoomSlider
#startPoint = new ol.Feature({
# geometry: new ol.geom.Polygon(polyCoords),
# labelPoint: new ol.geom.Point(labelCoords),
# name: "My Polygon"
#});
| 165411 | map = undefined
satLayer = undefined
startPoint = undefined
streetLayer = undefined
zoomSlider = undefined
featureList1 = new ol.Feature(
geometry: new ol.geom.LineString([
[
-81.62
41.88
]
-[
80
40
]
])
name: "<NAME>"
)
satLayer = new ol.layer.Tile(source: new ol.source.MapQuest(layer: "sat"))
streetLayer = new ol.layer.Tile(source: new ol.source.MapQuest(layer: "osm"))
#projection:new ol.proj.EPSG4326(),
featuresLayer1 = new ol.layer.Vector(source: new ol.source.Vector(features: featureList1)) #this array is defined above
map = new ol.Map(
interactions: ol.interaction.defaults().extend([new ol.interaction.Select(style: new ol.style.Style(image: new ol.style.Circle(
radius: 5
fill: new ol.style.Fill(color: "#FF0000")
)))])
target: "map"
layers: [
satLayer
streetLayer
]
view: new ol.View(
center: ol.proj.transform([
37.41
8.82
], "EPSG:4326", "EPSG:3857")
zoom: 4
)
)
map.addLayer satLayer #remember to capitalize the L's!
map.addLayer streetLayer
map.addLayer featuresLayer1
#Styles:
blueStyle = [new ol.style.Style(
fill: new ol.style.Fill(color: "blue")
stroke: new ol.style.Stroke(
color: "blue"
width: 3
)
)]
greenStyle = [new ol.style.Style(
fill: new ol.style.Fill(color: "#00FF00")
stroke: new ol.style.Stroke(
color: "#00FF00"
width: 3
)
)]
redStyle = [new ol.style.Style(
fill: new ol.style.Fill(color: "#FF0000")
stroke: new ol.style.Stroke(
color: "#FF0000"
width: 3
)
)]
markStyle = [new ol.style.Style({})]
#ol3 API docs has only has a title, but nothing in the body for styles
#pass for now
#there are actually functions to get and trace location of the mobile device (probably with GPS enabled) on map with setTracking(), and stuff like getAltitude(
#The following zoom slider actually works!
zoomSlider = new ol.control.ZoomSlider()
map.addControl zoomSlider
#startPoint = new ol.Feature({
# geometry: new ol.geom.Polygon(polyCoords),
# labelPoint: new ol.geom.Point(labelCoords),
# name: "<NAME> Polygon"
#});
| true | map = undefined
satLayer = undefined
startPoint = undefined
streetLayer = undefined
zoomSlider = undefined
featureList1 = new ol.Feature(
geometry: new ol.geom.LineString([
[
-81.62
41.88
]
-[
80
40
]
])
name: "PI:NAME:<NAME>END_PI"
)
satLayer = new ol.layer.Tile(source: new ol.source.MapQuest(layer: "sat"))
streetLayer = new ol.layer.Tile(source: new ol.source.MapQuest(layer: "osm"))
#projection:new ol.proj.EPSG4326(),
featuresLayer1 = new ol.layer.Vector(source: new ol.source.Vector(features: featureList1)) #this array is defined above
map = new ol.Map(
interactions: ol.interaction.defaults().extend([new ol.interaction.Select(style: new ol.style.Style(image: new ol.style.Circle(
radius: 5
fill: new ol.style.Fill(color: "#FF0000")
)))])
target: "map"
layers: [
satLayer
streetLayer
]
view: new ol.View(
center: ol.proj.transform([
37.41
8.82
], "EPSG:4326", "EPSG:3857")
zoom: 4
)
)
map.addLayer satLayer #remember to capitalize the L's!
map.addLayer streetLayer
map.addLayer featuresLayer1
#Styles:
blueStyle = [new ol.style.Style(
fill: new ol.style.Fill(color: "blue")
stroke: new ol.style.Stroke(
color: "blue"
width: 3
)
)]
greenStyle = [new ol.style.Style(
fill: new ol.style.Fill(color: "#00FF00")
stroke: new ol.style.Stroke(
color: "#00FF00"
width: 3
)
)]
redStyle = [new ol.style.Style(
fill: new ol.style.Fill(color: "#FF0000")
stroke: new ol.style.Stroke(
color: "#FF0000"
width: 3
)
)]
markStyle = [new ol.style.Style({})]
#ol3 API docs has only has a title, but nothing in the body for styles
#pass for now
#there are actually functions to get and trace location of the mobile device (probably with GPS enabled) on map with setTracking(), and stuff like getAltitude(
#The following zoom slider actually works!
zoomSlider = new ol.control.ZoomSlider()
map.addControl zoomSlider
#startPoint = new ol.Feature({
# geometry: new ol.geom.Polygon(polyCoords),
# labelPoint: new ol.geom.Point(labelCoords),
# name: "PI:NAME:<NAME>END_PI Polygon"
#});
|
[
{
"context": "=\n network: 'test' #test / live\n password: 'enter_your_password_here'\n storePath: './keys.txt' #null if no need to ",
"end": 293,
"score": 0.9992064833641052,
"start": 269,
"tag": "PASSWORD",
"value": "enter_your_password_here"
}
] | src/index.coffee | DrJekyllandMrHyde/bit | 129 | http = require 'http'
bitcore = require 'bitcore'
Key = require './key'
Transaction = require './transaction'
fs = require 'fs'
crypt = require './encrypt'
ee = require('events').EventEmitter
class Main
settings =
network: 'test' #test / live
password: 'enter_your_password_here'
storePath: './keys.txt' #null if no need to store
encryptPrivateKey: false
payToAddress: 'PUT_YOUR_ADDRESS_HERE'
payReminderToAddress: null
includeUnconfirmed: false
checkTransactionEvery: (1000 * 60 * 2) #2 minutes dev: 5000
checkBalanceTimeout: (1000 * 60 * 60 * 2) #60 minutes timeout --remove
checkUnspentTimeout: (1000 * 60 * 60 * 2) #60 minutes timeout
minimumConfirmations: 1
txFee: 0.0001
constructor: (address, o = {}) ->
return 'must have address' unless address
ee.call(this)
console.log 'hello ' + address
@settings = extend(settings, o)
generateAddress: (o, privateKey) =>
if privateKey
key = new Key settings, o, privateKey
else
key = new Key extend(settings, o)
key.checkBalance() if o and o.alertWhenHasBalance
key
encrypt: (s) =>
crypt.encrypt s, @settings.password
decrypt: (s) =>
crypt.decrypt s, @settings.password
extend = (object, properties) ->
for key, val of properties
object[key] = val
object
Main.prototype.__proto__ = ee.prototype
module.exports = Main | 187692 | http = require 'http'
bitcore = require 'bitcore'
Key = require './key'
Transaction = require './transaction'
fs = require 'fs'
crypt = require './encrypt'
ee = require('events').EventEmitter
class Main
settings =
network: 'test' #test / live
password: '<PASSWORD>'
storePath: './keys.txt' #null if no need to store
encryptPrivateKey: false
payToAddress: 'PUT_YOUR_ADDRESS_HERE'
payReminderToAddress: null
includeUnconfirmed: false
checkTransactionEvery: (1000 * 60 * 2) #2 minutes dev: 5000
checkBalanceTimeout: (1000 * 60 * 60 * 2) #60 minutes timeout --remove
checkUnspentTimeout: (1000 * 60 * 60 * 2) #60 minutes timeout
minimumConfirmations: 1
txFee: 0.0001
constructor: (address, o = {}) ->
return 'must have address' unless address
ee.call(this)
console.log 'hello ' + address
@settings = extend(settings, o)
generateAddress: (o, privateKey) =>
if privateKey
key = new Key settings, o, privateKey
else
key = new Key extend(settings, o)
key.checkBalance() if o and o.alertWhenHasBalance
key
encrypt: (s) =>
crypt.encrypt s, @settings.password
decrypt: (s) =>
crypt.decrypt s, @settings.password
extend = (object, properties) ->
for key, val of properties
object[key] = val
object
Main.prototype.__proto__ = ee.prototype
module.exports = Main | true | http = require 'http'
bitcore = require 'bitcore'
Key = require './key'
Transaction = require './transaction'
fs = require 'fs'
crypt = require './encrypt'
ee = require('events').EventEmitter
class Main
settings =
network: 'test' #test / live
password: 'PI:PASSWORD:<PASSWORD>END_PI'
storePath: './keys.txt' #null if no need to store
encryptPrivateKey: false
payToAddress: 'PUT_YOUR_ADDRESS_HERE'
payReminderToAddress: null
includeUnconfirmed: false
checkTransactionEvery: (1000 * 60 * 2) #2 minutes dev: 5000
checkBalanceTimeout: (1000 * 60 * 60 * 2) #60 minutes timeout --remove
checkUnspentTimeout: (1000 * 60 * 60 * 2) #60 minutes timeout
minimumConfirmations: 1
txFee: 0.0001
constructor: (address, o = {}) ->
return 'must have address' unless address
ee.call(this)
console.log 'hello ' + address
@settings = extend(settings, o)
generateAddress: (o, privateKey) =>
if privateKey
key = new Key settings, o, privateKey
else
key = new Key extend(settings, o)
key.checkBalance() if o and o.alertWhenHasBalance
key
encrypt: (s) =>
crypt.encrypt s, @settings.password
decrypt: (s) =>
crypt.decrypt s, @settings.password
extend = (object, properties) ->
for key, val of properties
object[key] = val
object
Main.prototype.__proto__ = ee.prototype
module.exports = Main |
[
{
"context": "://yasm.tortall.net/'\n,\n # Intermediate\n name: 'Asmble'\n source: 'WebAssembly'\n target: 'Java Byte",
"end": 650,
"score": 0.8112674951553345,
"start": 648,
"tag": "NAME",
"value": "As"
},
{
"context": " type: 'Intermediate'\n url: 'https://github.com/cretz/as... | src/compilers.coffee | EruditePanda/compilers | 0 | @COMPILERS = [
# Assembler
name: 'FASM'
source: 'Assembly'
target: 'Machine Code'
type: 'Assembler'
url: 'https://flatassembler.net/'
,
name: 'GAS'
source: 'Assembly'
target: 'Machine Code'
type: 'Assembler'
url: 'https://www.gnu.org/software/binutils/'
,
name: 'MASM'
source: 'Assembly'
target: 'Machine Code'
type: 'Assembler'
url: 'http://www.masm32.com/'
,
name: 'NASM'
source: 'Assembly'
target: 'Machine Code'
type: 'Assembler'
url: 'http://www.nasm.us/'
,
name: 'YASM'
source: 'Assembly'
target: 'Machine Code'
type: 'Assembler'
url: 'http://yasm.tortall.net/'
,
# Intermediate
name: 'Asmble'
source: 'WebAssembly'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'https://github.com/cretz/asmble/'
,
name: 'Ceylon Compiler'
source: 'Ceylon'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://ceylon-lang.org/'
,
name: 'Clang C'
source: 'C'
target: 'LLVM IR'
type: 'Intermediate'
url: 'http://clang.llvm.org/'
,
name: 'Clang C++'
source: 'C++'
target: 'LLVM IR'
type: 'Intermediate'
url: 'http://clang.llvm.org/'
,
name: 'Clang Objective-C'
source: 'Objective-C'
target: 'LLVM IR'
type: 'Intermediate'
url: 'http://clang.llvm.org/'
,
name: 'Clojure Compiler'
source: 'Clojure'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'https://clojure.org/index'
,
name: 'Crystal Compiler'
source: 'Crystal'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://crystal-lang.org/'
,
name: 'Flang'
source: 'Fortran'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://github.com/flang-compiler/flang'
,
name: 'GHC LLVM'
source: 'Haskell'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://www.haskell.org/ghc/'
,
name: 'Groovy Compiler'
source: 'Groovy'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://groovy-lang.org/groovyc.html'
,
name: 'IronPython'
source: 'Python'
target: 'CIL'
type: 'Intermediate'
url: 'http://ironpython.net/'
,
name: 'Java Compiler'
source: 'Java'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://openjdk.java.net/groups/compiler/'
,
name: 'JRuby'
source: 'Ruby'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://jruby.org/'
,
name: 'Julia Compiler',
source: 'Julia'
target: 'LLVM IR'
type: 'Intermediate'
url: 'http://julialang.org/'
,
name: 'Jython'
source: 'Python'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://www.jython.org/'
,
name: 'Kotlin Compiler'
source: 'Kotlin'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'https://kotlinlang.org/'
,
name: 'LDC'
source: 'D'
target: 'LLVM IR'
type: 'Intermediate'
url: 'http://wiki.dlang.org/LDC'
,
name: 'LLILC'
source: 'CIL'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://github.com/dotnet/llilc'
,
name: 'Phalanger'
source: 'PHP'
target: 'CIL'
type: 'Intermediate'
url: 'https://phalanger.codeplex.com/'
,
name: 'Roslyn C#'
source: 'C#'
target: 'CIL'
type: 'Intermediate'
url: 'https://github.com/dotnet/roslyn'
,
name: 'Roslyn VB.NET'
source: 'Visual Basic .NET'
target: 'CIL'
type: 'Intermediate'
url: 'https://github.com/dotnet/roslyn'
,
name: 'Rust Compiler'
source: 'Rust'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://www.rust-lang.org/'
,
name: 'Scala Compiler'
source: 'Scala'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://www.scala-lang.org/'
,
name: 'Swift Compiler'
source: 'Swift'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://swift.org/'
,
name: 'Visual F#'
source: 'F#'
target: 'CIL'
type: 'Intermediate'
url: 'https://github.com/Microsoft/visualfsharp'
,
name: 'VOC'
source: 'Python'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'https://pybee.org/voc'
,
# JIT
name: 'CLR'
source: 'CIL'
target: 'Machine Code'
type: 'JIT'
url: 'https://msdn.microsoft.com/en-us/library/k8d11d4s.aspx'
,
name: 'HHVM Hack',
source: 'Hack'
target: 'Machine Code'
type: 'JIT'
url: 'http://hhvm.com/'
,
name: 'HHVM PHP',
source: 'PHP'
target: 'Machine Code'
type: 'JIT'
url: 'http://hhvm.com/'
,
name: 'JVM',
source: 'Java Bytecode'
target: 'Machine Code'
type: 'JIT'
url: 'https://docs.oracle.com/javase/specs/jvms/se8/html/index.html'
,
name: 'LuaJIT',
source: 'Lua'
target: 'Machine Code'
type: 'JIT'
url: 'http://luajit.org/'
,
name: 'PyPy'
source: 'Python'
target: 'Machine Code'
type: 'JIT'
url: 'http://pypy.org/'
,
name: 'V8'
source: 'JavaScript'
target: 'Machine Code'
type: 'JIT'
url: 'https://developers.google.com/v8/'
,
# Native
name: 'DMD'
source: 'D'
target: 'Machine Code'
type: 'Native'
url: 'https://tour.dlang.org/'
,
name: 'Free Pascal'
source: 'Pascal'
target: 'Machine Code'
type: 'Native'
url: 'http://www.freepascal.org/'
,
name: 'FreeBASIC'
source: 'BASIC'
target: 'Machine Code'
type: 'Native'
url: 'http://www.freebasic.net/'
,
name: 'G++'
source: 'C++'
target: 'Machine Code'
type: 'Native'
url: 'https://gcc.gnu.org/'
,
name: 'GCC'
source: 'C'
target: 'Machine Code'
type: 'Native'
url: 'https://gcc.gnu.org/'
,
name: 'GFortran'
source: 'Fortran'
target: 'Machine Code'
type: 'Native'
url: 'https://gcc.gnu.org/fortran/'
,
name: 'GHC'
source: 'Haskell'
target: 'Machine Code'
type: 'Native'
url: 'https://www.haskell.org/ghc/'
,
name: 'GNAT'
source: 'Ada'
target: 'Machine Code'
type: 'Native'
url: 'https://www.gnu.org/software/gnat/'
,
name: 'Go Compiler'
source: 'Go'
target: 'Machine Code'
type: 'Native'
url: 'https://golang.org/'
,
name: 'Intel C'
source: 'C'
target: 'Machine Code'
type: 'Native'
url: 'https://software.intel.com/en-us/c-compilers'
,
name: 'Intel C++'
source: 'C++'
target: 'Machine Code'
type: 'Native'
url: 'https://software.intel.com/en-us/c-compilers'
,
name: 'LLVM'
source: 'LLVM IR'
target: 'Machine Code'
type: 'Native'
url: 'http://llvm.org/'
,
name: 'OCaml Compiler'
source: 'OCaml'
target: 'Machine Code'
type: 'Native'
url: 'https://ocaml.org/'
,
name: 'UHC'
source: 'Haskell'
target: 'Machine Code'
type: 'Native'
url: 'http://foswiki.cs.uu.nl/foswiki/UHC'
,
name: 'Visual C'
source: 'C'
target: 'Machine Code'
type: 'Native'
url: 'http://landinghub.visualstudio.com/visual-cpp-build-tools'
,
name: 'Visual C++'
source: 'C++'
target: 'Machine Code'
type: 'Native'
url: 'http://landinghub.visualstudio.com/visual-cpp-build-tools'
,
# Transpiler
name: 'Bck2Brwsr'
source: 'Java Bytecode'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://wiki.apidesign.org/wiki/Bck2Brwsr'
,
name: 'Bridge.NET'
source: 'C#'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://bridge.net/'
,
name: 'Brython'
source: 'Python'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://www.brython.info/'
,
name: 'BuckleScript'
source: 'OCaml'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://bloomberg.github.io/bucklescript/'
,
name: 'Ceylon JavaScript Compiler'
source: 'Ceylon'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://ceylon-lang.org/'
,
name: 'ClojureScript'
source: 'Clojure'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://clojurescript.org/'
,
name: 'CoffeeScript Compiler'
source: 'CoffeeScript'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://coffeescript.org/'
,
name: 'Corrode'
source: 'C'
target: 'Rust'
type: 'Transpiler'
url: 'https://github.com/jameysharp/corrode'
,
name: 'Dart-to-JavaScript'
source: 'Dart'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://webdev.dartlang.org/tools/dart2js'
,
name: 'Dragome'
source: 'Java Bytecode'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://www.dragome.com'
,
name: 'Elm Compiler'
source: 'Elm'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://elm-lang.org/'
,
name: 'Emscripten'
source: 'LLVM IR'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://emscripten.org'
,
name: 'Fable'
source: 'F#'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://fable-compiler.github.io/'
,
name: 'GHC C'
source: 'Haskell'
target: 'C'
type: 'Transpiler'
url: 'https://www.haskell.org/ghc/'
,
name: 'GHCJS'
source: 'Haskell'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://github.com/ghcjs'
,
name: 'GopherJS'
source: 'Go'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://www.gopherjs.org/'
,
name: 'Grumpy'
source: 'Python'
target: 'Go'
type: 'Transpiler'
url: 'https://github.com/google/grumpy'
,
name: 'GWT'
source: 'Java'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://www.gwtproject.org/'
,
name: 'Haste'
source: 'Haskell'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://haste-lang.org'
,
name: 'Haxe ActionScript Compiler'
source: 'Haxe'
target: 'ActionScript'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe C# Compiler'
source: 'Haxe'
target: 'C#'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe C++ Compiler'
source: 'Haxe'
target: 'C++'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe HashLink Compiler'
source: 'Haxe'
target: 'C'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe Java Compiler'
source: 'Haxe'
target: 'Java'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe JavaScript Compiler'
source: 'Haxe'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe Lua Compiler'
source: 'Haxe'
target: 'Lua'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe PHP Compiler'
source: 'Haxe'
target: 'PHP'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe Python Compiler'
source: 'Haxe'
target: 'Python'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'J2ObjC'
source: 'Java'
target: 'Objective-C'
type: 'Transpiler'
url: 'http://j2objc.org/'
,
name: 'Js2Py'
source: 'JavaScript'
target: 'Python'
type: 'Transpiler'
url: 'https://github.com/PiotrDabkowski/Js2Py'
,
name: 'JSIL'
source: 'CIL'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://jsil.org/'
,
name: 'JSweet'
source: 'Java'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://www.jsweet.org/'
,
name: 'Kotlin JavaScript Compiler'
source: 'Kotlin'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://kotlinlang.org/'
,
name: 'LLVM C Backend'
source: 'LLVM IR'
target: 'C'
type: 'Transpiler'
url: 'https://github.com/JuliaComputing/llvm-cbe'
,
name: 'MoonScript Compiler'
source: 'MoonScript'
target: 'Lua'
type: 'Transpiler'
url: 'http://moonscript.org/'
,
name: 'Nim C Compiler'
source: 'Nim'
target: 'C'
type: 'Transpiler'
url: 'http://nim-lang.org/'
,
name: 'Nim C++ Compiler'
source: 'Nim'
target: 'C++'
type: 'Transpiler'
url: 'http://nim-lang.org/'
,
name: 'Nim JavaScript Compiler'
source: 'Nim'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://nim-lang.org/'
,
name: 'Nim Objective-C Compiler'
source: 'Nim'
target: 'Objective-C'
type: 'Transpiler'
url: 'http://nim-lang.org/'
,
name: 'Opal'
source: 'Ruby'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://opalrb.org/'
,
name: 'Pythran'
source: 'Python'
target: 'C++'
type: 'Transpiler'
url: 'https://github.com/serge-sans-paille/pythran'
,
name: 'Scala.js'
source: 'Scala'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://www.scala-js.org/'
,
name: 'SharpNative'
source: 'C#'
target: 'D'
type: 'Transpiler'
url: 'https://github.com/afrog33k/SharpNative'
,
name: 'TeaVM'
source: 'Java Bytecode'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://teavm.org/'
,
name: 'Transcrypt'
source: 'Python'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://transcrypt.org/'
,
name: 'TypeScript Compiler'
source: 'TypeScript'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://www.typescriptlang.org/'
,
name: 'UHC JavaScript Compiler'
source: 'Haskell'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://foswiki.cs.uu.nl/foswiki/UHC'
,
]
| 121042 | @COMPILERS = [
# Assembler
name: 'FASM'
source: 'Assembly'
target: 'Machine Code'
type: 'Assembler'
url: 'https://flatassembler.net/'
,
name: 'GAS'
source: 'Assembly'
target: 'Machine Code'
type: 'Assembler'
url: 'https://www.gnu.org/software/binutils/'
,
name: 'MASM'
source: 'Assembly'
target: 'Machine Code'
type: 'Assembler'
url: 'http://www.masm32.com/'
,
name: 'NASM'
source: 'Assembly'
target: 'Machine Code'
type: 'Assembler'
url: 'http://www.nasm.us/'
,
name: 'YASM'
source: 'Assembly'
target: 'Machine Code'
type: 'Assembler'
url: 'http://yasm.tortall.net/'
,
# Intermediate
name: '<NAME>mble'
source: 'WebAssembly'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'https://github.com/cretz/asmble/'
,
name: 'Ceylon Compiler'
source: 'Ceylon'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://ceylon-lang.org/'
,
name: 'Clang C'
source: 'C'
target: 'LLVM IR'
type: 'Intermediate'
url: 'http://clang.llvm.org/'
,
name: 'Clang C++'
source: 'C++'
target: 'LLVM IR'
type: 'Intermediate'
url: 'http://clang.llvm.org/'
,
name: 'Clang Objective-C'
source: 'Objective-C'
target: 'LLVM IR'
type: 'Intermediate'
url: 'http://clang.llvm.org/'
,
name: 'Clojure Compiler'
source: 'Clojure'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'https://clojure.org/index'
,
name: 'Crystal Compiler'
source: 'Crystal'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://crystal-lang.org/'
,
name: 'Flang'
source: 'Fortran'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://github.com/flang-compiler/flang'
,
name: 'GHC LLVM'
source: 'Haskell'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://www.haskell.org/ghc/'
,
name: 'Groovy Compiler'
source: 'Groovy'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://groovy-lang.org/groovyc.html'
,
name: 'IronPython'
source: 'Python'
target: 'CIL'
type: 'Intermediate'
url: 'http://ironpython.net/'
,
name: 'Java Compiler'
source: 'Java'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://openjdk.java.net/groups/compiler/'
,
name: 'JRuby'
source: 'Ruby'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://jruby.org/'
,
name: 'Julia Compiler',
source: 'Julia'
target: 'LLVM IR'
type: 'Intermediate'
url: 'http://julialang.org/'
,
name: 'Jython'
source: 'Python'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://www.jython.org/'
,
name: 'Kotlin Compiler'
source: 'Kotlin'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'https://kotlinlang.org/'
,
name: 'LDC'
source: 'D'
target: 'LLVM IR'
type: 'Intermediate'
url: 'http://wiki.dlang.org/LDC'
,
name: 'LLILC'
source: 'CIL'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://github.com/dotnet/llilc'
,
name: 'Phalanger'
source: 'PHP'
target: 'CIL'
type: 'Intermediate'
url: 'https://phalanger.codeplex.com/'
,
name: 'Roslyn C#'
source: 'C#'
target: 'CIL'
type: 'Intermediate'
url: 'https://github.com/dotnet/roslyn'
,
name: 'Roslyn VB.NET'
source: 'Visual Basic .NET'
target: 'CIL'
type: 'Intermediate'
url: 'https://github.com/dotnet/roslyn'
,
name: 'Rust Compiler'
source: 'Rust'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://www.rust-lang.org/'
,
name: 'Scala Compiler'
source: 'Scala'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://www.scala-lang.org/'
,
name: 'Swift Compiler'
source: 'Swift'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://swift.org/'
,
name: 'Visual F#'
source: 'F#'
target: 'CIL'
type: 'Intermediate'
url: 'https://github.com/Microsoft/visualfsharp'
,
name: 'VOC'
source: 'Python'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'https://pybee.org/voc'
,
# JIT
name: 'CLR'
source: 'CIL'
target: 'Machine Code'
type: 'JIT'
url: 'https://msdn.microsoft.com/en-us/library/k8d11d4s.aspx'
,
name: 'HHVM Hack',
source: 'Hack'
target: 'Machine Code'
type: 'JIT'
url: 'http://hhvm.com/'
,
name: 'HHVM PHP',
source: 'PHP'
target: 'Machine Code'
type: 'JIT'
url: 'http://hhvm.com/'
,
name: 'JVM',
source: 'Java Bytecode'
target: 'Machine Code'
type: 'JIT'
url: 'https://docs.oracle.com/javase/specs/jvms/se8/html/index.html'
,
name: 'LuaJIT',
source: 'Lua'
target: 'Machine Code'
type: 'JIT'
url: 'http://luajit.org/'
,
name: 'PyPy'
source: 'Python'
target: 'Machine Code'
type: 'JIT'
url: 'http://pypy.org/'
,
name: 'V8'
source: 'JavaScript'
target: 'Machine Code'
type: 'JIT'
url: 'https://developers.google.com/v8/'
,
# Native
name: 'DMD'
source: 'D'
target: 'Machine Code'
type: 'Native'
url: 'https://tour.dlang.org/'
,
name: 'Free Pascal'
source: 'Pascal'
target: 'Machine Code'
type: 'Native'
url: 'http://www.freepascal.org/'
,
name: 'FreeBASIC'
source: 'BASIC'
target: 'Machine Code'
type: 'Native'
url: 'http://www.freebasic.net/'
,
name: 'G++'
source: 'C++'
target: 'Machine Code'
type: 'Native'
url: 'https://gcc.gnu.org/'
,
name: 'GCC'
source: 'C'
target: 'Machine Code'
type: 'Native'
url: 'https://gcc.gnu.org/'
,
name: 'GFortran'
source: 'Fortran'
target: 'Machine Code'
type: 'Native'
url: 'https://gcc.gnu.org/fortran/'
,
name: 'GHC'
source: 'Haskell'
target: 'Machine Code'
type: 'Native'
url: 'https://www.haskell.org/ghc/'
,
name: 'GNAT'
source: 'Ada'
target: 'Machine Code'
type: 'Native'
url: 'https://www.gnu.org/software/gnat/'
,
name: 'Go Compiler'
source: 'Go'
target: 'Machine Code'
type: 'Native'
url: 'https://golang.org/'
,
name: 'Intel C'
source: 'C'
target: 'Machine Code'
type: 'Native'
url: 'https://software.intel.com/en-us/c-compilers'
,
name: 'Intel C++'
source: 'C++'
target: 'Machine Code'
type: 'Native'
url: 'https://software.intel.com/en-us/c-compilers'
,
name: 'LLVM'
source: 'LLVM IR'
target: 'Machine Code'
type: 'Native'
url: 'http://llvm.org/'
,
name: 'OCaml Compiler'
source: 'OCaml'
target: 'Machine Code'
type: 'Native'
url: 'https://ocaml.org/'
,
name: 'UHC'
source: 'Haskell'
target: 'Machine Code'
type: 'Native'
url: 'http://foswiki.cs.uu.nl/foswiki/UHC'
,
name: 'Visual C'
source: 'C'
target: 'Machine Code'
type: 'Native'
url: 'http://landinghub.visualstudio.com/visual-cpp-build-tools'
,
name: 'Visual C++'
source: 'C++'
target: 'Machine Code'
type: 'Native'
url: 'http://landinghub.visualstudio.com/visual-cpp-build-tools'
,
# Transpiler
name: 'Bck2Brwsr'
source: 'Java Bytecode'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://wiki.apidesign.org/wiki/Bck2Brwsr'
,
name: 'Bridge.NET'
source: 'C#'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://bridge.net/'
,
name: 'Brython'
source: 'Python'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://www.brython.info/'
,
name: 'BuckleScript'
source: 'OCaml'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://bloomberg.github.io/bucklescript/'
,
name: 'Ceylon JavaScript Compiler'
source: 'Ceylon'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://ceylon-lang.org/'
,
name: 'ClojureScript'
source: 'Clojure'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://clojurescript.org/'
,
name: 'CoffeeScript Compiler'
source: 'CoffeeScript'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://coffeescript.org/'
,
name: 'Corrode'
source: 'C'
target: 'Rust'
type: 'Transpiler'
url: 'https://github.com/jameysharp/corrode'
,
name: 'Dart-to-JavaScript'
source: 'Dart'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://webdev.dartlang.org/tools/dart2js'
,
name: 'Dragome'
source: 'Java Bytecode'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://www.dragome.com'
,
name: 'Elm Compiler'
source: 'Elm'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://elm-lang.org/'
,
name: 'Emscripten'
source: 'LLVM IR'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://emscripten.org'
,
name: 'Fable'
source: 'F#'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://fable-compiler.github.io/'
,
name: 'GHC C'
source: 'Haskell'
target: 'C'
type: 'Transpiler'
url: 'https://www.haskell.org/ghc/'
,
name: 'GHCJS'
source: 'Haskell'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://github.com/ghcjs'
,
name: 'GopherJS'
source: 'Go'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://www.gopherjs.org/'
,
name: 'Grumpy'
source: 'Python'
target: 'Go'
type: 'Transpiler'
url: 'https://github.com/google/grumpy'
,
name: 'GWT'
source: 'Java'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://www.gwtproject.org/'
,
name: 'Haste'
source: 'Haskell'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://haste-lang.org'
,
name: 'Haxe ActionScript Compiler'
source: 'Haxe'
target: 'ActionScript'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe C# Compiler'
source: 'Haxe'
target: 'C#'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe C++ Compiler'
source: 'Haxe'
target: 'C++'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe HashLink Compiler'
source: 'Haxe'
target: 'C'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe Java Compiler'
source: 'Haxe'
target: 'Java'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe JavaScript Compiler'
source: 'Haxe'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe Lua Compiler'
source: 'Haxe'
target: 'Lua'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe PHP Compiler'
source: 'Haxe'
target: 'PHP'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe Python Compiler'
source: 'Haxe'
target: 'Python'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'J2ObjC'
source: 'Java'
target: 'Objective-C'
type: 'Transpiler'
url: 'http://j2objc.org/'
,
name: 'Js2Py'
source: 'JavaScript'
target: 'Python'
type: 'Transpiler'
url: 'https://github.com/PiotrDabkowski/Js2Py'
,
name: 'JSIL'
source: 'CIL'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://jsil.org/'
,
name: 'JSweet'
source: 'Java'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://www.jsweet.org/'
,
name: 'Kotlin JavaScript Compiler'
source: 'Kotlin'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://kotlinlang.org/'
,
name: 'LLVM C Backend'
source: 'LLVM IR'
target: 'C'
type: 'Transpiler'
url: 'https://github.com/JuliaComputing/llvm-cbe'
,
name: 'MoonScript Compiler'
source: 'MoonScript'
target: 'Lua'
type: 'Transpiler'
url: 'http://moonscript.org/'
,
name: 'Nim C Compiler'
source: 'Nim'
target: 'C'
type: 'Transpiler'
url: 'http://nim-lang.org/'
,
name: 'Nim C++ Compiler'
source: 'Nim'
target: 'C++'
type: 'Transpiler'
url: 'http://nim-lang.org/'
,
name: 'Nim JavaScript Compiler'
source: 'Nim'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://nim-lang.org/'
,
name: 'Nim Objective-C Compiler'
source: 'Nim'
target: 'Objective-C'
type: 'Transpiler'
url: 'http://nim-lang.org/'
,
name: 'Opal'
source: 'Ruby'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://opalrb.org/'
,
name: 'Pythran'
source: 'Python'
target: 'C++'
type: 'Transpiler'
url: 'https://github.com/serge-sans-paille/pythran'
,
name: 'Scala.js'
source: 'Scala'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://www.scala-js.org/'
,
name: 'SharpNative'
source: 'C#'
target: 'D'
type: 'Transpiler'
url: 'https://github.com/afrog33k/SharpNative'
,
name: 'TeaVM'
source: 'Java Bytecode'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://teavm.org/'
,
name: 'Transcrypt'
source: 'Python'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://transcrypt.org/'
,
name: 'TypeScript Compiler'
source: 'TypeScript'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://www.typescriptlang.org/'
,
name: 'UHC JavaScript Compiler'
source: 'Haskell'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://foswiki.cs.uu.nl/foswiki/UHC'
,
]
| true | @COMPILERS = [
# Assembler
name: 'FASM'
source: 'Assembly'
target: 'Machine Code'
type: 'Assembler'
url: 'https://flatassembler.net/'
,
name: 'GAS'
source: 'Assembly'
target: 'Machine Code'
type: 'Assembler'
url: 'https://www.gnu.org/software/binutils/'
,
name: 'MASM'
source: 'Assembly'
target: 'Machine Code'
type: 'Assembler'
url: 'http://www.masm32.com/'
,
name: 'NASM'
source: 'Assembly'
target: 'Machine Code'
type: 'Assembler'
url: 'http://www.nasm.us/'
,
name: 'YASM'
source: 'Assembly'
target: 'Machine Code'
type: 'Assembler'
url: 'http://yasm.tortall.net/'
,
# Intermediate
name: 'PI:NAME:<NAME>END_PImble'
source: 'WebAssembly'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'https://github.com/cretz/asmble/'
,
name: 'Ceylon Compiler'
source: 'Ceylon'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://ceylon-lang.org/'
,
name: 'Clang C'
source: 'C'
target: 'LLVM IR'
type: 'Intermediate'
url: 'http://clang.llvm.org/'
,
name: 'Clang C++'
source: 'C++'
target: 'LLVM IR'
type: 'Intermediate'
url: 'http://clang.llvm.org/'
,
name: 'Clang Objective-C'
source: 'Objective-C'
target: 'LLVM IR'
type: 'Intermediate'
url: 'http://clang.llvm.org/'
,
name: 'Clojure Compiler'
source: 'Clojure'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'https://clojure.org/index'
,
name: 'Crystal Compiler'
source: 'Crystal'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://crystal-lang.org/'
,
name: 'Flang'
source: 'Fortran'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://github.com/flang-compiler/flang'
,
name: 'GHC LLVM'
source: 'Haskell'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://www.haskell.org/ghc/'
,
name: 'Groovy Compiler'
source: 'Groovy'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://groovy-lang.org/groovyc.html'
,
name: 'IronPython'
source: 'Python'
target: 'CIL'
type: 'Intermediate'
url: 'http://ironpython.net/'
,
name: 'Java Compiler'
source: 'Java'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://openjdk.java.net/groups/compiler/'
,
name: 'JRuby'
source: 'Ruby'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://jruby.org/'
,
name: 'Julia Compiler',
source: 'Julia'
target: 'LLVM IR'
type: 'Intermediate'
url: 'http://julialang.org/'
,
name: 'Jython'
source: 'Python'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://www.jython.org/'
,
name: 'Kotlin Compiler'
source: 'Kotlin'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'https://kotlinlang.org/'
,
name: 'LDC'
source: 'D'
target: 'LLVM IR'
type: 'Intermediate'
url: 'http://wiki.dlang.org/LDC'
,
name: 'LLILC'
source: 'CIL'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://github.com/dotnet/llilc'
,
name: 'Phalanger'
source: 'PHP'
target: 'CIL'
type: 'Intermediate'
url: 'https://phalanger.codeplex.com/'
,
name: 'Roslyn C#'
source: 'C#'
target: 'CIL'
type: 'Intermediate'
url: 'https://github.com/dotnet/roslyn'
,
name: 'Roslyn VB.NET'
source: 'Visual Basic .NET'
target: 'CIL'
type: 'Intermediate'
url: 'https://github.com/dotnet/roslyn'
,
name: 'Rust Compiler'
source: 'Rust'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://www.rust-lang.org/'
,
name: 'Scala Compiler'
source: 'Scala'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'http://www.scala-lang.org/'
,
name: 'Swift Compiler'
source: 'Swift'
target: 'LLVM IR'
type: 'Intermediate'
url: 'https://swift.org/'
,
name: 'Visual F#'
source: 'F#'
target: 'CIL'
type: 'Intermediate'
url: 'https://github.com/Microsoft/visualfsharp'
,
name: 'VOC'
source: 'Python'
target: 'Java Bytecode'
type: 'Intermediate'
url: 'https://pybee.org/voc'
,
# JIT
name: 'CLR'
source: 'CIL'
target: 'Machine Code'
type: 'JIT'
url: 'https://msdn.microsoft.com/en-us/library/k8d11d4s.aspx'
,
name: 'HHVM Hack',
source: 'Hack'
target: 'Machine Code'
type: 'JIT'
url: 'http://hhvm.com/'
,
name: 'HHVM PHP',
source: 'PHP'
target: 'Machine Code'
type: 'JIT'
url: 'http://hhvm.com/'
,
name: 'JVM',
source: 'Java Bytecode'
target: 'Machine Code'
type: 'JIT'
url: 'https://docs.oracle.com/javase/specs/jvms/se8/html/index.html'
,
name: 'LuaJIT',
source: 'Lua'
target: 'Machine Code'
type: 'JIT'
url: 'http://luajit.org/'
,
name: 'PyPy'
source: 'Python'
target: 'Machine Code'
type: 'JIT'
url: 'http://pypy.org/'
,
name: 'V8'
source: 'JavaScript'
target: 'Machine Code'
type: 'JIT'
url: 'https://developers.google.com/v8/'
,
# Native
name: 'DMD'
source: 'D'
target: 'Machine Code'
type: 'Native'
url: 'https://tour.dlang.org/'
,
name: 'Free Pascal'
source: 'Pascal'
target: 'Machine Code'
type: 'Native'
url: 'http://www.freepascal.org/'
,
name: 'FreeBASIC'
source: 'BASIC'
target: 'Machine Code'
type: 'Native'
url: 'http://www.freebasic.net/'
,
name: 'G++'
source: 'C++'
target: 'Machine Code'
type: 'Native'
url: 'https://gcc.gnu.org/'
,
name: 'GCC'
source: 'C'
target: 'Machine Code'
type: 'Native'
url: 'https://gcc.gnu.org/'
,
name: 'GFortran'
source: 'Fortran'
target: 'Machine Code'
type: 'Native'
url: 'https://gcc.gnu.org/fortran/'
,
name: 'GHC'
source: 'Haskell'
target: 'Machine Code'
type: 'Native'
url: 'https://www.haskell.org/ghc/'
,
name: 'GNAT'
source: 'Ada'
target: 'Machine Code'
type: 'Native'
url: 'https://www.gnu.org/software/gnat/'
,
name: 'Go Compiler'
source: 'Go'
target: 'Machine Code'
type: 'Native'
url: 'https://golang.org/'
,
name: 'Intel C'
source: 'C'
target: 'Machine Code'
type: 'Native'
url: 'https://software.intel.com/en-us/c-compilers'
,
name: 'Intel C++'
source: 'C++'
target: 'Machine Code'
type: 'Native'
url: 'https://software.intel.com/en-us/c-compilers'
,
name: 'LLVM'
source: 'LLVM IR'
target: 'Machine Code'
type: 'Native'
url: 'http://llvm.org/'
,
name: 'OCaml Compiler'
source: 'OCaml'
target: 'Machine Code'
type: 'Native'
url: 'https://ocaml.org/'
,
name: 'UHC'
source: 'Haskell'
target: 'Machine Code'
type: 'Native'
url: 'http://foswiki.cs.uu.nl/foswiki/UHC'
,
name: 'Visual C'
source: 'C'
target: 'Machine Code'
type: 'Native'
url: 'http://landinghub.visualstudio.com/visual-cpp-build-tools'
,
name: 'Visual C++'
source: 'C++'
target: 'Machine Code'
type: 'Native'
url: 'http://landinghub.visualstudio.com/visual-cpp-build-tools'
,
# Transpiler
name: 'Bck2Brwsr'
source: 'Java Bytecode'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://wiki.apidesign.org/wiki/Bck2Brwsr'
,
name: 'Bridge.NET'
source: 'C#'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://bridge.net/'
,
name: 'Brython'
source: 'Python'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://www.brython.info/'
,
name: 'BuckleScript'
source: 'OCaml'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://bloomberg.github.io/bucklescript/'
,
name: 'Ceylon JavaScript Compiler'
source: 'Ceylon'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://ceylon-lang.org/'
,
name: 'ClojureScript'
source: 'Clojure'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://clojurescript.org/'
,
name: 'CoffeeScript Compiler'
source: 'CoffeeScript'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://coffeescript.org/'
,
name: 'Corrode'
source: 'C'
target: 'Rust'
type: 'Transpiler'
url: 'https://github.com/jameysharp/corrode'
,
name: 'Dart-to-JavaScript'
source: 'Dart'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://webdev.dartlang.org/tools/dart2js'
,
name: 'Dragome'
source: 'Java Bytecode'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://www.dragome.com'
,
name: 'Elm Compiler'
source: 'Elm'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://elm-lang.org/'
,
name: 'Emscripten'
source: 'LLVM IR'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://emscripten.org'
,
name: 'Fable'
source: 'F#'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://fable-compiler.github.io/'
,
name: 'GHC C'
source: 'Haskell'
target: 'C'
type: 'Transpiler'
url: 'https://www.haskell.org/ghc/'
,
name: 'GHCJS'
source: 'Haskell'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://github.com/ghcjs'
,
name: 'GopherJS'
source: 'Go'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://www.gopherjs.org/'
,
name: 'Grumpy'
source: 'Python'
target: 'Go'
type: 'Transpiler'
url: 'https://github.com/google/grumpy'
,
name: 'GWT'
source: 'Java'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://www.gwtproject.org/'
,
name: 'Haste'
source: 'Haskell'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://haste-lang.org'
,
name: 'Haxe ActionScript Compiler'
source: 'Haxe'
target: 'ActionScript'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe C# Compiler'
source: 'Haxe'
target: 'C#'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe C++ Compiler'
source: 'Haxe'
target: 'C++'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe HashLink Compiler'
source: 'Haxe'
target: 'C'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe Java Compiler'
source: 'Haxe'
target: 'Java'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe JavaScript Compiler'
source: 'Haxe'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe Lua Compiler'
source: 'Haxe'
target: 'Lua'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe PHP Compiler'
source: 'Haxe'
target: 'PHP'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'Haxe Python Compiler'
source: 'Haxe'
target: 'Python'
type: 'Transpiler'
url: 'https://haxe.org/'
,
name: 'J2ObjC'
source: 'Java'
target: 'Objective-C'
type: 'Transpiler'
url: 'http://j2objc.org/'
,
name: 'Js2Py'
source: 'JavaScript'
target: 'Python'
type: 'Transpiler'
url: 'https://github.com/PiotrDabkowski/Js2Py'
,
name: 'JSIL'
source: 'CIL'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://jsil.org/'
,
name: 'JSweet'
source: 'Java'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://www.jsweet.org/'
,
name: 'Kotlin JavaScript Compiler'
source: 'Kotlin'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://kotlinlang.org/'
,
name: 'LLVM C Backend'
source: 'LLVM IR'
target: 'C'
type: 'Transpiler'
url: 'https://github.com/JuliaComputing/llvm-cbe'
,
name: 'MoonScript Compiler'
source: 'MoonScript'
target: 'Lua'
type: 'Transpiler'
url: 'http://moonscript.org/'
,
name: 'Nim C Compiler'
source: 'Nim'
target: 'C'
type: 'Transpiler'
url: 'http://nim-lang.org/'
,
name: 'Nim C++ Compiler'
source: 'Nim'
target: 'C++'
type: 'Transpiler'
url: 'http://nim-lang.org/'
,
name: 'Nim JavaScript Compiler'
source: 'Nim'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://nim-lang.org/'
,
name: 'Nim Objective-C Compiler'
source: 'Nim'
target: 'Objective-C'
type: 'Transpiler'
url: 'http://nim-lang.org/'
,
name: 'Opal'
source: 'Ruby'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://opalrb.org/'
,
name: 'Pythran'
source: 'Python'
target: 'C++'
type: 'Transpiler'
url: 'https://github.com/serge-sans-paille/pythran'
,
name: 'Scala.js'
source: 'Scala'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://www.scala-js.org/'
,
name: 'SharpNative'
source: 'C#'
target: 'D'
type: 'Transpiler'
url: 'https://github.com/afrog33k/SharpNative'
,
name: 'TeaVM'
source: 'Java Bytecode'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://teavm.org/'
,
name: 'Transcrypt'
source: 'Python'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://transcrypt.org/'
,
name: 'TypeScript Compiler'
source: 'TypeScript'
target: 'JavaScript'
type: 'Transpiler'
url: 'https://www.typescriptlang.org/'
,
name: 'UHC JavaScript Compiler'
source: 'Haskell'
target: 'JavaScript'
type: 'Transpiler'
url: 'http://foswiki.cs.uu.nl/foswiki/UHC'
,
]
|
[
{
"context": "Google Safebrowsing Report for URL\n#\n# Author:\n# A. Gianotto - @snipe\n# Updated by Igor Antunes - @darigazz1",
"end": 360,
"score": 0.9998040199279785,
"start": 349,
"tag": "NAME",
"value": "A. Gianotto"
},
{
"context": "wsing Report for URL\n#\n# Author:\n# A... | src/google-safebrowsing.coffee | Darigazz/hubot-simple-sec-candies | 0 | # Description:
# Get Website Report from Google Safebrowsing (https://developers.google.com/safe-browsing)
#
# Dependencies:
# None
#
# Configuration:
# GOOGLE_SAFEBROWSING_API_KEY - Sign up at https://developers.google.com/safe-browsing/key_signup
#
# Commands:
# hubot gsafe <url> - Gets Google Safebrowsing Report for URL
#
# Author:
# A. Gianotto - @snipe
# Updated by Igor Antunes - @darigazz1984
GOOGLE_SAFEBROWSING_API_KEY = process.env.GOOGLE_SAFEBROWSING_API_KEY
is_empty = (obj) ->
return true if not obj? or obj.length is 0
return false if obj.length? and obj.length > 0
for key of obj
return false if Object.prototype.hasOwnProperty.call(obj,key)
return true
module.exports = (robot) ->
robot.respond /gsafe (.*)/i, (msg) ->
if GOOGLE_SAFEBROWSING_API_KEY?
gsafe_term = msg.match[1].toLowerCase()
request_body = JSON.stringify({client:{clientId:'home',clientVersion:'0.1'},threatInfo:{threatTypes:['MALWARE','SOCIAL_ENGINEERING','UNWANTED_SOFTWARE'],platformTypes:['ALL_PLATFORMS'],threatEntryTypes:['URL'],threatEntries:[{url:gsafe_term}]}})
api_url = "https://safebrowsing.googleapis.com/v4/threatMatches:find"
request_url = api_url
request_url += "?key=#{GOOGLE_SAFEBROWSING_API_KEY}"
robot.http(request_url)
.header('Content-Type','application/json')
.post(request_body) (err, res, body) ->
d = JSON.parse(body)
if res.statusCode is 200
if is_empty(d)
msg.send "[CLEAN] The URL #{gsafe_term} is NOT curently listed as suspicious in Google Safebrowsing. More info: at http://www.google.com/safebrowsing/diagnostic?site=#{encodeURIComponent gsafe_term}"
else
msg.send "[SUSPICIOUS] The URL #{gsafe_term} is listed as Malicious in Google Safebrowsing. More info: at http://www.google.com/safebrowsing/diagnostic?site=#{encodeURIComponent gsafe_term}"
else
msg.send "[ERROR] Got a #{res.statusCode} instead of a 200."
else
msg.send "API Key not configured"
| 12234 | # Description:
# Get Website Report from Google Safebrowsing (https://developers.google.com/safe-browsing)
#
# Dependencies:
# None
#
# Configuration:
# GOOGLE_SAFEBROWSING_API_KEY - Sign up at https://developers.google.com/safe-browsing/key_signup
#
# Commands:
# hubot gsafe <url> - Gets Google Safebrowsing Report for URL
#
# Author:
# <NAME> - @snipe
# Updated by <NAME> - @darigazz1984
GOOGLE_SAFEBROWSING_API_KEY = process.env.GOOGLE_SAFEBROWSING_API_KEY
is_empty = (obj) ->
return true if not obj? or obj.length is 0
return false if obj.length? and obj.length > 0
for key of obj
return false if Object.prototype.hasOwnProperty.call(obj,key)
return true
module.exports = (robot) ->
robot.respond /gsafe (.*)/i, (msg) ->
if GOOGLE_SAFEBROWSING_API_KEY?
gsafe_term = msg.match[1].toLowerCase()
request_body = JSON.stringify({client:{clientId:'home',clientVersion:'0.1'},threatInfo:{threatTypes:['MALWARE','SOCIAL_ENGINEERING','UNWANTED_SOFTWARE'],platformTypes:['ALL_PLATFORMS'],threatEntryTypes:['URL'],threatEntries:[{url:gsafe_term}]}})
api_url = "https://safebrowsing.googleapis.com/v4/threatMatches:find"
request_url = api_url
request_url += "?key=#{GOOGLE_SAFEBROWSING_API_KEY}"
robot.http(request_url)
.header('Content-Type','application/json')
.post(request_body) (err, res, body) ->
d = JSON.parse(body)
if res.statusCode is 200
if is_empty(d)
msg.send "[CLEAN] The URL #{gsafe_term} is NOT curently listed as suspicious in Google Safebrowsing. More info: at http://www.google.com/safebrowsing/diagnostic?site=#{encodeURIComponent gsafe_term}"
else
msg.send "[SUSPICIOUS] The URL #{gsafe_term} is listed as Malicious in Google Safebrowsing. More info: at http://www.google.com/safebrowsing/diagnostic?site=#{encodeURIComponent gsafe_term}"
else
msg.send "[ERROR] Got a #{res.statusCode} instead of a 200."
else
msg.send "API Key not configured"
| true | # Description:
# Get Website Report from Google Safebrowsing (https://developers.google.com/safe-browsing)
#
# Dependencies:
# None
#
# Configuration:
# GOOGLE_SAFEBROWSING_API_KEY - Sign up at https://developers.google.com/safe-browsing/key_signup
#
# Commands:
# hubot gsafe <url> - Gets Google Safebrowsing Report for URL
#
# Author:
# PI:NAME:<NAME>END_PI - @snipe
# Updated by PI:NAME:<NAME>END_PI - @darigazz1984
GOOGLE_SAFEBROWSING_API_KEY = process.env.GOOGLE_SAFEBROWSING_API_KEY
is_empty = (obj) ->
return true if not obj? or obj.length is 0
return false if obj.length? and obj.length > 0
for key of obj
return false if Object.prototype.hasOwnProperty.call(obj,key)
return true
module.exports = (robot) ->
robot.respond /gsafe (.*)/i, (msg) ->
if GOOGLE_SAFEBROWSING_API_KEY?
gsafe_term = msg.match[1].toLowerCase()
request_body = JSON.stringify({client:{clientId:'home',clientVersion:'0.1'},threatInfo:{threatTypes:['MALWARE','SOCIAL_ENGINEERING','UNWANTED_SOFTWARE'],platformTypes:['ALL_PLATFORMS'],threatEntryTypes:['URL'],threatEntries:[{url:gsafe_term}]}})
api_url = "https://safebrowsing.googleapis.com/v4/threatMatches:find"
request_url = api_url
request_url += "?key=#{GOOGLE_SAFEBROWSING_API_KEY}"
robot.http(request_url)
.header('Content-Type','application/json')
.post(request_body) (err, res, body) ->
d = JSON.parse(body)
if res.statusCode is 200
if is_empty(d)
msg.send "[CLEAN] The URL #{gsafe_term} is NOT curently listed as suspicious in Google Safebrowsing. More info: at http://www.google.com/safebrowsing/diagnostic?site=#{encodeURIComponent gsafe_term}"
else
msg.send "[SUSPICIOUS] The URL #{gsafe_term} is listed as Malicious in Google Safebrowsing. More info: at http://www.google.com/safebrowsing/diagnostic?site=#{encodeURIComponent gsafe_term}"
else
msg.send "[ERROR] Got a #{res.statusCode} instead of a 200."
else
msg.send "API Key not configured"
|
[
{
"context": ": \"\"\n cdnPrefix: \"\"\n talkAccountApiUrl: \"http://127.0.0.1:7632/account\"\n teambition:\n clientSecret: 'ab",
"end": 220,
"score": 0.9985922574996948,
"start": 211,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "bition:\n clientSecret: 'abc'\n... | test/main.coffee | jianliaoim/talk-services | 40 | # Initialize service
requireDir = require 'require-dir'
# Load mocked servers
require './servers/app'
loader = require '../src/loader'
loader.config =
apiHost: ""
cdnPrefix: ""
talkAccountApiUrl: "http://127.0.0.1:7632/account"
teambition:
clientSecret: 'abc'
host: 'http://127.0.0.1:7632/tb'
rss:
serviceUrl: 'http://127.0.0.1:7632/rss/worker'
github:
apiHost: 'http://127.0.0.1:7632/github'
talkai:
apikey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
devid: "123456"
trello:
apiKey: 'aaa'
apiHost: 'http://127.0.0.1:7632/trello'
# Load all services
require './loader'
require './servers/app'
requireDir './services'
| 177417 | # Initialize service
requireDir = require 'require-dir'
# Load mocked servers
require './servers/app'
loader = require '../src/loader'
loader.config =
apiHost: ""
cdnPrefix: ""
talkAccountApiUrl: "http://127.0.0.1:7632/account"
teambition:
clientSecret: 'abc'
host: 'http://127.0.0.1:7632/tb'
rss:
serviceUrl: 'http://127.0.0.1:7632/rss/worker'
github:
apiHost: 'http://127.0.0.1:7632/github'
talkai:
apikey: "<KEY>"
devid: "123456"
trello:
apiKey: '<KEY>'
apiHost: 'http://127.0.0.1:7632/trello'
# Load all services
require './loader'
require './servers/app'
requireDir './services'
| true | # Initialize service
requireDir = require 'require-dir'
# Load mocked servers
require './servers/app'
loader = require '../src/loader'
loader.config =
apiHost: ""
cdnPrefix: ""
talkAccountApiUrl: "http://127.0.0.1:7632/account"
teambition:
clientSecret: 'abc'
host: 'http://127.0.0.1:7632/tb'
rss:
serviceUrl: 'http://127.0.0.1:7632/rss/worker'
github:
apiHost: 'http://127.0.0.1:7632/github'
talkai:
apikey: "PI:KEY:<KEY>END_PI"
devid: "123456"
trello:
apiKey: 'PI:KEY:<KEY>END_PI'
apiHost: 'http://127.0.0.1:7632/trello'
# Load all services
require './loader'
require './servers/app'
requireDir './services'
|
[
{
"context": "le.exports.CURRENT_USER_KEY = CURRENT_USER_KEY = 'whoami'\nBEEN_HERE_BEFORE_KEY = 'beenHereBefore'\n\nmodule.",
"end": 179,
"score": 0.9934448599815369,
"start": 173,
"tag": "KEY",
"value": "whoami"
},
{
"context": "RRENT_USER_KEY = 'whoami'\nBEEN_HERE_BEFORE_KEY = 'bee... | app/lib/auth.coffee | vyz1194/codecombat | 0 | {backboneFailure, genericFailure} = require 'lib/errors'
User = require 'models/User'
storage = require 'lib/storage'
module.exports.CURRENT_USER_KEY = CURRENT_USER_KEY = 'whoami'
BEEN_HERE_BEFORE_KEY = 'beenHereBefore'
module.exports.createUser = (userObject, failure=backboneFailure) ->
user = new User(userObject)
user.save({}, {
error: failure,
success: (model) ->
storage.save(CURRENT_USER_KEY, model)
window.location.reload()
})
module.exports.loginUser = (userObject, failure=genericFailure) ->
jqxhr = $.post('/auth/login',
{
username:userObject.email,
password:userObject.password
},
(model) ->
storage.save(CURRENT_USER_KEY, model)
window.location.reload()
)
jqxhr.fail(failure)
module.exports.logoutUser = ->
FB?.logout?()
res = $.post('/auth/logout', {}, ->
storage.save(CURRENT_USER_KEY, null)
window.location.reload()
)
res.fail(genericFailure)
init = ->
# Load the user from local storage, and refresh it from the server.
# Also refresh and cache the gravatar info.
storedUser = storage.load(CURRENT_USER_KEY)
firstTime = not storedUser
module.exports.me = window.me = new User(storedUser)
me.url = -> '/auth/whoami'
me.fetch()
me.on 'sync', ->
me.url = -> "/db/user/#{me.id}"
trackFirstArrival() if firstTime
if me and not me.get('testGroupNumber')?
# Assign testGroupNumber to returning visitors; new ones in server/handlers/user
me.set 'testGroupNumber', Math.floor(Math.random() * 256)
me.save()
storage.save(CURRENT_USER_KEY, me.attributes)
me.loadGravatarProfile() if me.get('email')
me.on('sync', userSynced)
userSynced = (user) ->
Backbone.Mediator.publish('me:synced', {me:user})
storage.save(CURRENT_USER_KEY, user)
init()
onSetVolume = (e) ->
return if e.volume is me.get('volume')
me.set('volume', e.volume)
me.save()
Backbone.Mediator.subscribe('level-set-volume', onSetVolume, module.exports)
trackFirstArrival = ->
# will have to filter out users who log in with existing accounts separately
# but can at least not track logouts as first arrivals using local storage
beenHereBefore = storage.load(BEEN_HERE_BEFORE_KEY)
return if beenHereBefore
window.tracker?.trackEvent 'First Arrived'
storage.save(BEEN_HERE_BEFORE_KEY, true)
| 101843 | {backboneFailure, genericFailure} = require 'lib/errors'
User = require 'models/User'
storage = require 'lib/storage'
module.exports.CURRENT_USER_KEY = CURRENT_USER_KEY = '<KEY>'
BEEN_HERE_BEFORE_KEY = '<KEY>'
module.exports.createUser = (userObject, failure=backboneFailure) ->
user = new User(userObject)
user.save({}, {
error: failure,
success: (model) ->
storage.save(CURRENT_USER_KEY, model)
window.location.reload()
})
module.exports.loginUser = (userObject, failure=genericFailure) ->
jqxhr = $.post('/auth/login',
{
username:userObject.email,
password:<PASSWORD>
},
(model) ->
storage.save(CURRENT_USER_KEY, model)
window.location.reload()
)
jqxhr.fail(failure)
module.exports.logoutUser = ->
FB?.logout?()
res = $.post('/auth/logout', {}, ->
storage.save(CURRENT_USER_KEY, null)
window.location.reload()
)
res.fail(genericFailure)
init = ->
# Load the user from local storage, and refresh it from the server.
# Also refresh and cache the gravatar info.
storedUser = storage.load(CURRENT_USER_KEY)
firstTime = not storedUser
module.exports.me = window.me = new User(storedUser)
me.url = -> '/auth/whoami'
me.fetch()
me.on 'sync', ->
me.url = -> "/db/user/#{me.id}"
trackFirstArrival() if firstTime
if me and not me.get('testGroupNumber')?
# Assign testGroupNumber to returning visitors; new ones in server/handlers/user
me.set 'testGroupNumber', Math.floor(Math.random() * 256)
me.save()
storage.save(CURRENT_USER_KEY, me.attributes)
me.loadGravatarProfile() if me.get('email')
me.on('sync', userSynced)
userSynced = (user) ->
Backbone.Mediator.publish('me:synced', {me:user})
storage.save(CURRENT_USER_KEY, user)
init()
onSetVolume = (e) ->
return if e.volume is me.get('volume')
me.set('volume', e.volume)
me.save()
Backbone.Mediator.subscribe('level-set-volume', onSetVolume, module.exports)
trackFirstArrival = ->
# will have to filter out users who log in with existing accounts separately
# but can at least not track logouts as first arrivals using local storage
beenHereBefore = storage.load(BEEN_HERE_BEFORE_KEY)
return if beenHereBefore
window.tracker?.trackEvent 'First Arrived'
storage.save(BEEN_HERE_BEFORE_KEY, true)
| true | {backboneFailure, genericFailure} = require 'lib/errors'
User = require 'models/User'
storage = require 'lib/storage'
module.exports.CURRENT_USER_KEY = CURRENT_USER_KEY = 'PI:KEY:<KEY>END_PI'
BEEN_HERE_BEFORE_KEY = 'PI:KEY:<KEY>END_PI'
module.exports.createUser = (userObject, failure=backboneFailure) ->
user = new User(userObject)
user.save({}, {
error: failure,
success: (model) ->
storage.save(CURRENT_USER_KEY, model)
window.location.reload()
})
module.exports.loginUser = (userObject, failure=genericFailure) ->
jqxhr = $.post('/auth/login',
{
username:userObject.email,
password:PI:PASSWORD:<PASSWORD>END_PI
},
(model) ->
storage.save(CURRENT_USER_KEY, model)
window.location.reload()
)
jqxhr.fail(failure)
module.exports.logoutUser = ->
FB?.logout?()
res = $.post('/auth/logout', {}, ->
storage.save(CURRENT_USER_KEY, null)
window.location.reload()
)
res.fail(genericFailure)
init = ->
# Load the user from local storage, and refresh it from the server.
# Also refresh and cache the gravatar info.
storedUser = storage.load(CURRENT_USER_KEY)
firstTime = not storedUser
module.exports.me = window.me = new User(storedUser)
me.url = -> '/auth/whoami'
me.fetch()
me.on 'sync', ->
me.url = -> "/db/user/#{me.id}"
trackFirstArrival() if firstTime
if me and not me.get('testGroupNumber')?
# Assign testGroupNumber to returning visitors; new ones in server/handlers/user
me.set 'testGroupNumber', Math.floor(Math.random() * 256)
me.save()
storage.save(CURRENT_USER_KEY, me.attributes)
me.loadGravatarProfile() if me.get('email')
me.on('sync', userSynced)
userSynced = (user) ->
Backbone.Mediator.publish('me:synced', {me:user})
storage.save(CURRENT_USER_KEY, user)
init()
onSetVolume = (e) ->
return if e.volume is me.get('volume')
me.set('volume', e.volume)
me.save()
Backbone.Mediator.subscribe('level-set-volume', onSetVolume, module.exports)
trackFirstArrival = ->
# will have to filter out users who log in with existing accounts separately
# but can at least not track logouts as first arrivals using local storage
beenHereBefore = storage.load(BEEN_HERE_BEFORE_KEY)
return if beenHereBefore
window.tracker?.trackEvent 'First Arrived'
storage.save(BEEN_HERE_BEFORE_KEY, true)
|
[
{
"context": "eruvian.org'\n\t\t\tscope: 'read write'\n\t\t\tclientId: 'ca4bde63-9a81-4202-b869-69041f5d9217',\n\t\t\tredirectUri: 'http://dianw.github.io/yama-ad",
"end": 216,
"score": 0.8246803283691406,
"start": 180,
"tag": "KEY",
"value": "ca4bde63-9a81-4202-b869-69041f5d9217"
}
] | app/config/config.prod.coffee | dianw/yama-admin | 0 | 'use strict'
class OauthConfig extends Config
constructor: (oauthProvider) ->
oauthProvider.configure
site: 'http://yama2.meruvian.org'
scope: 'read write'
clientId: 'ca4bde63-9a81-4202-b869-69041f5d9217',
redirectUri: 'http://dianw.github.io/yama-admin'
class RestConfig extends Config
constructor: (RestangularProvider) ->
RestangularProvider.setBaseUrl 'http://yama2.meruvian.org/api'
| 204651 | 'use strict'
class OauthConfig extends Config
constructor: (oauthProvider) ->
oauthProvider.configure
site: 'http://yama2.meruvian.org'
scope: 'read write'
clientId: '<KEY>',
redirectUri: 'http://dianw.github.io/yama-admin'
class RestConfig extends Config
constructor: (RestangularProvider) ->
RestangularProvider.setBaseUrl 'http://yama2.meruvian.org/api'
| true | 'use strict'
class OauthConfig extends Config
constructor: (oauthProvider) ->
oauthProvider.configure
site: 'http://yama2.meruvian.org'
scope: 'read write'
clientId: 'PI:KEY:<KEY>END_PI',
redirectUri: 'http://dianw.github.io/yama-admin'
class RestConfig extends Config
constructor: (RestangularProvider) ->
RestangularProvider.setBaseUrl 'http://yama2.meruvian.org/api'
|
[
{
"context": "# @author xiaoshu.wb\n# @version 1.0.0\n# @see all of file class type\n# ",
"end": 20,
"score": 0.990637481212616,
"start": 10,
"tag": "USERNAME",
"value": "xiaoshu.wb"
},
{
"context": "0\n# @see all of file class type\n# @Time 2017-02-09 Cambridge Guildholl\n\n{SelectL... | lib/create-files-type-select.coffee | TheraPackages/create-files | 1 | # @author xiaoshu.wb
# @version 1.0.0
# @see all of file class type
# @Time 2017-02-09 Cambridge Guildholl
{SelectListView, $$,$} = require 'atom-space-pen-views'
path = require 'path'
module.exports =
CreateFileType: class CreateFileType extends SelectListView
createFileType = null
initialize: (createFileTypestate) ->
super
@setItems([{icon: 'icon text-icon medium-blue', title: 'blank',suffix:""},{icon: 'icon word-icon light-blue', title: 'WEEX(.we)',suffix:".we"},{icon: 'icon js-icon medium-yellow', title: 'Javascript(.js)',suffix:".js"},{icon: 'icon vue-icon light-green', title: 'Vue(.vue)',suffix:".vue"},{icon: 'icon lua-icon medium-red', title: 'Lua(.lua)',suffix:".lua"},{icon: 'icon css3-icon dark-blue', title: 'Css3(.css)',suffix:".css"},{icon: 'icon css3-icon medium-maroon', title: 'Less(.less)',suffix:".less"},{icon: 'icon npm-icon medium-red', title: 'Json(.json)',suffix:".json"},{icon: 'icon markdown-icon medium-blue', title: 'Markdown(.md)',suffix:".md"}])
@filterEditorView.hide()
@createFileType = createFileTypestate
viewForItem: (item) ->
$$ ->
@li =>
#<a class="list-group-item" href="#"><i class="fa fa-home fa-fw" aria-hidden="true"></i> Home</a>
@i class:item.icon
@span item.title
confirmed: (item) ->
@currentText = @createFileType.getText()
@currentText = path.join(@currentText, "untitled") if @currentText.endsWith(path.sep)
#首先判断是否为空
if(@currentText)
dirmap = path.parse(@currentText)
tempdir = path.format(
dir: dirmap.dir
name: dirmap.name
ext: item.suffix)
console.log(tempdir)
@createFileType.setText(tempdir)
@createFileType.focus()
cancelled: ->
console.log("This view was cancelled")
| 26111 | # @author xiaoshu.wb
# @version 1.0.0
# @see all of file class type
# @Time 2017-02-09 <NAME>
{SelectListView, $$,$} = require 'atom-space-pen-views'
path = require 'path'
module.exports =
CreateFileType: class CreateFileType extends SelectListView
createFileType = null
initialize: (createFileTypestate) ->
super
@setItems([{icon: 'icon text-icon medium-blue', title: 'blank',suffix:""},{icon: 'icon word-icon light-blue', title: 'WEEX(.we)',suffix:".we"},{icon: 'icon js-icon medium-yellow', title: 'Javascript(.js)',suffix:".js"},{icon: 'icon vue-icon light-green', title: 'Vue(.vue)',suffix:".vue"},{icon: 'icon lua-icon medium-red', title: 'Lua(.lua)',suffix:".lua"},{icon: 'icon css3-icon dark-blue', title: 'Css3(.css)',suffix:".css"},{icon: 'icon css3-icon medium-maroon', title: 'Less(.less)',suffix:".less"},{icon: 'icon npm-icon medium-red', title: 'Json(.json)',suffix:".json"},{icon: 'icon markdown-icon medium-blue', title: 'Markdown(.md)',suffix:".md"}])
@filterEditorView.hide()
@createFileType = createFileTypestate
viewForItem: (item) ->
$$ ->
@li =>
#<a class="list-group-item" href="#"><i class="fa fa-home fa-fw" aria-hidden="true"></i> Home</a>
@i class:item.icon
@span item.title
confirmed: (item) ->
@currentText = @createFileType.getText()
@currentText = path.join(@currentText, "untitled") if @currentText.endsWith(path.sep)
#首先判断是否为空
if(@currentText)
dirmap = path.parse(@currentText)
tempdir = path.format(
dir: dirmap.dir
name: dirmap.name
ext: item.suffix)
console.log(tempdir)
@createFileType.setText(tempdir)
@createFileType.focus()
cancelled: ->
console.log("This view was cancelled")
| true | # @author xiaoshu.wb
# @version 1.0.0
# @see all of file class type
# @Time 2017-02-09 PI:NAME:<NAME>END_PI
{SelectListView, $$,$} = require 'atom-space-pen-views'
path = require 'path'
module.exports =
CreateFileType: class CreateFileType extends SelectListView
createFileType = null
initialize: (createFileTypestate) ->
super
@setItems([{icon: 'icon text-icon medium-blue', title: 'blank',suffix:""},{icon: 'icon word-icon light-blue', title: 'WEEX(.we)',suffix:".we"},{icon: 'icon js-icon medium-yellow', title: 'Javascript(.js)',suffix:".js"},{icon: 'icon vue-icon light-green', title: 'Vue(.vue)',suffix:".vue"},{icon: 'icon lua-icon medium-red', title: 'Lua(.lua)',suffix:".lua"},{icon: 'icon css3-icon dark-blue', title: 'Css3(.css)',suffix:".css"},{icon: 'icon css3-icon medium-maroon', title: 'Less(.less)',suffix:".less"},{icon: 'icon npm-icon medium-red', title: 'Json(.json)',suffix:".json"},{icon: 'icon markdown-icon medium-blue', title: 'Markdown(.md)',suffix:".md"}])
@filterEditorView.hide()
@createFileType = createFileTypestate
viewForItem: (item) ->
$$ ->
@li =>
#<a class="list-group-item" href="#"><i class="fa fa-home fa-fw" aria-hidden="true"></i> Home</a>
@i class:item.icon
@span item.title
confirmed: (item) ->
@currentText = @createFileType.getText()
@currentText = path.join(@currentText, "untitled") if @currentText.endsWith(path.sep)
#首先判断是否为空
if(@currentText)
dirmap = path.parse(@currentText)
tempdir = path.format(
dir: dirmap.dir
name: dirmap.name
ext: item.suffix)
console.log(tempdir)
@createFileType.setText(tempdir)
@createFileType.focus()
cancelled: ->
console.log("This view was cancelled")
|
[
{
"context": "#############\n#\n#\tMoocita collections\n# Created by Markus on 26/10/2015.\n#\n################################",
"end": 99,
"score": 0.9996252059936523,
"start": 93,
"tag": "NAME",
"value": "Markus"
}
] | server/publications/permissions.coffee | MooqitaSFH/worklearn | 0 | #######################################################
#
# Moocita collections
# Created by Markus on 26/10/2015.
#
#######################################################
#######################################################
Meteor.publish "permissions", () ->
user_id = this.userId
if not user_id
throw new Meteor.Error "Not permitted."
if not has_role Permissions, WILDCARD, ADMIN
throw new Meteor.Error "Not permitted."
crs = Permissions.find()
log_publication crs, user_id, "permissions"
return crs
| 15301 | #######################################################
#
# Moocita collections
# Created by <NAME> on 26/10/2015.
#
#######################################################
#######################################################
Meteor.publish "permissions", () ->
user_id = this.userId
if not user_id
throw new Meteor.Error "Not permitted."
if not has_role Permissions, WILDCARD, ADMIN
throw new Meteor.Error "Not permitted."
crs = Permissions.find()
log_publication crs, user_id, "permissions"
return crs
| true | #######################################################
#
# Moocita collections
# Created by PI:NAME:<NAME>END_PI on 26/10/2015.
#
#######################################################
#######################################################
Meteor.publish "permissions", () ->
user_id = this.userId
if not user_id
throw new Meteor.Error "Not permitted."
if not has_role Permissions, WILDCARD, ADMIN
throw new Meteor.Error "Not permitted."
crs = Permissions.find()
log_publication crs, user_id, "permissions"
return crs
|
[
{
"context": "r-sharelatex\": \n\t\t\t\tlog:->\n\t\t\t\terr:->\n\t\t@token = \"12312321i\"\n\t\t@user_id = \"user_id_here\"\n\t\t@user = \n\t\t\temail ",
"end": 1178,
"score": 0.9981472492218018,
"start": 1169,
"tag": "PASSWORD",
"value": "12312321i"
},
{
"context": "oken = \"1231232... | test/unit/coffee/PasswordReset/PasswordResetHandlerTests.coffee | shyoshyo/web-sharelatex | 1 | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/PasswordReset/PasswordResetHandler"
expect = require("chai").expect
describe "PasswordResetHandler", ->
beforeEach ->
@settings =
siteUrl: "www.sharelatex.com"
@OneTimeTokenHandler =
getNewToken:sinon.stub()
getValueFromTokenAndExpire:sinon.stub()
@UserGetter =
getUserByMainEmail:sinon.stub()
getUser: sinon.stub()
@EmailHandler =
sendEmail:sinon.stub()
@AuthenticationManager =
setUserPassword:sinon.stub()
setUserPasswordInV1:sinon.stub()
setUserPasswordInV2:sinon.stub()
@V1Api =
request: sinon.stub()
@PasswordResetHandler = SandboxedModule.require modulePath, requires:
"../User/UserGetter": @UserGetter
"../Security/OneTimeTokenHandler": @OneTimeTokenHandler
"../Email/EmailHandler":@EmailHandler
"../Authentication/AuthenticationManager":@AuthenticationManager
"../V1/V1Api": @V1Api
"settings-sharelatex": @settings
"logger-sharelatex":
log:->
err:->
@token = "12312321i"
@user_id = "user_id_here"
@user =
email : @email = "bob@bob.com"
@password = "my great secret password"
@callback = sinon.stub()
describe "generateAndEmailResetToken", ->
describe "when in ShareLaTeX", ->
it "should check the user exists", (done)->
@UserGetter.getUserByMainEmail.callsArgWith(1)
@OneTimeTokenHandler.getNewToken.yields()
@PasswordResetHandler.generateAndEmailResetToken @user.email, (err, exists)=>
exists.should.equal false
done()
it "should send the email with the token", (done)->
@UserGetter.getUserByMainEmail.callsArgWith(1, null, @user)
@OneTimeTokenHandler.getNewToken.yields(null, @token)
@EmailHandler.sendEmail.callsArgWith(2)
@PasswordResetHandler.generateAndEmailResetToken @user.email, (err, exists)=>
@EmailHandler.sendEmail.called.should.equal true
exists.should.equal true
args = @EmailHandler.sendEmail.args[0]
args[0].should.equal "passwordResetRequested"
args[1].setNewPasswordUrl.should.equal "#{@settings.siteUrl}/user/password/set?passwordResetToken=#{@token}&email=#{encodeURIComponent(@user.email)}"
done()
it "should return exists = false for a holdingAccount", (done) ->
@user.holdingAccount = true
@UserGetter.getUserByMainEmail.callsArgWith(1, null, @user)
@OneTimeTokenHandler.getNewToken.yields()
@PasswordResetHandler.generateAndEmailResetToken @user.email, (err, exists)=>
exists.should.equal false
done()
describe "when in overleaf", ->
beforeEach ->
@settings.overleaf = true
describe "when the email exists", ->
beforeEach ->
@V1Api.request.yields(null, {}, { user_id: 42 })
@OneTimeTokenHandler.getNewToken.yields(null, @token)
@EmailHandler.sendEmail.yields()
@PasswordResetHandler.generateAndEmailResetToken @email, @callback
it 'should call the v1 api for the user', ->
@V1Api.request.calledWith({
url: "/api/v1/sharelatex/user_emails"
qs:
email: @email
expectedStatusCodes: [404]
}).should.equal true
it 'should set the password token data to the user id and email', ->
@OneTimeTokenHandler.getNewToken
.calledWith('password', {
v1_user_id: 42
})
.should.equal true
it 'should send an email with the token', ->
@EmailHandler.sendEmail.called.should.equal true
args = @EmailHandler.sendEmail.args[0]
args[0].should.equal "passwordResetRequested"
args[1].setNewPasswordUrl.should.equal "#{@settings.siteUrl}/user/password/set?passwordResetToken=#{@token}&email=#{encodeURIComponent(@user.email)}"
it 'should return exists == true', ->
@callback.calledWith(null, true).should.equal true
describe "when the email doesn't exist", ->
beforeEach ->
@V1Api.request = sinon.stub().yields(null, { statusCode: 404 }, {})
@PasswordResetHandler.generateAndEmailResetToken @email, @callback
it 'should not set the password token data', ->
@OneTimeTokenHandler.getNewToken
.called.should.equal false
it 'should send an email with the token', ->
@EmailHandler.sendEmail.called.should.equal false
it 'should return exists == false', ->
@callback.calledWith(null, false).should.equal true
describe "setNewUserPassword", ->
describe "when no data is found", ->
beforeEach ->
@OneTimeTokenHandler.getValueFromTokenAndExpire.yields(null, null)
@PasswordResetHandler.setNewUserPassword @token, @password, @callback
it 'should return exists == false', ->
@callback.calledWith(null, false).should.equal true
describe 'when the data is an old style user_id', ->
beforeEach ->
@AuthenticationManager.setUserPassword.yields(null, true, @user_id)
@OneTimeTokenHandler.getValueFromTokenAndExpire.yields(null, @user_id)
@PasswordResetHandler.setNewUserPassword @token, @password, @callback
it 'should call setUserPasswordInV2', ->
@AuthenticationManager.setUserPassword
.calledWith(@user_id, @password)
.should.equal true
it 'should reset == true and the user_id', ->
@callback.calledWith(null, true, @user_id).should.equal true
describe 'when the data is a new style user_id', ->
beforeEach ->
@AuthenticationManager.setUserPassword.yields(null, true, @user_id)
@OneTimeTokenHandler.getValueFromTokenAndExpire.yields(null, {@user_id})
@PasswordResetHandler.setNewUserPassword @token, @password, @callback
it 'should call setUserPasswordInV2', ->
@AuthenticationManager.setUserPassword
.calledWith(@user_id, @password)
.should.equal true
it 'should reset == true and the user_id', ->
@callback.calledWith(null, true, @user_id).should.equal true
describe 'when the data is v1 id', ->
beforeEach ->
@v1_user_id = 2345
@AuthenticationManager.setUserPasswordInV1.yields(null, true)
@UserGetter.getUser.withArgs({'overleaf.id': @v1_user_id}).yields(null, { _id: @user_id })
@OneTimeTokenHandler.getValueFromTokenAndExpire.yields(null, {@v1_user_id})
@PasswordResetHandler.setNewUserPassword @token, @password, @callback
it 'should call setUserPasswordInV1', ->
@AuthenticationManager.setUserPasswordInV1
.calledWith(@v1_user_id, @password)
.should.equal true
it 'should look up the user by v1 id for the v2 user id', ->
@UserGetter.getUser
.calledWith({'overleaf.id': @v1_user_id})
.should.equal true
it 'should reset == true and the user_id', ->
@callback.calledWith(null, true, @user_id).should.equal true
| 182310 | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/PasswordReset/PasswordResetHandler"
expect = require("chai").expect
describe "PasswordResetHandler", ->
beforeEach ->
@settings =
siteUrl: "www.sharelatex.com"
@OneTimeTokenHandler =
getNewToken:sinon.stub()
getValueFromTokenAndExpire:sinon.stub()
@UserGetter =
getUserByMainEmail:sinon.stub()
getUser: sinon.stub()
@EmailHandler =
sendEmail:sinon.stub()
@AuthenticationManager =
setUserPassword:sinon.stub()
setUserPasswordInV1:sinon.stub()
setUserPasswordInV2:sinon.stub()
@V1Api =
request: sinon.stub()
@PasswordResetHandler = SandboxedModule.require modulePath, requires:
"../User/UserGetter": @UserGetter
"../Security/OneTimeTokenHandler": @OneTimeTokenHandler
"../Email/EmailHandler":@EmailHandler
"../Authentication/AuthenticationManager":@AuthenticationManager
"../V1/V1Api": @V1Api
"settings-sharelatex": @settings
"logger-sharelatex":
log:->
err:->
@token = "<PASSWORD>"
@user_id = "user_id_here"
@user =
email : @email = "<EMAIL>"
@password = "<PASSWORD>"
@callback = sinon.stub()
describe "generateAndEmailResetToken", ->
describe "when in ShareLaTeX", ->
it "should check the user exists", (done)->
@UserGetter.getUserByMainEmail.callsArgWith(1)
@OneTimeTokenHandler.getNewToken.yields()
@PasswordResetHandler.generateAndEmailResetToken @user.email, (err, exists)=>
exists.should.equal false
done()
it "should send the email with the token", (done)->
@UserGetter.getUserByMainEmail.callsArgWith(1, null, @user)
@OneTimeTokenHandler.getNewToken.yields(null, @token)
@EmailHandler.sendEmail.callsArgWith(2)
@PasswordResetHandler.generateAndEmailResetToken @user.email, (err, exists)=>
@EmailHandler.sendEmail.called.should.equal true
exists.should.equal true
args = @EmailHandler.sendEmail.args[0]
args[0].should.equal "passwordResetRequested"
args[1].setNewPasswordUrl.should.equal "#{@settings.siteUrl}/user/password/set?passwordResetToken=#{@token}&email=#{encodeURIComponent(@user.email)}"
done()
it "should return exists = false for a holdingAccount", (done) ->
@user.holdingAccount = true
@UserGetter.getUserByMainEmail.callsArgWith(1, null, @user)
@OneTimeTokenHandler.getNewToken.yields()
@PasswordResetHandler.generateAndEmailResetToken @user.email, (err, exists)=>
exists.should.equal false
done()
describe "when in overleaf", ->
beforeEach ->
@settings.overleaf = true
describe "when the email exists", ->
beforeEach ->
@V1Api.request.yields(null, {}, { user_id: 42 })
@OneTimeTokenHandler.getNewToken.yields(null, @token)
@EmailHandler.sendEmail.yields()
@PasswordResetHandler.generateAndEmailResetToken @email, @callback
it 'should call the v1 api for the user', ->
@V1Api.request.calledWith({
url: "/api/v1/sharelatex/user_emails"
qs:
email: @email
expectedStatusCodes: [404]
}).should.equal true
it 'should set the password token data to the user id and email', ->
@OneTimeTokenHandler.getNewToken
.calledWith('password', {
v1_user_id: 42
})
.should.equal true
it 'should send an email with the token', ->
@EmailHandler.sendEmail.called.should.equal true
args = @EmailHandler.sendEmail.args[0]
args[0].should.equal "passwordResetRequested"
args[1].setNewPasswordUrl.should.equal "#{@settings.siteUrl}/user/password/set?passwordResetToken=#{@token}&email=#{encodeURIComponent(@user.email)}"
it 'should return exists == true', ->
@callback.calledWith(null, true).should.equal true
describe "when the email doesn't exist", ->
beforeEach ->
@V1Api.request = sinon.stub().yields(null, { statusCode: 404 }, {})
@PasswordResetHandler.generateAndEmailResetToken @email, @callback
it 'should not set the password token data', ->
@OneTimeTokenHandler.getNewToken
.called.should.equal false
it 'should send an email with the token', ->
@EmailHandler.sendEmail.called.should.equal false
it 'should return exists == false', ->
@callback.calledWith(null, false).should.equal true
describe "setNewUserPassword", ->
describe "when no data is found", ->
beforeEach ->
@OneTimeTokenHandler.getValueFromTokenAndExpire.yields(null, null)
@PasswordResetHandler.setNewUserPassword @token, @password, @callback
it 'should return exists == false', ->
@callback.calledWith(null, false).should.equal true
describe 'when the data is an old style user_id', ->
beforeEach ->
@AuthenticationManager.setUserPassword.yields(null, true, @user_id)
@OneTimeTokenHandler.getValueFromTokenAndExpire.yields(null, @user_id)
@PasswordResetHandler.setNewUserPassword @token, @password, @callback
it 'should call setUserPasswordInV2', ->
@AuthenticationManager.setUserPassword
.calledWith(@user_id, @password)
.should.equal true
it 'should reset == true and the user_id', ->
@callback.calledWith(null, true, @user_id).should.equal true
describe 'when the data is a new style user_id', ->
beforeEach ->
@AuthenticationManager.setUserPassword.yields(null, true, @user_id)
@OneTimeTokenHandler.getValueFromTokenAndExpire.yields(null, {@user_id})
@PasswordResetHandler.setNewUserPassword @token, @password, @callback
it 'should call setUserPasswordInV2', ->
@AuthenticationManager.setUserPassword
.calledWith(@user_id, @password)
.should.equal true
it 'should reset == true and the user_id', ->
@callback.calledWith(null, true, @user_id).should.equal true
describe 'when the data is v1 id', ->
beforeEach ->
@v1_user_id = 2345
@AuthenticationManager.setUserPasswordInV1.yields(null, true)
@UserGetter.getUser.withArgs({'overleaf.id': @v1_user_id}).yields(null, { _id: @user_id })
@OneTimeTokenHandler.getValueFromTokenAndExpire.yields(null, {@v1_user_id})
@PasswordResetHandler.setNewUserPassword @token, @password, @callback
it 'should call setUserPasswordInV1', ->
@AuthenticationManager.setUserPasswordInV1
.calledWith(@v1_user_id, @password)
.should.equal true
it 'should look up the user by v1 id for the v2 user id', ->
@UserGetter.getUser
.calledWith({'overleaf.id': @v1_user_id})
.should.equal true
it 'should reset == true and the user_id', ->
@callback.calledWith(null, true, @user_id).should.equal true
| true | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/PasswordReset/PasswordResetHandler"
expect = require("chai").expect
describe "PasswordResetHandler", ->
beforeEach ->
@settings =
siteUrl: "www.sharelatex.com"
@OneTimeTokenHandler =
getNewToken:sinon.stub()
getValueFromTokenAndExpire:sinon.stub()
@UserGetter =
getUserByMainEmail:sinon.stub()
getUser: sinon.stub()
@EmailHandler =
sendEmail:sinon.stub()
@AuthenticationManager =
setUserPassword:sinon.stub()
setUserPasswordInV1:sinon.stub()
setUserPasswordInV2:sinon.stub()
@V1Api =
request: sinon.stub()
@PasswordResetHandler = SandboxedModule.require modulePath, requires:
"../User/UserGetter": @UserGetter
"../Security/OneTimeTokenHandler": @OneTimeTokenHandler
"../Email/EmailHandler":@EmailHandler
"../Authentication/AuthenticationManager":@AuthenticationManager
"../V1/V1Api": @V1Api
"settings-sharelatex": @settings
"logger-sharelatex":
log:->
err:->
@token = "PI:PASSWORD:<PASSWORD>END_PI"
@user_id = "user_id_here"
@user =
email : @email = "PI:EMAIL:<EMAIL>END_PI"
@password = "PI:PASSWORD:<PASSWORD>END_PI"
@callback = sinon.stub()
describe "generateAndEmailResetToken", ->
describe "when in ShareLaTeX", ->
it "should check the user exists", (done)->
@UserGetter.getUserByMainEmail.callsArgWith(1)
@OneTimeTokenHandler.getNewToken.yields()
@PasswordResetHandler.generateAndEmailResetToken @user.email, (err, exists)=>
exists.should.equal false
done()
it "should send the email with the token", (done)->
@UserGetter.getUserByMainEmail.callsArgWith(1, null, @user)
@OneTimeTokenHandler.getNewToken.yields(null, @token)
@EmailHandler.sendEmail.callsArgWith(2)
@PasswordResetHandler.generateAndEmailResetToken @user.email, (err, exists)=>
@EmailHandler.sendEmail.called.should.equal true
exists.should.equal true
args = @EmailHandler.sendEmail.args[0]
args[0].should.equal "passwordResetRequested"
args[1].setNewPasswordUrl.should.equal "#{@settings.siteUrl}/user/password/set?passwordResetToken=#{@token}&email=#{encodeURIComponent(@user.email)}"
done()
it "should return exists = false for a holdingAccount", (done) ->
@user.holdingAccount = true
@UserGetter.getUserByMainEmail.callsArgWith(1, null, @user)
@OneTimeTokenHandler.getNewToken.yields()
@PasswordResetHandler.generateAndEmailResetToken @user.email, (err, exists)=>
exists.should.equal false
done()
describe "when in overleaf", ->
beforeEach ->
@settings.overleaf = true
describe "when the email exists", ->
beforeEach ->
@V1Api.request.yields(null, {}, { user_id: 42 })
@OneTimeTokenHandler.getNewToken.yields(null, @token)
@EmailHandler.sendEmail.yields()
@PasswordResetHandler.generateAndEmailResetToken @email, @callback
it 'should call the v1 api for the user', ->
@V1Api.request.calledWith({
url: "/api/v1/sharelatex/user_emails"
qs:
email: @email
expectedStatusCodes: [404]
}).should.equal true
it 'should set the password token data to the user id and email', ->
@OneTimeTokenHandler.getNewToken
.calledWith('password', {
v1_user_id: 42
})
.should.equal true
it 'should send an email with the token', ->
@EmailHandler.sendEmail.called.should.equal true
args = @EmailHandler.sendEmail.args[0]
args[0].should.equal "passwordResetRequested"
args[1].setNewPasswordUrl.should.equal "#{@settings.siteUrl}/user/password/set?passwordResetToken=#{@token}&email=#{encodeURIComponent(@user.email)}"
it 'should return exists == true', ->
@callback.calledWith(null, true).should.equal true
describe "when the email doesn't exist", ->
beforeEach ->
@V1Api.request = sinon.stub().yields(null, { statusCode: 404 }, {})
@PasswordResetHandler.generateAndEmailResetToken @email, @callback
it 'should not set the password token data', ->
@OneTimeTokenHandler.getNewToken
.called.should.equal false
it 'should send an email with the token', ->
@EmailHandler.sendEmail.called.should.equal false
it 'should return exists == false', ->
@callback.calledWith(null, false).should.equal true
describe "setNewUserPassword", ->
describe "when no data is found", ->
beforeEach ->
@OneTimeTokenHandler.getValueFromTokenAndExpire.yields(null, null)
@PasswordResetHandler.setNewUserPassword @token, @password, @callback
it 'should return exists == false', ->
@callback.calledWith(null, false).should.equal true
describe 'when the data is an old style user_id', ->
beforeEach ->
@AuthenticationManager.setUserPassword.yields(null, true, @user_id)
@OneTimeTokenHandler.getValueFromTokenAndExpire.yields(null, @user_id)
@PasswordResetHandler.setNewUserPassword @token, @password, @callback
it 'should call setUserPasswordInV2', ->
@AuthenticationManager.setUserPassword
.calledWith(@user_id, @password)
.should.equal true
it 'should reset == true and the user_id', ->
@callback.calledWith(null, true, @user_id).should.equal true
describe 'when the data is a new style user_id', ->
beforeEach ->
@AuthenticationManager.setUserPassword.yields(null, true, @user_id)
@OneTimeTokenHandler.getValueFromTokenAndExpire.yields(null, {@user_id})
@PasswordResetHandler.setNewUserPassword @token, @password, @callback
it 'should call setUserPasswordInV2', ->
@AuthenticationManager.setUserPassword
.calledWith(@user_id, @password)
.should.equal true
it 'should reset == true and the user_id', ->
@callback.calledWith(null, true, @user_id).should.equal true
describe 'when the data is v1 id', ->
beforeEach ->
@v1_user_id = 2345
@AuthenticationManager.setUserPasswordInV1.yields(null, true)
@UserGetter.getUser.withArgs({'overleaf.id': @v1_user_id}).yields(null, { _id: @user_id })
@OneTimeTokenHandler.getValueFromTokenAndExpire.yields(null, {@v1_user_id})
@PasswordResetHandler.setNewUserPassword @token, @password, @callback
it 'should call setUserPasswordInV1', ->
@AuthenticationManager.setUserPasswordInV1
.calledWith(@v1_user_id, @password)
.should.equal true
it 'should look up the user by v1 id for the v2 user id', ->
@UserGetter.getUser
.calledWith({'overleaf.id': @v1_user_id})
.should.equal true
it 'should reset == true and the user_id', ->
@callback.calledWith(null, true, @user_id).should.equal true
|
[
{
"context": "# POST /hubot/chatops/test/:room\n#\n# Author:\n# Jamesford\n#\n\nenvar = process.env.HUBOT_CHATOPS_TEST\n_ ",
"end": 499,
"score": 0.6924542784690857,
"start": 495,
"tag": "NAME",
"value": "Jame"
},
{
"context": "OST /hubot/chatops/test/:room\n#\n# Author:\n# Jam... | scripts/custom-test.coffee | Jamesford/hubot-chatops-custom-test | 1 | # Description:
# Test the chato.ps custom plugin feature
#
# Dependencies:
# "underscore": "1.7.0"
#
# Configuration:
# HUBOT_CHATOPS_TEST
#
# Commands:
# test bot hearing - Tests `robot.hear` method
# hubot test response - Tests `robot.respond` method
# hubot test http - Tests `robot.http()` method
# hubot test envar - Tests environment variable was set
# hubot test dependencies - Tests dependencies are available
#
# URLS:
# POST /hubot/chatops/test/:room
#
# Author:
# Jamesford
#
envar = process.env.HUBOT_CHATOPS_TEST
_ = require 'underscore'
module.exports = (robot) ->
robot.hear /test bot hearing/i, (msg) ->
msg.send 'I heard "test bot hearing" being said'
robot.respond /test response/i, (msg) ->
msg.send 'Responding to "testresponse"!'
robot.respond /test http/i, (msg) ->
robot.http('http://www.randomtext.me/api/gibberish/p-1/5-10')
.get() (err, res, body) ->
if err
msg.send 'Encountered error:', err
else
text = JSON.parse(body).text_out
text = text.replace('<p>', '').replace('</p>', '').trim()
msg.send "Success: #{text}"
robot.enter (msg) ->
msg.send 'Hello!'
robot.leave (msg) ->
msg.send 'Aww they left!'
robot.respond /test envar/i, (msg) ->
unless envar?
msg.send "Missing HUBOT_CHATOPS_TEST in environment: please set and try again"
return
msg.send "HUBOT_CHATOPS_TEST: #{envar}"
robot.respond /test dependencies/i, (msg) ->
range = _.range(10)
msg.send "_.range(10): #{range}"
robot.router.post '/hubot/chatops/test/:room', (req, res) ->
msg = { room: req.params.room }
if req.body.message
robot.send msg, req.body.message
res.send(200)
else
robot.send user, "I received a message for you, but there was an error :("
res.send(400) | 89682 | # Description:
# Test the chato.ps custom plugin feature
#
# Dependencies:
# "underscore": "1.7.0"
#
# Configuration:
# HUBOT_CHATOPS_TEST
#
# Commands:
# test bot hearing - Tests `robot.hear` method
# hubot test response - Tests `robot.respond` method
# hubot test http - Tests `robot.http()` method
# hubot test envar - Tests environment variable was set
# hubot test dependencies - Tests dependencies are available
#
# URLS:
# POST /hubot/chatops/test/:room
#
# Author:
# <NAME>sf<NAME>
#
envar = process.env.HUBOT_CHATOPS_TEST
_ = require 'underscore'
module.exports = (robot) ->
robot.hear /test bot hearing/i, (msg) ->
msg.send 'I heard "test bot hearing" being said'
robot.respond /test response/i, (msg) ->
msg.send 'Responding to "testresponse"!'
robot.respond /test http/i, (msg) ->
robot.http('http://www.randomtext.me/api/gibberish/p-1/5-10')
.get() (err, res, body) ->
if err
msg.send 'Encountered error:', err
else
text = JSON.parse(body).text_out
text = text.replace('<p>', '').replace('</p>', '').trim()
msg.send "Success: #{text}"
robot.enter (msg) ->
msg.send 'Hello!'
robot.leave (msg) ->
msg.send 'Aww they left!'
robot.respond /test envar/i, (msg) ->
unless envar?
msg.send "Missing HUBOT_CHATOPS_TEST in environment: please set and try again"
return
msg.send "HUBOT_CHATOPS_TEST: #{envar}"
robot.respond /test dependencies/i, (msg) ->
range = _.range(10)
msg.send "_.range(10): #{range}"
robot.router.post '/hubot/chatops/test/:room', (req, res) ->
msg = { room: req.params.room }
if req.body.message
robot.send msg, req.body.message
res.send(200)
else
robot.send user, "I received a message for you, but there was an error :("
res.send(400) | true | # Description:
# Test the chato.ps custom plugin feature
#
# Dependencies:
# "underscore": "1.7.0"
#
# Configuration:
# HUBOT_CHATOPS_TEST
#
# Commands:
# test bot hearing - Tests `robot.hear` method
# hubot test response - Tests `robot.respond` method
# hubot test http - Tests `robot.http()` method
# hubot test envar - Tests environment variable was set
# hubot test dependencies - Tests dependencies are available
#
# URLS:
# POST /hubot/chatops/test/:room
#
# Author:
# PI:NAME:<NAME>END_PIsfPI:NAME:<NAME>END_PI
#
envar = process.env.HUBOT_CHATOPS_TEST
_ = require 'underscore'
module.exports = (robot) ->
robot.hear /test bot hearing/i, (msg) ->
msg.send 'I heard "test bot hearing" being said'
robot.respond /test response/i, (msg) ->
msg.send 'Responding to "testresponse"!'
robot.respond /test http/i, (msg) ->
robot.http('http://www.randomtext.me/api/gibberish/p-1/5-10')
.get() (err, res, body) ->
if err
msg.send 'Encountered error:', err
else
text = JSON.parse(body).text_out
text = text.replace('<p>', '').replace('</p>', '').trim()
msg.send "Success: #{text}"
robot.enter (msg) ->
msg.send 'Hello!'
robot.leave (msg) ->
msg.send 'Aww they left!'
robot.respond /test envar/i, (msg) ->
unless envar?
msg.send "Missing HUBOT_CHATOPS_TEST in environment: please set and try again"
return
msg.send "HUBOT_CHATOPS_TEST: #{envar}"
robot.respond /test dependencies/i, (msg) ->
range = _.range(10)
msg.send "_.range(10): #{range}"
robot.router.post '/hubot/chatops/test/:room', (req, res) ->
msg = { room: req.params.room }
if req.body.message
robot.send msg, req.body.message
res.send(200)
else
robot.send user, "I received a message for you, but there was an error :("
res.send(400) |
[
{
"context": "fy_synthtetic\n # of a synthetic attribute (Jyrki Niemi 2015-02-24)\n # TODO (Jyrki Niemi): This co",
"end": 1016,
"score": 0.9996768832206726,
"start": 1005,
"tag": "NAME",
"value": "Jyrki Niemi"
},
{
"context": "ttribute (Jyrki Niemi 2015-02-24)\n ... | app/scripts/widgets.coffee | CSCfi/Kielipankki-korp-frontend | 0 | Sidebar =
_init: () ->
updateContent: (sentenceData, wordData, corpus, tokens) ->
@element.html ("""<div id="selected_sentence" />
<div id="selected_word" />
<div id="deptree_link" />
<div id="selected_links" />""")
corpusObj = settings.corpora[corpus]
formattedCorpusInfo =
if settings?.corpusExtraInfo
then util.formatCorpusExtraInfo(
corpusObj,
info_items: settings.corpusExtraInfo?.sidebar
item_paragraphs: true)
else ""
if formattedCorpusInfo
formattedCorpusInfo = "<br/>" + formattedCorpusInfo
$("<div />").html("<h4 rel='localize[corpus]'></h4> <p>#{corpusObj.title}</p><div id='sidebar-corpus-info'>#{formattedCorpusInfo}</div>").prependTo "#selected_sentence"
# All token data, to be passed to the function stringify_synthtetic
# of a synthetic attribute (Jyrki Niemi 2015-02-24)
# TODO (Jyrki Niemi): This could now be removed as Språkbanken's code
# also passes tokens to @renderCorpusContent and @renderCustomContent
token_data =
pos_attrs : wordData
struct_attrs : sentenceData
tokens : tokens
unless $.isEmptyObject(corpusObj.attributes)
$("#selected_word").append $("<h4>").localeKey("word_attr")
posData = @renderCorpusContent("pos", wordData, sentenceData,
corpusObj.attributes, tokens,
corpusObj.synthetic_attr_names.attributes, token_data)
# posData.appendTo "#selected_word"
$("#selected_word").append posData
unless $.isEmptyObject(corpusObj.struct_attributes)
$("#selected_sentence").append $("<h4>").localeKey("sentence_attr")
@renderCorpusContent("struct", wordData, sentenceData,
corpusObj.struct_attributes, tokens,
corpusObj.synthetic_attr_names.struct_attributes, token_data)
.appendTo "#selected_sentence"
unless $.isEmptyObject(corpusObj.custom_attributes)
[word, sentence] = @renderCustomContent(wordData, sentenceData, corpusObj.custom_attributes, tokens)
word.appendTo "#selected_word"
sentence.appendTo "#selected_sentence"
# Links in a separate link section
unless $.isEmptyObject(corpusObj.link_attributes)
@renderCorpusContent("link", wordData, sentenceData,
corpusObj.link_attributes, tokens,
corpusObj.synthetic_attr_names.link_attributes, token_data)
.appendTo "#selected_links"
@element.localize()
@applyEllipse()
if corpusObj.attributes.deprel
@renderGraph(tokens)
renderGraph : (tokens) ->
outerW = $(window).width() - 80
$("<span class='link show_deptree'>Visa träd</button>").localeKey("show_deptree").click( ->
info = $("<span class='info' />")
iframe = $('<iframe src="lib/deptrees/deptrees.html"></iframe>').css("width", outerW - 40).load ->
wnd = this.contentWindow
tokens = tokens
wnd.draw_deptree.call wnd, tokens, (msg) ->
[type, val] = _.head _.pairs msg
info.empty().append $("<span>").localeKey(type), $("<span>: </span>"), $("<span>").localeKey("#{type}_#{val}")
$("#deptree_popup").empty().append(info, iframe).dialog(
height : 300
width : outerW
).parent().find(".ui-dialog-title").localeKey("dep_tree")
).appendTo("#deptree_link")
renderCorpusContent: (type, wordData, sentenceData, corpus_attrs, tokens,
synthetic_attr_names, token_data) ->
if type == "struct" or type == "link"
pairs = _.pairs(sentenceData)
else if type == "pos"
pairs = _.pairs(wordData)
for item in (wordData._struct or [])
key = item.substring(0, item.indexOf(" "))
val = item.substring(item.indexOf(" ") + 1)
if key of corpus_attrs
pairs.push([key, val])
pairs = _.filter pairs, ([key, val]) -> corpus_attrs[key]
pairs.sort ([a], [b]) ->
ord1 = corpus_attrs[a].order
ord2 = corpus_attrs[b].order
# first three cases to handle ord1 or ord2 being undefined
if ord1 == ord2
return 0
if not ord1
return 1
if not ord2
return -1
else
return ord2 - ord1
items = []
for [key, value] in pairs
items = items.concat (@renderItem key, value, corpus_attrs[key], wordData, sentenceData, token_data, tokens).get?(0)
items = _.compact items
# Append possible synthetic attributes (Jyrki Niemi 2015-02-24)
# TODO: Support the order property; it should be possible to
# interleave normal and synthetic attributes.
if synthetic_attr_names.length
synthetic = for key in synthetic_attr_names
@renderItem key, null, corpus_attrs[key], wordData, sentenceData, tokens, token_data
items = items.concat(synthetic)
return $(items)
renderCustomContent: (wordData, sentenceData, corpus_attrs, tokens) ->
struct_items = []
pos_items = []
for key, attrs of corpus_attrs
output = @renderItem(key, null, attrs, wordData, sentenceData, tokens)
if attrs.customType == "struct"
struct_items.push output
else if attrs.customType == "pos"
pos_items.push output
return [$(pos_items), $(struct_items)]
renderItem: (key, value, attrs, wordData, sentenceData, tokens, token_data) ->
# Convert &, < and > to HTML character entities (for
# stringifying attribute values for which stringify is not
# defined). (Jyrki Niemi 2016-12-15)
encodeHtmlEntities = (s) ->
s.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
# Map a value via the dataset property if it exists and is not
# an array, that it, is a mapping (object with properties).
# FIXME: This does not yield a correct result if the dataset
# keys are regular expressions as they may be. Should we
# perhaps have separate dataset mappings for the query,
# allowing regexps, and for stringifying values, not allowing
# regexps? (Jyrki Niemi 2017-05-16)
mapViaDataset = (value) ->
if attrs.dataset? and not _.isArray(attrs.dataset)
return attrs.dataset[value] or value
else
return value
if attrs.displayType in ["hidden", "date_interval"] or
attrs.displayOnly == "search" or attrs.hideSidebar
return ""
if attrs.type == "url" and attrs?.url_opts?.hide_url
# If url_opts.hide_url, hide the url and show the localized
# label as the link, or nothing, if the value is empty.
# Note that this does not work for synthetic attributes,
# as their value is null at this point, so they are
# handled further below.
if value == ""
return ""
output = $("<p></p>")
else if attrs.label
output = $("<p><span rel='localize[#{attrs.label}]'></span>: </p>")
else
output = $("<p></p>")
if attrs.renderItem
return output.append(attrs.renderItem key, value, attrs, wordData, sentenceData, tokens)
output.data("attrs", attrs)
# Convert an undefined value to the empty string (Jyrki Niemi
# 2015-08-26)
value ?= ""
if (value == "|" or value == "") and
not (attrs.translationKey? and attrs.dataset?[value]?) and
not attrs.stringify_synthetic?
# The original version only appended to the output here
# but did not return yet. Would we need further processing
# for empty values in some cases? (Jyrki Niemi 2015-08-26)
output.append "<i rel='localize[empty]' style='color : grey'>${util.getLocaleString('empty')}</i>"
return output
# Transform the value if a transformation function has been
# specified. (Jyrki Niemi 2015-10-26)
if attrs.transform?
value = attrs.transform(value)
if attrs.type == "set" and attrs.taginfo_url
# For a set-valued attribute, add the taginfo link right
# after the attribute label (Jyrki Niemi 2016-02-10)
output.append """<a href='#{attrs.taginfo_url}' target='_blank'>
<span id='sidbar_info' class='ui-icon ui-icon-info'></span>
</a>
"""
if attrs.type == "set" and attrs.display?.expandList
valueArray = _.filter(value?.split("|") or [], Boolean)
attrSettings = attrs.display.expandList
if attrs.ranked
valueArray = _.map valueArray, (value) -> val = value.split(":"); [val[0], val[val.length - 1]]
lis = []
for [value, prob], outerIdx in valueArray
li = $("<li></li>")
subValues = if attrSettings.splitValue then attrSettings.splitValue value else [value]
for subValue, idx in subValues
val = (attrs.stringify or attrSettings.stringify or _.identity)(subValue)
inner = $("<span>" + val + "</span>");
if attrs.internalSearch and (attrSettings.linkAllValues or outerIdx is 0)
inner.data("key", subValue)
inner.addClass("link").click ->
searchKey = attrSettings.searchKey or key
cqpVal = $(this).data("key")
cqpExpr = if attrSettings.internalSearch then attrSettings.internalSearch searchKey, cqpVal else "[#{searchKey} contains '#{cqpVal}']"
search({"search": "cqp|" + cqpExpr})
if attrs.externalSearch
address = _.template(attrs.externalSearch, {val : subValue})
karpLink = $("<a href='#{address}' class='external_link' target='_blank' style='margin-top: -6px'></a>")
li.append inner
if attrSettings.joinValues and idx isnt subValues.length - 1
li.append attrSettings.joinValues
li.append "<span class='prob'> (" + prob + ")</span>"
if karpLink
li.append karpLink
lis.push li
else
lis = []
for value in valueArray
li = $("<li></li>")
li.append value
lis.push li
if lis.length == 0
ul = $('<i rel="localize[empty]" style="color : grey"></i>')
else
ul = $("<ul class='hide-prob' style='list-style:initial'>")
ul.append lis
if lis.length isnt 1
_.map lis, (li, idx) -> if idx != 0 then li.css('display', 'none')
showAll = $("<span class='link' rel='localize[complemgram_show_all]'></span><span> (" + (lis.length - 1) + ")</span>")
ul.append showAll
showOne = $("<span class='link' rel='localize[complemgram_show_one]'></span>")
showOne.css "display", "none"
ul.append showOne
showAll.click () ->
showAll.css "display", "none"
showOne.css "display", "inline"
ul.removeClass "hide-prob"
_.map lis, (li) ->
li.css "display", "list-item"
showOne.click () ->
showAll.css "display", "inline"
showOne.css "display", "none"
ul.addClass "hide-prob"
_.map lis, (li, i) ->
if i != 0
li.css "display", "none"
output.append ul
return output
else if attrs.type == "set"
pattern = attrs.pattern or '<span data-key="<%= key %>"><%= val %></span>'
ul = $("<ul>")
getStringVal = (str) ->
return _.reduce(_.invoke(_.invoke(str, "charCodeAt", 0), "toString"), (a,b) -> a + b);
valueArray = _.filter(value?.split("|") or [], Boolean)
if key == "variants"
# TODO: this doesn't sort quite as expected
valueArray.sort (a, b) ->
splita = util.splitLemgram(a);
splitb = util.splitLemgram(b);
strvala = getStringVal(splita.form) + splita.index + getStringVal(splita.pos);
strvalb = getStringVal(splitb.form) + splitb.index + getStringVal(splitb.pos);
return parseInt(strvala) - parseInt(strvalb);
itr = if _.isArray(valueArray) then valueArray else _.values(valueArray)
lis = for x in itr when x.length
val = (attrs.stringify or encodeHtmlEntities)(x)
inner = $(_.template(pattern, {key : x, val : val}))
if attrs.translationKey?
prefix = attrs.translationKey or ""
val = mapViaDataset(val)
inner.localeKey(prefix + val)
if attrs.internalSearch
inner.addClass("link").click ->
cqpVal = $(this).data("key")
search({"search": "cqp|[#{key} contains '#{cqpVal}']"})
li = $("<li></li>").data("key", x).append inner
if attrs.externalSearch
address = _.template(attrs.externalSearch, {val : x})
li.append $("<a href='#{address}' class='external_link' target='_blank'></a>")
li
ul.append lis
output.append ul
return output
str_value = if attrs.stringify_synthetic
attrs.stringify_synthetic(token_data)
else
(attrs.stringify or encodeHtmlEntities)(value)
if attrs.type == "url"
# If the value is empty or undefined and the URL is not to
# be shown, do not show the link at all. This handles
# synthetic attribute values; others are handled above.
if not str_value and attrs?.url_opts?.hide_url
return ""
url_opts = attrs.url_opts or {}
# If url_opts.new_window, open the link to a new window
target = if url_opts.new_window
" target='_blank'"
else
""
# The value with class sidebar_url does not wrap and is
# subject to abbreviating with an ellipsis, but a link
# with a link text instead of an URL should be allowed to
# wrap and not abbreviated, so use class sidebar_link for
# it. (Jyrki Niemi 2017-10-19)
class_attr = "class='exturl sidebar_" +
(if url_opts.hide_url then "link" else "url") + "'"
# If the function attrs.url_opts.stringify_link is
# defined, use it to make the complete link (HTML "a"
# element(s)). The function takes as arguments the name of
# the current attribute, its stringified value, its
# configuration properties, and HTML attributes for the a
# element. stringify_link is useful e.g. when a link
# attribute contains more than one URL. (Jyrki Niemi
# 2016-02-10)
if url_opts.stringify_link
return output.append attrs.url_opts.stringify_link(
key, str_value, attrs, "#{class_attr}#{target}")
# If url_prefix is specified, prepend it to the URL
url = (attrs.url_prefix or "") + str_value
# If url_opts.hide_url, use the localized label as the
# link text, otherwise the URL
link_text = if url_opts.hide_url
"<span rel='localize[#{attrs.label}]'>#{key}</span>"
else
decodeURI(str_value)
return output.append "<a href='#{url}' #{class_attr}#{target}>#{link_text}</a>"
else if attrs.taginfo_url or (key == "msd" and attrs.taginfo_url != "")
# For msd, an empty taginfo_url disables the info link, a
# non-empty value is used as an URL to link to, and an
# undefined value links to the default URL
# markup/msdtags.html. For other attributes, require that
# taginfo_url is defined and non-empty.(Jyrki Niemi
# 2015-02-04, 2016-02-10)
taginfo_url = attrs.taginfo_url or "markup/msdtags.html"
return output.append """<span class='msd_sidebar'>#{str_value}</span>
<a href='#{taginfo_url}' target='_blank'>
<span id='sidbar_info' class='ui-icon ui-icon-info'></span>
</a>
</span>
"""
else if attrs.pattern
return output.append _.template attrs.pattern, {key : key, val : str_value, pos_attrs : wordData, struct_attrs : sentenceData }
else
if attrs.translationKey?
str_value = mapViaDataset(str_value)
# Språkbanken's Korp requires an English translation
# for the localization to be used, but that is not
# appropriate for Kielipankki's Korp. However, would
# it be better to use the bare value instead of the
# translation key if a translation in the active
# language is missing? (Jyrki Niemi 2017-11-01)
# if loc_data["en"][attrs.translationKey + str_value]
# return output.append "<span rel='localize[#{attrs.translationKey}#{str_value}]'></span>"
# else
# return output.append "<span>#{str_value}</span>"
return output.append "<span rel='localize[#{attrs.translationKey}#{str_value}]'></span>"
else
return output.append "<span>#{str_value || ''}</span>"
applyEllipse: ->
# oldDisplay = @element.css("display")
# @element.css "display", "block"
totalWidth = @element.width()
# ellipse for too long links of type=url
@element.find(".sidebar_url").css("white-space", "nowrap").each ->
while $(this).width() > totalWidth
oldtext = $(this).text()
a = _.str.trim(oldtext, "/").replace("...", "").split("/")
domain = a.slice(2, 3)
midsection = a.slice(3).join("/")
midsection = "..." + midsection.slice(2)
$(this).text ["http:/"].concat(domain, midsection).join("/")
break if midsection is "..."
# @element.css "display", oldDisplay
updatePlacement: ->
max = Math.round($("#columns").position().top)
if $(window).scrollTop() < max
@element.removeClass "fixed"
else @element.addClass "fixed" if $("#left-column").height() > $("#sidebar").height()
$.widget("korp.sidebar", Sidebar)
$.widget "korp.radioList",
options:
change: $.noop
separator: "|"
selected: "default"
_create: ->
@_super()
self = this
$.each @element, ->
# $.proxy(self.options.change, self.element)();
$(this).children().wrap("<li />").click(->
unless $(this).is(".radioList_selected")
self.select $(this).data("mode")
self._trigger "change", $(this).data("mode")
).parent().prepend($("<span>").text(self.options.separator)).wrapAll "<ul class='inline_list' />"
@element.find(".inline_list span:first").remove()
@select @options.selected
select: (mode) ->
@options.selected = mode
target = @element.find("a").filter(->
$(this).data("mode") is mode
)
@element.find(".radioList_selected").removeClass "radioList_selected"
@element.find(target).addClass "radioList_selected"
@element
getSelected: ->
@element.find ".radioList_selected"
| 219369 | Sidebar =
_init: () ->
updateContent: (sentenceData, wordData, corpus, tokens) ->
@element.html ("""<div id="selected_sentence" />
<div id="selected_word" />
<div id="deptree_link" />
<div id="selected_links" />""")
corpusObj = settings.corpora[corpus]
formattedCorpusInfo =
if settings?.corpusExtraInfo
then util.formatCorpusExtraInfo(
corpusObj,
info_items: settings.corpusExtraInfo?.sidebar
item_paragraphs: true)
else ""
if formattedCorpusInfo
formattedCorpusInfo = "<br/>" + formattedCorpusInfo
$("<div />").html("<h4 rel='localize[corpus]'></h4> <p>#{corpusObj.title}</p><div id='sidebar-corpus-info'>#{formattedCorpusInfo}</div>").prependTo "#selected_sentence"
# All token data, to be passed to the function stringify_synthtetic
# of a synthetic attribute (<NAME> 2015-02-24)
# TODO (<NAME>): This could now be removed as Språkbanken's code
# also passes tokens to @renderCorpusContent and @renderCustomContent
token_data =
pos_attrs : wordData
struct_attrs : sentenceData
tokens : tokens
unless $.isEmptyObject(corpusObj.attributes)
$("#selected_word").append $("<h4>").localeKey("word_attr")
posData = @renderCorpusContent("pos", wordData, sentenceData,
corpusObj.attributes, tokens,
corpusObj.synthetic_attr_names.attributes, token_data)
# posData.appendTo "#selected_word"
$("#selected_word").append posData
unless $.isEmptyObject(corpusObj.struct_attributes)
$("#selected_sentence").append $("<h4>").localeKey("sentence_attr")
@renderCorpusContent("struct", wordData, sentenceData,
corpusObj.struct_attributes, tokens,
corpusObj.synthetic_attr_names.struct_attributes, token_data)
.appendTo "#selected_sentence"
unless $.isEmptyObject(corpusObj.custom_attributes)
[word, sentence] = @renderCustomContent(wordData, sentenceData, corpusObj.custom_attributes, tokens)
word.appendTo "#selected_word"
sentence.appendTo "#selected_sentence"
# Links in a separate link section
unless $.isEmptyObject(corpusObj.link_attributes)
@renderCorpusContent("link", wordData, sentenceData,
corpusObj.link_attributes, tokens,
corpusObj.synthetic_attr_names.link_attributes, token_data)
.appendTo "#selected_links"
@element.localize()
@applyEllipse()
if corpusObj.attributes.deprel
@renderGraph(tokens)
renderGraph : (tokens) ->
outerW = $(window).width() - 80
$("<span class='link show_deptree'>Visa träd</button>").localeKey("show_deptree").click( ->
info = $("<span class='info' />")
iframe = $('<iframe src="lib/deptrees/deptrees.html"></iframe>').css("width", outerW - 40).load ->
wnd = this.contentWindow
tokens = tokens
wnd.draw_deptree.call wnd, tokens, (msg) ->
[type, val] = _.head _.pairs msg
info.empty().append $("<span>").localeKey(type), $("<span>: </span>"), $("<span>").localeKey("#{type}_#{val}")
$("#deptree_popup").empty().append(info, iframe).dialog(
height : 300
width : outerW
).parent().find(".ui-dialog-title").localeKey("dep_tree")
).appendTo("#deptree_link")
renderCorpusContent: (type, wordData, sentenceData, corpus_attrs, tokens,
synthetic_attr_names, token_data) ->
if type == "struct" or type == "link"
pairs = _.pairs(sentenceData)
else if type == "pos"
pairs = _.pairs(wordData)
for item in (wordData._struct or [])
key = item.substring(0, item.indexOf(" "))
val = item.substring(item.indexOf(" ") + 1)
if key of corpus_attrs
pairs.push([key, val])
pairs = _.filter pairs, ([key, val]) -> corpus_attrs[key]
pairs.sort ([a], [b]) ->
ord1 = corpus_attrs[a].order
ord2 = corpus_attrs[b].order
# first three cases to handle ord1 or ord2 being undefined
if ord1 == ord2
return 0
if not ord1
return 1
if not ord2
return -1
else
return ord2 - ord1
items = []
for [key, value] in pairs
items = items.concat (@renderItem key, value, corpus_attrs[key], wordData, sentenceData, token_data, tokens).get?(0)
items = _.compact items
# Append possible synthetic attributes (J<NAME>emi 2015-02-24)
# TODO: Support the order property; it should be possible to
# interleave normal and synthetic attributes.
if synthetic_attr_names.length
synthetic = for key in synthetic_attr_names
@renderItem key, null, corpus_attrs[key], wordData, sentenceData, tokens, token_data
items = items.concat(synthetic)
return $(items)
renderCustomContent: (wordData, sentenceData, corpus_attrs, tokens) ->
struct_items = []
pos_items = []
for key, attrs of corpus_attrs
output = @renderItem(key, null, attrs, wordData, sentenceData, tokens)
if attrs.customType == "struct"
struct_items.push output
else if attrs.customType == "pos"
pos_items.push output
return [$(pos_items), $(struct_items)]
renderItem: (key, value, attrs, wordData, sentenceData, tokens, token_data) ->
# Convert &, < and > to HTML character entities (for
# stringifying attribute values for which stringify is not
# defined). (<NAME> 2016-12-15)
encodeHtmlEntities = (s) ->
s.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
# Map a value via the dataset property if it exists and is not
# an array, that it, is a mapping (object with properties).
# FIXME: This does not yield a correct result if the dataset
# keys are regular expressions as they may be. Should we
# perhaps have separate dataset mappings for the query,
# allowing regexps, and for stringifying values, not allowing
# regexps? (<NAME> 2017-05-16)
mapViaDataset = (value) ->
if attrs.dataset? and not _.isArray(attrs.dataset)
return attrs.dataset[value] or value
else
return value
if attrs.displayType in ["hidden", "date_interval"] or
attrs.displayOnly == "search" or attrs.hideSidebar
return ""
if attrs.type == "url" and attrs?.url_opts?.hide_url
# If url_opts.hide_url, hide the url and show the localized
# label as the link, or nothing, if the value is empty.
# Note that this does not work for synthetic attributes,
# as their value is null at this point, so they are
# handled further below.
if value == ""
return ""
output = $("<p></p>")
else if attrs.label
output = $("<p><span rel='localize[#{attrs.label}]'></span>: </p>")
else
output = $("<p></p>")
if attrs.renderItem
return output.append(attrs.renderItem key, value, attrs, wordData, sentenceData, tokens)
output.data("attrs", attrs)
# Convert an undefined value to the empty string (J<NAME>emi
# 2015-08-26)
value ?= ""
if (value == "|" or value == "") and
not (attrs.translationKey? and attrs.dataset?[value]?) and
not attrs.stringify_synthetic?
# The original version only appended to the output here
# but did not return yet. Would we need further processing
# for empty values in some cases? (<NAME> 2015-08-26)
output.append "<i rel='localize[empty]' style='color : grey'>${util.getLocaleString('empty')}</i>"
return output
# Transform the value if a transformation function has been
# specified. (<NAME>emi 2015-10-26)
if attrs.transform?
value = attrs.transform(value)
if attrs.type == "set" and attrs.taginfo_url
# For a set-valued attribute, add the taginfo link right
# after the attribute label (<NAME> 2016-02-10)
output.append """<a href='#{attrs.taginfo_url}' target='_blank'>
<span id='sidbar_info' class='ui-icon ui-icon-info'></span>
</a>
"""
if attrs.type == "set" and attrs.display?.expandList
valueArray = _.filter(value?.split("|") or [], Boolean)
attrSettings = attrs.display.expandList
if attrs.ranked
valueArray = _.map valueArray, (value) -> val = value.split(":"); [val[0], val[val.length - 1]]
lis = []
for [value, prob], outerIdx in valueArray
li = $("<li></li>")
subValues = if attrSettings.splitValue then attrSettings.splitValue value else [value]
for subValue, idx in subValues
val = (attrs.stringify or attrSettings.stringify or _.identity)(subValue)
inner = $("<span>" + val + "</span>");
if attrs.internalSearch and (attrSettings.linkAllValues or outerIdx is 0)
inner.data("key", subValue)
inner.addClass("link").click ->
searchKey = attrSettings.searchKey or key
cqpVal = $(this).data("key")
cqpExpr = if attrSettings.internalSearch then attrSettings.internalSearch searchKey, cqpVal else "[#{searchKey} contains '#{cqpVal}']"
search({"search": "cqp|" + cqpExpr})
if attrs.externalSearch
address = _.template(attrs.externalSearch, {val : subValue})
karpLink = $("<a href='#{address}' class='external_link' target='_blank' style='margin-top: -6px'></a>")
li.append inner
if attrSettings.joinValues and idx isnt subValues.length - 1
li.append attrSettings.joinValues
li.append "<span class='prob'> (" + prob + ")</span>"
if karpLink
li.append karpLink
lis.push li
else
lis = []
for value in valueArray
li = $("<li></li>")
li.append value
lis.push li
if lis.length == 0
ul = $('<i rel="localize[empty]" style="color : grey"></i>')
else
ul = $("<ul class='hide-prob' style='list-style:initial'>")
ul.append lis
if lis.length isnt 1
_.map lis, (li, idx) -> if idx != 0 then li.css('display', 'none')
showAll = $("<span class='link' rel='localize[complemgram_show_all]'></span><span> (" + (lis.length - 1) + ")</span>")
ul.append showAll
showOne = $("<span class='link' rel='localize[complemgram_show_one]'></span>")
showOne.css "display", "none"
ul.append showOne
showAll.click () ->
showAll.css "display", "none"
showOne.css "display", "inline"
ul.removeClass "hide-prob"
_.map lis, (li) ->
li.css "display", "list-item"
showOne.click () ->
showAll.css "display", "inline"
showOne.css "display", "none"
ul.addClass "hide-prob"
_.map lis, (li, i) ->
if i != 0
li.css "display", "none"
output.append ul
return output
else if attrs.type == "set"
pattern = attrs.pattern or '<span data-key="<%= key %>"><%= val %></span>'
ul = $("<ul>")
getStringVal = (str) ->
return _.reduce(_.invoke(_.invoke(str, "charCodeAt", 0), "toString"), (a,b) -> a + b);
valueArray = _.filter(value?.split("|") or [], Boolean)
if key == "variants"
# TODO: this doesn't sort quite as expected
valueArray.sort (a, b) ->
splita = util.splitLemgram(a);
splitb = util.splitLemgram(b);
strvala = getStringVal(splita.form) + splita.index + getStringVal(splita.pos);
strvalb = getStringVal(splitb.form) + splitb.index + getStringVal(splitb.pos);
return parseInt(strvala) - parseInt(strvalb);
itr = if _.isArray(valueArray) then valueArray else _.values(valueArray)
lis = for x in itr when x.length
val = (attrs.stringify or encodeHtmlEntities)(x)
inner = $(_.template(pattern, {key : x, val : val}))
if attrs.translationKey?
prefix = attrs.translationKey or ""
val = mapViaDataset(val)
inner.localeKey(prefix + val)
if attrs.internalSearch
inner.addClass("link").click ->
cqpVal = $(this).data("key")
search({"search": "cqp|[#{key} contains '#{cqpVal}']"})
li = $("<li></li>").data("key", x).append inner
if attrs.externalSearch
address = _.template(attrs.externalSearch, {val : x})
li.append $("<a href='#{address}' class='external_link' target='_blank'></a>")
li
ul.append lis
output.append ul
return output
str_value = if attrs.stringify_synthetic
attrs.stringify_synthetic(token_data)
else
(attrs.stringify or encodeHtmlEntities)(value)
if attrs.type == "url"
# If the value is empty or undefined and the URL is not to
# be shown, do not show the link at all. This handles
# synthetic attribute values; others are handled above.
if not str_value and attrs?.url_opts?.hide_url
return ""
url_opts = attrs.url_opts or {}
# If url_opts.new_window, open the link to a new window
target = if url_opts.new_window
" target='_blank'"
else
""
# The value with class sidebar_url does not wrap and is
# subject to abbreviating with an ellipsis, but a link
# with a link text instead of an URL should be allowed to
# wrap and not abbreviated, so use class sidebar_link for
# it. (<NAME> 2017-10-19)
class_attr = "class='exturl sidebar_" +
(if url_opts.hide_url then "link" else "url") + "'"
# If the function attrs.url_opts.stringify_link is
# defined, use it to make the complete link (HTML "a"
# element(s)). The function takes as arguments the name of
# the current attribute, its stringified value, its
# configuration properties, and HTML attributes for the a
# element. stringify_link is useful e.g. when a link
# attribute contains more than one URL. (<NAME>emi
# 2016-02-10)
if url_opts.stringify_link
return output.append attrs.url_opts.stringify_link(
key, str_value, attrs, "#{class_attr}#{target}")
# If url_prefix is specified, prepend it to the URL
url = (attrs.url_prefix or "") + str_value
# If url_opts.hide_url, use the localized label as the
# link text, otherwise the URL
link_text = if url_opts.hide_url
"<span rel='localize[#{attrs.label}]'>#{key}</span>"
else
decodeURI(str_value)
return output.append "<a href='#{url}' #{class_attr}#{target}>#{link_text}</a>"
else if attrs.taginfo_url or (key == "msd" and attrs.taginfo_url != "")
# For msd, an empty taginfo_url disables the info link, a
# non-empty value is used as an URL to link to, and an
# undefined value links to the default URL
# markup/msdtags.html. For other attributes, require that
# taginfo_url is defined and non-empty.(<NAME>
# 2015-02-04, 2016-02-10)
taginfo_url = attrs.taginfo_url or "markup/msdtags.html"
return output.append """<span class='msd_sidebar'>#{str_value}</span>
<a href='#{taginfo_url}' target='_blank'>
<span id='sidbar_info' class='ui-icon ui-icon-info'></span>
</a>
</span>
"""
else if attrs.pattern
return output.append _.template attrs.pattern, {key : key, val : str_value, pos_attrs : wordData, struct_attrs : sentenceData }
else
if attrs.translationKey?
str_value = mapViaDataset(str_value)
# Språkbanken's Korp requires an English translation
# for the localization to be used, but that is not
# appropriate for Kielipankki's Korp. However, would
# it be better to use the bare value instead of the
# translation key if a translation in the active
# language is missing? (<NAME> 2017-11-01)
# if loc_data["en"][attrs.translationKey + str_value]
# return output.append "<span rel='localize[#{attrs.translationKey}#{str_value}]'></span>"
# else
# return output.append "<span>#{str_value}</span>"
return output.append "<span rel='localize[#{attrs.translationKey}#{str_value}]'></span>"
else
return output.append "<span>#{str_value || ''}</span>"
applyEllipse: ->
# oldDisplay = @element.css("display")
# @element.css "display", "block"
totalWidth = @element.width()
# ellipse for too long links of type=url
@element.find(".sidebar_url").css("white-space", "nowrap").each ->
while $(this).width() > totalWidth
oldtext = $(this).text()
a = _.str.trim(oldtext, "/").replace("...", "").split("/")
domain = a.slice(2, 3)
midsection = a.slice(3).join("/")
midsection = "..." + midsection.slice(2)
$(this).text ["http:/"].concat(domain, midsection).join("/")
break if midsection is "..."
# @element.css "display", oldDisplay
updatePlacement: ->
max = Math.round($("#columns").position().top)
if $(window).scrollTop() < max
@element.removeClass "fixed"
else @element.addClass "fixed" if $("#left-column").height() > $("#sidebar").height()
$.widget("korp.sidebar", Sidebar)
$.widget "korp.radioList",
options:
change: $.noop
separator: "|"
selected: "default"
_create: ->
@_super()
self = this
$.each @element, ->
# $.proxy(self.options.change, self.element)();
$(this).children().wrap("<li />").click(->
unless $(this).is(".radioList_selected")
self.select $(this).data("mode")
self._trigger "change", $(this).data("mode")
).parent().prepend($("<span>").text(self.options.separator)).wrapAll "<ul class='inline_list' />"
@element.find(".inline_list span:first").remove()
@select @options.selected
select: (mode) ->
@options.selected = mode
target = @element.find("a").filter(->
$(this).data("mode") is mode
)
@element.find(".radioList_selected").removeClass "radioList_selected"
@element.find(target).addClass "radioList_selected"
@element
getSelected: ->
@element.find ".radioList_selected"
| true | Sidebar =
_init: () ->
updateContent: (sentenceData, wordData, corpus, tokens) ->
@element.html ("""<div id="selected_sentence" />
<div id="selected_word" />
<div id="deptree_link" />
<div id="selected_links" />""")
corpusObj = settings.corpora[corpus]
formattedCorpusInfo =
if settings?.corpusExtraInfo
then util.formatCorpusExtraInfo(
corpusObj,
info_items: settings.corpusExtraInfo?.sidebar
item_paragraphs: true)
else ""
if formattedCorpusInfo
formattedCorpusInfo = "<br/>" + formattedCorpusInfo
$("<div />").html("<h4 rel='localize[corpus]'></h4> <p>#{corpusObj.title}</p><div id='sidebar-corpus-info'>#{formattedCorpusInfo}</div>").prependTo "#selected_sentence"
# All token data, to be passed to the function stringify_synthtetic
# of a synthetic attribute (PI:NAME:<NAME>END_PI 2015-02-24)
# TODO (PI:NAME:<NAME>END_PI): This could now be removed as Språkbanken's code
# also passes tokens to @renderCorpusContent and @renderCustomContent
token_data =
pos_attrs : wordData
struct_attrs : sentenceData
tokens : tokens
unless $.isEmptyObject(corpusObj.attributes)
$("#selected_word").append $("<h4>").localeKey("word_attr")
posData = @renderCorpusContent("pos", wordData, sentenceData,
corpusObj.attributes, tokens,
corpusObj.synthetic_attr_names.attributes, token_data)
# posData.appendTo "#selected_word"
$("#selected_word").append posData
unless $.isEmptyObject(corpusObj.struct_attributes)
$("#selected_sentence").append $("<h4>").localeKey("sentence_attr")
@renderCorpusContent("struct", wordData, sentenceData,
corpusObj.struct_attributes, tokens,
corpusObj.synthetic_attr_names.struct_attributes, token_data)
.appendTo "#selected_sentence"
unless $.isEmptyObject(corpusObj.custom_attributes)
[word, sentence] = @renderCustomContent(wordData, sentenceData, corpusObj.custom_attributes, tokens)
word.appendTo "#selected_word"
sentence.appendTo "#selected_sentence"
# Links in a separate link section
unless $.isEmptyObject(corpusObj.link_attributes)
@renderCorpusContent("link", wordData, sentenceData,
corpusObj.link_attributes, tokens,
corpusObj.synthetic_attr_names.link_attributes, token_data)
.appendTo "#selected_links"
@element.localize()
@applyEllipse()
if corpusObj.attributes.deprel
@renderGraph(tokens)
renderGraph : (tokens) ->
outerW = $(window).width() - 80
$("<span class='link show_deptree'>Visa träd</button>").localeKey("show_deptree").click( ->
info = $("<span class='info' />")
iframe = $('<iframe src="lib/deptrees/deptrees.html"></iframe>').css("width", outerW - 40).load ->
wnd = this.contentWindow
tokens = tokens
wnd.draw_deptree.call wnd, tokens, (msg) ->
[type, val] = _.head _.pairs msg
info.empty().append $("<span>").localeKey(type), $("<span>: </span>"), $("<span>").localeKey("#{type}_#{val}")
$("#deptree_popup").empty().append(info, iframe).dialog(
height : 300
width : outerW
).parent().find(".ui-dialog-title").localeKey("dep_tree")
).appendTo("#deptree_link")
renderCorpusContent: (type, wordData, sentenceData, corpus_attrs, tokens,
synthetic_attr_names, token_data) ->
if type == "struct" or type == "link"
pairs = _.pairs(sentenceData)
else if type == "pos"
pairs = _.pairs(wordData)
for item in (wordData._struct or [])
key = item.substring(0, item.indexOf(" "))
val = item.substring(item.indexOf(" ") + 1)
if key of corpus_attrs
pairs.push([key, val])
pairs = _.filter pairs, ([key, val]) -> corpus_attrs[key]
pairs.sort ([a], [b]) ->
ord1 = corpus_attrs[a].order
ord2 = corpus_attrs[b].order
# first three cases to handle ord1 or ord2 being undefined
if ord1 == ord2
return 0
if not ord1
return 1
if not ord2
return -1
else
return ord2 - ord1
items = []
for [key, value] in pairs
items = items.concat (@renderItem key, value, corpus_attrs[key], wordData, sentenceData, token_data, tokens).get?(0)
items = _.compact items
# Append possible synthetic attributes (JPI:NAME:<NAME>END_PIemi 2015-02-24)
# TODO: Support the order property; it should be possible to
# interleave normal and synthetic attributes.
if synthetic_attr_names.length
synthetic = for key in synthetic_attr_names
@renderItem key, null, corpus_attrs[key], wordData, sentenceData, tokens, token_data
items = items.concat(synthetic)
return $(items)
renderCustomContent: (wordData, sentenceData, corpus_attrs, tokens) ->
struct_items = []
pos_items = []
for key, attrs of corpus_attrs
output = @renderItem(key, null, attrs, wordData, sentenceData, tokens)
if attrs.customType == "struct"
struct_items.push output
else if attrs.customType == "pos"
pos_items.push output
return [$(pos_items), $(struct_items)]
renderItem: (key, value, attrs, wordData, sentenceData, tokens, token_data) ->
# Convert &, < and > to HTML character entities (for
# stringifying attribute values for which stringify is not
# defined). (PI:NAME:<NAME>END_PI 2016-12-15)
encodeHtmlEntities = (s) ->
s.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
# Map a value via the dataset property if it exists and is not
# an array, that it, is a mapping (object with properties).
# FIXME: This does not yield a correct result if the dataset
# keys are regular expressions as they may be. Should we
# perhaps have separate dataset mappings for the query,
# allowing regexps, and for stringifying values, not allowing
# regexps? (PI:NAME:<NAME>END_PI 2017-05-16)
mapViaDataset = (value) ->
if attrs.dataset? and not _.isArray(attrs.dataset)
return attrs.dataset[value] or value
else
return value
if attrs.displayType in ["hidden", "date_interval"] or
attrs.displayOnly == "search" or attrs.hideSidebar
return ""
if attrs.type == "url" and attrs?.url_opts?.hide_url
# If url_opts.hide_url, hide the url and show the localized
# label as the link, or nothing, if the value is empty.
# Note that this does not work for synthetic attributes,
# as their value is null at this point, so they are
# handled further below.
if value == ""
return ""
output = $("<p></p>")
else if attrs.label
output = $("<p><span rel='localize[#{attrs.label}]'></span>: </p>")
else
output = $("<p></p>")
if attrs.renderItem
return output.append(attrs.renderItem key, value, attrs, wordData, sentenceData, tokens)
output.data("attrs", attrs)
# Convert an undefined value to the empty string (JPI:NAME:<NAME>END_PIemi
# 2015-08-26)
value ?= ""
if (value == "|" or value == "") and
not (attrs.translationKey? and attrs.dataset?[value]?) and
not attrs.stringify_synthetic?
# The original version only appended to the output here
# but did not return yet. Would we need further processing
# for empty values in some cases? (PI:NAME:<NAME>END_PI 2015-08-26)
output.append "<i rel='localize[empty]' style='color : grey'>${util.getLocaleString('empty')}</i>"
return output
# Transform the value if a transformation function has been
# specified. (PI:NAME:<NAME>END_PIemi 2015-10-26)
if attrs.transform?
value = attrs.transform(value)
if attrs.type == "set" and attrs.taginfo_url
# For a set-valued attribute, add the taginfo link right
# after the attribute label (PI:NAME:<NAME>END_PI 2016-02-10)
output.append """<a href='#{attrs.taginfo_url}' target='_blank'>
<span id='sidbar_info' class='ui-icon ui-icon-info'></span>
</a>
"""
if attrs.type == "set" and attrs.display?.expandList
valueArray = _.filter(value?.split("|") or [], Boolean)
attrSettings = attrs.display.expandList
if attrs.ranked
valueArray = _.map valueArray, (value) -> val = value.split(":"); [val[0], val[val.length - 1]]
lis = []
for [value, prob], outerIdx in valueArray
li = $("<li></li>")
subValues = if attrSettings.splitValue then attrSettings.splitValue value else [value]
for subValue, idx in subValues
val = (attrs.stringify or attrSettings.stringify or _.identity)(subValue)
inner = $("<span>" + val + "</span>");
if attrs.internalSearch and (attrSettings.linkAllValues or outerIdx is 0)
inner.data("key", subValue)
inner.addClass("link").click ->
searchKey = attrSettings.searchKey or key
cqpVal = $(this).data("key")
cqpExpr = if attrSettings.internalSearch then attrSettings.internalSearch searchKey, cqpVal else "[#{searchKey} contains '#{cqpVal}']"
search({"search": "cqp|" + cqpExpr})
if attrs.externalSearch
address = _.template(attrs.externalSearch, {val : subValue})
karpLink = $("<a href='#{address}' class='external_link' target='_blank' style='margin-top: -6px'></a>")
li.append inner
if attrSettings.joinValues and idx isnt subValues.length - 1
li.append attrSettings.joinValues
li.append "<span class='prob'> (" + prob + ")</span>"
if karpLink
li.append karpLink
lis.push li
else
lis = []
for value in valueArray
li = $("<li></li>")
li.append value
lis.push li
if lis.length == 0
ul = $('<i rel="localize[empty]" style="color : grey"></i>')
else
ul = $("<ul class='hide-prob' style='list-style:initial'>")
ul.append lis
if lis.length isnt 1
_.map lis, (li, idx) -> if idx != 0 then li.css('display', 'none')
showAll = $("<span class='link' rel='localize[complemgram_show_all]'></span><span> (" + (lis.length - 1) + ")</span>")
ul.append showAll
showOne = $("<span class='link' rel='localize[complemgram_show_one]'></span>")
showOne.css "display", "none"
ul.append showOne
showAll.click () ->
showAll.css "display", "none"
showOne.css "display", "inline"
ul.removeClass "hide-prob"
_.map lis, (li) ->
li.css "display", "list-item"
showOne.click () ->
showAll.css "display", "inline"
showOne.css "display", "none"
ul.addClass "hide-prob"
_.map lis, (li, i) ->
if i != 0
li.css "display", "none"
output.append ul
return output
else if attrs.type == "set"
pattern = attrs.pattern or '<span data-key="<%= key %>"><%= val %></span>'
ul = $("<ul>")
getStringVal = (str) ->
return _.reduce(_.invoke(_.invoke(str, "charCodeAt", 0), "toString"), (a,b) -> a + b);
valueArray = _.filter(value?.split("|") or [], Boolean)
if key == "variants"
# TODO: this doesn't sort quite as expected
valueArray.sort (a, b) ->
splita = util.splitLemgram(a);
splitb = util.splitLemgram(b);
strvala = getStringVal(splita.form) + splita.index + getStringVal(splita.pos);
strvalb = getStringVal(splitb.form) + splitb.index + getStringVal(splitb.pos);
return parseInt(strvala) - parseInt(strvalb);
itr = if _.isArray(valueArray) then valueArray else _.values(valueArray)
lis = for x in itr when x.length
val = (attrs.stringify or encodeHtmlEntities)(x)
inner = $(_.template(pattern, {key : x, val : val}))
if attrs.translationKey?
prefix = attrs.translationKey or ""
val = mapViaDataset(val)
inner.localeKey(prefix + val)
if attrs.internalSearch
inner.addClass("link").click ->
cqpVal = $(this).data("key")
search({"search": "cqp|[#{key} contains '#{cqpVal}']"})
li = $("<li></li>").data("key", x).append inner
if attrs.externalSearch
address = _.template(attrs.externalSearch, {val : x})
li.append $("<a href='#{address}' class='external_link' target='_blank'></a>")
li
ul.append lis
output.append ul
return output
str_value = if attrs.stringify_synthetic
attrs.stringify_synthetic(token_data)
else
(attrs.stringify or encodeHtmlEntities)(value)
if attrs.type == "url"
# If the value is empty or undefined and the URL is not to
# be shown, do not show the link at all. This handles
# synthetic attribute values; others are handled above.
if not str_value and attrs?.url_opts?.hide_url
return ""
url_opts = attrs.url_opts or {}
# If url_opts.new_window, open the link to a new window
target = if url_opts.new_window
" target='_blank'"
else
""
# The value with class sidebar_url does not wrap and is
# subject to abbreviating with an ellipsis, but a link
# with a link text instead of an URL should be allowed to
# wrap and not abbreviated, so use class sidebar_link for
# it. (PI:NAME:<NAME>END_PI 2017-10-19)
class_attr = "class='exturl sidebar_" +
(if url_opts.hide_url then "link" else "url") + "'"
# If the function attrs.url_opts.stringify_link is
# defined, use it to make the complete link (HTML "a"
# element(s)). The function takes as arguments the name of
# the current attribute, its stringified value, its
# configuration properties, and HTML attributes for the a
# element. stringify_link is useful e.g. when a link
# attribute contains more than one URL. (PI:NAME:<NAME>END_PIemi
# 2016-02-10)
if url_opts.stringify_link
return output.append attrs.url_opts.stringify_link(
key, str_value, attrs, "#{class_attr}#{target}")
# If url_prefix is specified, prepend it to the URL
url = (attrs.url_prefix or "") + str_value
# If url_opts.hide_url, use the localized label as the
# link text, otherwise the URL
link_text = if url_opts.hide_url
"<span rel='localize[#{attrs.label}]'>#{key}</span>"
else
decodeURI(str_value)
return output.append "<a href='#{url}' #{class_attr}#{target}>#{link_text}</a>"
else if attrs.taginfo_url or (key == "msd" and attrs.taginfo_url != "")
# For msd, an empty taginfo_url disables the info link, a
# non-empty value is used as an URL to link to, and an
# undefined value links to the default URL
# markup/msdtags.html. For other attributes, require that
# taginfo_url is defined and non-empty.(PI:NAME:<NAME>END_PI
# 2015-02-04, 2016-02-10)
taginfo_url = attrs.taginfo_url or "markup/msdtags.html"
return output.append """<span class='msd_sidebar'>#{str_value}</span>
<a href='#{taginfo_url}' target='_blank'>
<span id='sidbar_info' class='ui-icon ui-icon-info'></span>
</a>
</span>
"""
else if attrs.pattern
return output.append _.template attrs.pattern, {key : key, val : str_value, pos_attrs : wordData, struct_attrs : sentenceData }
else
if attrs.translationKey?
str_value = mapViaDataset(str_value)
# Språkbanken's Korp requires an English translation
# for the localization to be used, but that is not
# appropriate for Kielipankki's Korp. However, would
# it be better to use the bare value instead of the
# translation key if a translation in the active
# language is missing? (PI:NAME:<NAME>END_PI 2017-11-01)
# if loc_data["en"][attrs.translationKey + str_value]
# return output.append "<span rel='localize[#{attrs.translationKey}#{str_value}]'></span>"
# else
# return output.append "<span>#{str_value}</span>"
return output.append "<span rel='localize[#{attrs.translationKey}#{str_value}]'></span>"
else
return output.append "<span>#{str_value || ''}</span>"
applyEllipse: ->
# oldDisplay = @element.css("display")
# @element.css "display", "block"
totalWidth = @element.width()
# ellipse for too long links of type=url
@element.find(".sidebar_url").css("white-space", "nowrap").each ->
while $(this).width() > totalWidth
oldtext = $(this).text()
a = _.str.trim(oldtext, "/").replace("...", "").split("/")
domain = a.slice(2, 3)
midsection = a.slice(3).join("/")
midsection = "..." + midsection.slice(2)
$(this).text ["http:/"].concat(domain, midsection).join("/")
break if midsection is "..."
# @element.css "display", oldDisplay
updatePlacement: ->
max = Math.round($("#columns").position().top)
if $(window).scrollTop() < max
@element.removeClass "fixed"
else @element.addClass "fixed" if $("#left-column").height() > $("#sidebar").height()
$.widget("korp.sidebar", Sidebar)
$.widget "korp.radioList",
options:
change: $.noop
separator: "|"
selected: "default"
_create: ->
@_super()
self = this
$.each @element, ->
# $.proxy(self.options.change, self.element)();
$(this).children().wrap("<li />").click(->
unless $(this).is(".radioList_selected")
self.select $(this).data("mode")
self._trigger "change", $(this).data("mode")
).parent().prepend($("<span>").text(self.options.separator)).wrapAll "<ul class='inline_list' />"
@element.find(".inline_list span:first").remove()
@select @options.selected
select: (mode) ->
@options.selected = mode
target = @element.find("a").filter(->
$(this).data("mode") is mode
)
@element.find(".radioList_selected").removeClass "radioList_selected"
@element.find(target).addClass "radioList_selected"
@element
getSelected: ->
@element.find ".radioList_selected"
|
[
{
"context": "setItems} are of the type\n # `{\"id\": 3, \"name\": \"Atom\"}` then you would return `\"name\"` from this metho",
"end": 1961,
"score": 0.9967793822288513,
"start": 1957,
"tag": "NAME",
"value": "Atom"
}
] | lib/view/emp-enable-lua-view.coffee | jcrom/emp-debugger | 2 | {$, $$, View, SelectListView} = require 'atom-space-pen-views'
path = require 'path'
emp = require '../exports/emp'
relate_view = require './emp-relate-view'
path_fliter = require '../util/path-loader'
tmp_offline_path = ''
relate_all_views = ''
module.exports =
class EnableLuaView extends SelectListView
emp_socket_server: null
initialize: (serializeState, @emp_socket_server) ->
# console.log 'enable view process initial'
super
@addClass('overlay from-top')
# @setMaxItems(20)
@autoDetect = index: 'Auto Detect'
unless tmp_offline_path = atom.config.get(emp.EMP_OFFLINE_RELATE_DIR)
tmp_offline_path = emp.EMP_OFFLINE_RELATE_PATH_V
atom.commands.add "atom-workspace","emp-debugger:enable-lua", => @enable_lua()
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@cancel()
# @remove()
enable_lua: ->
# console.log "enable_view"
if @panel?
@cancel()
else
path_fliter.load_all_path tmp_offline_path, emp.EMP_SCRIPT_FILTER_IGNORE, (paths) ->
# console.log result
relate_all_views = paths
@setItems(@get_script_items())
@storeFocusedElement()
@panel = atom.workspace.addModalPanel(item:this)
@focusFilterEditor()
get_script_items: ->
# console.log @emp_socket_server.get_client_map()
# console.log @emp_socket_server.get_client_map().get_all_views()
tmp_map = @emp_socket_server.get_client_map().get_all_script()
re_map = new Array()
index = 0
len = tmp_map.length
for name,scr_obj of tmp_map
re_map.push(scr_obj)
re_map
# Public: Get the property name to use when filtering items.
#
# This method may be overridden by classes to allow fuzzy filtering based
# on a specific property of the item objects.
#
# For example if the objects you pass to {::setItems} are of the type
# `{"id": 3, "name": "Atom"}` then you would return `"name"` from this method
# to fuzzy filter by that property when text is entered into this view's
# editor.
#
# Returns the property name to fuzzy filter by.
getFilterKey: ->
# console.log "get key"
'script_index'
# Public: Create a view for the given model item.
#
# This method must be overridden by subclasses.
#
# This is called when the item is about to appended to the list view.
#
# item - The model item being rendered. This will always be one of the items
# previously passed to {::setItems}.
#
# Returns a String of HTML, DOM element, jQuery object, or View.
viewForItem: (item) ->
# console.log "view item"
icon_class = "status-added icon-diff-added"
icon_class = "status-ignored icon-diff-ignored" unless !item.readed
"<li class=\"two-lines\">
<div class=\"status icon #{icon_class}\"></div>
<div class=\"primary-line icon icon-file-text\">#{item.script_index}</div>
<div class=\"secondary-line no-icon\">From client: ##{item.fa_address}:#{item.fa_from}</div>"
# Public: Callback function for when an item is selected.
#
# This method must be overridden by subclasses.
#
# item - The selected model item. This will always be one of the items
# previously passed to {::setItems}.
#
# Returns a DOM element, jQuery object, or {View}.
confirmed: (item) ->
# console.log("#{item.index} was selected")
# console.log item.readed
item.set_readed()
@initial_new_pane(item)
@cancel()
cancelled: ->
@panel?.destroy()
@panel = null
# initial a new editor pane
initial_new_pane: (item)->
tmp_name = item.script_name
if dest_file_path = item.dir
project_path = atom.project.getPaths()[0]
tmp_file_path = path.join project_path, dest_file_path
if fs.existsSync tmp_file_path
@create_editor tmp_file_path, item
else
com_filter_arr = []
# console.log relate_all_views
# console.log tmp_name
re_path_arr = path_fliter.filter_path(relate_all_views, tmp_name)
# console.log re_path_arr
for tmp_item in re_path_arr
if tmp_item.name is tmp_name
com_filter_arr.push(tmp_item)
if com_filter_arr.length is 0
atom.workspace.open().then (tmp_editor) =>
@store_info(tmp_editor, item)
else if com_filter_arr.length is 1
tmp_item = com_filter_arr.pop()
@create_editor tmp_item.dir, item
else
unless @path_view?
@path_view = new relate_view(tmp_offline_path, emp.EMP_SCRIPT_FILTER_IGNORE)
@path_view.enable_view(com_filter_arr, item, this.create_editor)
create_editor:(tmp_file_path, item) ->
changeFocus = true
atom.workspace.open(tmp_file_path, { changeFocus }).then (tmp_editor) =>
tmp_editor["emp_live_view"] = item.fa_view.view
tmp_editor["emp_live_script_name"] = item.script_name
tmp_editor["emp_live_script"] = item
# console.log tmp_editor
tmp_editor.setText(item.script_con)
gramers = @getGrammars()
tmp_editor.setGrammar(gramers[0]) unless gramers[0] is undefined
store_info: (tmp_editor, item)->
tmp_editor["emp_live_view"] = item.fa_view.view
tmp_editor["emp_live_script_name"] = item.script_name
tmp_editor["emp_live_script"] = item
# console.log tmp_editor
tmp_editor.setText(item.script_con)
gramers = @getGrammars()
tmp_editor.setGrammar(gramers[0]) unless gramers[0] is undefined
# set the opened editor grammar, default is HTML
getGrammars: ->
grammars = atom.grammars.getGrammars().filter (grammar) ->
(grammar isnt atom.grammars.nullGrammar) and
grammar.name is 'Lua'
if !grammars
grammars = atom.grammars.getGrammars().filter (grammar) ->
(grammar isnt atom.grammars.nullGrammar) and
grammar.name is 'Emp View'
grammars
| 167914 | {$, $$, View, SelectListView} = require 'atom-space-pen-views'
path = require 'path'
emp = require '../exports/emp'
relate_view = require './emp-relate-view'
path_fliter = require '../util/path-loader'
tmp_offline_path = ''
relate_all_views = ''
module.exports =
class EnableLuaView extends SelectListView
emp_socket_server: null
initialize: (serializeState, @emp_socket_server) ->
# console.log 'enable view process initial'
super
@addClass('overlay from-top')
# @setMaxItems(20)
@autoDetect = index: 'Auto Detect'
unless tmp_offline_path = atom.config.get(emp.EMP_OFFLINE_RELATE_DIR)
tmp_offline_path = emp.EMP_OFFLINE_RELATE_PATH_V
atom.commands.add "atom-workspace","emp-debugger:enable-lua", => @enable_lua()
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@cancel()
# @remove()
enable_lua: ->
# console.log "enable_view"
if @panel?
@cancel()
else
path_fliter.load_all_path tmp_offline_path, emp.EMP_SCRIPT_FILTER_IGNORE, (paths) ->
# console.log result
relate_all_views = paths
@setItems(@get_script_items())
@storeFocusedElement()
@panel = atom.workspace.addModalPanel(item:this)
@focusFilterEditor()
get_script_items: ->
# console.log @emp_socket_server.get_client_map()
# console.log @emp_socket_server.get_client_map().get_all_views()
tmp_map = @emp_socket_server.get_client_map().get_all_script()
re_map = new Array()
index = 0
len = tmp_map.length
for name,scr_obj of tmp_map
re_map.push(scr_obj)
re_map
# Public: Get the property name to use when filtering items.
#
# This method may be overridden by classes to allow fuzzy filtering based
# on a specific property of the item objects.
#
# For example if the objects you pass to {::setItems} are of the type
# `{"id": 3, "name": "<NAME>"}` then you would return `"name"` from this method
# to fuzzy filter by that property when text is entered into this view's
# editor.
#
# Returns the property name to fuzzy filter by.
getFilterKey: ->
# console.log "get key"
'script_index'
# Public: Create a view for the given model item.
#
# This method must be overridden by subclasses.
#
# This is called when the item is about to appended to the list view.
#
# item - The model item being rendered. This will always be one of the items
# previously passed to {::setItems}.
#
# Returns a String of HTML, DOM element, jQuery object, or View.
viewForItem: (item) ->
# console.log "view item"
icon_class = "status-added icon-diff-added"
icon_class = "status-ignored icon-diff-ignored" unless !item.readed
"<li class=\"two-lines\">
<div class=\"status icon #{icon_class}\"></div>
<div class=\"primary-line icon icon-file-text\">#{item.script_index}</div>
<div class=\"secondary-line no-icon\">From client: ##{item.fa_address}:#{item.fa_from}</div>"
# Public: Callback function for when an item is selected.
#
# This method must be overridden by subclasses.
#
# item - The selected model item. This will always be one of the items
# previously passed to {::setItems}.
#
# Returns a DOM element, jQuery object, or {View}.
confirmed: (item) ->
# console.log("#{item.index} was selected")
# console.log item.readed
item.set_readed()
@initial_new_pane(item)
@cancel()
cancelled: ->
@panel?.destroy()
@panel = null
# initial a new editor pane
initial_new_pane: (item)->
tmp_name = item.script_name
if dest_file_path = item.dir
project_path = atom.project.getPaths()[0]
tmp_file_path = path.join project_path, dest_file_path
if fs.existsSync tmp_file_path
@create_editor tmp_file_path, item
else
com_filter_arr = []
# console.log relate_all_views
# console.log tmp_name
re_path_arr = path_fliter.filter_path(relate_all_views, tmp_name)
# console.log re_path_arr
for tmp_item in re_path_arr
if tmp_item.name is tmp_name
com_filter_arr.push(tmp_item)
if com_filter_arr.length is 0
atom.workspace.open().then (tmp_editor) =>
@store_info(tmp_editor, item)
else if com_filter_arr.length is 1
tmp_item = com_filter_arr.pop()
@create_editor tmp_item.dir, item
else
unless @path_view?
@path_view = new relate_view(tmp_offline_path, emp.EMP_SCRIPT_FILTER_IGNORE)
@path_view.enable_view(com_filter_arr, item, this.create_editor)
create_editor:(tmp_file_path, item) ->
changeFocus = true
atom.workspace.open(tmp_file_path, { changeFocus }).then (tmp_editor) =>
tmp_editor["emp_live_view"] = item.fa_view.view
tmp_editor["emp_live_script_name"] = item.script_name
tmp_editor["emp_live_script"] = item
# console.log tmp_editor
tmp_editor.setText(item.script_con)
gramers = @getGrammars()
tmp_editor.setGrammar(gramers[0]) unless gramers[0] is undefined
store_info: (tmp_editor, item)->
tmp_editor["emp_live_view"] = item.fa_view.view
tmp_editor["emp_live_script_name"] = item.script_name
tmp_editor["emp_live_script"] = item
# console.log tmp_editor
tmp_editor.setText(item.script_con)
gramers = @getGrammars()
tmp_editor.setGrammar(gramers[0]) unless gramers[0] is undefined
# set the opened editor grammar, default is HTML
getGrammars: ->
grammars = atom.grammars.getGrammars().filter (grammar) ->
(grammar isnt atom.grammars.nullGrammar) and
grammar.name is 'Lua'
if !grammars
grammars = atom.grammars.getGrammars().filter (grammar) ->
(grammar isnt atom.grammars.nullGrammar) and
grammar.name is 'Emp View'
grammars
| true | {$, $$, View, SelectListView} = require 'atom-space-pen-views'
path = require 'path'
emp = require '../exports/emp'
relate_view = require './emp-relate-view'
path_fliter = require '../util/path-loader'
tmp_offline_path = ''
relate_all_views = ''
module.exports =
class EnableLuaView extends SelectListView
emp_socket_server: null
initialize: (serializeState, @emp_socket_server) ->
# console.log 'enable view process initial'
super
@addClass('overlay from-top')
# @setMaxItems(20)
@autoDetect = index: 'Auto Detect'
unless tmp_offline_path = atom.config.get(emp.EMP_OFFLINE_RELATE_DIR)
tmp_offline_path = emp.EMP_OFFLINE_RELATE_PATH_V
atom.commands.add "atom-workspace","emp-debugger:enable-lua", => @enable_lua()
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@cancel()
# @remove()
enable_lua: ->
# console.log "enable_view"
if @panel?
@cancel()
else
path_fliter.load_all_path tmp_offline_path, emp.EMP_SCRIPT_FILTER_IGNORE, (paths) ->
# console.log result
relate_all_views = paths
@setItems(@get_script_items())
@storeFocusedElement()
@panel = atom.workspace.addModalPanel(item:this)
@focusFilterEditor()
get_script_items: ->
# console.log @emp_socket_server.get_client_map()
# console.log @emp_socket_server.get_client_map().get_all_views()
tmp_map = @emp_socket_server.get_client_map().get_all_script()
re_map = new Array()
index = 0
len = tmp_map.length
for name,scr_obj of tmp_map
re_map.push(scr_obj)
re_map
# Public: Get the property name to use when filtering items.
#
# This method may be overridden by classes to allow fuzzy filtering based
# on a specific property of the item objects.
#
# For example if the objects you pass to {::setItems} are of the type
# `{"id": 3, "name": "PI:NAME:<NAME>END_PI"}` then you would return `"name"` from this method
# to fuzzy filter by that property when text is entered into this view's
# editor.
#
# Returns the property name to fuzzy filter by.
getFilterKey: ->
# console.log "get key"
'script_index'
# Public: Create a view for the given model item.
#
# This method must be overridden by subclasses.
#
# This is called when the item is about to appended to the list view.
#
# item - The model item being rendered. This will always be one of the items
# previously passed to {::setItems}.
#
# Returns a String of HTML, DOM element, jQuery object, or View.
viewForItem: (item) ->
# console.log "view item"
icon_class = "status-added icon-diff-added"
icon_class = "status-ignored icon-diff-ignored" unless !item.readed
"<li class=\"two-lines\">
<div class=\"status icon #{icon_class}\"></div>
<div class=\"primary-line icon icon-file-text\">#{item.script_index}</div>
<div class=\"secondary-line no-icon\">From client: ##{item.fa_address}:#{item.fa_from}</div>"
# Public: Callback function for when an item is selected.
#
# This method must be overridden by subclasses.
#
# item - The selected model item. This will always be one of the items
# previously passed to {::setItems}.
#
# Returns a DOM element, jQuery object, or {View}.
confirmed: (item) ->
# console.log("#{item.index} was selected")
# console.log item.readed
item.set_readed()
@initial_new_pane(item)
@cancel()
cancelled: ->
@panel?.destroy()
@panel = null
# initial a new editor pane
initial_new_pane: (item)->
tmp_name = item.script_name
if dest_file_path = item.dir
project_path = atom.project.getPaths()[0]
tmp_file_path = path.join project_path, dest_file_path
if fs.existsSync tmp_file_path
@create_editor tmp_file_path, item
else
com_filter_arr = []
# console.log relate_all_views
# console.log tmp_name
re_path_arr = path_fliter.filter_path(relate_all_views, tmp_name)
# console.log re_path_arr
for tmp_item in re_path_arr
if tmp_item.name is tmp_name
com_filter_arr.push(tmp_item)
if com_filter_arr.length is 0
atom.workspace.open().then (tmp_editor) =>
@store_info(tmp_editor, item)
else if com_filter_arr.length is 1
tmp_item = com_filter_arr.pop()
@create_editor tmp_item.dir, item
else
unless @path_view?
@path_view = new relate_view(tmp_offline_path, emp.EMP_SCRIPT_FILTER_IGNORE)
@path_view.enable_view(com_filter_arr, item, this.create_editor)
create_editor:(tmp_file_path, item) ->
changeFocus = true
atom.workspace.open(tmp_file_path, { changeFocus }).then (tmp_editor) =>
tmp_editor["emp_live_view"] = item.fa_view.view
tmp_editor["emp_live_script_name"] = item.script_name
tmp_editor["emp_live_script"] = item
# console.log tmp_editor
tmp_editor.setText(item.script_con)
gramers = @getGrammars()
tmp_editor.setGrammar(gramers[0]) unless gramers[0] is undefined
store_info: (tmp_editor, item)->
tmp_editor["emp_live_view"] = item.fa_view.view
tmp_editor["emp_live_script_name"] = item.script_name
tmp_editor["emp_live_script"] = item
# console.log tmp_editor
tmp_editor.setText(item.script_con)
gramers = @getGrammars()
tmp_editor.setGrammar(gramers[0]) unless gramers[0] is undefined
# set the opened editor grammar, default is HTML
getGrammars: ->
grammars = atom.grammars.getGrammars().filter (grammar) ->
(grammar isnt atom.grammars.nullGrammar) and
grammar.name is 'Lua'
if !grammars
grammars = atom.grammars.getGrammars().filter (grammar) ->
(grammar isnt atom.grammars.nullGrammar) and
grammar.name is 'Emp View'
grammars
|
[
{
"context": "\t\t\t\t\tusername: 'd_' + uuid,\n\t\t\t\t\tpassword: currentApiKey,\n\t\t\t\t\tserveraddress: registry\n\t\t\t@dockerProgress.",
"end": 5222,
"score": 0.521144688129425,
"start": 5216,
"tag": "PASSWORD",
"value": "ApiKey"
},
{
"context": "rkGateway: (netName) =>\n\t\tr... | src/lib/docker-utils.coffee | hippolyt/resin-supervisor | 0 | constants = require './constants'
DockerToolbelt = require 'docker-toolbelt'
{ DockerProgress } = require 'docker-progress'
Promise = require 'bluebird'
dockerDelta = require 'docker-delta'
_ = require 'lodash'
{ request, resumable } = require './request'
{ envArrayToObject } = require './conversions'
{ DeltaStillProcessingError, InvalidNetGatewayError } = require './errors'
{ checkInt } = require './validation'
applyRsyncDelta = (imgSrc, deltaUrl, applyTimeout, opts, onProgress, log) ->
log('Applying rsync delta...')
new Promise (resolve, reject) ->
req = resumable(Object.assign({ url: deltaUrl }, opts))
.on('progress', onProgress)
.on('retry', onProgress)
.on('error', reject)
.on 'response', (res) ->
if res.statusCode isnt 200
reject(new Error("Got #{res.statusCode} when requesting delta from storage."))
else if parseInt(res.headers['content-length']) is 0
reject(new Error('Invalid delta URL.'))
else
deltaStream = dockerDelta.applyDelta(imgSrc, { log, timeout: applyTimeout })
res.pipe(deltaStream)
.on('id', (id) -> resolve('sha256:' + id))
.on 'error', (err) ->
log("Delta stream emitted error: #{err}")
req.abort(err)
reject(err)
applyBalenaDelta = (docker, deltaImg, token, onProgress, log) ->
log('Applying balena delta...')
if token?
log('Using registry auth token')
auth = { authconfig: registrytoken: token }
docker.dockerProgress.pull(deltaImg, onProgress, auth)
.then ->
docker.getImage(deltaImg).inspect().get('Id')
module.exports = class DockerUtils extends DockerToolbelt
constructor: (opts) ->
super(opts)
@dockerProgress = new DockerProgress(dockerToolbelt: this)
@supervisorTagPromise = @normaliseImageName(constants.supervisorImage)
getRepoAndTag: (image) =>
@getRegistryAndName(image)
.then ({ registry, imageName, tagName }) ->
if registry?
registry = registry.toString().replace(':443', '')
repoName = "#{registry}/#{imageName}"
else
repoName = imageName
return { repo: repoName, tag: tagName }
fetchDeltaWithProgress: (imgDest, fullDeltaOpts, onProgress) =>
{
deltaRequestTimeout, deltaApplyTimeout, deltaRetryCount, deltaRetryInterval,
uuid, currentApiKey, deltaEndpoint, apiEndpoint,
deltaSource, deltaSourceId, deltaVersion, startFromEmpty = false
} = fullDeltaOpts
retryCount = checkInt(deltaRetryCount)
retryInterval = checkInt(deltaRetryInterval)
requestTimeout = checkInt(deltaRequestTimeout)
applyTimeout = checkInt(deltaApplyTimeout)
version = checkInt(deltaVersion)
deltaSource = 'resin/scratch' if startFromEmpty or !deltaSource?
deltaSourceId ?= deltaSource
log = (str) ->
console.log("delta(#{deltaSource}): #{str}")
if not (version in [ 2, 3 ])
log("Unsupported delta version: #{version}. Falling back to regular pull")
return @fetchImageWithProgress(imgDest, fullDeltaOpts, onProgress)
docker = this
log("Starting delta to #{imgDest}")
Promise.join @getRegistryAndName(imgDest), @getRegistryAndName(deltaSource), (dstInfo, srcInfo) ->
tokenEndpoint = "#{apiEndpoint}/auth/v1/token"
opts =
auth:
user: 'd_' + uuid
pass: currentApiKey
sendImmediately: true
json: true
timeout: requestTimeout
url = "#{tokenEndpoint}?service=#{dstInfo.registry}&scope=repository:#{dstInfo.imageName}:pull&scope=repository:#{srcInfo.imageName}:pull"
request.getAsync(url, opts)
.get(1)
.then (responseBody) ->
token = responseBody?.token
opts =
followRedirect: false
timeout: requestTimeout
if token?
opts.auth =
bearer: token
sendImmediately: true
request.getAsync("#{deltaEndpoint}/api/v#{version}/delta?src=#{deltaSource}&dest=#{imgDest}", opts)
.spread (res, data) ->
if res.statusCode in [ 502, 504 ]
throw new DeltaStillProcessingError()
switch version
when 2
if not (300 <= res.statusCode < 400 and res.headers['location']?)
throw new Error("Got #{res.statusCode} when requesting image from delta server.")
deltaUrl = res.headers['location']
if deltaSource is 'resin/scratch'
deltaSrc = null
else
deltaSrc = deltaSourceId
resumeOpts = { timeout: requestTimeout, maxRetries: retryCount, retryInterval }
applyRsyncDelta(deltaSrc, deltaUrl, applyTimeout, resumeOpts, onProgress, log)
when 3
if res.statusCode isnt 200
throw new Error("Got #{res.statusCode} when requesting image from delta server.")
name = JSON.parse(data).name
applyBalenaDelta(docker, name, token, onProgress, log)
else
# we guard against arbitrary versions above, so this can't really happen
throw new Error("Unsupported delta version: #{version}")
.catch dockerDelta.OutOfSyncError, (err) =>
log('Falling back to regular pull')
@fetchImageWithProgress(imgDest, fullDeltaOpts, onProgress)
.tap ->
log('Delta applied successfully')
.tapCatch (err) ->
log("Delta failed with: #{err}")
fetchImageWithProgress: (image, { uuid, currentApiKey }, onProgress) =>
@getRegistryAndName(image)
.then ({ registry }) =>
dockerOptions =
authconfig:
username: 'd_' + uuid,
password: currentApiKey,
serveraddress: registry
@dockerProgress.pull(image, onProgress, dockerOptions)
.then =>
@getImage(image).inspect().get('Id')
getImageEnv: (id) ->
@getImage(id).inspect()
.get('Config').get('Env')
.then(envArrayToObject)
.catch (err) ->
console.log('Error getting env from image', err, err.stack)
return {}
getNetworkGateway: (netName) =>
return Promise.resolve('127.0.0.1') if netName == 'host'
@getNetwork(netName).inspect()
.then (netInfo) ->
conf = netInfo?.IPAM?.Config?[0]
return conf.Gateway if conf?.Gateway?
return conf.Subnet.replace('.0/16', '.1') if _.endsWith(conf?.Subnet, '.0/16')
throw new InvalidNetGatewayError("Cannot determine network gateway for #{netName}")
| 48259 | constants = require './constants'
DockerToolbelt = require 'docker-toolbelt'
{ DockerProgress } = require 'docker-progress'
Promise = require 'bluebird'
dockerDelta = require 'docker-delta'
_ = require 'lodash'
{ request, resumable } = require './request'
{ envArrayToObject } = require './conversions'
{ DeltaStillProcessingError, InvalidNetGatewayError } = require './errors'
{ checkInt } = require './validation'
applyRsyncDelta = (imgSrc, deltaUrl, applyTimeout, opts, onProgress, log) ->
log('Applying rsync delta...')
new Promise (resolve, reject) ->
req = resumable(Object.assign({ url: deltaUrl }, opts))
.on('progress', onProgress)
.on('retry', onProgress)
.on('error', reject)
.on 'response', (res) ->
if res.statusCode isnt 200
reject(new Error("Got #{res.statusCode} when requesting delta from storage."))
else if parseInt(res.headers['content-length']) is 0
reject(new Error('Invalid delta URL.'))
else
deltaStream = dockerDelta.applyDelta(imgSrc, { log, timeout: applyTimeout })
res.pipe(deltaStream)
.on('id', (id) -> resolve('sha256:' + id))
.on 'error', (err) ->
log("Delta stream emitted error: #{err}")
req.abort(err)
reject(err)
applyBalenaDelta = (docker, deltaImg, token, onProgress, log) ->
log('Applying balena delta...')
if token?
log('Using registry auth token')
auth = { authconfig: registrytoken: token }
docker.dockerProgress.pull(deltaImg, onProgress, auth)
.then ->
docker.getImage(deltaImg).inspect().get('Id')
module.exports = class DockerUtils extends DockerToolbelt
constructor: (opts) ->
super(opts)
@dockerProgress = new DockerProgress(dockerToolbelt: this)
@supervisorTagPromise = @normaliseImageName(constants.supervisorImage)
getRepoAndTag: (image) =>
@getRegistryAndName(image)
.then ({ registry, imageName, tagName }) ->
if registry?
registry = registry.toString().replace(':443', '')
repoName = "#{registry}/#{imageName}"
else
repoName = imageName
return { repo: repoName, tag: tagName }
fetchDeltaWithProgress: (imgDest, fullDeltaOpts, onProgress) =>
{
deltaRequestTimeout, deltaApplyTimeout, deltaRetryCount, deltaRetryInterval,
uuid, currentApiKey, deltaEndpoint, apiEndpoint,
deltaSource, deltaSourceId, deltaVersion, startFromEmpty = false
} = fullDeltaOpts
retryCount = checkInt(deltaRetryCount)
retryInterval = checkInt(deltaRetryInterval)
requestTimeout = checkInt(deltaRequestTimeout)
applyTimeout = checkInt(deltaApplyTimeout)
version = checkInt(deltaVersion)
deltaSource = 'resin/scratch' if startFromEmpty or !deltaSource?
deltaSourceId ?= deltaSource
log = (str) ->
console.log("delta(#{deltaSource}): #{str}")
if not (version in [ 2, 3 ])
log("Unsupported delta version: #{version}. Falling back to regular pull")
return @fetchImageWithProgress(imgDest, fullDeltaOpts, onProgress)
docker = this
log("Starting delta to #{imgDest}")
Promise.join @getRegistryAndName(imgDest), @getRegistryAndName(deltaSource), (dstInfo, srcInfo) ->
tokenEndpoint = "#{apiEndpoint}/auth/v1/token"
opts =
auth:
user: 'd_' + uuid
pass: currentApiKey
sendImmediately: true
json: true
timeout: requestTimeout
url = "#{tokenEndpoint}?service=#{dstInfo.registry}&scope=repository:#{dstInfo.imageName}:pull&scope=repository:#{srcInfo.imageName}:pull"
request.getAsync(url, opts)
.get(1)
.then (responseBody) ->
token = responseBody?.token
opts =
followRedirect: false
timeout: requestTimeout
if token?
opts.auth =
bearer: token
sendImmediately: true
request.getAsync("#{deltaEndpoint}/api/v#{version}/delta?src=#{deltaSource}&dest=#{imgDest}", opts)
.spread (res, data) ->
if res.statusCode in [ 502, 504 ]
throw new DeltaStillProcessingError()
switch version
when 2
if not (300 <= res.statusCode < 400 and res.headers['location']?)
throw new Error("Got #{res.statusCode} when requesting image from delta server.")
deltaUrl = res.headers['location']
if deltaSource is 'resin/scratch'
deltaSrc = null
else
deltaSrc = deltaSourceId
resumeOpts = { timeout: requestTimeout, maxRetries: retryCount, retryInterval }
applyRsyncDelta(deltaSrc, deltaUrl, applyTimeout, resumeOpts, onProgress, log)
when 3
if res.statusCode isnt 200
throw new Error("Got #{res.statusCode} when requesting image from delta server.")
name = JSON.parse(data).name
applyBalenaDelta(docker, name, token, onProgress, log)
else
# we guard against arbitrary versions above, so this can't really happen
throw new Error("Unsupported delta version: #{version}")
.catch dockerDelta.OutOfSyncError, (err) =>
log('Falling back to regular pull')
@fetchImageWithProgress(imgDest, fullDeltaOpts, onProgress)
.tap ->
log('Delta applied successfully')
.tapCatch (err) ->
log("Delta failed with: #{err}")
fetchImageWithProgress: (image, { uuid, currentApiKey }, onProgress) =>
@getRegistryAndName(image)
.then ({ registry }) =>
dockerOptions =
authconfig:
username: 'd_' + uuid,
password: current<PASSWORD>,
serveraddress: registry
@dockerProgress.pull(image, onProgress, dockerOptions)
.then =>
@getImage(image).inspect().get('Id')
getImageEnv: (id) ->
@getImage(id).inspect()
.get('Config').get('Env')
.then(envArrayToObject)
.catch (err) ->
console.log('Error getting env from image', err, err.stack)
return {}
getNetworkGateway: (netName) =>
return Promise.resolve('127.0.0.1') if netName == 'host'
@getNetwork(netName).inspect()
.then (netInfo) ->
conf = netInfo?.IPAM?.Config?[0]
return conf.Gateway if conf?.Gateway?
return conf.Subnet.replace('.0/16', '.1') if _.endsWith(conf?.Subnet, '.0/16')
throw new InvalidNetGatewayError("Cannot determine network gateway for #{netName}")
| true | constants = require './constants'
DockerToolbelt = require 'docker-toolbelt'
{ DockerProgress } = require 'docker-progress'
Promise = require 'bluebird'
dockerDelta = require 'docker-delta'
_ = require 'lodash'
{ request, resumable } = require './request'
{ envArrayToObject } = require './conversions'
{ DeltaStillProcessingError, InvalidNetGatewayError } = require './errors'
{ checkInt } = require './validation'
applyRsyncDelta = (imgSrc, deltaUrl, applyTimeout, opts, onProgress, log) ->
log('Applying rsync delta...')
new Promise (resolve, reject) ->
req = resumable(Object.assign({ url: deltaUrl }, opts))
.on('progress', onProgress)
.on('retry', onProgress)
.on('error', reject)
.on 'response', (res) ->
if res.statusCode isnt 200
reject(new Error("Got #{res.statusCode} when requesting delta from storage."))
else if parseInt(res.headers['content-length']) is 0
reject(new Error('Invalid delta URL.'))
else
deltaStream = dockerDelta.applyDelta(imgSrc, { log, timeout: applyTimeout })
res.pipe(deltaStream)
.on('id', (id) -> resolve('sha256:' + id))
.on 'error', (err) ->
log("Delta stream emitted error: #{err}")
req.abort(err)
reject(err)
applyBalenaDelta = (docker, deltaImg, token, onProgress, log) ->
log('Applying balena delta...')
if token?
log('Using registry auth token')
auth = { authconfig: registrytoken: token }
docker.dockerProgress.pull(deltaImg, onProgress, auth)
.then ->
docker.getImage(deltaImg).inspect().get('Id')
module.exports = class DockerUtils extends DockerToolbelt
constructor: (opts) ->
super(opts)
@dockerProgress = new DockerProgress(dockerToolbelt: this)
@supervisorTagPromise = @normaliseImageName(constants.supervisorImage)
getRepoAndTag: (image) =>
@getRegistryAndName(image)
.then ({ registry, imageName, tagName }) ->
if registry?
registry = registry.toString().replace(':443', '')
repoName = "#{registry}/#{imageName}"
else
repoName = imageName
return { repo: repoName, tag: tagName }
fetchDeltaWithProgress: (imgDest, fullDeltaOpts, onProgress) =>
{
deltaRequestTimeout, deltaApplyTimeout, deltaRetryCount, deltaRetryInterval,
uuid, currentApiKey, deltaEndpoint, apiEndpoint,
deltaSource, deltaSourceId, deltaVersion, startFromEmpty = false
} = fullDeltaOpts
retryCount = checkInt(deltaRetryCount)
retryInterval = checkInt(deltaRetryInterval)
requestTimeout = checkInt(deltaRequestTimeout)
applyTimeout = checkInt(deltaApplyTimeout)
version = checkInt(deltaVersion)
deltaSource = 'resin/scratch' if startFromEmpty or !deltaSource?
deltaSourceId ?= deltaSource
log = (str) ->
console.log("delta(#{deltaSource}): #{str}")
if not (version in [ 2, 3 ])
log("Unsupported delta version: #{version}. Falling back to regular pull")
return @fetchImageWithProgress(imgDest, fullDeltaOpts, onProgress)
docker = this
log("Starting delta to #{imgDest}")
Promise.join @getRegistryAndName(imgDest), @getRegistryAndName(deltaSource), (dstInfo, srcInfo) ->
tokenEndpoint = "#{apiEndpoint}/auth/v1/token"
opts =
auth:
user: 'd_' + uuid
pass: currentApiKey
sendImmediately: true
json: true
timeout: requestTimeout
url = "#{tokenEndpoint}?service=#{dstInfo.registry}&scope=repository:#{dstInfo.imageName}:pull&scope=repository:#{srcInfo.imageName}:pull"
request.getAsync(url, opts)
.get(1)
.then (responseBody) ->
token = responseBody?.token
opts =
followRedirect: false
timeout: requestTimeout
if token?
opts.auth =
bearer: token
sendImmediately: true
request.getAsync("#{deltaEndpoint}/api/v#{version}/delta?src=#{deltaSource}&dest=#{imgDest}", opts)
.spread (res, data) ->
if res.statusCode in [ 502, 504 ]
throw new DeltaStillProcessingError()
switch version
when 2
if not (300 <= res.statusCode < 400 and res.headers['location']?)
throw new Error("Got #{res.statusCode} when requesting image from delta server.")
deltaUrl = res.headers['location']
if deltaSource is 'resin/scratch'
deltaSrc = null
else
deltaSrc = deltaSourceId
resumeOpts = { timeout: requestTimeout, maxRetries: retryCount, retryInterval }
applyRsyncDelta(deltaSrc, deltaUrl, applyTimeout, resumeOpts, onProgress, log)
when 3
if res.statusCode isnt 200
throw new Error("Got #{res.statusCode} when requesting image from delta server.")
name = JSON.parse(data).name
applyBalenaDelta(docker, name, token, onProgress, log)
else
# we guard against arbitrary versions above, so this can't really happen
throw new Error("Unsupported delta version: #{version}")
.catch dockerDelta.OutOfSyncError, (err) =>
log('Falling back to regular pull')
@fetchImageWithProgress(imgDest, fullDeltaOpts, onProgress)
.tap ->
log('Delta applied successfully')
.tapCatch (err) ->
log("Delta failed with: #{err}")
fetchImageWithProgress: (image, { uuid, currentApiKey }, onProgress) =>
@getRegistryAndName(image)
.then ({ registry }) =>
dockerOptions =
authconfig:
username: 'd_' + uuid,
password: currentPI:PASSWORD:<PASSWORD>END_PI,
serveraddress: registry
@dockerProgress.pull(image, onProgress, dockerOptions)
.then =>
@getImage(image).inspect().get('Id')
getImageEnv: (id) ->
@getImage(id).inspect()
.get('Config').get('Env')
.then(envArrayToObject)
.catch (err) ->
console.log('Error getting env from image', err, err.stack)
return {}
getNetworkGateway: (netName) =>
return Promise.resolve('127.0.0.1') if netName == 'host'
@getNetwork(netName).inspect()
.then (netInfo) ->
conf = netInfo?.IPAM?.Config?[0]
return conf.Gateway if conf?.Gateway?
return conf.Subnet.replace('.0/16', '.1') if _.endsWith(conf?.Subnet, '.0/16')
throw new InvalidNetGatewayError("Cannot determine network gateway for #{netName}")
|
[
{
"context": "vices.remove done\n\n beforeEach ->\n @redisKey = uuid.v1()\n @jobManager = new JobManager\n client: ne",
"end": 634,
"score": 0.9531676173210144,
"start": 625,
"tag": "KEY",
"value": "uuid.v1()"
}
] | test/enqueue-for-sent-spec.coffee | octoblu/meshblu-core-manager-webhook | 0 | Datastore = require 'meshblu-core-datastore'
JobManager = require 'meshblu-core-job-manager'
mongojs = require 'mongojs'
redis = require 'fakeredis'
RedisNS = require '@octoblu/redis-ns'
uuid = require 'uuid'
{beforeEach, describe, it, sinon} = global
{expect} = require 'chai'
WebhookManager = require '../'
describe '->enqueueForSent', ->
beforeEach (done) ->
database = mongojs 'meshblu-core-manager-webhook', ['devices']
@datastore = new Datastore
database: database
collection: 'devices'
database.devices.remove done
beforeEach ->
@redisKey = uuid.v1()
@jobManager = new JobManager
client: new RedisNS 'ns', redis.createClient(@redisKey)
timeoutSeconds: 1
beforeEach ->
client = new RedisNS 'ns', redis.createClient(@redisKey)
jobManager = new JobManager {client: client, timeoutSeconds: 1}
@uuidAliasResolver = {resolve: sinon.stub()}
@sut = new WebhookManager {@datastore, jobManager, @uuidAliasResolver}
describe 'when the device has one webhooks', ->
beforeEach (done) ->
@datastore.insert {
uuid: 'uuid'
meshblu:
forwarders:
message:
sent: [{
type: 'webhook'
url: 'https://google.com'
method: 'POST'
}]
}, done
describe 'when called with two aliases that dont match', ->
beforeEach (done) ->
@uuidAliasResolver.resolve.withArgs('from').yields null, 'from'
@uuidAliasResolver.resolve.withArgs('to').yields null, 'uuid'
@uuidAliasResolver.resolve.withArgs('uuid').yields null, 'uuid'
@sut.enqueueForSent {
uuid: 'uuid'
route: [{type: 'message.sent', to: 'to', from: 'from'}]
forwardedRoutes: []
rawData: '{}'
type: 'message.sent'
}, done
it 'should enqueue a job to deliver the webhook', (done) ->
@jobManager.getRequest ['request'], (error, request) =>
return done error if error?
expect(request).to.containSubset {
metadata:
jobType: 'DeliverWebhook'
auth:
uuid: 'uuid'
fromUuid: 'uuid'
toUuid: 'uuid'
messageType: 'message.sent'
route: [{type: "message.sent", from: "from", to: "to"}]
forwardedRoutes: []
options:
type: 'webhook'
url: 'https://google.com'
method: 'POST'
rawData: '{}'
}
done()
describe 'when called with two aliases that match', ->
beforeEach (done) ->
@uuidAliasResolver.resolve.withArgs('from').yields null, 'uuid'
@uuidAliasResolver.resolve.withArgs('to').yields null, 'uuid'
@uuidAliasResolver.resolve.withArgs('uuid').yields null, 'uuid'
@sut.enqueueForSent {
uuid: 'uuid'
route: [{type: 'message.sent', to: 'to', from: 'from'}]
forwardedRoutes: []
rawData: '{}'
type: 'message.sent'
}, done
it 'should enqueue a job to deliver the webhook', (done) ->
@jobManager.getRequest ['request'], (error, request) =>
return done error if error?
expect(request).to.containSubset {
metadata:
jobType: 'DeliverWebhook'
auth:
uuid: 'uuid'
fromUuid: 'uuid'
toUuid: 'uuid'
messageType: 'message.sent'
route: [{type: "message.sent", from: "from", to: "to"}]
forwardedRoutes: []
options:
type: 'webhook'
url: 'https://google.com'
method: 'POST'
rawData: '{}'
}
done()
| 115301 | Datastore = require 'meshblu-core-datastore'
JobManager = require 'meshblu-core-job-manager'
mongojs = require 'mongojs'
redis = require 'fakeredis'
RedisNS = require '@octoblu/redis-ns'
uuid = require 'uuid'
{beforeEach, describe, it, sinon} = global
{expect} = require 'chai'
WebhookManager = require '../'
describe '->enqueueForSent', ->
beforeEach (done) ->
database = mongojs 'meshblu-core-manager-webhook', ['devices']
@datastore = new Datastore
database: database
collection: 'devices'
database.devices.remove done
beforeEach ->
@redisKey = <KEY>
@jobManager = new JobManager
client: new RedisNS 'ns', redis.createClient(@redisKey)
timeoutSeconds: 1
beforeEach ->
client = new RedisNS 'ns', redis.createClient(@redisKey)
jobManager = new JobManager {client: client, timeoutSeconds: 1}
@uuidAliasResolver = {resolve: sinon.stub()}
@sut = new WebhookManager {@datastore, jobManager, @uuidAliasResolver}
describe 'when the device has one webhooks', ->
beforeEach (done) ->
@datastore.insert {
uuid: 'uuid'
meshblu:
forwarders:
message:
sent: [{
type: 'webhook'
url: 'https://google.com'
method: 'POST'
}]
}, done
describe 'when called with two aliases that dont match', ->
beforeEach (done) ->
@uuidAliasResolver.resolve.withArgs('from').yields null, 'from'
@uuidAliasResolver.resolve.withArgs('to').yields null, 'uuid'
@uuidAliasResolver.resolve.withArgs('uuid').yields null, 'uuid'
@sut.enqueueForSent {
uuid: 'uuid'
route: [{type: 'message.sent', to: 'to', from: 'from'}]
forwardedRoutes: []
rawData: '{}'
type: 'message.sent'
}, done
it 'should enqueue a job to deliver the webhook', (done) ->
@jobManager.getRequest ['request'], (error, request) =>
return done error if error?
expect(request).to.containSubset {
metadata:
jobType: 'DeliverWebhook'
auth:
uuid: 'uuid'
fromUuid: 'uuid'
toUuid: 'uuid'
messageType: 'message.sent'
route: [{type: "message.sent", from: "from", to: "to"}]
forwardedRoutes: []
options:
type: 'webhook'
url: 'https://google.com'
method: 'POST'
rawData: '{}'
}
done()
describe 'when called with two aliases that match', ->
beforeEach (done) ->
@uuidAliasResolver.resolve.withArgs('from').yields null, 'uuid'
@uuidAliasResolver.resolve.withArgs('to').yields null, 'uuid'
@uuidAliasResolver.resolve.withArgs('uuid').yields null, 'uuid'
@sut.enqueueForSent {
uuid: 'uuid'
route: [{type: 'message.sent', to: 'to', from: 'from'}]
forwardedRoutes: []
rawData: '{}'
type: 'message.sent'
}, done
it 'should enqueue a job to deliver the webhook', (done) ->
@jobManager.getRequest ['request'], (error, request) =>
return done error if error?
expect(request).to.containSubset {
metadata:
jobType: 'DeliverWebhook'
auth:
uuid: 'uuid'
fromUuid: 'uuid'
toUuid: 'uuid'
messageType: 'message.sent'
route: [{type: "message.sent", from: "from", to: "to"}]
forwardedRoutes: []
options:
type: 'webhook'
url: 'https://google.com'
method: 'POST'
rawData: '{}'
}
done()
| true | Datastore = require 'meshblu-core-datastore'
JobManager = require 'meshblu-core-job-manager'
mongojs = require 'mongojs'
redis = require 'fakeredis'
RedisNS = require '@octoblu/redis-ns'
uuid = require 'uuid'
{beforeEach, describe, it, sinon} = global
{expect} = require 'chai'
WebhookManager = require '../'
describe '->enqueueForSent', ->
beforeEach (done) ->
database = mongojs 'meshblu-core-manager-webhook', ['devices']
@datastore = new Datastore
database: database
collection: 'devices'
database.devices.remove done
beforeEach ->
@redisKey = PI:KEY:<KEY>END_PI
@jobManager = new JobManager
client: new RedisNS 'ns', redis.createClient(@redisKey)
timeoutSeconds: 1
beforeEach ->
client = new RedisNS 'ns', redis.createClient(@redisKey)
jobManager = new JobManager {client: client, timeoutSeconds: 1}
@uuidAliasResolver = {resolve: sinon.stub()}
@sut = new WebhookManager {@datastore, jobManager, @uuidAliasResolver}
describe 'when the device has one webhooks', ->
beforeEach (done) ->
@datastore.insert {
uuid: 'uuid'
meshblu:
forwarders:
message:
sent: [{
type: 'webhook'
url: 'https://google.com'
method: 'POST'
}]
}, done
describe 'when called with two aliases that dont match', ->
beforeEach (done) ->
@uuidAliasResolver.resolve.withArgs('from').yields null, 'from'
@uuidAliasResolver.resolve.withArgs('to').yields null, 'uuid'
@uuidAliasResolver.resolve.withArgs('uuid').yields null, 'uuid'
@sut.enqueueForSent {
uuid: 'uuid'
route: [{type: 'message.sent', to: 'to', from: 'from'}]
forwardedRoutes: []
rawData: '{}'
type: 'message.sent'
}, done
it 'should enqueue a job to deliver the webhook', (done) ->
@jobManager.getRequest ['request'], (error, request) =>
return done error if error?
expect(request).to.containSubset {
metadata:
jobType: 'DeliverWebhook'
auth:
uuid: 'uuid'
fromUuid: 'uuid'
toUuid: 'uuid'
messageType: 'message.sent'
route: [{type: "message.sent", from: "from", to: "to"}]
forwardedRoutes: []
options:
type: 'webhook'
url: 'https://google.com'
method: 'POST'
rawData: '{}'
}
done()
describe 'when called with two aliases that match', ->
beforeEach (done) ->
@uuidAliasResolver.resolve.withArgs('from').yields null, 'uuid'
@uuidAliasResolver.resolve.withArgs('to').yields null, 'uuid'
@uuidAliasResolver.resolve.withArgs('uuid').yields null, 'uuid'
@sut.enqueueForSent {
uuid: 'uuid'
route: [{type: 'message.sent', to: 'to', from: 'from'}]
forwardedRoutes: []
rawData: '{}'
type: 'message.sent'
}, done
it 'should enqueue a job to deliver the webhook', (done) ->
@jobManager.getRequest ['request'], (error, request) =>
return done error if error?
expect(request).to.containSubset {
metadata:
jobType: 'DeliverWebhook'
auth:
uuid: 'uuid'
fromUuid: 'uuid'
toUuid: 'uuid'
messageType: 'message.sent'
route: [{type: "message.sent", from: "from", to: "to"}]
forwardedRoutes: []
options:
type: 'webhook'
url: 'https://google.com'
method: 'POST'
rawData: '{}'
}
done()
|
[
{
"context": " email = (app, req, res) ->\n mail = {\n from: \"Fred Foo ✔ <foo@blurdybloop.com>\",\n to: \"bar@blurdybloo",
"end": 119,
"score": 0.9998711943626404,
"start": 111,
"tag": "NAME",
"value": "Fred Foo"
},
{
"context": "p, req, res) ->\n mail = {\n from: \"Fred ... | dispatch/recipients/email.coffee | drewblas/consignment | 1 | # Log to console.log
util = require('util')
module.exports = email = (app, req, res) ->
mail = {
from: "Fred Foo ✔ <foo@blurdybloop.com>",
to: "bar@blurdybloop.com, baz@blurdybloop.com",
subject: "Hello ✔",
text: JSON.stringify(simple_request(req)),
}
app.smtp.sendMail mail, (error, response) ->
if error
console.warn error
else
console.log "Message sent: " + response.message
return "email" | 62874 | # Log to console.log
util = require('util')
module.exports = email = (app, req, res) ->
mail = {
from: "<NAME> ✔ <<EMAIL>>",
to: "<EMAIL>, <EMAIL>",
subject: "Hello ✔",
text: JSON.stringify(simple_request(req)),
}
app.smtp.sendMail mail, (error, response) ->
if error
console.warn error
else
console.log "Message sent: " + response.message
return "email" | true | # Log to console.log
util = require('util')
module.exports = email = (app, req, res) ->
mail = {
from: "PI:NAME:<NAME>END_PI ✔ <PI:EMAIL:<EMAIL>END_PI>",
to: "PI:EMAIL:<EMAIL>END_PI, PI:EMAIL:<EMAIL>END_PI",
subject: "Hello ✔",
text: JSON.stringify(simple_request(req)),
}
app.smtp.sendMail mail, (error, response) ->
if error
console.warn error
else
console.log "Message sent: " + response.message
return "email" |
[
{
"context": " 'should initialize', ->\n\t\tkm = new KM 'apiKey', 'evan@example.com'\n\t\tkm.apiKey.should.equal 'apiKey'\n\t\tkm.person.sh",
"end": 231,
"score": 0.9999135136604309,
"start": 215,
"tag": "EMAIL",
"value": "evan@example.com"
},
{
"context": "y.should.equal 'apiKey'\n\... | test/mocha/kissmetrics.coffee | evansolomon/kissmetrics-js | 1 | should = require 'should'
KM = require '../../src/kissmetrics'
describe 'KM module', ->
it 'should exist', ->
should.exist KM
describe 'KM instance', ->
it 'should initialize', ->
km = new KM 'apiKey', 'evan@example.com'
km.apiKey.should.equal 'apiKey'
km.person.should.equal 'evan@example.com'
it 'should be instance of KissmetricsClient', ->
km = new KM 'apiKey', 'evan@example.com'
km.should.be.an.instanceOf KM
it 'should have API methods', ->
km = new KM 'apiKey', 'evan@example.com'
km.should.have.property 'record'
km.should.have.property 'set'
km.should.have.property 'alias'
describe 'Record', ->
it 'should record events', ->
expectedOutput = /^GET \/?e\?_n=test%20event&_k=apiKey&_p=evan%40example\.com HTTP\/1\.1/
km = new KM 'apiKey', 'evan@example.com'
km.record('test event').queries.pop().output.pop().match(expectedOutput).should.be.ok
describe 'Set', ->
it 'should set properties', ->
expectedOutput = /GET \/?s\?place=home&_k=apiKey&_p=evan%40example\.com HTTP\/1\.1/
km = new KM 'apiKey', 'evan@example.com'
km.set({place: 'home'}).queries.pop().output.pop().match(expectedOutput).should.be.ok
it 'should set multiple properties', ->
expectedOutput = /GET \/?s\?place=home&otherPlace=work&_k=apiKey&_p=evan%40example\.com HTTP\/1\.1/
km = new KM 'apiKey', 'evan@example.com'
km.set({place: 'home', otherPlace: 'work'}).queries.pop().output.pop().match(expectedOutput).should.be.ok
describe 'Alias', ->
it 'should alias people', ->
expectedOutput = /GET \/?a\?_n=notevan%40example.com&_k=apiKey&_p=evan%40example\.com HTTP\/1\.1/
km = new KM 'apiKey', 'evan@example.com'
km.alias('notevan@example.com').queries.pop().output.pop().match(expectedOutput).should.be.ok
it 'should change person on alias', ->
km = new KM 'apiKey', 'evan@example.com'
km.alias 'someone@example.com'
km.person.should.be.equal 'someone@example.com'
describe 'Client API', ->
it 'should be chainable', ->
expectedOutput = /GET \/?a\?_n=notevan%40example.com&_k=apiKey&_p=evan%40example\.com HTTP\/1\.1/
km = new KM 'apiKey', 'evan@example.com'
km.record('foo').alias('notevan@example.com').queries.pop().output.pop().match(expectedOutput).should.be.ok
it 'should require apiKey', ->
km = new KM 'apiKey', 'evan@example.com'
delete km.apiKey
(-> km.record 'foo').should.throw "API key required"
it 'should require person', ->
km = new KM 'apiKey', 'evan@example.com'
delete km.person
(-> km.record 'foo').should.throw 'Person required'
describe 'Query log', ->
it 'should log all queries', ->
km = new KM 'apiKey', 'evan@example.com'
km.record('foo').record('bar').set({foo: 'bar'}).alias('someone else')
km.queries.length.should.be.equal 4
it 'should log queries in order', ->
km = new KM 'apiKey', 'evan@example.com'
km.record('foo')
firstQueryLogged = km.queries[0]
km.record('bar').set({foo: 'bar'}).alias('someone else')
km.queries[0].should.be.equal firstQueryLogged
| 218681 | should = require 'should'
KM = require '../../src/kissmetrics'
describe 'KM module', ->
it 'should exist', ->
should.exist KM
describe 'KM instance', ->
it 'should initialize', ->
km = new KM 'apiKey', '<EMAIL>'
km.apiKey.should.equal 'apiKey'
km.person.should.equal '<EMAIL>'
it 'should be instance of KissmetricsClient', ->
km = new KM 'apiKey', '<EMAIL>'
km.should.be.an.instanceOf KM
it 'should have API methods', ->
km = new KM 'apiKey', '<EMAIL>'
km.should.have.property 'record'
km.should.have.property 'set'
km.should.have.property 'alias'
describe 'Record', ->
it 'should record events', ->
expectedOutput = /^GET \/?e\?_n=test%20event&_k=apiKey&_p=evan%40example\.com HTTP\/1\.1/
km = new KM 'apiKey', '<EMAIL>'
km.record('test event').queries.pop().output.pop().match(expectedOutput).should.be.ok
describe 'Set', ->
it 'should set properties', ->
expectedOutput = /GET \/?s\?place=home&_k=apiKey&_p=evan%40example\.com HTTP\/1\.1/
km = new KM 'apiKey', '<EMAIL>'
km.set({place: 'home'}).queries.pop().output.pop().match(expectedOutput).should.be.ok
it 'should set multiple properties', ->
expectedOutput = /GET \/?s\?place=home&otherPlace=work&_k=apiKey&_p=evan%40example\.com HTTP\/1\.1/
km = new KM 'apiKey', '<EMAIL>'
km.set({place: 'home', otherPlace: 'work'}).queries.pop().output.pop().match(expectedOutput).should.be.ok
describe 'Alias', ->
it 'should alias people', ->
expectedOutput = /GET \/?a\?_n=notevan%40example.com&_k=apiKey&_p=evan%40example\.com HTTP\/1\.1/
km = new KM 'apiKey', '<EMAIL>'
km.alias('<EMAIL>').queries.pop().output.pop().match(expectedOutput).should.be.ok
it 'should change person on alias', ->
km = new KM 'apiKey', '<EMAIL>'
km.alias '<EMAIL>'
km.person.should.be.equal '<EMAIL>'
describe 'Client API', ->
it 'should be chainable', ->
expectedOutput = /GET \/?a\?_n=notevan%40example.com&_k=apiKey&_p=evan%40example\.com HTTP\/1\.1/
km = new KM 'apiKey', '<EMAIL>'
km.record('foo').alias('<EMAIL>').queries.pop().output.pop().match(expectedOutput).should.be.ok
it 'should require apiKey', ->
km = new KM 'apiKey', '<EMAIL>'
delete km.apiKey
(-> km.record 'foo').should.throw "API key required"
it 'should require person', ->
km = new KM 'apiKey', '<EMAIL>'
delete km.person
(-> km.record 'foo').should.throw 'Person required'
describe 'Query log', ->
it 'should log all queries', ->
km = new KM 'apiKey', '<EMAIL>'
km.record('foo').record('bar').set({foo: 'bar'}).alias('someone else')
km.queries.length.should.be.equal 4
it 'should log queries in order', ->
km = new KM 'apiKey', 'evan<EMAIL>'
km.record('foo')
firstQueryLogged = km.queries[0]
km.record('bar').set({foo: 'bar'}).alias('someone else')
km.queries[0].should.be.equal firstQueryLogged
| true | should = require 'should'
KM = require '../../src/kissmetrics'
describe 'KM module', ->
it 'should exist', ->
should.exist KM
describe 'KM instance', ->
it 'should initialize', ->
km = new KM 'apiKey', 'PI:EMAIL:<EMAIL>END_PI'
km.apiKey.should.equal 'apiKey'
km.person.should.equal 'PI:EMAIL:<EMAIL>END_PI'
it 'should be instance of KissmetricsClient', ->
km = new KM 'apiKey', 'PI:EMAIL:<EMAIL>END_PI'
km.should.be.an.instanceOf KM
it 'should have API methods', ->
km = new KM 'apiKey', 'PI:EMAIL:<EMAIL>END_PI'
km.should.have.property 'record'
km.should.have.property 'set'
km.should.have.property 'alias'
describe 'Record', ->
it 'should record events', ->
expectedOutput = /^GET \/?e\?_n=test%20event&_k=apiKey&_p=evan%40example\.com HTTP\/1\.1/
km = new KM 'apiKey', 'PI:EMAIL:<EMAIL>END_PI'
km.record('test event').queries.pop().output.pop().match(expectedOutput).should.be.ok
describe 'Set', ->
it 'should set properties', ->
expectedOutput = /GET \/?s\?place=home&_k=apiKey&_p=evan%40example\.com HTTP\/1\.1/
km = new KM 'apiKey', 'PI:EMAIL:<EMAIL>END_PI'
km.set({place: 'home'}).queries.pop().output.pop().match(expectedOutput).should.be.ok
it 'should set multiple properties', ->
expectedOutput = /GET \/?s\?place=home&otherPlace=work&_k=apiKey&_p=evan%40example\.com HTTP\/1\.1/
km = new KM 'apiKey', 'PI:EMAIL:<EMAIL>END_PI'
km.set({place: 'home', otherPlace: 'work'}).queries.pop().output.pop().match(expectedOutput).should.be.ok
describe 'Alias', ->
it 'should alias people', ->
expectedOutput = /GET \/?a\?_n=notevan%40example.com&_k=apiKey&_p=evan%40example\.com HTTP\/1\.1/
km = new KM 'apiKey', 'PI:EMAIL:<EMAIL>END_PI'
km.alias('PI:EMAIL:<EMAIL>END_PI').queries.pop().output.pop().match(expectedOutput).should.be.ok
it 'should change person on alias', ->
km = new KM 'apiKey', 'PI:EMAIL:<EMAIL>END_PI'
km.alias 'PI:EMAIL:<EMAIL>END_PI'
km.person.should.be.equal 'PI:EMAIL:<EMAIL>END_PI'
describe 'Client API', ->
it 'should be chainable', ->
expectedOutput = /GET \/?a\?_n=notevan%40example.com&_k=apiKey&_p=evan%40example\.com HTTP\/1\.1/
km = new KM 'apiKey', 'PI:EMAIL:<EMAIL>END_PI'
km.record('foo').alias('PI:EMAIL:<EMAIL>END_PI').queries.pop().output.pop().match(expectedOutput).should.be.ok
it 'should require apiKey', ->
km = new KM 'apiKey', 'PI:EMAIL:<EMAIL>END_PI'
delete km.apiKey
(-> km.record 'foo').should.throw "API key required"
it 'should require person', ->
km = new KM 'apiKey', 'PI:EMAIL:<EMAIL>END_PI'
delete km.person
(-> km.record 'foo').should.throw 'Person required'
describe 'Query log', ->
it 'should log all queries', ->
km = new KM 'apiKey', 'PI:EMAIL:<EMAIL>END_PI'
km.record('foo').record('bar').set({foo: 'bar'}).alias('someone else')
km.queries.length.should.be.equal 4
it 'should log queries in order', ->
km = new KM 'apiKey', 'evanPI:EMAIL:<EMAIL>END_PI'
km.record('foo')
firstQueryLogged = km.queries[0]
km.record('bar').set({foo: 'bar'}).alias('someone else')
km.queries[0].should.be.equal firstQueryLogged
|
[
{
"context": "'en', [])\n # _suggest('kni', 'en', [text: 'Swiss Army Knife'])\n # _suggest('offiz', 'de', [text: 'Schw",
"end": 5919,
"score": 0.9977371096611023,
"start": 5903,
"tag": "NAME",
"value": "Swiss Army Knife"
},
{
"context": "nife'])\n # _suggest('off... | src/spec/integration/products.spec.coffee | commercetools/sphere-node-sdk | 13 | debug = require('debug')('spec-integration:products')
_ = require 'underscore'
_.mixin require 'underscore-mixins'
Promise = require 'bluebird'
{SphereClient} = require '../../lib/main'
Config = require('../../config').config
uniqueId = (prefix) ->
_.uniqueId "#{prefix}#{new Date().getTime()}_"
newProductType = ->
name: 'Clothing'
description: 'A sample product type'
updateAttribute = (version) ->
version: version
actions: [
{
action: "addAttributeDefinition"
attribute:
type:
name: "enum"
values: [{key: "red", label: "Red"}, {key: "blue", label: "Blue"}]
name: "color"
label:
en: "Color"
attributeConstraint: "CombinationUnique"
isRequired: true
isSearchable: false
},
{
action: "addAttributeDefinition"
attribute:
type:
name: "enum"
values: [{key: "M", label: "Medium"}, {key: "L", label: "Large"}]
name: "size"
label:
en: "Size"
attributeConstraint: "CombinationUnique"
isRequired: true
isSearchable: false
}
]
newProduct = (pType) ->
name:
en: uniqueId 'product'
slug:
en: uniqueId 'slug'
productType:
id: pType.id
typeId: 'product-type'
masterVariant:
sku: uniqueId 'sku-'
newProductWithSearchKeywords = (pType) ->
_.extend newProduct(pType),
searchKeywords:
en: [
{text: 'Multi tool'}
{text: 'Swiss Army Knife', suggestTokenizer: {type: 'whitespace'}}
]
de: [
{text: 'Schweizer Messer', suggestTokenizer: {type: 'custom', inputs: ['schweizer messer', 'offiziersmesser', 'sackmesser']}}
]
updateUnpublish = (version) ->
version: version
actions: [
{action: "unpublish"}
]
updatePublish = (version) ->
version: version
actions: [
{action: "publish"}
]
describe 'Integration Products', ->
beforeEach (done) ->
@client = new SphereClient config: Config
debug 'Creating a ProductType'
@client.productTypes.save(newProductType())
.then (result) =>
expect(result.statusCode).toBe 201
@productType = result.body
debug 'Creating 50 products'
Promise.all _.map [1..50], => @client.products.save(newProduct(@productType))
.then (results) ->
debug "Created #{results.length} products"
done()
.catch (error) -> done(_.prettify(error))
, 20000 # 20sec
afterEach (done) ->
debug 'Unpublishing all products'
@client.products.sort('id').where('masterData(published = "true")').process (payload) =>
Promise.all _.map payload.body.results, (product) =>
@client.products.byId(product.id).update(updateUnpublish(product.version))
.then (results) =>
debug "Unpublished #{results.length} products"
debug 'About to delete all products'
@client.products.all().fetch()
.then (payload) =>
debug "Deleting #{payload.body.total} products"
Promise.all _.map payload.body.results, (product) =>
@client.products.byId(product.id).delete(product.version)
.then (results) =>
debug "Deleted #{results.length} products"
debug 'About to delete all product types'
@client.productTypes.all().fetch()
.then (payload) =>
debug "Deleting #{payload.body.total} product types"
Promise.all _.map payload.body.results, (productType) =>
@client.productTypes.byId(productType.id).delete(productType.version)
.then (results) ->
debug "Deleted #{results.length} product types"
done()
.catch (error) -> done(_.prettify(error))
, 60000 # 1min
it 'should publish all products', (done) ->
debug 'About to publish all products'
@client.products.sort('id')
.where('masterData(published = "false")')
.where('masterData(hasStagedChanges = "true")')
.whereOperator('or')
.process (payload) =>
Promise.all _.map payload.body.results, (product) =>
@client.products.byId(product.id).update(updatePublish(product.version))
.then (results) -> done()
.catch (error) -> done(_.prettify(error))
, 60000 # 1min
it 'should add attribute to product type', (done) ->
debug 'Creating attribute definitions'
@client.productTypes.byId(@productType.id).update(updateAttribute(@productType.version))
.then (result) ->
expect(result.statusCode).toBe 200
done()
.catch (error) -> done(_.prettify(error))
, 30000 # 30sec
it 'should use reference expansion when creating and updating a product', (done) ->
@client.products.expand('productType').create newProduct(@productType)
.then (result) =>
expect(result.body.productType.hasOwnProperty('obj')).toBe(true)
@client.products.expand('productType').byId(result.body.id).update updatePublish(result.body.version)
.then (result) ->
expect(result.body.productType.hasOwnProperty('obj')).toBe(true)
done()
.catch (error) -> done(_.prettify(error))
, 60000 # 60sec
# it 'should search for suggestions', (done) ->
# debug 'Creating products with search keywords'
# Promise.all _.map [1..5], => @client.products.save(newProductWithSearchKeywords(@productType))
#
# _suggest = (text, lang, expectedResult) =>
# new Promise (resolve, reject) =>
# debug 'searching for %s', text
# @client.productProjections
# .staged(true)
# .searchKeywords(text, lang)
# .suggest()
# .then (result) ->
# expect(result.statusCode).toBe 200
# expect(result.body["searchKeywords.#{lang}"]).toEqual expectedResult
# resolve()
# .catch (e) -> reject e
#
# # let's wait a bit to give ES time to create the index
# setTimeout ->
# Promise.all [
# _suggest('multi', 'en', [text: 'Multi tool'])
# _suggest('tool', 'en', [])
# _suggest('kni', 'en', [text: 'Swiss Army Knife'])
# _suggest('offiz', 'de', [text: 'Schweizer Messer'])
# ]
# .then -> done()
# .catch (error) -> done(_.prettify(error))
# , 5000 # 5sec
# , 30000 # 30sec
#
# it "should query using 'byQueryString'", (done) ->
# slugToLookFor = 'this-is-what-we-are-looking-for'
# # let's create a special product that we can securely query for
# @client.products.save(_.extend newProduct(@productType), {slug: {en: slugToLookFor}, masterVariant: {sku: '01234'}})
#
# # let's wait a bit to give ES time to create the index
# setTimeout =>
# # query for limit
# @client.productProjections.byQueryString('limit=3&staged=true', true).fetch()
# .then (result) =>
# expect(result.body.count).toBe 3
#
# # query for slug
# @client.productProjections.byQueryString("where=slug(en = \"#{slugToLookFor}\")&staged=true", false).fetch()
# .then (result) =>
# expect(result.body.count).toBe 1
# expect(result.body.results[0].slug.en).toBe slugToLookFor
#
# # search for sku
# @client.productProjections.byQueryString("text.en=01234&staged=true", false).search()
# .then (result) ->
# expect(result.body.count).toBe 1
# expect(result.body.results[0].slug.en).toBe slugToLookFor
# done()
# .catch (error) -> done(_.prettify(error))
# , 5000 # 5sec
# , 20000 # 20sec
#
# it 'should uses search endpoint', (done) ->
# slugToLookFor = 'this-is-what-we-are-looking-for'
# # let's create a special product that we can securely search for
# @client.products.save(_.extend newProduct(@productType), {slug: {en: slugToLookFor}})
#
# # let's wait a bit to give ES time to create the index
# setTimeout =>
# @client.productProjections.text('sku', 'en').staged(true).perPage(80).search()
# .then (result) =>
# expect(result.body.count).toBeGreaterThan 50
# expect(result.body.results.length).toBeGreaterThan 50
#
# @client.productProjections.text(slugToLookFor, 'en').staged(true).search()
# .then (result) ->
# expect(result.body.count).toBe 1
# expect(result.body.results[0].slug.en).toBe slugToLookFor
# done()
# .catch (error) -> done(_.prettify(error))
# , 5000 # 5sec
# , 20000 # 20sec
#
# it 'should search with full-text for special characters', (done) ->
# specialChar = 'äöüß'
# @client.products.save(_.extend newProduct(@productType), {name: {en: specialChar}})
#
# # let's wait a bit to give ES time to create the index
# setTimeout =>
# @client.productProjections
# .text(specialChar, 'en')
# .staged(true)
# .perPage(1)
# .search()
# .then (result) =>
# expect(result.body.count).toBe 1
# expect(result.body.results[0].name.en).toBe specialChar
# done()
# .catch (error) -> done(_.prettify(error))
# , 5000 # 5sec
# , 20000 # 20sec
| 152936 | debug = require('debug')('spec-integration:products')
_ = require 'underscore'
_.mixin require 'underscore-mixins'
Promise = require 'bluebird'
{SphereClient} = require '../../lib/main'
Config = require('../../config').config
uniqueId = (prefix) ->
_.uniqueId "#{prefix}#{new Date().getTime()}_"
newProductType = ->
name: 'Clothing'
description: 'A sample product type'
updateAttribute = (version) ->
version: version
actions: [
{
action: "addAttributeDefinition"
attribute:
type:
name: "enum"
values: [{key: "red", label: "Red"}, {key: "blue", label: "Blue"}]
name: "color"
label:
en: "Color"
attributeConstraint: "CombinationUnique"
isRequired: true
isSearchable: false
},
{
action: "addAttributeDefinition"
attribute:
type:
name: "enum"
values: [{key: "M", label: "Medium"}, {key: "L", label: "Large"}]
name: "size"
label:
en: "Size"
attributeConstraint: "CombinationUnique"
isRequired: true
isSearchable: false
}
]
newProduct = (pType) ->
name:
en: uniqueId 'product'
slug:
en: uniqueId 'slug'
productType:
id: pType.id
typeId: 'product-type'
masterVariant:
sku: uniqueId 'sku-'
newProductWithSearchKeywords = (pType) ->
_.extend newProduct(pType),
searchKeywords:
en: [
{text: 'Multi tool'}
{text: 'Swiss Army Knife', suggestTokenizer: {type: 'whitespace'}}
]
de: [
{text: 'Schweizer Messer', suggestTokenizer: {type: 'custom', inputs: ['schweizer messer', 'offiziersmesser', 'sackmesser']}}
]
updateUnpublish = (version) ->
version: version
actions: [
{action: "unpublish"}
]
updatePublish = (version) ->
version: version
actions: [
{action: "publish"}
]
describe 'Integration Products', ->
beforeEach (done) ->
@client = new SphereClient config: Config
debug 'Creating a ProductType'
@client.productTypes.save(newProductType())
.then (result) =>
expect(result.statusCode).toBe 201
@productType = result.body
debug 'Creating 50 products'
Promise.all _.map [1..50], => @client.products.save(newProduct(@productType))
.then (results) ->
debug "Created #{results.length} products"
done()
.catch (error) -> done(_.prettify(error))
, 20000 # 20sec
afterEach (done) ->
debug 'Unpublishing all products'
@client.products.sort('id').where('masterData(published = "true")').process (payload) =>
Promise.all _.map payload.body.results, (product) =>
@client.products.byId(product.id).update(updateUnpublish(product.version))
.then (results) =>
debug "Unpublished #{results.length} products"
debug 'About to delete all products'
@client.products.all().fetch()
.then (payload) =>
debug "Deleting #{payload.body.total} products"
Promise.all _.map payload.body.results, (product) =>
@client.products.byId(product.id).delete(product.version)
.then (results) =>
debug "Deleted #{results.length} products"
debug 'About to delete all product types'
@client.productTypes.all().fetch()
.then (payload) =>
debug "Deleting #{payload.body.total} product types"
Promise.all _.map payload.body.results, (productType) =>
@client.productTypes.byId(productType.id).delete(productType.version)
.then (results) ->
debug "Deleted #{results.length} product types"
done()
.catch (error) -> done(_.prettify(error))
, 60000 # 1min
it 'should publish all products', (done) ->
debug 'About to publish all products'
@client.products.sort('id')
.where('masterData(published = "false")')
.where('masterData(hasStagedChanges = "true")')
.whereOperator('or')
.process (payload) =>
Promise.all _.map payload.body.results, (product) =>
@client.products.byId(product.id).update(updatePublish(product.version))
.then (results) -> done()
.catch (error) -> done(_.prettify(error))
, 60000 # 1min
it 'should add attribute to product type', (done) ->
debug 'Creating attribute definitions'
@client.productTypes.byId(@productType.id).update(updateAttribute(@productType.version))
.then (result) ->
expect(result.statusCode).toBe 200
done()
.catch (error) -> done(_.prettify(error))
, 30000 # 30sec
it 'should use reference expansion when creating and updating a product', (done) ->
@client.products.expand('productType').create newProduct(@productType)
.then (result) =>
expect(result.body.productType.hasOwnProperty('obj')).toBe(true)
@client.products.expand('productType').byId(result.body.id).update updatePublish(result.body.version)
.then (result) ->
expect(result.body.productType.hasOwnProperty('obj')).toBe(true)
done()
.catch (error) -> done(_.prettify(error))
, 60000 # 60sec
# it 'should search for suggestions', (done) ->
# debug 'Creating products with search keywords'
# Promise.all _.map [1..5], => @client.products.save(newProductWithSearchKeywords(@productType))
#
# _suggest = (text, lang, expectedResult) =>
# new Promise (resolve, reject) =>
# debug 'searching for %s', text
# @client.productProjections
# .staged(true)
# .searchKeywords(text, lang)
# .suggest()
# .then (result) ->
# expect(result.statusCode).toBe 200
# expect(result.body["searchKeywords.#{lang}"]).toEqual expectedResult
# resolve()
# .catch (e) -> reject e
#
# # let's wait a bit to give ES time to create the index
# setTimeout ->
# Promise.all [
# _suggest('multi', 'en', [text: 'Multi tool'])
# _suggest('tool', 'en', [])
# _suggest('kni', 'en', [text: '<NAME>'])
# _suggest('offiz', 'de', [text: '<NAME>'])
# ]
# .then -> done()
# .catch (error) -> done(_.prettify(error))
# , 5000 # 5sec
# , 30000 # 30sec
#
# it "should query using 'byQueryString'", (done) ->
# slugToLookFor = 'this-is-what-we-are-looking-for'
# # let's create a special product that we can securely query for
# @client.products.save(_.extend newProduct(@productType), {slug: {en: slugToLookFor}, masterVariant: {sku: '01234'}})
#
# # let's wait a bit to give ES time to create the index
# setTimeout =>
# # query for limit
# @client.productProjections.byQueryString('limit=3&staged=true', true).fetch()
# .then (result) =>
# expect(result.body.count).toBe 3
#
# # query for slug
# @client.productProjections.byQueryString("where=slug(en = \"#{slugToLookFor}\")&staged=true", false).fetch()
# .then (result) =>
# expect(result.body.count).toBe 1
# expect(result.body.results[0].slug.en).toBe slugToLookFor
#
# # search for sku
# @client.productProjections.byQueryString("text.en=01234&staged=true", false).search()
# .then (result) ->
# expect(result.body.count).toBe 1
# expect(result.body.results[0].slug.en).toBe slugToLookFor
# done()
# .catch (error) -> done(_.prettify(error))
# , 5000 # 5sec
# , 20000 # 20sec
#
# it 'should uses search endpoint', (done) ->
# slugToLookFor = 'this-is-what-we-are-looking-for'
# # let's create a special product that we can securely search for
# @client.products.save(_.extend newProduct(@productType), {slug: {en: slugToLookFor}})
#
# # let's wait a bit to give ES time to create the index
# setTimeout =>
# @client.productProjections.text('sku', 'en').staged(true).perPage(80).search()
# .then (result) =>
# expect(result.body.count).toBeGreaterThan 50
# expect(result.body.results.length).toBeGreaterThan 50
#
# @client.productProjections.text(slugToLookFor, 'en').staged(true).search()
# .then (result) ->
# expect(result.body.count).toBe 1
# expect(result.body.results[0].slug.en).toBe slugToLookFor
# done()
# .catch (error) -> done(_.prettify(error))
# , 5000 # 5sec
# , 20000 # 20sec
#
# it 'should search with full-text for special characters', (done) ->
# specialChar = 'äöüß'
# @client.products.save(_.extend newProduct(@productType), {name: {en: specialChar}})
#
# # let's wait a bit to give ES time to create the index
# setTimeout =>
# @client.productProjections
# .text(specialChar, 'en')
# .staged(true)
# .perPage(1)
# .search()
# .then (result) =>
# expect(result.body.count).toBe 1
# expect(result.body.results[0].name.en).toBe specialChar
# done()
# .catch (error) -> done(_.prettify(error))
# , 5000 # 5sec
# , 20000 # 20sec
| true | debug = require('debug')('spec-integration:products')
_ = require 'underscore'
_.mixin require 'underscore-mixins'
Promise = require 'bluebird'
{SphereClient} = require '../../lib/main'
Config = require('../../config').config
uniqueId = (prefix) ->
_.uniqueId "#{prefix}#{new Date().getTime()}_"
newProductType = ->
name: 'Clothing'
description: 'A sample product type'
updateAttribute = (version) ->
version: version
actions: [
{
action: "addAttributeDefinition"
attribute:
type:
name: "enum"
values: [{key: "red", label: "Red"}, {key: "blue", label: "Blue"}]
name: "color"
label:
en: "Color"
attributeConstraint: "CombinationUnique"
isRequired: true
isSearchable: false
},
{
action: "addAttributeDefinition"
attribute:
type:
name: "enum"
values: [{key: "M", label: "Medium"}, {key: "L", label: "Large"}]
name: "size"
label:
en: "Size"
attributeConstraint: "CombinationUnique"
isRequired: true
isSearchable: false
}
]
newProduct = (pType) ->
name:
en: uniqueId 'product'
slug:
en: uniqueId 'slug'
productType:
id: pType.id
typeId: 'product-type'
masterVariant:
sku: uniqueId 'sku-'
newProductWithSearchKeywords = (pType) ->
_.extend newProduct(pType),
searchKeywords:
en: [
{text: 'Multi tool'}
{text: 'Swiss Army Knife', suggestTokenizer: {type: 'whitespace'}}
]
de: [
{text: 'Schweizer Messer', suggestTokenizer: {type: 'custom', inputs: ['schweizer messer', 'offiziersmesser', 'sackmesser']}}
]
updateUnpublish = (version) ->
version: version
actions: [
{action: "unpublish"}
]
updatePublish = (version) ->
version: version
actions: [
{action: "publish"}
]
describe 'Integration Products', ->
beforeEach (done) ->
@client = new SphereClient config: Config
debug 'Creating a ProductType'
@client.productTypes.save(newProductType())
.then (result) =>
expect(result.statusCode).toBe 201
@productType = result.body
debug 'Creating 50 products'
Promise.all _.map [1..50], => @client.products.save(newProduct(@productType))
.then (results) ->
debug "Created #{results.length} products"
done()
.catch (error) -> done(_.prettify(error))
, 20000 # 20sec
afterEach (done) ->
debug 'Unpublishing all products'
@client.products.sort('id').where('masterData(published = "true")').process (payload) =>
Promise.all _.map payload.body.results, (product) =>
@client.products.byId(product.id).update(updateUnpublish(product.version))
.then (results) =>
debug "Unpublished #{results.length} products"
debug 'About to delete all products'
@client.products.all().fetch()
.then (payload) =>
debug "Deleting #{payload.body.total} products"
Promise.all _.map payload.body.results, (product) =>
@client.products.byId(product.id).delete(product.version)
.then (results) =>
debug "Deleted #{results.length} products"
debug 'About to delete all product types'
@client.productTypes.all().fetch()
.then (payload) =>
debug "Deleting #{payload.body.total} product types"
Promise.all _.map payload.body.results, (productType) =>
@client.productTypes.byId(productType.id).delete(productType.version)
.then (results) ->
debug "Deleted #{results.length} product types"
done()
.catch (error) -> done(_.prettify(error))
, 60000 # 1min
it 'should publish all products', (done) ->
debug 'About to publish all products'
@client.products.sort('id')
.where('masterData(published = "false")')
.where('masterData(hasStagedChanges = "true")')
.whereOperator('or')
.process (payload) =>
Promise.all _.map payload.body.results, (product) =>
@client.products.byId(product.id).update(updatePublish(product.version))
.then (results) -> done()
.catch (error) -> done(_.prettify(error))
, 60000 # 1min
it 'should add attribute to product type', (done) ->
debug 'Creating attribute definitions'
@client.productTypes.byId(@productType.id).update(updateAttribute(@productType.version))
.then (result) ->
expect(result.statusCode).toBe 200
done()
.catch (error) -> done(_.prettify(error))
, 30000 # 30sec
it 'should use reference expansion when creating and updating a product', (done) ->
@client.products.expand('productType').create newProduct(@productType)
.then (result) =>
expect(result.body.productType.hasOwnProperty('obj')).toBe(true)
@client.products.expand('productType').byId(result.body.id).update updatePublish(result.body.version)
.then (result) ->
expect(result.body.productType.hasOwnProperty('obj')).toBe(true)
done()
.catch (error) -> done(_.prettify(error))
, 60000 # 60sec
# it 'should search for suggestions', (done) ->
# debug 'Creating products with search keywords'
# Promise.all _.map [1..5], => @client.products.save(newProductWithSearchKeywords(@productType))
#
# _suggest = (text, lang, expectedResult) =>
# new Promise (resolve, reject) =>
# debug 'searching for %s', text
# @client.productProjections
# .staged(true)
# .searchKeywords(text, lang)
# .suggest()
# .then (result) ->
# expect(result.statusCode).toBe 200
# expect(result.body["searchKeywords.#{lang}"]).toEqual expectedResult
# resolve()
# .catch (e) -> reject e
#
# # let's wait a bit to give ES time to create the index
# setTimeout ->
# Promise.all [
# _suggest('multi', 'en', [text: 'Multi tool'])
# _suggest('tool', 'en', [])
# _suggest('kni', 'en', [text: 'PI:NAME:<NAME>END_PI'])
# _suggest('offiz', 'de', [text: 'PI:NAME:<NAME>END_PI'])
# ]
# .then -> done()
# .catch (error) -> done(_.prettify(error))
# , 5000 # 5sec
# , 30000 # 30sec
#
# it "should query using 'byQueryString'", (done) ->
# slugToLookFor = 'this-is-what-we-are-looking-for'
# # let's create a special product that we can securely query for
# @client.products.save(_.extend newProduct(@productType), {slug: {en: slugToLookFor}, masterVariant: {sku: '01234'}})
#
# # let's wait a bit to give ES time to create the index
# setTimeout =>
# # query for limit
# @client.productProjections.byQueryString('limit=3&staged=true', true).fetch()
# .then (result) =>
# expect(result.body.count).toBe 3
#
# # query for slug
# @client.productProjections.byQueryString("where=slug(en = \"#{slugToLookFor}\")&staged=true", false).fetch()
# .then (result) =>
# expect(result.body.count).toBe 1
# expect(result.body.results[0].slug.en).toBe slugToLookFor
#
# # search for sku
# @client.productProjections.byQueryString("text.en=01234&staged=true", false).search()
# .then (result) ->
# expect(result.body.count).toBe 1
# expect(result.body.results[0].slug.en).toBe slugToLookFor
# done()
# .catch (error) -> done(_.prettify(error))
# , 5000 # 5sec
# , 20000 # 20sec
#
# it 'should uses search endpoint', (done) ->
# slugToLookFor = 'this-is-what-we-are-looking-for'
# # let's create a special product that we can securely search for
# @client.products.save(_.extend newProduct(@productType), {slug: {en: slugToLookFor}})
#
# # let's wait a bit to give ES time to create the index
# setTimeout =>
# @client.productProjections.text('sku', 'en').staged(true).perPage(80).search()
# .then (result) =>
# expect(result.body.count).toBeGreaterThan 50
# expect(result.body.results.length).toBeGreaterThan 50
#
# @client.productProjections.text(slugToLookFor, 'en').staged(true).search()
# .then (result) ->
# expect(result.body.count).toBe 1
# expect(result.body.results[0].slug.en).toBe slugToLookFor
# done()
# .catch (error) -> done(_.prettify(error))
# , 5000 # 5sec
# , 20000 # 20sec
#
# it 'should search with full-text for special characters', (done) ->
# specialChar = 'äöüß'
# @client.products.save(_.extend newProduct(@productType), {name: {en: specialChar}})
#
# # let's wait a bit to give ES time to create the index
# setTimeout =>
# @client.productProjections
# .text(specialChar, 'en')
# .staged(true)
# .perPage(1)
# .search()
# .then (result) =>
# expect(result.body.count).toBe 1
# expect(result.body.results[0].name.en).toBe specialChar
# done()
# .catch (error) -> done(_.prettify(error))
# , 5000 # 5sec
# , 20000 # 20sec
|
[
{
"context": "###\n * gulp-supervisor\n * https://github.com/leny/gulp-supervisor\n *\n * Copyright (c) 2014 Leny\n * ",
"end": 49,
"score": 0.9995951652526855,
"start": 45,
"tag": "USERNAME",
"value": "leny"
},
{
"context": ".com/leny/gulp-supervisor\n *\n * Copyright (c) 2014 Leny\... | node_modules/gulp-supervisor/index.coffee | PLopezD/boilerplate-node | 13 | ###
* gulp-supervisor
* https://github.com/leny/gulp-supervisor
*
* Copyright (c) 2014 Leny
* Licensed under the MIT license.
###
"use strict"
supervisor = require "supervisor"
# --- kindOf
# cf. grunt.util.kindOf
kindsOf = {}
"Number String Boolean Function RegExp Array Date Error".split( " " ).forEach (k) ->
kindsOf[ "[object #{ k }]"] = k.toLowerCase()
kindOf = ( value ) ->
return String value unless value?
kindsOf[ kindsOf.toString.call( value ) ] or "object"
module.exports = ( sScript, oOptions = {} ) ->
aOptions = []
aOptions.push "--watch", oOptions.watch.join "," if kindOf( oOptions.watch ) is "array"
aOptions.push "--ignore", oOptions.ignore.join "," if kindOf( oOptions.ignore ) is "array"
aOptions.push "--extensions", oOptions.extensions.join "," if kindOf( oOptions.extensions ) is "array"
aOptions.push "--exec", oOptions.exec if kindOf( oOptions.exec ) is "string"
aOptions.push "--poll-interval", "#{ oOptions.pollInterval }" if kindOf( oOptions.pollInterval ) is "number"
aOptions.push "--no-restart-on", oOptions.noRestartOn if kindOf( oOptions.noRestartOn ) is "string" and ( oOptions.noRestartOn is "error" or oOptions.noRestartOn is "exit" )
aOptions.push "--debug" if oOptions.debug is yes
aOptions.push "--debug-brk" if oOptions.debugBrk is yes
aOptions.push "--harmony" if oOptions.harmony is yes
aOptions.push "--force-watch" if oOptions.forceWatch is yes
aOptions.push "--quiet" if oOptions.quiet is yes
aOptions.push "--", sScript
aOptions.push oOptions.args... if kindOf( oOptions.args ) is "array"
supervisor.run aOptions
| 46631 | ###
* gulp-supervisor
* https://github.com/leny/gulp-supervisor
*
* Copyright (c) 2014 <NAME>
* Licensed under the MIT license.
###
"use strict"
supervisor = require "supervisor"
# --- kindOf
# cf. grunt.util.kindOf
kindsOf = {}
"Number String Boolean Function RegExp Array Date Error".split( " " ).forEach (k) ->
kindsOf[ "[object #{ k }]"] = k.toLowerCase()
kindOf = ( value ) ->
return String value unless value?
kindsOf[ kindsOf.toString.call( value ) ] or "object"
module.exports = ( sScript, oOptions = {} ) ->
aOptions = []
aOptions.push "--watch", oOptions.watch.join "," if kindOf( oOptions.watch ) is "array"
aOptions.push "--ignore", oOptions.ignore.join "," if kindOf( oOptions.ignore ) is "array"
aOptions.push "--extensions", oOptions.extensions.join "," if kindOf( oOptions.extensions ) is "array"
aOptions.push "--exec", oOptions.exec if kindOf( oOptions.exec ) is "string"
aOptions.push "--poll-interval", "#{ oOptions.pollInterval }" if kindOf( oOptions.pollInterval ) is "number"
aOptions.push "--no-restart-on", oOptions.noRestartOn if kindOf( oOptions.noRestartOn ) is "string" and ( oOptions.noRestartOn is "error" or oOptions.noRestartOn is "exit" )
aOptions.push "--debug" if oOptions.debug is yes
aOptions.push "--debug-brk" if oOptions.debugBrk is yes
aOptions.push "--harmony" if oOptions.harmony is yes
aOptions.push "--force-watch" if oOptions.forceWatch is yes
aOptions.push "--quiet" if oOptions.quiet is yes
aOptions.push "--", sScript
aOptions.push oOptions.args... if kindOf( oOptions.args ) is "array"
supervisor.run aOptions
| true | ###
* gulp-supervisor
* https://github.com/leny/gulp-supervisor
*
* Copyright (c) 2014 PI:NAME:<NAME>END_PI
* Licensed under the MIT license.
###
"use strict"
supervisor = require "supervisor"
# --- kindOf
# cf. grunt.util.kindOf
kindsOf = {}
"Number String Boolean Function RegExp Array Date Error".split( " " ).forEach (k) ->
kindsOf[ "[object #{ k }]"] = k.toLowerCase()
kindOf = ( value ) ->
return String value unless value?
kindsOf[ kindsOf.toString.call( value ) ] or "object"
module.exports = ( sScript, oOptions = {} ) ->
aOptions = []
aOptions.push "--watch", oOptions.watch.join "," if kindOf( oOptions.watch ) is "array"
aOptions.push "--ignore", oOptions.ignore.join "," if kindOf( oOptions.ignore ) is "array"
aOptions.push "--extensions", oOptions.extensions.join "," if kindOf( oOptions.extensions ) is "array"
aOptions.push "--exec", oOptions.exec if kindOf( oOptions.exec ) is "string"
aOptions.push "--poll-interval", "#{ oOptions.pollInterval }" if kindOf( oOptions.pollInterval ) is "number"
aOptions.push "--no-restart-on", oOptions.noRestartOn if kindOf( oOptions.noRestartOn ) is "string" and ( oOptions.noRestartOn is "error" or oOptions.noRestartOn is "exit" )
aOptions.push "--debug" if oOptions.debug is yes
aOptions.push "--debug-brk" if oOptions.debugBrk is yes
aOptions.push "--harmony" if oOptions.harmony is yes
aOptions.push "--force-watch" if oOptions.forceWatch is yes
aOptions.push "--quiet" if oOptions.quiet is yes
aOptions.push "--", sScript
aOptions.push oOptions.args... if kindOf( oOptions.args ) is "array"
supervisor.run aOptions
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9993203282356262,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | lib/freelist.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
"use strict"
# This is a free list to avoid creating so many of the same object.
exports.FreeList = (name, max, constructor) ->
@name = name
@constructor = constructor
@max = max
@list = []
return
exports.FreeList::alloc = ->
#debug("alloc " + this.name + " " + this.list.length);
(if @list.length then @list.shift() else @constructor.apply(this, arguments))
exports.FreeList::free = (obj) ->
#debug("free " + this.name + " " + this.list.length);
if @list.length < @max
@list.push obj
return true
false
| 158183 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
"use strict"
# This is a free list to avoid creating so many of the same object.
exports.FreeList = (name, max, constructor) ->
@name = name
@constructor = constructor
@max = max
@list = []
return
exports.FreeList::alloc = ->
#debug("alloc " + this.name + " " + this.list.length);
(if @list.length then @list.shift() else @constructor.apply(this, arguments))
exports.FreeList::free = (obj) ->
#debug("free " + this.name + " " + this.list.length);
if @list.length < @max
@list.push obj
return true
false
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
"use strict"
# This is a free list to avoid creating so many of the same object.
exports.FreeList = (name, max, constructor) ->
@name = name
@constructor = constructor
@max = max
@list = []
return
exports.FreeList::alloc = ->
#debug("alloc " + this.name + " " + this.list.length);
(if @list.length then @list.shift() else @constructor.apply(this, arguments))
exports.FreeList::free = (obj) ->
#debug("free " + this.name + " " + this.list.length);
if @list.length < @max
@list.push obj
return true
false
|
[
{
"context": " \"omni\", \"tabs\", or \"bookmarks\".\n constructor: (@name) ->\n @port = chrome.runtime.connect name: \"com",
"end": 11280,
"score": 0.9395833015441895,
"start": 11276,
"tag": "USERNAME",
"value": "name"
},
{
"context": "xtend request,\n handler: \"filter\"\n... | pages/vomnibar.coffee | xc8tlik/vimium | 1 | #
# This controls the contents of the Vomnibar iframe. We use an iframe to avoid changing the selection on the
# page (useful for bookmarklets), ensure that the Vomnibar style is unaffected by the page, and simplify key
# handling in vimium_frontend.coffee
#
Vomnibar =
vomnibarUI: null # the dialog instance for this window
getUI: -> @vomnibarUI
completers: {}
getCompleter: (name) ->
@completers[name] ?= new BackgroundCompleter name
activate: (userOptions) ->
options =
completer: "omni"
query: ""
newTab: false
selectFirst: false
keyword: null
extend options, userOptions
extend options, refreshInterval: if options.completer == "omni" then 150 else 0
completer = @getCompleter options.completer
@vomnibarUI ?= new VomnibarUI()
completer.refresh @vomnibarUI
@vomnibarUI.setInitialSelectionValue if options.selectFirst then 0 else -1
@vomnibarUI.setCompleter completer
@vomnibarUI.setRefreshInterval options.refreshInterval
@vomnibarUI.setForceNewTab options.newTab
@vomnibarUI.setQuery options.query
@vomnibarUI.setKeyword options.keyword
@vomnibarUI.update true
hide: -> @vomnibarUI?.hide()
onHidden: -> @vomnibarUI?.onHidden()
class VomnibarUI
constructor: ->
@refreshInterval = 0
@postHideCallback = null
@initDom()
setQuery: (query) -> @input.value = query
setKeyword: (keyword) -> @customSearchMode = keyword
setInitialSelectionValue: (@initialSelectionValue) ->
setRefreshInterval: (@refreshInterval) ->
setForceNewTab: (@forceNewTab) ->
setCompleter: (@completer) -> @reset()
setKeywords: (@keywords) ->
# The sequence of events when the vomnibar is hidden is as follows:
# 1. Post a "hide" message to the host page.
# 2. The host page hides the vomnibar.
# 3. When that page receives the focus, and it posts back a "hidden" message.
# 3. Only once the "hidden" message is received here is any required action invoked (in onHidden).
# This ensures that the vomnibar is actually hidden before any new tab is created, and avoids flicker after
# opening a link in a new tab then returning to the original tab (see #1485).
hide: (@postHideCallback = null) ->
UIComponentServer.postMessage "hide"
@reset()
@completer?.reset()
onHidden: ->
@postHideCallback?()
@postHideCallback = null
reset: ->
@clearUpdateTimer()
@completionList.style.display = ""
@input.value = ""
@completions = []
@previousInputValue = null
@customSearchMode = null
@selection = @initialSelectionValue
@keywords = []
@seenTabToOpenCompletionList = false
updateSelection: ->
# For custom search engines, we suppress the leading term (e.g. the "w" of "w query terms") within the
# vomnibar input.
if @lastReponse.isCustomSearch and not @customSearchMode?
queryTerms = @input.value.trim().split /\s+/
@customSearchMode = queryTerms[0]
@input.value = queryTerms[1..].join " "
# For suggestions for custom search engines, we copy the suggested text into the input when the item is
# selected, and revert when it is not. This allows the user to select a suggestion and then continue
# typing.
if 0 <= @selection and @completions[@selection].insertText?
@previousInputValue ?= @input.value
@input.value = @completions[@selection].insertText
else if @previousInputValue?
@input.value = @previousInputValue
@previousInputValue = null
# Highlight the selected entry, and only the selected entry.
for i in [0...@completionList.children.length]
@completionList.children[i].className = (if i == @selection then "vomnibarSelected" else "")
# Returns the user's action ("up", "down", "tab", etc, or null) based on their keypress. We support the
# arrow keys and various other shortcuts, and this function hides the event-decoding complexity.
actionFromKeyEvent: (event) ->
key = KeyboardUtils.getKeyChar(event)
if (KeyboardUtils.isEscape(event))
return "dismiss"
else if (key == "up" ||
(event.shiftKey && event.keyCode == keyCodes.tab) ||
(event.ctrlKey && (key == "k" || key == "p")))
return "up"
else if (event.keyCode == keyCodes.tab && !event.shiftKey)
return "tab"
else if (key == "down" ||
(event.ctrlKey && (key == "j" || key == "n")))
return "down"
else if (event.keyCode == keyCodes.enter)
return "enter"
else if event.keyCode == keyCodes.backspace || event.keyCode == keyCodes.deleteKey
return "delete"
null
onKeydown: (event) =>
@lastAction = action = @actionFromKeyEvent event
return true unless action # pass through
openInNewTab = @forceNewTab ||
(event.shiftKey || event.ctrlKey || event.altKey || KeyboardUtils.isPrimaryModifierKey(event))
if (action == "dismiss")
@hide()
else if action in [ "tab", "down" ]
if action == "tab" and
@completer.name == "omni" and
not @seenTabToOpenCompletionList and
@input.value.trim().length == 0
@seenTabToOpenCompletionList = true
@update true
else
@selection += 1
@selection = @initialSelectionValue if @selection == @completions.length
@updateSelection()
else if (action == "up")
@selection -= 1
@selection = @completions.length - 1 if @selection < @initialSelectionValue
@updateSelection()
else if (action == "enter")
isCustomSearchPrimarySuggestion = @completions[@selection]?.isPrimarySuggestion and @lastReponse.engine?.searchUrl?
if @selection == -1 or isCustomSearchPrimarySuggestion
query = @input.value.trim()
# <Enter> on an empty query is a no-op.
return unless 0 < query.length
# First case (@selection == -1).
# If the user types something and hits enter without selecting a completion from the list, then:
# - If a search URL has been provided, then use it. This is custom search engine request.
# - Otherwise, send the query to the background page, which will open it as a URL or create a
# default search, as appropriate.
#
# Second case (isCustomSearchPrimarySuggestion).
# Alternatively, the selected completion could be the primary selection for a custom search engine.
# Because the the suggestions are updated asynchronously in omni mode, the user may have typed more
# text than that which is included in the URL associated with the primary suggestion. Therefore, to
# avoid a race condition, we construct the query from the actual contents of the input (query).
query = Utils.createSearchUrl query, @lastReponse.engine.searchUrl if isCustomSearchPrimarySuggestion
@hide ->
chrome.runtime.sendMessage
handler: if openInNewTab then "openUrlInNewTab" else "openUrlInCurrentTab"
url: query
else
completion = @completions[@selection]
@hide -> completion.performAction openInNewTab
else if action == "delete"
if @customSearchMode? and @input.selectionEnd == 0
# Normally, with custom search engines, the keyword (e,g, the "w" of "w query terms") is suppressed.
# If the cursor is at the start of the input, then reinstate the keyword (the "w").
@input.value = @customSearchMode + @input.value.ltrim()
@input.selectionStart = @input.selectionEnd = @customSearchMode.length
@customSearchMode = null
@update true
else if @seenTabToOpenCompletionList and @input.value.trim().length == 0
@seenTabToOpenCompletionList = false
@update true
else
return true # Do not suppress event.
# It seems like we have to manually suppress the event here and still return true.
event.stopImmediatePropagation()
event.preventDefault()
true
# Return the background-page query corresponding to the current input state. In other words, reinstate any
# search engine keyword which is currently being suppressed, and strip any prompted text.
getInputValueAsQuery: ->
(if @customSearchMode? then @customSearchMode + " " else "") + @input.value
updateCompletions: (callback = null) ->
@completer.filter
query: @getInputValueAsQuery()
seenTabToOpenCompletionList: @seenTabToOpenCompletionList
callback: (@lastReponse) =>
{ results } = @lastReponse
@completions = results
@selection = if @completions[0]?.autoSelect then 0 else @initialSelectionValue
# Update completion list with the new suggestions.
@completionList.innerHTML = @completions.map((completion) -> "<li>#{completion.html}</li>").join("")
@completionList.style.display = if @completions.length > 0 then "block" else ""
@selection = Math.min @completions.length - 1, Math.max @initialSelectionValue, @selection
@updateSelection()
callback?()
onInput: =>
@seenTabToOpenCompletionList = false
@completer.cancel()
if 0 <= @selection and @completions[@selection].customSearchMode and not @customSearchMode
@customSearchMode = @completions[@selection].customSearchMode
updateSynchronously = true
# If the user types, then don't reset any previous text, and reset the selection.
if @previousInputValue?
@previousInputValue = null
@selection = -1
@update updateSynchronously
clearUpdateTimer: ->
if @updateTimer?
window.clearTimeout @updateTimer
@updateTimer = null
shouldActivateCustomSearchMode: ->
queryTerms = @input.value.ltrim().split /\s+/
1 < queryTerms.length and queryTerms[0] in @keywords and not @customSearchMode
update: (updateSynchronously = false, callback = null) =>
# If the query text becomes a custom search (the user enters a search keyword), then we need to force a
# synchronous update (so that the state is updated immediately).
updateSynchronously ||= @shouldActivateCustomSearchMode()
if updateSynchronously
@clearUpdateTimer()
@updateCompletions callback
else if not @updateTimer?
# Update asynchronously for a better user experience, and to take some load off the CPU (not every
# keystroke will cause a dedicated update).
@updateTimer = Utils.setTimeout @refreshInterval, =>
@updateTimer = null
@updateCompletions callback
@input.focus()
initDom: ->
@box = document.getElementById("vomnibar")
@input = @box.querySelector("input")
@input.addEventListener "input", @onInput
@input.addEventListener "keydown", @onKeydown
@completionList = @box.querySelector("ul")
@completionList.style.display = ""
window.addEventListener "focus", => @input.focus()
# A click in the vomnibar itself refocuses the input.
@box.addEventListener "click", (event) =>
@input.focus()
event.stopImmediatePropagation()
# A click anywhere else hides the vomnibar.
document.body.addEventListener "click", => @hide()
#
# Sends requests to a Vomnibox completer on the background page.
#
class BackgroundCompleter
# The "name" is the background-page completer to connect to: "omni", "tabs", or "bookmarks".
constructor: (@name) ->
@port = chrome.runtime.connect name: "completions"
@messageId = null
@reset()
@port.onMessage.addListener (msg) =>
switch msg.handler
when "keywords"
@keywords = msg.keywords
@lastUI.setKeywords @keywords
when "completions"
if msg.id == @messageId
# The result objects coming from the background page will be of the form:
# { html: "", type: "", url: "", ... }
# Type will be one of [tab, bookmark, history, domain, search], or a custom search engine description.
for result in msg.results
extend result,
performAction:
if result.type == "tab"
@completionActions.switchToTab result.tabId
else
@completionActions.navigateToUrl result.url
# Handle the message, but only if it hasn't arrived too late.
@mostRecentCallback msg
filter: (request) ->
{ query, callback } = request
@mostRecentCallback = callback
@port.postMessage extend request,
handler: "filter"
name: @name
id: @messageId = Utils.createUniqueId()
queryTerms: query.trim().split(/\s+/).filter (s) -> 0 < s.length
# We don't send these keys.
callback: null
reset: ->
@keywords = []
refresh: (@lastUI) ->
@reset()
@port.postMessage name: @name, handler: "refresh"
cancel: ->
# Inform the background completer that it may (should it choose to do so) abandon any pending query
# (because the user is typing, and there will be another query along soon).
@port.postMessage name: @name, handler: "cancel"
# These are the actions we can perform when the user selects a result.
completionActions:
navigateToUrl: (url) -> (openInNewTab) ->
# If the URL is a bookmarklet (so, prefixed with "javascript:"), then we always open it in the current
# tab.
openInNewTab &&= not Utils.hasJavascriptPrefix url
chrome.runtime.sendMessage
handler: if openInNewTab then "openUrlInNewTab" else "openUrlInCurrentTab"
url: url
selected: openInNewTab
switchToTab: (tabId) -> ->
chrome.runtime.sendMessage handler: "selectSpecificTab", id: tabId
UIComponentServer.registerHandler (event) ->
switch event.data
when "hide" then Vomnibar.hide()
when "hidden" then Vomnibar.onHidden()
else Vomnibar.activate event.data
root = exports ? window
root.Vomnibar = Vomnibar
| 191281 | #
# This controls the contents of the Vomnibar iframe. We use an iframe to avoid changing the selection on the
# page (useful for bookmarklets), ensure that the Vomnibar style is unaffected by the page, and simplify key
# handling in vimium_frontend.coffee
#
Vomnibar =
vomnibarUI: null # the dialog instance for this window
getUI: -> @vomnibarUI
completers: {}
getCompleter: (name) ->
@completers[name] ?= new BackgroundCompleter name
activate: (userOptions) ->
options =
completer: "omni"
query: ""
newTab: false
selectFirst: false
keyword: null
extend options, userOptions
extend options, refreshInterval: if options.completer == "omni" then 150 else 0
completer = @getCompleter options.completer
@vomnibarUI ?= new VomnibarUI()
completer.refresh @vomnibarUI
@vomnibarUI.setInitialSelectionValue if options.selectFirst then 0 else -1
@vomnibarUI.setCompleter completer
@vomnibarUI.setRefreshInterval options.refreshInterval
@vomnibarUI.setForceNewTab options.newTab
@vomnibarUI.setQuery options.query
@vomnibarUI.setKeyword options.keyword
@vomnibarUI.update true
hide: -> @vomnibarUI?.hide()
onHidden: -> @vomnibarUI?.onHidden()
class VomnibarUI
constructor: ->
@refreshInterval = 0
@postHideCallback = null
@initDom()
setQuery: (query) -> @input.value = query
setKeyword: (keyword) -> @customSearchMode = keyword
setInitialSelectionValue: (@initialSelectionValue) ->
setRefreshInterval: (@refreshInterval) ->
setForceNewTab: (@forceNewTab) ->
setCompleter: (@completer) -> @reset()
setKeywords: (@keywords) ->
# The sequence of events when the vomnibar is hidden is as follows:
# 1. Post a "hide" message to the host page.
# 2. The host page hides the vomnibar.
# 3. When that page receives the focus, and it posts back a "hidden" message.
# 3. Only once the "hidden" message is received here is any required action invoked (in onHidden).
# This ensures that the vomnibar is actually hidden before any new tab is created, and avoids flicker after
# opening a link in a new tab then returning to the original tab (see #1485).
hide: (@postHideCallback = null) ->
UIComponentServer.postMessage "hide"
@reset()
@completer?.reset()
onHidden: ->
@postHideCallback?()
@postHideCallback = null
reset: ->
@clearUpdateTimer()
@completionList.style.display = ""
@input.value = ""
@completions = []
@previousInputValue = null
@customSearchMode = null
@selection = @initialSelectionValue
@keywords = []
@seenTabToOpenCompletionList = false
updateSelection: ->
# For custom search engines, we suppress the leading term (e.g. the "w" of "w query terms") within the
# vomnibar input.
if @lastReponse.isCustomSearch and not @customSearchMode?
queryTerms = @input.value.trim().split /\s+/
@customSearchMode = queryTerms[0]
@input.value = queryTerms[1..].join " "
# For suggestions for custom search engines, we copy the suggested text into the input when the item is
# selected, and revert when it is not. This allows the user to select a suggestion and then continue
# typing.
if 0 <= @selection and @completions[@selection].insertText?
@previousInputValue ?= @input.value
@input.value = @completions[@selection].insertText
else if @previousInputValue?
@input.value = @previousInputValue
@previousInputValue = null
# Highlight the selected entry, and only the selected entry.
for i in [0...@completionList.children.length]
@completionList.children[i].className = (if i == @selection then "vomnibarSelected" else "")
# Returns the user's action ("up", "down", "tab", etc, or null) based on their keypress. We support the
# arrow keys and various other shortcuts, and this function hides the event-decoding complexity.
actionFromKeyEvent: (event) ->
key = KeyboardUtils.getKeyChar(event)
if (KeyboardUtils.isEscape(event))
return "dismiss"
else if (key == "up" ||
(event.shiftKey && event.keyCode == keyCodes.tab) ||
(event.ctrlKey && (key == "k" || key == "p")))
return "up"
else if (event.keyCode == keyCodes.tab && !event.shiftKey)
return "tab"
else if (key == "down" ||
(event.ctrlKey && (key == "j" || key == "n")))
return "down"
else if (event.keyCode == keyCodes.enter)
return "enter"
else if event.keyCode == keyCodes.backspace || event.keyCode == keyCodes.deleteKey
return "delete"
null
onKeydown: (event) =>
@lastAction = action = @actionFromKeyEvent event
return true unless action # pass through
openInNewTab = @forceNewTab ||
(event.shiftKey || event.ctrlKey || event.altKey || KeyboardUtils.isPrimaryModifierKey(event))
if (action == "dismiss")
@hide()
else if action in [ "tab", "down" ]
if action == "tab" and
@completer.name == "omni" and
not @seenTabToOpenCompletionList and
@input.value.trim().length == 0
@seenTabToOpenCompletionList = true
@update true
else
@selection += 1
@selection = @initialSelectionValue if @selection == @completions.length
@updateSelection()
else if (action == "up")
@selection -= 1
@selection = @completions.length - 1 if @selection < @initialSelectionValue
@updateSelection()
else if (action == "enter")
isCustomSearchPrimarySuggestion = @completions[@selection]?.isPrimarySuggestion and @lastReponse.engine?.searchUrl?
if @selection == -1 or isCustomSearchPrimarySuggestion
query = @input.value.trim()
# <Enter> on an empty query is a no-op.
return unless 0 < query.length
# First case (@selection == -1).
# If the user types something and hits enter without selecting a completion from the list, then:
# - If a search URL has been provided, then use it. This is custom search engine request.
# - Otherwise, send the query to the background page, which will open it as a URL or create a
# default search, as appropriate.
#
# Second case (isCustomSearchPrimarySuggestion).
# Alternatively, the selected completion could be the primary selection for a custom search engine.
# Because the the suggestions are updated asynchronously in omni mode, the user may have typed more
# text than that which is included in the URL associated with the primary suggestion. Therefore, to
# avoid a race condition, we construct the query from the actual contents of the input (query).
query = Utils.createSearchUrl query, @lastReponse.engine.searchUrl if isCustomSearchPrimarySuggestion
@hide ->
chrome.runtime.sendMessage
handler: if openInNewTab then "openUrlInNewTab" else "openUrlInCurrentTab"
url: query
else
completion = @completions[@selection]
@hide -> completion.performAction openInNewTab
else if action == "delete"
if @customSearchMode? and @input.selectionEnd == 0
# Normally, with custom search engines, the keyword (e,g, the "w" of "w query terms") is suppressed.
# If the cursor is at the start of the input, then reinstate the keyword (the "w").
@input.value = @customSearchMode + @input.value.ltrim()
@input.selectionStart = @input.selectionEnd = @customSearchMode.length
@customSearchMode = null
@update true
else if @seenTabToOpenCompletionList and @input.value.trim().length == 0
@seenTabToOpenCompletionList = false
@update true
else
return true # Do not suppress event.
# It seems like we have to manually suppress the event here and still return true.
event.stopImmediatePropagation()
event.preventDefault()
true
# Return the background-page query corresponding to the current input state. In other words, reinstate any
# search engine keyword which is currently being suppressed, and strip any prompted text.
getInputValueAsQuery: ->
(if @customSearchMode? then @customSearchMode + " " else "") + @input.value
updateCompletions: (callback = null) ->
@completer.filter
query: @getInputValueAsQuery()
seenTabToOpenCompletionList: @seenTabToOpenCompletionList
callback: (@lastReponse) =>
{ results } = @lastReponse
@completions = results
@selection = if @completions[0]?.autoSelect then 0 else @initialSelectionValue
# Update completion list with the new suggestions.
@completionList.innerHTML = @completions.map((completion) -> "<li>#{completion.html}</li>").join("")
@completionList.style.display = if @completions.length > 0 then "block" else ""
@selection = Math.min @completions.length - 1, Math.max @initialSelectionValue, @selection
@updateSelection()
callback?()
onInput: =>
@seenTabToOpenCompletionList = false
@completer.cancel()
if 0 <= @selection and @completions[@selection].customSearchMode and not @customSearchMode
@customSearchMode = @completions[@selection].customSearchMode
updateSynchronously = true
# If the user types, then don't reset any previous text, and reset the selection.
if @previousInputValue?
@previousInputValue = null
@selection = -1
@update updateSynchronously
clearUpdateTimer: ->
if @updateTimer?
window.clearTimeout @updateTimer
@updateTimer = null
shouldActivateCustomSearchMode: ->
queryTerms = @input.value.ltrim().split /\s+/
1 < queryTerms.length and queryTerms[0] in @keywords and not @customSearchMode
update: (updateSynchronously = false, callback = null) =>
# If the query text becomes a custom search (the user enters a search keyword), then we need to force a
# synchronous update (so that the state is updated immediately).
updateSynchronously ||= @shouldActivateCustomSearchMode()
if updateSynchronously
@clearUpdateTimer()
@updateCompletions callback
else if not @updateTimer?
# Update asynchronously for a better user experience, and to take some load off the CPU (not every
# keystroke will cause a dedicated update).
@updateTimer = Utils.setTimeout @refreshInterval, =>
@updateTimer = null
@updateCompletions callback
@input.focus()
initDom: ->
@box = document.getElementById("vomnibar")
@input = @box.querySelector("input")
@input.addEventListener "input", @onInput
@input.addEventListener "keydown", @onKeydown
@completionList = @box.querySelector("ul")
@completionList.style.display = ""
window.addEventListener "focus", => @input.focus()
# A click in the vomnibar itself refocuses the input.
@box.addEventListener "click", (event) =>
@input.focus()
event.stopImmediatePropagation()
# A click anywhere else hides the vomnibar.
document.body.addEventListener "click", => @hide()
#
# Sends requests to a Vomnibox completer on the background page.
#
class BackgroundCompleter
# The "name" is the background-page completer to connect to: "omni", "tabs", or "bookmarks".
constructor: (@name) ->
@port = chrome.runtime.connect name: "completions"
@messageId = null
@reset()
@port.onMessage.addListener (msg) =>
switch msg.handler
when "keywords"
@keywords = msg.keywords
@lastUI.setKeywords @keywords
when "completions"
if msg.id == @messageId
# The result objects coming from the background page will be of the form:
# { html: "", type: "", url: "", ... }
# Type will be one of [tab, bookmark, history, domain, search], or a custom search engine description.
for result in msg.results
extend result,
performAction:
if result.type == "tab"
@completionActions.switchToTab result.tabId
else
@completionActions.navigateToUrl result.url
# Handle the message, but only if it hasn't arrived too late.
@mostRecentCallback msg
filter: (request) ->
{ query, callback } = request
@mostRecentCallback = callback
@port.postMessage extend request,
handler: "filter"
name: <NAME>
id: @messageId = Utils.createUniqueId()
queryTerms: query.trim().split(/\s+/).filter (s) -> 0 < s.length
# We don't send these keys.
callback: null
reset: ->
@keywords = []
refresh: (@lastUI) ->
@reset()
@port.postMessage name: @name, handler: "refresh"
cancel: ->
# Inform the background completer that it may (should it choose to do so) abandon any pending query
# (because the user is typing, and there will be another query along soon).
@port.postMessage name: @name, handler: "cancel"
# These are the actions we can perform when the user selects a result.
completionActions:
navigateToUrl: (url) -> (openInNewTab) ->
# If the URL is a bookmarklet (so, prefixed with "javascript:"), then we always open it in the current
# tab.
openInNewTab &&= not Utils.hasJavascriptPrefix url
chrome.runtime.sendMessage
handler: if openInNewTab then "openUrlInNewTab" else "openUrlInCurrentTab"
url: url
selected: openInNewTab
switchToTab: (tabId) -> ->
chrome.runtime.sendMessage handler: "selectSpecificTab", id: tabId
UIComponentServer.registerHandler (event) ->
switch event.data
when "hide" then Vomnibar.hide()
when "hidden" then Vomnibar.onHidden()
else Vomnibar.activate event.data
root = exports ? window
root.Vomnibar = Vomnibar
| true | #
# This controls the contents of the Vomnibar iframe. We use an iframe to avoid changing the selection on the
# page (useful for bookmarklets), ensure that the Vomnibar style is unaffected by the page, and simplify key
# handling in vimium_frontend.coffee
#
Vomnibar =
vomnibarUI: null # the dialog instance for this window
getUI: -> @vomnibarUI
completers: {}
getCompleter: (name) ->
@completers[name] ?= new BackgroundCompleter name
activate: (userOptions) ->
options =
completer: "omni"
query: ""
newTab: false
selectFirst: false
keyword: null
extend options, userOptions
extend options, refreshInterval: if options.completer == "omni" then 150 else 0
completer = @getCompleter options.completer
@vomnibarUI ?= new VomnibarUI()
completer.refresh @vomnibarUI
@vomnibarUI.setInitialSelectionValue if options.selectFirst then 0 else -1
@vomnibarUI.setCompleter completer
@vomnibarUI.setRefreshInterval options.refreshInterval
@vomnibarUI.setForceNewTab options.newTab
@vomnibarUI.setQuery options.query
@vomnibarUI.setKeyword options.keyword
@vomnibarUI.update true
hide: -> @vomnibarUI?.hide()
onHidden: -> @vomnibarUI?.onHidden()
class VomnibarUI
constructor: ->
@refreshInterval = 0
@postHideCallback = null
@initDom()
setQuery: (query) -> @input.value = query
setKeyword: (keyword) -> @customSearchMode = keyword
setInitialSelectionValue: (@initialSelectionValue) ->
setRefreshInterval: (@refreshInterval) ->
setForceNewTab: (@forceNewTab) ->
setCompleter: (@completer) -> @reset()
setKeywords: (@keywords) ->
# The sequence of events when the vomnibar is hidden is as follows:
# 1. Post a "hide" message to the host page.
# 2. The host page hides the vomnibar.
# 3. When that page receives the focus, and it posts back a "hidden" message.
# 3. Only once the "hidden" message is received here is any required action invoked (in onHidden).
# This ensures that the vomnibar is actually hidden before any new tab is created, and avoids flicker after
# opening a link in a new tab then returning to the original tab (see #1485).
hide: (@postHideCallback = null) ->
UIComponentServer.postMessage "hide"
@reset()
@completer?.reset()
onHidden: ->
@postHideCallback?()
@postHideCallback = null
reset: ->
@clearUpdateTimer()
@completionList.style.display = ""
@input.value = ""
@completions = []
@previousInputValue = null
@customSearchMode = null
@selection = @initialSelectionValue
@keywords = []
@seenTabToOpenCompletionList = false
updateSelection: ->
# For custom search engines, we suppress the leading term (e.g. the "w" of "w query terms") within the
# vomnibar input.
if @lastReponse.isCustomSearch and not @customSearchMode?
queryTerms = @input.value.trim().split /\s+/
@customSearchMode = queryTerms[0]
@input.value = queryTerms[1..].join " "
# For suggestions for custom search engines, we copy the suggested text into the input when the item is
# selected, and revert when it is not. This allows the user to select a suggestion and then continue
# typing.
if 0 <= @selection and @completions[@selection].insertText?
@previousInputValue ?= @input.value
@input.value = @completions[@selection].insertText
else if @previousInputValue?
@input.value = @previousInputValue
@previousInputValue = null
# Highlight the selected entry, and only the selected entry.
for i in [0...@completionList.children.length]
@completionList.children[i].className = (if i == @selection then "vomnibarSelected" else "")
# Returns the user's action ("up", "down", "tab", etc, or null) based on their keypress. We support the
# arrow keys and various other shortcuts, and this function hides the event-decoding complexity.
actionFromKeyEvent: (event) ->
key = KeyboardUtils.getKeyChar(event)
if (KeyboardUtils.isEscape(event))
return "dismiss"
else if (key == "up" ||
(event.shiftKey && event.keyCode == keyCodes.tab) ||
(event.ctrlKey && (key == "k" || key == "p")))
return "up"
else if (event.keyCode == keyCodes.tab && !event.shiftKey)
return "tab"
else if (key == "down" ||
(event.ctrlKey && (key == "j" || key == "n")))
return "down"
else if (event.keyCode == keyCodes.enter)
return "enter"
else if event.keyCode == keyCodes.backspace || event.keyCode == keyCodes.deleteKey
return "delete"
null
onKeydown: (event) =>
@lastAction = action = @actionFromKeyEvent event
return true unless action # pass through
openInNewTab = @forceNewTab ||
(event.shiftKey || event.ctrlKey || event.altKey || KeyboardUtils.isPrimaryModifierKey(event))
if (action == "dismiss")
@hide()
else if action in [ "tab", "down" ]
if action == "tab" and
@completer.name == "omni" and
not @seenTabToOpenCompletionList and
@input.value.trim().length == 0
@seenTabToOpenCompletionList = true
@update true
else
@selection += 1
@selection = @initialSelectionValue if @selection == @completions.length
@updateSelection()
else if (action == "up")
@selection -= 1
@selection = @completions.length - 1 if @selection < @initialSelectionValue
@updateSelection()
else if (action == "enter")
isCustomSearchPrimarySuggestion = @completions[@selection]?.isPrimarySuggestion and @lastReponse.engine?.searchUrl?
if @selection == -1 or isCustomSearchPrimarySuggestion
query = @input.value.trim()
# <Enter> on an empty query is a no-op.
return unless 0 < query.length
# First case (@selection == -1).
# If the user types something and hits enter without selecting a completion from the list, then:
# - If a search URL has been provided, then use it. This is custom search engine request.
# - Otherwise, send the query to the background page, which will open it as a URL or create a
# default search, as appropriate.
#
# Second case (isCustomSearchPrimarySuggestion).
# Alternatively, the selected completion could be the primary selection for a custom search engine.
# Because the the suggestions are updated asynchronously in omni mode, the user may have typed more
# text than that which is included in the URL associated with the primary suggestion. Therefore, to
# avoid a race condition, we construct the query from the actual contents of the input (query).
query = Utils.createSearchUrl query, @lastReponse.engine.searchUrl if isCustomSearchPrimarySuggestion
@hide ->
chrome.runtime.sendMessage
handler: if openInNewTab then "openUrlInNewTab" else "openUrlInCurrentTab"
url: query
else
completion = @completions[@selection]
@hide -> completion.performAction openInNewTab
else if action == "delete"
if @customSearchMode? and @input.selectionEnd == 0
# Normally, with custom search engines, the keyword (e,g, the "w" of "w query terms") is suppressed.
# If the cursor is at the start of the input, then reinstate the keyword (the "w").
@input.value = @customSearchMode + @input.value.ltrim()
@input.selectionStart = @input.selectionEnd = @customSearchMode.length
@customSearchMode = null
@update true
else if @seenTabToOpenCompletionList and @input.value.trim().length == 0
@seenTabToOpenCompletionList = false
@update true
else
return true # Do not suppress event.
# It seems like we have to manually suppress the event here and still return true.
event.stopImmediatePropagation()
event.preventDefault()
true
# Return the background-page query corresponding to the current input state. In other words, reinstate any
# search engine keyword which is currently being suppressed, and strip any prompted text.
getInputValueAsQuery: ->
(if @customSearchMode? then @customSearchMode + " " else "") + @input.value
updateCompletions: (callback = null) ->
@completer.filter
query: @getInputValueAsQuery()
seenTabToOpenCompletionList: @seenTabToOpenCompletionList
callback: (@lastReponse) =>
{ results } = @lastReponse
@completions = results
@selection = if @completions[0]?.autoSelect then 0 else @initialSelectionValue
# Update completion list with the new suggestions.
@completionList.innerHTML = @completions.map((completion) -> "<li>#{completion.html}</li>").join("")
@completionList.style.display = if @completions.length > 0 then "block" else ""
@selection = Math.min @completions.length - 1, Math.max @initialSelectionValue, @selection
@updateSelection()
callback?()
onInput: =>
@seenTabToOpenCompletionList = false
@completer.cancel()
if 0 <= @selection and @completions[@selection].customSearchMode and not @customSearchMode
@customSearchMode = @completions[@selection].customSearchMode
updateSynchronously = true
# If the user types, then don't reset any previous text, and reset the selection.
if @previousInputValue?
@previousInputValue = null
@selection = -1
@update updateSynchronously
clearUpdateTimer: ->
if @updateTimer?
window.clearTimeout @updateTimer
@updateTimer = null
shouldActivateCustomSearchMode: ->
queryTerms = @input.value.ltrim().split /\s+/
1 < queryTerms.length and queryTerms[0] in @keywords and not @customSearchMode
update: (updateSynchronously = false, callback = null) =>
# If the query text becomes a custom search (the user enters a search keyword), then we need to force a
# synchronous update (so that the state is updated immediately).
updateSynchronously ||= @shouldActivateCustomSearchMode()
if updateSynchronously
@clearUpdateTimer()
@updateCompletions callback
else if not @updateTimer?
# Update asynchronously for a better user experience, and to take some load off the CPU (not every
# keystroke will cause a dedicated update).
@updateTimer = Utils.setTimeout @refreshInterval, =>
@updateTimer = null
@updateCompletions callback
@input.focus()
initDom: ->
@box = document.getElementById("vomnibar")
@input = @box.querySelector("input")
@input.addEventListener "input", @onInput
@input.addEventListener "keydown", @onKeydown
@completionList = @box.querySelector("ul")
@completionList.style.display = ""
window.addEventListener "focus", => @input.focus()
# A click in the vomnibar itself refocuses the input.
@box.addEventListener "click", (event) =>
@input.focus()
event.stopImmediatePropagation()
# A click anywhere else hides the vomnibar.
document.body.addEventListener "click", => @hide()
#
# Sends requests to a Vomnibox completer on the background page.
#
class BackgroundCompleter
# The "name" is the background-page completer to connect to: "omni", "tabs", or "bookmarks".
constructor: (@name) ->
@port = chrome.runtime.connect name: "completions"
@messageId = null
@reset()
@port.onMessage.addListener (msg) =>
switch msg.handler
when "keywords"
@keywords = msg.keywords
@lastUI.setKeywords @keywords
when "completions"
if msg.id == @messageId
# The result objects coming from the background page will be of the form:
# { html: "", type: "", url: "", ... }
# Type will be one of [tab, bookmark, history, domain, search], or a custom search engine description.
for result in msg.results
extend result,
performAction:
if result.type == "tab"
@completionActions.switchToTab result.tabId
else
@completionActions.navigateToUrl result.url
# Handle the message, but only if it hasn't arrived too late.
@mostRecentCallback msg
filter: (request) ->
{ query, callback } = request
@mostRecentCallback = callback
@port.postMessage extend request,
handler: "filter"
name: PI:NAME:<NAME>END_PI
id: @messageId = Utils.createUniqueId()
queryTerms: query.trim().split(/\s+/).filter (s) -> 0 < s.length
# We don't send these keys.
callback: null
reset: ->
@keywords = []
refresh: (@lastUI) ->
@reset()
@port.postMessage name: @name, handler: "refresh"
cancel: ->
# Inform the background completer that it may (should it choose to do so) abandon any pending query
# (because the user is typing, and there will be another query along soon).
@port.postMessage name: @name, handler: "cancel"
# These are the actions we can perform when the user selects a result.
completionActions:
navigateToUrl: (url) -> (openInNewTab) ->
# If the URL is a bookmarklet (so, prefixed with "javascript:"), then we always open it in the current
# tab.
openInNewTab &&= not Utils.hasJavascriptPrefix url
chrome.runtime.sendMessage
handler: if openInNewTab then "openUrlInNewTab" else "openUrlInCurrentTab"
url: url
selected: openInNewTab
switchToTab: (tabId) -> ->
chrome.runtime.sendMessage handler: "selectSpecificTab", id: tabId
UIComponentServer.registerHandler (event) ->
switch event.data
when "hide" then Vomnibar.hide()
when "hidden" then Vomnibar.onHidden()
else Vomnibar.activate event.data
root = exports ? window
root.Vomnibar = Vomnibar
|
[
{
"context": "lick (e) =>\n connectionInfo = {\n user: @user.val(),\n password: @pass.val()\n proto",
"end": 3235,
"score": 0.8548396229743958,
"start": 3230,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "o = {\n user: @user.val(),\n pas... | lib/quick-query-connect-view.coffee | fabianfiorotto/quick-query | 74 | {View, $} = require 'atom-space-pen-views'
{remote} = require 'electron'
ssh2 = require 'ssh2'
element: null
module.exports =
class QuickQueryConnectView extends View
constructor: (@protocols) ->
@connectionsStates = []
super
initialize: ->
@port.val('3306')
@sshport.val('22')
@onWillConnect (promise) =>
@connect.prop('disabled',true)
fn = (=> @connect.prop('disabled',false))
promise.then(fn).catch(fn)
@pass.focus =>
@showpass.stop().show()
@pass.blur =>
@showpass.fadeOut()
@showpass.click =>
@showpass.toggleClass("on")
if @showpass.hasClass("on")
@pass.attr("type","text")
@sshpass.attr("type","text")
else
@pass.attr("type","password")
@sshpass.attr("type","password")
@pass.focus()
@connect.keydown (e) ->
$(this).click() if e.keyCode == 13
@protocol
.keydown (e) ->
if e.keyCode == 13
$(e.target).css height: 'auto'
e.target.size = 3
else if e.keyCode == 37 || e.keyCode == 38
$(e.target).find('option:selected').prev().prop('selected',true)
else if e.keyCode == 39 || e.keyCode == 40
$(e.target).find('option:selected').next().prop('selected',true)
.blur (e) ->
$(e.target).css height: ''
e.target.size = 0
.on 'change blur', (e) =>
if $(e.target).find('option:selected').length > 0
protocol = $(e.target).find('option:selected').data('protocol')
@find('.ssh-info').toggle(protocol.handler.sshSupport? && protocol.handler.sshSupport)
if protocol.handler.fromFilesystem?
@showLocalInfo()
if protocol.handler.fileExtencions?
@browse_file.data('extensions',protocol.handler.fileExtencions)
else
@browse_file.data('extensions',false)
else
@showRemoteInfo()
@port.val(protocol.handler.defaultPort.toString())
@browse_file.click (e) =>
options =
properties: ['openFile']
title: 'Open Database'
currentWindow = atom.getCurrentWindow()
if $(e.currentTarget).data("extensions")
options.filters = [{ name: 'Database', extensions: $(e.target).data("extensions") }]
remote.dialog.showOpenDialog(currentWindow, options).then (dialog) =>
@file.val(dialog.filePaths[0]) if dialog && !dialog.canceled
for key,protocol of @protocols
option = $('<option/>')
.text(protocol.name)
.val(key)
.data('protocol',protocol)
@protocol.append(option)
@sshkey.click (e) =>
if @sshkey.hasClass('selected')
@sshpass_label.text('SSH Password')
@sshkey.removeClass('selected')
else
currentWindow = atom.getCurrentWindow()
options =
properties: ['openFile']
title: 'Load SSH Key'
remote.dialog.showOpenDialog(currentWindow, options).then (dialog) =>
if dialog && !dialog.canceled
@sshkey.data('file', dialog.filePaths[0]).addClass('selected')
@sshpass_label.text('Passphrase')
@connect.click (e) =>
connectionInfo = {
user: @user.val(),
password: @pass.val()
protocol: @protocol.val()
}
if @protocols[connectionInfo.protocol]?.handler.fromFilesystem?
connectionInfo.file = @file.val()
else
connectionInfo.host = @host.val()
connectionInfo.port = @port.val()
if @protocols[connectionInfo.protocol]?.default?
defaults = @protocols[connectionInfo.protocol].default
connectionInfo[attr] = value for attr,value of defaults
if @database.val() != ''
connectionInfo.database = @database.val()
if @sshuser.val() != ''
connectionInfo.ssh =
username: @sshuser.val()
password: @sshpass.val()
port: @sshport.val()
connectionInfo.ssh.keyfile = @sshkey.data('file') if @sshkey.hasClass('selected')
$(@element).trigger('quickQuery.connect',[@buildConnection(connectionInfo)])
@advanced_toggle.click (e) =>
@advanced_info.slideToggle 400, =>
hidden = @advanced_info.is(":hidden")
@advanced_info.find('input').attr 'tabindex', (i,attr) -> if hidden then null else i + 6
@advanced_toggle.children("i").toggleClass("icon-chevron-down icon-chevron-left")
addProtocol: (key,protocol)->
@protocols[key] = protocol
option = $('<option/>')
.text(protocol.name)
.val(key)
.data('protocol',protocol)
@protocol.append(option)
for state in @connectionsStates
state.callback(state.info) if state.info.protocol == key
buildConnection: (connectionInfo)->
return @buildConnectionSSH(connectionInfo) if connectionInfo.ssh?
new Promise (resolve, reject)=>
protocolClass = @protocols[connectionInfo.protocol]?.handler
if protocolClass
connection = new protocolClass(connectionInfo)
connection.connect (err) =>
if err then reject(err) else resolve(connection)
@trigger('quickQuery.connected',connection) unless err?
else #whait until the package is loaded
@connectionsStates.push
info: connectionInfo
callback: (connectionInfo) =>
protocolClass = @protocols[connectionInfo.protocol].handler
connection = new protocolClass(connectionInfo)
connection.connect (err) =>
if err then reject(err) else resolve(connection)
@trigger('quickQuery.connected',connection) unless err?
buildConnectionSSH: (connectionInfo) ->
ssh = connectionInfo.ssh
conf =
host: connectionInfo.host,
port: ssh.port,
username: ssh.username,
if ssh.keyfile?
conf.privateKey = require('fs').readFileSync(ssh.keyfile)
conf.passphrase = ssh.password if ssh.password != ''
else
conf.password = ssh.password
new Promise (resolve, reject)=>
protocolClass = @protocols[connectionInfo.protocol]?.handler
conn = new ssh2.Client()
conn.on 'error', (err) -> reject(err)
conn.on 'ready', =>
conn.forwardOut '127.0.0.1', 12345, '127.0.0.1' ,connectionInfo.port, (err, stream) =>
conn.end?() if err?
stream.setTimeout = ((time, handler) -> @_client._sock.setTimeout(0, handler))
connectionInfo.stream = (->stream)
connection = new protocolClass(connectionInfo)
connection.connect (err) =>
console.log err if err?
if err then reject(err) else resolve(connection)
@trigger('quickQuery.connected',connection) unless err?
conn.connect(conf)
@content: ->
@div class: 'dialog quick-query-connect', =>
@div class: "col-sm-12" , =>
@label 'protocol'
@select outlet: "protocol", class: "form-control input-select" , id: "quick-query-protocol", tabindex: 1
@div class: "qq-remote-info row", =>
@div class: "col-sm-9" , =>
@label 'host'
@input outlet: "host", class: "input-text native-key-bindings", id: "quick-query-host", type: "text", tabindex: 2
@div class:"col-sm-3" , =>
@label 'port'
@input outlet: "port", class: "input-number native-key-bindings", id: "quick-query-port", type: "number", min:0, max: 65536, tabindex: 3
@div class: "qq-local-info row" , =>
@div class: "col-sm-12", =>
@label 'file'
@div class: "col-sm-9", =>
@input outlet: 'file', class: "input-text native-key-bindings", id: "quick-query-file", type: "text", tabindex: 2
@div class: "col-sm-3", =>
@button outlet: "browse_file", id:"quick-query-browse-file", class: "btn btn-default icon icon-file-directory", "Browse"
@div class: "qq-auth-info row", =>
@div class: "col-sm-6" , =>
@label 'user'
@input outlet: 'user', class: "input-text native-key-bindings", id: "quick-query-user", type: "text", tabindex: 4
@div class: "col-sm-6" , =>
@label 'password'
@div class: "pass-wrapper", =>
@input outlet: 'pass' ,class: "input-text native-key-bindings", id: "quick-query-pass", type: "password", tabindex: 5
@button outlet:"showpass", class:"show-password", title:"Show password", tabindex: "-1", =>
@i class: "icon icon-eye"
@div class: "qq-advanced-info-toggler row", =>
@div class: "col-sm-12", =>
@button outlet:"advanced_toggle", class: "advance-toggle", tabindex: "-1", title:"toggle advanced options",=>
@i class: "icon icon-chevron-left"
@div outlet: "advanced_info", class: "qq-advanced-info row", =>
@div class: "col-sm-12" , =>
@label 'default database (optional)'
@input outlet: 'database' ,class: "input-text native-key-bindings", id: "quick-query-database", type: "text"
@div class: "ssh-info col-sm-6" , =>
@label 'SSH username'
@input outlet: 'sshuser' ,class: "input-text native-key-bindings", id: "quick-query-ssh-user", type: "text"
@div class: "ssh-info col-sm-4" , =>
@label outlet: 'sshpass_label', 'SSH password'
@div class:'flex-row', =>
@div =>
@input outlet: 'sshpass', class: "input-text native-key-bindings", id: "quick-query-ssh-pass", type: "password"
@button outlet:"sshkey", title: "Load SSH Key", id:"quick-query-key", class: "btn btn-default icon icon-key", ""
@div class: "ssh-info col-sm-2" , =>
@label for: "quick-query-ssh-port",'SSH port'
@input outlet: 'sshport', class: "input-text native-key-bindings", id: "quick-query-ssh-port", type: "number", min:0, max: 65536
@div class: "col-sm-12" , =>
@button outlet:"connect", id:"quick-query-connect", class: "btn btn-default icon icon-plug" , tabindex: "99" , "Connect"
destroy: ->
@element.remove()
focusFirst: ->
@protocol.focus()
showLocalInfo: ->
@find(".qq-local-info").show()
@find(".qq-remote-info").hide()
showRemoteInfo: ->
@find(".qq-remote-info").show()
@find(".qq-local-info").hide()
onWillConnect: (callback)->
@bind 'quickQuery.connect', (e,connectionPromise) ->
callback(connectionPromise)
onConnectionStablished: (callback)->
@bind 'quickQuery.connected', (e,connection) ->
callback(connection)
| 3228 | {View, $} = require 'atom-space-pen-views'
{remote} = require 'electron'
ssh2 = require 'ssh2'
element: null
module.exports =
class QuickQueryConnectView extends View
constructor: (@protocols) ->
@connectionsStates = []
super
initialize: ->
@port.val('3306')
@sshport.val('22')
@onWillConnect (promise) =>
@connect.prop('disabled',true)
fn = (=> @connect.prop('disabled',false))
promise.then(fn).catch(fn)
@pass.focus =>
@showpass.stop().show()
@pass.blur =>
@showpass.fadeOut()
@showpass.click =>
@showpass.toggleClass("on")
if @showpass.hasClass("on")
@pass.attr("type","text")
@sshpass.attr("type","text")
else
@pass.attr("type","password")
@sshpass.attr("type","password")
@pass.focus()
@connect.keydown (e) ->
$(this).click() if e.keyCode == 13
@protocol
.keydown (e) ->
if e.keyCode == 13
$(e.target).css height: 'auto'
e.target.size = 3
else if e.keyCode == 37 || e.keyCode == 38
$(e.target).find('option:selected').prev().prop('selected',true)
else if e.keyCode == 39 || e.keyCode == 40
$(e.target).find('option:selected').next().prop('selected',true)
.blur (e) ->
$(e.target).css height: ''
e.target.size = 0
.on 'change blur', (e) =>
if $(e.target).find('option:selected').length > 0
protocol = $(e.target).find('option:selected').data('protocol')
@find('.ssh-info').toggle(protocol.handler.sshSupport? && protocol.handler.sshSupport)
if protocol.handler.fromFilesystem?
@showLocalInfo()
if protocol.handler.fileExtencions?
@browse_file.data('extensions',protocol.handler.fileExtencions)
else
@browse_file.data('extensions',false)
else
@showRemoteInfo()
@port.val(protocol.handler.defaultPort.toString())
@browse_file.click (e) =>
options =
properties: ['openFile']
title: 'Open Database'
currentWindow = atom.getCurrentWindow()
if $(e.currentTarget).data("extensions")
options.filters = [{ name: 'Database', extensions: $(e.target).data("extensions") }]
remote.dialog.showOpenDialog(currentWindow, options).then (dialog) =>
@file.val(dialog.filePaths[0]) if dialog && !dialog.canceled
for key,protocol of @protocols
option = $('<option/>')
.text(protocol.name)
.val(key)
.data('protocol',protocol)
@protocol.append(option)
@sshkey.click (e) =>
if @sshkey.hasClass('selected')
@sshpass_label.text('SSH Password')
@sshkey.removeClass('selected')
else
currentWindow = atom.getCurrentWindow()
options =
properties: ['openFile']
title: 'Load SSH Key'
remote.dialog.showOpenDialog(currentWindow, options).then (dialog) =>
if dialog && !dialog.canceled
@sshkey.data('file', dialog.filePaths[0]).addClass('selected')
@sshpass_label.text('Passphrase')
@connect.click (e) =>
connectionInfo = {
user: @user.val(),
password: <PASSWORD>()
protocol: @protocol.val()
}
if @protocols[connectionInfo.protocol]?.handler.fromFilesystem?
connectionInfo.file = @file.val()
else
connectionInfo.host = @host.val()
connectionInfo.port = @port.val()
if @protocols[connectionInfo.protocol]?.default?
defaults = @protocols[connectionInfo.protocol].default
connectionInfo[attr] = value for attr,value of defaults
if @database.val() != ''
connectionInfo.database = @database.val()
if @sshuser.val() != ''
connectionInfo.ssh =
username: @sshuser.val()
password: @sshpass.val()
port: @sshport.val()
connectionInfo.ssh.keyfile = @sshkey.data('file') if @sshkey.hasClass('selected')
$(@element).trigger('quickQuery.connect',[@buildConnection(connectionInfo)])
@advanced_toggle.click (e) =>
@advanced_info.slideToggle 400, =>
hidden = @advanced_info.is(":hidden")
@advanced_info.find('input').attr 'tabindex', (i,attr) -> if hidden then null else i + 6
@advanced_toggle.children("i").toggleClass("icon-chevron-down icon-chevron-left")
addProtocol: (key,protocol)->
@protocols[key] = protocol
option = $('<option/>')
.text(protocol.name)
.val(key)
.data('protocol',protocol)
@protocol.append(option)
for state in @connectionsStates
state.callback(state.info) if state.info.protocol == key
buildConnection: (connectionInfo)->
return @buildConnectionSSH(connectionInfo) if connectionInfo.ssh?
new Promise (resolve, reject)=>
protocolClass = @protocols[connectionInfo.protocol]?.handler
if protocolClass
connection = new protocolClass(connectionInfo)
connection.connect (err) =>
if err then reject(err) else resolve(connection)
@trigger('quickQuery.connected',connection) unless err?
else #whait until the package is loaded
@connectionsStates.push
info: connectionInfo
callback: (connectionInfo) =>
protocolClass = @protocols[connectionInfo.protocol].handler
connection = new protocolClass(connectionInfo)
connection.connect (err) =>
if err then reject(err) else resolve(connection)
@trigger('quickQuery.connected',connection) unless err?
buildConnectionSSH: (connectionInfo) ->
ssh = connectionInfo.ssh
conf =
host: connectionInfo.host,
port: ssh.port,
username: ssh.username,
if ssh.keyfile?
conf.privateKey = require('fs').readFileSync(ssh.keyfile)
conf.passphrase = ssh.password if ssh.password != ''
else
conf.password = ssh.password
new Promise (resolve, reject)=>
protocolClass = @protocols[connectionInfo.protocol]?.handler
conn = new ssh2.Client()
conn.on 'error', (err) -> reject(err)
conn.on 'ready', =>
conn.forwardOut '127.0.0.1', 12345, '127.0.0.1' ,connectionInfo.port, (err, stream) =>
conn.end?() if err?
stream.setTimeout = ((time, handler) -> @_client._sock.setTimeout(0, handler))
connectionInfo.stream = (->stream)
connection = new protocolClass(connectionInfo)
connection.connect (err) =>
console.log err if err?
if err then reject(err) else resolve(connection)
@trigger('quickQuery.connected',connection) unless err?
conn.connect(conf)
@content: ->
@div class: 'dialog quick-query-connect', =>
@div class: "col-sm-12" , =>
@label 'protocol'
@select outlet: "protocol", class: "form-control input-select" , id: "quick-query-protocol", tabindex: 1
@div class: "qq-remote-info row", =>
@div class: "col-sm-9" , =>
@label 'host'
@input outlet: "host", class: "input-text native-key-bindings", id: "quick-query-host", type: "text", tabindex: 2
@div class:"col-sm-3" , =>
@label 'port'
@input outlet: "port", class: "input-number native-key-bindings", id: "quick-query-port", type: "number", min:0, max: 65536, tabindex: 3
@div class: "qq-local-info row" , =>
@div class: "col-sm-12", =>
@label 'file'
@div class: "col-sm-9", =>
@input outlet: 'file', class: "input-text native-key-bindings", id: "quick-query-file", type: "text", tabindex: 2
@div class: "col-sm-3", =>
@button outlet: "browse_file", id:"quick-query-browse-file", class: "btn btn-default icon icon-file-directory", "Browse"
@div class: "qq-auth-info row", =>
@div class: "col-sm-6" , =>
@label 'user'
@input outlet: 'user', class: "input-text native-key-bindings", id: "quick-query-user", type: "text", tabindex: 4
@div class: "col-sm-6" , =>
@label 'password'
@div class: "pass-wrapper", =>
@input outlet: 'pass' ,class: "input-text native-key-bindings", id: "quick-query-pass", type: "password", tabindex: 5
@button outlet:"showpass", class:"show-password", title:"Show password", tabindex: "-1", =>
@i class: "icon icon-eye"
@div class: "qq-advanced-info-toggler row", =>
@div class: "col-sm-12", =>
@button outlet:"advanced_toggle", class: "advance-toggle", tabindex: "-1", title:"toggle advanced options",=>
@i class: "icon icon-chevron-left"
@div outlet: "advanced_info", class: "qq-advanced-info row", =>
@div class: "col-sm-12" , =>
@label 'default database (optional)'
@input outlet: 'database' ,class: "input-text native-key-bindings", id: "quick-query-database", type: "text"
@div class: "ssh-info col-sm-6" , =>
@label 'SSH username'
@input outlet: 'sshuser' ,class: "input-text native-key-bindings", id: "quick-query-ssh-user", type: "text"
@div class: "ssh-info col-sm-4" , =>
@label outlet: 'sshpass_label', 'SSH password'
@div class:'flex-row', =>
@div =>
@input outlet: 'sshpass', class: "input-text native-key-bindings", id: "quick-query-ssh-pass", type: "<PASSWORD>"
@button outlet:"sshkey", title: "Load SSH Key", id:"quick-query-key", class: "btn btn-default icon icon-key", ""
@div class: "ssh-info col-sm-2" , =>
@label for: "quick-query-ssh-port",'SSH port'
@input outlet: 'sshport', class: "input-text native-key-bindings", id: "quick-query-ssh-port", type: "number", min:0, max: 65536
@div class: "col-sm-12" , =>
@button outlet:"connect", id:"quick-query-connect", class: "btn btn-default icon icon-plug" , tabindex: "99" , "Connect"
destroy: ->
@element.remove()
focusFirst: ->
@protocol.focus()
showLocalInfo: ->
@find(".qq-local-info").show()
@find(".qq-remote-info").hide()
showRemoteInfo: ->
@find(".qq-remote-info").show()
@find(".qq-local-info").hide()
onWillConnect: (callback)->
@bind 'quickQuery.connect', (e,connectionPromise) ->
callback(connectionPromise)
onConnectionStablished: (callback)->
@bind 'quickQuery.connected', (e,connection) ->
callback(connection)
| true | {View, $} = require 'atom-space-pen-views'
{remote} = require 'electron'
ssh2 = require 'ssh2'
element: null
module.exports =
class QuickQueryConnectView extends View
constructor: (@protocols) ->
@connectionsStates = []
super
initialize: ->
@port.val('3306')
@sshport.val('22')
@onWillConnect (promise) =>
@connect.prop('disabled',true)
fn = (=> @connect.prop('disabled',false))
promise.then(fn).catch(fn)
@pass.focus =>
@showpass.stop().show()
@pass.blur =>
@showpass.fadeOut()
@showpass.click =>
@showpass.toggleClass("on")
if @showpass.hasClass("on")
@pass.attr("type","text")
@sshpass.attr("type","text")
else
@pass.attr("type","password")
@sshpass.attr("type","password")
@pass.focus()
@connect.keydown (e) ->
$(this).click() if e.keyCode == 13
@protocol
.keydown (e) ->
if e.keyCode == 13
$(e.target).css height: 'auto'
e.target.size = 3
else if e.keyCode == 37 || e.keyCode == 38
$(e.target).find('option:selected').prev().prop('selected',true)
else if e.keyCode == 39 || e.keyCode == 40
$(e.target).find('option:selected').next().prop('selected',true)
.blur (e) ->
$(e.target).css height: ''
e.target.size = 0
.on 'change blur', (e) =>
if $(e.target).find('option:selected').length > 0
protocol = $(e.target).find('option:selected').data('protocol')
@find('.ssh-info').toggle(protocol.handler.sshSupport? && protocol.handler.sshSupport)
if protocol.handler.fromFilesystem?
@showLocalInfo()
if protocol.handler.fileExtencions?
@browse_file.data('extensions',protocol.handler.fileExtencions)
else
@browse_file.data('extensions',false)
else
@showRemoteInfo()
@port.val(protocol.handler.defaultPort.toString())
@browse_file.click (e) =>
options =
properties: ['openFile']
title: 'Open Database'
currentWindow = atom.getCurrentWindow()
if $(e.currentTarget).data("extensions")
options.filters = [{ name: 'Database', extensions: $(e.target).data("extensions") }]
remote.dialog.showOpenDialog(currentWindow, options).then (dialog) =>
@file.val(dialog.filePaths[0]) if dialog && !dialog.canceled
for key,protocol of @protocols
option = $('<option/>')
.text(protocol.name)
.val(key)
.data('protocol',protocol)
@protocol.append(option)
@sshkey.click (e) =>
if @sshkey.hasClass('selected')
@sshpass_label.text('SSH Password')
@sshkey.removeClass('selected')
else
currentWindow = atom.getCurrentWindow()
options =
properties: ['openFile']
title: 'Load SSH Key'
remote.dialog.showOpenDialog(currentWindow, options).then (dialog) =>
if dialog && !dialog.canceled
@sshkey.data('file', dialog.filePaths[0]).addClass('selected')
@sshpass_label.text('Passphrase')
@connect.click (e) =>
connectionInfo = {
user: @user.val(),
password: PI:PASSWORD:<PASSWORD>END_PI()
protocol: @protocol.val()
}
if @protocols[connectionInfo.protocol]?.handler.fromFilesystem?
connectionInfo.file = @file.val()
else
connectionInfo.host = @host.val()
connectionInfo.port = @port.val()
if @protocols[connectionInfo.protocol]?.default?
defaults = @protocols[connectionInfo.protocol].default
connectionInfo[attr] = value for attr,value of defaults
if @database.val() != ''
connectionInfo.database = @database.val()
if @sshuser.val() != ''
connectionInfo.ssh =
username: @sshuser.val()
password: @sshpass.val()
port: @sshport.val()
connectionInfo.ssh.keyfile = @sshkey.data('file') if @sshkey.hasClass('selected')
$(@element).trigger('quickQuery.connect',[@buildConnection(connectionInfo)])
@advanced_toggle.click (e) =>
@advanced_info.slideToggle 400, =>
hidden = @advanced_info.is(":hidden")
@advanced_info.find('input').attr 'tabindex', (i,attr) -> if hidden then null else i + 6
@advanced_toggle.children("i").toggleClass("icon-chevron-down icon-chevron-left")
addProtocol: (key,protocol)->
@protocols[key] = protocol
option = $('<option/>')
.text(protocol.name)
.val(key)
.data('protocol',protocol)
@protocol.append(option)
for state in @connectionsStates
state.callback(state.info) if state.info.protocol == key
buildConnection: (connectionInfo)->
return @buildConnectionSSH(connectionInfo) if connectionInfo.ssh?
new Promise (resolve, reject)=>
protocolClass = @protocols[connectionInfo.protocol]?.handler
if protocolClass
connection = new protocolClass(connectionInfo)
connection.connect (err) =>
if err then reject(err) else resolve(connection)
@trigger('quickQuery.connected',connection) unless err?
else #whait until the package is loaded
@connectionsStates.push
info: connectionInfo
callback: (connectionInfo) =>
protocolClass = @protocols[connectionInfo.protocol].handler
connection = new protocolClass(connectionInfo)
connection.connect (err) =>
if err then reject(err) else resolve(connection)
@trigger('quickQuery.connected',connection) unless err?
buildConnectionSSH: (connectionInfo) ->
ssh = connectionInfo.ssh
conf =
host: connectionInfo.host,
port: ssh.port,
username: ssh.username,
if ssh.keyfile?
conf.privateKey = require('fs').readFileSync(ssh.keyfile)
conf.passphrase = ssh.password if ssh.password != ''
else
conf.password = ssh.password
new Promise (resolve, reject)=>
protocolClass = @protocols[connectionInfo.protocol]?.handler
conn = new ssh2.Client()
conn.on 'error', (err) -> reject(err)
conn.on 'ready', =>
conn.forwardOut '127.0.0.1', 12345, '127.0.0.1' ,connectionInfo.port, (err, stream) =>
conn.end?() if err?
stream.setTimeout = ((time, handler) -> @_client._sock.setTimeout(0, handler))
connectionInfo.stream = (->stream)
connection = new protocolClass(connectionInfo)
connection.connect (err) =>
console.log err if err?
if err then reject(err) else resolve(connection)
@trigger('quickQuery.connected',connection) unless err?
conn.connect(conf)
@content: ->
@div class: 'dialog quick-query-connect', =>
@div class: "col-sm-12" , =>
@label 'protocol'
@select outlet: "protocol", class: "form-control input-select" , id: "quick-query-protocol", tabindex: 1
@div class: "qq-remote-info row", =>
@div class: "col-sm-9" , =>
@label 'host'
@input outlet: "host", class: "input-text native-key-bindings", id: "quick-query-host", type: "text", tabindex: 2
@div class:"col-sm-3" , =>
@label 'port'
@input outlet: "port", class: "input-number native-key-bindings", id: "quick-query-port", type: "number", min:0, max: 65536, tabindex: 3
@div class: "qq-local-info row" , =>
@div class: "col-sm-12", =>
@label 'file'
@div class: "col-sm-9", =>
@input outlet: 'file', class: "input-text native-key-bindings", id: "quick-query-file", type: "text", tabindex: 2
@div class: "col-sm-3", =>
@button outlet: "browse_file", id:"quick-query-browse-file", class: "btn btn-default icon icon-file-directory", "Browse"
@div class: "qq-auth-info row", =>
@div class: "col-sm-6" , =>
@label 'user'
@input outlet: 'user', class: "input-text native-key-bindings", id: "quick-query-user", type: "text", tabindex: 4
@div class: "col-sm-6" , =>
@label 'password'
@div class: "pass-wrapper", =>
@input outlet: 'pass' ,class: "input-text native-key-bindings", id: "quick-query-pass", type: "password", tabindex: 5
@button outlet:"showpass", class:"show-password", title:"Show password", tabindex: "-1", =>
@i class: "icon icon-eye"
@div class: "qq-advanced-info-toggler row", =>
@div class: "col-sm-12", =>
@button outlet:"advanced_toggle", class: "advance-toggle", tabindex: "-1", title:"toggle advanced options",=>
@i class: "icon icon-chevron-left"
@div outlet: "advanced_info", class: "qq-advanced-info row", =>
@div class: "col-sm-12" , =>
@label 'default database (optional)'
@input outlet: 'database' ,class: "input-text native-key-bindings", id: "quick-query-database", type: "text"
@div class: "ssh-info col-sm-6" , =>
@label 'SSH username'
@input outlet: 'sshuser' ,class: "input-text native-key-bindings", id: "quick-query-ssh-user", type: "text"
@div class: "ssh-info col-sm-4" , =>
@label outlet: 'sshpass_label', 'SSH password'
@div class:'flex-row', =>
@div =>
@input outlet: 'sshpass', class: "input-text native-key-bindings", id: "quick-query-ssh-pass", type: "PI:PASSWORD:<PASSWORD>END_PI"
@button outlet:"sshkey", title: "Load SSH Key", id:"quick-query-key", class: "btn btn-default icon icon-key", ""
@div class: "ssh-info col-sm-2" , =>
@label for: "quick-query-ssh-port",'SSH port'
@input outlet: 'sshport', class: "input-text native-key-bindings", id: "quick-query-ssh-port", type: "number", min:0, max: 65536
@div class: "col-sm-12" , =>
@button outlet:"connect", id:"quick-query-connect", class: "btn btn-default icon icon-plug" , tabindex: "99" , "Connect"
destroy: ->
@element.remove()
focusFirst: ->
@protocol.focus()
showLocalInfo: ->
@find(".qq-local-info").show()
@find(".qq-remote-info").hide()
showRemoteInfo: ->
@find(".qq-remote-info").show()
@find(".qq-local-info").hide()
onWillConnect: (callback)->
@bind 'quickQuery.connect', (e,connectionPromise) ->
callback(connectionPromise)
onConnectionStablished: (callback)->
@bind 'quickQuery.connected', (e,connection) ->
callback(connection)
|
[
{
"context": "ame) -> \"DR. #{name}\"\n\npromise = Promise.resolve \"MANHATTAN\"\n\npromise\n\t.then attachTitle\n\t.then console.log\n",
"end": 99,
"score": 0.9161361455917358,
"start": 90,
"tag": "NAME",
"value": "MANHATTAN"
}
] | 08-values-and-promises.coffee | jazeee/nodeschool-promise-it-wont-hurt | 1 | require('es6-promise')
attachTitle = (name) -> "DR. #{name}"
promise = Promise.resolve "MANHATTAN"
promise
.then attachTitle
.then console.log
| 33479 | require('es6-promise')
attachTitle = (name) -> "DR. #{name}"
promise = Promise.resolve "<NAME>"
promise
.then attachTitle
.then console.log
| true | require('es6-promise')
attachTitle = (name) -> "DR. #{name}"
promise = Promise.resolve "PI:NAME:<NAME>END_PI"
promise
.then attachTitle
.then console.log
|
[
{
"context": "uest\n\t\t@project_id = \"3213213kl12j\"\n\t\t@user_id = \"2k3jlkjs9\"\n\t\t@content = \"my message here\"\n\t\t@callba",
"end": 655,
"score": 0.8893986344337463,
"start": 654,
"tag": "USERNAME",
"value": "2"
},
{
"context": "est\n\t\t@project_id = \"3213213kl12j\"\n\t\... | test/unit/coffee/Chat/ChatApiHandlerTests.coffee | davidmehren/web-sharelatex | 1 | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/Chat/ChatApiHandler"
expect = require("chai").expect
describe "ChatApiHandler", ->
beforeEach ->
@settings =
apis:
chat:
internal_url:"chat.sharelatex.env"
@request = sinon.stub()
@ChatApiHandler = SandboxedModule.require modulePath, requires:
"settings-sharelatex": @settings
"logger-sharelatex": { log: sinon.stub(), error: sinon.stub() }
"request": @request
@project_id = "3213213kl12j"
@user_id = "2k3jlkjs9"
@content = "my message here"
@callback = sinon.stub()
describe "sendGlobalMessage", ->
describe "successfully", ->
beforeEach ->
@message = { "mock": "message" }
@request.callsArgWith(1, null, {statusCode: 200}, @message)
@ChatApiHandler.sendGlobalMessage @project_id, @user_id, @content, @callback
it "should post the data to the chat api", ->
@request.calledWith({
url: "#{@settings.apis.chat.internal_url}/project/#{@project_id}/messages"
method: "POST"
json:
content: @content
user_id: @user_id
}).should.equal true
it "should return the message from the post", ->
@callback.calledWith(null, @message).should.equal true
describe "with a non-success status code", ->
beforeEach ->
@request.callsArgWith(1, null, {statusCode: 500})
@ChatApiHandler.sendGlobalMessage @project_id, @user_id, @content, @callback
it "should return an error", ->
error = new Error()
error.statusCode = 500
@callback.calledWith(error).should.equal true
describe "getGlobalMessages", ->
beforeEach ->
@messages = [{ "mock": "message" }]
@limit = 30
@before = "1234"
describe "successfully", ->
beforeEach ->
@request.callsArgWith(1, null, {statusCode: 200}, @messages)
@ChatApiHandler.getGlobalMessages @project_id, @limit, @before, @callback
it "should make get request for room to chat api", ->
@request.calledWith({
method: "GET"
url: "#{@settings.apis.chat.internal_url}/project/#{@project_id}/messages"
qs:
limit: @limit
before: @before
json: true
}).should.equal true
it "should return the messages from the request", ->
@callback.calledWith(null, @messages).should.equal true
describe "with failure error code", ->
beforeEach ->
@request.callsArgWith(1, null, {statusCode: 500}, null)
@ChatApiHandler.getGlobalMessages @project_id, @limit, @before, @callback
it "should return an error", ->
error = new Error()
error.statusCode = 500
@callback.calledWith(error).should.equal true
| 6071 | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/Chat/ChatApiHandler"
expect = require("chai").expect
describe "ChatApiHandler", ->
beforeEach ->
@settings =
apis:
chat:
internal_url:"chat.sharelatex.env"
@request = sinon.stub()
@ChatApiHandler = SandboxedModule.require modulePath, requires:
"settings-sharelatex": @settings
"logger-sharelatex": { log: sinon.stub(), error: sinon.stub() }
"request": @request
@project_id = "3213213kl12j"
@user_id = "2<PASSWORD>"
@content = "my message here"
@callback = sinon.stub()
describe "sendGlobalMessage", ->
describe "successfully", ->
beforeEach ->
@message = { "mock": "message" }
@request.callsArgWith(1, null, {statusCode: 200}, @message)
@ChatApiHandler.sendGlobalMessage @project_id, @user_id, @content, @callback
it "should post the data to the chat api", ->
@request.calledWith({
url: "#{@settings.apis.chat.internal_url}/project/#{@project_id}/messages"
method: "POST"
json:
content: @content
user_id: @user_id
}).should.equal true
it "should return the message from the post", ->
@callback.calledWith(null, @message).should.equal true
describe "with a non-success status code", ->
beforeEach ->
@request.callsArgWith(1, null, {statusCode: 500})
@ChatApiHandler.sendGlobalMessage @project_id, @user_id, @content, @callback
it "should return an error", ->
error = new Error()
error.statusCode = 500
@callback.calledWith(error).should.equal true
describe "getGlobalMessages", ->
beforeEach ->
@messages = [{ "mock": "message" }]
@limit = 30
@before = "1234"
describe "successfully", ->
beforeEach ->
@request.callsArgWith(1, null, {statusCode: 200}, @messages)
@ChatApiHandler.getGlobalMessages @project_id, @limit, @before, @callback
it "should make get request for room to chat api", ->
@request.calledWith({
method: "GET"
url: "#{@settings.apis.chat.internal_url}/project/#{@project_id}/messages"
qs:
limit: @limit
before: @before
json: true
}).should.equal true
it "should return the messages from the request", ->
@callback.calledWith(null, @messages).should.equal true
describe "with failure error code", ->
beforeEach ->
@request.callsArgWith(1, null, {statusCode: 500}, null)
@ChatApiHandler.getGlobalMessages @project_id, @limit, @before, @callback
it "should return an error", ->
error = new Error()
error.statusCode = 500
@callback.calledWith(error).should.equal true
| true | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/Chat/ChatApiHandler"
expect = require("chai").expect
describe "ChatApiHandler", ->
beforeEach ->
@settings =
apis:
chat:
internal_url:"chat.sharelatex.env"
@request = sinon.stub()
@ChatApiHandler = SandboxedModule.require modulePath, requires:
"settings-sharelatex": @settings
"logger-sharelatex": { log: sinon.stub(), error: sinon.stub() }
"request": @request
@project_id = "3213213kl12j"
@user_id = "2PI:PASSWORD:<PASSWORD>END_PI"
@content = "my message here"
@callback = sinon.stub()
describe "sendGlobalMessage", ->
describe "successfully", ->
beforeEach ->
@message = { "mock": "message" }
@request.callsArgWith(1, null, {statusCode: 200}, @message)
@ChatApiHandler.sendGlobalMessage @project_id, @user_id, @content, @callback
it "should post the data to the chat api", ->
@request.calledWith({
url: "#{@settings.apis.chat.internal_url}/project/#{@project_id}/messages"
method: "POST"
json:
content: @content
user_id: @user_id
}).should.equal true
it "should return the message from the post", ->
@callback.calledWith(null, @message).should.equal true
describe "with a non-success status code", ->
beforeEach ->
@request.callsArgWith(1, null, {statusCode: 500})
@ChatApiHandler.sendGlobalMessage @project_id, @user_id, @content, @callback
it "should return an error", ->
error = new Error()
error.statusCode = 500
@callback.calledWith(error).should.equal true
describe "getGlobalMessages", ->
beforeEach ->
@messages = [{ "mock": "message" }]
@limit = 30
@before = "1234"
describe "successfully", ->
beforeEach ->
@request.callsArgWith(1, null, {statusCode: 200}, @messages)
@ChatApiHandler.getGlobalMessages @project_id, @limit, @before, @callback
it "should make get request for room to chat api", ->
@request.calledWith({
method: "GET"
url: "#{@settings.apis.chat.internal_url}/project/#{@project_id}/messages"
qs:
limit: @limit
before: @before
json: true
}).should.equal true
it "should return the messages from the request", ->
@callback.calledWith(null, @messages).should.equal true
describe "with failure error code", ->
beforeEach ->
@request.callsArgWith(1, null, {statusCode: 500}, null)
@ChatApiHandler.getGlobalMessages @project_id, @limit, @before, @callback
it "should return an error", ->
error = new Error()
error.statusCode = 500
@callback.calledWith(error).should.equal true
|
[
{
"context": "on(1, 1, \"04223314cdffec8740150afe46db3575fae840362b137316c0d222a071607d61b2fd40abb2652a7fea20e3bb3e64dc6d495d59823d143c53c4fe4059c5ff16e406\")\nAttestation(2, 1, \"04c370d4013107a98dfef01d6db5",
"end": 1394,
"score": 0.9049073457717896,
"start": 1304,
"tag": "KEY",
"value": "... | app/src/dongle/dongle.coffee | ipsBruno/ledger-wallet-chrome | 173 |
States =
# Dongle juste created, not initialized.
UNDEFINED: undefined
# PIN required.
LOCKED: 'locked'
# PIN has been verified.
UNLOCKED: 'unlocked'
# No seed present, dongle must be setup.
BLANK: 'blank'
# Dongle has been unplugged.
DISCONNECTED: 'disconnected'
# An error appended, user must unplug/replug dongle.
ERROR: 'error'
Firmwares = ledger.dongle.Firmwares
Attestations = {}
class Attestation
xPoint: null
yPoint: null
Bytes: null
BatchId: null
DerivationId: null
constructor: (batchId, derivationId, value) ->
if _(this).isKindOf(Attestation)
@BatchId = batchId
@DerivationId = derivationId
@Id = Convert.toHexInt(batchId) + Convert.toHexInt(derivationId)
@String = value
@Bytes = parseInt(hex, 16) for hex in @String.match(/\w\w/g)
@xPoint = @String.substr(2,64)
@yPoint = @String.substr(66)
Attestations[@Id] = this
else
new Attestation(batchId, derivationId, value)
isBeta: -> @BatchId is 0
isProduction: -> !@isBeta()
getAttestationId: -> new ByteString(@Id, HEX)
Attestation(0, 1, "04e69fd3c044865200e66f124b5ea237c918503931bee070edfcab79a00a25d6b5a09afbee902b4b763ecf1f9c25f82d6b0cf72bce3faf98523a1066948f1a395f")
Attestation(1, 1, "04223314cdffec8740150afe46db3575fae840362b137316c0d222a071607d61b2fd40abb2652a7fea20e3bb3e64dc6d495d59823d143c53c4fe4059c5ff16e406")
Attestation(2, 1, "04c370d4013107a98dfef01d6db5bb3419deb9299535f0be47f05939a78b314a3c29b51fcaa9b3d46fa382c995456af50cd57fb017c0ce05e4a31864a79b8fbfd6")
# This path do not need a verified PIN to sign messages.
BitIdRootPath = "0'/0/0xb11e"
Errors = @ledger.errors
$log = -> ledger.utils.Logger.getLoggerByTag("Dongle")
# Populate dongle namespace.
@ledger.dongle ?= {}
_.extend @ledger.dongle,
States: States
BitIdRootPath: BitIdRootPath
###
Signals :
@emit state:changed(States)
@emit state:locked
@emit state:unlocked
@emit state:blank
@emit state:disconnected
@emit state:error(args...)
###
class @ledger.dongle.Dongle extends EventEmitter
Dongle = @
# @property
id: undefined
# @property
deviceId: undefined
# @property
productId: undefined
# @property [String]
state: States.UNDEFINED
# @property [ByteString]
firmwareVersion: undefined
# @property [Integer]
operationMode: undefined
# @private [BtChip]
_btchip: undefined
# @private [Array<ledger.wallet.ExtendedPublicKey>]
_xpubs: []
# @private @property [String] pin used to unlock dongle.
_pin: undefined
# @private @property [ledger.utils.PromiseQueue] Enqueue btchip calls to prevent multiple call to interfer
_btchipQueue = undefined
constructor: (card) ->
super
@_attestation = null
@_xpubs = _.clone(@_xpubs)
@id = card.deviceId
@deviceId = card.deviceId
@productId = card.productId
_btchipQueue = new ledger.utils.PromiseQueue("Dongle##{@id}")
@_btchip = new BTChip(card)
# Recovers dongle firmware version and initialize current state
connect: (forceBootloader = no, callback = undefined) ->
# Recover firmware version
# Create firmware info object
# Determine state (setup|locked|unlocked|blank)
# Resolve
@_forceBl = forceBootloader
@state = States.UNDEFINED
unless @isInBootloaderMode()
@_recoverFirmwareVersion().then =>
if @getFirmwareInformation().hasSetupFirmwareSupport() && !@getFirmwareInformation().hasScreenAndButton()
@getRemainingPinAttempt().then =>
@_setState(States.LOCKED)
States.LOCKED
.fail (error) =>
@_setState(States.BLANK)
States.BLANK
else
# Nano S, Blue
if @getFirmwareInformation().hasScreenAndButton()
@ensureDeviceIsUnlocked(on)
@_setState States.UNLOCKED
States.UNLOCKED
else
@_sendApdu(0xE0, 0x40, 0x00, 0x00, 0x05, 0x01).then (result) =>
switch @getSw()
when 0x9000, 0x6982
@_setState States.LOCKED
States.LOCKED
when 0x6985
configureBlank = =>
@_setState(States.BLANK)
States.BLANK
# Check restore
if @getFirmwareInformation().hasSubFirmwareSupport() and @getFirmwareInformation().hasOperationFirmwareSupport()
@restoreSetup().then =>
@_setState States.LOCKED
States.LOCKED
.catch => do configureBlank
else
do configureBlank
when 0x6faa
throw "Invalid statue - 0x6faa"
.catch (error) =>
console.error("Fail to initialize Dongle :", error)
@_setState(States.ERROR)
throw error
else
ledger.delay(0).then(=> @_setState States.BLANK).then(-> States.BLANK)
isNanoS: -> @productId == 0x0001
ensureDeviceIsUnlocked: (runForever = no) ->
return if @_ensureDeviceIsUnlockedTimeout?
@_ensureDeviceIsUnlockedTimeout = _.delay(() =>
@getPublicAddress("0'/0xb11e'").then =>
yes
.fail (err) =>
if @state is States.LOCKED
@disconnect()
yes
.then =>
@_ensureDeviceIsUnlockedTimeout = undefined
@ensureDeviceIsUnlocked(runForever) if runForever
.done()
, 30000)
setCoinVersion: (p2pkhVersion, p2shVersion, callback = undefined) ->
d = ledger.defer(callback)
if (@getFirmwareInformation().hasUInt16CoinVersion())
@_sendApdu(new ByteString("E014000002#{Convert.toHexShort(p2pkhVersion)}#{Convert.toHexShort(p2shVersion)}", HEX)).then ->
d.resolve()
.fail (e) ->
d.reject(e)
else
@_sendApdu(new ByteString("E014000002#{("0" + p2pkhVersion.toString(16)).substr(-2)}#{("0" + p2shVersion.toString(16)).substr(-2)}", HEX)).then ->
d.resolve()
.fail (e) ->
d.reject(e)
d.promise
getCoinVersion: (callback = undefined) ->
d = ledger.defer(callback)
d.resolve(
@_sendApdu(new ByteString("E016000000", HEX)).then (result) =>
if (@getFirmwareInformation().hasUInt16CoinVersion())
P2PKH = (result.byteAt(0) << 8) + result.byteAt(1)
P2SH = (result.byteAt(2) << 8) + result.byteAt(3)
message = result.bytes(5, result.byteAt(4))
short = result.bytes(5 + message.length + 1, result.byteAt(5 + message.length))
else
P2PKH = result.byteAt(0)
P2SH = result.byteAt(1)
message = result.bytes(3, result.byteAt(2))
short = result.bytes(3 + message.length + 1, result.byteAt(3 + message.length))
{P2PKH: P2PKH, P2SH: P2SH, message: "#{message} signed message:\n", short: short}
.fail =>
l "FAILED"
{P2PKH: ledger.bitcoin.Networks.bitcoin.version.regular, P2SH: ledger.bitcoin.Networks.bitcoin.version.P2SH, message: "Bitcoin signed message:\n", short: 'BTC'}
)
d.promise
getFirmwareInformation: -> @_firmwareInformation
getSw: -> @_btchip.card.SW
# Called when
disconnect: ->
clearTimeout(@_ensureDeviceIsUnlockedTimeout) if @_ensureDeviceIsUnlockedTimeout?
@_ensureDeviceIsUnlockedTimeout = undefined
@_btchip.card.disconnect()
@_setState(States.DISCONNECTED)
# @return [String] Firmware version, 1.0.0 for example.
getStringFirmwareVersion: -> Try(=> @getFirmwareInformation().getStringFirmwareVersion()).getOrElse('unknown')
# @return [Integer] Firmware version, 0x20010000010f for example.
getIntFirmwareVersion: -> @getFirmwareInformation().getIntFirmwareVersion()
###
Gets the raw version {ByteString} of the dongle.
@param [Boolean] isInBootLoaderMode Must be true if the current dongle is in bootloader mode.
@param [Boolean] forceBl Force the call in BootLoader mode
@param [Function] callback Called once the version is retrieved. The callback must be prototyped like size `(version, error) ->`
@return [Q.Promise]
###
getRawFirmwareVersion: (isInBootLoaderMode, forceBl=no, checkHiddenReloader = no, callback=undefined) ->
_btchipQueue.enqueue "getRawFirmwareVersion", =>
d = ledger.defer(callback)
apdu = new ByteString((if !isInBootLoaderMode and !forceBl then "E0C4000000" else "F001000000"), HEX)
@_sendApdu(apdu).then (result) =>
sw = @_btchip.card.SW
if !isInBootLoaderMode and !forceBl
if sw is 0x9000
d.resolve([result.byteAt(1), (result.byteAt(2) << 16) + (result.byteAt(3) << 8) + result.byteAt(4)])
else
# Not initialized now - Retry
d.resolve @getRawFirmwareVersion(isInBootLoaderMode, yes)
else
if sw is 0x9000
# Bootloader ok, let's see if hidden reloader
result2 = result
apdu = new ByteString("E001000000", HEX)
if checkHiddenReloader
@_sendApdu(apdu).then (result) =>
if @_btchip.card.SW isnt 0x9000
result = result2
d.resolve([0, (result.byteAt(5) << 16) + (result.byteAt(6) << 8) + result.byteAt(7)])
.fail ->
result = result2
d.resolve([0, (result.byteAt(5) << 16) + (result.byteAt(6) << 8) + result.byteAt(7)])
else
result = result2
d.resolve([0, (result.byteAt(5) << 16) + (result.byteAt(6) << 8) + result.byteAt(7)])
else if !isInBootLoaderMode and (sw is 0x6d00 or sw is 0x6e00)
# Unexpected - let's say it's 1.4.3
d.resolve([0, (1 << 16) + (4 << 8) + (3)])
else
d.rejectWithError(ledger.errors.UnknowError, "Failed to get version")
.fail (error) ->
d.rejectWithError(ledger.errors.UnknowError, error)
.catch (error) ->
console.error("Fail to getRawFirmwareVersion :", error)
.done()
d.promise
# @return [Boolean]
isInBootloaderMode: -> if @productId is 0x1808 or @productId is 0x1807 or @_forceBl then yes else no
# @return [ledger.fup.FirmwareUpdater]
getFirmwareUpdater: () -> ledger.fup.FirmwareUpdater.instance
# @return [Q.Promise]
isFirmwareUpdateAvailable: (callback=undefined) ->
d = ledger.defer(callback)
@getFirmwareUpdater().getFirmwareUpdateAvailability(this)
.then (availablity) ->
d.resolve(availablity.result is ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Update)
.fail (er) ->
d.rejectWithError(er)
.done()
d.promise
# @return [Q.Promise]
isFirmwareOverwriteOrUpdateAvailable: (callback=undefined) ->
d = ledger.defer(callback)
@getFirmwareUpdater().getFirmwareUpdateAvailability(this)
.then (availablity) ->
d.resolve(availablity.result is ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Update or availablity.result is ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Overwrite)
.fail (er) ->
d.rejectWithError(er)
.done()
d.promise
# Verify that dongle firmware is "official".
# @param [Function] callback Optional argument
# @return [Q.Promise]
isCertified: (callback=undefined) -> @_checkCertification(no, callback)
isBetaCertified: (callback=undefined) -> @_checkCertification(yes, callback)
_checkCertification: (isBeta, callback = undefined) ->
_btchipQueue.enqueue "checkCertification", =>
d = ledger.defer(callback)
return d.resolve(true).promise if @getIntFirmwareVersion() < ledger.dongle.Firmwares.V_L_1_0_0
randomValues = new Uint32Array(2)
crypto.getRandomValues(randomValues)
random = _.str.lpad(randomValues[0].toString(16), 8, '0') + _.str.lpad(randomValues[1].toString(16), 8, '0')
# 24.2. GET DEVICE ATTESTATION
@_sendApdu(new ByteString("E0"+"C2"+"00"+"00"+"08"+random, HEX), [0x9000])
.then (result) =>
attestation = result.toString(HEX)
dataToSign = attestation.substring(16,32) + random
dataSig = attestation.substring(32)
dataSig = "30" + dataSig.substr(2)
dataSigBytes = (parseInt(n,16) for n in dataSig.match(/\w\w/g))
sha = new JSUCrypt.hash.SHA256()
domain = JSUCrypt.ECFp.getEcDomainByName("secp256k1")
if isBeta
Attestation = Attestations["0000000000000001"]
else
Attestation = Attestations[result.bytes(0, 8).toString()]
affinePoint = new JSUCrypt.ECFp.AffinePoint(Attestation.xPoint, Attestation.yPoint)
pubkey = new JSUCrypt.key.EcFpPublicKey(256, domain, affinePoint)
ecsig = new JSUCrypt.signature.ECDSA(sha)
ecsig.init(pubkey, JSUCrypt.signature.MODE_VERIFY)
if ecsig.verify(dataToSign, dataSigBytes)
@_attestation = Attestation
d.resolve(this)
else
d.rejectWithError(Errors.DongleNotCertified)
return
.fail (err) =>
d.rejectWithError(Errors.CommunicationError, err)
.done()
d.promise
getAttestation: -> @_attestation
# Return asynchronously state. Wait until a state is set.
# @param [Function] callback Optional argument
# @return [Q.Promise]
getState: (callback=undefined) ->
d = ledger.defer(callback)
if @state is States.UNDEFINED
@once 'state:changed', (e, state) => d.resolve(state)
else
d.resolve(@state)
d.promise
# @return [Q.Promise] resolve with a Number, reject with a ledger Error.
getRemainingPinAttempt: (callback=undefined) ->
_btchipQueue.enqueue "getRemainingPinAttempt", =>
d = ledger.defer(callback)
@_sendApdu(new ByteString("E0228000010000", HEX), [0x9000])
.catch (statusCode) =>
if m = statusCode.match(/63c(\d)/)
d.resolve(parseInt(m[1]))
else
d.reject(@_handleErrorCode(statusCode))
.done()
d.promise
# @param [String] pin ASCII encoded
# @param [Function] callback Optional argument
# @return [Q.Promise]
unlockWithPinCode: (pin, callback=undefined) ->
Errors.throw(Errors.DongleAlreadyUnlock) if @state is States.UNLOCKED
_btchipQueue.enqueue "unlockWithPinCode", =>
d = ledger.defer(callback)
@_pin = pin
@_btchip.verifyPin_async(new ByteString(@_pin, ASCII))
.then =>
if @getFirmwareInformation().hasSubFirmwareSupport() and @getFirmwareInformation().hasSetupFirmwareSupport()
d.resolve()
return
# 19.7. SET OPERATION MODE
@_sendApdu(0xE0, 0x26, 0x01, 0x01, 0x01, 0x01, [0x9000])
.then =>
if @getIntFirmwareVersion() >= Firmwares.V_B_1_4_13
# 19.7. SET OPERATION MODE
mode = if @getIntFirmwareVersion() >= Firmwares.V_L_1_0_0 then 0x02 else 0x01
@_sendApdu(0xE0, 0x26, mode, 0x00, 0x01, 0x01, [0x9000]).fail(=> e('Unlock FAIL', arguments)).done()
@_setState(States.UNLOCKED)
d.resolve()
.fail (err) =>
error = Errors.new(Errors.NotSupportedDongle, err)
console.log("unlockWithPinCode 2 fail :", err)
d.reject(error)
.catch (error) ->
console.error("Fail to unlockWithPinCode 2 :", error)
.done()
.fail (err) =>
console.error("Fail to unlockWithPinCode 1 :", err)
error = @_handleErrorCode(err)
d.reject(error)
.catch (error) ->
console.error("Fail to unlockWithPinCode 1 :", error)
.done()
d.promise
lock: () ->
if @state isnt ledger.dongle.States.BLANK and @state?
@_setState(States.LOCKED)
###
@overload setup(pin, callback)
@param [String] pin
@param [Function] callback
@return [Q.Promise]
@overload setup(pin, options={}, callback=undefined)
@param [String] pin
@param [String] restoreSeed
@options options [String] restoreSeed
@options options [ByteString] keyMap
@param [Function] callback
@return [Q.Promise]
###
setup: (pin, restoreSeed, callback=undefined) ->
Errors.throw(Errors.DongleNotBlank) if @state isnt States.BLANK
[restoreSeed, callback] = [callback, restoreSeed] if ! callback && typeof restoreSeed == 'function'
_btchipQueue.enqueue "setup", =>
d = ledger.defer(callback)
# Validate seed
if restoreSeed?
bytesSeed = new ByteString(restoreSeed, HEX)
if bytesSeed.length != 64
e('Invalid seed :', restoreSeed)
return d.reject().promise
@_btchip.setupNew_async(
BTChip.MODE_WALLET,
BTChip.FEATURE_DETERMINISTIC_SIGNATURE | BTChip.FEATURE_NO_2FA_P2SH,
ledger.config.network.version.regular,
ledger.config.network.version.P2SH,
new ByteString(pin, ASCII),
undefined,
BTChip.QWERTY_KEYMAP_NEW,
restoreSeed?,
bytesSeed
).then( =>
if restoreSeed?
msg = "Seed restored, please reopen the extension"
else
msg = "Plug the dongle into a secure host to read the generated seed, then reopen the extension"
console.warn(msg)
@_setState(States.ERROR, msg)
d.resolve()
).fail( (err) =>
error = Errors.new(Errors.UnknowError, err)
d.reject(error)
).catch( (error) ->
console.error("Fail to setup :", error)
).done()
d.promise
setupSwappedBip39: (pin, userEntropy = undefined, callback = undefined) -> @_setupSwappedBip39({pin, userEntropy, callback})
restoreSwappedBip39: (pin, restoreSeed, callback = undefined) -> @_setupSwappedBip39({pin, restoreSeed, callback})
verifyAddressOnScreen: (path, callback) ->
Errors.throw(Errors.DongleLocked, 'Cannot get a public while the key is not unlocked') if @state isnt States.UNLOCKED && @state isnt States.UNDEFINED
_btchipQueue.enqueue "getPublicAddress", =>
d = ledger.defer(callback)
@_btchip.getWalletPublicKey_async(path, true, ledger.config.network.handleSegwit)
.then (result) =>
#ledger.wallet.Wallet.instance?.cache?.set [[path, result.bitcoinAddress.value]]
_.defer -> d.resolve(result)
.fail (err) =>
_.defer -> d.resolve({})
.done()
d.promise
_setupSwappedBip39: ({pin, userEntropy, restoreSeed, callback}) ->
Errors.throw(Errors.DongleNotBlank) if @state isnt States.BLANK
userEntropy ||= ledger.bitcoin.bip39.generateEntropy()
if restoreSeed?
indexes = ledger.bitcoin.bip39.mnemonicPhraseToWordIndexes(restoreSeed)
restoreSeed = (Convert.toHexShort(index) for index in indexes).join('')
d = ledger.defer(callback)
@_btchip.setupNew_async(
BTChip.MODE_WALLET,
BTChip.FEATURE_DETERMINISTIC_SIGNATURE | BTChip.FEATURE_NO_2FA_P2SH,
ledger.config.network.version.regular,
ledger.config.network.version.P2SH,
new ByteString(pin, ASCII),
undefined,
undefined,
false,
new ByteString(restoreSeed or userEntropy, HEX),
undefined, !restoreSeed?, restoreSeed?
).then (result) =>
mnemonic = []
for i in [0...24]
wordIndex = (result['swappedMnemonic'].byteAt(2 * i) << 8) + (result['swappedMnemonic'].byteAt(2 * i + 1))
mnemonic.push ledger.bitcoin.bip39.wordlist[wordIndex]
d.resolve(_.extend(result, mnemonic: mnemonic))
.fail (error) =>
d.reject(error)
.done()
d.promise
setupFinalizeBip39: (callback = undefined) ->
ledger.defer(callback).resolve(@_btchip.setupFinalizeBip39_async()).promise
restoreFinalizeBip29: (callback = undefined) ->
ledger.defer(callback).resolve(@_btchip.setupRecovery_async()).promise
restoreSetup: (callback = undefined) -> @_sendApdu(0xE0, 0x20, 0xFF, 0x00, 0x01, 0x00, [0x9000]).then(callback or _.noop)
isSwappedBip39FeatureEnabled: ->
@setupSwappedBip39("0000").then(-> yes).fail(-> no)
# @param [String] path
# @param [Function] callback Optional argument
# @return [Q.Promise]
getPublicAddress: (path, callback=undefined) ->
Errors.throw(Errors.DongleLocked, 'Cannot get a public while the key is not unlocked') if @state isnt States.UNLOCKED && @state isnt States.UNDEFINED
_btchipQueue.enqueue "getPublicAddress", =>
d = ledger.defer(callback)
@_btchip.getWalletPublicKey_async(path, false, false)
.then (result) =>
#ledger.wallet.Wallet.instance?.cache?.set [[path, result.bitcoinAddress.value]]
_.defer -> d.resolve(result)
.fail (err) =>
error = @_handleErrorCode(err)
_.defer -> d.reject(error)
.catch (error) ->
console.error("Fail to getPublicAddress :", error)
.done()
d.promise
# @param [String] message
# @param [String] path Optional argument
# @param [Function] callback Optional argument
# @return [Q.Promise]
signMessage: (message, {prefix, path, pubKey}, callback=undefined) ->
prefix ?= '\x18Bitcoin Signed Message:\n'
if ! pubKey?
@getPublicAddress(path).then((address) => console.log("address=", address); @signMessage(message, path: path, pubKey: address.publicKey, callback))
else
_btchipQueue.enqueue "signMessage", =>
d = ledger.defer(callback)
message = new ByteString(message, ASCII)
@_btchip.signMessagePrepare_async(path, message)
.then =>
return @_btchip.signMessageSign_async(if (@_pin?) then new ByteString(@_pin, ASCII) else new ByteString("0000", ASCII))
.then (sig) =>
signedMessage = @_convertMessageSignature(pubKey, message, prefix, sig.signature)
d.resolve(signedMessage)
.catch (error) ->
console.error("Fail to signMessage :", error)
d.reject(error)
.done()
d.promise
# @param [String] pubKey public key, hex encoded.
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve with a 32 bytes length pairing blob hex encoded.
initiateSecureScreen: (pubKey, callback=undefined) ->
_btchipQueue.enqueue "initiateSecureScreen", =>
d = ledger.defer(callback)
if @state != States.UNLOCKED
d.rejectWithError(Errors.DongleLocked)
else if ! pubKey.match(/^[0-9A-Fa-f]{130}$/)?
d.rejectWithError(Errors.InvalidArgument, "Invalid pubKey : #{pubKey}")
else
# 19.3. SETUP SECURE SCREEN
@_sendApdu(new ByteString("E0"+"12"+"01"+"00"+"41"+pubKey, HEX), [0x9000])
.then (c) ->
l 'initiateSecureScreen', c
d.resolve(c.toString())
.fail (error) -> d.reject(error)
.done()
d.promise
# @param [String] resp challenge response, hex encoded.
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve if pairing is successful.
confirmSecureScreen: (resp, callback=undefined) ->
_btchipQueue.enqueue "confirmSecureScreen", =>
d = ledger.defer(callback)
if @state != States.UNLOCKED
d.rejectWithError(Errors.DongleLocked)
else if ! resp.match(/^[0-9A-Fa-f]{32}$/)?
d.rejectWithError(Errors.InvalidArgument, "Invalid challenge resp : #{resp}")
else
# 19.3. SETUP SECURE SCREEN
@_sendApdu(new ByteString("E0"+"12"+"02"+"00"+"10"+resp, HEX), [0x9000])
.then () ->
l 'confirmSecureScreen'
d.resolve()
.fail (error) -> d.reject(error)
.done()
d.promise
# @param [String] path
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve if pairing is successful.
getExtendedPublicKey: (path, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state != States.UNLOCKED
d = ledger.defer(callback)
return d.resolve(@_xpubs[path]).promise if @_xpubs[path]?
xpub = new ledger.wallet.ExtendedPublicKey(@, path)
xpub.initialize () =>
@_xpubs[path] = xpub
d.resolve(xpub)
d.promise
###
@param [Array<Object>] inputs
@param [Array] associatedKeysets
@param changePath
@param [String] changeAddress
@param [String] recipientAddress
@param [Amount] amount
@param [Amount] fee
@param [Integer] lockTime
@param [Integer] sighashType
@param [String] authorization hex encoded
@param [Object] resumeData
@return [Q.Promise] Resolve with resumeData
###
createPaymentTransaction: (inputs, associatedKeysets, changePath, changeAddress, recipientAddress, amount, fees, data, lockTime, sighashType, authorization, resumeData) ->
if resumeData?
resumeData = _.clone(resumeData)
resumeData.scriptData = new ByteString(resumeData.scriptData, HEX)
resumeData.trustedInputs = (new ByteString(trustedInput, HEX) for trustedInput in resumeData.trustedInputs)
resumeData.publicKeys = (new ByteString(publicKey, HEX) for publicKey in resumeData.publicKeys)
if @getFirmwareInformation().isUsingInputFinalizeFull()
@_createPaymentTransactionNew(inputs, associatedKeysets, changePath, changeAddress, recipientAddress, amount, fees, lockTime, sighashType, authorization, data, resumeData)
else
@_createPaymentTransaction(inputs, associatedKeysets, changePath, recipientAddress, amount, fees, lockTime, sighashType, authorization, resumeData)
_createPaymentTransaction: (inputs, associatedKeysets, changePath, recipientAddress, amount, fees, lockTime, sighashType, authorization, resumeData) ->
_btchipQueue.enqueue "createPaymentTransaction", =>
@_btchip.createPaymentTransaction_async(
inputs, associatedKeysets, changePath,
new ByteString(recipientAddress, ASCII),
amount.toByteString(),
fees.toByteString(),
lockTime && new ByteString(Convert.toHexInt(lockTime), HEX),
sighashType && new ByteString(Convert.toHexInt(sighashType), HEX),
authorization && new ByteString(authorization, HEX),
resumeData
).then( (result) ->
if result instanceof ByteString
result = result.toString(HEX)
else
result.scriptData = result.scriptData.toString(HEX)
result.trustedInputs = (trustedInput.toString(HEX) for trustedInput in result.trustedInputs)
result.publicKeys = (publicKey.toString(HEX) for publicKey in result.publicKeys)
result.authorizationPaired = result.authorizationPaired.toString(HEX) if result.authorizationPaired?
result.authorizationReference = result.authorizationReference.toString(HEX) if result.authorizationReference?
return result
)
_createPaymentTransactionNew: (inputs, associatedKeysets, changePath, changeAddress, recipientAddress, amount, fees, lockTime, sighashType, authorization, data, resumeData) ->
@getPublicAddress(changePath).then (result) =>
changeAddress2 = result.bitcoinAddress.toString(ASCII)
inputAmounts = do =>
for [prevTx, index], i in inputs
ledger.Amount.fromSatoshi(prevTx.outputs[index].amount)
totalInputAmount = ledger.Amount.fromSatoshi(0)
for inputAmount in inputAmounts
totalInputAmount = totalInputAmount.add(inputAmount)
changeAmount = totalInputAmount.subtract(amount).subtract(fees)
changePath = undefined if changeAmount.lte(0)
VI = @_btchip.createVarint.bind(@_btchip)
OP_DUP = new ByteString('76', HEX)
OP_HASH160 = new ByteString('A9', HEX)
OP_EQUAL = new ByteString('87', HEX)
OP_EQUALVERIFY = new ByteString('88', HEX)
OP_CHECKSIG = new ByteString('AC', HEX)
OP_RETURN = new ByteString('6A', HEX)
if ledger.config.network.name is "zencash"
ParamHash = new ByteString('209ec9845acb02fab24e1c0368b3b517c1a4488fba97f0e3459ac053ea01000000', HEX)
AdjustAlign = new ByteString('03', HEX)
ParamHeight = new ByteString('c01f02', HEX)
OP_CHECKBLOCKATHEIGHT = new ByteString('b4', HEX)
ZenReplayProtection = ParamHash.concat(AdjustAlign).concat(ParamHeight).concat(OP_CHECKBLOCKATHEIGHT)
###
Create the output script
Count (VI) | Value (8) | PkScript (var) | ....
###
PkScript = (address) =>
hash160WithNetwork = ledger.bitcoin.addressToHash160WithNetwork(address)
p2pkhNetworkVersionSize = hash160WithNetwork.length - 20
hash160 = hash160WithNetwork.bytes(p2pkhNetworkVersionSize, hash160WithNetwork.length - p2pkhNetworkVersionSize) #ledger.bitcoin.addressToHash160(address)
if p2pkhNetworkVersionSize is 1
return P2shScript(hash160) if hash160WithNetwork.byteAt(0) is ledger.config.network.version.P2SH
else
return P2shScript(hash160) if (hash160WithNetwork.byteAt(0) << 8 | hash160WithNetwork.byteAt(1)) is ledger.config.network.version.P2SH
if ledger.config.network.name is "zencash"
script =
OP_DUP
.concat(OP_HASH160)
.concat(new ByteString(Convert.toHexByte(hash160.length), HEX))
.concat(hash160)
.concat(OP_EQUALVERIFY)
.concat(OP_CHECKSIG)
.concat(ZenReplayProtection)
VI(script.length).concat(script)
else
script =
OP_DUP
.concat(OP_HASH160)
.concat(new ByteString(Convert.toHexByte(hash160.length), HEX))
.concat(hash160)
.concat(OP_EQUALVERIFY)
.concat(OP_CHECKSIG)
VI(script.length).concat(script)
P2shScript = (hash160) =>
if ledger.config.network.name is "zencash"
script =
OP_HASH160
.concat(new ByteString(Convert.toHexByte(hash160.length), HEX))
.concat(hash160)
.concat(OP_EQUAL)
.concat(ZenReplayProtection)
VI(script.length).concat(script)
else
script =
OP_HASH160
.concat(new ByteString(Convert.toHexByte(hash160.length), HEX))
.concat(hash160)
.concat(OP_EQUAL)
VI(script.length).concat(script)
OpReturnScript = (data) =>
if ledger.config.network.name is "zencash"
script =
OP_RETURN
.concat(new ByteString(Convert.toHexByte(data.length / 2), HEX))
.concat(new ByteString(data, HEX))
.concat(ZenReplayProtection)
VI(script.length).concat(script)
else
script =
OP_RETURN
.concat(new ByteString(Convert.toHexByte(data.length / 2), HEX))
.concat(new ByteString(data, HEX))
VI(script.length).concat(script)
numberOfOutputs = 1 + (if (changeAmount.lte(0)) then 0 else 1) + (if (data?) then 1 else 0)
outputScript =
VI(numberOfOutputs)
.concat(amount.toScriptByteString())
.concat(PkScript(recipientAddress))
if changeAmount.gt(0)
outputScript = outputScript
.concat(changeAmount.toScriptByteString())
.concat(PkScript(changeAddress))
if data?
outputScript = outputScript
.concat(ledger.Amount.fromSatoshi(0).toScriptByteString())
.concat(OpReturnScript(data))
task = =>
if ledger.config.network.ticker == 'abc' || (ledger.config.network.ticker == 'btg' && !ledger.config.network.handleSegwit) || ledger.config.network.ticker == 'zec'
promise = @_btchip.createPaymentTransactionNewBIP143_async(
false, false,
inputs, associatedKeysets, changePath,
outputScript,
lockTime && new ByteString(Convert.toHexInt(lockTime), HEX),
sighashType && new ByteString(Convert.toHexInt(sighashType), HEX),
authorization && new ByteString(authorization, HEX),
resumeData
)
else
if ledger.config.network.handleSegwit
promise = @_btchip.createPaymentTransactionNewBIP143_async(
true, ledger.config.network.ticker == 'btg',
inputs, associatedKeysets, changePath,
outputScript,
lockTime && new ByteString(Convert.toHexInt(lockTime), HEX),
sighashType && new ByteString(Convert.toHexInt(sighashType), HEX),
authorization && new ByteString(authorization, HEX),
resumeData
)
else
promise = @_btchip.createPaymentTransactionNew_async(
inputs, associatedKeysets, changePath,
outputScript,
lockTime && new ByteString(Convert.toHexInt(lockTime), HEX),
sighashType && new ByteString(Convert.toHexInt(sighashType), HEX),
authorization && new ByteString(authorization, HEX),
resumeData
)
promise.then( (result) ->
if result instanceof ByteString
result = result.toString(HEX)
else
result.scriptData = result.scriptData.toString(HEX)
result.trustedInputs = (trustedInput.toString(HEX) for trustedInput in result.trustedInputs)
result.publicKeys = (publicKey.toString(HEX) for publicKey in result.publicKeys)
result.authorizationPaired = result.authorizationPaired.toString(HEX) if result.authorizationPaired?
result.authorizationReference = result.authorizationReference.toString(HEX) if result.authorizationReference?
result.encryptedOutputScript = result.encryptedOutputScript?.toString(HEX)
return result
)
_btchipQueue.enqueue("createPaymentTransaction", task, (if (@getFirmwareInformation().hasScreenAndButton()) then 72000000 else undefined))
.fail (er) ->
e er
formatP2SHOutputScript: (transaction) ->
@_btchip.formatP2SHOutputScript(transaction)
###
@return [Q.Promise]
###
signP2SHTransaction: (inputs, scripts, numOutputs, output, paths) ->
_btchipQueue.enqueue "signP2SHTransaction", =>
@_btchip.signP2SHTransaction_async(inputs, scripts, numOutputs, output, paths)
###
@param [String] input hex encoded
@return [Object]
[Array<Byte>] version length is 4
[Array<Object>] inputs
[Array<Byte>] prevout length is 36
[Array<Byte>] script var length
[Array<Byte>] sequence length is 4
[Array<Object>] outputs
[Array<Byte>] amount length is 4
[Array<Byte>] script var length
[Array<Byte>] locktime length is 4
###
splitTransaction: (input, areTransactionTimestamped, isSegwitSupported) ->
@_btchip.splitTransaction(new ByteString(input.raw, HEX), areTransactionTimestamped, isSegwitSupported)
_sendApdu: (args...) ->
apdu = new ByteString('', HEX)
swCheck = undefined
for arg, index in args
if arg instanceof ByteString
apdu = apdu.concat(arg)
else if index is args.length - 1 and _.isArray(arg)
swCheck = arg
else
apdu = apdu.concat(new ByteString((if _.isNumber(arg) then Convert.toHexByte(arg) else arg.replace(/\s/g, '')), HEX))
@_btchip.card.sendApdu_async(apdu, swCheck)
# @return [Q.Promise] Must be done
_recoverFirmwareVersion: ->
_btchipQueue.enqueue "recoverFirmwareVersion", =>
@_sendApdu('E0 C4 00 00 00 08').then (version) =>
firmware = new ledger.dongle.FirmwareInformation(this, version)
if firmware.isUsingInputFinalizeFull()
@_btchip.setUntrustedHashTransactionInputFinalizeFull()
if firmware.isUsingDeprecatedBip32Derivation()
@_btchip.setDeprecatedBIP32Derivation()
if firmware.isUsingDeprecatedSetupKeymap()
@_btchip.setDeprecatedSetupKeymap()
@_btchip.setCompressedPublicKeys(firmware.hasCompressedPublicKeysSupport())
@_firmwareInformation = firmware
.fail (error) =>
e("Firmware version not supported :", error)
throw error
# @return [Q.Promise] Must be done
_recoverOperationMode: ->
_btchipQueue.enqueue "recoverOperationMode", =>
@_btchip.getOperationMode_async().then (mode) =>
@operationMode = mode
_setState: (newState, args...) ->
[@state, oldState] = [newState, @state]
@emit "state:#{@state}", @state, args...
@emit 'state:changed', @state
# Set appropriate state, and return corresponding Error
# @param [String] errorCode
# @return [Error]
_handleErrorCode: (errorCode) ->
if errorCode.match("6982") # Pin required
@_setState(States.LOCKED)
error = Errors.new(Errors.DongleLocked, errorCode)
else if errorCode.match("6985") # Error ?
@_setState(States.BLANK)
error = Errors.new(Errors.BlankDongle, errorCode)
else if errorCode.match("6faa")
@_setState(States.ERROR)
error = Errors.new(Errors.UnknowError, errorCode)
else if errorCode.match(/63c\d/)
error = Errors.new(Errors.WrongPinCode, errorCode)
error.retryCount = parseInt(errorCode.substr(-1))
if error.retryCount == 0
@_setState(States.BLANK)
error.code = Errors.DongleLocked
else
@_setState(States.ERROR)
else
@_setState(States.UnknowError)
error = Errors.new(Errors.UnknowError, errorCode)
return error
_convertMessageSignature: (pubKey, message, prefix, signature) ->
bitcoin = new BitcoinExternal()
hash = bitcoin.getSignedMessageHash(message, prefix)
pubKey = bitcoin.compressPublicKey(pubKey)
for i in [0...4]
recoveredKey = bitcoin.recoverPublicKey(signature, hash, i)
recoveredKey = bitcoin.compressPublicKey(recoveredKey)
if recoveredKey.equals(pubKey)
splitSignature = bitcoin.splitAsn1Signature(signature)
sig = new ByteString(Convert.toHexByte(i + 27 + 4), HEX).concat(splitSignature[0]).concat(splitSignature[1])
break
throw "Recovery failed" if ! sig?
return @_convertBase64(sig)
_convertBase64: (data) ->
codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
output = ""
leven = 3 * (Math.floor(data.length / 3))
offset = 0
for i in [0...leven] when i % 3 == 0
output += codes.charAt((data.byteAt(offset) >> 2) & 0x3f)
output += codes.charAt((((data.byteAt(offset) & 3) << 4) + (data.byteAt(offset + 1) >> 4)) & 0x3f)
output += codes.charAt((((data.byteAt(offset + 1) & 0x0f) << 2) + (data.byteAt(offset + 2) >> 6)) & 0x3f)
output += codes.charAt(data.byteAt(offset + 2) & 0x3f)
offset += 3
if i < data.length
a = data.byteAt(offset)
b = if (i + 1) < data.length then data.byteAt(offset + 1) else 0
output += codes.charAt((a >> 2) & 0x3f)
output += codes.charAt((((a & 3) << 4) + (b >> 4)) & 0x3f)
output += if (i + 1) < data.length then codes.charAt((((b & 0x0f) << 2)) & 0x3f) else '='
output += '='
return output
| 79459 |
States =
# Dongle juste created, not initialized.
UNDEFINED: undefined
# PIN required.
LOCKED: 'locked'
# PIN has been verified.
UNLOCKED: 'unlocked'
# No seed present, dongle must be setup.
BLANK: 'blank'
# Dongle has been unplugged.
DISCONNECTED: 'disconnected'
# An error appended, user must unplug/replug dongle.
ERROR: 'error'
Firmwares = ledger.dongle.Firmwares
Attestations = {}
class Attestation
xPoint: null
yPoint: null
Bytes: null
BatchId: null
DerivationId: null
constructor: (batchId, derivationId, value) ->
if _(this).isKindOf(Attestation)
@BatchId = batchId
@DerivationId = derivationId
@Id = Convert.toHexInt(batchId) + Convert.toHexInt(derivationId)
@String = value
@Bytes = parseInt(hex, 16) for hex in @String.match(/\w\w/g)
@xPoint = @String.substr(2,64)
@yPoint = @String.substr(66)
Attestations[@Id] = this
else
new Attestation(batchId, derivationId, value)
isBeta: -> @BatchId is 0
isProduction: -> !@isBeta()
getAttestationId: -> new ByteString(@Id, HEX)
Attestation(0, 1, "04e69fd3c044865200e66f124b5ea237c918503931bee070edfcab79a00a25d6b5a09afbee902b4b763ecf1f9c25f82d6b0cf72bce3faf98523a1066948f1a395f")
Attestation(1, 1, "04223314cdffec8740150afe46db3575fae84036<KEY>")
Attestation(2, 1, "<KEY>")
# This path do not need a verified PIN to sign messages.
BitIdRootPath = "0'/0/0xb11e"
Errors = @ledger.errors
$log = -> ledger.utils.Logger.getLoggerByTag("Dongle")
# Populate dongle namespace.
@ledger.dongle ?= {}
_.extend @ledger.dongle,
States: States
BitIdRootPath: BitIdRootPath
###
Signals :
@emit state:changed(States)
@emit state:locked
@emit state:unlocked
@emit state:blank
@emit state:disconnected
@emit state:error(args...)
###
class @ledger.dongle.Dongle extends EventEmitter
Dongle = @
# @property
id: undefined
# @property
deviceId: undefined
# @property
productId: undefined
# @property [String]
state: States.UNDEFINED
# @property [ByteString]
firmwareVersion: undefined
# @property [Integer]
operationMode: undefined
# @private [BtChip]
_btchip: undefined
# @private [Array<ledger.wallet.ExtendedPublicKey>]
_xpubs: []
# @private @property [String] pin used to unlock dongle.
_pin: undefined
# @private @property [ledger.utils.PromiseQueue] Enqueue btchip calls to prevent multiple call to interfer
_btchipQueue = undefined
constructor: (card) ->
super
@_attestation = null
@_xpubs = _.clone(@_xpubs)
@id = card.deviceId
@deviceId = card.deviceId
@productId = card.productId
_btchipQueue = new ledger.utils.PromiseQueue("Dongle##{@id}")
@_btchip = new BTChip(card)
# Recovers dongle firmware version and initialize current state
connect: (forceBootloader = no, callback = undefined) ->
# Recover firmware version
# Create firmware info object
# Determine state (setup|locked|unlocked|blank)
# Resolve
@_forceBl = forceBootloader
@state = States.UNDEFINED
unless @isInBootloaderMode()
@_recoverFirmwareVersion().then =>
if @getFirmwareInformation().hasSetupFirmwareSupport() && !@getFirmwareInformation().hasScreenAndButton()
@getRemainingPinAttempt().then =>
@_setState(States.LOCKED)
States.LOCKED
.fail (error) =>
@_setState(States.BLANK)
States.BLANK
else
# Nano S, Blue
if @getFirmwareInformation().hasScreenAndButton()
@ensureDeviceIsUnlocked(on)
@_setState States.UNLOCKED
States.UNLOCKED
else
@_sendApdu(0xE0, 0x40, 0x00, 0x00, 0x05, 0x01).then (result) =>
switch @getSw()
when 0x9000, 0x6982
@_setState States.LOCKED
States.LOCKED
when 0x6985
configureBlank = =>
@_setState(States.BLANK)
States.BLANK
# Check restore
if @getFirmwareInformation().hasSubFirmwareSupport() and @getFirmwareInformation().hasOperationFirmwareSupport()
@restoreSetup().then =>
@_setState States.LOCKED
States.LOCKED
.catch => do configureBlank
else
do configureBlank
when 0x6faa
throw "Invalid statue - 0x6faa"
.catch (error) =>
console.error("Fail to initialize Dongle :", error)
@_setState(States.ERROR)
throw error
else
ledger.delay(0).then(=> @_setState States.BLANK).then(-> States.BLANK)
isNanoS: -> @productId == 0x0001
ensureDeviceIsUnlocked: (runForever = no) ->
return if @_ensureDeviceIsUnlockedTimeout?
@_ensureDeviceIsUnlockedTimeout = _.delay(() =>
@getPublicAddress("0'/0xb11e'").then =>
yes
.fail (err) =>
if @state is States.LOCKED
@disconnect()
yes
.then =>
@_ensureDeviceIsUnlockedTimeout = undefined
@ensureDeviceIsUnlocked(runForever) if runForever
.done()
, 30000)
setCoinVersion: (p2pkhVersion, p2shVersion, callback = undefined) ->
d = ledger.defer(callback)
if (@getFirmwareInformation().hasUInt16CoinVersion())
@_sendApdu(new ByteString("E014000002#{Convert.toHexShort(p2pkhVersion)}#{Convert.toHexShort(p2shVersion)}", HEX)).then ->
d.resolve()
.fail (e) ->
d.reject(e)
else
@_sendApdu(new ByteString("E014000002#{("0" + p2pkhVersion.toString(16)).substr(-2)}#{("0" + p2shVersion.toString(16)).substr(-2)}", HEX)).then ->
d.resolve()
.fail (e) ->
d.reject(e)
d.promise
getCoinVersion: (callback = undefined) ->
d = ledger.defer(callback)
d.resolve(
@_sendApdu(new ByteString("E016000000", HEX)).then (result) =>
if (@getFirmwareInformation().hasUInt16CoinVersion())
P2PKH = (result.byteAt(0) << 8) + result.byteAt(1)
P2SH = (result.byteAt(2) << 8) + result.byteAt(3)
message = result.bytes(5, result.byteAt(4))
short = result.bytes(5 + message.length + 1, result.byteAt(5 + message.length))
else
P2PKH = result.byteAt(0)
P2SH = result.byteAt(1)
message = result.bytes(3, result.byteAt(2))
short = result.bytes(3 + message.length + 1, result.byteAt(3 + message.length))
{P2PKH: P2PKH, P2SH: P2SH, message: "#{message} signed message:\n", short: short}
.fail =>
l "FAILED"
{P2PKH: ledger.bitcoin.Networks.bitcoin.version.regular, P2SH: ledger.bitcoin.Networks.bitcoin.version.P2SH, message: "Bitcoin signed message:\n", short: 'BTC'}
)
d.promise
getFirmwareInformation: -> @_firmwareInformation
getSw: -> @_btchip.card.SW
# Called when
disconnect: ->
clearTimeout(@_ensureDeviceIsUnlockedTimeout) if @_ensureDeviceIsUnlockedTimeout?
@_ensureDeviceIsUnlockedTimeout = undefined
@_btchip.card.disconnect()
@_setState(States.DISCONNECTED)
# @return [String] Firmware version, 1.0.0 for example.
getStringFirmwareVersion: -> Try(=> @getFirmwareInformation().getStringFirmwareVersion()).getOrElse('unknown')
# @return [Integer] Firmware version, 0x20010000010f for example.
getIntFirmwareVersion: -> @getFirmwareInformation().getIntFirmwareVersion()
###
Gets the raw version {ByteString} of the dongle.
@param [Boolean] isInBootLoaderMode Must be true if the current dongle is in bootloader mode.
@param [Boolean] forceBl Force the call in BootLoader mode
@param [Function] callback Called once the version is retrieved. The callback must be prototyped like size `(version, error) ->`
@return [Q.Promise]
###
getRawFirmwareVersion: (isInBootLoaderMode, forceBl=no, checkHiddenReloader = no, callback=undefined) ->
_btchipQueue.enqueue "getRawFirmwareVersion", =>
d = ledger.defer(callback)
apdu = new ByteString((if !isInBootLoaderMode and !forceBl then "E0C4000000" else "F001000000"), HEX)
@_sendApdu(apdu).then (result) =>
sw = @_btchip.card.SW
if !isInBootLoaderMode and !forceBl
if sw is 0x9000
d.resolve([result.byteAt(1), (result.byteAt(2) << 16) + (result.byteAt(3) << 8) + result.byteAt(4)])
else
# Not initialized now - Retry
d.resolve @getRawFirmwareVersion(isInBootLoaderMode, yes)
else
if sw is 0x9000
# Bootloader ok, let's see if hidden reloader
result2 = result
apdu = new ByteString("E001000000", HEX)
if checkHiddenReloader
@_sendApdu(apdu).then (result) =>
if @_btchip.card.SW isnt 0x9000
result = result2
d.resolve([0, (result.byteAt(5) << 16) + (result.byteAt(6) << 8) + result.byteAt(7)])
.fail ->
result = result2
d.resolve([0, (result.byteAt(5) << 16) + (result.byteAt(6) << 8) + result.byteAt(7)])
else
result = result2
d.resolve([0, (result.byteAt(5) << 16) + (result.byteAt(6) << 8) + result.byteAt(7)])
else if !isInBootLoaderMode and (sw is 0x6d00 or sw is 0x6e00)
# Unexpected - let's say it's 1.4.3
d.resolve([0, (1 << 16) + (4 << 8) + (3)])
else
d.rejectWithError(ledger.errors.UnknowError, "Failed to get version")
.fail (error) ->
d.rejectWithError(ledger.errors.UnknowError, error)
.catch (error) ->
console.error("Fail to getRawFirmwareVersion :", error)
.done()
d.promise
# @return [Boolean]
isInBootloaderMode: -> if @productId is 0x1808 or @productId is 0x1807 or @_forceBl then yes else no
# @return [ledger.fup.FirmwareUpdater]
getFirmwareUpdater: () -> ledger.fup.FirmwareUpdater.instance
# @return [Q.Promise]
isFirmwareUpdateAvailable: (callback=undefined) ->
d = ledger.defer(callback)
@getFirmwareUpdater().getFirmwareUpdateAvailability(this)
.then (availablity) ->
d.resolve(availablity.result is ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Update)
.fail (er) ->
d.rejectWithError(er)
.done()
d.promise
# @return [Q.Promise]
isFirmwareOverwriteOrUpdateAvailable: (callback=undefined) ->
d = ledger.defer(callback)
@getFirmwareUpdater().getFirmwareUpdateAvailability(this)
.then (availablity) ->
d.resolve(availablity.result is ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Update or availablity.result is ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Overwrite)
.fail (er) ->
d.rejectWithError(er)
.done()
d.promise
# Verify that dongle firmware is "official".
# @param [Function] callback Optional argument
# @return [Q.Promise]
isCertified: (callback=undefined) -> @_checkCertification(no, callback)
isBetaCertified: (callback=undefined) -> @_checkCertification(yes, callback)
_checkCertification: (isBeta, callback = undefined) ->
_btchipQueue.enqueue "checkCertification", =>
d = ledger.defer(callback)
return d.resolve(true).promise if @getIntFirmwareVersion() < ledger.dongle.Firmwares.V_L_1_0_0
randomValues = new Uint32Array(2)
crypto.getRandomValues(randomValues)
random = _.str.lpad(randomValues[0].toString(16), 8, '0') + _.str.lpad(randomValues[1].toString(16), 8, '0')
# 24.2. GET DEVICE ATTESTATION
@_sendApdu(new ByteString("E0"+"C2"+"00"+"00"+"08"+random, HEX), [0x9000])
.then (result) =>
attestation = result.toString(HEX)
dataToSign = attestation.substring(16,32) + random
dataSig = attestation.substring(32)
dataSig = "30" + dataSig.substr(2)
dataSigBytes = (parseInt(n,16) for n in dataSig.match(/\w\w/g))
sha = new JSUCrypt.hash.SHA256()
domain = JSUCrypt.ECFp.getEcDomainByName("secp256k1")
if isBeta
Attestation = Attestations["0000000000000001"]
else
Attestation = Attestations[result.bytes(0, 8).toString()]
affinePoint = new JSUCrypt.ECFp.AffinePoint(Attestation.xPoint, Attestation.yPoint)
pubkey = new JSUCrypt.key.EcFpPublicKey(256, domain, affinePoint)
ecsig = new JSUCrypt.signature.ECDSA(sha)
ecsig.init(pubkey, JSUCrypt.signature.MODE_VERIFY)
if ecsig.verify(dataToSign, dataSigBytes)
@_attestation = Attestation
d.resolve(this)
else
d.rejectWithError(Errors.DongleNotCertified)
return
.fail (err) =>
d.rejectWithError(Errors.CommunicationError, err)
.done()
d.promise
getAttestation: -> @_attestation
# Return asynchronously state. Wait until a state is set.
# @param [Function] callback Optional argument
# @return [Q.Promise]
getState: (callback=undefined) ->
d = ledger.defer(callback)
if @state is States.UNDEFINED
@once 'state:changed', (e, state) => d.resolve(state)
else
d.resolve(@state)
d.promise
# @return [Q.Promise] resolve with a Number, reject with a ledger Error.
getRemainingPinAttempt: (callback=undefined) ->
_btchipQueue.enqueue "getRemainingPinAttempt", =>
d = ledger.defer(callback)
@_sendApdu(new ByteString("E0228000010000", HEX), [0x9000])
.catch (statusCode) =>
if m = statusCode.match(/63c(\d)/)
d.resolve(parseInt(m[1]))
else
d.reject(@_handleErrorCode(statusCode))
.done()
d.promise
# @param [String] pin ASCII encoded
# @param [Function] callback Optional argument
# @return [Q.Promise]
unlockWithPinCode: (pin, callback=undefined) ->
Errors.throw(Errors.DongleAlreadyUnlock) if @state is States.UNLOCKED
_btchipQueue.enqueue "unlockWithPinCode", =>
d = ledger.defer(callback)
@_pin = pin
@_btchip.verifyPin_async(new ByteString(@_pin, ASCII))
.then =>
if @getFirmwareInformation().hasSubFirmwareSupport() and @getFirmwareInformation().hasSetupFirmwareSupport()
d.resolve()
return
# 19.7. SET OPERATION MODE
@_sendApdu(0xE0, 0x26, 0x01, 0x01, 0x01, 0x01, [0x9000])
.then =>
if @getIntFirmwareVersion() >= Firmwares.V_B_1_4_13
# 19.7. SET OPERATION MODE
mode = if @getIntFirmwareVersion() >= Firmwares.V_L_1_0_0 then 0x02 else 0x01
@_sendApdu(0xE0, 0x26, mode, 0x00, 0x01, 0x01, [0x9000]).fail(=> e('Unlock FAIL', arguments)).done()
@_setState(States.UNLOCKED)
d.resolve()
.fail (err) =>
error = Errors.new(Errors.NotSupportedDongle, err)
console.log("unlockWithPinCode 2 fail :", err)
d.reject(error)
.catch (error) ->
console.error("Fail to unlockWithPinCode 2 :", error)
.done()
.fail (err) =>
console.error("Fail to unlockWithPinCode 1 :", err)
error = @_handleErrorCode(err)
d.reject(error)
.catch (error) ->
console.error("Fail to unlockWithPinCode 1 :", error)
.done()
d.promise
lock: () ->
if @state isnt ledger.dongle.States.BLANK and @state?
@_setState(States.LOCKED)
###
@overload setup(pin, callback)
@param [String] pin
@param [Function] callback
@return [Q.Promise]
@overload setup(pin, options={}, callback=undefined)
@param [String] pin
@param [String] restoreSeed
@options options [String] restoreSeed
@options options [ByteString] keyMap
@param [Function] callback
@return [Q.Promise]
###
setup: (pin, restoreSeed, callback=undefined) ->
Errors.throw(Errors.DongleNotBlank) if @state isnt States.BLANK
[restoreSeed, callback] = [callback, restoreSeed] if ! callback && typeof restoreSeed == 'function'
_btchipQueue.enqueue "setup", =>
d = ledger.defer(callback)
# Validate seed
if restoreSeed?
bytesSeed = new ByteString(restoreSeed, HEX)
if bytesSeed.length != 64
e('Invalid seed :', restoreSeed)
return d.reject().promise
@_btchip.setupNew_async(
BTChip.MODE_WALLET,
BTChip.FEATURE_DETERMINISTIC_SIGNATURE | BTChip.FEATURE_NO_2FA_P2SH,
ledger.config.network.version.regular,
ledger.config.network.version.P2SH,
new ByteString(pin, ASCII),
undefined,
BTChip.QWERTY_KEYMAP_NEW,
restoreSeed?,
bytesSeed
).then( =>
if restoreSeed?
msg = "Seed restored, please reopen the extension"
else
msg = "Plug the dongle into a secure host to read the generated seed, then reopen the extension"
console.warn(msg)
@_setState(States.ERROR, msg)
d.resolve()
).fail( (err) =>
error = Errors.new(Errors.UnknowError, err)
d.reject(error)
).catch( (error) ->
console.error("Fail to setup :", error)
).done()
d.promise
setupSwappedBip39: (pin, userEntropy = undefined, callback = undefined) -> @_setupSwappedBip39({pin, userEntropy, callback})
restoreSwappedBip39: (pin, restoreSeed, callback = undefined) -> @_setupSwappedBip39({pin, restoreSeed, callback})
verifyAddressOnScreen: (path, callback) ->
Errors.throw(Errors.DongleLocked, 'Cannot get a public while the key is not unlocked') if @state isnt States.UNLOCKED && @state isnt States.UNDEFINED
_btchipQueue.enqueue "getPublicAddress", =>
d = ledger.defer(callback)
@_btchip.getWalletPublicKey_async(path, true, ledger.config.network.handleSegwit)
.then (result) =>
#ledger.wallet.Wallet.instance?.cache?.set [[path, result.bitcoinAddress.value]]
_.defer -> d.resolve(result)
.fail (err) =>
_.defer -> d.resolve({})
.done()
d.promise
_setupSwappedBip39: ({pin, userEntropy, restoreSeed, callback}) ->
Errors.throw(Errors.DongleNotBlank) if @state isnt States.BLANK
userEntropy ||= ledger.bitcoin.bip39.generateEntropy()
if restoreSeed?
indexes = ledger.bitcoin.bip39.mnemonicPhraseToWordIndexes(restoreSeed)
restoreSeed = (Convert.toHexShort(index) for index in indexes).join('')
d = ledger.defer(callback)
@_btchip.setupNew_async(
BTChip.MODE_WALLET,
BTChip.FEATURE_DETERMINISTIC_SIGNATURE | BTChip.FEATURE_NO_2FA_P2SH,
ledger.config.network.version.regular,
ledger.config.network.version.P2SH,
new ByteString(pin, ASCII),
undefined,
undefined,
false,
new ByteString(restoreSeed or userEntropy, HEX),
undefined, !restoreSeed?, restoreSeed?
).then (result) =>
mnemonic = []
for i in [0...24]
wordIndex = (result['swappedMnemonic'].byteAt(2 * i) << 8) + (result['swappedMnemonic'].byteAt(2 * i + 1))
mnemonic.push ledger.bitcoin.bip39.wordlist[wordIndex]
d.resolve(_.extend(result, mnemonic: mnemonic))
.fail (error) =>
d.reject(error)
.done()
d.promise
setupFinalizeBip39: (callback = undefined) ->
ledger.defer(callback).resolve(@_btchip.setupFinalizeBip39_async()).promise
restoreFinalizeBip29: (callback = undefined) ->
ledger.defer(callback).resolve(@_btchip.setupRecovery_async()).promise
restoreSetup: (callback = undefined) -> @_sendApdu(0xE0, 0x20, 0xFF, 0x00, 0x01, 0x00, [0x9000]).then(callback or _.noop)
isSwappedBip39FeatureEnabled: ->
@setupSwappedBip39("0000").then(-> yes).fail(-> no)
# @param [String] path
# @param [Function] callback Optional argument
# @return [Q.Promise]
getPublicAddress: (path, callback=undefined) ->
Errors.throw(Errors.DongleLocked, 'Cannot get a public while the key is not unlocked') if @state isnt States.UNLOCKED && @state isnt States.UNDEFINED
_btchipQueue.enqueue "getPublicAddress", =>
d = ledger.defer(callback)
@_btchip.getWalletPublicKey_async(path, false, false)
.then (result) =>
#ledger.wallet.Wallet.instance?.cache?.set [[path, result.bitcoinAddress.value]]
_.defer -> d.resolve(result)
.fail (err) =>
error = @_handleErrorCode(err)
_.defer -> d.reject(error)
.catch (error) ->
console.error("Fail to getPublicAddress :", error)
.done()
d.promise
# @param [String] message
# @param [String] path Optional argument
# @param [Function] callback Optional argument
# @return [Q.Promise]
signMessage: (message, {prefix, path, pubKey}, callback=undefined) ->
prefix ?= '\x18Bitcoin Signed Message:\n'
if ! pubKey?
@getPublicAddress(path).then((address) => console.log("address=", address); @signMessage(message, path: path, pubKey: address.publicKey, callback))
else
_btchipQueue.enqueue "signMessage", =>
d = ledger.defer(callback)
message = new ByteString(message, ASCII)
@_btchip.signMessagePrepare_async(path, message)
.then =>
return @_btchip.signMessageSign_async(if (@_pin?) then new ByteString(@_pin, ASCII) else new ByteString("0000", ASCII))
.then (sig) =>
signedMessage = @_convertMessageSignature(pubKey, message, prefix, sig.signature)
d.resolve(signedMessage)
.catch (error) ->
console.error("Fail to signMessage :", error)
d.reject(error)
.done()
d.promise
# @param [String] pubKey public key, hex encoded.
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve with a 32 bytes length pairing blob hex encoded.
initiateSecureScreen: (pubKey, callback=undefined) ->
_btchipQueue.enqueue "initiateSecureScreen", =>
d = ledger.defer(callback)
if @state != States.UNLOCKED
d.rejectWithError(Errors.DongleLocked)
else if ! pubKey.match(/^[<KEY>1<KEY>}$/)?
d.rejectWithError(Errors.InvalidArgument, "Invalid pubKey : #{pubKey}")
else
# 19.3. SETUP SECURE SCREEN
@_sendApdu(new ByteString("E0"+"12"+"01"+"00"+"41"+pubKey, HEX), [0x9000])
.then (c) ->
l 'initiateSecureScreen', c
d.resolve(c.toString())
.fail (error) -> d.reject(error)
.done()
d.promise
# @param [String] resp challenge response, hex encoded.
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve if pairing is successful.
confirmSecureScreen: (resp, callback=undefined) ->
_btchipQueue.enqueue "confirmSecureScreen", =>
d = ledger.defer(callback)
if @state != States.UNLOCKED
d.rejectWithError(Errors.DongleLocked)
else if ! resp.match(/^[0-9A-Fa-f]{32}$/)?
d.rejectWithError(Errors.InvalidArgument, "Invalid challenge resp : #{resp}")
else
# 19.3. SETUP SECURE SCREEN
@_sendApdu(new ByteString("E0"+"12"+"02"+"00"+"10"+resp, HEX), [0x9000])
.then () ->
l 'confirmSecureScreen'
d.resolve()
.fail (error) -> d.reject(error)
.done()
d.promise
# @param [String] path
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve if pairing is successful.
getExtendedPublicKey: (path, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state != States.UNLOCKED
d = ledger.defer(callback)
return d.resolve(@_xpubs[path]).promise if @_xpubs[path]?
xpub = new ledger.wallet.ExtendedPublicKey(@, path)
xpub.initialize () =>
@_xpubs[path] = xpub
d.resolve(xpub)
d.promise
###
@param [Array<Object>] inputs
@param [Array] associatedKeysets
@param changePath
@param [String] changeAddress
@param [String] recipientAddress
@param [Amount] amount
@param [Amount] fee
@param [Integer] lockTime
@param [Integer] sighashType
@param [String] authorization hex encoded
@param [Object] resumeData
@return [Q.Promise] Resolve with resumeData
###
createPaymentTransaction: (inputs, associatedKeysets, changePath, changeAddress, recipientAddress, amount, fees, data, lockTime, sighashType, authorization, resumeData) ->
if resumeData?
resumeData = _.clone(resumeData)
resumeData.scriptData = new ByteString(resumeData.scriptData, HEX)
resumeData.trustedInputs = (new ByteString(trustedInput, HEX) for trustedInput in resumeData.trustedInputs)
resumeData.publicKeys = (new ByteString(publicKey, HEX) for publicKey in resumeData.publicKeys)
if @getFirmwareInformation().isUsingInputFinalizeFull()
@_createPaymentTransactionNew(inputs, associatedKeysets, changePath, changeAddress, recipientAddress, amount, fees, lockTime, sighashType, authorization, data, resumeData)
else
@_createPaymentTransaction(inputs, associatedKeysets, changePath, recipientAddress, amount, fees, lockTime, sighashType, authorization, resumeData)
_createPaymentTransaction: (inputs, associatedKeysets, changePath, recipientAddress, amount, fees, lockTime, sighashType, authorization, resumeData) ->
_btchipQueue.enqueue "createPaymentTransaction", =>
@_btchip.createPaymentTransaction_async(
inputs, associatedKeysets, changePath,
new ByteString(recipientAddress, ASCII),
amount.toByteString(),
fees.toByteString(),
lockTime && new ByteString(Convert.toHexInt(lockTime), HEX),
sighashType && new ByteString(Convert.toHexInt(sighashType), HEX),
authorization && new ByteString(authorization, HEX),
resumeData
).then( (result) ->
if result instanceof ByteString
result = result.toString(HEX)
else
result.scriptData = result.scriptData.toString(HEX)
result.trustedInputs = (trustedInput.toString(HEX) for trustedInput in result.trustedInputs)
result.publicKeys = (publicKey.toString(HEX) for publicKey in result.publicKeys)
result.authorizationPaired = result.authorizationPaired.toString(HEX) if result.authorizationPaired?
result.authorizationReference = result.authorizationReference.toString(HEX) if result.authorizationReference?
return result
)
_createPaymentTransactionNew: (inputs, associatedKeysets, changePath, changeAddress, recipientAddress, amount, fees, lockTime, sighashType, authorization, data, resumeData) ->
@getPublicAddress(changePath).then (result) =>
changeAddress2 = result.bitcoinAddress.toString(ASCII)
inputAmounts = do =>
for [prevTx, index], i in inputs
ledger.Amount.fromSatoshi(prevTx.outputs[index].amount)
totalInputAmount = ledger.Amount.fromSatoshi(0)
for inputAmount in inputAmounts
totalInputAmount = totalInputAmount.add(inputAmount)
changeAmount = totalInputAmount.subtract(amount).subtract(fees)
changePath = undefined if changeAmount.lte(0)
VI = @_btchip.createVarint.bind(@_btchip)
OP_DUP = new ByteString('76', HEX)
OP_HASH160 = new ByteString('A9', HEX)
OP_EQUAL = new ByteString('87', HEX)
OP_EQUALVERIFY = new ByteString('88', HEX)
OP_CHECKSIG = new ByteString('AC', HEX)
OP_RETURN = new ByteString('6A', HEX)
if ledger.config.network.name is "zencash"
ParamHash = new ByteString('209ec9845acb02fab24e1c0368b3b517c1a4488fba97f0e3459ac053ea01000000', HEX)
AdjustAlign = new ByteString('03', HEX)
ParamHeight = new ByteString('c01f02', HEX)
OP_CHECKBLOCKATHEIGHT = new ByteString('b4', HEX)
ZenReplayProtection = ParamHash.concat(AdjustAlign).concat(ParamHeight).concat(OP_CHECKBLOCKATHEIGHT)
###
Create the output script
Count (VI) | Value (8) | PkScript (var) | ....
###
PkScript = (address) =>
hash160WithNetwork = ledger.bitcoin.addressToHash160WithNetwork(address)
p2pkhNetworkVersionSize = hash160WithNetwork.length - 20
hash160 = hash160WithNetwork.bytes(p2pkhNetworkVersionSize, hash160WithNetwork.length - p2pkhNetworkVersionSize) #ledger.bitcoin.addressToHash160(address)
if p2pkhNetworkVersionSize is 1
return P2shScript(hash160) if hash160WithNetwork.byteAt(0) is ledger.config.network.version.P2SH
else
return P2shScript(hash160) if (hash160WithNetwork.byteAt(0) << 8 | hash160WithNetwork.byteAt(1)) is ledger.config.network.version.P2SH
if ledger.config.network.name is "zencash"
script =
OP_DUP
.concat(OP_HASH160)
.concat(new ByteString(Convert.toHexByte(hash160.length), HEX))
.concat(hash160)
.concat(OP_EQUALVERIFY)
.concat(OP_CHECKSIG)
.concat(ZenReplayProtection)
VI(script.length).concat(script)
else
script =
OP_DUP
.concat(OP_HASH160)
.concat(new ByteString(Convert.toHexByte(hash160.length), HEX))
.concat(hash160)
.concat(OP_EQUALVERIFY)
.concat(OP_CHECKSIG)
VI(script.length).concat(script)
P2shScript = (hash160) =>
if ledger.config.network.name is "zencash"
script =
OP_HASH160
.concat(new ByteString(Convert.toHexByte(hash160.length), HEX))
.concat(hash160)
.concat(OP_EQUAL)
.concat(ZenReplayProtection)
VI(script.length).concat(script)
else
script =
OP_HASH160
.concat(new ByteString(Convert.toHexByte(hash160.length), HEX))
.concat(hash160)
.concat(OP_EQUAL)
VI(script.length).concat(script)
OpReturnScript = (data) =>
if ledger.config.network.name is "zencash"
script =
OP_RETURN
.concat(new ByteString(Convert.toHexByte(data.length / 2), HEX))
.concat(new ByteString(data, HEX))
.concat(ZenReplayProtection)
VI(script.length).concat(script)
else
script =
OP_RETURN
.concat(new ByteString(Convert.toHexByte(data.length / 2), HEX))
.concat(new ByteString(data, HEX))
VI(script.length).concat(script)
numberOfOutputs = 1 + (if (changeAmount.lte(0)) then 0 else 1) + (if (data?) then 1 else 0)
outputScript =
VI(numberOfOutputs)
.concat(amount.toScriptByteString())
.concat(PkScript(recipientAddress))
if changeAmount.gt(0)
outputScript = outputScript
.concat(changeAmount.toScriptByteString())
.concat(PkScript(changeAddress))
if data?
outputScript = outputScript
.concat(ledger.Amount.fromSatoshi(0).toScriptByteString())
.concat(OpReturnScript(data))
task = =>
if ledger.config.network.ticker == 'abc' || (ledger.config.network.ticker == 'btg' && !ledger.config.network.handleSegwit) || ledger.config.network.ticker == 'zec'
promise = @_btchip.createPaymentTransactionNewBIP143_async(
false, false,
inputs, associatedKeysets, changePath,
outputScript,
lockTime && new ByteString(Convert.toHexInt(lockTime), HEX),
sighashType && new ByteString(Convert.toHexInt(sighashType), HEX),
authorization && new ByteString(authorization, HEX),
resumeData
)
else
if ledger.config.network.handleSegwit
promise = @_btchip.createPaymentTransactionNewBIP143_async(
true, ledger.config.network.ticker == 'btg',
inputs, associatedKeysets, changePath,
outputScript,
lockTime && new ByteString(Convert.toHexInt(lockTime), HEX),
sighashType && new ByteString(Convert.toHexInt(sighashType), HEX),
authorization && new ByteString(authorization, HEX),
resumeData
)
else
promise = @_btchip.createPaymentTransactionNew_async(
inputs, associatedKeysets, changePath,
outputScript,
lockTime && new ByteString(Convert.toHexInt(lockTime), HEX),
sighashType && new ByteString(Convert.toHexInt(sighashType), HEX),
authorization && new ByteString(authorization, HEX),
resumeData
)
promise.then( (result) ->
if result instanceof ByteString
result = result.toString(HEX)
else
result.scriptData = result.scriptData.toString(HEX)
result.trustedInputs = (trustedInput.toString(HEX) for trustedInput in result.trustedInputs)
result.publicKeys = (publicKey.toString(HEX) for publicKey in result.publicKeys)
result.authorizationPaired = result.authorizationPaired.toString(HEX) if result.authorizationPaired?
result.authorizationReference = result.authorizationReference.toString(HEX) if result.authorizationReference?
result.encryptedOutputScript = result.encryptedOutputScript?.toString(HEX)
return result
)
_btchipQueue.enqueue("createPaymentTransaction", task, (if (@getFirmwareInformation().hasScreenAndButton()) then 72000000 else undefined))
.fail (er) ->
e er
formatP2SHOutputScript: (transaction) ->
@_btchip.formatP2SHOutputScript(transaction)
###
@return [Q.Promise]
###
signP2SHTransaction: (inputs, scripts, numOutputs, output, paths) ->
_btchipQueue.enqueue "signP2SHTransaction", =>
@_btchip.signP2SHTransaction_async(inputs, scripts, numOutputs, output, paths)
###
@param [String] input hex encoded
@return [Object]
[Array<Byte>] version length is 4
[Array<Object>] inputs
[Array<Byte>] prevout length is 36
[Array<Byte>] script var length
[Array<Byte>] sequence length is 4
[Array<Object>] outputs
[Array<Byte>] amount length is 4
[Array<Byte>] script var length
[Array<Byte>] locktime length is 4
###
splitTransaction: (input, areTransactionTimestamped, isSegwitSupported) ->
@_btchip.splitTransaction(new ByteString(input.raw, HEX), areTransactionTimestamped, isSegwitSupported)
_sendApdu: (args...) ->
apdu = new ByteString('', HEX)
swCheck = undefined
for arg, index in args
if arg instanceof ByteString
apdu = apdu.concat(arg)
else if index is args.length - 1 and _.isArray(arg)
swCheck = arg
else
apdu = apdu.concat(new ByteString((if _.isNumber(arg) then Convert.toHexByte(arg) else arg.replace(/\s/g, '')), HEX))
@_btchip.card.sendApdu_async(apdu, swCheck)
# @return [Q.Promise] Must be done
_recoverFirmwareVersion: ->
_btchipQueue.enqueue "recoverFirmwareVersion", =>
@_sendApdu('E0 C4 00 00 00 08').then (version) =>
firmware = new ledger.dongle.FirmwareInformation(this, version)
if firmware.isUsingInputFinalizeFull()
@_btchip.setUntrustedHashTransactionInputFinalizeFull()
if firmware.isUsingDeprecatedBip32Derivation()
@_btchip.setDeprecatedBIP32Derivation()
if firmware.isUsingDeprecatedSetupKeymap()
@_btchip.setDeprecatedSetupKeymap()
@_btchip.setCompressedPublicKeys(firmware.hasCompressedPublicKeysSupport())
@_firmwareInformation = firmware
.fail (error) =>
e("Firmware version not supported :", error)
throw error
# @return [Q.Promise] Must be done
_recoverOperationMode: ->
_btchipQueue.enqueue "recoverOperationMode", =>
@_btchip.getOperationMode_async().then (mode) =>
@operationMode = mode
_setState: (newState, args...) ->
[@state, oldState] = [newState, @state]
@emit "state:#{@state}", @state, args...
@emit 'state:changed', @state
# Set appropriate state, and return corresponding Error
# @param [String] errorCode
# @return [Error]
_handleErrorCode: (errorCode) ->
if errorCode.match("6982") # Pin required
@_setState(States.LOCKED)
error = Errors.new(Errors.DongleLocked, errorCode)
else if errorCode.match("6985") # Error ?
@_setState(States.BLANK)
error = Errors.new(Errors.BlankDongle, errorCode)
else if errorCode.match("6faa")
@_setState(States.ERROR)
error = Errors.new(Errors.UnknowError, errorCode)
else if errorCode.match(/63c\d/)
error = Errors.new(Errors.WrongPinCode, errorCode)
error.retryCount = parseInt(errorCode.substr(-1))
if error.retryCount == 0
@_setState(States.BLANK)
error.code = Errors.DongleLocked
else
@_setState(States.ERROR)
else
@_setState(States.UnknowError)
error = Errors.new(Errors.UnknowError, errorCode)
return error
_convertMessageSignature: (pubKey, message, prefix, signature) ->
bitcoin = new BitcoinExternal()
hash = bitcoin.getSignedMessageHash(message, prefix)
pubKey = bitcoin.compressPublicKey(pubKey)
for i in [0...4]
recoveredKey = bitcoin.recoverPublicKey(signature, hash, i)
recoveredKey = bitcoin.compressPublicKey(recoveredKey)
if recoveredKey.equals(pubKey)
splitSignature = bitcoin.splitAsn1Signature(signature)
sig = new ByteString(Convert.toHexByte(i + 27 + 4), HEX).concat(splitSignature[0]).concat(splitSignature[1])
break
throw "Recovery failed" if ! sig?
return @_convertBase64(sig)
_convertBase64: (data) ->
codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
output = ""
leven = 3 * (Math.floor(data.length / 3))
offset = 0
for i in [0...leven] when i % 3 == 0
output += codes.charAt((data.byteAt(offset) >> 2) & 0x3f)
output += codes.charAt((((data.byteAt(offset) & 3) << 4) + (data.byteAt(offset + 1) >> 4)) & 0x3f)
output += codes.charAt((((data.byteAt(offset + 1) & 0x0f) << 2) + (data.byteAt(offset + 2) >> 6)) & 0x3f)
output += codes.charAt(data.byteAt(offset + 2) & 0x3f)
offset += 3
if i < data.length
a = data.byteAt(offset)
b = if (i + 1) < data.length then data.byteAt(offset + 1) else 0
output += codes.charAt((a >> 2) & 0x3f)
output += codes.charAt((((a & 3) << 4) + (b >> 4)) & 0x3f)
output += if (i + 1) < data.length then codes.charAt((((b & 0x0f) << 2)) & 0x3f) else '='
output += '='
return output
| true |
States =
# Dongle juste created, not initialized.
UNDEFINED: undefined
# PIN required.
LOCKED: 'locked'
# PIN has been verified.
UNLOCKED: 'unlocked'
# No seed present, dongle must be setup.
BLANK: 'blank'
# Dongle has been unplugged.
DISCONNECTED: 'disconnected'
# An error appended, user must unplug/replug dongle.
ERROR: 'error'
Firmwares = ledger.dongle.Firmwares
Attestations = {}
class Attestation
xPoint: null
yPoint: null
Bytes: null
BatchId: null
DerivationId: null
constructor: (batchId, derivationId, value) ->
if _(this).isKindOf(Attestation)
@BatchId = batchId
@DerivationId = derivationId
@Id = Convert.toHexInt(batchId) + Convert.toHexInt(derivationId)
@String = value
@Bytes = parseInt(hex, 16) for hex in @String.match(/\w\w/g)
@xPoint = @String.substr(2,64)
@yPoint = @String.substr(66)
Attestations[@Id] = this
else
new Attestation(batchId, derivationId, value)
isBeta: -> @BatchId is 0
isProduction: -> !@isBeta()
getAttestationId: -> new ByteString(@Id, HEX)
Attestation(0, 1, "04e69fd3c044865200e66f124b5ea237c918503931bee070edfcab79a00a25d6b5a09afbee902b4b763ecf1f9c25f82d6b0cf72bce3faf98523a1066948f1a395f")
Attestation(1, 1, "04223314cdffec8740150afe46db3575fae84036PI:KEY:<KEY>END_PI")
Attestation(2, 1, "PI:KEY:<KEY>END_PI")
# This path do not need a verified PIN to sign messages.
BitIdRootPath = "0'/0/0xb11e"
Errors = @ledger.errors
$log = -> ledger.utils.Logger.getLoggerByTag("Dongle")
# Populate dongle namespace.
@ledger.dongle ?= {}
_.extend @ledger.dongle,
States: States
BitIdRootPath: BitIdRootPath
###
Signals :
@emit state:changed(States)
@emit state:locked
@emit state:unlocked
@emit state:blank
@emit state:disconnected
@emit state:error(args...)
###
class @ledger.dongle.Dongle extends EventEmitter
Dongle = @
# @property
id: undefined
# @property
deviceId: undefined
# @property
productId: undefined
# @property [String]
state: States.UNDEFINED
# @property [ByteString]
firmwareVersion: undefined
# @property [Integer]
operationMode: undefined
# @private [BtChip]
_btchip: undefined
# @private [Array<ledger.wallet.ExtendedPublicKey>]
_xpubs: []
# @private @property [String] pin used to unlock dongle.
_pin: undefined
# @private @property [ledger.utils.PromiseQueue] Enqueue btchip calls to prevent multiple call to interfer
_btchipQueue = undefined
constructor: (card) ->
super
@_attestation = null
@_xpubs = _.clone(@_xpubs)
@id = card.deviceId
@deviceId = card.deviceId
@productId = card.productId
_btchipQueue = new ledger.utils.PromiseQueue("Dongle##{@id}")
@_btchip = new BTChip(card)
# Recovers dongle firmware version and initialize current state
connect: (forceBootloader = no, callback = undefined) ->
# Recover firmware version
# Create firmware info object
# Determine state (setup|locked|unlocked|blank)
# Resolve
@_forceBl = forceBootloader
@state = States.UNDEFINED
unless @isInBootloaderMode()
@_recoverFirmwareVersion().then =>
if @getFirmwareInformation().hasSetupFirmwareSupport() && !@getFirmwareInformation().hasScreenAndButton()
@getRemainingPinAttempt().then =>
@_setState(States.LOCKED)
States.LOCKED
.fail (error) =>
@_setState(States.BLANK)
States.BLANK
else
# Nano S, Blue
if @getFirmwareInformation().hasScreenAndButton()
@ensureDeviceIsUnlocked(on)
@_setState States.UNLOCKED
States.UNLOCKED
else
@_sendApdu(0xE0, 0x40, 0x00, 0x00, 0x05, 0x01).then (result) =>
switch @getSw()
when 0x9000, 0x6982
@_setState States.LOCKED
States.LOCKED
when 0x6985
configureBlank = =>
@_setState(States.BLANK)
States.BLANK
# Check restore
if @getFirmwareInformation().hasSubFirmwareSupport() and @getFirmwareInformation().hasOperationFirmwareSupport()
@restoreSetup().then =>
@_setState States.LOCKED
States.LOCKED
.catch => do configureBlank
else
do configureBlank
when 0x6faa
throw "Invalid statue - 0x6faa"
.catch (error) =>
console.error("Fail to initialize Dongle :", error)
@_setState(States.ERROR)
throw error
else
ledger.delay(0).then(=> @_setState States.BLANK).then(-> States.BLANK)
isNanoS: -> @productId == 0x0001
ensureDeviceIsUnlocked: (runForever = no) ->
return if @_ensureDeviceIsUnlockedTimeout?
@_ensureDeviceIsUnlockedTimeout = _.delay(() =>
@getPublicAddress("0'/0xb11e'").then =>
yes
.fail (err) =>
if @state is States.LOCKED
@disconnect()
yes
.then =>
@_ensureDeviceIsUnlockedTimeout = undefined
@ensureDeviceIsUnlocked(runForever) if runForever
.done()
, 30000)
setCoinVersion: (p2pkhVersion, p2shVersion, callback = undefined) ->
d = ledger.defer(callback)
if (@getFirmwareInformation().hasUInt16CoinVersion())
@_sendApdu(new ByteString("E014000002#{Convert.toHexShort(p2pkhVersion)}#{Convert.toHexShort(p2shVersion)}", HEX)).then ->
d.resolve()
.fail (e) ->
d.reject(e)
else
@_sendApdu(new ByteString("E014000002#{("0" + p2pkhVersion.toString(16)).substr(-2)}#{("0" + p2shVersion.toString(16)).substr(-2)}", HEX)).then ->
d.resolve()
.fail (e) ->
d.reject(e)
d.promise
getCoinVersion: (callback = undefined) ->
d = ledger.defer(callback)
d.resolve(
@_sendApdu(new ByteString("E016000000", HEX)).then (result) =>
if (@getFirmwareInformation().hasUInt16CoinVersion())
P2PKH = (result.byteAt(0) << 8) + result.byteAt(1)
P2SH = (result.byteAt(2) << 8) + result.byteAt(3)
message = result.bytes(5, result.byteAt(4))
short = result.bytes(5 + message.length + 1, result.byteAt(5 + message.length))
else
P2PKH = result.byteAt(0)
P2SH = result.byteAt(1)
message = result.bytes(3, result.byteAt(2))
short = result.bytes(3 + message.length + 1, result.byteAt(3 + message.length))
{P2PKH: P2PKH, P2SH: P2SH, message: "#{message} signed message:\n", short: short}
.fail =>
l "FAILED"
{P2PKH: ledger.bitcoin.Networks.bitcoin.version.regular, P2SH: ledger.bitcoin.Networks.bitcoin.version.P2SH, message: "Bitcoin signed message:\n", short: 'BTC'}
)
d.promise
getFirmwareInformation: -> @_firmwareInformation
getSw: -> @_btchip.card.SW
# Called when
disconnect: ->
clearTimeout(@_ensureDeviceIsUnlockedTimeout) if @_ensureDeviceIsUnlockedTimeout?
@_ensureDeviceIsUnlockedTimeout = undefined
@_btchip.card.disconnect()
@_setState(States.DISCONNECTED)
# @return [String] Firmware version, 1.0.0 for example.
getStringFirmwareVersion: -> Try(=> @getFirmwareInformation().getStringFirmwareVersion()).getOrElse('unknown')
# @return [Integer] Firmware version, 0x20010000010f for example.
getIntFirmwareVersion: -> @getFirmwareInformation().getIntFirmwareVersion()
###
Gets the raw version {ByteString} of the dongle.
@param [Boolean] isInBootLoaderMode Must be true if the current dongle is in bootloader mode.
@param [Boolean] forceBl Force the call in BootLoader mode
@param [Function] callback Called once the version is retrieved. The callback must be prototyped like size `(version, error) ->`
@return [Q.Promise]
###
getRawFirmwareVersion: (isInBootLoaderMode, forceBl=no, checkHiddenReloader = no, callback=undefined) ->
_btchipQueue.enqueue "getRawFirmwareVersion", =>
d = ledger.defer(callback)
apdu = new ByteString((if !isInBootLoaderMode and !forceBl then "E0C4000000" else "F001000000"), HEX)
@_sendApdu(apdu).then (result) =>
sw = @_btchip.card.SW
if !isInBootLoaderMode and !forceBl
if sw is 0x9000
d.resolve([result.byteAt(1), (result.byteAt(2) << 16) + (result.byteAt(3) << 8) + result.byteAt(4)])
else
# Not initialized now - Retry
d.resolve @getRawFirmwareVersion(isInBootLoaderMode, yes)
else
if sw is 0x9000
# Bootloader ok, let's see if hidden reloader
result2 = result
apdu = new ByteString("E001000000", HEX)
if checkHiddenReloader
@_sendApdu(apdu).then (result) =>
if @_btchip.card.SW isnt 0x9000
result = result2
d.resolve([0, (result.byteAt(5) << 16) + (result.byteAt(6) << 8) + result.byteAt(7)])
.fail ->
result = result2
d.resolve([0, (result.byteAt(5) << 16) + (result.byteAt(6) << 8) + result.byteAt(7)])
else
result = result2
d.resolve([0, (result.byteAt(5) << 16) + (result.byteAt(6) << 8) + result.byteAt(7)])
else if !isInBootLoaderMode and (sw is 0x6d00 or sw is 0x6e00)
# Unexpected - let's say it's 1.4.3
d.resolve([0, (1 << 16) + (4 << 8) + (3)])
else
d.rejectWithError(ledger.errors.UnknowError, "Failed to get version")
.fail (error) ->
d.rejectWithError(ledger.errors.UnknowError, error)
.catch (error) ->
console.error("Fail to getRawFirmwareVersion :", error)
.done()
d.promise
# @return [Boolean]
isInBootloaderMode: -> if @productId is 0x1808 or @productId is 0x1807 or @_forceBl then yes else no
# @return [ledger.fup.FirmwareUpdater]
getFirmwareUpdater: () -> ledger.fup.FirmwareUpdater.instance
# @return [Q.Promise]
isFirmwareUpdateAvailable: (callback=undefined) ->
d = ledger.defer(callback)
@getFirmwareUpdater().getFirmwareUpdateAvailability(this)
.then (availablity) ->
d.resolve(availablity.result is ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Update)
.fail (er) ->
d.rejectWithError(er)
.done()
d.promise
# @return [Q.Promise]
isFirmwareOverwriteOrUpdateAvailable: (callback=undefined) ->
d = ledger.defer(callback)
@getFirmwareUpdater().getFirmwareUpdateAvailability(this)
.then (availablity) ->
d.resolve(availablity.result is ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Update or availablity.result is ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Overwrite)
.fail (er) ->
d.rejectWithError(er)
.done()
d.promise
# Verify that dongle firmware is "official".
# @param [Function] callback Optional argument
# @return [Q.Promise]
isCertified: (callback=undefined) -> @_checkCertification(no, callback)
isBetaCertified: (callback=undefined) -> @_checkCertification(yes, callback)
_checkCertification: (isBeta, callback = undefined) ->
_btchipQueue.enqueue "checkCertification", =>
d = ledger.defer(callback)
return d.resolve(true).promise if @getIntFirmwareVersion() < ledger.dongle.Firmwares.V_L_1_0_0
randomValues = new Uint32Array(2)
crypto.getRandomValues(randomValues)
random = _.str.lpad(randomValues[0].toString(16), 8, '0') + _.str.lpad(randomValues[1].toString(16), 8, '0')
# 24.2. GET DEVICE ATTESTATION
@_sendApdu(new ByteString("E0"+"C2"+"00"+"00"+"08"+random, HEX), [0x9000])
.then (result) =>
attestation = result.toString(HEX)
dataToSign = attestation.substring(16,32) + random
dataSig = attestation.substring(32)
dataSig = "30" + dataSig.substr(2)
dataSigBytes = (parseInt(n,16) for n in dataSig.match(/\w\w/g))
sha = new JSUCrypt.hash.SHA256()
domain = JSUCrypt.ECFp.getEcDomainByName("secp256k1")
if isBeta
Attestation = Attestations["0000000000000001"]
else
Attestation = Attestations[result.bytes(0, 8).toString()]
affinePoint = new JSUCrypt.ECFp.AffinePoint(Attestation.xPoint, Attestation.yPoint)
pubkey = new JSUCrypt.key.EcFpPublicKey(256, domain, affinePoint)
ecsig = new JSUCrypt.signature.ECDSA(sha)
ecsig.init(pubkey, JSUCrypt.signature.MODE_VERIFY)
if ecsig.verify(dataToSign, dataSigBytes)
@_attestation = Attestation
d.resolve(this)
else
d.rejectWithError(Errors.DongleNotCertified)
return
.fail (err) =>
d.rejectWithError(Errors.CommunicationError, err)
.done()
d.promise
getAttestation: -> @_attestation
# Return asynchronously state. Wait until a state is set.
# @param [Function] callback Optional argument
# @return [Q.Promise]
getState: (callback=undefined) ->
d = ledger.defer(callback)
if @state is States.UNDEFINED
@once 'state:changed', (e, state) => d.resolve(state)
else
d.resolve(@state)
d.promise
# @return [Q.Promise] resolve with a Number, reject with a ledger Error.
getRemainingPinAttempt: (callback=undefined) ->
_btchipQueue.enqueue "getRemainingPinAttempt", =>
d = ledger.defer(callback)
@_sendApdu(new ByteString("E0228000010000", HEX), [0x9000])
.catch (statusCode) =>
if m = statusCode.match(/63c(\d)/)
d.resolve(parseInt(m[1]))
else
d.reject(@_handleErrorCode(statusCode))
.done()
d.promise
# @param [String] pin ASCII encoded
# @param [Function] callback Optional argument
# @return [Q.Promise]
unlockWithPinCode: (pin, callback=undefined) ->
Errors.throw(Errors.DongleAlreadyUnlock) if @state is States.UNLOCKED
_btchipQueue.enqueue "unlockWithPinCode", =>
d = ledger.defer(callback)
@_pin = pin
@_btchip.verifyPin_async(new ByteString(@_pin, ASCII))
.then =>
if @getFirmwareInformation().hasSubFirmwareSupport() and @getFirmwareInformation().hasSetupFirmwareSupport()
d.resolve()
return
# 19.7. SET OPERATION MODE
@_sendApdu(0xE0, 0x26, 0x01, 0x01, 0x01, 0x01, [0x9000])
.then =>
if @getIntFirmwareVersion() >= Firmwares.V_B_1_4_13
# 19.7. SET OPERATION MODE
mode = if @getIntFirmwareVersion() >= Firmwares.V_L_1_0_0 then 0x02 else 0x01
@_sendApdu(0xE0, 0x26, mode, 0x00, 0x01, 0x01, [0x9000]).fail(=> e('Unlock FAIL', arguments)).done()
@_setState(States.UNLOCKED)
d.resolve()
.fail (err) =>
error = Errors.new(Errors.NotSupportedDongle, err)
console.log("unlockWithPinCode 2 fail :", err)
d.reject(error)
.catch (error) ->
console.error("Fail to unlockWithPinCode 2 :", error)
.done()
.fail (err) =>
console.error("Fail to unlockWithPinCode 1 :", err)
error = @_handleErrorCode(err)
d.reject(error)
.catch (error) ->
console.error("Fail to unlockWithPinCode 1 :", error)
.done()
d.promise
lock: () ->
if @state isnt ledger.dongle.States.BLANK and @state?
@_setState(States.LOCKED)
###
@overload setup(pin, callback)
@param [String] pin
@param [Function] callback
@return [Q.Promise]
@overload setup(pin, options={}, callback=undefined)
@param [String] pin
@param [String] restoreSeed
@options options [String] restoreSeed
@options options [ByteString] keyMap
@param [Function] callback
@return [Q.Promise]
###
setup: (pin, restoreSeed, callback=undefined) ->
Errors.throw(Errors.DongleNotBlank) if @state isnt States.BLANK
[restoreSeed, callback] = [callback, restoreSeed] if ! callback && typeof restoreSeed == 'function'
_btchipQueue.enqueue "setup", =>
d = ledger.defer(callback)
# Validate seed
if restoreSeed?
bytesSeed = new ByteString(restoreSeed, HEX)
if bytesSeed.length != 64
e('Invalid seed :', restoreSeed)
return d.reject().promise
@_btchip.setupNew_async(
BTChip.MODE_WALLET,
BTChip.FEATURE_DETERMINISTIC_SIGNATURE | BTChip.FEATURE_NO_2FA_P2SH,
ledger.config.network.version.regular,
ledger.config.network.version.P2SH,
new ByteString(pin, ASCII),
undefined,
BTChip.QWERTY_KEYMAP_NEW,
restoreSeed?,
bytesSeed
).then( =>
if restoreSeed?
msg = "Seed restored, please reopen the extension"
else
msg = "Plug the dongle into a secure host to read the generated seed, then reopen the extension"
console.warn(msg)
@_setState(States.ERROR, msg)
d.resolve()
).fail( (err) =>
error = Errors.new(Errors.UnknowError, err)
d.reject(error)
).catch( (error) ->
console.error("Fail to setup :", error)
).done()
d.promise
setupSwappedBip39: (pin, userEntropy = undefined, callback = undefined) -> @_setupSwappedBip39({pin, userEntropy, callback})
restoreSwappedBip39: (pin, restoreSeed, callback = undefined) -> @_setupSwappedBip39({pin, restoreSeed, callback})
verifyAddressOnScreen: (path, callback) ->
Errors.throw(Errors.DongleLocked, 'Cannot get a public while the key is not unlocked') if @state isnt States.UNLOCKED && @state isnt States.UNDEFINED
_btchipQueue.enqueue "getPublicAddress", =>
d = ledger.defer(callback)
@_btchip.getWalletPublicKey_async(path, true, ledger.config.network.handleSegwit)
.then (result) =>
#ledger.wallet.Wallet.instance?.cache?.set [[path, result.bitcoinAddress.value]]
_.defer -> d.resolve(result)
.fail (err) =>
_.defer -> d.resolve({})
.done()
d.promise
_setupSwappedBip39: ({pin, userEntropy, restoreSeed, callback}) ->
Errors.throw(Errors.DongleNotBlank) if @state isnt States.BLANK
userEntropy ||= ledger.bitcoin.bip39.generateEntropy()
if restoreSeed?
indexes = ledger.bitcoin.bip39.mnemonicPhraseToWordIndexes(restoreSeed)
restoreSeed = (Convert.toHexShort(index) for index in indexes).join('')
d = ledger.defer(callback)
@_btchip.setupNew_async(
BTChip.MODE_WALLET,
BTChip.FEATURE_DETERMINISTIC_SIGNATURE | BTChip.FEATURE_NO_2FA_P2SH,
ledger.config.network.version.regular,
ledger.config.network.version.P2SH,
new ByteString(pin, ASCII),
undefined,
undefined,
false,
new ByteString(restoreSeed or userEntropy, HEX),
undefined, !restoreSeed?, restoreSeed?
).then (result) =>
mnemonic = []
for i in [0...24]
wordIndex = (result['swappedMnemonic'].byteAt(2 * i) << 8) + (result['swappedMnemonic'].byteAt(2 * i + 1))
mnemonic.push ledger.bitcoin.bip39.wordlist[wordIndex]
d.resolve(_.extend(result, mnemonic: mnemonic))
.fail (error) =>
d.reject(error)
.done()
d.promise
setupFinalizeBip39: (callback = undefined) ->
ledger.defer(callback).resolve(@_btchip.setupFinalizeBip39_async()).promise
restoreFinalizeBip29: (callback = undefined) ->
ledger.defer(callback).resolve(@_btchip.setupRecovery_async()).promise
restoreSetup: (callback = undefined) -> @_sendApdu(0xE0, 0x20, 0xFF, 0x00, 0x01, 0x00, [0x9000]).then(callback or _.noop)
isSwappedBip39FeatureEnabled: ->
@setupSwappedBip39("0000").then(-> yes).fail(-> no)
# @param [String] path
# @param [Function] callback Optional argument
# @return [Q.Promise]
getPublicAddress: (path, callback=undefined) ->
Errors.throw(Errors.DongleLocked, 'Cannot get a public while the key is not unlocked') if @state isnt States.UNLOCKED && @state isnt States.UNDEFINED
_btchipQueue.enqueue "getPublicAddress", =>
d = ledger.defer(callback)
@_btchip.getWalletPublicKey_async(path, false, false)
.then (result) =>
#ledger.wallet.Wallet.instance?.cache?.set [[path, result.bitcoinAddress.value]]
_.defer -> d.resolve(result)
.fail (err) =>
error = @_handleErrorCode(err)
_.defer -> d.reject(error)
.catch (error) ->
console.error("Fail to getPublicAddress :", error)
.done()
d.promise
# @param [String] message
# @param [String] path Optional argument
# @param [Function] callback Optional argument
# @return [Q.Promise]
signMessage: (message, {prefix, path, pubKey}, callback=undefined) ->
prefix ?= '\x18Bitcoin Signed Message:\n'
if ! pubKey?
@getPublicAddress(path).then((address) => console.log("address=", address); @signMessage(message, path: path, pubKey: address.publicKey, callback))
else
_btchipQueue.enqueue "signMessage", =>
d = ledger.defer(callback)
message = new ByteString(message, ASCII)
@_btchip.signMessagePrepare_async(path, message)
.then =>
return @_btchip.signMessageSign_async(if (@_pin?) then new ByteString(@_pin, ASCII) else new ByteString("0000", ASCII))
.then (sig) =>
signedMessage = @_convertMessageSignature(pubKey, message, prefix, sig.signature)
d.resolve(signedMessage)
.catch (error) ->
console.error("Fail to signMessage :", error)
d.reject(error)
.done()
d.promise
# @param [String] pubKey public key, hex encoded.
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve with a 32 bytes length pairing blob hex encoded.
initiateSecureScreen: (pubKey, callback=undefined) ->
_btchipQueue.enqueue "initiateSecureScreen", =>
d = ledger.defer(callback)
if @state != States.UNLOCKED
d.rejectWithError(Errors.DongleLocked)
else if ! pubKey.match(/^[PI:KEY:<KEY>END_PI1PI:KEY:<KEY>END_PI}$/)?
d.rejectWithError(Errors.InvalidArgument, "Invalid pubKey : #{pubKey}")
else
# 19.3. SETUP SECURE SCREEN
@_sendApdu(new ByteString("E0"+"12"+"01"+"00"+"41"+pubKey, HEX), [0x9000])
.then (c) ->
l 'initiateSecureScreen', c
d.resolve(c.toString())
.fail (error) -> d.reject(error)
.done()
d.promise
# @param [String] resp challenge response, hex encoded.
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve if pairing is successful.
confirmSecureScreen: (resp, callback=undefined) ->
_btchipQueue.enqueue "confirmSecureScreen", =>
d = ledger.defer(callback)
if @state != States.UNLOCKED
d.rejectWithError(Errors.DongleLocked)
else if ! resp.match(/^[0-9A-Fa-f]{32}$/)?
d.rejectWithError(Errors.InvalidArgument, "Invalid challenge resp : #{resp}")
else
# 19.3. SETUP SECURE SCREEN
@_sendApdu(new ByteString("E0"+"12"+"02"+"00"+"10"+resp, HEX), [0x9000])
.then () ->
l 'confirmSecureScreen'
d.resolve()
.fail (error) -> d.reject(error)
.done()
d.promise
# @param [String] path
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve if pairing is successful.
getExtendedPublicKey: (path, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state != States.UNLOCKED
d = ledger.defer(callback)
return d.resolve(@_xpubs[path]).promise if @_xpubs[path]?
xpub = new ledger.wallet.ExtendedPublicKey(@, path)
xpub.initialize () =>
@_xpubs[path] = xpub
d.resolve(xpub)
d.promise
###
@param [Array<Object>] inputs
@param [Array] associatedKeysets
@param changePath
@param [String] changeAddress
@param [String] recipientAddress
@param [Amount] amount
@param [Amount] fee
@param [Integer] lockTime
@param [Integer] sighashType
@param [String] authorization hex encoded
@param [Object] resumeData
@return [Q.Promise] Resolve with resumeData
###
createPaymentTransaction: (inputs, associatedKeysets, changePath, changeAddress, recipientAddress, amount, fees, data, lockTime, sighashType, authorization, resumeData) ->
if resumeData?
resumeData = _.clone(resumeData)
resumeData.scriptData = new ByteString(resumeData.scriptData, HEX)
resumeData.trustedInputs = (new ByteString(trustedInput, HEX) for trustedInput in resumeData.trustedInputs)
resumeData.publicKeys = (new ByteString(publicKey, HEX) for publicKey in resumeData.publicKeys)
if @getFirmwareInformation().isUsingInputFinalizeFull()
@_createPaymentTransactionNew(inputs, associatedKeysets, changePath, changeAddress, recipientAddress, amount, fees, lockTime, sighashType, authorization, data, resumeData)
else
@_createPaymentTransaction(inputs, associatedKeysets, changePath, recipientAddress, amount, fees, lockTime, sighashType, authorization, resumeData)
_createPaymentTransaction: (inputs, associatedKeysets, changePath, recipientAddress, amount, fees, lockTime, sighashType, authorization, resumeData) ->
_btchipQueue.enqueue "createPaymentTransaction", =>
@_btchip.createPaymentTransaction_async(
inputs, associatedKeysets, changePath,
new ByteString(recipientAddress, ASCII),
amount.toByteString(),
fees.toByteString(),
lockTime && new ByteString(Convert.toHexInt(lockTime), HEX),
sighashType && new ByteString(Convert.toHexInt(sighashType), HEX),
authorization && new ByteString(authorization, HEX),
resumeData
).then( (result) ->
if result instanceof ByteString
result = result.toString(HEX)
else
result.scriptData = result.scriptData.toString(HEX)
result.trustedInputs = (trustedInput.toString(HEX) for trustedInput in result.trustedInputs)
result.publicKeys = (publicKey.toString(HEX) for publicKey in result.publicKeys)
result.authorizationPaired = result.authorizationPaired.toString(HEX) if result.authorizationPaired?
result.authorizationReference = result.authorizationReference.toString(HEX) if result.authorizationReference?
return result
)
_createPaymentTransactionNew: (inputs, associatedKeysets, changePath, changeAddress, recipientAddress, amount, fees, lockTime, sighashType, authorization, data, resumeData) ->
@getPublicAddress(changePath).then (result) =>
changeAddress2 = result.bitcoinAddress.toString(ASCII)
inputAmounts = do =>
for [prevTx, index], i in inputs
ledger.Amount.fromSatoshi(prevTx.outputs[index].amount)
totalInputAmount = ledger.Amount.fromSatoshi(0)
for inputAmount in inputAmounts
totalInputAmount = totalInputAmount.add(inputAmount)
changeAmount = totalInputAmount.subtract(amount).subtract(fees)
changePath = undefined if changeAmount.lte(0)
VI = @_btchip.createVarint.bind(@_btchip)
OP_DUP = new ByteString('76', HEX)
OP_HASH160 = new ByteString('A9', HEX)
OP_EQUAL = new ByteString('87', HEX)
OP_EQUALVERIFY = new ByteString('88', HEX)
OP_CHECKSIG = new ByteString('AC', HEX)
OP_RETURN = new ByteString('6A', HEX)
if ledger.config.network.name is "zencash"
ParamHash = new ByteString('209ec9845acb02fab24e1c0368b3b517c1a4488fba97f0e3459ac053ea01000000', HEX)
AdjustAlign = new ByteString('03', HEX)
ParamHeight = new ByteString('c01f02', HEX)
OP_CHECKBLOCKATHEIGHT = new ByteString('b4', HEX)
ZenReplayProtection = ParamHash.concat(AdjustAlign).concat(ParamHeight).concat(OP_CHECKBLOCKATHEIGHT)
###
Create the output script
Count (VI) | Value (8) | PkScript (var) | ....
###
PkScript = (address) =>
hash160WithNetwork = ledger.bitcoin.addressToHash160WithNetwork(address)
p2pkhNetworkVersionSize = hash160WithNetwork.length - 20
hash160 = hash160WithNetwork.bytes(p2pkhNetworkVersionSize, hash160WithNetwork.length - p2pkhNetworkVersionSize) #ledger.bitcoin.addressToHash160(address)
if p2pkhNetworkVersionSize is 1
return P2shScript(hash160) if hash160WithNetwork.byteAt(0) is ledger.config.network.version.P2SH
else
return P2shScript(hash160) if (hash160WithNetwork.byteAt(0) << 8 | hash160WithNetwork.byteAt(1)) is ledger.config.network.version.P2SH
if ledger.config.network.name is "zencash"
script =
OP_DUP
.concat(OP_HASH160)
.concat(new ByteString(Convert.toHexByte(hash160.length), HEX))
.concat(hash160)
.concat(OP_EQUALVERIFY)
.concat(OP_CHECKSIG)
.concat(ZenReplayProtection)
VI(script.length).concat(script)
else
script =
OP_DUP
.concat(OP_HASH160)
.concat(new ByteString(Convert.toHexByte(hash160.length), HEX))
.concat(hash160)
.concat(OP_EQUALVERIFY)
.concat(OP_CHECKSIG)
VI(script.length).concat(script)
P2shScript = (hash160) =>
if ledger.config.network.name is "zencash"
script =
OP_HASH160
.concat(new ByteString(Convert.toHexByte(hash160.length), HEX))
.concat(hash160)
.concat(OP_EQUAL)
.concat(ZenReplayProtection)
VI(script.length).concat(script)
else
script =
OP_HASH160
.concat(new ByteString(Convert.toHexByte(hash160.length), HEX))
.concat(hash160)
.concat(OP_EQUAL)
VI(script.length).concat(script)
OpReturnScript = (data) =>
if ledger.config.network.name is "zencash"
script =
OP_RETURN
.concat(new ByteString(Convert.toHexByte(data.length / 2), HEX))
.concat(new ByteString(data, HEX))
.concat(ZenReplayProtection)
VI(script.length).concat(script)
else
script =
OP_RETURN
.concat(new ByteString(Convert.toHexByte(data.length / 2), HEX))
.concat(new ByteString(data, HEX))
VI(script.length).concat(script)
numberOfOutputs = 1 + (if (changeAmount.lte(0)) then 0 else 1) + (if (data?) then 1 else 0)
outputScript =
VI(numberOfOutputs)
.concat(amount.toScriptByteString())
.concat(PkScript(recipientAddress))
if changeAmount.gt(0)
outputScript = outputScript
.concat(changeAmount.toScriptByteString())
.concat(PkScript(changeAddress))
if data?
outputScript = outputScript
.concat(ledger.Amount.fromSatoshi(0).toScriptByteString())
.concat(OpReturnScript(data))
task = =>
if ledger.config.network.ticker == 'abc' || (ledger.config.network.ticker == 'btg' && !ledger.config.network.handleSegwit) || ledger.config.network.ticker == 'zec'
promise = @_btchip.createPaymentTransactionNewBIP143_async(
false, false,
inputs, associatedKeysets, changePath,
outputScript,
lockTime && new ByteString(Convert.toHexInt(lockTime), HEX),
sighashType && new ByteString(Convert.toHexInt(sighashType), HEX),
authorization && new ByteString(authorization, HEX),
resumeData
)
else
if ledger.config.network.handleSegwit
promise = @_btchip.createPaymentTransactionNewBIP143_async(
true, ledger.config.network.ticker == 'btg',
inputs, associatedKeysets, changePath,
outputScript,
lockTime && new ByteString(Convert.toHexInt(lockTime), HEX),
sighashType && new ByteString(Convert.toHexInt(sighashType), HEX),
authorization && new ByteString(authorization, HEX),
resumeData
)
else
promise = @_btchip.createPaymentTransactionNew_async(
inputs, associatedKeysets, changePath,
outputScript,
lockTime && new ByteString(Convert.toHexInt(lockTime), HEX),
sighashType && new ByteString(Convert.toHexInt(sighashType), HEX),
authorization && new ByteString(authorization, HEX),
resumeData
)
promise.then( (result) ->
if result instanceof ByteString
result = result.toString(HEX)
else
result.scriptData = result.scriptData.toString(HEX)
result.trustedInputs = (trustedInput.toString(HEX) for trustedInput in result.trustedInputs)
result.publicKeys = (publicKey.toString(HEX) for publicKey in result.publicKeys)
result.authorizationPaired = result.authorizationPaired.toString(HEX) if result.authorizationPaired?
result.authorizationReference = result.authorizationReference.toString(HEX) if result.authorizationReference?
result.encryptedOutputScript = result.encryptedOutputScript?.toString(HEX)
return result
)
_btchipQueue.enqueue("createPaymentTransaction", task, (if (@getFirmwareInformation().hasScreenAndButton()) then 72000000 else undefined))
.fail (er) ->
e er
formatP2SHOutputScript: (transaction) ->
@_btchip.formatP2SHOutputScript(transaction)
###
@return [Q.Promise]
###
signP2SHTransaction: (inputs, scripts, numOutputs, output, paths) ->
_btchipQueue.enqueue "signP2SHTransaction", =>
@_btchip.signP2SHTransaction_async(inputs, scripts, numOutputs, output, paths)
###
@param [String] input hex encoded
@return [Object]
[Array<Byte>] version length is 4
[Array<Object>] inputs
[Array<Byte>] prevout length is 36
[Array<Byte>] script var length
[Array<Byte>] sequence length is 4
[Array<Object>] outputs
[Array<Byte>] amount length is 4
[Array<Byte>] script var length
[Array<Byte>] locktime length is 4
###
splitTransaction: (input, areTransactionTimestamped, isSegwitSupported) ->
@_btchip.splitTransaction(new ByteString(input.raw, HEX), areTransactionTimestamped, isSegwitSupported)
_sendApdu: (args...) ->
apdu = new ByteString('', HEX)
swCheck = undefined
for arg, index in args
if arg instanceof ByteString
apdu = apdu.concat(arg)
else if index is args.length - 1 and _.isArray(arg)
swCheck = arg
else
apdu = apdu.concat(new ByteString((if _.isNumber(arg) then Convert.toHexByte(arg) else arg.replace(/\s/g, '')), HEX))
@_btchip.card.sendApdu_async(apdu, swCheck)
# @return [Q.Promise] Must be done
_recoverFirmwareVersion: ->
_btchipQueue.enqueue "recoverFirmwareVersion", =>
@_sendApdu('E0 C4 00 00 00 08').then (version) =>
firmware = new ledger.dongle.FirmwareInformation(this, version)
if firmware.isUsingInputFinalizeFull()
@_btchip.setUntrustedHashTransactionInputFinalizeFull()
if firmware.isUsingDeprecatedBip32Derivation()
@_btchip.setDeprecatedBIP32Derivation()
if firmware.isUsingDeprecatedSetupKeymap()
@_btchip.setDeprecatedSetupKeymap()
@_btchip.setCompressedPublicKeys(firmware.hasCompressedPublicKeysSupport())
@_firmwareInformation = firmware
.fail (error) =>
e("Firmware version not supported :", error)
throw error
# @return [Q.Promise] Must be done
_recoverOperationMode: ->
_btchipQueue.enqueue "recoverOperationMode", =>
@_btchip.getOperationMode_async().then (mode) =>
@operationMode = mode
_setState: (newState, args...) ->
[@state, oldState] = [newState, @state]
@emit "state:#{@state}", @state, args...
@emit 'state:changed', @state
# Set appropriate state, and return corresponding Error
# @param [String] errorCode
# @return [Error]
_handleErrorCode: (errorCode) ->
if errorCode.match("6982") # Pin required
@_setState(States.LOCKED)
error = Errors.new(Errors.DongleLocked, errorCode)
else if errorCode.match("6985") # Error ?
@_setState(States.BLANK)
error = Errors.new(Errors.BlankDongle, errorCode)
else if errorCode.match("6faa")
@_setState(States.ERROR)
error = Errors.new(Errors.UnknowError, errorCode)
else if errorCode.match(/63c\d/)
error = Errors.new(Errors.WrongPinCode, errorCode)
error.retryCount = parseInt(errorCode.substr(-1))
if error.retryCount == 0
@_setState(States.BLANK)
error.code = Errors.DongleLocked
else
@_setState(States.ERROR)
else
@_setState(States.UnknowError)
error = Errors.new(Errors.UnknowError, errorCode)
return error
_convertMessageSignature: (pubKey, message, prefix, signature) ->
bitcoin = new BitcoinExternal()
hash = bitcoin.getSignedMessageHash(message, prefix)
pubKey = bitcoin.compressPublicKey(pubKey)
for i in [0...4]
recoveredKey = bitcoin.recoverPublicKey(signature, hash, i)
recoveredKey = bitcoin.compressPublicKey(recoveredKey)
if recoveredKey.equals(pubKey)
splitSignature = bitcoin.splitAsn1Signature(signature)
sig = new ByteString(Convert.toHexByte(i + 27 + 4), HEX).concat(splitSignature[0]).concat(splitSignature[1])
break
throw "Recovery failed" if ! sig?
return @_convertBase64(sig)
_convertBase64: (data) ->
codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
output = ""
leven = 3 * (Math.floor(data.length / 3))
offset = 0
for i in [0...leven] when i % 3 == 0
output += codes.charAt((data.byteAt(offset) >> 2) & 0x3f)
output += codes.charAt((((data.byteAt(offset) & 3) << 4) + (data.byteAt(offset + 1) >> 4)) & 0x3f)
output += codes.charAt((((data.byteAt(offset + 1) & 0x0f) << 2) + (data.byteAt(offset + 2) >> 6)) & 0x3f)
output += codes.charAt(data.byteAt(offset + 2) & 0x3f)
offset += 3
if i < data.length
a = data.byteAt(offset)
b = if (i + 1) < data.length then data.byteAt(offset + 1) else 0
output += codes.charAt((a >> 2) & 0x3f)
output += codes.charAt((((a & 3) << 4) + (b >> 4)) & 0x3f)
output += if (i + 1) < data.length then codes.charAt((((b & 0x0f) << 2)) & 0x3f) else '='
output += '='
return output
|
[
{
"context": " filename: \"sailing_photo.jpg\",\n id: \"dyla86usnzouam5wt7wt2bsvu\",\n message_ids:",
"end": 4739,
"score": 0.8513475060462952,
"start": 4737,
"tag": "USERNAME",
"value": "dy"
},
{
"context": "2592sewzy834bzhsbu0kt\"],\n account_id: \... | spec/file-spec.coffee | lever/nylas-nodejs | 0 | Nylas = require '../nylas'
NylasConnection = require '../nylas-connection'
File = require '../models/file'
Promise = require 'bluebird'
request = require 'request'
_ = require 'underscore'
testUntil = (fn) ->
finished = false
runs ->
fn (callback) ->
finished = true
waitsFor -> finished
describe "File", ->
beforeEach ->
@connection = new NylasConnection('123')
@file = new File(@connection)
@file.data = 'Sample data'
@file.contentType = 'text/plain'
@file.filename = 'sample.txt'
@file.id = 'fileId'
Promise.onPossiblyUnhandledRejection (e, promise) ->
describe "upload", ->
it "should do a POST request", ->
spyOn(@connection, 'request').andCallFake -> Promise.resolve()
@file.upload()
expect(@connection.request).toHaveBeenCalledWith({
method: 'POST',
json: false,
path: '/files',
formData:
file:
value: 'Sample data',
options:
filename: 'sample.txt',
contentType: 'text/plain'
})
describe "when the request succeeds", ->
beforeEach ->
spyOn(@connection, 'request').andCallFake ->
fileJSON = [{
id: 'id-1234'
filename: 'sample.txt'
}]
Promise.resolve(fileJSON)
it "should resolve with the file object", ->
testUntil (done) =>
@file.upload().then (file) ->
expect(file.id).toBe('id-1234')
expect(file.filename).toBe('sample.txt')
done()
it "should call the callback with the file object", ->
testUntil (done) =>
@file.upload (err, file) ->
expect(err).toBe(null)
expect(file.id).toBe('id-1234')
expect(file.filename).toBe('sample.txt')
done()
describe "when the request fails", ->
beforeEach ->
@error = new Error("Network error")
spyOn(@connection, 'request').andCallFake =>
Promise.reject(@error)
it "should reject with the error", ->
testUntil (done) =>
@file.upload().catch (err) =>
expect(err).toBe(@error)
done()
it "should call the callback with the error", ->
testUntil (done) =>
@file.upload (err, file) =>
expect(err).toBe(@error)
expect(file).toBe(undefined)
done()
describe "download", ->
it "should do a GET request", ->
spyOn(@connection, 'request').andCallFake -> Promise.resolve()
@file.download()
expect(@connection.request).toHaveBeenCalledWith({
path: '/files/fileId/download',
encoding: null,
downloadRequest: true
})
describe "when the request succeeds", ->
beforeEach ->
spyOn(@connection, 'request').andCallFake ->
response =
headers:
header1: '1'
header2: '2'
body: 'body'
otherField: 'other'
Promise.resolve(response)
it "should resolve with the file information", ->
testUntil (done) =>
@file.download().then (file) ->
fileInfo =
body: 'body'
header1: '1'
header2: '2'
expect(file).toEqual(fileInfo)
done()
it "should call the callback with the file object", ->
testUntil (done) =>
@file.download (err, file) ->
fileInfo =
body: 'body'
header1: '1'
header2: '2'
expect(err).toBe(null)
expect(file).toEqual(fileInfo)
done()
describe "when the request fails", ->
beforeEach ->
@error = new Error("Network error")
spyOn(@connection, 'request').andCallFake =>
Promise.reject(@error)
it "should reject with the error", ->
testUntil (done) =>
@file.download().catch (err) =>
expect(err).toBe(@error)
done()
it "should call the callback with the error", ->
testUntil (done) =>
@file.download (err, file) =>
expect(err).toBe(@error)
expect(file).toBe(undefined)
done()
describe "metadata", ->
it "should do a GET request", ->
spyOn(@connection, 'request').andCallFake -> Promise.resolve()
@file.metadata()
expect(@connection.request).toHaveBeenCalledWith({
path: '/files/fileId',
})
describe "when the request succeeds", ->
beforeEach ->
spyOn(@connection, 'request').andCallFake ->
response =
content_type: "image/jpeg",
filename: "sailing_photo.jpg",
id: "dyla86usnzouam5wt7wt2bsvu",
message_ids: ["cud32592sewzy834bzhsbu0kt"],
account_id: "6aakaxzi4j5gn6f7kbb9e0fxs",
object: "file",
size: 8380
Promise.resolve(response)
it "should resolve with the file information", ->
testUntil (done) =>
@file.metadata().then (response) ->
fileInfo =
content_type: "image/jpeg",
filename: "sailing_photo.jpg",
id: "dyla86usnzouam5wt7wt2bsvu",
message_ids: ["cud32592sewzy834bzhsbu0kt"],
account_id: "6aakaxzi4j5gn6f7kbb9e0fxs",
object: "file",
size: 8380
expect(response).toEqual(fileInfo)
done()
it "should call the callback with the file object", ->
testUntil (done) =>
@file.metadata (err, response) ->
fileInfo =
content_type: "image/jpeg",
filename: "sailing_photo.jpg",
id: "dyla86usnzouam5wt7wt2bsvu",
message_ids: ["cud32592sewzy834bzhsbu0kt"],
account_id: "6aakaxzi4j5gn6f7kbb9e0fxs",
object: "file",
size: 8380
expect(err).toBe(null)
expect(response).toEqual(fileInfo)
done()
describe "when the request fails", ->
beforeEach ->
@error = new Error("Network error")
spyOn(@connection, 'request').andCallFake =>
Promise.reject(@error)
it "should reject with the error", ->
testUntil (done) =>
@file.metadata().catch (err) =>
expect(err).toBe(@error)
done()
it "should call the callback with the error", ->
testUntil (done) =>
@file.metadata (err, file) =>
expect(err).toBe(@error)
expect(file).toBe(undefined)
done()
| 215426 | Nylas = require '../nylas'
NylasConnection = require '../nylas-connection'
File = require '../models/file'
Promise = require 'bluebird'
request = require 'request'
_ = require 'underscore'
testUntil = (fn) ->
finished = false
runs ->
fn (callback) ->
finished = true
waitsFor -> finished
describe "File", ->
beforeEach ->
@connection = new NylasConnection('123')
@file = new File(@connection)
@file.data = 'Sample data'
@file.contentType = 'text/plain'
@file.filename = 'sample.txt'
@file.id = 'fileId'
Promise.onPossiblyUnhandledRejection (e, promise) ->
describe "upload", ->
it "should do a POST request", ->
spyOn(@connection, 'request').andCallFake -> Promise.resolve()
@file.upload()
expect(@connection.request).toHaveBeenCalledWith({
method: 'POST',
json: false,
path: '/files',
formData:
file:
value: 'Sample data',
options:
filename: 'sample.txt',
contentType: 'text/plain'
})
describe "when the request succeeds", ->
beforeEach ->
spyOn(@connection, 'request').andCallFake ->
fileJSON = [{
id: 'id-1234'
filename: 'sample.txt'
}]
Promise.resolve(fileJSON)
it "should resolve with the file object", ->
testUntil (done) =>
@file.upload().then (file) ->
expect(file.id).toBe('id-1234')
expect(file.filename).toBe('sample.txt')
done()
it "should call the callback with the file object", ->
testUntil (done) =>
@file.upload (err, file) ->
expect(err).toBe(null)
expect(file.id).toBe('id-1234')
expect(file.filename).toBe('sample.txt')
done()
describe "when the request fails", ->
beforeEach ->
@error = new Error("Network error")
spyOn(@connection, 'request').andCallFake =>
Promise.reject(@error)
it "should reject with the error", ->
testUntil (done) =>
@file.upload().catch (err) =>
expect(err).toBe(@error)
done()
it "should call the callback with the error", ->
testUntil (done) =>
@file.upload (err, file) =>
expect(err).toBe(@error)
expect(file).toBe(undefined)
done()
describe "download", ->
it "should do a GET request", ->
spyOn(@connection, 'request').andCallFake -> Promise.resolve()
@file.download()
expect(@connection.request).toHaveBeenCalledWith({
path: '/files/fileId/download',
encoding: null,
downloadRequest: true
})
describe "when the request succeeds", ->
beforeEach ->
spyOn(@connection, 'request').andCallFake ->
response =
headers:
header1: '1'
header2: '2'
body: 'body'
otherField: 'other'
Promise.resolve(response)
it "should resolve with the file information", ->
testUntil (done) =>
@file.download().then (file) ->
fileInfo =
body: 'body'
header1: '1'
header2: '2'
expect(file).toEqual(fileInfo)
done()
it "should call the callback with the file object", ->
testUntil (done) =>
@file.download (err, file) ->
fileInfo =
body: 'body'
header1: '1'
header2: '2'
expect(err).toBe(null)
expect(file).toEqual(fileInfo)
done()
describe "when the request fails", ->
beforeEach ->
@error = new Error("Network error")
spyOn(@connection, 'request').andCallFake =>
Promise.reject(@error)
it "should reject with the error", ->
testUntil (done) =>
@file.download().catch (err) =>
expect(err).toBe(@error)
done()
it "should call the callback with the error", ->
testUntil (done) =>
@file.download (err, file) =>
expect(err).toBe(@error)
expect(file).toBe(undefined)
done()
describe "metadata", ->
it "should do a GET request", ->
spyOn(@connection, 'request').andCallFake -> Promise.resolve()
@file.metadata()
expect(@connection.request).toHaveBeenCalledWith({
path: '/files/fileId',
})
describe "when the request succeeds", ->
beforeEach ->
spyOn(@connection, 'request').andCallFake ->
response =
content_type: "image/jpeg",
filename: "sailing_photo.jpg",
id: "dyla86usnzouam5wt7wt2bsvu",
message_ids: ["cud32592sewzy834bzhsbu0kt"],
account_id: "<KEY>",
object: "file",
size: 8380
Promise.resolve(response)
it "should resolve with the file information", ->
testUntil (done) =>
@file.metadata().then (response) ->
fileInfo =
content_type: "image/jpeg",
filename: "sailing_photo.jpg",
id: "dyla86usnzouam5wt7wt2bsvu",
message_ids: ["cud32592sewzy834bzhsbu0kt"],
account_id: "<KEY>",
object: "file",
size: 8380
expect(response).toEqual(fileInfo)
done()
it "should call the callback with the file object", ->
testUntil (done) =>
@file.metadata (err, response) ->
fileInfo =
content_type: "image/jpeg",
filename: "sailing_photo.jpg",
id: "dyla86usnzouam5wt7wt2bsvu",
message_ids: ["cud32592sewzy834bzhsbu0kt"],
account_id: "<KEY>",
object: "file",
size: 8380
expect(err).toBe(null)
expect(response).toEqual(fileInfo)
done()
describe "when the request fails", ->
beforeEach ->
@error = new Error("Network error")
spyOn(@connection, 'request').andCallFake =>
Promise.reject(@error)
it "should reject with the error", ->
testUntil (done) =>
@file.metadata().catch (err) =>
expect(err).toBe(@error)
done()
it "should call the callback with the error", ->
testUntil (done) =>
@file.metadata (err, file) =>
expect(err).toBe(@error)
expect(file).toBe(undefined)
done()
| true | Nylas = require '../nylas'
NylasConnection = require '../nylas-connection'
File = require '../models/file'
Promise = require 'bluebird'
request = require 'request'
_ = require 'underscore'
testUntil = (fn) ->
finished = false
runs ->
fn (callback) ->
finished = true
waitsFor -> finished
describe "File", ->
beforeEach ->
@connection = new NylasConnection('123')
@file = new File(@connection)
@file.data = 'Sample data'
@file.contentType = 'text/plain'
@file.filename = 'sample.txt'
@file.id = 'fileId'
Promise.onPossiblyUnhandledRejection (e, promise) ->
describe "upload", ->
it "should do a POST request", ->
spyOn(@connection, 'request').andCallFake -> Promise.resolve()
@file.upload()
expect(@connection.request).toHaveBeenCalledWith({
method: 'POST',
json: false,
path: '/files',
formData:
file:
value: 'Sample data',
options:
filename: 'sample.txt',
contentType: 'text/plain'
})
describe "when the request succeeds", ->
beforeEach ->
spyOn(@connection, 'request').andCallFake ->
fileJSON = [{
id: 'id-1234'
filename: 'sample.txt'
}]
Promise.resolve(fileJSON)
it "should resolve with the file object", ->
testUntil (done) =>
@file.upload().then (file) ->
expect(file.id).toBe('id-1234')
expect(file.filename).toBe('sample.txt')
done()
it "should call the callback with the file object", ->
testUntil (done) =>
@file.upload (err, file) ->
expect(err).toBe(null)
expect(file.id).toBe('id-1234')
expect(file.filename).toBe('sample.txt')
done()
describe "when the request fails", ->
beforeEach ->
@error = new Error("Network error")
spyOn(@connection, 'request').andCallFake =>
Promise.reject(@error)
it "should reject with the error", ->
testUntil (done) =>
@file.upload().catch (err) =>
expect(err).toBe(@error)
done()
it "should call the callback with the error", ->
testUntil (done) =>
@file.upload (err, file) =>
expect(err).toBe(@error)
expect(file).toBe(undefined)
done()
describe "download", ->
it "should do a GET request", ->
spyOn(@connection, 'request').andCallFake -> Promise.resolve()
@file.download()
expect(@connection.request).toHaveBeenCalledWith({
path: '/files/fileId/download',
encoding: null,
downloadRequest: true
})
describe "when the request succeeds", ->
beforeEach ->
spyOn(@connection, 'request').andCallFake ->
response =
headers:
header1: '1'
header2: '2'
body: 'body'
otherField: 'other'
Promise.resolve(response)
it "should resolve with the file information", ->
testUntil (done) =>
@file.download().then (file) ->
fileInfo =
body: 'body'
header1: '1'
header2: '2'
expect(file).toEqual(fileInfo)
done()
it "should call the callback with the file object", ->
testUntil (done) =>
@file.download (err, file) ->
fileInfo =
body: 'body'
header1: '1'
header2: '2'
expect(err).toBe(null)
expect(file).toEqual(fileInfo)
done()
describe "when the request fails", ->
beforeEach ->
@error = new Error("Network error")
spyOn(@connection, 'request').andCallFake =>
Promise.reject(@error)
it "should reject with the error", ->
testUntil (done) =>
@file.download().catch (err) =>
expect(err).toBe(@error)
done()
it "should call the callback with the error", ->
testUntil (done) =>
@file.download (err, file) =>
expect(err).toBe(@error)
expect(file).toBe(undefined)
done()
describe "metadata", ->
it "should do a GET request", ->
spyOn(@connection, 'request').andCallFake -> Promise.resolve()
@file.metadata()
expect(@connection.request).toHaveBeenCalledWith({
path: '/files/fileId',
})
describe "when the request succeeds", ->
beforeEach ->
spyOn(@connection, 'request').andCallFake ->
response =
content_type: "image/jpeg",
filename: "sailing_photo.jpg",
id: "dyla86usnzouam5wt7wt2bsvu",
message_ids: ["cud32592sewzy834bzhsbu0kt"],
account_id: "PI:KEY:<KEY>END_PI",
object: "file",
size: 8380
Promise.resolve(response)
it "should resolve with the file information", ->
testUntil (done) =>
@file.metadata().then (response) ->
fileInfo =
content_type: "image/jpeg",
filename: "sailing_photo.jpg",
id: "dyla86usnzouam5wt7wt2bsvu",
message_ids: ["cud32592sewzy834bzhsbu0kt"],
account_id: "PI:KEY:<KEY>END_PI",
object: "file",
size: 8380
expect(response).toEqual(fileInfo)
done()
it "should call the callback with the file object", ->
testUntil (done) =>
@file.metadata (err, response) ->
fileInfo =
content_type: "image/jpeg",
filename: "sailing_photo.jpg",
id: "dyla86usnzouam5wt7wt2bsvu",
message_ids: ["cud32592sewzy834bzhsbu0kt"],
account_id: "PI:KEY:<KEY>END_PI",
object: "file",
size: 8380
expect(err).toBe(null)
expect(response).toEqual(fileInfo)
done()
describe "when the request fails", ->
beforeEach ->
@error = new Error("Network error")
spyOn(@connection, 'request').andCallFake =>
Promise.reject(@error)
it "should reject with the error", ->
testUntil (done) =>
@file.metadata().catch (err) =>
expect(err).toBe(@error)
done()
it "should call the callback with the error", ->
testUntil (done) =>
@file.metadata (err, file) =>
expect(err).toBe(@error)
expect(file).toBe(undefined)
done()
|
[
{
"context": "body\", ->\n\t\texpect(binding(\"send.body\")).toEqual \"7fF8WOaj2HNvqhnOgvCNWFlxbNFX3N2Fi13ueR/Fe5kT5/pZGp1oVUw+ZYIgv7ST/Ke4+F5/8JXQI87/mpHVlNF6UrYEHrqAnj0gewtcwQ20lf+Kc4aSaXwJN8XJuNYy\"",
"end": 694,
"score": 0.9996300339698792,
"start": 566,
"tag": "KEY",
"value": "7fF8WOaj2... | public/test/e2e/karma/fullbody.coffee | vetstoria-testing/angularjs-crypto | 77 | "use strict"
describe "fullbody example", ->
beforeEach ->
browser().navigateTo "/index.html#/fullbody"
expect(browser().location().url()).toBe "/fullbody"
it "check count of encrypted items to be three", ->
expect(repeater("div.plain").count()).toBe 1
it "check plain name", ->
expect(repeater("div.plain:eq(0)").column("item.name_enc")).toEqual ["COMMERZBANK AG"]
it "check plain value", ->
expect(repeater("div.plain:eq(0)").column("item.value_enc")).toEqual ["1504.75"]
it "check encrypted body", ->
expect(binding("send.body")).toEqual "7fF8WOaj2HNvqhnOgvCNWFlxbNFX3N2Fi13ueR/Fe5kT5/pZGp1oVUw+ZYIgv7ST/Ke4+F5/8JXQI87/mpHVlNF6UrYEHrqAnj0gewtcwQ20lf+Kc4aSaXwJN8XJuNYy" | 211157 | "use strict"
describe "fullbody example", ->
beforeEach ->
browser().navigateTo "/index.html#/fullbody"
expect(browser().location().url()).toBe "/fullbody"
it "check count of encrypted items to be three", ->
expect(repeater("div.plain").count()).toBe 1
it "check plain name", ->
expect(repeater("div.plain:eq(0)").column("item.name_enc")).toEqual ["COMMERZBANK AG"]
it "check plain value", ->
expect(repeater("div.plain:eq(0)").column("item.value_enc")).toEqual ["1504.75"]
it "check encrypted body", ->
expect(binding("send.body")).toEqual "<KEY>" | true | "use strict"
describe "fullbody example", ->
beforeEach ->
browser().navigateTo "/index.html#/fullbody"
expect(browser().location().url()).toBe "/fullbody"
it "check count of encrypted items to be three", ->
expect(repeater("div.plain").count()).toBe 1
it "check plain name", ->
expect(repeater("div.plain:eq(0)").column("item.name_enc")).toEqual ["COMMERZBANK AG"]
it "check plain value", ->
expect(repeater("div.plain:eq(0)").column("item.value_enc")).toEqual ["1504.75"]
it "check encrypted body", ->
expect(binding("send.body")).toEqual "PI:KEY:<KEY>END_PI" |
[
{
"context": " span '.path', contenteditable: '', @musicroot\n div '.explain.note', ->\n ",
"end": 2021,
"score": 0.8200041055679321,
"start": 2011,
"tag": "USERNAME",
"value": "@musicroot"
},
{
"context": "ground-link', href: 'http://www.flickr.... | otto.client.templates.coffee | ferguson/otto | 16 | ####
#### client side (body of otto.client.templates.coffee served as /otto.templates.js)
####
# binds to otto.templates (on the client side), not otto.client.templates
# for historical reasons (and brevity)
global.otto.client.templates = ->
$('head').append '<script src="static/js/coffeecup.js">' if not window['coffeecup']?
window.otto = window.otto || {}
window.otto.client = window.otto.client || {}
window.otto.client.templates = true # for otto.load_module's benefit
window.otto.templates = do ->
templates = {}
t = otto.t = templates
ccc = coffeecup.compile
# you can't reference 'templates' or 't' in the compiled functions scope
# (i'm guessing because they are 'eval'ed), use otto.templates instead
add = templates: templates, t: t
t.body_welcome = ccc ->
div '#welcome', otto.t.welcome @
t.body = ccc ->
nav '.channellist-container', ''
div '#mainpage', ''
div '.ouroboros-container', ''
#div '.footer-container', otto.t.footer()
div '.cursor-hider', ''
t.body_reset = ->
$('.channellist-container').empty()
$('#mainpage').empty()
$('.ouroboros-container').empty()
#$('.footer-container').html otto.t.footer()
$('.cursor-hider').empty()
t.welcome = ccc ->
div '.wecome-container', ->
div '.welcome', ->
text otto.t.logo()
div '.greeting', ->
div '.hi', 'hello!'
div '.explain', 'I love to play your music for you, but first I need to scan it'
div '.explain', 'don\'t worry, I won\'t move it or anything like that'
br()
br()
div '.explain', 'I\'ll scan for music in this folder'
div ->
div '.folder', ->
button '.control.medium2.selectfolder', otto.t.icon 'folder'
input '#selectFolder', type: 'file', style: 'display: none' #must match UIDelegate in Otto.py
span '.path', contenteditable: '', @musicroot
div '.explain.note', ->
text '(press '
button '.control.small.selectfolder.', otto.t.icon 'folder'
text ' to change this)'
button '.control.large.wide.loadmusic', 'scan'
div '.footer-container', ''
t.initialload = ccc ->
div '.welcome-container', ->
div '.welcome', ->
text otto.t.logo()
div '.initialload-container', otto.t.cubesloader @
t.cubeswithload = ccc ->
div '.cubeswithload-container', otto.t.cubesloader @
t.cubesloader = ccc ->
div '.loadingstatus', otto.t.loadingstatuses @
div '.loadingprogress', ''
div '.loadingcurrent', ''
div '.loadingcubes-container', ->
div '.loadingcubes', ''
t.loadingstatuses = ccc ->
div '.status.begin', ->
button '.control.large.wide.loadmusic2', 'scan'
div '.status.searching', ->
div '.loadingspinner', ->
div otto.t.ouroboros size: 'medium', direction: 'cw', speed: 'fast'
div '.note', 'searching'
div '.status.loading', ->
div '.loadingspinner', ->
div otto.t.ouroboros size: 'medium', direction: 'cw', speed: 'slow'
div '.note', 'scanning'
div '.status.finished', ->
div ->
text 'all finished! press '
button '.control.small.begin', otto.t.icon 'play'
text ' to begin.'
button '.control.medium2.begin', otto.t.icon 'play'
div '.status.nonefound', ->
div ->
div 'sorry, I was unable to find any music I can play'
br()
if @folder
div 'in folder ' + @folder
else
div 'in that folder'
br()
br()
button '.control.large.wide.restartload', 'restart'
div '.status.error', ->
div ->
text 'sorry, I encountered an error while scanning'
button '.control.large.wide.begin.continue', 'continue'
t.cubes = ccc ->
div '.cubes-container', ->
div '.landscape-right', ''
div '.landscape-left', ''
div '.cubes', ->
div '.scene', ''
#div '.resort.control.medium2', otto.t.icon 'cubes'
t.cubelink = ccc ->
div '.cubelink.'+@rowclass, 'data-id': @id, title: @title, ->
div '.cube', style: @style
t.stacklabel = ccc ->
div '.stacklabel', style: @style, @letter
t.countprogress = ccc ->
if @total or @count
div '.countprogress-binder', ->
s = @total
sizePercent = 100
progressPercent = Math.min((@count / @total * 100), 100)
div '.progress-maximum', ->
div '.progress-container', style: "width: #{sizePercent}%;", ->
div '.progress', ->
div '.progress-indicator', style: "width: #{progressPercent}%;", ''
div '.count-container', otto.t.count_widget(@)
t.logo = ccc ->
div '.logo-container', ->
#span '.logo', ''
a '.logo', href: 'http://ottoaudiojukebox.com/', target: '_blank', ->
t.mainpage = ccc ->
if @channel.layout is 'webcast'
text otto.t.channelbar channel: @channel
text otto.t.console()
text otto.t.webcast()
else if @channel.layout is 'featured'
text otto.t.channelbar channel: @channel
text otto.t.console()
text otto.t.featured()
#else if @channel.layout is 'holidays'
# happy holidays
else
text otto.t.channelbar channel: @channel
text otto.t.login()
text otto.t.playing @
text otto.t.thealbum()
div '.ondeckchattoggle-container', ->
div '.ondeck-container', ''
div '.chattoggle-container', ->
button '.control.medium.chattoggle.shy', {title: 'chat'}, otto.t.icon 'chat'
text otto.t.console()
text otto.t.browse @
#div '.footer-backer', ''
templates.console = coffeecup.compile ->
div '.console-container', tabindex: -1, ->
button '.control.medium.chattoggle.shy', otto.t.icon 'close'
div '.output-container', ->
div '.output.scrollkiller', ''
div '.input-container', ->
div '.inputl', ->
#pre '#prompt', ''
div '#prompt', ''
div '.inputr-container', ->
div '#inputr', -> # must be an id, not class
div '#terminal', ->
#textarea '.input', spellcheck: 'false'
#div '.inputcopy', ''
t.chathelp = ccc ->
div '.chathelp', ->
div '/cls - clear screen'
div '/next - next track'
div '/pause - pause playing'
div '/play - resume playing'
div '/nick <name> - change username'
div '/part - leave chat'
div '/help - show commands'
t.chatunknowncommand = ccc ->
div '.chatunknowncommand', ->
'unknown command ' + @prefix + @command
t.channelbar = ccc ->
console.log 'channelbar', @
div '.channelbar-container.reveal', ->
div '.channelbar', ->
div '.channelbar-left', ->
button '.control.medium.channeltoggle.shy', {title: 'channels'}, otto.t.icon 'menu'
div '.channelbar-center', ->
div '.channelname-container', ->
div '.channelname', @channel.fullname
div '.hostname', ->
#host = @host
#if host and host.indexOf(':') > 0
# host = host.substr(0, host.indexOf ':') || @host
#'http://' + host
r = /^(http:\/\/)?([^\/]*)/.exec(document.URL)
host = if r and r.length is 3 then r[2] else ''
host
text otto.t.logo()
div '.topcontrols-container', ->
#input '#fxtoggle', type: 'checkbox', checked: false
#label '#fx.shy', for: 'fxtoggle', ->
# span 'sound cues'
button '.control.medium2.soundfxtoggle.shy', {title: 'sound cues'}, otto.t.icon 'soundfx'
if Notification?
#input '#notificationstoggle', type: 'checkbox', checked: false
#label '#notifications.shy', for: 'notificationstoggle', ->
# span 'notifications'
button '.control.medium2.notificationstoggle.shy', {title: 'notifications'}, otto.t.icon 'notifications'
div '.channelbar-right', ->
#div '.chattoggle-container', ->
# button '.control.medium.chattoggle.shy', otto.t.icon 'chat'
div '.channelbar-lower', ->
div '.listeners-container', ''
templates.webcast = coffeecup.compile ->
div '#webcast-container', ->
div '#webcast-background', ->
img src: '/static/images/8013980828_82a933115b_k.jpg', title: '', alt: ''
div '#webcast-background-attribution', ->
a '#webcast-background-link', href: 'http://www.flickr.com/photos/joi/8013980828', target: '_blank',
"DJ Aaron by Joi Ito"
div '#webcast-overlay', ->
div '.autosizeX', 'data-autosize-max': 34, 'data-autosize-min': 19, 'data-autosize-right-margin': 56, ->
otto.autosize_clear_cache()
div ->
span '.webcast-title', "Live Webcast"
#div '#webcast-compatability', ->
# "live broadcast currently works in Chrome and Firefox only"
div '#webcast-chatpointer', ->
"there is a chat button in the upper right"
templates.featuredX = coffeecup.compile ->
div '#archive-container', ->
div '#archive-background', ->
img src: '/static/images/webcast.png', title: '', alt: ''
div '#archive-background-attribution', ->
a '#archive-background-link', href: 'https://www.facebook.com/photo.php?fbid=10150666518958461&set=o.406990045995364&type=1&theater', ->
"photo by [AttributionHere]"
div '#archive-overlay', ->
div '.autosize', 'data-autosize-max': 34, 'data-autosize-min': 19, 'data-autosize-right-margin': 56, ->
otto.autosize_clear_cache()
div ->
span '.archive-title', "Archives"
templates.featured = coffeecup.compile ->
div '#playlist.featured.reveal', ->
t.play_widget = ccc ->
button '#play.control.medium2', {title: 'play/pause'}, otto.t.icon 'play'
t.next_widget = ccc ->
button '#next.control.medium2.shy', {title: 'next'}, otto.t.icon 'kill'
# no longer used
t.lineout_widget = ccc ->
input '#lineouttoggle', type: 'checkbox', checked: false
label '#lineout.shy', for: 'lineouttoggle', ->
span 'server output'
text otto.t.volumelineout_widget
t.volume_widget = ccc ->
div '.volume-container', {title: 'local volume'}, ->
div '.volume', ''
t.volumelineout_widget = ccc ->
div '.volumelineout-container', {title: 'lineout volume'}, ->
div '.volumelineout', ''
t.size_widget = ccc ->
div '.size-widget.shy', ->
button '#size.smaller.control.small', {title: 'smaller'}, otto.t.icon 'smaller'
button '#size.bigger.control.small', {title: 'bigger'}, otto.t.icon 'bigger'
t.currentsong_widget = ccc ->
div '.currenttrack.autosize', {
'data-autosize-max': 34,
'data-autosize-min': 19,
'data-autosize-right-margin': 56 }, ->
otto.autosize_clear_cache()
if @song
span '.gotothere', 'data-id': @song._id, ->
@song.song || 'unknown'
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': @song._id
t.currentalbum_widget = ccc ->
if @song?.album
div '.album.gotothere', 'data-id': @song.albums[0]._id, ->
span @song.album
t.currentyear_widget = ccc ->
span '.year', @song?.year or ''
t.currentartist_widget = ccc ->
if @song?.artist
artist_id = @song.artists[0]?._id or 0
div '.artist.gotothere', 'data-id': artist_id, 'data-albumid': @song.albums[0]._id, ->
# data-albumid is a hack. see artist->fileunder note in gotothere code
@song.artist
t.count_widget = ccc ->
span '#count', ->
if @total or @count
totalstr = "#{@total}"
countstr = "#{@count}"
if countstr.length < totalstr.length
less = totalstr.length - countstr.length
for i in [1..less]
countstr = ' ' + countstr
span '#current-count', countstr
span '#total-count.sep', totalstr
t.time_widget = ccc ->
span '#time', ->
if @total or @current
totalstr = otto.t.format_time @total
currentstr = otto.t.format_time @current, totalstr.length
span '#current-time', currentstr
span '#total-time.sep', totalstr
t.timeprogress_widgets = ccc ->
if @total or @current
div '.timeprogress-binder', ->
s = @total
if s < 10 then s = 10
if s > 3600 then s = 3600
# fun fact: 2397 = 39:57, longest single to reach the UK charts!
#x = s / 2397 * 0.58
#x = s / 3600 * 0.58
x = s / 3600 * 1.718
scale = Math.sqrt( Math.log( x+1 ) )
sizePercent = scale * 100
progressPercent = Math.min((@current / @total * 100), 100)
div '.progress-maximum', {title: 'seek'}, ->
div '.progress-container', style: "width: #{sizePercent}%;", ->
div '.progress', ->
div '.progress-indicator', style: "width: #{progressPercent}%;", ''
div '.time-container', otto.t.time_widget(@)
t.channel_status_errata_widget = ccc ->
div '.time-container', ->
div '.time', ->
if @status.time
times = @status.time.split ':'
text otto.t.time_widget current: times[0], total: times[1]
#div '.audio', @status.audio || ''
div '.bitrate', if @status.bitrate then @status.bitrate + 'kbps' else ''
t.owner_widget = ccc ->
owner = ''
if @song? and @song.owners? and @song.owners[0]? and @song.owners[0].owner?
owner = @song.owners[0].owner
span '.owner', owner
t.requestor_widget = ccc ->
classstr = ''
if @nodecorations
if @song?.requestor
span '.requestor', @song.requestor.split('@')[0]
else
if @song? and @song.owners? and @song.owners[0]? and @song.owners[0].owner?
classstr = '.sep'
if @song?.requestor
span classstr, 'requested by '
span '.requestor', @song.requestor
t.filename_widget = ccc ->
if @song?.filename
span '.filename.shy', @song.filename
t.currentcover_widget = ccc ->
if @song
div '.thumb.px300.gotothere', { 'data-id': @song._id }, ->
if @song.cover
img
height: 300
width: 300
#src: "/image/300?id=#{@song.cover}"
src: "/image/orig?id=#{@song.cover}"
title: @song.album
else
div '.noimg.px300', ->
div @song.album
div '.noimgspacer', ''
div @song.artist
else
div '.thumb.px300', {}, ->
t.enqueue_widget = ccc ->
button '.enqueue.control.teeny.shy', ''
t.unqueue_widget = ccc ->
addtoclassstr = @addtoclassstr || ''
button '.btn.teeny.control.unqueue'+addtoclassstr, ''
t.currenttrack = ccc ->
div '.currenttrack-binder', ->
div '.currentsong-container', otto.t.currentsong_widget(@)
div '.timeprogress-container', otto.t.timeprogress_widgets(@)
div '.currentalbum-container', otto.t.currentalbum_widget(@)
div '.currentyear-container', otto.t.currentyear_widget(@)
div '.currentartist-container', otto.t.currentartist_widget(@)
div '.currenterrata-container', ->
div '.owner-container', otto.t.owner_widget(@)
div '.requestor-container', otto.t.requestor_widget(@)
div '.currentcover-container', otto.t.currentcover_widget(@)
div '.filename-container', ->
div '.filename-clipper', otto.t.filename_widget(@)
t.playing = ccc ->
div '.playing-container.reveal', ->
if otto.haslineout and otto.localhost
div '.play-container', otto.t.play_widget
div '.shy', otto.t.volumelineout_widget
else
#button '#connect.control.large.'+@channel.type, otto.t.icon 'disconnected'
#button '#connect.control.large.'+@channel.type, ->
div '.connect-container', ->
button '#connect.control.large', { title: 'connect/disconnect' }, ->
#img src: 'static/images/disconnected.svg', height: 20, width: 20
text otto.t.icon 'connect'
div '.shy', otto.t.volume_widget
size = @size || 'size1'
div ".size-container.#{size}", otto.t.size_widget
div ".next-container.#{size}", otto.t.next_widget
div ".currenttrack-container.#{size}", otto.t.currenttrack(@)
t.thealbum = ccc ->
div '.thealbum-container.reveal', ->
''
templates.browse = coffeecup.compile ->
div '.browse-container', ->
div '.browsecontrols-container', ->
div '.search-container', ->
form '#searchform.searchform', method:'get', action:'', ->
input '#searchtext.searchtext', type:'text', name:'search', placeholder: 'search', autocorrect: 'off', autocapitalize: 'off'
input '.search_button.buttonless', type:'submit', value:'Search'
div '.letterbar-container', ->
ul '.letterbar', ->
#bigwarning = if @largedatabase then '.warn.big' else '' # bzzz! not passed in FIXME
bigwarning = ''
li '.letter.control.shownewest.gap', {title: 'newest'}, otto.t.icon 'newest'
li '.letter.control.showall.gap'+bigwarning, {title: 'all'}, otto.t.icon 'all'
if not @largedatabase # need to make it faster, times out on very large databases FIXME
li '.letter.control.showusers.gap', {title: 'users'}, otto.t.icon 'users'
li '.letter.control.showstars.gap', {title: 'starred'}, otto.t.icon 'star'
li '.letter.control.showcubes.gap'+bigwarning, {title: 'cubes'}, otto.t.icon 'cubes'
# other fun character considerations: ⁂ ? № ⁕ ⁖ ⁝ ⁞ ⃛ ⋯ +⚂ ⚐ ⚑
# someday add back: st va
li '.letter.gap', 'A'
for letter in 'B C D E F G H I J K L M N O P Q R S T U V W X Y Z # ⋯'.split(' ')
if letter is '#'
li '.letter', {title: 'numbers'}, letter
else if letter is '⋯'
li '.letter', {title: 'other'}, letter
else
li '.letter', letter
#li '.letter.gap.warn.beta', '/'
#li '.letter.showlists.gap', '✓'
div '.browseresults-container', ''
t.footer = ccc ->
div '.logo-container.footer-logo-container', ->
span '.logo.footer-logo', ''
templates.login = coffeecup.compile ->
div '.login-container', ->
div '.login', ->
form '#loginform.loginform', method:'get', action:'', ->
span '.loginlabel', 'To browse and select songs '
# note the homograph unicode cryillic 'a' in 'email' in the placeholder string
# this is to keep safari from prompting for an auto fill. sigh.
input '#logintext.logintext', type:'text', placeholder: 'enter your emаil / username here', autocorrect: 'off', autocapitalize: 'off', autocomplete: 'off', autofill: 'off'
input '.login_button.buttonless', type:'submit', value:'Search'
templates.listeners = coffeecup.compile ->
span '.listeners', ->
count=0
othercount=0
for id in @listeners
if @listeners[id].socketids or @listeners[id].streams
#console.log @listeners[id].channelname
if @listeners[id].channelname and @listeners[id].channelname == otto.mychannel
count++
else
othercount++
if not count
label = 'no listeners'
else
label = count + ' ' + 'listener' + otto.t.plural(count)
span '.count', label
if count
span '.sep', ''
first = true
us = null
for id in @listeners
if @listeners[id].socketids or @listeners[id].streams
for sid of @listeners[id].socketids
if sid is @socketid
us = id
if us and @listeners[us]
text otto.t.format_listener listener: @listeners[us], first: first, me: true
first = false
for id in @listeners
if id is us
continue
if @listeners[id].socketids or @listeners[id].streams
if @listeners[id].channelname and @listeners[id].channelname == otto.mychannel
text otto.t.format_listener listener: @listeners[id], first: first, me: false
first = false
if othercount
label = othercount + ' ' + 'other listener' + otto.t.plural(othercount)
span '', ' | '
span '.count', label
for id in @listeners
if id is us
continue
if @listeners[id].socketids or @listeners[id].streams
if @listeners[id].channelname and @listeners[id].channelname != otto.mychannel
text otto.t.format_listener listener: @listeners[id], first: first, me: false, showchannel: true
first = false
templates.format_listener = coffeecup.compile ->
name = @listener.user || @listener.host || @listener.address
if @shortname
name = name.split('@')[0]
inchat = no
typing = no
focus = no
idle = yes
for id of @listener.socketids
socket = @listener.socketids[id]
if socket
inchat = yes if socket.inchat? and socket.inchat
typing = yes if socket.typing? and socket.typing
focus = yes if socket.focus? and socket.focus
if socket.idle?
idle = no if not socket.idle
if idle
idle = 1
for id of @listener.socketids
socket = @listener.socketids[id]
if socket
idle = socket.idle if socket.idle > idle
classes = ''
classes += '.streaming' if @listener.streams
classes += '.inchat' if inchat
classes += '.typing' if typing
classes += '.idle' if idle or not focus
classes += '.thisisme' if @me
classes += '.sep' if not @first
title = ''
title += 'Streaming' if @listener.streams
if @listener.streams > 1
title += "X#{@listener.streams}"
if inchat
title += ', ' if title != ''
title += 'In chat' if inchat
if typing
title += ', ' if title != ''
title += 'Typing'
if idle or not focus
title += ', ' if title != ''
if idle
minutes = Math.floor( (Date.now() - parseInt(idle)) / (60 * 1000) )
if minutes < 120
title += "Idle for #{minutes} minutes"
else
title += 'Idle since ' + Date(idle).toString()
else
title += 'Window not focused'
if @listener.host || @listener.address # i guess these are not being set? FIXME
title += ', ' if title != ''
title += 'Connected from ' + @listener.host || @listener.address
div '.listener'+classes, title: title, ->
text name
if @showchannel
span '.channel', ' (' + @listener.channelname + ')'
if @me
if @listener.user
span '.thisisme', ->
span '.you', '(you)'
button '.control.small.logout', {title: 'logout'}, otto.t.icon 'logout'
t.format_listeners_for_channel_in_channelbar = ccc ->
span '.listeners', ->
first = true
for id in @listeners
if @listeners[id].socketids or @listeners[id].streams
if @listeners[id].channelname and @listeners[id].channelname == @channelname
text otto.t.format_listener listener: @listeners[id], first: first, me: false, shortname: true
first = false
templates.channellist = coffeecup.compile ->
div '.channellistheader', ->
button '.control.medium.channeltoggle', otto.t.icon 'close'
ul ->
for i in [1..1]
for channel in @channellist
classes = '.changechannel'
classes = classes + '.currentchannel.open' if channel.name is otto.mychannel
li classes, 'data-channelname': channel.name, ->
button '.channelsettings.control.small.shy', {title: 'more info'}, otto.t.icon 'info'
div '.channelselect', ->
div '.channelname.autosize', {
'data-autosize-max': 20,
'data-autosize-min': 12,
'data-autosize-right-margin': 0 }, ->
otto.autosize_clear_cache()
channel.fullname
div '.channellisteners', ->
if @listeners
# if we reactive the count we should consider omitting if it's 1
#span '.listeners.count', count || ''
text otto.t.format_listeners_for_channel_in_channelbar listeners: @listeners, channelname: channel.name
button '.channeloutput.control.small.shy', {title: 'toggle lineout'}, otto.t.icon 'output'
div '.settings', ->
#button '.channelsettings.control.small', otto.t.icon 'close'
button '.channelplay.control.medium2', {title: 'play/pause'}, otto.t.icon 'play'
text otto.t.volumelineout_widget()
div '.channelerrata-container', ''
#button '.channelfork.control.small', {title: 'fork'}, otto.t.icon 'fork'
button '.crossfade.control.small', {title: 'crossfade'}, 'CF'
button '.replaygain.control.small', {title: 'replay gain'}, 'RG'
templates.page_it_out = (items, pagesize, lazychunksize, element, render) ->
pages = 0
pagestart = 0
# someday we should get clever here about not making pages with too few items
# we could also consider waiting to construct pages until they are scrolled to
while pagestart < items.length
pageitems = items.slice(pagestart, pagestart+pagesize)
chunkstart = 0
# further break the page into chunks to make it easier for lazyload searching
element '.page', ->
while chunkstart < pageitems.length
element '.lazychunk', ->
chunk = pageitems.slice(chunkstart, chunkstart+lazychunksize)
for item in chunk
# call the supplied render routine on each item
render item
chunkstart += lazychunksize
pagestart += pagesize
pages += 1
templates.startswith = coffeecup.compile ->
empty = true
otto.t.page_it_out @data, 200, 10, div, (item) ->
empty = false
text otto.t.artist item: item
if empty
div '.none', 'Nothing filed under ' + @params.value
templates.allalbums = coffeecup.compile ->
div '.thumbnails', ->
empty = true
otto.t.page_it_out @data, 300, 100, span, (album) ->
empty = false
div '.albumall', ->
div '.thumb.px120.expand', 'data-id': album._id, ->
if album.cover
img '.albumimg.lazy', height: 120, width: 120, \
#src: 'static/images/gray.gif', \
#src: 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==', \
#src: 'static/images/clear.gif', \
src: 'static/images/clear.png', \
'data-original': "/image/120?id=#{album.cover}", \
title: album.album
else
div '.noimg.px120', -> album.album + '<br>' + album.fileunder[0].name + '<br>' + album.owners[0].owner + '<br>' + album.year #+ album.genre
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': album._id
if empty
div '.none', 'No albums loaded'
templates.artist = coffeecup.compile ->
div '.artistlist', ->
if not @nostars
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': @item._id
div '.artistname-container', ->
span '.artistname.expand', {'data-id': @item._id }, @item.name # was @item.artist before fileunder
ul '.thumbnails', ->
if @item.albums?
albumorder = otto.t.orderalbums @item.albums
for album in albumorder
li '.h.thumb.px40.expand', 'data-id': album._id, 'data-container': @item._id, ->
if album.cover
img '.albumimg.lazy', src: 'static/images/clear.png', height: 40, width: 40, 'data-original': "/image/40?id=#{album.cover}", title: album.album
else
div '.noimg.px40', -> album.album
templates.album = coffeecup.compile ->
expand = if @noexpand then '' else '.expand'
div '.albumlist', ->
div '.thumbnails', ->
div '.thumb.px40'+expand, 'data-id': @item._id, 'data-container': @item._id, ->
if @item.cover
if @nolazy
img '.albumimg', src: "/image/40?id=#{@item.cover}", height: 40, width: 40, title: @item.album
else
img '.albumimg.lazy', src: 'static/images/clear.png', height: 40, width: 40, 'data-original': "/image/40?id=#{@item.cover}", title: @item.album
else
div '.noimg.px40', -> @item.album
span '.albumname'+expand, 'data-id': @item._id, ->
artistinfo = otto.compute_artistinfo @item
span @item.album
if artistinfo.single
span '.artist.sep', artistinfo.single
if @item.year?
span '.sep', @item.year
if otto.myusername and not @nostars
button '.stars.control.teeny.shy.n0', 'data-id': @item._id
templates.orderalbums = (albums) ->
albumorder = []
variousorder = []
for album in albums
if not album.artistinfo?
album.artistinfo = otto.compute_artistinfo album
if album.artistinfo.various
variousorder.push album
else
albumorder.push album
sorter = (a, b) ->
#if a.songs?[0]?.year? and b.songs?[0].year?
if a.year? and b.year?
ayear = Number(a.year)
byear = Number(b.year)
if ayear < byear
return -1
else if ayear > byear
return 1
else
if a.album? and b.album?
return a.album.localeCompare b.album, {sensitivity: "base", numeric: true}
else if a.album?
return -1
else if b.album?
return 1
else return 0
else if a.year?
return -1
else if b.year?
return 1
else
if a.album? and b.album?
return a.album.localeCompare b.album, {sensitivity: "base", numeric: true}
else if a.album?
return -1
else if b.album?
return 1
else return 0
albumorder.sort(sorter)
variousorder.sort(sorter)
return albumorder.concat(variousorder)
templates.albums_details = coffeecup.compile ->
div '.albumlist-container', { 'data-id': @_id }, ->
button '.close.control.tiny.shy', otto.t.icon 'close'
#if @data.length > 1
button '.close.lower.control.tiny.shy', otto.t.icon 'close'
div '.albumlist', ->
albumorder = otto.t.orderalbums @data
had_various = false
had_nonvarious = false
for album in albumorder
if album.artistinfo.various
if had_nonvarious and not had_various
div '.varioussep', ''
had_various = true
else
had_nonvarious = true
text otto.t.album_details album: album, fileunder: @fileunder
templates.album_details = coffeecup.compile ->
if not @album.artistinfo?
@album.artistinfo = otto.compute_artistinfo @album
div '.albumdetails', ->
div '.albumcover-container', ->
if @album.cover
div '.thumb.px200', ->
#img src: "/image/300?id=#{@album.cover}", alt: @album.album, title: @album.album
img src: "/image/orig?id=#{@album.cover}", alt: @album.album, title: @album.album
else
div '.noimg.px200', ->
if @album.artistinfo.various
span @album.artistinfo.various
else
for artist in @album.artistinfo.all
span -> artist
br()
span @album.album
div '.stars-container', ->
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': @album._id
div '.year-container', ->
if @album.years?
format_years = @album.years[0]
for year in @album.years[1..]
format_years += ', '+year
div '.year', format_years
else if @album.year?
div '.year', @album.year
div '.albuminfo', ->
div '.album', ->
span ".id#{@album._id}", 'data-id': @album._id, ->
span @album.album
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': @album._id
if @album.artistinfo.various
div '.artist', @album.artistinfo.various
else
for artist in @album.artistinfo.all
div '.artist', -> artist
if @album.owners?[0]?.owner
div '.owner', -> @album.owners[0].owner
div '.albumsongs.cf', ->
table ->
for song in @album.songs
tr -> td ->
text otto.t.enqueue_widget()
span ".id#{song._id}", {'data-id': song._id}, song.song
if @album.artistinfo.various or song.artist is not @album.artistinfo.primary
# this doesn't work when the fileunder name has been transformed in any way FIXME
if @album.artistinfo.various and @fileunder and song.artist is @fileunder.name
span '.subartist.highlight.sepgray', song.artist
else
span '.subartist.sep', song.artist
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': song._id
#button '.stars.control.teeny.shy.n0', {'data-id': song._id}, otto.t.icon 'star'
span '.time.sep.shy', otto.t.format_time(song.length)
div '.albumdir.dirpath.shy', ->
@album.dirpath
templates.ondeck = coffeecup.compile ->
table '.ondeck', ->
# the rest of the queue, on deck
for song in @songs
tr ->
td '.requestor-container', otto.t.requestor_widget( song: song, nodecorations: true )
td ->
text otto.t.unqueue_widget( addtoclassstr: '.shy' )
addtoclassstr = ''
if song.requestor
addtoclassstr='.requested'
span ".song.id#{song._id}#{addtoclassstr}", { 'data-id': song._id, 'data-mpdqueueid': song.mpdqueueid }, song.song
span '.album.sep', song.album
span '.artist.sep', song.artist
span '.sep', otto.t.format_time(song.length)
span '.shy', ->
if song.owners
owner = song.owners[0].owner
else
owner = ''
span '.owner.sep', -> owner
span '.filename.sep', -> song.filename
templates.featured = coffeecup.compile ->
ul '.ondeck', ->
# the rest of the queue, on deck
for song, n in @songs
li ->
if song.requestor
span '.requestor', ->
div -> song.requestor
else
span '.requestor', -> ''
if song.nowplaying
span '.playing.control.teeny', otto.t.icon 'play'
span '.song.currenttrack', -> song.song
else
button '.play.control.teeny.shy', id: song.mpdqueueid, 'data-position': n, ->
text otto.t.icon 'play'
span '.song', song.song
span '.album.sep', song.album
span '.artist.sep', song.artist
span '.sep', otto.t.format_time(song.length)
span '.shy', ->
if song.owners
owner = song.owners[0].owner
else
owner = ''
span '.owner.sep', -> owner
span '.filename.sep', -> song.filename
templates.alert = coffeecup.compile ->
div class: 'alert alert-info', ->
span @message
br()
br()
button '#ok.runself.control.large', 'ok'
text ' '
button '#cancel.runself.control.large', 'cancel'
templates.search = coffeecup.compile ->
div '.search', ->
if not @data.fileunders.length and not @data.albums.length and not @data.songs.length
div class: 'noresults'
else
if @data.fileunders.length
div class: 'section', 'Artists'
div ->
for fileunder in @data.fileunders
#li -> fileunder.name
div -> otto.t.artist item: fileunder
if @data.albums.length
div class: 'section', 'Albums'
div class: 'albums', ->
for album in @data.albums
div -> otto.t.album item: album
if @data.songcomposers? and @data.songcomposers.length
div '.section', 'Composers'
ul class: 'songs', ->
for song in @data.songcomposers
filename = song.filename
li ->
button '.enqueue.control.teeny.shy', 'data-oid': song.oid
composers = ''
if song.tags['©wrt']
composers = song.tags['©wrt']
composers = composers.replace /^\[u\'/, ''
composers = composers.replace /\'\]$/, ''
if song.tags['TCOM']
if composers
composers = composers + ', '
composers = song.tags['TCOM']
span "[#{composers}] "
span id: song.oid, class: 'song', -> song.song
span class: 'sep'
span class: 'album', -> song.album
span class: 'sep'
span class: 'artist', -> song.artist
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-oid': song.oid
span class: 'shy', ->
span class: 'sep'
span -> otto.t.format_time(song.length)
if song.owners
owner = song.owners[0].owner
else
owner = ''
span class: 'sep'
span class: 'queue owner', -> owner
span class: 'sep'
span class: 'queue filename', -> filename
songs_list = {}
if @data.songs.length
div class: 'section', 'Songs'
ul class: 'songs', ->
for song in @data.songs
songs_list[song._id] = true
li ->
text otto.t.enqueue_widget()
span ".song.id#{song._id}", { 'data-id': song._id }, song.song
span '.album.sep', song.album
span '.artist.sep', song.artist
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': song._id
span class: 'shy', ->
span class: 'sep'
span -> otto.t.format_time(song.length)
owner = ''
if song.owners
owner = song.owners[0].owner
span '.owner.sep', owner
span '.filename.sep', song.filename
other_cleaned = []
if @data.other
for song in @data.other
if songs_list[song._id]
continue
other_cleaned.push(song)
if other_cleaned.length
div 'Other'
ul class: 'my-new-list', ->
for song in other_cleaned
li ->
text otto.t.enqueue_widget()
span ".id#{song._id}", { 'data-id': song._id }, song.song
span '.sep', song.album
span '.sep', song.artist
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': song._id
span '.filename.sep.shy', song.filename
templates.newest_albums = coffeecup.compile ->
div '.search', ->
div '.section', 'Newest Albums'
empty = true
lasttimestamp = false
div '.albums', ->
owner = ''
for album in @data
empty = false
if lasttimestamp
interval = lasttimestamp - album.timestamp
else
interval = 0
lasttimestamp = album.timestamp
if album.owners?
if owner isnt album.owners[-1..][0].owner
owner = album.owners[-1..][0].owner
div '.newestowner', owner + ' ' + otto.t.format_timestamp(album.timestamp)
else if interval > 3600000
div '.newestowner', owner + ' ' + otto.t.format_timestamp(album.timestamp)
else if owner
owner = ''
div '.newestowner', '' + otto.t.format_timestamp(album.timestamp)
else if interval > 3600000
div '.newestowner', owner + ' ' + otto.t.format_timestamp(album.timestamp)
div -> otto.t.album item: album
if empty
div '.none', 'None'
otto.event_last_display_time = false
templates.event = coffeecup.compile ->
div '.event', ->
timestamp = new Date(@event.timestamp)
display_time = otto.t.format_time(timestamp.getHours() * 60 + timestamp.getMinutes(), 5)
if display_time isnt otto.event_last_display_time
span '.timestamp', display_time
otto.event_last_display_time = display_time
else
span '.timestamp', ''
#span class: 'id', -> @event.id
if @event.user
short_username = @event.user.split('@')[0]
span '.user', -> short_username
#span '.channel', -> @event.channel
if @event.message?
if otto.showdown_converter?
message_markeddown = otto.showdown_converter.makeHtml(@event.message)
else
message_markeddown = @event.message
span '.message', message_markeddown
#text message_markeddown
else
span '.name', -> @event.name
templates.event_text = (event) ->
text = ""
if event.user
short_username = event.user.split('@')[0]
else
short_username = 'unknown'
text += short_username + ' '
#text += event.channel
if event.message?
#if otto.showdown_converter?
# message_markeddown = otto.showdown_converter.makeHtml(@event.message)
#else
# message_markeddown = @event.message
#text += message_markeddown
text += event.message
else
text += event.name
templates.loader = coffeecup.compile ->
div class: 'event loader', ->
span class: 'message', "scan: #{@event}"
templates.show_users = coffeecup.compile ->
div '.userlist', ->
empty = true
if @data
table ->
for user in @data
empty = false
tr '.section', ->
td '.owner', user.owner
td if user.songs then "#{user.songs} song" + otto.t.plural(user.songs)
td if user.albums then "#{user.albums} album" + otto.t.plural(user.albums)
td if user.artists then "#{user.artists} artist" + otto.t.plural(user.artists)
td "#{user.stars} starred item" + otto.t.plural(user.stars)
if empty
div '.none', 'None'
templates.show_stars = coffeecup.compile ->
div '.starslist', ->
nostar = true
if @data
for user of @data
starlist = []
for staritem in @data[user]
if staritem.rank > 0
starlist.push staritem
if starlist and starlist.length
nostar = false
div ' '
div '.section', ->
span user
span '.sep', ->
span starlist.length.toString() + ' item' + otto.t.plural(starlist.length)
if otto.myusername
span class: 'shy', -> button class: 'download btn teeny control', 'data-id': user._id, -> i class: 'download-alt'
div '.songs', -> # .songs? that isn't good FIXME
if starlist and starlist.length
for item in starlist
switch item.otype
when 40 then addclass = '.starredartist'
when 20 then addclass = '.starredalbum'
else addclass = '.starredsong'
div '.starreditem'+addclass, ->
if otto.myusername and user is otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': item._id
else
button ".stars.control.teeny.n#{item.rank}.immutable.noupdate", 'data-id': item._id
if item.otype == 40
text otto.t.artist item: item, nostars: true
else if item.otype == 20
text otto.t.album item: item, nostars: true
else
song = item
text otto.t.enqueue_widget()
span ".song.id#{song._id}", { 'data-id': song._id }, song.song
span '.album.sep', song.album
span '.artist.sep', song.artist
span '.sep.shy', otto.t.format_time(song.length)
if song.owners
owner = song.owners[0].owner
span '.owner.sep.shy', owner
span '.filename.sep.shy', song.filename
if nostar
div '.nostars', 'Nothing starred yet'
templates.dirbrowser = coffeecup.compile ->
div '.dirbrowser', ->
ul '.path'
div '.subdirs'
div '.contents'
templates.dirbrowser_subdir = coffeecup.compile ->
ul ->
for dir in @data.dirs
li class: 'subdir', id: dir._id, 'data-filename': dir.filename, ->
dir.filename+'/'
templates.dirbrowser_item = coffeecup.compile ->
for dir in @data
li class: 'path', id: dir._id, -> dir.filename+'/'
templates.ouroboros = coffeecup.compile ->
div '.ouroboros', ->
modifiers = ''
modifiers += '.' + (@size || 'medium') # small, medium, large
modifiers += '.' + (@speed || 'normal') # slow, normal, fast
modifiers += '.' + (@direction || 'cw') # cw, ccw
modifiers += '.' + (@color || 'gray') # gray, blue
modifiers += '.' + (@background || 'dark') # dark, black
div ".ui-spinner#{modifiers}", ->
span '.side.left', ->
span '.fill', ''
span '.side.right', ->
span '.fill', ''
t.format_time = (seconds, minlen=4) ->
hours = parseInt(seconds / 3600)
seconds = seconds % 3600
minutes = parseInt(seconds / 60)
seconds = parseInt(seconds % 60)
if seconds < 10
seconds = '0' + seconds
else
seconds = '' + seconds
if minutes < 10 and (hours > 0 or minlen > 4)
minutes = '0' + minutes
else
minutes = '' + minutes
formatted = ''
if hours or minlen > 6
formatted = "#{hours}:#{minutes}:#{seconds}"
else
formatted = "#{minutes}:#{seconds}"
t.format_timestamp = (timestamp) ->
if timestamp
#d = new Date(timestamp * 1000)
#hours = d.getHours();
#minutes = d.getMinutes();
#seconds = d.getSeconds();
#day = d.getDate()
#month = d.getMonth()
#return moment(timestamp).fromNow() # i like this one
return moment(timestamp).format('ddd MMM Do YYYY ha')
else
return ''
templates.icon = coffeecup.compile ->
switch String @
when 'play' then span '.icon-play2', ''
when 'connect' then span '.icon-play', ''
when 'pause' then span '.icon-pause', ''
#when 'kill' then span '.icon-remove', ''
when 'kill' then span '.icon-minus', ''
when 'menu' then span '.icon-menu', ''
when 'chat' then span '.icon-bubble2', ''
when 'bigger' then span '.icon-zoomin', ''
when 'smaller' then span '.icon-zoomout', ''
when 'newest' then span '.icon-download', ''
when 'all' then span '.icon-grid', ''
when 'star' then span '.icon-star', ''
when 'users' then span '.icon-users', ''
when 'cubes' then span '.icon-stack2', ''
when 'close' then span '.icon-close', ''
when 'enqueue' then span '.icon-plus', ''
when 'unqueue' then span '.icon-minus', ''
when 'logout' then span '.icon-cancel-circle', ''
when 'fork' then span '.icon-fork', ''
when 'tag' then span '.icon-tag', ''
when 'tags' then span '.icon-tags', ''
#when 'output' then span '.icon-volume-medium', ''
when 'output' then span '.icon-volume-mute', ''
when 'outputmute' then span '.icon-volume-mute2', ''
when 'outputsel' then span '.icon-volume-mute', ''
when 'notifications' then span '.icon-bubble3', ''
when 'soundfx' then span '.icon-lightning', ''
when 'folder' then span '.icon-folder-open', ''
when 'info' then span '.icon-info', ''
else span '.icon-blocked', ''
t.plural = (count, single, plural) ->
return if count is 1 then single || '' else plural || 's'
console.log 'templates defined'
return templates
| 150704 | ####
#### client side (body of otto.client.templates.coffee served as /otto.templates.js)
####
# binds to otto.templates (on the client side), not otto.client.templates
# for historical reasons (and brevity)
global.otto.client.templates = ->
$('head').append '<script src="static/js/coffeecup.js">' if not window['coffeecup']?
window.otto = window.otto || {}
window.otto.client = window.otto.client || {}
window.otto.client.templates = true # for otto.load_module's benefit
window.otto.templates = do ->
templates = {}
t = otto.t = templates
ccc = coffeecup.compile
# you can't reference 'templates' or 't' in the compiled functions scope
# (i'm guessing because they are 'eval'ed), use otto.templates instead
add = templates: templates, t: t
t.body_welcome = ccc ->
div '#welcome', otto.t.welcome @
t.body = ccc ->
nav '.channellist-container', ''
div '#mainpage', ''
div '.ouroboros-container', ''
#div '.footer-container', otto.t.footer()
div '.cursor-hider', ''
t.body_reset = ->
$('.channellist-container').empty()
$('#mainpage').empty()
$('.ouroboros-container').empty()
#$('.footer-container').html otto.t.footer()
$('.cursor-hider').empty()
t.welcome = ccc ->
div '.wecome-container', ->
div '.welcome', ->
text otto.t.logo()
div '.greeting', ->
div '.hi', 'hello!'
div '.explain', 'I love to play your music for you, but first I need to scan it'
div '.explain', 'don\'t worry, I won\'t move it or anything like that'
br()
br()
div '.explain', 'I\'ll scan for music in this folder'
div ->
div '.folder', ->
button '.control.medium2.selectfolder', otto.t.icon 'folder'
input '#selectFolder', type: 'file', style: 'display: none' #must match UIDelegate in Otto.py
span '.path', contenteditable: '', @musicroot
div '.explain.note', ->
text '(press '
button '.control.small.selectfolder.', otto.t.icon 'folder'
text ' to change this)'
button '.control.large.wide.loadmusic', 'scan'
div '.footer-container', ''
t.initialload = ccc ->
div '.welcome-container', ->
div '.welcome', ->
text otto.t.logo()
div '.initialload-container', otto.t.cubesloader @
t.cubeswithload = ccc ->
div '.cubeswithload-container', otto.t.cubesloader @
t.cubesloader = ccc ->
div '.loadingstatus', otto.t.loadingstatuses @
div '.loadingprogress', ''
div '.loadingcurrent', ''
div '.loadingcubes-container', ->
div '.loadingcubes', ''
t.loadingstatuses = ccc ->
div '.status.begin', ->
button '.control.large.wide.loadmusic2', 'scan'
div '.status.searching', ->
div '.loadingspinner', ->
div otto.t.ouroboros size: 'medium', direction: 'cw', speed: 'fast'
div '.note', 'searching'
div '.status.loading', ->
div '.loadingspinner', ->
div otto.t.ouroboros size: 'medium', direction: 'cw', speed: 'slow'
div '.note', 'scanning'
div '.status.finished', ->
div ->
text 'all finished! press '
button '.control.small.begin', otto.t.icon 'play'
text ' to begin.'
button '.control.medium2.begin', otto.t.icon 'play'
div '.status.nonefound', ->
div ->
div 'sorry, I was unable to find any music I can play'
br()
if @folder
div 'in folder ' + @folder
else
div 'in that folder'
br()
br()
button '.control.large.wide.restartload', 'restart'
div '.status.error', ->
div ->
text 'sorry, I encountered an error while scanning'
button '.control.large.wide.begin.continue', 'continue'
t.cubes = ccc ->
div '.cubes-container', ->
div '.landscape-right', ''
div '.landscape-left', ''
div '.cubes', ->
div '.scene', ''
#div '.resort.control.medium2', otto.t.icon 'cubes'
t.cubelink = ccc ->
div '.cubelink.'+@rowclass, 'data-id': @id, title: @title, ->
div '.cube', style: @style
t.stacklabel = ccc ->
div '.stacklabel', style: @style, @letter
t.countprogress = ccc ->
if @total or @count
div '.countprogress-binder', ->
s = @total
sizePercent = 100
progressPercent = Math.min((@count / @total * 100), 100)
div '.progress-maximum', ->
div '.progress-container', style: "width: #{sizePercent}%;", ->
div '.progress', ->
div '.progress-indicator', style: "width: #{progressPercent}%;", ''
div '.count-container', otto.t.count_widget(@)
t.logo = ccc ->
div '.logo-container', ->
#span '.logo', ''
a '.logo', href: 'http://ottoaudiojukebox.com/', target: '_blank', ->
t.mainpage = ccc ->
if @channel.layout is 'webcast'
text otto.t.channelbar channel: @channel
text otto.t.console()
text otto.t.webcast()
else if @channel.layout is 'featured'
text otto.t.channelbar channel: @channel
text otto.t.console()
text otto.t.featured()
#else if @channel.layout is 'holidays'
# happy holidays
else
text otto.t.channelbar channel: @channel
text otto.t.login()
text otto.t.playing @
text otto.t.thealbum()
div '.ondeckchattoggle-container', ->
div '.ondeck-container', ''
div '.chattoggle-container', ->
button '.control.medium.chattoggle.shy', {title: 'chat'}, otto.t.icon 'chat'
text otto.t.console()
text otto.t.browse @
#div '.footer-backer', ''
templates.console = coffeecup.compile ->
div '.console-container', tabindex: -1, ->
button '.control.medium.chattoggle.shy', otto.t.icon 'close'
div '.output-container', ->
div '.output.scrollkiller', ''
div '.input-container', ->
div '.inputl', ->
#pre '#prompt', ''
div '#prompt', ''
div '.inputr-container', ->
div '#inputr', -> # must be an id, not class
div '#terminal', ->
#textarea '.input', spellcheck: 'false'
#div '.inputcopy', ''
t.chathelp = ccc ->
div '.chathelp', ->
div '/cls - clear screen'
div '/next - next track'
div '/pause - pause playing'
div '/play - resume playing'
div '/nick <name> - change username'
div '/part - leave chat'
div '/help - show commands'
t.chatunknowncommand = ccc ->
div '.chatunknowncommand', ->
'unknown command ' + @prefix + @command
t.channelbar = ccc ->
console.log 'channelbar', @
div '.channelbar-container.reveal', ->
div '.channelbar', ->
div '.channelbar-left', ->
button '.control.medium.channeltoggle.shy', {title: 'channels'}, otto.t.icon 'menu'
div '.channelbar-center', ->
div '.channelname-container', ->
div '.channelname', @channel.fullname
div '.hostname', ->
#host = @host
#if host and host.indexOf(':') > 0
# host = host.substr(0, host.indexOf ':') || @host
#'http://' + host
r = /^(http:\/\/)?([^\/]*)/.exec(document.URL)
host = if r and r.length is 3 then r[2] else ''
host
text otto.t.logo()
div '.topcontrols-container', ->
#input '#fxtoggle', type: 'checkbox', checked: false
#label '#fx.shy', for: 'fxtoggle', ->
# span 'sound cues'
button '.control.medium2.soundfxtoggle.shy', {title: 'sound cues'}, otto.t.icon 'soundfx'
if Notification?
#input '#notificationstoggle', type: 'checkbox', checked: false
#label '#notifications.shy', for: 'notificationstoggle', ->
# span 'notifications'
button '.control.medium2.notificationstoggle.shy', {title: 'notifications'}, otto.t.icon 'notifications'
div '.channelbar-right', ->
#div '.chattoggle-container', ->
# button '.control.medium.chattoggle.shy', otto.t.icon 'chat'
div '.channelbar-lower', ->
div '.listeners-container', ''
templates.webcast = coffeecup.compile ->
div '#webcast-container', ->
div '#webcast-background', ->
img src: '/static/images/8013980828_82a933115b_k.jpg', title: '', alt: ''
div '#webcast-background-attribution', ->
a '#webcast-background-link', href: 'http://www.flickr.com/photos/joi/8013980828', target: '_blank',
"DJ Aaron by <NAME>"
div '#webcast-overlay', ->
div '.autosizeX', 'data-autosize-max': 34, 'data-autosize-min': 19, 'data-autosize-right-margin': 56, ->
otto.autosize_clear_cache()
div ->
span '.webcast-title', "Live Webcast"
#div '#webcast-compatability', ->
# "live broadcast currently works in Chrome and Firefox only"
div '#webcast-chatpointer', ->
"there is a chat button in the upper right"
templates.featuredX = coffeecup.compile ->
div '#archive-container', ->
div '#archive-background', ->
img src: '/static/images/webcast.png', title: '', alt: ''
div '#archive-background-attribution', ->
a '#archive-background-link', href: 'https://www.facebook.com/photo.php?fbid=10150666518958461&set=o.406990045995364&type=1&theater', ->
"photo by [AttributionHere]"
div '#archive-overlay', ->
div '.autosize', 'data-autosize-max': 34, 'data-autosize-min': 19, 'data-autosize-right-margin': 56, ->
otto.autosize_clear_cache()
div ->
span '.archive-title', "Archives"
templates.featured = coffeecup.compile ->
div '#playlist.featured.reveal', ->
t.play_widget = ccc ->
button '#play.control.medium2', {title: 'play/pause'}, otto.t.icon 'play'
t.next_widget = ccc ->
button '#next.control.medium2.shy', {title: 'next'}, otto.t.icon 'kill'
# no longer used
t.lineout_widget = ccc ->
input '#lineouttoggle', type: 'checkbox', checked: false
label '#lineout.shy', for: 'lineouttoggle', ->
span 'server output'
text otto.t.volumelineout_widget
t.volume_widget = ccc ->
div '.volume-container', {title: 'local volume'}, ->
div '.volume', ''
t.volumelineout_widget = ccc ->
div '.volumelineout-container', {title: 'lineout volume'}, ->
div '.volumelineout', ''
t.size_widget = ccc ->
div '.size-widget.shy', ->
button '#size.smaller.control.small', {title: 'smaller'}, otto.t.icon 'smaller'
button '#size.bigger.control.small', {title: 'bigger'}, otto.t.icon 'bigger'
t.currentsong_widget = ccc ->
div '.currenttrack.autosize', {
'data-autosize-max': 34,
'data-autosize-min': 19,
'data-autosize-right-margin': 56 }, ->
otto.autosize_clear_cache()
if @song
span '.gotothere', 'data-id': @song._id, ->
@song.song || 'unknown'
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': @song._id
t.currentalbum_widget = ccc ->
if @song?.album
div '.album.gotothere', 'data-id': @song.albums[0]._id, ->
span @song.album
t.currentyear_widget = ccc ->
span '.year', @song?.year or ''
t.currentartist_widget = ccc ->
if @song?.artist
artist_id = @song.artists[0]?._id or 0
div '.artist.gotothere', 'data-id': artist_id, 'data-albumid': @song.albums[0]._id, ->
# data-albumid is a hack. see artist->fileunder note in gotothere code
@song.artist
t.count_widget = ccc ->
span '#count', ->
if @total or @count
totalstr = "#{@total}"
countstr = "#{@count}"
if countstr.length < totalstr.length
less = totalstr.length - countstr.length
for i in [1..less]
countstr = ' ' + countstr
span '#current-count', countstr
span '#total-count.sep', totalstr
t.time_widget = ccc ->
span '#time', ->
if @total or @current
totalstr = otto.t.format_time @total
currentstr = otto.t.format_time @current, totalstr.length
span '#current-time', currentstr
span '#total-time.sep', totalstr
t.timeprogress_widgets = ccc ->
if @total or @current
div '.timeprogress-binder', ->
s = @total
if s < 10 then s = 10
if s > 3600 then s = 3600
# fun fact: 2397 = 39:57, longest single to reach the UK charts!
#x = s / 2397 * 0.58
#x = s / 3600 * 0.58
x = s / 3600 * 1.718
scale = Math.sqrt( Math.log( x+1 ) )
sizePercent = scale * 100
progressPercent = Math.min((@current / @total * 100), 100)
div '.progress-maximum', {title: 'seek'}, ->
div '.progress-container', style: "width: #{sizePercent}%;", ->
div '.progress', ->
div '.progress-indicator', style: "width: #{progressPercent}%;", ''
div '.time-container', otto.t.time_widget(@)
t.channel_status_errata_widget = ccc ->
div '.time-container', ->
div '.time', ->
if @status.time
times = @status.time.split ':'
text otto.t.time_widget current: times[0], total: times[1]
#div '.audio', @status.audio || ''
div '.bitrate', if @status.bitrate then @status.bitrate + 'kbps' else ''
t.owner_widget = ccc ->
owner = ''
if @song? and @song.owners? and @song.owners[0]? and @song.owners[0].owner?
owner = @song.owners[0].owner
span '.owner', owner
t.requestor_widget = ccc ->
classstr = ''
if @nodecorations
if @song?.requestor
span '.requestor', @song.requestor.split('@')[0]
else
if @song? and @song.owners? and @song.owners[0]? and @song.owners[0].owner?
classstr = '.sep'
if @song?.requestor
span classstr, 'requested by '
span '.requestor', @song.requestor
t.filename_widget = ccc ->
if @song?.filename
span '.filename.shy', @song.filename
t.currentcover_widget = ccc ->
if @song
div '.thumb.px300.gotothere', { 'data-id': @song._id }, ->
if @song.cover
img
height: 300
width: 300
#src: "/image/300?id=#{@song.cover}"
src: "/image/orig?id=#{@song.cover}"
title: @song.album
else
div '.noimg.px300', ->
div @song.album
div '.noimgspacer', ''
div @song.artist
else
div '.thumb.px300', {}, ->
t.enqueue_widget = ccc ->
button '.enqueue.control.teeny.shy', ''
t.unqueue_widget = ccc ->
addtoclassstr = @addtoclassstr || ''
button '.btn.teeny.control.unqueue'+addtoclassstr, ''
t.currenttrack = ccc ->
div '.currenttrack-binder', ->
div '.currentsong-container', otto.t.currentsong_widget(@)
div '.timeprogress-container', otto.t.timeprogress_widgets(@)
div '.currentalbum-container', otto.t.currentalbum_widget(@)
div '.currentyear-container', otto.t.currentyear_widget(@)
div '.currentartist-container', otto.t.currentartist_widget(@)
div '.currenterrata-container', ->
div '.owner-container', otto.t.owner_widget(@)
div '.requestor-container', otto.t.requestor_widget(@)
div '.currentcover-container', otto.t.currentcover_widget(@)
div '.filename-container', ->
div '.filename-clipper', otto.t.filename_widget(@)
t.playing = ccc ->
div '.playing-container.reveal', ->
if otto.haslineout and otto.localhost
div '.play-container', otto.t.play_widget
div '.shy', otto.t.volumelineout_widget
else
#button '#connect.control.large.'+@channel.type, otto.t.icon 'disconnected'
#button '#connect.control.large.'+@channel.type, ->
div '.connect-container', ->
button '#connect.control.large', { title: 'connect/disconnect' }, ->
#img src: 'static/images/disconnected.svg', height: 20, width: 20
text otto.t.icon 'connect'
div '.shy', otto.t.volume_widget
size = @size || 'size1'
div ".size-container.#{size}", otto.t.size_widget
div ".next-container.#{size}", otto.t.next_widget
div ".currenttrack-container.#{size}", otto.t.currenttrack(@)
t.thealbum = ccc ->
div '.thealbum-container.reveal', ->
''
templates.browse = coffeecup.compile ->
div '.browse-container', ->
div '.browsecontrols-container', ->
div '.search-container', ->
form '#searchform.searchform', method:'get', action:'', ->
input '#searchtext.searchtext', type:'text', name:'search', placeholder: 'search', autocorrect: 'off', autocapitalize: 'off'
input '.search_button.buttonless', type:'submit', value:'Search'
div '.letterbar-container', ->
ul '.letterbar', ->
#bigwarning = if @largedatabase then '.warn.big' else '' # bzzz! not passed in FIXME
bigwarning = ''
li '.letter.control.shownewest.gap', {title: 'newest'}, otto.t.icon 'newest'
li '.letter.control.showall.gap'+bigwarning, {title: 'all'}, otto.t.icon 'all'
if not @largedatabase # need to make it faster, times out on very large databases FIXME
li '.letter.control.showusers.gap', {title: 'users'}, otto.t.icon 'users'
li '.letter.control.showstars.gap', {title: 'starred'}, otto.t.icon 'star'
li '.letter.control.showcubes.gap'+bigwarning, {title: 'cubes'}, otto.t.icon 'cubes'
# other fun character considerations: ⁂ ? № ⁕ ⁖ ⁝ ⁞ ⃛ ⋯ +⚂ ⚐ ⚑
# someday add back: st va
li '.letter.gap', 'A'
for letter in 'B C D E F G H I J K L M N O P Q R S T U V W X Y Z # ⋯'.split(' ')
if letter is '#'
li '.letter', {title: 'numbers'}, letter
else if letter is '⋯'
li '.letter', {title: 'other'}, letter
else
li '.letter', letter
#li '.letter.gap.warn.beta', '/'
#li '.letter.showlists.gap', '✓'
div '.browseresults-container', ''
t.footer = ccc ->
div '.logo-container.footer-logo-container', ->
span '.logo.footer-logo', ''
templates.login = coffeecup.compile ->
div '.login-container', ->
div '.login', ->
form '#loginform.loginform', method:'get', action:'', ->
span '.loginlabel', 'To browse and select songs '
# note the homograph unicode cryillic 'a' in 'email' in the placeholder string
# this is to keep safari from prompting for an auto fill. sigh.
input '#logintext.logintext', type:'text', placeholder: 'enter your emаil / username here', autocorrect: 'off', autocapitalize: 'off', autocomplete: 'off', autofill: 'off'
input '.login_button.buttonless', type:'submit', value:'Search'
templates.listeners = coffeecup.compile ->
span '.listeners', ->
count=0
othercount=0
for id in @listeners
if @listeners[id].socketids or @listeners[id].streams
#console.log @listeners[id].channelname
if @listeners[id].channelname and @listeners[id].channelname == otto.mychannel
count++
else
othercount++
if not count
label = 'no listeners'
else
label = count + ' ' + 'listener' + otto.t.plural(count)
span '.count', label
if count
span '.sep', ''
first = true
us = null
for id in @listeners
if @listeners[id].socketids or @listeners[id].streams
for sid of @listeners[id].socketids
if sid is @socketid
us = id
if us and @listeners[us]
text otto.t.format_listener listener: @listeners[us], first: first, me: true
first = false
for id in @listeners
if id is us
continue
if @listeners[id].socketids or @listeners[id].streams
if @listeners[id].channelname and @listeners[id].channelname == otto.mychannel
text otto.t.format_listener listener: @listeners[id], first: first, me: false
first = false
if othercount
label = othercount + ' ' + 'other listener' + otto.t.plural(othercount)
span '', ' | '
span '.count', label
for id in @listeners
if id is us
continue
if @listeners[id].socketids or @listeners[id].streams
if @listeners[id].channelname and @listeners[id].channelname != otto.mychannel
text otto.t.format_listener listener: @listeners[id], first: first, me: false, showchannel: true
first = false
templates.format_listener = coffeecup.compile ->
name = @listener.user || @listener.host || @listener.address
if @shortname
name = name.split('@')[0]
inchat = no
typing = no
focus = no
idle = yes
for id of @listener.socketids
socket = @listener.socketids[id]
if socket
inchat = yes if socket.inchat? and socket.inchat
typing = yes if socket.typing? and socket.typing
focus = yes if socket.focus? and socket.focus
if socket.idle?
idle = no if not socket.idle
if idle
idle = 1
for id of @listener.socketids
socket = @listener.socketids[id]
if socket
idle = socket.idle if socket.idle > idle
classes = ''
classes += '.streaming' if @listener.streams
classes += '.inchat' if inchat
classes += '.typing' if typing
classes += '.idle' if idle or not focus
classes += '.thisisme' if @me
classes += '.sep' if not @first
title = ''
title += 'Streaming' if @listener.streams
if @listener.streams > 1
title += "X#{@listener.streams}"
if inchat
title += ', ' if title != ''
title += 'In chat' if inchat
if typing
title += ', ' if title != ''
title += 'Typing'
if idle or not focus
title += ', ' if title != ''
if idle
minutes = Math.floor( (Date.now() - parseInt(idle)) / (60 * 1000) )
if minutes < 120
title += "Idle for #{minutes} minutes"
else
title += 'Idle since ' + Date(idle).toString()
else
title += 'Window not focused'
if @listener.host || @listener.address # i guess these are not being set? FIXME
title += ', ' if title != ''
title += 'Connected from ' + @listener.host || @listener.address
div '.listener'+classes, title: title, ->
text name
if @showchannel
span '.channel', ' (' + @listener.channelname + ')'
if @me
if @listener.user
span '.thisisme', ->
span '.you', '(you)'
button '.control.small.logout', {title: 'logout'}, otto.t.icon 'logout'
t.format_listeners_for_channel_in_channelbar = ccc ->
span '.listeners', ->
first = true
for id in @listeners
if @listeners[id].socketids or @listeners[id].streams
if @listeners[id].channelname and @listeners[id].channelname == @channelname
text otto.t.format_listener listener: @listeners[id], first: first, me: false, shortname: true
first = false
templates.channellist = coffeecup.compile ->
div '.channellistheader', ->
button '.control.medium.channeltoggle', otto.t.icon 'close'
ul ->
for i in [1..1]
for channel in @channellist
classes = '.changechannel'
classes = classes + '.currentchannel.open' if channel.name is otto.mychannel
li classes, 'data-channelname': channel.name, ->
button '.channelsettings.control.small.shy', {title: 'more info'}, otto.t.icon 'info'
div '.channelselect', ->
div '.channelname.autosize', {
'data-autosize-max': 20,
'data-autosize-min': 12,
'data-autosize-right-margin': 0 }, ->
otto.autosize_clear_cache()
channel.fullname
div '.channellisteners', ->
if @listeners
# if we reactive the count we should consider omitting if it's 1
#span '.listeners.count', count || ''
text otto.t.format_listeners_for_channel_in_channelbar listeners: @listeners, channelname: channel.name
button '.channeloutput.control.small.shy', {title: 'toggle lineout'}, otto.t.icon 'output'
div '.settings', ->
#button '.channelsettings.control.small', otto.t.icon 'close'
button '.channelplay.control.medium2', {title: 'play/pause'}, otto.t.icon 'play'
text otto.t.volumelineout_widget()
div '.channelerrata-container', ''
#button '.channelfork.control.small', {title: 'fork'}, otto.t.icon 'fork'
button '.crossfade.control.small', {title: 'crossfade'}, 'CF'
button '.replaygain.control.small', {title: 'replay gain'}, 'RG'
templates.page_it_out = (items, pagesize, lazychunksize, element, render) ->
pages = 0
pagestart = 0
# someday we should get clever here about not making pages with too few items
# we could also consider waiting to construct pages until they are scrolled to
while pagestart < items.length
pageitems = items.slice(pagestart, pagestart+pagesize)
chunkstart = 0
# further break the page into chunks to make it easier for lazyload searching
element '.page', ->
while chunkstart < pageitems.length
element '.lazychunk', ->
chunk = pageitems.slice(chunkstart, chunkstart+lazychunksize)
for item in chunk
# call the supplied render routine on each item
render item
chunkstart += lazychunksize
pagestart += pagesize
pages += 1
templates.startswith = coffeecup.compile ->
empty = true
otto.t.page_it_out @data, 200, 10, div, (item) ->
empty = false
text otto.t.artist item: item
if empty
div '.none', 'Nothing filed under ' + @params.value
templates.allalbums = coffeecup.compile ->
div '.thumbnails', ->
empty = true
otto.t.page_it_out @data, 300, 100, span, (album) ->
empty = false
div '.albumall', ->
div '.thumb.px120.expand', 'data-id': album._id, ->
if album.cover
img '.albumimg.lazy', height: 120, width: 120, \
#src: 'static/images/gray.gif', \
#src: 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==', \
#src: 'static/images/clear.gif', \
src: 'static/images/clear.png', \
'data-original': "/image/120?id=#{album.cover}", \
title: album.album
else
div '.noimg.px120', -> album.album + '<br>' + album.fileunder[0].name + '<br>' + album.owners[0].owner + '<br>' + album.year #+ album.genre
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': album._id
if empty
div '.none', 'No albums loaded'
templates.artist = coffeecup.compile ->
div '.artistlist', ->
if not @nostars
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': @item._id
div '.artistname-container', ->
span '.artistname.expand', {'data-id': @item._id }, @item.name # was @item.artist before fileunder
ul '.thumbnails', ->
if @item.albums?
albumorder = otto.t.orderalbums @item.albums
for album in albumorder
li '.h.thumb.px40.expand', 'data-id': album._id, 'data-container': @item._id, ->
if album.cover
img '.albumimg.lazy', src: 'static/images/clear.png', height: 40, width: 40, 'data-original': "/image/40?id=#{album.cover}", title: album.album
else
div '.noimg.px40', -> album.album
templates.album = coffeecup.compile ->
expand = if @noexpand then '' else '.expand'
div '.albumlist', ->
div '.thumbnails', ->
div '.thumb.px40'+expand, 'data-id': @item._id, 'data-container': @item._id, ->
if @item.cover
if @nolazy
img '.albumimg', src: "/image/40?id=#{@item.cover}", height: 40, width: 40, title: @item.album
else
img '.albumimg.lazy', src: 'static/images/clear.png', height: 40, width: 40, 'data-original': "/image/40?id=#{@item.cover}", title: @item.album
else
div '.noimg.px40', -> @item.album
span '.albumname'+expand, 'data-id': @item._id, ->
artistinfo = otto.compute_artistinfo @item
span @item.album
if artistinfo.single
span '.artist.sep', artistinfo.single
if @item.year?
span '.sep', @item.year
if otto.myusername and not @nostars
button '.stars.control.teeny.shy.n0', 'data-id': @item._id
templates.orderalbums = (albums) ->
albumorder = []
variousorder = []
for album in albums
if not album.artistinfo?
album.artistinfo = otto.compute_artistinfo album
if album.artistinfo.various
variousorder.push album
else
albumorder.push album
sorter = (a, b) ->
#if a.songs?[0]?.year? and b.songs?[0].year?
if a.year? and b.year?
ayear = Number(a.year)
byear = Number(b.year)
if ayear < byear
return -1
else if ayear > byear
return 1
else
if a.album? and b.album?
return a.album.localeCompare b.album, {sensitivity: "base", numeric: true}
else if a.album?
return -1
else if b.album?
return 1
else return 0
else if a.year?
return -1
else if b.year?
return 1
else
if a.album? and b.album?
return a.album.localeCompare b.album, {sensitivity: "base", numeric: true}
else if a.album?
return -1
else if b.album?
return 1
else return 0
albumorder.sort(sorter)
variousorder.sort(sorter)
return albumorder.concat(variousorder)
templates.albums_details = coffeecup.compile ->
div '.albumlist-container', { 'data-id': @_id }, ->
button '.close.control.tiny.shy', otto.t.icon 'close'
#if @data.length > 1
button '.close.lower.control.tiny.shy', otto.t.icon 'close'
div '.albumlist', ->
albumorder = otto.t.orderalbums @data
had_various = false
had_nonvarious = false
for album in albumorder
if album.artistinfo.various
if had_nonvarious and not had_various
div '.varioussep', ''
had_various = true
else
had_nonvarious = true
text otto.t.album_details album: album, fileunder: @fileunder
templates.album_details = coffeecup.compile ->
if not @album.artistinfo?
@album.artistinfo = otto.compute_artistinfo @album
div '.albumdetails', ->
div '.albumcover-container', ->
if @album.cover
div '.thumb.px200', ->
#img src: "/image/300?id=#{@album.cover}", alt: @album.album, title: @album.album
img src: "/image/orig?id=#{@album.cover}", alt: @album.album, title: @album.album
else
div '.noimg.px200', ->
if @album.artistinfo.various
span @album.artistinfo.various
else
for artist in @album.artistinfo.all
span -> artist
br()
span @album.album
div '.stars-container', ->
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': @album._id
div '.year-container', ->
if @album.years?
format_years = @album.years[0]
for year in @album.years[1..]
format_years += ', '+year
div '.year', format_years
else if @album.year?
div '.year', @album.year
div '.albuminfo', ->
div '.album', ->
span ".id#{@album._id}", 'data-id': @album._id, ->
span @album.album
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': @album._id
if @album.artistinfo.various
div '.artist', @album.artistinfo.various
else
for artist in @album.artistinfo.all
div '.artist', -> artist
if @album.owners?[0]?.owner
div '.owner', -> @album.owners[0].owner
div '.albumsongs.cf', ->
table ->
for song in @album.songs
tr -> td ->
text otto.t.enqueue_widget()
span ".id#{song._id}", {'data-id': song._id}, song.song
if @album.artistinfo.various or song.artist is not @album.artistinfo.primary
# this doesn't work when the fileunder name has been transformed in any way FIXME
if @album.artistinfo.various and @fileunder and song.artist is @fileunder.name
span '.subartist.highlight.sepgray', song.artist
else
span '.subartist.sep', song.artist
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': song._id
#button '.stars.control.teeny.shy.n0', {'data-id': song._id}, otto.t.icon 'star'
span '.time.sep.shy', otto.t.format_time(song.length)
div '.albumdir.dirpath.shy', ->
@album.dirpath
templates.ondeck = coffeecup.compile ->
table '.ondeck', ->
# the rest of the queue, on deck
for song in @songs
tr ->
td '.requestor-container', otto.t.requestor_widget( song: song, nodecorations: true )
td ->
text otto.t.unqueue_widget( addtoclassstr: '.shy' )
addtoclassstr = ''
if song.requestor
addtoclassstr='.requested'
span ".song.id#{song._id}#{addtoclassstr}", { 'data-id': song._id, 'data-mpdqueueid': song.mpdqueueid }, song.song
span '.album.sep', song.album
span '.artist.sep', song.artist
span '.sep', otto.t.format_time(song.length)
span '.shy', ->
if song.owners
owner = song.owners[0].owner
else
owner = ''
span '.owner.sep', -> owner
span '.filename.sep', -> song.filename
templates.featured = coffeecup.compile ->
ul '.ondeck', ->
# the rest of the queue, on deck
for song, n in @songs
li ->
if song.requestor
span '.requestor', ->
div -> song.requestor
else
span '.requestor', -> ''
if song.nowplaying
span '.playing.control.teeny', otto.t.icon 'play'
span '.song.currenttrack', -> song.song
else
button '.play.control.teeny.shy', id: song.mpdqueueid, 'data-position': n, ->
text otto.t.icon 'play'
span '.song', song.song
span '.album.sep', song.album
span '.artist.sep', song.artist
span '.sep', otto.t.format_time(song.length)
span '.shy', ->
if song.owners
owner = song.owners[0].owner
else
owner = ''
span '.owner.sep', -> owner
span '.filename.sep', -> song.filename
templates.alert = coffeecup.compile ->
div class: 'alert alert-info', ->
span @message
br()
br()
button '#ok.runself.control.large', 'ok'
text ' '
button '#cancel.runself.control.large', 'cancel'
templates.search = coffeecup.compile ->
div '.search', ->
if not @data.fileunders.length and not @data.albums.length and not @data.songs.length
div class: 'noresults'
else
if @data.fileunders.length
div class: 'section', 'Artists'
div ->
for fileunder in @data.fileunders
#li -> fileunder.name
div -> otto.t.artist item: fileunder
if @data.albums.length
div class: 'section', 'Albums'
div class: 'albums', ->
for album in @data.albums
div -> otto.t.album item: album
if @data.songcomposers? and @data.songcomposers.length
div '.section', 'Composers'
ul class: 'songs', ->
for song in @data.songcomposers
filename = song.filename
li ->
button '.enqueue.control.teeny.shy', 'data-oid': song.oid
composers = ''
if song.tags['©wrt']
composers = song.tags['©wrt']
composers = composers.replace /^\[u\'/, ''
composers = composers.replace /\'\]$/, ''
if song.tags['TCOM']
if composers
composers = composers + ', '
composers = song.tags['TCOM']
span "[#{composers}] "
span id: song.oid, class: 'song', -> song.song
span class: 'sep'
span class: 'album', -> song.album
span class: 'sep'
span class: 'artist', -> song.artist
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-oid': song.oid
span class: 'shy', ->
span class: 'sep'
span -> otto.t.format_time(song.length)
if song.owners
owner = song.owners[0].owner
else
owner = ''
span class: 'sep'
span class: 'queue owner', -> owner
span class: 'sep'
span class: 'queue filename', -> filename
songs_list = {}
if @data.songs.length
div class: 'section', 'Songs'
ul class: 'songs', ->
for song in @data.songs
songs_list[song._id] = true
li ->
text otto.t.enqueue_widget()
span ".song.id#{song._id}", { 'data-id': song._id }, song.song
span '.album.sep', song.album
span '.artist.sep', song.artist
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': song._id
span class: 'shy', ->
span class: 'sep'
span -> otto.t.format_time(song.length)
owner = ''
if song.owners
owner = song.owners[0].owner
span '.owner.sep', owner
span '.filename.sep', song.filename
other_cleaned = []
if @data.other
for song in @data.other
if songs_list[song._id]
continue
other_cleaned.push(song)
if other_cleaned.length
div 'Other'
ul class: 'my-new-list', ->
for song in other_cleaned
li ->
text otto.t.enqueue_widget()
span ".id#{song._id}", { 'data-id': song._id }, song.song
span '.sep', song.album
span '.sep', song.artist
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': song._id
span '.filename.sep.shy', song.filename
templates.newest_albums = coffeecup.compile ->
div '.search', ->
div '.section', 'Newest Albums'
empty = true
lasttimestamp = false
div '.albums', ->
owner = ''
for album in @data
empty = false
if lasttimestamp
interval = lasttimestamp - album.timestamp
else
interval = 0
lasttimestamp = album.timestamp
if album.owners?
if owner isnt album.owners[-1..][0].owner
owner = album.owners[-1..][0].owner
div '.newestowner', owner + ' ' + otto.t.format_timestamp(album.timestamp)
else if interval > 3600000
div '.newestowner', owner + ' ' + otto.t.format_timestamp(album.timestamp)
else if owner
owner = ''
div '.newestowner', '' + otto.t.format_timestamp(album.timestamp)
else if interval > 3600000
div '.newestowner', owner + ' ' + otto.t.format_timestamp(album.timestamp)
div -> otto.t.album item: album
if empty
div '.none', 'None'
otto.event_last_display_time = false
templates.event = coffeecup.compile ->
div '.event', ->
timestamp = new Date(@event.timestamp)
display_time = otto.t.format_time(timestamp.getHours() * 60 + timestamp.getMinutes(), 5)
if display_time isnt otto.event_last_display_time
span '.timestamp', display_time
otto.event_last_display_time = display_time
else
span '.timestamp', ''
#span class: 'id', -> @event.id
if @event.user
short_username = @event.user.split('@')[0]
span '.user', -> short_username
#span '.channel', -> @event.channel
if @event.message?
if otto.showdown_converter?
message_markeddown = otto.showdown_converter.makeHtml(@event.message)
else
message_markeddown = @event.message
span '.message', message_markeddown
#text message_markeddown
else
span '.name', -> @event.name
templates.event_text = (event) ->
text = ""
if event.user
short_username = event.user.split('@')[0]
else
short_username = 'unknown'
text += short_username + ' '
#text += event.channel
if event.message?
#if otto.showdown_converter?
# message_markeddown = otto.showdown_converter.makeHtml(@event.message)
#else
# message_markeddown = @event.message
#text += message_markeddown
text += event.message
else
text += event.name
templates.loader = coffeecup.compile ->
div class: 'event loader', ->
span class: 'message', "scan: #{@event}"
templates.show_users = coffeecup.compile ->
div '.userlist', ->
empty = true
if @data
table ->
for user in @data
empty = false
tr '.section', ->
td '.owner', user.owner
td if user.songs then "#{user.songs} song" + otto.t.plural(user.songs)
td if user.albums then "#{user.albums} album" + otto.t.plural(user.albums)
td if user.artists then "#{user.artists} artist" + otto.t.plural(user.artists)
td "#{user.stars} starred item" + otto.t.plural(user.stars)
if empty
div '.none', 'None'
templates.show_stars = coffeecup.compile ->
div '.starslist', ->
nostar = true
if @data
for user of @data
starlist = []
for staritem in @data[user]
if staritem.rank > 0
starlist.push staritem
if starlist and starlist.length
nostar = false
div ' '
div '.section', ->
span user
span '.sep', ->
span starlist.length.toString() + ' item' + otto.t.plural(starlist.length)
if otto.myusername
span class: 'shy', -> button class: 'download btn teeny control', 'data-id': user._id, -> i class: 'download-alt'
div '.songs', -> # .songs? that isn't good FIXME
if starlist and starlist.length
for item in starlist
switch item.otype
when 40 then addclass = '.starredartist'
when 20 then addclass = '.starredalbum'
else addclass = '.starredsong'
div '.starreditem'+addclass, ->
if otto.myusername and user is otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': item._id
else
button ".stars.control.teeny.n#{item.rank}.immutable.noupdate", 'data-id': item._id
if item.otype == 40
text otto.t.artist item: item, nostars: true
else if item.otype == 20
text otto.t.album item: item, nostars: true
else
song = item
text otto.t.enqueue_widget()
span ".song.id#{song._id}", { 'data-id': song._id }, song.song
span '.album.sep', song.album
span '.artist.sep', song.artist
span '.sep.shy', otto.t.format_time(song.length)
if song.owners
owner = song.owners[0].owner
span '.owner.sep.shy', owner
span '.filename.sep.shy', song.filename
if nostar
div '.nostars', 'Nothing starred yet'
templates.dirbrowser = coffeecup.compile ->
div '.dirbrowser', ->
ul '.path'
div '.subdirs'
div '.contents'
templates.dirbrowser_subdir = coffeecup.compile ->
ul ->
for dir in @data.dirs
li class: 'subdir', id: dir._id, 'data-filename': dir.filename, ->
dir.filename+'/'
templates.dirbrowser_item = coffeecup.compile ->
for dir in @data
li class: 'path', id: dir._id, -> dir.filename+'/'
templates.ouroboros = coffeecup.compile ->
div '.ouroboros', ->
modifiers = ''
modifiers += '.' + (@size || 'medium') # small, medium, large
modifiers += '.' + (@speed || 'normal') # slow, normal, fast
modifiers += '.' + (@direction || 'cw') # cw, ccw
modifiers += '.' + (@color || 'gray') # gray, blue
modifiers += '.' + (@background || 'dark') # dark, black
div ".ui-spinner#{modifiers}", ->
span '.side.left', ->
span '.fill', ''
span '.side.right', ->
span '.fill', ''
t.format_time = (seconds, minlen=4) ->
hours = parseInt(seconds / 3600)
seconds = seconds % 3600
minutes = parseInt(seconds / 60)
seconds = parseInt(seconds % 60)
if seconds < 10
seconds = '0' + seconds
else
seconds = '' + seconds
if minutes < 10 and (hours > 0 or minlen > 4)
minutes = '0' + minutes
else
minutes = '' + minutes
formatted = ''
if hours or minlen > 6
formatted = "#{hours}:#{minutes}:#{seconds}"
else
formatted = "#{minutes}:#{seconds}"
t.format_timestamp = (timestamp) ->
if timestamp
#d = new Date(timestamp * 1000)
#hours = d.getHours();
#minutes = d.getMinutes();
#seconds = d.getSeconds();
#day = d.getDate()
#month = d.getMonth()
#return moment(timestamp).fromNow() # i like this one
return moment(timestamp).format('ddd MMM Do YYYY ha')
else
return ''
templates.icon = coffeecup.compile ->
switch String @
when 'play' then span '.icon-play2', ''
when 'connect' then span '.icon-play', ''
when 'pause' then span '.icon-pause', ''
#when 'kill' then span '.icon-remove', ''
when 'kill' then span '.icon-minus', ''
when 'menu' then span '.icon-menu', ''
when 'chat' then span '.icon-bubble2', ''
when 'bigger' then span '.icon-zoomin', ''
when 'smaller' then span '.icon-zoomout', ''
when 'newest' then span '.icon-download', ''
when 'all' then span '.icon-grid', ''
when 'star' then span '.icon-star', ''
when 'users' then span '.icon-users', ''
when 'cubes' then span '.icon-stack2', ''
when 'close' then span '.icon-close', ''
when 'enqueue' then span '.icon-plus', ''
when 'unqueue' then span '.icon-minus', ''
when 'logout' then span '.icon-cancel-circle', ''
when 'fork' then span '.icon-fork', ''
when 'tag' then span '.icon-tag', ''
when 'tags' then span '.icon-tags', ''
#when 'output' then span '.icon-volume-medium', ''
when 'output' then span '.icon-volume-mute', ''
when 'outputmute' then span '.icon-volume-mute2', ''
when 'outputsel' then span '.icon-volume-mute', ''
when 'notifications' then span '.icon-bubble3', ''
when 'soundfx' then span '.icon-lightning', ''
when 'folder' then span '.icon-folder-open', ''
when 'info' then span '.icon-info', ''
else span '.icon-blocked', ''
t.plural = (count, single, plural) ->
return if count is 1 then single || '' else plural || 's'
console.log 'templates defined'
return templates
| true | ####
#### client side (body of otto.client.templates.coffee served as /otto.templates.js)
####
# binds to otto.templates (on the client side), not otto.client.templates
# for historical reasons (and brevity)
global.otto.client.templates = ->
$('head').append '<script src="static/js/coffeecup.js">' if not window['coffeecup']?
window.otto = window.otto || {}
window.otto.client = window.otto.client || {}
window.otto.client.templates = true # for otto.load_module's benefit
window.otto.templates = do ->
templates = {}
t = otto.t = templates
ccc = coffeecup.compile
# you can't reference 'templates' or 't' in the compiled functions scope
# (i'm guessing because they are 'eval'ed), use otto.templates instead
add = templates: templates, t: t
t.body_welcome = ccc ->
div '#welcome', otto.t.welcome @
t.body = ccc ->
nav '.channellist-container', ''
div '#mainpage', ''
div '.ouroboros-container', ''
#div '.footer-container', otto.t.footer()
div '.cursor-hider', ''
t.body_reset = ->
$('.channellist-container').empty()
$('#mainpage').empty()
$('.ouroboros-container').empty()
#$('.footer-container').html otto.t.footer()
$('.cursor-hider').empty()
t.welcome = ccc ->
div '.wecome-container', ->
div '.welcome', ->
text otto.t.logo()
div '.greeting', ->
div '.hi', 'hello!'
div '.explain', 'I love to play your music for you, but first I need to scan it'
div '.explain', 'don\'t worry, I won\'t move it or anything like that'
br()
br()
div '.explain', 'I\'ll scan for music in this folder'
div ->
div '.folder', ->
button '.control.medium2.selectfolder', otto.t.icon 'folder'
input '#selectFolder', type: 'file', style: 'display: none' #must match UIDelegate in Otto.py
span '.path', contenteditable: '', @musicroot
div '.explain.note', ->
text '(press '
button '.control.small.selectfolder.', otto.t.icon 'folder'
text ' to change this)'
button '.control.large.wide.loadmusic', 'scan'
div '.footer-container', ''
t.initialload = ccc ->
div '.welcome-container', ->
div '.welcome', ->
text otto.t.logo()
div '.initialload-container', otto.t.cubesloader @
t.cubeswithload = ccc ->
div '.cubeswithload-container', otto.t.cubesloader @
t.cubesloader = ccc ->
div '.loadingstatus', otto.t.loadingstatuses @
div '.loadingprogress', ''
div '.loadingcurrent', ''
div '.loadingcubes-container', ->
div '.loadingcubes', ''
t.loadingstatuses = ccc ->
div '.status.begin', ->
button '.control.large.wide.loadmusic2', 'scan'
div '.status.searching', ->
div '.loadingspinner', ->
div otto.t.ouroboros size: 'medium', direction: 'cw', speed: 'fast'
div '.note', 'searching'
div '.status.loading', ->
div '.loadingspinner', ->
div otto.t.ouroboros size: 'medium', direction: 'cw', speed: 'slow'
div '.note', 'scanning'
div '.status.finished', ->
div ->
text 'all finished! press '
button '.control.small.begin', otto.t.icon 'play'
text ' to begin.'
button '.control.medium2.begin', otto.t.icon 'play'
div '.status.nonefound', ->
div ->
div 'sorry, I was unable to find any music I can play'
br()
if @folder
div 'in folder ' + @folder
else
div 'in that folder'
br()
br()
button '.control.large.wide.restartload', 'restart'
div '.status.error', ->
div ->
text 'sorry, I encountered an error while scanning'
button '.control.large.wide.begin.continue', 'continue'
t.cubes = ccc ->
div '.cubes-container', ->
div '.landscape-right', ''
div '.landscape-left', ''
div '.cubes', ->
div '.scene', ''
#div '.resort.control.medium2', otto.t.icon 'cubes'
t.cubelink = ccc ->
div '.cubelink.'+@rowclass, 'data-id': @id, title: @title, ->
div '.cube', style: @style
t.stacklabel = ccc ->
div '.stacklabel', style: @style, @letter
t.countprogress = ccc ->
if @total or @count
div '.countprogress-binder', ->
s = @total
sizePercent = 100
progressPercent = Math.min((@count / @total * 100), 100)
div '.progress-maximum', ->
div '.progress-container', style: "width: #{sizePercent}%;", ->
div '.progress', ->
div '.progress-indicator', style: "width: #{progressPercent}%;", ''
div '.count-container', otto.t.count_widget(@)
t.logo = ccc ->
div '.logo-container', ->
#span '.logo', ''
a '.logo', href: 'http://ottoaudiojukebox.com/', target: '_blank', ->
t.mainpage = ccc ->
if @channel.layout is 'webcast'
text otto.t.channelbar channel: @channel
text otto.t.console()
text otto.t.webcast()
else if @channel.layout is 'featured'
text otto.t.channelbar channel: @channel
text otto.t.console()
text otto.t.featured()
#else if @channel.layout is 'holidays'
# happy holidays
else
text otto.t.channelbar channel: @channel
text otto.t.login()
text otto.t.playing @
text otto.t.thealbum()
div '.ondeckchattoggle-container', ->
div '.ondeck-container', ''
div '.chattoggle-container', ->
button '.control.medium.chattoggle.shy', {title: 'chat'}, otto.t.icon 'chat'
text otto.t.console()
text otto.t.browse @
#div '.footer-backer', ''
templates.console = coffeecup.compile ->
div '.console-container', tabindex: -1, ->
button '.control.medium.chattoggle.shy', otto.t.icon 'close'
div '.output-container', ->
div '.output.scrollkiller', ''
div '.input-container', ->
div '.inputl', ->
#pre '#prompt', ''
div '#prompt', ''
div '.inputr-container', ->
div '#inputr', -> # must be an id, not class
div '#terminal', ->
#textarea '.input', spellcheck: 'false'
#div '.inputcopy', ''
t.chathelp = ccc ->
div '.chathelp', ->
div '/cls - clear screen'
div '/next - next track'
div '/pause - pause playing'
div '/play - resume playing'
div '/nick <name> - change username'
div '/part - leave chat'
div '/help - show commands'
t.chatunknowncommand = ccc ->
div '.chatunknowncommand', ->
'unknown command ' + @prefix + @command
t.channelbar = ccc ->
console.log 'channelbar', @
div '.channelbar-container.reveal', ->
div '.channelbar', ->
div '.channelbar-left', ->
button '.control.medium.channeltoggle.shy', {title: 'channels'}, otto.t.icon 'menu'
div '.channelbar-center', ->
div '.channelname-container', ->
div '.channelname', @channel.fullname
div '.hostname', ->
#host = @host
#if host and host.indexOf(':') > 0
# host = host.substr(0, host.indexOf ':') || @host
#'http://' + host
r = /^(http:\/\/)?([^\/]*)/.exec(document.URL)
host = if r and r.length is 3 then r[2] else ''
host
text otto.t.logo()
div '.topcontrols-container', ->
#input '#fxtoggle', type: 'checkbox', checked: false
#label '#fx.shy', for: 'fxtoggle', ->
# span 'sound cues'
button '.control.medium2.soundfxtoggle.shy', {title: 'sound cues'}, otto.t.icon 'soundfx'
if Notification?
#input '#notificationstoggle', type: 'checkbox', checked: false
#label '#notifications.shy', for: 'notificationstoggle', ->
# span 'notifications'
button '.control.medium2.notificationstoggle.shy', {title: 'notifications'}, otto.t.icon 'notifications'
div '.channelbar-right', ->
#div '.chattoggle-container', ->
# button '.control.medium.chattoggle.shy', otto.t.icon 'chat'
div '.channelbar-lower', ->
div '.listeners-container', ''
templates.webcast = coffeecup.compile ->
div '#webcast-container', ->
div '#webcast-background', ->
img src: '/static/images/8013980828_82a933115b_k.jpg', title: '', alt: ''
div '#webcast-background-attribution', ->
a '#webcast-background-link', href: 'http://www.flickr.com/photos/joi/8013980828', target: '_blank',
"DJ Aaron by PI:NAME:<NAME>END_PI"
div '#webcast-overlay', ->
div '.autosizeX', 'data-autosize-max': 34, 'data-autosize-min': 19, 'data-autosize-right-margin': 56, ->
otto.autosize_clear_cache()
div ->
span '.webcast-title', "Live Webcast"
#div '#webcast-compatability', ->
# "live broadcast currently works in Chrome and Firefox only"
div '#webcast-chatpointer', ->
"there is a chat button in the upper right"
templates.featuredX = coffeecup.compile ->
div '#archive-container', ->
div '#archive-background', ->
img src: '/static/images/webcast.png', title: '', alt: ''
div '#archive-background-attribution', ->
a '#archive-background-link', href: 'https://www.facebook.com/photo.php?fbid=10150666518958461&set=o.406990045995364&type=1&theater', ->
"photo by [AttributionHere]"
div '#archive-overlay', ->
div '.autosize', 'data-autosize-max': 34, 'data-autosize-min': 19, 'data-autosize-right-margin': 56, ->
otto.autosize_clear_cache()
div ->
span '.archive-title', "Archives"
templates.featured = coffeecup.compile ->
div '#playlist.featured.reveal', ->
t.play_widget = ccc ->
button '#play.control.medium2', {title: 'play/pause'}, otto.t.icon 'play'
t.next_widget = ccc ->
button '#next.control.medium2.shy', {title: 'next'}, otto.t.icon 'kill'
# no longer used
t.lineout_widget = ccc ->
input '#lineouttoggle', type: 'checkbox', checked: false
label '#lineout.shy', for: 'lineouttoggle', ->
span 'server output'
text otto.t.volumelineout_widget
t.volume_widget = ccc ->
div '.volume-container', {title: 'local volume'}, ->
div '.volume', ''
t.volumelineout_widget = ccc ->
div '.volumelineout-container', {title: 'lineout volume'}, ->
div '.volumelineout', ''
t.size_widget = ccc ->
div '.size-widget.shy', ->
button '#size.smaller.control.small', {title: 'smaller'}, otto.t.icon 'smaller'
button '#size.bigger.control.small', {title: 'bigger'}, otto.t.icon 'bigger'
t.currentsong_widget = ccc ->
div '.currenttrack.autosize', {
'data-autosize-max': 34,
'data-autosize-min': 19,
'data-autosize-right-margin': 56 }, ->
otto.autosize_clear_cache()
if @song
span '.gotothere', 'data-id': @song._id, ->
@song.song || 'unknown'
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': @song._id
t.currentalbum_widget = ccc ->
if @song?.album
div '.album.gotothere', 'data-id': @song.albums[0]._id, ->
span @song.album
t.currentyear_widget = ccc ->
span '.year', @song?.year or ''
t.currentartist_widget = ccc ->
if @song?.artist
artist_id = @song.artists[0]?._id or 0
div '.artist.gotothere', 'data-id': artist_id, 'data-albumid': @song.albums[0]._id, ->
# data-albumid is a hack. see artist->fileunder note in gotothere code
@song.artist
t.count_widget = ccc ->
span '#count', ->
if @total or @count
totalstr = "#{@total}"
countstr = "#{@count}"
if countstr.length < totalstr.length
less = totalstr.length - countstr.length
for i in [1..less]
countstr = ' ' + countstr
span '#current-count', countstr
span '#total-count.sep', totalstr
t.time_widget = ccc ->
span '#time', ->
if @total or @current
totalstr = otto.t.format_time @total
currentstr = otto.t.format_time @current, totalstr.length
span '#current-time', currentstr
span '#total-time.sep', totalstr
t.timeprogress_widgets = ccc ->
if @total or @current
div '.timeprogress-binder', ->
s = @total
if s < 10 then s = 10
if s > 3600 then s = 3600
# fun fact: 2397 = 39:57, longest single to reach the UK charts!
#x = s / 2397 * 0.58
#x = s / 3600 * 0.58
x = s / 3600 * 1.718
scale = Math.sqrt( Math.log( x+1 ) )
sizePercent = scale * 100
progressPercent = Math.min((@current / @total * 100), 100)
div '.progress-maximum', {title: 'seek'}, ->
div '.progress-container', style: "width: #{sizePercent}%;", ->
div '.progress', ->
div '.progress-indicator', style: "width: #{progressPercent}%;", ''
div '.time-container', otto.t.time_widget(@)
t.channel_status_errata_widget = ccc ->
div '.time-container', ->
div '.time', ->
if @status.time
times = @status.time.split ':'
text otto.t.time_widget current: times[0], total: times[1]
#div '.audio', @status.audio || ''
div '.bitrate', if @status.bitrate then @status.bitrate + 'kbps' else ''
t.owner_widget = ccc ->
owner = ''
if @song? and @song.owners? and @song.owners[0]? and @song.owners[0].owner?
owner = @song.owners[0].owner
span '.owner', owner
t.requestor_widget = ccc ->
classstr = ''
if @nodecorations
if @song?.requestor
span '.requestor', @song.requestor.split('@')[0]
else
if @song? and @song.owners? and @song.owners[0]? and @song.owners[0].owner?
classstr = '.sep'
if @song?.requestor
span classstr, 'requested by '
span '.requestor', @song.requestor
t.filename_widget = ccc ->
if @song?.filename
span '.filename.shy', @song.filename
t.currentcover_widget = ccc ->
if @song
div '.thumb.px300.gotothere', { 'data-id': @song._id }, ->
if @song.cover
img
height: 300
width: 300
#src: "/image/300?id=#{@song.cover}"
src: "/image/orig?id=#{@song.cover}"
title: @song.album
else
div '.noimg.px300', ->
div @song.album
div '.noimgspacer', ''
div @song.artist
else
div '.thumb.px300', {}, ->
t.enqueue_widget = ccc ->
button '.enqueue.control.teeny.shy', ''
t.unqueue_widget = ccc ->
addtoclassstr = @addtoclassstr || ''
button '.btn.teeny.control.unqueue'+addtoclassstr, ''
t.currenttrack = ccc ->
div '.currenttrack-binder', ->
div '.currentsong-container', otto.t.currentsong_widget(@)
div '.timeprogress-container', otto.t.timeprogress_widgets(@)
div '.currentalbum-container', otto.t.currentalbum_widget(@)
div '.currentyear-container', otto.t.currentyear_widget(@)
div '.currentartist-container', otto.t.currentartist_widget(@)
div '.currenterrata-container', ->
div '.owner-container', otto.t.owner_widget(@)
div '.requestor-container', otto.t.requestor_widget(@)
div '.currentcover-container', otto.t.currentcover_widget(@)
div '.filename-container', ->
div '.filename-clipper', otto.t.filename_widget(@)
t.playing = ccc ->
div '.playing-container.reveal', ->
if otto.haslineout and otto.localhost
div '.play-container', otto.t.play_widget
div '.shy', otto.t.volumelineout_widget
else
#button '#connect.control.large.'+@channel.type, otto.t.icon 'disconnected'
#button '#connect.control.large.'+@channel.type, ->
div '.connect-container', ->
button '#connect.control.large', { title: 'connect/disconnect' }, ->
#img src: 'static/images/disconnected.svg', height: 20, width: 20
text otto.t.icon 'connect'
div '.shy', otto.t.volume_widget
size = @size || 'size1'
div ".size-container.#{size}", otto.t.size_widget
div ".next-container.#{size}", otto.t.next_widget
div ".currenttrack-container.#{size}", otto.t.currenttrack(@)
t.thealbum = ccc ->
div '.thealbum-container.reveal', ->
''
templates.browse = coffeecup.compile ->
div '.browse-container', ->
div '.browsecontrols-container', ->
div '.search-container', ->
form '#searchform.searchform', method:'get', action:'', ->
input '#searchtext.searchtext', type:'text', name:'search', placeholder: 'search', autocorrect: 'off', autocapitalize: 'off'
input '.search_button.buttonless', type:'submit', value:'Search'
div '.letterbar-container', ->
ul '.letterbar', ->
#bigwarning = if @largedatabase then '.warn.big' else '' # bzzz! not passed in FIXME
bigwarning = ''
li '.letter.control.shownewest.gap', {title: 'newest'}, otto.t.icon 'newest'
li '.letter.control.showall.gap'+bigwarning, {title: 'all'}, otto.t.icon 'all'
if not @largedatabase # need to make it faster, times out on very large databases FIXME
li '.letter.control.showusers.gap', {title: 'users'}, otto.t.icon 'users'
li '.letter.control.showstars.gap', {title: 'starred'}, otto.t.icon 'star'
li '.letter.control.showcubes.gap'+bigwarning, {title: 'cubes'}, otto.t.icon 'cubes'
# other fun character considerations: ⁂ ? № ⁕ ⁖ ⁝ ⁞ ⃛ ⋯ +⚂ ⚐ ⚑
# someday add back: st va
li '.letter.gap', 'A'
for letter in 'B C D E F G H I J K L M N O P Q R S T U V W X Y Z # ⋯'.split(' ')
if letter is '#'
li '.letter', {title: 'numbers'}, letter
else if letter is '⋯'
li '.letter', {title: 'other'}, letter
else
li '.letter', letter
#li '.letter.gap.warn.beta', '/'
#li '.letter.showlists.gap', '✓'
div '.browseresults-container', ''
t.footer = ccc ->
div '.logo-container.footer-logo-container', ->
span '.logo.footer-logo', ''
templates.login = coffeecup.compile ->
div '.login-container', ->
div '.login', ->
form '#loginform.loginform', method:'get', action:'', ->
span '.loginlabel', 'To browse and select songs '
# note the homograph unicode cryillic 'a' in 'email' in the placeholder string
# this is to keep safari from prompting for an auto fill. sigh.
input '#logintext.logintext', type:'text', placeholder: 'enter your emаil / username here', autocorrect: 'off', autocapitalize: 'off', autocomplete: 'off', autofill: 'off'
input '.login_button.buttonless', type:'submit', value:'Search'
templates.listeners = coffeecup.compile ->
span '.listeners', ->
count=0
othercount=0
for id in @listeners
if @listeners[id].socketids or @listeners[id].streams
#console.log @listeners[id].channelname
if @listeners[id].channelname and @listeners[id].channelname == otto.mychannel
count++
else
othercount++
if not count
label = 'no listeners'
else
label = count + ' ' + 'listener' + otto.t.plural(count)
span '.count', label
if count
span '.sep', ''
first = true
us = null
for id in @listeners
if @listeners[id].socketids or @listeners[id].streams
for sid of @listeners[id].socketids
if sid is @socketid
us = id
if us and @listeners[us]
text otto.t.format_listener listener: @listeners[us], first: first, me: true
first = false
for id in @listeners
if id is us
continue
if @listeners[id].socketids or @listeners[id].streams
if @listeners[id].channelname and @listeners[id].channelname == otto.mychannel
text otto.t.format_listener listener: @listeners[id], first: first, me: false
first = false
if othercount
label = othercount + ' ' + 'other listener' + otto.t.plural(othercount)
span '', ' | '
span '.count', label
for id in @listeners
if id is us
continue
if @listeners[id].socketids or @listeners[id].streams
if @listeners[id].channelname and @listeners[id].channelname != otto.mychannel
text otto.t.format_listener listener: @listeners[id], first: first, me: false, showchannel: true
first = false
templates.format_listener = coffeecup.compile ->
name = @listener.user || @listener.host || @listener.address
if @shortname
name = name.split('@')[0]
inchat = no
typing = no
focus = no
idle = yes
for id of @listener.socketids
socket = @listener.socketids[id]
if socket
inchat = yes if socket.inchat? and socket.inchat
typing = yes if socket.typing? and socket.typing
focus = yes if socket.focus? and socket.focus
if socket.idle?
idle = no if not socket.idle
if idle
idle = 1
for id of @listener.socketids
socket = @listener.socketids[id]
if socket
idle = socket.idle if socket.idle > idle
classes = ''
classes += '.streaming' if @listener.streams
classes += '.inchat' if inchat
classes += '.typing' if typing
classes += '.idle' if idle or not focus
classes += '.thisisme' if @me
classes += '.sep' if not @first
title = ''
title += 'Streaming' if @listener.streams
if @listener.streams > 1
title += "X#{@listener.streams}"
if inchat
title += ', ' if title != ''
title += 'In chat' if inchat
if typing
title += ', ' if title != ''
title += 'Typing'
if idle or not focus
title += ', ' if title != ''
if idle
minutes = Math.floor( (Date.now() - parseInt(idle)) / (60 * 1000) )
if minutes < 120
title += "Idle for #{minutes} minutes"
else
title += 'Idle since ' + Date(idle).toString()
else
title += 'Window not focused'
if @listener.host || @listener.address # i guess these are not being set? FIXME
title += ', ' if title != ''
title += 'Connected from ' + @listener.host || @listener.address
div '.listener'+classes, title: title, ->
text name
if @showchannel
span '.channel', ' (' + @listener.channelname + ')'
if @me
if @listener.user
span '.thisisme', ->
span '.you', '(you)'
button '.control.small.logout', {title: 'logout'}, otto.t.icon 'logout'
t.format_listeners_for_channel_in_channelbar = ccc ->
span '.listeners', ->
first = true
for id in @listeners
if @listeners[id].socketids or @listeners[id].streams
if @listeners[id].channelname and @listeners[id].channelname == @channelname
text otto.t.format_listener listener: @listeners[id], first: first, me: false, shortname: true
first = false
templates.channellist = coffeecup.compile ->
div '.channellistheader', ->
button '.control.medium.channeltoggle', otto.t.icon 'close'
ul ->
for i in [1..1]
for channel in @channellist
classes = '.changechannel'
classes = classes + '.currentchannel.open' if channel.name is otto.mychannel
li classes, 'data-channelname': channel.name, ->
button '.channelsettings.control.small.shy', {title: 'more info'}, otto.t.icon 'info'
div '.channelselect', ->
div '.channelname.autosize', {
'data-autosize-max': 20,
'data-autosize-min': 12,
'data-autosize-right-margin': 0 }, ->
otto.autosize_clear_cache()
channel.fullname
div '.channellisteners', ->
if @listeners
# if we reactive the count we should consider omitting if it's 1
#span '.listeners.count', count || ''
text otto.t.format_listeners_for_channel_in_channelbar listeners: @listeners, channelname: channel.name
button '.channeloutput.control.small.shy', {title: 'toggle lineout'}, otto.t.icon 'output'
div '.settings', ->
#button '.channelsettings.control.small', otto.t.icon 'close'
button '.channelplay.control.medium2', {title: 'play/pause'}, otto.t.icon 'play'
text otto.t.volumelineout_widget()
div '.channelerrata-container', ''
#button '.channelfork.control.small', {title: 'fork'}, otto.t.icon 'fork'
button '.crossfade.control.small', {title: 'crossfade'}, 'CF'
button '.replaygain.control.small', {title: 'replay gain'}, 'RG'
templates.page_it_out = (items, pagesize, lazychunksize, element, render) ->
pages = 0
pagestart = 0
# someday we should get clever here about not making pages with too few items
# we could also consider waiting to construct pages until they are scrolled to
while pagestart < items.length
pageitems = items.slice(pagestart, pagestart+pagesize)
chunkstart = 0
# further break the page into chunks to make it easier for lazyload searching
element '.page', ->
while chunkstart < pageitems.length
element '.lazychunk', ->
chunk = pageitems.slice(chunkstart, chunkstart+lazychunksize)
for item in chunk
# call the supplied render routine on each item
render item
chunkstart += lazychunksize
pagestart += pagesize
pages += 1
templates.startswith = coffeecup.compile ->
empty = true
otto.t.page_it_out @data, 200, 10, div, (item) ->
empty = false
text otto.t.artist item: item
if empty
div '.none', 'Nothing filed under ' + @params.value
templates.allalbums = coffeecup.compile ->
div '.thumbnails', ->
empty = true
otto.t.page_it_out @data, 300, 100, span, (album) ->
empty = false
div '.albumall', ->
div '.thumb.px120.expand', 'data-id': album._id, ->
if album.cover
img '.albumimg.lazy', height: 120, width: 120, \
#src: 'static/images/gray.gif', \
#src: 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==', \
#src: 'static/images/clear.gif', \
src: 'static/images/clear.png', \
'data-original': "/image/120?id=#{album.cover}", \
title: album.album
else
div '.noimg.px120', -> album.album + '<br>' + album.fileunder[0].name + '<br>' + album.owners[0].owner + '<br>' + album.year #+ album.genre
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': album._id
if empty
div '.none', 'No albums loaded'
templates.artist = coffeecup.compile ->
div '.artistlist', ->
if not @nostars
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': @item._id
div '.artistname-container', ->
span '.artistname.expand', {'data-id': @item._id }, @item.name # was @item.artist before fileunder
ul '.thumbnails', ->
if @item.albums?
albumorder = otto.t.orderalbums @item.albums
for album in albumorder
li '.h.thumb.px40.expand', 'data-id': album._id, 'data-container': @item._id, ->
if album.cover
img '.albumimg.lazy', src: 'static/images/clear.png', height: 40, width: 40, 'data-original': "/image/40?id=#{album.cover}", title: album.album
else
div '.noimg.px40', -> album.album
templates.album = coffeecup.compile ->
expand = if @noexpand then '' else '.expand'
div '.albumlist', ->
div '.thumbnails', ->
div '.thumb.px40'+expand, 'data-id': @item._id, 'data-container': @item._id, ->
if @item.cover
if @nolazy
img '.albumimg', src: "/image/40?id=#{@item.cover}", height: 40, width: 40, title: @item.album
else
img '.albumimg.lazy', src: 'static/images/clear.png', height: 40, width: 40, 'data-original': "/image/40?id=#{@item.cover}", title: @item.album
else
div '.noimg.px40', -> @item.album
span '.albumname'+expand, 'data-id': @item._id, ->
artistinfo = otto.compute_artistinfo @item
span @item.album
if artistinfo.single
span '.artist.sep', artistinfo.single
if @item.year?
span '.sep', @item.year
if otto.myusername and not @nostars
button '.stars.control.teeny.shy.n0', 'data-id': @item._id
templates.orderalbums = (albums) ->
albumorder = []
variousorder = []
for album in albums
if not album.artistinfo?
album.artistinfo = otto.compute_artistinfo album
if album.artistinfo.various
variousorder.push album
else
albumorder.push album
sorter = (a, b) ->
#if a.songs?[0]?.year? and b.songs?[0].year?
if a.year? and b.year?
ayear = Number(a.year)
byear = Number(b.year)
if ayear < byear
return -1
else if ayear > byear
return 1
else
if a.album? and b.album?
return a.album.localeCompare b.album, {sensitivity: "base", numeric: true}
else if a.album?
return -1
else if b.album?
return 1
else return 0
else if a.year?
return -1
else if b.year?
return 1
else
if a.album? and b.album?
return a.album.localeCompare b.album, {sensitivity: "base", numeric: true}
else if a.album?
return -1
else if b.album?
return 1
else return 0
albumorder.sort(sorter)
variousorder.sort(sorter)
return albumorder.concat(variousorder)
templates.albums_details = coffeecup.compile ->
div '.albumlist-container', { 'data-id': @_id }, ->
button '.close.control.tiny.shy', otto.t.icon 'close'
#if @data.length > 1
button '.close.lower.control.tiny.shy', otto.t.icon 'close'
div '.albumlist', ->
albumorder = otto.t.orderalbums @data
had_various = false
had_nonvarious = false
for album in albumorder
if album.artistinfo.various
if had_nonvarious and not had_various
div '.varioussep', ''
had_various = true
else
had_nonvarious = true
text otto.t.album_details album: album, fileunder: @fileunder
templates.album_details = coffeecup.compile ->
if not @album.artistinfo?
@album.artistinfo = otto.compute_artistinfo @album
div '.albumdetails', ->
div '.albumcover-container', ->
if @album.cover
div '.thumb.px200', ->
#img src: "/image/300?id=#{@album.cover}", alt: @album.album, title: @album.album
img src: "/image/orig?id=#{@album.cover}", alt: @album.album, title: @album.album
else
div '.noimg.px200', ->
if @album.artistinfo.various
span @album.artistinfo.various
else
for artist in @album.artistinfo.all
span -> artist
br()
span @album.album
div '.stars-container', ->
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': @album._id
div '.year-container', ->
if @album.years?
format_years = @album.years[0]
for year in @album.years[1..]
format_years += ', '+year
div '.year', format_years
else if @album.year?
div '.year', @album.year
div '.albuminfo', ->
div '.album', ->
span ".id#{@album._id}", 'data-id': @album._id, ->
span @album.album
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': @album._id
if @album.artistinfo.various
div '.artist', @album.artistinfo.various
else
for artist in @album.artistinfo.all
div '.artist', -> artist
if @album.owners?[0]?.owner
div '.owner', -> @album.owners[0].owner
div '.albumsongs.cf', ->
table ->
for song in @album.songs
tr -> td ->
text otto.t.enqueue_widget()
span ".id#{song._id}", {'data-id': song._id}, song.song
if @album.artistinfo.various or song.artist is not @album.artistinfo.primary
# this doesn't work when the fileunder name has been transformed in any way FIXME
if @album.artistinfo.various and @fileunder and song.artist is @fileunder.name
span '.subartist.highlight.sepgray', song.artist
else
span '.subartist.sep', song.artist
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': song._id
#button '.stars.control.teeny.shy.n0', {'data-id': song._id}, otto.t.icon 'star'
span '.time.sep.shy', otto.t.format_time(song.length)
div '.albumdir.dirpath.shy', ->
@album.dirpath
templates.ondeck = coffeecup.compile ->
table '.ondeck', ->
# the rest of the queue, on deck
for song in @songs
tr ->
td '.requestor-container', otto.t.requestor_widget( song: song, nodecorations: true )
td ->
text otto.t.unqueue_widget( addtoclassstr: '.shy' )
addtoclassstr = ''
if song.requestor
addtoclassstr='.requested'
span ".song.id#{song._id}#{addtoclassstr}", { 'data-id': song._id, 'data-mpdqueueid': song.mpdqueueid }, song.song
span '.album.sep', song.album
span '.artist.sep', song.artist
span '.sep', otto.t.format_time(song.length)
span '.shy', ->
if song.owners
owner = song.owners[0].owner
else
owner = ''
span '.owner.sep', -> owner
span '.filename.sep', -> song.filename
templates.featured = coffeecup.compile ->
ul '.ondeck', ->
# the rest of the queue, on deck
for song, n in @songs
li ->
if song.requestor
span '.requestor', ->
div -> song.requestor
else
span '.requestor', -> ''
if song.nowplaying
span '.playing.control.teeny', otto.t.icon 'play'
span '.song.currenttrack', -> song.song
else
button '.play.control.teeny.shy', id: song.mpdqueueid, 'data-position': n, ->
text otto.t.icon 'play'
span '.song', song.song
span '.album.sep', song.album
span '.artist.sep', song.artist
span '.sep', otto.t.format_time(song.length)
span '.shy', ->
if song.owners
owner = song.owners[0].owner
else
owner = ''
span '.owner.sep', -> owner
span '.filename.sep', -> song.filename
templates.alert = coffeecup.compile ->
div class: 'alert alert-info', ->
span @message
br()
br()
button '#ok.runself.control.large', 'ok'
text ' '
button '#cancel.runself.control.large', 'cancel'
templates.search = coffeecup.compile ->
div '.search', ->
if not @data.fileunders.length and not @data.albums.length and not @data.songs.length
div class: 'noresults'
else
if @data.fileunders.length
div class: 'section', 'Artists'
div ->
for fileunder in @data.fileunders
#li -> fileunder.name
div -> otto.t.artist item: fileunder
if @data.albums.length
div class: 'section', 'Albums'
div class: 'albums', ->
for album in @data.albums
div -> otto.t.album item: album
if @data.songcomposers? and @data.songcomposers.length
div '.section', 'Composers'
ul class: 'songs', ->
for song in @data.songcomposers
filename = song.filename
li ->
button '.enqueue.control.teeny.shy', 'data-oid': song.oid
composers = ''
if song.tags['©wrt']
composers = song.tags['©wrt']
composers = composers.replace /^\[u\'/, ''
composers = composers.replace /\'\]$/, ''
if song.tags['TCOM']
if composers
composers = composers + ', '
composers = song.tags['TCOM']
span "[#{composers}] "
span id: song.oid, class: 'song', -> song.song
span class: 'sep'
span class: 'album', -> song.album
span class: 'sep'
span class: 'artist', -> song.artist
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-oid': song.oid
span class: 'shy', ->
span class: 'sep'
span -> otto.t.format_time(song.length)
if song.owners
owner = song.owners[0].owner
else
owner = ''
span class: 'sep'
span class: 'queue owner', -> owner
span class: 'sep'
span class: 'queue filename', -> filename
songs_list = {}
if @data.songs.length
div class: 'section', 'Songs'
ul class: 'songs', ->
for song in @data.songs
songs_list[song._id] = true
li ->
text otto.t.enqueue_widget()
span ".song.id#{song._id}", { 'data-id': song._id }, song.song
span '.album.sep', song.album
span '.artist.sep', song.artist
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': song._id
span class: 'shy', ->
span class: 'sep'
span -> otto.t.format_time(song.length)
owner = ''
if song.owners
owner = song.owners[0].owner
span '.owner.sep', owner
span '.filename.sep', song.filename
other_cleaned = []
if @data.other
for song in @data.other
if songs_list[song._id]
continue
other_cleaned.push(song)
if other_cleaned.length
div 'Other'
ul class: 'my-new-list', ->
for song in other_cleaned
li ->
text otto.t.enqueue_widget()
span ".id#{song._id}", { 'data-id': song._id }, song.song
span '.sep', song.album
span '.sep', song.artist
if otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': song._id
span '.filename.sep.shy', song.filename
templates.newest_albums = coffeecup.compile ->
div '.search', ->
div '.section', 'Newest Albums'
empty = true
lasttimestamp = false
div '.albums', ->
owner = ''
for album in @data
empty = false
if lasttimestamp
interval = lasttimestamp - album.timestamp
else
interval = 0
lasttimestamp = album.timestamp
if album.owners?
if owner isnt album.owners[-1..][0].owner
owner = album.owners[-1..][0].owner
div '.newestowner', owner + ' ' + otto.t.format_timestamp(album.timestamp)
else if interval > 3600000
div '.newestowner', owner + ' ' + otto.t.format_timestamp(album.timestamp)
else if owner
owner = ''
div '.newestowner', '' + otto.t.format_timestamp(album.timestamp)
else if interval > 3600000
div '.newestowner', owner + ' ' + otto.t.format_timestamp(album.timestamp)
div -> otto.t.album item: album
if empty
div '.none', 'None'
otto.event_last_display_time = false
templates.event = coffeecup.compile ->
div '.event', ->
timestamp = new Date(@event.timestamp)
display_time = otto.t.format_time(timestamp.getHours() * 60 + timestamp.getMinutes(), 5)
if display_time isnt otto.event_last_display_time
span '.timestamp', display_time
otto.event_last_display_time = display_time
else
span '.timestamp', ''
#span class: 'id', -> @event.id
if @event.user
short_username = @event.user.split('@')[0]
span '.user', -> short_username
#span '.channel', -> @event.channel
if @event.message?
if otto.showdown_converter?
message_markeddown = otto.showdown_converter.makeHtml(@event.message)
else
message_markeddown = @event.message
span '.message', message_markeddown
#text message_markeddown
else
span '.name', -> @event.name
templates.event_text = (event) ->
text = ""
if event.user
short_username = event.user.split('@')[0]
else
short_username = 'unknown'
text += short_username + ' '
#text += event.channel
if event.message?
#if otto.showdown_converter?
# message_markeddown = otto.showdown_converter.makeHtml(@event.message)
#else
# message_markeddown = @event.message
#text += message_markeddown
text += event.message
else
text += event.name
templates.loader = coffeecup.compile ->
div class: 'event loader', ->
span class: 'message', "scan: #{@event}"
templates.show_users = coffeecup.compile ->
div '.userlist', ->
empty = true
if @data
table ->
for user in @data
empty = false
tr '.section', ->
td '.owner', user.owner
td if user.songs then "#{user.songs} song" + otto.t.plural(user.songs)
td if user.albums then "#{user.albums} album" + otto.t.plural(user.albums)
td if user.artists then "#{user.artists} artist" + otto.t.plural(user.artists)
td "#{user.stars} starred item" + otto.t.plural(user.stars)
if empty
div '.none', 'None'
templates.show_stars = coffeecup.compile ->
div '.starslist', ->
nostar = true
if @data
for user of @data
starlist = []
for staritem in @data[user]
if staritem.rank > 0
starlist.push staritem
if starlist and starlist.length
nostar = false
div ' '
div '.section', ->
span user
span '.sep', ->
span starlist.length.toString() + ' item' + otto.t.plural(starlist.length)
if otto.myusername
span class: 'shy', -> button class: 'download btn teeny control', 'data-id': user._id, -> i class: 'download-alt'
div '.songs', -> # .songs? that isn't good FIXME
if starlist and starlist.length
for item in starlist
switch item.otype
when 40 then addclass = '.starredartist'
when 20 then addclass = '.starredalbum'
else addclass = '.starredsong'
div '.starreditem'+addclass, ->
if otto.myusername and user is otto.myusername
button '.stars.control.teeny.shy.n0', 'data-id': item._id
else
button ".stars.control.teeny.n#{item.rank}.immutable.noupdate", 'data-id': item._id
if item.otype == 40
text otto.t.artist item: item, nostars: true
else if item.otype == 20
text otto.t.album item: item, nostars: true
else
song = item
text otto.t.enqueue_widget()
span ".song.id#{song._id}", { 'data-id': song._id }, song.song
span '.album.sep', song.album
span '.artist.sep', song.artist
span '.sep.shy', otto.t.format_time(song.length)
if song.owners
owner = song.owners[0].owner
span '.owner.sep.shy', owner
span '.filename.sep.shy', song.filename
if nostar
div '.nostars', 'Nothing starred yet'
templates.dirbrowser = coffeecup.compile ->
div '.dirbrowser', ->
ul '.path'
div '.subdirs'
div '.contents'
templates.dirbrowser_subdir = coffeecup.compile ->
ul ->
for dir in @data.dirs
li class: 'subdir', id: dir._id, 'data-filename': dir.filename, ->
dir.filename+'/'
templates.dirbrowser_item = coffeecup.compile ->
for dir in @data
li class: 'path', id: dir._id, -> dir.filename+'/'
templates.ouroboros = coffeecup.compile ->
div '.ouroboros', ->
modifiers = ''
modifiers += '.' + (@size || 'medium') # small, medium, large
modifiers += '.' + (@speed || 'normal') # slow, normal, fast
modifiers += '.' + (@direction || 'cw') # cw, ccw
modifiers += '.' + (@color || 'gray') # gray, blue
modifiers += '.' + (@background || 'dark') # dark, black
div ".ui-spinner#{modifiers}", ->
span '.side.left', ->
span '.fill', ''
span '.side.right', ->
span '.fill', ''
t.format_time = (seconds, minlen=4) ->
hours = parseInt(seconds / 3600)
seconds = seconds % 3600
minutes = parseInt(seconds / 60)
seconds = parseInt(seconds % 60)
if seconds < 10
seconds = '0' + seconds
else
seconds = '' + seconds
if minutes < 10 and (hours > 0 or minlen > 4)
minutes = '0' + minutes
else
minutes = '' + minutes
formatted = ''
if hours or minlen > 6
formatted = "#{hours}:#{minutes}:#{seconds}"
else
formatted = "#{minutes}:#{seconds}"
t.format_timestamp = (timestamp) ->
if timestamp
#d = new Date(timestamp * 1000)
#hours = d.getHours();
#minutes = d.getMinutes();
#seconds = d.getSeconds();
#day = d.getDate()
#month = d.getMonth()
#return moment(timestamp).fromNow() # i like this one
return moment(timestamp).format('ddd MMM Do YYYY ha')
else
return ''
templates.icon = coffeecup.compile ->
switch String @
when 'play' then span '.icon-play2', ''
when 'connect' then span '.icon-play', ''
when 'pause' then span '.icon-pause', ''
#when 'kill' then span '.icon-remove', ''
when 'kill' then span '.icon-minus', ''
when 'menu' then span '.icon-menu', ''
when 'chat' then span '.icon-bubble2', ''
when 'bigger' then span '.icon-zoomin', ''
when 'smaller' then span '.icon-zoomout', ''
when 'newest' then span '.icon-download', ''
when 'all' then span '.icon-grid', ''
when 'star' then span '.icon-star', ''
when 'users' then span '.icon-users', ''
when 'cubes' then span '.icon-stack2', ''
when 'close' then span '.icon-close', ''
when 'enqueue' then span '.icon-plus', ''
when 'unqueue' then span '.icon-minus', ''
when 'logout' then span '.icon-cancel-circle', ''
when 'fork' then span '.icon-fork', ''
when 'tag' then span '.icon-tag', ''
when 'tags' then span '.icon-tags', ''
#when 'output' then span '.icon-volume-medium', ''
when 'output' then span '.icon-volume-mute', ''
when 'outputmute' then span '.icon-volume-mute2', ''
when 'outputsel' then span '.icon-volume-mute', ''
when 'notifications' then span '.icon-bubble3', ''
when 'soundfx' then span '.icon-lightning', ''
when 'folder' then span '.icon-folder-open', ''
when 'info' then span '.icon-info', ''
else span '.icon-blocked', ''
t.plural = (count, single, plural) ->
return if count is 1 then single || '' else plural || 's'
console.log 'templates defined'
return templates
|
[
{
"context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje",
"end": 22,
"score": 0.9874122142791748,
"start": 16,
"tag": "NAME",
"value": "Konode"
}
] | src/clientFilePage/planTab/planSection.coffee | LogicalOutcomes/KoNote | 1 | # Copyright (c) Konode. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Plan section view, which is draggable
Imm = require 'immutable'
Decorate = require 'es-decorate'
Term = require '../../term'
load = (win) ->
React = win.React
R = React.DOM
{findDOMNode} = win.ReactDOM
{DragSource, DropTarget} = win.ReactDnD
Bootbox = win.bootbox
PlanTarget = require('./planTarget').load(win)
InactiveToggleWrapper = require('./inactiveToggleWrapper').load(win)
StatusButtonGroup = require('./statusButtonGroup').load(win)
ModifySectionStatusDialog = require('../modifySectionStatusDialog').load(win)
OpenDialogLink = require('../../openDialogLink').load(win)
WithTooltip = require('../../withTooltip').load(win)
CreatePlanTemplateDialog = require('../createPlanTemplateDialog').load(win)
ColorKeyBubble = require('../../colorKeyBubble').load(win)
{FaIcon, showWhen} = require('../../utils').load(win)
PlanSection = React.createClass
displayName: 'PlanSection'
mixins: [React.addons.PureRenderMixin]
propTypes: {
# DnD
connectDragSource: React.PropTypes.func.isRequired
connectDragPreview: React.PropTypes.func.isRequired
connectDropTarget: React.PropTypes.func.isRequired
isDragging: React.PropTypes.bool.isRequired
# DnD props
index: React.PropTypes.number.isRequired
id: React.PropTypes.any.isRequired
# Raw data
section: React.PropTypes.instanceOf(Imm.Map).isRequired
# Methods
reorderSection: React.PropTypes.func.isRequired
reorderTargetId: React.PropTypes.func.isRequired
}
getInitialState: -> {
displayDeactivatedTargets: null
displayCompletedTargets: null
isReorderHovered: false
}
render: ->
{
section
program
clientFile
plan
metricsById
currentTargetRevisionsById
planTargetsById
selectedTargetId
isReadOnly
isCollapsed
renameSection
addTargetToSection
hasTargetChanged
updateTarget
removeNewTarget
removeNewSection
onRemoveNewSection
setSelectedTarget
addMetricToTarget
deleteMetricFromTarget
getSectionIndex
expandTarget
expandSection
reorderSection
reorderTargetId
connectDragSource
connectDropTarget
connectDragPreview
isDragging
} = @props
{id, status} = section.toObject()
sectionIsInactive = status isnt 'default'
sectionIndex = @props.index
# Build targets by status, and order them manually into an array
# TODO: Make this an ordered set or something...
targetsByStatus = section.get('targetIds')
.map (id) -> currentTargetRevisionsById.get(id)
.groupBy (t) -> t.get('status')
targetsByStatusArray = Imm.List(['default', 'completed', 'deactivated']).map (status) ->
targetsByStatus.get(status)
return connectDropTarget connectDragPreview (
R.section({
id: "section-#{id}"
className: [
'planSection'
"status-#{status}"
'isCollapsed' if isCollapsed
'isDragging' if isDragging
'isReorderHovered' if @state.isReorderHovered
].join ' '
},
SectionHeader({
clientFile
section
program
isReadOnly
isCollapsed
allTargetsAreInactive: not targetsByStatus.get('default')
renameSection
getSectionIndex
addTargetToSection
onRemoveNewSection
sectionIsInactive
currentTargetRevisionsById
connectDragSource
expandSection
onReorderHover: @_onReorderHover
})
(if section.get('targetIds').size is 0
R.div({className: 'noTargets'},
"This #{Term 'section'} is empty."
)
)
(targetsByStatusArray.map (targets) =>
# TODO: Remove this in favour of [key, value] (prev. TODO)
return if not targets
status = targets.getIn [0, 'status']
size = targets.size
# Build the list of targets
PlanTargetsList = R.div({className: 'planTargetsList'},
(targets.map (target) =>
targetId = target.get('id')
index = section.get('targetIds').indexOf targetId
hasChanges = hasTargetChanged(targetId)
isSelected = targetId is selectedTargetId
isExistingTarget = planTargetsById.has(targetId)
PlanTarget({
key: targetId
target
metricsById
hasChanges
isSelected
isExistingTarget
isReadOnly
isCollapsed
sectionIsInactive
onRemoveNewTarget: removeNewTarget.bind null, id, targetId
onTargetUpdate: updateTarget.bind null, targetId
onTargetSelection: setSelectedTarget.bind null, targetId
setSelectedTarget # allows for setState cb
onExpandTarget: expandTarget.bind null, targetId
addMetricToTarget
deleteMetricFromTarget
reorderTargetId
section
sectionIndex
index
activeTabId: @props.activeTabId
})
)
)
# Return wrapped inactive target groups for display toggling
R.div({key: status},
switch status
when 'default'
PlanTargetsList
when 'deactivated'
InactiveToggleWrapper({
children: PlanTargetsList
dataType: 'target'
status, size
isExpanded: @state.displayDeactivatedTargets
onToggle: @_toggleDisplayDeactivatedTargets
})
when 'completed'
InactiveToggleWrapper({
children: PlanTargetsList
dataType: 'target'
status, size
isExpanded: @state.displayCompletedTargets
onToggle: @_toggleDisplayCompletedTargets
})
)
)
)
)
_toggleDisplayCompletedTargets: ->
displayCompletedTargets = not @state.displayCompletedTargets
@setState {displayCompletedTargets}
_toggleDisplayDeactivatedTargets: ->
displayDeactivatedTargets = not @state.displayDeactivatedTargets
@setState {displayDeactivatedTargets}
_onReorderHover: (isReorderHovered) -> @setState {isReorderHovered}
SectionHeader = React.createFactory React.createClass
displayName: 'SectionHeader'
mixins: [React.addons.PureRenderMixin]
render: ->
{
clientFile
section
program
isReadOnly
isCollapsed
allTargetsAreInactive
renameSection
getSectionIndex
addTargetToSection
removeNewSection
onRemoveNewSection
currentTargetRevisionsById
sectionIsInactive
connectDragSource
expandSection
onReorderHover
} = @props
sectionStatus = section.get('status')
sectionId = section.get('id')
# Figure out whether already exists in plan
isExistingSection = clientFile.getIn(['plan','sections']).some (obj) =>
obj.get('id') is section.get('id')
canSetStatus = isExistingSection and not isReadOnly
canModify = not isReadOnly and not sectionIsInactive
isAdmin = global.ActiveSession.isAdmin()
hasValidTargets = currentTargetRevisionsById.every((target) => target.get('name'));
return R.div({className: 'sectionHeader'},
connectDragSource (
R.div({
className: 'dragSource'
onMouseOver: => onReorderHover(true)
onMouseLeave: => onReorderHover(false)
},
FaIcon('arrows-v')
)
)
R.div({
title: "Edit name"
className: 'sectionName'
},
R.span({
onClick: ->
if isCollapsed
expandSection(sectionId)
else if canModify
renameSection(sectionId)
},
section.get('name')
(if program
ColorKeyBubble({
colorKeyHex: program.get('colorKeyHex')
popover: {
title: program.get('name')
content: program.get('description')
placement: 'top'
}
})
)
(if canModify and not isCollapsed
FaIcon('pencil', {className: 'renameIcon'})
)
)
)
(if canSetStatus and isAdmin
StatusButtonGroup({
planElementType: Term 'Section'
data: section
parentData: clientFile
isExisting: isExistingSection
status: sectionStatus
dangerMessage: (
if allTargetsAreInactive or sectionStatus isnt 'default'
null
else
"Careful: this #{Term 'section'} still has #{Term 'targets'} " +
"that have not been deactivated or marked complete."
)
onRemove: onRemoveNewSection
dialog: ModifySectionStatusDialog
isDisabled: isReadOnly
})
)
# TODO: Extract to component
(if not sectionIsInactive and isAdmin
R.div({className: 'btn-group btn-group-sm sectionButtons'},
R.button({
ref: 'addTarget'
className: 'addTarget btn btn-primary'
onClick: addTargetToSection.bind null, section.get('id')
disabled: not canModify
},
FaIcon('plus')
" Add #{Term 'Target'}"
)
WithTooltip({
title: "Create #{Term 'Section'} #{Term 'Template'}"
placement: 'top'
container: 'body'
},
if hasValidTargets then OpenDialogLink({
className: 'btn btn-default'
dialog: CreatePlanTemplateDialog
title: "Create #{Term 'Template'} from #{Term 'Section'}"
sections: Imm.List([section])
currentTargetRevisionsById
disabled: isReadOnly
},
FaIcon 'wpforms'
)
else R.div({
className: 'btn btn-default',
onClick: () => Bootbox.alert {
title: "Oops! One or more #{Term 'target'} are missing a name"
message: "All #{Term 'targets'} in a new #{Term 'section'} #{Term 'template'} must have a name. Please fix any empty #{Term 'target'} names, and try again."
}
}, FaIcon 'wpforms')
)
)
)
)
# Drag source contract
sectionSource = {
beginDrag: ({id, index}) -> {id, index}
}
sectionDestination = {
hover: (props, monitor, component) ->
dragIndex = monitor.getItem().index
hoverIndex = props.index
# Don't replace items with themselves
return if dragIndex is hoverIndex
# Determine rectangle on screen
hoverBoundingRect = findDOMNode(component).getBoundingClientRect()
# Get vertical middle
hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2
# Determine mouse position
clientOffset = monitor.getClientOffset()
# Get pixels to the top
hoverClientY = clientOffset.y - hoverBoundingRect.top
# Only perform the move when the mouse has crossed half of the item's height
# When dragging downwards, only move when the cursor is below 50%
# When dragging upwards, only move when the cursor is above 50%
# Dragging downwards
return if dragIndex < hoverIndex and hoverClientY < hoverMiddleY
# Dragging upwards
return if dragIndex > hoverIndex and hoverClientY > hoverMiddleY
# Time to actually perform the action
props.reorderSection(dragIndex, hoverIndex)
# (Example says to mutate here, but we're using Imm data)
monitor.getItem().index = hoverIndex;
}
# Specify props to inject into component
collectSource = (connect, monitor) -> {
connectDragSource: connect.dragSource()
connectDragPreview: connect.dragPreview()
isDragging: monitor.isDragging()
}
connectDestination = (connect) -> {
connectDropTarget: connect.dropTarget()
}
# Decorate/Wrap PlanSection with DragDropContext, DropTarget, and DragSource
return React.createFactory Decorate [
DropTarget('section', sectionDestination, connectDestination)
DragSource('section', sectionSource, collectSource)
], PlanSection
module.exports = {load}
| 49612 | # Copyright (c) <NAME>. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Plan section view, which is draggable
Imm = require 'immutable'
Decorate = require 'es-decorate'
Term = require '../../term'
load = (win) ->
React = win.React
R = React.DOM
{findDOMNode} = win.ReactDOM
{DragSource, DropTarget} = win.ReactDnD
Bootbox = win.bootbox
PlanTarget = require('./planTarget').load(win)
InactiveToggleWrapper = require('./inactiveToggleWrapper').load(win)
StatusButtonGroup = require('./statusButtonGroup').load(win)
ModifySectionStatusDialog = require('../modifySectionStatusDialog').load(win)
OpenDialogLink = require('../../openDialogLink').load(win)
WithTooltip = require('../../withTooltip').load(win)
CreatePlanTemplateDialog = require('../createPlanTemplateDialog').load(win)
ColorKeyBubble = require('../../colorKeyBubble').load(win)
{FaIcon, showWhen} = require('../../utils').load(win)
PlanSection = React.createClass
displayName: 'PlanSection'
mixins: [React.addons.PureRenderMixin]
propTypes: {
# DnD
connectDragSource: React.PropTypes.func.isRequired
connectDragPreview: React.PropTypes.func.isRequired
connectDropTarget: React.PropTypes.func.isRequired
isDragging: React.PropTypes.bool.isRequired
# DnD props
index: React.PropTypes.number.isRequired
id: React.PropTypes.any.isRequired
# Raw data
section: React.PropTypes.instanceOf(Imm.Map).isRequired
# Methods
reorderSection: React.PropTypes.func.isRequired
reorderTargetId: React.PropTypes.func.isRequired
}
getInitialState: -> {
displayDeactivatedTargets: null
displayCompletedTargets: null
isReorderHovered: false
}
render: ->
{
section
program
clientFile
plan
metricsById
currentTargetRevisionsById
planTargetsById
selectedTargetId
isReadOnly
isCollapsed
renameSection
addTargetToSection
hasTargetChanged
updateTarget
removeNewTarget
removeNewSection
onRemoveNewSection
setSelectedTarget
addMetricToTarget
deleteMetricFromTarget
getSectionIndex
expandTarget
expandSection
reorderSection
reorderTargetId
connectDragSource
connectDropTarget
connectDragPreview
isDragging
} = @props
{id, status} = section.toObject()
sectionIsInactive = status isnt 'default'
sectionIndex = @props.index
# Build targets by status, and order them manually into an array
# TODO: Make this an ordered set or something...
targetsByStatus = section.get('targetIds')
.map (id) -> currentTargetRevisionsById.get(id)
.groupBy (t) -> t.get('status')
targetsByStatusArray = Imm.List(['default', 'completed', 'deactivated']).map (status) ->
targetsByStatus.get(status)
return connectDropTarget connectDragPreview (
R.section({
id: "section-#{id}"
className: [
'planSection'
"status-#{status}"
'isCollapsed' if isCollapsed
'isDragging' if isDragging
'isReorderHovered' if @state.isReorderHovered
].join ' '
},
SectionHeader({
clientFile
section
program
isReadOnly
isCollapsed
allTargetsAreInactive: not targetsByStatus.get('default')
renameSection
getSectionIndex
addTargetToSection
onRemoveNewSection
sectionIsInactive
currentTargetRevisionsById
connectDragSource
expandSection
onReorderHover: @_onReorderHover
})
(if section.get('targetIds').size is 0
R.div({className: 'noTargets'},
"This #{Term 'section'} is empty."
)
)
(targetsByStatusArray.map (targets) =>
# TODO: Remove this in favour of [key, value] (prev. TODO)
return if not targets
status = targets.getIn [0, 'status']
size = targets.size
# Build the list of targets
PlanTargetsList = R.div({className: 'planTargetsList'},
(targets.map (target) =>
targetId = target.get('id')
index = section.get('targetIds').indexOf targetId
hasChanges = hasTargetChanged(targetId)
isSelected = targetId is selectedTargetId
isExistingTarget = planTargetsById.has(targetId)
PlanTarget({
key: targetId
target
metricsById
hasChanges
isSelected
isExistingTarget
isReadOnly
isCollapsed
sectionIsInactive
onRemoveNewTarget: removeNewTarget.bind null, id, targetId
onTargetUpdate: updateTarget.bind null, targetId
onTargetSelection: setSelectedTarget.bind null, targetId
setSelectedTarget # allows for setState cb
onExpandTarget: expandTarget.bind null, targetId
addMetricToTarget
deleteMetricFromTarget
reorderTargetId
section
sectionIndex
index
activeTabId: @props.activeTabId
})
)
)
# Return wrapped inactive target groups for display toggling
R.div({key: status},
switch status
when 'default'
PlanTargetsList
when 'deactivated'
InactiveToggleWrapper({
children: PlanTargetsList
dataType: 'target'
status, size
isExpanded: @state.displayDeactivatedTargets
onToggle: @_toggleDisplayDeactivatedTargets
})
when 'completed'
InactiveToggleWrapper({
children: PlanTargetsList
dataType: 'target'
status, size
isExpanded: @state.displayCompletedTargets
onToggle: @_toggleDisplayCompletedTargets
})
)
)
)
)
_toggleDisplayCompletedTargets: ->
displayCompletedTargets = not @state.displayCompletedTargets
@setState {displayCompletedTargets}
_toggleDisplayDeactivatedTargets: ->
displayDeactivatedTargets = not @state.displayDeactivatedTargets
@setState {displayDeactivatedTargets}
_onReorderHover: (isReorderHovered) -> @setState {isReorderHovered}
SectionHeader = React.createFactory React.createClass
displayName: 'SectionHeader'
mixins: [React.addons.PureRenderMixin]
render: ->
{
clientFile
section
program
isReadOnly
isCollapsed
allTargetsAreInactive
renameSection
getSectionIndex
addTargetToSection
removeNewSection
onRemoveNewSection
currentTargetRevisionsById
sectionIsInactive
connectDragSource
expandSection
onReorderHover
} = @props
sectionStatus = section.get('status')
sectionId = section.get('id')
# Figure out whether already exists in plan
isExistingSection = clientFile.getIn(['plan','sections']).some (obj) =>
obj.get('id') is section.get('id')
canSetStatus = isExistingSection and not isReadOnly
canModify = not isReadOnly and not sectionIsInactive
isAdmin = global.ActiveSession.isAdmin()
hasValidTargets = currentTargetRevisionsById.every((target) => target.get('name'));
return R.div({className: 'sectionHeader'},
connectDragSource (
R.div({
className: 'dragSource'
onMouseOver: => onReorderHover(true)
onMouseLeave: => onReorderHover(false)
},
FaIcon('arrows-v')
)
)
R.div({
title: "Edit name"
className: 'sectionName'
},
R.span({
onClick: ->
if isCollapsed
expandSection(sectionId)
else if canModify
renameSection(sectionId)
},
section.get('name')
(if program
ColorKeyBubble({
colorKeyHex: program.get('colorKeyHex')
popover: {
title: program.get('name')
content: program.get('description')
placement: 'top'
}
})
)
(if canModify and not isCollapsed
FaIcon('pencil', {className: 'renameIcon'})
)
)
)
(if canSetStatus and isAdmin
StatusButtonGroup({
planElementType: Term 'Section'
data: section
parentData: clientFile
isExisting: isExistingSection
status: sectionStatus
dangerMessage: (
if allTargetsAreInactive or sectionStatus isnt 'default'
null
else
"Careful: this #{Term 'section'} still has #{Term 'targets'} " +
"that have not been deactivated or marked complete."
)
onRemove: onRemoveNewSection
dialog: ModifySectionStatusDialog
isDisabled: isReadOnly
})
)
# TODO: Extract to component
(if not sectionIsInactive and isAdmin
R.div({className: 'btn-group btn-group-sm sectionButtons'},
R.button({
ref: 'addTarget'
className: 'addTarget btn btn-primary'
onClick: addTargetToSection.bind null, section.get('id')
disabled: not canModify
},
FaIcon('plus')
" Add #{Term 'Target'}"
)
WithTooltip({
title: "Create #{Term 'Section'} #{Term 'Template'}"
placement: 'top'
container: 'body'
},
if hasValidTargets then OpenDialogLink({
className: 'btn btn-default'
dialog: CreatePlanTemplateDialog
title: "Create #{Term 'Template'} from #{Term 'Section'}"
sections: Imm.List([section])
currentTargetRevisionsById
disabled: isReadOnly
},
FaIcon 'wpforms'
)
else R.div({
className: 'btn btn-default',
onClick: () => Bootbox.alert {
title: "Oops! One or more #{Term 'target'} are missing a name"
message: "All #{Term 'targets'} in a new #{Term 'section'} #{Term 'template'} must have a name. Please fix any empty #{Term 'target'} names, and try again."
}
}, FaIcon 'wpforms')
)
)
)
)
# Drag source contract
sectionSource = {
beginDrag: ({id, index}) -> {id, index}
}
sectionDestination = {
hover: (props, monitor, component) ->
dragIndex = monitor.getItem().index
hoverIndex = props.index
# Don't replace items with themselves
return if dragIndex is hoverIndex
# Determine rectangle on screen
hoverBoundingRect = findDOMNode(component).getBoundingClientRect()
# Get vertical middle
hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2
# Determine mouse position
clientOffset = monitor.getClientOffset()
# Get pixels to the top
hoverClientY = clientOffset.y - hoverBoundingRect.top
# Only perform the move when the mouse has crossed half of the item's height
# When dragging downwards, only move when the cursor is below 50%
# When dragging upwards, only move when the cursor is above 50%
# Dragging downwards
return if dragIndex < hoverIndex and hoverClientY < hoverMiddleY
# Dragging upwards
return if dragIndex > hoverIndex and hoverClientY > hoverMiddleY
# Time to actually perform the action
props.reorderSection(dragIndex, hoverIndex)
# (Example says to mutate here, but we're using Imm data)
monitor.getItem().index = hoverIndex;
}
# Specify props to inject into component
collectSource = (connect, monitor) -> {
connectDragSource: connect.dragSource()
connectDragPreview: connect.dragPreview()
isDragging: monitor.isDragging()
}
connectDestination = (connect) -> {
connectDropTarget: connect.dropTarget()
}
# Decorate/Wrap PlanSection with DragDropContext, DropTarget, and DragSource
return React.createFactory Decorate [
DropTarget('section', sectionDestination, connectDestination)
DragSource('section', sectionSource, collectSource)
], PlanSection
module.exports = {load}
| true | # Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Plan section view, which is draggable
Imm = require 'immutable'
Decorate = require 'es-decorate'
Term = require '../../term'
load = (win) ->
React = win.React
R = React.DOM
{findDOMNode} = win.ReactDOM
{DragSource, DropTarget} = win.ReactDnD
Bootbox = win.bootbox
PlanTarget = require('./planTarget').load(win)
InactiveToggleWrapper = require('./inactiveToggleWrapper').load(win)
StatusButtonGroup = require('./statusButtonGroup').load(win)
ModifySectionStatusDialog = require('../modifySectionStatusDialog').load(win)
OpenDialogLink = require('../../openDialogLink').load(win)
WithTooltip = require('../../withTooltip').load(win)
CreatePlanTemplateDialog = require('../createPlanTemplateDialog').load(win)
ColorKeyBubble = require('../../colorKeyBubble').load(win)
{FaIcon, showWhen} = require('../../utils').load(win)
PlanSection = React.createClass
displayName: 'PlanSection'
mixins: [React.addons.PureRenderMixin]
propTypes: {
# DnD
connectDragSource: React.PropTypes.func.isRequired
connectDragPreview: React.PropTypes.func.isRequired
connectDropTarget: React.PropTypes.func.isRequired
isDragging: React.PropTypes.bool.isRequired
# DnD props
index: React.PropTypes.number.isRequired
id: React.PropTypes.any.isRequired
# Raw data
section: React.PropTypes.instanceOf(Imm.Map).isRequired
# Methods
reorderSection: React.PropTypes.func.isRequired
reorderTargetId: React.PropTypes.func.isRequired
}
getInitialState: -> {
displayDeactivatedTargets: null
displayCompletedTargets: null
isReorderHovered: false
}
render: ->
{
section
program
clientFile
plan
metricsById
currentTargetRevisionsById
planTargetsById
selectedTargetId
isReadOnly
isCollapsed
renameSection
addTargetToSection
hasTargetChanged
updateTarget
removeNewTarget
removeNewSection
onRemoveNewSection
setSelectedTarget
addMetricToTarget
deleteMetricFromTarget
getSectionIndex
expandTarget
expandSection
reorderSection
reorderTargetId
connectDragSource
connectDropTarget
connectDragPreview
isDragging
} = @props
{id, status} = section.toObject()
sectionIsInactive = status isnt 'default'
sectionIndex = @props.index
# Build targets by status, and order them manually into an array
# TODO: Make this an ordered set or something...
targetsByStatus = section.get('targetIds')
.map (id) -> currentTargetRevisionsById.get(id)
.groupBy (t) -> t.get('status')
targetsByStatusArray = Imm.List(['default', 'completed', 'deactivated']).map (status) ->
targetsByStatus.get(status)
return connectDropTarget connectDragPreview (
R.section({
id: "section-#{id}"
className: [
'planSection'
"status-#{status}"
'isCollapsed' if isCollapsed
'isDragging' if isDragging
'isReorderHovered' if @state.isReorderHovered
].join ' '
},
SectionHeader({
clientFile
section
program
isReadOnly
isCollapsed
allTargetsAreInactive: not targetsByStatus.get('default')
renameSection
getSectionIndex
addTargetToSection
onRemoveNewSection
sectionIsInactive
currentTargetRevisionsById
connectDragSource
expandSection
onReorderHover: @_onReorderHover
})
(if section.get('targetIds').size is 0
R.div({className: 'noTargets'},
"This #{Term 'section'} is empty."
)
)
(targetsByStatusArray.map (targets) =>
# TODO: Remove this in favour of [key, value] (prev. TODO)
return if not targets
status = targets.getIn [0, 'status']
size = targets.size
# Build the list of targets
PlanTargetsList = R.div({className: 'planTargetsList'},
(targets.map (target) =>
targetId = target.get('id')
index = section.get('targetIds').indexOf targetId
hasChanges = hasTargetChanged(targetId)
isSelected = targetId is selectedTargetId
isExistingTarget = planTargetsById.has(targetId)
PlanTarget({
key: targetId
target
metricsById
hasChanges
isSelected
isExistingTarget
isReadOnly
isCollapsed
sectionIsInactive
onRemoveNewTarget: removeNewTarget.bind null, id, targetId
onTargetUpdate: updateTarget.bind null, targetId
onTargetSelection: setSelectedTarget.bind null, targetId
setSelectedTarget # allows for setState cb
onExpandTarget: expandTarget.bind null, targetId
addMetricToTarget
deleteMetricFromTarget
reorderTargetId
section
sectionIndex
index
activeTabId: @props.activeTabId
})
)
)
# Return wrapped inactive target groups for display toggling
R.div({key: status},
switch status
when 'default'
PlanTargetsList
when 'deactivated'
InactiveToggleWrapper({
children: PlanTargetsList
dataType: 'target'
status, size
isExpanded: @state.displayDeactivatedTargets
onToggle: @_toggleDisplayDeactivatedTargets
})
when 'completed'
InactiveToggleWrapper({
children: PlanTargetsList
dataType: 'target'
status, size
isExpanded: @state.displayCompletedTargets
onToggle: @_toggleDisplayCompletedTargets
})
)
)
)
)
_toggleDisplayCompletedTargets: ->
displayCompletedTargets = not @state.displayCompletedTargets
@setState {displayCompletedTargets}
_toggleDisplayDeactivatedTargets: ->
displayDeactivatedTargets = not @state.displayDeactivatedTargets
@setState {displayDeactivatedTargets}
_onReorderHover: (isReorderHovered) -> @setState {isReorderHovered}
SectionHeader = React.createFactory React.createClass
displayName: 'SectionHeader'
mixins: [React.addons.PureRenderMixin]
render: ->
{
clientFile
section
program
isReadOnly
isCollapsed
allTargetsAreInactive
renameSection
getSectionIndex
addTargetToSection
removeNewSection
onRemoveNewSection
currentTargetRevisionsById
sectionIsInactive
connectDragSource
expandSection
onReorderHover
} = @props
sectionStatus = section.get('status')
sectionId = section.get('id')
# Figure out whether already exists in plan
isExistingSection = clientFile.getIn(['plan','sections']).some (obj) =>
obj.get('id') is section.get('id')
canSetStatus = isExistingSection and not isReadOnly
canModify = not isReadOnly and not sectionIsInactive
isAdmin = global.ActiveSession.isAdmin()
hasValidTargets = currentTargetRevisionsById.every((target) => target.get('name'));
return R.div({className: 'sectionHeader'},
connectDragSource (
R.div({
className: 'dragSource'
onMouseOver: => onReorderHover(true)
onMouseLeave: => onReorderHover(false)
},
FaIcon('arrows-v')
)
)
R.div({
title: "Edit name"
className: 'sectionName'
},
R.span({
onClick: ->
if isCollapsed
expandSection(sectionId)
else if canModify
renameSection(sectionId)
},
section.get('name')
(if program
ColorKeyBubble({
colorKeyHex: program.get('colorKeyHex')
popover: {
title: program.get('name')
content: program.get('description')
placement: 'top'
}
})
)
(if canModify and not isCollapsed
FaIcon('pencil', {className: 'renameIcon'})
)
)
)
(if canSetStatus and isAdmin
StatusButtonGroup({
planElementType: Term 'Section'
data: section
parentData: clientFile
isExisting: isExistingSection
status: sectionStatus
dangerMessage: (
if allTargetsAreInactive or sectionStatus isnt 'default'
null
else
"Careful: this #{Term 'section'} still has #{Term 'targets'} " +
"that have not been deactivated or marked complete."
)
onRemove: onRemoveNewSection
dialog: ModifySectionStatusDialog
isDisabled: isReadOnly
})
)
# TODO: Extract to component
(if not sectionIsInactive and isAdmin
R.div({className: 'btn-group btn-group-sm sectionButtons'},
R.button({
ref: 'addTarget'
className: 'addTarget btn btn-primary'
onClick: addTargetToSection.bind null, section.get('id')
disabled: not canModify
},
FaIcon('plus')
" Add #{Term 'Target'}"
)
WithTooltip({
title: "Create #{Term 'Section'} #{Term 'Template'}"
placement: 'top'
container: 'body'
},
if hasValidTargets then OpenDialogLink({
className: 'btn btn-default'
dialog: CreatePlanTemplateDialog
title: "Create #{Term 'Template'} from #{Term 'Section'}"
sections: Imm.List([section])
currentTargetRevisionsById
disabled: isReadOnly
},
FaIcon 'wpforms'
)
else R.div({
className: 'btn btn-default',
onClick: () => Bootbox.alert {
title: "Oops! One or more #{Term 'target'} are missing a name"
message: "All #{Term 'targets'} in a new #{Term 'section'} #{Term 'template'} must have a name. Please fix any empty #{Term 'target'} names, and try again."
}
}, FaIcon 'wpforms')
)
)
)
)
# Drag source contract
sectionSource = {
beginDrag: ({id, index}) -> {id, index}
}
sectionDestination = {
hover: (props, monitor, component) ->
dragIndex = monitor.getItem().index
hoverIndex = props.index
# Don't replace items with themselves
return if dragIndex is hoverIndex
# Determine rectangle on screen
hoverBoundingRect = findDOMNode(component).getBoundingClientRect()
# Get vertical middle
hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2
# Determine mouse position
clientOffset = monitor.getClientOffset()
# Get pixels to the top
hoverClientY = clientOffset.y - hoverBoundingRect.top
# Only perform the move when the mouse has crossed half of the item's height
# When dragging downwards, only move when the cursor is below 50%
# When dragging upwards, only move when the cursor is above 50%
# Dragging downwards
return if dragIndex < hoverIndex and hoverClientY < hoverMiddleY
# Dragging upwards
return if dragIndex > hoverIndex and hoverClientY > hoverMiddleY
# Time to actually perform the action
props.reorderSection(dragIndex, hoverIndex)
# (Example says to mutate here, but we're using Imm data)
monitor.getItem().index = hoverIndex;
}
# Specify props to inject into component
collectSource = (connect, monitor) -> {
connectDragSource: connect.dragSource()
connectDragPreview: connect.dragPreview()
isDragging: monitor.isDragging()
}
connectDestination = (connect) -> {
connectDropTarget: connect.dropTarget()
}
# Decorate/Wrap PlanSection with DragDropContext, DropTarget, and DragSource
return React.createFactory Decorate [
DropTarget('section', sectionDestination, connectDestination)
DragSource('section', sectionSource, collectSource)
], PlanSection
module.exports = {load}
|
[
{
"context": "harge extends Skill\n target: TARGET_DIR8\n key: 'charge'\n name: 'charge'\n mp: 8\n cooldown: 5\n\n run: (",
"end": 63,
"score": 0.9964891672134399,
"start": 57,
"tag": "KEY",
"value": "charge"
}
] | js/skills/charge.coffee | ktchernov/7drl-lion.github.io | 27 | class Charge extends Skill
target: TARGET_DIR8
key: 'charge'
name: 'charge'
mp: 8
cooldown: 5
run: (dir) ->
[i, j] = @state.get_pos @id
[x, y] = @state.find_in_direction i, j, dir, (x, y, n) =>
@state.is_blocked_in_dir(x, y, dir) or n >= 6
return false if x == i and y == j
actor_short = @state.get_short_description @id
@state.msg @id, "You shout wildly and charge!"
@state.shout_by @id, "#{_.str.capitalize(actor_short)} shouts wildly and charges!"
@state.set_pos @id, x, y
@execute_action 'attack', dir
if @id == @state.player_id
SoundEffects.get().play_skill_used()
true
register_skill 'charge', Charge
| 124014 | class Charge extends Skill
target: TARGET_DIR8
key: '<KEY>'
name: 'charge'
mp: 8
cooldown: 5
run: (dir) ->
[i, j] = @state.get_pos @id
[x, y] = @state.find_in_direction i, j, dir, (x, y, n) =>
@state.is_blocked_in_dir(x, y, dir) or n >= 6
return false if x == i and y == j
actor_short = @state.get_short_description @id
@state.msg @id, "You shout wildly and charge!"
@state.shout_by @id, "#{_.str.capitalize(actor_short)} shouts wildly and charges!"
@state.set_pos @id, x, y
@execute_action 'attack', dir
if @id == @state.player_id
SoundEffects.get().play_skill_used()
true
register_skill 'charge', Charge
| true | class Charge extends Skill
target: TARGET_DIR8
key: 'PI:KEY:<KEY>END_PI'
name: 'charge'
mp: 8
cooldown: 5
run: (dir) ->
[i, j] = @state.get_pos @id
[x, y] = @state.find_in_direction i, j, dir, (x, y, n) =>
@state.is_blocked_in_dir(x, y, dir) or n >= 6
return false if x == i and y == j
actor_short = @state.get_short_description @id
@state.msg @id, "You shout wildly and charge!"
@state.shout_by @id, "#{_.str.capitalize(actor_short)} shouts wildly and charges!"
@state.set_pos @id, x, y
@execute_action 'attack', dir
if @id == @state.player_id
SoundEffects.get().play_skill_used()
true
register_skill 'charge', Charge
|
[
{
"context": " parser is generated by [Jison](http://github.com/zaach/jison)\n# from this grammar file. Jison is a botto",
"end": 73,
"score": 0.9996387958526611,
"start": 68,
"tag": "USERNAME",
"value": "zaach"
},
{
"context": "dy DSL for Jison grammar generation, thanks to\n# [Tim ... | src/grammar.coffee | clutchski/coffee-script | 1 | # The CoffeeScript parser is generated by [Jison](http://github.com/zaach/jison)
# from this grammar file. Jison is a bottom-up parser generator, similar in
# style to [Bison](http://www.gnu.org/software/bison), implemented in JavaScript.
# It can recognize [LALR(1), LR(0), SLR(1), and LR(1)](http://en.wikipedia.org/wiki/LR_grammar)
# type grammars. To create the Jison parser, we list the pattern to match
# on the left-hand side, and the action to take (usually the creation of syntax
# tree nodes) on the right. As the parser runs, it
# shifts tokens from our token stream, from left to right, and
# [attempts to match](http://en.wikipedia.org/wiki/Bottom-up_parsing)
# the token sequence against the rules below. When a match can be made, it
# reduces into the [nonterminal](http://en.wikipedia.org/wiki/Terminal_and_nonterminal_symbols)
# (the enclosing name at the top), and we proceed from there.
#
# If you run the `cake build:parser` command, Jison constructs a parse table
# from our rules and saves it into `lib/parser.js`.
# The only dependency is on the **Jison.Parser**.
{Parser} = require 'jison'
# Jison DSL
# ---------
# Since we're going to be wrapped in a function by Jison in any case, if our
# action immediately returns a value, we can optimize by removing the function
# wrapper and just returning the value directly.
unwrap = /^function\s*\(\)\s*\{\s*return\s*([\s\S]*);\s*\}/
# Our handy DSL for Jison grammar generation, thanks to
# [Tim Caswell](http://github.com/creationix). For every rule in the grammar,
# we pass the pattern-defining string, the action to run, and extra options,
# optionally. If no action is specified, we simply pass the value of the
# previous nonterminal.
o = (patternString, action, options) ->
patternString = patternString.replace /\s{2,}/g, ' '
return [patternString, '$$ = $1;', options] unless action
action = if match = unwrap.exec action then match[1] else "(#{action}())"
action = action.replace /\bnew /g, '$&yy.'
action = action.replace /\b(?:Block\.wrap|extend)\b/g, 'yy.$&'
[patternString, "$$ = #{action};", options]
# Grammatical Rules
# -----------------
# In all of the rules that follow, you'll see the name of the nonterminal as
# the key to a list of alternative matches. With each match's action, the
# dollar-sign variables are provided by Jison as references to the value of
# their numeric position, so in this rule:
#
# "Expression UNLESS Expression"
#
# `$1` would be the value of the first `Expression`, `$2` would be the token
# for the `UNLESS` terminal, and `$3` would be the value of the second
# `Expression`.
grammar =
# The **Root** is the top-level node in the syntax tree. Since we parse bottom-up,
# all parsing must end here.
Root: [
o '', -> new Block
o 'Body'
o 'Block TERMINATOR'
]
# Any list of statements and expressions, separated by line breaks or semicolons.
Body: [
o 'Line', -> Block.wrap [$1]
o 'Body TERMINATOR Line', -> $1.push $3
o 'Body TERMINATOR'
]
# Block and statements, which make up a line in a body.
Line: [
o 'Expression'
o 'Statement'
]
# Pure statements which cannot be expressions.
Statement: [
o 'Return'
o 'Comment'
o 'STATEMENT', -> new Literal $1
]
# All the different types of expressions in our language. The basic unit of
# CoffeeScript is the **Expression** -- everything that can be an expression
# is one. Blocks serve as the building blocks of many other rules, making
# them somewhat circular.
Expression: [
o 'Value'
o 'Invocation'
o 'Code'
o 'Operation'
o 'Assign'
o 'If'
o 'Try'
o 'While'
o 'For'
o 'Switch'
o 'Class'
o 'Throw'
]
# An indented block of expressions. Note that the [Rewriter](rewriter.html)
# will convert some postfix forms into blocks for us, by adjusting the
# token stream.
Block: [
o 'INDENT OUTDENT', -> new Block
o 'INDENT Body OUTDENT', -> $2
]
# A literal identifier, a variable name or property.
Identifier: [
o 'IDENTIFIER', -> new Literal $1
]
# Alphanumerics are separated from the other **Literal** matchers because
# they can also serve as keys in object literals.
AlphaNumeric: [
o 'NUMBER', -> new Literal $1
o 'STRING', -> new Literal $1
]
# All of our immediate values. Generally these can be passed straight
# through and printed to JavaScript.
Literal: [
o 'AlphaNumeric'
o 'JS', -> new Literal $1
o 'REGEX', -> new Literal $1
o 'DEBUGGER', -> new Literal $1
o 'BOOL', ->
val = new Literal $1
val.isUndefined = yes if $1 is 'undefined'
val
]
# Assignment of a variable, property, or index to a value.
Assign: [
o 'Assignable = Expression', -> new Assign $1, $3
o 'Assignable = TERMINATOR Expression', -> new Assign $1, $4
o 'Assignable = INDENT Expression OUTDENT', -> new Assign $1, $4
]
# Assignment when it happens within an object literal. The difference from
# the ordinary **Assign** is that these allow numbers and strings as keys.
AssignObj: [
o 'ObjAssignable', -> new Value $1
o 'ObjAssignable : Expression', -> new Assign new Value($1), $3, 'object'
o 'ObjAssignable :
INDENT Expression OUTDENT', -> new Assign new Value($1), $4, 'object'
o 'Comment'
]
ObjAssignable: [
o 'Identifier'
o 'AlphaNumeric'
o 'ThisProperty'
]
# A return statement from a function body.
Return: [
o 'RETURN Expression', -> new Return $2
o 'RETURN', -> new Return
]
# A block comment.
Comment: [
o 'HERECOMMENT', -> new Comment $1
]
# The **Code** node is the function literal. It's defined by an indented block
# of **Block** preceded by a function arrow, with an optional parameter
# list.
Code: [
o 'PARAM_START ParamList PARAM_END FuncGlyph Block', -> new Code $2, $5, $4
o 'FuncGlyph Block', -> new Code [], $2, $1
]
# CoffeeScript has two different symbols for functions. `->` is for ordinary
# functions, and `=>` is for functions bound to the current value of *this*.
FuncGlyph: [
o '->', -> 'func'
o '=>', -> 'boundfunc'
]
# An optional, trailing comma.
OptComma: [
o ''
o ','
]
# The list of parameters that a function accepts can be of any length.
ParamList: [
o '', -> []
o 'Param', -> [$1]
o 'ParamList , Param', -> $1.concat $3
]
# A single parameter in a function definition can be ordinary, or a splat
# that hoovers up the remaining arguments.
Param: [
o 'ParamVar', -> new Param $1
o 'ParamVar ...', -> new Param $1, null, on
o 'ParamVar = Expression', -> new Param $1, $3
]
# Function Parameters
ParamVar: [
o 'Identifier'
o 'ThisProperty'
o 'Array'
o 'Object'
]
# A splat that occurs outside of a parameter list.
Splat: [
o 'Expression ...', -> new Splat $1
]
# Variables and properties that can be assigned to.
SimpleAssignable: [
o 'Identifier', -> new Value $1
o 'Value Accessor', -> $1.add $2
o 'Invocation Accessor', -> new Value $1, [].concat $2
o 'ThisProperty'
]
# Everything that can be assigned to.
Assignable: [
o 'SimpleAssignable'
o 'Array', -> new Value $1
o 'Object', -> new Value $1
]
# The types of things that can be treated as values -- assigned to, invoked
# as functions, indexed into, named as a class, etc.
Value: [
o 'Assignable'
o 'Literal', -> new Value $1
o 'Parenthetical', -> new Value $1
o 'Range', -> new Value $1
o 'This'
]
# The general group of accessors into an object, by property, by prototype
# or by array index or slice.
Accessor: [
o '. Identifier', -> new Access $2
o '?. Identifier', -> new Access $2, 'soak'
o ':: Identifier', -> [(new Access new Literal 'prototype'), new Access $2]
o '::', -> new Access new Literal 'prototype'
o 'Index'
]
# Indexing into an object or array using bracket notation.
Index: [
o 'INDEX_START IndexValue INDEX_END', -> $2
o 'INDEX_SOAK Index', -> extend $2, soak : yes
]
IndexValue: [
o 'Expression', -> new Index $1
o 'Slice', -> new Slice $1
]
# In CoffeeScript, an object literal is simply a list of assignments.
Object: [
o '{ AssignList OptComma }', -> new Obj $2, $1.generated
]
# Assignment of properties within an object literal can be separated by
# comma, as in JavaScript, or simply by newline.
AssignList: [
o '', -> []
o 'AssignObj', -> [$1]
o 'AssignList , AssignObj', -> $1.concat $3
o 'AssignList OptComma TERMINATOR AssignObj', -> $1.concat $4
o 'AssignList OptComma INDENT AssignList OptComma OUTDENT', -> $1.concat $4
]
# Class definitions have optional bodies of prototype property assignments,
# and optional references to the superclass.
Class: [
o 'CLASS', -> new Class
o 'CLASS Block', -> new Class null, null, $2
o 'CLASS EXTENDS Expression', -> new Class null, $3
o 'CLASS EXTENDS Expression Block', -> new Class null, $3, $4
o 'CLASS SimpleAssignable', -> new Class $2
o 'CLASS SimpleAssignable Block', -> new Class $2, null, $3
o 'CLASS SimpleAssignable EXTENDS Expression', -> new Class $2, $4
o 'CLASS SimpleAssignable EXTENDS Expression Block', -> new Class $2, $4, $5
]
# Ordinary function invocation, or a chained series of calls.
Invocation: [
o 'Value OptFuncExist Arguments', -> new Call $1, $3, $2
o 'Invocation OptFuncExist Arguments', -> new Call $1, $3, $2
o 'SUPER', -> new Call 'super', [new Splat new Literal 'arguments']
o 'SUPER Arguments', -> new Call 'super', $2
]
# An optional existence check on a function.
OptFuncExist: [
o '', -> no
o 'FUNC_EXIST', -> yes
]
# The list of arguments to a function call.
Arguments: [
o 'CALL_START CALL_END', -> []
o 'CALL_START ArgList OptComma CALL_END', -> $2
]
# A reference to the *this* current object.
This: [
o 'THIS', -> new Value new Literal 'this'
o '@', -> new Value new Literal 'this'
]
# A reference to a property on *this*.
ThisProperty: [
o '@ Identifier', -> new Value new Literal('this'), [new Access($2)], 'this'
]
# The array literal.
Array: [
o '[ ]', -> new Arr []
o '[ ArgList OptComma ]', -> new Arr $2
]
# Inclusive and exclusive range dots.
RangeDots: [
o '..', -> 'inclusive'
o '...', -> 'exclusive'
]
# The CoffeeScript range literal.
Range: [
o '[ Expression RangeDots Expression ]', -> new Range $2, $4, $3
]
# Array slice literals.
Slice: [
o 'Expression RangeDots Expression', -> new Range $1, $3, $2
o 'Expression RangeDots', -> new Range $1, null, $2
o 'RangeDots Expression', -> new Range null, $2, $1
]
# The **ArgList** is both the list of objects passed into a function call,
# as well as the contents of an array literal
# (i.e. comma-separated expressions). Newlines work as well.
ArgList: [
o 'Arg', -> [$1]
o 'ArgList , Arg', -> $1.concat $3
o 'ArgList OptComma TERMINATOR Arg', -> $1.concat $4
o 'INDENT ArgList OptComma OUTDENT', -> $2
o 'ArgList OptComma INDENT ArgList OptComma OUTDENT', -> $1.concat $4
]
# Valid arguments are Blocks or Splats.
Arg: [
o 'Expression'
o 'Splat'
]
# Just simple, comma-separated, required arguments (no fancy syntax). We need
# this to be separate from the **ArgList** for use in **Switch** blocks, where
# having the newlines wouldn't make sense.
SimpleArgs: [
o 'Expression'
o 'SimpleArgs , Expression', -> [].concat $1, $3
]
# The variants of *try/catch/finally* exception handling blocks.
Try: [
o 'TRY Block', -> new Try $2
o 'TRY Block Catch', -> new Try $2, $3[0], $3[1]
o 'TRY Block FINALLY Block', -> new Try $2, null, null, $4
o 'TRY Block Catch FINALLY Block', -> new Try $2, $3[0], $3[1], $5
]
# A catch clause names its error and runs a block of code.
Catch: [
o 'CATCH Identifier Block', -> [$2, $3]
]
# Throw an exception object.
Throw: [
o 'THROW Expression', -> new Throw $2
]
# Parenthetical expressions. Note that the **Parenthetical** is a **Value**,
# not an **Expression**, so if you need to use an expression in a place
# where only values are accepted, wrapping it in parentheses will always do
# the trick.
Parenthetical: [
o '( Body )', -> new Parens $2
o '( INDENT Body OUTDENT )', -> new Parens $3
]
# The condition portion of a while loop.
WhileSource: [
o 'WHILE Expression', -> new While $2
o 'WHILE Expression WHEN Expression', -> new While $2, guard: $4
o 'UNTIL Expression', -> new While $2, invert: true
o 'UNTIL Expression WHEN Expression', -> new While $2, invert: true, guard: $4
]
# The while loop can either be normal, with a block of expressions to execute,
# or postfix, with a single expression. There is no do..while.
While: [
o 'WhileSource Block', -> $1.addBody $2
o 'Statement WhileSource', -> $2.addBody Block.wrap [$1]
o 'Expression WhileSource', -> $2.addBody Block.wrap [$1]
o 'Loop', -> $1
]
Loop: [
o 'LOOP Block', -> new While(new Literal 'true').addBody $2
o 'LOOP Expression', -> new While(new Literal 'true').addBody Block.wrap [$2]
]
# Array, object, and range comprehensions, at the most generic level.
# Comprehensions can either be normal, with a block of expressions to execute,
# or postfix, with a single expression.
For: [
o 'Statement ForBody', -> new For $1, $2
o 'Expression ForBody', -> new For $1, $2
o 'ForBody Block', -> new For $2, $1
]
ForBody: [
o 'FOR Range', -> source: new Value($2)
o 'ForStart ForSource', -> $2.own = $1.own; $2.name = $1[0]; $2.index = $1[1]; $2
]
ForStart: [
o 'FOR ForVariables', -> $2
o 'FOR OWN ForVariables', -> $3.own = yes; $3
]
# An array of all accepted values for a variable inside the loop.
# This enables support for pattern matching.
ForValue: [
o 'Identifier'
o 'Array', -> new Value $1
o 'Object', -> new Value $1
]
# An array or range comprehension has variables for the current element
# and (optional) reference to the current index. Or, *key, value*, in the case
# of object comprehensions.
ForVariables: [
o 'ForValue', -> [$1]
o 'ForValue , ForValue', -> [$1, $3]
]
# The source of a comprehension is an array or object with an optional guard
# clause. If it's an array comprehension, you can also choose to step through
# in fixed-size increments.
ForSource: [
o 'FORIN Expression', -> source: $2
o 'FOROF Expression', -> source: $2, object: yes
o 'FORIN Expression WHEN Expression', -> source: $2, guard: $4
o 'FOROF Expression WHEN Expression', -> source: $2, guard: $4, object: yes
o 'FORIN Expression BY Expression', -> source: $2, step: $4
o 'FORIN Expression WHEN Expression BY Expression', -> source: $2, guard: $4, step: $6
o 'FORIN Expression BY Expression WHEN Expression', -> source: $2, step: $4, guard: $6
]
Switch: [
o 'SWITCH Expression INDENT Whens OUTDENT', -> new Switch $2, $4
o 'SWITCH Expression INDENT Whens ELSE Block OUTDENT', -> new Switch $2, $4, $6
o 'SWITCH INDENT Whens OUTDENT', -> new Switch null, $3
o 'SWITCH INDENT Whens ELSE Block OUTDENT', -> new Switch null, $3, $5
]
Whens: [
o 'When'
o 'Whens When', -> $1.concat $2
]
# An individual **When** clause, with action.
When: [
o 'LEADING_WHEN SimpleArgs Block', -> [[$2, $3]]
o 'LEADING_WHEN SimpleArgs Block TERMINATOR', -> [[$2, $3]]
]
# The most basic form of *if* is a condition and an action. The following
# if-related rules are broken up along these lines in order to avoid
# ambiguity.
IfBlock: [
o 'IF Expression Block', -> new If $2, $3, type: $1
o 'IfBlock ELSE IF Expression Block', -> $1.addElse new If $4, $5, type: $3
]
# The full complement of *if* expressions, including postfix one-liner
# *if* and *unless*.
If: [
o 'IfBlock'
o 'IfBlock ELSE Block', -> $1.addElse $3
o 'Statement POST_IF Expression', -> new If $3, Block.wrap([$1]), type: $2, statement: true
o 'Expression POST_IF Expression', -> new If $3, Block.wrap([$1]), type: $2, statement: true
]
# Arithmetic and logical operators, working on one or more operands.
# Here they are grouped by order of precedence. The actual precedence rules
# are defined at the bottom of the page. It would be shorter if we could
# combine most of these rules into a single generic *Operand OpSymbol Operand*
# -type rule, but in order to make the precedence binding possible, separate
# rules are necessary.
Operation: [
o 'UNARY Expression', -> new Op $1 , $2
o '- Expression', (-> new Op '-', $2), prec: 'UNARY'
o '+ Expression', (-> new Op '+', $2), prec: 'UNARY'
o '-- SimpleAssignable', -> new Op '--', $2
o '++ SimpleAssignable', -> new Op '++', $2
o 'SimpleAssignable --', -> new Op '--', $1, null, true
o 'SimpleAssignable ++', -> new Op '++', $1, null, true
# [The existential operator](http://jashkenas.github.com/coffee-script/#existence).
o 'Expression ?', -> new Existence $1
o 'Expression + Expression', -> new Op '+' , $1, $3
o 'Expression - Expression', -> new Op '-' , $1, $3
o 'Expression MATH Expression', -> new Op $2, $1, $3
o 'Expression SHIFT Expression', -> new Op $2, $1, $3
o 'Expression COMPARE Expression', -> new Op $2, $1, $3
o 'Expression LOGIC Expression', -> new Op $2, $1, $3
o 'Expression RELATION Expression', ->
if $2.charAt(0) is '!'
new Op($2.slice(1), $1, $3).invert()
else
new Op $2, $1, $3
o 'SimpleAssignable COMPOUND_ASSIGN
Expression', -> new Assign $1, $3, $2
o 'SimpleAssignable COMPOUND_ASSIGN
INDENT Expression OUTDENT', -> new Assign $1, $4, $2
o 'SimpleAssignable EXTENDS Expression', -> new Extends $1, $3
]
# Precedence
# ----------
# Operators at the top of this list have higher precedence than the ones lower
# down. Following these rules is what makes `2 + 3 * 4` parse as:
#
# 2 + (3 * 4)
#
# And not:
#
# (2 + 3) * 4
operators = [
['left', '.', '?.', '::']
['left', 'CALL_START', 'CALL_END']
['nonassoc', '++', '--']
['left', '?']
['right', 'UNARY']
['left', 'MATH']
['left', '+', '-']
['left', 'SHIFT']
['left', 'RELATION']
['left', 'COMPARE']
['left', 'LOGIC']
['nonassoc', 'INDENT', 'OUTDENT']
['right', '=', ':', 'COMPOUND_ASSIGN', 'RETURN', 'THROW', 'EXTENDS']
['right', 'FORIN', 'FOROF', 'BY', 'WHEN']
['right', 'IF', 'ELSE', 'FOR', 'WHILE', 'UNTIL', 'LOOP', 'SUPER', 'CLASS']
['right', 'POST_IF']
]
# Wrapping Up
# -----------
# Finally, now that we have our **grammar** and our **operators**, we can create
# our **Jison.Parser**. We do this by processing all of our rules, recording all
# terminals (every symbol which does not appear as the name of a rule above)
# as "tokens".
tokens = []
for name, alternatives of grammar
grammar[name] = for alt in alternatives
for token in alt[0].split ' '
tokens.push token unless grammar[token]
alt[1] = "return #{alt[1]}" if name is 'Root'
alt
# Initialize the **Parser** with our list of terminal **tokens**, our **grammar**
# rules, and the name of the root. Reverse the operators because Jison orders
# precedence from low to high, and we have it high to low
# (as in [Yacc](http://dinosaur.compilertools.net/yacc/index.html)).
exports.parser = new Parser
tokens : tokens.join ' '
bnf : grammar
operators : operators.reverse()
startSymbol : 'Root'
| 11229 | # The CoffeeScript parser is generated by [Jison](http://github.com/zaach/jison)
# from this grammar file. Jison is a bottom-up parser generator, similar in
# style to [Bison](http://www.gnu.org/software/bison), implemented in JavaScript.
# It can recognize [LALR(1), LR(0), SLR(1), and LR(1)](http://en.wikipedia.org/wiki/LR_grammar)
# type grammars. To create the Jison parser, we list the pattern to match
# on the left-hand side, and the action to take (usually the creation of syntax
# tree nodes) on the right. As the parser runs, it
# shifts tokens from our token stream, from left to right, and
# [attempts to match](http://en.wikipedia.org/wiki/Bottom-up_parsing)
# the token sequence against the rules below. When a match can be made, it
# reduces into the [nonterminal](http://en.wikipedia.org/wiki/Terminal_and_nonterminal_symbols)
# (the enclosing name at the top), and we proceed from there.
#
# If you run the `cake build:parser` command, Jison constructs a parse table
# from our rules and saves it into `lib/parser.js`.
# The only dependency is on the **Jison.Parser**.
{Parser} = require 'jison'
# Jison DSL
# ---------
# Since we're going to be wrapped in a function by Jison in any case, if our
# action immediately returns a value, we can optimize by removing the function
# wrapper and just returning the value directly.
unwrap = /^function\s*\(\)\s*\{\s*return\s*([\s\S]*);\s*\}/
# Our handy DSL for Jison grammar generation, thanks to
# [<NAME>](http://github.com/creationix). For every rule in the grammar,
# we pass the pattern-defining string, the action to run, and extra options,
# optionally. If no action is specified, we simply pass the value of the
# previous nonterminal.
o = (patternString, action, options) ->
patternString = patternString.replace /\s{2,}/g, ' '
return [patternString, '$$ = $1;', options] unless action
action = if match = unwrap.exec action then match[1] else "(#{action}())"
action = action.replace /\bnew /g, '$&yy.'
action = action.replace /\b(?:Block\.wrap|extend)\b/g, 'yy.$&'
[patternString, "$$ = #{action};", options]
# Grammatical Rules
# -----------------
# In all of the rules that follow, you'll see the name of the nonterminal as
# the key to a list of alternative matches. With each match's action, the
# dollar-sign variables are provided by Jison as references to the value of
# their numeric position, so in this rule:
#
# "Expression UNLESS Expression"
#
# `$1` would be the value of the first `Expression`, `$2` would be the token
# for the `UNLESS` terminal, and `$3` would be the value of the second
# `Expression`.
grammar =
# The **Root** is the top-level node in the syntax tree. Since we parse bottom-up,
# all parsing must end here.
Root: [
o '', -> new Block
o 'Body'
o 'Block TERMINATOR'
]
# Any list of statements and expressions, separated by line breaks or semicolons.
Body: [
o 'Line', -> Block.wrap [$1]
o 'Body TERMINATOR Line', -> $1.push $3
o 'Body TERMINATOR'
]
# Block and statements, which make up a line in a body.
Line: [
o 'Expression'
o 'Statement'
]
# Pure statements which cannot be expressions.
Statement: [
o 'Return'
o 'Comment'
o 'STATEMENT', -> new Literal $1
]
# All the different types of expressions in our language. The basic unit of
# CoffeeScript is the **Expression** -- everything that can be an expression
# is one. Blocks serve as the building blocks of many other rules, making
# them somewhat circular.
Expression: [
o 'Value'
o 'Invocation'
o 'Code'
o 'Operation'
o 'Assign'
o 'If'
o 'Try'
o 'While'
o 'For'
o 'Switch'
o 'Class'
o 'Throw'
]
# An indented block of expressions. Note that the [Rewriter](rewriter.html)
# will convert some postfix forms into blocks for us, by adjusting the
# token stream.
Block: [
o 'INDENT OUTDENT', -> new Block
o 'INDENT Body OUTDENT', -> $2
]
# A literal identifier, a variable name or property.
Identifier: [
o 'IDENTIFIER', -> new Literal $1
]
# Alphanumerics are separated from the other **Literal** matchers because
# they can also serve as keys in object literals.
AlphaNumeric: [
o 'NUMBER', -> new Literal $1
o 'STRING', -> new Literal $1
]
# All of our immediate values. Generally these can be passed straight
# through and printed to JavaScript.
Literal: [
o 'AlphaNumeric'
o 'JS', -> new Literal $1
o 'REGEX', -> new Literal $1
o 'DEBUGGER', -> new Literal $1
o 'BOOL', ->
val = new Literal $1
val.isUndefined = yes if $1 is 'undefined'
val
]
# Assignment of a variable, property, or index to a value.
Assign: [
o 'Assignable = Expression', -> new Assign $1, $3
o 'Assignable = TERMINATOR Expression', -> new Assign $1, $4
o 'Assignable = INDENT Expression OUTDENT', -> new Assign $1, $4
]
# Assignment when it happens within an object literal. The difference from
# the ordinary **Assign** is that these allow numbers and strings as keys.
AssignObj: [
o 'ObjAssignable', -> new Value $1
o 'ObjAssignable : Expression', -> new Assign new Value($1), $3, 'object'
o 'ObjAssignable :
INDENT Expression OUTDENT', -> new Assign new Value($1), $4, 'object'
o 'Comment'
]
ObjAssignable: [
o 'Identifier'
o 'AlphaNumeric'
o 'ThisProperty'
]
# A return statement from a function body.
Return: [
o 'RETURN Expression', -> new Return $2
o 'RETURN', -> new Return
]
# A block comment.
Comment: [
o 'HERECOMMENT', -> new Comment $1
]
# The **Code** node is the function literal. It's defined by an indented block
# of **Block** preceded by a function arrow, with an optional parameter
# list.
Code: [
o 'PARAM_START ParamList PARAM_END FuncGlyph Block', -> new Code $2, $5, $4
o 'FuncGlyph Block', -> new Code [], $2, $1
]
# CoffeeScript has two different symbols for functions. `->` is for ordinary
# functions, and `=>` is for functions bound to the current value of *this*.
FuncGlyph: [
o '->', -> 'func'
o '=>', -> 'boundfunc'
]
# An optional, trailing comma.
OptComma: [
o ''
o ','
]
# The list of parameters that a function accepts can be of any length.
ParamList: [
o '', -> []
o 'Param', -> [$1]
o 'ParamList , Param', -> $1.concat $3
]
# A single parameter in a function definition can be ordinary, or a splat
# that hoovers up the remaining arguments.
Param: [
o 'ParamVar', -> new Param $1
o 'ParamVar ...', -> new Param $1, null, on
o 'ParamVar = Expression', -> new Param $1, $3
]
# Function Parameters
ParamVar: [
o 'Identifier'
o 'ThisProperty'
o 'Array'
o 'Object'
]
# A splat that occurs outside of a parameter list.
Splat: [
o 'Expression ...', -> new Splat $1
]
# Variables and properties that can be assigned to.
SimpleAssignable: [
o 'Identifier', -> new Value $1
o 'Value Accessor', -> $1.add $2
o 'Invocation Accessor', -> new Value $1, [].concat $2
o 'ThisProperty'
]
# Everything that can be assigned to.
Assignable: [
o 'SimpleAssignable'
o 'Array', -> new Value $1
o 'Object', -> new Value $1
]
# The types of things that can be treated as values -- assigned to, invoked
# as functions, indexed into, named as a class, etc.
Value: [
o 'Assignable'
o 'Literal', -> new Value $1
o 'Parenthetical', -> new Value $1
o 'Range', -> new Value $1
o 'This'
]
# The general group of accessors into an object, by property, by prototype
# or by array index or slice.
Accessor: [
o '. Identifier', -> new Access $2
o '?. Identifier', -> new Access $2, 'soak'
o ':: Identifier', -> [(new Access new Literal 'prototype'), new Access $2]
o '::', -> new Access new Literal 'prototype'
o 'Index'
]
# Indexing into an object or array using bracket notation.
Index: [
o 'INDEX_START IndexValue INDEX_END', -> $2
o 'INDEX_SOAK Index', -> extend $2, soak : yes
]
IndexValue: [
o 'Expression', -> new Index $1
o 'Slice', -> new Slice $1
]
# In CoffeeScript, an object literal is simply a list of assignments.
Object: [
o '{ AssignList OptComma }', -> new Obj $2, $1.generated
]
# Assignment of properties within an object literal can be separated by
# comma, as in JavaScript, or simply by newline.
AssignList: [
o '', -> []
o 'AssignObj', -> [$1]
o 'AssignList , AssignObj', -> $1.concat $3
o 'AssignList OptComma TERMINATOR AssignObj', -> $1.concat $4
o 'AssignList OptComma INDENT AssignList OptComma OUTDENT', -> $1.concat $4
]
# Class definitions have optional bodies of prototype property assignments,
# and optional references to the superclass.
Class: [
o 'CLASS', -> new Class
o 'CLASS Block', -> new Class null, null, $2
o 'CLASS EXTENDS Expression', -> new Class null, $3
o 'CLASS EXTENDS Expression Block', -> new Class null, $3, $4
o 'CLASS SimpleAssignable', -> new Class $2
o 'CLASS SimpleAssignable Block', -> new Class $2, null, $3
o 'CLASS SimpleAssignable EXTENDS Expression', -> new Class $2, $4
o 'CLASS SimpleAssignable EXTENDS Expression Block', -> new Class $2, $4, $5
]
# Ordinary function invocation, or a chained series of calls.
Invocation: [
o 'Value OptFuncExist Arguments', -> new Call $1, $3, $2
o 'Invocation OptFuncExist Arguments', -> new Call $1, $3, $2
o 'SUPER', -> new Call 'super', [new Splat new Literal 'arguments']
o 'SUPER Arguments', -> new Call 'super', $2
]
# An optional existence check on a function.
OptFuncExist: [
o '', -> no
o 'FUNC_EXIST', -> yes
]
# The list of arguments to a function call.
Arguments: [
o 'CALL_START CALL_END', -> []
o 'CALL_START ArgList OptComma CALL_END', -> $2
]
# A reference to the *this* current object.
This: [
o 'THIS', -> new Value new Literal 'this'
o '@', -> new Value new Literal 'this'
]
# A reference to a property on *this*.
ThisProperty: [
o '@ Identifier', -> new Value new Literal('this'), [new Access($2)], 'this'
]
# The array literal.
Array: [
o '[ ]', -> new Arr []
o '[ ArgList OptComma ]', -> new Arr $2
]
# Inclusive and exclusive range dots.
RangeDots: [
o '..', -> 'inclusive'
o '...', -> 'exclusive'
]
# The CoffeeScript range literal.
Range: [
o '[ Expression RangeDots Expression ]', -> new Range $2, $4, $3
]
# Array slice literals.
Slice: [
o 'Expression RangeDots Expression', -> new Range $1, $3, $2
o 'Expression RangeDots', -> new Range $1, null, $2
o 'RangeDots Expression', -> new Range null, $2, $1
]
# The **ArgList** is both the list of objects passed into a function call,
# as well as the contents of an array literal
# (i.e. comma-separated expressions). Newlines work as well.
ArgList: [
o 'Arg', -> [$1]
o 'ArgList , Arg', -> $1.concat $3
o 'ArgList OptComma TERMINATOR Arg', -> $1.concat $4
o 'INDENT ArgList OptComma OUTDENT', -> $2
o 'ArgList OptComma INDENT ArgList OptComma OUTDENT', -> $1.concat $4
]
# Valid arguments are Blocks or Splats.
Arg: [
o 'Expression'
o 'Splat'
]
# Just simple, comma-separated, required arguments (no fancy syntax). We need
# this to be separate from the **ArgList** for use in **Switch** blocks, where
# having the newlines wouldn't make sense.
SimpleArgs: [
o 'Expression'
o 'SimpleArgs , Expression', -> [].concat $1, $3
]
# The variants of *try/catch/finally* exception handling blocks.
Try: [
o 'TRY Block', -> new Try $2
o 'TRY Block Catch', -> new Try $2, $3[0], $3[1]
o 'TRY Block FINALLY Block', -> new Try $2, null, null, $4
o 'TRY Block Catch FINALLY Block', -> new Try $2, $3[0], $3[1], $5
]
# A catch clause names its error and runs a block of code.
Catch: [
o 'CATCH Identifier Block', -> [$2, $3]
]
# Throw an exception object.
Throw: [
o 'THROW Expression', -> new Throw $2
]
# Parenthetical expressions. Note that the **Parenthetical** is a **Value**,
# not an **Expression**, so if you need to use an expression in a place
# where only values are accepted, wrapping it in parentheses will always do
# the trick.
Parenthetical: [
o '( Body )', -> new Parens $2
o '( INDENT Body OUTDENT )', -> new Parens $3
]
# The condition portion of a while loop.
WhileSource: [
o 'WHILE Expression', -> new While $2
o 'WHILE Expression WHEN Expression', -> new While $2, guard: $4
o 'UNTIL Expression', -> new While $2, invert: true
o 'UNTIL Expression WHEN Expression', -> new While $2, invert: true, guard: $4
]
# The while loop can either be normal, with a block of expressions to execute,
# or postfix, with a single expression. There is no do..while.
While: [
o 'WhileSource Block', -> $1.addBody $2
o 'Statement WhileSource', -> $2.addBody Block.wrap [$1]
o 'Expression WhileSource', -> $2.addBody Block.wrap [$1]
o 'Loop', -> $1
]
Loop: [
o 'LOOP Block', -> new While(new Literal 'true').addBody $2
o 'LOOP Expression', -> new While(new Literal 'true').addBody Block.wrap [$2]
]
# Array, object, and range comprehensions, at the most generic level.
# Comprehensions can either be normal, with a block of expressions to execute,
# or postfix, with a single expression.
For: [
o 'Statement ForBody', -> new For $1, $2
o 'Expression ForBody', -> new For $1, $2
o 'ForBody Block', -> new For $2, $1
]
ForBody: [
o 'FOR Range', -> source: new Value($2)
o 'ForStart ForSource', -> $2.own = $1.own; $2.name = $1[0]; $2.index = $1[1]; $2
]
ForStart: [
o 'FOR ForVariables', -> $2
o 'FOR OWN ForVariables', -> $3.own = yes; $3
]
# An array of all accepted values for a variable inside the loop.
# This enables support for pattern matching.
ForValue: [
o 'Identifier'
o 'Array', -> new Value $1
o 'Object', -> new Value $1
]
# An array or range comprehension has variables for the current element
# and (optional) reference to the current index. Or, *key, value*, in the case
# of object comprehensions.
ForVariables: [
o 'ForValue', -> [$1]
o 'ForValue , ForValue', -> [$1, $3]
]
# The source of a comprehension is an array or object with an optional guard
# clause. If it's an array comprehension, you can also choose to step through
# in fixed-size increments.
ForSource: [
o 'FORIN Expression', -> source: $2
o 'FOROF Expression', -> source: $2, object: yes
o 'FORIN Expression WHEN Expression', -> source: $2, guard: $4
o 'FOROF Expression WHEN Expression', -> source: $2, guard: $4, object: yes
o 'FORIN Expression BY Expression', -> source: $2, step: $4
o 'FORIN Expression WHEN Expression BY Expression', -> source: $2, guard: $4, step: $6
o 'FORIN Expression BY Expression WHEN Expression', -> source: $2, step: $4, guard: $6
]
Switch: [
o 'SWITCH Expression INDENT Whens OUTDENT', -> new Switch $2, $4
o 'SWITCH Expression INDENT Whens ELSE Block OUTDENT', -> new Switch $2, $4, $6
o 'SWITCH INDENT Whens OUTDENT', -> new Switch null, $3
o 'SWITCH INDENT Whens ELSE Block OUTDENT', -> new Switch null, $3, $5
]
Whens: [
o 'When'
o 'Whens When', -> $1.concat $2
]
# An individual **When** clause, with action.
When: [
o 'LEADING_WHEN SimpleArgs Block', -> [[$2, $3]]
o 'LEADING_WHEN SimpleArgs Block TERMINATOR', -> [[$2, $3]]
]
# The most basic form of *if* is a condition and an action. The following
# if-related rules are broken up along these lines in order to avoid
# ambiguity.
IfBlock: [
o 'IF Expression Block', -> new If $2, $3, type: $1
o 'IfBlock ELSE IF Expression Block', -> $1.addElse new If $4, $5, type: $3
]
# The full complement of *if* expressions, including postfix one-liner
# *if* and *unless*.
If: [
o 'IfBlock'
o 'IfBlock ELSE Block', -> $1.addElse $3
o 'Statement POST_IF Expression', -> new If $3, Block.wrap([$1]), type: $2, statement: true
o 'Expression POST_IF Expression', -> new If $3, Block.wrap([$1]), type: $2, statement: true
]
# Arithmetic and logical operators, working on one or more operands.
# Here they are grouped by order of precedence. The actual precedence rules
# are defined at the bottom of the page. It would be shorter if we could
# combine most of these rules into a single generic *Operand OpSymbol Operand*
# -type rule, but in order to make the precedence binding possible, separate
# rules are necessary.
Operation: [
o 'UNARY Expression', -> new Op $1 , $2
o '- Expression', (-> new Op '-', $2), prec: 'UNARY'
o '+ Expression', (-> new Op '+', $2), prec: 'UNARY'
o '-- SimpleAssignable', -> new Op '--', $2
o '++ SimpleAssignable', -> new Op '++', $2
o 'SimpleAssignable --', -> new Op '--', $1, null, true
o 'SimpleAssignable ++', -> new Op '++', $1, null, true
# [The existential operator](http://jashkenas.github.com/coffee-script/#existence).
o 'Expression ?', -> new Existence $1
o 'Expression + Expression', -> new Op '+' , $1, $3
o 'Expression - Expression', -> new Op '-' , $1, $3
o 'Expression MATH Expression', -> new Op $2, $1, $3
o 'Expression SHIFT Expression', -> new Op $2, $1, $3
o 'Expression COMPARE Expression', -> new Op $2, $1, $3
o 'Expression LOGIC Expression', -> new Op $2, $1, $3
o 'Expression RELATION Expression', ->
if $2.charAt(0) is '!'
new Op($2.slice(1), $1, $3).invert()
else
new Op $2, $1, $3
o 'SimpleAssignable COMPOUND_ASSIGN
Expression', -> new Assign $1, $3, $2
o 'SimpleAssignable COMPOUND_ASSIGN
INDENT Expression OUTDENT', -> new Assign $1, $4, $2
o 'SimpleAssignable EXTENDS Expression', -> new Extends $1, $3
]
# Precedence
# ----------
# Operators at the top of this list have higher precedence than the ones lower
# down. Following these rules is what makes `2 + 3 * 4` parse as:
#
# 2 + (3 * 4)
#
# And not:
#
# (2 + 3) * 4
operators = [
['left', '.', '?.', '::']
['left', 'CALL_START', 'CALL_END']
['nonassoc', '++', '--']
['left', '?']
['right', 'UNARY']
['left', 'MATH']
['left', '+', '-']
['left', 'SHIFT']
['left', 'RELATION']
['left', 'COMPARE']
['left', 'LOGIC']
['nonassoc', 'INDENT', 'OUTDENT']
['right', '=', ':', 'COMPOUND_ASSIGN', 'RETURN', 'THROW', 'EXTENDS']
['right', 'FORIN', 'FOROF', 'BY', 'WHEN']
['right', 'IF', 'ELSE', 'FOR', 'WHILE', 'UNTIL', 'LOOP', 'SUPER', 'CLASS']
['right', 'POST_IF']
]
# Wrapping Up
# -----------
# Finally, now that we have our **grammar** and our **operators**, we can create
# our **Jison.Parser**. We do this by processing all of our rules, recording all
# terminals (every symbol which does not appear as the name of a rule above)
# as "tokens".
tokens = []
for name, alternatives of grammar
grammar[name] = for alt in alternatives
for token in alt[0].split ' '
tokens.push token unless grammar[token]
alt[1] = "return #{alt[1]}" if name is 'Root'
alt
# Initialize the **Parser** with our list of terminal **tokens**, our **grammar**
# rules, and the name of the root. Reverse the operators because Jison orders
# precedence from low to high, and we have it high to low
# (as in [Yacc](http://dinosaur.compilertools.net/yacc/index.html)).
exports.parser = new Parser
tokens : tokens.join ' '
bnf : grammar
operators : operators.reverse()
startSymbol : 'Root'
| true | # The CoffeeScript parser is generated by [Jison](http://github.com/zaach/jison)
# from this grammar file. Jison is a bottom-up parser generator, similar in
# style to [Bison](http://www.gnu.org/software/bison), implemented in JavaScript.
# It can recognize [LALR(1), LR(0), SLR(1), and LR(1)](http://en.wikipedia.org/wiki/LR_grammar)
# type grammars. To create the Jison parser, we list the pattern to match
# on the left-hand side, and the action to take (usually the creation of syntax
# tree nodes) on the right. As the parser runs, it
# shifts tokens from our token stream, from left to right, and
# [attempts to match](http://en.wikipedia.org/wiki/Bottom-up_parsing)
# the token sequence against the rules below. When a match can be made, it
# reduces into the [nonterminal](http://en.wikipedia.org/wiki/Terminal_and_nonterminal_symbols)
# (the enclosing name at the top), and we proceed from there.
#
# If you run the `cake build:parser` command, Jison constructs a parse table
# from our rules and saves it into `lib/parser.js`.
# The only dependency is on the **Jison.Parser**.
{Parser} = require 'jison'
# Jison DSL
# ---------
# Since we're going to be wrapped in a function by Jison in any case, if our
# action immediately returns a value, we can optimize by removing the function
# wrapper and just returning the value directly.
unwrap = /^function\s*\(\)\s*\{\s*return\s*([\s\S]*);\s*\}/
# Our handy DSL for Jison grammar generation, thanks to
# [PI:NAME:<NAME>END_PI](http://github.com/creationix). For every rule in the grammar,
# we pass the pattern-defining string, the action to run, and extra options,
# optionally. If no action is specified, we simply pass the value of the
# previous nonterminal.
o = (patternString, action, options) ->
patternString = patternString.replace /\s{2,}/g, ' '
return [patternString, '$$ = $1;', options] unless action
action = if match = unwrap.exec action then match[1] else "(#{action}())"
action = action.replace /\bnew /g, '$&yy.'
action = action.replace /\b(?:Block\.wrap|extend)\b/g, 'yy.$&'
[patternString, "$$ = #{action};", options]
# Grammatical Rules
# -----------------
# In all of the rules that follow, you'll see the name of the nonterminal as
# the key to a list of alternative matches. With each match's action, the
# dollar-sign variables are provided by Jison as references to the value of
# their numeric position, so in this rule:
#
# "Expression UNLESS Expression"
#
# `$1` would be the value of the first `Expression`, `$2` would be the token
# for the `UNLESS` terminal, and `$3` would be the value of the second
# `Expression`.
grammar =
# The **Root** is the top-level node in the syntax tree. Since we parse bottom-up,
# all parsing must end here.
Root: [
o '', -> new Block
o 'Body'
o 'Block TERMINATOR'
]
# Any list of statements and expressions, separated by line breaks or semicolons.
Body: [
o 'Line', -> Block.wrap [$1]
o 'Body TERMINATOR Line', -> $1.push $3
o 'Body TERMINATOR'
]
# Block and statements, which make up a line in a body.
Line: [
o 'Expression'
o 'Statement'
]
# Pure statements which cannot be expressions.
Statement: [
o 'Return'
o 'Comment'
o 'STATEMENT', -> new Literal $1
]
# All the different types of expressions in our language. The basic unit of
# CoffeeScript is the **Expression** -- everything that can be an expression
# is one. Blocks serve as the building blocks of many other rules, making
# them somewhat circular.
Expression: [
o 'Value'
o 'Invocation'
o 'Code'
o 'Operation'
o 'Assign'
o 'If'
o 'Try'
o 'While'
o 'For'
o 'Switch'
o 'Class'
o 'Throw'
]
# An indented block of expressions. Note that the [Rewriter](rewriter.html)
# will convert some postfix forms into blocks for us, by adjusting the
# token stream.
Block: [
o 'INDENT OUTDENT', -> new Block
o 'INDENT Body OUTDENT', -> $2
]
# A literal identifier, a variable name or property.
Identifier: [
o 'IDENTIFIER', -> new Literal $1
]
# Alphanumerics are separated from the other **Literal** matchers because
# they can also serve as keys in object literals.
AlphaNumeric: [
o 'NUMBER', -> new Literal $1
o 'STRING', -> new Literal $1
]
# All of our immediate values. Generally these can be passed straight
# through and printed to JavaScript.
Literal: [
o 'AlphaNumeric'
o 'JS', -> new Literal $1
o 'REGEX', -> new Literal $1
o 'DEBUGGER', -> new Literal $1
o 'BOOL', ->
val = new Literal $1
val.isUndefined = yes if $1 is 'undefined'
val
]
# Assignment of a variable, property, or index to a value.
Assign: [
o 'Assignable = Expression', -> new Assign $1, $3
o 'Assignable = TERMINATOR Expression', -> new Assign $1, $4
o 'Assignable = INDENT Expression OUTDENT', -> new Assign $1, $4
]
# Assignment when it happens within an object literal. The difference from
# the ordinary **Assign** is that these allow numbers and strings as keys.
AssignObj: [
o 'ObjAssignable', -> new Value $1
o 'ObjAssignable : Expression', -> new Assign new Value($1), $3, 'object'
o 'ObjAssignable :
INDENT Expression OUTDENT', -> new Assign new Value($1), $4, 'object'
o 'Comment'
]
ObjAssignable: [
o 'Identifier'
o 'AlphaNumeric'
o 'ThisProperty'
]
# A return statement from a function body.
Return: [
o 'RETURN Expression', -> new Return $2
o 'RETURN', -> new Return
]
# A block comment.
Comment: [
o 'HERECOMMENT', -> new Comment $1
]
# The **Code** node is the function literal. It's defined by an indented block
# of **Block** preceded by a function arrow, with an optional parameter
# list.
Code: [
o 'PARAM_START ParamList PARAM_END FuncGlyph Block', -> new Code $2, $5, $4
o 'FuncGlyph Block', -> new Code [], $2, $1
]
# CoffeeScript has two different symbols for functions. `->` is for ordinary
# functions, and `=>` is for functions bound to the current value of *this*.
FuncGlyph: [
o '->', -> 'func'
o '=>', -> 'boundfunc'
]
# An optional, trailing comma.
OptComma: [
o ''
o ','
]
# The list of parameters that a function accepts can be of any length.
ParamList: [
o '', -> []
o 'Param', -> [$1]
o 'ParamList , Param', -> $1.concat $3
]
# A single parameter in a function definition can be ordinary, or a splat
# that hoovers up the remaining arguments.
Param: [
o 'ParamVar', -> new Param $1
o 'ParamVar ...', -> new Param $1, null, on
o 'ParamVar = Expression', -> new Param $1, $3
]
# Function Parameters
ParamVar: [
o 'Identifier'
o 'ThisProperty'
o 'Array'
o 'Object'
]
# A splat that occurs outside of a parameter list.
Splat: [
o 'Expression ...', -> new Splat $1
]
# Variables and properties that can be assigned to.
SimpleAssignable: [
o 'Identifier', -> new Value $1
o 'Value Accessor', -> $1.add $2
o 'Invocation Accessor', -> new Value $1, [].concat $2
o 'ThisProperty'
]
# Everything that can be assigned to.
Assignable: [
o 'SimpleAssignable'
o 'Array', -> new Value $1
o 'Object', -> new Value $1
]
# The types of things that can be treated as values -- assigned to, invoked
# as functions, indexed into, named as a class, etc.
Value: [
o 'Assignable'
o 'Literal', -> new Value $1
o 'Parenthetical', -> new Value $1
o 'Range', -> new Value $1
o 'This'
]
# The general group of accessors into an object, by property, by prototype
# or by array index or slice.
Accessor: [
o '. Identifier', -> new Access $2
o '?. Identifier', -> new Access $2, 'soak'
o ':: Identifier', -> [(new Access new Literal 'prototype'), new Access $2]
o '::', -> new Access new Literal 'prototype'
o 'Index'
]
# Indexing into an object or array using bracket notation.
Index: [
o 'INDEX_START IndexValue INDEX_END', -> $2
o 'INDEX_SOAK Index', -> extend $2, soak : yes
]
IndexValue: [
o 'Expression', -> new Index $1
o 'Slice', -> new Slice $1
]
# In CoffeeScript, an object literal is simply a list of assignments.
Object: [
o '{ AssignList OptComma }', -> new Obj $2, $1.generated
]
# Assignment of properties within an object literal can be separated by
# comma, as in JavaScript, or simply by newline.
AssignList: [
o '', -> []
o 'AssignObj', -> [$1]
o 'AssignList , AssignObj', -> $1.concat $3
o 'AssignList OptComma TERMINATOR AssignObj', -> $1.concat $4
o 'AssignList OptComma INDENT AssignList OptComma OUTDENT', -> $1.concat $4
]
# Class definitions have optional bodies of prototype property assignments,
# and optional references to the superclass.
Class: [
o 'CLASS', -> new Class
o 'CLASS Block', -> new Class null, null, $2
o 'CLASS EXTENDS Expression', -> new Class null, $3
o 'CLASS EXTENDS Expression Block', -> new Class null, $3, $4
o 'CLASS SimpleAssignable', -> new Class $2
o 'CLASS SimpleAssignable Block', -> new Class $2, null, $3
o 'CLASS SimpleAssignable EXTENDS Expression', -> new Class $2, $4
o 'CLASS SimpleAssignable EXTENDS Expression Block', -> new Class $2, $4, $5
]
# Ordinary function invocation, or a chained series of calls.
Invocation: [
o 'Value OptFuncExist Arguments', -> new Call $1, $3, $2
o 'Invocation OptFuncExist Arguments', -> new Call $1, $3, $2
o 'SUPER', -> new Call 'super', [new Splat new Literal 'arguments']
o 'SUPER Arguments', -> new Call 'super', $2
]
# An optional existence check on a function.
OptFuncExist: [
o '', -> no
o 'FUNC_EXIST', -> yes
]
# The list of arguments to a function call.
Arguments: [
o 'CALL_START CALL_END', -> []
o 'CALL_START ArgList OptComma CALL_END', -> $2
]
# A reference to the *this* current object.
This: [
o 'THIS', -> new Value new Literal 'this'
o '@', -> new Value new Literal 'this'
]
# A reference to a property on *this*.
ThisProperty: [
o '@ Identifier', -> new Value new Literal('this'), [new Access($2)], 'this'
]
# The array literal.
Array: [
o '[ ]', -> new Arr []
o '[ ArgList OptComma ]', -> new Arr $2
]
# Inclusive and exclusive range dots.
RangeDots: [
o '..', -> 'inclusive'
o '...', -> 'exclusive'
]
# The CoffeeScript range literal.
Range: [
o '[ Expression RangeDots Expression ]', -> new Range $2, $4, $3
]
# Array slice literals.
Slice: [
o 'Expression RangeDots Expression', -> new Range $1, $3, $2
o 'Expression RangeDots', -> new Range $1, null, $2
o 'RangeDots Expression', -> new Range null, $2, $1
]
# The **ArgList** is both the list of objects passed into a function call,
# as well as the contents of an array literal
# (i.e. comma-separated expressions). Newlines work as well.
ArgList: [
o 'Arg', -> [$1]
o 'ArgList , Arg', -> $1.concat $3
o 'ArgList OptComma TERMINATOR Arg', -> $1.concat $4
o 'INDENT ArgList OptComma OUTDENT', -> $2
o 'ArgList OptComma INDENT ArgList OptComma OUTDENT', -> $1.concat $4
]
# Valid arguments are Blocks or Splats.
Arg: [
o 'Expression'
o 'Splat'
]
# Just simple, comma-separated, required arguments (no fancy syntax). We need
# this to be separate from the **ArgList** for use in **Switch** blocks, where
# having the newlines wouldn't make sense.
SimpleArgs: [
o 'Expression'
o 'SimpleArgs , Expression', -> [].concat $1, $3
]
# The variants of *try/catch/finally* exception handling blocks.
Try: [
o 'TRY Block', -> new Try $2
o 'TRY Block Catch', -> new Try $2, $3[0], $3[1]
o 'TRY Block FINALLY Block', -> new Try $2, null, null, $4
o 'TRY Block Catch FINALLY Block', -> new Try $2, $3[0], $3[1], $5
]
# A catch clause names its error and runs a block of code.
Catch: [
o 'CATCH Identifier Block', -> [$2, $3]
]
# Throw an exception object.
Throw: [
o 'THROW Expression', -> new Throw $2
]
# Parenthetical expressions. Note that the **Parenthetical** is a **Value**,
# not an **Expression**, so if you need to use an expression in a place
# where only values are accepted, wrapping it in parentheses will always do
# the trick.
Parenthetical: [
o '( Body )', -> new Parens $2
o '( INDENT Body OUTDENT )', -> new Parens $3
]
# The condition portion of a while loop.
WhileSource: [
o 'WHILE Expression', -> new While $2
o 'WHILE Expression WHEN Expression', -> new While $2, guard: $4
o 'UNTIL Expression', -> new While $2, invert: true
o 'UNTIL Expression WHEN Expression', -> new While $2, invert: true, guard: $4
]
# The while loop can either be normal, with a block of expressions to execute,
# or postfix, with a single expression. There is no do..while.
While: [
o 'WhileSource Block', -> $1.addBody $2
o 'Statement WhileSource', -> $2.addBody Block.wrap [$1]
o 'Expression WhileSource', -> $2.addBody Block.wrap [$1]
o 'Loop', -> $1
]
Loop: [
o 'LOOP Block', -> new While(new Literal 'true').addBody $2
o 'LOOP Expression', -> new While(new Literal 'true').addBody Block.wrap [$2]
]
# Array, object, and range comprehensions, at the most generic level.
# Comprehensions can either be normal, with a block of expressions to execute,
# or postfix, with a single expression.
For: [
o 'Statement ForBody', -> new For $1, $2
o 'Expression ForBody', -> new For $1, $2
o 'ForBody Block', -> new For $2, $1
]
ForBody: [
o 'FOR Range', -> source: new Value($2)
o 'ForStart ForSource', -> $2.own = $1.own; $2.name = $1[0]; $2.index = $1[1]; $2
]
ForStart: [
o 'FOR ForVariables', -> $2
o 'FOR OWN ForVariables', -> $3.own = yes; $3
]
# An array of all accepted values for a variable inside the loop.
# This enables support for pattern matching.
ForValue: [
o 'Identifier'
o 'Array', -> new Value $1
o 'Object', -> new Value $1
]
# An array or range comprehension has variables for the current element
# and (optional) reference to the current index. Or, *key, value*, in the case
# of object comprehensions.
ForVariables: [
o 'ForValue', -> [$1]
o 'ForValue , ForValue', -> [$1, $3]
]
# The source of a comprehension is an array or object with an optional guard
# clause. If it's an array comprehension, you can also choose to step through
# in fixed-size increments.
ForSource: [
o 'FORIN Expression', -> source: $2
o 'FOROF Expression', -> source: $2, object: yes
o 'FORIN Expression WHEN Expression', -> source: $2, guard: $4
o 'FOROF Expression WHEN Expression', -> source: $2, guard: $4, object: yes
o 'FORIN Expression BY Expression', -> source: $2, step: $4
o 'FORIN Expression WHEN Expression BY Expression', -> source: $2, guard: $4, step: $6
o 'FORIN Expression BY Expression WHEN Expression', -> source: $2, step: $4, guard: $6
]
Switch: [
o 'SWITCH Expression INDENT Whens OUTDENT', -> new Switch $2, $4
o 'SWITCH Expression INDENT Whens ELSE Block OUTDENT', -> new Switch $2, $4, $6
o 'SWITCH INDENT Whens OUTDENT', -> new Switch null, $3
o 'SWITCH INDENT Whens ELSE Block OUTDENT', -> new Switch null, $3, $5
]
Whens: [
o 'When'
o 'Whens When', -> $1.concat $2
]
# An individual **When** clause, with action.
When: [
o 'LEADING_WHEN SimpleArgs Block', -> [[$2, $3]]
o 'LEADING_WHEN SimpleArgs Block TERMINATOR', -> [[$2, $3]]
]
# The most basic form of *if* is a condition and an action. The following
# if-related rules are broken up along these lines in order to avoid
# ambiguity.
IfBlock: [
o 'IF Expression Block', -> new If $2, $3, type: $1
o 'IfBlock ELSE IF Expression Block', -> $1.addElse new If $4, $5, type: $3
]
# The full complement of *if* expressions, including postfix one-liner
# *if* and *unless*.
If: [
o 'IfBlock'
o 'IfBlock ELSE Block', -> $1.addElse $3
o 'Statement POST_IF Expression', -> new If $3, Block.wrap([$1]), type: $2, statement: true
o 'Expression POST_IF Expression', -> new If $3, Block.wrap([$1]), type: $2, statement: true
]
# Arithmetic and logical operators, working on one or more operands.
# Here they are grouped by order of precedence. The actual precedence rules
# are defined at the bottom of the page. It would be shorter if we could
# combine most of these rules into a single generic *Operand OpSymbol Operand*
# -type rule, but in order to make the precedence binding possible, separate
# rules are necessary.
Operation: [
o 'UNARY Expression', -> new Op $1 , $2
o '- Expression', (-> new Op '-', $2), prec: 'UNARY'
o '+ Expression', (-> new Op '+', $2), prec: 'UNARY'
o '-- SimpleAssignable', -> new Op '--', $2
o '++ SimpleAssignable', -> new Op '++', $2
o 'SimpleAssignable --', -> new Op '--', $1, null, true
o 'SimpleAssignable ++', -> new Op '++', $1, null, true
# [The existential operator](http://jashkenas.github.com/coffee-script/#existence).
o 'Expression ?', -> new Existence $1
o 'Expression + Expression', -> new Op '+' , $1, $3
o 'Expression - Expression', -> new Op '-' , $1, $3
o 'Expression MATH Expression', -> new Op $2, $1, $3
o 'Expression SHIFT Expression', -> new Op $2, $1, $3
o 'Expression COMPARE Expression', -> new Op $2, $1, $3
o 'Expression LOGIC Expression', -> new Op $2, $1, $3
o 'Expression RELATION Expression', ->
if $2.charAt(0) is '!'
new Op($2.slice(1), $1, $3).invert()
else
new Op $2, $1, $3
o 'SimpleAssignable COMPOUND_ASSIGN
Expression', -> new Assign $1, $3, $2
o 'SimpleAssignable COMPOUND_ASSIGN
INDENT Expression OUTDENT', -> new Assign $1, $4, $2
o 'SimpleAssignable EXTENDS Expression', -> new Extends $1, $3
]
# Precedence
# ----------
# Operators at the top of this list have higher precedence than the ones lower
# down. Following these rules is what makes `2 + 3 * 4` parse as:
#
# 2 + (3 * 4)
#
# And not:
#
# (2 + 3) * 4
operators = [
['left', '.', '?.', '::']
['left', 'CALL_START', 'CALL_END']
['nonassoc', '++', '--']
['left', '?']
['right', 'UNARY']
['left', 'MATH']
['left', '+', '-']
['left', 'SHIFT']
['left', 'RELATION']
['left', 'COMPARE']
['left', 'LOGIC']
['nonassoc', 'INDENT', 'OUTDENT']
['right', '=', ':', 'COMPOUND_ASSIGN', 'RETURN', 'THROW', 'EXTENDS']
['right', 'FORIN', 'FOROF', 'BY', 'WHEN']
['right', 'IF', 'ELSE', 'FOR', 'WHILE', 'UNTIL', 'LOOP', 'SUPER', 'CLASS']
['right', 'POST_IF']
]
# Wrapping Up
# -----------
# Finally, now that we have our **grammar** and our **operators**, we can create
# our **Jison.Parser**. We do this by processing all of our rules, recording all
# terminals (every symbol which does not appear as the name of a rule above)
# as "tokens".
tokens = []
for name, alternatives of grammar
grammar[name] = for alt in alternatives
for token in alt[0].split ' '
tokens.push token unless grammar[token]
alt[1] = "return #{alt[1]}" if name is 'Root'
alt
# Initialize the **Parser** with our list of terminal **tokens**, our **grammar**
# rules, and the name of the root. Reverse the operators because Jison orders
# precedence from low to high, and we have it high to low
# (as in [Yacc](http://dinosaur.compilertools.net/yacc/index.html)).
exports.parser = new Parser
tokens : tokens.join ' '
bnf : grammar
operators : operators.reverse()
startSymbol : 'Root'
|
[
{
"context": "-1 or map.indexOf('about:') > -1 then map else key + '?=t' + String(new Date().getTime()).substr(0,8)\n # console.log va",
"end": 9740,
"score": 0.9040820002555847,
"start": 9695,
"tag": "KEY",
"value": "+ '?=t' + String(new Date().getTime()).substr"
... | lib/build.coffee | lmtdit/libder | 3 | fs = require 'fs'
path = require 'path'
_ = require 'lodash'
gulp = require 'gulp'
gutil = require 'gulp-util'
less = require 'gulp-less'
mincss = require 'gulp-minify-css'
plumber = require 'gulp-plumber'
watch = require 'gulp-watch'
server = require('gulp-server-livereload')
setting = require './setting'
color = gutil.colors
_spaceName = setting.spaceName
_modName = setting.modName
###
# base functions
###
Tools =
# md5
md5: (text) ->
crypto.createHash('md5').update(text).digest('hex')
# make dir
mkdirsSync: (dirpath, mode)->
if fs.existsSync(dirpath)
return true
else
if Tools.mkdirsSync path.dirname(dirpath), mode
fs.mkdirSync(dirpath, mode)
return true
errHandler:(e)->
gutil.beep()
gutil.beep()
gutil.log e
htmlMinify:(source)->
return source
.replace(/<!--([\s\S]*?)-->/g, '')
.replace(/\/\*([\s\S]*?)\*\//g, '')
.replace(/^\s+$/g, '')
.replace(/\n/g, '')
.replace(/\t/g, '')
.replace(/\r/g, '')
.replace(/\n\s+/g, ' ')
.replace(/\s+/g, ' ')
.replace(/>([\n\s+]*?)</g,'><')
###
# js 生产文件处理函数
# @param {string} files 接收一个路径参数,同gulp.src
# @param {function} cb 处理过程中,处理一个buffer流的回调
# @param {function} cb2 所有buffer处理完成后的回调函数
###
_paths = {}
class jsCtl
_jsPath: setting.jsPath
_distPath: setting.distPath
amdReg: /define\s*\(([^(]*),?\s*?function\s*\([^\)]*\)\s*\{/
expStr: /define\s*\(([^(]*),?\s*?function/
depArrReg: /^[^\[]*(\[[^\]\[]*\]).*$/
filter:['less','tpl','vendor']
tryEval: (str)->
try
json = eval('(' + str + ')')
catch err
# 过滤依赖表里的关键词,排除空依赖
filterDepMap: (depMap)->
arr = []
filter = ["require", "exports", "module", ""]
for key in depMap
if key not in filter
arr.push key
return arr
# 将绝对路径转换为AMD模块ID
madeModId: (filepath)->
return filepath.replace(/\\/g,'/')
.split("#{_modName}/_src/")[1]
.replace(/.js$/,'')
# 将相对路径转换为AMD模块ID
madeModList: (depArr,curPath)->
_arr = []
# console.log depArr
if depArr.length > 0
for val in depArr
_val = val
if _val.indexOf('../') is 0 or _val.indexOf('./') is 0
_filePath = path.join curPath,_val
_val = @madeModId _filePath
_arr.push _val
return _arr
# 将js数组转字符串
arrToString: (arr)->
_str = ""
if arr.length > 0
_.forEach arr,(val,n)->
_str += (if n > 0 then "," else "") + "'#{val}'"
return "[#{_str}]"
# 给匿名AMD模块添加ID
_stream: (files,cb,cb2)->
_this = @
gulp.src [files]
.pipe plumber({errorHandler: Tools.errrHandler})
.on 'data',(source)->
_list = []
_filePath = source.path.replace(/\\/g,'/')
_nameObj = path.parse _filePath
_modId = _this.madeModId(_filePath)
_source = String(source.contents)
if _filePath.indexOf("/vendor/") is -1
_source = _source.replace _this.amdReg,(str,map)->
_depStr = map.replace _this.depArrReg, "$1"
if /^\[/.test(_depStr)
_arr = _this.tryEval _depStr
try
_arr = _this.filterDepMap(_arr)
# console.log _nameObj
_list = _this.madeModList(_arr,_nameObj.dir)
_str = _this.arrToString _list
return str.replace(_this.expStr, "define('#{_modId}',#{_str},function")
catch error
else
return str.replace(_this.expStr, "define('#{_modId}',function")
# _source = amdclean.clean({
# code:_source
# wrap:null
# })
# console.log _source
cb(_nameObj,_source)
.on 'end',cb2
# 文件写入磁盘
_buildJs: (name,source)->
_file = path.join(@_distPath, name)
Tools.mkdirsSync(path.dirname(_file))
fs.writeFileSync _file, source, 'utf8'
###
# Build AMDmodule with ID
# @param {string} file 同gulp.src接口所接收的参数,默认是js debug目录中的所有js文件
# @param {function} done 回调函数
###
init: (file,done)=>
gutil.log "Build js..."
if typeof file is 'function'
_done = file
_file = @_jsPath + '**/*.js'
else
_file = file or @_jsPath + '**/*.js'
_done = done or ->
_this = @
_num = 0
@_stream(
_file
(obj,source)->
_paths[obj.name] = "dist/#{obj.name}"
_source = source
_dir = obj.dir.split("#{_modName}/_src/")[1]
_distname = obj.name + obj.ext
_dir and (_distname = _dir + '/' + _distname)
_this._buildJs _distname,_source
->
gutil.log 'Build success!'
_done()
)
# 合并AMD模块
combo: (cb)=>
_baseUrl = './'
_main = "_src/#{pkg.name}.js"
_outName = "#{pkg.name}.js"
rjs
baseUrl: _baseUrl
name: _main
out: _outName
.on 'data',(output)->
_source = String(output.contents)
.pipe gulp.dest('./dist/')
.pipe uglify()
.pipe rename({
suffix: ".min",
extname: ".js"
})
.pipe gulp.dest('./dist/')
.on 'end',->
cb and cb()
# 构建方法
build =
# project init
init: ->
init_dir = [
setting.jsPath
setting.imgPath
setting.lessPath
setting.tplPath
# setting.js#{_spaceName}Path
# setting.distPath
]
for _dir in init_dir
Tools.mkdirsSync _dir
gutil.log "#{_dir} made success!"
_mainFile = path.join setting.jsPath,_modName + '.js'
if !fs.existsSync(_mainFile)
_jsData = "define(function(){\n\tvar #{_spaceName} = window.#{_spaceName} || (window.#{_spaceName} = {});\n\t/*code here*/\n\t\n\t#{_spaceName}.#{_modName}=#{_modName};\n\treturn #{_spaceName};\n});"
fs.writeFileSync _mainFile, _jsData, 'utf8'
# 修改package
try
# ...
pkg = require('../package.json')
pkg.name = _modName
pkg.description = setting.desc
pkg.version = setting.version
pkg.main = "dist/#{_modName}.js"
pkg.author =
name: setting.author
email: setting.email
pkg.keywords = [_modName]
_newPkg = JSON.stringify pkg, null, 4
fs.writeFileSync './package.json', _newPkg, 'utf8'
catch e
# ...
gutil.log color.cyan "#{_modName} init success!"
# build paths
paths:(obj)->
_Data = JSON.stringify obj, null, 2
fs.writeFileSync path.join(setting.distPath, "paths.json"), _Data, 'utf8'
gutil.log 'paths.json done!'
# build requireJs config
cfg:(obj)->
config = require '../config.json'
_distPath = setting.distPath
# 读取json配置
myPaths = obj or require '../dist/paths.json'
# 预留给第三方的js插件的接口
shimData = config.shim
jsPaths = config.paths
# 过滤核心库
newPaths = {}
for key,val of jsPaths
if key isnt 'require'
newPaths[key] = val
rCfg =
baseUrl: './'
paths: _.assign newPaths,myPaths
shim: shimData
jsSrcPath = config.jsSrcPath
require_cfg = "require.config(#{JSON.stringify(rCfg, null, 2)});"
fs.writeFileSync path.join('.', "require_cfg.js"), require_cfg, 'utf8'
gutil.log 'require_cfg.js done!'
# build less to js
less2js: (cb)->
_lessPath = setting.lessPath
_less = (lessFile,cb)->
_source = {}
gulp.src(lessFile)
.pipe plumber({errorHandler: Tools.errHandler})
.pipe less
compress: false
.pipe mincss({
keepBreaks:false
compatibility:
properties:
iePrefixHack:true
ieSuffixHack:true
})
.pipe gulp.dest(setting.distPath + "css")
.on 'data',(output)->
_fileName = path.basename(output.path,'.css')
_contents = output.contents.toString()
cssBgReg = /url\s*\(([^\)]+)\)/g
_contents = _contents.replace cssBgReg, (str,map)->
if map.indexOf('fonts/') isnt -1 or map.indexOf('font/') isnt -1 or map.indexOf('#') isnt -1
return str
else
key = map.replace(/(^\'|\")|(\'|\"$)/g, '')
# console.log key
val = if map.indexOf('data:') > -1 or map.indexOf('about:') > -1 then map else key + '?=t' + String(new Date().getTime()).substr(0,8)
# console.log val
return str.replace(map, val)
_source[_fileName] = _contents
.on 'end',->
cb and cb(_source)
_files = []
fs.readdirSync(_lessPath).forEach (f)->
if f.indexOf('.') != 0 and f.indexOf('.less') != -1
_lessFile = path.join(_lessPath, f)
_files.push _lessFile
if _files.length > 0
_less _files,(datas)->
css_source = "define(function(){var #{_spaceName}=window.#{_spaceName}||(window.#{_spaceName}={});#{_spaceName}.#{_modName}Css = #{JSON.stringify(datas)};return #{_spaceName};});"
fs.writeFileSync path.join(setting.jsPath,"#{_modName}Css.js"), css_source, 'utf8'
gutil.log 'lessToCss done!'
cb and cb()
else
gutil.log 'no less todo!'
cb and cb()
# build html tpl to js
tpl2js: (cb)->
_htmlMinify = Tools.htmlMinify
_tplPath = setting.tplPath
tplData = {}
_count = 0
fs.readdirSync(_tplPath).forEach (file)->
_file_path = path.join(_tplPath, file)
if fs.statSync(_file_path).isFile() and file.indexOf('.html') != -1 and file.indexOf('.') != 0
_count++
_fileName = path.basename(file,'.html')
_source = fs.readFileSync(_file_path, 'utf8')
# console.log _fileName
# 压缩html
file_source = Tools.htmlMinify(_source)
if file.indexOf('_') == 0
tplData[_fileName] = "<script id=\"tpl#{_fileName}\" type=\"text/html\">#{file_source}</script>"
else
tplData[_fileName] = file_source
if _count > 0
tpl_soure = "define(function(){var #{_spaceName}=window.#{_spaceName}||(window.#{_spaceName}={});#{_spaceName}.#{_modName}Tpl = #{JSON.stringify(tplData)};return #{_spaceName};});"
fs.writeFileSync path.join(setting.jsPath,"#{_modName}Tpl.js"), tpl_soure, 'utf8'
gutil.log 'tplTojs done!'
else
gutil.log 'no tpl todo!'
cb and cb()
# build js to dist dir
img2dist:(cb)->
_this = @
_cb = cb or ->
_imgPath = setting.imgPath
gulp.src(_imgPath + '*.*')
.pipe gulp.dest(setting.distPath + 'img')
.on "end",->
_cb()
# build js to dist dir
js2dist:(cb)->
_this = @
_cb = cb or ->
new jsCtl().init ->
# console.log _paths
_this.paths(_paths)
_this.cfg(_paths)
_cb()
_getType:(dir)->
type = ''
if dir.indexOf('_tpl') > 0
type = 'tpl'
else if dir.indexOf('_less') > 0
type = 'less'
else
type = 'js'
return type
watch:->
_this = @
_watchFiles = setting.watchFiles
watch _watchFiles,(file)->
try
_event = file.event
if _event isnt 'undefined'
_file_path = file.path.replace(/\\/g,'/')
_parse = path.parse _file_path
# console.log _parse
_type = _this._getType(_parse.dir)
switch _type
when 'js'
new jsCtl().init()
when 'less'
_this.less2js()
when 'tpl'
_this.tpl2js()
catch err
console.log err
server:->
appPath = setting.root
gulp.src(appPath)
.pipe server
livereload: false,
directoryListing: true,
open: true
host: 'localhost'
port: 8800
exports.setting = setting
# exports.Tools = Tools
exports.build = build | 63683 | fs = require 'fs'
path = require 'path'
_ = require 'lodash'
gulp = require 'gulp'
gutil = require 'gulp-util'
less = require 'gulp-less'
mincss = require 'gulp-minify-css'
plumber = require 'gulp-plumber'
watch = require 'gulp-watch'
server = require('gulp-server-livereload')
setting = require './setting'
color = gutil.colors
_spaceName = setting.spaceName
_modName = setting.modName
###
# base functions
###
Tools =
# md5
md5: (text) ->
crypto.createHash('md5').update(text).digest('hex')
# make dir
mkdirsSync: (dirpath, mode)->
if fs.existsSync(dirpath)
return true
else
if Tools.mkdirsSync path.dirname(dirpath), mode
fs.mkdirSync(dirpath, mode)
return true
errHandler:(e)->
gutil.beep()
gutil.beep()
gutil.log e
htmlMinify:(source)->
return source
.replace(/<!--([\s\S]*?)-->/g, '')
.replace(/\/\*([\s\S]*?)\*\//g, '')
.replace(/^\s+$/g, '')
.replace(/\n/g, '')
.replace(/\t/g, '')
.replace(/\r/g, '')
.replace(/\n\s+/g, ' ')
.replace(/\s+/g, ' ')
.replace(/>([\n\s+]*?)</g,'><')
###
# js 生产文件处理函数
# @param {string} files 接收一个路径参数,同gulp.src
# @param {function} cb 处理过程中,处理一个buffer流的回调
# @param {function} cb2 所有buffer处理完成后的回调函数
###
_paths = {}
class jsCtl
_jsPath: setting.jsPath
_distPath: setting.distPath
amdReg: /define\s*\(([^(]*),?\s*?function\s*\([^\)]*\)\s*\{/
expStr: /define\s*\(([^(]*),?\s*?function/
depArrReg: /^[^\[]*(\[[^\]\[]*\]).*$/
filter:['less','tpl','vendor']
tryEval: (str)->
try
json = eval('(' + str + ')')
catch err
# 过滤依赖表里的关键词,排除空依赖
filterDepMap: (depMap)->
arr = []
filter = ["require", "exports", "module", ""]
for key in depMap
if key not in filter
arr.push key
return arr
# 将绝对路径转换为AMD模块ID
madeModId: (filepath)->
return filepath.replace(/\\/g,'/')
.split("#{_modName}/_src/")[1]
.replace(/.js$/,'')
# 将相对路径转换为AMD模块ID
madeModList: (depArr,curPath)->
_arr = []
# console.log depArr
if depArr.length > 0
for val in depArr
_val = val
if _val.indexOf('../') is 0 or _val.indexOf('./') is 0
_filePath = path.join curPath,_val
_val = @madeModId _filePath
_arr.push _val
return _arr
# 将js数组转字符串
arrToString: (arr)->
_str = ""
if arr.length > 0
_.forEach arr,(val,n)->
_str += (if n > 0 then "," else "") + "'#{val}'"
return "[#{_str}]"
# 给匿名AMD模块添加ID
_stream: (files,cb,cb2)->
_this = @
gulp.src [files]
.pipe plumber({errorHandler: Tools.errrHandler})
.on 'data',(source)->
_list = []
_filePath = source.path.replace(/\\/g,'/')
_nameObj = path.parse _filePath
_modId = _this.madeModId(_filePath)
_source = String(source.contents)
if _filePath.indexOf("/vendor/") is -1
_source = _source.replace _this.amdReg,(str,map)->
_depStr = map.replace _this.depArrReg, "$1"
if /^\[/.test(_depStr)
_arr = _this.tryEval _depStr
try
_arr = _this.filterDepMap(_arr)
# console.log _nameObj
_list = _this.madeModList(_arr,_nameObj.dir)
_str = _this.arrToString _list
return str.replace(_this.expStr, "define('#{_modId}',#{_str},function")
catch error
else
return str.replace(_this.expStr, "define('#{_modId}',function")
# _source = amdclean.clean({
# code:_source
# wrap:null
# })
# console.log _source
cb(_nameObj,_source)
.on 'end',cb2
# 文件写入磁盘
_buildJs: (name,source)->
_file = path.join(@_distPath, name)
Tools.mkdirsSync(path.dirname(_file))
fs.writeFileSync _file, source, 'utf8'
###
# Build AMDmodule with ID
# @param {string} file 同gulp.src接口所接收的参数,默认是js debug目录中的所有js文件
# @param {function} done 回调函数
###
init: (file,done)=>
gutil.log "Build js..."
if typeof file is 'function'
_done = file
_file = @_jsPath + '**/*.js'
else
_file = file or @_jsPath + '**/*.js'
_done = done or ->
_this = @
_num = 0
@_stream(
_file
(obj,source)->
_paths[obj.name] = "dist/#{obj.name}"
_source = source
_dir = obj.dir.split("#{_modName}/_src/")[1]
_distname = obj.name + obj.ext
_dir and (_distname = _dir + '/' + _distname)
_this._buildJs _distname,_source
->
gutil.log 'Build success!'
_done()
)
# 合并AMD模块
combo: (cb)=>
_baseUrl = './'
_main = "_src/#{pkg.name}.js"
_outName = "#{pkg.name}.js"
rjs
baseUrl: _baseUrl
name: _main
out: _outName
.on 'data',(output)->
_source = String(output.contents)
.pipe gulp.dest('./dist/')
.pipe uglify()
.pipe rename({
suffix: ".min",
extname: ".js"
})
.pipe gulp.dest('./dist/')
.on 'end',->
cb and cb()
# 构建方法
build =
# project init
init: ->
init_dir = [
setting.jsPath
setting.imgPath
setting.lessPath
setting.tplPath
# setting.js#{_spaceName}Path
# setting.distPath
]
for _dir in init_dir
Tools.mkdirsSync _dir
gutil.log "#{_dir} made success!"
_mainFile = path.join setting.jsPath,_modName + '.js'
if !fs.existsSync(_mainFile)
_jsData = "define(function(){\n\tvar #{_spaceName} = window.#{_spaceName} || (window.#{_spaceName} = {});\n\t/*code here*/\n\t\n\t#{_spaceName}.#{_modName}=#{_modName};\n\treturn #{_spaceName};\n});"
fs.writeFileSync _mainFile, _jsData, 'utf8'
# 修改package
try
# ...
pkg = require('../package.json')
pkg.name = _modName
pkg.description = setting.desc
pkg.version = setting.version
pkg.main = "dist/#{_modName}.js"
pkg.author =
name: setting.author
email: setting.email
pkg.keywords = [_modName]
_newPkg = JSON.stringify pkg, null, 4
fs.writeFileSync './package.json', _newPkg, 'utf8'
catch e
# ...
gutil.log color.cyan "#{_modName} init success!"
# build paths
paths:(obj)->
_Data = JSON.stringify obj, null, 2
fs.writeFileSync path.join(setting.distPath, "paths.json"), _Data, 'utf8'
gutil.log 'paths.json done!'
# build requireJs config
cfg:(obj)->
config = require '../config.json'
_distPath = setting.distPath
# 读取json配置
myPaths = obj or require '../dist/paths.json'
# 预留给第三方的js插件的接口
shimData = config.shim
jsPaths = config.paths
# 过滤核心库
newPaths = {}
for key,val of jsPaths
if key isnt 'require'
newPaths[key] = val
rCfg =
baseUrl: './'
paths: _.assign newPaths,myPaths
shim: shimData
jsSrcPath = config.jsSrcPath
require_cfg = "require.config(#{JSON.stringify(rCfg, null, 2)});"
fs.writeFileSync path.join('.', "require_cfg.js"), require_cfg, 'utf8'
gutil.log 'require_cfg.js done!'
# build less to js
less2js: (cb)->
_lessPath = setting.lessPath
_less = (lessFile,cb)->
_source = {}
gulp.src(lessFile)
.pipe plumber({errorHandler: Tools.errHandler})
.pipe less
compress: false
.pipe mincss({
keepBreaks:false
compatibility:
properties:
iePrefixHack:true
ieSuffixHack:true
})
.pipe gulp.dest(setting.distPath + "css")
.on 'data',(output)->
_fileName = path.basename(output.path,'.css')
_contents = output.contents.toString()
cssBgReg = /url\s*\(([^\)]+)\)/g
_contents = _contents.replace cssBgReg, (str,map)->
if map.indexOf('fonts/') isnt -1 or map.indexOf('font/') isnt -1 or map.indexOf('#') isnt -1
return str
else
key = map.replace(/(^\'|\")|(\'|\"$)/g, '')
# console.log key
val = if map.indexOf('data:') > -1 or map.indexOf('about:') > -1 then map else key <KEY>(0,8)
# console.log val
return str.replace(map, val)
_source[_fileName] = _contents
.on 'end',->
cb and cb(_source)
_files = []
fs.readdirSync(_lessPath).forEach (f)->
if f.indexOf('.') != 0 and f.indexOf('.less') != -1
_lessFile = path.join(_lessPath, f)
_files.push _lessFile
if _files.length > 0
_less _files,(datas)->
css_source = "define(function(){var #{_spaceName}=window.#{_spaceName}||(window.#{_spaceName}={});#{_spaceName}.#{_modName}Css = #{JSON.stringify(datas)};return #{_spaceName};});"
fs.writeFileSync path.join(setting.jsPath,"#{_modName}Css.js"), css_source, 'utf8'
gutil.log 'lessToCss done!'
cb and cb()
else
gutil.log 'no less todo!'
cb and cb()
# build html tpl to js
tpl2js: (cb)->
_htmlMinify = Tools.htmlMinify
_tplPath = setting.tplPath
tplData = {}
_count = 0
fs.readdirSync(_tplPath).forEach (file)->
_file_path = path.join(_tplPath, file)
if fs.statSync(_file_path).isFile() and file.indexOf('.html') != -1 and file.indexOf('.') != 0
_count++
_fileName = path.basename(file,'.html')
_source = fs.readFileSync(_file_path, 'utf8')
# console.log _fileName
# 压缩html
file_source = Tools.htmlMinify(_source)
if file.indexOf('_') == 0
tplData[_fileName] = "<script id=\"tpl#{_fileName}\" type=\"text/html\">#{file_source}</script>"
else
tplData[_fileName] = file_source
if _count > 0
tpl_soure = "define(function(){var #{_spaceName}=window.#{_spaceName}||(window.#{_spaceName}={});#{_spaceName}.#{_modName}Tpl = #{JSON.stringify(tplData)};return #{_spaceName};});"
fs.writeFileSync path.join(setting.jsPath,"#{_modName}Tpl.js"), tpl_soure, 'utf8'
gutil.log 'tplTojs done!'
else
gutil.log 'no tpl todo!'
cb and cb()
# build js to dist dir
img2dist:(cb)->
_this = @
_cb = cb or ->
_imgPath = setting.imgPath
gulp.src(_imgPath + '*.*')
.pipe gulp.dest(setting.distPath + 'img')
.on "end",->
_cb()
# build js to dist dir
js2dist:(cb)->
_this = @
_cb = cb or ->
new jsCtl().init ->
# console.log _paths
_this.paths(_paths)
_this.cfg(_paths)
_cb()
_getType:(dir)->
type = ''
if dir.indexOf('_tpl') > 0
type = 'tpl'
else if dir.indexOf('_less') > 0
type = 'less'
else
type = 'js'
return type
watch:->
_this = @
_watchFiles = setting.watchFiles
watch _watchFiles,(file)->
try
_event = file.event
if _event isnt 'undefined'
_file_path = file.path.replace(/\\/g,'/')
_parse = path.parse _file_path
# console.log _parse
_type = _this._getType(_parse.dir)
switch _type
when 'js'
new jsCtl().init()
when 'less'
_this.less2js()
when 'tpl'
_this.tpl2js()
catch err
console.log err
server:->
appPath = setting.root
gulp.src(appPath)
.pipe server
livereload: false,
directoryListing: true,
open: true
host: 'localhost'
port: 8800
exports.setting = setting
# exports.Tools = Tools
exports.build = build | true | fs = require 'fs'
path = require 'path'
_ = require 'lodash'
gulp = require 'gulp'
gutil = require 'gulp-util'
less = require 'gulp-less'
mincss = require 'gulp-minify-css'
plumber = require 'gulp-plumber'
watch = require 'gulp-watch'
server = require('gulp-server-livereload')
setting = require './setting'
color = gutil.colors
_spaceName = setting.spaceName
_modName = setting.modName
###
# base functions
###
Tools =
# md5
md5: (text) ->
crypto.createHash('md5').update(text).digest('hex')
# make dir
mkdirsSync: (dirpath, mode)->
if fs.existsSync(dirpath)
return true
else
if Tools.mkdirsSync path.dirname(dirpath), mode
fs.mkdirSync(dirpath, mode)
return true
errHandler:(e)->
gutil.beep()
gutil.beep()
gutil.log e
htmlMinify:(source)->
return source
.replace(/<!--([\s\S]*?)-->/g, '')
.replace(/\/\*([\s\S]*?)\*\//g, '')
.replace(/^\s+$/g, '')
.replace(/\n/g, '')
.replace(/\t/g, '')
.replace(/\r/g, '')
.replace(/\n\s+/g, ' ')
.replace(/\s+/g, ' ')
.replace(/>([\n\s+]*?)</g,'><')
###
# js 生产文件处理函数
# @param {string} files 接收一个路径参数,同gulp.src
# @param {function} cb 处理过程中,处理一个buffer流的回调
# @param {function} cb2 所有buffer处理完成后的回调函数
###
_paths = {}
class jsCtl
_jsPath: setting.jsPath
_distPath: setting.distPath
amdReg: /define\s*\(([^(]*),?\s*?function\s*\([^\)]*\)\s*\{/
expStr: /define\s*\(([^(]*),?\s*?function/
depArrReg: /^[^\[]*(\[[^\]\[]*\]).*$/
filter:['less','tpl','vendor']
tryEval: (str)->
try
json = eval('(' + str + ')')
catch err
# 过滤依赖表里的关键词,排除空依赖
filterDepMap: (depMap)->
arr = []
filter = ["require", "exports", "module", ""]
for key in depMap
if key not in filter
arr.push key
return arr
# 将绝对路径转换为AMD模块ID
madeModId: (filepath)->
return filepath.replace(/\\/g,'/')
.split("#{_modName}/_src/")[1]
.replace(/.js$/,'')
# 将相对路径转换为AMD模块ID
madeModList: (depArr,curPath)->
_arr = []
# console.log depArr
if depArr.length > 0
for val in depArr
_val = val
if _val.indexOf('../') is 0 or _val.indexOf('./') is 0
_filePath = path.join curPath,_val
_val = @madeModId _filePath
_arr.push _val
return _arr
# 将js数组转字符串
arrToString: (arr)->
_str = ""
if arr.length > 0
_.forEach arr,(val,n)->
_str += (if n > 0 then "," else "") + "'#{val}'"
return "[#{_str}]"
# 给匿名AMD模块添加ID
_stream: (files,cb,cb2)->
_this = @
gulp.src [files]
.pipe plumber({errorHandler: Tools.errrHandler})
.on 'data',(source)->
_list = []
_filePath = source.path.replace(/\\/g,'/')
_nameObj = path.parse _filePath
_modId = _this.madeModId(_filePath)
_source = String(source.contents)
if _filePath.indexOf("/vendor/") is -1
_source = _source.replace _this.amdReg,(str,map)->
_depStr = map.replace _this.depArrReg, "$1"
if /^\[/.test(_depStr)
_arr = _this.tryEval _depStr
try
_arr = _this.filterDepMap(_arr)
# console.log _nameObj
_list = _this.madeModList(_arr,_nameObj.dir)
_str = _this.arrToString _list
return str.replace(_this.expStr, "define('#{_modId}',#{_str},function")
catch error
else
return str.replace(_this.expStr, "define('#{_modId}',function")
# _source = amdclean.clean({
# code:_source
# wrap:null
# })
# console.log _source
cb(_nameObj,_source)
.on 'end',cb2
# 文件写入磁盘
_buildJs: (name,source)->
_file = path.join(@_distPath, name)
Tools.mkdirsSync(path.dirname(_file))
fs.writeFileSync _file, source, 'utf8'
###
# Build AMDmodule with ID
# @param {string} file 同gulp.src接口所接收的参数,默认是js debug目录中的所有js文件
# @param {function} done 回调函数
###
init: (file,done)=>
gutil.log "Build js..."
if typeof file is 'function'
_done = file
_file = @_jsPath + '**/*.js'
else
_file = file or @_jsPath + '**/*.js'
_done = done or ->
_this = @
_num = 0
@_stream(
_file
(obj,source)->
_paths[obj.name] = "dist/#{obj.name}"
_source = source
_dir = obj.dir.split("#{_modName}/_src/")[1]
_distname = obj.name + obj.ext
_dir and (_distname = _dir + '/' + _distname)
_this._buildJs _distname,_source
->
gutil.log 'Build success!'
_done()
)
# 合并AMD模块
combo: (cb)=>
_baseUrl = './'
_main = "_src/#{pkg.name}.js"
_outName = "#{pkg.name}.js"
rjs
baseUrl: _baseUrl
name: _main
out: _outName
.on 'data',(output)->
_source = String(output.contents)
.pipe gulp.dest('./dist/')
.pipe uglify()
.pipe rename({
suffix: ".min",
extname: ".js"
})
.pipe gulp.dest('./dist/')
.on 'end',->
cb and cb()
# 构建方法
build =
# project init
init: ->
init_dir = [
setting.jsPath
setting.imgPath
setting.lessPath
setting.tplPath
# setting.js#{_spaceName}Path
# setting.distPath
]
for _dir in init_dir
Tools.mkdirsSync _dir
gutil.log "#{_dir} made success!"
_mainFile = path.join setting.jsPath,_modName + '.js'
if !fs.existsSync(_mainFile)
_jsData = "define(function(){\n\tvar #{_spaceName} = window.#{_spaceName} || (window.#{_spaceName} = {});\n\t/*code here*/\n\t\n\t#{_spaceName}.#{_modName}=#{_modName};\n\treturn #{_spaceName};\n});"
fs.writeFileSync _mainFile, _jsData, 'utf8'
# 修改package
try
# ...
pkg = require('../package.json')
pkg.name = _modName
pkg.description = setting.desc
pkg.version = setting.version
pkg.main = "dist/#{_modName}.js"
pkg.author =
name: setting.author
email: setting.email
pkg.keywords = [_modName]
_newPkg = JSON.stringify pkg, null, 4
fs.writeFileSync './package.json', _newPkg, 'utf8'
catch e
# ...
gutil.log color.cyan "#{_modName} init success!"
# build paths
paths:(obj)->
_Data = JSON.stringify obj, null, 2
fs.writeFileSync path.join(setting.distPath, "paths.json"), _Data, 'utf8'
gutil.log 'paths.json done!'
# build requireJs config
cfg:(obj)->
config = require '../config.json'
_distPath = setting.distPath
# 读取json配置
myPaths = obj or require '../dist/paths.json'
# 预留给第三方的js插件的接口
shimData = config.shim
jsPaths = config.paths
# 过滤核心库
newPaths = {}
for key,val of jsPaths
if key isnt 'require'
newPaths[key] = val
rCfg =
baseUrl: './'
paths: _.assign newPaths,myPaths
shim: shimData
jsSrcPath = config.jsSrcPath
require_cfg = "require.config(#{JSON.stringify(rCfg, null, 2)});"
fs.writeFileSync path.join('.', "require_cfg.js"), require_cfg, 'utf8'
gutil.log 'require_cfg.js done!'
# build less to js
less2js: (cb)->
_lessPath = setting.lessPath
_less = (lessFile,cb)->
_source = {}
gulp.src(lessFile)
.pipe plumber({errorHandler: Tools.errHandler})
.pipe less
compress: false
.pipe mincss({
keepBreaks:false
compatibility:
properties:
iePrefixHack:true
ieSuffixHack:true
})
.pipe gulp.dest(setting.distPath + "css")
.on 'data',(output)->
_fileName = path.basename(output.path,'.css')
_contents = output.contents.toString()
cssBgReg = /url\s*\(([^\)]+)\)/g
_contents = _contents.replace cssBgReg, (str,map)->
if map.indexOf('fonts/') isnt -1 or map.indexOf('font/') isnt -1 or map.indexOf('#') isnt -1
return str
else
key = map.replace(/(^\'|\")|(\'|\"$)/g, '')
# console.log key
val = if map.indexOf('data:') > -1 or map.indexOf('about:') > -1 then map else key PI:KEY:<KEY>END_PI(0,8)
# console.log val
return str.replace(map, val)
_source[_fileName] = _contents
.on 'end',->
cb and cb(_source)
_files = []
fs.readdirSync(_lessPath).forEach (f)->
if f.indexOf('.') != 0 and f.indexOf('.less') != -1
_lessFile = path.join(_lessPath, f)
_files.push _lessFile
if _files.length > 0
_less _files,(datas)->
css_source = "define(function(){var #{_spaceName}=window.#{_spaceName}||(window.#{_spaceName}={});#{_spaceName}.#{_modName}Css = #{JSON.stringify(datas)};return #{_spaceName};});"
fs.writeFileSync path.join(setting.jsPath,"#{_modName}Css.js"), css_source, 'utf8'
gutil.log 'lessToCss done!'
cb and cb()
else
gutil.log 'no less todo!'
cb and cb()
# build html tpl to js
tpl2js: (cb)->
_htmlMinify = Tools.htmlMinify
_tplPath = setting.tplPath
tplData = {}
_count = 0
fs.readdirSync(_tplPath).forEach (file)->
_file_path = path.join(_tplPath, file)
if fs.statSync(_file_path).isFile() and file.indexOf('.html') != -1 and file.indexOf('.') != 0
_count++
_fileName = path.basename(file,'.html')
_source = fs.readFileSync(_file_path, 'utf8')
# console.log _fileName
# 压缩html
file_source = Tools.htmlMinify(_source)
if file.indexOf('_') == 0
tplData[_fileName] = "<script id=\"tpl#{_fileName}\" type=\"text/html\">#{file_source}</script>"
else
tplData[_fileName] = file_source
if _count > 0
tpl_soure = "define(function(){var #{_spaceName}=window.#{_spaceName}||(window.#{_spaceName}={});#{_spaceName}.#{_modName}Tpl = #{JSON.stringify(tplData)};return #{_spaceName};});"
fs.writeFileSync path.join(setting.jsPath,"#{_modName}Tpl.js"), tpl_soure, 'utf8'
gutil.log 'tplTojs done!'
else
gutil.log 'no tpl todo!'
cb and cb()
# build js to dist dir
img2dist:(cb)->
_this = @
_cb = cb or ->
_imgPath = setting.imgPath
gulp.src(_imgPath + '*.*')
.pipe gulp.dest(setting.distPath + 'img')
.on "end",->
_cb()
# build js to dist dir
js2dist:(cb)->
_this = @
_cb = cb or ->
new jsCtl().init ->
# console.log _paths
_this.paths(_paths)
_this.cfg(_paths)
_cb()
_getType:(dir)->
type = ''
if dir.indexOf('_tpl') > 0
type = 'tpl'
else if dir.indexOf('_less') > 0
type = 'less'
else
type = 'js'
return type
watch:->
_this = @
_watchFiles = setting.watchFiles
watch _watchFiles,(file)->
try
_event = file.event
if _event isnt 'undefined'
_file_path = file.path.replace(/\\/g,'/')
_parse = path.parse _file_path
# console.log _parse
_type = _this._getType(_parse.dir)
switch _type
when 'js'
new jsCtl().init()
when 'less'
_this.less2js()
when 'tpl'
_this.tpl2js()
catch err
console.log err
server:->
appPath = setting.root
gulp.src(appPath)
.pipe server
livereload: false,
directoryListing: true,
open: true
host: 'localhost'
port: 8800
exports.setting = setting
# exports.Tools = Tools
exports.build = build |
[
{
"context": "ocalhost:27017/rialtoir'\n session:\n secret: 'koolcat'\n key: 'watlol'\n port: 9090\n pubdir: join __",
"end": 121,
"score": 0.7056816816329956,
"start": 115,
"tag": "KEY",
"value": "oolcat"
},
{
"context": "ltoir'\n session:\n secret: 'koolcat'\n key: ... | server/config/default.coffee | stevelacy/rialtoir-server | 0 | {join} = require 'path'
module.exports =
database: 'mongodb://localhost:27017/rialtoir'
session:
secret: 'koolcat'
key: 'watlol'
port: 9090
pubdir: join __dirname, '../../public'
redis:
host: 'localhost'
pass: ''
dbIndex: 12
port: 6379
| 57435 | {join} = require 'path'
module.exports =
database: 'mongodb://localhost:27017/rialtoir'
session:
secret: 'k<KEY>'
key: '<KEY>'
port: 9090
pubdir: join __dirname, '../../public'
redis:
host: 'localhost'
pass: ''
dbIndex: 12
port: 6379
| true | {join} = require 'path'
module.exports =
database: 'mongodb://localhost:27017/rialtoir'
session:
secret: 'kPI:KEY:<KEY>END_PI'
key: 'PI:KEY:<KEY>END_PI'
port: 9090
pubdir: join __dirname, '../../public'
redis:
host: 'localhost'
pass: ''
dbIndex: 12
port: 6379
|
[
{
"context": " cookie name (key)\n @_sessionConf.key or= \"connect.sid\"\n\n # supported stores: memory, redis (memc",
"end": 4096,
"score": 0.9832456111907959,
"start": 4085,
"tag": "KEY",
"value": "connect.sid"
}
] | src/server/conf/conf.coffee | LaPingvino/rizzoma | 88 | fs = require('fs-plus')
_ = require('underscore')
express = require('express')
everycache = require('everycache')
swig = require('swig')
path = require('path')
winston = require('winston')
CategoriedStdoutLogger = require('../common/logger/categoried_stdout').CategoriedStdoutLogger
StrUtils = require('../../share/utils/string')
class Conf
###
Окружение, в котором запущен сервер: хранение настроек, методы для работы с ними, возвращение соединений с БД и т.д.
###
constructor: (@settings) ->
@_db = {}
@_loggerConf = @_initLogger()
@_caches = {}
@_version = null
# пул логгеров
@_loggers = {}
# Настройка шаблонизатора
swig.init
allowErrors: true,
autoescape: true,
encoding: 'utf8',
filters: require('../templates/filters'),
tags: {},
extensions: {},
tzOffset: 0
root: @getTemplateRootDir()
getTemplateRootDir: () =>
versionedTemplatesRootDir = path.join(__dirname, '/../../../lib/templates')
if fs.existsSync(versionedTemplatesRootDir)
return versionedTemplatesRootDir
return path.join(__dirname, '/../templates')
getTemplate: () ->
###
Возвращает обеъект шаблонизатора. У него есть методы compileFile(filename), compileString(templateString)
@return swig
###
return swig
get: (key) ->
###
Возвращает значение из конфига по ключу (только первый уровень объекта конфигурации).
@param {String} key ключ конфига
###
if key of @settings
return @settings[key]
else
throw new Error("No #{key} in settings")
getDbConf: (connName) ->
###
Возвращает настройки для указанного соединения с БД.
@param {String} connName название соединения в конфиге
###
conf = @get('db')
if connName not of conf
throw new Error("No settings for db connection '#{connName}'")
return conf[connName]
getDb: (connName) ->
###
Возвращает соединение с БД.
При первом обращении создает это соединение.
@param {String} connName название соединения в конфиге
TODO: выделить метод getDbConnection, чтобы можно было доступиться к методам работы с сервером БД
TODO: вынести все методы работы с БД из Conf в отдельный модуль
###
dbConf = @getDbConf(connName)
return @_db[connName] if @_db[connName]
if dbConf.type == 'cradle'
cradle = require('cradle')
connection = new cradle.Connection("#{dbConf.protocol}://#{dbConf.hostname}", dbConf.port, dbConf.options)
return @_db[connName] = connection.database(dbConf.db)
else
throw new Error("Unknown db type #{dbConf.type}")
getDbUrl: (connName) ->
###
Возвращает строку коннекта к базе данных (URL), формат отличается в зависимости от типа базы данных.
@param {String} connName название соединения в конфиге
###
dbConf = @getDbConf(connName)
if dbConf.type == 'cradle'
u =
protocol: dbConf.protocol
hostname: dbConf.hostname
port: dbConf.port
pathname: dbConf.db
if dbConf.options.auth
u.auth = "#{dbConf.options.auth.username}:#{dbConf.options.auth.password}"
return require('url').format(u)
else
throw new Error("Unknown db type #{dbConf.type}")
getSessionConf: () ->
###
Возвращает параметры для connect's session middleware, инициализирует хранилище для сессий
@return: object
###
return @_sessionConf if @_sessionConf
@_sessionConf = @get('session')
@_sessionConf.cookie.maxAge *= 1000 if @_sessionConf.cookie.maxAge
@_sessionConf.refreshInterval = @_sessionConf.refreshInterval*1000
# session cookie name (key)
@_sessionConf.key or= "connect.sid"
# supported stores: memory, redis (memcache and others can be added)
@_sessionConf.storeType or= "memory"
switch @_sessionConf.storeType
when "memory"
@_sessionConf.store = new(require('express').session.MemoryStore)
when "redis"
RedisStore = require('connect-redis')(require('express'))
@_sessionConf.store = new RedisStore(@_sessionConf.storeOptions || {})
else
throw new Error("Unsupported connect session store type: #{@_sessionConf.storeType}")
# fingerprint по умолчанию возвращает user-agent, однако мы хотим использовать
# сессии в websocket-соединениях, в которых user-agent не передается
@_sessionConf.fingerprint = -> ''
return @_sessionConf
getCache: (type) ->
cache = @_caches[type]
return cache if cache
try
settings = @get('cache')[type]
throw new Error("No settings for cache type '#{type}'") if not settings
catch err
#process.stderr.write(err)
return null
try
cache = everycache.getCache(settings)
catch err
#process.stderr.write(err)
return null
return @_caches[type] = cache
getSearchConf: () ->
###
Возвращает параметры для поискового сервера.
###
return @get('search')
getSearchIndexerConf: () ->
###
Возвращает параметры для поискового сервера.
###
return @get('searchIndexer')
getSphinxIndexPrefix: () ->
return @getSearchIndexerConf().indexPrefix or 'dev'
getSearchPlugins: () ->
###
Возвращает параметры плагинов для поиска.
###
return @get('searchPlugins')
getAmqpConf: () ->
###
Настройки для подключения к AMQP брокеру.
###
return @get('amqpConnect')
getOtConf: () ->
###
Настройки для ot процессора.
###
otConf = @get('ot')
#Суффикс для имени очереди, которую слушает процесс.
#Необходимо обеспечить уникальные названия очередей для каждого процесса, но эти названия не должны меняться при
#перезапуске процесса. FRONTEND_QUEUE_SUFFIX - нужна только процессам, обслуживающим подписки пользователей.
otConf.frontendQueueSuffix = process.env.FRONTEND_QUEUE_SUFFIX
range = process.env.BACKEND_ID_RANGE
otConf.backendIdRange = _.uniq(range.split(',')) if range
return otConf
setServerAsOtBackend: () ->
@get('ot').isBackend = true
getAppListenPort: () ->
###
Возвращает порт, на котором должен принимать соединения HTTP-сервер.
Значение берется из переменной окружения LISTEN_PORT, из настроек (app.listen_port),
или возвращает значение по умолчанию (8000).
###
return process.env.LISTEN_PORT || @get('app').listenPort || 8000
getAppRoles: () ->
###
Возвращает список ролей, с которыми было запущено приложение.
Значения берутся из переменной окружения APP_ROLES, разделены запятыми.
По умолчанию возвращает ["default"].
@return: array
###
return (process.env.APP_ROLES || "default").split(',')
getAppName: () ->
###
Возвращает название приложения, берется из переменной окружения
###
return process.env.APP_NAME
getWaveUrl: () ->
return @get('app').waveUrl
getWaveEmbeddedUrl: ->
return @get('app').waveEmbeddedUrl
getWaveDriveUrl: ->
return @get('app').waveDriveUrl
getTagSearchUrl: ->
return '/tag/'
getLoggerConf: () ->
log_config = @get('logger')
if process.env.LOG_LEVEL and process.env.LOG_LEVEL != ''
log_config.logLevel = process.env.LOG_LEVEL
return log_config
getGeneratorConf: () ->
return @get('generator')
getAuthConf: () ->
return @get('auth')
getVersionInfo: () =>
###
Версия запущенного приложения, название бранча, время билда.
###
return @_version unless @_version is null
@_version = {}
try
version = require('../version')
if version
{version, branch} = version
branch = branch?.replace(/^trunk$|^master$|^[\d_]+/, "") # simplify branch name
branch = if branch then "/#{branch}" else ""
versionString = "#{version or "-"}#{branch}"
@_version = {version, branch, versionString}
return @_version
getVersion: () =>
###
Версия запущенного приложения
@returns string
###
return @getVersionInfo().version || ''
_initLogger: () ->
###
Инициализируем конфиг логгера
###
return @getLoggerConf()
getLogger: (loggerName=@_loggerConf.defaultLoggerName) ->
###
logger
###
return @_loggers[loggerName] if @_loggers[loggerName]
transports = null
if @_loggerConf.transports
transports = @_loggerConf.transports[loggerName]
transports = @_loggerConf.transports["*"] if not transports
# по умолчанию добавим наш логгер в стдаут
if not transports or not transports.length
transports = [{
transportClass: CategoriedStdoutLogger
colorize: true
loggerNameField: 'category'
}]
logLevel = @_loggerConf.logLevel.toLowerCase()
opts = { transports: [] }
for topts in transports
ttopts = _.clone(topts)
transportClass = topts.transportClass
delete ttopts.transportClass
ttopts.level = logLevel
if topts.loggerNameField
facility = loggerName
appName = @getAppName()
if topts.appInfo
facility = "#{appName}.#{facility}" if appName
ttopts["facilityApp"] = appName
ttopts["facilityCategory"] = loggerName
ttopts["facilityPid"] = process.pid
ttopts[topts.loggerNameField] = facility
delete ttopts.loggerNameField
opts.transports.push(new transportClass(ttopts))
logger = winston.loggers.add(loggerName, opts)
logger.setLevels(winston.config.syslog.levels)
logger.level = logLevel
logger.warn = logger.warning
@_loggers[loggerName] = logger
return logger
getAuthSourceConf: (source) ->
return @get('auth')[source]
getStorageProcessor: (client)->
filesConf = @get('files')
switch filesConf.type
when 'local'
LocalStorageProcessor = require('../file/local/processor').LocalStorageProcessor
return new LocalStorageProcessor()
when 's3'
s3Conf = filesConf.s3
bucketName = s3Conf.buckets?[client]
throw new Error('Missing S3 tokens') if not s3Conf or not s3Conf.accessKeyId or
not s3Conf.secretAccessKey or not s3Conf.awsAccountId or not s3Conf.region or
not bucketName or not s3Conf.linkExpiration
S3StorageProcessor = require('../file/s3/processor').S3StorageProcessor
return new S3StorageProcessor(s3Conf.accessKeyId, s3Conf.secretAccessKey,
s3Conf.awsAccountId, s3Conf.region, bucketName, s3Conf.linkExpiration)
else
throw new Error("Problem with settings: unknown files.type '#{filesConf.type}'")
getUploadSizeLimit: ->
@get('files').uploadSizeLimit
getNotificationConf: () ->
###
Возвращает объект настроек нотификаций
###
conf = @get('notification') || {}
conf.rules = conf.rules or {}
conf.hasTypeRules = (type) ->
return not _.isEmpty(conf.rules) and conf.rules[type] and conf.rules[type].length
conf.getTypeRules = (type) ->
return [] if not conf.hasTypeRules(type)
return conf.rules[type]
conf.getCommunicationTypes = () ->
rules = conf.rules
res = {}
for notificationType, transports of rules
communicationTypes = {}
for transport in transports
className = StrUtils.toCamelCase(transport) + "Transport"
communicationType = require("../notification/transport/" + transport)[className].getCommunicationType()
communicationTypes[communicationType] = communicationType
res[notificationType] = _.keys(communicationTypes)
return res
return conf
getGDriveConf: ->
@get('gDriveConf')
getHangoutConf: () ->
@get('hangout')
getApiConf: (transport) ->
return @get('api')[transport]
getApiTransportUrl: (transport) ->
transportConf = @get('api')[transport]
return if not transportConf
return "/api/#{transport}/#{transportConf.version}/"
getReferalEmailSalt: () ->
return @get('referalEmailSalt')
getContactsConfForSource: (sourceName) ->
return @get('contacts').sources[sourceName]
getExportConf: ->
return @get('export')
getStoreItemsInstalledByDefalult: () ->
return @get('store').itemsInstalledByDefault or []
getPaymentConf: () ->
return @get('payment')
getSitemapConf: () ->
return @get('sitemap')
module.exports = Conf
| 179397 | fs = require('fs-plus')
_ = require('underscore')
express = require('express')
everycache = require('everycache')
swig = require('swig')
path = require('path')
winston = require('winston')
CategoriedStdoutLogger = require('../common/logger/categoried_stdout').CategoriedStdoutLogger
StrUtils = require('../../share/utils/string')
class Conf
###
Окружение, в котором запущен сервер: хранение настроек, методы для работы с ними, возвращение соединений с БД и т.д.
###
constructor: (@settings) ->
@_db = {}
@_loggerConf = @_initLogger()
@_caches = {}
@_version = null
# пул логгеров
@_loggers = {}
# Настройка шаблонизатора
swig.init
allowErrors: true,
autoescape: true,
encoding: 'utf8',
filters: require('../templates/filters'),
tags: {},
extensions: {},
tzOffset: 0
root: @getTemplateRootDir()
getTemplateRootDir: () =>
versionedTemplatesRootDir = path.join(__dirname, '/../../../lib/templates')
if fs.existsSync(versionedTemplatesRootDir)
return versionedTemplatesRootDir
return path.join(__dirname, '/../templates')
getTemplate: () ->
###
Возвращает обеъект шаблонизатора. У него есть методы compileFile(filename), compileString(templateString)
@return swig
###
return swig
get: (key) ->
###
Возвращает значение из конфига по ключу (только первый уровень объекта конфигурации).
@param {String} key ключ конфига
###
if key of @settings
return @settings[key]
else
throw new Error("No #{key} in settings")
getDbConf: (connName) ->
###
Возвращает настройки для указанного соединения с БД.
@param {String} connName название соединения в конфиге
###
conf = @get('db')
if connName not of conf
throw new Error("No settings for db connection '#{connName}'")
return conf[connName]
getDb: (connName) ->
###
Возвращает соединение с БД.
При первом обращении создает это соединение.
@param {String} connName название соединения в конфиге
TODO: выделить метод getDbConnection, чтобы можно было доступиться к методам работы с сервером БД
TODO: вынести все методы работы с БД из Conf в отдельный модуль
###
dbConf = @getDbConf(connName)
return @_db[connName] if @_db[connName]
if dbConf.type == 'cradle'
cradle = require('cradle')
connection = new cradle.Connection("#{dbConf.protocol}://#{dbConf.hostname}", dbConf.port, dbConf.options)
return @_db[connName] = connection.database(dbConf.db)
else
throw new Error("Unknown db type #{dbConf.type}")
getDbUrl: (connName) ->
###
Возвращает строку коннекта к базе данных (URL), формат отличается в зависимости от типа базы данных.
@param {String} connName название соединения в конфиге
###
dbConf = @getDbConf(connName)
if dbConf.type == 'cradle'
u =
protocol: dbConf.protocol
hostname: dbConf.hostname
port: dbConf.port
pathname: dbConf.db
if dbConf.options.auth
u.auth = "#{dbConf.options.auth.username}:#{dbConf.options.auth.password}"
return require('url').format(u)
else
throw new Error("Unknown db type #{dbConf.type}")
getSessionConf: () ->
###
Возвращает параметры для connect's session middleware, инициализирует хранилище для сессий
@return: object
###
return @_sessionConf if @_sessionConf
@_sessionConf = @get('session')
@_sessionConf.cookie.maxAge *= 1000 if @_sessionConf.cookie.maxAge
@_sessionConf.refreshInterval = @_sessionConf.refreshInterval*1000
# session cookie name (key)
@_sessionConf.key or= "<KEY>"
# supported stores: memory, redis (memcache and others can be added)
@_sessionConf.storeType or= "memory"
switch @_sessionConf.storeType
when "memory"
@_sessionConf.store = new(require('express').session.MemoryStore)
when "redis"
RedisStore = require('connect-redis')(require('express'))
@_sessionConf.store = new RedisStore(@_sessionConf.storeOptions || {})
else
throw new Error("Unsupported connect session store type: #{@_sessionConf.storeType}")
# fingerprint по умолчанию возвращает user-agent, однако мы хотим использовать
# сессии в websocket-соединениях, в которых user-agent не передается
@_sessionConf.fingerprint = -> ''
return @_sessionConf
getCache: (type) ->
cache = @_caches[type]
return cache if cache
try
settings = @get('cache')[type]
throw new Error("No settings for cache type '#{type}'") if not settings
catch err
#process.stderr.write(err)
return null
try
cache = everycache.getCache(settings)
catch err
#process.stderr.write(err)
return null
return @_caches[type] = cache
getSearchConf: () ->
###
Возвращает параметры для поискового сервера.
###
return @get('search')
getSearchIndexerConf: () ->
###
Возвращает параметры для поискового сервера.
###
return @get('searchIndexer')
getSphinxIndexPrefix: () ->
return @getSearchIndexerConf().indexPrefix or 'dev'
getSearchPlugins: () ->
###
Возвращает параметры плагинов для поиска.
###
return @get('searchPlugins')
getAmqpConf: () ->
###
Настройки для подключения к AMQP брокеру.
###
return @get('amqpConnect')
getOtConf: () ->
###
Настройки для ot процессора.
###
otConf = @get('ot')
#Суффикс для имени очереди, которую слушает процесс.
#Необходимо обеспечить уникальные названия очередей для каждого процесса, но эти названия не должны меняться при
#перезапуске процесса. FRONTEND_QUEUE_SUFFIX - нужна только процессам, обслуживающим подписки пользователей.
otConf.frontendQueueSuffix = process.env.FRONTEND_QUEUE_SUFFIX
range = process.env.BACKEND_ID_RANGE
otConf.backendIdRange = _.uniq(range.split(',')) if range
return otConf
setServerAsOtBackend: () ->
@get('ot').isBackend = true
getAppListenPort: () ->
###
Возвращает порт, на котором должен принимать соединения HTTP-сервер.
Значение берется из переменной окружения LISTEN_PORT, из настроек (app.listen_port),
или возвращает значение по умолчанию (8000).
###
return process.env.LISTEN_PORT || @get('app').listenPort || 8000
getAppRoles: () ->
###
Возвращает список ролей, с которыми было запущено приложение.
Значения берутся из переменной окружения APP_ROLES, разделены запятыми.
По умолчанию возвращает ["default"].
@return: array
###
return (process.env.APP_ROLES || "default").split(',')
getAppName: () ->
###
Возвращает название приложения, берется из переменной окружения
###
return process.env.APP_NAME
getWaveUrl: () ->
return @get('app').waveUrl
getWaveEmbeddedUrl: ->
return @get('app').waveEmbeddedUrl
getWaveDriveUrl: ->
return @get('app').waveDriveUrl
getTagSearchUrl: ->
return '/tag/'
getLoggerConf: () ->
log_config = @get('logger')
if process.env.LOG_LEVEL and process.env.LOG_LEVEL != ''
log_config.logLevel = process.env.LOG_LEVEL
return log_config
getGeneratorConf: () ->
return @get('generator')
getAuthConf: () ->
return @get('auth')
getVersionInfo: () =>
###
Версия запущенного приложения, название бранча, время билда.
###
return @_version unless @_version is null
@_version = {}
try
version = require('../version')
if version
{version, branch} = version
branch = branch?.replace(/^trunk$|^master$|^[\d_]+/, "") # simplify branch name
branch = if branch then "/#{branch}" else ""
versionString = "#{version or "-"}#{branch}"
@_version = {version, branch, versionString}
return @_version
getVersion: () =>
###
Версия запущенного приложения
@returns string
###
return @getVersionInfo().version || ''
_initLogger: () ->
###
Инициализируем конфиг логгера
###
return @getLoggerConf()
getLogger: (loggerName=@_loggerConf.defaultLoggerName) ->
###
logger
###
return @_loggers[loggerName] if @_loggers[loggerName]
transports = null
if @_loggerConf.transports
transports = @_loggerConf.transports[loggerName]
transports = @_loggerConf.transports["*"] if not transports
# по умолчанию добавим наш логгер в стдаут
if not transports or not transports.length
transports = [{
transportClass: CategoriedStdoutLogger
colorize: true
loggerNameField: 'category'
}]
logLevel = @_loggerConf.logLevel.toLowerCase()
opts = { transports: [] }
for topts in transports
ttopts = _.clone(topts)
transportClass = topts.transportClass
delete ttopts.transportClass
ttopts.level = logLevel
if topts.loggerNameField
facility = loggerName
appName = @getAppName()
if topts.appInfo
facility = "#{appName}.#{facility}" if appName
ttopts["facilityApp"] = appName
ttopts["facilityCategory"] = loggerName
ttopts["facilityPid"] = process.pid
ttopts[topts.loggerNameField] = facility
delete ttopts.loggerNameField
opts.transports.push(new transportClass(ttopts))
logger = winston.loggers.add(loggerName, opts)
logger.setLevels(winston.config.syslog.levels)
logger.level = logLevel
logger.warn = logger.warning
@_loggers[loggerName] = logger
return logger
getAuthSourceConf: (source) ->
return @get('auth')[source]
getStorageProcessor: (client)->
filesConf = @get('files')
switch filesConf.type
when 'local'
LocalStorageProcessor = require('../file/local/processor').LocalStorageProcessor
return new LocalStorageProcessor()
when 's3'
s3Conf = filesConf.s3
bucketName = s3Conf.buckets?[client]
throw new Error('Missing S3 tokens') if not s3Conf or not s3Conf.accessKeyId or
not s3Conf.secretAccessKey or not s3Conf.awsAccountId or not s3Conf.region or
not bucketName or not s3Conf.linkExpiration
S3StorageProcessor = require('../file/s3/processor').S3StorageProcessor
return new S3StorageProcessor(s3Conf.accessKeyId, s3Conf.secretAccessKey,
s3Conf.awsAccountId, s3Conf.region, bucketName, s3Conf.linkExpiration)
else
throw new Error("Problem with settings: unknown files.type '#{filesConf.type}'")
getUploadSizeLimit: ->
@get('files').uploadSizeLimit
getNotificationConf: () ->
###
Возвращает объект настроек нотификаций
###
conf = @get('notification') || {}
conf.rules = conf.rules or {}
conf.hasTypeRules = (type) ->
return not _.isEmpty(conf.rules) and conf.rules[type] and conf.rules[type].length
conf.getTypeRules = (type) ->
return [] if not conf.hasTypeRules(type)
return conf.rules[type]
conf.getCommunicationTypes = () ->
rules = conf.rules
res = {}
for notificationType, transports of rules
communicationTypes = {}
for transport in transports
className = StrUtils.toCamelCase(transport) + "Transport"
communicationType = require("../notification/transport/" + transport)[className].getCommunicationType()
communicationTypes[communicationType] = communicationType
res[notificationType] = _.keys(communicationTypes)
return res
return conf
getGDriveConf: ->
@get('gDriveConf')
getHangoutConf: () ->
@get('hangout')
getApiConf: (transport) ->
return @get('api')[transport]
getApiTransportUrl: (transport) ->
transportConf = @get('api')[transport]
return if not transportConf
return "/api/#{transport}/#{transportConf.version}/"
getReferalEmailSalt: () ->
return @get('referalEmailSalt')
getContactsConfForSource: (sourceName) ->
return @get('contacts').sources[sourceName]
getExportConf: ->
return @get('export')
getStoreItemsInstalledByDefalult: () ->
return @get('store').itemsInstalledByDefault or []
getPaymentConf: () ->
return @get('payment')
getSitemapConf: () ->
return @get('sitemap')
module.exports = Conf
| true | fs = require('fs-plus')
_ = require('underscore')
express = require('express')
everycache = require('everycache')
swig = require('swig')
path = require('path')
winston = require('winston')
CategoriedStdoutLogger = require('../common/logger/categoried_stdout').CategoriedStdoutLogger
StrUtils = require('../../share/utils/string')
class Conf
###
Окружение, в котором запущен сервер: хранение настроек, методы для работы с ними, возвращение соединений с БД и т.д.
###
constructor: (@settings) ->
@_db = {}
@_loggerConf = @_initLogger()
@_caches = {}
@_version = null
# пул логгеров
@_loggers = {}
# Настройка шаблонизатора
swig.init
allowErrors: true,
autoescape: true,
encoding: 'utf8',
filters: require('../templates/filters'),
tags: {},
extensions: {},
tzOffset: 0
root: @getTemplateRootDir()
getTemplateRootDir: () =>
versionedTemplatesRootDir = path.join(__dirname, '/../../../lib/templates')
if fs.existsSync(versionedTemplatesRootDir)
return versionedTemplatesRootDir
return path.join(__dirname, '/../templates')
getTemplate: () ->
###
Возвращает обеъект шаблонизатора. У него есть методы compileFile(filename), compileString(templateString)
@return swig
###
return swig
get: (key) ->
###
Возвращает значение из конфига по ключу (только первый уровень объекта конфигурации).
@param {String} key ключ конфига
###
if key of @settings
return @settings[key]
else
throw new Error("No #{key} in settings")
getDbConf: (connName) ->
###
Возвращает настройки для указанного соединения с БД.
@param {String} connName название соединения в конфиге
###
conf = @get('db')
if connName not of conf
throw new Error("No settings for db connection '#{connName}'")
return conf[connName]
getDb: (connName) ->
###
Возвращает соединение с БД.
При первом обращении создает это соединение.
@param {String} connName название соединения в конфиге
TODO: выделить метод getDbConnection, чтобы можно было доступиться к методам работы с сервером БД
TODO: вынести все методы работы с БД из Conf в отдельный модуль
###
dbConf = @getDbConf(connName)
return @_db[connName] if @_db[connName]
if dbConf.type == 'cradle'
cradle = require('cradle')
connection = new cradle.Connection("#{dbConf.protocol}://#{dbConf.hostname}", dbConf.port, dbConf.options)
return @_db[connName] = connection.database(dbConf.db)
else
throw new Error("Unknown db type #{dbConf.type}")
getDbUrl: (connName) ->
###
Возвращает строку коннекта к базе данных (URL), формат отличается в зависимости от типа базы данных.
@param {String} connName название соединения в конфиге
###
dbConf = @getDbConf(connName)
if dbConf.type == 'cradle'
u =
protocol: dbConf.protocol
hostname: dbConf.hostname
port: dbConf.port
pathname: dbConf.db
if dbConf.options.auth
u.auth = "#{dbConf.options.auth.username}:#{dbConf.options.auth.password}"
return require('url').format(u)
else
throw new Error("Unknown db type #{dbConf.type}")
getSessionConf: () ->
###
Возвращает параметры для connect's session middleware, инициализирует хранилище для сессий
@return: object
###
return @_sessionConf if @_sessionConf
@_sessionConf = @get('session')
@_sessionConf.cookie.maxAge *= 1000 if @_sessionConf.cookie.maxAge
@_sessionConf.refreshInterval = @_sessionConf.refreshInterval*1000
# session cookie name (key)
@_sessionConf.key or= "PI:KEY:<KEY>END_PI"
# supported stores: memory, redis (memcache and others can be added)
@_sessionConf.storeType or= "memory"
switch @_sessionConf.storeType
when "memory"
@_sessionConf.store = new(require('express').session.MemoryStore)
when "redis"
RedisStore = require('connect-redis')(require('express'))
@_sessionConf.store = new RedisStore(@_sessionConf.storeOptions || {})
else
throw new Error("Unsupported connect session store type: #{@_sessionConf.storeType}")
# fingerprint по умолчанию возвращает user-agent, однако мы хотим использовать
# сессии в websocket-соединениях, в которых user-agent не передается
@_sessionConf.fingerprint = -> ''
return @_sessionConf
getCache: (type) ->
cache = @_caches[type]
return cache if cache
try
settings = @get('cache')[type]
throw new Error("No settings for cache type '#{type}'") if not settings
catch err
#process.stderr.write(err)
return null
try
cache = everycache.getCache(settings)
catch err
#process.stderr.write(err)
return null
return @_caches[type] = cache
getSearchConf: () ->
###
Возвращает параметры для поискового сервера.
###
return @get('search')
getSearchIndexerConf: () ->
###
Возвращает параметры для поискового сервера.
###
return @get('searchIndexer')
getSphinxIndexPrefix: () ->
return @getSearchIndexerConf().indexPrefix or 'dev'
getSearchPlugins: () ->
###
Возвращает параметры плагинов для поиска.
###
return @get('searchPlugins')
getAmqpConf: () ->
###
Настройки для подключения к AMQP брокеру.
###
return @get('amqpConnect')
getOtConf: () ->
###
Настройки для ot процессора.
###
otConf = @get('ot')
#Суффикс для имени очереди, которую слушает процесс.
#Необходимо обеспечить уникальные названия очередей для каждого процесса, но эти названия не должны меняться при
#перезапуске процесса. FRONTEND_QUEUE_SUFFIX - нужна только процессам, обслуживающим подписки пользователей.
otConf.frontendQueueSuffix = process.env.FRONTEND_QUEUE_SUFFIX
range = process.env.BACKEND_ID_RANGE
otConf.backendIdRange = _.uniq(range.split(',')) if range
return otConf
setServerAsOtBackend: () ->
@get('ot').isBackend = true
getAppListenPort: () ->
###
Возвращает порт, на котором должен принимать соединения HTTP-сервер.
Значение берется из переменной окружения LISTEN_PORT, из настроек (app.listen_port),
или возвращает значение по умолчанию (8000).
###
return process.env.LISTEN_PORT || @get('app').listenPort || 8000
getAppRoles: () ->
###
Возвращает список ролей, с которыми было запущено приложение.
Значения берутся из переменной окружения APP_ROLES, разделены запятыми.
По умолчанию возвращает ["default"].
@return: array
###
return (process.env.APP_ROLES || "default").split(',')
getAppName: () ->
###
Возвращает название приложения, берется из переменной окружения
###
return process.env.APP_NAME
getWaveUrl: () ->
return @get('app').waveUrl
getWaveEmbeddedUrl: ->
return @get('app').waveEmbeddedUrl
getWaveDriveUrl: ->
return @get('app').waveDriveUrl
getTagSearchUrl: ->
return '/tag/'
getLoggerConf: () ->
log_config = @get('logger')
if process.env.LOG_LEVEL and process.env.LOG_LEVEL != ''
log_config.logLevel = process.env.LOG_LEVEL
return log_config
getGeneratorConf: () ->
return @get('generator')
getAuthConf: () ->
return @get('auth')
getVersionInfo: () =>
###
Версия запущенного приложения, название бранча, время билда.
###
return @_version unless @_version is null
@_version = {}
try
version = require('../version')
if version
{version, branch} = version
branch = branch?.replace(/^trunk$|^master$|^[\d_]+/, "") # simplify branch name
branch = if branch then "/#{branch}" else ""
versionString = "#{version or "-"}#{branch}"
@_version = {version, branch, versionString}
return @_version
getVersion: () =>
###
Версия запущенного приложения
@returns string
###
return @getVersionInfo().version || ''
_initLogger: () ->
###
Инициализируем конфиг логгера
###
return @getLoggerConf()
getLogger: (loggerName=@_loggerConf.defaultLoggerName) ->
###
logger
###
return @_loggers[loggerName] if @_loggers[loggerName]
transports = null
if @_loggerConf.transports
transports = @_loggerConf.transports[loggerName]
transports = @_loggerConf.transports["*"] if not transports
# по умолчанию добавим наш логгер в стдаут
if not transports or not transports.length
transports = [{
transportClass: CategoriedStdoutLogger
colorize: true
loggerNameField: 'category'
}]
logLevel = @_loggerConf.logLevel.toLowerCase()
opts = { transports: [] }
for topts in transports
ttopts = _.clone(topts)
transportClass = topts.transportClass
delete ttopts.transportClass
ttopts.level = logLevel
if topts.loggerNameField
facility = loggerName
appName = @getAppName()
if topts.appInfo
facility = "#{appName}.#{facility}" if appName
ttopts["facilityApp"] = appName
ttopts["facilityCategory"] = loggerName
ttopts["facilityPid"] = process.pid
ttopts[topts.loggerNameField] = facility
delete ttopts.loggerNameField
opts.transports.push(new transportClass(ttopts))
logger = winston.loggers.add(loggerName, opts)
logger.setLevels(winston.config.syslog.levels)
logger.level = logLevel
logger.warn = logger.warning
@_loggers[loggerName] = logger
return logger
getAuthSourceConf: (source) ->
return @get('auth')[source]
getStorageProcessor: (client)->
filesConf = @get('files')
switch filesConf.type
when 'local'
LocalStorageProcessor = require('../file/local/processor').LocalStorageProcessor
return new LocalStorageProcessor()
when 's3'
s3Conf = filesConf.s3
bucketName = s3Conf.buckets?[client]
throw new Error('Missing S3 tokens') if not s3Conf or not s3Conf.accessKeyId or
not s3Conf.secretAccessKey or not s3Conf.awsAccountId or not s3Conf.region or
not bucketName or not s3Conf.linkExpiration
S3StorageProcessor = require('../file/s3/processor').S3StorageProcessor
return new S3StorageProcessor(s3Conf.accessKeyId, s3Conf.secretAccessKey,
s3Conf.awsAccountId, s3Conf.region, bucketName, s3Conf.linkExpiration)
else
throw new Error("Problem with settings: unknown files.type '#{filesConf.type}'")
getUploadSizeLimit: ->
@get('files').uploadSizeLimit
getNotificationConf: () ->
###
Возвращает объект настроек нотификаций
###
conf = @get('notification') || {}
conf.rules = conf.rules or {}
conf.hasTypeRules = (type) ->
return not _.isEmpty(conf.rules) and conf.rules[type] and conf.rules[type].length
conf.getTypeRules = (type) ->
return [] if not conf.hasTypeRules(type)
return conf.rules[type]
conf.getCommunicationTypes = () ->
rules = conf.rules
res = {}
for notificationType, transports of rules
communicationTypes = {}
for transport in transports
className = StrUtils.toCamelCase(transport) + "Transport"
communicationType = require("../notification/transport/" + transport)[className].getCommunicationType()
communicationTypes[communicationType] = communicationType
res[notificationType] = _.keys(communicationTypes)
return res
return conf
getGDriveConf: ->
@get('gDriveConf')
getHangoutConf: () ->
@get('hangout')
getApiConf: (transport) ->
return @get('api')[transport]
getApiTransportUrl: (transport) ->
transportConf = @get('api')[transport]
return if not transportConf
return "/api/#{transport}/#{transportConf.version}/"
getReferalEmailSalt: () ->
return @get('referalEmailSalt')
getContactsConfForSource: (sourceName) ->
return @get('contacts').sources[sourceName]
getExportConf: ->
return @get('export')
getStoreItemsInstalledByDefalult: () ->
return @get('store').itemsInstalledByDefault or []
getPaymentConf: () ->
return @get('payment')
getSitemapConf: () ->
return @get('sitemap')
module.exports = Conf
|
[
{
"context": "ffee\n# Copyright 2016 9165584 Canada Corporation <legal@fuzzy.ai>\n\nLemonadeStand = require './lemonade-stand'\n\nser",
"end": 73,
"score": 0.9999063611030579,
"start": 59,
"tag": "EMAIL",
"value": "legal@fuzzy.ai"
}
] | src/main.coffee | enterstudio/lemonade-stand | 2 | # main.coffee
# Copyright 2016 9165584 Canada Corporation <legal@fuzzy.ai>
LemonadeStand = require './lemonade-stand'
server = new LemonadeStand process.env
server.start (err) ->
if err
console.error(err)
else
console.log("Server listening on #{server.config.port}")
| 12491 | # main.coffee
# Copyright 2016 9165584 Canada Corporation <<EMAIL>>
LemonadeStand = require './lemonade-stand'
server = new LemonadeStand process.env
server.start (err) ->
if err
console.error(err)
else
console.log("Server listening on #{server.config.port}")
| true | # main.coffee
# Copyright 2016 9165584 Canada Corporation <PI:EMAIL:<EMAIL>END_PI>
LemonadeStand = require './lemonade-stand'
server = new LemonadeStand process.env
server.start (err) ->
if err
console.error(err)
else
console.log("Server listening on #{server.config.port}")
|
[
{
"context": " et qui parle {oral_detail}.'\n\n w_names = [\n 'Tum Tum',\n 'Lala', 'Crine', 'Mercier', 'Pompon',\n '",
"end": 530,
"score": 0.9976139664649963,
"start": 523,
"tag": "NAME",
"value": "Tum Tum"
},
{
"context": "oral_detail}.'\n\n w_names = [\n 'Tum Tum',\n... | app/scripts/data_fr.coffee | jrmi/rpghelper | 0 | # Import
angular.module('rpghelperApp').run (generator) ->
generator.add 'start', '{sex}'
generator.add 'sex', "<b>{firstname}</b> est une femme {intro}<br>C'est une personne {first_impression} motivée par {motivation}.", null, ['!man'], ['woman']
generator.add 'sex', "<b>{firstname}</b> est un homme {intro}<br>C'est une personne {first_impression} motivée par {motivation}.", null, ['!woman'], ['man']
generator.add 'intro', '{age} {type} qui {physical_detail} et qui parle {oral_detail}.'
w_names = [
'Tum Tum',
'Lala', 'Crine', 'Mercier', 'Pompon',
'Ik', 'Shan', 'Île', 'Ula', 'la fille de Joe',
'Amy', 'Rufe',
'B-A', 'la Souris',
'G', 'Omie',
'Jeanette', 'Cervelle',
'Matilda', 'Rêveuse', 'Perdrix',
'Raphaële', 'Entretoise', 'Victoire',
'Desséchée',
'Mill', 'Isa', 'Ratée',
'III', 'Herse', 'Levant', 'Bouilloire',
'Putride', 'Derniere',
'Clairon', 'Mimi', 'Fianelli',
'Pelette', 'Li', 'Harpie', 'Fa', 'Ridée', 'Fusible',
'Visage', 'Gueularde',
'Timbrée',
'Shazza', 'Faune',
'Guinde', 'Douillette', 'Pomme de Pin',
'la Suissesse'
]
m_names = [
'Tum Tum', 'Noueux', 'Tondu', 'Leblanc',
'Bill', 'Pompon',
'Ik',
'Dremmer', 'Balloches', 'Rufe',
'Jakabaka', 'Ba', 'la Souris', 'Tête de chien',
'Hugo', 'Roark', 'Lemoine', 'Pierre',
'Norvell', 'G', 'Omie', 'Sage', 'Corbett',
'Rhum', 'Piquant', 'Cervelle',
'Rothschild', 'Rêveur', 'Perdrix',
'Raphaël', 'Entretoise', 'Victoire', 'Bar', 'Crin',
'Desséché', 'Millions', 'Grome', 'Foster',
'Mill', 'Danceny', 'Newton', 'Tao', 'Raté',
'III', 'Princy', 'Herse', 'Levant', 'Bouilloire',
'Putride', 'Dernier', 'Deux-Coups', 'Patrick',
'Clairon', 'Abondo', 'Fianelli', 'Frank',
'Pelet', 'Li', 'Riz', 'Do', 'Ridé', 'Fusible',
'Visage', 'Repus', 'Gueulard', 'Imam', 'Bon-Œil',
'Timbré', 'Laporte', 'Menton', 'Gros-Yeux',
'Soleil', 'Hoche',
'Richard', 'Guinde', 'Pomme de Pin',
'Futal', 'Angleur', 'Goudry', 'Marteau',
'Antoine', 'Deuil'
]
for name in w_names
generator.add 'firstname', name, null, ['woman'], ['woman'], {name: name}
for name in m_names
generator.add 'firstname', name, null, ['man'], ['man'], {name: name}
generator.add 'type', ""
generator.add 'type', "humain ", null, ['fantasy']
generator.add 'type', "nain ", null, ['fantasy']
generator.add 'type', "elfe ", null, ['fantasy']
generator.add 'type', "orc ", null, ['fantasy']
generator.add 'type', "troll ", null, ['fantasy']
generator.add 'age', 'agé', null, ['man']
generator.add 'age', 'agée', null, ['woman']
generator.add 'age', 'jeune'
generator.add 'age', '', 6
generator.add 'first_impression', "séduisante"
generator.add 'first_impression', "dégoutante"
generator.add 'first_impression', "mystérieuse"
generator.add 'first_impression', "étonnante"
generator.add 'first_impression', "impressionnante"
generator.add 'first_impression', "calme"
generator.add 'first_impression', "qui inspire la confiance"
generator.add 'first_impression', "banale", 10
generator.add 'first_impression', "hideuse"
generator.add 'first_impression', "chétive"
generator.add 'first_impression', "triste"
generator.add 'first_impression', "qui semble malade"
# body
#generator.add 'physical_detail', "est mince"
generator.add 'physical_detail', "est rachitique"
generator.add 'physical_detail', "est albinos", 0.3
generator.add 'physical_detail', "a un gros bide"
generator.add 'physical_detail', "est très grand", null, ['man']
generator.add 'physical_detail', "est très musclé", null, ['man']
generator.add 'physical_detail', "est tout rond", null, ['man']
generator.add 'physical_detail', "est tout petit", null, ['man']
generator.add 'physical_detail', "est très grande", null, ['woman']
generator.add 'physical_detail', "est très musclée", null, ['woman']
generator.add 'physical_detail', "est toute ronde", null, ['woman']
generator.add 'physical_detail', "est toute petite", null, ['woman']
generator.add 'physical_detail', "est obèse"
generator.add 'physical_detail', "est vouté"
generator.add 'physical_detail', "est bossu"
generator.add 'physical_detail', "a la peau {skin_color}"
# Ears
generator.add 'physical_detail', "a de gros lobes d'oreille"
generator.add 'physical_detail', "n'a qu'une seule oreille"
generator.add 'physical_detail', "n'a pas de lobe d'oreille"
generator.add 'physical_detail', "a les oreilles décolées"
generator.add 'physical_detail', "a des boucles d'oreille"
generator.add 'physical_detail', "a les oreilles déformées"
# mouth
generator.add 'physical_detail', "a la bouche en cul de poule"
generator.add 'physical_detail', "a un bec de lièvre"
generator.add 'physical_detail', "a des dents parfaites"
#generator.add 'physical_detail', "a des dents pointues"
generator.add 'physical_detail', "a des dents gatées"
#generator.add 'physical_detail', "a des lèvres très fines"
#generator.add 'physical_detail', "a de grosses lèvres"
generator.add 'physical_detail', "a des dents en métal"
generator.add 'physical_detail', "a des dents de lapin"
generator.add 'physical_detail', "a des dents de la chance"
generator.add 'physical_detail', "a des dents manquantes"
generator.add 'physical_detail', "n'a pas de dent"
# Arms
generator.add 'physical_detail', "a un bras manquant"
generator.add 'physical_detail', "a des mains énormes"
generator.add 'physical_detail', "a des tatouages sur les bras"
generator.add 'physical_detail', "a des tatouages sur les mains"
generator.add 'physical_detail', "a une main manquante"
generator.add 'physical_detail', "a des mains disproportionnées"
# Noze
#generator.add 'physical_detail', "a le nez en trompette"
generator.add 'physical_detail', "a le nez cassé"
generator.add 'physical_detail', "a le nez pointu"
#generator.add 'physical_detail', "a un nez de cochon"
generator.add 'physical_detail', "n'a pas de nez"
generator.add 'physical_detail', "a un piercing sur le nez"
# Eyes
generator.add 'physical_detail', "a les yeux verrons"
#generator.add 'physical_detail', "porte des lunettes"
generator.add 'physical_detail', "a un oeuil en moins"
generator.add 'physical_detail', "a les yeux injectés de sang"
#generator.add 'physical_detail', "a un oeuil sans pupille"
generator.add 'physical_detail', "a les yeux très maquillés", null, ['woman']
generator.add 'physical_detail', "a un strabisme"
generator.add 'physical_detail', "a les yeux globuleux"
generator.add 'physical_detail', "n'a pas de sourcils"
# Face
generator.add 'physical_detail', "a une longue barbe", null, ['man']
#generator.add 'physical_detail', "a un percing au visage"
generator.add 'physical_detail', "a des favoris", null, ['man']
generator.add 'physical_detail', "a une moustache", null, ['man']
generator.add 'physical_detail', "est imberbe", null, ['man']
generator.add 'physical_detail', "est mal rasé", null, ['man']
#generator.add 'physical_detail', "a un bouc", null, ['man']
generator.add 'physical_detail', "a des rubans dans sa barbe", null, ['man']
generator.add 'physical_detail', "a des élastiques dans sa barbe", null, ['man']
generator.add 'physical_detail', "a des cicatrices sur le visage"
#generator.add 'physical_detail', "a des piercings sur le visage"
generator.add 'physical_detail', "a le visage trop maquillé", null, ['woman']
generator.add 'physical_detail', "a le visage pâle"
generator.add 'physical_detail', "a des tatouages sur le visage"
#generator.add 'physical_detail', "a les joues roses"
generator.add 'physical_detail', "a des peintures tribales sur le visage"
#generator.add 'physical_detail', "a le visage buriné"
generator.add 'physical_detail', "a de l'acnée"
generator.add 'physical_detail', "a les cheveux rasés"
# Hairs
generator.add 'physical_detail', "a les cheveux rasés"
generator.add 'physical_detail', "a les cheveux {hair_color}"
#generator.add 'physical_detail', "a les cheveux en bataille"
generator.add 'physical_detail', "a les cheveux gras"
generator.add 'physical_detail', "a les cheveux très long"
generator.add 'physical_detail', "a des dessins rasés sur le crane"
generator.add 'physical_detail', "a des couettes"
generator.add 'physical_detail', "a des dreadlocks"
generator.add 'skin_color', "très blanche"
generator.add 'skin_color', "noire"
generator.add 'skin_color', "grise"
generator.add 'skin_color', "jaune"
generator.add 'skin_color', "rouge", null, ['fantasy']
generator.add 'hair_color', "blanc", 3
generator.add 'hair_color', "rose"
generator.add 'hair_color', "poivre et sel"
generator.add 'hair_color', "rouge"
generator.add 'oral_detail', "en répetant « {word_repeat} »", 6
generator.add 'oral_detail', "souvent à des gens absents"
generator.add 'oral_detail', "avec un langage ordurier"
generator.add 'oral_detail', "avec un cheveux sur la langue"
generator.add 'oral_detail', "avec une petite voix"
generator.add 'oral_detail', "avec une voix débile"
generator.add 'oral_detail', "avec une voix suraigue"
generator.add 'oral_detail', "avec une voix chantante"
#generator.add 'oral_detail', "avec de l'accent"
generator.add 'oral_detail', "en beguayant"
generator.add 'oral_detail', "en zozotant"
generator.add 'oral_detail', "en postillionnant"
generator.add 'oral_detail', "en shuintant"
generator.add 'oral_detail', "en marmonant"
generator.add 'oral_detail', "d'une voix monotone"
generator.add 'oral_detail', "d'une voix faible"
generator.add 'oral_detail', "d'une voix nasillarde"
generator.add 'oral_detail', "d'une voix guturale"
generator.add 'oral_detail', "en étant essouflé"
generator.add 'oral_detail', "en articulant excessivement"
generator.add 'oral_detail', "en agitant ses doigts"
generator.add 'oral_detail', "en s'amusant avec un objet"
#generator.add 'oral_detail', "en gesticulant"
generator.add 'oral_detail', "en se carressant la barbe", null, ['man']
#generator.add 'oral_detail', "en changeant d'histoire souvent"
generator.add 'oral_detail', "en recherchant l'approbation de son auditoire"
#generator.add 'oral_detail', "en jouant la comédie"
generator.add 'oral_detail', "en s'adressant à lui même"
generator.add 'oral_detail', "avec fatalisme"
generator.add 'oral_detail', "avec optimisme"
generator.add 'oral_detail', "par questions"
generator.add 'oral_detail', "très vite"
generator.add 'oral_detail', "très lentement"
generator.add 'oral_detail', "avec un vocabulaire réduit"
generator.add 'oral_detail', "en disgressant sans cesse"
generator.add 'oral_detail', "en reniflant"
generator.add 'oral_detail', "de lui par son nom"
generator.add 'oral_detail', "sans s'arrêter"
generator.add 'oral_detail', "en mâchant quelque chose"
generator.add 'oral_detail', "après s'être racler la gorge"
generator.add 'oral_detail', "en évitant les contacts occulaires"
#generator.add 'oral_detail', "en étant très près des gens"
generator.add 'oral_detail', "avec une mauvaise haleine"
generator.add 'oral_detail', "en prenant le temps de répondre"
#generator.add 'oral_detail', "en ayant l'air distrait"
generator.add 'oral_detail', "en voulant être pote"
generator.add 'oral_detail', "sans terminer ses phrases"
generator.add 'oral_detail', "souvent à des gens absents"
generator.add 'oral_detail', "en rôtant régulierement"
generator.add 'oral_detail', "en soupirant régulièrement"
generator.add 'oral_detail', "en tordant la bouche"
#generator.add 'oral_detail', "avec un faux sourire permanent"
#generator.add 'oral_detail', "en se léchant les lêvres"
generator.add 'word_repeat', "Ok !!!"
generator.add 'word_repeat', "Euhhhhh...."
generator.add 'word_repeat', "Tu vois c'que j'veux dire ?"
generator.add 'word_repeat', "Morte de rire"
generator.add 'word_repeat', "Putain"
generator.add 'word_repeat', "Délire"
generator.add 'word_repeat', "Comment on dit déjà ?"
generator.add 'word_repeat', "Délire"
generator.add 'word_repeat', "j'ai toujours révé de dire ça"
generator.add 'start_idea', "C'est {people} {people_adj} qui {interact_with_people} {people} {people_adj}"
generator.add 'start_idea', "C'est {people} {people_adj} qui {interact_with_people} {people} {people_adj} dans {place}"
generator.add 'start_idea', "C'est {people} {people_adj} qui {interact_with_place} {place} {place_adj}"
generator.add 'start_idea', "C'est {people} {people_adj} qui {interact_with_place} {place} {place_adj} avec {people}"
generator.add 'people', "un scientifique"
generator.add 'people', "un gourou"
generator.add 'people', "un chef d'état"
generator.add 'people', "un top model"
generator.add 'people', "un dealer", null, ['!fantasy']
generator.add 'people', "un flic"
generator.add 'people', "une personne riche"
generator.add 'people', "un acteur"
generator.add 'people', "un corporatiste", null, ['cyber']
generator.add 'people', "un fixer", null, ['cyber']
generator.add 'people', "un médecin"
generator.add 'people', "un journaliste"
generator.add 'people', "un mendiant"
generator.add 'people_adj', "fou"
generator.add 'people_adj', "machiavélique"
generator.add 'people_adj', "célèbre"
generator.add 'people_adj', "très vieux"
generator.add 'people_adj', "démoniaque"
generator.add 'people_adj', "généreux"
generator.add 'people_adj', ""
generator.add 'people_adj', ""
generator.add 'people_adj', ""
generator.add 'interact_with_people', "demande de l'aide a"
generator.add 'interact_with_people', "poursuit"
generator.add 'interact_with_people', "recherche"
generator.add 'interact_with_people', "veux séduire"
generator.add 'interact_with_people', "se fait passer pour"
generator.add 'interact_with_people', "torture"
generator.add 'interact_with_people', "s'allie avec"
generator.add 'interact_with_place', "veux s'introduire dans"
generator.add 'interact_with_place', "construit"
generator.add 'interact_with_place', "découvre"
generator.add 'interact_with_place', "détruit"
generator.add 'interact_with_place', "se cache dans"
generator.add 'interact_with_place', "veux s'évader d'"
generator.add 'interact_with_place', "veux se débarrasser d'"
generator.add 'interact_with_place', "achète"
generator.add 'place', "une prison"
generator.add 'place', "un laboratoire"
generator.add 'place', "un hôtel", null, ['!fantasy']
generator.add 'place', "une secte"
generator.add 'place', "une université"
generator.add 'place', "une école"
generator.add 'place', "une morque"
generator.add 'place', "un égout", null, ['!fantasy']
generator.add 'place', "un supermarché", null, ['!fantasy']
generator.add 'place', "un club privé", null, ['!fantasy']
generator.add 'place', "un casino", null, ['!fantasy']
generator.add 'place', "un cinéma", null, ['!fantasy']
generator.add 'place', "une centrale nucléaire", null, ['!fantasy']
generator.add 'place', "une base militaire", null, ['!fantasy']
generator.add 'place', "un asile psychiatrique"
generator.add 'place', "une église"
generator.add 'place', "une forêt"
generator.add 'place', "un château"
generator.add 'place', "une usine", null, ['!fantasy']
generator.add 'place_adj', "illégal(e)"
generator.add 'place_adj', "clandestin(e)"
generator.add 'place_adj', "hanté(e)", null, ['fantasy']
generator.add 'place_adj', "détruit(e)"
generator.add 'place_adj', "désert(e)"
generator.add 'place_adj', "abandoné(e)"
generator.add 'place_adj', "caché(e)"
generator.add 'place_adj', "piégé(e)"
generator.add 'place_adj', "", 2
generator.add 'impro_muse', "{when}"
generator.add 'when', "à la préhistoire {where}, {who} {what}", null, null, ['prehistory']
generator.add 'when', "de nos jours {where}, {who} {what}"
generator.add 'when', "au moyen age {where}, {who} {what}", null, null, ['middle_age']
generator.add 'when', "pendant la guerre {where}, {who} {what}"
generator.add 'when', "dans le futur {where}, {who} {what}"
generator.add 'when', "après une apocalypse {where}, {who} {what}"
generator.add 'when', "pendant la nuit {where}, {who} {what}"
generator.add 'where', "dans la forêt"
generator.add 'where', "dans un supermarché", null, ['!prehistory']
generator.add 'where', "dans un château"
generator.add 'where', "à la plage"
generator.add 'where', "dans un laboratoire", null, ['!prehistory']
generator.add 'where', "sur un bateau", null, ['!prehistory']
generator.add 'where', "sur une île"
generator.add 'where', "chez le dentiste"
generator.add 'where', "chez le coiffeur"
generator.add 'where', "dans un cimetière", null, ['!prehistory']
generator.add 'where', "dans une usine", null, ['!prehistory']
generator.add 'where', "dans une morgue", null, ['!prehistory']
generator.add 'where', "en chine {where}"
generator.add 'where', "en amérique {where}"
generator.add 'where', "en angleterre {where}"
generator.add 'where', "en espagne {where}"
generator.add 'where', "au groenland {where}"
generator.add 'where', "en égypte {where}"
generator.add 'where', "en afrique {where}"
generator.add 'where', "en inde {where}"
generator.add 'where', "dans un labyrinthe"
generator.add 'where', "dans le ciel"
generator.add 'where', "dans un tapis", null, ['!prehistory']
generator.add 'where', "dans l'herbe", null, ['!prehistory']
generator.add 'where', "sous l'eau"
generator.add 'where', "dans un corps vivant"
generator.add 'who', "un homme {who_details}"
generator.add 'who', "une femme {who_details}"
generator.add 'who', "une fillette {who_details}"
generator.add 'who', "un petit garçon {who_details}"
generator.add 'who', "une femme agée {who_details}"
generator.add 'who', "un homme agé {who_details}"
generator.add 'who', "un couple"
generator.add 'who_details', "qui porte un sac à dos"
generator.add 'who_details', "complètement dépressif"
generator.add 'who_details', "complètement lunatique"
generator.add 'who_details', "avec une voix suraigue"
generator.add 'who_details', "avec la bouche en cul de poule"
generator.add 'who_details', "avec un vélo", null, ['!middle_age', '!prehistory']
generator.add 'who_details', "vouté"
generator.add 'who_details', "wesh wesh", null, ['!middle_age', '!prehistory']
generator.add 'who_details', "très distingué"
generator.add 'who_details', "complètement fou"
generator.add 'who_details', "en colère"
generator.add 'who_details', "qui n'a pas le sens de l'orientation"
generator.add 'who_details', "avec un animal de compagnie"
generator.add 'who_details', "qui a les pieds collés au sol"
generator.add 'who_details', "malhonnnète"
#domains.who_details.add ""
generator.add 'what', "coupe du bois"
generator.add 'what', "joue au tennis", null, ['!middle_age', '!prehistory']
generator.add 'what', "fait des tags", null, ['!middle_age', '!prehistory']
generator.add 'what', "travaille le jardin"
generator.add 'what', "démine une bombe", null, ['!middle_age', '!prehistory']
generator.add 'what', "passe le permis", null, ['!middle_age', '!prehistory']
generator.add 'what', "dispense un cours"
generator.add 'what', "écrit un poème"
generator.add 'what', "fait des ricochets"
generator.add 'what', "fabrique une potion"
generator.add 'what', "réalise une expérience scientifique"
generator.add 'what', "pêche des poissons"
generator.add 'what', "fait du ski", null, ['!middle_age', '!prehistory']
generator.add 'what', "vole un objet précieux"
generator.add 'motivation', "la vengeance"
generator.add 'motivation', "la faim"
generator.add 'motivation', "le désir"
generator.add 'motivation', "la haine"
generator.add 'motivation', "la jalousie"
generator.add 'motivation', "le pouvoir"
actions = [
'Sépare-les',
'Capture quelqu’un',
'Coinces-en un',
'Rends coups pour coups (dégâts établis)',
'Annonce une emmerde à venir',
'Annonce une emmerde hors-champ',
'Inflige des dégâts (comme établis)',
'Prive-les de leur matos',
'Fais-les passer à la caisse',
'Déclenche les défauts de leur matos',
'Dis-leur ce qu’il risque de se passer et redemande',
'Offre-leur une opportunité, avec ou sans prix à payer',
'Retourne leur propre action contre eux',
'Choisis une action d’une de tes menaces ( venant d’un front)'
]
generator.add 'action', actions
generator.add 'threat', '{warlord}'
generator.add 'threat', '{landscape}'
generator.add 'threat', '{brutes}'
generator.add 'threat', '{afflictions}'
generator.add 'threat', '{grotesque}'
generator.add 'warlord', 'un esclavagiste'
generator.add 'warlord', 'une reine mère'
generator.add 'warlord', 'un prophète'
generator.add 'warlord', 'un dictateur'
generator.add 'warlord', 'un conquérant'
generator.add 'warlord', 'un male alpha'
generator.add 'brutes', "un chasseur d'homme"
generator.add 'brutes', "un parasite"
generator.add 'brutes', "un culte/une secte"
generator.add 'brutes', "une famille"
generator.add 'brutes', "un homme de main"
generator.add 'brutes', "une foule en colère"
generator.add 'afflictions', 'une maladie'
generator.add 'afflictions', 'une illusion'
generator.add 'afflictions', 'une barière'
generator.add 'afflictions', 'une coutume'
generator.add 'afflictions', 'une innondation'
generator.add 'afflictions', 'un orage'
generator.add 'afflictions', 'une sècheresse'
generator.add 'afflictions', 'une invasion de {invade_type}'
generator.add 'invade_type', 'sauterelles'
generator.add 'invade_type', 'mouches'
generator.add 'invade_type', 'serpents'
generator.add 'invade_type', 'larves'
generator.add 'invade_type', 'grenouilles'
generator.add 'invade_type', 'fourmis'
generator.add 'invade_type', 'chat'
generator.add 'invade_type', 'chien'
generator.add 'grotesque', 'un cannibal'
generator.add 'grotesque', 'un mutant'
generator.add 'grotesque', 'un masochiste'
generator.add 'grotesque', 'un être malformé'
generator.add 'grotesque', 'un fou'
generator.add 'grotesque', 'un malade contagieux'
generator.add 'landscape', 'une prison'
generator.add 'landscape', 'un lieu maudit'
generator.add 'landscape', 'une fournaise'
generator.add 'landscape', 'un mirage'
generator.add 'landscape', 'un labyrinthe'
generator.add 'landscape', 'une forteresse'
generator.add 'landscape', 'un effondrement'
# Story part generator
generator.add 'story_part', 'Lieu : {story_place}'
generator.add 'story_part', 'Personne : {story_people}'
generator.add 'story_part', 'Evénement : {story_event}'
generator.add 'story_part', 'Objet : {story_object}'
generator.add 'story_part', 'Sensation : {story_feeling}'
generator.add 'story_place', 'un escalier {story_adj_ojb}'
generator.add 'story_place', 'une chambre {story_adj_ojb}'
generator.add 'story_place', 'un train {story_adj_ojb}'
generator.add 'story_place', 'au sol'
generator.add 'story_place', 'en l\'air'
generator.add 'story_place', 'sous terre'
generator.add 'story_place', '{place} {place_adj}', 2
generator.add 'story_place', '{landscape}', 2
generator.add 'story_people', '{people}'
generator.add 'story_people', '{grotesque}'
generator.add 'story_people', '{brutes}'
generator.add 'story_people', '{warlord}'
generator.add 'story_event', 'une poursuite'
generator.add 'story_event', 'une séduction'
generator.add 'story_event', 'une chute'
generator.add 'story_event', 'une usurpation d\'identité'
generator.add 'story_event', 'une rencontre innatendue'
generator.add 'story_event', 'une rencontre inéspérée'
generator.add 'story_event', 'une erreur sur la personne'
generator.add 'story_event', 'un orage'
generator.add 'story_event', 'une pluie'
generator.add 'story_event', 'une tempête'
generator.add 'story_event', 'un saut temporel', null, ['sci-fi']
generator.add 'story_event', 'une embuscade'
generator.add 'story_event', 'une bonne surprise'
generator.add 'story_event', 'une mauvaise surprise'
generator.add 'story_event', 'un cri horrible'
generator.add 'story_event', 'affliction', 3
generator.add 'story_object', '{story_obj} {story_adj_ojb}'
generator.add 'story_obj', 'un livre'
generator.add 'story_obj', 'un dé'
generator.add 'story_obj', 'une chaise'
generator.add 'story_obj', 'un ordinateur'
generator.add 'story_obj', 'un sac'
generator.add 'story_obj', 'un stylo'
generator.add 'story_obj', 'une arme'
generator.add 'story_obj', 'un outil'
generator.add 'story_obj', 'une paire de chaussure'
generator.add 'story_obj', 'un véhicule'
generator.add 'story_obj', 'une paire de lunette'
generator.add 'story_obj', 'une montre'
generator.add 'story_obj', 'une carte géographique'
generator.add 'story_adj_ojb', 'cassé(e)'
generator.add 'story_adj_ojb', 'magique'
generator.add 'story_adj_ojb', 'maudit(e)'
generator.add 'story_adj_ojb', 'dangereux(se)'
generator.add 'story_adj_ojb', 'piégé(e)'
generator.add 'story_feeling', 'une odeur horrible'
generator.add 'story_feeling', 'une odeur agréable'
generator.add 'story_feeling', 'il fait très chaud'
generator.add 'story_feeling', 'il fait très froid'
generator.add 'story_feeling', 'le sommeil'
generator.add 'story_feeling', 'la fatigue'
generator.add 'story_feeling', '{motivation}'
generator.add 'story_adj_feel', 'ignoble'
generator.add 'story_adj_feel', 'agréable'
generator.add 'story_adj_feel', 'horrible'
generator.add 'story_adj_feel', 'étonnant(e)'
| 104301 | # Import
angular.module('rpghelperApp').run (generator) ->
generator.add 'start', '{sex}'
generator.add 'sex', "<b>{firstname}</b> est une femme {intro}<br>C'est une personne {first_impression} motivée par {motivation}.", null, ['!man'], ['woman']
generator.add 'sex', "<b>{firstname}</b> est un homme {intro}<br>C'est une personne {first_impression} motivée par {motivation}.", null, ['!woman'], ['man']
generator.add 'intro', '{age} {type} qui {physical_detail} et qui parle {oral_detail}.'
w_names = [
'<NAME>',
'<NAME>', '<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>', '<NAME>', 'la fille de <NAME>',
'<NAME>', '<NAME>',
'B-A', 'la Souris',
'<NAME>', '<NAME>',
'<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>',
'<NAME>', 'Entretoise', 'Victoire',
'D<NAME>',
'<NAME>', '<NAME>', '<NAME>',
'III', 'Herse', 'Levant', 'Bouillo<NAME>',
'<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>',
'Pe<NAME>', 'Li', '<NAME>ie', 'Fa', 'R<NAME>ée', 'Fusible',
'Visage', 'Gueularde',
'<NAME>',
'<NAME>', '<NAME>',
'<NAME>', '<NAME>lette', 'Pomme de Pin',
'la Suissesse'
]
m_names = [
'<NAME>', '<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>',
'<NAME>',
'<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>'
]
for name in w_names
generator.add 'firstname', name, null, ['woman'], ['woman'], {name: name}
for name in m_names
generator.add 'firstname', name, null, ['man'], ['man'], {name: name}
generator.add 'type', ""
generator.add 'type', "humain ", null, ['fantasy']
generator.add 'type', "nain ", null, ['fantasy']
generator.add 'type', "elfe ", null, ['fantasy']
generator.add 'type', "orc ", null, ['fantasy']
generator.add 'type', "troll ", null, ['fantasy']
generator.add 'age', 'agé', null, ['man']
generator.add 'age', 'agée', null, ['woman']
generator.add 'age', 'jeune'
generator.add 'age', '', 6
generator.add 'first_impression', "séduisante"
generator.add 'first_impression', "dégoutante"
generator.add 'first_impression', "mystérieuse"
generator.add 'first_impression', "étonnante"
generator.add 'first_impression', "impressionnante"
generator.add 'first_impression', "calme"
generator.add 'first_impression', "qui inspire la confiance"
generator.add 'first_impression', "banale", 10
generator.add 'first_impression', "hideuse"
generator.add 'first_impression', "chétive"
generator.add 'first_impression', "triste"
generator.add 'first_impression', "qui semble malade"
# body
#generator.add 'physical_detail', "est mince"
generator.add 'physical_detail', "est rachitique"
generator.add 'physical_detail', "est albinos", 0.3
generator.add 'physical_detail', "a un gros bide"
generator.add 'physical_detail', "est très grand", null, ['man']
generator.add 'physical_detail', "est très musclé", null, ['man']
generator.add 'physical_detail', "est tout rond", null, ['man']
generator.add 'physical_detail', "est tout petit", null, ['man']
generator.add 'physical_detail', "est très grande", null, ['woman']
generator.add 'physical_detail', "est très musclée", null, ['woman']
generator.add 'physical_detail', "est toute ronde", null, ['woman']
generator.add 'physical_detail', "est toute petite", null, ['woman']
generator.add 'physical_detail', "est obèse"
generator.add 'physical_detail', "est vouté"
generator.add 'physical_detail', "est bossu"
generator.add 'physical_detail', "a la peau {skin_color}"
# Ears
generator.add 'physical_detail', "a de gros lobes d'oreille"
generator.add 'physical_detail', "n'a qu'une seule oreille"
generator.add 'physical_detail', "n'a pas de lobe d'oreille"
generator.add 'physical_detail', "a les oreilles décolées"
generator.add 'physical_detail', "a des boucles d'oreille"
generator.add 'physical_detail', "a les oreilles déformées"
# mouth
generator.add 'physical_detail', "a la bouche en cul de poule"
generator.add 'physical_detail', "a un bec de lièvre"
generator.add 'physical_detail', "a des dents parfaites"
#generator.add 'physical_detail', "a des dents pointues"
generator.add 'physical_detail', "a des dents gatées"
#generator.add 'physical_detail', "a des lèvres très fines"
#generator.add 'physical_detail', "a de grosses lèvres"
generator.add 'physical_detail', "a des dents en métal"
generator.add 'physical_detail', "a des dents de lapin"
generator.add 'physical_detail', "a des dents de la chance"
generator.add 'physical_detail', "a des dents manquantes"
generator.add 'physical_detail', "n'a pas de dent"
# Arms
generator.add 'physical_detail', "a un bras manquant"
generator.add 'physical_detail', "a des mains énormes"
generator.add 'physical_detail', "a des tatouages sur les bras"
generator.add 'physical_detail', "a des tatouages sur les mains"
generator.add 'physical_detail', "a une main manquante"
generator.add 'physical_detail', "a des mains disproportionnées"
# Noze
#generator.add 'physical_detail', "a le nez en trompette"
generator.add 'physical_detail', "a le nez cassé"
generator.add 'physical_detail', "a le nez pointu"
#generator.add 'physical_detail', "a un nez de cochon"
generator.add 'physical_detail', "n'a pas de nez"
generator.add 'physical_detail', "a un piercing sur le nez"
# Eyes
generator.add 'physical_detail', "a les yeux verrons"
#generator.add 'physical_detail', "porte des lunettes"
generator.add 'physical_detail', "a un oeuil en moins"
generator.add 'physical_detail', "a les yeux injectés de sang"
#generator.add 'physical_detail', "a un oeuil sans pupille"
generator.add 'physical_detail', "a les yeux très maquillés", null, ['woman']
generator.add 'physical_detail', "a un strabisme"
generator.add 'physical_detail', "a les yeux globuleux"
generator.add 'physical_detail', "n'a pas de sourcils"
# Face
generator.add 'physical_detail', "a une longue barbe", null, ['man']
#generator.add 'physical_detail', "a un percing au visage"
generator.add 'physical_detail', "a des favoris", null, ['man']
generator.add 'physical_detail', "a une moustache", null, ['man']
generator.add 'physical_detail', "est imberbe", null, ['man']
generator.add 'physical_detail', "est mal rasé", null, ['man']
#generator.add 'physical_detail', "a un bouc", null, ['man']
generator.add 'physical_detail', "a des rubans dans sa barbe", null, ['man']
generator.add 'physical_detail', "a des élastiques dans sa barbe", null, ['man']
generator.add 'physical_detail', "a des cicatrices sur le visage"
#generator.add 'physical_detail', "a des piercings sur le visage"
generator.add 'physical_detail', "a le visage trop maquillé", null, ['woman']
generator.add 'physical_detail', "a le visage pâle"
generator.add 'physical_detail', "a des tatouages sur le visage"
#generator.add 'physical_detail', "a les joues roses"
generator.add 'physical_detail', "a des peintures tribales sur le visage"
#generator.add 'physical_detail', "a le visage buriné"
generator.add 'physical_detail', "a de l'acnée"
generator.add 'physical_detail', "a les cheveux rasés"
# Hairs
generator.add 'physical_detail', "a les cheveux rasés"
generator.add 'physical_detail', "a les cheveux {hair_color}"
#generator.add 'physical_detail', "a les cheveux en bataille"
generator.add 'physical_detail', "a les cheveux gras"
generator.add 'physical_detail', "a les cheveux très long"
generator.add 'physical_detail', "a des dessins rasés sur le crane"
generator.add 'physical_detail', "a des couettes"
generator.add 'physical_detail', "a des dreadlocks"
generator.add 'skin_color', "très blanche"
generator.add 'skin_color', "noire"
generator.add 'skin_color', "grise"
generator.add 'skin_color', "jaune"
generator.add 'skin_color', "rouge", null, ['fantasy']
generator.add 'hair_color', "blanc", 3
generator.add 'hair_color', "rose"
generator.add 'hair_color', "poivre et sel"
generator.add 'hair_color', "rouge"
generator.add 'oral_detail', "en répetant « {word_repeat} »", 6
generator.add 'oral_detail', "souvent à des gens absents"
generator.add 'oral_detail', "avec un langage ordurier"
generator.add 'oral_detail', "avec un cheveux sur la langue"
generator.add 'oral_detail', "avec une petite voix"
generator.add 'oral_detail', "avec une voix débile"
generator.add 'oral_detail', "avec une voix suraigue"
generator.add 'oral_detail', "avec une voix chantante"
#generator.add 'oral_detail', "avec de l'accent"
generator.add 'oral_detail', "en beguayant"
generator.add 'oral_detail', "en zozotant"
generator.add 'oral_detail', "en postillionnant"
generator.add 'oral_detail', "en shuintant"
generator.add 'oral_detail', "en marmonant"
generator.add 'oral_detail', "d'une voix monotone"
generator.add 'oral_detail', "d'une voix faible"
generator.add 'oral_detail', "d'une voix nasillarde"
generator.add 'oral_detail', "d'une voix guturale"
generator.add 'oral_detail', "en étant essouflé"
generator.add 'oral_detail', "en articulant excessivement"
generator.add 'oral_detail', "en agitant ses doigts"
generator.add 'oral_detail', "en s'amusant avec un objet"
#generator.add 'oral_detail', "en gesticulant"
generator.add 'oral_detail', "en se carressant la barbe", null, ['man']
#generator.add 'oral_detail', "en changeant d'histoire souvent"
generator.add 'oral_detail', "en recherchant l'approbation de son auditoire"
#generator.add 'oral_detail', "en jouant la comédie"
generator.add 'oral_detail', "en s'adressant à lui même"
generator.add 'oral_detail', "avec fatalisme"
generator.add 'oral_detail', "avec optimisme"
generator.add 'oral_detail', "par questions"
generator.add 'oral_detail', "très vite"
generator.add 'oral_detail', "très lentement"
generator.add 'oral_detail', "avec un vocabulaire réduit"
generator.add 'oral_detail', "en disgressant sans cesse"
generator.add 'oral_detail', "en reniflant"
generator.add 'oral_detail', "de lui par son nom"
generator.add 'oral_detail', "sans s'arrêter"
generator.add 'oral_detail', "en mâchant quelque chose"
generator.add 'oral_detail', "après s'être racler la gorge"
generator.add 'oral_detail', "en évitant les contacts occulaires"
#generator.add 'oral_detail', "en étant très près des gens"
generator.add 'oral_detail', "avec une mauvaise haleine"
generator.add 'oral_detail', "en prenant le temps de répondre"
#generator.add 'oral_detail', "en ayant l'air distrait"
generator.add 'oral_detail', "en voulant être pote"
generator.add 'oral_detail', "sans terminer ses phrases"
generator.add 'oral_detail', "souvent à des gens absents"
generator.add 'oral_detail', "en rôtant régulierement"
generator.add 'oral_detail', "en soupirant régulièrement"
generator.add 'oral_detail', "en tordant la bouche"
#generator.add 'oral_detail', "avec un faux sourire permanent"
#generator.add 'oral_detail', "en se léchant les lêvres"
generator.add 'word_repeat', "Ok !!!"
generator.add 'word_repeat', "Euhhhhh...."
generator.add 'word_repeat', "Tu vois c'que j'veux dire ?"
generator.add 'word_repeat', "Morte de rire"
generator.add 'word_repeat', "Putain"
generator.add 'word_repeat', "Délire"
generator.add 'word_repeat', "Comment on dit déjà ?"
generator.add 'word_repeat', "Délire"
generator.add 'word_repeat', "j'ai toujours révé de dire ça"
generator.add 'start_idea', "C'est {people} {people_adj} qui {interact_with_people} {people} {people_adj}"
generator.add 'start_idea', "C'est {people} {people_adj} qui {interact_with_people} {people} {people_adj} dans {place}"
generator.add 'start_idea', "C'est {people} {people_adj} qui {interact_with_place} {place} {place_adj}"
generator.add 'start_idea', "C'est {people} {people_adj} qui {interact_with_place} {place} {place_adj} avec {people}"
generator.add 'people', "un scientifique"
generator.add 'people', "un gourou"
generator.add 'people', "un chef d'état"
generator.add 'people', "un top model"
generator.add 'people', "un dealer", null, ['!fantasy']
generator.add 'people', "un flic"
generator.add 'people', "une personne riche"
generator.add 'people', "un acteur"
generator.add 'people', "un corporatiste", null, ['cyber']
generator.add 'people', "un fixer", null, ['cyber']
generator.add 'people', "un médecin"
generator.add 'people', "un journaliste"
generator.add 'people', "un mendiant"
generator.add 'people_adj', "fou"
generator.add 'people_adj', "machiavélique"
generator.add 'people_adj', "célèbre"
generator.add 'people_adj', "très vieux"
generator.add 'people_adj', "démoniaque"
generator.add 'people_adj', "généreux"
generator.add 'people_adj', ""
generator.add 'people_adj', ""
generator.add 'people_adj', ""
generator.add 'interact_with_people', "demande de l'aide a"
generator.add 'interact_with_people', "poursuit"
generator.add 'interact_with_people', "recherche"
generator.add 'interact_with_people', "veux séduire"
generator.add 'interact_with_people', "se fait passer pour"
generator.add 'interact_with_people', "torture"
generator.add 'interact_with_people', "s'allie avec"
generator.add 'interact_with_place', "veux s'introduire dans"
generator.add 'interact_with_place', "construit"
generator.add 'interact_with_place', "découvre"
generator.add 'interact_with_place', "détruit"
generator.add 'interact_with_place', "se cache dans"
generator.add 'interact_with_place', "veux s'évader d'"
generator.add 'interact_with_place', "veux se débarrasser d'"
generator.add 'interact_with_place', "achète"
generator.add 'place', "une prison"
generator.add 'place', "un laboratoire"
generator.add 'place', "un hôtel", null, ['!fantasy']
generator.add 'place', "une secte"
generator.add 'place', "une université"
generator.add 'place', "une école"
generator.add 'place', "une morque"
generator.add 'place', "un égout", null, ['!fantasy']
generator.add 'place', "un supermarché", null, ['!fantasy']
generator.add 'place', "un club privé", null, ['!fantasy']
generator.add 'place', "un casino", null, ['!fantasy']
generator.add 'place', "un cinéma", null, ['!fantasy']
generator.add 'place', "une centrale nucléaire", null, ['!fantasy']
generator.add 'place', "une base militaire", null, ['!fantasy']
generator.add 'place', "un asile psychiatrique"
generator.add 'place', "une église"
generator.add 'place', "une forêt"
generator.add 'place', "un château"
generator.add 'place', "une usine", null, ['!fantasy']
generator.add 'place_adj', "illégal(e)"
generator.add 'place_adj', "clandestin(e)"
generator.add 'place_adj', "hanté(e)", null, ['fantasy']
generator.add 'place_adj', "détruit(e)"
generator.add 'place_adj', "désert(e)"
generator.add 'place_adj', "abandoné(e)"
generator.add 'place_adj', "caché(e)"
generator.add 'place_adj', "piégé(e)"
generator.add 'place_adj', "", 2
generator.add 'impro_muse', "{when}"
generator.add 'when', "à la préhistoire {where}, {who} {what}", null, null, ['prehistory']
generator.add 'when', "de nos jours {where}, {who} {what}"
generator.add 'when', "au moyen age {where}, {who} {what}", null, null, ['middle_age']
generator.add 'when', "pendant la guerre {where}, {who} {what}"
generator.add 'when', "dans le futur {where}, {who} {what}"
generator.add 'when', "après une apocalypse {where}, {who} {what}"
generator.add 'when', "pendant la nuit {where}, {who} {what}"
generator.add 'where', "dans la forêt"
generator.add 'where', "dans un supermarché", null, ['!prehistory']
generator.add 'where', "dans un château"
generator.add 'where', "à la plage"
generator.add 'where', "dans un laboratoire", null, ['!prehistory']
generator.add 'where', "sur un bateau", null, ['!prehistory']
generator.add 'where', "sur une île"
generator.add 'where', "chez le dentiste"
generator.add 'where', "chez le coiffeur"
generator.add 'where', "dans un cimetière", null, ['!prehistory']
generator.add 'where', "dans une usine", null, ['!prehistory']
generator.add 'where', "dans une morgue", null, ['!prehistory']
generator.add 'where', "en chine {where}"
generator.add 'where', "en amérique {where}"
generator.add 'where', "en angleterre {where}"
generator.add 'where', "en espagne {where}"
generator.add 'where', "au groenland {where}"
generator.add 'where', "en égypte {where}"
generator.add 'where', "en afrique {where}"
generator.add 'where', "en inde {where}"
generator.add 'where', "dans un labyrinthe"
generator.add 'where', "dans le ciel"
generator.add 'where', "dans un tapis", null, ['!prehistory']
generator.add 'where', "dans l'herbe", null, ['!prehistory']
generator.add 'where', "sous l'eau"
generator.add 'where', "dans un corps vivant"
generator.add 'who', "un homme {who_details}"
generator.add 'who', "une femme {who_details}"
generator.add 'who', "une fillette {who_details}"
generator.add 'who', "un petit garçon {who_details}"
generator.add 'who', "une femme agée {who_details}"
generator.add 'who', "un homme agé {who_details}"
generator.add 'who', "un couple"
generator.add 'who_details', "qui porte un sac à dos"
generator.add 'who_details', "complètement dépressif"
generator.add 'who_details', "complètement lunatique"
generator.add 'who_details', "avec une voix suraigue"
generator.add 'who_details', "avec la bouche en cul de poule"
generator.add 'who_details', "avec un vélo", null, ['!middle_age', '!prehistory']
generator.add 'who_details', "vouté"
generator.add 'who_details', "wesh wesh", null, ['!middle_age', '!prehistory']
generator.add 'who_details', "très distingué"
generator.add 'who_details', "complètement fou"
generator.add 'who_details', "en colère"
generator.add 'who_details', "qui n'a pas le sens de l'orientation"
generator.add 'who_details', "avec un animal de compagnie"
generator.add 'who_details', "qui a les pieds collés au sol"
generator.add 'who_details', "malhonnnète"
#domains.who_details.add ""
generator.add 'what', "coupe du bois"
generator.add 'what', "joue au tennis", null, ['!middle_age', '!prehistory']
generator.add 'what', "fait des tags", null, ['!middle_age', '!prehistory']
generator.add 'what', "travaille le jardin"
generator.add 'what', "démine une bombe", null, ['!middle_age', '!prehistory']
generator.add 'what', "passe le permis", null, ['!middle_age', '!prehistory']
generator.add 'what', "dispense un cours"
generator.add 'what', "écrit un poème"
generator.add 'what', "fait des ricochets"
generator.add 'what', "fabrique une potion"
generator.add 'what', "réalise une expérience scientifique"
generator.add 'what', "pêche des poissons"
generator.add 'what', "fait du ski", null, ['!middle_age', '!prehistory']
generator.add 'what', "vole un objet précieux"
generator.add 'motivation', "la vengeance"
generator.add 'motivation', "la faim"
generator.add 'motivation', "le désir"
generator.add 'motivation', "la haine"
generator.add 'motivation', "la jalousie"
generator.add 'motivation', "le pouvoir"
actions = [
'Sépare-les',
'Capture quelqu’un',
'Coinces-en un',
'Rends coups pour coups (dégâts établis)',
'Annonce une emmerde à venir',
'Annonce une emmerde hors-champ',
'Inflige des dégâts (comme établis)',
'Prive-les de leur matos',
'Fais-les passer à la caisse',
'Déclenche les défauts de leur matos',
'Dis-leur ce qu’il risque de se passer et redemande',
'Offre-leur une opportunité, avec ou sans prix à payer',
'Retourne leur propre action contre eux',
'Choisis une action d’une de tes menaces ( venant d’un front)'
]
generator.add 'action', actions
generator.add 'threat', '{warlord}'
generator.add 'threat', '{landscape}'
generator.add 'threat', '{brutes}'
generator.add 'threat', '{afflictions}'
generator.add 'threat', '{grotesque}'
generator.add 'warlord', 'un esclavagiste'
generator.add 'warlord', 'une reine mère'
generator.add 'warlord', 'un prophète'
generator.add 'warlord', 'un dictateur'
generator.add 'warlord', 'un conquérant'
generator.add 'warlord', 'un male alpha'
generator.add 'brutes', "un chasseur d'homme"
generator.add 'brutes', "un parasite"
generator.add 'brutes', "un culte/une secte"
generator.add 'brutes', "une famille"
generator.add 'brutes', "un homme de main"
generator.add 'brutes', "une foule en colère"
generator.add 'afflictions', 'une maladie'
generator.add 'afflictions', 'une illusion'
generator.add 'afflictions', 'une barière'
generator.add 'afflictions', 'une coutume'
generator.add 'afflictions', 'une innondation'
generator.add 'afflictions', 'un orage'
generator.add 'afflictions', 'une sècheresse'
generator.add 'afflictions', 'une invasion de {invade_type}'
generator.add 'invade_type', 'sauterelles'
generator.add 'invade_type', 'mouches'
generator.add 'invade_type', 'serpents'
generator.add 'invade_type', 'larves'
generator.add 'invade_type', 'grenouilles'
generator.add 'invade_type', 'fourmis'
generator.add 'invade_type', 'chat'
generator.add 'invade_type', 'chien'
generator.add 'grotesque', 'un cannibal'
generator.add 'grotesque', 'un mutant'
generator.add 'grotesque', 'un masochiste'
generator.add 'grotesque', 'un être malformé'
generator.add 'grotesque', 'un fou'
generator.add 'grotesque', 'un malade contagieux'
generator.add 'landscape', 'une prison'
generator.add 'landscape', 'un lieu maudit'
generator.add 'landscape', 'une fournaise'
generator.add 'landscape', 'un mirage'
generator.add 'landscape', 'un labyrinthe'
generator.add 'landscape', 'une forteresse'
generator.add 'landscape', 'un effondrement'
# Story part generator
generator.add 'story_part', 'Lieu : {story_place}'
generator.add 'story_part', 'Personne : {story_people}'
generator.add 'story_part', 'Evénement : {story_event}'
generator.add 'story_part', 'Objet : {story_object}'
generator.add 'story_part', 'Sensation : {story_feeling}'
generator.add 'story_place', 'un escalier {story_adj_ojb}'
generator.add 'story_place', 'une chambre {story_adj_ojb}'
generator.add 'story_place', 'un train {story_adj_ojb}'
generator.add 'story_place', 'au sol'
generator.add 'story_place', 'en l\'air'
generator.add 'story_place', 'sous terre'
generator.add 'story_place', '{place} {place_adj}', 2
generator.add 'story_place', '{landscape}', 2
generator.add 'story_people', '{people}'
generator.add 'story_people', '{grotesque}'
generator.add 'story_people', '{brutes}'
generator.add 'story_people', '{warlord}'
generator.add 'story_event', 'une poursuite'
generator.add 'story_event', 'une séduction'
generator.add 'story_event', 'une chute'
generator.add 'story_event', 'une usurpation d\'identité'
generator.add 'story_event', 'une rencontre innatendue'
generator.add 'story_event', 'une rencontre inéspérée'
generator.add 'story_event', 'une erreur sur la personne'
generator.add 'story_event', 'un orage'
generator.add 'story_event', 'une pluie'
generator.add 'story_event', 'une tempête'
generator.add 'story_event', 'un saut temporel', null, ['sci-fi']
generator.add 'story_event', 'une embuscade'
generator.add 'story_event', 'une bonne surprise'
generator.add 'story_event', 'une mauvaise surprise'
generator.add 'story_event', 'un cri horrible'
generator.add 'story_event', 'affliction', 3
generator.add 'story_object', '{story_obj} {story_adj_ojb}'
generator.add 'story_obj', 'un livre'
generator.add 'story_obj', 'un dé'
generator.add 'story_obj', 'une chaise'
generator.add 'story_obj', 'un ordinateur'
generator.add 'story_obj', 'un sac'
generator.add 'story_obj', 'un stylo'
generator.add 'story_obj', 'une arme'
generator.add 'story_obj', 'un outil'
generator.add 'story_obj', 'une paire de chaussure'
generator.add 'story_obj', 'un véhicule'
generator.add 'story_obj', 'une paire de lunette'
generator.add 'story_obj', 'une montre'
generator.add 'story_obj', 'une carte géographique'
generator.add 'story_adj_ojb', 'cassé(e)'
generator.add 'story_adj_ojb', 'magique'
generator.add 'story_adj_ojb', 'maudit(e)'
generator.add 'story_adj_ojb', 'dangereux(se)'
generator.add 'story_adj_ojb', 'piégé(e)'
generator.add 'story_feeling', 'une odeur horrible'
generator.add 'story_feeling', 'une odeur agréable'
generator.add 'story_feeling', 'il fait très chaud'
generator.add 'story_feeling', 'il fait très froid'
generator.add 'story_feeling', 'le sommeil'
generator.add 'story_feeling', 'la fatigue'
generator.add 'story_feeling', '{motivation}'
generator.add 'story_adj_feel', 'ignoble'
generator.add 'story_adj_feel', 'agréable'
generator.add 'story_adj_feel', 'horrible'
generator.add 'story_adj_feel', 'étonnant(e)'
| true | # Import
angular.module('rpghelperApp').run (generator) ->
generator.add 'start', '{sex}'
generator.add 'sex', "<b>{firstname}</b> est une femme {intro}<br>C'est une personne {first_impression} motivée par {motivation}.", null, ['!man'], ['woman']
generator.add 'sex', "<b>{firstname}</b> est un homme {intro}<br>C'est une personne {first_impression} motivée par {motivation}.", null, ['!woman'], ['man']
generator.add 'intro', '{age} {type} qui {physical_detail} et qui parle {oral_detail}.'
w_names = [
'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'la fille de PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'B-A', 'la Souris',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'Entretoise', 'Victoire',
'DPI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'III', 'Herse', 'Levant', 'BouilloPI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PePI:NAME:<NAME>END_PI', 'Li', 'PI:NAME:<NAME>END_PIie', 'Fa', 'RPI:NAME:<NAME>END_PIée', 'Fusible',
'Visage', 'Gueularde',
'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PIlette', 'Pomme de Pin',
'la Suissesse'
]
m_names = [
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'
]
for name in w_names
generator.add 'firstname', name, null, ['woman'], ['woman'], {name: name}
for name in m_names
generator.add 'firstname', name, null, ['man'], ['man'], {name: name}
generator.add 'type', ""
generator.add 'type', "humain ", null, ['fantasy']
generator.add 'type', "nain ", null, ['fantasy']
generator.add 'type', "elfe ", null, ['fantasy']
generator.add 'type', "orc ", null, ['fantasy']
generator.add 'type', "troll ", null, ['fantasy']
generator.add 'age', 'agé', null, ['man']
generator.add 'age', 'agée', null, ['woman']
generator.add 'age', 'jeune'
generator.add 'age', '', 6
generator.add 'first_impression', "séduisante"
generator.add 'first_impression', "dégoutante"
generator.add 'first_impression', "mystérieuse"
generator.add 'first_impression', "étonnante"
generator.add 'first_impression', "impressionnante"
generator.add 'first_impression', "calme"
generator.add 'first_impression', "qui inspire la confiance"
generator.add 'first_impression', "banale", 10
generator.add 'first_impression', "hideuse"
generator.add 'first_impression', "chétive"
generator.add 'first_impression', "triste"
generator.add 'first_impression', "qui semble malade"
# body
#generator.add 'physical_detail', "est mince"
generator.add 'physical_detail', "est rachitique"
generator.add 'physical_detail', "est albinos", 0.3
generator.add 'physical_detail', "a un gros bide"
generator.add 'physical_detail', "est très grand", null, ['man']
generator.add 'physical_detail', "est très musclé", null, ['man']
generator.add 'physical_detail', "est tout rond", null, ['man']
generator.add 'physical_detail', "est tout petit", null, ['man']
generator.add 'physical_detail', "est très grande", null, ['woman']
generator.add 'physical_detail', "est très musclée", null, ['woman']
generator.add 'physical_detail', "est toute ronde", null, ['woman']
generator.add 'physical_detail', "est toute petite", null, ['woman']
generator.add 'physical_detail', "est obèse"
generator.add 'physical_detail', "est vouté"
generator.add 'physical_detail', "est bossu"
generator.add 'physical_detail', "a la peau {skin_color}"
# Ears
generator.add 'physical_detail', "a de gros lobes d'oreille"
generator.add 'physical_detail', "n'a qu'une seule oreille"
generator.add 'physical_detail', "n'a pas de lobe d'oreille"
generator.add 'physical_detail', "a les oreilles décolées"
generator.add 'physical_detail', "a des boucles d'oreille"
generator.add 'physical_detail', "a les oreilles déformées"
# mouth
generator.add 'physical_detail', "a la bouche en cul de poule"
generator.add 'physical_detail', "a un bec de lièvre"
generator.add 'physical_detail', "a des dents parfaites"
#generator.add 'physical_detail', "a des dents pointues"
generator.add 'physical_detail', "a des dents gatées"
#generator.add 'physical_detail', "a des lèvres très fines"
#generator.add 'physical_detail', "a de grosses lèvres"
generator.add 'physical_detail', "a des dents en métal"
generator.add 'physical_detail', "a des dents de lapin"
generator.add 'physical_detail', "a des dents de la chance"
generator.add 'physical_detail', "a des dents manquantes"
generator.add 'physical_detail', "n'a pas de dent"
# Arms
generator.add 'physical_detail', "a un bras manquant"
generator.add 'physical_detail', "a des mains énormes"
generator.add 'physical_detail', "a des tatouages sur les bras"
generator.add 'physical_detail', "a des tatouages sur les mains"
generator.add 'physical_detail', "a une main manquante"
generator.add 'physical_detail', "a des mains disproportionnées"
# Noze
#generator.add 'physical_detail', "a le nez en trompette"
generator.add 'physical_detail', "a le nez cassé"
generator.add 'physical_detail', "a le nez pointu"
#generator.add 'physical_detail', "a un nez de cochon"
generator.add 'physical_detail', "n'a pas de nez"
generator.add 'physical_detail', "a un piercing sur le nez"
# Eyes
generator.add 'physical_detail', "a les yeux verrons"
#generator.add 'physical_detail', "porte des lunettes"
generator.add 'physical_detail', "a un oeuil en moins"
generator.add 'physical_detail', "a les yeux injectés de sang"
#generator.add 'physical_detail', "a un oeuil sans pupille"
generator.add 'physical_detail', "a les yeux très maquillés", null, ['woman']
generator.add 'physical_detail', "a un strabisme"
generator.add 'physical_detail', "a les yeux globuleux"
generator.add 'physical_detail', "n'a pas de sourcils"
# Face
generator.add 'physical_detail', "a une longue barbe", null, ['man']
#generator.add 'physical_detail', "a un percing au visage"
generator.add 'physical_detail', "a des favoris", null, ['man']
generator.add 'physical_detail', "a une moustache", null, ['man']
generator.add 'physical_detail', "est imberbe", null, ['man']
generator.add 'physical_detail', "est mal rasé", null, ['man']
#generator.add 'physical_detail', "a un bouc", null, ['man']
generator.add 'physical_detail', "a des rubans dans sa barbe", null, ['man']
generator.add 'physical_detail', "a des élastiques dans sa barbe", null, ['man']
generator.add 'physical_detail', "a des cicatrices sur le visage"
#generator.add 'physical_detail', "a des piercings sur le visage"
generator.add 'physical_detail', "a le visage trop maquillé", null, ['woman']
generator.add 'physical_detail', "a le visage pâle"
generator.add 'physical_detail', "a des tatouages sur le visage"
#generator.add 'physical_detail', "a les joues roses"
generator.add 'physical_detail', "a des peintures tribales sur le visage"
#generator.add 'physical_detail', "a le visage buriné"
generator.add 'physical_detail', "a de l'acnée"
generator.add 'physical_detail', "a les cheveux rasés"
# Hairs
generator.add 'physical_detail', "a les cheveux rasés"
generator.add 'physical_detail', "a les cheveux {hair_color}"
#generator.add 'physical_detail', "a les cheveux en bataille"
generator.add 'physical_detail', "a les cheveux gras"
generator.add 'physical_detail', "a les cheveux très long"
generator.add 'physical_detail', "a des dessins rasés sur le crane"
generator.add 'physical_detail', "a des couettes"
generator.add 'physical_detail', "a des dreadlocks"
generator.add 'skin_color', "très blanche"
generator.add 'skin_color', "noire"
generator.add 'skin_color', "grise"
generator.add 'skin_color', "jaune"
generator.add 'skin_color', "rouge", null, ['fantasy']
generator.add 'hair_color', "blanc", 3
generator.add 'hair_color', "rose"
generator.add 'hair_color', "poivre et sel"
generator.add 'hair_color', "rouge"
generator.add 'oral_detail', "en répetant « {word_repeat} »", 6
generator.add 'oral_detail', "souvent à des gens absents"
generator.add 'oral_detail', "avec un langage ordurier"
generator.add 'oral_detail', "avec un cheveux sur la langue"
generator.add 'oral_detail', "avec une petite voix"
generator.add 'oral_detail', "avec une voix débile"
generator.add 'oral_detail', "avec une voix suraigue"
generator.add 'oral_detail', "avec une voix chantante"
#generator.add 'oral_detail', "avec de l'accent"
generator.add 'oral_detail', "en beguayant"
generator.add 'oral_detail', "en zozotant"
generator.add 'oral_detail', "en postillionnant"
generator.add 'oral_detail', "en shuintant"
generator.add 'oral_detail', "en marmonant"
generator.add 'oral_detail', "d'une voix monotone"
generator.add 'oral_detail', "d'une voix faible"
generator.add 'oral_detail', "d'une voix nasillarde"
generator.add 'oral_detail', "d'une voix guturale"
generator.add 'oral_detail', "en étant essouflé"
generator.add 'oral_detail', "en articulant excessivement"
generator.add 'oral_detail', "en agitant ses doigts"
generator.add 'oral_detail', "en s'amusant avec un objet"
#generator.add 'oral_detail', "en gesticulant"
generator.add 'oral_detail', "en se carressant la barbe", null, ['man']
#generator.add 'oral_detail', "en changeant d'histoire souvent"
generator.add 'oral_detail', "en recherchant l'approbation de son auditoire"
#generator.add 'oral_detail', "en jouant la comédie"
generator.add 'oral_detail', "en s'adressant à lui même"
generator.add 'oral_detail', "avec fatalisme"
generator.add 'oral_detail', "avec optimisme"
generator.add 'oral_detail', "par questions"
generator.add 'oral_detail', "très vite"
generator.add 'oral_detail', "très lentement"
generator.add 'oral_detail', "avec un vocabulaire réduit"
generator.add 'oral_detail', "en disgressant sans cesse"
generator.add 'oral_detail', "en reniflant"
generator.add 'oral_detail', "de lui par son nom"
generator.add 'oral_detail', "sans s'arrêter"
generator.add 'oral_detail', "en mâchant quelque chose"
generator.add 'oral_detail', "après s'être racler la gorge"
generator.add 'oral_detail', "en évitant les contacts occulaires"
#generator.add 'oral_detail', "en étant très près des gens"
generator.add 'oral_detail', "avec une mauvaise haleine"
generator.add 'oral_detail', "en prenant le temps de répondre"
#generator.add 'oral_detail', "en ayant l'air distrait"
generator.add 'oral_detail', "en voulant être pote"
generator.add 'oral_detail', "sans terminer ses phrases"
generator.add 'oral_detail', "souvent à des gens absents"
generator.add 'oral_detail', "en rôtant régulierement"
generator.add 'oral_detail', "en soupirant régulièrement"
generator.add 'oral_detail', "en tordant la bouche"
#generator.add 'oral_detail', "avec un faux sourire permanent"
#generator.add 'oral_detail', "en se léchant les lêvres"
generator.add 'word_repeat', "Ok !!!"
generator.add 'word_repeat', "Euhhhhh...."
generator.add 'word_repeat', "Tu vois c'que j'veux dire ?"
generator.add 'word_repeat', "Morte de rire"
generator.add 'word_repeat', "Putain"
generator.add 'word_repeat', "Délire"
generator.add 'word_repeat', "Comment on dit déjà ?"
generator.add 'word_repeat', "Délire"
generator.add 'word_repeat', "j'ai toujours révé de dire ça"
generator.add 'start_idea', "C'est {people} {people_adj} qui {interact_with_people} {people} {people_adj}"
generator.add 'start_idea', "C'est {people} {people_adj} qui {interact_with_people} {people} {people_adj} dans {place}"
generator.add 'start_idea', "C'est {people} {people_adj} qui {interact_with_place} {place} {place_adj}"
generator.add 'start_idea', "C'est {people} {people_adj} qui {interact_with_place} {place} {place_adj} avec {people}"
generator.add 'people', "un scientifique"
generator.add 'people', "un gourou"
generator.add 'people', "un chef d'état"
generator.add 'people', "un top model"
generator.add 'people', "un dealer", null, ['!fantasy']
generator.add 'people', "un flic"
generator.add 'people', "une personne riche"
generator.add 'people', "un acteur"
generator.add 'people', "un corporatiste", null, ['cyber']
generator.add 'people', "un fixer", null, ['cyber']
generator.add 'people', "un médecin"
generator.add 'people', "un journaliste"
generator.add 'people', "un mendiant"
generator.add 'people_adj', "fou"
generator.add 'people_adj', "machiavélique"
generator.add 'people_adj', "célèbre"
generator.add 'people_adj', "très vieux"
generator.add 'people_adj', "démoniaque"
generator.add 'people_adj', "généreux"
generator.add 'people_adj', ""
generator.add 'people_adj', ""
generator.add 'people_adj', ""
generator.add 'interact_with_people', "demande de l'aide a"
generator.add 'interact_with_people', "poursuit"
generator.add 'interact_with_people', "recherche"
generator.add 'interact_with_people', "veux séduire"
generator.add 'interact_with_people', "se fait passer pour"
generator.add 'interact_with_people', "torture"
generator.add 'interact_with_people', "s'allie avec"
generator.add 'interact_with_place', "veux s'introduire dans"
generator.add 'interact_with_place', "construit"
generator.add 'interact_with_place', "découvre"
generator.add 'interact_with_place', "détruit"
generator.add 'interact_with_place', "se cache dans"
generator.add 'interact_with_place', "veux s'évader d'"
generator.add 'interact_with_place', "veux se débarrasser d'"
generator.add 'interact_with_place', "achète"
generator.add 'place', "une prison"
generator.add 'place', "un laboratoire"
generator.add 'place', "un hôtel", null, ['!fantasy']
generator.add 'place', "une secte"
generator.add 'place', "une université"
generator.add 'place', "une école"
generator.add 'place', "une morque"
generator.add 'place', "un égout", null, ['!fantasy']
generator.add 'place', "un supermarché", null, ['!fantasy']
generator.add 'place', "un club privé", null, ['!fantasy']
generator.add 'place', "un casino", null, ['!fantasy']
generator.add 'place', "un cinéma", null, ['!fantasy']
generator.add 'place', "une centrale nucléaire", null, ['!fantasy']
generator.add 'place', "une base militaire", null, ['!fantasy']
generator.add 'place', "un asile psychiatrique"
generator.add 'place', "une église"
generator.add 'place', "une forêt"
generator.add 'place', "un château"
generator.add 'place', "une usine", null, ['!fantasy']
generator.add 'place_adj', "illégal(e)"
generator.add 'place_adj', "clandestin(e)"
generator.add 'place_adj', "hanté(e)", null, ['fantasy']
generator.add 'place_adj', "détruit(e)"
generator.add 'place_adj', "désert(e)"
generator.add 'place_adj', "abandoné(e)"
generator.add 'place_adj', "caché(e)"
generator.add 'place_adj', "piégé(e)"
generator.add 'place_adj', "", 2
generator.add 'impro_muse', "{when}"
generator.add 'when', "à la préhistoire {where}, {who} {what}", null, null, ['prehistory']
generator.add 'when', "de nos jours {where}, {who} {what}"
generator.add 'when', "au moyen age {where}, {who} {what}", null, null, ['middle_age']
generator.add 'when', "pendant la guerre {where}, {who} {what}"
generator.add 'when', "dans le futur {where}, {who} {what}"
generator.add 'when', "après une apocalypse {where}, {who} {what}"
generator.add 'when', "pendant la nuit {where}, {who} {what}"
generator.add 'where', "dans la forêt"
generator.add 'where', "dans un supermarché", null, ['!prehistory']
generator.add 'where', "dans un château"
generator.add 'where', "à la plage"
generator.add 'where', "dans un laboratoire", null, ['!prehistory']
generator.add 'where', "sur un bateau", null, ['!prehistory']
generator.add 'where', "sur une île"
generator.add 'where', "chez le dentiste"
generator.add 'where', "chez le coiffeur"
generator.add 'where', "dans un cimetière", null, ['!prehistory']
generator.add 'where', "dans une usine", null, ['!prehistory']
generator.add 'where', "dans une morgue", null, ['!prehistory']
generator.add 'where', "en chine {where}"
generator.add 'where', "en amérique {where}"
generator.add 'where', "en angleterre {where}"
generator.add 'where', "en espagne {where}"
generator.add 'where', "au groenland {where}"
generator.add 'where', "en égypte {where}"
generator.add 'where', "en afrique {where}"
generator.add 'where', "en inde {where}"
generator.add 'where', "dans un labyrinthe"
generator.add 'where', "dans le ciel"
generator.add 'where', "dans un tapis", null, ['!prehistory']
generator.add 'where', "dans l'herbe", null, ['!prehistory']
generator.add 'where', "sous l'eau"
generator.add 'where', "dans un corps vivant"
generator.add 'who', "un homme {who_details}"
generator.add 'who', "une femme {who_details}"
generator.add 'who', "une fillette {who_details}"
generator.add 'who', "un petit garçon {who_details}"
generator.add 'who', "une femme agée {who_details}"
generator.add 'who', "un homme agé {who_details}"
generator.add 'who', "un couple"
generator.add 'who_details', "qui porte un sac à dos"
generator.add 'who_details', "complètement dépressif"
generator.add 'who_details', "complètement lunatique"
generator.add 'who_details', "avec une voix suraigue"
generator.add 'who_details', "avec la bouche en cul de poule"
generator.add 'who_details', "avec un vélo", null, ['!middle_age', '!prehistory']
generator.add 'who_details', "vouté"
generator.add 'who_details', "wesh wesh", null, ['!middle_age', '!prehistory']
generator.add 'who_details', "très distingué"
generator.add 'who_details', "complètement fou"
generator.add 'who_details', "en colère"
generator.add 'who_details', "qui n'a pas le sens de l'orientation"
generator.add 'who_details', "avec un animal de compagnie"
generator.add 'who_details', "qui a les pieds collés au sol"
generator.add 'who_details', "malhonnnète"
#domains.who_details.add ""
generator.add 'what', "coupe du bois"
generator.add 'what', "joue au tennis", null, ['!middle_age', '!prehistory']
generator.add 'what', "fait des tags", null, ['!middle_age', '!prehistory']
generator.add 'what', "travaille le jardin"
generator.add 'what', "démine une bombe", null, ['!middle_age', '!prehistory']
generator.add 'what', "passe le permis", null, ['!middle_age', '!prehistory']
generator.add 'what', "dispense un cours"
generator.add 'what', "écrit un poème"
generator.add 'what', "fait des ricochets"
generator.add 'what', "fabrique une potion"
generator.add 'what', "réalise une expérience scientifique"
generator.add 'what', "pêche des poissons"
generator.add 'what', "fait du ski", null, ['!middle_age', '!prehistory']
generator.add 'what', "vole un objet précieux"
generator.add 'motivation', "la vengeance"
generator.add 'motivation', "la faim"
generator.add 'motivation', "le désir"
generator.add 'motivation', "la haine"
generator.add 'motivation', "la jalousie"
generator.add 'motivation', "le pouvoir"
actions = [
'Sépare-les',
'Capture quelqu’un',
'Coinces-en un',
'Rends coups pour coups (dégâts établis)',
'Annonce une emmerde à venir',
'Annonce une emmerde hors-champ',
'Inflige des dégâts (comme établis)',
'Prive-les de leur matos',
'Fais-les passer à la caisse',
'Déclenche les défauts de leur matos',
'Dis-leur ce qu’il risque de se passer et redemande',
'Offre-leur une opportunité, avec ou sans prix à payer',
'Retourne leur propre action contre eux',
'Choisis une action d’une de tes menaces ( venant d’un front)'
]
generator.add 'action', actions
generator.add 'threat', '{warlord}'
generator.add 'threat', '{landscape}'
generator.add 'threat', '{brutes}'
generator.add 'threat', '{afflictions}'
generator.add 'threat', '{grotesque}'
generator.add 'warlord', 'un esclavagiste'
generator.add 'warlord', 'une reine mère'
generator.add 'warlord', 'un prophète'
generator.add 'warlord', 'un dictateur'
generator.add 'warlord', 'un conquérant'
generator.add 'warlord', 'un male alpha'
generator.add 'brutes', "un chasseur d'homme"
generator.add 'brutes', "un parasite"
generator.add 'brutes', "un culte/une secte"
generator.add 'brutes', "une famille"
generator.add 'brutes', "un homme de main"
generator.add 'brutes', "une foule en colère"
generator.add 'afflictions', 'une maladie'
generator.add 'afflictions', 'une illusion'
generator.add 'afflictions', 'une barière'
generator.add 'afflictions', 'une coutume'
generator.add 'afflictions', 'une innondation'
generator.add 'afflictions', 'un orage'
generator.add 'afflictions', 'une sècheresse'
generator.add 'afflictions', 'une invasion de {invade_type}'
generator.add 'invade_type', 'sauterelles'
generator.add 'invade_type', 'mouches'
generator.add 'invade_type', 'serpents'
generator.add 'invade_type', 'larves'
generator.add 'invade_type', 'grenouilles'
generator.add 'invade_type', 'fourmis'
generator.add 'invade_type', 'chat'
generator.add 'invade_type', 'chien'
generator.add 'grotesque', 'un cannibal'
generator.add 'grotesque', 'un mutant'
generator.add 'grotesque', 'un masochiste'
generator.add 'grotesque', 'un être malformé'
generator.add 'grotesque', 'un fou'
generator.add 'grotesque', 'un malade contagieux'
generator.add 'landscape', 'une prison'
generator.add 'landscape', 'un lieu maudit'
generator.add 'landscape', 'une fournaise'
generator.add 'landscape', 'un mirage'
generator.add 'landscape', 'un labyrinthe'
generator.add 'landscape', 'une forteresse'
generator.add 'landscape', 'un effondrement'
# Story part generator
generator.add 'story_part', 'Lieu : {story_place}'
generator.add 'story_part', 'Personne : {story_people}'
generator.add 'story_part', 'Evénement : {story_event}'
generator.add 'story_part', 'Objet : {story_object}'
generator.add 'story_part', 'Sensation : {story_feeling}'
generator.add 'story_place', 'un escalier {story_adj_ojb}'
generator.add 'story_place', 'une chambre {story_adj_ojb}'
generator.add 'story_place', 'un train {story_adj_ojb}'
generator.add 'story_place', 'au sol'
generator.add 'story_place', 'en l\'air'
generator.add 'story_place', 'sous terre'
generator.add 'story_place', '{place} {place_adj}', 2
generator.add 'story_place', '{landscape}', 2
generator.add 'story_people', '{people}'
generator.add 'story_people', '{grotesque}'
generator.add 'story_people', '{brutes}'
generator.add 'story_people', '{warlord}'
generator.add 'story_event', 'une poursuite'
generator.add 'story_event', 'une séduction'
generator.add 'story_event', 'une chute'
generator.add 'story_event', 'une usurpation d\'identité'
generator.add 'story_event', 'une rencontre innatendue'
generator.add 'story_event', 'une rencontre inéspérée'
generator.add 'story_event', 'une erreur sur la personne'
generator.add 'story_event', 'un orage'
generator.add 'story_event', 'une pluie'
generator.add 'story_event', 'une tempête'
generator.add 'story_event', 'un saut temporel', null, ['sci-fi']
generator.add 'story_event', 'une embuscade'
generator.add 'story_event', 'une bonne surprise'
generator.add 'story_event', 'une mauvaise surprise'
generator.add 'story_event', 'un cri horrible'
generator.add 'story_event', 'affliction', 3
generator.add 'story_object', '{story_obj} {story_adj_ojb}'
generator.add 'story_obj', 'un livre'
generator.add 'story_obj', 'un dé'
generator.add 'story_obj', 'une chaise'
generator.add 'story_obj', 'un ordinateur'
generator.add 'story_obj', 'un sac'
generator.add 'story_obj', 'un stylo'
generator.add 'story_obj', 'une arme'
generator.add 'story_obj', 'un outil'
generator.add 'story_obj', 'une paire de chaussure'
generator.add 'story_obj', 'un véhicule'
generator.add 'story_obj', 'une paire de lunette'
generator.add 'story_obj', 'une montre'
generator.add 'story_obj', 'une carte géographique'
generator.add 'story_adj_ojb', 'cassé(e)'
generator.add 'story_adj_ojb', 'magique'
generator.add 'story_adj_ojb', 'maudit(e)'
generator.add 'story_adj_ojb', 'dangereux(se)'
generator.add 'story_adj_ojb', 'piégé(e)'
generator.add 'story_feeling', 'une odeur horrible'
generator.add 'story_feeling', 'une odeur agréable'
generator.add 'story_feeling', 'il fait très chaud'
generator.add 'story_feeling', 'il fait très froid'
generator.add 'story_feeling', 'le sommeil'
generator.add 'story_feeling', 'la fatigue'
generator.add 'story_feeling', '{motivation}'
generator.add 'story_adj_feel', 'ignoble'
generator.add 'story_adj_feel', 'agréable'
generator.add 'story_adj_feel', 'horrible'
generator.add 'story_adj_feel', 'étonnant(e)'
|
[
{
"context": "nucode:stats:total:docs'\n\n\tloadDoc: (id, cb) ->\n\t\t#@session.channel.unsubscribeAll()\n\t\t@session.channel.subscribe(id)\n\t\tdocID = text",
"end": 2109,
"score": 0.9347808361053467,
"start": 2077,
"tag": "EMAIL",
"value": "#@session.channel.unsubscribeAll"
}
] | app/server/app.coffee | werg/snucode | 4 | # Server-side Code
textID2RedisKey = (id) ->
"snucode:doc:" + id
createDocID = (cb) ->
id = Math.random().toString(36).substring(7)
R.exists textID2RedisKey(id), (err, exists) ->
if exists
createDocID cb
else
# todo: this does not create a new document
# so there could be race conditions
cb id
validColor = (color) ->
numval = parseInt color.substring(1), 16
color[0] is '#' and numval < 16777216 and numval >= 0
validUserID = (user_id) ->
result = true
for c in user_id.toLowerCase().split()
result = result and not isNaN parseInt c, 36
return result
validAuthor = (author) ->
validColor(author.color) and validUserID(author.user_id)
setColor = (author, textID, cb) ->
colorKey = textID2RedisKey(textID) + ':colors'
R.hset colorKey, author.user_id, author.color, cb
exports.actions =
pushChange: (change, cb) ->
change.socket_id = @request.socket_id
SS.publish.channel [change.textID], 'newChange', change
color = @session.attributes.author.color
user_id = @session.attributes.author.user_id
rid = textID2RedisKey(change.textID)
redis_args = [rid]
for addC in change.addChars
redis_args.push addC.place
redis_args.push addC.id
R.zadd redis_args, ->
redis_args = [rid]
R.zrem redis_args.concat(change.removeCharIDs), ->
R.hset rid + ':color', user_id, color, ->
cb()
setAuthor: (author, cb) ->
if validAuthor(author)
unless @session.attributes?
@session.attributes = {}
@session.attributes.author = author
@session.save ->
cb true
else
cb false
getAuthor: (cb) ->
if @session.attributes.author?
cb @session.attributes.author
else
R.incr 'snucode:stats:total:authors'
cb false
setColor: (textID, cb) ->
setColor @session.attributes.author, textID, cb
# to do broadcast some kind of color change message?
authorOnline: (textID, cb) ->
if @session.attributes.author?
SS.publish.channel [textID], 'authorOnline', @session.attributes.author
cb()
newDocID: (cb) ->
createDocID cb
R.incr 'snucode:stats:total:docs'
loadDoc: (id, cb) ->
#@session.channel.unsubscribeAll()
@session.channel.subscribe(id)
docID = textID2RedisKey(id)
# delete document after two weeks
R.expire docID, 1209600
R.expire docID + ':authors', 1209600
R.incr 'snucode:stats:total:loads'
# retrieve doc
R.zrange docID, 0,-1,"withscores", (err, pchars) ->
chars = []
while pchars.length > 0
p = pchars.pop()
id = pchars.pop()
val = id[id.length-1]
auth = id.split(':')[1]
chars.push
'value': val
'id': id
'place': parseFloat(p)
'author': auth
R.hgetall docID + ':authors', (authors) ->
cb chars, authors
calcOffset: (clientTime, cb) ->
# todo: check whether it's Date.now
cb Date.now() - clientTime
| 681 | # Server-side Code
textID2RedisKey = (id) ->
"snucode:doc:" + id
createDocID = (cb) ->
id = Math.random().toString(36).substring(7)
R.exists textID2RedisKey(id), (err, exists) ->
if exists
createDocID cb
else
# todo: this does not create a new document
# so there could be race conditions
cb id
validColor = (color) ->
numval = parseInt color.substring(1), 16
color[0] is '#' and numval < 16777216 and numval >= 0
validUserID = (user_id) ->
result = true
for c in user_id.toLowerCase().split()
result = result and not isNaN parseInt c, 36
return result
validAuthor = (author) ->
validColor(author.color) and validUserID(author.user_id)
setColor = (author, textID, cb) ->
colorKey = textID2RedisKey(textID) + ':colors'
R.hset colorKey, author.user_id, author.color, cb
exports.actions =
pushChange: (change, cb) ->
change.socket_id = @request.socket_id
SS.publish.channel [change.textID], 'newChange', change
color = @session.attributes.author.color
user_id = @session.attributes.author.user_id
rid = textID2RedisKey(change.textID)
redis_args = [rid]
for addC in change.addChars
redis_args.push addC.place
redis_args.push addC.id
R.zadd redis_args, ->
redis_args = [rid]
R.zrem redis_args.concat(change.removeCharIDs), ->
R.hset rid + ':color', user_id, color, ->
cb()
setAuthor: (author, cb) ->
if validAuthor(author)
unless @session.attributes?
@session.attributes = {}
@session.attributes.author = author
@session.save ->
cb true
else
cb false
getAuthor: (cb) ->
if @session.attributes.author?
cb @session.attributes.author
else
R.incr 'snucode:stats:total:authors'
cb false
setColor: (textID, cb) ->
setColor @session.attributes.author, textID, cb
# to do broadcast some kind of color change message?
authorOnline: (textID, cb) ->
if @session.attributes.author?
SS.publish.channel [textID], 'authorOnline', @session.attributes.author
cb()
newDocID: (cb) ->
createDocID cb
R.incr 'snucode:stats:total:docs'
loadDoc: (id, cb) ->
<EMAIL>()
@session.channel.subscribe(id)
docID = textID2RedisKey(id)
# delete document after two weeks
R.expire docID, 1209600
R.expire docID + ':authors', 1209600
R.incr 'snucode:stats:total:loads'
# retrieve doc
R.zrange docID, 0,-1,"withscores", (err, pchars) ->
chars = []
while pchars.length > 0
p = pchars.pop()
id = pchars.pop()
val = id[id.length-1]
auth = id.split(':')[1]
chars.push
'value': val
'id': id
'place': parseFloat(p)
'author': auth
R.hgetall docID + ':authors', (authors) ->
cb chars, authors
calcOffset: (clientTime, cb) ->
# todo: check whether it's Date.now
cb Date.now() - clientTime
| true | # Server-side Code
textID2RedisKey = (id) ->
"snucode:doc:" + id
createDocID = (cb) ->
id = Math.random().toString(36).substring(7)
R.exists textID2RedisKey(id), (err, exists) ->
if exists
createDocID cb
else
# todo: this does not create a new document
# so there could be race conditions
cb id
validColor = (color) ->
numval = parseInt color.substring(1), 16
color[0] is '#' and numval < 16777216 and numval >= 0
validUserID = (user_id) ->
result = true
for c in user_id.toLowerCase().split()
result = result and not isNaN parseInt c, 36
return result
validAuthor = (author) ->
validColor(author.color) and validUserID(author.user_id)
setColor = (author, textID, cb) ->
colorKey = textID2RedisKey(textID) + ':colors'
R.hset colorKey, author.user_id, author.color, cb
exports.actions =
pushChange: (change, cb) ->
change.socket_id = @request.socket_id
SS.publish.channel [change.textID], 'newChange', change
color = @session.attributes.author.color
user_id = @session.attributes.author.user_id
rid = textID2RedisKey(change.textID)
redis_args = [rid]
for addC in change.addChars
redis_args.push addC.place
redis_args.push addC.id
R.zadd redis_args, ->
redis_args = [rid]
R.zrem redis_args.concat(change.removeCharIDs), ->
R.hset rid + ':color', user_id, color, ->
cb()
setAuthor: (author, cb) ->
if validAuthor(author)
unless @session.attributes?
@session.attributes = {}
@session.attributes.author = author
@session.save ->
cb true
else
cb false
getAuthor: (cb) ->
if @session.attributes.author?
cb @session.attributes.author
else
R.incr 'snucode:stats:total:authors'
cb false
setColor: (textID, cb) ->
setColor @session.attributes.author, textID, cb
# to do broadcast some kind of color change message?
authorOnline: (textID, cb) ->
if @session.attributes.author?
SS.publish.channel [textID], 'authorOnline', @session.attributes.author
cb()
newDocID: (cb) ->
createDocID cb
R.incr 'snucode:stats:total:docs'
loadDoc: (id, cb) ->
PI:EMAIL:<EMAIL>END_PI()
@session.channel.subscribe(id)
docID = textID2RedisKey(id)
# delete document after two weeks
R.expire docID, 1209600
R.expire docID + ':authors', 1209600
R.incr 'snucode:stats:total:loads'
# retrieve doc
R.zrange docID, 0,-1,"withscores", (err, pchars) ->
chars = []
while pchars.length > 0
p = pchars.pop()
id = pchars.pop()
val = id[id.length-1]
auth = id.split(':')[1]
chars.push
'value': val
'id': id
'place': parseFloat(p)
'author': auth
R.hgetall docID + ':authors', (authors) ->
cb chars, authors
calcOffset: (clientTime, cb) ->
# todo: check whether it's Date.now
cb Date.now() - clientTime
|
[
{
"context": "'request')\n\nbox = 'sadasdwqdqwdasd'\nfromTarget = \"no-reply@goodgame.ru\"\n\nrequest.get(\n url: \"http://mailinator.com/sett",
"end": 88,
"score": 0.999456524848938,
"start": 68,
"tag": "EMAIL",
"value": "no-reply@goodgame.ru"
}
] | mail.coffee | limitium/ggchat | 0 | request = require('request')
box = 'sadasdwqdqwdasd'
fromTarget = "no-reply@goodgame.ru"
request.get(
url: "http://mailinator.com/settttt?box=#{box}&time=" + (Date.now())
, (err, response, body)=>
boxMeta = JSON.parse(body)
request.get(
url: "http://mailinator.com/grab?inbox=#{box}&address=#{boxMeta.address}&time=" + (Date.now())
, (err, response, body)=>
mails = JSON.parse(body)
for mail in mails.maildir
if mail.fromfull is fromTarget
request.get(
url: "http://mailinator.com/rendermail.jsp?msgid=#{mail.id}&time=" + (Date.now())
, (err, response, body)=>
m = body.match(/"http:\/\/goodgame\.ru\/activate\/(.*?)\/"/)
console.log m[1]
)
)
)
| 158877 | request = require('request')
box = 'sadasdwqdqwdasd'
fromTarget = "<EMAIL>"
request.get(
url: "http://mailinator.com/settttt?box=#{box}&time=" + (Date.now())
, (err, response, body)=>
boxMeta = JSON.parse(body)
request.get(
url: "http://mailinator.com/grab?inbox=#{box}&address=#{boxMeta.address}&time=" + (Date.now())
, (err, response, body)=>
mails = JSON.parse(body)
for mail in mails.maildir
if mail.fromfull is fromTarget
request.get(
url: "http://mailinator.com/rendermail.jsp?msgid=#{mail.id}&time=" + (Date.now())
, (err, response, body)=>
m = body.match(/"http:\/\/goodgame\.ru\/activate\/(.*?)\/"/)
console.log m[1]
)
)
)
| true | request = require('request')
box = 'sadasdwqdqwdasd'
fromTarget = "PI:EMAIL:<EMAIL>END_PI"
request.get(
url: "http://mailinator.com/settttt?box=#{box}&time=" + (Date.now())
, (err, response, body)=>
boxMeta = JSON.parse(body)
request.get(
url: "http://mailinator.com/grab?inbox=#{box}&address=#{boxMeta.address}&time=" + (Date.now())
, (err, response, body)=>
mails = JSON.parse(body)
for mail in mails.maildir
if mail.fromfull is fromTarget
request.get(
url: "http://mailinator.com/rendermail.jsp?msgid=#{mail.id}&time=" + (Date.now())
, (err, response, body)=>
m = body.match(/"http:\/\/goodgame\.ru\/activate\/(.*?)\/"/)
console.log m[1]
)
)
)
|
[
{
"context": "ntroller()\n controller.user =\n name: 'joe'\n password: 'secret'\n\n controller.sub",
"end": 1161,
"score": 0.999563455581665,
"start": 1158,
"tag": "NAME",
"value": "joe"
},
{
"context": "ler.user =\n name: 'joe'\n password: 'secr... | spec/javascripts/controllers/loginController_spec.coffee | sectore/CafeTownsend-Angular-Rails | 70 | describe 'LoginController', ->
beforeEach module('cafeTownsend')
beforeEach module('test')
beforeEach inject ($rootScope, $controller, MockFactory) ->
@mockFactory = MockFactory
@deferred = @mockFactory.deferred
# routes
@location = @mockFactory.location()
# mocking service
@sessionService = @mockFactory.sessionService()
@viewState = @mockFactory.viewState()
# controller factory
@createController = ->
$controller "LoginController",
$location: @location
SessionService: @sessionService
ViewState: @viewState
afterEach ->
it 'is injectable', ->
controller = @createController()
expect(controller).not.to.be(undefined)
describe 'initialize()', ->
it 'updates the view state', inject((ViewState) ->
@createController()
expect(ViewState.current).to.be('login')
)
it 'stores currentUser', ->
controller = @createController()
expect(controller.user).not.to.be(undefined)
describe 'submit()', ->
it 'calls service with user data to login', ->
controller = @createController()
controller.user =
name: 'joe'
password: 'secret'
controller.submit(true)
expect(@sessionService.login.calledWithExactly(controller.user)).to.be.ok()
it 'updates location.path if the login was successfully', inject(($rootScope)->
@sessionService.authorized.returns true
controller = @createController()
@deferred.resolve()
controller.submit(true)
# Propagate promise resolution to 'then' functions using $apply().
# @see: https://docs.angularjs.org/api/ng/service/$q
$rootScope.$apply()
expect(@location.path.calledWith('/employees')).to.be.ok()
)
it 'shows an error message if the login was NOT successfully', inject(($rootScope)->
@sessionService.authorized.returns false
controller = @createController()
@deferred.resolve()
controller.submit(true)
$rootScope.$apply()
expect(controller.loginError).to.be('Invalid username or password!')
)
it 'shows an error message if the login throws an error', inject(($rootScope)->
controller = @createController()
@deferred.reject()
controller.submit(true)
$rootScope.$apply()
expect(controller.loginError).to.be.ok()
)
describe 'hasLoginError()', ->
it 'hides the message by default', ->
controller = @createController()
expect(controller.hasLoginError()).not.to.be.ok()
it 'shows the message if the message is available', ->
controller = @createController()
controller.loginError = 'hello world'
expect(controller.hasLoginError()).to.be.ok() | 75180 | describe 'LoginController', ->
beforeEach module('cafeTownsend')
beforeEach module('test')
beforeEach inject ($rootScope, $controller, MockFactory) ->
@mockFactory = MockFactory
@deferred = @mockFactory.deferred
# routes
@location = @mockFactory.location()
# mocking service
@sessionService = @mockFactory.sessionService()
@viewState = @mockFactory.viewState()
# controller factory
@createController = ->
$controller "LoginController",
$location: @location
SessionService: @sessionService
ViewState: @viewState
afterEach ->
it 'is injectable', ->
controller = @createController()
expect(controller).not.to.be(undefined)
describe 'initialize()', ->
it 'updates the view state', inject((ViewState) ->
@createController()
expect(ViewState.current).to.be('login')
)
it 'stores currentUser', ->
controller = @createController()
expect(controller.user).not.to.be(undefined)
describe 'submit()', ->
it 'calls service with user data to login', ->
controller = @createController()
controller.user =
name: '<NAME>'
password: '<PASSWORD>'
controller.submit(true)
expect(@sessionService.login.calledWithExactly(controller.user)).to.be.ok()
it 'updates location.path if the login was successfully', inject(($rootScope)->
@sessionService.authorized.returns true
controller = @createController()
@deferred.resolve()
controller.submit(true)
# Propagate promise resolution to 'then' functions using $apply().
# @see: https://docs.angularjs.org/api/ng/service/$q
$rootScope.$apply()
expect(@location.path.calledWith('/employees')).to.be.ok()
)
it 'shows an error message if the login was NOT successfully', inject(($rootScope)->
@sessionService.authorized.returns false
controller = @createController()
@deferred.resolve()
controller.submit(true)
$rootScope.$apply()
expect(controller.loginError).to.be('Invalid username or password!')
)
it 'shows an error message if the login throws an error', inject(($rootScope)->
controller = @createController()
@deferred.reject()
controller.submit(true)
$rootScope.$apply()
expect(controller.loginError).to.be.ok()
)
describe 'hasLoginError()', ->
it 'hides the message by default', ->
controller = @createController()
expect(controller.hasLoginError()).not.to.be.ok()
it 'shows the message if the message is available', ->
controller = @createController()
controller.loginError = 'hello world'
expect(controller.hasLoginError()).to.be.ok() | true | describe 'LoginController', ->
beforeEach module('cafeTownsend')
beforeEach module('test')
beforeEach inject ($rootScope, $controller, MockFactory) ->
@mockFactory = MockFactory
@deferred = @mockFactory.deferred
# routes
@location = @mockFactory.location()
# mocking service
@sessionService = @mockFactory.sessionService()
@viewState = @mockFactory.viewState()
# controller factory
@createController = ->
$controller "LoginController",
$location: @location
SessionService: @sessionService
ViewState: @viewState
afterEach ->
it 'is injectable', ->
controller = @createController()
expect(controller).not.to.be(undefined)
describe 'initialize()', ->
it 'updates the view state', inject((ViewState) ->
@createController()
expect(ViewState.current).to.be('login')
)
it 'stores currentUser', ->
controller = @createController()
expect(controller.user).not.to.be(undefined)
describe 'submit()', ->
it 'calls service with user data to login', ->
controller = @createController()
controller.user =
name: 'PI:NAME:<NAME>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
controller.submit(true)
expect(@sessionService.login.calledWithExactly(controller.user)).to.be.ok()
it 'updates location.path if the login was successfully', inject(($rootScope)->
@sessionService.authorized.returns true
controller = @createController()
@deferred.resolve()
controller.submit(true)
# Propagate promise resolution to 'then' functions using $apply().
# @see: https://docs.angularjs.org/api/ng/service/$q
$rootScope.$apply()
expect(@location.path.calledWith('/employees')).to.be.ok()
)
it 'shows an error message if the login was NOT successfully', inject(($rootScope)->
@sessionService.authorized.returns false
controller = @createController()
@deferred.resolve()
controller.submit(true)
$rootScope.$apply()
expect(controller.loginError).to.be('Invalid username or password!')
)
it 'shows an error message if the login throws an error', inject(($rootScope)->
controller = @createController()
@deferred.reject()
controller.submit(true)
$rootScope.$apply()
expect(controller.loginError).to.be.ok()
)
describe 'hasLoginError()', ->
it 'hides the message by default', ->
controller = @createController()
expect(controller.hasLoginError()).not.to.be.ok()
it 'shows the message if the message is available', ->
controller = @createController()
controller.loginError = 'hello world'
expect(controller.hasLoginError()).to.be.ok() |
[
{
"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.9998824596405029,
"start": 61,
"tag": "NAME",
"value": "Jessym Reziga"
},
{
"context": "f the Konsserto package.\n *\n * (c) Je... | node_modules/konsserto/lib/src/Konsserto/Component/Middleware/MiddlewareInstance.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.
###
Tools = use('@Konsserto/Component/Static/Tools')
# MiddlewareInstance
#
# @author Jessym Reziga <jessym@konsserto.com>
class MiddlewareInstance
# Class constructor
# @param {MiddlewareDefinition} middlewareDefinition The middleware definition object
# @param {Controller} controllerDefinition The controller definition object
constructor: (@middlewareDefinition, @controllerDefinition) ->
@controller = new controllerDefinition
console.log('[Middleware] middleware: ' + @getControllerName() + ':' + @getMethod())
# @param {Controller} controller The controller
setController: (@controller) ->
return this
# @param {MiddlewareDefinition} middlewareDefinition The middleware definition
setMiddlewareDefinition: (@middlewareDefinition) ->
return this
# @param {Controller} controller The controller definition
setControllerDefinition: (@controllerDefinition) ->
return this
# @return {MiddlewareDefinition} The middleware definition
getDefinition: () ->
return @middlewareDefinition
# @return {Controller} The controller
getController: () ->
return @controller
# @return {String} The controller name
getControllerName: () ->
return @getController().constructor.name
# @return {Controller} The controller definition
getControllerDefinition: () ->
return @controllerDefinition
# @return {String} The controller definition method name
getMethod: () ->
return @getDefinition().getMethodName() + 'Action'
# @return {Object} The current request of the middleware
getRequest: () ->
return @request
# @return {Object} The current response of the middleware
getResponse: () ->
return @response
# @param {Object} request The current request of the middleware
setRequest: (@request) ->
@getController().setRequest(@request)
return this
# @param {Object} response The current response of the middleware
setResponse: (@response) ->
@getController().setResponse(@response)
return this
# @param {Object} next The current next object of the middleware
setNext: (@next) ->
@getController().setNext(@next)
return this
# @return {Object} The current next object of the middleware
getNext: () ->
return @next
# @return {Boolean} Check if the action method exists
methodExists: () ->
method = @getMethod()
if !method? || !@getController()[method]?
return false
return true
# @return {Object} The actual method of the controller
getMethodInstance: () ->
if @getController()[@getMethod()]?
return @getController()[@getMethod()]
throw new Error('No method ' + @getMethod() + ' in middleware ' + @getDefinition().getMiddlewareName())
# @return {Object} The response of the middleware
getResponse: () ->
return Tools.call(@getMethodInstance(), {})
module.exports = MiddlewareInstance | 181856 | ###
* 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.
###
Tools = use('@Konsserto/Component/Static/Tools')
# MiddlewareInstance
#
# @author <NAME> <<EMAIL>>
class MiddlewareInstance
# Class constructor
# @param {MiddlewareDefinition} middlewareDefinition The middleware definition object
# @param {Controller} controllerDefinition The controller definition object
constructor: (@middlewareDefinition, @controllerDefinition) ->
@controller = new controllerDefinition
console.log('[Middleware] middleware: ' + @getControllerName() + ':' + @getMethod())
# @param {Controller} controller The controller
setController: (@controller) ->
return this
# @param {MiddlewareDefinition} middlewareDefinition The middleware definition
setMiddlewareDefinition: (@middlewareDefinition) ->
return this
# @param {Controller} controller The controller definition
setControllerDefinition: (@controllerDefinition) ->
return this
# @return {MiddlewareDefinition} The middleware definition
getDefinition: () ->
return @middlewareDefinition
# @return {Controller} The controller
getController: () ->
return @controller
# @return {String} The controller name
getControllerName: () ->
return @getController().constructor.name
# @return {Controller} The controller definition
getControllerDefinition: () ->
return @controllerDefinition
# @return {String} The controller definition method name
getMethod: () ->
return @getDefinition().getMethodName() + 'Action'
# @return {Object} The current request of the middleware
getRequest: () ->
return @request
# @return {Object} The current response of the middleware
getResponse: () ->
return @response
# @param {Object} request The current request of the middleware
setRequest: (@request) ->
@getController().setRequest(@request)
return this
# @param {Object} response The current response of the middleware
setResponse: (@response) ->
@getController().setResponse(@response)
return this
# @param {Object} next The current next object of the middleware
setNext: (@next) ->
@getController().setNext(@next)
return this
# @return {Object} The current next object of the middleware
getNext: () ->
return @next
# @return {Boolean} Check if the action method exists
methodExists: () ->
method = @getMethod()
if !method? || !@getController()[method]?
return false
return true
# @return {Object} The actual method of the controller
getMethodInstance: () ->
if @getController()[@getMethod()]?
return @getController()[@getMethod()]
throw new Error('No method ' + @getMethod() + ' in middleware ' + @getDefinition().getMiddlewareName())
# @return {Object} The response of the middleware
getResponse: () ->
return Tools.call(@getMethodInstance(), {})
module.exports = MiddlewareInstance | 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.
###
Tools = use('@Konsserto/Component/Static/Tools')
# MiddlewareInstance
#
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
class MiddlewareInstance
# Class constructor
# @param {MiddlewareDefinition} middlewareDefinition The middleware definition object
# @param {Controller} controllerDefinition The controller definition object
constructor: (@middlewareDefinition, @controllerDefinition) ->
@controller = new controllerDefinition
console.log('[Middleware] middleware: ' + @getControllerName() + ':' + @getMethod())
# @param {Controller} controller The controller
setController: (@controller) ->
return this
# @param {MiddlewareDefinition} middlewareDefinition The middleware definition
setMiddlewareDefinition: (@middlewareDefinition) ->
return this
# @param {Controller} controller The controller definition
setControllerDefinition: (@controllerDefinition) ->
return this
# @return {MiddlewareDefinition} The middleware definition
getDefinition: () ->
return @middlewareDefinition
# @return {Controller} The controller
getController: () ->
return @controller
# @return {String} The controller name
getControllerName: () ->
return @getController().constructor.name
# @return {Controller} The controller definition
getControllerDefinition: () ->
return @controllerDefinition
# @return {String} The controller definition method name
getMethod: () ->
return @getDefinition().getMethodName() + 'Action'
# @return {Object} The current request of the middleware
getRequest: () ->
return @request
# @return {Object} The current response of the middleware
getResponse: () ->
return @response
# @param {Object} request The current request of the middleware
setRequest: (@request) ->
@getController().setRequest(@request)
return this
# @param {Object} response The current response of the middleware
setResponse: (@response) ->
@getController().setResponse(@response)
return this
# @param {Object} next The current next object of the middleware
setNext: (@next) ->
@getController().setNext(@next)
return this
# @return {Object} The current next object of the middleware
getNext: () ->
return @next
# @return {Boolean} Check if the action method exists
methodExists: () ->
method = @getMethod()
if !method? || !@getController()[method]?
return false
return true
# @return {Object} The actual method of the controller
getMethodInstance: () ->
if @getController()[@getMethod()]?
return @getController()[@getMethod()]
throw new Error('No method ' + @getMethod() + ' in middleware ' + @getDefinition().getMiddlewareName())
# @return {Object} The response of the middleware
getResponse: () ->
return Tools.call(@getMethodInstance(), {})
module.exports = MiddlewareInstance |
[
{
"context": "ord::provider\n\n class Setting\n constructor: (@name, @cb) ->\n @value = ActiveRecord::[@name]\n ",
"end": 582,
"score": 0.9149273037910461,
"start": 578,
"tag": "USERNAME",
"value": "name"
},
{
"context": "Record::[@name]\n @key = provider.dir.settings... | src/provider/foundationdb/activerecord/initializers/settings.coffee | frisb/formalize | 2 | _ = require('underscore')
async = require('async')
fdb = require('fdb').apiVersion(200)
deepak = require('deepak')(fdb)
Debug = require('../../../debug')
matchArray = (array1, array2) ->
return false if array1.length isnt array2.length
for x, i in array1
y = array2[i]
return false if (typeof(x) isnt typeof(y))
# do not try match functions
if (typeof(x) isnt 'function')
return false if !_.isEqual(x, y)
true
module.exports = (ActiveRecord, callback) ->
provider = ActiveRecord::provider
class Setting
constructor: (@name, @cb) ->
@value = ActiveRecord::[@name]
@key = provider.dir.settings.pack([@name])
@debug = new Debug(provider.config.debug)
activated: ->
@value.active = true
@cb(null)
@debug.log('Settings', @name)
verify: (initializer) ->
return false if @value.initializer.length isnt initializer.length
deepEquals = _.isEqual(@value.initializer, initializer)
if (!deepEquals)
for x in @value.initializer
for y in initializer
if (x.name is y.name)
# x and y must same numberof properties
return false if Object.keys(x).length isnt Object.keys(y).length
# try match key array but not filter functions
return false if !matchArray(x.key, y.key)
true
loadCallback: (initializer) ->
if (initializer isnt null)
@debug.buffer('loaded from db', 1)
#@debug.buffer('config initializer', @value.initializer)
verified = @verify(initializer)
@debug.buffer('verified', verified)
if (verified)
# saved initializer matches provider config
@value.init(initializer)
@activated()
else if (provider.force)
# config allows the provider to override the saved configuration
@save(ActiveRecord, @value.initializer)
else
message = "Formalize FoundationDB provider configuration for #{@name} does not match the saved initializer.
Either modify the config file accordingly, or use the 'force: true' provider flag to save the new configuration."
throw new Error(message)
else if (@value)
@debug.buffer(@name, 'initializer not loaded from db')
@save(ActiveRecord, @value.initializer)
else
throw new Error("No #{@name} provided for ActiveRecord type '#{ActiveRecord::typeName}'")
load: (ActiveRecord) ->
@debug.buffer('loading', 1)
provider.db.get @key, (err, val) =>
if (err)
console.error(err)
else
@loadCallback(deepak.unpackValue(val))
save: (ActiveRecord, initializer) ->
provider.db.set(@key, deepak.packValue(initializer))
@debug.buffer('saved', 1)
@activated()
init: ->
active = (@value && @value.active)
@debug.buffer('active', active)
if (active)
@cb(null)
else
@load(ActiveRecord)
initSetting = (name, cb) ->
setting = new Setting(name, cb)
setting.init()
eachCallback = (err) ->
if (err)
console.error(err)
else
callback()
async.each(['schema', 'indexes', 'counters'], initSetting, eachCallback)
| 184250 | _ = require('underscore')
async = require('async')
fdb = require('fdb').apiVersion(200)
deepak = require('deepak')(fdb)
Debug = require('../../../debug')
matchArray = (array1, array2) ->
return false if array1.length isnt array2.length
for x, i in array1
y = array2[i]
return false if (typeof(x) isnt typeof(y))
# do not try match functions
if (typeof(x) isnt 'function')
return false if !_.isEqual(x, y)
true
module.exports = (ActiveRecord, callback) ->
provider = ActiveRecord::provider
class Setting
constructor: (@name, @cb) ->
@value = ActiveRecord::[@name]
@key = provider.dir.settings.<KEY>([@name])
@debug = new Debug(provider.config.debug)
activated: ->
@value.active = true
@cb(null)
@debug.log('Settings', @name)
verify: (initializer) ->
return false if @value.initializer.length isnt initializer.length
deepEquals = _.isEqual(@value.initializer, initializer)
if (!deepEquals)
for x in @value.initializer
for y in initializer
if (x.name is y.name)
# x and y must same numberof properties
return false if Object.keys(x).length isnt Object.keys(y).length
# try match key array but not filter functions
return false if !matchArray(x.key, y.key)
true
loadCallback: (initializer) ->
if (initializer isnt null)
@debug.buffer('loaded from db', 1)
#@debug.buffer('config initializer', @value.initializer)
verified = @verify(initializer)
@debug.buffer('verified', verified)
if (verified)
# saved initializer matches provider config
@value.init(initializer)
@activated()
else if (provider.force)
# config allows the provider to override the saved configuration
@save(ActiveRecord, @value.initializer)
else
message = "Formalize FoundationDB provider configuration for #{@name} does not match the saved initializer.
Either modify the config file accordingly, or use the 'force: true' provider flag to save the new configuration."
throw new Error(message)
else if (@value)
@debug.buffer(@name, 'initializer not loaded from db')
@save(ActiveRecord, @value.initializer)
else
throw new Error("No #{@name} provided for ActiveRecord type '#{ActiveRecord::typeName}'")
load: (ActiveRecord) ->
@debug.buffer('loading', 1)
provider.db.get @key, (err, val) =>
if (err)
console.error(err)
else
@loadCallback(deepak.unpackValue(val))
save: (ActiveRecord, initializer) ->
provider.db.set(@key, deepak.packValue(initializer))
@debug.buffer('saved', 1)
@activated()
init: ->
active = (@value && @value.active)
@debug.buffer('active', active)
if (active)
@cb(null)
else
@load(ActiveRecord)
initSetting = (name, cb) ->
setting = new Setting(name, cb)
setting.init()
eachCallback = (err) ->
if (err)
console.error(err)
else
callback()
async.each(['schema', 'indexes', 'counters'], initSetting, eachCallback)
| true | _ = require('underscore')
async = require('async')
fdb = require('fdb').apiVersion(200)
deepak = require('deepak')(fdb)
Debug = require('../../../debug')
matchArray = (array1, array2) ->
return false if array1.length isnt array2.length
for x, i in array1
y = array2[i]
return false if (typeof(x) isnt typeof(y))
# do not try match functions
if (typeof(x) isnt 'function')
return false if !_.isEqual(x, y)
true
module.exports = (ActiveRecord, callback) ->
provider = ActiveRecord::provider
class Setting
constructor: (@name, @cb) ->
@value = ActiveRecord::[@name]
@key = provider.dir.settings.PI:KEY:<KEY>END_PI([@name])
@debug = new Debug(provider.config.debug)
activated: ->
@value.active = true
@cb(null)
@debug.log('Settings', @name)
verify: (initializer) ->
return false if @value.initializer.length isnt initializer.length
deepEquals = _.isEqual(@value.initializer, initializer)
if (!deepEquals)
for x in @value.initializer
for y in initializer
if (x.name is y.name)
# x and y must same numberof properties
return false if Object.keys(x).length isnt Object.keys(y).length
# try match key array but not filter functions
return false if !matchArray(x.key, y.key)
true
loadCallback: (initializer) ->
if (initializer isnt null)
@debug.buffer('loaded from db', 1)
#@debug.buffer('config initializer', @value.initializer)
verified = @verify(initializer)
@debug.buffer('verified', verified)
if (verified)
# saved initializer matches provider config
@value.init(initializer)
@activated()
else if (provider.force)
# config allows the provider to override the saved configuration
@save(ActiveRecord, @value.initializer)
else
message = "Formalize FoundationDB provider configuration for #{@name} does not match the saved initializer.
Either modify the config file accordingly, or use the 'force: true' provider flag to save the new configuration."
throw new Error(message)
else if (@value)
@debug.buffer(@name, 'initializer not loaded from db')
@save(ActiveRecord, @value.initializer)
else
throw new Error("No #{@name} provided for ActiveRecord type '#{ActiveRecord::typeName}'")
load: (ActiveRecord) ->
@debug.buffer('loading', 1)
provider.db.get @key, (err, val) =>
if (err)
console.error(err)
else
@loadCallback(deepak.unpackValue(val))
save: (ActiveRecord, initializer) ->
provider.db.set(@key, deepak.packValue(initializer))
@debug.buffer('saved', 1)
@activated()
init: ->
active = (@value && @value.active)
@debug.buffer('active', active)
if (active)
@cb(null)
else
@load(ActiveRecord)
initSetting = (name, cb) ->
setting = new Setting(name, cb)
setting.init()
eachCallback = (err) ->
if (err)
console.error(err)
else
callback()
async.each(['schema', 'indexes', 'counters'], initSetting, eachCallback)
|
[
{
"context": "})\n\nformSchema = {\n type: 'object'\n required: ['firstName', 'lastName', 'role', 'numStudents', 'city', 'sta",
"end": 8485,
"score": 0.9989628791809082,
"start": 8476,
"tag": "NAME",
"value": "firstName"
},
{
"context": "a = {\n type: 'object'\n required: ['first... | app/views/teachers/ConvertToTeacherAccountView.coffee | cihatislamdede/codecombat | 4,858 | require('app/styles/teachers/teacher-trial-requests.sass')
RootView = require 'views/core/RootView'
forms = require 'core/forms'
TrialRequest = require 'models/TrialRequest'
TrialRequests = require 'collections/TrialRequests'
AuthModal = require 'views/core/AuthModal'
errors = require 'core/errors'
User = require 'models/User'
ConfirmModal = require 'views/core/ConfirmModal'
algolia = require 'core/services/algolia'
countryList = require('country-list')()
UsaStates = require('usa-states').UsaStates
State = require 'models/State'
DISTRICT_NCES_KEYS = ['district', 'district_id', 'district_schools', 'district_students', 'phone']
SCHOOL_NCES_KEYS = DISTRICT_NCES_KEYS.concat(['id', 'name', 'students'])
module.exports = class ConvertToTeacherAccountView extends RootView
id: 'convert-to-teacher-account-view'
template: require 'templates/teachers/convert-to-teacher-account-view'
logoutRedirectURL: null
events:
'change form': 'onChangeForm'
'submit form': 'onSubmitForm'
'click #logout-link': -> me.logout()
'change input[name="city"]': 'invalidateNCES'
'change input[name="state"]': 'invalidateNCES'
'change select[name="state"]': 'invalidateNCES'
'change input[name="district"]': 'invalidateNCES'
'change select[name="country"]': 'onChangeCountry'
initialize: ->
if me.isAnonymous()
application.router.navigate('/teachers/signup', {trigger: true, replace: true})
return
@trialRequest = new TrialRequest()
@trialRequests = new TrialRequests()
@trialRequests.fetchOwn()
@supermodel.trackCollection(@trialRequests)
@countries = countryList.getNames()
@usaStates = new UsaStates().states
@usaStatesAbbreviations = new UsaStates().arrayOf('abbreviations')
window.tracker?.trackEvent 'Teachers Convert Account Loaded', category: 'Teachers', ['Mixpanel']
@state = new State {
showUsaStateDropdown: true
stateValue: null
}
@listenTo @state, 'change:showUsaStateDropdown', -> @renderSelectors('.state')
@listenTo @state, 'change:stateValue', -> @renderSelectors('.state')
onLeaveMessage: ->
if @formChanged
return 'Your account has not been updated! If you continue, your changes will be lost.'
invalidateNCES: ->
for key in SCHOOL_NCES_KEYS
@$('input[name="nces_' + key + '"]').val ''
onChangeCountry: (e) ->
@invalidateNCES()
stateElem = @$('select[name="state"]')
if @$('[name="state"]').prop('nodeName') == 'INPUT'
stateElem = @$('input[name="state"]')
stateVal = stateElem.val()
@state.set({stateValue: stateVal})
if e.target.value == 'United States'
@state.set({showUsaStateDropdown: true})
if !@usaStatesAbbreviations.includes(stateVal)
@state.set({stateValue: ''})
else
@state.set({showUsaStateDropdown: false})
onLoaded: ->
if @trialRequests.size() and me.isTeacher()
return application.router.navigate('/teachers', { trigger: true, replace: true })
super()
afterRender: ->
super()
# apply existing trial request on form
properties = @trialRequest.get('properties')
if properties
forms.objectToForm(@$('form'), properties)
commonLevels = _.map @$('[name="educationLevel"]'), (el) -> $(el).val()
submittedLevels = properties.educationLevel or []
otherLevel = _.first(_.difference(submittedLevels, commonLevels)) or ''
@$('#other-education-level-checkbox').attr('checked', !!otherLevel)
@$('#other-education-level-input').val(otherLevel)
$("#organization-control").algolia_autocomplete({hint: false}, [
source: (query, callback) ->
algolia.schoolsIndex.search(query, { hitsPerPage: 5, aroundLatLngViaIP: false }).then (answer) ->
callback answer.hits
, ->
callback []
displayKey: 'name',
templates:
suggestion: (suggestion) ->
hr = suggestion._highlightResult
"<div class='school'> #{hr.name.value} </div>" +
"<div class='district'>#{hr.district.value}, " +
"<span>#{hr.city?.value}, #{hr.state.value}</span></div>"
]).on 'autocomplete:selected', (event, suggestion, dataset) =>
@$('input[name="district"]').val suggestion.district
@$('input[name="city"]').val suggestion.city
@$('input[name="state"]').val suggestion.state
@$('select[name="state"]').val suggestion.state
@$('select[name="country"]').val 'United States'
@state.set({showUsaStateDropdown: true})
@state.set({stateValue: suggestion.state})
for key in SCHOOL_NCES_KEYS
@$('input[name="nces_' + key + '"]').val suggestion[key]
@onChangeForm()
$("#district-control").algolia_autocomplete({hint: false}, [
source: (query, callback) ->
algolia.schoolsIndex.search(query, { hitsPerPage: 5, aroundLatLngViaIP: false }).then (answer) ->
callback answer.hits
, ->
callback []
displayKey: 'district',
templates:
suggestion: (suggestion) ->
hr = suggestion._highlightResult
"<div class='district'>#{hr.district.value}, " +
"<span>#{hr.city?.value}, #{hr.state.value}</span></div>"
]).on 'autocomplete:selected', (event, suggestion, dataset) =>
@$('input[name="organization"]').val '' # TODO: does not persist on tabbing: back to school, back to district
@$('input[name="city"]').val suggestion.city
@$('input[name="state"]').val suggestion.state
@$('select[name="state"]').val suggestion.state
@$('select[name="country"]').val 'United States'
@state.set({showUsaStateDropdown: true})
@state.set({stateValue: suggestion.state})
for key in DISTRICT_NCES_KEYS
@$('input[name="nces_' + key + '"]').val suggestion[key]
@onChangeForm()
onChangeForm: ->
unless @formChanged
window.tracker?.trackEvent 'Teachers Convert Account Form Started', category: 'Teachers', ['Mixpanel']
@formChanged = true
onSubmitForm: (e) ->
e.preventDefault()
form = @$('form')
attrs = forms.formToObject(form)
trialRequestAttrs = _.cloneDeep(attrs)
# Don't save n/a district entries, but do validate required district client-side
trialRequestAttrs = _.omit(trialRequestAttrs, 'district') if trialRequestAttrs.district?.replace(/\s/ig, '').match(/^n\/?a$/ig)
if @$('#other-education-level-checkbox').is(':checked')
val = @$('#other-education-level-input').val()
trialRequestAttrs.educationLevel.push(val) if val
forms.clearFormAlerts(form)
result = tv4.validateMultiple(trialRequestAttrs, formSchema)
error = false
if not result.valid
forms.applyErrorsToForm(form, result.errors)
error = true
if not _.size(trialRequestAttrs.educationLevel)
forms.setErrorToProperty(form, 'educationLevel', 'include at least one')
error = true
unless attrs.district
forms.setErrorToProperty(form, 'district', $.i18n.t('common.required_field'))
error = true
if error
forms.scrollToFirstError()
return
trialRequestAttrs['siteOrigin'] = 'convert teacher'
@trialRequest = new TrialRequest({
type: 'course'
properties: trialRequestAttrs
})
if me.get('role') is 'student' and not me.isAnonymous()
modal = new ConfirmModal({
title: ''
body: "<p>#{$.i18n.t('teachers_quote.conversion_warning')}</p><p>#{$.i18n.t('teachers_quote.learn_more_modal')}</p>"
confirm: $.i18n.t('common.continue')
decline: $.i18n.t('common.cancel')
})
@openModalView(modal)
modal.once 'confirm', @saveTrialRequest, @
else
@saveTrialRequest()
saveTrialRequest: ->
@trialRequest.notyErrors = false
@$('#create-account-btn').text('Sending').attr('disabled', true)
@trialRequest.save()
@trialRequest.on 'sync', @onTrialRequestSubmit, @
@trialRequest.on 'error', @onTrialRequestError, @
onTrialRequestError: (model, jqxhr) ->
@$('#submit-request-btn').text('Submit').attr('disabled', false)
errors.showNotyNetworkError(arguments...)
onTrialRequestSubmit: ->
window.tracker?.trackEvent 'Teachers Convert Account Submitted', category: 'Teachers', ['Mixpanel']
@formChanged = false
me.setRole @trialRequest.get('properties').role.toLowerCase(), true
me.unsubscribe()
application.router.navigate('/teachers/classes', {trigger: true})
formSchema = {
type: 'object'
required: ['firstName', 'lastName', 'role', 'numStudents', 'city', 'state', 'country']
properties:
firstName: { type: 'string' }
lastName: { type: 'string' }
phoneNumber: { type: 'string' }
role: { type: 'string' }
organization: { type: 'string' }
district: { type: 'string' }
city: { type: 'string' }
state: { type: 'string' }
country: { type: 'string' }
numStudents: { type: 'string' }
numStudentsTotal: { type: 'string' }
educationLevel: {
type: 'array'
items: { type: 'string' }
}
notes: { type: 'string' }
}
for key in SCHOOL_NCES_KEYS
formSchema['nces_' + key] = type: 'string'
| 89168 | require('app/styles/teachers/teacher-trial-requests.sass')
RootView = require 'views/core/RootView'
forms = require 'core/forms'
TrialRequest = require 'models/TrialRequest'
TrialRequests = require 'collections/TrialRequests'
AuthModal = require 'views/core/AuthModal'
errors = require 'core/errors'
User = require 'models/User'
ConfirmModal = require 'views/core/ConfirmModal'
algolia = require 'core/services/algolia'
countryList = require('country-list')()
UsaStates = require('usa-states').UsaStates
State = require 'models/State'
DISTRICT_NCES_KEYS = ['district', 'district_id', 'district_schools', 'district_students', 'phone']
SCHOOL_NCES_KEYS = DISTRICT_NCES_KEYS.concat(['id', 'name', 'students'])
module.exports = class ConvertToTeacherAccountView extends RootView
id: 'convert-to-teacher-account-view'
template: require 'templates/teachers/convert-to-teacher-account-view'
logoutRedirectURL: null
events:
'change form': 'onChangeForm'
'submit form': 'onSubmitForm'
'click #logout-link': -> me.logout()
'change input[name="city"]': 'invalidateNCES'
'change input[name="state"]': 'invalidateNCES'
'change select[name="state"]': 'invalidateNCES'
'change input[name="district"]': 'invalidateNCES'
'change select[name="country"]': 'onChangeCountry'
initialize: ->
if me.isAnonymous()
application.router.navigate('/teachers/signup', {trigger: true, replace: true})
return
@trialRequest = new TrialRequest()
@trialRequests = new TrialRequests()
@trialRequests.fetchOwn()
@supermodel.trackCollection(@trialRequests)
@countries = countryList.getNames()
@usaStates = new UsaStates().states
@usaStatesAbbreviations = new UsaStates().arrayOf('abbreviations')
window.tracker?.trackEvent 'Teachers Convert Account Loaded', category: 'Teachers', ['Mixpanel']
@state = new State {
showUsaStateDropdown: true
stateValue: null
}
@listenTo @state, 'change:showUsaStateDropdown', -> @renderSelectors('.state')
@listenTo @state, 'change:stateValue', -> @renderSelectors('.state')
onLeaveMessage: ->
if @formChanged
return 'Your account has not been updated! If you continue, your changes will be lost.'
invalidateNCES: ->
for key in SCHOOL_NCES_KEYS
@$('input[name="nces_' + key + '"]').val ''
onChangeCountry: (e) ->
@invalidateNCES()
stateElem = @$('select[name="state"]')
if @$('[name="state"]').prop('nodeName') == 'INPUT'
stateElem = @$('input[name="state"]')
stateVal = stateElem.val()
@state.set({stateValue: stateVal})
if e.target.value == 'United States'
@state.set({showUsaStateDropdown: true})
if !@usaStatesAbbreviations.includes(stateVal)
@state.set({stateValue: ''})
else
@state.set({showUsaStateDropdown: false})
onLoaded: ->
if @trialRequests.size() and me.isTeacher()
return application.router.navigate('/teachers', { trigger: true, replace: true })
super()
afterRender: ->
super()
# apply existing trial request on form
properties = @trialRequest.get('properties')
if properties
forms.objectToForm(@$('form'), properties)
commonLevels = _.map @$('[name="educationLevel"]'), (el) -> $(el).val()
submittedLevels = properties.educationLevel or []
otherLevel = _.first(_.difference(submittedLevels, commonLevels)) or ''
@$('#other-education-level-checkbox').attr('checked', !!otherLevel)
@$('#other-education-level-input').val(otherLevel)
$("#organization-control").algolia_autocomplete({hint: false}, [
source: (query, callback) ->
algolia.schoolsIndex.search(query, { hitsPerPage: 5, aroundLatLngViaIP: false }).then (answer) ->
callback answer.hits
, ->
callback []
displayKey: 'name',
templates:
suggestion: (suggestion) ->
hr = suggestion._highlightResult
"<div class='school'> #{hr.name.value} </div>" +
"<div class='district'>#{hr.district.value}, " +
"<span>#{hr.city?.value}, #{hr.state.value}</span></div>"
]).on 'autocomplete:selected', (event, suggestion, dataset) =>
@$('input[name="district"]').val suggestion.district
@$('input[name="city"]').val suggestion.city
@$('input[name="state"]').val suggestion.state
@$('select[name="state"]').val suggestion.state
@$('select[name="country"]').val 'United States'
@state.set({showUsaStateDropdown: true})
@state.set({stateValue: suggestion.state})
for key in SCHOOL_NCES_KEYS
@$('input[name="nces_' + key + '"]').val suggestion[key]
@onChangeForm()
$("#district-control").algolia_autocomplete({hint: false}, [
source: (query, callback) ->
algolia.schoolsIndex.search(query, { hitsPerPage: 5, aroundLatLngViaIP: false }).then (answer) ->
callback answer.hits
, ->
callback []
displayKey: 'district',
templates:
suggestion: (suggestion) ->
hr = suggestion._highlightResult
"<div class='district'>#{hr.district.value}, " +
"<span>#{hr.city?.value}, #{hr.state.value}</span></div>"
]).on 'autocomplete:selected', (event, suggestion, dataset) =>
@$('input[name="organization"]').val '' # TODO: does not persist on tabbing: back to school, back to district
@$('input[name="city"]').val suggestion.city
@$('input[name="state"]').val suggestion.state
@$('select[name="state"]').val suggestion.state
@$('select[name="country"]').val 'United States'
@state.set({showUsaStateDropdown: true})
@state.set({stateValue: suggestion.state})
for key in DISTRICT_NCES_KEYS
@$('input[name="nces_' + key + '"]').val suggestion[key]
@onChangeForm()
onChangeForm: ->
unless @formChanged
window.tracker?.trackEvent 'Teachers Convert Account Form Started', category: 'Teachers', ['Mixpanel']
@formChanged = true
onSubmitForm: (e) ->
e.preventDefault()
form = @$('form')
attrs = forms.formToObject(form)
trialRequestAttrs = _.cloneDeep(attrs)
# Don't save n/a district entries, but do validate required district client-side
trialRequestAttrs = _.omit(trialRequestAttrs, 'district') if trialRequestAttrs.district?.replace(/\s/ig, '').match(/^n\/?a$/ig)
if @$('#other-education-level-checkbox').is(':checked')
val = @$('#other-education-level-input').val()
trialRequestAttrs.educationLevel.push(val) if val
forms.clearFormAlerts(form)
result = tv4.validateMultiple(trialRequestAttrs, formSchema)
error = false
if not result.valid
forms.applyErrorsToForm(form, result.errors)
error = true
if not _.size(trialRequestAttrs.educationLevel)
forms.setErrorToProperty(form, 'educationLevel', 'include at least one')
error = true
unless attrs.district
forms.setErrorToProperty(form, 'district', $.i18n.t('common.required_field'))
error = true
if error
forms.scrollToFirstError()
return
trialRequestAttrs['siteOrigin'] = 'convert teacher'
@trialRequest = new TrialRequest({
type: 'course'
properties: trialRequestAttrs
})
if me.get('role') is 'student' and not me.isAnonymous()
modal = new ConfirmModal({
title: ''
body: "<p>#{$.i18n.t('teachers_quote.conversion_warning')}</p><p>#{$.i18n.t('teachers_quote.learn_more_modal')}</p>"
confirm: $.i18n.t('common.continue')
decline: $.i18n.t('common.cancel')
})
@openModalView(modal)
modal.once 'confirm', @saveTrialRequest, @
else
@saveTrialRequest()
saveTrialRequest: ->
@trialRequest.notyErrors = false
@$('#create-account-btn').text('Sending').attr('disabled', true)
@trialRequest.save()
@trialRequest.on 'sync', @onTrialRequestSubmit, @
@trialRequest.on 'error', @onTrialRequestError, @
onTrialRequestError: (model, jqxhr) ->
@$('#submit-request-btn').text('Submit').attr('disabled', false)
errors.showNotyNetworkError(arguments...)
onTrialRequestSubmit: ->
window.tracker?.trackEvent 'Teachers Convert Account Submitted', category: 'Teachers', ['Mixpanel']
@formChanged = false
me.setRole @trialRequest.get('properties').role.toLowerCase(), true
me.unsubscribe()
application.router.navigate('/teachers/classes', {trigger: true})
formSchema = {
type: 'object'
required: ['<NAME>', '<NAME>', 'role', 'numStudents', 'city', 'state', 'country']
properties:
firstName: { type: 'string' }
<NAME>: { type: 'string' }
phoneNumber: { type: 'string' }
role: { type: 'string' }
organization: { type: 'string' }
district: { type: 'string' }
city: { type: 'string' }
state: { type: 'string' }
country: { type: 'string' }
numStudents: { type: 'string' }
numStudentsTotal: { type: 'string' }
educationLevel: {
type: 'array'
items: { type: 'string' }
}
notes: { type: 'string' }
}
for key in SCHOOL_NCES_KEYS
formSchema['nces_' + key] = type: 'string'
| true | require('app/styles/teachers/teacher-trial-requests.sass')
RootView = require 'views/core/RootView'
forms = require 'core/forms'
TrialRequest = require 'models/TrialRequest'
TrialRequests = require 'collections/TrialRequests'
AuthModal = require 'views/core/AuthModal'
errors = require 'core/errors'
User = require 'models/User'
ConfirmModal = require 'views/core/ConfirmModal'
algolia = require 'core/services/algolia'
countryList = require('country-list')()
UsaStates = require('usa-states').UsaStates
State = require 'models/State'
DISTRICT_NCES_KEYS = ['district', 'district_id', 'district_schools', 'district_students', 'phone']
SCHOOL_NCES_KEYS = DISTRICT_NCES_KEYS.concat(['id', 'name', 'students'])
module.exports = class ConvertToTeacherAccountView extends RootView
id: 'convert-to-teacher-account-view'
template: require 'templates/teachers/convert-to-teacher-account-view'
logoutRedirectURL: null
events:
'change form': 'onChangeForm'
'submit form': 'onSubmitForm'
'click #logout-link': -> me.logout()
'change input[name="city"]': 'invalidateNCES'
'change input[name="state"]': 'invalidateNCES'
'change select[name="state"]': 'invalidateNCES'
'change input[name="district"]': 'invalidateNCES'
'change select[name="country"]': 'onChangeCountry'
initialize: ->
if me.isAnonymous()
application.router.navigate('/teachers/signup', {trigger: true, replace: true})
return
@trialRequest = new TrialRequest()
@trialRequests = new TrialRequests()
@trialRequests.fetchOwn()
@supermodel.trackCollection(@trialRequests)
@countries = countryList.getNames()
@usaStates = new UsaStates().states
@usaStatesAbbreviations = new UsaStates().arrayOf('abbreviations')
window.tracker?.trackEvent 'Teachers Convert Account Loaded', category: 'Teachers', ['Mixpanel']
@state = new State {
showUsaStateDropdown: true
stateValue: null
}
@listenTo @state, 'change:showUsaStateDropdown', -> @renderSelectors('.state')
@listenTo @state, 'change:stateValue', -> @renderSelectors('.state')
onLeaveMessage: ->
if @formChanged
return 'Your account has not been updated! If you continue, your changes will be lost.'
invalidateNCES: ->
for key in SCHOOL_NCES_KEYS
@$('input[name="nces_' + key + '"]').val ''
onChangeCountry: (e) ->
@invalidateNCES()
stateElem = @$('select[name="state"]')
if @$('[name="state"]').prop('nodeName') == 'INPUT'
stateElem = @$('input[name="state"]')
stateVal = stateElem.val()
@state.set({stateValue: stateVal})
if e.target.value == 'United States'
@state.set({showUsaStateDropdown: true})
if !@usaStatesAbbreviations.includes(stateVal)
@state.set({stateValue: ''})
else
@state.set({showUsaStateDropdown: false})
onLoaded: ->
if @trialRequests.size() and me.isTeacher()
return application.router.navigate('/teachers', { trigger: true, replace: true })
super()
afterRender: ->
super()
# apply existing trial request on form
properties = @trialRequest.get('properties')
if properties
forms.objectToForm(@$('form'), properties)
commonLevels = _.map @$('[name="educationLevel"]'), (el) -> $(el).val()
submittedLevels = properties.educationLevel or []
otherLevel = _.first(_.difference(submittedLevels, commonLevels)) or ''
@$('#other-education-level-checkbox').attr('checked', !!otherLevel)
@$('#other-education-level-input').val(otherLevel)
$("#organization-control").algolia_autocomplete({hint: false}, [
source: (query, callback) ->
algolia.schoolsIndex.search(query, { hitsPerPage: 5, aroundLatLngViaIP: false }).then (answer) ->
callback answer.hits
, ->
callback []
displayKey: 'name',
templates:
suggestion: (suggestion) ->
hr = suggestion._highlightResult
"<div class='school'> #{hr.name.value} </div>" +
"<div class='district'>#{hr.district.value}, " +
"<span>#{hr.city?.value}, #{hr.state.value}</span></div>"
]).on 'autocomplete:selected', (event, suggestion, dataset) =>
@$('input[name="district"]').val suggestion.district
@$('input[name="city"]').val suggestion.city
@$('input[name="state"]').val suggestion.state
@$('select[name="state"]').val suggestion.state
@$('select[name="country"]').val 'United States'
@state.set({showUsaStateDropdown: true})
@state.set({stateValue: suggestion.state})
for key in SCHOOL_NCES_KEYS
@$('input[name="nces_' + key + '"]').val suggestion[key]
@onChangeForm()
$("#district-control").algolia_autocomplete({hint: false}, [
source: (query, callback) ->
algolia.schoolsIndex.search(query, { hitsPerPage: 5, aroundLatLngViaIP: false }).then (answer) ->
callback answer.hits
, ->
callback []
displayKey: 'district',
templates:
suggestion: (suggestion) ->
hr = suggestion._highlightResult
"<div class='district'>#{hr.district.value}, " +
"<span>#{hr.city?.value}, #{hr.state.value}</span></div>"
]).on 'autocomplete:selected', (event, suggestion, dataset) =>
@$('input[name="organization"]').val '' # TODO: does not persist on tabbing: back to school, back to district
@$('input[name="city"]').val suggestion.city
@$('input[name="state"]').val suggestion.state
@$('select[name="state"]').val suggestion.state
@$('select[name="country"]').val 'United States'
@state.set({showUsaStateDropdown: true})
@state.set({stateValue: suggestion.state})
for key in DISTRICT_NCES_KEYS
@$('input[name="nces_' + key + '"]').val suggestion[key]
@onChangeForm()
onChangeForm: ->
unless @formChanged
window.tracker?.trackEvent 'Teachers Convert Account Form Started', category: 'Teachers', ['Mixpanel']
@formChanged = true
onSubmitForm: (e) ->
e.preventDefault()
form = @$('form')
attrs = forms.formToObject(form)
trialRequestAttrs = _.cloneDeep(attrs)
# Don't save n/a district entries, but do validate required district client-side
trialRequestAttrs = _.omit(trialRequestAttrs, 'district') if trialRequestAttrs.district?.replace(/\s/ig, '').match(/^n\/?a$/ig)
if @$('#other-education-level-checkbox').is(':checked')
val = @$('#other-education-level-input').val()
trialRequestAttrs.educationLevel.push(val) if val
forms.clearFormAlerts(form)
result = tv4.validateMultiple(trialRequestAttrs, formSchema)
error = false
if not result.valid
forms.applyErrorsToForm(form, result.errors)
error = true
if not _.size(trialRequestAttrs.educationLevel)
forms.setErrorToProperty(form, 'educationLevel', 'include at least one')
error = true
unless attrs.district
forms.setErrorToProperty(form, 'district', $.i18n.t('common.required_field'))
error = true
if error
forms.scrollToFirstError()
return
trialRequestAttrs['siteOrigin'] = 'convert teacher'
@trialRequest = new TrialRequest({
type: 'course'
properties: trialRequestAttrs
})
if me.get('role') is 'student' and not me.isAnonymous()
modal = new ConfirmModal({
title: ''
body: "<p>#{$.i18n.t('teachers_quote.conversion_warning')}</p><p>#{$.i18n.t('teachers_quote.learn_more_modal')}</p>"
confirm: $.i18n.t('common.continue')
decline: $.i18n.t('common.cancel')
})
@openModalView(modal)
modal.once 'confirm', @saveTrialRequest, @
else
@saveTrialRequest()
saveTrialRequest: ->
@trialRequest.notyErrors = false
@$('#create-account-btn').text('Sending').attr('disabled', true)
@trialRequest.save()
@trialRequest.on 'sync', @onTrialRequestSubmit, @
@trialRequest.on 'error', @onTrialRequestError, @
onTrialRequestError: (model, jqxhr) ->
@$('#submit-request-btn').text('Submit').attr('disabled', false)
errors.showNotyNetworkError(arguments...)
onTrialRequestSubmit: ->
window.tracker?.trackEvent 'Teachers Convert Account Submitted', category: 'Teachers', ['Mixpanel']
@formChanged = false
me.setRole @trialRequest.get('properties').role.toLowerCase(), true
me.unsubscribe()
application.router.navigate('/teachers/classes', {trigger: true})
formSchema = {
type: 'object'
required: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'role', 'numStudents', 'city', 'state', 'country']
properties:
firstName: { type: 'string' }
PI:NAME:<NAME>END_PI: { type: 'string' }
phoneNumber: { type: 'string' }
role: { type: 'string' }
organization: { type: 'string' }
district: { type: 'string' }
city: { type: 'string' }
state: { type: 'string' }
country: { type: 'string' }
numStudents: { type: 'string' }
numStudentsTotal: { type: 'string' }
educationLevel: {
type: 'array'
items: { type: 'string' }
}
notes: { type: 'string' }
}
for key in SCHOOL_NCES_KEYS
formSchema['nces_' + key] = type: 'string'
|
[
{
"context": "'../index')\nPromise = require('bluebird')\n\nkey = 'foo'\nvalue = 'bar'\n\ndescribe 'Matching lru-cache API'",
"end": 213,
"score": 0.9947082996368408,
"start": 210,
"tag": "KEY",
"value": "foo"
}
] | test/test.coffee | balena-io/bluebird-lru-cache | 2 | chai = require('chai')
chaiAsPromised = require('chai-as-promised')
chai.use(chaiAsPromised)
{expect} = chai
LRU = require('lru-cache')
BluebirdLRU = require('../index')
Promise = require('bluebird')
key = 'foo'
value = 'bar'
describe 'Matching lru-cache API', ->
bcache = BluebirdLRU(noreject: true)
lcache = LRU()
matchingApi = (method, args...) ->
result = bcache[method](args...)
expected = lcache[method](args...)
expect(result).to.eventually.deep.equal(expected)
fetchTests = ->
it 'get', ->
matchingApi('get', key)
it 'peek', ->
matchingApi('peek', key)
it 'has', ->
matchingApi('has', key)
it 'keys', ->
matchingApi('keys')
it 'values', ->
matchingApi('values')
describe 'after set', ->
it 'set', ->
matchingApi('set', key, value)
fetchTests()
describe 'after delete', ->
it 'del', ->
matchingApi('del', key)
fetchTests()
describe 'after reset', ->
it 'set again', ->
matchingApi('set', key, value)
it 'reset', ->
matchingApi('reset', key)
fetchTests()
describe 'Rejection divergence', ->
bcache = BluebirdLRU()
rejectionApi = (method, args...) ->
result = bcache[method](args...)
.then -> throw new Error()
.catch BluebirdLRU.NoSuchKeyError, (err) -> err.key
expect(result).to.eventually.equal(key)
it 'get', ->
rejectionApi('get', key)
it 'peek', ->
rejectionApi('peek', key)
describe 'Automatic fetching', ->
bcache = BluebirdLRU(
fetchFn: (key) ->
return key + 'bar'
)
autoFetchApi = (method, args...) ->
result = bcache[method](args...)
expect(result).to.eventually.equal(key + 'bar')
it 'get', ->
autoFetchApi('get', key)
it 'peek', ->
bcache.reset().then ->
autoFetchApi('peek', key)
| 90309 | chai = require('chai')
chaiAsPromised = require('chai-as-promised')
chai.use(chaiAsPromised)
{expect} = chai
LRU = require('lru-cache')
BluebirdLRU = require('../index')
Promise = require('bluebird')
key = '<KEY>'
value = 'bar'
describe 'Matching lru-cache API', ->
bcache = BluebirdLRU(noreject: true)
lcache = LRU()
matchingApi = (method, args...) ->
result = bcache[method](args...)
expected = lcache[method](args...)
expect(result).to.eventually.deep.equal(expected)
fetchTests = ->
it 'get', ->
matchingApi('get', key)
it 'peek', ->
matchingApi('peek', key)
it 'has', ->
matchingApi('has', key)
it 'keys', ->
matchingApi('keys')
it 'values', ->
matchingApi('values')
describe 'after set', ->
it 'set', ->
matchingApi('set', key, value)
fetchTests()
describe 'after delete', ->
it 'del', ->
matchingApi('del', key)
fetchTests()
describe 'after reset', ->
it 'set again', ->
matchingApi('set', key, value)
it 'reset', ->
matchingApi('reset', key)
fetchTests()
describe 'Rejection divergence', ->
bcache = BluebirdLRU()
rejectionApi = (method, args...) ->
result = bcache[method](args...)
.then -> throw new Error()
.catch BluebirdLRU.NoSuchKeyError, (err) -> err.key
expect(result).to.eventually.equal(key)
it 'get', ->
rejectionApi('get', key)
it 'peek', ->
rejectionApi('peek', key)
describe 'Automatic fetching', ->
bcache = BluebirdLRU(
fetchFn: (key) ->
return key + 'bar'
)
autoFetchApi = (method, args...) ->
result = bcache[method](args...)
expect(result).to.eventually.equal(key + 'bar')
it 'get', ->
autoFetchApi('get', key)
it 'peek', ->
bcache.reset().then ->
autoFetchApi('peek', key)
| true | chai = require('chai')
chaiAsPromised = require('chai-as-promised')
chai.use(chaiAsPromised)
{expect} = chai
LRU = require('lru-cache')
BluebirdLRU = require('../index')
Promise = require('bluebird')
key = 'PI:KEY:<KEY>END_PI'
value = 'bar'
describe 'Matching lru-cache API', ->
bcache = BluebirdLRU(noreject: true)
lcache = LRU()
matchingApi = (method, args...) ->
result = bcache[method](args...)
expected = lcache[method](args...)
expect(result).to.eventually.deep.equal(expected)
fetchTests = ->
it 'get', ->
matchingApi('get', key)
it 'peek', ->
matchingApi('peek', key)
it 'has', ->
matchingApi('has', key)
it 'keys', ->
matchingApi('keys')
it 'values', ->
matchingApi('values')
describe 'after set', ->
it 'set', ->
matchingApi('set', key, value)
fetchTests()
describe 'after delete', ->
it 'del', ->
matchingApi('del', key)
fetchTests()
describe 'after reset', ->
it 'set again', ->
matchingApi('set', key, value)
it 'reset', ->
matchingApi('reset', key)
fetchTests()
describe 'Rejection divergence', ->
bcache = BluebirdLRU()
rejectionApi = (method, args...) ->
result = bcache[method](args...)
.then -> throw new Error()
.catch BluebirdLRU.NoSuchKeyError, (err) -> err.key
expect(result).to.eventually.equal(key)
it 'get', ->
rejectionApi('get', key)
it 'peek', ->
rejectionApi('peek', key)
describe 'Automatic fetching', ->
bcache = BluebirdLRU(
fetchFn: (key) ->
return key + 'bar'
)
autoFetchApi = (method, args...) ->
result = bcache[method](args...)
expect(result).to.eventually.equal(key + 'bar')
it 'get', ->
autoFetchApi('get', key)
it 'peek', ->
bcache.reset().then ->
autoFetchApi('peek', key)
|
[
{
"context": "mple\n when 'author'\n default_profile_id: \"billpowers\"\n id: _.uniqueId()\n name: \"Bill Powers\"",
"end": 541,
"score": 0.998145580291748,
"start": 531,
"tag": "USERNAME",
"value": "billpowers"
},
{
"context": " \"billpowers\"\n id: _.uniqueId... | test/helpers/fabricate.coffee | anandaroop/flare | 23 | #
# A function that helps create fixture data modeled after the Gravity API.
# Pass in the name of the model and any extending data and it'll return
# a vanilla javascript object populated with fixture json data.
#
# e.g. `fabricate('artwork', { title: 'Three Wolf Moon'` })
#
# TODO: Find a good way to share this between intertia/torque/microgravity
#
_ = require 'underscore'
module.exports = fabricate = (type, extObj = {}) ->
_.extend switch type
# kept as an example
when 'author'
default_profile_id: "billpowers"
id: _.uniqueId()
name: "Bill Powers"
type: "User"
, extObj
| 102247 | #
# A function that helps create fixture data modeled after the Gravity API.
# Pass in the name of the model and any extending data and it'll return
# a vanilla javascript object populated with fixture json data.
#
# e.g. `fabricate('artwork', { title: 'Three Wolf Moon'` })
#
# TODO: Find a good way to share this between intertia/torque/microgravity
#
_ = require 'underscore'
module.exports = fabricate = (type, extObj = {}) ->
_.extend switch type
# kept as an example
when 'author'
default_profile_id: "billpowers"
id: _.uniqueId()
name: "<NAME>"
type: "User"
, extObj
| true | #
# A function that helps create fixture data modeled after the Gravity API.
# Pass in the name of the model and any extending data and it'll return
# a vanilla javascript object populated with fixture json data.
#
# e.g. `fabricate('artwork', { title: 'Three Wolf Moon'` })
#
# TODO: Find a good way to share this between intertia/torque/microgravity
#
_ = require 'underscore'
module.exports = fabricate = (type, extObj = {}) ->
_.extend switch type
# kept as an example
when 'author'
default_profile_id: "billpowers"
id: _.uniqueId()
name: "PI:NAME:<NAME>END_PI"
type: "User"
, extObj
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.