commit
stringlengths 40
40
| old_file
stringlengths 6
181
| new_file
stringlengths 6
181
| old_contents
stringlengths 448
7.17k
| new_contents
stringlengths 449
7.17k
| subject
stringlengths 0
450
| message
stringlengths 6
4.92k
| lang
stringclasses 1
value | license
stringclasses 12
values | repos
stringlengths 9
33.9k
|
|---|---|---|---|---|---|---|---|---|---|
163d3370cbbff179486d908ab085a267cb80eb55
|
share/lua/website/dailymotion.lua
|
share/lua/website/dailymotion.lua
|
-- libquvi-scripts
-- Copyright (C) 2010-2011 Toni Gundogdu <legatvs@gmail.com>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
-- "http://dai.ly/cityofscars",
-- "http://www.dailymotion.com/video/xdpig1_city-of-scars_shortfilms",
local Dailymotion = {} -- Utility functions unique to this script.
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "dailymotion%.%w+"
r.formats = "default|best"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain, "dai.ly"},
{"/video/","/%w+$","/family_filter"})
return r
end
-- Query available formats.
function query_formats(self)
local U = require 'quvi/util'
local page = Dailymotion.fetch_page(self, U)
local formats = Dailymotion.iter_formats(page, U)
local t = {}
for _,v in pairs(formats) do
table.insert(t, Dailymotion.to_s(v))
end
table.sort(t)
self.formats = table.concat(t, "|")
return self
end
-- Parse media URL.
function parse(self)
self.host_id = "dailymotion"
local U = require 'quvi/util'
local page = Dailymotion.fetch_page(self, U)
local _,_,s = page:find('title="(.-)"')
self.title = s or error("no match: media title")
local _,_,s = page:find("video/(.-)_")
self.id = s or error("no match: media id")
local _,_,s = page:find('"og:image" content="(.-)"')
self.thumbnail_url = s or ''
local formats = Dailymotion.iter_formats(page, U)
local format = U.choose_format(self, formats,
Dailymotion.choose_best,
Dailymotion.choose_default,
Dailymotion.to_s)
or error("unable to choose format")
self.url = {format.url or error("no match: media url")}
return self
end
--
-- Utility functions
--
function Dailymotion.fetch_page(self, U)
self.page_url = Dailymotion.normalize(self.page_url)
local _,_,s = self.page_url:find('/family_filter%?urlback=(.+)')
if s then
self.page_url = 'http://dailymotion.com' .. U.unescape(s)
end
local opts = {arbitrary_cookie = 'family_filter=off'}
return quvi.fetch(self.page_url, opts)
end
function Dailymotion.normalize(page_url) -- "Normalize" embedded URLs
if page_url:find("/swf/") then
page_url = page_url:gsub("/swf/", "/")
elseif page_url:find("/embed/") then
page_url = page_url:gsub("/embed/", "/")
end
return page_url
end
function Dailymotion.iter_formats(page, U)
local _,_,seq = page:find('"sequence",%s+"(.-)"')
if not seq then
local e = "no match: sequence"
if page:find("_partnerplayer") then
e = e .. ": looks like a partner video which we do not support"
end
error(e)
end
seq = U.unescape(seq)
--[[
local _,_,msg = seq:find('"message":"(.-)[<"]')
if msg then
msg = msg:gsub('+',' ')
error(msg:gsub('\\',''))
end
]]--
local _,_,vpp = seq:find('"videoPluginParameters":{(.-)}')
if not vpp then
-- See also <http://sourceforge.net/apps/trac/clive/ticket/4>
error("no match: video plugin params")
end
local t = {}
for url in vpp:gfind('%w+URL":"(.-)"') do
url = url:gsub("\\/", "/")
local _,_,c,w,h,cn = url:find('(%w+)%-(%d+)x(%d+).-%.(%w+)')
if not c then
error('no match: codec, width, height, container')
end
-- print(c,w,h,cn)
table.insert(t, {width=tonumber(w), height=tonumber(h),
container=cn, codec=string.lower(c),
url=url})
end
return t
end
function Dailymotion.choose_default(formats) -- Lowest quality available
local r = {width=0xffff, height=0xffff, url=nil}
local U = require 'quvi/util'
for _,v in pairs(formats) do
if U.is_lower_quality(v,r) then
r = v
end
end
-- for k,v in pairs(r) do print(k,v) end
return r
end
function Dailymotion.choose_best(formats) -- Highest quality available
local r = {width=0, height=0, url=nil}
local U = require 'quvi/util'
for _,v in pairs(formats) do
if U.is_higher_quality(v,r) then
r = v
end
end
-- for k,v in pairs(r) do print(k,v) end
return r
end
function Dailymotion.to_s(t)
return string.format("%s_%sp", t.container, t.height)
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2010-2011 Toni Gundogdu <legatvs@gmail.com>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
-- "http://dai.ly/cityofscars",
-- "http://www.dailymotion.com/video/xdpig1_city-of-scars_shortfilms",
local Dailymotion = {} -- Utility functions unique to this script.
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "dailymotion%.%w+"
r.formats = "default|best"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain, "dai.ly"},
{"/video/","/%w+$","/family_filter"})
return r
end
-- Query available formats.
function query_formats(self)
local U = require 'quvi/util'
local page = Dailymotion.fetch_page(self, U)
local formats = Dailymotion.iter_formats(page, U)
local t = {}
for _,v in pairs(formats) do
table.insert(t, Dailymotion.to_s(v))
end
table.sort(t)
self.formats = table.concat(t, "|")
return self
end
-- Parse media URL.
function parse(self)
self.host_id = "dailymotion"
local U = require 'quvi/util'
local page = Dailymotion.fetch_page(self, U)
local _,_,s = page:find('title="(.-)"')
self.title = s or error("no match: media title")
local _,_,s = page:find("video/(.-)_")
self.id = s or error("no match: media id")
local _,_,s = page:find('"og:image" content="(.-)"')
self.thumbnail_url = s or ''
local formats = Dailymotion.iter_formats(page, U)
local format = U.choose_format(self, formats,
Dailymotion.choose_best,
Dailymotion.choose_default,
Dailymotion.to_s)
or error("unable to choose format")
self.url = {format.url or error("no match: media url")}
return self
end
--
-- Utility functions
--
function Dailymotion.fetch_page(self, U)
self.page_url = Dailymotion.normalize(self.page_url)
local _,_,s = self.page_url:find('/family_filter%?urlback=(.+)')
if s then
self.page_url = 'http://dailymotion.com' .. U.unescape(s)
end
local opts = {arbitrary_cookie = 'family_filter=off'}
return quvi.fetch(self.page_url, opts)
end
function Dailymotion.normalize(page_url) -- "Normalize" embedded URLs
if page_url:find("/swf/") then
page_url = page_url:gsub("/swf/", "/")
elseif page_url:find("/embed/") then
page_url = page_url:gsub("/embed/", "/")
end
return page_url
end
function Dailymotion.iter_formats(page, U)
local seq = page:match('"sequence",%s+"(.-)"')
if not seq then
local e = "no match: sequence"
if page:find("_partnerplayer") then
e = e .. ": looks like a partner video which we do not support"
end
error(e)
end
seq = U.unescape(seq)
local t = {}
for url in seq:gfind('%w+URL":"(.-)"') do
local c,w,h,cn = url:match('(%w+)%-(%d+)x(%d+).-%.(%w+)')
if c then
table.insert(t, {width=tonumber(w), height=tonumber(h),
container=cn, codec=string.lower(c),
url=url:gsub("\\/", "/")})
-- print(c,w,h,cn)
end
end
if #t == 0 then
error("no match: media URL")
end
return t
end
function Dailymotion.choose_default(formats) -- Lowest quality available
local r = {width=0xffff, height=0xffff, url=nil}
local U = require 'quvi/util'
for _,v in pairs(formats) do
if U.is_lower_quality(v,r) then
r = v
end
end
-- for k,v in pairs(r) do print(k,v) end
return r
end
function Dailymotion.choose_best(formats) -- Highest quality available
local r = {width=0, height=0, url=nil}
local U = require 'quvi/util'
for _,v in pairs(formats) do
if U.is_higher_quality(v,r) then
r = v
end
end
-- for k,v in pairs(r) do print(k,v) end
return r
end
function Dailymotion.to_s(t)
return string.format("%s_%sp", t.container, t.height)
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
FIX: dailymotion.lua:130: no match: video plugin params
|
FIX: dailymotion.lua:130: no match: video plugin params
* http://sourceforge.net/apps/trac/quvi/ticket/82
|
Lua
|
agpl-3.0
|
alech/libquvi-scripts,DangerCove/libquvi-scripts,hadess/libquvi-scripts-iplayer,legatvs/libquvi-scripts,alech/libquvi-scripts,DangerCove/libquvi-scripts,hadess/libquvi-scripts-iplayer,legatvs/libquvi-scripts
|
6f3e8bd878505b024a96ac7ac6f1447086afc1d4
|
share/lua/website/xhamster.lua
|
share/lua/website/xhamster.lua
|
-- libquvi-scripts
-- Copyright (C) 2012 Toni Gundogdu <legatvs@gmail.com>
-- Copyright (C) 2010 Paul Kocialkowski <contact@paulk.fr>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "xhamster%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/movies/%d+/"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return self
end
-- Parse media URL.
function parse(self)
self.host_id = "xhamster"
local p = quvi.fetch(self.page_url)
self.title = p:match('class="mTitle">.-<h1?.>(.-)</h1>')
or error("no match: media title")
self.id = self.page_url:match("/movies/(.-)/")
or error("no match: media ID")
local s = p:match("'srv': '(.-)'")
or error("no match: server")
local f = p:match("'file': '(.-)'")
or error("no match: file")
self.url = {s .."/key=".. f}
return self
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2012 Toni Gundogdu <legatvs@gmail.com>
-- Copyright (C) 2010 Paul Kocialkowski <contact@paulk.fr>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "xhamster%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/movies/%d+/"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return self
end
-- Parse media URL.
function parse(self)
self.host_id = "xhamster"
local p = quvi.fetch(self.page_url)
self.title = p:match('class="mTitle">.-<h1?.>(.-)</h1>')
or error("no match: media title")
self.id = self.page_url:match("/movies/(.-)/")
or error("no match: media ID")
local U = require 'quvi/util'
local f = p:match("'file': '(.-)'") or error("no match: file")
f = U.unescape(f)
local u = ''
if not f:match('^http') then
u = p:match("'srv': '(.-)'") or error("no match: server")
u = u .."/key="
end
self.url = {u..f}
return self
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
FIX: xhamster.lua: server response code 404
|
FIX: xhamster.lua: server response code 404
Fixes "error: server response code 404 (conncode=0)" with some
of the videos.
|
Lua
|
lgpl-2.1
|
hadess/libquvi-scripts-iplayer,alech/libquvi-scripts,legatvs/libquvi-scripts,legatvs/libquvi-scripts,hadess/libquvi-scripts-iplayer,alech/libquvi-scripts,DangerCove/libquvi-scripts,DangerCove/libquvi-scripts
|
7f6767b298612da0d8ae4da708f77a0f77601264
|
service/clusterproxy.lua
|
service/clusterproxy.lua
|
local skynet = require "skynet"
local cluster = require "cluster"
local node, address = ...
skynet.register_protocol {
name = "system",
id = skynet.PTYPE_SYSTEM,
unpack = function (...) return ... end,
}
local forward_map = {
[skynet.PTYPE_LUA] = skynet.PTYPE_SYSTEM,
[skynet.PTYPE_RESPONSE] = skynet.PTYPE_RESPONSE, -- don't free response message
}
skynet.forward_type( forward_map ,function()
local clusterd = skynet.uniqueservice("clusterd")
local n = tonumber(address)
if n then
address = n
end
skynet.dispatch("system", function (session, source, msg, sz)
local m,s = skynet.rawcall(clusterd, "lua", skynet.pack("req", node, address, msg, sz))
skynet.ret(skynet.rawcall(clusterd, "lua", skynet.pack("req", node, address, msg, sz)))
end)
end)
|
local skynet = require "skynet"
local cluster = require "cluster"
local node, address = ...
skynet.register_protocol {
name = "system",
id = skynet.PTYPE_SYSTEM,
unpack = function (...) return ... end,
}
local forward_map = {
[skynet.PTYPE_LUA] = skynet.PTYPE_SYSTEM,
[skynet.PTYPE_RESPONSE] = skynet.PTYPE_RESPONSE, -- don't free response message
}
skynet.forward_type( forward_map ,function()
local clusterd = skynet.uniqueservice("clusterd")
local n = tonumber(address)
if n then
address = n
end
skynet.dispatch("system", function (session, source, msg, sz)
skynet.ret(skynet.rawcall(clusterd, "lua", skynet.pack("req", node, address, msg, sz)))
end)
end)
|
remove duplicated line to fix issue #166
|
remove duplicated line to fix issue #166
|
Lua
|
mit
|
microcai/skynet,helling34/skynet,helling34/skynet,czlc/skynet,KAndQ/skynet,sundream/skynet,LuffyPan/skynet,xjdrew/skynet,LuffyPan/skynet,Ding8222/skynet,icetoggle/skynet,samael65535/skynet,ypengju/skynet_comment,zhoukk/skynet,xcjmine/skynet,vizewang/skynet,harryzeng/skynet,cpascal/skynet,liuxuezhan/skynet,felixdae/skynet,longmian/skynet,bttscut/skynet,Zirpon/skynet,nightcj/mmo,cdd990/skynet,MRunFoss/skynet,ruleless/skynet,czlc/skynet,chenjiansnail/skynet,togolwb/skynet,your-gatsby/skynet,xinjuncoding/skynet,ag6ag/skynet,wangjunwei01/skynet,your-gatsby/skynet,bingo235/skynet,lynx-seu/skynet,zhaijialong/skynet,chfg007/skynet,longmian/skynet,zhangshiqian1214/skynet,bingo235/skynet,kyle-wang/skynet,lawnight/skynet,yinjun322/skynet,lc412/skynet,harryzeng/skynet,harryzeng/skynet,icetoggle/skynet,korialuo/skynet,LiangMa/skynet,enulex/skynet,KittyCookie/skynet,Zirpon/skynet,lynx-seu/skynet,chenjiansnail/skynet,felixdae/skynet,cloudwu/skynet,MoZhonghua/skynet,jxlczjp77/skynet,ag6ag/skynet,xinmingyao/skynet,ypengju/skynet_comment,pichina/skynet,plsytj/skynet,sdgdsffdsfff/skynet,QuiQiJingFeng/skynet,xinmingyao/skynet,sanikoyes/skynet,catinred2/skynet,microcai/skynet,ilylia/skynet,puXiaoyi/skynet,xubigshu/skynet,zhangshiqian1214/skynet,felixdae/skynet,fhaoquan/skynet,kyle-wang/skynet,hongling0/skynet,cpascal/skynet,kebo/skynet,cloudwu/skynet,fztcjjl/skynet,ludi1991/skynet,asanosoyokaze/skynet,plsytj/skynet,your-gatsby/skynet,Markal128/skynet,LiangMa/skynet,togolwb/skynet,MRunFoss/skynet,yinjun322/skynet,zzh442856860/skynet-Note,zhouxiaoxiaoxujian/skynet,firedtoad/skynet,wangyi0226/skynet,leezhongshan/skynet,firedtoad/skynet,zhaijialong/skynet,gitfancode/skynet,ilylia/skynet,JiessieDawn/skynet,zhoukk/skynet,ludi1991/skynet,javachengwc/skynet,leezhongshan/skynet,bingo235/skynet,iskygame/skynet,dymx101/skynet,xinjuncoding/skynet,jiuaiwo1314/skynet,codingabc/skynet,xjdrew/skynet,cdd990/skynet,javachengwc/skynet,winglsh/skynet,pigparadise/skynet,zzh442856860/skynet,enulex/skynet,hongling0/skynet,rainfiel/skynet,iskygame/skynet,Ding8222/skynet,great90/skynet,lc412/skynet,firedtoad/skynet,cdd990/skynet,helling34/skynet,wangjunwei01/skynet,jiuaiwo1314/skynet,korialuo/skynet,plsytj/skynet,ludi1991/skynet,winglsh/skynet,fztcjjl/skynet,kebo/skynet,Ding8222/skynet,chuenlungwang/skynet,ypengju/skynet_comment,puXiaoyi/skynet,czlc/skynet,zzh442856860/skynet,zhangshiqian1214/skynet,bigrpg/skynet,gitfancode/skynet,microcai/skynet,liuxuezhan/skynet,KAndQ/skynet,MetSystem/skynet,rainfiel/skynet,xubigshu/skynet,QuiQiJingFeng/skynet,hongling0/skynet,letmefly/skynet,letmefly/skynet,zzh442856860/skynet,longmian/skynet,lynx-seu/skynet,boyuegame/skynet,u20024804/skynet,MRunFoss/skynet,ludi1991/skynet,jxlczjp77/skynet,sanikoyes/skynet,matinJ/skynet,pichina/skynet,zhoukk/skynet,xcjmine/skynet,Zirpon/skynet,chfg007/skynet,xcjmine/skynet,ruleless/skynet,catinred2/skynet,chuenlungwang/skynet,boyuegame/skynet,great90/skynet,chenjiansnail/skynet,JiessieDawn/skynet,sdgdsffdsfff/skynet,zzh442856860/skynet-Note,ilylia/skynet,matinJ/skynet,icetoggle/skynet,catinred2/skynet,liuxuezhan/skynet,xjdrew/skynet,liuxuezhan/skynet,rainfiel/skynet,kebo/skynet,cmingjian/skynet,dymx101/skynet,asanosoyokaze/skynet,MetSystem/skynet,zhangshiqian1214/skynet,leezhongshan/skynet,zhaijialong/skynet,enulex/skynet,cuit-zhaxin/skynet,zhangshiqian1214/skynet,wangyi0226/skynet,wangjunwei01/skynet,chuenlungwang/skynet,samael65535/skynet,zzh442856860/skynet-Note,zhouxiaoxiaoxujian/skynet,lawnight/skynet,bigrpg/skynet,zhangshiqian1214/skynet,u20024804/skynet,pichina/skynet,asanosoyokaze/skynet,codingabc/skynet,letmefly/skynet,letmefly/skynet,pigparadise/skynet,korialuo/skynet,gitfancode/skynet,kyle-wang/skynet,winglsh/skynet,samael65535/skynet,fztcjjl/skynet,javachengwc/skynet,KAndQ/skynet,vizewang/skynet,codingabc/skynet,QuiQiJingFeng/skynet,chfg007/skynet,JiessieDawn/skynet,MetSystem/skynet,cloudwu/skynet,puXiaoyi/skynet,yunGit/skynet,xinjuncoding/skynet,LuffyPan/skynet,sundream/skynet,lawnight/skynet,u20024804/skynet,sanikoyes/skynet,KittyCookie/skynet,cmingjian/skynet,matinJ/skynet,cpascal/skynet,nightcj/mmo,jiuaiwo1314/skynet,yinjun322/skynet,fhaoquan/skynet,yunGit/skynet,sdgdsffdsfff/skynet,jxlczjp77/skynet,ruleless/skynet,iskygame/skynet,dymx101/skynet,Markal128/skynet,bttscut/skynet,KittyCookie/skynet,nightcj/mmo,zhouxiaoxiaoxujian/skynet,togolwb/skynet,bigrpg/skynet,MoZhonghua/skynet,great90/skynet,vizewang/skynet,LiangMa/skynet,lawnight/skynet,fhaoquan/skynet,lc412/skynet,wangyi0226/skynet,zzh442856860/skynet-Note,MoZhonghua/skynet,cuit-zhaxin/skynet,yunGit/skynet,boyuegame/skynet,cuit-zhaxin/skynet,cmingjian/skynet,ag6ag/skynet,bttscut/skynet,Markal128/skynet,sundream/skynet,pigparadise/skynet
|
e031599c0a14c5fd6efc174d9ce431d32c57cb55
|
frontend/ui/widget/filechooser.lua
|
frontend/ui/widget/filechooser.lua
|
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Menu = require("ui/widget/menu")
local Screen = require("device").screen
local Device = require("device")
local util = require("ffi/util")
local DEBUG = require("dbg")
local _ = require("gettext")
local ffi = require("ffi")
ffi.cdef[[
int strcoll (char *str1, char *str2);
]]
-- string sort function respecting LC_COLLATE
local function strcoll(str1, str2)
return ffi.C.strcoll(ffi.cast("char*", str1), ffi.cast("char*", str2)) <= 0
end
local FileChooser = Menu:extend{
height = Screen:getHeight(),
width = Screen:getWidth(),
no_title = true,
path = lfs.currentdir(),
parent = nil,
show_hidden = nil,
filter = function(filename) return true end,
exclude_dirs = {"%.sdr$"},
strcoll = strcoll,
collate = "strcoll", -- or collate = "access",
reverse_collate = false,
}
function FileChooser:init()
-- common dir filter
self.dir_filter = function(dirname)
for _, pattern in ipairs(self.exclude_dirs) do
if dirname:match(pattern) then return end
end
return true
end
-- disable string collating in Kobo devices. See issue koreader/koreader#686
if Device:isKobo() then self.strcoll = nil end
self.item_table = self:genItemTableFromPath(self.path)
Menu.init(self) -- call parent's init()
end
function FileChooser:genItemTableFromPath(path)
local dirs = {}
local files = {}
-- lfs.dir directory without permission will give error
local ok, iter, dir_obj = pcall(lfs.dir, self.path)
if ok then
for f in iter, dir_obj do
if self.show_hidden or not string.match(f, "^%.[^.]") then
local filename = self.path.."/"..f
local attributes = lfs.attributes(filename)
if attributes.mode == "directory" and f ~= "." and f~=".." then
if self.dir_filter(filename) then
table.insert(dirs, {name = f, attr = attributes})
end
elseif attributes.mode == "file" then
if self.file_filter(filename) then
table.insert(files, {name = f, attr = attributes})
end
end
end
end
end
local sorting = nil
local reverse = self.reverse_collate
if self.collate == "strcoll" then
sorting = self.strcoll and function(a, b)
return self.strcoll(a.name, b.name) == not reverse
end or function(a, b)
return (a.name < b.name) == not reverse
end
elseif self.collate == "access" then
sorting = function(a, b)
if reverse then
return a.attr.access < b.attr.access
else
return a.attr.access > b.attr.access
end
end
end
table.sort(dirs, sorting)
if path ~= "/" then table.insert(dirs, 1, {name = ".."}) end
table.sort(files, sorting)
local item_table = {}
for i, dir in ipairs(dirs) do
local path = self.path.."/"..dir.name
local items = 0
local ok, iter, dir_obj = pcall(lfs.dir, path)
if ok then
for f in iter, dir_obj do
items = items + 1
end
-- exclude "." and ".."
items = items - 2
end
local istr = items .. (items > 1 and _(" items") or _(" item"))
table.insert(item_table, {
text = dir.name.."/",
mandatory = istr,
path = path
})
end
for _, file in ipairs(files) do
local full_path = self.path.."/"..file.name
local file_size = lfs.attributes(full_path, "size") or 0
local sstr = ""
if file_size > 1024*1024 then
sstr = string.format("%4.1f MB", file_size/1024/1024)
elseif file_size > 1024 then
sstr = string.format("%4.1f KB", file_size/1024)
else
sstr = string.format("%d B", file_size)
end
table.insert(item_table, {
text = file.name,
mandatory = sstr,
path = full_path
})
end
-- lfs.dir iterated node string may be encoded with some weird codepage on Windows
-- we need to encode them to utf-8
if ffi.os == "Windows" then
for k, v in pairs(item_table) do
if v.text then
v.text = util.multiByteToUTF8(v.text) or ""
end
end
end
return item_table
end
function FileChooser:refreshPath()
self:swithItemTable(nil, self:genItemTableFromPath(self.path))
end
function FileChooser:changeToPath(path)
path = util.realpath(path)
self.path = path
self:refreshPath()
end
function FileChooser:toggleHiddenFiles()
self.show_hidden = not self.show_hidden
self:refreshPath()
end
function FileChooser:setCollate(collate)
self.collate = collate
self:refreshPath()
end
function FileChooser:toggleReverseCollate()
self.reverse_collate = not self.reverse_collate
self:refreshPath()
end
function FileChooser:onMenuSelect(item)
-- parent directory of dir without permission get nil mode
-- we need to change to parent path in this case
if lfs.attributes(item.path, "mode") == "file" then
self:onFileSelect(item.path)
else
self:changeToPath(item.path)
end
return true
end
function FileChooser:onMenuHold(item)
self:onFileHold(item.path)
return true
end
function FileChooser:onFileSelect(file)
UIManager:close(self)
return true
end
function FileChooser:onFileHold(file)
return true
end
return FileChooser
|
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Menu = require("ui/widget/menu")
local Screen = require("device").screen
local Device = require("device")
local util = require("ffi/util")
local DEBUG = require("dbg")
local _ = require("gettext")
local ffi = require("ffi")
ffi.cdef[[
int strcoll (const char *str1, const char *str2);
]]
-- string sort function respecting LC_COLLATE
local function strcoll(str1, str2)
return ffi.C.strcoll(str1, str2) < 0
end
local FileChooser = Menu:extend{
height = Screen:getHeight(),
width = Screen:getWidth(),
no_title = true,
path = lfs.currentdir(),
parent = nil,
show_hidden = nil,
filter = function(filename) return true end,
exclude_dirs = {"%.sdr$"},
strcoll = strcoll,
collate = "strcoll", -- or collate = "access",
reverse_collate = false,
}
function FileChooser:init()
-- common dir filter
self.dir_filter = function(dirname)
for _, pattern in ipairs(self.exclude_dirs) do
if dirname:match(pattern) then return end
end
return true
end
-- circumvent string collating in Kobo devices. See issue koreader/koreader#686
if Device:isKobo() then
self.strcoll = function(a, b) return a < b end
end
self.item_table = self:genItemTableFromPath(self.path)
Menu.init(self) -- call parent's init()
end
function FileChooser:genItemTableFromPath(path)
local dirs = {}
local files = {}
-- lfs.dir directory without permission will give error
local ok, iter, dir_obj = pcall(lfs.dir, self.path)
if ok then
for f in iter, dir_obj do
if self.show_hidden or not string.match(f, "^%.[^.]") then
local filename = self.path.."/"..f
local attributes = lfs.attributes(filename)
if attributes.mode == "directory" and f ~= "." and f~=".." then
if self.dir_filter(filename) then
table.insert(dirs, {name = f, attr = attributes})
end
elseif attributes.mode == "file" then
if self.file_filter(filename) then
table.insert(files, {name = f, attr = attributes})
end
end
end
end
end
local sorting = nil
local reverse = self.reverse_collate
if self.collate == "strcoll" then
sorting = function(a, b)
return self.strcoll(a.name, b.name) == not reverse
end
elseif self.collate == "access" then
sorting = function(a, b)
if reverse then
return a.attr.access < b.attr.access
else
return a.attr.access > b.attr.access
end
end
end
table.sort(dirs, sorting)
if path ~= "/" then table.insert(dirs, 1, {name = ".."}) end
table.sort(files, sorting)
local item_table = {}
for i, dir in ipairs(dirs) do
local path = self.path.."/"..dir.name
local items = 0
local ok, iter, dir_obj = pcall(lfs.dir, path)
if ok then
for f in iter, dir_obj do
items = items + 1
end
-- exclude "." and ".."
items = items - 2
end
local istr = items .. (items > 1 and _(" items") or _(" item"))
table.insert(item_table, {
text = dir.name.."/",
mandatory = istr,
path = path
})
end
for _, file in ipairs(files) do
local full_path = self.path.."/"..file.name
local file_size = lfs.attributes(full_path, "size") or 0
local sstr = ""
if file_size > 1024*1024 then
sstr = string.format("%4.1f MB", file_size/1024/1024)
elseif file_size > 1024 then
sstr = string.format("%4.1f KB", file_size/1024)
else
sstr = string.format("%d B", file_size)
end
table.insert(item_table, {
text = file.name,
mandatory = sstr,
path = full_path
})
end
-- lfs.dir iterated node string may be encoded with some weird codepage on Windows
-- we need to encode them to utf-8
if ffi.os == "Windows" then
for k, v in pairs(item_table) do
if v.text then
v.text = util.multiByteToUTF8(v.text) or ""
end
end
end
return item_table
end
function FileChooser:refreshPath()
self:swithItemTable(nil, self:genItemTableFromPath(self.path))
end
function FileChooser:changeToPath(path)
path = util.realpath(path)
self.path = path
self:refreshPath()
end
function FileChooser:toggleHiddenFiles()
self.show_hidden = not self.show_hidden
self:refreshPath()
end
function FileChooser:setCollate(collate)
self.collate = collate
self:refreshPath()
end
function FileChooser:toggleReverseCollate()
self.reverse_collate = not self.reverse_collate
self:refreshPath()
end
function FileChooser:onMenuSelect(item)
-- parent directory of dir without permission get nil mode
-- we need to change to parent path in this case
if lfs.attributes(item.path, "mode") == "file" then
self:onFileSelect(item.path)
else
self:changeToPath(item.path)
end
return true
end
function FileChooser:onMenuHold(item)
self:onFileHold(item.path)
return true
end
function FileChooser:onFileSelect(file)
UIManager:close(self)
return true
end
function FileChooser:onFileHold(file)
return true
end
return FileChooser
|
fix strcoll() workaround
|
fix strcoll() workaround
The strcoll() workaround we had in place for Kobo devices was (or has
become) ineffective. We had set self.strcoll to nil on Kobo devices -
but this was the instance variable. Setting it to nil effectively makes
the instance variable vanish, so when trying to access it later, it
was not there and got looked up via the metatable - which had the original
reference. Setting it to nil had no effect whatsoever.
We simplify that approach and set the replacement function where before we
had set this to nil.
This is a partial fix for issue #1183 (and explains a comment in issue #686
which says that the old fix did not work).
However, to really fix #1183 - if we want to do so - we would need a collate
function that normalizes uppercase/lowercase before compare.
|
Lua
|
agpl-3.0
|
apletnev/koreader,ashang/koreader,noname007/koreader,Frenzie/koreader,poire-z/koreader,poire-z/koreader,chihyang/koreader,koreader/koreader,pazos/koreader,NickSavage/koreader,Hzj-jie/koreader,koreader/koreader,ashhher3/koreader,robert00s/koreader,chrox/koreader,houqp/koreader,frankyifei/koreader,Frenzie/koreader,NiLuJe/koreader,mwoz123/koreader,Markismus/koreader,NiLuJe/koreader,mihailim/koreader,lgeek/koreader
|
2d89e16fab2fbc1f2deff857dcfb306e8fef8722
|
frontend/apps/reader/modules/readerdogear.lua
|
frontend/apps/reader/modules/readerdogear.lua
|
local InputContainer = require("ui/widget/container/inputcontainer")
local RightContainer = require("ui/widget/container/rightcontainer")
local ImageWidget = require("ui/widget/imagewidget")
local GestureRange = require("ui/gesturerange")
local Device = require("device")
local Geom = require("ui/geometry")
local Screen = require("device").screen
local Event = require("ui/event")
local ReaderDogear = InputContainer:new{}
function ReaderDogear:init()
local widget = ImageWidget:new{
file = "resources/icons/dogear.png",
alpha = true,
}
self[1] = RightContainer:new{
dimen = Geom:new{w = Screen:getWidth(), h = widget:getSize().h},
widget,
}
self:resetLayout()
end
function ReaderDogear:resetLayout()
local new_screen_width = Screen:getWidth()
if new_screen_width == self._last_screen_width then return end
local new_screen_height = Screen:getHeight()
self._last_screen_width = new_screen_width
self[1].dimen.w = new_screen_width
if Device:isTouchDevice() then
self.ges_events = {
Tap = {
GestureRange:new{
ges = "tap",
range = Geom:new{
x = new_screen_width*DTAP_ZONE_BOOKMARK.x,
y = new_screen_height*DTAP_ZONE_BOOKMARK.y,
w = new_screen_width*DTAP_ZONE_BOOKMARK.w,
h = new_screen_height*DTAP_ZONE_BOOKMARK.h
}
}
},
Hold = {
GestureRange:new{
ges = "hold",
range = Geom:new{
x = new_screen_width*DTAP_ZONE_BOOKMARK.x,
y = new_screen_height*DTAP_ZONE_BOOKMARK.y,
w = new_screen_width*DTAP_ZONE_BOOKMARK.w,
h = new_screen_height*DTAP_ZONE_BOOKMARK.h
}
}
}
}
end
end
function ReaderDogear:onTap()
self.ui:handleEvent(Event:new("ToggleBookmark"))
return true
end
function ReaderDogear:onHold()
self.ui:handleEvent(Event:new("ToggleBookmarkFlipping"))
return true
end
function ReaderDogear:onSetDogearVisibility(visible)
self.view.dogear_visible = visible
return true
end
return ReaderDogear
|
local Device = require("device")
local Event = require("ui/event")
local Geom = require("ui/geometry")
local GestureRange = require("ui/gesturerange")
local ImageWidget = require("ui/widget/imagewidget")
local InputContainer = require("ui/widget/container/inputcontainer")
local RightContainer = require("ui/widget/container/rightcontainer")
local Screen = require("device").screen
local ReaderDogear = InputContainer:new{}
function ReaderDogear:init()
local widget = ImageWidget:new{
file = "resources/icons/dogear.png",
alpha = true,
}
self[1] = RightContainer:new{
dimen = Geom:new{w = Screen:getWidth(), h = widget:getSize().h},
widget,
}
self:resetLayout()
end
function ReaderDogear:resetLayout()
local new_screen_width = Screen:getWidth()
if new_screen_width == self._last_screen_width then return end
local new_screen_height = Screen:getHeight()
self._last_screen_width = new_screen_width
self[1].dimen.w = new_screen_width
if Device:isTouchDevice() then
self.ges_events = {
Tap = {
GestureRange:new{
ges = "tap",
range = Geom:new{
x = new_screen_width*DTAP_ZONE_BOOKMARK.x,
y = new_screen_height*DTAP_ZONE_BOOKMARK.y,
w = new_screen_width*DTAP_ZONE_BOOKMARK.w,
h = new_screen_height*DTAP_ZONE_BOOKMARK.h
}
}
}
}
end
end
function ReaderDogear:onTap()
self.ui:handleEvent(Event:new("ToggleBookmark"))
return true
end
function ReaderDogear:onSetDogearVisibility(visible)
self.view.dogear_visible = visible
return true
end
return ReaderDogear
|
Fix: Can't long-press lookup word inside bookmark tap zone (#3048)
|
Fix: Can't long-press lookup word inside bookmark tap zone (#3048)
* Fix: Can't long-press lookup word inside bookmark tap zone
|
Lua
|
agpl-3.0
|
Hzj-jie/koreader,mwoz123/koreader,Frenzie/koreader,NiLuJe/koreader,koreader/koreader,Markismus/koreader,pazos/koreader,mihailim/koreader,houqp/koreader,NiLuJe/koreader,apletnev/koreader,koreader/koreader,poire-z/koreader,poire-z/koreader,Frenzie/koreader,lgeek/koreader
|
0b71cdaaad609fa825553a28fc9cdf28e0c4db89
|
libs/core/luasrc/model/wireless.lua
|
libs/core/luasrc/model/wireless.lua
|
--[[
LuCI - Wireless model
Copyright 2009 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local pairs, i18n, uci, math = pairs, luci.i18n, luci.model.uci, math
local iwi = require "iwinfo"
local utl = require "luci.util"
local uct = require "luci.model.uci.bind"
module "luci.model.wireless"
local ub = uct.bind("wireless")
local st, ifs
function init(cursor)
cursor:unload("wireless")
cursor:load("wireless")
ub:init(cursor)
st = uci.cursor_state()
ifs = { }
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
local id = "%s.network%d" %{ s.device, count }
ifs[id] = {
id = id,
sid = s['.name'],
count = count
}
local dev = st:get("wireless", s['.name'], "ifname")
or st:get("wireless", s['.name'], "device")
local wtype = dev and iwi.type(dev)
if dev and wtype then
ifs[id].winfo = iwi[wtype]
ifs[id].wdev = dev
end
end)
end
function get_device(self, dev)
return device(dev)
end
function get_network(self, id)
if ifs[id] then
return network(ifs[id].sid)
else
local n
for n, _ in pairs(ifs) do
if ifs[n].sid == id then
return network(id)
end
end
end
end
function shortname(self, iface)
if iface.wdev and iface.winfo then
return "%s %q" %{
i18n.translate("a_s_if_iwmode_" .. iface:active_mode(), iface.winfo.mode(iface.wdev)),
iface:active_ssid() or "(hidden)"
}
else
return iface:name()
end
end
function get_i18n(self, iface)
if iface.wdev and iface.winfo then
return "%s: %s %q (%s)" %{
i18n.translate("a_s_if_wifinet", "Wireless Network"),
i18n.translate("a_s_if_iwmode_" .. iface:active_mode(), iface.winfo.mode(iface.wdev)),
iface:active_ssid() or "(hidden)", iface.wdev
}
else
return "%s: %q" %{ i18n.translate("a_s_if_wifinet", "Wireless Network"), iface:name() }
end
end
function rename_network(self, old, new)
local i
for i, _ in pairs(ifs) do
if ifs[i].network == old then
ifs[i].network = new
end
end
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.network == old then
if new then
ub.uci:set("wireless", s['.name'], "network", new)
else
ub.uci:delete("wireless", s['.name'], "network")
end
end
end)
end
function del_network(self, old)
return self:rename_network(old, nil)
end
function find_interfaces(self, iflist, brlist)
local iface
for iface, _ in pairs(ifs) do
iflist[iface] = ifs[iface]
end
end
function ignore_interface(self, iface)
if ifs and ifs[iface] then
return false
else
return iwi.type(iface) and true or false
end
end
function add_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:set("wireless", ifs[iface].sid, "network", net:name())
ifs[iface].network = net:name()
return true
end
return false
end
function del_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:delete("wireless", ifs[iface].sid, "network")
--return true
end
return false
end
device = ub:section("wifi-device")
device:property("type")
device:property("channel")
device:property("disabled")
function device.name(self)
return self.sid
end
function device.get_networks(self)
local nets = { }
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.device == self:name() then
nets[#nets+1] = network(s['.name'])
end
end)
return nets
end
network = ub:section("wifi-iface")
network:property("mode")
network:property("ssid")
network:property("bssid")
network:property("network")
function network._init(self, sid)
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
return s['.name'] ~= sid
end)
local dev = st:get("wireless", sid, "ifname")
or st:get("wireless", sid, "device")
if dev then
self.id = "%s.network%d" %{ dev, count }
local wtype = iwi.type(dev)
if dev and wtype then
self.winfo = iwi[wtype]
self.wdev = dev
end
end
end
function network.name(self)
return self.id
end
function network.ifname(self)
return self.wdev
end
function network.get_device(self)
if self.device then
return device(self.device)
end
end
function network.active_mode(self)
local m = self.winfo and self.winfo.mode(self.wdev)
if m == "Master" or m == "Auto" then
m = "ap"
elseif m == "Ad-Hoc" then
m = "adhoc"
elseif m == "Client" then
m = "sta"
elseif m then
m = m:lower()
else
m = self:mode()
end
return m or "ap"
end
function network.active_mode_i18n(self)
return i18n.translate("a_s_if_iwmode_" .. self:active_mode())
end
function network.active_ssid(self)
return self.winfo and self.winfo.ssid(self.wdev) or
self:ssid()
end
function network.active_bssid(self)
return self.winfo and self.winfo.bssid(self.wdev) or
self:bssid() or "00:00:00:00:00:00"
end
function network.signal(self)
return self.winfo and self.winfo.signal(self.wdev) or 0
end
function network.noise(self)
return self.winfo and self.winfo.noise(self.wdev) or 0
end
function network.signal_level(self)
if self:active_bssid() ~= "00:00:00:00:00:00" then
local signal = self:signal()
local noise = self:noise()
if signal > 0 and noise > 0 then
local snr = -1 * (noise - signal)
return math.floor(snr / 5)
else
return 0
end
else
return -1
end
end
function network.signal_percent(self)
local qc = self.winfo and
self.winfo.quality(self.wdev) or 0
local qm = self.winfo and
self.winfo.quality_max(self.wdev) or 0
if qc > 0 and qm > 0 then
return math.floor((100 / qm) * qc)
else
return 0
end
end
|
--[[
LuCI - Wireless model
Copyright 2009 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local pairs, i18n, uci, math = pairs, luci.i18n, luci.model.uci, math
local iwi = require "iwinfo"
local utl = require "luci.util"
local uct = require "luci.model.uci.bind"
module "luci.model.wireless"
local ub = uct.bind("wireless")
local st, ifs
function init(cursor)
cursor:unload("wireless")
cursor:load("wireless")
ub:init(cursor)
st = uci.cursor_state()
ifs = { }
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
local id = "%s.network%d" %{ s.device, count }
ifs[id] = {
id = id,
sid = s['.name'],
count = count
}
local dev = st:get("wireless", s['.name'], "ifname")
or st:get("wireless", s['.name'], "device")
local wtype = dev and iwi.type(dev)
if dev and wtype then
ifs[id].winfo = iwi[wtype]
ifs[id].wdev = dev
end
end)
end
function get_device(self, dev)
return device(dev)
end
function get_devices(self)
local devs = { }
ub.uci:foreach("wireless", "wifi-device",
function(s) devs[#devs+1] = device(s['.name']) end)
return devs
end
function get_network(self, id)
if ifs[id] then
return network(ifs[id].sid)
else
local n
for n, _ in pairs(ifs) do
if ifs[n].sid == id then
return network(id)
end
end
end
end
function shortname(self, iface)
if iface.wdev and iface.winfo then
return "%s %q" %{
i18n.translate("a_s_if_iwmode_" .. iface:active_mode(), iface.winfo.mode(iface.wdev)),
iface:active_ssid() or "(hidden)"
}
else
return iface:name()
end
end
function get_i18n(self, iface)
if iface.wdev and iface.winfo then
return "%s: %s %q (%s)" %{
i18n.translate("a_s_if_wifinet", "Wireless Network"),
i18n.translate("a_s_if_iwmode_" .. iface:active_mode(), iface.winfo.mode(iface.wdev)),
iface:active_ssid() or "(hidden)", iface.wdev
}
else
return "%s: %q" %{ i18n.translate("a_s_if_wifinet", "Wireless Network"), iface:name() }
end
end
function del_network(self, id)
if ifs[id] then
ub.uci:delete("wireless", ifs[id].sid)
ifs[id] = nil
else
local n
for n, _ in pairs(ifs) do
if ifs[n].sid == id then
ub.uci:delete("wireless", id)
ifs[n] = nil
end
end
end
end
function find_interfaces(self, iflist, brlist)
local iface
for iface, _ in pairs(ifs) do
iflist[iface] = ifs[iface]
end
end
function ignore_interface(self, iface)
if ifs and ifs[iface] then
return false
else
return iwi.type(iface) and true or false
end
end
function add_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:set("wireless", ifs[iface].sid, "network", net:name())
ifs[iface].network = net:name()
return true
end
return false
end
function del_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:delete("wireless", ifs[iface].sid, "network")
--return true
end
return false
end
device = ub:section("wifi-device")
device:property("type")
device:property("channel")
device:property_bool("disabled")
function device.name(self)
return self.sid
end
function device.is_up(self)
local rv = false
if not self:disabled() then
st:foreach("wireless", "wifi-iface",
function(s)
if s.device == self:name() and s.up == "1" then
rv = true
return false
end
end)
end
return rv
end
function device.get_networks(self)
local nets = { }
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.device == self:name() then
nets[#nets+1] = network(s['.name'])
end
end)
return nets
end
network = ub:section("wifi-iface")
network:property("mode")
network:property("ssid")
network:property("bssid")
network:property("network")
function network._init(self, sid)
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
return s['.name'] ~= sid
end)
local dev = st:get("wireless", sid, "ifname")
or st:get("wireless", sid, "device")
if dev then
self.id = "%s.network%d" %{ dev, count }
local wtype = iwi.type(dev)
if dev and wtype then
self.winfo = iwi[wtype]
self.wdev = dev
end
end
end
function network.name(self)
return self.id
end
function network.ifname(self)
return self.wdev
end
function network.get_device(self)
if self.device then
return device(self.device)
end
end
function network.is_up(self)
return (st:get("wireless", self.sid, "up") == "1")
end
function network.active_mode(self)
local m = self.winfo and self.winfo.mode(self.wdev)
if m == "Master" or m == "Auto" then
m = "ap"
elseif m == "Ad-Hoc" then
m = "adhoc"
elseif m == "Client" then
m = "sta"
elseif m then
m = m:lower()
else
m = self:mode()
end
return m or "ap"
end
function network.active_mode_i18n(self)
return i18n.translate("a_s_if_iwmode_" .. self:active_mode())
end
function network.active_ssid(self)
return self.winfo and self.winfo.ssid(self.wdev) or
self:ssid()
end
function network.active_bssid(self)
return self.winfo and self.winfo.bssid(self.wdev) or
self:bssid() or "00:00:00:00:00:00"
end
function network.active_encryption(self)
return self.winfo and self.winfo.enctype(self.wdev) or "-"
end
function network.assoclist(self)
return self.winfo and self.winfo.assoclist(self.wdev) or { }
end
function network.frequency(self)
local freq = self.winfo and self.winfo.frequency(self.wdev)
return freq and freq > 0 and "%.03f" % (freq / 1000)
end
function network.bitrate(self)
local rate = self.winfo and self.winfo.bitrate(self.wdev)
return rate and rate > 0 and (rate / 1000)
end
function network.channel(self)
return self.winfo and self.winfo.channel(self.wdef)
end
function network.signal(self)
return self.winfo and self.winfo.signal(self.wdev) or 0
end
function network.noise(self)
return self.winfo and self.winfo.noise(self.wdev) or 0
end
function network.signal_level(self, s, n)
if self:active_bssid() ~= "00:00:00:00:00:00" then
local signal = s or self:signal()
local noise = n or self:noise()
if signal < 0 and noise < 0 then
local snr = -1 * (noise - signal)
return math.floor(snr / 5)
else
return 0
end
else
return -1
end
end
function network.signal_percent(self)
local qc = self.winfo and
self.winfo.quality(self.wdev) or 0
local qm = self.winfo and
self.winfo.quality_max(self.wdev) or 0
if qc > 0 and qm > 0 then
return math.floor((100 / qm) * qc)
else
return 0
end
end
|
libs/core: extend and fix luci.model.wireless
|
libs/core: extend and fix luci.model.wireless
|
Lua
|
apache-2.0
|
LuttyYang/luci,aa65535/luci,david-xiao/luci,palmettos/cnLuCI,maxrio/luci981213,RedSnake64/openwrt-luci-packages,daofeng2015/luci,taiha/luci,male-puppies/luci,shangjiyu/luci-with-extra,sujeet14108/luci,remakeelectric/luci,sujeet14108/luci,nmav/luci,shangjiyu/luci-with-extra,forward619/luci,bright-things/ionic-luci,Sakura-Winkey/LuCI,aircross/OpenWrt-Firefly-LuCI,tcatm/luci,joaofvieira/luci,Sakura-Winkey/LuCI,Hostle/luci,tobiaswaldvogel/luci,981213/luci-1,lcf258/openwrtcn,openwrt/luci,ollie27/openwrt_luci,tcatm/luci,oneru/luci,cshore/luci,nmav/luci,oneru/luci,ollie27/openwrt_luci,MinFu/luci,Hostle/luci,mumuqz/luci,openwrt-es/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,RuiChen1113/luci,remakeelectric/luci,joaofvieira/luci,Wedmer/luci,db260179/openwrt-bpi-r1-luci,981213/luci-1,urueedi/luci,Hostle/openwrt-luci-multi-user,kuoruan/lede-luci,dwmw2/luci,fkooman/luci,jorgifumi/luci,remakeelectric/luci,kuoruan/luci,schidler/ionic-luci,palmettos/test,chris5560/openwrt-luci,bright-things/ionic-luci,openwrt/luci,bright-things/ionic-luci,kuoruan/lede-luci,kuoruan/luci,mumuqz/luci,lcf258/openwrtcn,daofeng2015/luci,Kyklas/luci-proto-hso,palmettos/cnLuCI,daofeng2015/luci,opentechinstitute/luci,opentechinstitute/luci,palmettos/cnLuCI,LazyZhu/openwrt-luci-trunk-mod,RuiChen1113/luci,rogerpueyo/luci,cshore-firmware/openwrt-luci,bright-things/ionic-luci,Kyklas/luci-proto-hso,RuiChen1113/luci,Wedmer/luci,keyidadi/luci,bright-things/ionic-luci,aa65535/luci,jorgifumi/luci,deepak78/new-luci,maxrio/luci981213,lcf258/openwrtcn,chris5560/openwrt-luci,cshore-firmware/openwrt-luci,RedSnake64/openwrt-luci-packages,artynet/luci,artynet/luci,dwmw2/luci,thess/OpenWrt-luci,oneru/luci,david-xiao/luci,joaofvieira/luci,zhaoxx063/luci,NeoRaider/luci,dwmw2/luci,palmettos/test,keyidadi/luci,slayerrensky/luci,cshore-firmware/openwrt-luci,teslamint/luci,florian-shellfire/luci,nwf/openwrt-luci,lcf258/openwrtcn,rogerpueyo/luci,ollie27/openwrt_luci,bittorf/luci,aa65535/luci,obsy/luci,Hostle/openwrt-luci-multi-user,maxrio/luci981213,cappiewu/luci,male-puppies/luci,bright-things/ionic-luci,db260179/openwrt-bpi-r1-luci,thess/OpenWrt-luci,LazyZhu/openwrt-luci-trunk-mod,ff94315/luci-1,teslamint/luci,openwrt/luci,RedSnake64/openwrt-luci-packages,fkooman/luci,LuttyYang/luci,obsy/luci,jchuang1977/luci-1,wongsyrone/luci-1,aircross/OpenWrt-Firefly-LuCI,marcel-sch/luci,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,hnyman/luci,oyido/luci,fkooman/luci,RedSnake64/openwrt-luci-packages,cappiewu/luci,Kyklas/luci-proto-hso,mumuqz/luci,cshore/luci,aircross/OpenWrt-Firefly-LuCI,Noltari/luci,LuttyYang/luci,jorgifumi/luci,aircross/OpenWrt-Firefly-LuCI,ReclaimYourPrivacy/cloak-luci,urueedi/luci,Hostle/luci,tobiaswaldvogel/luci,Hostle/openwrt-luci-multi-user,mumuqz/luci,RuiChen1113/luci,bright-things/ionic-luci,aa65535/luci,palmettos/test,hnyman/luci,male-puppies/luci,lbthomsen/openwrt-luci,RuiChen1113/luci,obsy/luci,marcel-sch/luci,taiha/luci,florian-shellfire/luci,slayerrensky/luci,openwrt-es/openwrt-luci,dismantl/luci-0.12,Hostle/luci,teslamint/luci,artynet/luci,cshore-firmware/openwrt-luci,opentechinstitute/luci,artynet/luci,artynet/luci,cshore/luci,kuoruan/lede-luci,bittorf/luci,palmettos/cnLuCI,palmettos/test,schidler/ionic-luci,lcf258/openwrtcn,fkooman/luci,dwmw2/luci,Sakura-Winkey/LuCI,jchuang1977/luci-1,schidler/ionic-luci,tcatm/luci,sujeet14108/luci,keyidadi/luci,keyidadi/luci,jlopenwrtluci/luci,wongsyrone/luci-1,cshore/luci,male-puppies/luci,mumuqz/luci,oneru/luci,ff94315/luci-1,aa65535/luci,slayerrensky/luci,Hostle/luci,joaofvieira/luci,thess/OpenWrt-luci,chris5560/openwrt-luci,Hostle/luci,opentechinstitute/luci,teslamint/luci,schidler/ionic-luci,oyido/luci,chris5560/openwrt-luci,palmettos/cnLuCI,981213/luci-1,mumuqz/luci,nmav/luci,maxrio/luci981213,palmettos/test,Noltari/luci,cshore-firmware/openwrt-luci,ff94315/luci-1,NeoRaider/luci,ollie27/openwrt_luci,nmav/luci,jorgifumi/luci,harveyhu2012/luci,tobiaswaldvogel/luci,nwf/openwrt-luci,hnyman/luci,nwf/openwrt-luci,Hostle/openwrt-luci-multi-user,opentechinstitute/luci,slayerrensky/luci,jlopenwrtluci/luci,RedSnake64/openwrt-luci-packages,teslamint/luci,deepak78/new-luci,male-puppies/luci,NeoRaider/luci,schidler/ionic-luci,kuoruan/luci,Wedmer/luci,david-xiao/luci,schidler/ionic-luci,thess/OpenWrt-luci,db260179/openwrt-bpi-r1-luci,marcel-sch/luci,tobiaswaldvogel/luci,NeoRaider/luci,opentechinstitute/luci,thesabbir/luci,forward619/luci,jchuang1977/luci-1,david-xiao/luci,RuiChen1113/luci,kuoruan/lede-luci,marcel-sch/luci,jchuang1977/luci-1,dismantl/luci-0.12,db260179/openwrt-bpi-r1-luci,male-puppies/luci,male-puppies/luci,kuoruan/luci,jchuang1977/luci-1,jlopenwrtluci/luci,ff94315/luci-1,palmettos/cnLuCI,lcf258/openwrtcn,remakeelectric/luci,marcel-sch/luci,nwf/openwrt-luci,RuiChen1113/luci,maxrio/luci981213,ReclaimYourPrivacy/cloak-luci,taiha/luci,db260179/openwrt-bpi-r1-luci,cappiewu/luci,taiha/luci,mumuqz/luci,LazyZhu/openwrt-luci-trunk-mod,florian-shellfire/luci,palmettos/test,daofeng2015/luci,dwmw2/luci,joaofvieira/luci,harveyhu2012/luci,aircross/OpenWrt-Firefly-LuCI,kuoruan/lede-luci,florian-shellfire/luci,LuttyYang/luci,cshore/luci,joaofvieira/luci,thesabbir/luci,artynet/luci,cshore/luci,harveyhu2012/luci,taiha/luci,db260179/openwrt-bpi-r1-luci,hnyman/luci,oyido/luci,dwmw2/luci,obsy/luci,oneru/luci,tcatm/luci,deepak78/new-luci,slayerrensky/luci,oyido/luci,oneru/luci,oyido/luci,openwrt-es/openwrt-luci,david-xiao/luci,Wedmer/luci,Kyklas/luci-proto-hso,jorgifumi/luci,Noltari/luci,forward619/luci,RuiChen1113/luci,urueedi/luci,jchuang1977/luci-1,ollie27/openwrt_luci,florian-shellfire/luci,joaofvieira/luci,male-puppies/luci,kuoruan/luci,cshore-firmware/openwrt-luci,oneru/luci,david-xiao/luci,cshore/luci,bittorf/luci,obsy/luci,Noltari/luci,Wedmer/luci,jlopenwrtluci/luci,Sakura-Winkey/LuCI,harveyhu2012/luci,aa65535/luci,dismantl/luci-0.12,RedSnake64/openwrt-luci-packages,cappiewu/luci,Sakura-Winkey/LuCI,thesabbir/luci,kuoruan/lede-luci,david-xiao/luci,lbthomsen/openwrt-luci,joaofvieira/luci,urueedi/luci,slayerrensky/luci,sujeet14108/luci,openwrt-es/openwrt-luci,keyidadi/luci,marcel-sch/luci,MinFu/luci,florian-shellfire/luci,nmav/luci,bright-things/ionic-luci,rogerpueyo/luci,tcatm/luci,Wedmer/luci,MinFu/luci,remakeelectric/luci,chris5560/openwrt-luci,florian-shellfire/luci,Noltari/luci,deepak78/new-luci,db260179/openwrt-bpi-r1-luci,wongsyrone/luci-1,teslamint/luci,cshore/luci,forward619/luci,Noltari/luci,Hostle/openwrt-luci-multi-user,jlopenwrtluci/luci,openwrt-es/openwrt-luci,zhaoxx063/luci,lbthomsen/openwrt-luci,dwmw2/luci,daofeng2015/luci,shangjiyu/luci-with-extra,urueedi/luci,nmav/luci,wongsyrone/luci-1,rogerpueyo/luci,bittorf/luci,nmav/luci,LazyZhu/openwrt-luci-trunk-mod,wongsyrone/luci-1,fkooman/luci,ReclaimYourPrivacy/cloak-luci,kuoruan/lede-luci,ReclaimYourPrivacy/cloak-luci,taiha/luci,ff94315/luci-1,tcatm/luci,tcatm/luci,slayerrensky/luci,forward619/luci,Sakura-Winkey/LuCI,MinFu/luci,zhaoxx063/luci,remakeelectric/luci,thess/OpenWrt-luci,rogerpueyo/luci,fkooman/luci,kuoruan/luci,artynet/luci,nmav/luci,harveyhu2012/luci,dismantl/luci-0.12,daofeng2015/luci,Kyklas/luci-proto-hso,Wedmer/luci,Kyklas/luci-proto-hso,openwrt/luci,Hostle/luci,openwrt/luci,marcel-sch/luci,hnyman/luci,chris5560/openwrt-luci,obsy/luci,MinFu/luci,palmettos/cnLuCI,keyidadi/luci,NeoRaider/luci,lbthomsen/openwrt-luci,MinFu/luci,Sakura-Winkey/LuCI,rogerpueyo/luci,maxrio/luci981213,bittorf/luci,thess/OpenWrt-luci,urueedi/luci,artynet/luci,urueedi/luci,LazyZhu/openwrt-luci-trunk-mod,lcf258/openwrtcn,981213/luci-1,jorgifumi/luci,opentechinstitute/luci,hnyman/luci,kuoruan/luci,schidler/ionic-luci,remakeelectric/luci,Noltari/luci,dismantl/luci-0.12,tobiaswaldvogel/luci,remakeelectric/luci,lcf258/openwrtcn,LazyZhu/openwrt-luci-trunk-mod,dwmw2/luci,jchuang1977/luci-1,oyido/luci,openwrt/luci,thesabbir/luci,thesabbir/luci,aircross/OpenWrt-Firefly-LuCI,ollie27/openwrt_luci,thesabbir/luci,chris5560/openwrt-luci,obsy/luci,cappiewu/luci,fkooman/luci,zhaoxx063/luci,dismantl/luci-0.12,Hostle/luci,thesabbir/luci,shangjiyu/luci-with-extra,openwrt-es/openwrt-luci,ollie27/openwrt_luci,deepak78/new-luci,NeoRaider/luci,slayerrensky/luci,lcf258/openwrtcn,teslamint/luci,aa65535/luci,opentechinstitute/luci,ReclaimYourPrivacy/cloak-luci,aircross/OpenWrt-Firefly-LuCI,oneru/luci,Hostle/openwrt-luci-multi-user,taiha/luci,981213/luci-1,deepak78/new-luci,dismantl/luci-0.12,zhaoxx063/luci,oyido/luci,ReclaimYourPrivacy/cloak-luci,shangjiyu/luci-with-extra,jlopenwrtluci/luci,schidler/ionic-luci,zhaoxx063/luci,openwrt-es/openwrt-luci,MinFu/luci,zhaoxx063/luci,jorgifumi/luci,ff94315/luci-1,tcatm/luci,lbthomsen/openwrt-luci,thesabbir/luci,lbthomsen/openwrt-luci,Hostle/openwrt-luci-multi-user,lbthomsen/openwrt-luci,jlopenwrtluci/luci,cshore-firmware/openwrt-luci,LuttyYang/luci,aa65535/luci,kuoruan/luci,MinFu/luci,bittorf/luci,nwf/openwrt-luci,NeoRaider/luci,nwf/openwrt-luci,marcel-sch/luci,wongsyrone/luci-1,thess/OpenWrt-luci,lbthomsen/openwrt-luci,palmettos/test,bittorf/luci,NeoRaider/luci,openwrt/luci,forward619/luci,Kyklas/luci-proto-hso,keyidadi/luci,981213/luci-1,cappiewu/luci,shangjiyu/luci-with-extra,Noltari/luci,teslamint/luci,Wedmer/luci,harveyhu2012/luci,981213/luci-1,obsy/luci,artynet/luci,ff94315/luci-1,ReclaimYourPrivacy/cloak-luci,forward619/luci,RedSnake64/openwrt-luci-packages,deepak78/new-luci,rogerpueyo/luci,LuttyYang/luci,shangjiyu/luci-with-extra,nwf/openwrt-luci,taiha/luci,rogerpueyo/luci,hnyman/luci,chris5560/openwrt-luci,oyido/luci,nmav/luci,zhaoxx063/luci,sujeet14108/luci,cappiewu/luci,lcf258/openwrtcn,kuoruan/lede-luci,shangjiyu/luci-with-extra,openwrt/luci,jlopenwrtluci/luci,david-xiao/luci,forward619/luci,tobiaswaldvogel/luci,wongsyrone/luci-1,wongsyrone/luci-1,thess/OpenWrt-luci,sujeet14108/luci,sujeet14108/luci,keyidadi/luci,Hostle/openwrt-luci-multi-user,nwf/openwrt-luci,cappiewu/luci,jchuang1977/luci-1,db260179/openwrt-bpi-r1-luci,jorgifumi/luci,cshore-firmware/openwrt-luci,tobiaswaldvogel/luci,bittorf/luci,florian-shellfire/luci,fkooman/luci,LuttyYang/luci,palmettos/cnLuCI,sujeet14108/luci,urueedi/luci,maxrio/luci981213,ff94315/luci-1,tobiaswaldvogel/luci,palmettos/test,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,openwrt-es/openwrt-luci,daofeng2015/luci,mumuqz/luci,LuttyYang/luci,daofeng2015/luci,deepak78/new-luci,harveyhu2012/luci,hnyman/luci,Noltari/luci,Sakura-Winkey/LuCI
|
b8c1b19db880689eb4cf861f68833bbfb9b1dfc2
|
CCLib/src/java/lang/native/Throwable.lua
|
CCLib/src/java/lang/native/Throwable.lua
|
natives["java.lang.Throwable"] = natives["java.lang.Throwable"] or {}
natives["java.lang.Throwable"]["fillInStackTrace()Ljava/lang/Throwable;"] = function(this)
local stackTrace = newArray(getArrayClass("[Ljava.lang.StackTraceElement;"), 0)
local lStackTrace = getStackTrace()
stackTrace[4] = #lStackTrace - 1
local StackTraceElement = classByName("java.lang.StackTraceElement")
for i=1,#lStackTrace-1 do
local v = lStackTrace[i]
stackTrace[5][i] = newInstance(StackTraceElement)
local m = findMethod(StackTraceElement, "<init>(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V")
local lineNumber = v.lineNumber
if bit.band(m.acc,METHOD_ACC.NATIVE) == METHOD_ACC.NATIVE then
lineNumber = -2
end
m[1](stackTrace[5][i], toJString(v.className), toJString(v.methodName), toJString(v.fileName or ""), lineNumber or -1)
end
setObjectField(this, "stackTrace", stackTrace)
return this
end
|
natives["java.lang.Throwable"] = natives["java.lang.Throwable"] or {}
natives["java.lang.Throwable"]["fillInStackTrace()Ljava/lang/Throwable;"] = function(this)
local stackTrace = newArray(getArrayClass("[Ljava.lang.StackTraceElement;"), 0)
local lStackTrace = getStackTrace()
stackTrace[4] = #lStackTrace - 1
local StackTraceElement = classByName("java.lang.StackTraceElement")
for i=1,#lStackTrace-1 do
local v = lStackTrace[i]
stackTrace[5][#lStackTrace - i] = newInstance(StackTraceElement)
local m = findMethod(StackTraceElement, "<init>(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V")
local lineNumber = v.lineNumber
if bit.band(m.acc,METHOD_ACC.NATIVE) == METHOD_ACC.NATIVE then
lineNumber = -2
end
m[1](stackTrace[5][#lStackTrace - i], toJString(v.className), toJString(v.methodName), toJString(v.fileName or ""), lineNumber or -1)
end
setObjectField(this, "stackTrace", stackTrace)
return this
end
|
Fix stack trace order being reversed
|
Fix stack trace order being reversed
|
Lua
|
mit
|
Team-CC-Corp/JVML-JIT,apemanzilla/JVML-JIT
|
c679e85bb6ebf56086e685ec8984d7e748497d63
|
premake.lua
|
premake.lua
|
project.name = "Premake4"
-- Project options
addoption("no-tests", "Build without automated tests")
-- Output directories
project.config["Debug"].bindir = "bin/debug"
project.config["Release"].bindir = "bin/release"
-- Packages
dopackage("src")
-- Cleanup code
function doclean(cmd, arg)
docommand(cmd, arg)
os.rmdir("bin")
os.rmdir("doc")
end
-- Release code
REPOS = "https://premake.svn.sourceforge.net/svnroot/premake"
TRUNK = "/trunk"
BRANCHES = "/branches/4.0-alpha/"
function dorelease(cmd, arg)
if (not arg) then
error "You must specify a version"
end
-------------------------------------------------------------------
-- Make sure everything is good before I start
-------------------------------------------------------------------
print("")
print("PRE-FLIGHT CHECKLIST")
print(" * is README up-to-date?")
print(" * is CHANGELOG up-to-date?")
print(" * did you test build with GCC?")
print(" * did you test build with Doxygen?")
print(" * are 'svn' (all) and '7z' (Windows) available?")
print("")
print("Press [Enter] to continue or [^C] to quit.")
io.stdin:read("*l")
-------------------------------------------------------------------
-- Set up environment
-------------------------------------------------------------------
local version = arg
os.mkdir("releases")
local folder = "premake-"..version
local trunk = REPOS..TRUNK
local branch = REPOS..BRANCHES..version
-------------------------------------------------------------------
-- Build and run all automated tests on working copy
-------------------------------------------------------------------
print("Building tests on working copy...")
os.execute("premake --target gnu >releases/release.log")
result = os.execute("make CONFIG=Release >releases/release.log")
if (result ~= 0) then
error("Test build failed; see release.log for details")
end
-------------------------------------------------------------------
-- Look for a release branch in SVN, and create one from trunk if necessary
-------------------------------------------------------------------
print("Checking for release branch...")
os.chdir("releases")
result = os.execute(string.format("svn ls %s >release.log 2>&1", branch))
if (result ~= 0) then
print("Creating release branch...")
result = os.execute(string.format('svn copy %s %s -m "Creating release branch for %s" >release.log', trunk, branch, version))
if (result ~= 0) then
error("Failed to create release branch at "..branch)
end
end
-------------------------------------------------------------------
-- Checkout a local copy of the release branch
-------------------------------------------------------------------
print("Getting source code from release branch...")
os.execute(string.format("svn co %s %s >release.log", branch, folder))
if (not os.fileexists(folder.."/README.txt")) then
error("Unable to checkout from repository at "..branch)
end
-------------------------------------------------------------------
-- Embed version numbers into the files
-------------------------------------------------------------------
-- (embed version #s)
-- (check into branch)
-------------------------------------------------------------------
-- Build the release binary for this platform
-------------------------------------------------------------------
print("Building release version...")
os.chdir(folder)
os.execute("premake --clean --no-tests --target gnu >../release.log")
os.chdir("bin/release")
if (windows) then
os.execute("make CONFIG=Release >../release.log")
result = os.execute(string.format("7z a -tzip ..\\..\\..\\premake-win32-%s.zip premake4.exe >../release.log", version))
elseif (macosx) then
os.execute('TARGET_ARCH="-arch i386 -arch ppc" make CONFIG=Release >../release.log')
result = os.execute(string.format("tar czvf ../../../premake-macosx-%s.tar.gz premake4 >../release.log", version))
else
os.execute("make CONFIG=Release >../release.log")
result = os.execute(string.format("tar czvf ../../../premake-linux-%s.tar.gz bin/release/premake4 >../release.log", version))
end
if (result ~= 0) then
error("Failed to build binary package; see release.log for details")
end
os.chdir("../../..")
-------------------------------------------------------------------
-- Build the source code package (MacOSX only)
-------------------------------------------------------------------
if (macosx) then
result = os.execute(string.format("zip -r9 premake-src-%s.zip %s/* >release.log", version, folder))
if (result ~= 0) then
error("Failed to build source code package; see release.log for details")
end
end
-------------------------------------------------------------------
-- Clean up
-------------------------------------------------------------------
print("Cleaning up...")
os.rmdir(folder)
os.remove("release.log")
-------------------------------------------------------------------
-- Next steps
-------------------------------------------------------------------
if (windows) then
print("DONE - now run release script under Linux")
elseif (linux) then
print("DONE - now run release script under Mac OS X")
else
print("DONE - really this time")
end
end
|
project.name = "Premake4"
-- Project options
addoption("no-tests", "Build without automated tests")
-- Output directories
project.config["Debug"].bindir = "bin/debug"
project.config["Release"].bindir = "bin/release"
-- Packages
dopackage("src")
-- Cleanup code
function doclean(cmd, arg)
docommand(cmd, arg)
os.rmdir("bin")
os.rmdir("doc")
end
-- Release code
REPOS = "https://premake.svn.sourceforge.net/svnroot/premake"
TRUNK = "/trunk"
BRANCHES = "/branches/4.0-alpha/"
function dorelease(cmd, arg)
if (not arg) then
error "You must specify a version"
end
-------------------------------------------------------------------
-- Make sure everything is good before I start
-------------------------------------------------------------------
print("")
print("PRE-FLIGHT CHECKLIST")
print(" * is README up-to-date?")
print(" * is CHANGELOG up-to-date?")
print(" * did you test build with GCC?")
print(" * did you test build with Doxygen?")
print(" * are 'svn' (all) and '7z' (Windows) available?")
print("")
print("Press [Enter] to continue or [^C] to quit.")
io.stdin:read("*l")
-------------------------------------------------------------------
-- Set up environment
-------------------------------------------------------------------
local version = arg
os.mkdir("releases")
local folder = "premake-"..version
local trunk = REPOS..TRUNK
local branch = REPOS..BRANCHES..version
-------------------------------------------------------------------
-- Build and run all automated tests on working copy
-------------------------------------------------------------------
print("Building tests on working copy...")
os.execute("premake --target gnu >releases/release.log")
result = os.execute("make CONFIG=Release >releases/release.log")
if (result ~= 0) then
error("Test build failed; see release.log for details")
end
-------------------------------------------------------------------
-- Look for a release branch in SVN, and create one from trunk if necessary
-------------------------------------------------------------------
print("Checking for release branch...")
os.chdir("releases")
result = os.execute(string.format("svn ls %s >release.log 2>&1", branch))
if (result ~= 0) then
print("Creating release branch...")
result = os.execute(string.format('svn copy %s %s -m "Creating release branch for %s" >release.log', trunk, branch, version))
if (result ~= 0) then
error("Failed to create release branch at "..branch)
end
end
-------------------------------------------------------------------
-- Checkout a local copy of the release branch
-------------------------------------------------------------------
print("Getting source code from release branch...")
os.execute(string.format("svn co %s %s >release.log", branch, folder))
if (not os.fileexists(folder.."/README.txt")) then
error("Unable to checkout from repository at "..branch)
end
-------------------------------------------------------------------
-- Embed version numbers into the files
-------------------------------------------------------------------
-- (embed version #s)
-- (check into branch)
-------------------------------------------------------------------
-- Build the release binary for this platform
-------------------------------------------------------------------
print("Building release version...")
os.chdir(folder)
os.execute("premake --clean --no-tests --target gnu >../release.log")
if (windows) then
os.execute("make CONFIG=Release >../release.log")
os.chdir("bin/release")
result = os.execute(string.format("7z a -tzip ..\\..\\..\\premake-win32-%s.zip premake4.exe >../release.log", version))
elseif (macosx) then
os.execute('TARGET_ARCH="-arch i386 -arch ppc" make CONFIG=Release >../release.log')
os.chdir("bin/release")
result = os.execute(string.format("tar czvf ../../../premake-macosx-%s.tar.gz premake4 >../release.log", version))
else
os.execute("make CONFIG=Release >../release.log")
os.chdir("bin/release")
result = os.execute(string.format("tar czvf ../../../premake-linux-%s.tar.gz bin/release/premake4 >../release.log", version))
end
if (result ~= 0) then
error("Failed to build binary package; see release.log for details")
end
os.chdir("../../..")
-------------------------------------------------------------------
-- Build the source code package (MacOSX only)
-------------------------------------------------------------------
if (macosx) then
result = os.execute(string.format("zip -r9 premake-src-%s.zip %s/* >release.log", version, folder))
if (result ~= 0) then
error("Failed to build source code package; see release.log for details")
end
end
-------------------------------------------------------------------
-- Clean up
-------------------------------------------------------------------
print("Cleaning up...")
os.rmdir(folder)
os.remove("release.log")
-------------------------------------------------------------------
-- Next steps
-------------------------------------------------------------------
if (windows) then
print("DONE - now run release script under Linux")
elseif (linux) then
print("DONE - now run release script under Mac OS X")
else
print("DONE - really this time")
end
end
|
Another fix to my fix
|
Another fix to my fix
|
Lua
|
bsd-3-clause
|
dimitarcl/premake-dev,Amorph/premake-dev,Amorph/premake-stable,dimitarcl/premake-dev,Amorph/premake-stable,dimitarcl/premake-dev,Amorph/premake-dev,Amorph/premake-dev,Amorph/premake-stable
|
6ac4dc75a86ea8accc195bb4dee9b2108d59004a
|
output/scripts/common.lua
|
output/scripts/common.lua
|
-- Create a new class that inherits from a base class
--
function inherits_from(baseClass)
-- The following lines are equivalent to the SimpleClass example:
-- Create the table and metatable representing the class.
local new_class = {}
local class_mt = { __index = new_class }
-- Note that this function uses class_mt as an upvalue, so every instance
-- of the class will share the same metatable.
--
function new_class:create()
local newinst = {}
setmetatable( newinst, class_mt )
return newinst
end
-- The following is the key to implementing inheritance:
-- The __index member of the new class's metatable references the
-- base class. This implies that all methods of the base class will
-- be exposed to the sub-class, and that the sub-class can override
-- any of these methods.
--
if baseClass then
setmetatable( new_class, { __index = baseClass } )
end
return new_class
end
function rewrite(component, entry, omit_properties)
--print(inspect(entry))
--print(debug.traceback())
if omit_properties == nil then
for key, val in pairs(entry) do
component[key] = val
end
else
for key, val in pairs(entry) do
if omit_properties[key] == nil then
component[key] = val
end
end
end
end
function ptr_lookup(entry, entities_lookup)
if type(entry) == "string" then
return entities_lookup[entry]
else
return entry
end
end
function rewrite_ptr(component, entry, properties, entities_lookup)
if properties == nil then return end
for key, val in pairs(properties) do
component[key]:set(ptr_lookup(entry[key], entities_lookup))
end
end
function recursive_write(final_entries, entries, omit_names)
omit_names = omit_names or {}
--print(debug.traceback())
for key, entry in pairs(entries) do
if omit_names[key] == nil then
if type(entry) == "table" then
if final_entries[key] == nil then final_entries[key] = {} end
recursive_write(final_entries[key], entry)
else
final_entries[key] = entry
end
end
end
end
function entries_from_archetypes(archetype, entries, final_entries)
recursive_write(final_entries, archetype)
recursive_write(final_entries, entries)
end
function archetyped(archetype, entries)
local final_entries = {}
entries_from_archetypes(archetype, entries, final_entries)
return final_entries
end
function map_uv_square(texcoords_to_map, texture_to_map)
local lefttop = vec2()
local bottomright = vec2()
for i = 0, texcoords_to_map:get_vertex_count()-1 do
local v = texcoords_to_map:get_vertex(i).pos
if v.x < lefttop.x then lefttop.x = v.x end
if v.y < lefttop.y then lefttop.y = v.y end
if v.x > bottomright.x then bottomright.x = v.x end
if v.y > bottomright.y then bottomright.y = v.y end
end
for i = 0, texcoords_to_map:get_vertex_count()-1 do
local v = texcoords_to_map:get_vertex(i)
v:set_texcoord (vec2(
(v.pos.x - lefttop.x) / (bottomright.x-lefttop.x),
(v.pos.y - lefttop.y) / (bottomright.y-lefttop.y)
), texture_to_map)
end
end
|
-- Create a new class that inherits from a base class
--
function inherits_from(baseClass)
-- The following lines are equivalent to the SimpleClass example:
-- Create the table and metatable representing the class.
local new_class = {}
local class_mt = { __index = new_class }
-- Note that this function uses class_mt as an upvalue, so every instance
-- of the class will share the same metatable.
--
function new_class:create()
local newinst = {}
setmetatable( newinst, class_mt )
return newinst
end
-- The following is the key to implementing inheritance:
-- The __index member of the new class's metatable references the
-- base class. This implies that all methods of the base class will
-- be exposed to the sub-class, and that the sub-class can override
-- any of these methods.
--
if baseClass then
setmetatable( new_class, { __index = baseClass } )
end
return new_class
end
function rewrite(component, entry, omit_properties)
--print(inspect(entry))
--print(debug.traceback())
if omit_properties == nil then
for key, val in pairs(entry) do
component[key] = val
end
else
for key, val in pairs(entry) do
if omit_properties[key] == nil then
component[key] = val
end
end
end
end
function ptr_lookup(entry, entities_lookup)
if type(entry) == "string" then
return entities_lookup[entry]
else
return entry
end
end
function rewrite_ptr(component, entry, properties, entities_lookup)
if properties == nil then return end
for key, val in pairs(properties) do
component[key]:set(ptr_lookup(entry[key], entities_lookup))
end
end
function recursive_write(final_entries, entries, omit_names)
omit_names = omit_names or {}
--print(debug.traceback())
for key, entry in pairs(entries) do
if omit_names[key] == nil then
if type(entry) == "table" then
if final_entries[key] == nil then final_entries[key] = {} end
recursive_write(final_entries[key], entry)
else
final_entries[key] = entry
end
end
end
end
function entries_from_archetypes(archetype, entries, final_entries)
recursive_write(final_entries, archetype)
recursive_write(final_entries, entries)
end
function archetyped(archetype, entries)
local final_entries = {}
entries_from_archetypes(archetype, entries, final_entries)
return final_entries
end
function map_uv_square(texcoords_to_map, texture_to_map)
local lefttop = vec2(texcoords_to_map:get_vertex(0).pos.x, texcoords_to_map:get_vertex(0).pos.y)
local bottomright = vec2(texcoords_to_map:get_vertex(0).pos.x, texcoords_to_map:get_vertex(0).pos.y)
for i = 0, texcoords_to_map:get_vertex_count()-1 do
local v = texcoords_to_map:get_vertex(i).pos
if v.x < lefttop.x then lefttop.x = v.x end
if v.y < lefttop.y then lefttop.y = v.y end
if v.x > bottomright.x then bottomright.x = v.x end
if v.y > bottomright.y then bottomright.y = v.y end
end
for i = 0, texcoords_to_map:get_vertex_count()-1 do
local v = texcoords_to_map:get_vertex(i)
v:set_texcoord (vec2(
(v.pos.x - lefttop.x) / (bottomright.x-lefttop.x),
(v.pos.y - lefttop.y) / (bottomright.y-lefttop.y)
), texture_to_map)
end
end
|
bug in map_uv_square
|
bug in map_uv_square
|
Lua
|
agpl-3.0
|
DaTa-/Hypersomnia,TeamHypersomnia/Hypersomnia,DaTa-/Hypersomnia,TeamHypersomnia/Augmentations,DaTa-/Hypersomnia,TeamHypersomnia/Hypersomnia,TeamHypersomnia/Hypersomnia,TeamHypersomnia/Augmentations,TeamHypersomnia/Hypersomnia,TeamHypersomnia/Hypersomnia
|
fd804446373b0608c3cbb40ec12bf38521105fca
|
tableSave.lua
|
tableSave.lua
|
do
-- declare local variables
--// exportstring( string )
--// returns a "Lua" portable version of the string
local function exportstring( s )
return string.format("%q", s)
end
--// The Save Function
function table.save( tbl,filename )
local charS,charE = " ","\n"
local file,err = io.open( filename, "wb" )
if err then return err end
-- initiate variables for save procedure
local tables,lookup = { tbl },{ [tbl] = 1 }
file:write( "return {"..charE )
for idx,t in ipairs( tables ) do
file:write( "-- Table: {"..idx.."}"..charE )
file:write( "{"..charE )
local thandled = {}
for i,v in ipairs( t ) do
thandled[i] = true
local stype = type( v )
-- only handle value
if stype == "table" then
if not lookup[v] then
table.insert( tables, v )
lookup[v] = #tables
end
file:write( charS.."{"..lookup[v].."},"..charE )
elseif stype == "string" then
file:write( charS..exportstring( v )..","..charE )
elseif stype == "number" then
file:write( charS..tostring( v )..","..charE )
end
end
for i,v in pairs( t ) do
-- escape handled values
if (not thandled[i]) then
local str = ""
local stype = type( i )
-- handle index
if stype == "table" then
if not lookup[i] then
table.insert( tables,i )
lookup[i] = #tables
end
str = charS.."[{"..lookup[i].."}]="
elseif stype == "string" then
str = charS.."["..exportstring( i ).."]="
elseif stype == "number" then
str = charS.."["..tostring( i ).."]="
end
if str ~= "" then
stype = type( v )
-- handle value
if stype == "table" then
if not lookup[v] then
table.insert( tables,v )
lookup[v] = #tables
end
file:write( str.."{"..lookup[v].."},"..charE )
elseif stype == "string" then
file:write( str..exportstring( v )..","..charE )
elseif stype == "number" then
file:write( str..tostring( v )..","..charE )
elseif stype == "boolean" then
file:write( str..tostring( v )..","..charE )
end
end
end
end
file:write( "},"..charE )
end
file:write( "}" )
file:close()
end
--// The Load Function
function table.load( sfile )
local ftables,err = loadfile( sfile )
if err then return _,err end
local tables = ftables()
for idx = 1,#tables do
local tolinki = {}
for i,v in pairs( tables[idx] ) do
if type( v ) == "table" then
tables[idx][i] = tables[v[1]]
end
if type( i ) == "table" and tables[i[1]] then
table.insert( tolinki,{ i,tables[i[1]] } )
end
end
-- link indices
for _,v in ipairs( tolinki ) do
tables[idx][v[2]],tables[idx][v[1]] = tables[idx][v[1]],nil
end
end
return tables[1]
end
-- close do
end
|
do
-- declare local variables
--// exportstring( string )
--// returns a "Lua" portable version of the string
local function exportstring( s )
return string.format("%q", s)
end
--// The Save Function
function table.save( tbl,filename )
local charS,charE = " ","\n"
local file,err = io.open( filename, "wb" )
if err then return err end
-- initiate variables for save procedure
local tables,lookup = { tbl },{ [tbl] = 1 }
file:write( "return {"..charE )
for idx,t in ipairs( tables ) do
file:write( "-- Table: {"..idx.."}"..charE )
file:write( "{"..charE )
local thandled = {}
for i,v in ipairs( t ) do
thandled[i] = true
local stype = type( v )
-- only handle value
if stype == "table" then
if not lookup[v] then
table.insert( tables, v )
lookup[v] = #tables
end
file:write( charS.."{"..lookup[v].."},"..charE )
elseif stype == "string" then
file:write( charS..exportstring( v )..","..charE )
elseif stype == "number" then
file:write( charS..tostring( v )..","..charE )
end
end
for i,v in pairs( t ) do
-- escape handled values
if (not thandled[i]) then
local str = ""
local stype = type( i )
-- handle index
if stype == "table" then
if not lookup[i] then
table.insert( tables,i )
lookup[i] = #tables
end
str = charS.."[{"..lookup[i].."}]="
elseif stype == "string" then
str = charS.."["..exportstring( i ).."]="
elseif stype == "number" then
str = charS.."["..tostring( i ).."]="
end
if str ~= "" then
stype = type( v )
-- handle value
if stype == "table" then
if not lookup[v] then
table.insert( tables,v )
lookup[v] = #tables
end
file:write( str.."{"..lookup[v].."},"..charE )
elseif stype == "string" then
file:write( str..exportstring( v )..","..charE )
elseif stype == "number" then
local num = tostring( v )
if num == "nan" or num == "-nan" or num == "inf" or num == "-inf" then
file:write( str..(num:sub(1,1) == "-" and "-" or "").."tonumber(\""..num.."\"),"..charE )
else
file:write( str..num..","..charE )
end
elseif stype == "boolean" then
file:write( str..tostring( v )..","..charE )
end
end
end
end
file:write( "},"..charE )
end
file:write( "}" )
file:close()
end
--// The Load Function
function table.load( sfile )
local ftables,err = loadfile( sfile )
if err then return _,err end
local tables = ftables()
for idx = 1,#tables do
local tolinki = {}
for i,v in pairs( tables[idx] ) do
if type( v ) == "table" then
tables[idx][i] = tables[v[1]]
end
if type( i ) == "table" and tables[i[1]] then
table.insert( tolinki,{ i,tables[i[1]] } )
end
end
-- link indices
for _,v in ipairs( tolinki ) do
tables[idx][v[2]],tables[idx][v[1]] = tables[idx][v[1]],nil
end
end
return tables[1]
end
-- close do
end
|
fix -nan or -inf cash corrupting gameUsers.txt
|
fix -nan or -inf cash corrupting gameUsers.txt
|
Lua
|
mit
|
cracker64/Crackbot,GLolol/Crackbot,wolfy1339/WolfyBot,wolfy1339/WolfyBot,GLolol/Crackbot,cracker64/Crackbot,wolfy1339/WolfyBot
|
05cad423ce2582a2828f35291c825f8ce7eb38a1
|
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/cpufreq.lua
|
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/cpufreq.lua
|
-- Licensed to the public under the Apache License 2.0.
module("luci.statistics.rrdtool.definitions.cpufreq",package.seeall)
local uci = require("luci.model.uci").cursor()
local extraitems = uci:get("luci_statistics", "collectd_cpufreq", "ExtraItems") or nil
function item()
return luci.i18n.translate("CPU Frequency")
end
function rrdargs( graph, plugin, plugin_instance, dtype )
local cpufreq = {
title = "%H: Processor frequency - core %pi",
alt_autoscale = true,
vlabel = "Frequency (Hz)",
number_format = "%3.2lf%s",
data = {
types = {"cpufreq" },
options = {
cpufreq = { color = "ff0000", title = "Frequency" },
}
}
}
if extraitems then
local transitions = {
title = "%H: Frequency transitions - core %pi",
alt_autoscale = true,
vlabel = "Transitions",
number_format = "%3.2lf%s",
data = {
types = { "transitions" },
options = {
transitions = { color = "0000ff", title = "Transitions", noarea=true },
}
}
}
local percentage = {
title = "%H: Frequency distribution - core %pi",
alt_autoscale = true,
vlabel = "Frequency (Hz)",
number_format = "%5.2lf%%",
data = {
types = { "percent" },
options = {
percent = { title = "Frequency %di" },
}
}
}
return { cpufreq, transitions, percentage }
else
return { cpufreq }
end
end
|
-- Licensed to the public under the Apache License 2.0.
module("luci.statistics.rrdtool.definitions.cpufreq",package.seeall)
local uci = require("luci.model.uci").cursor()
local extraitems = uci:get("luci_statistics", "collectd_cpufreq", "ExtraItems") or nil
function item()
return luci.i18n.translate("CPU Frequency")
end
function rrdargs( graph, plugin, plugin_instance, dtype )
local cpufreq = {
title = "%H: Processor frequency - core %pi",
alt_autoscale = true,
vlabel = "Frequency (Hz)",
number_format = "%3.2lf%s",
data = {
types = {"cpufreq" },
options = {
cpufreq = { color = "ff0000", title = "Frequency" },
}
}
}
if extraitems then
local transitions = {
title = "%H: Frequency transitions - core %pi",
alt_autoscale = true,
vlabel = "Transitions",
number_format = "%3.2lf%s",
data = {
types = { "transitions" },
options = {
transitions = { color = "0000ff", title = "Transitions", noarea=true },
}
}
}
local percentage = {
title = "%H: Frequency distribution - core %pi",
alt_autoscale = true,
vlabel = "Percent",
number_format = "%5.2lf%%",
ordercolor = true,
data = {
types = { "percent" },
options = {
percent = { title = "%di Hz", negweight = true },
}
}
}
return { cpufreq, transitions, percentage }
else
return { cpufreq }
end
end
|
luci-app-statistics: cpufreq: enhance additional data
|
luci-app-statistics: cpufreq: enhance additional data
* Use the new data series sorting and coloring options to
display the frequencies in order and with matching coloring in
different cores.
* Fix the y-axis text and legend in the frequency usage graph
Signed-off-by: Hannu Nyman <ab53a3387de93e31696058c104e6f769cd83fd1b@iki.fi>
|
Lua
|
apache-2.0
|
nmav/luci,nmav/luci,rogerpueyo/luci,hnyman/luci,hnyman/luci,lbthomsen/openwrt-luci,artynet/luci,rogerpueyo/luci,nmav/luci,lbthomsen/openwrt-luci,openwrt/luci,openwrt/luci,Noltari/luci,rogerpueyo/luci,tobiaswaldvogel/luci,hnyman/luci,Noltari/luci,Noltari/luci,openwrt/luci,Noltari/luci,hnyman/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,openwrt/luci,artynet/luci,rogerpueyo/luci,openwrt/luci,tobiaswaldvogel/luci,nmav/luci,lbthomsen/openwrt-luci,nmav/luci,rogerpueyo/luci,tobiaswaldvogel/luci,artynet/luci,lbthomsen/openwrt-luci,Noltari/luci,hnyman/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,Noltari/luci,tobiaswaldvogel/luci,nmav/luci,artynet/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,nmav/luci,openwrt/luci,tobiaswaldvogel/luci,Noltari/luci,artynet/luci,openwrt/luci,hnyman/luci,lbthomsen/openwrt-luci,artynet/luci,artynet/luci,artynet/luci,Noltari/luci,hnyman/luci,nmav/luci,Noltari/luci,openwrt/luci,lbthomsen/openwrt-luci,artynet/luci,nmav/luci,rogerpueyo/luci,hnyman/luci
|
43444727069b653afff514d03cf73cff285bfc78
|
mod_statsd/mod_statsd.lua
|
mod_statsd/mod_statsd.lua
|
-- Log common stats to statsd
--
-- Copyright (C) 2014 Daurnimator
--
-- This module is MIT/X11 licensed.
local socket = require "socket"
local iterators = require "util.iterators"
local jid = require "util.jid"
local options = module:get_option("statsd") or {}
-- Create UDP socket to statsd server
local sock = socket.udp()
sock:setpeername(options.hostname or "127.0.0.1", options.port or 8125)
-- Metrics are namespaced by ".", and seperated by newline
function clean(s) return (s:gsub("[%.:\n]", "_")) end
-- A 'safer' send function to expose
function send(s) return sock:send(s) end
-- prefix should end in "."
local prefix = (options.prefix or ("prosody." .. clean(module.host))) .. "."
-- Track users as they bind/unbind
-- count bare sessions every time, as we have no way to tell if it's a new bare session or not
module:hook("resource-bind", function(event)
send(prefix.."bare_sessions:"..iterators.count(bare_sessions).."|g")
send(prefix.."full_sessions:+1|g")
end, 1)
module:hook("resource-unbind", function(event)
send(prefix.."bare_sessions:"..iterators.count(bare_sessions).."|g")
send(prefix.."full_sessions:-1|g")
end, 1)
-- Track MUC occupants as they join/leave
module:hook("muc-occupant-joined", function(event)
send(prefix.."n_occupants:+1|g")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".occupants:+1|g")
end)
module:hook("muc-occupant-left", function(event)
send(prefix.."n_occupants:-1|g")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".occupants:-1|g")
end)
-- Misc other MUC
module:hook("muc-broadcast-message", function(event)
send(prefix.."broadcast-message:1|c")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".broadcast-message:1|c")
end)
module:hook("muc-invite", function(event)
send(prefix.."invite:1|c")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".invite:1|c")
local to_node, to_host, to_resource = jid.split(event.stanza.attr.to)
send(prefix..clean(to_node)..".invites:1|c")
end)
|
-- Log common stats to statsd
--
-- Copyright (C) 2014 Daurnimator
--
-- This module is MIT/X11 licensed.
local socket = require "socket"
local iterators = require "util.iterators"
local jid = require "util.jid"
local options = module:get_option("statsd") or {}
-- Create UDP socket to statsd server
local sock = socket.udp()
sock:setpeername(options.hostname or "127.0.0.1", options.port or 8125)
-- Metrics are namespaced by ".", and seperated by newline
function clean(s) return (s:gsub("[%.:\n]", "_")) end
-- A 'safer' send function to expose
function send(s) return sock:send(s) end
-- prefix should end in "."
local prefix = (options.prefix or "prosody") .. "."
if not options.no_host then
prefix = prefix .. clean(module.host) .. "."
end
-- Track users as they bind/unbind
-- count bare sessions every time, as we have no way to tell if it's a new bare session or not
module:hook("resource-bind", function(event)
send(prefix.."bare_sessions:"..iterators.count(bare_sessions).."|g")
send(prefix.."full_sessions:+1|g")
end, 1)
module:hook("resource-unbind", function(event)
send(prefix.."bare_sessions:"..iterators.count(bare_sessions).."|g")
send(prefix.."full_sessions:-1|g")
end, 1)
-- Track MUC occupants as they join/leave
module:hook("muc-occupant-joined", function(event)
send(prefix.."n_occupants:+1|g")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".occupants:+1|g")
end)
module:hook("muc-occupant-left", function(event)
send(prefix.."n_occupants:-1|g")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".occupants:-1|g")
end)
-- Misc other MUC
module:hook("muc-broadcast-message", function(event)
send(prefix.."broadcast-message:1|c")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".broadcast-message:1|c")
end)
module:hook("muc-invite", function(event)
send(prefix.."invite:1|c")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".invite:1|c")
local to_node, to_host, to_resource = jid.split(event.stanza.attr.to)
send(prefix..clean(to_node)..".invites:1|c")
end)
|
mod_statsd: Optionally include host in prefix
|
mod_statsd: Optionally include host in prefix
|
Lua
|
mit
|
NSAKEY/prosody-modules,either1/prosody-modules,amenophis1er/prosody-modules,joewalker/prosody-modules,vfedoroff/prosody-modules,brahmi2/prosody-modules,LanceJenkinZA/prosody-modules,asdofindia/prosody-modules,obelisk21/prosody-modules,mardraze/prosody-modules,BurmistrovJ/prosody-modules,iamliqiang/prosody-modules,apung/prosody-modules,guilhem/prosody-modules,cryptotoad/prosody-modules,guilhem/prosody-modules,vfedoroff/prosody-modules,apung/prosody-modules,prosody-modules/import,jkprg/prosody-modules,iamliqiang/prosody-modules,softer/prosody-modules,mardraze/prosody-modules,iamliqiang/prosody-modules,asdofindia/prosody-modules,amenophis1er/prosody-modules,softer/prosody-modules,vince06fr/prosody-modules,NSAKEY/prosody-modules,stephen322/prosody-modules,prosody-modules/import,1st8/prosody-modules,stephen322/prosody-modules,NSAKEY/prosody-modules,cryptotoad/prosody-modules,dhotson/prosody-modules,amenophis1er/prosody-modules,1st8/prosody-modules,either1/prosody-modules,Craige/prosody-modules,vince06fr/prosody-modules,mmusial/prosody-modules,brahmi2/prosody-modules,syntafin/prosody-modules,mardraze/prosody-modules,heysion/prosody-modules,heysion/prosody-modules,amenophis1er/prosody-modules,obelisk21/prosody-modules,asdofindia/prosody-modules,mardraze/prosody-modules,amenophis1er/prosody-modules,cryptotoad/prosody-modules,stephen322/prosody-modules,softer/prosody-modules,BurmistrovJ/prosody-modules,drdownload/prosody-modules,Craige/prosody-modules,olax/prosody-modules,syntafin/prosody-modules,drdownload/prosody-modules,vfedoroff/prosody-modules,LanceJenkinZA/prosody-modules,jkprg/prosody-modules,olax/prosody-modules,asdofindia/prosody-modules,drdownload/prosody-modules,1st8/prosody-modules,brahmi2/prosody-modules,mmusial/prosody-modules,syntafin/prosody-modules,syntafin/prosody-modules,obelisk21/prosody-modules,1st8/prosody-modules,jkprg/prosody-modules,stephen322/prosody-modules,either1/prosody-modules,BurmistrovJ/prosody-modules,BurmistrovJ/prosody-modules,joewalker/prosody-modules,dhotson/prosody-modules,prosody-modules/import,jkprg/prosody-modules,prosody-modules/import,crunchuser/prosody-modules,stephen322/prosody-modules,crunchuser/prosody-modules,olax/prosody-modules,vince06fr/prosody-modules,iamliqiang/prosody-modules,heysion/prosody-modules,joewalker/prosody-modules,softer/prosody-modules,apung/prosody-modules,mmusial/prosody-modules,NSAKEY/prosody-modules,apung/prosody-modules,asdofindia/prosody-modules,olax/prosody-modules,softer/prosody-modules,Craige/prosody-modules,dhotson/prosody-modules,vfedoroff/prosody-modules,NSAKEY/prosody-modules,vince06fr/prosody-modules,crunchuser/prosody-modules,vince06fr/prosody-modules,LanceJenkinZA/prosody-modules,iamliqiang/prosody-modules,either1/prosody-modules,cryptotoad/prosody-modules,heysion/prosody-modules,apung/prosody-modules,vfedoroff/prosody-modules,BurmistrovJ/prosody-modules,mmusial/prosody-modules,guilhem/prosody-modules,dhotson/prosody-modules,joewalker/prosody-modules,heysion/prosody-modules,either1/prosody-modules,LanceJenkinZA/prosody-modules,mmusial/prosody-modules,drdownload/prosody-modules,joewalker/prosody-modules,brahmi2/prosody-modules,guilhem/prosody-modules,obelisk21/prosody-modules,mardraze/prosody-modules,Craige/prosody-modules,obelisk21/prosody-modules,crunchuser/prosody-modules,1st8/prosody-modules,olax/prosody-modules,drdownload/prosody-modules,Craige/prosody-modules,crunchuser/prosody-modules,brahmi2/prosody-modules,cryptotoad/prosody-modules,LanceJenkinZA/prosody-modules,prosody-modules/import,guilhem/prosody-modules,syntafin/prosody-modules,jkprg/prosody-modules,dhotson/prosody-modules
|
6357cd1853192677b59e329beb5ca9e8376e8638
|
share/lua/website/break.lua
|
share/lua/website/break.lua
|
-- libquvi-scripts
-- Copyright (C) 2010-2012 Toni Gundogdu <legatvs@gmail.com>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "break%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/index/"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return self
end
-- Parse media URL.
function parse(self)
self.host_id = "break"
local p = quvi.fetch(self.page_url)
self.title = p:match('id="vid_title" content="(.-)"')
or error("no match: media title")
self.id = p:match("ContentID='(.-)'")
or error("no match: media ID")
local fn = p:match("FileName='(.-)'")
or error("no match: file name")
local fh = p:match('flashVars.icon = "(.-)"')
or error("no match: file hash")
self.url = {string.format("%s.flv?%s", fn, fh)}
return self
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2010-2012 Toni Gundogdu <legatvs@gmail.com>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "break%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/index/"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return self
end
-- Parse media URL.
function parse(self)
self.host_id = "break"
local p = quvi.fetch(self.page_url)
self.title = p:match("sVidTitle:%s+['\"](.-)['\"]")
or error("no match: media title")
self.id = p:match("iContentID:%s+'(.-)'")
or error("no match: media ID")
self.thumbnail_url = p:match('"og:image" content="(.-)"') or ''
local n = p:match("videoPath:%s+['\"](.-)['\"]")
or error("no match: file path")
local h = p:match("icon:%s+['\"](.-)['\"]")
or error("no match: file hash")
self.url = {string.format("%s?%s", n, h)}
return self
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
FIX: break.lua: multiple patterns
|
FIX: break.lua: multiple patterns
Fix {title,id,filepath,filehash} patterns. Add thumbnail_url.
Signed-off-by: Toni Gundogdu <eac2284b3c43676907b96f08de9d3d52d5df0361@gmail.com>
|
Lua
|
agpl-3.0
|
alech/libquvi-scripts,legatvs/libquvi-scripts,legatvs/libquvi-scripts,DangerCove/libquvi-scripts,alech/libquvi-scripts,DangerCove/libquvi-scripts
|
05dd61b9ec514a2408d0562a26672b9864ce1243
|
irc/handlers.lua
|
irc/handlers.lua
|
local pairs = pairs
local error = error
local tonumber = tonumber
local table = table
module "irc"
handlers = {}
handlers["PING"] = function(o, prefix, query)
o:send("PONG :%s", query)
end
handlers["001"] = function(o, prefix, me)
o.authed = true
o.nick = me
end
handlers["PRIVMSG"] = function(o, prefix, channel, message)
if message:sub(1,1) == "\001" then
local space = message:find(" ") or #message
o:invoke("OnCTCP", parsePrefix(prefix), channel, message:sub(2, space-1):upper(), message:sub(space+1,#message-1))
else
o:invoke("OnChat", parsePrefix(prefix), channel, message)
end
end
handlers["NOTICE"] = function(o, prefix, channel, message)
o:invoke("OnNotice", parsePrefix(prefix), channel, message)
end
handlers["JOIN"] = function(o, prefix, channel)
local user = parsePrefix(prefix)
if o.track_users then
if user.nick == o.nick then
o.channels[channel] = {users = {}}
else
o.channels[channel].users[user.nick] = user
end
end
o:invoke("OnJoin", user, channel)
end
handlers["PART"] = function(o, prefix, channel, reason)
local user = parsePrefix(prefix)
if o.track_users then
if user.nick == o.nick then
o.channels[channel] = nil
else
o.channels[channel].users[user.nick] = nil
end
end
o:invoke("OnPart", user, channel, reason)
end
handlers["QUIT"] = function(o, prefix, msg)
local user = parsePrefix(prefix)
if o.track_users then
for channel, v in pairs(o.channels) do
v.users[user.nick] = nil
end
end
o:invoke("OnQuit", user, msg)
end
handlers["NICK"] = function(o, prefix, newnick)
local user = parsePrefix(prefix)
if o.track_users then
for channel, v in pairs(o.channels) do
local users = v.users
local oldinfo = users[user.nick]
if oldinfo then
users[newnick] = oldinfo
users[newnick].nick = newnick
if users[newnick].fullhost then
users[newnick].fullhost = users[newnick].nick.."!"..users[newnick].username.."@"..users[newnick].host
end
users[user.nick] = nil
o:invoke("NickChange", user, newnick, channel)
end
end
else
o:invoke("NickChange", user, newnick)
end
if user.nick == o.nick then
o.nick = newnick
end
end
local function needNewNick(o, prefix, target, badnick)
local newnick = o.nickGenerator(badnick)
o:send("NICK %s", newnick)
end
-- ERR_ERRONEUSNICKNAME (Misspelt but remains for historical reasons)
handlers["432"] = needNewNick
-- ERR_NICKNAMEINUSE
handlers["433"] = needNewNick
--WHO list
handlers["352"] = function(o, prefix, me, channel, name1, host, serv, name, access1 ,something, something2)
if o.track_users then
local user = {nick=name, host=host, username=name1, serv=serv, access=parseAccess(access1), fullhost=name.."!"..name1.."@"..host}
--print(user.nick,user.host,user.ID,user.serv,user.access)
o.channels[channel].users[user.nick] = user
end
end
--NAMES list
--disabled, better to always track everything instead of having it have an empty user with just an "access" field
--also it is broken a bit anyway
--[[handlers["353"] = function(o, prefix, me, chanType, channel, names)
if o.track_users then
o.channels[channel] = o.channels[channel] or {users = {}, type = chanType}
local users = o.channels[channel].users
for nick in names:gmatch("(%S+)") do
local access, name = parseNick(nick)
users[name] = {access = access}
end
end
end]]
--end of NAMES
handlers["366"] = function(o, prefix, me, channel, msg)
if o.track_users then
o:invoke("NameList", channel, msg)
end
end
--no topic
handlers["331"] = function(o, prefix, me, channel)
o:invoke("OnTopic", channel, nil)
end
--new topic
handlers["TOPIC"] = function(o, prefix, channel, topic)
o:invoke("OnTopic", channel, topic)
end
handlers["332"] = function(o, prefix, me, channel, topic)
o:invoke("OnTopic", channel, topic)
end
--topic creation info
handlers["333"] = function(o, prefix, me, channel, nick, time)
o:invoke("OnTopicInfo", channel, nick, tonumber(time))
end
handlers["KICK"] = function(o, prefix, channel, kicked, reason)
o:invoke("OnKick", channel, kicked, parsePrefix(prefix), reason)
end
--RPL_UMODEIS
--To answer a query about a client's own mode, RPL_UMODEIS is sent back
handlers["221"] = function(o, prefix, user, modes)
o:invoke("OnUserMode", modes)
end
--RPL_CHANNELMODEIS
--The result from common irc servers differs from that defined by the rfc
handlers["324"] = function(o, prefix, user, channel, modes)
o:invoke("OnChannelMode", channel, modes)
end
handlers["MODE"] = function(o, prefix, target, modes, ...)
if o.track_users and target ~= o.nick then
local add = true
local optList = {...}
for c in modes:gmatch(".") do
if c == "+" then add = true
elseif c == "-" then add = false
elseif c == "o" then
local user = table.remove(optList, 1)
if user and o.channels[target].users[user] then o.channels[target].users[user].access.op = add end
elseif c == "h" then
local user = table.remove(optList, 1)
if user then o.channels[target].users[user].access.halfop = add end
elseif c == "v" then
local user = table.remove(optList, 1)
if user then o.channels[target].users[user].access.voice = add end
elseif c == "b" or c == "q" then
table.remove(optList, 1)
end
end
end
o:invoke("OnModeChange", parsePrefix(prefix), target, modes, ...)
end
handlers["ERROR"] = function(o, prefix, message)
o:invoke("OnDisconnect", message, true)
o:shutdown()
error(message, 3)
end
|
local pairs = pairs
local error = error
local tonumber = tonumber
local table = table
module "irc"
handlers = {}
handlers["PING"] = function(o, prefix, query)
o:send("PONG :%s", query)
end
handlers["001"] = function(o, prefix, me)
o.authed = true
o.nick = me
end
handlers["PRIVMSG"] = function(o, prefix, channel, message)
if message:sub(1,1) == "\001" then
local space = message:find(" ") or #message
o:invoke("OnCTCP", parsePrefix(prefix), channel, message:sub(2, space-1):upper(), message:sub(space+1,#message-1))
else
o:invoke("OnChat", parsePrefix(prefix), channel, message)
end
end
handlers["NOTICE"] = function(o, prefix, channel, message)
o:invoke("OnNotice", parsePrefix(prefix), channel, message)
end
handlers["JOIN"] = function(o, prefix, channel)
local user = parsePrefix(prefix)
if o.track_users then
if user.nick == o.nick and not o.channels[channel] then
o.channels[channel] = {users = {}}
end
o.channels[channel].users[user.nick] = user
end
o:invoke("OnJoin", user, channel)
end
handlers["PART"] = function(o, prefix, channel, reason)
local user = parsePrefix(prefix)
if o.track_users then
if user.nick == o.nick then
o.channels[channel] = nil
else
o.channels[channel].users[user.nick] = nil
end
end
o:invoke("OnPart", user, channel, reason)
end
handlers["QUIT"] = function(o, prefix, msg)
local user = parsePrefix(prefix)
if o.track_users then
for channel, v in pairs(o.channels) do
v.users[user.nick] = nil
end
end
o:invoke("OnQuit", user, msg)
end
handlers["NICK"] = function(o, prefix, newnick)
local user = parsePrefix(prefix)
if o.track_users then
for channel, v in pairs(o.channels) do
local users = v.users
local oldinfo = users[user.nick]
if oldinfo then
users[newnick] = oldinfo
users[newnick].nick = newnick
if users[newnick].fullhost then
users[newnick].fullhost = users[newnick].nick.."!"..users[newnick].username.."@"..users[newnick].host
end
users[user.nick] = nil
o:invoke("NickChange", user, newnick, channel)
end
end
else
o:invoke("NickChange", user, newnick)
end
if user.nick == o.nick then
o.nick = newnick
end
end
local function needNewNick(o, prefix, target, badnick)
local newnick = o.nickGenerator(badnick)
o:send("NICK %s", newnick)
end
-- ERR_ERRONEUSNICKNAME (Misspelt but remains for historical reasons)
handlers["432"] = needNewNick
-- ERR_NICKNAMEINUSE
handlers["433"] = needNewNick
--WHO list
handlers["352"] = function(o, prefix, me, channel, name1, host, serv, name, access1 ,something, something2)
if o.track_users then
local user = {nick=name, host=host, username=name1, serv=serv, access=parseAccess(access1), fullhost=name.."!"..name1.."@"..host}
--print(user.nick,user.host,user.ID,user.serv,user.access)
if not o.channels[channel] then
o.channels[channel] = {users = {}}
end
o.channels[channel].users[user.nick] = user
end
end
--NAMES list
--disabled, better to always track everything instead of having it have an empty user with just an "access" field
--also it is broken a bit anyway
--[[handlers["353"] = function(o, prefix, me, chanType, channel, names)
if o.track_users then
o.channels[channel] = o.channels[channel] or {users = {}, type = chanType}
local users = o.channels[channel].users
for nick in names:gmatch("(%S+)") do
local access, name = parseNick(nick)
users[name] = {access = access}
end
end
end]]
--end of NAMES
handlers["366"] = function(o, prefix, me, channel, msg)
if o.track_users then
o:invoke("NameList", channel, msg)
end
end
--no topic
handlers["331"] = function(o, prefix, me, channel)
o:invoke("OnTopic", channel, nil)
end
--new topic
handlers["TOPIC"] = function(o, prefix, channel, topic)
o:invoke("OnTopic", channel, topic)
end
handlers["332"] = function(o, prefix, me, channel, topic)
o:invoke("OnTopic", channel, topic)
end
--topic creation info
handlers["333"] = function(o, prefix, me, channel, nick, time)
o:invoke("OnTopicInfo", channel, nick, tonumber(time))
end
handlers["KICK"] = function(o, prefix, channel, kicked, reason)
o:invoke("OnKick", channel, kicked, parsePrefix(prefix), reason)
end
--RPL_UMODEIS
--To answer a query about a client's own mode, RPL_UMODEIS is sent back
handlers["221"] = function(o, prefix, user, modes)
o:invoke("OnUserMode", modes)
end
--RPL_CHANNELMODEIS
--The result from common irc servers differs from that defined by the rfc
handlers["324"] = function(o, prefix, user, channel, modes)
o:invoke("OnChannelMode", channel, modes)
end
handlers["MODE"] = function(o, prefix, target, modes, ...)
if o.track_users and target ~= o.nick then
local add = true
local optList = {...}
for c in modes:gmatch(".") do
if c == "+" then add = true
elseif c == "-" then add = false
elseif c == "o" then
local user = table.remove(optList, 1)
if user and o.channels[target].users[user] then o.channels[target].users[user].access.op = add end
elseif c == "h" then
local user = table.remove(optList, 1)
if user then o.channels[target].users[user].access.halfop = add end
elseif c == "v" then
local user = table.remove(optList, 1)
if user then o.channels[target].users[user].access.voice = add end
elseif c == "b" or c == "q" then
table.remove(optList, 1)
end
end
end
o:invoke("OnModeChange", parsePrefix(prefix), target, modes, ...)
end
handlers["ERROR"] = function(o, prefix, message)
o:invoke("OnDisconnect", message, true)
o:shutdown()
error(message, 3)
end
|
fix crash on startup (seems to be when WHO response happens before the channel is joined)
|
fix crash on startup (seems to be when WHO response happens before the channel is joined)
|
Lua
|
mit
|
GLolol/Crackbot,cracker64/Crackbot,cracker64/Crackbot,GLolol/Crackbot,wolfy1339/WolfyBot,wolfy1339/WolfyBot,wolfy1339/WolfyBot
|
0566df5f2839e2f0f06eaf3d7c8725a21426dd76
|
frontend/apps/filemanager/filemanagerfilesearcher.lua
|
frontend/apps/filemanager/filemanagerfilesearcher.lua
|
local CenterContainer = require("ui/widget/container/centercontainer")
local InputContainer = require("ui/widget/container/inputcontainer")
local DocumentRegistry = require("document/documentregistry")
local InputDialog = require("ui/widget/inputdialog")
local InfoMessage = require("ui/widget/infomessage")
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Menu = require("ui/widget/menu")
local Screen = require("device").screen
local util = require("ffi/util")
local Font = require("ui/font")
local DEBUG = require("dbg")
local _ = require("gettext")
local FileSearcher = InputContainer:new{
search_dialog = nil,
--filesearcher
-- state buffer
dirs = {},
files = {},
results = {},
items = 0,
commands = nil,
--filemanagersearch
use_previous_search_results = false,
lastsearch = nil,
}
function FileSearcher:readDir()
self.dirs = {self.path}
DEBUG("self.path", self.path)
self.files = {}
while #self.dirs ~= 0 do
local new_dirs = {}
-- handle each dir
for __, d in pairs(self.dirs) do
-- handle files in d
for f in lfs.dir(d) do
local fullpath = d.."/"..f
local attributes = lfs.attributes(fullpath)
if attributes.mode == "directory" and f ~= "." and f~=".." then
table.insert(new_dirs, fullpath)
elseif attributes.mode == "file" and DocumentRegistry:getProvider(fullpath) then
table.insert(self.files, {name = f, path = fullpath, attr = attributes})
end
end
end
self.dirs = new_dirs
end
end
function FileSearcher:setSearchResults()
local ReaderUI = require("apps/reader/readerui")
local keywords = self.search_value
--DEBUG("self.files", self.files)
self.results = {}
if keywords == " " then -- one space to show all files
self.results = self.files
else
for __,f in pairs(self.files) do
DEBUG("f", f)
if string.find(string.lower(f.name), string.lower(keywords)) then
f.text = f.name
f.name = nil
f.callback = function()
ReaderUI:showReader(f.path)
end
table.insert(self.results, f)
end
end
end
--DEBUG("self.results", self.results)
self.keywords = keywords
self.items = #self.results
end
function FileSearcher:init(search_path)
self.path = search_path or lfs.currentdir()
self:showSearch()
end
function FileSearcher:close()
if self.search_value then
UIManager:close(self.search_dialog)
if string.len(self.search_value) > 0 then
self:readDir() -- TODO this probably doesn't need to be repeated once it's been done
self:setSearchResults() -- TODO doesn't have to be repeated if the search term is the same
if #self.results > 0 then
self:showSearchResults() -- TODO something about no results
else
UIManager:show(
InfoMessage:new{
text = util.template(_("Found no files matching '%1'."), self.search_value)
}
)
end
end
end
end
function FileSearcher:showSearch()
local dummy = self.search_value
self.search_dialog = InputDialog:new{
title = _("Search for books by filename"),
input = self.search_value,
buttons = {
{
{
text = _("Cancel"),
enabled = true,
callback = function()
self.search_dialog:onClose()
UIManager:close(self.search_dialog)
end,
},
{
text = _("Find books"),
enabled = true,
callback = function()
self.search_value = self.search_dialog:getInputText()
if self.search_value == dummy then -- probably DELETE this if/else block
self.use_previous_search_results = true
else
self.use_previous_search_results = false
end
self:close()
end,
},
},
},
}
self.search_dialog:onShowKeyboard()
UIManager:show(self.search_dialog)
end
function FileSearcher:showSearchResults()
local menu_container = CenterContainer:new{
dimen = Screen:getSize(),
}
self.search_menu = Menu:new{
width = Screen:getWidth()-15,
height = Screen:getHeight()-15,
show_parent = menu_container,
onMenuHold = self.onMenuHold,
cface = Font:getFace("cfont", 22),
_manager = self,
}
table.insert(menu_container, self.search_menu)
self.search_menu.close_callback = function()
UIManager:close(menu_container)
end
table.sort(self.results, function(v1,v2) return v1.text < v2.text end)
self.search_menu:switchItemTable(_("Search Results"), self.results)
UIManager:show(menu_container)
end
return FileSearcher
|
local CenterContainer = require("ui/widget/container/centercontainer")
local InputContainer = require("ui/widget/container/inputcontainer")
local DocumentRegistry = require("document/documentregistry")
local InputDialog = require("ui/widget/inputdialog")
local InfoMessage = require("ui/widget/infomessage")
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Menu = require("ui/widget/menu")
local Screen = require("device").screen
local util = require("ffi/util")
local Font = require("ui/font")
local DEBUG = require("dbg")
local _ = require("gettext")
local FileSearcher = InputContainer:new{
search_dialog = nil,
--filesearcher
-- state buffer
dirs = {},
files = {},
results = {},
items = 0,
commands = nil,
--filemanagersearch
use_previous_search_results = false,
lastsearch = nil,
}
function FileSearcher:readDir()
self.dirs = {self.path}
DEBUG("self.path", self.path)
self.files = {}
while #self.dirs ~= 0 do
local new_dirs = {}
-- handle each dir
for __, d in pairs(self.dirs) do
-- handle files in d
for f in lfs.dir(d) do
local fullpath = d.."/"..f
local attributes = lfs.attributes(fullpath)
if attributes.mode == "directory" and f ~= "." and f~=".." then
table.insert(new_dirs, fullpath)
table.insert(self.files, {name = f, path = fullpath, attr = attributes})
elseif attributes.mode == "file" and DocumentRegistry:getProvider(fullpath) then
table.insert(self.files, {name = f, path = fullpath, attr = attributes})
end
end
end
self.dirs = new_dirs
end
end
function FileSearcher:setSearchResults()
local FileManager = require("apps/filemanager/filemanager")
local ReaderUI = require("apps/reader/readerui")
local keywords = self.search_value
--DEBUG("self.files", self.files)
self.results = {}
if keywords == " " then -- one space to show all files
self.results = self.files
else
for __,f in pairs(self.files) do
DEBUG("f", f)
if string.find(string.lower(f.name), string.lower(keywords)) then
if f.attr.mode == "directory" then
f.text = f.name.."/"
f.name = nil
f.callback = function()
FileManager:showFiles(f.path)
end
table.insert(self.results, f)
else
f.text = f.name
f.name = nil
f.callback = function()
ReaderUI:showReader(f.path)
end
table.insert(self.results, f)
end
end
end
end
--DEBUG("self.results", self.results)
self.keywords = keywords
self.items = #self.results
end
function FileSearcher:init(search_path)
self.path = search_path or lfs.currentdir()
self:showSearch()
end
function FileSearcher:close()
if self.search_value then
UIManager:close(self.search_dialog)
if string.len(self.search_value) > 0 then
self:readDir() -- TODO this probably doesn't need to be repeated once it's been done
self:setSearchResults() -- TODO doesn't have to be repeated if the search term is the same
if #self.results > 0 then
self:showSearchResults() -- TODO something about no results
else
UIManager:show(
InfoMessage:new{
text = util.template(_("Found no files matching '%1'."), self.search_value)
}
)
end
end
end
end
function FileSearcher:showSearch()
local dummy = self.search_value
self.search_dialog = InputDialog:new{
title = _("Search for books by filename"),
input = self.search_value,
buttons = {
{
{
text = _("Cancel"),
enabled = true,
callback = function()
self.search_dialog:onClose()
UIManager:close(self.search_dialog)
end,
},
{
text = _("Find books"),
enabled = true,
callback = function()
self.search_value = self.search_dialog:getInputText()
if self.search_value == dummy then -- probably DELETE this if/else block
self.use_previous_search_results = true
else
self.use_previous_search_results = false
end
self:close()
end,
},
},
},
}
self.search_dialog:onShowKeyboard()
UIManager:show(self.search_dialog)
end
function FileSearcher:showSearchResults()
local menu_container = CenterContainer:new{
dimen = Screen:getSize(),
}
self.search_menu = Menu:new{
width = Screen:getWidth()-15,
height = Screen:getHeight()-15,
show_parent = menu_container,
onMenuHold = self.onMenuHold,
cface = Font:getFace("cfont", 22),
_manager = self,
}
table.insert(menu_container, self.search_menu)
self.search_menu.close_callback = function()
UIManager:close(menu_container)
end
table.sort(self.results, function(v1,v2) return v1.text < v2.text end)
self.search_menu:switchItemTable(_("Search Results"), self.results)
UIManager:show(menu_container)
end
return FileSearcher
|
FileSearcher: also show directory results
|
FileSearcher: also show directory results
Fixes #2177
|
Lua
|
agpl-3.0
|
Frenzie/koreader,poire-z/koreader,robert00s/koreader,houqp/koreader,apletnev/koreader,Hzj-jie/koreader,NiLuJe/koreader,Markismus/koreader,pazos/koreader,mihailim/koreader,poire-z/koreader,koreader/koreader,mwoz123/koreader,lgeek/koreader,Frenzie/koreader,NiLuJe/koreader,koreader/koreader
|
a3a8b418966a32301e4cbec74e4b760f01d61c54
|
mod_register_json/mod_register_json.lua
|
mod_register_json/mod_register_json.lua
|
-- Expose a simple servlet to handle user registrations from web pages
-- via JSON.
--
-- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur
-- aka Zash.
local jid_prep = require "util.jid".prep;
local jid_split = require "util.jid".split;
local usermanager = require "core.usermanager";
local b64_decode = require "util.encodings".base64.decode;
local json_decode = require "util.json".decode;
module.host = "*" -- HTTP/BOSH Servlets need to be global.
-- Pick up configuration.
local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted";
local throttle_time = module:get_option("reg_servlet_ttime") or false;
local whitelist = module:get_option("reg_servlet_wl") or {};
local blacklist = module:get_option("reg_servlet_bl") or {};
local recent_ips = {};
-- Begin
for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end
for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end
local function http_response(code, message, extra_headers)
local response = {
status = code .. " " .. message;
body = message .. "\n"; }
if extra_headers then response.headers = extra_headers; end
return response
end
local function handle_req(method, body, request)
if request.method ~= "POST" then
return http_response(405, "Bad method...", {["Allow"] = "POST"});
end
if not request.headers["authorization"] then
return http_response(401, "No... No...",
{["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'})
end
local user, password = b64_decode(request.headers.authorization
:match("[^ ]*$") or ""):match("([^:]*):(.*)");
user = jid_prep(user);
if not user or not password then return http_response(400, "What's this..?"); end
local user_node, user_host = jid_split(user)
if not hosts[user_host] then return http_response(401, "Negative."); end
module:log("warn", "%s is authing to submit a new user registration data", user)
if not usermanager.test_password(user_node, user_host, password) then
module:log("warn", "%s failed authentication", user)
return http_response(401, "Who the hell are you?! Guards!");
end
local req_body;
-- We check that what we have is valid JSON wise else we throw an error...
if not pcall(function() req_body = json_decode(body) end) then
module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user);
return http_response(400, "JSON Decoding failed.");
else
-- Check if user is an admin of said host
if not usermanager.is_admin(user, req_body["host"]) then
module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]);
return http_response(401, "I obey only to my masters... Have a nice day.");
else
-- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code)
if blacklist[req_body["ip"]] then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end
if throttle_time and not whitelist[req_body["ip"]] then
if not recent_ips[req_body["ip"]] then
recent_ips[req_body["ip"]] = { time = os_time(), count = 1 };
else
local ip = recent_ips[req_body["ip"]];
ip.count = ip.count + 1;
if os_time() - ip.time < throttle_time then
ip.time = os_time();
module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]);
return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again.");
end
ip.time = os_time();
end
end
-- We first check if the supplied username for registration is already there.
if not usermanager.user_exists(req_body["username"], req_body["host"]) then
usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]);
module:log("debug", "%s registration data submission for %s is successful", user, req_body["user"]);
return http_response(200, "Done.");
else
module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["user"]);
return http_response(409, "User already exists.");
end
end
end
end
-- Set it up!
local function setup()
local ports = module:get_option("reg_servlet_port") or { 9280 };
local base_name = module:get_option("reg_servlet_base") or "register_account";
local ssl_cert = module:get_option("reg_servlet_sslcert") or false;
local ssl_key = module:get_option("reg_servlet_sslkey") or false;
if not ssl_cert or not ssl_key then
require "net.httpserver".new_from_config(ports, handle_req, { base = base_name });
else
if module:get_option("reg_servlet_port") == nil then ports = { 9443 }; end
require "net.httpserver".new_from_config(ports, handle_req, { ssl = { key = ssl_key, certificate = ssl_cert }, base = base_name });
end
end
if prosody.start_time then -- already started
setup();
else
prosody.events.add_handler("server-started", setup);
end
|
-- Expose a simple servlet to handle user registrations from web pages
-- via JSON.
--
-- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur
-- aka Zash.
local jid_prep = require "util.jid".prep;
local jid_split = require "util.jid".split;
local usermanager = require "core.usermanager";
local b64_decode = require "util.encodings".base64.decode;
local json_decode = require "util.json".decode;
module.host = "*" -- HTTP/BOSH Servlets need to be global.
-- Pick up configuration.
local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted";
local throttle_time = module:get_option("reg_servlet_ttime") or false;
local whitelist = module:get_option("reg_servlet_wl") or {};
local blacklist = module:get_option("reg_servlet_bl") or {};
local recent_ips = {};
-- Begin
for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end
for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end
local function http_response(code, message, extra_headers)
local response = {
status = code .. " " .. message;
body = message .. "\n"; }
if extra_headers then response.headers = extra_headers; end
return response
end
local function handle_req(method, body, request)
if request.method ~= "POST" then
return http_response(405, "Bad method...", {["Allow"] = "POST"});
end
if not request.headers["authorization"] then
return http_response(401, "No... No...",
{["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'})
end
local user, password = b64_decode(request.headers.authorization
:match("[^ ]*$") or ""):match("([^:]*):(.*)");
user = jid_prep(user);
if not user or not password then return http_response(400, "What's this..?"); end
local user_node, user_host = jid_split(user)
if not hosts[user_host] then return http_response(401, "Negative."); end
module:log("warn", "%s is authing to submit a new user registration data", user)
if not usermanager.test_password(user_node, user_host, password) then
module:log("warn", "%s failed authentication", user)
return http_response(401, "Who the hell are you?! Guards!");
end
local req_body;
-- We check that what we have is valid JSON wise else we throw an error...
if not pcall(function() req_body = json_decode(body) end) then
module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user);
return http_response(400, "JSON Decoding failed.");
else
-- Decode JSON data and check that all bits are there else throw an error
req_body = json_decode(body);
if req_body["username"] == nil or req_body["password"] == nil or req_body["host"] == nil or req_body["ip"] == nil then
module:log("debug", "%s supplied an insufficent number of elements or wrong elements for the JSON registration", user);
return http_response(400, "Invalid syntax.");
end
-- Check if user is an admin of said host
if not usermanager.is_admin(user, req_body["host"]) then
module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]);
return http_response(401, "I obey only to my masters... Have a nice day.");
else
-- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code)
if blacklist[req_body["ip"]] then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end
if throttle_time and not whitelist[req_body["ip"]] then
if not recent_ips[req_body["ip"]] then
recent_ips[req_body["ip"]] = { time = os_time(), count = 1 };
else
local ip = recent_ips[req_body["ip"]];
ip.count = ip.count + 1;
if os_time() - ip.time < throttle_time then
ip.time = os_time();
module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]);
return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again.");
end
ip.time = os_time();
end
end
-- We first check if the supplied username for registration is already there.
if not usermanager.user_exists(req_body["username"], req_body["host"]) then
usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]);
module:log("debug", "%s registration data submission for %s is successful", user, req_body["user"]);
return http_response(200, "Done.");
else
module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["user"]);
return http_response(409, "User already exists.");
end
end
end
end
-- Set it up!
local function setup()
local ports = module:get_option("reg_servlet_port") or { 9280 };
local base_name = module:get_option("reg_servlet_base") or "register_account";
local ssl_cert = module:get_option("reg_servlet_sslcert") or false;
local ssl_key = module:get_option("reg_servlet_sslkey") or false;
if not ssl_cert or not ssl_key then
require "net.httpserver".new_from_config(ports, handle_req, { base = base_name });
else
if module:get_option("reg_servlet_port") == nil then ports = { 9443 }; end
require "net.httpserver".new_from_config(ports, handle_req, { ssl = { key = ssl_key, certificate = ssl_cert }, base = base_name });
end
end
if prosody.start_time then -- already started
setup();
else
prosody.events.add_handler("server-started", setup);
end
|
mod_register_json: Let's call it the first commit, fixed all code errors (aka it works).
|
mod_register_json: Let's call it the first commit, fixed all code errors (aka it works).
|
Lua
|
mit
|
crunchuser/prosody-modules,joewalker/prosody-modules,softer/prosody-modules,either1/prosody-modules,joewalker/prosody-modules,dhotson/prosody-modules,apung/prosody-modules,LanceJenkinZA/prosody-modules,dhotson/prosody-modules,Craige/prosody-modules,olax/prosody-modules,guilhem/prosody-modules,cryptotoad/prosody-modules,either1/prosody-modules,obelisk21/prosody-modules,vince06fr/prosody-modules,BurmistrovJ/prosody-modules,mardraze/prosody-modules,iamliqiang/prosody-modules,asdofindia/prosody-modules,cryptotoad/prosody-modules,jkprg/prosody-modules,cryptotoad/prosody-modules,BurmistrovJ/prosody-modules,drdownload/prosody-modules,olax/prosody-modules,stephen322/prosody-modules,1st8/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,softer/prosody-modules,jkprg/prosody-modules,obelisk21/prosody-modules,amenophis1er/prosody-modules,syntafin/prosody-modules,heysion/prosody-modules,NSAKEY/prosody-modules,jkprg/prosody-modules,mardraze/prosody-modules,amenophis1er/prosody-modules,syntafin/prosody-modules,amenophis1er/prosody-modules,asdofindia/prosody-modules,stephen322/prosody-modules,vince06fr/prosody-modules,vfedoroff/prosody-modules,vfedoroff/prosody-modules,LanceJenkinZA/prosody-modules,heysion/prosody-modules,mardraze/prosody-modules,mmusial/prosody-modules,crunchuser/prosody-modules,olax/prosody-modules,prosody-modules/import,joewalker/prosody-modules,stephen322/prosody-modules,jkprg/prosody-modules,NSAKEY/prosody-modules,mmusial/prosody-modules,brahmi2/prosody-modules,vfedoroff/prosody-modules,LanceJenkinZA/prosody-modules,amenophis1er/prosody-modules,obelisk21/prosody-modules,1st8/prosody-modules,drdownload/prosody-modules,mmusial/prosody-modules,BurmistrovJ/prosody-modules,olax/prosody-modules,1st8/prosody-modules,vfedoroff/prosody-modules,Craige/prosody-modules,syntafin/prosody-modules,dhotson/prosody-modules,softer/prosody-modules,NSAKEY/prosody-modules,asdofindia/prosody-modules,either1/prosody-modules,drdownload/prosody-modules,mmusial/prosody-modules,vince06fr/prosody-modules,dhotson/prosody-modules,prosody-modules/import,NSAKEY/prosody-modules,brahmi2/prosody-modules,vfedoroff/prosody-modules,olax/prosody-modules,guilhem/prosody-modules,NSAKEY/prosody-modules,vince06fr/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,LanceJenkinZA/prosody-modules,either1/prosody-modules,prosody-modules/import,cryptotoad/prosody-modules,BurmistrovJ/prosody-modules,drdownload/prosody-modules,asdofindia/prosody-modules,either1/prosody-modules,apung/prosody-modules,prosody-modules/import,heysion/prosody-modules,mmusial/prosody-modules,Craige/prosody-modules,joewalker/prosody-modules,brahmi2/prosody-modules,Craige/prosody-modules,jkprg/prosody-modules,stephen322/prosody-modules,joewalker/prosody-modules,drdownload/prosody-modules,iamliqiang/prosody-modules,LanceJenkinZA/prosody-modules,obelisk21/prosody-modules,apung/prosody-modules,iamliqiang/prosody-modules,heysion/prosody-modules,1st8/prosody-modules,syntafin/prosody-modules,crunchuser/prosody-modules,syntafin/prosody-modules,iamliqiang/prosody-modules,brahmi2/prosody-modules,softer/prosody-modules,guilhem/prosody-modules,crunchuser/prosody-modules,guilhem/prosody-modules,1st8/prosody-modules,prosody-modules/import,apung/prosody-modules,cryptotoad/prosody-modules,BurmistrovJ/prosody-modules,softer/prosody-modules,vince06fr/prosody-modules,mardraze/prosody-modules,amenophis1er/prosody-modules,crunchuser/prosody-modules,stephen322/prosody-modules,mardraze/prosody-modules,iamliqiang/prosody-modules,brahmi2/prosody-modules,asdofindia/prosody-modules,dhotson/prosody-modules,heysion/prosody-modules
|
729b0a07df9ca90deed2a154c38ff6c2cd2eec5c
|
mod_s2s_auth_dane/mod_s2s_auth_dane.lua
|
mod_s2s_auth_dane/mod_s2s_auth_dane.lua
|
-- mod_s2s_auth_dane
-- Copyright (C) 2013-2014 Kim Alvefur
--
-- This file is MIT/X11 licensed.
--
-- In your DNS, put
-- _xmpp-server.example.com. IN TLSA 3 0 1 <sha256 hash of certificate>
--
-- Known issues:
-- Race condition
-- Could be done much cleaner if mod_s2s was using util.async
--
-- TODO Things to test/handle:
-- Negative or bogus answers
-- No encryption offered
-- Different hostname before and after STARTTLS - mod_s2s should complain
-- Interaction with Dialback
module:set_global();
local type = type;
local t_insert = table.insert;
local set = require"util.set";
local dns_lookup = require"net.adns".lookup;
local hashes = require"util.hashes";
local base64 = require"util.encodings".base64;
local idna_to_ascii = require "util.encodings".idna.to_ascii;
local s2sout = module:depends"s2s".route_to_new_session.s2sout;
local pat = "%-%-%-%-%-BEGIN ([A-Z ]+)%-%-%-%-%-\r?\n"..
"([0-9A-Za-z=+/\r\n]*)\r?\n%-%-%-%-%-END %1%-%-%-%-%-";
local function pem2der(pem)
local typ, data = pem:match(pat);
if typ and data then
return base64.decode(data), typ;
end
end
local use_map = { ["DANE-EE"] = 3; ["DANE-TA"] = 2; ["PKIX-EE"] = 1; ["PKIX-CA"] = 0 }
local implemented_uses = set.new { "DANE-EE", "PKIX-EE" };
local configured_uses = module:get_option_set("dane_uses", { "DANE-EE" });
local enabled_uses = set.intersection(implemented_uses, configured_uses) / function(use) return use_map[use] end;
local function dane_lookup(host_session, cb, a,b,c,e)
if host_session.dane ~= nil then return end
if host_session.direction == "incoming" then
local name = idna_to_ascii(host_session.from_host);
if not name then return end
local handle = dns_lookup(function (answer)
if not answer.secure then
if cb then return cb(a,b,c,e); end
return;
end
if #answer == 1 and answer[1].srv.target == '.' then return end
local srv_hosts = { answer = answer };
local dane = {};
host_session.dane = dane;
host_session.srv_hosts = srv_hosts;
local n = #answer
for _, record in ipairs(answer) do
t_insert(srv_hosts, record.srv);
dns_lookup(function(dane_answer)
n = n - 1;
if dane_answer.bogus then
t_insert(dane, { bogus = dane_answer.bogus });
elseif dane_answer.secure then
for _, record in ipairs(dane_answer) do
t_insert(dane, record);
end
end
if n == 0 and cb then return cb(a,b,c,e); end
end, ("_%d._tcp.%s."):format(record.srv.port, record.srv.target), "TLSA");
end
end, "_xmpp-server._tcp."..name..".", "SRV");
return true;
elseif host_session.direction == "outgoing" then
local srv_choice = host_session.srv_hosts[host_session.srv_choice];
host_session.dane = dns_lookup(function(answer)
if answer and (answer.secure and #answer > 0) or answer.bogus then
srv_choice.dane = answer;
else
srv_choice.dane = false;
end
host_session.dane = srv_choice.dane;
if cb then return cb(a,b,c,e); end
end, ("_%d._tcp.%s."):format(srv_choice.port, srv_choice.target), "TLSA");
return true;
end
end
local _try_connect = s2sout.try_connect;
function s2sout.try_connect(host_session, connect_host, connect_port, err)
if not host_session.srv_hosts then
host_session.srv_hosts = { target = connect_host, port = connect_port };
host_session.srv_choice = 1;
end
if not err and dane_lookup(host_session, _try_connect, host_session, connect_host, connect_port, err) then
return true;
end
return _try_connect(host_session, connect_host, connect_port, err);
end
function module.add_host(module)
module:hook("s2s-stream-features", function(event)
-- dane_lookup(origin, origin.from_host);
dane_lookup(event.origin);
end, 1);
module:hook("s2s-authenticated", function(event)
local session = event.session;
if session.dane and not session.secure then
-- TLSA record but no TLS, not ok.
-- TODO Optional?
-- Bogus replies should trigger this path
-- How does this interact with Dialback?
session:close({
condition = "policy-violation",
text = "Encrypted server-to-server communication is required but was not "
..((session.direction == "outgoing" and "offered") or "used")
});
return false;
end
end);
end
module:hook("s2s-check-certificate", function(event)
local session, cert = event.session, event.cert;
local dane = session.dane;
if type(dane) == "table" then
local use, select, match, tlsa, certdata, match_found, supported_found;
for i = 1, #dane do
tlsa = dane[i].tlsa;
module:log("debug", "TLSA %s %s %s %d bytes of data", tlsa:getUsage(), tlsa:getSelector(), tlsa:getMatchType(), #tlsa.data);
use, select, match, certdata = tlsa.use, tlsa.select, tlsa.match;
if enabled_uses:contains(use) then
-- PKIX-EE or DANE-EE
if use == 1 or use == 3 then
supported_found = true
if select == 0 then
certdata = pem2der(cert:pem());
elseif select == 1 and cert.pubkey then
certdata = pem2der(cert:pubkey()); -- Not supported in stock LuaSec
else
module:log("warn", "DANE selector %s is unsupported", tlsa:getSelector() or select);
end
if match == 1 then
certdata = certdata and hashes.sha256(certdata);
elseif match == 2 then
certdata = certdata and hashes.sha512(certdata);
elseif match ~= 0 then
module:log("warn", "DANE match rule %s is unsupported", tlsa:getMatchType() or match);
certdata = nil;
end
-- Should we check if the cert subject matches?
if certdata and certdata == tlsa.data then
(session.log or module._log)("info", "DANE validation successful");
session.cert_identity_status = "valid";
if use == 3 then -- DANE-EE, chain status equals DNSSEC chain status
session.cert_chain_status = "valid";
-- for usage 1, PKIX-EE, the chain has to be valid already
end
match_found = true;
break;
end
end
end
end
if supported_found and not match_found or dane.bogus then
-- No TLSA matched or response was bogus
(session.log or module._log)("warn", "DANE validation failed");
session.cert_identity_status = "invalid";
session.cert_chain_status = "invalid";
end
end
end);
function module.unload()
-- Restore the original try_connect function
s2sout.try_connect = _try_connect;
end
|
-- mod_s2s_auth_dane
-- Copyright (C) 2013-2014 Kim Alvefur
--
-- This file is MIT/X11 licensed.
--
-- In your DNS, put
-- _xmpp-server.example.com. IN TLSA 3 0 1 <sha256 hash of certificate>
--
-- Known issues:
-- Race condition
-- Could be done much cleaner if mod_s2s was using util.async
--
-- TODO Things to test/handle:
-- Negative or bogus answers
-- No encryption offered
-- Different hostname before and after STARTTLS - mod_s2s should complain
-- Interaction with Dialback
module:set_global();
local type = type;
local t_insert = table.insert;
local set = require"util.set";
local dns_lookup = require"net.adns".lookup;
local hashes = require"util.hashes";
local base64 = require"util.encodings".base64;
local idna_to_ascii = require "util.encodings".idna.to_ascii;
local s2sout = module:depends"s2s".route_to_new_session.s2sout;
local pat = "%-%-%-%-%-BEGIN ([A-Z ]+)%-%-%-%-%-\r?\n"..
"([0-9A-Za-z=+/\r\n]*)\r?\n%-%-%-%-%-END %1%-%-%-%-%-";
local function pem2der(pem)
local typ, data = pem:match(pat);
if typ and data then
return base64.decode(data), typ;
end
end
local use_map = { ["DANE-EE"] = 3; ["DANE-TA"] = 2; ["PKIX-EE"] = 1; ["PKIX-CA"] = 0 }
local implemented_uses = set.new { "DANE-EE", "PKIX-EE" };
local configured_uses = module:get_option_set("dane_uses", { "DANE-EE" });
local enabled_uses = set.intersection(implemented_uses, configured_uses) / function(use) return use_map[use] end;
local function dane_lookup(host_session, cb, a,b,c,e)
if host_session.dane ~= nil then return end
if host_session.direction == "incoming" then
local name = idna_to_ascii(host_session.from_host);
if not name then return end
local handle = dns_lookup(function (answer)
if not answer.secure then
if cb then return cb(a,b,c,e); end
return;
end
if #answer == 1 and answer[1].srv.target == '.' then return end
local srv_hosts = { answer = answer };
local dane = {};
host_session.dane = dane;
host_session.srv_hosts = srv_hosts;
local n = #answer
for _, record in ipairs(answer) do
t_insert(srv_hosts, record.srv);
dns_lookup(function(dane_answer)
n = n - 1;
if dane_answer.bogus then
t_insert(dane, { bogus = dane_answer.bogus });
elseif dane_answer.secure then
for _, record in ipairs(dane_answer) do
t_insert(dane, record);
end
end
if n == 0 and cb then return cb(a,b,c,e); end
end, ("_%d._tcp.%s."):format(record.srv.port, record.srv.target), "TLSA");
end
end, "_xmpp-server._tcp."..name..".", "SRV");
return true;
elseif host_session.direction == "outgoing" then
local srv_hosts = host_session.srv_hosts;
if not (srv_choice and srv_choice.answer and srv_choice.answer.secure) then
local srv_choice = host_session.srv_hosts[host_session.srv_choice];
host_session.dane = dns_lookup(function(answer)
if answer and (answer.secure and #answer > 0) or answer.bogus then
srv_choice.dane = answer;
else
srv_choice.dane = false;
end
host_session.dane = srv_choice.dane;
if cb then return cb(a,b,c,e); end
end, ("_%d._tcp.%s."):format(srv_choice.port, srv_choice.target), "TLSA");
return true;
end
end
local _try_connect = s2sout.try_connect;
function s2sout.try_connect(host_session, connect_host, connect_port, err)
if not host_session.srv_hosts then
host_session.srv_hosts = { answer = { secure = true }, { target = connect_host, port = connect_port } };
host_session.srv_choice = 1;
end
if not err and dane_lookup(host_session, _try_connect, host_session, connect_host, connect_port, err) then
return true;
end
return _try_connect(host_session, connect_host, connect_port, err);
end
function module.add_host(module)
module:hook("s2s-stream-features", function(event)
-- dane_lookup(origin, origin.from_host);
dane_lookup(event.origin);
end, 1);
module:hook("s2s-authenticated", function(event)
local session = event.session;
if session.dane and not session.secure then
-- TLSA record but no TLS, not ok.
-- TODO Optional?
-- Bogus replies should trigger this path
-- How does this interact with Dialback?
session:close({
condition = "policy-violation",
text = "Encrypted server-to-server communication is required but was not "
..((session.direction == "outgoing" and "offered") or "used")
});
return false;
end
end);
end
module:hook("s2s-check-certificate", function(event)
local session, cert = event.session, event.cert;
local dane = session.dane;
if type(dane) == "table" then
local use, select, match, tlsa, certdata, match_found, supported_found;
for i = 1, #dane do
tlsa = dane[i].tlsa;
module:log("debug", "TLSA %s %s %s %d bytes of data", tlsa:getUsage(), tlsa:getSelector(), tlsa:getMatchType(), #tlsa.data);
use, select, match, certdata = tlsa.use, tlsa.select, tlsa.match;
if enabled_uses:contains(use) then
-- PKIX-EE or DANE-EE
if use == 1 or use == 3 then
supported_found = true
if select == 0 then
certdata = pem2der(cert:pem());
elseif select == 1 and cert.pubkey then
certdata = pem2der(cert:pubkey()); -- Not supported in stock LuaSec
else
module:log("warn", "DANE selector %s is unsupported", tlsa:getSelector() or select);
end
if match == 1 then
certdata = certdata and hashes.sha256(certdata);
elseif match == 2 then
certdata = certdata and hashes.sha512(certdata);
elseif match ~= 0 then
module:log("warn", "DANE match rule %s is unsupported", tlsa:getMatchType() or match);
certdata = nil;
end
-- Should we check if the cert subject matches?
if certdata and certdata == tlsa.data then
(session.log or module._log)("info", "DANE validation successful");
session.cert_identity_status = "valid";
if use == 3 then -- DANE-EE, chain status equals DNSSEC chain status
session.cert_chain_status = "valid";
-- for usage 1, PKIX-EE, the chain has to be valid already
end
match_found = true;
break;
end
end
end
end
if supported_found and not match_found or dane.bogus then
-- No TLSA matched or response was bogus
(session.log or module._log)("warn", "DANE validation failed");
session.cert_identity_status = "invalid";
session.cert_chain_status = "invalid";
end
end
end);
function module.unload()
-- Restore the original try_connect function
s2sout.try_connect = _try_connect;
end
|
mod_s2s_auth_dane: Fix for a17c2c4043e5
|
mod_s2s_auth_dane: Fix for a17c2c4043e5
|
Lua
|
mit
|
apung/prosody-modules,brahmi2/prosody-modules,iamliqiang/prosody-modules,syntafin/prosody-modules,brahmi2/prosody-modules,obelisk21/prosody-modules,apung/prosody-modules,BurmistrovJ/prosody-modules,either1/prosody-modules,heysion/prosody-modules,vince06fr/prosody-modules,olax/prosody-modules,stephen322/prosody-modules,mardraze/prosody-modules,LanceJenkinZA/prosody-modules,joewalker/prosody-modules,joewalker/prosody-modules,Craige/prosody-modules,syntafin/prosody-modules,vfedoroff/prosody-modules,stephen322/prosody-modules,heysion/prosody-modules,1st8/prosody-modules,guilhem/prosody-modules,either1/prosody-modules,softer/prosody-modules,stephen322/prosody-modules,amenophis1er/prosody-modules,prosody-modules/import,drdownload/prosody-modules,NSAKEY/prosody-modules,obelisk21/prosody-modules,brahmi2/prosody-modules,vince06fr/prosody-modules,heysion/prosody-modules,LanceJenkinZA/prosody-modules,NSAKEY/prosody-modules,either1/prosody-modules,asdofindia/prosody-modules,drdownload/prosody-modules,prosody-modules/import,mardraze/prosody-modules,obelisk21/prosody-modules,jkprg/prosody-modules,iamliqiang/prosody-modules,Craige/prosody-modules,softer/prosody-modules,1st8/prosody-modules,dhotson/prosody-modules,mardraze/prosody-modules,amenophis1er/prosody-modules,crunchuser/prosody-modules,guilhem/prosody-modules,syntafin/prosody-modules,drdownload/prosody-modules,jkprg/prosody-modules,LanceJenkinZA/prosody-modules,cryptotoad/prosody-modules,mmusial/prosody-modules,guilhem/prosody-modules,joewalker/prosody-modules,cryptotoad/prosody-modules,guilhem/prosody-modules,heysion/prosody-modules,apung/prosody-modules,heysion/prosody-modules,brahmi2/prosody-modules,cryptotoad/prosody-modules,dhotson/prosody-modules,1st8/prosody-modules,jkprg/prosody-modules,olax/prosody-modules,crunchuser/prosody-modules,amenophis1er/prosody-modules,mmusial/prosody-modules,vfedoroff/prosody-modules,crunchuser/prosody-modules,dhotson/prosody-modules,NSAKEY/prosody-modules,asdofindia/prosody-modules,cryptotoad/prosody-modules,guilhem/prosody-modules,olax/prosody-modules,iamliqiang/prosody-modules,mardraze/prosody-modules,crunchuser/prosody-modules,prosody-modules/import,Craige/prosody-modules,vfedoroff/prosody-modules,LanceJenkinZA/prosody-modules,BurmistrovJ/prosody-modules,mmusial/prosody-modules,Craige/prosody-modules,NSAKEY/prosody-modules,crunchuser/prosody-modules,syntafin/prosody-modules,Craige/prosody-modules,asdofindia/prosody-modules,1st8/prosody-modules,obelisk21/prosody-modules,mmusial/prosody-modules,BurmistrovJ/prosody-modules,either1/prosody-modules,softer/prosody-modules,apung/prosody-modules,olax/prosody-modules,prosody-modules/import,amenophis1er/prosody-modules,vfedoroff/prosody-modules,apung/prosody-modules,prosody-modules/import,joewalker/prosody-modules,stephen322/prosody-modules,obelisk21/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,amenophis1er/prosody-modules,drdownload/prosody-modules,asdofindia/prosody-modules,softer/prosody-modules,stephen322/prosody-modules,vince06fr/prosody-modules,vince06fr/prosody-modules,vfedoroff/prosody-modules,syntafin/prosody-modules,either1/prosody-modules,iamliqiang/prosody-modules,jkprg/prosody-modules,brahmi2/prosody-modules,NSAKEY/prosody-modules,cryptotoad/prosody-modules,mardraze/prosody-modules,asdofindia/prosody-modules,softer/prosody-modules,jkprg/prosody-modules,dhotson/prosody-modules,BurmistrovJ/prosody-modules,dhotson/prosody-modules,BurmistrovJ/prosody-modules,mmusial/prosody-modules,joewalker/prosody-modules,olax/prosody-modules,drdownload/prosody-modules,vince06fr/prosody-modules,LanceJenkinZA/prosody-modules
|
493c88782947a2856c20a40af1ad0d757705ea73
|
spec/unit/readerfooter_spec.lua
|
spec/unit/readerfooter_spec.lua
|
require("commonrequire")
local DocumentRegistry = require("document/documentregistry")
local ReaderUI = require("apps/reader/readerui")
local DEBUG = require("dbg")
describe("Readerfooter module", function()
it("should setup footer for epub without error", function()
local sample_epub = "spec/front/unit/data/juliet.epub"
local readerui = ReaderUI:new{
document = DocumentRegistry:openDocument(sample_epub),
}
readerui.view.footer.settings.page_progress = true
readerui.view.footer.settings.all_at_once = true
readerui.view.footer:updateFooterPage()
timeinfo = readerui.view.footer:getTimeInfo()
assert.are.same('B:0% | '..timeinfo..' | 1 / 1 | => 0 | R:100% | TB: 00:00 | TC: 00:00',
readerui.view.footer.progress_text.text)
end)
it("should setup footer for pdf without error", function()
local sample_pdf = "spec/front/unit/data/2col.pdf"
local readerui = ReaderUI:new{
document = DocumentRegistry:openDocument(sample_pdf),
}
readerui.view.footer.settings.page_progress = true
readerui.view.footer.settings.all_at_once = true
readerui.view.footer:updateFooterPage()
timeinfo = readerui.view.footer:getTimeInfo()
assert.are.same('B:0% | '..timeinfo..' | 1 / 2 | => 1 | R:50% | TB: na | TC: na',
readerui.view.footer.progress_text.text)
end)
end)
|
require("commonrequire")
local DocumentRegistry = require("document/documentregistry")
local ReaderUI = require("apps/reader/readerui")
local DEBUG = require("dbg")
describe("Readerfooter module", function()
it("should setup footer for epub without error", function()
local sample_epub = "spec/front/unit/data/juliet.epub"
local readerui = ReaderUI:new{
document = DocumentRegistry:openDocument(sample_epub),
}
readerui.view.footer.settings.page_progress = true
readerui.view.footer.settings.all_at_once = true
readerui.view.footer:updateFooterPage()
timeinfo = readerui.view.footer:getTimeInfo()
-- stats has not been initialized here, so we get na TB and TC
assert.are.same('B:0% | '..timeinfo..' | 1 / 1 | => 0 | R:100% | TB: na | TC: na',
readerui.view.footer.progress_text.text)
end)
it("should setup footer for pdf without error", function()
local sample_pdf = "spec/front/unit/data/2col.pdf"
local readerui = ReaderUI:new{
document = DocumentRegistry:openDocument(sample_pdf),
}
readerui.view.footer.settings.page_progress = true
readerui.view.footer.settings.all_at_once = true
readerui.view.footer:updateFooterPage()
timeinfo = readerui.view.footer:getTimeInfo()
assert.are.same('B:0% | '..timeinfo..' | 1 / 2 | => 1 | R:50% | TB: na | TC: na',
readerui.view.footer.progress_text.text)
end)
end)
|
fix travis testfront
|
fix travis testfront
|
Lua
|
agpl-3.0
|
Frenzie/koreader,mihailim/koreader,mwoz123/koreader,Frenzie/koreader,chihyang/koreader,Markismus/koreader,NickSavage/koreader,poire-z/koreader,lgeek/koreader,apletnev/koreader,koreader/koreader,frankyifei/koreader,Hzj-jie/koreader,robert00s/koreader,pazos/koreader,koreader/koreader,NiLuJe/koreader,NiLuJe/koreader,houqp/koreader,poire-z/koreader
|
740bb20850378d5f3c3abd4cbe35720174d2c5e5
|
libs/uci/luasrc/model/uci/bind.lua
|
libs/uci/luasrc/model/uci/bind.lua
|
--[[
LuCI - UCI utilities for model classes
Copyright 2009 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local assert, pairs, type = assert, pairs, type
local utl = require "luci.util"
module "luci.model.uci.bind"
bind = utl.class()
function bind.__init__(self, config, cursor)
assert(config, "call to bind() without config file")
self.cfg = config
self.uci = cursor
end
function bind.init(self, cursor)
assert(cursor, "call to init() without uci cursor")
self.uci = cursor
end
function bind.section(self, stype)
local x = utl.class(bsection)
x.__init__ = function(inst, sid)
assert(self.uci:get(self.cfg, sid) == stype,
"attempt to instantiate bsection(%q) of wrong type, expected %q"
% { sid, stype })
inst.bind = self
inst.stype = stype
inst.sid = sid
end
return x
end
function bind.usection(self, stype)
local x = utl.class(bsection)
x.__init__ = function(inst)
inst.bind = self
inst.stype = stype
inst.sid = true
end
return x()
end
function bind.list(self, list, add, rem)
local lookup = { }
if type(list) == "string" then
local item
for item in list:gmatch("%S+") do
lookup[item] = true
end
elseif type(list) == "table" then
local item
for _, item in pairs(list) do
lookup[item] = true
end
end
if add then lookup[add] = true end
if rem then lookup[rem] = nil end
return utl.keys(lookup)
end
function bind.bool(self, v)
return ( v == "1" or v == "true" or v == "yes" or v == "on" )
end
bsection = utl.class()
function bsection.uciop(self, op, ...)
assert(self.bind and self.bind.uci,
"attempt to use unitialized binding: " .. type(self.sid))
return op and self.bind.uci[op](self.bind.uci, self.bind.cfg, ...)
or self.bind.uci
end
function bsection.get(self, k, c)
local v
self:uciop("foreach", self.stype,
function(s)
if type(c) == "table" then
local ck, cv
for ck, cv in pairs(c) do
if s[ck] ~= cv then return true end
end
elseif type(c) == "string" and s['.name'] ~= c then
return true
end
if k ~= nil then
v = s[k]
else
v = s
end
return false
end)
return v
end
function bsection.set(self, k, v, c)
local stat
self:uciop("foreach", self.stype,
function(s)
if type(c) == "table" then
local ck, cv
for ck, cv in pairs(c) do
if s[ck] ~= cv then return true end
end
elseif type(c) == "string" and s['.name'] ~= c then
return true
end
stat = self:uciop("set", c, k, v)
return false
end)
return stat or false
end
function bsection.property(self, k, n)
self[n or k] = function(c, val)
if val == nil then
return c:get(k, c.sid)
else
return c:set(k, val, c.sid)
end
end
end
function bsection.property_bool(self, k, n)
self[n or k] = function(c, val)
if val == nil then
return self.bind:bool(c:get(k, c.sid))
else
return c:set(k, self.bind:bool(val) and "1" or "0", c.sid)
end
end
end
|
--[[
LuCI - UCI utilities for model classes
Copyright 2009 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local assert, pairs, type = assert, pairs, type
local utl = require "luci.util"
module "luci.model.uci.bind"
bind = utl.class()
function bind.__init__(self, config, cursor)
assert(config, "call to bind() without config file")
self.cfg = config
self.uci = cursor
end
function bind.init(self, cursor)
assert(cursor, "call to init() without uci cursor")
self.uci = cursor
end
function bind.section(self, stype)
local x = utl.class(bsection)
x.__init__ = function(inst, sid)
assert(self.uci:get(self.cfg, sid) == stype,
"attempt to instantiate bsection(%q) of wrong type, expected %q"
% { sid, stype })
inst.bind = self
inst.stype = stype
inst.sid = sid
end
return x
end
function bind.usection(self, stype)
local x = utl.class(bsection)
x.__init__ = function(inst)
inst.bind = self
inst.stype = stype
inst.sid = true
end
return x()
end
function bind.list(self, list, add, rem)
local lookup = { }
if type(list) == "string" then
local item
for item in list:gmatch("%S+") do
lookup[item] = true
end
elseif type(list) == "table" then
local item
for _, item in pairs(list) do
lookup[item] = true
end
end
if add then lookup[add] = true end
if rem then lookup[rem] = nil end
return utl.keys(lookup)
end
function bind.bool(self, v)
return ( v == "1" or v == "true" or v == "yes" or v == "on" )
end
bsection = utl.class()
function bsection.uciop(self, op, ...)
assert(self.bind and self.bind.uci,
"attempt to use unitialized binding")
if op then
return self.bind.uci[op](self.bind.uci, self.bind.cfg, ...)
else
return self.bind.uci
end
end
function bsection.get(self, k, c)
local v
if type(c) == "string" then
v = self:uciop("get", c, k)
else
self:uciop("foreach", self.stype,
function(s)
if type(c) == "table" then
local ck, cv
for ck, cv in pairs(c) do
if s[ck] ~= cv then return true end
end
end
if k ~= nil then
v = s[k]
else
v = s
end
return false
end)
end
return v
end
function bsection.set(self, k, v, c)
local stat
if type(c) == "string" then
stat = self:uciop("set", c, k, v)
else
self:uciop("foreach", self.stype,
function(s)
if type(c) == "table" then
local ck, cv
for ck, cv in pairs(c) do
if s[ck] ~= cv then return true end
end
end
stat = self:uciop("set", c, k, v)
return false
end)
end
return stat or false
end
function bsection.property(self, k, n)
self[n or k] = function(c, val)
if val == nil then
return c:get(k, c.sid)
else
return c:set(k, val, c.sid)
end
end
end
function bsection.property_bool(self, k, n)
self[n or k] = function(c, val)
if val == nil then
return self.bind:bool(c:get(k, c.sid))
else
return c:set(k, self.bind:bool(val) and "1" or "0", c.sid)
end
end
end
|
libs/uci: optimize get & set performance in luci.model.uci.bind, fix ambiguous case in uciop()
|
libs/uci: optimize get & set performance in luci.model.uci.bind, fix ambiguous case in uciop()
|
Lua
|
apache-2.0
|
thess/OpenWrt-luci,teslamint/luci,kuoruan/luci,teslamint/luci,bright-things/ionic-luci,jorgifumi/luci,LazyZhu/openwrt-luci-trunk-mod,opentechinstitute/luci,RedSnake64/openwrt-luci-packages,palmettos/test,wongsyrone/luci-1,Sakura-Winkey/LuCI,jchuang1977/luci-1,slayerrensky/luci,lcf258/openwrtcn,aa65535/luci,kuoruan/luci,jchuang1977/luci-1,rogerpueyo/luci,RuiChen1113/luci,lcf258/openwrtcn,zhaoxx063/luci,kuoruan/luci,palmettos/cnLuCI,marcel-sch/luci,palmettos/test,lbthomsen/openwrt-luci,dwmw2/luci,cshore/luci,artynet/luci,bright-things/ionic-luci,fkooman/luci,bright-things/ionic-luci,db260179/openwrt-bpi-r1-luci,joaofvieira/luci,shangjiyu/luci-with-extra,kuoruan/luci,harveyhu2012/luci,openwrt-es/openwrt-luci,lcf258/openwrtcn,jlopenwrtluci/luci,Hostle/openwrt-luci-multi-user,tcatm/luci,981213/luci-1,kuoruan/luci,jorgifumi/luci,cshore/luci,sujeet14108/luci,LuttyYang/luci,male-puppies/luci,male-puppies/luci,ff94315/luci-1,schidler/ionic-luci,nmav/luci,keyidadi/luci,slayerrensky/luci,dismantl/luci-0.12,obsy/luci,shangjiyu/luci-with-extra,RuiChen1113/luci,sujeet14108/luci,dwmw2/luci,hnyman/luci,forward619/luci,maxrio/luci981213,david-xiao/luci,jlopenwrtluci/luci,ollie27/openwrt_luci,palmettos/cnLuCI,cshore/luci,deepak78/new-luci,male-puppies/luci,palmettos/cnLuCI,nmav/luci,ff94315/luci-1,thess/OpenWrt-luci,ff94315/luci-1,joaofvieira/luci,maxrio/luci981213,openwrt-es/openwrt-luci,opentechinstitute/luci,fkooman/luci,ReclaimYourPrivacy/cloak-luci,MinFu/luci,david-xiao/luci,jchuang1977/luci-1,joaofvieira/luci,maxrio/luci981213,ReclaimYourPrivacy/cloak-luci,jchuang1977/luci-1,dwmw2/luci,openwrt-es/openwrt-luci,openwrt/luci,RedSnake64/openwrt-luci-packages,oyido/luci,schidler/ionic-luci,oneru/luci,thess/OpenWrt-luci,oneru/luci,Hostle/luci,taiha/luci,slayerrensky/luci,forward619/luci,jorgifumi/luci,sujeet14108/luci,urueedi/luci,oneru/luci,Hostle/luci,cshore-firmware/openwrt-luci,cshore/luci,florian-shellfire/luci,fkooman/luci,LazyZhu/openwrt-luci-trunk-mod,dismantl/luci-0.12,maxrio/luci981213,obsy/luci,ReclaimYourPrivacy/cloak-luci,david-xiao/luci,ReclaimYourPrivacy/cloak-luci,harveyhu2012/luci,ReclaimYourPrivacy/cloak-luci,Noltari/luci,Wedmer/luci,bright-things/ionic-luci,tcatm/luci,mumuqz/luci,obsy/luci,MinFu/luci,daofeng2015/luci,keyidadi/luci,openwrt/luci,981213/luci-1,kuoruan/luci,MinFu/luci,lcf258/openwrtcn,chris5560/openwrt-luci,cshore-firmware/openwrt-luci,hnyman/luci,fkooman/luci,ollie27/openwrt_luci,aa65535/luci,palmettos/test,joaofvieira/luci,nwf/openwrt-luci,teslamint/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,opentechinstitute/luci,schidler/ionic-luci,bright-things/ionic-luci,oneru/luci,RedSnake64/openwrt-luci-packages,ollie27/openwrt_luci,Wedmer/luci,db260179/openwrt-bpi-r1-luci,tobiaswaldvogel/luci,male-puppies/luci,florian-shellfire/luci,aircross/OpenWrt-Firefly-LuCI,lbthomsen/openwrt-luci,cshore-firmware/openwrt-luci,RuiChen1113/luci,kuoruan/lede-luci,jlopenwrtluci/luci,dismantl/luci-0.12,cappiewu/luci,schidler/ionic-luci,thesabbir/luci,deepak78/new-luci,Kyklas/luci-proto-hso,hnyman/luci,db260179/openwrt-bpi-r1-luci,oneru/luci,palmettos/cnLuCI,obsy/luci,keyidadi/luci,jlopenwrtluci/luci,harveyhu2012/luci,RedSnake64/openwrt-luci-packages,RuiChen1113/luci,schidler/ionic-luci,thesabbir/luci,RuiChen1113/luci,dwmw2/luci,florian-shellfire/luci,bright-things/ionic-luci,remakeelectric/luci,oyido/luci,opentechinstitute/luci,zhaoxx063/luci,db260179/openwrt-bpi-r1-luci,tcatm/luci,thess/OpenWrt-luci,cshore/luci,ReclaimYourPrivacy/cloak-luci,aircross/OpenWrt-Firefly-LuCI,shangjiyu/luci-with-extra,Noltari/luci,joaofvieira/luci,NeoRaider/luci,zhaoxx063/luci,LazyZhu/openwrt-luci-trunk-mod,Wedmer/luci,oyido/luci,jlopenwrtluci/luci,marcel-sch/luci,sujeet14108/luci,nwf/openwrt-luci,keyidadi/luci,Sakura-Winkey/LuCI,slayerrensky/luci,bittorf/luci,fkooman/luci,deepak78/new-luci,urueedi/luci,dwmw2/luci,cshore/luci,Hostle/luci,urueedi/luci,tcatm/luci,db260179/openwrt-bpi-r1-luci,daofeng2015/luci,ollie27/openwrt_luci,david-xiao/luci,rogerpueyo/luci,nwf/openwrt-luci,chris5560/openwrt-luci,deepak78/new-luci,RuiChen1113/luci,florian-shellfire/luci,palmettos/test,jchuang1977/luci-1,oyido/luci,fkooman/luci,nwf/openwrt-luci,maxrio/luci981213,Hostle/luci,florian-shellfire/luci,shangjiyu/luci-with-extra,aircross/OpenWrt-Firefly-LuCI,teslamint/luci,jlopenwrtluci/luci,lcf258/openwrtcn,aa65535/luci,jorgifumi/luci,palmettos/test,Sakura-Winkey/LuCI,openwrt-es/openwrt-luci,ollie27/openwrt_luci,LuttyYang/luci,opentechinstitute/luci,rogerpueyo/luci,urueedi/luci,LazyZhu/openwrt-luci-trunk-mod,deepak78/new-luci,MinFu/luci,deepak78/new-luci,wongsyrone/luci-1,daofeng2015/luci,artynet/luci,thesabbir/luci,lbthomsen/openwrt-luci,zhaoxx063/luci,male-puppies/luci,forward619/luci,dwmw2/luci,daofeng2015/luci,NeoRaider/luci,wongsyrone/luci-1,shangjiyu/luci-with-extra,david-xiao/luci,Sakura-Winkey/LuCI,rogerpueyo/luci,forward619/luci,artynet/luci,tobiaswaldvogel/luci,mumuqz/luci,jchuang1977/luci-1,cappiewu/luci,Kyklas/luci-proto-hso,Wedmer/luci,jlopenwrtluci/luci,lbthomsen/openwrt-luci,taiha/luci,male-puppies/luci,forward619/luci,nmav/luci,thess/OpenWrt-luci,LuttyYang/luci,LuttyYang/luci,oyido/luci,lbthomsen/openwrt-luci,male-puppies/luci,obsy/luci,MinFu/luci,nmav/luci,forward619/luci,981213/luci-1,daofeng2015/luci,bittorf/luci,marcel-sch/luci,Hostle/luci,cshore-firmware/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,ReclaimYourPrivacy/cloak-luci,thess/OpenWrt-luci,openwrt/luci,rogerpueyo/luci,oneru/luci,tcatm/luci,Noltari/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,jorgifumi/luci,urueedi/luci,remakeelectric/luci,openwrt-es/openwrt-luci,marcel-sch/luci,NeoRaider/luci,urueedi/luci,kuoruan/luci,lcf258/openwrtcn,maxrio/luci981213,palmettos/cnLuCI,lcf258/openwrtcn,Wedmer/luci,palmettos/cnLuCI,Sakura-Winkey/LuCI,slayerrensky/luci,Wedmer/luci,urueedi/luci,oneru/luci,openwrt/luci,taiha/luci,opentechinstitute/luci,mumuqz/luci,Wedmer/luci,jorgifumi/luci,david-xiao/luci,openwrt/luci,tcatm/luci,cappiewu/luci,aa65535/luci,thesabbir/luci,tobiaswaldvogel/luci,ReclaimYourPrivacy/cloak-luci,aircross/OpenWrt-Firefly-LuCI,taiha/luci,cshore-firmware/openwrt-luci,Kyklas/luci-proto-hso,jchuang1977/luci-1,Hostle/luci,daofeng2015/luci,sujeet14108/luci,aa65535/luci,kuoruan/lede-luci,ollie27/openwrt_luci,teslamint/luci,chris5560/openwrt-luci,thesabbir/luci,marcel-sch/luci,mumuqz/luci,Hostle/openwrt-luci-multi-user,zhaoxx063/luci,tobiaswaldvogel/luci,hnyman/luci,dismantl/luci-0.12,LazyZhu/openwrt-luci-trunk-mod,Wedmer/luci,remakeelectric/luci,keyidadi/luci,oyido/luci,hnyman/luci,wongsyrone/luci-1,chris5560/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,openwrt-es/openwrt-luci,shangjiyu/luci-with-extra,kuoruan/lede-luci,obsy/luci,palmettos/cnLuCI,dwmw2/luci,bittorf/luci,forward619/luci,oyido/luci,male-puppies/luci,harveyhu2012/luci,obsy/luci,kuoruan/lede-luci,schidler/ionic-luci,db260179/openwrt-bpi-r1-luci,cappiewu/luci,artynet/luci,slayerrensky/luci,nmav/luci,thesabbir/luci,aircross/OpenWrt-Firefly-LuCI,Sakura-Winkey/LuCI,LazyZhu/openwrt-luci-trunk-mod,forward619/luci,aa65535/luci,oyido/luci,cshore/luci,db260179/openwrt-bpi-r1-luci,chris5560/openwrt-luci,ff94315/luci-1,MinFu/luci,rogerpueyo/luci,RedSnake64/openwrt-luci-packages,harveyhu2012/luci,david-xiao/luci,keyidadi/luci,marcel-sch/luci,tcatm/luci,lbthomsen/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,deepak78/new-luci,Hostle/luci,remakeelectric/luci,zhaoxx063/luci,tobiaswaldvogel/luci,nwf/openwrt-luci,openwrt/luci,kuoruan/lede-luci,ff94315/luci-1,obsy/luci,cappiewu/luci,aa65535/luci,bright-things/ionic-luci,sujeet14108/luci,bright-things/ionic-luci,chris5560/openwrt-luci,NeoRaider/luci,lbthomsen/openwrt-luci,Noltari/luci,nwf/openwrt-luci,zhaoxx063/luci,lcf258/openwrtcn,palmettos/test,Kyklas/luci-proto-hso,mumuqz/luci,palmettos/test,schidler/ionic-luci,lcf258/openwrtcn,Kyklas/luci-proto-hso,ff94315/luci-1,ff94315/luci-1,Noltari/luci,tcatm/luci,MinFu/luci,tobiaswaldvogel/luci,981213/luci-1,LuttyYang/luci,zhaoxx063/luci,palmettos/cnLuCI,cappiewu/luci,lcf258/openwrtcn,shangjiyu/luci-with-extra,dismantl/luci-0.12,remakeelectric/luci,nwf/openwrt-luci,nwf/openwrt-luci,RuiChen1113/luci,cshore/luci,teslamint/luci,palmettos/test,Hostle/openwrt-luci-multi-user,jlopenwrtluci/luci,artynet/luci,981213/luci-1,Sakura-Winkey/LuCI,hnyman/luci,mumuqz/luci,cappiewu/luci,bittorf/luci,taiha/luci,joaofvieira/luci,jorgifumi/luci,artynet/luci,wongsyrone/luci-1,bittorf/luci,rogerpueyo/luci,hnyman/luci,florian-shellfire/luci,cshore-firmware/openwrt-luci,harveyhu2012/luci,RedSnake64/openwrt-luci-packages,chris5560/openwrt-luci,bittorf/luci,RuiChen1113/luci,nmav/luci,cshore-firmware/openwrt-luci,981213/luci-1,fkooman/luci,cshore-firmware/openwrt-luci,cappiewu/luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,thess/OpenWrt-luci,slayerrensky/luci,LuttyYang/luci,openwrt-es/openwrt-luci,thesabbir/luci,artynet/luci,marcel-sch/luci,Hostle/openwrt-luci-multi-user,schidler/ionic-luci,tobiaswaldvogel/luci,RedSnake64/openwrt-luci-packages,LuttyYang/luci,david-xiao/luci,shangjiyu/luci-with-extra,LazyZhu/openwrt-luci-trunk-mod,Kyklas/luci-proto-hso,joaofvieira/luci,harveyhu2012/luci,Hostle/openwrt-luci-multi-user,aa65535/luci,Noltari/luci,artynet/luci,nmav/luci,fkooman/luci,wongsyrone/luci-1,ff94315/luci-1,urueedi/luci,bittorf/luci,slayerrensky/luci,kuoruan/lede-luci,NeoRaider/luci,taiha/luci,Noltari/luci,keyidadi/luci,kuoruan/luci,mumuqz/luci,wongsyrone/luci-1,openwrt/luci,bittorf/luci,rogerpueyo/luci,NeoRaider/luci,teslamint/luci,dwmw2/luci,hnyman/luci,daofeng2015/luci,Hostle/openwrt-luci-multi-user,dismantl/luci-0.12,florian-shellfire/luci,remakeelectric/luci,sujeet14108/luci,Kyklas/luci-proto-hso,oneru/luci,sujeet14108/luci,Noltari/luci,kuoruan/lede-luci,deepak78/new-luci,jorgifumi/luci,ollie27/openwrt_luci,NeoRaider/luci,keyidadi/luci,openwrt/luci,artynet/luci,teslamint/luci,maxrio/luci981213,wongsyrone/luci-1,taiha/luci,opentechinstitute/luci,nmav/luci,remakeelectric/luci,daofeng2015/luci,Noltari/luci,mumuqz/luci,chris5560/openwrt-luci,dismantl/luci-0.12,nmav/luci,Hostle/openwrt-luci-multi-user,opentechinstitute/luci,florian-shellfire/luci,marcel-sch/luci,taiha/luci,Hostle/luci,joaofvieira/luci,thesabbir/luci,981213/luci-1,ollie27/openwrt_luci,NeoRaider/luci,maxrio/luci981213,Hostle/openwrt-luci-multi-user,remakeelectric/luci,MinFu/luci,LuttyYang/luci,jchuang1977/luci-1,thess/OpenWrt-luci
|
f5010994b9b921d799504a46a0f8d1817d656f5c
|
kong/plugins/hmac-auth/access.lua
|
kong/plugins/hmac-auth/access.lua
|
local cache = require "kong.tools.database_cache"
local stringy = require "stringy"
local responses = require "kong.tools.responses"
local constants = require "kong.constants"
local math_abs = math.abs
local ngx_time = ngx.time
local ngx_gmatch = ngx.re.gmatch
local ngx_decode_base64 = ngx.decode_base64
local ngx_parse_time = ngx.parse_http_time
local ngx_sha1 = ngx.hmac_sha1
local ngx_set_header = ngx.req.set_header
local ngx_set_headers = ngx.req.get_headers
local ngx_log = ngx.log
local split = stringy.split
local AUTHORIZATION = "authorization"
local PROXY_AUTHORIZATION = "proxy-authorization"
local DATE = "date"
local X_DATE = "x-date"
local SIGNATURE_NOT_VALID = "HMAC signature cannot be verified"
local _M = {}
local function retrieve_hmac_fields(request, headers, header_name, conf)
local hmac_params = {}
local authorization_header = headers[header_name]
-- parse the header to retrieve hamc parameters
if authorization_header then
local iterator, iter_err = ngx_gmatch(authorization_header, "\\s*[Hh]mac\\s*username=\"(.+)\",\\s*algorithm=\"(.+)\",\\s*headers=\"(.+)\",\\s*signature=\"(.+)\"")
if not iterator then
ngx_log(ngx.ERR, iter_err)
return
end
local m, err = iterator()
if err then
ngx_log(ngx.ERR, err)
return
end
if m and #m >= 4 then
hmac_params.username = m[1]
hmac_params.algorithm = m[2]
hmac_params.hmac_headers = split(m[3], " ")
hmac_params.signature = m[4]
end
end
if conf.hide_credentials then
request.clear_header(header_name)
end
return hmac_params
end
local function create_hash(request, hmac_params, headers)
local signing_string = ""
local hmac_headers = hmac_params.hmac_headers
local count = #hmac_headers
for i = 1, count do
local header = hmac_headers[i]
local header_value = headers[header]
if not header_value then
if header == "request-line" then
-- request-line in hmac headers list
signing_string = signing_string..split(request.raw_header(), "\r\n")[1]
else
signing_string = signing_string..header..":"
end
else
signing_string = signing_string..header..":".." "..header_value
end
if i < count then
signing_string = signing_string.."\n"
end
end
return ngx_sha1(hmac_params.secret, signing_string)
end
local function validate_signature(request, hmac_params, headers)
local digest = create_hash(request, hmac_params, headers)
if digest then
return digest == ngx_decode_base64(hmac_params.signature)
end
end
local function hmacauth_credential_key(username)
return "hmacauth_credentials/"..username
end
local function load_credential(username)
local credential
if username then
credential = cache.get_or_set(hmacauth_credential_key(username), function()
local keys, err = dao.hmacauth_credentials:find_by_keys { username = username }
local result
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
elseif #keys > 0 then
result = keys[1]
end
return result
end)
end
return credential
end
local function validate_clock_skew(headers, date_header_name, allowed_clock_skew)
local date = headers[date_header_name]
if not date then
return false
end
local requestTime = ngx_parse_time(date)
if not requestTime then
return false
end
local skew = math_abs(ngx_time() - requestTime)
if skew > allowed_clock_skew then
return false
end
return true
end
function _M.execute(conf)
local headers = ngx_set_headers();
-- If both headers are missing, return 401
if not (headers[AUTHORIZATION] or headers[PROXY_AUTHORIZATION]) then
ngx.ctx.stop_phases = true
return responses.send_HTTP_UNAUTHORIZED()
end
-- validate clock skew
if not (validate_clock_skew(headers, X_DATE, conf.clock_skew) or validate_clock_skew(headers, DATE, conf.clock_skew)) then
responses.send_HTTP_FORBIDDEN("HMAC signature cannot be verified, a valid date or x-date header is required for HMAC Authentication")
end
-- retrieve hmac parameter from Proxy-Authorization header
local hmac_params = retrieve_hmac_fields(ngx.req, headers, PROXY_AUTHORIZATION, conf)
-- Try with the authorization header
if not hmac_params.username then
hmac_params = retrieve_hmac_fields(ngx.req, headers, AUTHORIZATION, conf)
end
if not (hmac_params.username and hmac_params.signature) then
responses.send_HTTP_FORBIDDEN(SIGNATURE_NOT_VALID)
end
-- validate signature
local credential = load_credential(hmac_params.username)
if not credential then
responses.send_HTTP_FORBIDDEN(SIGNATURE_NOT_VALID)
end
hmac_params.secret = credential.secret
if not validate_signature(ngx.req, hmac_params, headers) then
ngx.ctx.stop_phases = true -- interrupt other phases of this request
return responses.send_HTTP_FORBIDDEN("HMAC signature does not match")
end
-- Retrieve consumer
local consumer = cache.get_or_set(cache.consumer_key(credential.consumer_id), function()
local result, err = dao.consumers:find_by_primary_key({ id = credential.consumer_id })
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
return result
end)
ngx_set_header(constants.HEADERS.CONSUMER_ID, consumer.id)
ngx_set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id)
ngx_set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username)
ngx.req.set_header(constants.HEADERS.CREDENTIAL_USERNAME, credential.username)
ngx.ctx.authenticated_credential = credential
end
return _M
|
local cache = require "kong.tools.database_cache"
local stringy = require "stringy"
local responses = require "kong.tools.responses"
local constants = require "kong.constants"
local math_abs = math.abs
local ngx_time = ngx.time
local ngx_gmatch = ngx.re.gmatch
local ngx_decode_base64 = ngx.decode_base64
local ngx_parse_time = ngx.parse_http_time
local ngx_sha1 = ngx.hmac_sha1
local ngx_set_header = ngx.req.set_header
local ngx_set_headers = ngx.req.get_headers
local ngx_log = ngx.log
local split = stringy.split
local AUTHORIZATION = "authorization"
local PROXY_AUTHORIZATION = "proxy-authorization"
local DATE = "date"
local X_DATE = "x-date"
local SIGNATURE_NOT_VALID = "HMAC signature cannot be verified"
local _M = {}
local function retrieve_hmac_fields(request, headers, header_name, conf)
local hmac_params = {}
local authorization_header = headers[header_name]
-- parse the header to retrieve hamc parameters
if authorization_header then
local iterator, iter_err = ngx_gmatch(authorization_header, "\\s*[Hh]mac\\s*username=\"(.+)\",\\s*algorithm=\"(.+)\",\\s*headers=\"(.+)\",\\s*signature=\"(.+)\"")
if not iterator then
ngx_log(ngx.ERR, iter_err)
return
end
local m, err = iterator()
if err then
ngx_log(ngx.ERR, err)
return
end
if m and #m >= 4 then
hmac_params.username = m[1]
hmac_params.algorithm = m[2]
hmac_params.hmac_headers = split(m[3], " ")
hmac_params.signature = m[4]
end
end
if conf.hide_credentials then
request.clear_header(header_name)
end
return hmac_params
end
local function create_hash(request, hmac_params, headers)
local signing_string = ""
local hmac_headers = hmac_params.hmac_headers
local count = #hmac_headers
for i = 1, count do
local header = hmac_headers[i]
local header_value = headers[header]
if not header_value then
if header == "request-line" then
-- request-line in hmac headers list
signing_string = signing_string..split(request.raw_header(), "\r\n")[1]
else
signing_string = signing_string..header..":"
end
else
signing_string = signing_string..header..":".." "..header_value
end
if i < count then
signing_string = signing_string.."\n"
end
end
return ngx_sha1(hmac_params.secret, signing_string)
end
local function is_digest_equal(digest_1, digest_2)
if #digest_1 ~= #digest_1 then
return false
end
local result = true
for i=1, #digest_1 do
if digest_1:sub(i, i) ~= digest_2:sub(i, i) then
result = false
end
end
return result
end
local function validate_signature(request, hmac_params, headers)
local digest = create_hash(request, hmac_params, headers)
if digest then
return is_digest_equal(digest, ngx_decode_base64(hmac_params.signature))
end
end
local function hmacauth_credential_key(username)
return "hmacauth_credentials/"..username
end
local function load_credential(username)
local credential
if username then
credential = cache.get_or_set(hmacauth_credential_key(username), function()
local keys, err = dao.hmacauth_credentials:find_by_keys { username = username }
local result
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
elseif #keys > 0 then
result = keys[1]
end
return result
end)
end
return credential
end
local function validate_clock_skew(headers, date_header_name, allowed_clock_skew)
local date = headers[date_header_name]
if not date then
return false
end
local requestTime = ngx_parse_time(date)
if not requestTime then
return false
end
local skew = math_abs(ngx_time() - requestTime)
if skew > allowed_clock_skew then
return false
end
return true
end
function _M.execute(conf)
local headers = ngx_set_headers();
-- If both headers are missing, return 401
if not (headers[AUTHORIZATION] or headers[PROXY_AUTHORIZATION]) then
ngx.ctx.stop_phases = true
return responses.send_HTTP_UNAUTHORIZED()
end
-- validate clock skew
if not (validate_clock_skew(headers, X_DATE, conf.clock_skew) or validate_clock_skew(headers, DATE, conf.clock_skew)) then
responses.send_HTTP_FORBIDDEN("HMAC signature cannot be verified, a valid date or x-date header is required for HMAC Authentication")
end
-- retrieve hmac parameter from Proxy-Authorization header
local hmac_params = retrieve_hmac_fields(ngx.req, headers, PROXY_AUTHORIZATION, conf)
-- Try with the authorization header
if not hmac_params.username then
hmac_params = retrieve_hmac_fields(ngx.req, headers, AUTHORIZATION, conf)
end
if not (hmac_params.username and hmac_params.signature) then
responses.send_HTTP_FORBIDDEN(SIGNATURE_NOT_VALID)
end
-- validate signature
local credential = load_credential(hmac_params.username)
if not credential then
responses.send_HTTP_FORBIDDEN(SIGNATURE_NOT_VALID)
end
hmac_params.secret = credential.secret
if not validate_signature(ngx.req, hmac_params, headers) then
ngx.ctx.stop_phases = true -- interrupt other phases of this request
return responses.send_HTTP_FORBIDDEN("HMAC signature does not match")
end
-- Retrieve consumer
local consumer = cache.get_or_set(cache.consumer_key(credential.consumer_id), function()
local result, err = dao.consumers:find_by_primary_key({ id = credential.consumer_id })
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
return result
end)
ngx_set_header(constants.HEADERS.CONSUMER_ID, consumer.id)
ngx_set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id)
ngx_set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username)
ngx.req.set_header(constants.HEADERS.CREDENTIAL_USERNAME, credential.username)
ngx.ctx.authenticated_credential = credential
end
return _M
|
hotfix(hmac-auth) constant time digest comparison
|
hotfix(hmac-auth) constant time digest comparison
fix #655
|
Lua
|
apache-2.0
|
shiprabehera/kong,Kong/kong,Vermeille/kong,Mashape/kong,li-wl/kong,jebenexer/kong,salazar/kong,xvaara/kong,ajayk/kong,ccyphers/kong,jerizm/kong,beauli/kong,Kong/kong,smanolache/kong,Kong/kong,icyxp/kong,akh00/kong
|
ff9c15d1452026c9e8933ebc18af07aba9668e33
|
lua/Transition.lua
|
lua/Transition.lua
|
--! Perform soft transitions of properties in one state to another.
--!
--! Copyright 2012-13 Bifrost Entertainment. All rights reserved.
--! \author Tommy Nguyen
local __count = 0
local __transitions = {}
local function clear()
for i = 1, __count do
__transitions[i] = nil
end
__count = 0
end
local function register(t)
__count = __count + 1
__transitions[__count] = t
end
local function unregister(t)
for i = 1, __count do
if __transitions[i] == t then
__transitions[i] = __transitions[__count]
__count = __count - 1
break
end
end
end
local Transition = {
Functions = require("TransitionFunctions"),
clear = clear,
fadein = nil,
fadeout = nil,
fadeto = nil,
move = nil,
rotate = nil,
scaleto = nil
}
setmetatable(Transition, {
__update = function(dt)
for i = __count, 1, -1 do
__transitions[i]:tick(dt)
end
end
})
local function ticker(iterate, finalize, duration)
local elapsed = 0
return function(self, dt)
elapsed = elapsed + dt
local progress = elapsed / duration
if progress >= 1.0 then
finalize(self)
unregister(self)
else
iterate(self, progress)
end
end
end
local LinearFunction = Transition.Functions.linear
do -- fadein, fadeout
local audio = rainbow.audio
local play = audio.play
local set_gain = audio.set_gain
local stop = audio.stop
local function create(source, iterate, finalize, duration)
local self = {
cancel = unregister,
source = source,
tick = ticker(iterate, finalize, duration),
transition = LinearFunction
}
register(self)
return self
end
local function in_finalize(self)
set_gain(self.source, 1.0)
end
local function in_iterate(self, progress)
set_gain(self.source, progress)
end
local function out_finalize(self)
stop(self.source)
end
local function out_iterate(self, progress)
set_gain(self.source, 1.0 - progress)
end
function Transition.fadein(source, duration)
play(source)
return create(source, in_iterate, in_finalize, duration)
end
function Transition.fadeout(source, duration)
return create(source, out_iterate, out_finalize, duration)
end
end
do -- move
local function finalize(self)
self.move(self.node, self.x1 - self.x, self.y1 - self.y)
end
local function iterate(self, progress)
local x = self.transition(self.x0, self.x1, progress)
local y = self.transition(self.y0, self.y1, progress)
self.move(self.node, x - self.x, y - self.y)
self.x, self.y = x, y
end
local function move_drawable(drawable, x, y)
drawable:move(x, y)
end
local function move_node(node, x, y)
rainbow.scenegraph:move(node, x, y)
end
function Transition.move(node, x, y, duration, method)
local self = {
cancel = unregister,
move = move_drawable,
node = node,
tick = ticker(iterate, finalize, duration),
transition = method or LinearFunction,
x = 0,
y = 0,
x0 = 0,
y0 = 0,
x1 = x,
y1 = y
}
if type(node) == "table" then
assert(node.get_position, "Object must implement :get_position()")
assert(node.move, "Object must implement :move()")
self.x0, self.y0 = node:get_position()
self.x, self.y = self.x0, self.y0
elseif type(node) == "userdata" then
self.move = move_node
else
error("Invalid object")
end
register(self)
return self
end
end
do -- rotate
local function finalize(self)
self.sprite:set_rotation(self.r1)
end
local function iterate(self, progress)
self.sprite:set_rotation(self.transition(self.r0, self.r1, progress))
end
function Transition.rotate(sprite, r, duration, method)
local self = {
cancel = unregister,
r0 = sprite:get_angle(),
r1 = r,
sprite = sprite,
tick = ticker(iterate, finalize, duration),
transition = method or LinearFunction
}
register(self)
return self
end
end
do -- scaleto
local function finalize(self)
self.sprite:set_scale(self.final)
end
local function iterate(self, progress)
self.sprite:set_scale(self.transition(self.start, self.final, progress))
end
function Transition.scaleto(sprite, start, final, duration, method)
local self = {
cancel = unregister,
final = final,
sprite = sprite,
start = start,
tick = ticker(iterate, finalize, duration),
transition = method or LinearFunction
}
register(self)
return self
end
end
do -- fadeto
local function finalize(self)
self.sprite:set_color(self.r, self.g, self.b, self.a1)
end
local function iterate(self, progress)
self.sprite:set_color(self.r, self.g, self.b, self.transition(self.a, self.a1, progress))
end
function Transition.fadeto(sprite, alpha, duration, method)
local self = {
cancel = unregister,
r = 255, g = 255, b = 255, a = 255,
a1 = alpha,
sprite = sprite,
tick = ticker(iterate, finalize, duration),
transition = method or LinearFunction
}
self.r, self.g, self.b, self.a = sprite:get_color()
register(self)
return self
end
end
return rainbow.module.register(Transition)
|
--! Perform soft transitions of properties in one state to another.
--!
--! Copyright 2012-13 Bifrost Entertainment. All rights reserved.
--! \author Tommy Nguyen
local module_path = (...):match("(.*[./\\])[^./\\]+") or ""
local __count = 0
local __transitions = {}
local function clear()
for i = 1, __count do
__transitions[i] = nil
end
__count = 0
end
local function register(t)
__count = __count + 1
__transitions[__count] = t
end
local function unregister(t)
for i = 1, __count do
if __transitions[i] == t then
__transitions[i] = __transitions[__count]
__count = __count - 1
break
end
end
end
local Transition = {
Functions = require(module_path .. "TransitionFunctions"),
clear = clear,
fadein = nil,
fadeout = nil,
fadeto = nil,
move = nil,
rotate = nil,
scaleto = nil
}
setmetatable(Transition, {
__update = function(dt)
for i = __count, 1, -1 do
__transitions[i]:tick(dt)
end
end
})
local function ticker(iterate, finalize, duration)
local elapsed = 0
return function(self, dt)
elapsed = elapsed + dt
local progress = elapsed / duration
if progress >= 1.0 then
finalize(self)
unregister(self)
else
iterate(self, progress)
end
end
end
local LinearFunction = Transition.Functions.linear
do -- fadein, fadeout
local audio = rainbow.audio
local play = audio.play
local set_gain = audio.set_gain
local stop = audio.stop
local function create(source, iterate, finalize, duration)
local self = {
cancel = unregister,
source = source,
tick = ticker(iterate, finalize, duration),
transition = LinearFunction
}
register(self)
return self
end
local function in_finalize(self)
set_gain(self.source, 1.0)
end
local function in_iterate(self, progress)
set_gain(self.source, progress)
end
local function out_finalize(self)
stop(self.source)
end
local function out_iterate(self, progress)
set_gain(self.source, 1.0 - progress)
end
function Transition.fadein(source, duration)
play(source)
return create(source, in_iterate, in_finalize, duration)
end
function Transition.fadeout(source, duration)
return create(source, out_iterate, out_finalize, duration)
end
end
do -- move
local function finalize(self)
self.move(self.node, self.x1 - self.x, self.y1 - self.y)
end
local function iterate(self, progress)
local x = self.transition(self.x0, self.x1, progress)
local y = self.transition(self.y0, self.y1, progress)
self.move(self.node, x - self.x, y - self.y)
self.x, self.y = x, y
end
local function move_drawable(drawable, x, y)
drawable:move(x, y)
end
local function move_node(node, x, y)
rainbow.scenegraph:move(node, x, y)
end
function Transition.move(node, x, y, duration, method)
local self = {
cancel = unregister,
move = move_drawable,
node = node,
tick = ticker(iterate, finalize, duration),
transition = method or LinearFunction,
x = 0,
y = 0,
x0 = 0,
y0 = 0,
x1 = x,
y1 = y
}
if type(node) == "table" then
assert(node.get_position, "Object must implement :get_position()")
assert(node.move, "Object must implement :move()")
self.x0, self.y0 = node:get_position()
self.x, self.y = self.x0, self.y0
elseif type(node) == "userdata" then
self.move = move_node
else
error("Invalid object")
end
register(self)
return self
end
end
do -- rotate
local function finalize(self)
self.sprite:set_rotation(self.r1)
end
local function iterate(self, progress)
self.sprite:set_rotation(self.transition(self.r0, self.r1, progress))
end
function Transition.rotate(sprite, r, duration, method)
local self = {
cancel = unregister,
r0 = sprite:get_angle(),
r1 = r,
sprite = sprite,
tick = ticker(iterate, finalize, duration),
transition = method or LinearFunction
}
register(self)
return self
end
end
do -- scaleto
local function finalize(self)
self.sprite:set_scale(self.final)
end
local function iterate(self, progress)
self.sprite:set_scale(self.transition(self.start, self.final, progress))
end
function Transition.scaleto(sprite, start, final, duration, method)
local self = {
cancel = unregister,
final = final,
sprite = sprite,
start = start,
tick = ticker(iterate, finalize, duration),
transition = method or LinearFunction
}
register(self)
return self
end
end
do -- fadeto
local function finalize(self)
self.sprite:set_color(self.r, self.g, self.b, self.a1)
end
local function iterate(self, progress)
self.sprite:set_color(self.r, self.g, self.b, self.transition(self.a, self.a1, progress))
end
function Transition.fadeto(sprite, alpha, duration, method)
local self = {
cancel = unregister,
r = 255, g = 255, b = 255, a = 255,
a1 = alpha,
sprite = sprite,
tick = ticker(iterate, finalize, duration),
transition = method or LinearFunction
}
self.r, self.g, self.b, self.a = sprite:get_color()
register(self)
return self
end
end
return rainbow.module.register(Transition)
|
Fixed Transition failing to require files when in folder.
|
Fixed Transition failing to require files when in folder.
|
Lua
|
mit
|
tn0502/rainbow,pandaforks/tido-rainbow,tn0502/rainbow,pandaforks/tido-rainbow,tn0502/rainbow,pandaforks/tido-rainbow,pandaforks/tido-rainbow,tn0502/rainbow,tn0502/rainbow,pandaforks/tido-rainbow,tn0502/rainbow
|
14b90d0a8821a18bd672e93e8367f1838bba6b74
|
src/CppParser/Bindings/premake4.lua
|
src/CppParser/Bindings/premake4.lua
|
project "CppSharp.Parser.Gen"
kind "ConsoleApp"
language "C#"
location "."
debugdir "."
files { "ParserGen.cs", "*.lua" }
links { "CppSharp.AST", "CppSharp.Generator" }
configuration { "vs*" }
links { "CppSharp.Parser" }
configuration { "not vs*" }
links { "CppSharp.Parser.CSharp" }
project "CppSharp.Parser.CSharp"
kind "SharedLib"
language "C#"
location "."
dependson { "CppSharp.CppParser" }
flags { common_flags, "Unsafe" }
files
{
"CSharp/**.cs",
"**.lua"
}
links { "CppSharp.Runtime" }
configuration "vs*"
project "CppSharp.Parser.CLI"
kind "SharedLib"
language "C++"
SetupNativeProject()
dependson { "CppSharp.CppParser" }
flags { common_flags, "Managed" }
configuration "vs*"
buildoptions { clang_msvc_flags }
configuration "*"
files
{
"CLI/AST.h",
"CLI/AST.cpp",
"CLI/**.h",
"CLI/**.cpp",
"**.lua"
}
includedirs { "../../../include/", "../../../src/CppParser/" }
configuration "*"
links { "CppSharp.CppParser" }
|
project "CppSharp.Parser.Gen"
kind "ConsoleApp"
language "C#"
location "."
debugdir "."
files { "ParserGen.cs", "*.lua" }
links { "CppSharp.AST", "CppSharp.Generator" }
SetupParser()
project "CppSharp.Parser.CSharp"
kind "SharedLib"
language "C#"
location "."
dependson { "CppSharp.CppParser" }
flags { common_flags, "Unsafe" }
files
{
"CSharp/**.cs",
"**.lua"
}
links { "CppSharp.Runtime" }
configuration "vs*"
project "CppSharp.Parser.CLI"
kind "SharedLib"
language "C++"
SetupNativeProject()
dependson { "CppSharp.CppParser" }
flags { common_flags, "Managed" }
configuration "vs*"
buildoptions { clang_msvc_flags }
configuration "*"
files
{
"CLI/AST.h",
"CLI/AST.cpp",
"CLI/**.h",
"CLI/**.cpp",
"**.lua"
}
includedirs { "../../../include/", "../../../src/CppParser/" }
configuration "*"
links { "CppSharp.CppParser" }
|
Fixed the ParserGen build script to use the SetupParser helper function.
|
Fixed the ParserGen build script to use the SetupParser helper function.
|
Lua
|
mit
|
Samana/CppSharp,zillemarco/CppSharp,genuinelucifer/CppSharp,txdv/CppSharp,ddobrev/CppSharp,genuinelucifer/CppSharp,mono/CppSharp,mono/CppSharp,ddobrev/CppSharp,ddobrev/CppSharp,xistoso/CppSharp,KonajuGames/CppSharp,mydogisbox/CppSharp,SonyaSa/CppSharp,mohtamohit/CppSharp,Samana/CppSharp,txdv/CppSharp,mydogisbox/CppSharp,txdv/CppSharp,xistoso/CppSharp,SonyaSa/CppSharp,imazen/CppSharp,KonajuGames/CppSharp,xistoso/CppSharp,ddobrev/CppSharp,Samana/CppSharp,inordertotest/CppSharp,zillemarco/CppSharp,zillemarco/CppSharp,zillemarco/CppSharp,txdv/CppSharp,inordertotest/CppSharp,mono/CppSharp,zillemarco/CppSharp,u255436/CppSharp,u255436/CppSharp,mono/CppSharp,nalkaro/CppSharp,mono/CppSharp,imazen/CppSharp,mydogisbox/CppSharp,txdv/CppSharp,mono/CppSharp,u255436/CppSharp,genuinelucifer/CppSharp,inordertotest/CppSharp,SonyaSa/CppSharp,mohtamohit/CppSharp,KonajuGames/CppSharp,xistoso/CppSharp,genuinelucifer/CppSharp,KonajuGames/CppSharp,mohtamohit/CppSharp,mydogisbox/CppSharp,Samana/CppSharp,KonajuGames/CppSharp,ktopouzi/CppSharp,mydogisbox/CppSharp,inordertotest/CppSharp,ktopouzi/CppSharp,nalkaro/CppSharp,u255436/CppSharp,nalkaro/CppSharp,Samana/CppSharp,mohtamohit/CppSharp,u255436/CppSharp,ktopouzi/CppSharp,nalkaro/CppSharp,nalkaro/CppSharp,imazen/CppSharp,genuinelucifer/CppSharp,imazen/CppSharp,inordertotest/CppSharp,ddobrev/CppSharp,ktopouzi/CppSharp,SonyaSa/CppSharp,imazen/CppSharp,mohtamohit/CppSharp,SonyaSa/CppSharp,xistoso/CppSharp,ktopouzi/CppSharp
|
5e3d86a33fc7d9478a856c8e5eda25225581ecef
|
src/CppParser/Bindings/premake4.lua
|
src/CppParser/Bindings/premake4.lua
|
project "CppSharp.Parser.Gen"
kind "ConsoleApp"
language "C#"
SetupManagedProject()
debugdir "."
files { "ParserGen.cs", "*.lua" }
links { "CppSharp.AST", "CppSharp.Generator" }
SetupParser()
project "CppSharp.Parser.CSharp"
kind "SharedLib"
language "C#"
SetupManagedProject()
dependson { "CppSharp.CppParser" }
flags { common_flags, "Unsafe" }
files
{
"CSharp/**.cs",
"**.lua"
}
links { "CppSharp.Runtime" }
if string.starts(action, "vs") then
project "CppSharp.Parser.CLI"
kind "SharedLib"
language "C++"
SetupNativeProject()
dependson { "CppSharp.CppParser" }
flags { common_flags, "Managed" }
configuration "vs*"
buildoptions { clang_msvc_flags }
configuration "*"
files
{
"CLI/AST.h",
"CLI/AST.cpp",
"CLI/**.h",
"CLI/**.cpp",
"**.lua"
}
includedirs { "../../../include/", "../../../src/CppParser/" }
configuration "*"
links { "CppSharp.CppParser" }
end
|
project "CppSharp.Parser.Gen"
kind "ConsoleApp"
language "C#"
SetupManagedProject()
debugdir "."
files { "ParserGen.cs", "*.lua" }
links { "CppSharp.AST", "CppSharp.Generator" }
SetupParser()
project "CppSharp.Parser.CSharp"
kind "SharedLib"
language "C#"
SetupManagedProject()
dependson { "CppSharp.CppParser" }
flags { common_flags, "Unsafe" }
files
{
"**.lua"
}
links { "CppSharp.Runtime" }
configuration "macosx"
files { "CSharp/i686-apple-darwin12.4.0/**.cs" }
configuration "not macosx"
files { "CSharp/*.cs" }
configuration ""
if string.starts(action, "vs") then
project "CppSharp.Parser.CLI"
kind "SharedLib"
language "C++"
SetupNativeProject()
dependson { "CppSharp.CppParser" }
flags { common_flags, "Managed" }
configuration "vs*"
buildoptions { clang_msvc_flags }
configuration "*"
files
{
"CLI/AST.h",
"CLI/AST.cpp",
"CLI/**.h",
"CLI/**.cpp",
"**.lua"
}
includedirs { "../../../include/", "../../../src/CppParser/" }
configuration "*"
links { "CppSharp.CppParser" }
end
|
Fixed parser bindings build to correctly choose the correct generated bindings depending on the platform.
|
Fixed parser bindings build to correctly choose the correct generated bindings depending on the platform.
|
Lua
|
mit
|
mono/CppSharp,xistoso/CppSharp,xistoso/CppSharp,nalkaro/CppSharp,nalkaro/CppSharp,Samana/CppSharp,mydogisbox/CppSharp,imazen/CppSharp,genuinelucifer/CppSharp,mono/CppSharp,u255436/CppSharp,KonajuGames/CppSharp,SonyaSa/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,imazen/CppSharp,genuinelucifer/CppSharp,SonyaSa/CppSharp,KonajuGames/CppSharp,ktopouzi/CppSharp,Samana/CppSharp,ktopouzi/CppSharp,txdv/CppSharp,KonajuGames/CppSharp,ktopouzi/CppSharp,inordertotest/CppSharp,mohtamohit/CppSharp,SonyaSa/CppSharp,u255436/CppSharp,Samana/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,genuinelucifer/CppSharp,imazen/CppSharp,u255436/CppSharp,txdv/CppSharp,Samana/CppSharp,nalkaro/CppSharp,xistoso/CppSharp,KonajuGames/CppSharp,Samana/CppSharp,inordertotest/CppSharp,ktopouzi/CppSharp,mohtamohit/CppSharp,mono/CppSharp,genuinelucifer/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,ddobrev/CppSharp,zillemarco/CppSharp,genuinelucifer/CppSharp,txdv/CppSharp,SonyaSa/CppSharp,xistoso/CppSharp,imazen/CppSharp,txdv/CppSharp,u255436/CppSharp,txdv/CppSharp,zillemarco/CppSharp,SonyaSa/CppSharp,mydogisbox/CppSharp,ktopouzi/CppSharp,imazen/CppSharp,mohtamohit/CppSharp,mydogisbox/CppSharp,nalkaro/CppSharp,mohtamohit/CppSharp,mono/CppSharp,KonajuGames/CppSharp,xistoso/CppSharp,u255436/CppSharp,ddobrev/CppSharp,nalkaro/CppSharp,mono/CppSharp,mydogisbox/CppSharp,mohtamohit/CppSharp,inordertotest/CppSharp,mydogisbox/CppSharp,mono/CppSharp,inordertotest/CppSharp
|
d6016cba04d7637aab04f4e55716db19523cfa47
|
defaut/Paladin.lua
|
defaut/Paladin.lua
|
Ovale.defaut["PALADIN"] = [[Define(avenging_wrath 31884)
SpellInfo(avenging_wrath duration=20 cd=180 )
SpellAddBuff(avenging_wrath avenging_wrath=1)
Define(blessing_of_kings 20217)
SpellInfo(blessing_of_kings duration=3600 )
SpellAddBuff(blessing_of_kings blessing_of_kings=1)
Define(blessing_of_might 19740)
SpellInfo(blessing_of_might duration=3600 )
SpellAddBuff(blessing_of_might blessing_of_might=1)
Define(crusader_strike 35395)
SpellInfo(crusader_strike holy=-1 cd=4.5 )
Define(execution_sentence 114916)
SpellInfo(execution_sentence duration=10 tick=1 )
SpellAddTargetDebuff(execution_sentence execution_sentence=1)
Define(exorcism 879)
SpellInfo(exorcism holy=-1 cd=15 )
Define(guardian_of_ancient_kings 86659)
SpellInfo(guardian_of_ancient_kings duration=12 cd=180 )
SpellAddBuff(guardian_of_ancient_kings guardian_of_ancient_kings=1)
Define(hammer_of_wrath 24275)
SpellInfo(hammer_of_wrath holy=-0 cd=6 )
Define(inquisition 84963)
SpellInfo(inquisition duration=10 holy=1 )
SpellAddBuff(inquisition inquisition=1)
Define(judgment 20271)
SpellInfo(judgment cd=6 )
Define(rebuke 96231)
SpellInfo(rebuke duration=4 cd=15 )
Define(seal_of_insight 20165)
SpellAddBuff(seal_of_insight seal_of_insight=1)
Define(seal_of_truth 31801)
SpellAddBuff(seal_of_truth seal_of_truth=1)
Define(templars_verdict 85256)
SpellInfo(templars_verdict holy=3 )
AddCheckBox(showwait L(showwait) default)
AddIcon mastery=3 help=main
{
if not InCombat()
{
if not BuffPresent(str_agi_int any=1) Spell(blessing_of_kings)
if not BuffPresent(mastery any=1) and not BuffPresent(str_agi_int any=1) Spell(blessing_of_might)
unless Stance(1) Spell(seal_of_truth)
}
if ManaPercent() >=90 or Stance(0) unless Stance(1) Spell(seal_of_truth)
if ManaPercent() <=30 unless Stance(4) Spell(seal_of_insight)
if {BuffExpires(inquisition) or BuffRemains(inquisition) <=2 } and {HolyPower() >=3 } Spell(inquisition)
if HolyPower() ==5 Spell(templars_verdict)
Spell(hammer_of_wrath usable=1)
if SpellCooldown(hammer_of_wrath) >0 and SpellCooldown(hammer_of_wrath) <=0.2 if CheckBoxOn(showwait) Texture(Spell_nature_timestop)
Spell(exorcism)
if target.HealthPercent() <=20 or BuffPresent(avenging_wrath) Spell(judgment)
Spell(crusader_strike)
Spell(judgment)
if HolyPower() >=3 Spell(templars_verdict)
}
AddIcon mastery=3 help=offgcd
{
if target.IsInterruptible() Spell(rebuke)
if BuffPresent(inquisition) Spell(execution_sentence)
}
AddIcon mastery=3 help=cd
{
if BuffPresent(inquisition) Spell(avenging_wrath)
if BuffPresent(avenging_wrath) Spell(guardian_of_ancient_kings)
if BuffPresent(inquisition) { Item(Trinket0Slot usable=1) Item(Trinket1Slot usable=1) }
}
]]
|
Ovale.defaut["PALADIN"] = [[Define(avenging_wrath 31884)
SpellInfo(avenging_wrath duration=20 cd=180 )
SpellAddBuff(avenging_wrath avenging_wrath=1)
Define(blessing_of_kings 20217)
SpellInfo(blessing_of_kings duration=3600 )
SpellAddBuff(blessing_of_kings blessing_of_kings=1)
Define(blessing_of_might 19740)
SpellInfo(blessing_of_might duration=3600 )
SpellAddBuff(blessing_of_might blessing_of_might=1)
Define(crusader_strike 35395)
SpellInfo(crusader_strike holy=-1 cd=4.5 )
Define(execution_sentence 114916)
SpellInfo(execution_sentence duration=10 tick=1 )
SpellAddTargetDebuff(execution_sentence execution_sentence=1)
Define(exorcism 879)
SpellInfo(exorcism holy=-1 cd=15 )
Define(exorcism_glyphed 122032)
SpellInfo(exorcism_glyphed holy=-1 cd=15)
Define(guardian_of_ancient_kings 86659)
SpellInfo(guardian_of_ancient_kings duration=12 cd=180 )
SpellAddBuff(guardian_of_ancient_kings guardian_of_ancient_kings=1)
Define(hammer_of_wrath 24275)
SpellInfo(hammer_of_wrath holy=-0 cd=6 )
Define(inquisition 84963)
SpellInfo(inquisition duration=10 holy=1 )
SpellAddBuff(inquisition inquisition=1)
Define(judgment 20271)
SpellInfo(judgment cd=6 )
Define(rebuke 96231)
SpellInfo(rebuke duration=4 cd=15 )
Define(seal_of_insight 20165)
SpellAddBuff(seal_of_insight seal_of_insight=1)
Define(seal_of_truth 31801)
SpellAddBuff(seal_of_truth seal_of_truth=1)
Define(templars_verdict 85256)
SpellInfo(templars_verdict holy=3 )
Define(glyph_of_mass_exorcism 122028)
AddCheckBox(showwait L(showwait) default)
AddIcon mastery=3 help=main
{
if not InCombat()
{
if not BuffPresent(str_agi_int any=1) Spell(blessing_of_kings)
if not BuffPresent(mastery any=1) and not BuffPresent(str_agi_int any=1) Spell(blessing_of_might)
unless Stance(1) Spell(seal_of_truth)
}
if ManaPercent() >=90 or Stance(0) unless Stance(1) Spell(seal_of_truth)
if ManaPercent() <=30 unless Stance(4) Spell(seal_of_insight)
if {BuffExpires(inquisition) or BuffRemains(inquisition) <=2 } and {HolyPower() >=3 } Spell(inquisition)
if HolyPower() ==5 Spell(templars_verdict)
Spell(hammer_of_wrath usable=1)
if SpellCooldown(hammer_of_wrath) >0 and SpellCooldown(hammer_of_wrath) <=0.2 if CheckBoxOn(showwait) Texture(Spell_nature_timestop)
if Glyph(glyph_of_mass_exorcism no) Spell(exorcism)
if Glyph(glyph_of_mass_exorcism) Spell(exorcism_glyphed)
if target.HealthPercent() <=20 or BuffPresent(avenging_wrath) Spell(judgment)
Spell(crusader_strike)
Spell(judgment)
if HolyPower() >=3 Spell(templars_verdict)
}
AddIcon mastery=3 help=offgcd
{
if target.IsInterruptible() Spell(rebuke)
if BuffPresent(inquisition) Spell(execution_sentence)
}
AddIcon mastery=3 help=cd
{
if BuffPresent(inquisition) Spell(avenging_wrath)
if BuffPresent(avenging_wrath) Spell(guardian_of_ancient_kings)
if BuffPresent(inquisition) { Item(Trinket0Slot usable=1) Item(Trinket1Slot usable=1) }
}
]]
|
Fix ticket 175 - Paladin Priority broken with Glyph of Exorcism
|
Fix ticket 175 - Paladin Priority broken with Glyph of Exorcism
When using the Glyph of Mass Exorcism, the spell ID of Exorcism changes
from 879 to 122032.
git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@671 d5049fe3-3747-40f7-a4b5-f36d6801af5f
|
Lua
|
mit
|
eXhausted/Ovale,ultijlam/ovale,Xeltor/ovale,ultijlam/ovale,eXhausted/Ovale,eXhausted/Ovale,ultijlam/ovale
|
353099ec332cbcf714ca018f67f22d44c3d6451c
|
OS/DiskOS/Programs/load.lua
|
OS/DiskOS/Programs/load.lua
|
local source = select(1,...)
local term = require("terminal")
local eapi = require("Editors")
local png = false
if source and source ~= "@clip" and source ~= "-?" then
source = term.resolve(source)
if source:sub(-4,-1) == ".png" then
png = true
elseif source:sub(-5,-1) ~= ".lk12" then
local lksrc = source..".lk12"
if fs.exists(lksrc) then
source = lksrc
elseif fs.exists(source..".png") then
source = source..".png"
png = true
else
source = lksrc
end
end
elseif source ~= "@clip" and source ~= "-?" then source = eapi.filePath end
if not source or source == "-?" then
printUsage(
"load <file>","Loads a game into memory",
"load","Reloads the current game",
"load @clip","Load from clipboard"
)
return
end
if source ~= "@clip" and not fs.exists(source) then return 1, "File doesn't exists" end
if source ~= "@clip" and fs.isDirectory(source) then return 1, "Couldn't load a directory !" end
local saveData = source == "@clip" and clipboard() or fs.read(source)
if png then
FDD.importDisk(saveData)
saveData = memget(RamUtils.FRAM,64*1024)
end
if not saveData:sub(0,5) == "LK12;" then return 1, "This is not a valid LK12 file !!" end
saveData = saveData:gsub("\r\n","\n")
--LK12;OSData;OSName;DataType;Version;Compression;CompressLevel; data"
--local header = "LK12;OSData;DiskOS;DiskGame;V"..saveVer..";"..sw.."x"..sh..";C:"
local datasum = 0
local nextargiter = string.gmatch(saveData,".")
local function nextarg()
local start = datasum + 1
while true do
datasum = datasum + 1
local char = nextargiter()
if not char then
datasum = datasum - 1
return
end
if char == ";" then
break
end
end
return saveData:sub(start,datasum-1)
end
nextarg() --Skip LK12;
local filetype = nextarg()
if not filetype then return 1, "Invalid Data !" end
if filetype ~= "OSData" then
if filetype == "GPUIMG" then --Import it
if eapi.leditors[eapi.editors.sprite] then
local simg = imagedata(screenSize())
local limg = imagedata(saveData)
simg:paste(limg)
eapi.leditors[eapi.editors.sprite]:import(simg:encode()..";0;")
color(11) print("Imported to sprite editor successfully") return
end
elseif filetype == "TILEMAP" then
if eapi.leditors[eapi.editors.tile] then
eapi.leditors[eapi.editors.tile]:import(saveData)
color(11) print("Imported to tilemap editor successfully") return
end
else
return 1, "Can't load '"..filetype.."' files !"
end
end
local osname = nextarg()
if not osname then return 1, "Invalid Data !" end
if osname ~= "DiskOS" then return 1, "Can't load files from '"..osname.."' OS !" end
local datatype = nextarg()
if not datatype then return 1, "Invalid Data !" end
if datatype ~= "DiskGame" then return 1, "Can't load '"..datatype.."' from '"..osname.."' OS !" end
local dataver = nextarg()
if not dataver then return 1, "Invalid Data !" end
dataver = tonumber(string.match(dataver,"V(%d+)"))
if not dataver then return 1, "Invalid Data !" end
if dataver > _DiskVer then return 1, "Can't load disks newer than V".._DiskVer..", provided: V"..dataver end
if dataver < _MinDiskVer then color(8) return 1, "Can't load disks older than V".._DiskVer..", provided: V"..dataver..", Use 'update_disk' command to update the disk" end
local sw, sh = screenSize()
local datares = nextarg()
if not datares then return 1, "Invalid Data !" end
local dataw, datah = string.match(datares,"(%d+)x(%d+)")
if not (dataw and datah) then return 1, "Invalid Data !" end dataw, datah = tonumber(dataw), tonumber(datah)
if dataw ~= sw or datah ~= sh then return 1, "This disk is made for GPUs with "..dataw.."x"..datah.." resolution, current GPU is "..sw.."x"..sh end
local compress = nextarg()
if not compress then return 1, "Invalid Data !" end
compress = string.match(compress,"C:(.+)")
if not compress then return 1, "Invalid Data !" end
if compress == "binary" then
local revision = nextarg()
if not revision then return 1, "Invalid Data !" end
revision = string.match(revision,"Rev:(%d+)")
if not revision then return 1, "Invalid Data !" end
revision = tonumber(revision)
if revision < 1 then return 1, "Can't load binary saves with revision 0 or lower ("..revision..")" end
if revision > 1 then return 1, "Can't load binary saves with revision 2 or higher" end
local data = saveData:sub(datasum+1,-1)
eapi.filePath = source
eapi:decode(data)
else
local clevel = nextarg()
if not clevel then color(8) print("Invalid Data !") return 1, "Invalid Data !" end
clevel = string.match(clevel,"CLvl:(.+)")
if not clevel then color(8) print("Invalid Data !") return 1, "Invalid Data !" end clevel = tonumber(clevel)
local data = saveData:sub(datasum+2,-1)
if compress ~= "none" then --Decompress
local b64data, char = math.b64dec(data)
if not b64data then cprint(char) cprint(string.byte(char)) error(tostring(char)) end
data = math.decompress(b64data,compress,clevel)
end
eapi.filePath = source
eapi:import(data)
end
color(11) print("Loaded successfully")
|
local source = select(1,...)
local term = require("terminal")
local eapi = require("Editors")
local png = false
if source and source ~= "@clip" and source ~= "-?" then
source = term.resolve(source)
if source:sub(-4,-1) == ".png" then
png = true
elseif source:sub(-5,-1) ~= ".lk12" then
local lksrc = source..".lk12"
if fs.exists(lksrc) then
source = lksrc
elseif fs.exists(source..".png") then
source = source..".png"
png = true
else
source = lksrc
end
end
elseif source ~= "@clip" and source ~= "-?" then source = eapi.filePath end
if not source or source == "-?" then
printUsage(
"load <file>","Loads a game into memory",
"load","Reloads the current game",
"load @clip","Load from clipboard"
)
return
end
if source ~= "@clip" and not fs.exists(source) then return 1, "File doesn't exists" end
if source ~= "@clip" and fs.isDirectory(source) then return 1, "Couldn't load a directory !" end
local saveData = source == "@clip" and clipboard() or fs.read(source)
if png then
FDD.importDisk(saveData)
saveData = memget(RamUtils.FRAM,64*1024)
end
if not saveData:sub(0,5) == "LK12;" then return 1, "This is not a valid LK12 file !!" end
saveData = saveData:gsub("\r\n","\n")
--LK12;OSData;OSName;DataType;Version;Compression;CompressLevel; data"
--local header = "LK12;OSData;DiskOS;DiskGame;V"..saveVer..";"..sw.."x"..sh..";C:"
local datasum = 0
local nextargiter = string.gmatch(saveData,".")
local function nextarg()
local start = datasum + 1
while true do
datasum = datasum + 1
local char = nextargiter()
if not char then
datasum = datasum - 1
return
end
if char == ";" then
break
end
end
return saveData:sub(start,datasum-1)
end
nextarg() --Skip LK12;
local filetype = nextarg()
if not filetype then return 1, "Invalid Data !" end
if filetype ~= "OSData" then
if filetype == "GPUIMG" then --Import it
if eapi.leditors[eapi.editors.sprite] then
local simg = imagedata(screenSize())
local limg = imagedata(saveData)
simg:paste(limg)
eapi.leditors[eapi.editors.sprite]:import(simg:encode()..";0;")
color(11) print("Imported to sprite editor successfully") return
end
elseif filetype == "TILEMAP" then
if eapi.leditors[eapi.editors.tile] then
eapi.leditors[eapi.editors.tile]:import(saveData)
color(11) print("Imported to tilemap editor successfully") return
end
else
return 1, "Can't load '"..filetype.."' files !"
end
end
local osname = nextarg()
if not osname then return 1, "Invalid Data !" end
if osname ~= "DiskOS" then return 1, "Can't load files from '"..osname.."' OS !" end
local datatype = nextarg()
if not datatype then return 1, "Invalid Data !" end
if datatype ~= "DiskGame" then return 1, "Can't load '"..datatype.."' from '"..osname.."' OS !" end
local dataver = nextarg()
if not dataver then return 1, "Invalid Data !" end
dataver = tonumber(string.match(dataver,"V(%d+)"))
if not dataver then return 1, "Invalid Data !" end
if dataver > _DiskVer then return 1, "Can't load disks newer than V".._DiskVer..", provided: V"..dataver end
if dataver < _MinDiskVer then return 1, "Can't load disks older than V".._DiskVer..", provided: V"..dataver..", Use 'update_disk' command to update the disk" end
local sw, sh = screenSize()
local datares = nextarg()
if not datares then return 1, "Invalid Data !" end
local dataw, datah = string.match(datares,"(%d+)x(%d+)")
if not (dataw and datah) then return 1, "Invalid Data !" end dataw, datah = tonumber(dataw), tonumber(datah)
if dataw ~= sw or datah ~= sh then return 1, "This disk is made for GPUs with "..dataw.."x"..datah.." resolution, current GPU is "..sw.."x"..sh end
local compress = nextarg()
if not compress then return 1, "Invalid Data !" end
compress = string.match(compress,"C:(.+)")
if not compress then return 1, "Invalid Data !" end
if compress == "binary" then
local revision = nextarg()
if not revision then return 1, "Invalid Data !" end
revision = string.match(revision,"Rev:(%d+)")
if not revision then return 1, "Invalid Data !" end
revision = tonumber(revision)
if revision < 1 then return 1, "Can't load binary saves with revision 0 or lower ("..revision..")" end
if revision > 1 then return 1, "Can't load binary saves with revision 2 or higher" end
local data = saveData:sub(datasum+1,-1)
eapi.filePath = source
eapi:decode(data)
else
local clevel = nextarg()
if not clevel then return 1, "Invalid Data !" end
clevel = string.match(clevel,"CLvl:(.+)")
if not clevel then return 1, "Invalid Data !" end clevel = tonumber(clevel)
local data = saveData:sub(datasum+2,-1)
if compress ~= "none" then --Decompress
local b64data, char = math.b64dec(data)
if not b64data then cprint(char) cprint(string.byte(char)) error(tostring(char)) end
data = math.decompress(b64data,compress,clevel)
end
eapi.filePath = source
eapi:import(data)
end
color(11) print("Loaded successfully")
|
Typofixes in `load` command
|
Typofixes in `load` command
Former-commit-id: 2dedf6eb1bd1ae29476dc7ccfd756243bfa455e0
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
086dbdb657e7994f996b18791812e4779ac43340
|
frontend/ui/widget/scrolltextwidget.lua
|
frontend/ui/widget/scrolltextwidget.lua
|
local InputContainer = require("ui/widget/container/inputcontainer")
local TextBoxWidget = require("ui/widget/textboxwidget")
local VerticalScrollBar = require("ui/widget/verticalscrollbar")
local Geom = require("ui/geometry")
local GestureRange = require("ui/gesturerange")
local UIManager = require("ui/uimanager")
local Device = require("device")
local Screen = Device.screen
local Input = Device.input
local HorizontalGroup = require("ui/widget/horizontalgroup")
local HorizontalSpan = require("ui/widget/horizontalspan")
local Blitbuffer = require("ffi/blitbuffer")
--[[
Text widget with vertical scroll bar
--]]
local ScrollTextWidget = InputContainer:new{
text = nil,
charlist = nil,
charpos = nil,
editable = false,
face = nil,
fgcolor = Blitbuffer.COLOR_BLACK,
width = 400,
height = 20,
scroll_bar_width = Screen:scaleBySize(6),
text_scroll_span = Screen:scaleBySize(6),
dialog = nil,
}
function ScrollTextWidget:init()
self.text_widget = TextBoxWidget:new{
text = self.text,
charlist = self.charlist,
charpos = self.charpos,
editable = self.editable,
face = self.face,
fgcolor = self.fgcolor,
width = self.width - self.scroll_bar_width - self.text_scroll_span,
height = self.height
}
local visible_line_count = self.text_widget:getVisLineCount()
local total_line_count = self.text_widget:getAllLineCount()
self.v_scroll_bar = VerticalScrollBar:new{
enable = visible_line_count < total_line_count,
low = 0,
high = visible_line_count/total_line_count,
width = self.scroll_bar_width,
height = self.height,
}
local horizontal_group = HorizontalGroup:new{}
table.insert(horizontal_group, self.text_widget)
table.insert(horizontal_group, HorizontalSpan:new{self.text_scroll_span})
table.insert(horizontal_group, self.v_scroll_bar)
self[1] = horizontal_group
self.dimen = Geom:new(self[1]:getSize())
if Device:isTouchDevice() then
self.ges_events = {
ScrollText = {
GestureRange:new{
ges = "swipe",
range = function() return self.dimen end,
},
},
}
end
if Device:hasKeyboard() or Device:hasKeys() then
self.key_events = {
ScrollDown = {{Input.group.PgFwd}, doc = "scroll down"},
ScrollUp = {{Input.group.PgBack}, doc = "scroll up"},
}
end
end
function ScrollTextWidget:unfocus()
self.text_widget:unfocus()
end
function ScrollTextWidget:focus()
self.text_widget:focus()
end
function ScrollTextWidget:scrollText(direction)
if direction == 0 then return end
local low, high
if direction > 0 then
low, high = self.text_widget:scrollDown()
else
low, high = self.text_widget:scrollUp()
end
self.v_scroll_bar:set(low, high)
UIManager:setDirty(self.dialog, function()
return "partial", self.dimen
end)
end
function ScrollTextWidget:onScrollText(arg, ges)
if ges.direction == "north" then
self:scrollText(1)
elseif ges.direction == "south" then
self:scrollText(-1)
end
return true
end
function ScrollTextWidget:onScrollDown()
self:scrollText(1)
return true
end
function ScrollTextWidget:onScrollUp()
self:scrollText(-1)
return true
end
return ScrollTextWidget
|
local InputContainer = require("ui/widget/container/inputcontainer")
local TextBoxWidget = require("ui/widget/textboxwidget")
local VerticalScrollBar = require("ui/widget/verticalscrollbar")
local Geom = require("ui/geometry")
local GestureRange = require("ui/gesturerange")
local UIManager = require("ui/uimanager")
local Device = require("device")
local Screen = Device.screen
local Input = Device.input
local HorizontalGroup = require("ui/widget/horizontalgroup")
local HorizontalSpan = require("ui/widget/horizontalspan")
local Blitbuffer = require("ffi/blitbuffer")
--[[
Text widget with vertical scroll bar
--]]
local ScrollTextWidget = InputContainer:new{
text = nil,
charlist = nil,
charpos = nil,
editable = false,
face = nil,
fgcolor = Blitbuffer.COLOR_BLACK,
width = 400,
height = 20,
scroll_bar_width = Screen:scaleBySize(6),
text_scroll_span = Screen:scaleBySize(6),
dialog = nil,
}
function ScrollTextWidget:init()
self.text_widget = TextBoxWidget:new{
text = self.text,
charlist = self.charlist,
charpos = self.charpos,
editable = self.editable,
face = self.face,
fgcolor = self.fgcolor,
width = self.width - self.scroll_bar_width - self.text_scroll_span,
height = self.height
}
local visible_line_count = self.text_widget:getVisLineCount()
local total_line_count = self.text_widget:getAllLineCount()
self.v_scroll_bar = VerticalScrollBar:new{
enable = visible_line_count < total_line_count,
low = 0,
high = visible_line_count/total_line_count,
width = self.scroll_bar_width,
height = self.height,
}
local horizontal_group = HorizontalGroup:new{}
table.insert(horizontal_group, self.text_widget)
table.insert(horizontal_group, HorizontalSpan:new{self.text_scroll_span})
table.insert(horizontal_group, self.v_scroll_bar)
self[1] = horizontal_group
self.dimen = Geom:new(self[1]:getSize())
if Device:isTouchDevice() then
self.ges_events = {
ScrollText = {
GestureRange:new{
ges = "swipe",
range = function() return self.dimen end,
},
},
}
end
if Device:hasKeyboard() or Device:hasKeys() then
self.key_events = {
ScrollDown = {{Input.group.PgFwd}, doc = "scroll down"},
ScrollUp = {{Input.group.PgBack}, doc = "scroll up"},
}
end
end
function ScrollTextWidget:unfocus()
self.text_widget:unfocus()
end
function ScrollTextWidget:focus()
self.text_widget:focus()
end
function ScrollTextWidget:moveCursor(x, y)
self.text_widget:moveCursor(x, y)
end
function ScrollTextWidget:scrollText(direction)
if direction == 0 then return end
local low, high
if direction > 0 then
low, high = self.text_widget:scrollDown()
else
low, high = self.text_widget:scrollUp()
end
self.v_scroll_bar:set(low, high)
UIManager:setDirty(self.dialog, function()
return "partial", self.dimen
end)
end
function ScrollTextWidget:onScrollText(arg, ges)
if ges.direction == "north" then
self:scrollText(1)
elseif ges.direction == "south" then
self:scrollText(-1)
end
return true
end
function ScrollTextWidget:onScrollDown()
self:scrollText(1)
return true
end
function ScrollTextWidget:onScrollUp()
self:scrollText(-1)
return true
end
return ScrollTextWidget
|
scrolltextwidget(fix): add moveCursor method
|
scrolltextwidget(fix): add moveCursor method
|
Lua
|
agpl-3.0
|
houqp/koreader,poire-z/koreader,mihailim/koreader,Frenzie/koreader,robert00s/koreader,NiLuJe/koreader,Markismus/koreader,Frenzie/koreader,apletnev/koreader,pazos/koreader,lgeek/koreader,mwoz123/koreader,NickSavage/koreader,Hzj-jie/koreader,koreader/koreader,NiLuJe/koreader,koreader/koreader,poire-z/koreader
|
982af59fac8a105a6ebff28a10e40219686f791b
|
kong/cluster_events/strategies/postgres.lua
|
kong/cluster_events/strategies/postgres.lua
|
local utils = require "kong.tools.utils"
local pgmoon = require "pgmoon"
local max = math.max
local fmt = string.format
local concat = table.concat
local setmetatable = setmetatable
local new_tab
do
local ok
ok, new_tab = pcall(require, "table.new")
if not ok then
new_tab = function(narr, nrec) return {} end
end
end
local INSERT_QUERY = [[
INSERT INTO cluster_events(id, node_id, at, nbf, expire_at, channel, data)
VALUES(%s, %s, to_timestamp(%f), to_timestamp(%s), to_timestamp(%s), %s, %s)
]]
local SELECT_INTERVAL_QUERY = [[
SELECT id, node_id, channel, data,
extract(epoch from at) as at,
extract(epoch from nbf) as nbf
FROM cluster_events
WHERE channel IN (%s)
AND at > to_timestamp(%f)
AND at <= to_timestamp(%f)
]]
local _M = {}
local mt = { __index = _M }
function _M.new(dao_factory, page_size, event_ttl)
local self = {
db = dao_factory.db,
--page_size = page_size,
event_ttl = event_ttl,
}
return setmetatable(self, mt)
end
function _M:insert(node_id, channel, at, data, nbf)
local expire_at = max(at + self.event_ttl, at)
if not nbf then
nbf = "NULL"
end
local pg_id = pgmoon.Postgres.escape_literal(nil, utils.uuid())
local pg_node_id = pgmoon.Postgres.escape_literal(nil, node_id)
local pg_channel = pgmoon.Postgres.escape_literal(nil, channel)
local pg_data = pgmoon.Postgres.escape_literal(nil, data)
local q = fmt(INSERT_QUERY, pg_id, pg_node_id, at, nbf, expire_at,
pg_channel, pg_data)
local res, err = self.db:query(q)
if not res then
return nil, "could not insert invalidation row: " .. err
end
return true
end
function _M:select_interval(channels, min_at, max_at)
local n_chans = #channels
local pg_channels = new_tab(n_chans, 0)
for i = 1, n_chans do
pg_channels[i] = pgmoon.Postgres.escape_literal(nil, channels[i])
end
local q = fmt(SELECT_INTERVAL_QUERY, concat(pg_channels, ","), min_at,
max_at)
local ran
-- TODO: implement pagination for this strategy as
-- well.
--
-- we need to behave like lua-cassandra's iteration:
-- provide an iterator that enters the loop, with a
-- page = 0 argument if there is no first page, and a
-- page = 1 argument with the fetched rows elsewise
return function(_, p_rows)
if ran then
return nil
end
local res, err = self.db:query(q)
local page = #res > 0 and 1 or 0
ran = true
return res, err, page
end
end
function _M:truncate_events()
return self.db:query("TRUNCATE cluster_events")
end
return _M
|
local utils = require "kong.tools.utils"
local pgmoon = require "pgmoon"
local max = math.max
local fmt = string.format
local concat = table.concat
local setmetatable = setmetatable
local new_tab
do
local ok
ok, new_tab = pcall(require, "table.new")
if not ok then
new_tab = function(narr, nrec) return {} end
end
end
local INSERT_QUERY = [[
INSERT INTO cluster_events(id, node_id, at, nbf, expire_at, channel, data)
VALUES(%s, %s, to_timestamp(%f), to_timestamp(%s), to_timestamp(%s), %s, %s)
]]
local SELECT_INTERVAL_QUERY = [[
SELECT id, node_id, channel, data,
extract(epoch from at) as at,
extract(epoch from nbf) as nbf
FROM cluster_events
WHERE channel IN (%s)
AND at > to_timestamp(%f)
AND at <= to_timestamp(%f)
]]
local _M = {}
local mt = { __index = _M }
function _M.new(dao_factory, page_size, event_ttl)
local self = {
db = dao_factory.db,
--page_size = page_size,
event_ttl = event_ttl,
}
return setmetatable(self, mt)
end
function _M:insert(node_id, channel, at, data, nbf)
local expire_at = max(at + self.event_ttl, at)
if not nbf then
nbf = "NULL"
end
local pg_id = pgmoon.Postgres.escape_literal(nil, utils.uuid())
local pg_node_id = pgmoon.Postgres.escape_literal(nil, node_id)
local pg_channel = pgmoon.Postgres.escape_literal(nil, channel)
local pg_data = pgmoon.Postgres.escape_literal(nil, data)
local q = fmt(INSERT_QUERY, pg_id, pg_node_id, at, nbf, expire_at,
pg_channel, pg_data)
local res, err = self.db:query(q)
if not res then
return nil, "could not insert invalidation row: " .. err
end
return true
end
function _M:select_interval(channels, min_at, max_at)
local n_chans = #channels
local pg_channels = new_tab(n_chans, 0)
for i = 1, n_chans do
pg_channels[i] = pgmoon.Postgres.escape_literal(nil, channels[i])
end
local q = fmt(SELECT_INTERVAL_QUERY, concat(pg_channels, ","), min_at,
max_at)
local ran
-- TODO: implement pagination for this strategy as
-- well.
--
-- we need to behave like lua-cassandra's iteration:
-- provide an iterator that enters the loop, with a
-- page = 0 argument if there is no first page, and a
-- page = 1 argument with the fetched rows elsewise
return function(_, p_rows)
if ran then
return nil
end
local res, err = self.db:query(q)
if not res then
return nil, err
end
local page = #res > 0 and 1 or 0
ran = true
return res, err, page
end
end
function _M:truncate_events()
return self.db:query("TRUNCATE cluster_events")
end
return _M
|
fix(cluster) add missing error handling in Postgres strategy
|
fix(cluster) add missing error handling in Postgres strategy
From #2709
|
Lua
|
apache-2.0
|
jebenexer/kong,Kong/kong,Kong/kong,icyxp/kong,shiprabehera/kong,salazar/kong,Mashape/kong,Kong/kong
|
338b54e3dd01422bbeb4c3ebe21b37151efb929a
|
kong/plugins/oauth2/migrations/postgres.lua
|
kong/plugins/oauth2/migrations/postgres.lua
|
return {
{
name = "2015-08-03-132400_init_oauth2",
up = [[
CREATE TABLE IF NOT EXISTS oauth2_credentials(
id uuid,
name text,
consumer_id uuid REFERENCES consumers (id) ON DELETE CASCADE,
client_id text UNIQUE,
client_secret text UNIQUE,
redirect_uri text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_credentials_consumer_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_consumer_idx ON oauth2_credentials(consumer_id);
END IF;
IF (SELECT to_regclass('oauth2_credentials_client_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_client_idx ON oauth2_credentials(client_id);
END IF;
IF (SELECT to_regclass('oauth2_credentials_secret_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_secret_idx ON oauth2_credentials(client_secret);
END IF;
END$$;
CREATE TABLE IF NOT EXISTS oauth2_authorization_codes(
id uuid,
code text UNIQUE,
authenticated_userid text,
scope text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_autorization_code_idx')) IS NULL THEN
CREATE INDEX oauth2_autorization_code_idx ON oauth2_authorization_codes(code);
END IF;
IF (SELECT to_regclass('oauth2_authorization_userid_idx')) IS NULL THEN
CREATE INDEX oauth2_authorization_userid_idx ON oauth2_authorization_codes(authenticated_userid);
END IF;
END$$;
CREATE TABLE IF NOT EXISTS oauth2_tokens(
id uuid,
credential_id uuid REFERENCES oauth2_credentials (id) ON DELETE CASCADE,
access_token text UNIQUE,
token_type text,
refresh_token text UNIQUE,
expires_in int,
authenticated_userid text,
scope text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_accesstoken_idx')) IS NULL THEN
CREATE INDEX oauth2_accesstoken_idx ON oauth2_tokens(access_token);
END IF;
IF (SELECT to_regclass('oauth2_token_refresh_idx')) IS NULL THEN
CREATE INDEX oauth2_token_refresh_idx ON oauth2_tokens(refresh_token);
END IF;
IF (SELECT to_regclass('oauth2_token_userid_idx')) IS NULL THEN
CREATE INDEX oauth2_token_userid_idx ON oauth2_tokens(authenticated_userid);
END IF;
END$$;
]],
down = [[
DROP TABLE oauth2_credentials;
DROP TABLE oauth2_authorization_codes;
DROP TABLE oauth2_tokens;
]]
},
{
name = "2016-07-15-oauth2_code_credential_id",
up = [[
DELETE FROM oauth2_authorization_codes;
ALTER TABLE oauth2_authorization_codes ADD COLUMN credential_id uuid REFERENCES oauth2_credentials (id) ON DELETE CASCADE;
]],
down = [[
ALTER TABLE oauth2_authorization_codes DROP COLUMN credential_id;
]]
}
}
|
return {
{
name = "2015-08-03-132400_init_oauth2",
up = [[
CREATE TABLE IF NOT EXISTS oauth2_credentials(
id uuid,
name text,
consumer_id uuid REFERENCES consumers (id) ON DELETE CASCADE,
client_id text UNIQUE,
client_secret text UNIQUE,
redirect_uri text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_credentials_consumer_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_consumer_idx ON oauth2_credentials(consumer_id);
END IF;
IF (SELECT to_regclass('oauth2_credentials_client_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_client_idx ON oauth2_credentials(client_id);
END IF;
IF (SELECT to_regclass('oauth2_credentials_secret_idx')) IS NULL THEN
CREATE INDEX oauth2_credentials_secret_idx ON oauth2_credentials(client_secret);
END IF;
END$$;
CREATE TABLE IF NOT EXISTS oauth2_authorization_codes(
id uuid,
code text UNIQUE,
authenticated_userid text,
scope text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_autorization_code_idx')) IS NULL THEN
CREATE INDEX oauth2_autorization_code_idx ON oauth2_authorization_codes(code);
END IF;
IF (SELECT to_regclass('oauth2_authorization_userid_idx')) IS NULL THEN
CREATE INDEX oauth2_authorization_userid_idx ON oauth2_authorization_codes(authenticated_userid);
END IF;
END$$;
CREATE TABLE IF NOT EXISTS oauth2_tokens(
id uuid,
credential_id uuid REFERENCES oauth2_credentials (id) ON DELETE CASCADE,
access_token text UNIQUE,
token_type text,
refresh_token text UNIQUE,
expires_in int,
authenticated_userid text,
scope text,
created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'),
PRIMARY KEY (id)
);
DO $$
BEGIN
IF (SELECT to_regclass('oauth2_accesstoken_idx')) IS NULL THEN
CREATE INDEX oauth2_accesstoken_idx ON oauth2_tokens(access_token);
END IF;
IF (SELECT to_regclass('oauth2_token_refresh_idx')) IS NULL THEN
CREATE INDEX oauth2_token_refresh_idx ON oauth2_tokens(refresh_token);
END IF;
IF (SELECT to_regclass('oauth2_token_userid_idx')) IS NULL THEN
CREATE INDEX oauth2_token_userid_idx ON oauth2_tokens(authenticated_userid);
END IF;
END$$;
]],
down = [[
DROP TABLE oauth2_credentials;
DROP TABLE oauth2_authorization_codes;
DROP TABLE oauth2_tokens;
]]
},
{
name = "2016-04-14-283949_serialize_redirect_uri",
up = function(_, _, factory)
local schema = factory.oauth2_credentials.schema
schema.fields.redirect_uri.type = "string"
local json = require "cjson"
local apps, err = factory.oauth2_credentials.db:find_all('oauth2_credentials', nil, schema);
if err then
return err
end
for _, app in ipairs(apps) do
local redirect_uri = {};
redirect_uri[1] = app.redirect_uri
local redirect_uri_str = json.encode(redirect_uri)
local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri_str.."' WHERE id='"..app.id.."'"
local _, err = factory.oauth2_credentials.db:queries(req)
if err then
return err
end
end
end,
down = function(_,_,factory)
local apps, err = factory.oauth2_credentials:find_all()
if err then
return err
end
for _, app in ipairs(apps) do
local redirect_uri = app.redirect_uri[1]
local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri.."' WHERE id='"..app.id.."'"
local _, err = factory.oauth2_credentials.db:queries(req)
if err then
return err
end
end
end
},
{
name = "2016-07-15-oauth2_code_credential_id",
up = [[
DELETE FROM oauth2_authorization_codes;
ALTER TABLE oauth2_authorization_codes ADD COLUMN credential_id uuid REFERENCES oauth2_credentials (id) ON DELETE CASCADE;
]],
down = [[
ALTER TABLE oauth2_authorization_codes DROP COLUMN credential_id;
]]
}
}
|
hotfix(oauth2) missing migration for postgres
|
hotfix(oauth2) missing migration for postgres
|
Lua
|
apache-2.0
|
Kong/kong,ccyphers/kong,icyxp/kong,li-wl/kong,salazar/kong,Mashape/kong,akh00/kong,jebenexer/kong,shiprabehera/kong,Kong/kong,Kong/kong
|
c483441208358fe98b1edbde033b7a958767f8ff
|
share/lua/sd/icecast.lua
|
share/lua/sd/icecast.lua
|
--[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Fabio Ritrovato <sephiroth87 at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
require "simplexml"
function descriptor()
return { title="Icecast Radio Directory" }
end
function main()
local tree = simplexml.parse_url("http://dir.xiph.org/yp.xml")
for _, station in ipairs( tree.children ) do
simplexml.add_name_maps( station )
local station_name = station.children_map["server_name"][1].children[1]
if station_name == "Unspecified name" or station_name == ""
then
station_name = station.children_map["listen_url"][1].children[1]
end
vlc.sd.add_item( {path=station.children_map["listen_url"][1].children[1],
title=station_name,
genre=station.children_map["genre"][1].children[1],
nowplaying=station.children_map["current_song"][1].children[1],
meta={
["Icecast Bitrate"]=station.children_map["bitrate"][1].children[1];
["Icecast Server Type"]=station.children_map["server_type"][1].children[1];
}} )
end
end
|
--[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Fabio Ritrovato <sephiroth87 at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
require "simplexml"
function descriptor()
return { title="Icecast Radio Directory" }
end
function main()
local tree = simplexml.parse_url("http://dir.xiph.org/yp.xml")
for _, station in ipairs( tree.children ) do
simplexml.add_name_maps( station )
local station_name = station.children_map["server_name"][1].children[1]
if station_name == "Unspecified name" or station_name == ""
then
station_name = station.children_map["listen_url"][1].children[1]
if string.find( station_name, "radionomy.com" )
then
station_name = string.match( station_name, "([^/]+)$")
station_name = string.gsub( station_name, "-", "\ " )
end
end
vlc.sd.add_item( {path=station.children_map["listen_url"][1].children[1],
title=station_name,
genre=station.children_map["genre"][1].children[1],
nowplaying=station.children_map["current_song"][1].children[1],
meta={
["Icecast Bitrate"]=station.children_map["bitrate"][1].children[1];
["Icecast Server Type"]=station.children_map["server_type"][1].children[1];
}} )
end
end
|
lua: icecast: can fix radionomy's station names
|
lua: icecast: can fix radionomy's station names
|
Lua
|
lgpl-2.1
|
xkfz007/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,jomanmuk/vlc-2.1,krichter722/vlc,vlc-mirror/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.2,krichter722/vlc,vlc-mirror/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,xkfz007/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,krichter722/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,shyamalschandra/vlc,krichter722/vlc,jomanmuk/vlc-2.2,xkfz007/vlc
|
7144c1d36ffef99c6563d2716e85a852142643ce
|
share/lua/sd/icecast.lua
|
share/lua/sd/icecast.lua
|
--[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Fabio Ritrovato <sephiroth87 at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
require "simplexml"
function descriptor()
return { title="Icecast Radio Directory" }
end
function main()
local tree = simplexml.parse_url("http://dir.xiph.org/yp.xml")
for _, station in ipairs( tree.children ) do
simplexml.add_name_maps( station )
local station_name = station.children_map["server_name"][1].children[1]
if station_name == "Unspecified name" or station_name == ""
then
station_name = station.children_map["listen_url"][1].children[1]
if string.find( station_name, "radionomy.com" )
then
station_name = string.match( station_name, "([^/]+)$")
station_name = string.gsub( station_name, "-", " " )
end
end
vlc.sd.add_item( {path=station.children_map["listen_url"][1].children[1],
title=station_name,
genre=station.children_map["genre"][1].children[1],
nowplaying=station.children_map["current_song"][1].children[1],
uiddata=station.children_map["listen_url"][1].children[1]
.. station.children_map["server_name"][1].children[1],
meta={
["Listing Source"]="dir.xiph.org",
["Listing Type"]="radio",
["Icecast Bitrate"]=station.children_map["bitrate"][1].children[1],
["Icecast Server Type"]=station.children_map["server_type"][1].children[1]
}} )
end
end
|
--[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Fabio Ritrovato <sephiroth87 at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
require "simplexml"
function descriptor()
return { title="Icecast Radio Directory" }
end
function dropnil(s)
if s == nil then return "" else return s end
end
function main()
local tree = simplexml.parse_url("http://dir.xiph.org/yp.xml")
for _, station in ipairs( tree.children ) do
simplexml.add_name_maps( station )
local station_name = station.children_map["server_name"][1].children[1]
if station_name == "Unspecified name" or station_name == "" or station_name == nil
then
station_name = station.children_map["listen_url"][1].children[1]
if string.find( station_name, "radionomy.com" )
then
station_name = string.match( station_name, "([^/]+)$")
station_name = string.gsub( station_name, "-", " " )
end
end
vlc.sd.add_item( {path=station.children_map["listen_url"][1].children[1],
title=station_name,
genre=dropnil(station.children_map["genre"][1].children[1]),
nowplaying=dropnil(station.children_map["current_song"][1].children[1]),
uiddata=station.children_map["listen_url"][1].children[1]
.. dropnil(station.children_map["server_name"][1].children[1]),
meta={
["Listing Source"]="dir.xiph.org",
["Listing Type"]="radio",
["Icecast Bitrate"]=dropnil(station.children_map["bitrate"][1].children[1]),
["Icecast Server Type"]=dropnil(station.children_map["server_type"][1].children[1])
}} )
end
end
|
lua: sd: strengthen icecast. (fix #8425)
|
lua: sd: strengthen icecast. (fix #8425)
XML is correct, but data is still random and full of junk...
|
Lua
|
lgpl-2.1
|
shyamalschandra/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,krichter722/vlc,vlc-mirror/vlc,xkfz007/vlc,shyamalschandra/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,krichter722/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,vlc-mirror/vlc,xkfz007/vlc,krichter722/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.1,krichter722/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,krichter722/vlc,xkfz007/vlc
|
c842b668b0ada4757aca0f7feccf041a24628b2b
|
contrib/package/olsrd-luci/files/lib/config/olsr.lua
|
contrib/package/olsrd-luci/files/lib/config/olsr.lua
|
#!/usr/bin/lua
--[[
OLSRd configuration generator
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.fs")
require("luci.util")
require("luci.model.uci")
local conf = luci.model.uci.get_all("olsr")
local function _value(val)
if val:match("^[0-9%. \t]+$") or val == "yes" or val == "no" then
return val
else
return string.format( '"%s"', val )
end
end
local function _section(sect,sval,parstr)
local rv = ""
local pad = ""
if sval then
rv = string.format( '%s "%s"\n{\n', conf[sect][".type"], conf[sect][sval] )
pad = "\t"
end
for k, v in luci.util.spairs(conf[sect]) do
if k:sub(1,1) ~= '.' and k ~= sval then
if parstr then
rv = rv .. string.format(
'%s%s "%s"\t"%s"\n',
pad, parstr,
k:gsub( "_", "-" ), -- XXX: find a better solution for this
v
)
else
rv = rv .. string.format(
'%s%s\t%s\n',
pad, k, _value(v)
)
end
end
end
if sval then
rv = rv .. "}\n"
end
return rv
end
local function _hna(sval)
local rv = string.format( "%s\n{\n", sval )
for k, v in luci.util.spairs(conf) do
if conf[k][".type"] == sval and conf[k].NetAddr and conf[k].Prefix then
rv = rv .. string.format(
"\t%s\t%s\n",
conf[k].NetAddr,
conf[k].Prefix
)
end
end
return rv .. "}\n"
end
local function _ipc(sval)
local rv = string.format( "%s\n{\n", sval )
for k, v in luci.util.spairs(conf[sval]) do
if k:sub(1,1) ~= "." then
local vals = luci.util.split(v, "%s+", nil, true)
if k == "Net" then
for i = 1,#vals,2 do
rv = rv .. string.format(
"\tNet\t%s\t%s\n",
vals[i], vals[i+1]
)
end
elseif k == "Host" then
for i, v in ipairs(vals) do
rv = rv .. string.format(
"\t%s\t%s\n",
k, vals[i]
)
end
else
rv = rv .. string.format(
"\t%s\t%s\n",
k, v
)
end
end
end
return rv .. "}\n"
end
-- general config section
print( _section("general") )
-- plugin config sections
for k, v in luci.util.spairs(conf) do
if conf[k][".type"] == "LoadPlugin" then
if v.Library and luci.fs.access("/usr/lib/"..v.Library) then
print( _section( k, "Library", "PlParam" ) )
end
end
end
-- interface config sections
for k, v in luci.util.spairs(conf) do
if conf[k][".type"] == "Interface" then
print( _section( k, "Interface" ) )
end
end
-- write Hna4, Hna6 sections
print( _hna("Hna4") )
print( _hna("Hna6") )
-- write IpcConnect section
print( _ipc("IpcConnect") )
|
#!/usr/bin/lua
--[[
OLSRd configuration generator
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.fs")
require("luci.util")
require("luci.model.uci")
local uci = luci.model.uci.cursor()
local conf = uci:get_all("olsr")
local function _value(val)
if val:match("^[0-9%. \t]+$") or val == "yes" or val == "no" then
return val
else
return string.format( '"%s"', val )
end
end
local function _section(sect,sval,parstr)
local rv = ""
local pad = ""
if sval then
if sval == "Interface" then
rv = string.format( 'Interface "%s"\n{\n', uci:get("network",conf[sect][sval],"ifname") )
else
rv = string.format( '%s "%s"\n{\n', conf[sect][".type"], conf[sect][sval] )
end
pad = "\t"
end
for k, v in luci.util.spairs(conf[sect]) do
if k:sub(1,1) ~= '.' and k ~= sval then
if parstr then
rv = rv .. string.format(
'%s%s "%s"\t"%s"\n',
pad, parstr,
k:gsub( "_", "-" ), -- XXX: find a better solution for this
v
)
else
rv = rv .. string.format(
'%s%s\t%s\n',
pad, k, _value(v)
)
end
end
end
if sval then
rv = rv .. "}\n"
end
return rv
end
local function _hna(sval)
local rv = string.format( "%s\n{\n", sval )
for k, v in luci.util.spairs(conf) do
if conf[k][".type"] == sval and conf[k].NetAddr and conf[k].Prefix then
rv = rv .. string.format(
"\t%s\t%s\n",
conf[k].NetAddr,
conf[k].Prefix
)
end
end
return rv .. "}\n"
end
local function _ipc(sval)
local rv = string.format( "%s\n{\n", sval )
for k, v in luci.util.spairs(conf[sval]) do
if k:sub(1,1) ~= "." then
local vals = luci.util.split(v, "%s+", nil, true)
if k == "Net" then
for i = 1,#vals,2 do
rv = rv .. string.format(
"\tNet\t%s\t%s\n",
vals[i], vals[i+1]
)
end
elseif k == "Host" then
for i, v in ipairs(vals) do
rv = rv .. string.format(
"\t%s\t%s\n",
k, vals[i]
)
end
else
rv = rv .. string.format(
"\t%s\t%s\n",
k, v
)
end
end
end
return rv .. "}\n"
end
-- general config section
print( _section("general") )
-- plugin config sections
for k, v in luci.util.spairs(conf) do
if conf[k][".type"] == "LoadPlugin" then
if v.Library and luci.fs.access("/usr/lib/"..v.Library) then
print( _section( k, "Library", "PlParam" ) )
end
end
end
-- interface config sections
for k, v in luci.util.spairs(conf) do
if conf[k][".type"] == "Interface" then
print( _section( k, "Interface" ) )
end
end
-- write Hna4, Hna6 sections
print( _hna("Hna4") )
print( _hna("Hna6") )
-- write IpcConnect section
print( _ipc("IpcConnect") )
|
* luci/contrib/olsrd-luci: adept config generator to new uci api and fix ifname in interface sections
|
* luci/contrib/olsrd-luci: adept config generator to new uci api and fix ifname in interface sections
|
Lua
|
apache-2.0
|
forward619/luci,Noltari/luci,teslamint/luci,jchuang1977/luci-1,keyidadi/luci,Wedmer/luci,palmettos/cnLuCI,keyidadi/luci,MinFu/luci,cshore/luci,bright-things/ionic-luci,RuiChen1113/luci,ollie27/openwrt_luci,nmav/luci,dismantl/luci-0.12,LazyZhu/openwrt-luci-trunk-mod,NeoRaider/luci,openwrt/luci,bittorf/luci,obsy/luci,remakeelectric/luci,mumuqz/luci,981213/luci-1,lbthomsen/openwrt-luci,ReclaimYourPrivacy/cloak-luci,male-puppies/luci,cappiewu/luci,mumuqz/luci,dwmw2/luci,harveyhu2012/luci,remakeelectric/luci,Kyklas/luci-proto-hso,oneru/luci,dwmw2/luci,ReclaimYourPrivacy/cloak-luci,openwrt-es/openwrt-luci,jlopenwrtluci/luci,jorgifumi/luci,kuoruan/lede-luci,palmettos/cnLuCI,981213/luci-1,ollie27/openwrt_luci,jorgifumi/luci,Hostle/luci,Hostle/luci,bright-things/ionic-luci,forward619/luci,dwmw2/luci,slayerrensky/luci,rogerpueyo/luci,deepak78/new-luci,sujeet14108/luci,MinFu/luci,jchuang1977/luci-1,bittorf/luci,keyidadi/luci,chris5560/openwrt-luci,Wedmer/luci,schidler/ionic-luci,oyido/luci,Wedmer/luci,urueedi/luci,NeoRaider/luci,Hostle/luci,RedSnake64/openwrt-luci-packages,dwmw2/luci,openwrt-es/openwrt-luci,RuiChen1113/luci,marcel-sch/luci,artynet/luci,deepak78/new-luci,oneru/luci,Sakura-Winkey/LuCI,palmettos/test,daofeng2015/luci,hnyman/luci,mumuqz/luci,urueedi/luci,dismantl/luci-0.12,dwmw2/luci,shangjiyu/luci-with-extra,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,florian-shellfire/luci,deepak78/new-luci,obsy/luci,david-xiao/luci,thesabbir/luci,david-xiao/luci,rogerpueyo/luci,cshore-firmware/openwrt-luci,RuiChen1113/luci,daofeng2015/luci,wongsyrone/luci-1,male-puppies/luci,wongsyrone/luci-1,jlopenwrtluci/luci,daofeng2015/luci,oneru/luci,palmettos/cnLuCI,Sakura-Winkey/LuCI,Wedmer/luci,thesabbir/luci,thesabbir/luci,kuoruan/lede-luci,rogerpueyo/luci,RedSnake64/openwrt-luci-packages,sujeet14108/luci,LazyZhu/openwrt-luci-trunk-mod,Noltari/luci,aircross/OpenWrt-Firefly-LuCI,daofeng2015/luci,opentechinstitute/luci,chris5560/openwrt-luci,schidler/ionic-luci,urueedi/luci,dwmw2/luci,RuiChen1113/luci,wongsyrone/luci-1,nmav/luci,ReclaimYourPrivacy/cloak-luci,fkooman/luci,db260179/openwrt-bpi-r1-luci,ff94315/luci-1,lbthomsen/openwrt-luci,LuttyYang/luci,david-xiao/luci,dismantl/luci-0.12,oyido/luci,tcatm/luci,Kyklas/luci-proto-hso,marcel-sch/luci,palmettos/test,florian-shellfire/luci,lbthomsen/openwrt-luci,slayerrensky/luci,jlopenwrtluci/luci,chris5560/openwrt-luci,zhaoxx063/luci,florian-shellfire/luci,hnyman/luci,wongsyrone/luci-1,opentechinstitute/luci,NeoRaider/luci,ReclaimYourPrivacy/cloak-luci,joaofvieira/luci,schidler/ionic-luci,marcel-sch/luci,rogerpueyo/luci,nmav/luci,ff94315/luci-1,marcel-sch/luci,harveyhu2012/luci,LuttyYang/luci,palmettos/cnLuCI,lcf258/openwrtcn,Noltari/luci,harveyhu2012/luci,LuttyYang/luci,Wedmer/luci,lbthomsen/openwrt-luci,jorgifumi/luci,oyido/luci,joaofvieira/luci,schidler/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,Noltari/luci,taiha/luci,remakeelectric/luci,thesabbir/luci,cappiewu/luci,tobiaswaldvogel/luci,slayerrensky/luci,teslamint/luci,nwf/openwrt-luci,shangjiyu/luci-with-extra,Wedmer/luci,schidler/ionic-luci,forward619/luci,chris5560/openwrt-luci,forward619/luci,ollie27/openwrt_luci,florian-shellfire/luci,cshore/luci,david-xiao/luci,schidler/ionic-luci,male-puppies/luci,aa65535/luci,remakeelectric/luci,nwf/openwrt-luci,bright-things/ionic-luci,chris5560/openwrt-luci,obsy/luci,LuttyYang/luci,chris5560/openwrt-luci,openwrt/luci,openwrt/luci,ollie27/openwrt_luci,tcatm/luci,nmav/luci,fkooman/luci,oneru/luci,zhaoxx063/luci,slayerrensky/luci,deepak78/new-luci,kuoruan/lede-luci,harveyhu2012/luci,LazyZhu/openwrt-luci-trunk-mod,db260179/openwrt-bpi-r1-luci,fkooman/luci,palmettos/test,rogerpueyo/luci,palmettos/test,maxrio/luci981213,jlopenwrtluci/luci,teslamint/luci,hnyman/luci,cshore/luci,lcf258/openwrtcn,mumuqz/luci,taiha/luci,jorgifumi/luci,forward619/luci,openwrt-es/openwrt-luci,deepak78/new-luci,tcatm/luci,oyido/luci,maxrio/luci981213,male-puppies/luci,db260179/openwrt-bpi-r1-luci,chris5560/openwrt-luci,aa65535/luci,openwrt/luci,keyidadi/luci,remakeelectric/luci,tobiaswaldvogel/luci,NeoRaider/luci,shangjiyu/luci-with-extra,MinFu/luci,harveyhu2012/luci,cshore-firmware/openwrt-luci,deepak78/new-luci,kuoruan/lede-luci,bright-things/ionic-luci,wongsyrone/luci-1,mumuqz/luci,marcel-sch/luci,cshore-firmware/openwrt-luci,MinFu/luci,jchuang1977/luci-1,shangjiyu/luci-with-extra,Hostle/luci,thess/OpenWrt-luci,deepak78/new-luci,fkooman/luci,Hostle/luci,sujeet14108/luci,RedSnake64/openwrt-luci-packages,harveyhu2012/luci,openwrt-es/openwrt-luci,sujeet14108/luci,david-xiao/luci,nwf/openwrt-luci,kuoruan/luci,mumuqz/luci,shangjiyu/luci-with-extra,zhaoxx063/luci,opentechinstitute/luci,keyidadi/luci,palmettos/test,kuoruan/lede-luci,Kyklas/luci-proto-hso,ff94315/luci-1,cshore/luci,hnyman/luci,MinFu/luci,dismantl/luci-0.12,slayerrensky/luci,zhaoxx063/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,hnyman/luci,jchuang1977/luci-1,male-puppies/luci,Noltari/luci,Hostle/openwrt-luci-multi-user,lcf258/openwrtcn,ollie27/openwrt_luci,RuiChen1113/luci,rogerpueyo/luci,aa65535/luci,oyido/luci,jlopenwrtluci/luci,tcatm/luci,maxrio/luci981213,kuoruan/luci,marcel-sch/luci,teslamint/luci,dismantl/luci-0.12,sujeet14108/luci,joaofvieira/luci,sujeet14108/luci,openwrt/luci,nmav/luci,male-puppies/luci,teslamint/luci,kuoruan/lede-luci,aircross/OpenWrt-Firefly-LuCI,palmettos/test,maxrio/luci981213,david-xiao/luci,Noltari/luci,palmettos/cnLuCI,kuoruan/luci,Sakura-Winkey/LuCI,remakeelectric/luci,shangjiyu/luci-with-extra,Hostle/openwrt-luci-multi-user,zhaoxx063/luci,chris5560/openwrt-luci,Hostle/luci,dismantl/luci-0.12,urueedi/luci,db260179/openwrt-bpi-r1-luci,NeoRaider/luci,shangjiyu/luci-with-extra,tobiaswaldvogel/luci,palmettos/cnLuCI,cshore-firmware/openwrt-luci,maxrio/luci981213,lcf258/openwrtcn,Hostle/openwrt-luci-multi-user,lcf258/openwrtcn,oyido/luci,cappiewu/luci,Sakura-Winkey/LuCI,Kyklas/luci-proto-hso,cshore-firmware/openwrt-luci,kuoruan/luci,artynet/luci,obsy/luci,Hostle/openwrt-luci-multi-user,Noltari/luci,Noltari/luci,nmav/luci,wongsyrone/luci-1,cappiewu/luci,kuoruan/lede-luci,ff94315/luci-1,tcatm/luci,cshore-firmware/openwrt-luci,sujeet14108/luci,obsy/luci,bright-things/ionic-luci,slayerrensky/luci,florian-shellfire/luci,jorgifumi/luci,bright-things/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,jchuang1977/luci-1,kuoruan/luci,sujeet14108/luci,aa65535/luci,openwrt/luci,Hostle/luci,rogerpueyo/luci,joaofvieira/luci,tcatm/luci,tobiaswaldvogel/luci,981213/luci-1,keyidadi/luci,maxrio/luci981213,thess/OpenWrt-luci,thess/OpenWrt-luci,nmav/luci,opentechinstitute/luci,hnyman/luci,tobiaswaldvogel/luci,rogerpueyo/luci,artynet/luci,dwmw2/luci,florian-shellfire/luci,fkooman/luci,hnyman/luci,palmettos/cnLuCI,thesabbir/luci,Wedmer/luci,Kyklas/luci-proto-hso,urueedi/luci,cshore-firmware/openwrt-luci,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,openwrt-es/openwrt-luci,thess/OpenWrt-luci,bittorf/luci,tobiaswaldvogel/luci,ollie27/openwrt_luci,nwf/openwrt-luci,ReclaimYourPrivacy/cloak-luci,jorgifumi/luci,hnyman/luci,mumuqz/luci,marcel-sch/luci,zhaoxx063/luci,aa65535/luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,dismantl/luci-0.12,obsy/luci,daofeng2015/luci,lcf258/openwrtcn,palmettos/cnLuCI,artynet/luci,LazyZhu/openwrt-luci-trunk-mod,fkooman/luci,obsy/luci,artynet/luci,lbthomsen/openwrt-luci,urueedi/luci,ff94315/luci-1,aircross/OpenWrt-Firefly-LuCI,thess/OpenWrt-luci,Kyklas/luci-proto-hso,zhaoxx063/luci,981213/luci-1,ff94315/luci-1,aircross/OpenWrt-Firefly-LuCI,bittorf/luci,thesabbir/luci,Hostle/openwrt-luci-multi-user,kuoruan/luci,forward619/luci,shangjiyu/luci-with-extra,tobiaswaldvogel/luci,jorgifumi/luci,ff94315/luci-1,urueedi/luci,NeoRaider/luci,opentechinstitute/luci,RedSnake64/openwrt-luci-packages,florian-shellfire/luci,cappiewu/luci,forward619/luci,thess/OpenWrt-luci,keyidadi/luci,ollie27/openwrt_luci,daofeng2015/luci,kuoruan/lede-luci,aa65535/luci,lcf258/openwrtcn,deepak78/new-luci,lbthomsen/openwrt-luci,male-puppies/luci,taiha/luci,jorgifumi/luci,cappiewu/luci,joaofvieira/luci,ff94315/luci-1,aircross/OpenWrt-Firefly-LuCI,openwrt/luci,ollie27/openwrt_luci,nwf/openwrt-luci,slayerrensky/luci,artynet/luci,thesabbir/luci,LuttyYang/luci,joaofvieira/luci,bittorf/luci,LuttyYang/luci,jchuang1977/luci-1,openwrt-es/openwrt-luci,keyidadi/luci,cshore/luci,LazyZhu/openwrt-luci-trunk-mod,joaofvieira/luci,nmav/luci,aircross/OpenWrt-Firefly-LuCI,wongsyrone/luci-1,jlopenwrtluci/luci,forward619/luci,opentechinstitute/luci,thess/OpenWrt-luci,taiha/luci,urueedi/luci,aircross/OpenWrt-Firefly-LuCI,Hostle/luci,oyido/luci,fkooman/luci,oneru/luci,nwf/openwrt-luci,bright-things/ionic-luci,opentechinstitute/luci,remakeelectric/luci,florian-shellfire/luci,thess/OpenWrt-luci,LazyZhu/openwrt-luci-trunk-mod,tcatm/luci,ReclaimYourPrivacy/cloak-luci,artynet/luci,LuttyYang/luci,harveyhu2012/luci,Hostle/openwrt-luci-multi-user,oneru/luci,tcatm/luci,Hostle/openwrt-luci-multi-user,taiha/luci,obsy/luci,981213/luci-1,jchuang1977/luci-1,schidler/ionic-luci,thesabbir/luci,remakeelectric/luci,male-puppies/luci,cshore/luci,lbthomsen/openwrt-luci,daofeng2015/luci,wongsyrone/luci-1,NeoRaider/luci,oyido/luci,jchuang1977/luci-1,artynet/luci,cshore/luci,nmav/luci,taiha/luci,kuoruan/luci,981213/luci-1,palmettos/test,MinFu/luci,teslamint/luci,teslamint/luci,db260179/openwrt-bpi-r1-luci,Wedmer/luci,MinFu/luci,cappiewu/luci,maxrio/luci981213,bittorf/luci,MinFu/luci,cshore/luci,slayerrensky/luci,zhaoxx063/luci,cshore-firmware/openwrt-luci,lcf258/openwrtcn,nwf/openwrt-luci,RedSnake64/openwrt-luci-packages,RuiChen1113/luci,david-xiao/luci,jlopenwrtluci/luci,aa65535/luci,artynet/luci,jlopenwrtluci/luci,Kyklas/luci-proto-hso,Hostle/openwrt-luci-multi-user,fkooman/luci,mumuqz/luci,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,maxrio/luci981213,openwrt-es/openwrt-luci,marcel-sch/luci,palmettos/test,bittorf/luci,oneru/luci,nwf/openwrt-luci,kuoruan/luci,RedSnake64/openwrt-luci-packages,lbthomsen/openwrt-luci,lcf258/openwrtcn,Noltari/luci,openwrt/luci,ReclaimYourPrivacy/cloak-luci,lcf258/openwrtcn,981213/luci-1,taiha/luci,aa65535/luci,LuttyYang/luci,taiha/luci,daofeng2015/luci,bittorf/luci,Sakura-Winkey/LuCI,bright-things/ionic-luci,ReclaimYourPrivacy/cloak-luci,NeoRaider/luci,oneru/luci,schidler/ionic-luci,cappiewu/luci,joaofvieira/luci,dwmw2/luci,opentechinstitute/luci,david-xiao/luci,teslamint/luci
|
1121e2885a43e01766b0aa179fdc97be8b873afe
|
modules/admin-full/luasrc/model/cbi/admin_network/hosts.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/hosts.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
require("luci.util")
m = Map("dhcp", translate("Hostnames"))
s = m:section(TypedSection, "domain", translate("Host entries"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
hn = s:option(Value, "name", translate("Hostname"))
hn.datatype = "hostname"
hn.rmempty = true
ip = s:option(Value, "ip", translate("IP address"))
ip.datatype = "ipaddr"
ip.rmempty = true
for i, dataset in ipairs(luci.sys.net.arptable()) do
ip:value(
dataset["IP address"],
"%s (%s)" %{ dataset["IP address"], dataset["HW address"] }
)
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
require("luci.util")
m = Map("dhcp", translate("Hostnames"))
s = m:section(TypedSection, "domain", translate("Host entries"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
hn = s:option(Value, "name", translate("Hostname"))
hn.datatype = "hostname"
hn.rmempty = true
ip = s:option(Value, "ip", translate("IP address"))
ip.datatype = "ipaddr"
ip.rmempty = true
local arptable = luci.sys.net.arptable() or {}
for i, dataset in ipairs(arptable) do
ip:value(
dataset["IP address"],
"%s (%s)" %{ dataset["IP address"], dataset["HW address"] }
)
end
return m
|
admin-full/network/hosts: Fix problem when arptable is empty, #482
|
admin-full/network/hosts: Fix problem when arptable is empty, #482
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@9416 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
ch3n2k/luci,phi-psi/luci,eugenesan/openwrt-luci,phi-psi/luci,zwhfly/openwrt-luci,ch3n2k/luci,vhpham80/luci,zwhfly/openwrt-luci,vhpham80/luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,ch3n2k/luci,8devices/carambola2-luci,yeewang/openwrt-luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,gwlim/luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,vhpham80/luci,Canaan-Creative/luci,Canaan-Creative/luci,ch3n2k/luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,Canaan-Creative/luci,vhpham80/luci,Canaan-Creative/luci,ch3n2k/luci,yeewang/openwrt-luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,phi-psi/luci,eugenesan/openwrt-luci,gwlim/luci,8devices/carambola2-luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,phi-psi/luci,gwlim/luci,ch3n2k/luci,phi-psi/luci,ThingMesh/openwrt-luci,ch3n2k/luci,gwlim/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,Canaan-Creative/luci,zwhfly/openwrt-luci,gwlim/luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,phi-psi/luci
|
7b5e62b8960715ac4fafcf627242ae48db6dc95e
|
service/clusterd.lua
|
service/clusterd.lua
|
local skynet = require "skynet"
local sc = require "socketchannel"
local socket = require "socket"
local cluster = require "cluster.c"
local config_name = skynet.getenv "cluster"
local node_address = {}
local function loadconfig()
local f = assert(io.open(config_name))
local source = f:read "*a"
f:close()
assert(load(source, "@"..config_name, "t", node_address))()
end
local node_session = {}
local command = {}
local function read_response(sock)
local sz = socket.header(sock:read(2))
local msg = sock:read(sz)
return cluster.unpackresponse(msg) -- session, ok, data
end
local function open_channel(t, key)
local host, port = string.match(node_address[key], "([^:]+):(.*)$")
local c = sc.channel {
host = host,
port = tonumber(port),
response = read_response,
}
assert(c:connect(true))
t[key] = c
node_session[key] = 1
return c
end
local node_channel = setmetatable({}, { __index = open_channel })
function command.reload()
loadconfig()
skynet.ret(skynet.pack(nil))
end
function command.listen(source, addr, port)
local gate = skynet.newservice("gate")
if port == nil then
addr, port = string.match(node_address[addr], "([^:]+):(.*)$")
end
skynet.call(gate, "lua", "open", { address = addr, port = port })
skynet.ret(skynet.pack(nil))
end
function command.req(source, node, addr, msg, sz)
local request
local c = node_channel[node]
local session = node_session[node]
-- msg is a local pointer, cluster.packrequest will free it
request, node_session[node] = cluster.packrequest(addr, session , msg, sz)
local ok, result = pcall(c.request, c, request, session)
skynet.ret(c:request(request, session))
end
local request_fd = {}
function command.socket(source, subcmd, fd, msg)
if subcmd == "data" then
local addr, session, msg = cluster.unpackrequest(msg)
local ok , msg, sz = pcall(skynet.rawcall, addr, "lua", msg)
local response
if ok then
response = cluster.packresponse(session, true, msg, sz)
else
response = cluster.packresponse(session, false, msg)
end
socket.write(fd, response)
elseif subcmd == "open" then
skynet.error(string.format("socket accept from %s", msg))
skynet.call(source, "lua", "accept", fd)
else
skynet.error(string.format("socket %s %d : %s", subcmd, fd, msg))
end
end
skynet.start(function()
loadconfig()
skynet.dispatch("lua", function(session , source, cmd, ...)
local f = assert(command[cmd])
f(source, ...)
end)
end)
|
local skynet = require "skynet"
local sc = require "socketchannel"
local socket = require "socket"
local cluster = require "cluster.c"
local config_name = skynet.getenv "cluster"
local node_address = {}
local function loadconfig()
local f = assert(io.open(config_name))
local source = f:read "*a"
f:close()
assert(load(source, "@"..config_name, "t", node_address))()
end
local node_session = {}
local command = {}
local function read_response(sock)
local sz = socket.header(sock:read(2))
local msg = sock:read(sz)
return cluster.unpackresponse(msg) -- session, ok, data
end
local function open_channel(t, key)
local host, port = string.match(node_address[key], "([^:]+):(.*)$")
local c = sc.channel {
host = host,
port = tonumber(port),
response = read_response,
}
assert(c:connect(true))
t[key] = c
node_session[key] = 1
return c
end
local node_channel = setmetatable({}, { __index = open_channel })
function command.reload()
loadconfig()
skynet.ret(skynet.pack(nil))
end
function command.listen(source, addr, port)
local gate = skynet.newservice("gate")
if port == nil then
addr, port = string.match(node_address[addr], "([^:]+):(.*)$")
end
skynet.call(gate, "lua", "open", { address = addr, port = port })
skynet.ret(skynet.pack(nil))
end
function command.req(source, node, addr, msg, sz)
local request
local c = node_channel[node]
local session = node_session[node]
-- msg is a local pointer, cluster.packrequest will free it
request, node_session[node] = cluster.packrequest(addr, session , msg, sz)
skynet.ret(c:request(request, session))
end
local request_fd = {}
function command.socket(source, subcmd, fd, msg)
if subcmd == "data" then
local addr, session, msg = cluster.unpackrequest(msg)
local ok , msg, sz = pcall(skynet.rawcall, addr, "lua", msg)
local response
if ok then
response = cluster.packresponse(session, true, msg, sz)
else
response = cluster.packresponse(session, false, msg)
end
socket.write(fd, response)
elseif subcmd == "open" then
skynet.error(string.format("socket accept from %s", msg))
skynet.call(source, "lua", "accept", fd)
else
skynet.error(string.format("socket %s %d : %s", subcmd, fd, msg))
end
end
skynet.start(function()
loadconfig()
skynet.dispatch("lua", function(session , source, cmd, ...)
local f = assert(command[cmd])
f(source, ...)
end)
end)
|
fix typo
|
fix typo
|
Lua
|
mit
|
ilylia/skynet,lc412/skynet,qyli/test,microcai/skynet,yinjun322/skynet,zhaijialong/skynet,felixdae/skynet,catinred2/skynet,lawnight/skynet,gitfancode/skynet,qyli/test,cuit-zhaxin/skynet,Markal128/skynet,ypengju/skynet_comment,cpascal/skynet,cuit-zhaxin/skynet,cdd990/skynet,yinjun322/skynet,gitfancode/skynet,zhaijialong/skynet,MoZhonghua/skynet,czlc/skynet,microcai/skynet,chfg007/skynet,iskygame/skynet,great90/skynet,zhouxiaoxiaoxujian/skynet,KAndQ/skynet,zzh442856860/skynet-Note,cmingjian/skynet,zhangshiqian1214/skynet,bigrpg/skynet,JiessieDawn/skynet,lynx-seu/skynet,your-gatsby/skynet,iskygame/skynet,codingabc/skynet,javachengwc/skynet,harryzeng/skynet,zzh442856860/skynet-Note,ypengju/skynet_comment,winglsh/skynet,ruleless/skynet,rainfiel/skynet,puXiaoyi/skynet,lawnight/skynet,helling34/skynet,chenjiansnail/skynet,zhoukk/skynet,zhangshiqian1214/skynet,boyuegame/skynet,fhaoquan/skynet,QuiQiJingFeng/skynet,leezhongshan/skynet,kebo/skynet,codingabc/skynet,zhangshiqian1214/skynet,bttscut/skynet,fztcjjl/skynet,chenjiansnail/skynet,wangyi0226/skynet,ilylia/skynet,togolwb/skynet,chuenlungwang/skynet,korialuo/skynet,korialuo/skynet,samael65535/skynet,ludi1991/skynet,sanikoyes/skynet,microcai/skynet,liuxuezhan/skynet,your-gatsby/skynet,MetSystem/skynet,harryzeng/skynet,pigparadise/skynet,pigparadise/skynet,iskygame/skynet,JiessieDawn/skynet,letmefly/skynet,Markal128/skynet,yunGit/skynet,asanosoyokaze/skynet,hongling0/skynet,dymx101/skynet,liuxuezhan/skynet,liuxuezhan/skynet,xinjuncoding/skynet,enulex/skynet,letmefly/skynet,ludi1991/skynet,ag6ag/skynet,LuffyPan/skynet,ypengju/skynet_comment,KAndQ/skynet,lynx-seu/skynet,puXiaoyi/skynet,asanosoyokaze/skynet,helling34/skynet,wangyi0226/skynet,bingo235/skynet,wangjunwei01/skynet,u20024804/skynet,jxlczjp77/skynet,bigrpg/skynet,xjdrew/skynet,sundream/skynet,xinjuncoding/skynet,chuenlungwang/skynet,ruleless/skynet,lawnight/skynet,longmian/skynet,cpascal/skynet,zzh442856860/skynet,xcjmine/skynet,bingo235/skynet,chenjiansnail/skynet,MetSystem/skynet,ag6ag/skynet,Zirpon/skynet,zhaijialong/skynet,zhouxiaoxiaoxujian/skynet,KittyCookie/skynet,cmingjian/skynet,felixdae/skynet,jxlczjp77/skynet,leezhongshan/skynet,sdgdsffdsfff/skynet,vizewang/skynet,javachengwc/skynet,puXiaoyi/skynet,jiuaiwo1314/skynet,plsytj/skynet,xinmingyao/skynet,LiangMa/skynet,korialuo/skynet,rainfiel/skynet,cloudwu/skynet,xubigshu/skynet,ag6ag/skynet,vizewang/skynet,vizewang/skynet,JiessieDawn/skynet,catinred2/skynet,zhoukk/skynet,asanosoyokaze/skynet,winglsh/skynet,fhaoquan/skynet,enulex/skynet,bingo235/skynet,icetoggle/skynet,hongling0/skynet,kyle-wang/skynet,dymx101/skynet,cloudwu/skynet,sdgdsffdsfff/skynet,winglsh/skynet,cdd990/skynet,sundream/skynet,MoZhonghua/skynet,firedtoad/skynet,QuiQiJingFeng/skynet,cpascal/skynet,czlc/skynet,kebo/skynet,Zirpon/skynet,firedtoad/skynet,LiangMa/skynet,LuffyPan/skynet,nightcj/mmo,boyuegame/skynet,xcjmine/skynet,KAndQ/skynet,ludi1991/skynet,matinJ/skynet,felixdae/skynet,samael65535/skynet,lc412/skynet,jiuaiwo1314/skynet,MoZhonghua/skynet,zhoukk/skynet,yinjun322/skynet,chfg007/skynet,wangjunwei01/skynet,sanikoyes/skynet,ruleless/skynet,MRunFoss/skynet,icetoggle/skynet,chuenlungwang/skynet,rainfiel/skynet,chfg007/skynet,yunGit/skynet,MRunFoss/skynet,zzh442856860/skynet-Note,Markal128/skynet,javachengwc/skynet,xcjmine/skynet,leezhongshan/skynet,Ding8222/skynet,cdd990/skynet,zhangshiqian1214/skynet,qyli/test,LuffyPan/skynet,togolwb/skynet,nightcj/mmo,cloudwu/skynet,helling34/skynet,fztcjjl/skynet,matinJ/skynet,zhouxiaoxiaoxujian/skynet,pichina/skynet,sanikoyes/skynet,LiangMa/skynet,yunGit/skynet,QuiQiJingFeng/skynet,letmefly/skynet,harryzeng/skynet,dymx101/skynet,ilylia/skynet,czlc/skynet,bttscut/skynet,MetSystem/skynet,jxlczjp77/skynet,great90/skynet,fhaoquan/skynet,firedtoad/skynet,xinjuncoding/skynet,togolwb/skynet,pigparadise/skynet,longmian/skynet,xjdrew/skynet,nightcj/mmo,wangyi0226/skynet,zzh442856860/skynet,liuxuezhan/skynet,u20024804/skynet,zhangshiqian1214/skynet,pichina/skynet,cmingjian/skynet,plsytj/skynet,Zirpon/skynet,kebo/skynet,boyuegame/skynet,qyli/test,pichina/skynet,xubigshu/skynet,catinred2/skynet,xjdrew/skynet,MRunFoss/skynet,plsytj/skynet,codingabc/skynet,your-gatsby/skynet,fztcjjl/skynet,KittyCookie/skynet,icetoggle/skynet,lc412/skynet,Ding8222/skynet,ludi1991/skynet,gitfancode/skynet,hongling0/skynet,kyle-wang/skynet,great90/skynet,zzh442856860/skynet-Note,zzh442856860/skynet,samael65535/skynet,zhangshiqian1214/skynet,xinmingyao/skynet,kyle-wang/skynet,sdgdsffdsfff/skynet,longmian/skynet,jiuaiwo1314/skynet,sundream/skynet,bttscut/skynet,KittyCookie/skynet,Ding8222/skynet,wangjunwei01/skynet,letmefly/skynet,lynx-seu/skynet,cuit-zhaxin/skynet,enulex/skynet,lawnight/skynet,u20024804/skynet,matinJ/skynet,bigrpg/skynet
|
791d540a5a8b9397a12f50d555832a8d49bdba70
|
frontend/apps/filemanager/filemanagerfilesearcher.lua
|
frontend/apps/filemanager/filemanagerfilesearcher.lua
|
local CenterContainer = require("ui/widget/container/centercontainer")
local InputContainer = require("ui/widget/container/inputcontainer")
local DocumentRegistry = require("document/documentregistry")
local InputDialog = require("ui/widget/inputdialog")
local InfoMessage = require("ui/widget/infomessage")
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Menu = require("ui/widget/menu")
local Screen = require("device").screen
local util = require("ffi/util")
local Font = require("ui/font")
local DEBUG = require("dbg")
local _ = require("gettext")
local FileSearcher = InputContainer:new{
search_dialog = nil,
--filesearcher
-- state buffer
dirs = {},
files = {},
results = {},
items = 0,
commands = nil,
--filemanagersearch
use_previous_search_results = false,
lastsearch = nil,
}
function FileSearcher:readDir()
self.dirs = {self.path}
DEBUG("self.path", self.path)
self.files = {}
while #self.dirs ~= 0 do
local new_dirs = {}
-- handle each dir
for __, d in pairs(self.dirs) do
-- handle files in d
for f in lfs.dir(d) do
local fullpath = d.."/"..f
local attributes = lfs.attributes(fullpath)
if attributes.mode == "directory" and f ~= "." and f~=".." then
table.insert(new_dirs, fullpath)
table.insert(self.files, {name = f, path = fullpath, attr = attributes})
elseif attributes.mode == "file" and DocumentRegistry:getProvider(fullpath) then
table.insert(self.files, {name = f, path = fullpath, attr = attributes})
end
end
end
self.dirs = new_dirs
end
end
function FileSearcher:setSearchResults()
local FileManager = require("apps/filemanager/filemanager")
local ReaderUI = require("apps/reader/readerui")
local keywords = self.search_value
--DEBUG("self.files", self.files)
self.results = {}
if keywords == " " then -- one space to show all files
self.results = self.files
else
for __,f in pairs(self.files) do
DEBUG("f", f)
if string.find(string.lower(f.name), string.lower(keywords)) then
if f.attr.mode == "directory" then
f.text = f.name.."/"
f.name = nil
f.callback = function()
FileManager:showFiles(f.path)
end
table.insert(self.results, f)
else
f.text = f.name
f.name = nil
f.callback = function()
ReaderUI:showReader(f.path)
end
table.insert(self.results, f)
end
end
end
end
--DEBUG("self.results", self.results)
self.keywords = keywords
self.items = #self.results
end
function FileSearcher:init(search_path)
self.path = search_path or lfs.currentdir()
self:showSearch()
end
function FileSearcher:close()
if self.search_value then
UIManager:close(self.search_dialog)
if string.len(self.search_value) > 0 then
self:readDir() -- TODO this probably doesn't need to be repeated once it's been done
self:setSearchResults() -- TODO doesn't have to be repeated if the search term is the same
if #self.results > 0 then
self:showSearchResults() -- TODO something about no results
else
UIManager:show(
InfoMessage:new{
text = util.template(_("Found no files matching '%1'."), self.search_value)
}
)
end
end
end
end
function FileSearcher:showSearch()
local dummy = self.search_value
self.search_dialog = InputDialog:new{
title = _("Search for books by filename"),
input = self.search_value,
buttons = {
{
{
text = _("Cancel"),
enabled = true,
callback = function()
self.search_dialog:onClose()
UIManager:close(self.search_dialog)
end,
},
{
text = _("Find books"),
enabled = true,
callback = function()
self.search_value = self.search_dialog:getInputText()
if self.search_value == dummy then -- probably DELETE this if/else block
self.use_previous_search_results = true
else
self.use_previous_search_results = false
end
self:close()
end,
},
},
},
}
self.search_dialog:onShowKeyboard()
UIManager:show(self.search_dialog)
end
function FileSearcher:showSearchResults()
local menu_container = CenterContainer:new{
dimen = Screen:getSize(),
}
self.search_menu = Menu:new{
width = Screen:getWidth()-15,
height = Screen:getHeight()-15,
show_parent = menu_container,
onMenuHold = self.onMenuHold,
cface = Font:getFace("cfont", 22),
_manager = self,
}
table.insert(menu_container, self.search_menu)
self.search_menu.close_callback = function()
UIManager:close(menu_container)
end
table.sort(self.results, function(v1,v2) return v1.text < v2.text end)
self.search_menu:switchItemTable(_("Search Results"), self.results)
UIManager:show(menu_container)
end
return FileSearcher
|
local CenterContainer = require("ui/widget/container/centercontainer")
local InputContainer = require("ui/widget/container/inputcontainer")
local DocumentRegistry = require("document/documentregistry")
local InputDialog = require("ui/widget/inputdialog")
local InfoMessage = require("ui/widget/infomessage")
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Menu = require("ui/widget/menu")
local Screen = require("device").screen
local util = require("ffi/util")
local Font = require("ui/font")
local DEBUG = require("dbg")
local _ = require("gettext")
local FileSearcher = InputContainer:new{
search_dialog = nil,
--filesearcher
-- state buffer
dirs = {},
files = {},
results = {},
items = 0,
commands = nil,
--filemanagersearch
use_previous_search_results = false,
lastsearch = nil,
}
function FileSearcher:readDir()
self.dirs = {self.path}
DEBUG("self.path", self.path)
self.files = {}
while #self.dirs ~= 0 do
local new_dirs = {}
-- handle each dir
for __, d in pairs(self.dirs) do
-- handle files in d
for f in lfs.dir(d) do
local fullpath = d.."/"..f
local attributes = lfs.attributes(fullpath)
if attributes.mode == "directory" and f ~= "." and f~=".." then
table.insert(new_dirs, fullpath)
table.insert(self.files, {name = f, path = fullpath, attr = attributes})
elseif attributes.mode == "file" and DocumentRegistry:getProvider(fullpath) then
table.insert(self.files, {name = f, path = fullpath, attr = attributes})
end
end
end
self.dirs = new_dirs
end
end
function FileSearcher:setSearchResults()
local FileManager = require("apps/filemanager/filemanager")
local ReaderUI = require("apps/reader/readerui")
local keywords = self.search_value
--DEBUG("self.files", self.files)
self.results = {}
if keywords == " " then -- one space to show all files
self.results = self.files
else
for __,f in pairs(self.files) do
--DEBUG("f", f)
if string.find(string.lower(f.name), string.lower(keywords)) and string.sub(f.name,-4) ~= ".sdr" then
if f.attr.mode == "directory" then
f.text = f.name.."/"
f.name = nil
f.callback = function()
FileManager:showFiles(f.path)
end
table.insert(self.results, f)
else
f.text = f.name
f.name = nil
f.callback = function()
ReaderUI:showReader(f.path)
end
table.insert(self.results, f)
end
end
end
end
--DEBUG("self.results", self.results)
self.keywords = keywords
self.items = #self.results
end
function FileSearcher:init(search_path)
self.path = search_path or lfs.currentdir()
self:showSearch()
end
function FileSearcher:close()
if self.search_value then
UIManager:close(self.search_dialog)
if string.len(self.search_value) > 0 then
self:readDir() -- TODO this probably doesn't need to be repeated once it's been done
self:setSearchResults() -- TODO doesn't have to be repeated if the search term is the same
if #self.results > 0 then
self:showSearchResults() -- TODO something about no results
else
UIManager:show(
InfoMessage:new{
text = util.template(_("Found no files matching '%1'."), self.search_value)
}
)
end
end
end
end
function FileSearcher:showSearch()
local dummy = self.search_value
self.search_dialog = InputDialog:new{
title = _("Search for books by filename"),
input = self.search_value,
buttons = {
{
{
text = _("Cancel"),
enabled = true,
callback = function()
self.search_dialog:onClose()
UIManager:close(self.search_dialog)
end,
},
{
text = _("Find books"),
enabled = true,
callback = function()
self.search_value = self.search_dialog:getInputText()
if self.search_value == dummy then -- probably DELETE this if/else block
self.use_previous_search_results = true
else
self.use_previous_search_results = false
end
self:close()
end,
},
},
},
}
self.search_dialog:onShowKeyboard()
UIManager:show(self.search_dialog)
end
function FileSearcher:showSearchResults()
local menu_container = CenterContainer:new{
dimen = Screen:getSize(),
}
self.search_menu = Menu:new{
width = Screen:getWidth()-15,
height = Screen:getHeight()-15,
show_parent = menu_container,
onMenuHold = self.onMenuHold,
cface = Font:getFace("cfont", 22),
_manager = self,
}
table.insert(menu_container, self.search_menu)
self.search_menu.close_callback = function()
UIManager:close(menu_container)
end
table.sort(self.results, function(v1,v2) return v1.text < v2.text end)
self.search_menu:switchItemTable(_("Search Results"), self.results)
UIManager:show(menu_container)
end
return FileSearcher
|
FileSearcher: filter .sdr directories
|
FileSearcher: filter .sdr directories
Fixes #2665
|
Lua
|
agpl-3.0
|
koreader/koreader,mwoz123/koreader,Frenzie/koreader,NiLuJe/koreader,poire-z/koreader,pazos/koreader,robert00s/koreader,koreader/koreader,Frenzie/koreader,NiLuJe/koreader,apletnev/koreader,lgeek/koreader,poire-z/koreader,Markismus/koreader,mihailim/koreader,Hzj-jie/koreader,houqp/koreader
|
57eb0c64861c7ce7371f7c0d73c40dbc841c496c
|
mod_websocket/mod_websocket.lua
|
mod_websocket/mod_websocket.lua
|
-- Prosody IM
-- Copyright (C) 2012 Florian Zeitz
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
module:set_global();
local add_filter = require "util.filters".add_filter;
local sha1 = require "util.hashes".sha1;
local base64 = require "util.encodings".base64.encode;
local softreq = require "util.dependencies".softreq;
local portmanager = require "core.portmanager";
local bit = softreq"bit" or softreq"bit32" or module:log("error", "No bit module found. Either LuaJIT 2 or Lua 5.2 is required");
local band = bit.band;
local bxor = bit.bxor;
local cross_domain = module:get_option("cross_domain_websocket");
if cross_domain then
if cross_domain == true then
cross_domain = "*";
elseif type(cross_domain) == "table" then
cross_domain = table.concat(cross_domain, ", ");
end
if type(cross_domain) ~= "string" then
cross_domain = nil;
end
end
module:depends("c2s")
local sessions = module:shared("c2s/sessions");
local c2s_listener = portmanager.get_service("c2s").listener;
-- Websocket helpers
local function parse_frame(frame)
local result = {};
local pos = 1;
local length_bytes = 0;
local counter = 0;
local tmp_byte;
if #frame < 2 then return; end
tmp_byte = string.byte(frame, pos);
result.FIN = band(tmp_byte, 0x80) > 0;
result.RSV1 = band(tmp_byte, 0x40) > 0;
result.RSV2 = band(tmp_byte, 0x20) > 0;
result.RSV3 = band(tmp_byte, 0x10) > 0;
result.opcode = band(tmp_byte, 0x0F);
pos = pos + 1;
tmp_byte = string.byte(frame, pos);
result.MASK = band(tmp_byte, 0x80) > 0;
result.length = band(tmp_byte, 0x7F);
if result.length == 126 then
length_bytes = 2;
result.length = 0;
elseif result.length == 127 then
length_bytes = 8;
result.length = 0;
end
if #frame < (2 + length_bytes) then return; end
for i = 1, length_bytes do
pos = pos + 1;
result.length = result.length * 256 + string.byte(frame, pos);
end
if #frame < (2 + length_bytes + (result.MASK and 4 or 0) + result.length) then return; end
if result.MASK then
result.key = {string.byte(frame, pos+1), string.byte(frame, pos+2),
string.byte(frame, pos+3), string.byte(frame, pos+4)}
pos = pos + 5;
result.data = "";
for i = pos, pos + result.length - 1 do
result.data = result.data .. string.char(bxor(result.key[counter+1], string.byte(frame, i)));
counter = (counter + 1) % 4;
end
else
result.data = frame:sub(pos + 1, pos + result.length);
end
return result, 2 + length_bytes + (result.MASK and 4 or 0) + result.length;
end
local function build_frame(desc)
local length;
local result = "";
local data = desc.data or "";
result = result .. string.char(0x80 * (desc.FIN and 1 or 0) + desc.opcode);
length = #data;
if length <= 125 then -- 7-bit length
result = result .. string.char(length);
elseif length <= 0xFFFF then -- 2-byte length
result = result .. string.char(126);
result = result .. string.char(length/0x100) .. string.char(length%0x100);
else -- 8-byte length
result = result .. string.char(127);
for i = 7, 0, -1 do
result = result .. string.char(( length / (2^(8*i)) ) % 0x100);
end
end
result = result .. data;
return result;
end
--- Filter stuff
function handle_request(event, path)
local request, response = event.request, event.response;
local conn = response.conn;
if not request.headers.sec_websocket_key then
response.headers.content_type = "text/html";
return [[<!DOCTYPE html><html><head><title>Websocket</title></head><body>
<p>It works! Now point your WebSocket client to this URL to connect to Prosody.</p>
</body></html>]];
end
local wants_xmpp = false;
(request.headers.sec_websocket_protocol or ""):gsub("([^,]*),?", function (proto)
if proto == "xmpp" then wants_xmpp = true; end
end);
if not wants_xmpp then
return 501;
end
local function websocket_close(code, message)
local data = string.char(code/0x100) .. string.char(code%0x100) .. message;
conn:write(build_frame({opcode = 0x8, FIN = true, data = data}));
conn:close();
end
local dataBuffer;
local function handle_frame(frame)
module:log("debug", "Websocket received: %s (%i bytes)", frame.data, #frame.data);
-- Error cases
if frame.RSV1 or frame.RSV2 or frame.RSV3 then -- Reserved bits non zero
websocket_close(1002, "Reserved bits not zero");
return false;
end
if frame.opcode >= 0x8 and frame.length > 125 then -- Control frame with too much payload
websocket_close(1002, "Payload too large");
return false;
end
if frame.opcode >= 0x8 and not frame.FIN then -- Fragmented control frame
websocket_close(1002, "Fragmented control frame");
return false;
end
if (frame.opcode > 0x2 and frame.opcode < 0x8) or (frame.opcode > 0xA) then
websocket_close(1002, "Reserved opcode");
return false;
end
if frame.opcode == 0x0 and not dataBuffer then
websocket_close(1002, "Unexpected continuation frame");
return false;
end
if (frame.opcode == 0x1 or frame.opcode == 0x2) and dataBuffer then
websocket_close(1002, "Continuation frame expected");
return false;
end
-- Valid cases
if frame.opcode == 0x0 then -- Continuation frame
dataBuffer = dataBuffer .. frame.data;
elseif frame.opcode == 0x1 then -- Text frame
dataBuffer = frame.data;
elseif frame.opcode == 0x2 then -- Binary frame
websocket_close(1003, "Only text frames are supported");
return;
elseif frame.opcode == 0x8 then -- Close request
websocket_close(1000, "Goodbye");
return;
elseif frame.opcode == 0x9 then -- Ping frame
frame.opcode = 0xA;
conn:write(build_frame(frame));
return "";
else
log("warn", "Received frame with unsupported opcode %i", frame.opcode);
return "";
end
if frame.FIN then
data = dataBuffer;
dataBuffer = nil;
return data;
end
return "";
end
conn:setlistener(c2s_listener);
c2s_listener.onconnect(conn);
local frameBuffer = "";
add_filter(sessions[conn], "bytes/in", function(data)
local cache = "";
frameBuffer = frameBuffer .. data;
local frame, length = parse_frame(frameBuffer);
while frame do
frameBuffer = frameBuffer:sub(length + 1);
local result = handle_frame(frame);
if not result then return; end
cache = cache .. result;
frame, length = parse_frame(frameBuffer);
end
return cache;
end);
add_filter(sessions[conn], "bytes/out", function(data)
return build_frame({ FIN = true, opcode = 0x01, data = tostring(data)});
end);
response.status = "101 Switching Protocols";
response.headers.upgrade = "websocket";
response.headers.connection = "Upgrade";
response.headers.sec_webSocket_accept = base64(sha1(request.headers.sec_websocket_key .. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
response.headers.sec_webSocket_protocol = "xmpp";
response.headers.access_control_allow_origin = cross_domain;
return "";
end
function module.add_host(module)
module:depends("http");
module:provides("http", {
name = "xmpp-websocket";
route = {
["GET"] = handle_request;
["GET /"] = handle_request;
};
});
end
|
-- Prosody IM
-- Copyright (C) 2012 Florian Zeitz
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
module:set_global();
local add_filter = require "util.filters".add_filter;
local sha1 = require "util.hashes".sha1;
local base64 = require "util.encodings".base64.encode;
local softreq = require "util.dependencies".softreq;
local portmanager = require "core.portmanager";
local bit;
pcall(function() bit = require"bit"; end);
bit = bit or softreq"bit32"
if not bit then module:log("error", "No bit module found. Either LuaJIT 2, lua-bitop or Lua 5.2 is required"); end
local band = bit.band;
local bxor = bit.bxor;
local cross_domain = module:get_option("cross_domain_websocket");
if cross_domain then
if cross_domain == true then
cross_domain = "*";
elseif type(cross_domain) == "table" then
cross_domain = table.concat(cross_domain, ", ");
end
if type(cross_domain) ~= "string" then
cross_domain = nil;
end
end
module:depends("c2s")
local sessions = module:shared("c2s/sessions");
local c2s_listener = portmanager.get_service("c2s").listener;
-- Websocket helpers
local function parse_frame(frame)
local result = {};
local pos = 1;
local length_bytes = 0;
local counter = 0;
local tmp_byte;
if #frame < 2 then return; end
tmp_byte = string.byte(frame, pos);
result.FIN = band(tmp_byte, 0x80) > 0;
result.RSV1 = band(tmp_byte, 0x40) > 0;
result.RSV2 = band(tmp_byte, 0x20) > 0;
result.RSV3 = band(tmp_byte, 0x10) > 0;
result.opcode = band(tmp_byte, 0x0F);
pos = pos + 1;
tmp_byte = string.byte(frame, pos);
result.MASK = band(tmp_byte, 0x80) > 0;
result.length = band(tmp_byte, 0x7F);
if result.length == 126 then
length_bytes = 2;
result.length = 0;
elseif result.length == 127 then
length_bytes = 8;
result.length = 0;
end
if #frame < (2 + length_bytes) then return; end
for i = 1, length_bytes do
pos = pos + 1;
result.length = result.length * 256 + string.byte(frame, pos);
end
if #frame < (2 + length_bytes + (result.MASK and 4 or 0) + result.length) then return; end
if result.MASK then
result.key = {string.byte(frame, pos+1), string.byte(frame, pos+2),
string.byte(frame, pos+3), string.byte(frame, pos+4)}
pos = pos + 5;
result.data = "";
for i = pos, pos + result.length - 1 do
result.data = result.data .. string.char(bxor(result.key[counter+1], string.byte(frame, i)));
counter = (counter + 1) % 4;
end
else
result.data = frame:sub(pos + 1, pos + result.length);
end
return result, 2 + length_bytes + (result.MASK and 4 or 0) + result.length;
end
local function build_frame(desc)
local length;
local result = "";
local data = desc.data or "";
result = result .. string.char(0x80 * (desc.FIN and 1 or 0) + desc.opcode);
length = #data;
if length <= 125 then -- 7-bit length
result = result .. string.char(length);
elseif length <= 0xFFFF then -- 2-byte length
result = result .. string.char(126);
result = result .. string.char(length/0x100) .. string.char(length%0x100);
else -- 8-byte length
result = result .. string.char(127);
for i = 7, 0, -1 do
result = result .. string.char(( length / (2^(8*i)) ) % 0x100);
end
end
result = result .. data;
return result;
end
--- Filter stuff
function handle_request(event, path)
local request, response = event.request, event.response;
local conn = response.conn;
if not request.headers.sec_websocket_key then
response.headers.content_type = "text/html";
return [[<!DOCTYPE html><html><head><title>Websocket</title></head><body>
<p>It works! Now point your WebSocket client to this URL to connect to Prosody.</p>
</body></html>]];
end
local wants_xmpp = false;
(request.headers.sec_websocket_protocol or ""):gsub("([^,]*),?", function (proto)
if proto == "xmpp" then wants_xmpp = true; end
end);
if not wants_xmpp then
return 501;
end
local function websocket_close(code, message)
local data = string.char(code/0x100) .. string.char(code%0x100) .. message;
conn:write(build_frame({opcode = 0x8, FIN = true, data = data}));
conn:close();
end
local dataBuffer;
local function handle_frame(frame)
module:log("debug", "Websocket received: %s (%i bytes)", frame.data, #frame.data);
-- Error cases
if frame.RSV1 or frame.RSV2 or frame.RSV3 then -- Reserved bits non zero
websocket_close(1002, "Reserved bits not zero");
return false;
end
if frame.opcode >= 0x8 and frame.length > 125 then -- Control frame with too much payload
websocket_close(1002, "Payload too large");
return false;
end
if frame.opcode >= 0x8 and not frame.FIN then -- Fragmented control frame
websocket_close(1002, "Fragmented control frame");
return false;
end
if (frame.opcode > 0x2 and frame.opcode < 0x8) or (frame.opcode > 0xA) then
websocket_close(1002, "Reserved opcode");
return false;
end
if frame.opcode == 0x0 and not dataBuffer then
websocket_close(1002, "Unexpected continuation frame");
return false;
end
if (frame.opcode == 0x1 or frame.opcode == 0x2) and dataBuffer then
websocket_close(1002, "Continuation frame expected");
return false;
end
-- Valid cases
if frame.opcode == 0x0 then -- Continuation frame
dataBuffer = dataBuffer .. frame.data;
elseif frame.opcode == 0x1 then -- Text frame
dataBuffer = frame.data;
elseif frame.opcode == 0x2 then -- Binary frame
websocket_close(1003, "Only text frames are supported");
return;
elseif frame.opcode == 0x8 then -- Close request
websocket_close(1000, "Goodbye");
return;
elseif frame.opcode == 0x9 then -- Ping frame
frame.opcode = 0xA;
conn:write(build_frame(frame));
return "";
else
log("warn", "Received frame with unsupported opcode %i", frame.opcode);
return "";
end
if frame.FIN then
data = dataBuffer;
dataBuffer = nil;
return data;
end
return "";
end
conn:setlistener(c2s_listener);
c2s_listener.onconnect(conn);
local frameBuffer = "";
add_filter(sessions[conn], "bytes/in", function(data)
local cache = "";
frameBuffer = frameBuffer .. data;
local frame, length = parse_frame(frameBuffer);
while frame do
frameBuffer = frameBuffer:sub(length + 1);
local result = handle_frame(frame);
if not result then return; end
cache = cache .. result;
frame, length = parse_frame(frameBuffer);
end
return cache;
end);
add_filter(sessions[conn], "bytes/out", function(data)
return build_frame({ FIN = true, opcode = 0x01, data = tostring(data)});
end);
response.status = "101 Switching Protocols";
response.headers.upgrade = "websocket";
response.headers.connection = "Upgrade";
response.headers.sec_webSocket_accept = base64(sha1(request.headers.sec_websocket_key .. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
response.headers.sec_webSocket_protocol = "xmpp";
response.headers.access_control_allow_origin = cross_domain;
return "";
end
function module.add_host(module)
module:depends("http");
module:provides("http", {
name = "xmpp-websocket";
route = {
["GET"] = handle_request;
["GET /"] = handle_request;
};
});
end
|
mod_websocket: Fix require to work with lua-bitop (Thanks Istv?n and Zash)
|
mod_websocket: Fix require to work with lua-bitop (Thanks Istv?n and Zash)
|
Lua
|
mit
|
LanceJenkinZA/prosody-modules,LanceJenkinZA/prosody-modules,1st8/prosody-modules,vince06fr/prosody-modules,crunchuser/prosody-modules,BurmistrovJ/prosody-modules,either1/prosody-modules,jkprg/prosody-modules,vfedoroff/prosody-modules,asdofindia/prosody-modules,either1/prosody-modules,brahmi2/prosody-modules,obelisk21/prosody-modules,crunchuser/prosody-modules,crunchuser/prosody-modules,mardraze/prosody-modules,olax/prosody-modules,crunchuser/prosody-modules,guilhem/prosody-modules,iamliqiang/prosody-modules,softer/prosody-modules,stephen322/prosody-modules,olax/prosody-modules,prosody-modules/import,LanceJenkinZA/prosody-modules,brahmi2/prosody-modules,joewalker/prosody-modules,olax/prosody-modules,cryptotoad/prosody-modules,obelisk21/prosody-modules,vince06fr/prosody-modules,amenophis1er/prosody-modules,dhotson/prosody-modules,apung/prosody-modules,heysion/prosody-modules,mardraze/prosody-modules,BurmistrovJ/prosody-modules,mmusial/prosody-modules,amenophis1er/prosody-modules,softer/prosody-modules,mardraze/prosody-modules,Craige/prosody-modules,BurmistrovJ/prosody-modules,syntafin/prosody-modules,mardraze/prosody-modules,vince06fr/prosody-modules,stephen322/prosody-modules,Craige/prosody-modules,stephen322/prosody-modules,asdofindia/prosody-modules,apung/prosody-modules,mmusial/prosody-modules,asdofindia/prosody-modules,heysion/prosody-modules,jkprg/prosody-modules,1st8/prosody-modules,amenophis1er/prosody-modules,vfedoroff/prosody-modules,vfedoroff/prosody-modules,syntafin/prosody-modules,cryptotoad/prosody-modules,vfedoroff/prosody-modules,syntafin/prosody-modules,syntafin/prosody-modules,joewalker/prosody-modules,NSAKEY/prosody-modules,jkprg/prosody-modules,amenophis1er/prosody-modules,apung/prosody-modules,guilhem/prosody-modules,apung/prosody-modules,stephen322/prosody-modules,dhotson/prosody-modules,vince06fr/prosody-modules,either1/prosody-modules,asdofindia/prosody-modules,amenophis1er/prosody-modules,Craige/prosody-modules,NSAKEY/prosody-modules,mmusial/prosody-modules,iamliqiang/prosody-modules,LanceJenkinZA/prosody-modules,heysion/prosody-modules,drdownload/prosody-modules,softer/prosody-modules,cryptotoad/prosody-modules,iamliqiang/prosody-modules,prosody-modules/import,joewalker/prosody-modules,LanceJenkinZA/prosody-modules,stephen322/prosody-modules,1st8/prosody-modules,drdownload/prosody-modules,1st8/prosody-modules,mardraze/prosody-modules,iamliqiang/prosody-modules,NSAKEY/prosody-modules,jkprg/prosody-modules,brahmi2/prosody-modules,crunchuser/prosody-modules,cryptotoad/prosody-modules,BurmistrovJ/prosody-modules,joewalker/prosody-modules,olax/prosody-modules,vince06fr/prosody-modules,guilhem/prosody-modules,1st8/prosody-modules,mmusial/prosody-modules,olax/prosody-modules,vfedoroff/prosody-modules,heysion/prosody-modules,asdofindia/prosody-modules,cryptotoad/prosody-modules,Craige/prosody-modules,drdownload/prosody-modules,brahmi2/prosody-modules,apung/prosody-modules,prosody-modules/import,either1/prosody-modules,dhotson/prosody-modules,guilhem/prosody-modules,brahmi2/prosody-modules,joewalker/prosody-modules,obelisk21/prosody-modules,drdownload/prosody-modules,either1/prosody-modules,guilhem/prosody-modules,dhotson/prosody-modules,BurmistrovJ/prosody-modules,softer/prosody-modules,drdownload/prosody-modules,softer/prosody-modules,obelisk21/prosody-modules,heysion/prosody-modules,NSAKEY/prosody-modules,dhotson/prosody-modules,NSAKEY/prosody-modules,prosody-modules/import,prosody-modules/import,mmusial/prosody-modules,syntafin/prosody-modules,iamliqiang/prosody-modules,jkprg/prosody-modules,obelisk21/prosody-modules,Craige/prosody-modules
|
aa2e1edfa5c3ccc878cd615c7729a892eae72947
|
applications/luci-app-mwan3/luasrc/model/cbi/mwan/ruleconfig.lua
|
applications/luci-app-mwan3/luasrc/model/cbi/mwan/ruleconfig.lua
|
-- Copyright 2014 Aedan Renner <chipdankly@gmail.com>
-- Copyright 2018 Florian Eckert <fe@dev.tdt.de>
-- Licensed to the public under the GNU General Public License v2.
local dsp = require "luci.dispatcher"
local util = require("luci.util")
local m, mwan_rule, src_ip, src_port, dest_ip, dest_port, proto, sticky
local timeout, ipset, logging, policy
arg[1] = arg[1] or ""
local ipsets = util.split(util.trim(util.exec("ipset -n -L 2>/dev/null | grep -v mwan3_ | sort")), "\n", nil, true) or {}
m = Map("mwan3", translatef("MWAN Rule Configuration - %s", arg[1]))
m.redirect = dsp.build_url("admin", "network", "mwan", "rule")
mwan_rule = m:section(NamedSection, arg[1], "rule", "")
mwan_rule.addremove = false
mwan_rule.dynamic = false
src_ip = mwan_rule:option(Value, "src_ip", translate("Source address"),
translate("Supports CIDR notation (eg \"192.168.100.0/24\") without quotes"))
src_ip.datatype = ipaddr
src_port = mwan_rule:option(Value, "src_port", translate("Source port"),
translate("May be entered as a single or multiple port(s) (eg \"22\" or \"80,443\") or as a portrange (eg \"1024:2048\") without quotes"))
dest_ip = mwan_rule:option(Value, "dest_ip", translate("Destination address"),
translate("Supports CIDR notation (eg \"192.168.100.0/24\") without quotes"))
dest_ip.datatype = ipaddr
dest_port = mwan_rule:option(Value, "dest_port", translate("Destination port"),
translate("May be entered as a single or multiple port(s) (eg \"22\" or \"80,443\") or as a portrange (eg \"1024:2048\") without quotes"))
proto = mwan_rule:option(Value, "proto", translate("Protocol"),
translate("View the content of /etc/protocols for protocol description"))
proto.default = "all"
proto.rmempty = false
proto:value("all")
proto:value("tcp")
proto:value("udp")
proto:value("icmp")
proto:value("esp")
sticky = mwan_rule:option(ListValue, "sticky", translate("Sticky"),
translate("Traffic from the same source IP address that previously matched this rule within the sticky timeout period will use the same WAN interface"))
sticky.default = "0"
sticky:value("1", translate("Yes"))
sticky:value("0", translate("No"))
timeout = mwan_rule:option(Value, "timeout", translate("Sticky timeout"),
translate("Seconds. Acceptable values: 1-1000000. Defaults to 600 if not set"))
timeout.datatype = "range(1, 1000000)"
ipset = mwan_rule:option(Value, "ipset", translate("IPset"),
translate("Name of IPset rule. Requires IPset rule in /etc/dnsmasq.conf (eg \"ipset=/youtube.com/youtube\")"))
for _, z in ipairs(ipsets) do
ipset:value(z)
end
logging = mwan_rule:option(Flag, "logging", translate("Logging"),
translate("Enables firewall rule logging (global mwan3 logging must also be enabled)"))
policy = mwan_rule:option(Value, "use_policy", translate("Policy assigned"))
m.uci:foreach("mwan3", "policy",
function(s)
policy:value(s['.name'], s['.name'])
end
)
policy:value("unreachable", translate("unreachable (reject)"))
policy:value("blackhole", translate("blackhole (drop)"))
policy:value("default", translate("default (use main routing table)"))
return m
|
-- Copyright 2014 Aedan Renner <chipdankly@gmail.com>
-- Copyright 2018 Florian Eckert <fe@dev.tdt.de>
-- Licensed to the public under the GNU General Public License v2.
local dsp = require "luci.dispatcher"
local util = require("luci.util")
local m, mwan_rule, src_ip, src_port, dest_ip, dest_port, proto, sticky
local timeout, ipset, logging, policy
arg[1] = arg[1] or ""
local ipsets = util.split(util.trim(util.exec("ipset -n -L 2>/dev/null | grep -v mwan3_ | sort")), "\n", nil, true) or {}
m = Map("mwan3", translatef("MWAN Rule Configuration - %s", arg[1]))
m.redirect = dsp.build_url("admin", "network", "mwan", "rule")
mwan_rule = m:section(NamedSection, arg[1], "rule", "")
mwan_rule.addremove = false
mwan_rule.dynamic = false
src_ip = mwan_rule:option(Value, "src_ip", translate("Source address"),
translate("Supports CIDR notation (eg \"192.168.100.0/24\") without quotes"))
src_ip.datatype = ipaddr
src_port = mwan_rule:option(Value, "src_port", translate("Source port"),
translate("May be entered as a single or multiple port(s) (eg \"22\" or \"80,443\") or as a portrange (eg \"1024:2048\") without quotes"))
dest_ip = mwan_rule:option(Value, "dest_ip", translate("Destination address"),
translate("Supports CIDR notation (eg \"192.168.100.0/24\") without quotes"))
dest_ip.datatype = ipaddr
dest_port = mwan_rule:option(Value, "dest_port", translate("Destination port"),
translate("May be entered as a single or multiple port(s) (eg \"22\" or \"80,443\") or as a portrange (eg \"1024:2048\") without quotes"))
proto = mwan_rule:option(Value, "proto", translate("Protocol"),
translate("View the content of /etc/protocols for protocol description"))
proto.default = "all"
proto.rmempty = false
proto:value("all")
proto:value("tcp")
proto:value("udp")
proto:value("icmp")
proto:value("esp")
sticky = mwan_rule:option(ListValue, "sticky", translate("Sticky"),
translate("Traffic from the same source IP address that previously matched this rule within the sticky timeout period will use the same WAN interface"))
sticky.default = "0"
sticky:value("1", translate("Yes"))
sticky:value("0", translate("No"))
timeout = mwan_rule:option(Value, "timeout", translate("Sticky timeout"),
translate("Seconds. Acceptable values: 1-1000000. Defaults to 600 if not set"))
timeout.datatype = "range(1, 1000000)"
ipset = mwan_rule:option(Value, "ipset", translate("IPset"),
translate("Name of IPset rule. Requires IPset rule in /etc/dnsmasq.conf (eg \"ipset=/youtube.com/youtube\")"))
ipset:value("", translate("-- Please choose --"))
for _, z in ipairs(ipsets) do
ipset:value(z)
end
logging = mwan_rule:option(Flag, "logging", translate("Logging"),
translate("Enables firewall rule logging (global mwan3 logging must also be enabled)"))
policy = mwan_rule:option(Value, "use_policy", translate("Policy assigned"))
m.uci:foreach("mwan3", "policy",
function(s)
policy:value(s['.name'], s['.name'])
end
)
policy:value("unreachable", translate("unreachable (reject)"))
policy:value("blackhole", translate("blackhole (drop)"))
policy:value("default", translate("default (use main routing table)"))
return m
|
luci-app-mwan3: fix possibility to not select an ipset
|
luci-app-mwan3: fix possibility to not select an ipset
Signed-off-by: Florian Eckert <ee3e4af9c48a69f5a5c47153eb4a777754bfbe6f@dev.tdt.de>
|
Lua
|
apache-2.0
|
openwrt-es/openwrt-luci,nmav/luci,Noltari/luci,openwrt/luci,artynet/luci,nmav/luci,hnyman/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,nmav/luci,openwrt/luci,nmav/luci,Noltari/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,openwrt-es/openwrt-luci,artynet/luci,rogerpueyo/luci,hnyman/luci,nmav/luci,nmav/luci,nmav/luci,Noltari/luci,nmav/luci,tobiaswaldvogel/luci,hnyman/luci,openwrt/luci,openwrt-es/openwrt-luci,hnyman/luci,lbthomsen/openwrt-luci,nmav/luci,rogerpueyo/luci,artynet/luci,openwrt/luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,artynet/luci,openwrt/luci,Noltari/luci,Noltari/luci,artynet/luci,rogerpueyo/luci,hnyman/luci,lbthomsen/openwrt-luci,Noltari/luci,Noltari/luci,openwrt/luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,Noltari/luci,rogerpueyo/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,artynet/luci,lbthomsen/openwrt-luci,artynet/luci,rogerpueyo/luci,tobiaswaldvogel/luci,artynet/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,openwrt/luci,hnyman/luci,tobiaswaldvogel/luci,rogerpueyo/luci,rogerpueyo/luci,Noltari/luci,hnyman/luci,artynet/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,hnyman/luci,openwrt/luci
|
50c56b01043113b77f47ae9634d671b67376475b
|
access.lua
|
access.lua
|
-- import requirements
-- allow either ccjsonjson, or th-LuaJSON
local has_cjson, jsonmod = pcall(require, "cjson")
if not has_cjson then
jsonmod = require "json"
end
-- Ubuntu broke the install. Puts the source in /usr/share/lua/5.1/https.lua,
-- but since the source defines itself as the module "ssl.https", after we
-- load the source, we need to grab the actual thing.
pcall(require,"https")
local https = require "ssl.https" -- /usr/share/lua/5.1/https.lua
local ltn12 = require("ltn12")
local uri = ngx.var.uri
local uri_args = ngx.req.get_uri_args()
local scheme = ngx.var.scheme
local server_name = ngx.var.server_name
-- setup some app-level vars
local client_id = ngx.var.ngo_client_id
local client_secret = ngx.var.ngo_client_secret
local domain = ngx.var.ngo_domain
local cb_scheme = ngx.var.ngo_callback_scheme or scheme
local cb_server_name = ngx.var.ngo_callback_host or server_name
local cb_uri = ngx.var.ngo_callback_uri or "/_oauth"
local cb_url = cb_scheme.."://"..cb_server_name..cb_uri
local signout_uri = ngx.var.ngo_signout_uri or "/_signout"
local debug = ngx.var.ngo_debug
local whitelist = ngx.var.ngo_whitelist
local blacklist = ngx.var.ngo_blacklist
local secure_cookies = ngx.var.ngo_secure_cookies
-- See https://developers.google.com/accounts/docs/OAuth2WebServer
if uri == signout_uri then
ngx.header["Set-Cookie"] = "AccessToken=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"
return ngx.redirect(scheme.."://"..server_name)
end
if not ngx.var.cookie_AccessToken then
-- If no access token and this isn't the callback URI, redirect to oauth
if uri ~= cb_uri then
-- Redirect to the /oauth endpoint, request access to ALL scopes
return ngx.redirect("https://accounts.google.com/o/oauth2/auth?client_id="..client_id.."&scope=email&response_type=code&redirect_uri="..ngx.escape_uri(cb_url).."&state="..ngx.escape_uri(uri).."&login_hint="..ngx.escape_uri(domain))
end
-- Fetch teh authorization code from the parameters
local auth_code = uri_args["code"]
local auth_error = uri_args["error"]
if auth_error then
ngx.log(ngx.ERR, "received "..auth_error.." from https://accounts.google.com/o/oauth2/auth")
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
if debug then
ngx.log(ngx.ERR, "DEBUG: fetching token for auth code "..auth_code)
end
-- TODO: Switch to NBIO sockets
-- If I get around to working luasec, this says how to pass a function which
-- can generate a socket, needed for NBIO using nginx cosocket
-- http://lua-users.org/lists/lua-l/2009-02/msg00251.html
local res, code, headers, status = https.request(
"https://accounts.google.com/o/oauth2/token",
"code="..ngx.escape_uri(auth_code).."&client_id="..client_id.."&client_secret="..client_secret.."&redirect_uri="..ngx.escape_uri(cb_url).."&grant_type=authorization_code"
)
if debug then
ngx.log(ngx.ERR, "DEBUG: token response "..res..code..status)
end
if code~=200 then
ngx.log(ngx.ERR, "received "..code.." from https://accounts.google.com/o/oauth2/token")
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
-- use version 1 cookies so we don't have to encode. MSIE-old beware
local json = jsonmod.decode( res )
local access_token = json["access_token"]
local cookie_tail = ";version=1;path=/;Max-Age="..json["expires_in"]
if secure_cookies then
cookie_tail = cookie_tail..";secure"
end
local send_headers = {
Authorization = "Bearer "..access_token,
}
local result_table = {}
local res2, code2, headers2, status2 = https.request({
url = "https://www.googleapis.com/oauth2/v2/userinfo",
method = "GET",
headers = send_headers,
sink = ltn12.sink.table(result_table),
})
if code2~=200 then
ngx.log(ngx.ERR, "received "..code2.." from https://www.googleapis.com/oauth2/v2/userinfo")
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
if debug then
ngx.log(ngx.ERR, "DEBUG: userinfo response "..res2..code2..status2..table.concat(result_table))
end
json = jsonmod.decode( table.concat(result_table) )
local name = json["name"]
local email = json["email"]
local picture = json["picture"]
-- If no whitelist or blacklist, match on domain
if not whitelist and not blacklist and domain then
if not string.find(email, "@"..domain) then
if debug then
ngx.log(ngx.ERR, "DEBUG: "..email.." not in "..domain)
end
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
end
if whitelist then
if not string.find(whitelist, email) then
if debug then
ngx.log(ngx.ERR, "DEBUG: "..email.." not in whitelist")
end
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
end
if blacklist then
if string.find(blacklist, email) then
if debug then
ngx.log(ngx.ERR, "DEBUG: "..email.." in blacklist")
end
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
end
ngx.header["Set-Cookie"] = {
"AccessToken="..access_token..cookie_tail,
"Name="..ngx.escape_uri(name)..cookie_tail,
"Email="..ngx.escape_uri(email)..cookie_tail,
"Picture="..ngx.escape_uri(picture)..cookie_tail
}
-- Redirect
if debug then
ngx.log(ngx.ERR, "DEBUG: authorized "..json["email"]..", redirecting to "..uri_args["state"])
end
return ngx.redirect(uri_args["state"])
end
|
-- import requirements
-- allow either ccjsonjson, or th-LuaJSON
local has_cjson, jsonmod = pcall(require, "cjson")
if not has_cjson then
jsonmod = require "json"
end
-- Ubuntu broke the install. Puts the source in /usr/share/lua/5.1/https.lua,
-- but since the source defines itself as the module "ssl.https", after we
-- load the source, we need to grab the actual thing.
pcall(require,"https")
local https = require "ssl.https" -- /usr/share/lua/5.1/https.lua
local ltn12 = require("ltn12")
local uri = ngx.var.uri
local uri_args = ngx.req.get_uri_args()
local scheme = ngx.var.scheme
local server_name = ngx.var.server_name
-- setup some app-level vars
local client_id = ngx.var.ngo_client_id
local client_secret = ngx.var.ngo_client_secret
local domain = ngx.var.ngo_domain
local cb_scheme = ngx.var.ngo_callback_scheme or scheme
local cb_server_name = ngx.var.ngo_callback_host or server_name
local cb_uri = ngx.var.ngo_callback_uri or "/_oauth"
local cb_url = cb_scheme.."://"..cb_server_name..cb_uri
local redir_url = cb_scheme.."://"..cb_server_name..uri
local signout_uri = ngx.var.ngo_signout_uri or "/_signout"
local debug = ngx.var.ngo_debug
local whitelist = ngx.var.ngo_whitelist
local blacklist = ngx.var.ngo_blacklist
local secure_cookies = ngx.var.ngo_secure_cookies
-- See https://developers.google.com/accounts/docs/OAuth2WebServer
if uri == signout_uri then
ngx.header["Set-Cookie"] = "AccessToken=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"
return ngx.redirect(cb_scheme.."://"..server_name)
end
if not ngx.var.cookie_AccessToken then
-- If no access token and this isn't the callback URI, redirect to oauth
if uri ~= cb_uri then
-- Redirect to the /oauth endpoint, request access to ALL scopes
return ngx.redirect("https://accounts.google.com/o/oauth2/auth?client_id="..client_id.."&scope=email&response_type=code&redirect_uri="..ngx.escape_uri(cb_url).."&state="..ngx.escape_uri(redir_url).."&login_hint="..ngx.escape_uri(domain))
end
-- Fetch teh authorization code from the parameters
local auth_code = uri_args["code"]
local auth_error = uri_args["error"]
if auth_error then
ngx.log(ngx.ERR, "received "..auth_error.." from https://accounts.google.com/o/oauth2/auth")
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
if debug then
ngx.log(ngx.ERR, "DEBUG: fetching token for auth code "..auth_code)
end
-- TODO: Switch to NBIO sockets
-- If I get around to working luasec, this says how to pass a function which
-- can generate a socket, needed for NBIO using nginx cosocket
-- http://lua-users.org/lists/lua-l/2009-02/msg00251.html
local res, code, headers, status = https.request(
"https://accounts.google.com/o/oauth2/token",
"code="..ngx.escape_uri(auth_code).."&client_id="..client_id.."&client_secret="..client_secret.."&redirect_uri="..ngx.escape_uri(cb_url).."&grant_type=authorization_code"
)
if debug then
ngx.log(ngx.ERR, "DEBUG: token response "..res..code..status)
end
if code~=200 then
ngx.log(ngx.ERR, "received "..code.." from https://accounts.google.com/o/oauth2/token")
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
-- use version 1 cookies so we don't have to encode. MSIE-old beware
local json = jsonmod.decode( res )
local access_token = json["access_token"]
local cookie_tail = ";version=1;path=/;Max-Age="..json["expires_in"]
if secure_cookies then
cookie_tail = cookie_tail..";secure"
end
local send_headers = {
Authorization = "Bearer "..access_token,
}
local result_table = {}
local res2, code2, headers2, status2 = https.request({
url = "https://www.googleapis.com/oauth2/v2/userinfo",
method = "GET",
headers = send_headers,
sink = ltn12.sink.table(result_table),
})
if code2~=200 then
ngx.log(ngx.ERR, "received "..code2.." from https://www.googleapis.com/oauth2/v2/userinfo")
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
if debug then
ngx.log(ngx.ERR, "DEBUG: userinfo response "..res2..code2..status2..table.concat(result_table))
end
json = jsonmod.decode( table.concat(result_table) )
local name = json["name"]
local email = json["email"]
local picture = json["picture"]
-- If no whitelist or blacklist, match on domain
if not whitelist and not blacklist and domain then
if not string.find(email, "@"..domain) then
if debug then
ngx.log(ngx.ERR, "DEBUG: "..email.." not in "..domain)
end
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
end
if whitelist then
if not string.find(whitelist, email) then
if debug then
ngx.log(ngx.ERR, "DEBUG: "..email.." not in whitelist")
end
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
end
if blacklist then
if string.find(blacklist, email) then
if debug then
ngx.log(ngx.ERR, "DEBUG: "..email.." in blacklist")
end
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
end
ngx.header["Set-Cookie"] = {
"AccessToken="..access_token..cookie_tail,
"Name="..ngx.escape_uri(name)..cookie_tail,
"Email="..ngx.escape_uri(email)..cookie_tail,
"Picture="..ngx.escape_uri(picture)..cookie_tail
}
-- Redirect
if debug then
ngx.log(ngx.ERR, "DEBUG: authorized "..json["email"]..", redirecting to "..uri_args["state"])
end
return ngx.redirect(uri_args["state"])
end
|
Changed logout and post-auth redirect to respect cb_scheme variable (fixes HTTP servers running behind an HTTPS proxy)
|
Changed logout and post-auth redirect to respect cb_scheme variable (fixes HTTP servers running behind an HTTPS proxy)
|
Lua
|
mit
|
ivan1986/nginx-google-oauth,agoragames/nginx-google-oauth,ivan1986/nginx-google-oauth,agoragames/nginx-google-oauth,milliwayslabs/nginx-google-oauth,milliwayslabs/nginx-google-oauth
|
12baf681cade7228219964d5b43fa5fc8ca2c3ce
|
share/lua/playlist/koreus.lua
|
share/lua/playlist/koreus.lua
|
--[[
Copyright 2009 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
if vlc.access ~= "http" then
return false
end
koreus_site = string.match( vlc.path, "koreus" )
if not koreus_site then
return false
end
return ( string.match( vlc.path, "video" ) ) -- http://www.koreus.com/video/pouet.html
end
-- Parse function.
function parse()
while true do
line = vlc.readline()
if not line then break end
if string.match( line, "<meta name=\"title\"" ) then
_,_,name = string.find( line, "content=\"(.-)\"" )
name = vlc.strings.resolve_xml_special_chars( name )
end
if string.match( line, "<meta name=\"description\"" ) then
_,_,description = string.find( line, "content=\"(.-)\"" )
description = vlc.strings.resolve_xml_special_chars( description )
end
if string.match( line, "<meta name=\"author\"" ) then
_,_,artist = string.find( line, "content=\"(.-)\"" )
artist = vlc.strings.resolve_xml_special_chars( artist )
end
if string.match( line, "link rel=\"image_src\"" ) then
_,_,arturl = string.find( line, "href=\"(.-)\"" )
end
vid_url = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%.mp4)' )
if vid_url then
return { { path = vid_url; name = name; description = description; artist = artist; arturl = arturl } }
end
end
return {}
end
|
--[[
Copyright 2009 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
if vlc.access ~= "http" then
return false
end
koreus_site = string.match( vlc.path, "koreus" )
if not koreus_site then
return false
end
return ( string.match( vlc.path, "video" ) ) -- http://www.koreus.com/video/pouet.html
end
-- Parse function.
function parse()
while true do
line = vlc.readline()
if not line then break end
if string.match( line, "<meta name=\"title\"" ) then
_,_,name = string.find( line, "content=\"(.-)\"" )
name = vlc.strings.resolve_xml_special_chars( name )
end
if string.match( line, "<meta name=\"description\"" ) then
_,_,description = string.find( line, "content=\"(.-)\"" )
if (description ~= nil) then
description = vlc.strings.resolve_xml_special_chars( description )
end
end
if string.match( line, "<meta name=\"author\"" ) then
_,_,artist = string.find( line, "content=\"(.-)\"" )
artist = vlc.strings.resolve_xml_special_chars( artist )
end
if string.match( line, "link rel=\"image_src\"" ) then
_,_,arturl = string.find( line, "href=\"(.-)\"" )
end
vid_url = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%.mp4)' )
if vid_url then
return { { path = vid_url; name = name; description = description; artist = artist; arturl = arturl } }
end
end
return {}
end
|
Koreus: fix on broken pages
|
Koreus: fix on broken pages
|
Lua
|
lgpl-2.1
|
vlc-mirror/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,xkfz007/vlc,shyamalschandra/vlc,krichter722/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,krichter722/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,shyamalschandra/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,krichter722/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,xkfz007/vlc,krichter722/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,shyamalschandra/vlc,xkfz007/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,jomanmuk/vlc-2.1
|
847769a9d809c0b873e81c7affab38abcf0d8dc7
|
build/Tests.lua
|
build/Tests.lua
|
-- Tests/examples helpers
function SetupExampleProject()
SetupNativeProjects()
location (path.join(builddir, "deps"))
end
function SetupTestProject(name, file, lib)
SetupTestGeneratorProject(name)
SetupTestNativeProject(name)
SetupTestProjectsCSharp(name, file, lib)
SetupTestProjectsCLI(name, file, lib)
end
function SetupTestCSharp(name)
SetupTestGeneratorProject(name)
SetupTestNativeProject(name)
SetupTestProjectsCSharp(name)
end
function SetupTestGeneratorProject(name)
project(name .. ".Gen")
kind "ConsoleApp"
language "C#"
location "."
files { name .. ".cs" }
dependson { name .. ".Native" }
links
{
"CppSharp.AST",
"CppSharp.Generator",
"CppSharp.Parser",
}
end
function SetupTestGeneratorBuildEvent(name)
local exePath = SafePath("$(TargetDir)" .. name .. ".Gen.exe")
prebuildcommands { exePath }
end
function SetupTestNativeProject(name)
project(name .. ".Native")
SetupNativeProject()
kind "SharedLib"
language "C++"
flags { common_flags }
files { "**.h", "**.cpp" }
end
function LinkNUnit()
libdirs
{
depsdir .. "/NUnit",
depsdir .. "/NSubstitute"
}
links
{
"NUnit.Framework",
"NSubstitute"
}
end
function SetupTestProjectsCSharp(name, file, lib)
project(name .. ".CSharp")
kind "SharedLib"
language "C#"
location "."
flags { "Unsafe" }
dependson { name .. ".Gen", name .. ".Native" }
SetupTestGeneratorBuildEvent(name)
files
{
path.join(gendir, name, name .. ".cs"),
}
links { "CppSharp.Runtime" }
project(name .. ".Tests.CSharp")
kind "SharedLib"
language "C#"
location "."
flags { "Unsafe" }
files { name .. ".Tests.cs" }
links { name .. ".CSharp" }
dependson { name .. ".Native" }
LinkNUnit()
end
function SetupTestProjectsCLI(name, file, lib)
project(name .. ".CLI")
SetupNativeProject()
kind "SharedLib"
language "C++"
flags { "Managed" }
dependson { name .. ".Gen", name .. ".Native" }
SetupTestGeneratorBuildEvent(name)
files
{
path.join(gendir, name, name .. ".cpp"),
path.join(gendir, name, name .. ".h"),
}
includedirs { path.join(testsdir, name), incdir }
links { name .. ".Native" }
project(name .. ".Tests.CLI")
kind "SharedLib"
language "C#"
location "."
files { name .. ".Tests.cs" }
links { name .. ".CLI" }
dependson { name .. ".Native" }
LinkNUnit()
end
function IncludeExamples()
print("Searching for examples...")
IncludeDir(examplesdir)
end
function IncludeTests()
print("Searching for tests...")
IncludeDir(testsdir)
end
|
-- Tests/examples helpers
function SetupExampleProject()
SetupNativeProjects()
location (path.join(builddir, "deps"))
end
function SetupTestProject(name, file, lib)
SetupTestGeneratorProject(name)
SetupTestNativeProject(name)
SetupTestProjectsCSharp(name, file, lib)
SetupTestProjectsCLI(name, file, lib)
end
function SetupTestCSharp(name)
SetupTestGeneratorProject(name)
SetupTestNativeProject(name)
SetupTestProjectsCSharp(name)
end
function SetupManagedTestProject()
kind "SharedLib"
language "C#"
flags { "Unsafe" }
local c = configuration "vs*"
location "."
configuration(c)
end
function SetupTestGeneratorProject(name)
project(name .. ".Gen")
SetupManagedTestProject()
kind "ConsoleApp"
files { name .. ".cs" }
dependson { name .. ".Native" }
links
{
"CppSharp.AST",
"CppSharp.Generator",
"CppSharp.Parser",
}
end
function SetupTestGeneratorBuildEvent(name)
local exePath = SafePath("$(TargetDir)" .. name .. ".Gen.exe")
prebuildcommands { exePath }
end
function SetupTestNativeProject(name)
project(name .. ".Native")
SetupNativeProject()
kind "SharedLib"
language "C++"
flags { common_flags }
files { "**.h", "**.cpp" }
end
function LinkNUnit()
libdirs
{
depsdir .. "/NUnit",
depsdir .. "/NSubstitute"
}
links
{
"NUnit.Framework",
"NSubstitute"
}
end
function SetupTestProjectsCSharp(name, file, lib)
project(name .. ".CSharp")
SetupManagedTestProject()
dependson { name .. ".Gen", name .. ".Native" }
SetupTestGeneratorBuildEvent(name)
files
{
path.join(gendir, name, name .. ".cs"),
}
links { "CppSharp.Runtime" }
project(name .. ".Tests.CSharp")
SetupManagedTestProject()
files { name .. ".Tests.cs" }
links { name .. ".CSharp" }
dependson { name .. ".Native" }
LinkNUnit()
links { "CppSharp.Runtime" }
end
function SetupTestProjectsCLI(name, file, lib)
project(name .. ".CLI")
SetupNativeProject()
kind "SharedLib"
language "C++"
flags { "Managed" }
dependson { name .. ".Gen", name .. ".Native" }
SetupTestGeneratorBuildEvent(name)
files
{
path.join(gendir, name, name .. ".cpp"),
path.join(gendir, name, name .. ".h"),
}
includedirs { path.join(testsdir, name), incdir }
links { name .. ".Native" }
project(name .. ".Tests.CLI")
SetupManagedTestProject()
files { name .. ".Tests.cs" }
links { name .. ".CLI" }
dependson { name .. ".Native" }
LinkNUnit()
end
function IncludeExamples()
print("Searching for examples...")
IncludeDir(examplesdir)
end
function IncludeTests()
print("Searching for tests...")
IncludeDir(testsdir)
end
|
Fixed the tests build scripts.
|
Fixed the tests build scripts.
|
Lua
|
mit
|
mono/CppSharp,mydogisbox/CppSharp,Samana/CppSharp,Samana/CppSharp,zillemarco/CppSharp,genuinelucifer/CppSharp,genuinelucifer/CppSharp,zillemarco/CppSharp,u255436/CppSharp,zillemarco/CppSharp,KonajuGames/CppSharp,txdv/CppSharp,SonyaSa/CppSharp,ktopouzi/CppSharp,SonyaSa/CppSharp,inordertotest/CppSharp,mohtamohit/CppSharp,nalkaro/CppSharp,txdv/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,txdv/CppSharp,inordertotest/CppSharp,ddobrev/CppSharp,Samana/CppSharp,txdv/CppSharp,genuinelucifer/CppSharp,inordertotest/CppSharp,mono/CppSharp,ktopouzi/CppSharp,u255436/CppSharp,KonajuGames/CppSharp,xistoso/CppSharp,ddobrev/CppSharp,imazen/CppSharp,mydogisbox/CppSharp,mydogisbox/CppSharp,ktopouzi/CppSharp,txdv/CppSharp,zillemarco/CppSharp,xistoso/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,u255436/CppSharp,u255436/CppSharp,xistoso/CppSharp,ddobrev/CppSharp,mono/CppSharp,mydogisbox/CppSharp,Samana/CppSharp,xistoso/CppSharp,ddobrev/CppSharp,xistoso/CppSharp,mohtamohit/CppSharp,mohtamohit/CppSharp,nalkaro/CppSharp,imazen/CppSharp,ktopouzi/CppSharp,KonajuGames/CppSharp,mydogisbox/CppSharp,KonajuGames/CppSharp,imazen/CppSharp,mono/CppSharp,nalkaro/CppSharp,inordertotest/CppSharp,ktopouzi/CppSharp,imazen/CppSharp,SonyaSa/CppSharp,mono/CppSharp,imazen/CppSharp,mono/CppSharp,SonyaSa/CppSharp,nalkaro/CppSharp,nalkaro/CppSharp,KonajuGames/CppSharp,mohtamohit/CppSharp,inordertotest/CppSharp,SonyaSa/CppSharp,genuinelucifer/CppSharp,Samana/CppSharp,genuinelucifer/CppSharp
|
8970ff6d495ee362098545b8f4a075ebda5d8099
|
share/lua/playlist/mpora.lua
|
share/lua/playlist/mpora.lua
|
--[[
$Id$
Copyright © 2009 the VideoLAN team
Authors: Konstantin Pavlov (thresh@videolan.org)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "video.mpora.com/watch/" )
end
-- Parse function.
function parse()
p = {}
while true do
-- Try to find the video's title
line = vlc.readline()
if not line then break end
if string.match( line, "meta name=\"title\"" ) then
_,_,name = string.find( line, "content=\"(.*)\" />" )
end
if string.match( line, "image_src" ) then
_,_,arturl = string.find( line, "image_src\" href=\"(.*)\" />" )
end
if string.match( line, "filmID" ) then
_,_,video = string.find( line, "var filmID = \'(.*)\';")
table.insert( p, { path = "http://cdn0.mpora.com/play/video/"..video.."/mp4/"; name = name; arturl = arturl } )
end
if string.match( line, "definitionLink hd" ) then
table.insert( p, { path = "http://cdn0.mpora.com/play/video/"..video.."_hd/mp4/"; name = name.." (HD)", arturl = arturl } )
end
end
return p
end
|
--[[
$Id$
Copyright © 2009 the VideoLAN team
Authors: Konstantin Pavlov (thresh@videolan.org)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "video.mpora.com/watch/" )
end
-- Parse function.
function parse()
p = {}
while true do
-- Try to find the video's title
line = vlc.readline()
if not line then break end
if string.match( line, "meta name=\"title\"" ) then
_,_,name = string.find( line, "content=\"(.*)\" />" )
end
if string.match( line, "image_src" ) then
_,_,arturl = string.find( line, "image_src\" href=\"(.*)\" />" )
end
if string.match( line, "filmID" ) then
_,_,video = string.find( line, "var filmID = \'(.*)\';")
end
end
if not name or not arturl or not video then return nil end
-- Try and get URL for SD video.
sd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/")
if not sd then return nil end
page = sd:read( 65653 )
sdurl = string.match( page, "url=\"(.*)\" />")
page = nil
table.insert( p, { path = sdurl; name = name; arturl = arturl; } )
-- Try and check if HD video is available.
checkhd = vlc.stream("http://api.mpora.com/tv/player/load/vid/"..video.."/platform/video/domain/video.mpora.com/" )
if not checkhd then return nil end
page = checkhd:read( 65653 )
hashd = tonumber( string.match( page, "<has_hd>(%d)</has_hd>" ) )
page = nil
if hashd then
hd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/hd/true/")
page = hd:read( 65653 )
hdurl = string.match( page, "url=\"(.*)\" />")
table.insert( p, { path = hdurl; name = name.." (HD)"; arturl = arturl } )
end
return p
end
|
Fix MPORA lua playlist script.
|
Fix MPORA lua playlist script.
|
Lua
|
lgpl-2.1
|
vlc-mirror/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,krichter722/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,vlc-mirror/vlc,xkfz007/vlc,xkfz007/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,shyamalschandra/vlc,xkfz007/vlc,krichter722/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,krichter722/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.2,krichter722/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,shyamalschandra/vlc,shyamalschandra/vlc,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.1
|
593f6384879544855fb0486ca87d9be160a99e91
|
mod_lastlog/mod_lastlog.lua
|
mod_lastlog/mod_lastlog.lua
|
local datamanager = require "util.datamanager";
local time = os.time;
local log_ip = module:get_option_boolean("lastlog_ip_address", false);
local host = module.host;
module:hook("authentication-success", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "login";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end
end);
module:hook("resource-unbind", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "logout";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end
end);
function module.command(arg)
local user, host = require "util.jid".prepped_split(table.remove(arg, 1));
local lastlog = datamanager.load(user, host, "lastlog") or {};
print("Last login: "..(lastlog and os.date("%Y-%m-%d %H:%m:%s", datamanager.load(user, host, "lastlog").time) or "<unknown>"));
if lastlog.ip then
print("IP address: "..lastlog.ip);
end
return 0;
end
|
local datamanager = require "util.datamanager";
local time = os.time;
local log_ip = module:get_option_boolean("lastlog_ip_address", false);
local host = module.host;
module:hook("authentication-success", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "login";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end
end);
module:hook("resource-unbind", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "logout";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end
end);
function module.command(arg)
local user, host = require "util.jid".prepped_split(table.remove(arg, 1));
require"core.storagemanager".initialize_host(host);
local lastlog = assert(datamanager.load(user, host, "lastlog"));
if lastlog then
print(("Last %s: %s"):format(lastlog.event or "login",
lastlog.timestamp and os.date("%Y-%m-%d %H:%M:%S", lastlog.timestamp) or "<unknown>"));
if lastlog.ip then
print("IP address: "..lastlog.ip);
end
else
print("No record found");
end
return 0;
end
|
mod_lastlog: Fix command
|
mod_lastlog: Fix command
|
Lua
|
mit
|
iamliqiang/prosody-modules,jkprg/prosody-modules,syntafin/prosody-modules,cryptotoad/prosody-modules,drdownload/prosody-modules,LanceJenkinZA/prosody-modules,mardraze/prosody-modules,obelisk21/prosody-modules,1st8/prosody-modules,asdofindia/prosody-modules,jkprg/prosody-modules,drdownload/prosody-modules,stephen322/prosody-modules,iamliqiang/prosody-modules,vince06fr/prosody-modules,dhotson/prosody-modules,vfedoroff/prosody-modules,crunchuser/prosody-modules,asdofindia/prosody-modules,prosody-modules/import,apung/prosody-modules,asdofindia/prosody-modules,brahmi2/prosody-modules,mmusial/prosody-modules,either1/prosody-modules,dhotson/prosody-modules,softer/prosody-modules,olax/prosody-modules,obelisk21/prosody-modules,stephen322/prosody-modules,dhotson/prosody-modules,mmusial/prosody-modules,obelisk21/prosody-modules,either1/prosody-modules,syntafin/prosody-modules,guilhem/prosody-modules,vfedoroff/prosody-modules,vince06fr/prosody-modules,softer/prosody-modules,Craige/prosody-modules,heysion/prosody-modules,drdownload/prosody-modules,cryptotoad/prosody-modules,BurmistrovJ/prosody-modules,joewalker/prosody-modules,heysion/prosody-modules,mmusial/prosody-modules,NSAKEY/prosody-modules,prosody-modules/import,1st8/prosody-modules,prosody-modules/import,syntafin/prosody-modules,cryptotoad/prosody-modules,olax/prosody-modules,either1/prosody-modules,softer/prosody-modules,amenophis1er/prosody-modules,Craige/prosody-modules,vince06fr/prosody-modules,1st8/prosody-modules,drdownload/prosody-modules,BurmistrovJ/prosody-modules,softer/prosody-modules,vfedoroff/prosody-modules,mmusial/prosody-modules,syntafin/prosody-modules,guilhem/prosody-modules,amenophis1er/prosody-modules,brahmi2/prosody-modules,jkprg/prosody-modules,LanceJenkinZA/prosody-modules,BurmistrovJ/prosody-modules,either1/prosody-modules,BurmistrovJ/prosody-modules,Craige/prosody-modules,NSAKEY/prosody-modules,joewalker/prosody-modules,joewalker/prosody-modules,heysion/prosody-modules,olax/prosody-modules,crunchuser/prosody-modules,iamliqiang/prosody-modules,LanceJenkinZA/prosody-modules,LanceJenkinZA/prosody-modules,apung/prosody-modules,mardraze/prosody-modules,softer/prosody-modules,NSAKEY/prosody-modules,crunchuser/prosody-modules,crunchuser/prosody-modules,brahmi2/prosody-modules,guilhem/prosody-modules,olax/prosody-modules,asdofindia/prosody-modules,stephen322/prosody-modules,NSAKEY/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,vfedoroff/prosody-modules,cryptotoad/prosody-modules,mardraze/prosody-modules,guilhem/prosody-modules,crunchuser/prosody-modules,either1/prosody-modules,guilhem/prosody-modules,vince06fr/prosody-modules,mardraze/prosody-modules,iamliqiang/prosody-modules,stephen322/prosody-modules,Craige/prosody-modules,asdofindia/prosody-modules,dhotson/prosody-modules,brahmi2/prosody-modules,joewalker/prosody-modules,heysion/prosody-modules,mardraze/prosody-modules,apung/prosody-modules,joewalker/prosody-modules,LanceJenkinZA/prosody-modules,BurmistrovJ/prosody-modules,prosody-modules/import,jkprg/prosody-modules,stephen322/prosody-modules,apung/prosody-modules,amenophis1er/prosody-modules,obelisk21/prosody-modules,Craige/prosody-modules,amenophis1er/prosody-modules,cryptotoad/prosody-modules,vince06fr/prosody-modules,1st8/prosody-modules,1st8/prosody-modules,brahmi2/prosody-modules,vfedoroff/prosody-modules,drdownload/prosody-modules,prosody-modules/import,olax/prosody-modules,syntafin/prosody-modules,jkprg/prosody-modules,amenophis1er/prosody-modules,NSAKEY/prosody-modules,dhotson/prosody-modules,iamliqiang/prosody-modules,mmusial/prosody-modules,heysion/prosody-modules
|
9f31be2af67e592fa8f4046f7c09104c6ae95b1d
|
lua/entities/gmod_starfall_hologram/cl_init.lua
|
lua/entities/gmod_starfall_hologram/cl_init.lua
|
include( "shared.lua" )
ENT.RenderGroup = RENDERGROUP_BOTH
-- Umsgs may be recieved before the entity is initialized, place
-- them in here until initialization.
local msgQueueNames = {}
local msgQueueData = {}
local function msgQueueAdd ( umname, ent, udata )
local names, data = msgQueueNames[ ent ], msgQueueData[ ent ]
if not names then
names, data = {}, {}
msgQueueNames[ ent ] = names
msgQueueData[ ent ] = data
end
local i = #names + 1
names[ i ] = umname
data[ i ] = udata
end
local function msgQueueProcess ( ent )
local entid = ent:EntIndex()
local names, data = msgQueueNames[ entid ], msgQueueData[ entid ]
if names then
for i = 1 , #names do
local name = names[ i ]
if name == "scale" then
ent:SetScale( data[ i ] )
elseif name == "clip" then
ent:UpdateClip( unpack( data[ i ] ) )
end
end
msgQueueNames[ entid ] = nil
msgQueueData[ entid ] = nil
end
end
-- ------------------------ MAIN FUNCTIONS ------------------------ --
function ENT:Initialize()
self.clips = {}
self.unlit = false
self.scale = Vector(1,1,1)
msgQueueProcess(self)
end
function ENT:Draw()
-- Setup clipping
local l = #self.clips
if l > 0 then
render.EnableClipping(true)
for i=1,l do
local clip = self.clips[i]
if clip.enabled then
local norm = clip.normal
local origin = clip.origin
if clip.islocal then
norm = self:LocalToWorld(norm) - self:GetPos()
origin = self:LocalToWorld(origin)
end
render.PushCustomClipPlane(norm, norm:Dot(origin))
end
end
end
render.SuppressEngineLighting(self.unlit)
self:DrawModel()
render.SuppressEngineLighting(false)
for i=1,#self.clips do render.PopCustomClipPlane() end
render.EnableClipping(false)
end
-- ------------------------ CLIPPING ------------------------ --
--- Updates a clip plane definition.
function ENT:UpdateClip(index, enabled, origin, normal, islocal)
local clip = self.clips[index]
if not clip then
clip = {}
self.clips[index] = clip
end
clip.enabled = enabled
clip.normal = normal
clip.origin = origin
clip.islocal = islocal
end
net.Receive("starfall_hologram_clip", function ()
local entid = net.ReadUInt( 32 )
local holoent = Entity( entid )
if not holoent:GetTable() then
-- Uninitialized
msgQueueAdd( "clip", entid, {
net.ReadUInt( 16 ),
net.ReadBit() ~= 0,
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
net.ReadBit() ~= 0
} )
else
holoent:UpdateClip (
net.ReadUInt( 16 ),
net.ReadBit() ~= 0,
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
net.ReadBit() ~= 0
)
end
end )
-- ------------------------ SCALING ------------------------ --
--- Sets the hologram scale
-- @param scale Vector scale
function ENT:SetScale ( scale )
self.scale = scale
local m = Matrix()
m:Scale( scale )
self:EnableMatrix( "RenderMultiply", m )
local propmax = self:OBBMaxs()
local propmin = self:OBBMins()
propmax.x = scale.x * propmax.x
propmax.y = scale.y * propmax.y
propmax.z = scale.z * propmax.z
propmin.x = scale.x * propmin.x
propmin.y = scale.y * propmin.y
propmin.z = scale.z * propmin.z
self:SetRenderBounds( propmax, propmin )
end
net.Receive("starfall_hologram_scale", function ()
local entid = net.ReadUInt( 32 )
local holoent = Entity( entid )
if not holoent:GetTable() then
-- Uninitialized
msgQueueAdd( "scale", entid, Vector(net.ReadDouble(), net.ReadDouble(), net.ReadDouble()) )
else
holoent:SetScale( Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ) )
end
end )
|
include( "shared.lua" )
ENT.RenderGroup = RENDERGROUP_BOTH
-- Umsgs may be recieved before the entity is initialized, place
-- them in here until initialization.
local msgQueueNames = {}
local msgQueueData = {}
local function msgQueueAdd ( umname, ent, udata )
local names, data = msgQueueNames[ ent ], msgQueueData[ ent ]
if not names then
names, data = {}, {}
msgQueueNames[ ent ] = names
msgQueueData[ ent ] = data
end
local i = #names + 1
names[ i ] = umname
data[ i ] = udata
end
local function msgQueueProcess ( ent )
local entid = ent:EntIndex()
local names, data = msgQueueNames[ entid ], msgQueueData[ entid ]
if names then
for i = 1 , #names do
local name = names[ i ]
if name == "scale" then
ent:SetScale( data[ i ] )
elseif name == "clip" then
ent:UpdateClip( unpack( data[ i ] ) )
end
end
msgQueueNames[ entid ] = nil
msgQueueData[ entid ] = nil
end
end
-- ------------------------ MAIN FUNCTIONS ------------------------ --
function ENT:Initialize()
self.clips = {}
self.unlit = false
self.scale = Vector(1,1,1)
self.initialised = true
msgQueueProcess(self)
end
function ENT:Draw()
-- Setup clipping
local l = #self.clips
if l > 0 then
render.EnableClipping(true)
for i=1,l do
local clip = self.clips[i]
if clip.enabled then
local norm = clip.normal
local origin = clip.origin
if clip.islocal then
norm = self:LocalToWorld(norm) - self:GetPos()
origin = self:LocalToWorld(origin)
end
render.PushCustomClipPlane(norm, norm:Dot(origin))
end
end
end
render.SuppressEngineLighting(self.unlit)
self:DrawModel()
render.SuppressEngineLighting(false)
for i=1,#self.clips do render.PopCustomClipPlane() end
render.EnableClipping(false)
end
-- ------------------------ CLIPPING ------------------------ --
--- Updates a clip plane definition.
function ENT:UpdateClip(index, enabled, origin, normal, islocal)
local clip = self.clips[index]
if not clip then
clip = {}
self.clips[index] = clip
end
clip.enabled = enabled
clip.normal = normal
clip.origin = origin
clip.islocal = islocal
end
net.Receive("starfall_hologram_clip", function ()
local entid = net.ReadUInt( 32 )
local holoent = Entity( entid )
if ( not IsValid( holoent ) ) or ( not holoent.initialised ) then
-- Uninitialized
msgQueueAdd( "clip", entid, {
net.ReadUInt( 16 ),
net.ReadBit() ~= 0,
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
net.ReadBit() ~= 0
} )
else
holoent:UpdateClip (
net.ReadUInt( 16 ),
net.ReadBit() ~= 0,
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
net.ReadBit() ~= 0
)
end
end )
-- ------------------------ SCALING ------------------------ --
--- Sets the hologram scale
-- @param scale Vector scale
function ENT:SetScale ( scale )
self.scale = scale
local m = Matrix()
m:Scale( scale )
self:EnableMatrix( "RenderMultiply", m )
local propmax = self:OBBMaxs()
local propmin = self:OBBMins()
propmax.x = scale.x * propmax.x
propmax.y = scale.y * propmax.y
propmax.z = scale.z * propmax.z
propmin.x = scale.x * propmin.x
propmin.y = scale.y * propmin.y
propmin.z = scale.z * propmin.z
self:SetRenderBounds( propmax, propmin )
end
net.Receive("starfall_hologram_scale", function ()
local entid = net.ReadUInt( 32 )
local holoent = Entity( entid )
if ( not IsValid ( holoent ) ) or ( not holoent.initialised ) then
-- Uninitialized
msgQueueAdd( "scale", entid, Vector(net.ReadDouble(), net.ReadDouble(), net.ReadDouble()) )
else
holoent:SetScale( Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ) )
end
end )
|
Fix rare hologram error
|
Fix rare hologram error
If the net message for scaling/clipping arrived in a specific period of
time, it would error. This makes sure the entity is properly initialised
before any scaling or clipping is done.
Finally fixes #20
|
Lua
|
bsd-3-clause
|
INPStarfall/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,Jazzelhawk/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall
|
8368e219b0f716563998bc2465ebe1853b2bc65c
|
mod_pastebin/mod_pastebin.lua
|
mod_pastebin/mod_pastebin.lua
|
local st = require "util.stanza";
local httpserver = require "net.httpserver";
local uuid_new = require "util.uuid".generate;
local os_time = os.time;
local length_threshold = config.get("*", "core", "pastebin_threshold") or 500;
local base_url;
local pastes = {};
local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im";
local xmlns_xhtml = "http://www.w3.org/1999/xhtml";
local function pastebin_message(text)
local uuid = uuid_new();
pastes[uuid] = { text = text, time = os_time() };
return base_url..uuid;
end
function handle_request(method, body, request)
local pasteid = request.url.path:match("[^/]+$");
if not pasteid or not pastes[pasteid] then
return "Invalid paste id, perhaps it expired?";
end
--module:log("debug", "Received request, replying: %s", pastes[pasteid].text);
return pastes[pasteid].text;
end
function check_message(data)
local origin, stanza = data.origin, data.stanza;
local body, bodyindex, htmlindex;
for k,v in ipairs(stanza) do
if v.name == "body" then
body, bodyindex = v, k;
elseif v.name == "html" and v.attr.xmlns == xmlns_xhtml then
htmlindex = k;
end
end
if not body then return; end
body = body:get_text();
module:log("debug", "Body(%s) length: %d", type(body), #(body or ""));
if body and #body > length_threshold then
local url = pastebin_message(body);
module:log("debug", "Pasted message as %s", url);
--module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex]));
stanza[bodyindex][1] = url;
local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml });
html:tag("p"):text(body:sub(1,150)):up();
html:tag("a", { href = url }):text("[...]"):up();
stanza[htmlindex or #stanza+1] = html;
end
end
module:hook("message/bare", check_message);
local ports = config.get(module.host, "core", "pastebin_ports") or { 5280 };
for _, options in ipairs(ports) do
local port, base, ssl, interface = 5280, "pastebin", false, nil;
if type(options) == "number" then
port = options;
elseif type(options) == "table" then
port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface;
elseif type(options) == "string" then
base = options;
end
base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/");
httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl }
end
|
local st = require "util.stanza";
local httpserver = require "net.httpserver";
local uuid_new = require "util.uuid".generate;
local os_time = os.time;
local length_threshold = config.get("*", "core", "pastebin_threshold") or 500;
local base_url = config.get(module.host, "core", "pastebin_url");
local pastes = {};
local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im";
local xmlns_xhtml = "http://www.w3.org/1999/xhtml";
local function pastebin_message(text)
local uuid = uuid_new();
pastes[uuid] = { text = text, time = os_time() };
return base_url..uuid;
end
function handle_request(method, body, request)
local pasteid = request.url.path:match("[^/]+$");
if not pasteid or not pastes[pasteid] then
return "Invalid paste id, perhaps it expired?";
end
--module:log("debug", "Received request, replying: %s", pastes[pasteid].text);
return pastes[pasteid].text;
end
function check_message(data)
local origin, stanza = data.origin, data.stanza;
local body, bodyindex, htmlindex;
for k,v in ipairs(stanza) do
if v.name == "body" then
body, bodyindex = v, k;
elseif v.name == "html" and v.attr.xmlns == xmlns_xhtml then
htmlindex = k;
end
end
if not body then return; end
body = body:get_text();
module:log("debug", "Body(%s) length: %d", type(body), #(body or ""));
if body and #body > length_threshold then
local url = pastebin_message(body);
module:log("debug", "Pasted message as %s", url);
--module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex]));
stanza[bodyindex][1] = url;
local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml });
html:tag("p"):text(body:sub(1,150)):up();
html:tag("a", { href = url }):text("[...]"):up();
stanza[htmlindex or #stanza+1] = html;
end
end
module:hook("message/bare", check_message);
local ports = config.get(module.host, "core", "pastebin_ports") or { 5280 };
for _, options in ipairs(ports) do
local port, base, ssl, interface = 5280, "pastebin", false, nil;
if type(options) == "number" then
port = options;
elseif type(options) == "table" then
port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface;
elseif type(options) == "string" then
base = options;
end
base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/");
httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl }
end
|
mod_pastebin: Small fix to read the pastebin URL from the config
|
mod_pastebin: Small fix to read the pastebin URL from the config
|
Lua
|
mit
|
brahmi2/prosody-modules,stephen322/prosody-modules,olax/prosody-modules,stephen322/prosody-modules,heysion/prosody-modules,1st8/prosody-modules,brahmi2/prosody-modules,mmusial/prosody-modules,vfedoroff/prosody-modules,crunchuser/prosody-modules,asdofindia/prosody-modules,heysion/prosody-modules,LanceJenkinZA/prosody-modules,drdownload/prosody-modules,asdofindia/prosody-modules,iamliqiang/prosody-modules,BurmistrovJ/prosody-modules,NSAKEY/prosody-modules,dhotson/prosody-modules,BurmistrovJ/prosody-modules,asdofindia/prosody-modules,cryptotoad/prosody-modules,mmusial/prosody-modules,jkprg/prosody-modules,amenophis1er/prosody-modules,iamliqiang/prosody-modules,apung/prosody-modules,jkprg/prosody-modules,vince06fr/prosody-modules,softer/prosody-modules,mardraze/prosody-modules,jkprg/prosody-modules,joewalker/prosody-modules,brahmi2/prosody-modules,dhotson/prosody-modules,syntafin/prosody-modules,NSAKEY/prosody-modules,vfedoroff/prosody-modules,cryptotoad/prosody-modules,cryptotoad/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,drdownload/prosody-modules,guilhem/prosody-modules,LanceJenkinZA/prosody-modules,brahmi2/prosody-modules,vince06fr/prosody-modules,NSAKEY/prosody-modules,Craige/prosody-modules,syntafin/prosody-modules,BurmistrovJ/prosody-modules,LanceJenkinZA/prosody-modules,joewalker/prosody-modules,mmusial/prosody-modules,crunchuser/prosody-modules,mardraze/prosody-modules,apung/prosody-modules,1st8/prosody-modules,syntafin/prosody-modules,olax/prosody-modules,joewalker/prosody-modules,amenophis1er/prosody-modules,guilhem/prosody-modules,dhotson/prosody-modules,joewalker/prosody-modules,heysion/prosody-modules,prosody-modules/import,Craige/prosody-modules,LanceJenkinZA/prosody-modules,softer/prosody-modules,stephen322/prosody-modules,prosody-modules/import,apung/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,1st8/prosody-modules,mmusial/prosody-modules,softer/prosody-modules,drdownload/prosody-modules,brahmi2/prosody-modules,vfedoroff/prosody-modules,mardraze/prosody-modules,obelisk21/prosody-modules,vince06fr/prosody-modules,cryptotoad/prosody-modules,vfedoroff/prosody-modules,either1/prosody-modules,either1/prosody-modules,obelisk21/prosody-modules,olax/prosody-modules,heysion/prosody-modules,BurmistrovJ/prosody-modules,stephen322/prosody-modules,guilhem/prosody-modules,jkprg/prosody-modules,BurmistrovJ/prosody-modules,joewalker/prosody-modules,jkprg/prosody-modules,prosody-modules/import,olax/prosody-modules,crunchuser/prosody-modules,amenophis1er/prosody-modules,mardraze/prosody-modules,LanceJenkinZA/prosody-modules,prosody-modules/import,asdofindia/prosody-modules,syntafin/prosody-modules,iamliqiang/prosody-modules,amenophis1er/prosody-modules,amenophis1er/prosody-modules,cryptotoad/prosody-modules,obelisk21/prosody-modules,mardraze/prosody-modules,either1/prosody-modules,dhotson/prosody-modules,drdownload/prosody-modules,vfedoroff/prosody-modules,either1/prosody-modules,guilhem/prosody-modules,prosody-modules/import,mmusial/prosody-modules,dhotson/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,crunchuser/prosody-modules,crunchuser/prosody-modules,1st8/prosody-modules,drdownload/prosody-modules,apung/prosody-modules,vince06fr/prosody-modules,Craige/prosody-modules,iamliqiang/prosody-modules,vince06fr/prosody-modules,obelisk21/prosody-modules,iamliqiang/prosody-modules,syntafin/prosody-modules,stephen322/prosody-modules,asdofindia/prosody-modules,heysion/prosody-modules,softer/prosody-modules,softer/prosody-modules,NSAKEY/prosody-modules,either1/prosody-modules,NSAKEY/prosody-modules,olax/prosody-modules
|
8937557a2808b6ec5876a12d46b00af9f6e1a55e
|
mod_pastebin/mod_pastebin.lua
|
mod_pastebin/mod_pastebin.lua
|
local st = require "util.stanza";
local httpserver = require "net.httpserver";
local uuid_new = require "util.uuid".generate;
local os_time = os.time;
local t_insert, t_remove = table.insert, table.remove;
local add_task = require "util.timer".add_task;
local length_threshold = config.get(module.host, "core", "pastebin_threshold") or 500;
local line_threshold = config.get(module.host, "core", "pastebin_line_threshold") or 4;
local base_url = config.get(module.host, "core", "pastebin_url");
-- Seconds a paste should live for in seconds (config is in hours), default 24 hours
local expire_after = math.floor((config.get(module.host, "core", "pastebin_expire_after") or 24) * 3600);
local trigger_string = config.get(module.host, "core", "pastebin_trigger");
trigger_string = (trigger_string and trigger_string .. " ");
local pastes = {};
local default_headers = { ["Content-Type"] = "text/plain; charset=utf-8" };
local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im";
local xmlns_xhtml = "http://www.w3.org/1999/xhtml";
function pastebin_text(text)
local uuid = uuid_new();
pastes[uuid] = { body = text, time = os_time(), headers = default_headers };
pastes[#pastes+1] = uuid;
if not pastes[2] then -- No other pastes, give the timer a kick
add_task(expire_after, expire_pastes);
end
return base_url..uuid;
end
function handle_request(method, body, request)
local pasteid = request.url.path:match("[^/]+$");
if not pasteid or not pastes[pasteid] then
return "Invalid paste id, perhaps it expired?";
end
--module:log("debug", "Received request, replying: %s", pastes[pasteid].text);
return pastes[pasteid];
end
function check_message(data)
local origin, stanza = data.origin, data.stanza;
local body, bodyindex, htmlindex;
for k,v in ipairs(stanza) do
if v.name == "body" then
body, bodyindex = v, k;
elseif v.name == "html" and v.attr.xmlns == xmlns_xhtmlim then
htmlindex = k;
end
end
if not body then return; end
body = body:get_text();
--module:log("debug", "Body(%s) length: %d", type(body), #(body or ""));
if body and (
(#body > length_threshold) or
(trigger_string and body:find(trigger_string, 1, true) == 1) or
(select(2, body:gsub("\n", "%0")) >= line_threshold)
) then
if trigger_string then
body = body:gsub("^" .. trigger_string, "", 1);
end
local url = pastebin_text(body);
module:log("debug", "Pasted message as %s", url);
--module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex]));
stanza[bodyindex][1] = url;
local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml });
html:tag("p"):text(body:sub(1,150):gsub("[\128-\255]+$", "")):up();
html:tag("a", { href = url }):text("[...]"):up();
stanza[htmlindex or #stanza+1] = html;
end
end
module:hook("message/bare", check_message);
function expire_pastes(time)
time = time or os_time(); -- COMPAT with 0.5
if pastes[1] then
pastes[pastes[1]] = nil;
t_remove(pastes, 1);
if pastes[1] then
return (expire_after - (time - pastes[pastes[1]].time)) + 1;
end
end
end
local ports = config.get(module.host, "core", "pastebin_ports") or { 5280 };
for _, options in ipairs(ports) do
local port, base, ssl, interface = 5280, "pastebin", false, nil;
if type(options) == "number" then
port = options;
elseif type(options) == "table" then
port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface;
elseif type(options) == "string" then
base = options;
end
base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/");
httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl }
end
|
local st = require "util.stanza";
local httpserver = require "net.httpserver";
local uuid_new = require "util.uuid".generate;
local os_time = os.time;
local t_insert, t_remove = table.insert, table.remove;
local add_task = require "util.timer".add_task;
local function drop_invalid_utf8(seq)
local start = seq:byte();
module:log("utf8: %d, %d", start, #seq);
if (start <= 223 and #seq < 2)
or (start >= 224 and start <= 239 and #seq < 3)
or (start >= 240 and start <= 244 and #seq < 4)
or (start > 244) then
return "";
end
return seq;
end
local length_threshold = config.get(module.host, "core", "pastebin_threshold") or 500;
local line_threshold = config.get(module.host, "core", "pastebin_line_threshold") or 4;
local base_url = config.get(module.host, "core", "pastebin_url");
-- Seconds a paste should live for in seconds (config is in hours), default 24 hours
local expire_after = math.floor((config.get(module.host, "core", "pastebin_expire_after") or 24) * 3600);
local trigger_string = config.get(module.host, "core", "pastebin_trigger");
trigger_string = (trigger_string and trigger_string .. " ");
local pastes = {};
local default_headers = { ["Content-Type"] = "text/plain; charset=utf-8" };
local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im";
local xmlns_xhtml = "http://www.w3.org/1999/xhtml";
function pastebin_text(text)
local uuid = uuid_new();
pastes[uuid] = { body = text, time = os_time(), headers = default_headers };
pastes[#pastes+1] = uuid;
if not pastes[2] then -- No other pastes, give the timer a kick
add_task(expire_after, expire_pastes);
end
return base_url..uuid;
end
function handle_request(method, body, request)
local pasteid = request.url.path:match("[^/]+$");
if not pasteid or not pastes[pasteid] then
return "Invalid paste id, perhaps it expired?";
end
--module:log("debug", "Received request, replying: %s", pastes[pasteid].text);
return pastes[pasteid];
end
function check_message(data)
local origin, stanza = data.origin, data.stanza;
local body, bodyindex, htmlindex;
for k,v in ipairs(stanza) do
if v.name == "body" then
body, bodyindex = v, k;
elseif v.name == "html" and v.attr.xmlns == xmlns_xhtmlim then
htmlindex = k;
end
end
if not body then return; end
body = body:get_text();
--module:log("debug", "Body(%s) length: %d", type(body), #(body or ""));
if body and (
(#body > length_threshold) or
(trigger_string and body:find(trigger_string, 1, true) == 1) or
(select(2, body:gsub("\n", "%0")) >= line_threshold)
) then
if trigger_string then
body = body:gsub("^" .. trigger_string, "", 1);
end
local url = pastebin_text(body);
module:log("debug", "Pasted message as %s", url);
--module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex]));
stanza[bodyindex][1] = url;
local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml });
html:tag("p"):text(body:sub(1,150):gsub("[\194-\244][\128-\191]*$", drop_invalid_utf8)):up();
html:tag("a", { href = url }):text("[...]"):up();
stanza[htmlindex or #stanza+1] = html;
end
end
module:hook("message/bare", check_message);
function expire_pastes(time)
time = time or os_time(); -- COMPAT with 0.5
if pastes[1] then
pastes[pastes[1]] = nil;
t_remove(pastes, 1);
if pastes[1] then
return (expire_after - (time - pastes[pastes[1]].time)) + 1;
end
end
end
local ports = config.get(module.host, "core", "pastebin_ports") or { 5280 };
for _, options in ipairs(ports) do
local port, base, ssl, interface = 5280, "pastebin", false, nil;
if type(options) == "number" then
port = options;
elseif type(options) == "table" then
port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface;
elseif type(options) == "string" then
base = options;
end
base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/");
httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl }
end
|
mod_pastebin: Better fix for stripping truncated UFT-8 sequences
|
mod_pastebin: Better fix for stripping truncated UFT-8 sequences
|
Lua
|
mit
|
apung/prosody-modules,mardraze/prosody-modules,mmusial/prosody-modules,cryptotoad/prosody-modules,NSAKEY/prosody-modules,1st8/prosody-modules,syntafin/prosody-modules,BurmistrovJ/prosody-modules,brahmi2/prosody-modules,vfedoroff/prosody-modules,heysion/prosody-modules,mardraze/prosody-modules,iamliqiang/prosody-modules,amenophis1er/prosody-modules,NSAKEY/prosody-modules,BurmistrovJ/prosody-modules,iamliqiang/prosody-modules,dhotson/prosody-modules,drdownload/prosody-modules,heysion/prosody-modules,jkprg/prosody-modules,joewalker/prosody-modules,syntafin/prosody-modules,apung/prosody-modules,cryptotoad/prosody-modules,apung/prosody-modules,asdofindia/prosody-modules,LanceJenkinZA/prosody-modules,guilhem/prosody-modules,stephen322/prosody-modules,obelisk21/prosody-modules,amenophis1er/prosody-modules,brahmi2/prosody-modules,Craige/prosody-modules,jkprg/prosody-modules,olax/prosody-modules,either1/prosody-modules,drdownload/prosody-modules,stephen322/prosody-modules,NSAKEY/prosody-modules,softer/prosody-modules,joewalker/prosody-modules,either1/prosody-modules,crunchuser/prosody-modules,guilhem/prosody-modules,Craige/prosody-modules,stephen322/prosody-modules,vince06fr/prosody-modules,olax/prosody-modules,vince06fr/prosody-modules,vfedoroff/prosody-modules,dhotson/prosody-modules,NSAKEY/prosody-modules,joewalker/prosody-modules,BurmistrovJ/prosody-modules,1st8/prosody-modules,syntafin/prosody-modules,either1/prosody-modules,apung/prosody-modules,asdofindia/prosody-modules,prosody-modules/import,amenophis1er/prosody-modules,LanceJenkinZA/prosody-modules,prosody-modules/import,1st8/prosody-modules,BurmistrovJ/prosody-modules,iamliqiang/prosody-modules,stephen322/prosody-modules,olax/prosody-modules,softer/prosody-modules,vince06fr/prosody-modules,jkprg/prosody-modules,softer/prosody-modules,mmusial/prosody-modules,cryptotoad/prosody-modules,crunchuser/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,prosody-modules/import,iamliqiang/prosody-modules,NSAKEY/prosody-modules,asdofindia/prosody-modules,BurmistrovJ/prosody-modules,Craige/prosody-modules,mardraze/prosody-modules,drdownload/prosody-modules,dhotson/prosody-modules,dhotson/prosody-modules,softer/prosody-modules,brahmi2/prosody-modules,amenophis1er/prosody-modules,amenophis1er/prosody-modules,either1/prosody-modules,obelisk21/prosody-modules,LanceJenkinZA/prosody-modules,olax/prosody-modules,crunchuser/prosody-modules,heysion/prosody-modules,LanceJenkinZA/prosody-modules,jkprg/prosody-modules,mmusial/prosody-modules,crunchuser/prosody-modules,brahmi2/prosody-modules,LanceJenkinZA/prosody-modules,vince06fr/prosody-modules,mmusial/prosody-modules,softer/prosody-modules,1st8/prosody-modules,dhotson/prosody-modules,asdofindia/prosody-modules,joewalker/prosody-modules,iamliqiang/prosody-modules,asdofindia/prosody-modules,mardraze/prosody-modules,obelisk21/prosody-modules,mmusial/prosody-modules,syntafin/prosody-modules,vfedoroff/prosody-modules,joewalker/prosody-modules,vince06fr/prosody-modules,cryptotoad/prosody-modules,drdownload/prosody-modules,Craige/prosody-modules,vfedoroff/prosody-modules,either1/prosody-modules,guilhem/prosody-modules,apung/prosody-modules,stephen322/prosody-modules,1st8/prosody-modules,guilhem/prosody-modules,cryptotoad/prosody-modules,brahmi2/prosody-modules,obelisk21/prosody-modules,crunchuser/prosody-modules,mardraze/prosody-modules,jkprg/prosody-modules,drdownload/prosody-modules,prosody-modules/import,vfedoroff/prosody-modules,olax/prosody-modules,obelisk21/prosody-modules,syntafin/prosody-modules,prosody-modules/import,heysion/prosody-modules,heysion/prosody-modules
|
04b5a204e46d6a7ac2ea3eecc8004666b96d28c0
|
demos/monkey/threepwood.lua
|
demos/monkey/threepwood.lua
|
--! Monkey Demo: Guybrush Threepwood
--!
--! Copyright 2011-12 Bifrost Entertainment. All rights reserved.
--! \author Tommy Nguyen
Threepwood = {};
Threepwood.__index = Threepwood;
function Threepwood.new(assets)
local guybrush = {};
setmetatable(guybrush, Threepwood);
-- Load Guybrush standing, facing left or right
guybrush.standingr = assets:create(400, 875, 104, 149);
guybrush.standingl = assets:create(504, 875, 104, 149);
-- Load Guybrush walking, facing left or right
guybrush.walkingl = {};
guybrush.walkingr = {};
local x = 400;
for i = 1,6 do
guybrush.walkingl[i] = assets:create(x, 724, 104, 149);
guybrush.walkingr[i] = assets:create(x, 575, 104, 149);
x = x + 104;
end
guybrush.walkingl = rainbow.animation(nil, guybrush.walkingl, 7);
guybrush.walkingr = rainbow.animation(nil, guybrush.walkingr, 7);
-- Variables for controlling animations
guybrush.walk = nil;
guybrush.walking = nil;
guybrush.direction = nil;
guybrush.face = 1;
guybrush.lock = false;
return guybrush;
end
function Threepwood:deinit()
rainbow.scenegraph:remove(self.parent_node, self.node);
rainbow.input.unsubscribe(self);
end
function Threepwood:get_position()
return self.x, self.y;
end
function Threepwood:init(parent, spritebatch, x, y)
-- Add Guybrush to the sprite batch.
self.sprite = spritebatch:add(400, 875, 104, 149);
self.x = x;
self.y = y;
self.sprite:set_position(self.x, self.y);
-- Bind the animation to the sprite.
self.walkingl:set_sprite(self.sprite);
self.walkingr:set_sprite(self.sprite);
self.parent_node = parent;
end
function Threepwood:move(pos)
if self.lock then
return
end
-- Determine the direction Guybrush is facing and start the walking animation.
rainbow.scenegraph:remove(self.parent_node, self.animation_node);
self.walk = pos;
if self.x < self.walk.x then
self.direction = self.standingr;
self.face = 1;
self.walking = self.walkingr;
else
self.direction = self.standingl;
self.face = -1;
self.walking = self.walkingl;
end
self.animation_node = rainbow.scenegraph:add_animation(self.parent_node, self.walking);
end
function Threepwood:stop()
rainbow.scenegraph:remove(self.parent_node, self.animation_node);
self.sprite:set_texture(self.direction);
self.walk = nil;
end
function Threepwood:update()
if self.walk then
-- While Guybrush is walking check for when he reaches his destination
-- and stop the animation.
local diff_x = global_scale * self.face;
self.x = self.x + diff_x;
if self.face > 0 and self.x >= self.walk.x or self.face < 0 and self.x <= self.walk.x then
diff_x = diff_x - (self.x - self.walk.x);
self.x = self.walk.x;
self.walk = nil;
self:stop();
end
self.sprite:move(diff_x, 0);
elseif self.lock then
-- While Guybrush is locked, get his screen position
self.x, self.y = self.sprite:get_position();
end
end
|
--! Monkey Demo: Guybrush Threepwood
--!
--! Copyright 2011-12 Bifrost Entertainment. All rights reserved.
--! \author Tommy Nguyen
Threepwood = {};
Threepwood.__index = Threepwood;
function Threepwood.new(assets)
local guybrush = {};
setmetatable(guybrush, Threepwood);
-- Load Guybrush standing, facing left or right
guybrush.standingr = assets:create(400, 875, 104, 149);
guybrush.standingl = assets:create(504, 875, 104, 149);
-- Load Guybrush walking, facing left or right
guybrush.walkingl = {};
guybrush.walkingr = {};
local x = 400;
for i = 1,6 do
guybrush.walkingl[i] = assets:create(x, 724, 104, 149);
guybrush.walkingr[i] = assets:create(x, 575, 104, 149);
x = x + 104;
end
guybrush.walkingl = rainbow.animation(nil, guybrush.walkingl, 7);
guybrush.walkingr = rainbow.animation(nil, guybrush.walkingr, 7);
-- Variables for controlling animations
guybrush.walk = nil;
guybrush.walking = nil;
guybrush.direction = nil;
guybrush.face = 1;
guybrush.lock = false;
return guybrush;
end
function Threepwood:deinit()
rainbow.scenegraph:remove(self.parent_node, self.node);
rainbow.input.unsubscribe(self);
end
function Threepwood:get_position()
return self.x, self.y;
end
function Threepwood:init(parent, spritebatch, x, y)
-- Add Guybrush to the sprite batch.
self.sprite = spritebatch:add(400, 875, 104, 149);
self.x = x;
self.y = y;
self.sprite:set_position(self.x, self.y);
-- Bind the animation to the sprite.
self.walkingl:set_sprite(self.sprite);
self.walkingr:set_sprite(self.sprite);
self.parent_node = parent;
end
function Threepwood:move(pos)
if self.lock then
return
end
-- Determine the direction Guybrush is facing and start the walking animation.
if self.animation_node then
rainbow.scenegraph:remove(self.parent_node, self.animation_node);
end
self.walk = pos;
if self.x < self.walk.x then
self.direction = self.standingr;
self.face = 1;
self.walking = self.walkingr;
else
self.direction = self.standingl;
self.face = -1;
self.walking = self.walkingl;
end
self.animation_node = rainbow.scenegraph:add_animation(self.parent_node, self.walking);
end
function Threepwood:stop()
rainbow.scenegraph:remove(self.parent_node, self.animation_node);
self.animation_node = nil;
self.sprite:set_texture(self.direction);
self.walk = nil;
end
function Threepwood:update()
if self.walk then
-- While Guybrush is walking check for when he reaches his destination
-- and stop the animation.
local diff_x = global_scale * self.face;
self.x = self.x + diff_x;
if self.face > 0 and self.x >= self.walk.x or self.face < 0 and self.x <= self.walk.x then
diff_x = diff_x - (self.x - self.walk.x);
self.x = self.walk.x;
self.walk = nil;
self:stop();
end
self.sprite:move(diff_x, 0);
elseif self.lock then
-- While Guybrush is locked, get his screen position
self.x, self.y = self.sprite:get_position();
end
end
|
demos/monkey: Fixed a segmentation fault.
|
demos/monkey: Fixed a segmentation fault.
Spamming mouse/touch events can cause Threepwood's
animation node to be removed twice.
|
Lua
|
mit
|
tn0502/rainbow,tn0502/rainbow,tn0502/rainbow,tn0502/rainbow,pandaforks/tido-rainbow,pandaforks/tido-rainbow,pandaforks/tido-rainbow,tn0502/rainbow,pandaforks/tido-rainbow,pandaforks/tido-rainbow,tn0502/rainbow
|
58d9f5c0b3172809f7981e5ac78fcefa5d5ca8ee
|
tools/kobo_touch_probe.lua
|
tools/kobo_touch_probe.lua
|
-- touch probe utility
-- usage: ./luajit tools/kobo_touch_probe.lua
require "defaults"
package.path = "common/?.lua;rocks/share/lua/5.1/?.lua;frontend/?.lua;" .. package.path
package.cpath = "common/?.so;common/?.dll;/usr/lib/lua/?.so;rocks/lib/lua/5.1/?.so;" .. package.cpath
local DataStorage = require("datastorage")
local _ = require("gettext")
-- read settings and check for language override
-- has to be done before requiring other files because
-- they might call gettext on load
G_reader_settings = require("luasettings"):open(
DataStorage:getDataDir().."/settings.reader.lua")
local lang_locale = G_reader_settings:readSetting("language")
if lang_locale then
_.changeLang(lang_locale)
end
local InputContainer = require("ui/widget/container/inputcontainer")
local CenterContainer = require("ui/widget/container/centercontainer")
local FrameContainer = require("ui/widget/container/framecontainer")
local RightContainer = require("ui/widget/container/rightcontainer")
local OverlapGroup = require("ui/widget/overlapgroup")
local ImageWidget = require("ui/widget/imagewidget")
local TextWidget = require("ui/widget/textwidget")
local GestureRange = require("ui/gesturerange")
local UIManager = require("ui/uimanager")
local Blitbuffer = require("ffi/blitbuffer")
local Geom = require("ui/geometry")
local Device = require("device")
local Screen = Device.screen
local Input = Device.input
local Font = require("ui/font")
local dbg = require("dbg")
--dbg:turnOn()
local TouchProbe = InputContainer:new{
curr_probe_step = 1,
}
function TouchProbe:init()
self.ges_events = {
TapProbe = {
GestureRange:new{
ges = "tap",
}
},
}
self.image_widget = ImageWidget:new{
file = "resources/kobo-touch-probe.png",
}
local screen_w, screen_h = Screen:getWidth(), Screen:getHeight()
local img_w, img_h = self.image_widget:getSize().w, self.image_widget:getSize().h
self.probe_steps = {
{
hint_text = _("Tap the lower right corner"),
hint_icon_pos = {
x = screen_w-img_w,
y = screen_h-img_h,
}
},
{
hint_text = _("Tap the upper right corner"),
hint_icon_pos = {
x = screen_w-img_w,
y = 0,
}
},
}
self.hint_text_widget = TextWidget:new{
text = '',
face = Font:getFace("cfont", 30),
}
self[1] = FrameContainer:new{
bordersize = 0,
background = Blitbuffer.COLOR_WHITE,
OverlapGroup:new{
dimen = Screen:getSize(),
CenterContainer:new{
dimen = Screen:getSize(),
self.hint_text_widget,
},
self.image_widget,
},
}
self:updateProbeInstruction()
end
function TouchProbe:updateProbeInstruction()
local probe_step = self.probe_steps[self.curr_probe_step]
self.image_widget.overlap_offset = {
probe_step.hint_icon_pos.x,
probe_step.hint_icon_pos.y,
}
self.hint_text_widget:setText(probe_step.hint_text)
end
function TouchProbe:saveSwitchXYSetting(need_to_switch_xy)
-- save the settings here so device.input can pick it up
G_reader_settings:saveSetting("kobo_touch_switch_xy", need_to_switch_xy)
G_reader_settings:flush()
UIManager:quit()
end
function TouchProbe:onTapProbe(arg, ges)
if self.curr_probe_step == 1 then
local shorter_edge = math.min(Screen:getHeight(), Screen:getWidth())
if math.min(ges.pos.x, ges.pos.y) < shorter_edge/2 then
-- x mirrored, x should be close to zero and y should be close to
-- screen height
local need_to_switch_xy = ges.pos.x > ges.pos.y
self:saveSwitchXYSetting(need_to_switch_xy)
else
-- x not mirroed, need one more probe
self.curr_probe_step = 2
self:updateProbeInstruction()
UIManager:setDirty(self)
end
elseif self.curr_probe_step == 2 then
-- x not mirrored, y should be close to zero and x should be close
-- TouchProbe screen width
local need_to_switch_xy = ges.pos.x < ges.pos.y
self:saveSwitchXYSetting(need_to_switch_xy)
end
end
return TouchProbe
|
-- touch probe utility
-- usage: ./luajit tools/kobo_touch_probe.lua
require "defaults"
package.path = "common/?.lua;rocks/share/lua/5.1/?.lua;frontend/?.lua;" .. package.path
package.cpath = "common/?.so;common/?.dll;/usr/lib/lua/?.so;rocks/lib/lua/5.1/?.so;" .. package.cpath
local DataStorage = require("datastorage")
local _ = require("gettext")
-- read settings and check for language override
-- but don't re-read if already done, to avoid causing problems for unit tests
-- has to be done before requiring other files because
-- they might call gettext on load
if G_reader_settings == nil then
G_reader_settings = require("luasettings"):open(
DataStorage:getDataDir().."/settings.reader.lua")
end
local lang_locale = G_reader_settings:readSetting("language")
if lang_locale then
_.changeLang(lang_locale)
end
local InputContainer = require("ui/widget/container/inputcontainer")
local CenterContainer = require("ui/widget/container/centercontainer")
local FrameContainer = require("ui/widget/container/framecontainer")
local RightContainer = require("ui/widget/container/rightcontainer")
local OverlapGroup = require("ui/widget/overlapgroup")
local ImageWidget = require("ui/widget/imagewidget")
local TextWidget = require("ui/widget/textwidget")
local GestureRange = require("ui/gesturerange")
local UIManager = require("ui/uimanager")
local Blitbuffer = require("ffi/blitbuffer")
local Geom = require("ui/geometry")
local Device = require("device")
local Screen = Device.screen
local Input = Device.input
local Font = require("ui/font")
local dbg = require("dbg")
--dbg:turnOn()
local TouchProbe = InputContainer:new{
curr_probe_step = 1,
}
function TouchProbe:init()
self.ges_events = {
TapProbe = {
GestureRange:new{
ges = "tap",
}
},
}
self.image_widget = ImageWidget:new{
file = "resources/kobo-touch-probe.png",
}
local screen_w, screen_h = Screen:getWidth(), Screen:getHeight()
local img_w, img_h = self.image_widget:getSize().w, self.image_widget:getSize().h
self.probe_steps = {
{
hint_text = _("Tap the lower right corner"),
hint_icon_pos = {
x = screen_w-img_w,
y = screen_h-img_h,
}
},
{
hint_text = _("Tap the upper right corner"),
hint_icon_pos = {
x = screen_w-img_w,
y = 0,
}
},
}
self.hint_text_widget = TextWidget:new{
text = '',
face = Font:getFace("cfont", 30),
}
self[1] = FrameContainer:new{
bordersize = 0,
background = Blitbuffer.COLOR_WHITE,
OverlapGroup:new{
dimen = Screen:getSize(),
CenterContainer:new{
dimen = Screen:getSize(),
self.hint_text_widget,
},
self.image_widget,
},
}
self:updateProbeInstruction()
end
function TouchProbe:updateProbeInstruction()
local probe_step = self.probe_steps[self.curr_probe_step]
self.image_widget.overlap_offset = {
probe_step.hint_icon_pos.x,
probe_step.hint_icon_pos.y,
}
self.hint_text_widget:setText(probe_step.hint_text)
end
function TouchProbe:saveSwitchXYSetting(need_to_switch_xy)
-- save the settings here so device.input can pick it up
G_reader_settings:saveSetting("kobo_touch_switch_xy", need_to_switch_xy)
G_reader_settings:flush()
UIManager:quit()
end
function TouchProbe:onTapProbe(arg, ges)
if self.curr_probe_step == 1 then
local shorter_edge = math.min(Screen:getHeight(), Screen:getWidth())
if math.min(ges.pos.x, ges.pos.y) < shorter_edge/2 then
-- x mirrored, x should be close to zero and y should be close to
-- screen height
local need_to_switch_xy = ges.pos.x > ges.pos.y
self:saveSwitchXYSetting(need_to_switch_xy)
else
-- x not mirroed, need one more probe
self.curr_probe_step = 2
self:updateProbeInstruction()
UIManager:setDirty(self)
end
elseif self.curr_probe_step == 2 then
-- x not mirrored, y should be close to zero and x should be close
-- TouchProbe screen width
local need_to_switch_xy = ges.pos.x < ges.pos.y
self:saveSwitchXYSetting(need_to_switch_xy)
end
end
return TouchProbe
|
[fix, spec] Stop the kobo_touch_probe test from causing problems for other tests. (#3877)
|
[fix, spec] Stop the kobo_touch_probe test from causing problems for other tests. (#3877)
Previously, it caused problems because it was overriding G_reader_settings,
which caused the Translator test to fail on the second (but not first) run.
|
Lua
|
agpl-3.0
|
Frenzie/koreader,NiLuJe/koreader,mihailim/koreader,koreader/koreader,koreader/koreader,poire-z/koreader,NiLuJe/koreader,Markismus/koreader,poire-z/koreader,lgeek/koreader,mwoz123/koreader,pazos/koreader,Hzj-jie/koreader,Frenzie/koreader,houqp/koreader
|
9190a1653faf0bac9ff9ed2bbb258b09393a4110
|
lua/include/pipe.lua
|
lua/include/pipe.lua
|
local mod = {}
local memory = require "memory"
local ffi = require "ffi"
local serpent = require "Serpent"
local dpdk = require "dpdk"
ffi.cdef [[
// dummy
struct spsc_ptr_queue { };
struct spsc_ptr_queue* make_pipe();
void enqueue(struct spsc_ptr_queue* queue, void* data);
void* try_dequeue(struct spsc_ptr_queue* queue);
void* peek(struct spsc_ptr_queue* queue);
uint8_t pop(struct spsc_ptr_queue* queue);
size_t count(struct spsc_ptr_queue* queue);
]]
local C = ffi.C
mod.slowPipe = {}
local slowPipe = mod.slowPipe
slowPipe.__index = slowPipe
--- Create a new slow pipe.
-- A pipe can only be used by exactly two tasks: a single reader and a single writer.
-- Slow pipes are called slow pipe because they are slow (duh).
-- Any objects passed to it will be *serialized* as strings.
-- This means that it supports arbitrary Lua objects following MoonGens usual serialization rules.
-- Use a 'fast pipe' if you need fast inter-task communication. Fast pipes are restricted to LuaJIT FFI objects.
function mod:newSlowPipe()
return setmetatable({
pipe = C.make_pipe()
}, slowPipe)
end
function slowPipe:send(...)
local vals = serpent.dump({ ... })
local buf = memory.alloc("char*", #vals + 1)
ffi.copy(buf, vals)
C.enqueue(self.pipe, buf)
end
function slowPipe:tryRecv(wait)
while wait >= 0 do
local buf = C.try_dequeue(self.pipe)
if buf ~= nil then
return unpackAll(loadstring(ffi.string(buf))())
end
wait = wait - 10
if wait < 0 then
break
end
dpdk.sleepMicros(10)
end
end
function slowPipe:recv()
local function loop(...)
if not ... then
return loop(self:tryRecv(10))
else
return ...
end
end
return loop()
end
function slowPipe:__serialize()
return "require'pipe'; return " .. serpent.addMt(serpent.dumpRaw(self), "require('pipe').slowPipe"), true
end
function mod:newFastPipe()
error("NYI")
end
return mod
|
local mod = {}
local memory = require "memory"
local ffi = require "ffi"
local serpent = require "Serpent"
local dpdk = require "dpdk"
ffi.cdef [[
// dummy
struct spsc_ptr_queue { };
struct spsc_ptr_queue* make_pipe();
void enqueue(struct spsc_ptr_queue* queue, void* data);
void* try_dequeue(struct spsc_ptr_queue* queue);
void* peek(struct spsc_ptr_queue* queue);
uint8_t pop(struct spsc_ptr_queue* queue);
size_t count(struct spsc_ptr_queue* queue);
]]
local C = ffi.C
mod.slowPipe = {}
local slowPipe = mod.slowPipe
slowPipe.__index = slowPipe
--- Create a new slow pipe.
-- A pipe can only be used by exactly two tasks: a single reader and a single writer.
-- Slow pipes are called slow pipe because they are slow (duh).
-- Any objects passed to it will be *serialized* as strings.
-- This means that it supports arbitrary Lua objects following MoonGens usual serialization rules.
-- Use a 'fast pipe' if you need fast inter-task communication. Fast pipes are restricted to LuaJIT FFI objects.
function mod:newSlowPipe()
return setmetatable({
pipe = C.make_pipe()
}, slowPipe)
end
function slowPipe:send(...)
local vals = serpent.dump({ ... })
local buf = memory.alloc("char*", #vals + 1)
ffi.copy(buf, vals)
C.enqueue(self.pipe, buf)
end
function slowPipe:tryRecv(wait)
while wait >= 0 do
local buf = C.try_dequeue(self.pipe)
if buf ~= nil then
local result = loadstring(ffi.string(buf))()
memory.free(buf)
return unpackAll(result)
end
wait = wait - 10
if wait < 0 then
break
end
dpdk.sleepMicros(10)
end
end
function slowPipe:recv()
local function loop(...)
if not ... then
return loop(self:tryRecv(10))
else
return ...
end
end
return loop()
end
function slowPipe:__serialize()
return "require'pipe'; return " .. serpent.addMt(serpent.dumpRaw(self), "require('pipe').slowPipe"), true
end
function mod:newFastPipe()
error("NYI")
end
return mod
|
fix memory leak
|
fix memory leak
|
Lua
|
mit
|
emmericp/MoonGen,bmichalo/MoonGen,atheurer/MoonGen,kidaa/MoonGen,scholzd/MoonGen,NetronomeMoongen/MoonGen,gallenmu/MoonGen,duk3luk3/MoonGen,kidaa/MoonGen,wenhuizhang/MoonGen,bmichalo/MoonGen,duk3luk3/MoonGen,pavel-odintsov/MoonGen,gallenmu/MoonGen,NetronomeMoongen/MoonGen,gallenmu/MoonGen,slyon/MoonGen,kidaa/MoonGen,NetronomeMoongen/MoonGen,werpat/MoonGen,scholzd/MoonGen,slyon/MoonGen,slyon/MoonGen,pavel-odintsov/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,werpat/MoonGen,werpat/MoonGen,schoenb/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,schoenb/MoonGen,wenhuizhang/MoonGen,schoenb/MoonGen,gallenmu/MoonGen,duk3luk3/MoonGen,bmichalo/MoonGen,wenhuizhang/MoonGen,scholzd/MoonGen,emmericp/MoonGen,dschoeffm/MoonGen,slyon/MoonGen,dschoeffm/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,atheurer/MoonGen,pavel-odintsov/MoonGen,atheurer/MoonGen
|
c62d5520e16b2ecdfef4dc83479813b6d8293f44
|
Parallel.lua
|
Parallel.lua
|
local Parallel, parent = torch.class('nn.Parallel', 'nn.Container')
function Parallel:__init(inputDimension,outputDimension)
parent.__init(self)
self.modules = {}
self.size = torch.LongStorage()
self.inputDimension = inputDimension
self.outputDimension = outputDimension
end
function Parallel:updateOutput(input)
local nModule=input:size(self.inputDimension)
local outputs = {}
for i=1,nModule do
local currentInput = input:select(self.inputDimension,i)
local currentOutput = self.modules[i]:updateOutput(currentInput)
table.insert(outputs, currentOutput)
local outputSize = currentOutput:size(self.outputDimension)
if i == 1 then
self.size:resize(currentOutput:dim()):copy(currentOutput:size())
else
self.size[self.outputDimension] = self.size[self.outputDimension] + outputSize
end
end
self.output:resize(self.size)
local offset = 1
for i=1,nModule do
local currentOutput = outputs[i]
local outputSize = currentOutput:size(self.outputDimension)
self.output:narrow(self.outputDimension, offset, outputSize):copy(currentOutput)
offset = offset + currentOutput:size(self.outputDimension)
end
return self.output
end
function Parallel:updateGradInput(input, gradOutput)
local nModule=input:size(self.inputDimension)
self.gradInput:resizeAs(input)
local offset = 1
for i=1,nModule do
local module=self.modules[i]
local currentInput = input:select(self.inputDimension,i)
local currentOutput = module.output
local outputSize = currentOutput:size(self.outputDimension)
local currentGradOutput = gradOutput:narrow(self.outputDimension, offset, outputSize)
local currentGradInput = module:updateGradInput(currentInput, currentGradOutput)
self.gradInput:select(self.inputDimension,i):copy(currentGradInput)
offset = offset + outputSize
end
return self.gradInput
end
function Parallel:accGradParameters(input, gradOutput, scale)
local nModule=input:size(self.inputDimension)
local offset = 1
for i=1,nModule do
local module = self.modules[i]
local currentOutput = module.output
local outputSize = currentOutput:size(self.outputDimension)
module:accGradParameters(
input:select(self.inputDimension,i),
gradOutput:narrow(self.outputDimension, offset,outputSize),
scale
)
offset = offset + outputSize
end
end
function Parallel:accUpdateGradParameters(input, gradOutput, lr)
local nModule=input:size(self.inputDimension)
local offset = 1
for i=1,nModule do
local module = self.modules[i];
local currentOutput = module.output
module:accUpdateGradParameters(
input:select(self.inputDimension,i),
gradOutput:narrow(self.outputDimension, offset,
currentOutput:size(self.outputDimension)),
lr)
offset = offset + currentOutput:size(self.outputDimension)
end
end
function Parallel:__tostring__()
local tab = ' '
local line = '\n'
local next = ' |`-> '
local ext = ' | '
local extlast = ' '
local last = ' ... -> '
local str = torch.type(self)
str = str .. ' {' .. line .. tab .. 'input'
for i=1,#self.modules do
if i == self.modules then
str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. extlast)
else
str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. ext)
end
end
str = str .. line .. tab .. last .. 'output'
str = str .. line .. '}'
return str
end
|
local Parallel, parent = torch.class('nn.Parallel', 'nn.Container')
function Parallel:__init(inputDimension,outputDimension)
parent.__init(self)
self.modules = {}
self.inputDimension = inputDimension
self.outputDimension = outputDimension
end
function Parallel:updateOutput(input)
local nModule=input:size(self.inputDimension)
local outputs = {}
local totalOutputSize = torch.LongStorage()
for i=1,nModule do
local currentInput = input:select(self.inputDimension,i)
local currentOutput = self.modules[i]:updateOutput(currentInput)
table.insert(outputs, currentOutput)
local outputSize = currentOutput:size(self.outputDimension)
if i == 1 then
totalOutputSize:resize(currentOutput:dim()):copy(currentOutput:size())
else
totalOutputSize[self.outputDimension] = totalOutputSize[self.outputDimension] + outputSize
end
end
self.output:resize(totalOutputSize)
local offset = 1
for i=1,nModule do
local currentOutput = outputs[i]
local outputSize = currentOutput:size(self.outputDimension)
self.output:narrow(self.outputDimension, offset, outputSize):copy(currentOutput)
offset = offset + currentOutput:size(self.outputDimension)
end
return self.output
end
function Parallel:updateGradInput(input, gradOutput)
local nModule=input:size(self.inputDimension)
self.gradInput:resizeAs(input)
local offset = 1
for i=1,nModule do
local module=self.modules[i]
local currentInput = input:select(self.inputDimension,i)
local currentOutput = module.output
local outputSize = currentOutput:size(self.outputDimension)
local currentGradOutput = gradOutput:narrow(self.outputDimension, offset, outputSize)
local currentGradInput = module:updateGradInput(currentInput, currentGradOutput)
self.gradInput:select(self.inputDimension,i):copy(currentGradInput)
offset = offset + outputSize
end
return self.gradInput
end
function Parallel:accGradParameters(input, gradOutput, scale)
local nModule=input:size(self.inputDimension)
local offset = 1
for i=1,nModule do
local module = self.modules[i]
local currentOutput = module.output
local outputSize = currentOutput:size(self.outputDimension)
module:accGradParameters(
input:select(self.inputDimension,i),
gradOutput:narrow(self.outputDimension, offset,outputSize),
scale
)
offset = offset + outputSize
end
end
function Parallel:accUpdateGradParameters(input, gradOutput, lr)
local nModule=input:size(self.inputDimension)
local offset = 1
for i=1,nModule do
local module = self.modules[i];
local currentOutput = module.output
module:accUpdateGradParameters(
input:select(self.inputDimension,i),
gradOutput:narrow(self.outputDimension, offset,
currentOutput:size(self.outputDimension)),
lr)
offset = offset + currentOutput:size(self.outputDimension)
end
end
function Parallel:__tostring__()
local tab = ' '
local line = '\n'
local next = ' |`-> '
local ext = ' | '
local extlast = ' '
local last = ' ... -> '
local str = torch.type(self)
str = str .. ' {' .. line .. tab .. 'input'
for i=1,#self.modules do
if i == self.modules then
str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. extlast)
else
str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. ext)
end
end
str = str .. line .. tab .. last .. 'output'
str = str .. line .. '}'
return str
end
|
fix size for parallel container
|
fix size for parallel container
|
Lua
|
bsd-3-clause
|
Moodstocks/nn,jhjin/nn,witgo/nn,caldweln/nn,nicholas-leonard/nn,PraveerSINGH/nn,diz-vara/nn,apaszke/nn,kmul00/nn,colesbury/nn,xianjiec/nn,andreaskoepf/nn,lukasc-ch/nn,elbamos/nn,jonathantompson/nn,eriche2016/nn,joeyhng/nn,sagarwaghmare69/nn
|
35c52421b98c39e2e7d618405b2b6d48a5117ff9
|
src/application.lua
|
src/application.lua
|
if not cfg.data.sta_ssid then
print('Wifi: Missing config')
return
end
if (not cfg.data.mqtt_user) or (not cfg.data.mqtt_password) then
print('MQTT: Missing config')
return
end
local queue_report = nil
local send_report = nil
local flush_data = nil
mq_id = "ESP-" .. node.chipid()
local mq_prefix = "/nodes/" .. mq_id
local mq = mqtt.Client(mq_id, 120, cfg.data.mqtt_user, cfg.data.mqtt_password)
local mq_connected = false
mq_cmds = triggerModules('_command_handlers')
mq_cmds = tablesMerge(mq_cmds)
mq_data = {}
mq_data_ptr = 0
mq_report_step = 0
-- Register MQTT event handlers
-- See http://www.hivemq.com/blog/mqtt-essentials-part-9-last-will-and-testament
mq:lwt("/lwt", "offline", 0, 0)
mq:on("connect", function(conn)
print("MQTT: Connected")
mq_connected = true
tmr.stop(0)
-- Subscribe to all command topics
for topic, handler in pairs(mq_cmds) do
if topic:sub(1, 1) ~= '/' then
topic = mq_prefix .. '/commands/' .. topic
end
print('MQTT: Subscribing to topic:', topic)
mq:subscribe(topic, 0, function(conn) end)
end
send_report()
collectgarbage()
end)
mq:on("offline", function(conn)
print("MQTT: Disconnected")
mq_connected = false
end)
mq:on("message", function(conn, topic, data)
print("MQTT: Received, topic:", topic)
local part = topic:match(mq_prefix .. '(/.+)') or topic
local cmd = part:match('/commands/(.+)') or part
if cmd ~= nil and mq_cmds[cmd] then
print('CMD: Handling command:', cmd)
local cmd_evt = {
data = cjson.decode(data)
}
local cmd_res = mq_cmds[cmd](cmd_evt)
if cmd_res ~= nil then
if type(cmd_res) == 'table' then
if cmd_evt.data and cmd_evt.data.rid then
cmd_res.rid = cmd_evt.data.rid
end
cmd_res = cjson.encode(cmd_res)
end
mq_data[#mq_data + 1] = { mq_prefix .. '/responses/' .. part, cmd_res }
flush_data()
end
cmd_res = nil
cmd_evt = nil
end
cmd = nil
part = nil
collectgarbage()
if data ~= nil then
print("MQTT: Data:", data)
end
end)
wifi.setphymode(wifi.PHYMODE_N)
wifi.setmode(wifi.STATION)
wifi.sta.eventMonReg(wifi.STA_GOTIP, function()
-- wifi.sta.eventMonReg(wifi.STA_GOTIP, "unreg")
wifi.sta.eventMonStop("unreg all")
print("WIFI: Connected")
send_report()
end)
print("WIFI: Connecting..")
wifi.sta.eventMonStart()
wifi.sta.config(cfg.data.sta_ssid, cfg.data.sta_psk)
flush_data = function(callback)
mq_data_ptr = mq_data_ptr + 1
if mq_data_ptr > #mq_data then
mq_data = {}
mq_data_ptr = 0
if callback ~= nil then
callback()
end
else
local d = mq_data[mq_data_ptr]
mq:publish(d[1], d[2], 0, 0, function(conn)
flush_data(callback)
end)
d = nil
end
collectgarbage()
end
queue_report = function()
if cfg.data.sleep then
if mq_connected then
mq:close()
end
node.dsleep(cfg.data.report_interval * 1000 * 1000, 4)
else
tmr.stop(0)
tmr.alarm(0, cfg.data.report_interval * 1000, 0, function()
send_report()
collectgarbage()
end)
end
end
send_report = function()
if not wifi.sta.getip() then
print('Report: Skipping, no Wifi')
queue_report()
elseif not mq_connected then
print('Report: Skipping, no MQTT')
mq:connect(cfg.data.mqtt_host, cfg.data.mqtt_port, cfg.data.mqtt_secure)
-- Wait a second for MQTT connection
tmr.alarm(0, 1000, 0, function()
queue_report()
end)
else
print('Report: Sending..')
mq_data = triggerModules('_report_data')
mq_data = tablesMerge(mq_data)
collectgarbage()
flush_data(function()
print('Report: Finished')
queue_report()
end)
end
end
|
if not cfg.data.sta_ssid then
print('Wifi: Missing config')
return
end
if (not cfg.data.mqtt_user) or (not cfg.data.mqtt_password) then
print('MQTT: Missing config')
return
end
local queue_report = nil
local send_report = nil
local flush_data = nil
mq_id = "ESP-" .. node.chipid()
local mq_prefix = "/nodes/" .. mq_id
local mq = mqtt.Client(mq_id, 120, cfg.data.mqtt_user, cfg.data.mqtt_password)
local mq_connected = false
mq_cmds = triggerModules('_command_handlers')
mq_cmds = tablesMerge(mq_cmds)
mq_data = {}
mq_data_ptr = 0
mq_report_step = 0
-- Register MQTT event handlers
-- See http://www.hivemq.com/blog/mqtt-essentials-part-9-last-will-and-testament
mq:lwt("/lwt", "offline", 0, 0)
mq:on("connect", function(conn)
print("MQTT: Connected")
mq_connected = true
tmr.stop(0)
-- Subscribe to all command topics
for topic, handler in pairs(mq_cmds) do
if topic:sub(1, 1) ~= '/' then
topic = mq_prefix .. '/commands/' .. topic
end
print('MQTT: Subscribing to topic:', topic)
mq:subscribe(topic, 0, function(conn) end)
end
send_report()
collectgarbage()
end)
mq:on("offline", function(conn)
print("MQTT: Disconnected")
mq_connected = false
end)
mq:on("message", function(conn, topic, data)
print("MQTT: Received, topic:", topic)
local part = topic:sub(1, #mq_prefix + 1) == mq_prefix .. '/' and topic:sub(#mq_prefix + 1) or topic
local cmd = part:match('/commands/(.+)') or part
if cmd ~= nil and mq_cmds[cmd] then
print('CMD: Handling command:', cmd)
local cmd_evt = {
data = cjson.decode(data)
}
local cmd_res = mq_cmds[cmd](cmd_evt)
if cmd_res ~= nil then
if type(cmd_res) == 'table' then
if cmd_evt.data and cmd_evt.data.rid then
cmd_res.rid = cmd_evt.data.rid
end
cmd_res = cjson.encode(cmd_res)
end
mq_data[#mq_data + 1] = { mq_prefix .. '/responses/' .. part, cmd_res }
flush_data()
end
cmd_res = nil
cmd_evt = nil
end
cmd = nil
part = nil
collectgarbage()
if data ~= nil then
print("MQTT: Data:", data)
end
end)
wifi.setphymode(wifi.PHYMODE_N)
wifi.setmode(wifi.STATION)
wifi.sta.eventMonReg(wifi.STA_GOTIP, function()
-- wifi.sta.eventMonReg(wifi.STA_GOTIP, "unreg")
wifi.sta.eventMonStop("unreg all")
print("WIFI: Connected")
send_report()
end)
print("WIFI: Connecting..")
wifi.sta.eventMonStart()
wifi.sta.config(cfg.data.sta_ssid, cfg.data.sta_psk)
flush_data = function(callback)
mq_data_ptr = mq_data_ptr + 1
if mq_data_ptr > #mq_data then
mq_data = {}
mq_data_ptr = 0
if callback ~= nil then
callback()
end
else
local d = mq_data[mq_data_ptr]
mq:publish(d[1], d[2], 0, 0, function(conn)
flush_data(callback)
end)
d = nil
end
collectgarbage()
end
queue_report = function()
if cfg.data.sleep then
if mq_connected then
mq:close()
end
node.dsleep(cfg.data.report_interval * 1000 * 1000, 4)
else
tmr.stop(0)
tmr.alarm(0, cfg.data.report_interval * 1000, 0, function()
send_report()
collectgarbage()
end)
end
end
send_report = function()
if not wifi.sta.getip() then
print('Report: Skipping, no Wifi')
queue_report()
elseif not mq_connected then
print('Report: Skipping, no MQTT')
mq:connect(cfg.data.mqtt_host, cfg.data.mqtt_port, cfg.data.mqtt_secure)
-- Wait a second for MQTT connection
tmr.alarm(0, 1000, 0, function()
queue_report()
end)
else
print('Report: Sending..')
mq_data = triggerModules('_report_data')
mq_data = tablesMerge(mq_data)
collectgarbage()
flush_data(function()
print('Report: Finished')
queue_report()
end)
end
end
|
One of many potential fixes. I hate lua.
|
One of many potential fixes. I hate lua.
Signed-off-by: Kalman Olah <aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d@kalmanolah.net>
|
Lua
|
mit
|
kalmanolah/kalmon-ESP8266
|
8307cb5f7b862c71988a80d6b0c3ade401a32642
|
lib/wax-scripts/ext/table.lua
|
lib/wax-scripts/ext/table.lua
|
function table.clone(t, nometa)
local u = {}
if not nometa then
setmetatable(u, getmetatable(t))
end
for i, v in pairs(t) do
if type(v) == "table" then
u[i] = table.clone(v)
else
u[i] = v
end
end
return u
end
function table.merge(t, u)
local r = table.clone(t)
for i, v in pairs(u) do
r[i] = v
end
return r
end
function table.keys(t)
local keys = {}
for k, v in pairs(t) do table.insert(keys, k) end
return keys
end
function table.unique(t)
local seen = {}
for i, v in ipairs(t) do
if not table.includes(seen, v) then table.insert(seen, v) end
end
return seen
end
function table.values(t)
local values = {}
for k, v in pairs(t) do table.insert(values, v) end
return values
end
function table.last(t)
return t[#t]
end
function table.append(t, moreValues)
for i, v in ipairs(moreValues) do
table.insert(t, v)
end
return t
end
function table.indexOf(t, value)
for k, v in pairs(t) do
if v == value then return k end
end
return nil
end
function table.includes(t, value)
return table.indexOf(t, value)
end
function table.removeValue(t, value)
local index = table.indexOf(t, value)
table.remove(t, index)
return t
end
function table.each(t, func)
for k, v in pairs(t) do
func(v)
end
end
function table.find(t, func)
for k, v in pairs(t) do
if func(v) then return v end
end
return nil
end
function table.filter(t, func)
local matches = {}
for k, v in pairs(t) do
if func(v) then table.insert(matches, v) end
end
return matches
end
function table.map(t, func)
local mapped = {}
for k, v in pairs(t) do
table.insert(mapped, func(v, k))
end
return mapped
end
function table.groupBy(t, func)
local grouped = {}
for k, v in pairs(t) do
local groupKey = func(v)
if not grouped[groupKey] then grouped[groupKey] = {} end
table.insert(grouped[groupKey], v)
end
return grouped
end
function table.tostring(t, indent)
local output = {}
if type(t) == "table" then
table.insert(output, "{\n")
for k, v in pairs(t) do
local innerIndent = (indent or " ") .. (indent or " ")
table.insert(output, innerIndent .. tostring(k) .. " = ")
table.insert(output, table.tostring(v, innerIndent))
end
if indent then
table.insert(output, (indent or "") .. "},\n")
else
table.insert(output, "}")
end
else
if type(t) == "string" then t = string.format("%q", t) end -- quote strings
table.insert(output, tostring(t) .. ",\n")
end
return table.concat(output)
end
|
function table.clone(t, nometa)
local u = {}
if not nometa then
setmetatable(u, getmetatable(t))
end
for i, v in pairs(t) do
if type(v) == "table" then
u[i] = table.clone(v)
else
u[i] = v
end
end
return u
end
function table.merge(t, u)
local r = table.clone(t)
for i, v in pairs(u) do
r[i] = v
end
return r
end
function table.keys(t)
local keys = {}
for k, v in pairs(t) do table.insert(keys, k) end
return keys
end
function table.unique(t)
local seen = {}
for i, v in ipairs(t) do
if not table.includes(seen, v) then table.insert(seen, v) end
end
return seen
end
function table.values(t)
local values = {}
for k, v in pairs(t) do table.insert(values, v) end
return values
end
function table.last(t)
return t[#t]
end
function table.append(t, moreValues)
for i, v in ipairs(moreValues) do
table.insert(t, v)
end
return t
end
function table.indexOf(t, value)
for k, v in pairs(t) do
if v == value then return k end
end
return nil
end
function table.includes(t, value)
return table.indexOf(t, value)
end
function table.removeValue(t, value)
local index = table.indexOf(t, value)
table.remove(t, index)
return t
end
function table.each(t, func)
for k, v in pairs(t) do
func(v)
end
end
function table.find(t, func)
for k, v in pairs(t) do
if func(v) then return v end
end
return nil
end
function table.filter(t, func)
local matches = {}
for k, v in pairs(t) do
if func(v) then table.insert(matches, v) end
end
return matches
end
function table.map(t, func)
local mapped = {}
for k, v in pairs(t) do
table.insert(mapped, func(v, k))
end
return mapped
end
function table.groupBy(t, func)
local grouped = {}
for k, v in pairs(t) do
local groupKey = func(v)
if not grouped[groupKey] then grouped[groupKey] = {} end
table.insert(grouped[groupKey], v)
end
return grouped
end
function table.tostring(tbl, indent, limit, depth, jstack)
limit = limit or 20
depth = depth or 7
jstack = jstack or {}
local i = 0
local output = {}
if type(tbl) == "table" then
-- very important to avoid disgracing ourselves with circular referencs...
for i,t in ipairs(jstack) do
if tbl == t then
return "<self>,\n"
end
end
table.insert(jstack, tbl)
table.insert(output, "{\n")
for key, value in pairs(tbl) do
local innerIndent = (indent or " ") .. (indent or " ")
table.insert(output, innerIndent .. tostring(key) .. " = ")
table.insert(output,
value == tbl and "<self>," or table.tostring(value, innerIndent, limit, depth, jstack)
)
i = i + 1
if i > limit then
table.insert(output, (innerIndent or "") .. "...\n")
break
end
end
table.insert(output, indent and (indent or "") .. "},\n" or "}")
else
if type(tbl) == "string" then tbl = string.format("%q", tbl) end -- quote strings
table.insert(output, tostring(tbl) .. ",\n")
end
return table.concat(output)
end
|
Fixing circular referencs problem in table.tostring
|
Fixing circular referencs problem in table.tostring
|
Lua
|
mit
|
probablycorey/wax,chiyun1/wax,qskycolor/wax,dxd214/wax,chiyun1/wax,RoyZeng/wax,1yvT0s/wax,felipejfc/n-wax,LiJingBiao/wax,RoyZeng/wax,LiJingBiao/wax,taobao-idev/wax,FlashHand/wax,BITA-app/wax,hj3938/wax,probablycorey/wax,1yvT0s/wax,LiJingBiao/wax,a20251313/wax,marinehero/wax,1yvT0s/wax,dxd214/wax,dxd214/wax,marinehero/wax,dxd214/wax,BITA-app/wax,probablycorey/wax,RoyZeng/wax,FlashHand/wax,a20251313/wax,taobao-idev/wax,1yvT0s/wax,felipejfc/n-wax,RoyZeng/wax,BITA-app/wax,felipejfc/n-wax,qskycolor/wax,LiJingBiao/wax,marinehero/wax,FlashHand/wax,probablycorey/wax,taobao-idev/wax,FlashHand/wax,hj3938/wax,felipejfc/n-wax,marinehero/wax,qskycolor/wax,hj3938/wax,chiyun1/wax,taobao-idev/wax,a20251313/wax,hj3938/wax,a20251313/wax,qskycolor/wax,BITA-app/wax,chiyun1/wax
|
1d589d3612cd7bd8ad2d94974a4909dae6889478
|
mod_archive_muc/mod_archive_muc.lua
|
mod_archive_muc/mod_archive_muc.lua
|
-- Prosody IM
-- Copyright (C) 2010 Dai Zhiwei
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local st = require "util.stanza";
local dm = require "util.datamanager";
local jid = require "util.jid";
local datetime = require "util.datetime";
local PREFS_DIR = "archive_muc_prefs";
local ARCHIVE_DIR = "archive_muc";
local HOST = 'localhost';
local AUTO_ARCHIVING_ENABLED = true;
module:add_feature("urn:xmpp:archive#preferences");
module:add_feature("urn:xmpp:archive#management");
------------------------------------------------------------
-- Utils
------------------------------------------------------------
local function load_prefs(node, host)
return st.deserialize(dm.load(node, host, PREFS_DIR));
end
local function store_prefs(data, node, host)
dm.store(node, host, PREFS_DIR, st.preserialize(data));
end
local function date_time(localtime)
return datetime.datetime(localtime);
end
local function match_jid(rule, id)
return not rule or jid.compare(id, rule);
end
local function is_earlier(start, coll_start)
return not start or start <= coll_start;
end
local function is_later(endtime, coll_start)
return not endtime or endtime >= coll_start;
end
------------------------------------------------------------
-- Preferences
------------------------------------------------------------
local function preferences_handler(event)
local origin, stanza = event.origin, event.stanza;
module:log("debug", "-- Enter muc preferences_handler()");
module:log("debug", "-- muc pref:\n%s", tostring(stanza));
if stanza.attr.type == "get" then
local data = load_prefs(origin.username, origin.host);
if data then
origin.send(st.reply(stanza):add_child(data));
else
origin.send(st.reply(stanza));
end
elseif stanza.attr.type == "set" then
local node, host = origin.username, origin.host;
if stanza.tags[1] and stanza.tags[1].name == 'prefs' then
store_prefs(stanza.tags[1], node, host);
origin.send(st.reply(stanza));
local user = bare_sessions[node.."@"..host];
local push = st.iq({type="set"});
push:add_child(stanza.tags[1]);
for _, res in pairs(user and user.sessions or NULL) do -- broadcast to all resources
if res.presence then -- to resource
push.attr.to = res.full_jid;
res.send(push);
end
end
end
end
return true;
end
------------------------------------------------------------
-- Archive Management
------------------------------------------------------------
local function management_handler(event)
module:log("debug", "-- Enter muc management_handler()");
local origin, stanza = event.origin, event.stanza;
local node, host = origin.username, origin.host;
local data = dm.list_load(node, host, ARCHIVE_DIR);
local elem = stanza.tags[1];
local resset = {}
if data then
for i = #data, 1, -1 do
local forwarded = st.deserialize(data[i]);
local res = (match_jid(elem.attr["with"], forwarded.tags[2].attr.from)
or match_jid(elem.attr["with"], forwarded.tags[2].attr.to))
and is_earlier(elem.attr["start"], forwarded.tags[1].attr["stamp"])
and is_later(elem.attr["end"], forwarded.tags[1].attr["stamp"]);
if res then
table.insert(resset, forwarded);
end
end
for i = #resset, 1, -1 do
local res = st.message({to = stanza.attr.from, id=st.new_id()});
res:add_child(resset[i]);
origin.send(res);
end
end
origin.send(st.reply(stanza));
return true;
end
------------------------------------------------------------
-- Message Handler
------------------------------------------------------------
local function is_in(list, jid)
for _,v in ipairs(list) do
if match_jid(v:get_text(), jid) then -- JID Matching
return true;
end
end
return false;
end
local function is_in_roster(node, host, jid)
-- TODO
return true;
end
local function apply_pref(node, host, jid)
local pref = load_prefs(node, host);
if not pref then
return AUTO_ARCHIVING_ENABLED;
end
local always = pref:child_with_name('always');
if always and is_in(always, jid) then
return true;
end
local never = pref:child_with_name('never');
if never and is_in(never, jid) then
return false;
end
local default = pref.attr['default'];
if default == 'roster' then
return is_in_roster(node, host, jid);
elseif default == 'always' then
return true;
elseif default == 'never' then
return false;
end
return AUTO_ARCHIVING_ENABLED;
end
local function store_msg(msg, node, host)
local forwarded = st.stanza('forwarded', {xmlns='urn:xmpp:forward:tmp'});
forwarded:tag('delay', {xmlns='urn:xmpp:delay',stamp=date_time()}):up();
forwarded:add_child(msg);
dm.list_append(node, host, ARCHIVE_DIR, st.preserialize(forwarded));
end
local function msg_handler(data)
module:log("debug", "-- Enter muc msg_handler()");
local origin, stanza = data.origin, data.stanza;
local body = stanza:child_with_name("body");
if body then
local from_node, from_host = jid.split(stanza.attr.from);
local to_node, to_host = jid.split(stanza.attr.to);
-- FIXME only archive messages of users on this host
if from_host == HOST and apply_pref(from_node, from_host, stanza.attr.to) then
store_msg(stanza, from_node, from_host);
end
if to_host == HOST and apply_pref(to_node, to_host, stanza.attr.from) then
store_msg(stanza, to_node, to_host);
end
end
return nil;
end
-- Preferences
module:hook("iq/self/urn:xmpp:archive#preferences:prefs", preferences_handler);
-- Archive management
module:hook("iq/self/urn:xmpp:archive#management:query", management_handler);
module:hook("message/full", msg_handler, 20);
module:hook("message/bare", msg_handler, 20);
-- TODO prefs: [1] = "\n ";
|
-- Prosody IM
-- Copyright (C) 2010 Dai Zhiwei
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local st = require "util.stanza";
local dm = require "util.datamanager";
local jid = require "util.jid";
local datetime = require "util.datetime";
local um = require "core.usermanager";
local rom = require "core.rostermanager";
local PREFS_DIR = "archive_muc_prefs";
local ARCHIVE_DIR = "archive_muc";
local AUTO_ARCHIVING_ENABLED = true;
module:add_feature("urn:xmpp:archive#preferences");
module:add_feature("urn:xmpp:archive#management");
------------------------------------------------------------
-- Utils
------------------------------------------------------------
local function load_prefs(node, host)
return st.deserialize(dm.load(node, host, PREFS_DIR));
end
local function store_prefs(data, node, host)
dm.store(node, host, PREFS_DIR, st.preserialize(data));
end
local date_time = datetime.datetime;
local function match_jid(rule, id)
return not rule or jid.compare(id, rule);
end
local function is_earlier(start, coll_start)
return not start or start <= coll_start;
end
local function is_later(endtime, coll_start)
return not endtime or endtime >= coll_start;
end
------------------------------------------------------------
-- Preferences
------------------------------------------------------------
local function preferences_handler(event)
local origin, stanza = event.origin, event.stanza;
module:log("debug", "-- Enter muc preferences_handler()");
module:log("debug", "-- muc pref:\n%s", tostring(stanza));
if stanza.attr.type == "get" then
local data = load_prefs(origin.username, origin.host);
if data then
origin.send(st.reply(stanza):add_child(data));
else
origin.send(st.reply(stanza));
end
elseif stanza.attr.type == "set" then
local node, host = origin.username, origin.host;
if stanza.tags[1] and stanza.tags[1].name == 'prefs' then
store_prefs(stanza.tags[1], node, host);
origin.send(st.reply(stanza));
local user = bare_sessions[node.."@"..host];
local push = st.iq({type="set"});
push:add_child(stanza.tags[1]);
for _, res in pairs(user and user.sessions or NULL) do -- broadcast to all resources
if res.presence then -- to resource
push.attr.to = res.full_jid;
res.send(push);
end
end
end
end
return true;
end
------------------------------------------------------------
-- Archive Management
------------------------------------------------------------
local function management_handler(event)
module:log("debug", "-- Enter muc management_handler()");
local origin, stanza = event.origin, event.stanza;
local node, host = origin.username, origin.host;
local data = dm.list_load(node, host, ARCHIVE_DIR);
local elem = stanza.tags[1];
local resset = {}
if data then
for i = #data, 1, -1 do
local forwarded = st.deserialize(data[i]);
local res = (match_jid(elem.attr["with"], forwarded.tags[2].attr.from)
or match_jid(elem.attr["with"], forwarded.tags[2].attr.to))
and is_earlier(elem.attr["start"], forwarded.tags[1].attr["stamp"])
and is_later(elem.attr["end"], forwarded.tags[1].attr["stamp"]);
if res then
table.insert(resset, forwarded);
end
end
for i = #resset, 1, -1 do
local res = st.message({to = stanza.attr.from, id=st.new_id()});
res:add_child(resset[i]);
origin.send(res);
end
end
origin.send(st.reply(stanza));
return true;
end
------------------------------------------------------------
-- Message Handler
------------------------------------------------------------
local function is_in(list, jid)
for _,v in ipairs(list) do
if match_jid(v:get_text(), jid) then -- JID Matching
return true;
end
end
return false;
end
local function is_in_roster(node, host, id)
return rom.is_contact_subscribed(node, host, jid.bare(id));
end
local function apply_pref(node, host, jid)
local pref = load_prefs(node, host);
if not pref then
return AUTO_ARCHIVING_ENABLED;
end
local always = pref:child_with_name('always');
if always and is_in(always, jid) then
return true;
end
local never = pref:child_with_name('never');
if never and is_in(never, jid) then
return false;
end
local default = pref.attr['default'];
if default == 'roster' then
return is_in_roster(node, host, jid);
elseif default == 'always' then
return true;
elseif default == 'never' then
return false;
end
return AUTO_ARCHIVING_ENABLED;
end
local function store_msg(msg, node, host)
local forwarded = st.stanza('forwarded', {xmlns='urn:xmpp:forward:tmp'});
forwarded:tag('delay', {xmlns='urn:xmpp:delay',stamp=date_time()}):up();
forwarded:add_child(msg);
dm.list_append(node, host, ARCHIVE_DIR, st.preserialize(forwarded));
end
local function msg_handler(data)
module:log("debug", "-- Enter muc msg_handler()");
local origin, stanza = data.origin, data.stanza;
local body = stanza:child_with_name("body");
if body then
local from_node, from_host = jid.split(stanza.attr.from);
local to_node, to_host = jid.split(stanza.attr.to);
if um.user_exists(from_node, from_host) and apply_pref(from_node, from_host, stanza.attr.to) then
store_msg(stanza, from_node, from_host);
end
if um.user_exists(to_node, to_host) and apply_pref(to_node, to_host, stanza.attr.from) then
store_msg(stanza, to_node, to_host);
end
end
return nil;
end
-- Preferences
module:hook("iq/self/urn:xmpp:archive#preferences:prefs", preferences_handler);
-- Archive management
module:hook("iq/self/urn:xmpp:archive#management:query", management_handler);
module:hook("message/bare", msg_handler, 20);
-- TODO prefs: [1] = "\n ";
|
mod_archive_muc: use usermanager to check if some user exists; use rostermanager to check if someone is in the roster; minor fixes.
|
mod_archive_muc: use usermanager to check if some user exists; use rostermanager to check if someone is in the roster; minor fixes.
|
Lua
|
mit
|
vfedoroff/prosody-modules,prosody-modules/import,obelisk21/prosody-modules,drdownload/prosody-modules,joewalker/prosody-modules,cryptotoad/prosody-modules,mardraze/prosody-modules,drdownload/prosody-modules,joewalker/prosody-modules,syntafin/prosody-modules,olax/prosody-modules,heysion/prosody-modules,heysion/prosody-modules,joewalker/prosody-modules,obelisk21/prosody-modules,amenophis1er/prosody-modules,1st8/prosody-modules,drdownload/prosody-modules,stephen322/prosody-modules,olax/prosody-modules,brahmi2/prosody-modules,either1/prosody-modules,asdofindia/prosody-modules,1st8/prosody-modules,jkprg/prosody-modules,heysion/prosody-modules,NSAKEY/prosody-modules,softer/prosody-modules,heysion/prosody-modules,crunchuser/prosody-modules,Craige/prosody-modules,crunchuser/prosody-modules,apung/prosody-modules,vfedoroff/prosody-modules,vince06fr/prosody-modules,obelisk21/prosody-modules,amenophis1er/prosody-modules,brahmi2/prosody-modules,dhotson/prosody-modules,cryptotoad/prosody-modules,BurmistrovJ/prosody-modules,vince06fr/prosody-modules,brahmi2/prosody-modules,vfedoroff/prosody-modules,softer/prosody-modules,NSAKEY/prosody-modules,joewalker/prosody-modules,NSAKEY/prosody-modules,mardraze/prosody-modules,apung/prosody-modules,either1/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,dhotson/prosody-modules,brahmi2/prosody-modules,asdofindia/prosody-modules,softer/prosody-modules,BurmistrovJ/prosody-modules,mardraze/prosody-modules,jkprg/prosody-modules,NSAKEY/prosody-modules,iamliqiang/prosody-modules,LanceJenkinZA/prosody-modules,vince06fr/prosody-modules,stephen322/prosody-modules,olax/prosody-modules,asdofindia/prosody-modules,stephen322/prosody-modules,dhotson/prosody-modules,brahmi2/prosody-modules,crunchuser/prosody-modules,mardraze/prosody-modules,vfedoroff/prosody-modules,drdownload/prosody-modules,asdofindia/prosody-modules,stephen322/prosody-modules,BurmistrovJ/prosody-modules,NSAKEY/prosody-modules,jkprg/prosody-modules,dhotson/prosody-modules,dhotson/prosody-modules,1st8/prosody-modules,jkprg/prosody-modules,olax/prosody-modules,asdofindia/prosody-modules,prosody-modules/import,prosody-modules/import,LanceJenkinZA/prosody-modules,prosody-modules/import,cryptotoad/prosody-modules,vince06fr/prosody-modules,iamliqiang/prosody-modules,Craige/prosody-modules,iamliqiang/prosody-modules,Craige/prosody-modules,crunchuser/prosody-modules,LanceJenkinZA/prosody-modules,1st8/prosody-modules,vfedoroff/prosody-modules,amenophis1er/prosody-modules,guilhem/prosody-modules,either1/prosody-modules,BurmistrovJ/prosody-modules,LanceJenkinZA/prosody-modules,prosody-modules/import,cryptotoad/prosody-modules,LanceJenkinZA/prosody-modules,drdownload/prosody-modules,crunchuser/prosody-modules,apung/prosody-modules,syntafin/prosody-modules,heysion/prosody-modules,1st8/prosody-modules,cryptotoad/prosody-modules,syntafin/prosody-modules,obelisk21/prosody-modules,mmusial/prosody-modules,apung/prosody-modules,mmusial/prosody-modules,olax/prosody-modules,apung/prosody-modules,mmusial/prosody-modules,either1/prosody-modules,mmusial/prosody-modules,vince06fr/prosody-modules,Craige/prosody-modules,mardraze/prosody-modules,amenophis1er/prosody-modules,iamliqiang/prosody-modules,softer/prosody-modules,BurmistrovJ/prosody-modules,guilhem/prosody-modules,stephen322/prosody-modules,syntafin/prosody-modules,mmusial/prosody-modules,guilhem/prosody-modules,obelisk21/prosody-modules,either1/prosody-modules,softer/prosody-modules,jkprg/prosody-modules,syntafin/prosody-modules,amenophis1er/prosody-modules,guilhem/prosody-modules,iamliqiang/prosody-modules,joewalker/prosody-modules
|
b0506ad28d5560aff4aa92f7812ad42375c3a579
|
kong/plugins/oauth2/migrations/cassandra.lua
|
kong/plugins/oauth2/migrations/cassandra.lua
|
return {
{
name = "2015-08-03-132400_init_oauth2",
up = [[
CREATE TABLE IF NOT EXISTS oauth2_credentials(
id uuid,
name text,
consumer_id uuid,
client_id text,
client_secret text,
redirect_uri text,
created_at timestamp,
PRIMARY KEY (id)
);
CREATE INDEX IF NOT EXISTS ON oauth2_credentials(consumer_id);
CREATE INDEX IF NOT EXISTS ON oauth2_credentials(client_id);
CREATE INDEX IF NOT EXISTS ON oauth2_credentials(client_secret);
CREATE TABLE IF NOT EXISTS oauth2_authorization_codes(
id uuid,
code text,
authenticated_userid text,
scope text,
created_at timestamp,
PRIMARY KEY (id)
) WITH default_time_to_live = 300;
CREATE INDEX IF NOT EXISTS ON oauth2_authorization_codes(code);
CREATE INDEX IF NOT EXISTS ON oauth2_authorization_codes(authenticated_userid);
CREATE TABLE IF NOT EXISTS oauth2_tokens(
id uuid,
credential_id uuid,
access_token text,
token_type text,
refresh_token text,
expires_in int,
authenticated_userid text,
scope text,
created_at timestamp,
PRIMARY KEY (id)
);
CREATE INDEX IF NOT EXISTS ON oauth2_tokens(access_token);
CREATE INDEX IF NOT EXISTS ON oauth2_tokens(refresh_token);
CREATE INDEX IF NOT EXISTS ON oauth2_tokens(authenticated_userid);
]],
down = [[
DROP TABLE oauth2_credentials;
DROP TABLE oauth2_authorization_codes;
DROP TABLE oauth2_tokens;
]]
},
{
name = "2015-08-24-215800_cascade_delete_index",
up = [[
CREATE INDEX IF NOT EXISTS oauth2_credential_id_idx ON oauth2_tokens(credential_id);
]],
down = [[
DROP INDEX oauth2_credential_id_idx;
]]
},
{
name = "2016-02-29-435612_remove_ttl",
up = [[
ALTER TABLE oauth2_authorization_codes WITH default_time_to_live = 0;
]],
down = [[
ALTER TABLE oauth2_authorization_codes WITH default_time_to_live = 3600;
]]
},
{
name = "2016-04-14-283949_serialize_redirect_uri",
up = function(_, _, factory)
local json = require "cjson"
local apps, err = factory.oauth2_credentials.db:find_all('oauth2_credentials', nil, nil);
if err then
return err
end
for _, app in ipairs(apps) do
local redirect_uri = {};
redirect_uri[1] = app.redirect_uri
local redirect_uri_str = json.encode(redirect_uri)
local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri_str.."' WHERE id="..app.id
local _, err = factory.oauth2_credentials.db:queries(req)
if err then
return err
end
end
end,
down = function(_,_,factory)
local apps, err = factory.oauth2_credentials:find_all()
if err then
return err
end
for _, app in ipairs(apps) do
local redirect_uri = app.redirect_uri[1]
local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri.."' WHERE id="..app.id
local _, err = factory.oauth2_credentials.db:queries(req)
if err then
return err
end
end
end
},
{
name = "2016-07-15-oauth2_code_credential_id",
up = [[
TRUNCATE oauth2_authorization_codes;
ALTER TABLE oauth2_authorization_codes ADD credential_id uuid;
]],
down = [[
ALTER TABLE oauth2_authorization_codes DROP credential_id;
]]
}
}
|
return {
{
name = "2015-08-03-132400_init_oauth2",
up = [[
CREATE TABLE IF NOT EXISTS oauth2_credentials(
id uuid,
name text,
consumer_id uuid,
client_id text,
client_secret text,
redirect_uri text,
created_at timestamp,
PRIMARY KEY (id)
);
CREATE INDEX IF NOT EXISTS ON oauth2_credentials(consumer_id);
CREATE INDEX IF NOT EXISTS ON oauth2_credentials(client_id);
CREATE INDEX IF NOT EXISTS ON oauth2_credentials(client_secret);
CREATE TABLE IF NOT EXISTS oauth2_authorization_codes(
id uuid,
code text,
authenticated_userid text,
scope text,
created_at timestamp,
PRIMARY KEY (id)
) WITH default_time_to_live = 300;
CREATE INDEX IF NOT EXISTS ON oauth2_authorization_codes(code);
CREATE INDEX IF NOT EXISTS ON oauth2_authorization_codes(authenticated_userid);
CREATE TABLE IF NOT EXISTS oauth2_tokens(
id uuid,
credential_id uuid,
access_token text,
token_type text,
refresh_token text,
expires_in int,
authenticated_userid text,
scope text,
created_at timestamp,
PRIMARY KEY (id)
);
CREATE INDEX IF NOT EXISTS ON oauth2_tokens(access_token);
CREATE INDEX IF NOT EXISTS ON oauth2_tokens(refresh_token);
CREATE INDEX IF NOT EXISTS ON oauth2_tokens(authenticated_userid);
]],
down = [[
DROP TABLE oauth2_credentials;
DROP TABLE oauth2_authorization_codes;
DROP TABLE oauth2_tokens;
]]
},
{
name = "2015-08-24-215800_cascade_delete_index",
up = [[
CREATE INDEX IF NOT EXISTS oauth2_credential_id_idx ON oauth2_tokens(credential_id);
]],
down = [[
DROP INDEX oauth2_credential_id_idx;
]]
},
{
name = "2016-02-29-435612_remove_ttl",
up = [[
ALTER TABLE oauth2_authorization_codes WITH default_time_to_live = 0;
]],
down = [[
ALTER TABLE oauth2_authorization_codes WITH default_time_to_live = 3600;
]]
},
{
name = "2016-04-14-283949_serialize_redirect_uri",
up = function(_, _, factory)
local json = require "cjson"
local apps, err = factory.oauth2_credentials.db:find_all('oauth2_credentials', nil, nil);
if err then
return err
end
for _, app in ipairs(apps) do
local redirect_uri = {};
redirect_uri[1] = app.redirect_uri
local redirect_uri_str = json.encode(redirect_uri)
local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri_str.."' WHERE id="..app.id
local _, err = factory.oauth2_credentials.db:queries(req)
if err then
return err
end
end
end,
down = function(_,_,factory)
local apps, err = factory.oauth2_credentials:find_all()
if err then
return err
end
for _, app in ipairs(apps) do
local redirect_uri = app.redirect_uri[1]
local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri.."' WHERE id="..app.id
local _, err = factory.oauth2_credentials.db:queries(req)
if err then
return err
end
end
end
},
{
name = "2016-07-15-oauth2_code_credential_id",
up = [[
TRUNCATE oauth2_authorization_codes;
ALTER TABLE oauth2_authorization_codes ADD credential_id uuid;
]],
down = [[
ALTER TABLE oauth2_authorization_codes DROP credential_id;
]]
},
{
name = "2016-09-19-oauth2_code_index",
up = [[
CREATE INDEX IF NOT EXISTS ON oauth2_authorization_codes(credential_id);
]]
}
}
|
fix(oauth2) create Cassandra index on oauth2_authorization_codes(credential_id)
|
fix(oauth2) create Cassandra index on oauth2_authorization_codes(credential_id)
|
Lua
|
apache-2.0
|
Mashape/kong,icyxp/kong,ccyphers/kong,shiprabehera/kong,akh00/kong,Kong/kong,Kong/kong,Kong/kong,li-wl/kong,salazar/kong,jebenexer/kong
|
3191cf9cbf6bebc49df996aa4b3257469710912b
|
defaut/Demoniste.lua
|
defaut/Demoniste.lua
|
Ovale.defaut["WARLOCK"]=
[[
Define(CURSEELEMENTS 1490)
Define(CURSEAGONY 980)
Define(CURSEDOOM 603)
Define(CURSETONGUES 1714)
Define(CURSEWEAKNESS 702)
Define(UNSTABLEAFFLICTION 30108)
Define(CORRUPTION 172)
Define(TALENTUNSTABLEAFFLICTION 1670)
Define(TALENTSHADOWBOLT 944)
Define(IMMOLATE 348)
Define(TALENTIMMOLATE 961)
Define(TALENTEMBERSTORM 966)
Define(SOULFIRE 6353)
Define(SHADOWBOLT 686)
Define(HAUNT 48181)
Define(TALENTBACKDRAFT 1888)
Define(CONFLAGRATE 17962)
Define(DRAINSOUL 47855)
Define(SHADOWEMBRACE 32391)
Define(TALENTSHADOWEMBRACE 1763)
Define(METAMORPHOSIS 47241)
Define(TALENTDECIMATION 2261)
Define(SOULSHARD 6265)
Define(DEMONICEMPOWERMENT 47193)
Define(INCINERATE 29722)
Define(DECIMATION 63167)
Define(CHAOSBOLT 50796)
AddListItem(curse elements SpellName(CURSEELEMENTS))
AddListItem(curse agony SpellName(CURSEAGONY) default)
AddListItem(curse doom SpellName(CURSEDOOM))
AddListItem(curse tongues SpellName(CURSETONGUES))
AddListItem(curse weakness SpellName(CURSEWEAKNESS))
SpellInfo(HAUNT cd=8)
SpellInfo(CONFLAGRATE cd=10)
SpellInfo(CHAOSBOLT cd=12)
SpellAddTargetDebuff(CORRUPTION CORRUPTION=18)
SpellAddTargetDebuff(CURSEAGONY CURSEAGONY=24)
SpellAddTargetDebuff(CURSEELEMENTS CURSEELEMENTS=300)
SpellAddTargetDebuff(CURSEDOOM CURSEDOOM=60)
SpellAddTargetDebuff(UNSTABLEAFFLICTION UNSTABLEAFFLICTION=15)
SpellAddTargetDebuff(IMMOLATE IMMOLATE=15)
SpellAddBuff(SHADOWBOLT SHADOWEMBRACE=12)
ScoreSpells(CURSEELEMENTS SHADOWBOLT HAUNT UNSTABLEAFFLICTION IMMOLATE CONFLAGRATE CURSEDOOM CURSETONGUES CURSEWEAKNESS
CURSEAGONY CORRUPTION SOULFIRE DRAINSOUL INCINERATE SHADOWBOLT)
AddIcon help=main
{
if List(curse elements) and TargetDebuffExpires(CURSEELEMENTS 2) and TargetDeadIn(more 8) Spell(CURSEELEMENTS)
if TalentPoints(TALENTSHADOWEMBRACE more 0) and TargetDebuffExpires(SHADOWEMBRACE 0) Spell(SHADOWBOLT)
if TargetDebuffExpires(HAUNT 1.5 mine=1) Spell(HAUNT)
if TargetDebuffExpires(UNSTABLEAFFLICTION 1.5 mine=1 haste=spell) and TargetDeadIn(more 8) Spell(UNSTABLEAFFLICTION)
if TalentPoints(TALENTBACKDRAFT more 0) and TargetDebuffExpires(IMMOLATE 3 mine=1)
and TargetDebuffPresent(IMMOLATE mine=1) Spell(CONFLAGRATE)
if TargetDebuffExpires(IMMOLATE 1.5 mine=1 haste=spell) and
{TargetLifePercent(more 25) or TalentPoints(TALENTDECIMATION more 0)} and TargetDeadIn(more 8)
Spell(IMMOLATE)
if List(curse doom) and TargetDebuffExpires(CURSEDOOM 0 mine=1) and TargetDeadIn(more 60) Spell(CURSEDOOM)
if List(curse tongues) and TargetDebuffExpires(CURSETONGUES 2) Spell(CURSETONGUES)
if List(curse weakness) and TargetDebuffExpires(CURSEWEAKNESS 2) Spell(CURSEWEAKNESS)
if List(curse agony) and TargetDebuffExpires(CURSEAGONY 0 mine=1) and TargetDeadIn(more 10) Spell(CURSEAGONY)
if TargetDebuffExpires(CORRUPTION 0 mine=1) and TargetDeadIn(more 9) Spell(CORRUPTION)
if BuffPresent(DECIMATION) Spell(SOULFIRE)
if TargetLifePercent(less 25) and Level(more 76) and {TalentPoints(TALENTDECIMATION less 1) or ItemCount(SOULSHARD less 16)} Spell(DRAINSOUL)
Spell(CHAOSBOLT)
if TalentPoints(TALENTEMBERSTORM more 0) Spell(INCINERATE)
Spell(SHADOWBOLT)
}
AddIcon help=cd
{
Spell(METAMORPHOSIS)
Spell(DEMONICEMPOWERMENT)
Item(Trinket0Slot usable=1)
Item(Trinket1Slot usable=1)
}
]]
|
Ovale.defaut["WARLOCK"]=
[[
Define(CURSEELEMENTS 1490)
Define(CURSEAGONY 980)
Define(CURSEDOOM 603)
Define(CURSETONGUES 1714)
Define(CURSEWEAKNESS 702)
Define(UNSTABLEAFFLICTION 30108)
Define(CORRUPTION 172)
Define(TALENTUNSTABLEAFFLICTION 1670)
Define(TALENTSHADOWBOLT 944)
Define(IMMOLATE 348)
Define(TALENTIMMOLATE 961)
Define(TALENTEMBERSTORM 966)
Define(SOULFIRE 6353)
Define(SHADOWBOLT 686)
Define(HAUNT 48181)
Define(TALENTBACKDRAFT 1888)
Define(CONFLAGRATE 17962)
Define(DRAINSOUL 47855)
Define(SHADOWEMBRACE 32391)
Define(TALENTSHADOWEMBRACE 1763)
Define(METAMORPHOSIS 47241)
Define(TALENTDECIMATION 2261)
Define(SOULSHARD 6265)
Define(DEMONICEMPOWERMENT 47193)
Define(INCINERATE 29722)
Define(DECIMATION 63167)
Define(CHAOSBOLT 50796)
AddListItem(curse elements SpellName(CURSEELEMENTS))
AddListItem(curse agony SpellName(CURSEAGONY))
AddListItem(curse doom SpellName(CURSEDOOM) default)
AddListItem(curse tongues SpellName(CURSETONGUES))
AddListItem(curse weakness SpellName(CURSEWEAKNESS))
SpellInfo(HAUNT cd=8)
SpellInfo(CONFLAGRATE cd=10)
SpellInfo(CHAOSBOLT cd=12)
SpellAddTargetDebuff(CORRUPTION CORRUPTION=18)
SpellAddTargetDebuff(CURSEAGONY CURSEAGONY=24)
SpellAddTargetDebuff(CURSEELEMENTS CURSEELEMENTS=300)
SpellAddTargetDebuff(CURSEDOOM CURSEDOOM=60)
SpellAddTargetDebuff(UNSTABLEAFFLICTION UNSTABLEAFFLICTION=15)
SpellAddTargetDebuff(IMMOLATE IMMOLATE=15)
SpellAddBuff(SHADOWBOLT SHADOWEMBRACE=12)
ScoreSpells(CURSEELEMENTS SHADOWBOLT HAUNT UNSTABLEAFFLICTION IMMOLATE CONFLAGRATE CURSEDOOM CURSETONGUES CURSEWEAKNESS
CURSEAGONY CORRUPTION SOULFIRE DRAINSOUL INCINERATE SHADOWBOLT)
AddIcon help=main
{
if List(curse elements) and TargetDebuffExpires(CURSEELEMENTS 2) and TargetDeadIn(more 8) Spell(CURSEELEMENTS)
if TalentPoints(TALENTSHADOWEMBRACE more 0) and TargetDebuffExpires(SHADOWEMBRACE 0) Spell(SHADOWBOLT)
if TargetDebuffExpires(HAUNT 1.5 mine=1) Spell(HAUNT)
if TargetDebuffExpires(UNSTABLEAFFLICTION 1.5 mine=1 haste=spell) and TargetDeadIn(more 8) Spell(UNSTABLEAFFLICTION)
if TalentPoints(TALENTBACKDRAFT more 0) and TargetDebuffExpires(IMMOLATE 3 mine=1)
and TargetDebuffPresent(IMMOLATE mine=1) Spell(CONFLAGRATE)
if TargetDebuffExpires(IMMOLATE 1.5 mine=1 haste=spell) and
{TargetLifePercent(more 25) or TalentPoints(TALENTDECIMATION more 0)} and TargetDeadIn(more 8)
Spell(IMMOLATE)
if List(curse doom) and TargetDebuffExpires(CURSEDOOM 0 mine=1)
{
if TargetDeadIn(more 60) Spell(CURSEDOOM)
if TargetDebuffExpires(CURSEAGONY 0 mine=1) Spell(CURSEAGONY)
}
if List(curse tongues) and TargetDebuffExpires(CURSETONGUES 2) Spell(CURSETONGUES)
if List(curse weakness) and TargetDebuffExpires(CURSEWEAKNESS 2) Spell(CURSEWEAKNESS)
if List(curse agony) and TargetDebuffExpires(CURSEAGONY 0 mine=1) and TargetDeadIn(more 10) Spell(CURSEAGONY)
if TargetDebuffExpires(CORRUPTION 0 mine=1) and TargetDeadIn(more 9) and TalentPoints(TALENTEMBERSTORM less 1) Spell(CORRUPTION)
if BuffPresent(DECIMATION) Spell(SOULFIRE)
if TargetLifePercent(less 25) and Level(more 76) and {TalentPoints(TALENTDECIMATION less 1) or ItemCount(SOULSHARD less 16)}
and TalentPoints(TALENTEMBERSTORM less 1) Spell(DRAINSOUL)
Spell(CHAOSBOLT)
if TalentPoints(TALENTEMBERSTORM more 0) Spell(INCINERATE)
Spell(SHADOWBOLT)
}
AddIcon help=cd
{
Spell(METAMORPHOSIS)
Spell(DEMONICEMPOWERMENT)
Item(Trinket0Slot usable=1)
Item(Trinket1Slot usable=1)
}
]]
|
destruction warlock fixes
|
destruction warlock fixes
git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@148 d5049fe3-3747-40f7-a4b5-f36d6801af5f
|
Lua
|
mit
|
ultijlam/ovale,eXhausted/Ovale,Xeltor/ovale,ultijlam/ovale,eXhausted/Ovale,eXhausted/Ovale,ultijlam/ovale
|
b0ec4e7f5ecea7a0f7bb3c7c8eacbe9fdcdef5ef
|
build/Tests.lua
|
build/Tests.lua
|
-- Tests/examples helpers
function SetupExampleProject()
kind "ConsoleApp"
language "C#"
debugdir "."
files { "**.cs", "./*.lua" }
links
{
"CppSharp.AST",
"CppSharp.Generator",
"CppSharp.Parser"
}
SetupManagedProject()
SetupParser()
end
function SetupTestProject(name, extraFiles)
SetupTestGeneratorProject(name)
SetupTestNativeProject(name)
SetupTestProjectsCSharp(name, nil, extraFiles)
SetupTestProjectsCLI(name, extraFiles)
end
function SetupTestCSharp(name)
SetupTestGeneratorProject(name)
SetupTestNativeProject(name)
SetupTestProjectsCSharp(name)
end
function SetupTestCLI(name)
SetupTestGeneratorProject(name)
SetupTestNativeProject(name)
SetupTestProjectsCLI(name)
end
function SetupManagedTestProject()
SetupManagedProject()
kind "SharedLib"
language "C#"
clr "Unsafe"
end
function SetupTestGeneratorProject(name, depends)
project(name .. ".Gen")
SetupManagedTestProject()
kind "ConsoleApp"
files { name .. ".cs" }
vpaths { ["*"] = "*" }
dependson { name .. ".Native" }
linktable = {
"System.Core",
"CppSharp.AST",
"CppSharp.Generator",
"CppSharp.Generator.Tests",
"CppSharp.Parser"
}
if depends ~= nil then
table.insert(linktable, depends .. ".Gen")
end
links(linktable)
SetupParser()
end
function SetupTestGeneratorBuildEvent(name)
local runtimeExe = os.is("windows") and "" or "mono --debug "
if string.starts(action, "vs") then
local exePath = SafePath("$(TargetDir)" .. name .. ".Gen.exe")
prebuildcommands { runtimeExe .. exePath }
else
local exePath = SafePath("%{cfg.buildtarget.directory}/" .. name .. ".Gen.exe")
prebuildcommands { runtimeExe .. exePath }
end
end
function SetupTestNativeProject(name, depends)
if string.starts(action, "vs") and not os.is("windows") then
return
end
project(name .. ".Native")
SetupNativeProject()
kind "SharedLib"
language "C++"
files { "**.h", "**.cpp" }
vpaths { ["*"] = "*" }
if depends ~= nil then
links { depends .. ".Native" }
end
end
function LinkNUnit()
libdirs
{
depsdir .. "/NUnit",
depsdir .. "/NSubstitute"
}
links
{
"nunit.framework",
"NSubstitute"
}
end
function SetupTestProjectsCSharp(name, depends)
project(name .. ".CSharp")
SetupManagedTestProject()
dependson { name .. ".Gen", name .. ".Native" }
SetupTestGeneratorBuildEvent(name)
files
{
path.join(gendir, name, name .. ".cs"),
path.join(gendir, name, "Std.cs")
}
vpaths { ["*"] = "*" }
linktable = { "CppSharp.Runtime" }
if depends ~= nil then
table.insert(linktable, depends .. ".CSharp")
end
links(linktable)
project(name .. ".Tests.CSharp")
SetupManagedTestProject()
files { name .. ".Tests.cs" }
vpaths { ["*"] = "*" }
links { name .. ".CSharp", "CppSharp.Generator.Tests" }
dependson { name .. ".Native" }
LinkNUnit()
links { "CppSharp.Runtime" }
end
function SetupTestProjectsCLI(name, extraFiles)
if not os.is("windows") then
return
end
project(name .. ".CLI")
SetupNativeProject()
kind "SharedLib"
language "C++"
flags { "Managed" }
dependson { name .. ".Gen", name .. ".Native" }
SetupTestGeneratorBuildEvent(name)
files
{
path.join(gendir, name, name .. ".cpp"),
path.join(gendir, name, name .. ".h")
}
if extraFiles ~= nil then
for _, file in pairs(extraFiles) do
files { path.join(gendir, name, file .. ".cpp") }
files { path.join(gendir, name, file .. ".h") }
end
end
vpaths { ["*"] = "*" }
includedirs { path.join(testsdir, name), incdir }
links { name .. ".Native" }
project(name .. ".Tests.CLI")
SetupManagedTestProject()
files { name .. ".Tests.cs" }
vpaths { ["*"] = "*" }
links { name .. ".CLI", "CppSharp.Generator.Tests" }
dependson { name .. ".Native" }
LinkNUnit()
end
function IncludeExamples()
--print("Searching for examples...")
IncludeDir(examplesdir)
end
function IncludeTests()
--print("Searching for tests...")
IncludeDir(testsdir)
end
|
-- Tests/examples helpers
function SetupExampleProject()
kind "ConsoleApp"
language "C#"
debugdir "."
files { "**.cs", "./*.lua" }
links
{
"CppSharp",
"CppSharp.AST",
"CppSharp.Generator",
"CppSharp.Parser"
}
SetupManagedProject()
SetupParser()
end
function SetupTestProject(name, extraFiles)
SetupTestGeneratorProject(name)
SetupTestNativeProject(name)
SetupTestProjectsCSharp(name, nil, extraFiles)
SetupTestProjectsCLI(name, extraFiles)
end
function SetupTestCSharp(name)
SetupTestGeneratorProject(name)
SetupTestNativeProject(name)
SetupTestProjectsCSharp(name)
end
function SetupTestCLI(name)
SetupTestGeneratorProject(name)
SetupTestNativeProject(name)
SetupTestProjectsCLI(name)
end
function SetupManagedTestProject()
SetupManagedProject()
kind "SharedLib"
language "C#"
clr "Unsafe"
end
function SetupTestGeneratorProject(name, depends)
project(name .. ".Gen")
SetupManagedTestProject()
kind "ConsoleApp"
files { name .. ".cs" }
vpaths { ["*"] = "*" }
dependson { name .. ".Native" }
linktable = {
"System.Core",
"CppSharp",
"CppSharp.AST",
"CppSharp.Generator",
"CppSharp.Generator.Tests",
"CppSharp.Parser"
}
if depends ~= nil then
table.insert(linktable, depends .. ".Gen")
end
links(linktable)
SetupParser()
end
function SetupTestGeneratorBuildEvent(name)
local runtimeExe = os.is("windows") and "" or "mono --debug "
if string.starts(action, "vs") then
local exePath = SafePath("$(TargetDir)" .. name .. ".Gen.exe")
prebuildcommands { runtimeExe .. exePath }
else
local exePath = SafePath("%{cfg.buildtarget.directory}/" .. name .. ".Gen.exe")
prebuildcommands { runtimeExe .. exePath }
end
end
function SetupTestNativeProject(name, depends)
if string.starts(action, "vs") and not os.is("windows") then
return
end
project(name .. ".Native")
SetupNativeProject()
kind "SharedLib"
language "C++"
files { "**.h", "**.cpp" }
vpaths { ["*"] = "*" }
if depends ~= nil then
links { depends .. ".Native" }
end
end
function LinkNUnit()
libdirs
{
depsdir .. "/NUnit",
depsdir .. "/NSubstitute"
}
links
{
"nunit.framework",
"NSubstitute"
}
end
function SetupTestProjectsCSharp(name, depends)
project(name .. ".CSharp")
SetupManagedTestProject()
dependson { name .. ".Gen", name .. ".Native" }
SetupTestGeneratorBuildEvent(name)
files
{
path.join(gendir, name, name .. ".cs"),
path.join(gendir, name, "Std.cs")
}
vpaths { ["*"] = "*" }
linktable = { "CppSharp.Runtime" }
if depends ~= nil then
table.insert(linktable, depends .. ".CSharp")
end
links(linktable)
project(name .. ".Tests.CSharp")
SetupManagedTestProject()
files { name .. ".Tests.cs" }
vpaths { ["*"] = "*" }
links { name .. ".CSharp", "CppSharp.Generator.Tests" }
dependson { name .. ".Native" }
LinkNUnit()
links { "CppSharp.Runtime" }
end
function SetupTestProjectsCLI(name, extraFiles)
if not os.is("windows") then
return
end
project(name .. ".CLI")
SetupNativeProject()
kind "SharedLib"
language "C++"
flags { "Managed" }
dependson { name .. ".Gen", name .. ".Native" }
SetupTestGeneratorBuildEvent(name)
files
{
path.join(gendir, name, name .. ".cpp"),
path.join(gendir, name, name .. ".h")
}
if extraFiles ~= nil then
for _, file in pairs(extraFiles) do
files { path.join(gendir, name, file .. ".cpp") }
files { path.join(gendir, name, file .. ".h") }
end
end
vpaths { ["*"] = "*" }
includedirs { path.join(testsdir, name), incdir }
links { name .. ".Native" }
project(name .. ".Tests.CLI")
SetupManagedTestProject()
files { name .. ".Tests.cs" }
vpaths { ["*"] = "*" }
links { name .. ".CLI", "CppSharp.Generator.Tests" }
dependson { name .. ".Native" }
LinkNUnit()
end
function IncludeExamples()
--print("Searching for examples...")
IncludeDir(examplesdir)
end
function IncludeTests()
--print("Searching for tests...")
IncludeDir(testsdir)
end
|
Fixed generated build files to directly link against "CppSharp" for test projects.
|
Fixed generated build files to directly link against "CppSharp" for test projects.
|
Lua
|
mit
|
inordertotest/CppSharp,inordertotest/CppSharp,mohtamohit/CppSharp,mohtamohit/CppSharp,ktopouzi/CppSharp,zillemarco/CppSharp,inordertotest/CppSharp,mohtamohit/CppSharp,inordertotest/CppSharp,u255436/CppSharp,ddobrev/CppSharp,ktopouzi/CppSharp,mohtamohit/CppSharp,mono/CppSharp,u255436/CppSharp,ddobrev/CppSharp,mono/CppSharp,ddobrev/CppSharp,mono/CppSharp,zillemarco/CppSharp,u255436/CppSharp,zillemarco/CppSharp,inordertotest/CppSharp,mono/CppSharp,u255436/CppSharp,ddobrev/CppSharp,ktopouzi/CppSharp,ddobrev/CppSharp,mono/CppSharp,mono/CppSharp,ktopouzi/CppSharp,zillemarco/CppSharp,zillemarco/CppSharp,ktopouzi/CppSharp,u255436/CppSharp,mohtamohit/CppSharp
|
d71130644e6c91685363168e5cf92f17c67bd0c8
|
tundra.lua
|
tundra.lua
|
-----------------------------------------------------------------------------------------------------------------------
local mac_opts = {
"-Wall",
"-I.", "-DPRODBG_MAC",
"-Weverything", "-Werror",
"-Wno-c11-extensions",
"-Wno-variadic-macros",
"-Wno-c++98-compat-pedantic",
"-Wno-old-style-cast",
"-Wno-documentation",
"-Wno-reserved-id-macro",
"-Wno-missing-prototypes",
"-Wno-deprecated-declarations",
"-Wno-cast-qual",
"-Wno-gnu-anonymous-struct",
"-Wno-nested-anon-types",
"-Wno-padded",
"-Wno-c99-extensions",
"-Wno-missing-field-initializers",
"-Wno-weak-vtables",
"-Wno-format-nonliteral",
"-Wno-non-virtual-dtor",
"-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
}
local macosx = {
Env = {
CCOPTS = {
mac_opts,
},
CXXOPTS = {
mac_opts,
"-std=c++11",
},
SHLIBOPTS = { "-lstdc++" },
PROGCOM = { "-lstdc++" },
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
Frameworks = { "Cocoa" },
}
local macosx_wx = {
Env = {
CCOPTS = {
mac_opts,
"-PRODBG_WX",
},
CXXOPTS = {
mac_opts,
"-PRODBG_WX",
},
},
Frameworks = { "Cocoa" },
}
local macosx_test = {
Env = {
CCOPTS = {
mac_opts,
"-Wno-everything",
"-coverage",
},
CXXOPTS = {
mac_opts,
"-Wno-everything",
"-coverage",
"-std=c++11",
},
SHLIBOPTS = { "-lstdc++", "-coverage" },
PROGCOM = { "-lstdc++", "-coverage" },
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
Frameworks = { "Cocoa" },
}
-----------------------------------------------------------------------------------------------------------------------
local gcc_opts = {
"-I.",
"-Wno-array-bounds", "-Wno-attributes", "-Wno-unused-value",
"-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"",
"-Wall", "-DPRODBG_UNIX",
"-fPIC",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
}
local gcc_env = {
Env = {
CCOPTS = {
gcc_opts,
},
CXXOPTS = {
gcc_opts,
"-std=c++11",
},
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
ReplaceEnv = {
PROGCOM = "$(LD) $(PROGOPTS) $(LIBPATH:p-L) -o $(@) -Wl,--start-group $(LIBS:p-l) $(<) -Wl,--end-group"
},
}
-----------------------------------------------------------------------------------------------------------------------
local win64_opts = {
"/DPRODBG_WIN",
"/EHsc", "/FS", "/MT", "/W3", "/I.", "/WX", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4200", "/wd4152", "/wd4996", "/wd4389", "/wd4201", "/wd4152", "/wd4996", "/wd4389",
"\"/DOBJECT_DIR=$(OBJECTDIR:#)\"",
{ "/Od"; Config = "*-*-debug" },
{ "/O2"; Config = "*-*-release" },
}
local win64 = {
Env = {
GENERATE_PDB = "1",
CCOPTS = {
win64_opts,
},
CXXOPTS = {
win64_opts,
},
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
OBJCCOM = "meh",
},
}
-----------------------------------------------------------------------------------------------------------------------
Build {
Passes = {
BuildTools = { Name="Build Tools", BuildOrder = 1 },
GenerateSources = { Name="Generate sources", BuildOrder = 2 },
},
Units = {
"units.tools.lua",
"units.libs.lua",
"units.misc.lua",
"units.plugins.lua",
"units.prodbg.lua",
"units.tests.lua",
},
Configs = {
Config { Name = "macosx-clang", DefaultOnHost = "macosx", Inherit = macosx, Tools = { "clang-osx" } },
Config { Name = "macosx_test-clang", SupportedHosts = { "macosx" }, Inherit = macosx_test, Tools = { "clang-osx" } },
Config { Name = "macosx_wx-clang", SupportedHosts = { "macosx" }, Inherit = macosx_test, Tools = { "clang-osx" } },
Config { Name = "win64-msvc", DefaultOnHost = { "windows" }, Inherit = win64, Tools = { { "msvc" }, "generic-asm" } },
Config { Name = "linux-gcc", DefaultOnHost = { "linux" }, Inherit = gcc_env, Tools = { "gcc" } },
},
IdeGenerationHints = {
Msvc = {
-- Remap config names to MSVC platform names (affects things like header scanning & debugging)
PlatformMappings = {
['win64-msvc'] = 'x64',
},
-- Remap variant names to MSVC friendly names
VariantMappings = {
['release'] = 'Release',
['debug'] = 'Debug',
},
},
MsvcSolutions = {
['ProDBG.sln'] = { } -- will get everything
},
},
}
|
-----------------------------------------------------------------------------------------------------------------------
local mac_opts = {
"-Wall",
"-I.", "-DPRODBG_MAC",
"-Weverything", "-Werror",
"-Wno-unknown-warning-option",
"-Wno-c11-extensions",
"-Wno-variadic-macros",
"-Wno-c++98-compat-pedantic",
"-Wno-old-style-cast",
"-Wno-documentation",
"-Wno-reserved-id-macro",
"-Wno-missing-prototypes",
"-Wno-deprecated-declarations",
"-Wno-cast-qual",
"-Wno-gnu-anonymous-struct",
"-Wno-nested-anon-types",
"-Wno-padded",
"-Wno-c99-extensions",
"-Wno-missing-field-initializers",
"-Wno-weak-vtables",
"-Wno-format-nonliteral",
"-Wno-non-virtual-dtor",
"-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
}
local macosx = {
Env = {
CCOPTS = {
mac_opts,
},
CXXOPTS = {
mac_opts,
"-std=c++11",
},
SHLIBOPTS = { "-lstdc++" },
PROGCOM = { "-lstdc++" },
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
Frameworks = { "Cocoa" },
}
local macosx_wx = {
Env = {
CCOPTS = {
mac_opts,
"-PRODBG_WX",
},
CXXOPTS = {
mac_opts,
"-PRODBG_WX",
},
},
Frameworks = { "Cocoa" },
}
local macosx_test = {
Env = {
CCOPTS = {
mac_opts,
"-Wno-everything",
"-coverage",
},
CXXOPTS = {
mac_opts,
"-Wno-everything",
"-coverage",
"-std=c++11",
},
SHLIBOPTS = { "-lstdc++", "-coverage" },
PROGCOM = { "-lstdc++", "-coverage" },
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
Frameworks = { "Cocoa" },
}
-----------------------------------------------------------------------------------------------------------------------
local gcc_opts = {
"-I.",
"-Wno-array-bounds", "-Wno-attributes", "-Wno-unused-value",
"-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"",
"-Wall", "-DPRODBG_UNIX",
"-fPIC",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
}
local gcc_env = {
Env = {
CCOPTS = {
gcc_opts,
},
CXXOPTS = {
gcc_opts,
"-std=c++11",
},
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
ReplaceEnv = {
PROGCOM = "$(LD) $(PROGOPTS) $(LIBPATH:p-L) -o $(@) -Wl,--start-group $(LIBS:p-l) $(<) -Wl,--end-group"
},
}
-----------------------------------------------------------------------------------------------------------------------
local win64_opts = {
"/DPRODBG_WIN",
"/EHsc", "/FS", "/MT", "/W3", "/I.", "/WX", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4200", "/wd4152", "/wd4996", "/wd4389", "/wd4201", "/wd4152", "/wd4996", "/wd4389",
"\"/DOBJECT_DIR=$(OBJECTDIR:#)\"",
{ "/Od"; Config = "*-*-debug" },
{ "/O2"; Config = "*-*-release" },
}
local win64 = {
Env = {
GENERATE_PDB = "1",
CCOPTS = {
win64_opts,
},
CXXOPTS = {
win64_opts,
},
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
OBJCCOM = "meh",
},
}
-----------------------------------------------------------------------------------------------------------------------
Build {
Passes = {
BuildTools = { Name="Build Tools", BuildOrder = 1 },
GenerateSources = { Name="Generate sources", BuildOrder = 2 },
},
Units = {
"units.tools.lua",
"units.libs.lua",
"units.misc.lua",
"units.plugins.lua",
"units.prodbg.lua",
"units.tests.lua",
},
Configs = {
Config { Name = "macosx-clang", DefaultOnHost = "macosx", Inherit = macosx, Tools = { "clang-osx" } },
Config { Name = "macosx_test-clang", SupportedHosts = { "macosx" }, Inherit = macosx_test, Tools = { "clang-osx" } },
Config { Name = "macosx_wx-clang", SupportedHosts = { "macosx" }, Inherit = macosx_test, Tools = { "clang-osx" } },
Config { Name = "win64-msvc", DefaultOnHost = { "windows" }, Inherit = win64, Tools = { { "msvc" }, "generic-asm" } },
Config { Name = "linux-gcc", DefaultOnHost = { "linux" }, Inherit = gcc_env, Tools = { "gcc" } },
},
IdeGenerationHints = {
Msvc = {
-- Remap config names to MSVC platform names (affects things like header scanning & debugging)
PlatformMappings = {
['win64-msvc'] = 'x64',
},
-- Remap variant names to MSVC friendly names
VariantMappings = {
['release'] = 'Release',
['debug'] = 'Debug',
},
},
MsvcSolutions = {
['ProDBG.sln'] = { } -- will get everything
},
},
}
|
Fixed so we can still build old version of Xcode
|
Fixed so we can still build old version of Xcode
|
Lua
|
mit
|
emoon/ProDBG,v3n/ProDBG,RobertoMalatesta/ProDBG,v3n/ProDBG,v3n/ProDBG,kondrak/ProDBG,ashemedai/ProDBG,ashemedai/ProDBG,emoon/ProDBG,SlNPacifist/ProDBG,RobertoMalatesta/ProDBG,kondrak/ProDBG,SlNPacifist/ProDBG,ashemedai/ProDBG,ashemedai/ProDBG,SlNPacifist/ProDBG,v3n/ProDBG,kondrak/ProDBG,emoon/ProDBG,kondrak/ProDBG,kondrak/ProDBG,ashemedai/ProDBG,emoon/ProDBG,ashemedai/ProDBG,RobertoMalatesta/ProDBG,RobertoMalatesta/ProDBG,SlNPacifist/ProDBG,emoon/ProDBG,emoon/ProDBG,RobertoMalatesta/ProDBG,v3n/ProDBG,SlNPacifist/ProDBG,SlNPacifist/ProDBG,v3n/ProDBG,kondrak/ProDBG
|
efcc8c8fb40f5792f81eb118ccdfa7c3e9627106
|
training/dump_model.lua
|
training/dump_model.lua
|
require 'torch'
require 'nn'
require 'features'
io.stdout:setvbuf("no")
embeddingsFolder=arg[1];
--name=arg[2]
output=arg[3];
modelFolder=arg[2] --embeddingsFolder .. '/' .. name
mlp = torch.load(modelFolder .. '/bestModel')
features = nn.Features(embeddingsFolder .. '/embeddings.words', embeddingsFolder .. '/lemmas', modelFolder .. '/suffixes', modelFolder .. '/postags', modelFolder .. '/categories', modelFolder .. '/frequentwords')
wordTable = mlp:get(1):get(1).weight
suffixTable = mlp:get(1):get(2).weight
capsTable = mlp:get(1):get(3).weight
-- CLASSIFIER
io.output(output .. "/classifier")
linear = mlp:get(4)
outputDimension = linear.weight:size()[1]
featureDimension = linear.weight:size()[2]
for i = 1,outputDimension do
for j=1,featureDimension do
if (j > 1) then
io.write(' ')
end
io.write(linear.weight[i][j])
end
io.write('\n')
end
io.flush()
io.output(output .. "/bias")
for i = 1,outputDimension do
io.write(linear.bias[i] .. '\n')
end
io.flush()
-- SUFFIX
io.output(output .. "/suffix")
io.write("*suffix_pad*")
embeddings = suffixTable[features.paddingIndex]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
io.write("*unknown_suffix*")
embeddings = suffixTable[features.unknownSuffixIndex]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
for word,index in pairs(features.suffixToIndex) do
io.write(word)
embeddings = suffixTable[index]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
end
-- CAPS
io.output(output .. "/capitals")
io.write("*caps_pad*")
embeddings = capsTable[features.paddingIndex]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
io.write("*lower_case*")
embeddings = capsTable[2]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
io.write("*upper_case*")
embeddings = capsTable[3]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
-- EMBEDDINGS
io.output(output .. "/embeddings")
io.write("*unknown_lower*")
embeddings = wordTable[features.unknownLowerIndex]
for i = 1,50 do
io.write(' ' .. embeddings[i])
end
io.write('\n')
io.write("*unknown_upper*")
embeddings = wordTable[features.unknownUpperIndex]
for i = 1,50 do
io.write(' ' .. embeddings[i])
end
io.write('\n')
io.write("*unknown_special*")
embeddings = wordTable[features.specialCharIndex]
for i = 1,50 do
io.write(' ' .. embeddings[i])
end
io.write('\n')
io.write("*left_pad*")
embeddings = wordTable[features.leftPaddingIndex]
for i = 1,50 do
io.write(' ' .. embeddings[i])
end
io.write('\n')
io.write("*right_pad*")
embeddings = wordTable[features.rightPaddingIndex]
for i = 1,50 do
io.write(' ' .. embeddings[i])
end
io.write('\n')
for word,index in pairs(features.wordToIndex) do
io.write(word)
embeddings = wordTable[index]
for i = 1,50 do
io.write(' ' .. embeddings[i])
end
io.write('\n')
end
io.flush()
|
require 'torch'
require 'nn'
require 'features'
io.stdout:setvbuf("no")
embeddingsFolder=arg[1];
--name=arg[2]
output=arg[3];
modelFolder=arg[2] --embeddingsFolder .. '/' .. name
mlp = torch.load(modelFolder .. '/bestModel')
features = nn.Features(embeddingsFolder .. '/embeddings.words', embeddingsFolder .. '/lemmas', modelFolder .. '/suffixes', modelFolder .. '/postags', modelFolder .. '/categories', modelFolder .. '/frequentwords')
wordTable = mlp:get(1):get(1).weight
suffixTable = mlp:get(1):get(2).weight
capsTable = mlp:get(1):get(3).weight
-- CLASSIFIER
io.output(output .. "/classifier")
linear = mlp:get(4)
outputDimension = linear.weight:size()[1]
featureDimension = linear.weight:size()[2]
for i = 1,outputDimension do
for j=1,featureDimension do
if (j > 1) then
io.write(' ')
end
io.write(linear.weight[i][j])
end
io.write('\n')
end
io.flush()
io.output(output .. "/bias")
for i = 1,outputDimension do
io.write(linear.bias[i] .. '\n')
end
io.flush()
-- SUFFIX
io.output(output .. "/suffix")
io.write("*suffix_pad*")
embeddings = suffixTable[features.paddingIndex]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
io.write("*unknown_suffix*")
embeddings = suffixTable[features.unknownSuffixIndex]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
for word,index in pairs(features.suffixToIndex) do
io.write(word)
embeddings = suffixTable[index]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
end
-- CAPS
io.output(output .. "/capitals")
io.write("*caps_pad*")
embeddings = capsTable[features.paddingIndex]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
io.write("*lower_case*")
embeddings = capsTable[2]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
io.write("*upper_case*")
embeddings = capsTable[3]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
-- EMBEDDINGS
io.output(output .. "/embeddings")
io.write("*unknown_lower*")
embeddings = wordTable[features.unknownLowerIndex]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
io.write("*unknown_upper*")
embeddings = wordTable[features.unknownUpperIndex]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
io.write("*unknown_special*")
embeddings = wordTable[features.specialCharIndex]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
io.write("*left_pad*")
embeddings = wordTable[features.leftPaddingIndex]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
io.write("*right_pad*")
embeddings = wordTable[features.rightPaddingIndex]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
for word,index in pairs(features.wordToIndex) do
io.write(word)
embeddings = wordTable[index]
for i = 1,embeddings:size()[1] do
io.write(' ' .. embeddings[i])
end
io.write('\n')
end
io.flush()
|
fixed bug in dump_model.lua: use correct vector length
|
fixed bug in dump_model.lua: use correct vector length
|
Lua
|
mit
|
lukovnikov/easyccg,lukovnikov/easyccg,mikelewis0/easyccg,mikelewis0/easyccg,mikelewis0/easyccg,lukovnikov/easyccg
|
87f1cf5622eb5fa6d7b6378166c8cc6926aaaa72
|
MCServer/Plugins/InfoReg.lua
|
MCServer/Plugins/InfoReg.lua
|
-- InfoReg.lua
-- Implements registration functions that process g_PluginInfo
--- Lists all the subcommands that the player has permissions for
local function ListSubcommands(a_Player, a_Subcommands, a_CmdString)
if (a_Player == nil) then
LOGINFO("The " .. a_CmdString .. " command requires another verb:")
else
a_Player:SendMessage("The " .. a_CmdString .. " command requires another verb:")
end
-- Enum all the subcommands:
local Verbs = {}
for cmd, info in pairs(a_Subcommands) do
if ((a_Player == nil) or (a_Player:HasPermission(info.Permission or ""))) then
table.insert(Verbs, a_CmdString .. " " .. cmd)
end
end
table.sort(Verbs)
-- Send the list:
if (a_Player == nil) then
for idx, verb in ipairs(Verbs) do
LOGINFO(" " .. verb)
end
else
for idx, verb in ipairs(Verbs) do
a_Player:SendMessage(cCompositeChat(" ", mtInfo):AddSuggestCommandPart(verb, verb))
end
end
end
--- This is a generic command callback used for handling multicommands' parent commands
-- For example, if there are "/gal save" and "/gal load" commands, this callback handles the "/gal" command
-- It is used for both console and in-game commands; the console version has a_Player set to nil
local function MultiCommandHandler(a_Split, a_Player, a_CmdString, a_CmdInfo, a_Level)
local Verb = a_Split[a_Level + 1];
if (Verb == nil) then
-- No verb was specified. If there is a handler for the upper level command, call it:
if (a_CmdInfo.Handler ~= nil) then
return a_CmdInfo.Handler(a_Split, a_Player);
end
-- Let the player know they need to give a subcommand:
assert(type(a_CmdInfo.Subcommands) == "table", "Info.lua error: There is no handler for command \"" .. a_CmdString .. "\" and there are no subcommands defined at level " .. a_Level)
ListSubcommands(a_Player, a_CmdInfo.Subcommands, a_CmdString);
return true;
end
-- A verb was specified, look it up in the subcommands table:
local Subcommand = a_CmdInfo.Subcommands[Verb];
if (Subcommand == nil) then
if (a_Level > 1) then
-- This is a true subcommand, display the message and make MCS think the command was handled
-- Otherwise we get weird behavior: for "/cmd verb" we get "unknown command /cmd" although "/cmd" is valid
if (a_Player == nil) then
LOGWARNING("The " .. a_CmdString .. " command doesn't support verb " .. Verb)
else
a_Player:SendMessage("The " .. a_CmdString .. " command doesn't support verb " .. Verb)
end
return true;
end
-- This is a top-level command, let MCS handle the unknown message
return false;
end
-- Check the permission:
if (a_Player ~= nil) then
if not(a_Player:HasPermission(Subcommand.Permission or "")) then
a_Player:SendMessage("You don't have permission to execute this command");
return true;
end
end
-- If the handler is not valid, check the next sublevel:
if (Subcommand.Handler == nil) then
if (Subcommand.Subcommands == nil) then
LOG("Cannot find handler for command " .. a_CmdString .. " " .. Verb);
return false;
end
return MultiCommandHandler(a_Split, a_Player, a_CmdString .. " " .. Verb, Subcommand, a_Level + 1);
end
-- Execute:
return Subcommand.Handler(a_Split, a_Player);
end
--- Registers all commands specified in the g_PluginInfo.Commands
function RegisterPluginInfoCommands()
-- A sub-function that registers all subcommands of a single command, using the command's Subcommands table
-- The a_Prefix param already contains the space after the previous command
-- a_Level is the depth of the subcommands being registered, with 1 being the top level command
local function RegisterSubcommands(a_Prefix, a_Subcommands, a_Level)
assert(a_Subcommands ~= nil);
-- A table that will hold aliases to subcommands temporarily, during subcommand iteration
local AliasTable = {}
-- Iterate through the subcommands, register them, and accumulate aliases:
for cmd, info in pairs(a_Subcommands) do
local CmdName = a_Prefix .. cmd;
local Handler = info.Handler;
-- Provide a special handler for multicommands:
if (info.Subcommands ~= nil) then
Handler = function(a_Split, a_Player)
return MultiCommandHandler(a_Split, a_Player, CmdName, info, a_Level);
end
end
if (Handler == nil) then
LOGWARNING(g_PluginInfo.Name .. ": Invalid handler for command " .. CmdName .. ", command will not be registered.");
else
local HelpString;
if (info.HelpString ~= nil) then
HelpString = " - " .. info.HelpString;
else
HelpString = "";
end
cPluginManager.BindCommand(CmdName, info.Permission or "", Handler, HelpString);
-- Register all aliases for the command:
if (info.Alias ~= nil) then
if (type(info.Alias) == "string") then
info.Alias = {info.Alias};
end
for idx, alias in ipairs(info.Alias) do
cPluginManager.BindCommand(a_Prefix .. alias, info.Permission or "", Handler, HelpString);
-- Also copy the alias's info table as a separate subcommand,
-- so that MultiCommandHandler() handles it properly. Need to off-load into a separate table
-- than the one we're currently iterating and join after the iterating.
AliasTable[alias] = info
end
end
end -- else (if Handler == nil)
-- Recursively register any subcommands:
if (info.Subcommands ~= nil) then
RegisterSubcommands(a_Prefix .. cmd .. " ", info.Subcommands, a_Level + 1);
end
end -- for cmd, info - a_Subcommands[]
-- Add the subcommand aliases that were off-loaded during registration:
for alias, info in pairs(AliasTable) do
a_Subcommands[alias] = info
end
AliasTable = {}
end
-- Loop through all commands in the plugin info, register each:
RegisterSubcommands("", g_PluginInfo.Commands, 1);
end
--- Registers all console commands specified in the g_PluginInfo.ConsoleCommands
function RegisterPluginInfoConsoleCommands()
-- A sub-function that registers all subcommands of a single command, using the command's Subcommands table
-- The a_Prefix param already contains the space after the previous command
local function RegisterSubcommands(a_Prefix, a_Subcommands, a_Level)
assert(a_Subcommands ~= nil);
for cmd, info in pairs(a_Subcommands) do
local CmdName = a_Prefix .. cmd;
local Handler = info.Handler
if (Handler == nil) then
Handler = function(a_Split)
return MultiCommandHandler(a_Split, nil, CmdName, info, a_Level);
end
end
cPluginManager.BindConsoleCommand(CmdName, Handler, info.HelpString or "");
-- Recursively register any subcommands:
if (info.Subcommands ~= nil) then
RegisterSubcommands(a_Prefix .. cmd .. " ", info.Subcommands, a_Level + 1);
end
end
end
-- Loop through all commands in the plugin info, register each:
RegisterSubcommands("", g_PluginInfo.ConsoleCommands, 1);
end
|
-- InfoReg.lua
-- Implements registration functions that process g_PluginInfo
--- Lists all the subcommands that the player has permissions for
local function ListSubcommands(a_Player, a_Subcommands, a_CmdString)
if (a_Player == nil) then
LOGINFO("The " .. a_CmdString .. " command requires another verb:")
else
a_Player:SendMessage("The " .. a_CmdString .. " command requires another verb:")
end
-- Enum all the subcommands:
local Verbs = {}
for cmd, info in pairs(a_Subcommands) do
if ((a_Player == nil) or (a_Player:HasPermission(info.Permission or ""))) then
table.insert(Verbs, a_CmdString .. " " .. cmd)
end
end
table.sort(Verbs)
-- Send the list:
if (a_Player == nil) then
for idx, verb in ipairs(Verbs) do
LOGINFO(" " .. verb)
end
else
for idx, verb in ipairs(Verbs) do
a_Player:SendMessage(cCompositeChat(" ", mtInfo):AddSuggestCommandPart(verb, verb))
end
end
end
--- This is a generic command callback used for handling multicommands' parent commands
-- For example, if there are "/gal save" and "/gal load" commands, this callback handles the "/gal" command
-- It is used for both console and in-game commands; the console version has a_Player set to nil
local function MultiCommandHandler(a_Split, a_Player, a_CmdString, a_CmdInfo, a_Level, a_EntireCommand)
local Verb = a_Split[a_Level + 1]
if (Verb == nil) then
-- No verb was specified. If there is a handler for the upper level command, call it:
if (a_CmdInfo.Handler ~= nil) then
return a_CmdInfo.Handler(a_Split, a_Player, a_EntireCommand)
end
-- Let the player know they need to give a subcommand:
assert(type(a_CmdInfo.Subcommands) == "table", "Info.lua error: There is no handler for command \"" .. a_CmdString .. "\" and there are no subcommands defined at level " .. a_Level)
ListSubcommands(a_Player, a_CmdInfo.Subcommands, a_CmdString)
return true
end
-- A verb was specified, look it up in the subcommands table:
local Subcommand = a_CmdInfo.Subcommands[Verb]
if (Subcommand == nil) then
if (a_Level > 1) then
-- This is a true subcommand, display the message and make MCS think the command was handled
-- Otherwise we get weird behavior: for "/cmd verb" we get "unknown command /cmd" although "/cmd" is valid
if (a_Player == nil) then
LOGWARNING("The " .. a_CmdString .. " command doesn't support verb " .. Verb)
else
a_Player:SendMessage("The " .. a_CmdString .. " command doesn't support verb " .. Verb)
end
return true
end
-- This is a top-level command, let MCS handle the unknown message
return false;
end
-- Check the permission:
if (a_Player ~= nil) then
if not(a_Player:HasPermission(Subcommand.Permission or "")) then
a_Player:SendMessage("You don't have permission to execute this command")
return true
end
end
-- If the handler is not valid, check the next sublevel:
if (Subcommand.Handler == nil) then
if (Subcommand.Subcommands == nil) then
LOG("Cannot find handler for command " .. a_CmdString .. " " .. Verb)
return false
end
return MultiCommandHandler(a_Split, a_Player, a_CmdString .. " " .. Verb, Subcommand, a_Level + 1, a_EntireCommand)
end
-- Execute:
return Subcommand.Handler(a_Split, a_Player, a_EntireCommand)
end
--- Registers all commands specified in the g_PluginInfo.Commands
function RegisterPluginInfoCommands()
-- A sub-function that registers all subcommands of a single command, using the command's Subcommands table
-- The a_Prefix param already contains the space after the previous command
-- a_Level is the depth of the subcommands being registered, with 1 being the top level command
local function RegisterSubcommands(a_Prefix, a_Subcommands, a_Level)
assert(a_Subcommands ~= nil)
-- A table that will hold aliases to subcommands temporarily, during subcommand iteration
local AliasTable = {}
-- Iterate through the subcommands, register them, and accumulate aliases:
for cmd, info in pairs(a_Subcommands) do
local CmdName = a_Prefix .. cmd
local Handler = info.Handler
-- Provide a special handler for multicommands:
if (info.Subcommands ~= nil) then
Handler = function(a_Split, a_Player, a_EntireCommand)
return MultiCommandHandler(a_Split, a_Player, CmdName, info, a_Level, a_EntireCommand)
end
end
if (Handler == nil) then
LOGWARNING(g_PluginInfo.Name .. ": Invalid handler for command " .. CmdName .. ", command will not be registered.")
else
local HelpString
if (info.HelpString ~= nil) then
HelpString = " - " .. info.HelpString
else
HelpString = ""
end
cPluginManager.BindCommand(CmdName, info.Permission or "", Handler, HelpString)
-- Register all aliases for the command:
if (info.Alias ~= nil) then
if (type(info.Alias) == "string") then
info.Alias = {info.Alias}
end
for idx, alias in ipairs(info.Alias) do
cPluginManager.BindCommand(a_Prefix .. alias, info.Permission or "", Handler, HelpString)
-- Also copy the alias's info table as a separate subcommand,
-- so that MultiCommandHandler() handles it properly. Need to off-load into a separate table
-- than the one we're currently iterating and join after the iterating.
AliasTable[alias] = info
end
end
end -- else (if Handler == nil)
-- Recursively register any subcommands:
if (info.Subcommands ~= nil) then
RegisterSubcommands(a_Prefix .. cmd .. " ", info.Subcommands, a_Level + 1)
end
end -- for cmd, info - a_Subcommands[]
-- Add the subcommand aliases that were off-loaded during registration:
for alias, info in pairs(AliasTable) do
a_Subcommands[alias] = info
end
AliasTable = {}
end
-- Loop through all commands in the plugin info, register each:
RegisterSubcommands("", g_PluginInfo.Commands, 1)
end
--- Registers all console commands specified in the g_PluginInfo.ConsoleCommands
function RegisterPluginInfoConsoleCommands()
-- A sub-function that registers all subcommands of a single command, using the command's Subcommands table
-- The a_Prefix param already contains the space after the previous command
local function RegisterSubcommands(a_Prefix, a_Subcommands, a_Level)
assert(a_Subcommands ~= nil)
for cmd, info in pairs(a_Subcommands) do
local CmdName = a_Prefix .. cmd
local Handler = info.Handler
if (Handler == nil) then
Handler = function(a_Split, a_EntireCommand)
return MultiCommandHandler(a_Split, nil, CmdName, info, a_Level, a_EntireCommand)
end
end
cPluginManager.BindConsoleCommand(CmdName, Handler, info.HelpString or "")
-- Recursively register any subcommands:
if (info.Subcommands ~= nil) then
RegisterSubcommands(a_Prefix .. cmd .. " ", info.Subcommands, a_Level + 1)
end
end
end
-- Loop through all commands in the plugin info, register each:
RegisterSubcommands("", g_PluginInfo.ConsoleCommands, 1)
end
|
InfoReg: Fixed EntireCommand handling for MultiCommandHandler().
|
InfoReg: Fixed EntireCommand handling for MultiCommandHandler().
The EntireCommand wasn't propagated into the handlers.
|
Lua
|
apache-2.0
|
bendl/cuberite,Tri125/MCServer,birkett/cuberite,johnsoch/cuberite,Fighter19/cuberite,QUSpilPrgm/cuberite,mmdk95/cuberite,nevercast/cuberite,electromatter/cuberite,Howaner/MCServer,mmdk95/cuberite,nounoursheureux/MCServer,HelenaKitty/EbooMC,thetaeo/cuberite,Schwertspize/cuberite,birkett/cuberite,marvinkopf/cuberite,electromatter/cuberite,birkett/MCServer,nevercast/cuberite,Howaner/MCServer,Tri125/MCServer,mmdk95/cuberite,tonibm19/cuberite,nicodinh/cuberite,bendl/cuberite,marvinkopf/cuberite,marvinkopf/cuberite,johnsoch/cuberite,HelenaKitty/EbooMC,SamOatesPlugins/cuberite,guijun/MCServer,mc-server/MCServer,electromatter/cuberite,birkett/MCServer,SamOatesPlugins/cuberite,SamOatesPlugins/cuberite,mmdk95/cuberite,birkett/cuberite,Tri125/MCServer,tonibm19/cuberite,Schwertspize/cuberite,mjssw/cuberite,johnsoch/cuberite,mc-server/MCServer,QUSpilPrgm/cuberite,electromatter/cuberite,Schwertspize/cuberite,linnemannr/MCServer,Howaner/MCServer,zackp30/cuberite,Fighter19/cuberite,kevinr/cuberite,mc-server/MCServer,kevinr/cuberite,Fighter19/cuberite,nichwall/cuberite,linnemannr/MCServer,johnsoch/cuberite,nichwall/cuberite,mjssw/cuberite,birkett/cuberite,thetaeo/cuberite,Frownigami1/cuberite,Howaner/MCServer,tonibm19/cuberite,nichwall/cuberite,birkett/MCServer,nicodinh/cuberite,linnemannr/MCServer,marvinkopf/cuberite,nounoursheureux/MCServer,Haxi52/cuberite,kevinr/cuberite,Haxi52/cuberite,mjssw/cuberite,electromatter/cuberite,birkett/MCServer,ionux/MCServer,Haxi52/cuberite,Altenius/cuberite,Frownigami1/cuberite,QUSpilPrgm/cuberite,Howaner/MCServer,tonibm19/cuberite,Altenius/cuberite,Tri125/MCServer,HelenaKitty/EbooMC,ionux/MCServer,birkett/cuberite,tonibm19/cuberite,birkett/MCServer,nounoursheureux/MCServer,Altenius/cuberite,QUSpilPrgm/cuberite,nichwall/cuberite,Schwertspize/cuberite,Howaner/MCServer,nicodinh/cuberite,marvinkopf/cuberite,bendl/cuberite,nichwall/cuberite,nevercast/cuberite,HelenaKitty/EbooMC,SamOatesPlugins/cuberite,mmdk95/cuberite,guijun/MCServer,Haxi52/cuberite,nounoursheureux/MCServer,nounoursheureux/MCServer,guijun/MCServer,nichwall/cuberite,thetaeo/cuberite,Haxi52/cuberite,zackp30/cuberite,linnemannr/MCServer,Fighter19/cuberite,mc-server/MCServer,Frownigami1/cuberite,bendl/cuberite,guijun/MCServer,tonibm19/cuberite,birkett/MCServer,linnemannr/MCServer,nevercast/cuberite,mjssw/cuberite,ionux/MCServer,ionux/MCServer,Fighter19/cuberite,linnemannr/MCServer,zackp30/cuberite,bendl/cuberite,birkett/cuberite,nounoursheureux/MCServer,thetaeo/cuberite,thetaeo/cuberite,zackp30/cuberite,electromatter/cuberite,HelenaKitty/EbooMC,zackp30/cuberite,thetaeo/cuberite,mjssw/cuberite,Altenius/cuberite,mmdk95/cuberite,ionux/MCServer,nicodinh/cuberite,Tri125/MCServer,nicodinh/cuberite,nicodinh/cuberite,ionux/MCServer,mc-server/MCServer,SamOatesPlugins/cuberite,Schwertspize/cuberite,kevinr/cuberite,kevinr/cuberite,Tri125/MCServer,Haxi52/cuberite,mjssw/cuberite,Fighter19/cuberite,guijun/MCServer,kevinr/cuberite,zackp30/cuberite,nevercast/cuberite,Frownigami1/cuberite,johnsoch/cuberite,Altenius/cuberite,guijun/MCServer,QUSpilPrgm/cuberite,nevercast/cuberite,marvinkopf/cuberite,mc-server/MCServer,Frownigami1/cuberite,QUSpilPrgm/cuberite
|
4416872603829a1b1f8777255640cfd416ff8c91
|
premake.lua
|
premake.lua
|
project.name = "Premake4"
-- Project options
addoption("no-tests", "Build without automated tests")
-- Output directories
project.config["Debug"].bindir = "bin/debug"
project.config["Release"].bindir = "bin/release"
-- Packages
dopackage("src")
-- Cleanup code
function doclean(cmd, arg)
docommand(cmd, arg)
os.rmdir("bin")
os.rmdir("doc")
end
-- Release code
REPOS = "https://premake.svn.sourceforge.net/svnroot/premake"
TRUNK = "/trunk"
BRANCHES = "/branches/4.0-alpha/"
function dorelease(cmd, arg)
if (not arg) then
error "You must specify a version"
end
-------------------------------------------------------------------
-- Make sure everything is good before I start
-------------------------------------------------------------------
print("")
print("PRE-FLIGHT CHECKLIST")
print(" * is README up-to-date?")
print(" * is CHANGELOG up-to-date?")
print(" * did you test build with GCC?")
print(" * did you test build with Doxygen?")
print(" * are 'svn' (all) and '7z' (Windows) available?")
print("")
print("Press [Enter] to continue or [^C] to quit.")
io.stdin:read("*l")
-------------------------------------------------------------------
-- Set up environment
-------------------------------------------------------------------
local version = arg
os.mkdir("releases")
local folder = "premake-"..version
local trunk = REPOS..TRUNK
local branch = REPOS..BRANCHES..version
-------------------------------------------------------------------
-- Build and run all automated tests on working copy
-------------------------------------------------------------------
print("Building tests on working copy...")
os.execute("premake --target gnu >releases/release.log")
result = os.execute("make CONFIG=Release >releases/release.log")
if (result ~= 0) then
error("Test build failed; see release.log for details")
end
-------------------------------------------------------------------
-- Look for a release branch in SVN, and create one from trunk if necessary
-------------------------------------------------------------------
print("Checking for release branch...")
os.chdir("releases")
result = os.execute(string.format("svn ls %s >release.log 2>&1", branch))
if (result ~= 0) then
print("Creating release branch...")
result = os.execute(string.format('svn copy %s %s -m "Creating release branch for %s" >release.log', trunk, branch, version))
if (result ~= 0) then
error("Failed to create release branch at "..branch)
end
end
-------------------------------------------------------------------
-- Checkout a local copy of the release branch
-------------------------------------------------------------------
print("Getting source code from release branch...")
os.execute(string.format("svn co %s %s >release.log", branch, folder))
if (not os.fileexists(folder.."/README.txt")) then
error("Unable to checkout from repository at "..branch)
end
-------------------------------------------------------------------
-- Embed version numbers into the files
-------------------------------------------------------------------
-- (embed version #s)
-- (check into branch)
-------------------------------------------------------------------
-- Build the release binary for this platform
-------------------------------------------------------------------
print("Building release version...")
os.chdir(folder)
os.execute("premake --clean --no-tests --target gnu >../release.log")
os.execute("make CONFIG=Release >../release.log")
if (windows) then
result = os.execute(string.format("7z a -tzip ..\\premake-win32-%s.zip bin\\release\\premake4.exe >../release.log", version))
elseif (macosx) then
result = os.execute(string.format("tar czvf ../premake-macosx-%s.tar.gz bin/release/premake4 >../release.log", version))
else
result = os.execute(string.format("tar czvf ../premake-linux-%s.tar.gz bin/release/premake4 >../release.log", version))
end
if (result ~= 0) then
error("Failed to build binary package; see release.log for details")
end
-------------------------------------------------------------------
-- Clean up
-------------------------------------------------------------------
print("Cleaning up...")
os.chdir("..")
os.rmdir(folder)
os.remove("release.log")
-------------------------------------------------------------------
-- Next steps
-------------------------------------------------------------------
if (windows) then
print("DONE - now run release script under Linux")
elseif (linux) then
print("DONE - now run release script under Mac OS X")
else
print("DONE - really this time")
end
end
|
project.name = "Premake4"
-- Project options
addoption("no-tests", "Build without automated tests")
-- Output directories
project.config["Debug"].bindir = "bin/debug"
project.config["Release"].bindir = "bin/release"
-- Packages
dopackage("src")
-- Cleanup code
function doclean(cmd, arg)
docommand(cmd, arg)
os.rmdir("bin")
os.rmdir("doc")
end
-- Release code
REPOS = "https://premake.svn.sourceforge.net/svnroot/premake"
TRUNK = "/trunk"
BRANCHES = "/branches/4.0-alpha/"
function dorelease(cmd, arg)
if (not arg) then
error "You must specify a version"
end
-------------------------------------------------------------------
-- Make sure everything is good before I start
-------------------------------------------------------------------
print("")
print("PRE-FLIGHT CHECKLIST")
print(" * is README up-to-date?")
print(" * is CHANGELOG up-to-date?")
print(" * did you test build with GCC?")
print(" * did you test build with Doxygen?")
print(" * are 'svn' (all) and '7z' (Windows) available?")
print("")
print("Press [Enter] to continue or [^C] to quit.")
io.stdin:read("*l")
-------------------------------------------------------------------
-- Set up environment
-------------------------------------------------------------------
local version = arg
os.mkdir("releases")
local folder = "premake-"..version
local trunk = REPOS..TRUNK
local branch = REPOS..BRANCHES..version
-------------------------------------------------------------------
-- Build and run all automated tests on working copy
-------------------------------------------------------------------
print("Building tests on working copy...")
os.execute("premake --target gnu >releases/release.log")
result = os.execute("make CONFIG=Release >releases/release.log")
if (result ~= 0) then
error("Test build failed; see release.log for details")
end
-------------------------------------------------------------------
-- Look for a release branch in SVN, and create one from trunk if necessary
-------------------------------------------------------------------
print("Checking for release branch...")
os.chdir("releases")
result = os.execute(string.format("svn ls %s >release.log 2>&1", branch))
if (result ~= 0) then
print("Creating release branch...")
result = os.execute(string.format('svn copy %s %s -m "Creating release branch for %s" >release.log', trunk, branch, version))
if (result ~= 0) then
error("Failed to create release branch at "..branch)
end
end
-------------------------------------------------------------------
-- Checkout a local copy of the release branch
-------------------------------------------------------------------
print("Getting source code from release branch...")
os.execute(string.format("svn co %s %s >release.log", branch, folder))
if (not os.fileexists(folder.."/README.txt")) then
error("Unable to checkout from repository at "..branch)
end
-------------------------------------------------------------------
-- Embed version numbers into the files
-------------------------------------------------------------------
-- (embed version #s)
-- (check into branch)
-------------------------------------------------------------------
-- Build the release binary for this platform
-------------------------------------------------------------------
print("Building release version...")
os.chdir(folder)
os.execute("premake --clean --no-tests --target gnu >../release.log")
os.execute("make CONFIG=Release >../release.log")
os.chdir("bin/release")
if (windows) then
result = os.execute(string.format("7z a -tzip ..\\..\\..\\premake-win32-%s.zip premake4.exe >../release.log", version))
elseif (macosx) then
result = os.execute(string.format("tar czvf ../../../premake-macosx-%s.tar.gz premake4 >../release.log", version))
else
result = os.execute(string.format("tar czvf ../../../premake-linux-%s.tar.gz bin/release/premake4 >../release.log", version))
end
if (result ~= 0) then
error("Failed to build binary package; see release.log for details")
end
os.chdir("../..")
-------------------------------------------------------------------
-- Clean up
-------------------------------------------------------------------
print("Cleaning up...")
os.chdir("..")
os.rmdir(folder)
os.remove("release.log")
-------------------------------------------------------------------
-- Next steps
-------------------------------------------------------------------
if (windows) then
print("DONE - now run release script under Linux")
elseif (linux) then
print("DONE - now run release script under Mac OS X")
else
print("DONE - really this time")
end
end
|
Fixes to release script
|
Fixes to release script
|
Lua
|
bsd-3-clause
|
dimitarcl/premake-dev,Amorph/premake-dev,Amorph/premake-stable,dimitarcl/premake-dev,Amorph/premake-dev,Amorph/premake-stable,Amorph/premake-stable,Amorph/premake-dev,dimitarcl/premake-dev
|
ec0853bebbbe5f1e3bc0a63bebc468c32f8873e3
|
lualib/redis.lua
|
lualib/redis.lua
|
local skynet = require "skynet"
local socket = require "socket"
local config = require "config"
local redis_conf = skynet.getenv "redis"
local name = config (redis_conf)
local readline = socket.readline
local readbytes = socket.read
local table = table
local string = string
local redis = {}
local command = {}
local meta = {
__index = command,
__gc = function(self)
socket.close(self.__handle)
end,
}
function redis.connect(dbname)
local db_conf = name[dbname]
local fd = assert(socket.open(db_conf.host, db_conf.port or 6379))
local r = setmetatable( { __handle = fd, __mode = false }, meta )
if db_conf.db ~= nil then
r:select(db_conf.db)
end
return r
end
function command:disconnect()
socket.close(self.__handle)
setmetatable(self, nil)
end
local function compose_message(msg)
local lines = { "*" .. #msg }
for _,v in ipairs(msg) do
local t = type(v)
if t == "number" then
v = tostring(v)
elseif t == "userdata" then
v = int64.tostring(int64.new(v),10)
end
table.insert(lines,"$"..#v)
table.insert(lines,v)
end
table.insert(lines,"")
local cmd = table.concat(lines,"\r\n")
return cmd
end
local redcmd = {}
redcmd[42] = function(fd, data) -- '*'
local n = tonumber(data)
if n < 0 then
return true, nil
end
local bulk = {}
for i = 1,n do
local line = readline(fd,"\r\n")
local bytes = tonumber(string.sub(line,2))
if bytes >= 0 then
local data = readbytes(fd, bytes + 2)
-- bulk[i] = nil when bytes < 0
bulk[i] = string.sub(data,1,-3)
end
end
return true, bulk
end
redcmd[36] = function(fd, data) -- '$'
local bytes = tonumber(data)
if bytes < 0 then
return true,nil
end
local firstline = readbytes(fd, bytes+2)
return true,string.sub(firstline,1,-3)
end
redcmd[43] = function(fd, data) -- '+'
return true,data
end
redcmd[45] = function(fd, data) -- '-'
return false,data
end
redcmd[58] = function(fd, data) -- ':'
-- todo: return string later
return true, tonumber(data)
end
local function read_response(fd)
local result = readline(fd, "\r\n")
local firstchar = string.byte(result)
local data = string.sub(result,2)
return redcmd[firstchar](fd,data)
end
setmetatable(command, { __index = function(t,k)
local cmd = string.upper(k)
local f = function (self, ...)
local fd = self.__handle
if self.__mode then
socket.write(fd, compose_message { cmd, ... })
self.__batch = self.__batch + 1
else
socket.lock(fd)
socket.write(fd, compose_message { cmd, ... })
local ok, ret = read_response(fd)
socket.unlock(fd)
assert(ok, ret)
return ret
end
end
t[k] = f
return f
end})
function command:exists(key)
assert(not self.__mode, "exists can't used in batch mode")
local fd = self.__handle
socket.lock(fd)
socket.write(fd, compose_message { "EXISTS", key })
local ok, exists = read_response(fd)
socket.unlock(fd)
assert(ok, exists)
return exists ~= 0
end
function command:sismember(key, value)
assert(not self.__mode, "sismember can't used in batch mode")
local fd = self.__handle
socket.lock(fd)
socket.write(fd, compose_message { "SISMEMBER", key, value })
local ok, ismember = read_response(fd)
socket.unlock(fd)
assert(ok, ismember)
return ismember ~= 0
end
function command:batch(mode)
if mode == "end" then
local fd = self.__handle
if self.__mode == "read" then
local allok = true
local allret = {}
for i = 1, self.__batch do
local ok, ret = read_response(fd)
allok = allok and ok
allret[i] = ret
end
socket.unlock(self.__handle)
assert(allok, "batch read failed")
self.__mode = false
return allret
else
local allok = true
for i = 1, self.__batch do
local ok = read_response(fd)
allok = allok and ok
end
socket.unlock(self.__handle)
self.__mode = false
return allok
end
else
assert(mode == "read" or mode == "write")
self.__mode = mode
self.__batch = 0
socket.lock(self.__handle)
end
end
return redis
|
local skynet = require "skynet"
local socket = require "socket"
local config = require "config"
local redis_conf = skynet.getenv "redis"
local name = config (redis_conf)
local readline = socket.readline
local readbytes = socket.read
local table = table
local string = string
local redis = {}
local command = {}
local meta = {
__index = command,
__gc = function(self)
socket.close(self.__handle)
end,
}
function redis.connect(dbname)
local db_conf = name[dbname]
local fd = assert(socket.open(db_conf.host, db_conf.port or 6379))
local r = setmetatable( { __handle = fd, __mode = false }, meta )
if db_conf.db ~= nil then
r:select(db_conf.db)
end
return r
end
function command:disconnect()
socket.close(self.__handle)
setmetatable(self, nil)
end
local function compose_message(msg)
local lines = { "*" .. #msg }
for _,v in ipairs(msg) do
local t = type(v)
if t == "number" then
v = tostring(v)
elseif t == "userdata" then
v = int64.tostring(int64.new(v),10)
end
table.insert(lines,"$"..#v)
table.insert(lines,v)
end
table.insert(lines,"")
local cmd = table.concat(lines,"\r\n")
return cmd
end
local redcmd = {}
redcmd[42] = function(fd, data) -- '*'
local n = tonumber(data)
if n < 0 then
return true, nil
end
local bulk = {}
for i = 1,n do
local line = readline(fd,"\r\n")
local bytes = tonumber(string.sub(line,2))
if bytes >= 0 then
local data = readbytes(fd, bytes + 2)
-- bulk[i] = nil when bytes < 0
bulk[i] = string.sub(data,1,-3)
end
end
return true, bulk
end
redcmd[36] = function(fd, data) -- '$'
local bytes = tonumber(data)
if bytes < 0 then
return true,nil
end
local firstline = readbytes(fd, bytes+2)
return true,string.sub(firstline,1,-3)
end
redcmd[43] = function(fd, data) -- '+'
return true,data
end
redcmd[45] = function(fd, data) -- '-'
return false,data
end
redcmd[58] = function(fd, data) -- ':'
-- todo: return string later
return true, tonumber(data)
end
local function read_response(fd)
local result = readline(fd, "\r\n")
local firstchar = string.byte(result)
local data = string.sub(result,2)
return redcmd[firstchar](fd,data)
end
setmetatable(command, { __index = function(t,k)
local cmd = string.upper(k)
local f = function (self, ...)
local fd = self.__handle
if self.__mode then
socket.write(fd, compose_message { cmd, ... })
self.__batch = self.__batch + 1
else
socket.lock(fd)
socket.write(fd, compose_message { cmd, ... })
local ok, ret = read_response(fd)
socket.unlock(fd)
assert(ok, ret)
return ret
end
end
t[k] = f
return f
end})
function command:exists(key)
assert(not self.__mode, "exists can't used in batch mode")
local fd = self.__handle
socket.lock(fd)
socket.write(fd, compose_message { "EXISTS", key })
local ok, exists = read_response(fd)
socket.unlock(fd)
assert(ok, exists)
return exists ~= 0
end
function command:sismember(key, value)
assert(not self.__mode, "sismember can't used in batch mode")
local fd = self.__handle
socket.lock(fd)
socket.write(fd, compose_message { "SISMEMBER", key, value })
local ok, ismember = read_response(fd)
socket.unlock(fd)
assert(ok, ismember)
return ismember ~= 0
end
function command:batch(mode)
if mode == "end" then
local fd = self.__handle
if self.__mode == "read" then
local allok = true
local allret = {}
for i = 1, self.__batch do
local ok, ret = read_response(fd)
allok = allok and ok
allret[i] = ret
end
self.__mode = false
socket.unlock(self.__handle)
assert(allok, "batch read failed")
return allret
else
local allok = true
for i = 1, self.__batch do
local ok = read_response(fd)
allok = allok and ok
end
self.__mode = false
socket.unlock(self.__handle)
return allok
end
else
assert(not self.__mode and (mode == "read" or mode == "write"))
socket.lock(self.__handle)
self.__mode = mode
self.__batch = 0
end
end
return redis
|
bugfix: redis batch mode. fix Issue #51
|
bugfix: redis batch mode. fix Issue #51
|
Lua
|
mit
|
longmian/skynet,zhangshiqian1214/skynet,KittyCookie/skynet,javachengwc/skynet,cloudwu/skynet,Zirpon/skynet,winglsh/skynet,fztcjjl/skynet,vizewang/skynet,MoZhonghua/skynet,chenjiansnail/skynet,sundream/skynet,sundream/skynet,zzh442856860/skynet,LiangMa/skynet,plsytj/skynet,ruleless/skynet,ilylia/skynet,JiessieDawn/skynet,longmian/skynet,cuit-zhaxin/skynet,zhouxiaoxiaoxujian/skynet,felixdae/skynet,lawnight/skynet,hongling0/skynet,samael65535/skynet,xcjmine/skynet,felixdae/skynet,felixdae/skynet,matinJ/skynet,catinred2/skynet,QuiQiJingFeng/skynet,kebo/skynet,cmingjian/skynet,iskygame/skynet,ruleless/skynet,dymx101/skynet,puXiaoyi/skynet,leezhongshan/skynet,fztcjjl/skynet,matinJ/skynet,cmingjian/skynet,enulex/skynet,iskygame/skynet,great90/skynet,zhangshiqian1214/skynet,jiuaiwo1314/skynet,matinJ/skynet,asanosoyokaze/skynet,harryzeng/skynet,KAndQ/skynet,KittyCookie/skynet,MoZhonghua/skynet,nightcj/mmo,lawnight/skynet,ludi1991/skynet,lc412/skynet,zzh442856860/skynet-Note,xjdrew/skynet,zhangshiqian1214/skynet,kebo/skynet,catinred2/skynet,rainfiel/skynet,harryzeng/skynet,bigrpg/skynet,MRunFoss/skynet,enulex/skynet,togolwb/skynet,KAndQ/skynet,wangyi0226/skynet,JiessieDawn/skynet,wangjunwei01/skynet,qyli/test,letmefly/skynet,leezhongshan/skynet,liuxuezhan/skynet,your-gatsby/skynet,kyle-wang/skynet,hongling0/skynet,firedtoad/skynet,peimin/skynet_v0.1_with_notes,u20024804/skynet,chuenlungwang/skynet,u20024804/skynet,MetSystem/skynet,sdgdsffdsfff/skynet,peimin/skynet_v0.1_with_notes,cdd990/skynet,zhaijialong/skynet,vizewang/skynet,xcjmine/skynet,sundream/skynet,jxlczjp77/skynet,zhangshiqian1214/skynet,qyli/test,wangyi0226/skynet,sanikoyes/skynet,ruleless/skynet,jxlczjp77/skynet,sanikoyes/skynet,cpascal/skynet,xinmingyao/skynet,sanikoyes/skynet,fztcjjl/skynet,xubigshu/skynet,chfg007/skynet,samael65535/skynet,boyuegame/skynet,boyuegame/skynet,jiuaiwo1314/skynet,kyle-wang/skynet,gitfancode/skynet,xinjuncoding/skynet,czlc/skynet,bingo235/skynet,ypengju/skynet_comment,microcai/skynet,liuxuezhan/skynet,wangyi0226/skynet,helling34/skynet,ag6ag/skynet,bttscut/skynet,cdd990/skynet,liuxuezhan/skynet,fhaoquan/skynet,zhaijialong/skynet,gitfancode/skynet,bingo235/skynet,catinred2/skynet,liuxuezhan/skynet,zhouxiaoxiaoxujian/skynet,puXiaoyi/skynet,microcai/skynet,zhoukk/skynet,codingabc/skynet,MoZhonghua/skynet,MRunFoss/skynet,xubigshu/skynet,lynx-seu/skynet,zzh442856860/skynet,firedtoad/skynet,javachengwc/skynet,cuit-zhaxin/skynet,pigparadise/skynet,Ding8222/skynet,czlc/skynet,KittyCookie/skynet,great90/skynet,cpascal/skynet,KAndQ/skynet,bigrpg/skynet,pigparadise/skynet,bingo235/skynet,ag6ag/skynet,lawnight/skynet,lynx-seu/skynet,xjdrew/skynet,Ding8222/skynet,chenjiansnail/skynet,enulex/skynet,pichina/skynet,zhoukk/skynet,vizewang/skynet,Zirpon/skynet,yinjun322/skynet,cuit-zhaxin/skynet,QuiQiJingFeng/skynet,togolwb/skynet,xinjuncoding/skynet,MetSystem/skynet,LiangMa/skynet,u20024804/skynet,microcai/skynet,firedtoad/skynet,icetoggle/skynet,korialuo/skynet,yunGit/skynet,Markal128/skynet,ypengju/skynet_comment,great90/skynet,chfg007/skynet,yunGit/skynet,zzh442856860/skynet-Note,cloudwu/skynet,bttscut/skynet,icetoggle/skynet,sdgdsffdsfff/skynet,fhaoquan/skynet,zzh442856860/skynet,kebo/skynet,togolwb/skynet,xjdrew/skynet,pichina/skynet,LuffyPan/skynet,bigrpg/skynet,letmefly/skynet,qyli/test,ypengju/skynet_comment,wangjunwei01/skynet,puXiaoyi/skynet,LuffyPan/skynet,winglsh/skynet,ag6ag/skynet,yinjun322/skynet,bttscut/skynet,dymx101/skynet,helling34/skynet,leezhongshan/skynet,QuiQiJingFeng/skynet,zhoukk/skynet,your-gatsby/skynet,boyuegame/skynet,korialuo/skynet,harryzeng/skynet,yunGit/skynet,ilylia/skynet,cloudwu/skynet,plsytj/skynet,zhangshiqian1214/skynet,nightcj/mmo,rainfiel/skynet,jxlczjp77/skynet,plsytj/skynet,lynx-seu/skynet,ludi1991/skynet,yinjun322/skynet,zhangshiqian1214/skynet,chenjiansnail/skynet,jiuaiwo1314/skynet,cpascal/skynet,letmefly/skynet,czlc/skynet,javachengwc/skynet,Zirpon/skynet,chuenlungwang/skynet,xinjuncoding/skynet,kyle-wang/skynet,winglsh/skynet,zzh442856860/skynet-Note,samael65535/skynet,korialuo/skynet,cdd990/skynet,qyli/test,cmingjian/skynet,wangjunwei01/skynet,LiangMa/skynet,lc412/skynet,asanosoyokaze/skynet,pigparadise/skynet,letmefly/skynet,codingabc/skynet,xcjmine/skynet,ludi1991/skynet,longmian/skynet,LuffyPan/skynet,Ding8222/skynet,MetSystem/skynet,lc412/skynet,peimin/skynet,dymx101/skynet,asanosoyokaze/skynet,helling34/skynet,Markal128/skynet,your-gatsby/skynet,chuenlungwang/skynet,Markal128/skynet,ludi1991/skynet,icetoggle/skynet,JiessieDawn/skynet,iskygame/skynet,chfg007/skynet,xinmingyao/skynet,codingabc/skynet,pichina/skynet,hongling0/skynet,lawnight/skynet,nightcj/mmo,rainfiel/skynet,peimin/skynet,sdgdsffdsfff/skynet,gitfancode/skynet,fhaoquan/skynet,zhaijialong/skynet,zzh442856860/skynet-Note,MRunFoss/skynet,ilylia/skynet,zhouxiaoxiaoxujian/skynet
|
271ce20cabc748da2c00bd772f5a11d2fb010b73
|
kong/tools/config_loader.lua
|
kong/tools/config_loader.lua
|
local yaml = require "yaml"
local IO = require "kong.tools.io"
local utils = require "kong.tools.utils"
local logger = require "kong.cli.utils.logger"
local luarocks = require "kong.cli.utils.luarocks"
local stringy = require "stringy"
local constants = require "kong.constants"
local config_defaults = require "kong.tools.config_defaults"
local function get_type(value, val_type)
if val_type == "array" and utils.is_array(value) then
return "array"
else
return type(value)
end
end
local function is_valid_IPv4(ip)
if not ip or stringy.strip(ip) == "" then return false end
local a, b, c, d = ip:match("^(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)$")
a = tonumber(a)
b = tonumber(b)
c = tonumber(c)
d = tonumber(d)
if not a or not b or not c or not d then return false end
if a < 0 or 255 < a then return false end
if b < 0 or 255 < b then return false end
if c < 0 or 255 < c then return false end
if d < 0 or 255 < d then return false end
return true
end
local function is_valid_address(value, only_IPv4)
if not value or stringy.strip(value) == "" then return false end
local parts = stringy.split(value, ":")
if #parts ~= 2 then return false end
if stringy.strip(parts[1]) == "" then return false end
if only_IPv4 and not is_valid_IPv4(parts[1]) then return false end
local port = tonumber(parts[2])
if not port then return false end
if not (port > 0 and port <= 65535) then return false end
return true
end
local checks = {
type = function(value, key_infos, value_type)
if value_type ~= key_infos.type then
return "must be a "..key_infos.type
end
end,
minimum = function(value, key_infos, value_type)
if value_type == "number" and key_infos.min ~= nil and value < key_infos.min then
return "must be greater than "..key_infos.min
end
end,
enum = function(value, key_infos, value_type)
if key_infos.enum ~= nil and not utils.table_contains(key_infos.enum, value) then
return string.format("must be one of: '%s'", table.concat(key_infos.enum, ", "))
end
end
}
local function validate_config_schema(config, config_schema)
if not config_schema then config_schema = config_defaults end
local errors, property
for config_key, key_infos in pairs(config_schema) do
-- Default value
property = config[config_key]
if property == nil then
property = key_infos.default
end
-- Recursion on table values
if key_infos.type == "table" and key_infos.content ~= nil then
if property == nil then
property = {}
end
local ok, s_errors = validate_config_schema(property, key_infos.content)
if not ok then
for s_k, s_v in pairs(s_errors) do
errors = utils.add_error(errors, config_key.."."..s_k, s_v)
end
end
end
-- Nullable checking
if property ~= nil and not key_infos.nullable then
local property_type = get_type(property, key_infos.type)
local err
-- Individual checks
for _, check_fun in pairs(checks) do
err = check_fun(property, key_infos, property_type)
if err then
errors = utils.add_error(errors, config_key, err)
end
end
end
config[config_key] = property
end
return errors == nil, errors
end
local _M = {}
function _M.validate(config)
local ok, errors = validate_config_schema(config)
if not ok then
return false, errors
end
-- Check listen addresses
if config.proxy_listen and not is_valid_address(config.proxy_listen) then
return false, {proxy_listen = config.proxy_listen.." is not a valid \"host:port\" value"}
end
if config.proxy_listen_ssl and not is_valid_address(config.proxy_listen_ssl) then
return false, {proxy_listen_ssl = config.proxy_listen_ssl.." is not a valid \"host:port\" value"}
end
if config.admin_api_listen and not is_valid_address(config.admin_api_listen) then
return false, {admin_api_listen = config.admin_api_listen.." is not a valid \"host:port\" value"}
end
-- Cluster listen addresses must have an IPv4 host (no hostnames)
if config.cluster_listen and not is_valid_address(config.cluster_listen, true) then
return false, {cluster_listen = config.cluster_listen.." is not a valid \"ip:port\" value"}
end
if config.cluster_listen_rpc and not is_valid_address(config.cluster_listen_rpc, true) then
return false, {cluster_listen_rpc = config.cluster_listen_rpc.." is not a valid \"ip:port\" value"}
end
-- Same for the cluster.advertise value
if config.cluster and config.cluster.advertise and stringy.strip(config.cluster.advertise) ~= "" and not is_valid_address(config.cluster.advertise, true) then
return false, {["cluster.advertise"] = config.cluster.advertise.." is not a valid \"ip:port\" value"}
end
return true
end
function _M.load(config_path)
local config_contents = IO.read_file(config_path)
if not config_contents then
logger:error("No configuration file at: "..config_path)
os.exit(1)
end
local config = yaml.load(config_contents)
local ok, errors = _M.validate(config)
if not ok then
for config_key, config_error in pairs(errors) do
if type(config_error) == "table" then
config_error = table.concat(config_error, ", ")
end
logger:warn(string.format("%s: %s", config_key, config_error))
end
logger:error("Invalid properties in given configuration file")
os.exit(1)
end
-- Adding computed properties
config.pid_file = IO.path:join(config.nginx_working_dir, constants.CLI.NGINX_PID)
config.dao_config = config[config.database]
if config.dns_resolver == "dnsmasq" then
config.dns_resolver = {
address = "127.0.0.1:"..config.dns_resolvers_available.dnsmasq.port,
port = config.dns_resolvers_available.dnsmasq.port,
dnsmasq = true
}
else
config.dns_resolver = {address = config.dns_resolvers_available.server.address}
end
-- Load absolute path for the nginx working directory
if not stringy.startswith(config.nginx_working_dir, "/") then
-- It's a relative path, convert it to absolute
local fs = require "luarocks.fs"
config.nginx_working_dir = fs.current_dir().."/"..config.nginx_working_dir
end
config.plugins = utils.table_merge(constants.PLUGINS_AVAILABLE, config.custom_plugins)
return config, config_path
end
function _M.load_default(config_path)
if not IO.file_exists(config_path) then
logger:warn("No configuration at: "..config_path.." using default config instead.")
config_path = IO.path:join(luarocks.get_config_dir(), "kong.yml")
end
logger:info("Using configuration: "..config_path)
return _M.load(config_path)
end
return _M
|
local yaml = require "yaml"
local IO = require "kong.tools.io"
local utils = require "kong.tools.utils"
local logger = require "kong.cli.utils.logger"
local luarocks = require "kong.cli.utils.luarocks"
local stringy = require "stringy"
local constants = require "kong.constants"
local config_defaults = require "kong.tools.config_defaults"
local function get_type(value, val_type)
if val_type == "array" and utils.is_array(value) then
return "array"
else
return type(value)
end
end
local function is_valid_IPv4(ip)
if not ip or stringy.strip(ip) == "" then return false end
local a, b, c, d = ip:match("^(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)$")
a = tonumber(a)
b = tonumber(b)
c = tonumber(c)
d = tonumber(d)
if not a or not b or not c or not d then return false end
if a < 0 or 255 < a then return false end
if b < 0 or 255 < b then return false end
if c < 0 or 255 < c then return false end
if d < 0 or 255 < d then return false end
return true
end
local function is_valid_address(value, only_IPv4)
if not value or stringy.strip(value) == "" then return false end
local parts = stringy.split(value, ":")
if #parts ~= 2 then return false end
if stringy.strip(parts[1]) == "" then return false end
if only_IPv4 and not is_valid_IPv4(parts[1]) then return false end
local port = tonumber(parts[2])
if not port then return false end
if not (port > 0 and port <= 65535) then return false end
return true
end
local checks = {
type = function(value, key_infos, value_type)
if value_type ~= key_infos.type then
return "must be a "..key_infos.type
end
end,
minimum = function(value, key_infos, value_type)
if value_type == "number" and key_infos.min ~= nil and value < key_infos.min then
return "must be greater than "..key_infos.min
end
end,
enum = function(value, key_infos, value_type)
if key_infos.enum ~= nil and not utils.table_contains(key_infos.enum, value) then
return string.format("must be one of: '%s'", table.concat(key_infos.enum, ", "))
end
end
}
local function validate_config_schema(config, config_schema)
if not config_schema then config_schema = config_defaults end
local errors, property
for config_key, key_infos in pairs(config_schema) do
-- Default value
property = config[config_key]
if property == nil then
property = key_infos.default
end
-- Recursion on table values
if key_infos.type == "table" and key_infos.content ~= nil then
if property == nil then
property = {}
end
local ok, s_errors = validate_config_schema(property, key_infos.content)
if not ok then
for s_k, s_v in pairs(s_errors) do
errors = utils.add_error(errors, config_key.."."..s_k, s_v)
end
end
end
-- Nullable checking
if property ~= nil and not key_infos.nullable then
local property_type = get_type(property, key_infos.type)
local err
-- Individual checks
for _, check_fun in pairs(checks) do
err = check_fun(property, key_infos, property_type)
if err then
errors = utils.add_error(errors, config_key, err)
end
end
end
config[config_key] = property
end
return errors == nil, errors
end
local _M = {}
function _M.validate(config)
local ok, errors = validate_config_schema(config)
if not ok then
return false, errors
end
-- Check listen addresses
if config.proxy_listen and not is_valid_address(config.proxy_listen) then
return false, {proxy_listen = config.proxy_listen.." is not a valid \"host:port\" value"}
end
if config.proxy_listen_ssl and not is_valid_address(config.proxy_listen_ssl) then
return false, {proxy_listen_ssl = config.proxy_listen_ssl.." is not a valid \"host:port\" value"}
end
if config.admin_api_listen and not is_valid_address(config.admin_api_listen) then
return false, {admin_api_listen = config.admin_api_listen.." is not a valid \"host:port\" value"}
end
-- Cluster listen addresses must have an IPv4 host (no hostnames)
if config.cluster_listen and not is_valid_address(config.cluster_listen, true) then
return false, {cluster_listen = config.cluster_listen.." is not a valid \"ip:port\" value"}
end
if config.cluster_listen_rpc and not is_valid_address(config.cluster_listen_rpc, true) then
return false, {cluster_listen_rpc = config.cluster_listen_rpc.." is not a valid \"ip:port\" value"}
end
-- Same for the cluster.advertise value
if config.cluster and config.cluster.advertise and stringy.strip(config.cluster.advertise) ~= "" and not is_valid_address(config.cluster.advertise, true) then
return false, {["cluster.advertise"] = config.cluster.advertise.." is not a valid \"ip:port\" value"}
end
return true
end
function _M.load(config_path)
local config_contents = IO.read_file(config_path)
if not config_contents then
logger:error("No configuration file at: "..config_path)
os.exit(1)
end
local status,config = pcall(yaml.load,config_contents)
if not status then
logger:error("Could not parse configuration at: "..config_path)
os.exit(1)
end
local ok, errors = _M.validate(config)
if not ok then
for config_key, config_error in pairs(errors) do
if type(config_error) == "table" then
config_error = table.concat(config_error, ", ")
end
logger:warn(string.format("%s: %s", config_key, config_error))
end
logger:error("Invalid properties in given configuration file")
os.exit(1)
end
-- Adding computed properties
config.pid_file = IO.path:join(config.nginx_working_dir, constants.CLI.NGINX_PID)
config.dao_config = config[config.database]
if config.dns_resolver == "dnsmasq" then
config.dns_resolver = {
address = "127.0.0.1:"..config.dns_resolvers_available.dnsmasq.port,
port = config.dns_resolvers_available.dnsmasq.port,
dnsmasq = true
}
else
config.dns_resolver = {address = config.dns_resolvers_available.server.address}
end
-- Load absolute path for the nginx working directory
if not stringy.startswith(config.nginx_working_dir, "/") then
-- It's a relative path, convert it to absolute
local fs = require "luarocks.fs"
config.nginx_working_dir = fs.current_dir().."/"..config.nginx_working_dir
end
config.plugins = utils.table_merge(constants.PLUGINS_AVAILABLE, config.custom_plugins)
return config, config_path
end
function _M.load_default(config_path)
if not IO.file_exists(config_path) then
logger:warn("No configuration at: "..config_path.." using default config instead.")
config_path = IO.path:join(luarocks.get_config_dir(), "kong.yml")
end
logger:info("Using configuration: "..config_path)
return _M.load(config_path)
end
return _M
|
feat(conf) graceful error message on invalid conf
|
feat(conf) graceful error message on invalid conf
Fix #949
Signed-off-by: Thibault Charbonnier <3c2e9133e272cb489e2fea0c4328cf56b08e4226@me.com>
|
Lua
|
apache-2.0
|
li-wl/kong,smanolache/kong,Vermeille/kong,jerizm/kong,jebenexer/kong,icyxp/kong,akh00/kong,shiprabehera/kong,Kong/kong,Kong/kong,Kong/kong,ccyphers/kong,Mashape/kong,salazar/kong,beauli/kong
|
01126eee62231b3370f5fd796d93f40846ad5dbb
|
modules/client_serverlist/serverlist.lua
|
modules/client_serverlist/serverlist.lua
|
ServerList = {}
-- private variables
local serverListWindow = nil
local serverTextList = nil
local servers = {}
-- private functions
function getServer(host)
for k,server in pairs(servers) do
if server.host == host then
return server
end
end
end
function getServerKey(host)
for k,server in pairs(servers) do
if server.host == host then
return k
end
end
end
-- public functions
function ServerList.init()
serverListWindow = g_ui.displayUI('serverlist')
serverTextList = serverListWindow:getChildById('serverList')
servers = g_settings.getNode('ServerList') or {}
ServerList.load()
end
function ServerList.terminate()
ServerList.destroy()
g_settings.setNode('ServerList', servers)
ServerList = nil
end
function ServerList.load()
for k,server in pairs(servers) do
ServerList.add(server.host, server.port, server.protocol, true)
end
end
function ServerList.select()
local selected = serverTextList:getFocusedChild()
if selected then
local server = servers[getServerKey(selected:getId())]
if server then
EnterGame.setDefaultServer(server.host, server.port, server.protocol)
EnterGame.setAccountName(server.account)
EnterGame.setPassword(server.password)
ServerList.hide()
end
end
end
function ServerList.add(host, port, protocol, load)
if not load and getServerKey(host) then
return false, 'Server already exists'
elseif host == '' or port == '' then
return false, 'Required fields are missing'
end
local widget = g_ui.createWidget('ServerWidget', serverTextList)
widget:setId(host)
if not load then
servers[table.size(servers)+1] = {
host = host,
port = port,
protocol = protocol,
account = '',
password = ''
}
end
local details = widget:getChildById('details')
details:setText(host..':'..port)
local proto = widget:getChildById('protocol')
proto:setText(protocol)
connect(widget, { onDoubleClick = function () ServerList.select() return true end } )
return true
end
function ServerList.remove(host)
servers[getServerKey(host)] = nil
end
function ServerList.destroy()
if serverListWindow then
serverTextList = nil
serverListWindow:destroy()
serverListWindow = nil
end
end
function ServerList.show()
if g_game.isOnline() then
return
end
serverListWindow:show()
serverListWindow:raise()
serverListWindow:focus()
end
function ServerList.hide()
serverListWindow:hide()
end
function ServerList.setServerAccount(host, account)
local key = getServerKey(host)
if servers[key] then
servers[key].account = account
end
end
function ServerList.setServerPassword(host, password)
local key = getServerKey(host)
if servers[key] then
servers[key].password = password
end
end
|
ServerList = {}
-- private variables
local serverListWindow = nil
local serverTextList = nil
local servers = {}
-- public functions
function ServerList.init()
serverListWindow = g_ui.displayUI('serverlist')
serverTextList = serverListWindow:getChildById('serverList')
servers = g_settings.getNode('ServerList') or {}
ServerList.load()
end
function ServerList.terminate()
ServerList.destroy()
g_settings.setNode('ServerList', servers)
ServerList = nil
end
function ServerList.load()
for k,server in pairs(servers) do
ServerList.add(k, server.port, server.protocol, true)
end
end
function ServerList.select()
local selected = serverTextList:getFocusedChild()
if selected then
local server = servers[selected:getId()]
if server then
EnterGame.setDefaultServer(selected:getId(), server.port, server.protocol)
EnterGame.setAccountName(server.account)
EnterGame.setPassword(server.password)
ServerList.hide()
end
end
end
function ServerList.add(host, port, protocol, load)
if not load and servers[host] then
return false, 'Server already exists'
elseif host == '' or port == '' then
return false, 'Required fields are missing'
end
local widget = g_ui.createWidget('ServerWidget', serverTextList)
widget:setId(host)
if not load then
servers[host] = {
port = port,
protocol = protocol,
account = '',
password = ''
}
end
local details = widget:getChildById('details')
details:setText(host..':'..port)
local proto = widget:getChildById('protocol')
proto:setText(protocol)
connect(widget, { onDoubleClick = function () ServerList.select() return true end } )
return true
end
function ServerList.remove(host)
servers[host] = nil
end
function ServerList.destroy()
if serverListWindow then
serverTextList = nil
serverListWindow:destroy()
serverListWindow = nil
end
end
function ServerList.show()
if g_game.isOnline() then
return
end
serverListWindow:show()
serverListWindow:raise()
serverListWindow:focus()
end
function ServerList.hide()
serverListWindow:hide()
end
function ServerList.setServerAccount(host, account)
if servers[host] then
servers[host].account = account
end
end
function ServerList.setServerPassword(host, password)
if servers[host] then
servers[host].password = password
end
end
|
Some fixes for the server list module * Fixed an indexing issue in the settings Note: Forgot to mention that it will store the last account/password used for that server
|
Some fixes for the server list module
* Fixed an indexing issue in the settings
Note: Forgot to mention that it will store the last account/password used for that server
|
Lua
|
mit
|
dreamsxin/otclient,Radseq/otclient,kwketh/otclient,EvilHero90/otclient,gpedro/otclient,Cavitt/otclient_mapgen,Radseq/otclient,gpedro/otclient,gpedro/otclient,dreamsxin/otclient,dreamsxin/otclient,EvilHero90/otclient,kwketh/otclient,Cavitt/otclient_mapgen
|
c1ad5ef59deaf218896303c4571ead3d8298646a
|
lua/include/histogram.lua
|
lua/include/histogram.lua
|
local histogram = {}
histogram.__index = histogram
function histogram.create()
local histo = {}
setmetatable(histo, histogram)
histo.histo = {}
histo.dirty = true
return histo
end
function histogram:update(k)
self.histo[k] = (self.histo[k] or 0) +1
self.dirty = true
end
function histogram:calc()
self.sortedHisto = {}
self.sum = 0
self.samples = 0
for k, v in pairs(self.histo) do
table.insert(self.sortedHisto, {k = k, v = v})
self.samples = self.samples + v
self.sum = self.sum + k * v
end
self.avg = self.sum / self.samples
table.sort(self.sortedHisto, function(e1, e2) return e1.k < e2.k end)
local quartSamples = self.samples / 4
self.lowerQuart = nil
self.median = nil
self.upperQuart = nil
local idx = 0
for _, p in ipairs(self.sortedHisto) do
if not self.lowerQuart and idx >= quartSamples then
self.lowerQuart = p.k
elseif not self.median and idx >= quartSamples * 2 then
self.median = p.k
elseif not self.upperQuart and idx >= quartSamples * 3 then
self.upperQuart = p.k
break
end
idx = idx + p.v
end
self.dirty = false
end
function histogram:quartiles()
if self.dirty then self:calc() end
return self.lowerQuart, self.median, self.upperQuart
end
function histogram:samples()
local i = 0
if self.dirty then self:calc() end
local n = #self.sortedHisto
return function()
if not self.dirty then
i = i + 1
if i <= n then return self.sortedHisto[i] end
end
end
end
return histogram
|
local histogram = {}
histogram.__index = histogram
function histogram.create()
local histo = {}
setmetatable(histo, histogram)
histo.histo = {}
histo.dirty = true
return histo
end
function histogram:update(k)
self.histo[k] = (self.histo[k] or 0) +1
self.dirty = true
end
function histogram:calc()
self.sortedHisto = {}
self.sum = 0
self.numSamples = 0
for k, v in pairs(self.histo) do
table.insert(self.sortedHisto, {k = k, v = v})
self.numSamples = self.numSamples + v
self.sum = self.sum + k * v
end
self.avg = self.sum / self.numSamples
table.sort(self.sortedHisto, function(e1, e2) return e1.k < e2.k end)
local quartSamples = self.numSamples / 4
self.lowerQuart = nil
self.median = nil
self.upperQuart = nil
local idx = 0
for _, p in ipairs(self.sortedHisto) do
if not self.lowerQuart and idx >= quartSamples then
self.lowerQuart = p.k
elseif not self.median and idx >= quartSamples * 2 then
self.median = p.k
elseif not self.upperQuart and idx >= quartSamples * 3 then
self.upperQuart = p.k
break
end
idx = idx + p.v
end
self.dirty = false
end
function histogram:totals()
if self.dirty then self:calc() end
return self.numSamples, self.sum, self.avg
end
function histogram:quartiles()
if self.dirty then self:calc() end
return self.lowerQuart, self.median, self.upperQuart
end
function histogram:samples()
local i = 0
if self.dirty then self:calc() end
local n = #self.sortedHisto
return function()
if not self.dirty then
i = i + 1
if i <= n then return self.sortedHisto[i] end
end
end
end
return histogram
|
Add accessor for totals to histogram class
|
Add accessor for totals to histogram class
numSamples, sum, and avg can now be accessed in a clean way via the
:totals() method. This fixes a problem whereby the fields could be
accessed while they were in dirty state.
|
Lua
|
mit
|
atheurer/MoonGen,schoenb/MoonGen,schoenb/MoonGen,emmericp/MoonGen,slyon/MoonGen,wenhuizhang/MoonGen,atheurer/MoonGen,werpat/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,kidaa/MoonGen,emmericp/MoonGen,slyon/MoonGen,gallenmu/MoonGen,duk3luk3/MoonGen,dschoeffm/MoonGen,werpat/MoonGen,kidaa/MoonGen,atheurer/MoonGen,pavel-odintsov/MoonGen,NetronomeMoongen/MoonGen,pavel-odintsov/MoonGen,schoenb/MoonGen,NetronomeMoongen/MoonGen,pavel-odintsov/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,NetronomeMoongen/MoonGen,emmericp/MoonGen,bmichalo/MoonGen,scholzd/MoonGen,dschoeffm/MoonGen,duk3luk3/MoonGen,gallenmu/MoonGen,kidaa/MoonGen,slyon/MoonGen,gallenmu/MoonGen,slyon/MoonGen,wenhuizhang/MoonGen,bmichalo/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,werpat/MoonGen,wenhuizhang/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,duk3luk3/MoonGen
|
7775233688fd91ef17b70db7932cb910bd94fac9
|
frontend/ui/widget/radiobutton.lua
|
frontend/ui/widget/radiobutton.lua
|
--[[--
Widget that shows a radiobutton checked (`◉`) or unchecked (`◯`)
or nothing of the same size.
Example:
local RadioButton = require("ui/widget/radiobutton")
local parent_widget = FrameContainer:new{}
table.insert(parent_widget, RadioButton:new{
checkable = false, -- shows nothing when false, defaults to true
checked = function() end, -- whether the box is checked
})
UIManager:show(parent_widget)
]]
local Blitbuffer = require("ffi/blitbuffer")
local Device = require("device")
local Font = require("ui/font")
local FrameContainer = require("ui/widget/container/framecontainer")
local Geom = require("ui/geometry")
local GestureRange = require("ui/gesturerange")
local InputContainer = require("ui/widget/container/inputcontainer")
local LeftContainer = require("ui/widget/container/leftcontainer")
local TextWidget = require("ui/widget/textwidget")
local UIManager = require("ui/uimanager")
local RadioButton = InputContainer:new{
checkable = true,
checked = false,
enabled = true,
face = Font:getFace("smallinfofont"),
background = Blitbuffer.COLOR_WHITE,
width = 0,
height = 0,
}
function RadioButton:init()
self._checked_widget = TextWidget:new{
text = "◉ " .. self.text,
face = self.face,
max_width = self.max_width,
}
self._unchecked_widget = TextWidget:new{
text = "◯ " .. self.text,
face = self.face,
max_width = self.max_width,
}
self._empty_widget = TextWidget:new{
text = "" .. self.text,
face = self.face,
max_width = self.max_width,
}
self._widget_size = self._unchecked_widget:getSize()
if self.width == nil then
self.width = self._widget_size.w
end
self._radio_button = self.checkable
and (self.checked and self._checked_widget or self._unchecked_widget)
or self._empty_widget
self:update()
self.dimen = self.frame:getSize()
if Device:isTouchDevice() then
self.ges_events = {
TapCheckButton = {
GestureRange:new{
ges = "tap",
range = self.dimen,
},
doc = "Tap Button",
},
HoldCheckButton = {
GestureRange:new{
ges = "hold",
range = self.dimen,
},
doc = "Hold Button",
}
}
end
end
function RadioButton:update()
if self[1] then
self[1]:free()
end
self.frame = FrameContainer:new{
margin = self.margin,
bordersize = self.bordersize,
background = self.background,
radius = self.radius,
padding = self.padding,
LeftContainer:new{
dimen = Geom:new{
w = self.width,
h = self._widget_size.h
},
self._radio_button,
}
}
self[1] = self.frame
end
function RadioButton:onFocus()
self.frame.invert = true
return true
end
function RadioButton:onUnfocus()
self.frame.invert = false
return true
end
function RadioButton:onTapCheckButton()
if self.enabled and self.callback then
if G_reader_settings:isFalse("flash_ui") then
self.callback()
else
-- While I'd like to only flash the button itself, we have to make do with flashing the full width of the TextWidget...
self.frame.invert = true
UIManager:widgetRepaint(self.frame, self.dimen.x, self.dimen.y)
UIManager:setDirty(nil, function()
return "fast", self.dimen
end)
UIManager:tickAfterNext(function()
self.callback()
self.frame.invert = false
UIManager:widgetRepaint(self.frame, self.dimen.x, self.dimen.y)
UIManager:setDirty(nil, function()
return "fast", self.dimen
end)
end)
end
elseif self.tap_input then
self:onInput(self.tap_input)
elseif type(self.tap_input_func) == "function" then
self:onInput(self.tap_input_func())
end
return true
end
function RadioButton:onHoldCheckButton()
if self.enabled and self.hold_callback then
self.hold_callback()
elseif self.hold_input then
self:onInput(self.hold_input)
elseif type(self.hold_input_func) == "function" then
self:onInput(self.hold_input_func())
end
return true
end
function RadioButton:check(callback)
self._radio_button = self._checked_widget
self.checked = true
self:update()
UIManager:setDirty(self.parent, function()
return "fast", self.dimen
end)
end
function RadioButton:unCheck()
self._radio_button = self._unchecked_widget
self.checked = false
self:update()
UIManager:setDirty(self.parent, function()
return "fast", self.dimen
end)
end
return RadioButton
|
--[[--
Widget that shows a radiobutton checked (`◉`) or unchecked (`◯`)
or nothing of the same size.
Example:
local RadioButton = require("ui/widget/radiobutton")
local parent_widget = FrameContainer:new{}
table.insert(parent_widget, RadioButton:new{
checkable = false, -- shows nothing when false, defaults to true
checked = function() end, -- whether the box is checked
})
UIManager:show(parent_widget)
]]
local Blitbuffer = require("ffi/blitbuffer")
local Device = require("device")
local Font = require("ui/font")
local FrameContainer = require("ui/widget/container/framecontainer")
local Geom = require("ui/geometry")
local GestureRange = require("ui/gesturerange")
local InputContainer = require("ui/widget/container/inputcontainer")
local LeftContainer = require("ui/widget/container/leftcontainer")
local TextWidget = require("ui/widget/textwidget")
local UIManager = require("ui/uimanager")
local RadioButton = InputContainer:new{
checkable = true,
checked = false,
enabled = true,
face = Font:getFace("smallinfofont"),
background = Blitbuffer.COLOR_WHITE,
width = 0,
height = 0,
}
function RadioButton:init()
self._checked_widget = TextWidget:new{
text = "◉ " .. self.text,
face = self.face,
max_width = self.max_width,
}
self._unchecked_widget = TextWidget:new{
text = "◯ " .. self.text,
face = self.face,
max_width = self.max_width,
}
self._empty_widget = TextWidget:new{
text = "" .. self.text,
face = self.face,
max_width = self.max_width,
}
self._widget_size = self._unchecked_widget:getSize()
if self.width == nil then
self.width = self._widget_size.w
end
self._radio_button = self.checkable
and (self.checked and self._checked_widget or self._unchecked_widget)
or self._empty_widget
self:update()
self.dimen = self.frame:getSize()
if Device:isTouchDevice() then
self.ges_events = {
TapCheckButton = {
GestureRange:new{
ges = "tap",
range = self.dimen,
},
doc = "Tap Button",
},
HoldCheckButton = {
GestureRange:new{
ges = "hold",
range = self.dimen,
},
doc = "Hold Button",
}
}
end
end
function RadioButton:update()
self.frame = FrameContainer:new{
margin = self.margin,
bordersize = self.bordersize,
background = self.background,
radius = self.radius,
padding = self.padding,
LeftContainer:new{
dimen = Geom:new{
w = self.width,
h = self._widget_size.h
},
self._radio_button,
}
}
self[1] = self.frame
end
function RadioButton:onFocus()
self.frame.invert = true
return true
end
function RadioButton:onUnfocus()
self.frame.invert = false
return true
end
function RadioButton:onTapCheckButton()
if self.enabled and self.callback then
if G_reader_settings:isFalse("flash_ui") then
self.callback()
else
-- While I'd like to only flash the button itself, we have to make do with flashing the full width of the TextWidget...
self.frame.invert = true
UIManager:widgetRepaint(self.frame, self.dimen.x, self.dimen.y)
UIManager:setDirty(nil, function()
return "fast", self.dimen
end)
UIManager:tickAfterNext(function()
self.callback()
self.frame.invert = false
UIManager:widgetRepaint(self.frame, self.dimen.x, self.dimen.y)
UIManager:setDirty(nil, function()
return "fast", self.dimen
end)
end)
end
elseif self.tap_input then
self:onInput(self.tap_input)
elseif type(self.tap_input_func) == "function" then
self:onInput(self.tap_input_func())
end
return true
end
function RadioButton:onHoldCheckButton()
if self.enabled and self.hold_callback then
self.hold_callback()
elseif self.hold_input then
self:onInput(self.hold_input)
elseif type(self.hold_input_func) == "function" then
self:onInput(self.hold_input_func())
end
return true
end
function RadioButton:check(callback)
self._radio_button = self._checked_widget
self.checked = true
self:update()
UIManager:setDirty(self.parent, function()
return "fast", self.dimen
end)
end
function RadioButton:unCheck()
self._radio_button = self._unchecked_widget
self.checked = false
self:update()
UIManager:setDirty(self.parent, function()
return "fast", self.dimen
end)
end
return RadioButton
|
[fix] Prevent xtext crash by not freeing TextWidget prematurely (#5616)
|
[fix] Prevent xtext crash by not freeing TextWidget prematurely (#5616)
Fixes <https://github.com/koreader/koreader/issues/5614>.
|
Lua
|
agpl-3.0
|
Frenzie/koreader,koreader/koreader,pazos/koreader,mwoz123/koreader,NiLuJe/koreader,NiLuJe/koreader,koreader/koreader,Markismus/koreader,poire-z/koreader,Frenzie/koreader,mihailim/koreader,Hzj-jie/koreader,poire-z/koreader
|
cb7cc6e86a49864e2349c19484279370268e89fd
|
share/luaplaylist/dailymotion.lua
|
share/luaplaylist/dailymotion.lua
|
-- $Id$
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "dailymotion.com" )
and string.match( vlc.peek( 256 ), "<!DOCTYPE.*<title>Video " )
end
-- Parse function.
function parse()
while true
do
line = vlc.readline()
if not line then break end
if string.match( line, "param name=\"flashvars\" value=\"url=" )
then
path = vlc.decode_uri( string.gsub( line, "^.*param name=\"flashvars\" value=\"url=([^&]*).*$", "%1" ) )
end
--[[ if string.match( line, "<title>" )
then
title = vlc.decode_uri( string.gsub( line, "^.*<title>([^<]*).*$", "%1" ) )
end ]]
if string.match( line, "<meta name=\"description\"" )
then
name = vlc.resolve_xml_special_chars( string.gsub( line, "^.*name=\"description\" content=\"%w+ (.*) %w+ %w+ %w+ %w+ Videos\..*$", "%1" ) )
description = vlc.resolve_xml_special_chars( string.gsub( line, "^.*name=\"description\" content=\"%w+ .* %w+ %w+ %w+ %w+ Videos\. ([^\"]*)\".*$", "%1" ) )
end
if string.match( line, "<link rel=\"thumbnail\"" )
then
arturl = string.gsub( line, "^.*\"thumbnail\" type=\"([^\"]*)\".*$", "http://%1" ) -- looks like the dailymotion people mixed up type and href here ...
end
if path and name and description and arturl then break end
end
return { { path = path; name = name; description = description; url = vlc.path; arturl = arturl } }
end
|
-- $Id$
--[[
Translate Daily Motion video webpages URLs to the corresponding
FLV URL.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "dailymotion.com" )
and string.match( vlc.peek( 256 ), "<!DOCTYPE.*<title>Video " )
end
-- Parse function.
function parse()
while true
do
line = vlc.readline()
if not line then break end
if string.match( line, "param name=\"flashvars\" value=\".*url=" )
then
vlc.msg_err( "Tada!" )
path = vlc.decode_uri( string.gsub( line, "^.*param name=\"flashvars\" value=\".*url=([^&]*).*$", "%1" ) )
vlc.msg_err( path )
end
--[[ if string.match( line, "<title>" )
then
title = vlc.decode_uri( string.gsub( line, "^.*<title>([^<]*).*$", "%1" ) )
end ]]
if string.match( line, "<meta name=\"description\"" )
then
name = vlc.resolve_xml_special_chars( string.gsub( line, "^.*name=\"description\" content=\"%w+ (.*) %w+ %w+ %w+ %w+ Videos\..*$", "%1" ) )
description = vlc.resolve_xml_special_chars( string.gsub( line, "^.*name=\"description\" content=\"%w+ .* %w+ %w+ %w+ %w+ Videos\. ([^\"]*)\".*$", "%1" ) )
end
if string.match( line, "<link rel=\"thumbnail\"" )
then
arturl = string.gsub( line, "^.*\"thumbnail\" type=\"([^\"]*)\".*$", "http://%1" ) -- looks like the dailymotion people mixed up type and href here ...
end
if path and name and description and arturl then break end
end
return { { path = path; name = name; description = description; url = vlc.path; arturl = arturl } }
end
|
Fix the url translation
|
Fix the url translation
|
Lua
|
lgpl-2.1
|
jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,krichter722/vlc,krichter722/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc,krichter722/vlc,krichter722/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,krichter722/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc
|
1013ef286c1b85936dfb29ad6e0e42edd98ad054
|
kong/core/reports.lua
|
kong/core/reports.lua
|
local cjson = require "cjson.safe"
local utils = require "kong.tools.utils"
local singletons = require "kong.singletons"
local constants = require "kong.constants"
local kong_dict = ngx.shared.kong
local udp_sock = ngx.socket.udp
local timer_at = ngx.timer.at
local ngx_log = ngx.log
local concat = table.concat
local tostring = tostring
local pairs = pairs
local type = type
local ERR = ngx.ERR
local sub = string.sub
local PING_INTERVAL = 3600
local PING_KEY = "events:reports"
local BUFFERED_REQUESTS_COUNT_KEYS = "events:requests"
local _buffer = {}
local _enabled = false
local _unique_str = utils.random_string()
local _buffer_immutable_idx
do
-- initialize immutable buffer data (the same for each report)
local meta = require "kong.meta"
local system_infos = utils.get_system_infos()
-- <14>: syslog facility code 'log alert'
_buffer[#_buffer + 1] = "<14>version=" .. meta._VERSION
for k, v in pairs(system_infos) do
_buffer[#_buffer + 1] = k .. "=" .. v
end
_buffer_immutable_idx = #_buffer -- max idx for immutable slots
end
local function log(lvl, ...)
ngx_log(lvl, "[reports] ", ...)
end
-- UDP logger
local function send_report(signal_type, t, host, port)
if not _enabled then
return
elseif type(signal_type) ~= "string" then
return error("signal_type (arg #1) must be a string", 2)
end
t = t or {}
host = host or constants.SYSLOG.ADDRESS
port = port or constants.SYSLOG.PORT
-- add signal type to data
t.signal = signal_type
-- insert given entity in mutable part of buffer
local mutable_idx = _buffer_immutable_idx
for k, v in pairs(t) do
if k ~= "created_at" and sub(k, -2) ~= "id" then
if type(v) == "table" then
local json, err = cjson.encode(v)
if err then
log(ERR, "could not JSON encode given table entity: ", err)
end
v = json
end
mutable_idx = mutable_idx + 1
_buffer[mutable_idx] = k .. "=" .. tostring(v)
end
end
local sock = udp_sock()
local ok, err = sock:setpeername(host, port)
if not ok then
log(ERR, "could not set peer name for UDP socket: ", err)
return
end
sock:settimeout(1000)
-- concat and send buffer
--print(concat(_buffer, ";", 1, mutable_idx))
ok, err = sock:send(concat(_buffer, ";", 1, mutable_idx))
if not ok then
log(ERR, "could not send data: ", err)
end
ok, err = sock:close()
if not ok then
log(ERR, "could not close socket: ", err)
end
end
-- ping timer handler
-- Hold a lock for the whole interval (exptime) to prevent multiple
-- worker processes from sending the test request simultaneously.
-- Other workers do not need to wait until this lock is released,
-- and can ignore the event, knowing another worker is handling it.
-- We substract 1ms to the exp time to prevent a race condition
-- with the next timer event.
local function get_lock(key, exptime)
local ok, err = kong_dict:safe_add(key, true, exptime - 0.001)
if not ok and err ~= "exists" then
log(ERR, "could not get lock from 'kong' shm: ", err)
end
return ok
end
local function create_timer(...)
local ok, err = timer_at(...)
if not ok then
log(ERR, "could not create ping timer: ", err)
end
end
local function ping_handler(premature)
if premature then
return
end
-- all workers need to register a recurring timer, in case one of them
-- crashes. Hence, this must be called before the `get_lock()` call.
create_timer(PING_INTERVAL, ping_handler)
if not get_lock(PING_KEY, PING_INTERVAL) then
return
end
local n_requests, err = kong_dict:get(BUFFERED_REQUESTS_COUNT_KEYS)
if err then
log(ERR, "could not get buffered requests count from 'kong' shm: ", err)
elseif not n_requests then
n_requests = 0
end
send_report("ping", {
requests = n_requests,
unique_id = _unique_str,
database = singletons.configuration.database
})
local ok, err = kong_dict:incr(BUFFERED_REQUESTS_COUNT_KEYS, -n_requests, n_requests)
if not ok then
log(ERR, "could not reset buffered requests count in 'kong' shm: ", err)
end
end
return {
-- plugin handler
init_worker = function()
if not _enabled then
return
end
create_timer(PING_INTERVAL, ping_handler)
end,
log = function()
if not _enabled then
return
end
local ok, err = kong_dict:incr(BUFFERED_REQUESTS_COUNT_KEYS, 1, 0)
if not ok then
log(ERR, "could not increment buffered requests count in 'kong' shm: ",
err)
end
end,
-- custom methods
toggle = function(enable)
_enabled = enable
end,
send = send_report,
}
|
local cjson = require "cjson.safe"
local utils = require "kong.tools.utils"
local singletons = require "kong.singletons"
local constants = require "kong.constants"
local kong_dict = ngx.shared.kong
local udp_sock = ngx.socket.udp
local timer_at = ngx.timer.at
local ngx_log = ngx.log
local concat = table.concat
local tostring = tostring
local pairs = pairs
local type = type
local ERR = ngx.ERR
local sub = string.sub
local PING_INTERVAL = 3600
local PING_KEY = "events:reports"
local BUFFERED_REQUESTS_COUNT_KEYS = "events:requests"
local _buffer = {}
local _enabled = false
local _unique_str = utils.random_string()
local _buffer_immutable_idx
do
-- initialize immutable buffer data (the same for each report)
local meta = require "kong.meta"
local system_infos = utils.get_system_infos()
-- <14>: syslog facility code 'log alert'
_buffer[#_buffer + 1] = "<14>version=" .. meta._VERSION
for k, v in pairs(system_infos) do
_buffer[#_buffer + 1] = k .. "=" .. v
end
_buffer_immutable_idx = #_buffer -- max idx for immutable slots
end
local function log(lvl, ...)
ngx_log(lvl, "[reports] ", ...)
end
-- UDP logger
local function send_report(signal_type, t, host, port)
if not _enabled then
return
elseif type(signal_type) ~= "string" then
return error("signal_type (arg #1) must be a string", 2)
end
t = t or {}
host = host or constants.SYSLOG.ADDRESS
port = port or constants.SYSLOG.PORT
-- add signal type to data
t.signal = signal_type
-- insert given entity in mutable part of buffer
local mutable_idx = _buffer_immutable_idx
for k, v in pairs(t) do
if k == "unique_id" or (k ~= "created_at" and sub(k, -2) ~= "id") then
if type(v) == "table" then
local json, err = cjson.encode(v)
if err then
log(ERR, "could not JSON encode given table entity: ", err)
end
v = json
end
mutable_idx = mutable_idx + 1
_buffer[mutable_idx] = k .. "=" .. tostring(v)
end
end
local sock = udp_sock()
local ok, err = sock:setpeername(host, port)
if not ok then
log(ERR, "could not set peer name for UDP socket: ", err)
return
end
sock:settimeout(1000)
-- concat and send buffer
ok, err = sock:send(concat(_buffer, ";", 1, mutable_idx))
if not ok then
log(ERR, "could not send data: ", err)
end
ok, err = sock:close()
if not ok then
log(ERR, "could not close socket: ", err)
end
end
-- ping timer handler
-- Hold a lock for the whole interval (exptime) to prevent multiple
-- worker processes from sending the test request simultaneously.
-- Other workers do not need to wait until this lock is released,
-- and can ignore the event, knowing another worker is handling it.
-- We substract 1ms to the exp time to prevent a race condition
-- with the next timer event.
local function get_lock(key, exptime)
local ok, err = kong_dict:safe_add(key, true, exptime - 0.001)
if not ok and err ~= "exists" then
log(ERR, "could not get lock from 'kong' shm: ", err)
end
return ok
end
local function create_timer(...)
local ok, err = timer_at(...)
if not ok then
log(ERR, "could not create ping timer: ", err)
end
end
local function ping_handler(premature)
if premature then
return
end
-- all workers need to register a recurring timer, in case one of them
-- crashes. Hence, this must be called before the `get_lock()` call.
create_timer(PING_INTERVAL, ping_handler)
if not get_lock(PING_KEY, PING_INTERVAL) then
return
end
local n_requests, err = kong_dict:get(BUFFERED_REQUESTS_COUNT_KEYS)
if err then
log(ERR, "could not get buffered requests count from 'kong' shm: ", err)
elseif not n_requests then
n_requests = 0
end
send_report("ping", {
requests = n_requests,
unique_id = _unique_str,
database = singletons.configuration.database
})
local ok, err = kong_dict:incr(BUFFERED_REQUESTS_COUNT_KEYS, -n_requests, n_requests)
if not ok then
log(ERR, "could not reset buffered requests count in 'kong' shm: ", err)
end
end
return {
-- plugin handler
init_worker = function()
if not _enabled then
return
end
create_timer(PING_INTERVAL, ping_handler)
end,
log = function()
if not _enabled then
return
end
local ok, err = kong_dict:incr(BUFFERED_REQUESTS_COUNT_KEYS, 1, 0)
if not ok then
log(ERR, "could not increment buffered requests count in 'kong' shm: ",
err)
end
end,
-- custom methods
toggle = function(enable)
_enabled = enable
end,
send = send_report,
}
|
fix(reports) send unique_id again
|
fix(reports) send unique_id again
|
Lua
|
apache-2.0
|
akh00/kong,li-wl/kong,Kong/kong,salazar/kong,Kong/kong,Mashape/kong,ccyphers/kong,shiprabehera/kong,Kong/kong,jebenexer/kong,icyxp/kong
|
a2da9444015fa367dc4d81b0514410f01b58be46
|
build/scripts/LLVM.lua
|
build/scripts/LLVM.lua
|
require "Build"
require "Utils"
require "../Helpers"
local llvm = basedir .. "/../deps/llvm"
-- If we are inside vagrant then clone and build LLVM outside the shared folder,
-- otherwise file I/O performance will be terrible.
if is_vagrant() then
llvm = "~/llvm"
end
local llvm_build = llvm .. "/" .. os.get()
function get_llvm_rev()
return cat(basedir .. "/LLVM-commit")
end
function get_clang_rev()
return cat(basedir .. "/Clang-commit")
end
function clone_llvm()
local llvm_release = get_llvm_rev()
print("LLVM release: " .. llvm_release)
local clang_release = get_clang_rev()
print("Clang release: " .. clang_release)
if os.isdir(llvm) and not os.isdir(llvm .. "/.git") then
error("LLVM directory is not a git repository.")
end
if not os.isdir(llvm) then
git.clone(llvm, "http://llvm.org/git/llvm.git")
else
git.reset_hard(llvm, "HEAD")
git.pull_rebase(llvm)
end
local clang = llvm .. "/tools/clang"
if not os.isdir(clang) then
git.clone(clang, "http://llvm.org/git/clang.git")
else
git.reset_hard(clang, "HEAD")
git.pull_rebase(clang)
end
git.reset_hard(llvm, llvm_release)
git.reset_hard(clang, clang_release)
end
function get_llvm_package_name(rev, conf)
if not rev then
rev = get_llvm_rev()
end
if not conf then
conf = get_llvm_configuration_name()
end
rev = string.sub(rev, 0, 6)
return table.concat({"llvm", rev, os.get(), conf}, "-")
end
function get_llvm_configuration_name()
return os.is("windows") and "RelWithDebInfo" or "Release"
end
function extract_7z(archive, dest_dir)
return execute(string.format("7z x %s -o%s -y", archive, dest_dir), true)
end
function download_llvm()
local base = "https://dl.dropboxusercontent.com/u/194502/CppSharp/llvm/"
local pkg_name = get_llvm_package_name()
local archive = pkg_name .. ".7z"
-- check if we already have the file downloaded
if not os.isfile(archive) then
download(base .. archive, archive)
end
-- extract the package
if not os.isdir(pkg_name) then
extract_7z(archive, pkg_name)
end
end
function cmake(gen, conf)
local cwd = os.getcwd()
os.chdir(llvm_build)
local cmd = "cmake -G " .. '"' .. gen .. '"'
.. ' -DCLANG_BUILD_EXAMPLES=false -DCLANG_INCLUDE_DOCS=false -DCLANG_INCLUDE_TESTS=false'
.. ' -DCLANG_ENABLE_ARCMT=false -DCLANG_ENABLE_REWRITER=false -DCLANG_ENABLE_STATIC_ANALYZER=false'
.. ' -DLLVM_INCLUDE_EXAMPLES=false -DLLVM_INCLUDE_DOCS=false -DLLVM_INCLUDE_TESTS=false'
.. ' -DLLVM_TARGETS_TO_BUILD="X86"'
.. ' -DCMAKE_BUILD_TYPE=' .. conf .. ' ..'
execute(cmd)
os.chdir(cwd)
end
function clean_llvm(llvm_build)
if os.isdir(llvm_build) then os.rmdir(llvm_build) end
os.mkdir(llvm_build)
end
function build_llvm(llvm_build)
local conf = get_llvm_configuration_name()
local use_msbuild = false
if os.is("windows") and use_msbuild then
cmake("Visual Studio 12 2013", conf)
local llvm_sln = path.join(llvm_build, "LLVM.sln")
msbuild(llvm_sln, conf)
else
cmake("Ninja", conf)
ninja(llvm_build)
ninja(llvm_build, "clang-headers")
end
end
function package_llvm(conf, llvm, llvm_build)
local rev = git.rev_parse(llvm, "HEAD")
if string.is_empty(rev) then
rev = get_llvm_rev()
end
local out = get_llvm_package_name(rev, conf)
if os.isdir(out) then os.rmdir(out) end
os.mkdir(out)
os.copydir(llvm .. "/include", out .. "/include")
os.copydir(llvm_build .. "/include", out .. "/build/include")
local llvm_msbuild_libdir = "/" .. conf .. "/lib"
local lib_dir = os.is("windows") and os.isdir(llvm_msbuild_libdir)
and llvm_msbuild_libdir or "/lib"
local llvm_build_libdir = llvm_build .. lib_dir
if os.is("windows") and os.isdir(llvm_build_libdir) then
os.copydir(llvm_build_libdir, out .. "/build" .. lib_dir, "*.lib")
else
os.copydir(llvm_build_libdir, out .. "/build/lib", "*.a")
end
os.copydir(llvm .. "/tools/clang/include", out .. "/tools/clang/include")
os.copydir(llvm_build .. "/tools/clang/include", out .. "/build/tools/clang/include")
os.copydir(llvm .. "/tools/clang/lib/CodeGen", out .. "/tools/clang/lib/CodeGen", "*.h")
os.copydir(llvm .. "/tools/clang/lib/Driver", out .. "/tools/clang/lib/Driver", "*.h")
local out_lib_dir = out .. "/build" .. lib_dir
if os.is("windows") then
os.rmfiles(out_lib_dir, "LLVM*ObjCARCOpts*.lib")
os.rmfiles(out_lib_dir, "clang*ARC*.lib")
os.rmfiles(out_lib_dir, "clang*Matchers*.lib")
os.rmfiles(out_lib_dir, "clang*Rewrite*.lib")
os.rmfiles(out_lib_dir, "clang*StaticAnalyzer*.lib")
os.rmfiles(out_lib_dir, "clang*Tooling*.lib")
else
os.rmfiles(out_lib_dir, "libllvm*ObjCARCOpts*.a")
os.rmfiles(out_lib_dir, "libclang*ARC*.a")
os.rmfiles(out_lib_dir, "libclang*Matchers*.a")
os.rmfiles(out_lib_dir, "libclang*Rewrite*.a")
os.rmfiles(out_lib_dir, "libclang*StaticAnalyzer*.a")
os.rmfiles(out_lib_dir, "libclang*Tooling*.a")
end
return out
end
function archive_llvm(dir)
execute("7z a " .. dir .. ".7z " .. "./" .. dir .. "/*")
end
if _ACTION == "clone_llvm" then
clone_llvm()
os.exit()
end
if _ACTION == "build_llvm" then
clean_llvm(llvm_build)
build_llvm(llvm_build)
os.exit()
end
if _ACTION == "package_llvm" then
local conf = get_llvm_configuration_name()
local pkg = package_llvm(conf, llvm, llvm_build)
archive_llvm(pkg)
os.exit()
end
if _ACTION == "download_llvm" then
download_llvm()
os.exit()
end
|
require "Build"
require "Utils"
require "../Helpers"
local llvm = basedir .. "/../deps/llvm"
-- If we are inside vagrant then clone and build LLVM outside the shared folder,
-- otherwise file I/O performance will be terrible.
if is_vagrant() then
llvm = "~/llvm"
end
local llvm_build = llvm .. "/" .. os.get()
function get_llvm_rev()
return cat(basedir .. "/LLVM-commit")
end
function get_clang_rev()
return cat(basedir .. "/Clang-commit")
end
function clone_llvm()
local llvm_release = get_llvm_rev()
print("LLVM release: " .. llvm_release)
local clang_release = get_clang_rev()
print("Clang release: " .. clang_release)
if os.isdir(llvm) and not os.isdir(llvm .. "/.git") then
error("LLVM directory is not a git repository.")
end
if not os.isdir(llvm) then
git.clone(llvm, "http://llvm.org/git/llvm.git")
else
git.reset_hard(llvm, "HEAD")
git.pull_rebase(llvm)
end
local clang = llvm .. "/tools/clang"
if not os.isdir(clang) then
git.clone(clang, "http://llvm.org/git/clang.git")
else
git.reset_hard(clang, "HEAD")
git.pull_rebase(clang)
end
git.reset_hard(llvm, llvm_release)
git.reset_hard(clang, clang_release)
end
function get_llvm_package_name(rev, conf)
if not rev then
rev = get_llvm_rev()
end
if not conf then
conf = get_llvm_configuration_name()
end
rev = string.sub(rev, 0, 6)
return table.concat({"llvm", rev, os.get(), conf}, "-")
end
function get_llvm_configuration_name()
return os.is("windows") and "RelWithDebInfo" or "Release"
end
function extract_7z(archive, dest_dir)
return execute(string.format("7z x %s -o%s -y", archive, dest_dir), true)
end
function download_llvm()
local base = "https://dl.dropboxusercontent.com/u/194502/CppSharp/llvm/"
local pkg_name = get_llvm_package_name()
local archive = pkg_name .. ".7z"
-- check if we already have the file downloaded
if not os.isfile(archive) then
download(base .. archive, archive)
end
-- extract the package
if not os.isdir(pkg_name) then
extract_7z(archive, pkg_name)
end
end
function cmake(gen, conf, options)
local cwd = os.getcwd()
os.chdir(llvm_build)
local cmd = "cmake -G " .. '"' .. gen .. '"'
.. ' -DCLANG_BUILD_EXAMPLES=false -DCLANG_INCLUDE_DOCS=false -DCLANG_INCLUDE_TESTS=false'
.. ' -DCLANG_ENABLE_ARCMT=false -DCLANG_ENABLE_REWRITER=false -DCLANG_ENABLE_STATIC_ANALYZER=false'
.. ' -DLLVM_INCLUDE_EXAMPLES=false -DLLVM_INCLUDE_DOCS=false -DLLVM_INCLUDE_TESTS=false'
.. ' -DLLVM_TARGETS_TO_BUILD="X86"'
.. ' -DCMAKE_BUILD_TYPE=' .. conf .. ' ..'
.. ' ' .. options
execute(cmd)
os.chdir(cwd)
end
function clean_llvm(llvm_build)
if os.isdir(llvm_build) then os.rmdir(llvm_build) end
os.mkdir(llvm_build)
end
function build_llvm(llvm_build)
local conf = get_llvm_configuration_name()
local use_msbuild = false
if os.is("windows") and use_msbuild then
cmake("Visual Studio 12 2013", conf)
local llvm_sln = path.join(llvm_build, "LLVM.sln")
msbuild(llvm_sln, conf)
else
local options = os.is("macosx") and
"-DLLVM_ENABLE_LIBCXX=true -DLLVM_BUILD_32_BITS=true" or ""
cmake("Ninja", conf, options)
ninja(llvm_build)
ninja(llvm_build, "clang-headers")
end
end
function package_llvm(conf, llvm, llvm_build)
local rev = git.rev_parse(llvm, "HEAD")
if string.is_empty(rev) then
rev = get_llvm_rev()
end
local out = get_llvm_package_name(rev, conf)
if os.isdir(out) then os.rmdir(out) end
os.mkdir(out)
os.copydir(llvm .. "/include", out .. "/include")
os.copydir(llvm_build .. "/include", out .. "/build/include")
local llvm_msbuild_libdir = "/" .. conf .. "/lib"
local lib_dir = os.is("windows") and os.isdir(llvm_msbuild_libdir)
and llvm_msbuild_libdir or "/lib"
local llvm_build_libdir = llvm_build .. lib_dir
if os.is("windows") and os.isdir(llvm_build_libdir) then
os.copydir(llvm_build_libdir, out .. "/build" .. lib_dir, "*.lib")
else
os.copydir(llvm_build_libdir, out .. "/build/lib", "*.a")
end
os.copydir(llvm .. "/tools/clang/include", out .. "/tools/clang/include")
os.copydir(llvm_build .. "/tools/clang/include", out .. "/build/tools/clang/include")
os.copydir(llvm .. "/tools/clang/lib/CodeGen", out .. "/tools/clang/lib/CodeGen", "*.h")
os.copydir(llvm .. "/tools/clang/lib/Driver", out .. "/tools/clang/lib/Driver", "*.h")
local out_lib_dir = out .. "/build" .. lib_dir
if os.is("windows") then
os.rmfiles(out_lib_dir, "LLVM*ObjCARCOpts*.lib")
os.rmfiles(out_lib_dir, "clang*ARC*.lib")
os.rmfiles(out_lib_dir, "clang*Matchers*.lib")
os.rmfiles(out_lib_dir, "clang*Rewrite*.lib")
os.rmfiles(out_lib_dir, "clang*StaticAnalyzer*.lib")
os.rmfiles(out_lib_dir, "clang*Tooling*.lib")
else
os.rmfiles(out_lib_dir, "libllvm*ObjCARCOpts*.a")
os.rmfiles(out_lib_dir, "libclang*ARC*.a")
os.rmfiles(out_lib_dir, "libclang*Matchers*.a")
os.rmfiles(out_lib_dir, "libclang*Rewrite*.a")
os.rmfiles(out_lib_dir, "libclang*StaticAnalyzer*.a")
os.rmfiles(out_lib_dir, "libclang*Tooling*.a")
end
return out
end
function archive_llvm(dir)
execute("7z a " .. dir .. ".7z " .. "./" .. dir .. "/*")
end
if _ACTION == "clone_llvm" then
clone_llvm()
os.exit()
end
if _ACTION == "build_llvm" then
clean_llvm(llvm_build)
build_llvm(llvm_build)
os.exit()
end
if _ACTION == "package_llvm" then
local conf = get_llvm_configuration_name()
local pkg = package_llvm(conf, llvm, llvm_build)
archive_llvm(pkg)
os.exit()
end
if _ACTION == "download_llvm" then
download_llvm()
os.exit()
end
|
Fixed OSX CMake configuration in LLVM build scripts.
|
Fixed OSX CMake configuration in LLVM build scripts.
|
Lua
|
mit
|
zillemarco/CppSharp,mohtamohit/CppSharp,zillemarco/CppSharp,ktopouzi/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,ddobrev/CppSharp,ddobrev/CppSharp,mono/CppSharp,genuinelucifer/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,mono/CppSharp,genuinelucifer/CppSharp,inordertotest/CppSharp,ktopouzi/CppSharp,mono/CppSharp,mohtamohit/CppSharp,ddobrev/CppSharp,genuinelucifer/CppSharp,inordertotest/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,mono/CppSharp,inordertotest/CppSharp,u255436/CppSharp,inordertotest/CppSharp,mono/CppSharp,u255436/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,ktopouzi/CppSharp,mono/CppSharp,zillemarco/CppSharp,u255436/CppSharp,ktopouzi/CppSharp,genuinelucifer/CppSharp,ktopouzi/CppSharp,zillemarco/CppSharp,genuinelucifer/CppSharp,mohtamohit/CppSharp
|
5fec6dbe7bf0d481f924290a6aee35fb23abcd02
|
modules/admin-full/luasrc/model/cbi/admin_system/admin.lua
|
modules/admin-full/luasrc/model/cbi/admin_system/admin.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
m = Map("system", translate("Router Password"),
translate("Changes the administrator password for accessing the device"))
s = m:section(TypedSection, "_dummy", "")
s.addremove = false
s.anonymous = true
pw1 = s:option(Value, "pw1", translate("Password"))
pw1.password = true
pw2 = s:option(Value, "pw2", translate("Confirmation"))
pw2.password = true
function s.cfgsections()
return { "_pass" }
end
function m.on_commit(map)
local v1 = pw1:formvalue("_pass")
local v2 = pw2:formvalue("_pass")
if v1 and v2 and #v1 > 0 and #v2 > 0 then
if v1 == v2 then
if luci.sys.user.setpasswd("root", v1) == 0 then
m.message = translate("Password successfully changed!")
else
m.message = translate("Unknown Error, password not changed!")
end
else
m.message = translate("Given password confirmation did not match, password not changed!")
end
end
end
m2 = Map("dropbear", translate("SSH Access"),
translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server"))
s = m2:section(TypedSection, "dropbear", translate("Dropbear Instance"))
s.anonymous = true
s.addremove = true
ni = s:option(Value, "Interface", translate("Interface"),
translate("Listen only on the given interface or, if unspecified, on all"))
ni.template = "cbi/network_netlist"
ni.nocreate = true
ni.unspecified = true
pt = s:option(Value, "Port", translate("Port"),
translate("Specifies the listening port of this <em>Dropbear</em> instance"))
pt.datatype = "port"
pt.default = 22
pa = s:option(Flag, "PasswordAuth", translate("Password authentication"),
translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication"))
pa.enabled = "on"
pa.disabled = "off"
pa.default = pa.enabled
pa.rmempty = false
ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"),
translate("Allow the <em>root</em> user to login with password"))
ra.enabled = "on"
ra.disabled = "off"
ra.default = ra.enabled
gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"),
translate("Allow remote hosts to connect to local SSH forwarded ports"))
gp.enabled = "on"
gp.disabled = "off"
gp.default = gp.disabled
s2 = m2:section(TypedSection, "_dummy", translate("SSH-Keys"),
translate("Here you can paste public SSH-Keys (one per line) for SSH public-key authentication."))
s2.addremove = false
s2.anonymous = true
s2.template = "cbi/tblsection"
function s2.cfgsections()
return { "_keys" }
end
keys = s2:option(TextValue, "_data", "")
keys.wrap = "off"
keys.rows = 3
keys.rmempty = false
function keys.cfgvalue()
return fs.readfile("/etc/dropbear/authorized_keys") or ""
end
function keys.write(self, section, value)
if value then
fs.writefile("/etc/dropbear/authorized_keys", value:gsub("\r\n", "\n"))
end
end
return m, m2
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
m = Map("system", translate("Router Password"),
translate("Changes the administrator password for accessing the device"))
s = m:section(TypedSection, "_dummy", "")
s.addremove = false
s.anonymous = true
pw1 = s:option(Value, "pw1", translate("Password"))
pw1.password = true
pw2 = s:option(Value, "pw2", translate("Confirmation"))
pw2.password = true
function s.cfgsections()
return { "_pass" }
end
function m.on_commit(map)
local v1 = pw1:formvalue("_pass")
local v2 = pw2:formvalue("_pass")
if v1 and v2 and #v1 > 0 and #v2 > 0 then
if v1 == v2 then
if luci.sys.user.setpasswd("root", v1) == 0 then
m.message = translate("Password successfully changed!")
else
m.message = translate("Unknown Error, password not changed!")
end
else
m.message = translate("Given password confirmation did not match, password not changed!")
end
end
end
if fs.access("/etc/config/dropbear") then
m2 = Map("dropbear", translate("SSH Access"),
translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server"))
s = m2:section(TypedSection, "dropbear", translate("Dropbear Instance"))
s.anonymous = true
s.addremove = true
ni = s:option(Value, "Interface", translate("Interface"),
translate("Listen only on the given interface or, if unspecified, on all"))
ni.template = "cbi/network_netlist"
ni.nocreate = true
ni.unspecified = true
pt = s:option(Value, "Port", translate("Port"),
translate("Specifies the listening port of this <em>Dropbear</em> instance"))
pt.datatype = "port"
pt.default = 22
pa = s:option(Flag, "PasswordAuth", translate("Password authentication"),
translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication"))
pa.enabled = "on"
pa.disabled = "off"
pa.default = pa.enabled
pa.rmempty = false
ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"),
translate("Allow the <em>root</em> user to login with password"))
ra.enabled = "on"
ra.disabled = "off"
ra.default = ra.enabled
gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"),
translate("Allow remote hosts to connect to local SSH forwarded ports"))
gp.enabled = "on"
gp.disabled = "off"
gp.default = gp.disabled
s2 = m2:section(TypedSection, "_dummy", translate("SSH-Keys"),
translate("Here you can paste public SSH-Keys (one per line) for SSH public-key authentication."))
s2.addremove = false
s2.anonymous = true
s2.template = "cbi/tblsection"
function s2.cfgsections()
return { "_keys" }
end
keys = s2:option(TextValue, "_data", "")
keys.wrap = "off"
keys.rows = 3
keys.rmempty = false
function keys.cfgvalue()
return fs.readfile("/etc/dropbear/authorized_keys") or ""
end
function keys.write(self, section, value)
if value then
fs.writefile("/etc/dropbear/authorized_keys", value:gsub("\r\n", "\n"))
end
end
end
return m, m2
|
modules/admin-full: fix System -> Administration menu if dropbear is not installed
|
modules/admin-full: fix System -> Administration menu if dropbear is not installed
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8070 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
saraedum/luci-packages-old,Canaan-Creative/luci,saraedum/luci-packages-old,phi-psi/luci,phi-psi/luci,Flexibity/luci,freifunk-gluon/luci,vhpham80/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,phi-psi/luci,dtaht/cerowrt-luci-3.3,stephank/luci,phi-psi/luci,Canaan-Creative/luci,jschmidlapp/luci,saraedum/luci-packages-old,stephank/luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,gwlim/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,ch3n2k/luci,Flexibity/luci,ch3n2k/luci,stephank/luci,saraedum/luci-packages-old,ch3n2k/luci,eugenesan/openwrt-luci,vhpham80/luci,freifunk-gluon/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,vhpham80/luci,vhpham80/luci,8devices/carambola2-luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,phi-psi/luci,Flexibity/luci,zwhfly/openwrt-luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,stephank/luci,ThingMesh/openwrt-luci,ch3n2k/luci,gwlim/luci,yeewang/openwrt-luci,jschmidlapp/luci,saraedum/luci-packages-old,Canaan-Creative/luci,jschmidlapp/luci,jschmidlapp/luci,saraedum/luci-packages-old,freifunk-gluon/luci,8devices/carambola2-luci,jschmidlapp/luci,stephank/luci,gwlim/luci,yeewang/openwrt-luci,gwlim/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,jschmidlapp/luci,Canaan-Creative/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,Flexibity/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,Flexibity/luci,phi-psi/luci,vhpham80/luci,gwlim/luci,Canaan-Creative/luci,8devices/carambola2-luci,stephank/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,gwlim/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,Flexibity/luci,jschmidlapp/luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,ch3n2k/luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,gwlim/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,yeewang/openwrt-luci,8devices/carambola2-luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci
|
debfd75f3384cac10939c62c2f884ae3c1a8cb4e
|
modules/freifunk/luasrc/model/cbi/freifunk/public_status.lua
|
modules/freifunk/luasrc/model/cbi/freifunk/public_status.lua
|
require "luci.sys"
require "luci.tools.webadmin"
local bit = require "bit"
local uci = luci.model.uci.cursor_state()
local ffzone = luci.tools.webadmin.firewall_find_zone("freifunk")
local ffznet = ffzone and uci:get("firewall", ffzone, "network")
local ffwifs = ffznet and luci.util.split(ffznet, " ") or {}
-- System --
f = SimpleForm("system", "System")
f.submit = false
f.reset = false
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
f:field(DummyValue, "_system", translate("system")).value = system
f:field(DummyValue, "_cpu", translate("m_i_processor")).value = model
local load1, load5, load15 = luci.sys.loadavg()
f:field(DummyValue, "_la", translate("load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
f:field(DummyValue, "_memtotal", translate("m_i_memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
translate("mem_cached") or "",
100 * membuffers / memtotal,
translate("mem_buffered") or "",
100 * memfree / memtotal,
translate("mem_free") or "")
f:field(DummyValue, "_systime", translate("m_i_systemtime")).value =
os.date("%c")
f:field(DummyValue, "_uptime", translate("m_i_uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
-- Wireless --
local wireless = uci:get_all("wireless")
local wifidata = luci.sys.wifi.getiwconfig()
local ifaces = {}
for k, v in pairs(wireless) do
if v[".type"] == "wifi-iface" and (
luci.util.contains(ffwifs, v.device) or
( #ffwifs == 0 and (not v.encryption or v.encryption == "none") ) )
then
table.insert(ifaces, v)
end
end
m = SimpleForm("wireless", "Freifunk WLAN")
m.submit = false
m.reset = false
s = m:section(Table, ifaces, translate("networks"))
link = s:option(DummyValue, "_link", translate("link"))
function link.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return wifidata[ifname] and wifidata[ifname]["Link Quality"] or "-"
end
essid = s:option(DummyValue, "ssid", "ESSID")
bssid = s:option(DummyValue, "_bsiid", "BSSID")
function bssid.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return (wifidata[ifname] and (wifidata[ifname].Cell
or wifidata[ifname]["Access Point"])) or "-"
end
channel = s:option(DummyValue, "channel", translate("channel"))
function channel.cfgvalue(self, section)
return wireless[self.map:get(section, "device")].channel
end
protocol = s:option(DummyValue, "_mode", translate("protocol"))
function protocol.cfgvalue(self, section)
local mode = wireless[self.map:get(section, "device")].mode
return mode and "802." .. mode
end
mode = s:option(DummyValue, "mode", translate("mode"))
encryption = s:option(DummyValue, "encryption", translate("iwscan_encr"))
power = s:option(DummyValue, "_power", translate("power"))
function power.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return wifidata[ifname] and wifidata[ifname]["Tx-Power"] or "-"
end
scan = s:option(Button, "_scan", translate("scan"))
scan.inputstyle = "find"
function scan.cfgvalue(self, section)
return self.map:get(section, "ifname") or false
end
t2 = m:section(Table, {}, translate("iwscan"), translate("iwscan1"))
function scan.write(self, section)
t2.render = t2._render
local ifname = self.map:get(section, "ifname")
luci.util.update(t2.data, luci.sys.wifi.iwscan(ifname))
end
t2._render = t2.render
t2.render = function() end
t2:option(DummyValue, "Quality", translate("iwscan_link"))
essid = t2:option(DummyValue, "ESSID", "ESSID")
function essid.cfgvalue(self, section)
return luci.util.pcdata(self.map:get(section, "ESSID"))
end
t2:option(DummyValue, "Address", "BSSID")
t2:option(DummyValue, "Mode", translate("mode"))
chan = t2:option(DummyValue, "channel", translate("channel"))
function chan.cfgvalue(self, section)
return self.map:get(section, "Channel")
or self.map:get(section, "Frequency")
or "-"
end
t2:option(DummyValue, "Encryption key", translate("iwscan_encr"))
t2:option(DummyValue, "Signal level", translate("iwscan_signal"))
t2:option(DummyValue, "Noise level", translate("iwscan_noise"))
-- Routes --
r = SimpleForm("routes", "Standardrouten")
r.submit = false
r.reset = false
local routes = {}
for i, route in ipairs(luci.sys.net.routes()) do
if route.dest:prefix() == 0 then
routes[#routes+1] = route
end
end
v = r:section(Table, routes)
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].device)
or routes[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes[section].dest:network():string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return routes[section].dest:mask():string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return routes[section].gateway:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return routes[section].metric
end
local routes6 = {}
for i, route in ipairs(luci.sys.net.routes6() or {}) do
if route.dest:prefix() == 0 then
routes6[#routes6+1] = route
end
end
if #routes6 > 0 then
v6 = r:section(Table, routes6)
net = v6:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes6[section].device)
or routes6[section].device
end
target = v6:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes6[section].dest:string()
end
gateway = v6:option(DummyValue, "gateway6", translate("gateway6"))
function gateway.cfgvalue(self, section)
return routes6[section].source:string()
end
metric = v6:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
local metr = routes6[section].metric
local lower = bit.band(metr, 0xffff)
local higher = bit.rshift(bit.band(metr, 0xffff0000), 16)
return "%04X%04X" % {higher, lower}
end
end
return f, m, r
|
require "luci.sys"
require "luci.tools.webadmin"
local bit = require "bit"
local uci = luci.model.uci.cursor_state()
local ffzone = luci.tools.webadmin.firewall_find_zone("freifunk")
local ffznet = ffzone and uci:get("firewall", ffzone, "network")
local ffwifs = ffznet and luci.util.split(ffznet, " ") or {}
-- System --
f = SimpleForm("system", "System")
f.submit = false
f.reset = false
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
f:field(DummyValue, "_system", translate("system")).value = system
f:field(DummyValue, "_cpu", translate("m_i_processor")).value = model
local load1, load5, load15 = luci.sys.loadavg()
f:field(DummyValue, "_la", translate("load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
f:field(DummyValue, "_memtotal", translate("m_i_memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
tostring(translate("mem_cached"), "")),
100 * membuffers / memtotal,
tostring(translate("mem_buffered", "")),
100 * memfree / memtotal,
tostring(translate("mem_free", ""))
f:field(DummyValue, "_systime", translate("m_i_systemtime")).value =
os.date("%c")
f:field(DummyValue, "_uptime", translate("m_i_uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
-- Wireless --
local wireless = uci:get_all("wireless")
local wifidata = luci.sys.wifi.getiwconfig()
local ifaces = {}
for k, v in pairs(wireless) do
if v[".type"] == "wifi-iface" and (
luci.util.contains(ffwifs, v.device) or
( #ffwifs == 0 and (not v.encryption or v.encryption == "none") ) )
then
table.insert(ifaces, v)
end
end
m = SimpleForm("wireless", "Freifunk WLAN")
m.submit = false
m.reset = false
s = m:section(Table, ifaces, translate("networks"))
link = s:option(DummyValue, "_link", translate("link"))
function link.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return wifidata[ifname] and wifidata[ifname]["Link Quality"] or "-"
end
essid = s:option(DummyValue, "ssid", "ESSID")
bssid = s:option(DummyValue, "_bsiid", "BSSID")
function bssid.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return (wifidata[ifname] and (wifidata[ifname].Cell
or wifidata[ifname]["Access Point"])) or "-"
end
channel = s:option(DummyValue, "channel", translate("channel"))
function channel.cfgvalue(self, section)
return wireless[self.map:get(section, "device")].channel
end
protocol = s:option(DummyValue, "_mode", translate("protocol"))
function protocol.cfgvalue(self, section)
local mode = wireless[self.map:get(section, "device")].mode
return mode and "802." .. mode
end
mode = s:option(DummyValue, "mode", translate("mode"))
encryption = s:option(DummyValue, "encryption", translate("iwscan_encr"))
power = s:option(DummyValue, "_power", translate("power"))
function power.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
return wifidata[ifname] and wifidata[ifname]["Tx-Power"] or "-"
end
scan = s:option(Button, "_scan", translate("scan"))
scan.inputstyle = "find"
function scan.cfgvalue(self, section)
return self.map:get(section, "ifname") or false
end
t2 = m:section(Table, {}, translate("iwscan"), translate("iwscan1"))
function scan.write(self, section)
t2.render = t2._render
local ifname = self.map:get(section, "ifname")
luci.util.update(t2.data, luci.sys.wifi.iwscan(ifname))
end
t2._render = t2.render
t2.render = function() end
t2:option(DummyValue, "Quality", translate("iwscan_link"))
essid = t2:option(DummyValue, "ESSID", "ESSID")
function essid.cfgvalue(self, section)
return luci.util.pcdata(self.map:get(section, "ESSID"))
end
t2:option(DummyValue, "Address", "BSSID")
t2:option(DummyValue, "Mode", translate("mode"))
chan = t2:option(DummyValue, "channel", translate("channel"))
function chan.cfgvalue(self, section)
return self.map:get(section, "Channel")
or self.map:get(section, "Frequency")
or "-"
end
t2:option(DummyValue, "Encryption key", translate("iwscan_encr"))
t2:option(DummyValue, "Signal level", translate("iwscan_signal"))
t2:option(DummyValue, "Noise level", translate("iwscan_noise"))
-- Routes --
r = SimpleForm("routes", "Standardrouten")
r.submit = false
r.reset = false
local routes = {}
for i, route in ipairs(luci.sys.net.routes()) do
if route.dest:prefix() == 0 then
routes[#routes+1] = route
end
end
v = r:section(Table, routes)
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].device)
or routes[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes[section].dest:network():string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return routes[section].dest:mask():string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return routes[section].gateway:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return routes[section].metric
end
local routes6 = {}
for i, route in ipairs(luci.sys.net.routes6() or {}) do
if route.dest:prefix() == 0 then
routes6[#routes6+1] = route
end
end
if #routes6 > 0 then
v6 = r:section(Table, routes6)
net = v6:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes6[section].device)
or routes6[section].device
end
target = v6:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes6[section].dest:string()
end
gateway = v6:option(DummyValue, "gateway6", translate("gateway6"))
function gateway.cfgvalue(self, section)
return routes6[section].source:string()
end
metric = v6:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
local metr = routes6[section].metric
local lower = bit.band(metr, 0xffff)
local higher = bit.rshift(bit.band(metr, 0xffff0000), 16)
return "%04X%04X" % {higher, lower}
end
end
return f, m, r
|
modules/freifunk: fix same problem
|
modules/freifunk: fix same problem
|
Lua
|
apache-2.0
|
obsy/luci,remakeelectric/luci,palmettos/cnLuCI,dismantl/luci-0.12,Hostle/openwrt-luci-multi-user,artynet/luci,cshore/luci,Kyklas/luci-proto-hso,palmettos/cnLuCI,oyido/luci,LazyZhu/openwrt-luci-trunk-mod,keyidadi/luci,obsy/luci,lcf258/openwrtcn,dwmw2/luci,marcel-sch/luci,daofeng2015/luci,david-xiao/luci,keyidadi/luci,kuoruan/lede-luci,ReclaimYourPrivacy/cloak-luci,harveyhu2012/luci,david-xiao/luci,david-xiao/luci,marcel-sch/luci,tobiaswaldvogel/luci,sujeet14108/luci,zhaoxx063/luci,chris5560/openwrt-luci,tobiaswaldvogel/luci,MinFu/luci,nmav/luci,Noltari/luci,oyido/luci,db260179/openwrt-bpi-r1-luci,slayerrensky/luci,openwrt/luci,RedSnake64/openwrt-luci-packages,taiha/luci,ollie27/openwrt_luci,daofeng2015/luci,thesabbir/luci,NeoRaider/luci,palmettos/cnLuCI,sujeet14108/luci,jlopenwrtluci/luci,MinFu/luci,ff94315/luci-1,ff94315/luci-1,aa65535/luci,daofeng2015/luci,RedSnake64/openwrt-luci-packages,Wedmer/luci,LuttyYang/luci,bittorf/luci,tcatm/luci,cshore/luci,zhaoxx063/luci,marcel-sch/luci,opentechinstitute/luci,openwrt/luci,cshore/luci,nwf/openwrt-luci,tobiaswaldvogel/luci,joaofvieira/luci,mumuqz/luci,NeoRaider/luci,remakeelectric/luci,LazyZhu/openwrt-luci-trunk-mod,MinFu/luci,daofeng2015/luci,nwf/openwrt-luci,harveyhu2012/luci,thesabbir/luci,db260179/openwrt-bpi-r1-luci,oneru/luci,jlopenwrtluci/luci,thesabbir/luci,nwf/openwrt-luci,forward619/luci,dismantl/luci-0.12,jlopenwrtluci/luci,kuoruan/lede-luci,teslamint/luci,sujeet14108/luci,shangjiyu/luci-with-extra,fkooman/luci,marcel-sch/luci,david-xiao/luci,openwrt-es/openwrt-luci,male-puppies/luci,Hostle/luci,Kyklas/luci-proto-hso,slayerrensky/luci,aircross/OpenWrt-Firefly-LuCI,db260179/openwrt-bpi-r1-luci,nwf/openwrt-luci,Sakura-Winkey/LuCI,taiha/luci,joaofvieira/luci,sujeet14108/luci,obsy/luci,male-puppies/luci,jchuang1977/luci-1,tobiaswaldvogel/luci,forward619/luci,LuttyYang/luci,oyido/luci,chris5560/openwrt-luci,wongsyrone/luci-1,joaofvieira/luci,ollie27/openwrt_luci,zhaoxx063/luci,aircross/OpenWrt-Firefly-LuCI,florian-shellfire/luci,kuoruan/lede-luci,lcf258/openwrtcn,palmettos/cnLuCI,shangjiyu/luci-with-extra,joaofvieira/luci,marcel-sch/luci,nwf/openwrt-luci,maxrio/luci981213,bright-things/ionic-luci,tcatm/luci,zhaoxx063/luci,Wedmer/luci,obsy/luci,male-puppies/luci,kuoruan/luci,ff94315/luci-1,Noltari/luci,bright-things/ionic-luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,jchuang1977/luci-1,urueedi/luci,MinFu/luci,kuoruan/lede-luci,cappiewu/luci,lcf258/openwrtcn,jorgifumi/luci,daofeng2015/luci,lcf258/openwrtcn,RuiChen1113/luci,thess/OpenWrt-luci,RedSnake64/openwrt-luci-packages,MinFu/luci,kuoruan/luci,LazyZhu/openwrt-luci-trunk-mod,Kyklas/luci-proto-hso,jorgifumi/luci,ReclaimYourPrivacy/cloak-luci,david-xiao/luci,jchuang1977/luci-1,jorgifumi/luci,LazyZhu/openwrt-luci-trunk-mod,aircross/OpenWrt-Firefly-LuCI,RedSnake64/openwrt-luci-packages,wongsyrone/luci-1,wongsyrone/luci-1,lbthomsen/openwrt-luci,schidler/ionic-luci,bright-things/ionic-luci,remakeelectric/luci,openwrt/luci,ff94315/luci-1,wongsyrone/luci-1,nmav/luci,Sakura-Winkey/LuCI,dismantl/luci-0.12,LuttyYang/luci,maxrio/luci981213,nwf/openwrt-luci,db260179/openwrt-bpi-r1-luci,LuttyYang/luci,keyidadi/luci,bittorf/luci,Noltari/luci,nmav/luci,taiha/luci,mumuqz/luci,bittorf/luci,obsy/luci,florian-shellfire/luci,palmettos/cnLuCI,nwf/openwrt-luci,opentechinstitute/luci,RuiChen1113/luci,florian-shellfire/luci,tobiaswaldvogel/luci,kuoruan/luci,nmav/luci,lbthomsen/openwrt-luci,RuiChen1113/luci,cshore/luci,thess/OpenWrt-luci,kuoruan/lede-luci,ollie27/openwrt_luci,openwrt/luci,palmettos/test,aircross/OpenWrt-Firefly-LuCI,remakeelectric/luci,mumuqz/luci,RuiChen1113/luci,bittorf/luci,rogerpueyo/luci,florian-shellfire/luci,db260179/openwrt-bpi-r1-luci,ReclaimYourPrivacy/cloak-luci,rogerpueyo/luci,marcel-sch/luci,Wedmer/luci,opentechinstitute/luci,bright-things/ionic-luci,tcatm/luci,hnyman/luci,LuttyYang/luci,Wedmer/luci,remakeelectric/luci,cshore/luci,oyido/luci,thesabbir/luci,thess/OpenWrt-luci,dwmw2/luci,lcf258/openwrtcn,jorgifumi/luci,Noltari/luci,taiha/luci,urueedi/luci,Hostle/luci,MinFu/luci,oneru/luci,taiha/luci,thesabbir/luci,nmav/luci,chris5560/openwrt-luci,zhaoxx063/luci,981213/luci-1,RuiChen1113/luci,oneru/luci,oyido/luci,fkooman/luci,cshore-firmware/openwrt-luci,openwrt-es/openwrt-luci,wongsyrone/luci-1,remakeelectric/luci,fkooman/luci,lbthomsen/openwrt-luci,joaofvieira/luci,tcatm/luci,marcel-sch/luci,thess/OpenWrt-luci,mumuqz/luci,kuoruan/lede-luci,oneru/luci,ollie27/openwrt_luci,jorgifumi/luci,ff94315/luci-1,oneru/luci,oyido/luci,teslamint/luci,jorgifumi/luci,hnyman/luci,jchuang1977/luci-1,dwmw2/luci,chris5560/openwrt-luci,RedSnake64/openwrt-luci-packages,cshore-firmware/openwrt-luci,aa65535/luci,teslamint/luci,bright-things/ionic-luci,rogerpueyo/luci,teslamint/luci,jlopenwrtluci/luci,RedSnake64/openwrt-luci-packages,oyido/luci,aa65535/luci,harveyhu2012/luci,kuoruan/lede-luci,bittorf/luci,hnyman/luci,joaofvieira/luci,deepak78/new-luci,Hostle/openwrt-luci-multi-user,thess/OpenWrt-luci,ollie27/openwrt_luci,RuiChen1113/luci,palmettos/test,ollie27/openwrt_luci,male-puppies/luci,teslamint/luci,Hostle/luci,Hostle/luci,Sakura-Winkey/LuCI,schidler/ionic-luci,dwmw2/luci,harveyhu2012/luci,david-xiao/luci,florian-shellfire/luci,Hostle/openwrt-luci-multi-user,shangjiyu/luci-with-extra,forward619/luci,zhaoxx063/luci,RedSnake64/openwrt-luci-packages,cappiewu/luci,kuoruan/luci,Wedmer/luci,urueedi/luci,mumuqz/luci,sujeet14108/luci,harveyhu2012/luci,Wedmer/luci,opentechinstitute/luci,urueedi/luci,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,981213/luci-1,thesabbir/luci,oneru/luci,jlopenwrtluci/luci,ff94315/luci-1,florian-shellfire/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,deepak78/new-luci,david-xiao/luci,male-puppies/luci,rogerpueyo/luci,thesabbir/luci,dismantl/luci-0.12,slayerrensky/luci,Hostle/openwrt-luci-multi-user,Hostle/openwrt-luci-multi-user,mumuqz/luci,Hostle/openwrt-luci-multi-user,LuttyYang/luci,male-puppies/luci,981213/luci-1,deepak78/new-luci,tcatm/luci,chris5560/openwrt-luci,joaofvieira/luci,daofeng2015/luci,taiha/luci,forward619/luci,artynet/luci,Noltari/luci,tobiaswaldvogel/luci,jlopenwrtluci/luci,NeoRaider/luci,openwrt-es/openwrt-luci,remakeelectric/luci,aa65535/luci,oneru/luci,lbthomsen/openwrt-luci,dwmw2/luci,RuiChen1113/luci,thess/OpenWrt-luci,LuttyYang/luci,cappiewu/luci,slayerrensky/luci,openwrt/luci,chris5560/openwrt-luci,Sakura-Winkey/LuCI,keyidadi/luci,nmav/luci,cshore-firmware/openwrt-luci,MinFu/luci,openwrt/luci,shangjiyu/luci-with-extra,Hostle/luci,ReclaimYourPrivacy/cloak-luci,NeoRaider/luci,wongsyrone/luci-1,palmettos/test,artynet/luci,Noltari/luci,LazyZhu/openwrt-luci-trunk-mod,obsy/luci,nwf/openwrt-luci,aa65535/luci,schidler/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,maxrio/luci981213,wongsyrone/luci-1,daofeng2015/luci,palmettos/test,urueedi/luci,forward619/luci,sujeet14108/luci,bright-things/ionic-luci,NeoRaider/luci,db260179/openwrt-bpi-r1-luci,cshore-firmware/openwrt-luci,NeoRaider/luci,lcf258/openwrtcn,schidler/ionic-luci,Kyklas/luci-proto-hso,palmettos/test,keyidadi/luci,maxrio/luci981213,lcf258/openwrtcn,Hostle/openwrt-luci-multi-user,slayerrensky/luci,kuoruan/luci,981213/luci-1,aa65535/luci,kuoruan/lede-luci,shangjiyu/luci-with-extra,cappiewu/luci,Kyklas/luci-proto-hso,981213/luci-1,obsy/luci,ollie27/openwrt_luci,chris5560/openwrt-luci,zhaoxx063/luci,tcatm/luci,harveyhu2012/luci,LuttyYang/luci,jorgifumi/luci,sujeet14108/luci,lcf258/openwrtcn,deepak78/new-luci,jlopenwrtluci/luci,kuoruan/luci,deepak78/new-luci,cappiewu/luci,palmettos/cnLuCI,rogerpueyo/luci,hnyman/luci,Noltari/luci,daofeng2015/luci,taiha/luci,palmettos/test,aircross/OpenWrt-Firefly-LuCI,Kyklas/luci-proto-hso,wongsyrone/luci-1,aircross/OpenWrt-Firefly-LuCI,NeoRaider/luci,Noltari/luci,ReclaimYourPrivacy/cloak-luci,cshore-firmware/openwrt-luci,Noltari/luci,jchuang1977/luci-1,opentechinstitute/luci,thess/OpenWrt-luci,NeoRaider/luci,bittorf/luci,male-puppies/luci,lbthomsen/openwrt-luci,ff94315/luci-1,cappiewu/luci,slayerrensky/luci,maxrio/luci981213,openwrt-es/openwrt-luci,thess/OpenWrt-luci,maxrio/luci981213,981213/luci-1,dwmw2/luci,shangjiyu/luci-with-extra,aircross/OpenWrt-Firefly-LuCI,Wedmer/luci,aa65535/luci,jchuang1977/luci-1,jchuang1977/luci-1,oneru/luci,hnyman/luci,harveyhu2012/luci,Hostle/openwrt-luci-multi-user,fkooman/luci,Hostle/luci,jlopenwrtluci/luci,ReclaimYourPrivacy/cloak-luci,oyido/luci,keyidadi/luci,jorgifumi/luci,cappiewu/luci,dwmw2/luci,hnyman/luci,schidler/ionic-luci,dismantl/luci-0.12,taiha/luci,joaofvieira/luci,male-puppies/luci,openwrt-es/openwrt-luci,lcf258/openwrtcn,tcatm/luci,forward619/luci,MinFu/luci,forward619/luci,mumuqz/luci,opentechinstitute/luci,remakeelectric/luci,Hostle/luci,schidler/ionic-luci,slayerrensky/luci,maxrio/luci981213,artynet/luci,cshore/luci,nmav/luci,rogerpueyo/luci,ollie27/openwrt_luci,rogerpueyo/luci,Wedmer/luci,teslamint/luci,cshore-firmware/openwrt-luci,opentechinstitute/luci,slayerrensky/luci,Sakura-Winkey/LuCI,mumuqz/luci,artynet/luci,schidler/ionic-luci,ff94315/luci-1,lbthomsen/openwrt-luci,fkooman/luci,db260179/openwrt-bpi-r1-luci,shangjiyu/luci-with-extra,RuiChen1113/luci,maxrio/luci981213,cshore-firmware/openwrt-luci,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,hnyman/luci,openwrt-es/openwrt-luci,chris5560/openwrt-luci,artynet/luci,nmav/luci,cshore/luci,cshore/luci,urueedi/luci,artynet/luci,nmav/luci,Kyklas/luci-proto-hso,palmettos/cnLuCI,forward619/luci,Hostle/luci,obsy/luci,urueedi/luci,kuoruan/luci,fkooman/luci,rogerpueyo/luci,aa65535/luci,openwrt-es/openwrt-luci,palmettos/cnLuCI,bright-things/ionic-luci,deepak78/new-luci,florian-shellfire/luci,openwrt-es/openwrt-luci,florian-shellfire/luci,shangjiyu/luci-with-extra,jchuang1977/luci-1,dwmw2/luci,openwrt/luci,fkooman/luci,sujeet14108/luci,palmettos/test,keyidadi/luci,zhaoxx063/luci,Sakura-Winkey/LuCI,hnyman/luci,cappiewu/luci,opentechinstitute/luci,artynet/luci,palmettos/test,teslamint/luci,lcf258/openwrtcn,lbthomsen/openwrt-luci,kuoruan/luci,fkooman/luci,bittorf/luci,LazyZhu/openwrt-luci-trunk-mod,thesabbir/luci,schidler/ionic-luci,urueedi/luci,dismantl/luci-0.12,marcel-sch/luci,cshore-firmware/openwrt-luci,keyidadi/luci,openwrt/luci,981213/luci-1,teslamint/luci,bright-things/ionic-luci,dismantl/luci-0.12,bittorf/luci,deepak78/new-luci,david-xiao/luci,tcatm/luci,deepak78/new-luci,artynet/luci,LazyZhu/openwrt-luci-trunk-mod
|
2db41115bdeb6151f4882647d0b08971d3d202d4
|
mod_carbons/mod_carbons.lua
|
mod_carbons/mod_carbons.lua
|
-- XEP-0280: Message Carbons implementation for Prosody
-- Copyright (C) 2011 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local xmlns_carbons = "urn:xmpp:carbons:2";
local xmlns_carbons_old = "urn:xmpp:carbons:1";
local xmlns_carbons_really_old = "urn:xmpp:carbons:0";
local xmlns_forward = "urn:xmpp:forward:0";
local full_sessions, bare_sessions = full_sessions, bare_sessions;
local function toggle_carbons(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].name;
module:log("debug", "%s %sd carbons", origin.full_jid, state);
origin.want_carbons = state == "enable" and stanza.tags[1].attr.xmlns;
origin.send(st.reply(stanza));
return true
end
end
module:hook("iq/self/"..xmlns_carbons..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons..":enable", toggle_carbons);
-- COMPAT
module:hook("iq/self/"..xmlns_carbons_old..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons_old..":enable", toggle_carbons);
-- COMPAT :(
if module:get_option_boolean("carbons_v0") then
module:hook("iq/self/"..xmlns_carbons_really_old..":carbons", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].attr.mode;
origin.want_carbons = state == "enable" and xmlns_carbons_really_old;
origin.send(st.reply(stanza));
return true;
end
end);
end
local function message_handler(event, c2s)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_from = stanza.attr.from;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return -- No carbons for messages of type error or headline
end
-- Stanza sent by a local client
local bare_jid = jid_bare(orig_from);
local target_session = origin;
local top_priority = false;
local user_sessions = bare_sessions[bare_jid];
-- Stanza about to be delivered to a local client
if not c2s then
bare_jid = jid_bare(orig_to);
target_session = full_sessions[orig_to];
user_sessions = bare_sessions[bare_jid];
if not target_session and user_sessions then
-- The top resources will already receive this message per normal routing rules,
-- so we are going to skip them in order to avoid sending duplicated messages.
local top_resources = user_sessions.top_resources;
top_priority = top_resources and top_resources[1].priority
end
end
if not user_sessions then
module:log("debug", "Skip carbons for offline user");
return -- No use in sending carbons to an offline user
end
if not c2s and stanza:get_child("private", xmlns_carbons) then
stanza:maptags(function(tag)
return tag.attr.xmlns == xmlns_carbons
and tag.name == "private" and tag or nil;
end);
module:log("debug", "Message tagged private, ignoring");
return
elseif stanza:get_child("no-copy", "urn:xmpp:hints") then
module:log("debug", "Message has no-copy hint, ignoring");
return
end
-- Create the carbon copy and wrap it as per the Stanza Forwarding XEP
local copy = st.clone(stanza);
copy.attr.xmlns = "jabber:client";
local carbon = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons })
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
-- COMPAT
local carbon_old = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_old }):up()
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
-- COMPAT
local carbon_really_old = st.clone(stanza)
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_really_old }):up()
user_sessions = user_sessions and user_sessions.sessions;
for _, session in pairs(user_sessions) do
-- Carbons are sent to resources that have enabled it
if session.want_carbons
-- but not the resource that sent the message, or the one that it's directed to
and session ~= target_session
-- and isn't among the top resources that would receive the message per standard routing rules
and (c2s or session.priority ~= top_priority)
-- don't send v0 carbons (or copies) for c2s
and (not c2s or session.want_carbons ~= xmlns_carbons_really_old) then
carbon.attr.to = session.full_jid;
module:log("debug", "Sending carbon to %s", session.full_jid);
local carbon = session.want_carbons == xmlns_carbons_old and carbon_old -- COMPAT
or session.want_carbons == xmlns_carbons_really_old and carbon_really_old -- COMPAT
or carbon;
session.send(carbon);
end
end
end
local function c2s_message_handler(event)
return message_handler(event, true)
end
-- Stanzas sent by local clients
module:hook("pre-message/host", c2s_message_handler, 1);
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanzas to local clients
module:hook("message/bare", message_handler, 1);
module:hook("message/full", message_handler, 1);
module:add_feature(xmlns_carbons);
module:add_feature(xmlns_carbons_old);
if module:get_option_boolean("carbons_v0") then
module:add_feature(xmlns_carbons_really_old);
end
|
-- XEP-0280: Message Carbons implementation for Prosody
-- Copyright (C) 2011 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local xmlns_carbons = "urn:xmpp:carbons:2";
local xmlns_carbons_old = "urn:xmpp:carbons:1";
local xmlns_carbons_really_old = "urn:xmpp:carbons:0";
local xmlns_forward = "urn:xmpp:forward:0";
local full_sessions, bare_sessions = full_sessions, bare_sessions;
local function toggle_carbons(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].name;
module:log("debug", "%s %sd carbons", origin.full_jid, state);
origin.want_carbons = state == "enable" and stanza.tags[1].attr.xmlns;
origin.send(st.reply(stanza));
return true
end
end
module:hook("iq/self/"..xmlns_carbons..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons..":enable", toggle_carbons);
-- COMPAT
module:hook("iq/self/"..xmlns_carbons_old..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons_old..":enable", toggle_carbons);
-- COMPAT :(
if module:get_option_boolean("carbons_v0") then
module:hook("iq/self/"..xmlns_carbons_really_old..":carbons", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].attr.mode;
origin.want_carbons = state == "enable" and xmlns_carbons_really_old;
origin.send(st.reply(stanza));
return true;
end
end);
end
local function message_handler(event, c2s)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_from = stanza.attr.from;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return -- No carbons for messages of type error or headline
end
-- Stanza sent by a local client
local bare_jid = jid_bare(orig_from);
local target_session = origin;
local top_priority = false;
local user_sessions = bare_sessions[bare_jid];
-- Stanza about to be delivered to a local client
if not c2s then
bare_jid = jid_bare(orig_to);
target_session = full_sessions[orig_to];
user_sessions = bare_sessions[bare_jid];
if not target_session and user_sessions then
-- The top resources will already receive this message per normal routing rules,
-- so we are going to skip them in order to avoid sending duplicated messages.
local top_resources = user_sessions.top_resources;
top_priority = top_resources and top_resources[1].priority
end
end
if not user_sessions then
module:log("debug", "Skip carbons for offline user");
return -- No use in sending carbons to an offline user
end
if not c2s and stanza:get_child("private", xmlns_carbons) then
stanza:maptags(function(tag)
if not ( tag.attr.xmlns == xmlns_carbons and tag.name == "private" ) then
return tag;
end
end);
module:log("debug", "Message tagged private, ignoring");
return
elseif stanza:get_child("no-copy", "urn:xmpp:hints") then
module:log("debug", "Message has no-copy hint, ignoring");
return
end
-- Create the carbon copy and wrap it as per the Stanza Forwarding XEP
local copy = st.clone(stanza);
copy.attr.xmlns = "jabber:client";
local carbon = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons })
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
-- COMPAT
local carbon_old = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_old }):up()
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
-- COMPAT
local carbon_really_old = st.clone(stanza)
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_really_old }):up()
user_sessions = user_sessions and user_sessions.sessions;
for _, session in pairs(user_sessions) do
-- Carbons are sent to resources that have enabled it
if session.want_carbons
-- but not the resource that sent the message, or the one that it's directed to
and session ~= target_session
-- and isn't among the top resources that would receive the message per standard routing rules
and (c2s or session.priority ~= top_priority)
-- don't send v0 carbons (or copies) for c2s
and (not c2s or session.want_carbons ~= xmlns_carbons_really_old) then
carbon.attr.to = session.full_jid;
module:log("debug", "Sending carbon to %s", session.full_jid);
local carbon = session.want_carbons == xmlns_carbons_old and carbon_old -- COMPAT
or session.want_carbons == xmlns_carbons_really_old and carbon_really_old -- COMPAT
or carbon;
session.send(carbon);
end
end
end
local function c2s_message_handler(event)
return message_handler(event, true)
end
-- Stanzas sent by local clients
module:hook("pre-message/host", c2s_message_handler, 1);
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanzas to local clients
module:hook("message/bare", message_handler, 1);
module:hook("message/full", message_handler, 1);
module:add_feature(xmlns_carbons);
module:add_feature(xmlns_carbons_old);
if module:get_option_boolean("carbons_v0") then
module:add_feature(xmlns_carbons_really_old);
end
|
mod_carbons: Fix <private/> handling
|
mod_carbons: Fix <private/> handling
|
Lua
|
mit
|
asdofindia/prosody-modules,BurmistrovJ/prosody-modules,mardraze/prosody-modules,mmusial/prosody-modules,asdofindia/prosody-modules,drdownload/prosody-modules,heysion/prosody-modules,olax/prosody-modules,cryptotoad/prosody-modules,softer/prosody-modules,BurmistrovJ/prosody-modules,Craige/prosody-modules,crunchuser/prosody-modules,asdofindia/prosody-modules,syntafin/prosody-modules,mardraze/prosody-modules,jkprg/prosody-modules,jkprg/prosody-modules,apung/prosody-modules,softer/prosody-modules,dhotson/prosody-modules,mmusial/prosody-modules,iamliqiang/prosody-modules,asdofindia/prosody-modules,mmusial/prosody-modules,olax/prosody-modules,guilhem/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,vfedoroff/prosody-modules,prosody-modules/import,softer/prosody-modules,vince06fr/prosody-modules,amenophis1er/prosody-modules,dhotson/prosody-modules,drdownload/prosody-modules,stephen322/prosody-modules,dhotson/prosody-modules,joewalker/prosody-modules,heysion/prosody-modules,brahmi2/prosody-modules,stephen322/prosody-modules,syntafin/prosody-modules,prosody-modules/import,obelisk21/prosody-modules,BurmistrovJ/prosody-modules,LanceJenkinZA/prosody-modules,Craige/prosody-modules,heysion/prosody-modules,vfedoroff/prosody-modules,1st8/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,syntafin/prosody-modules,obelisk21/prosody-modules,vince06fr/prosody-modules,olax/prosody-modules,stephen322/prosody-modules,NSAKEY/prosody-modules,prosody-modules/import,BurmistrovJ/prosody-modules,iamliqiang/prosody-modules,olax/prosody-modules,dhotson/prosody-modules,joewalker/prosody-modules,guilhem/prosody-modules,obelisk21/prosody-modules,brahmi2/prosody-modules,1st8/prosody-modules,vfedoroff/prosody-modules,mardraze/prosody-modules,Craige/prosody-modules,LanceJenkinZA/prosody-modules,cryptotoad/prosody-modules,NSAKEY/prosody-modules,jkprg/prosody-modules,apung/prosody-modules,jkprg/prosody-modules,brahmi2/prosody-modules,guilhem/prosody-modules,drdownload/prosody-modules,iamliqiang/prosody-modules,drdownload/prosody-modules,LanceJenkinZA/prosody-modules,mardraze/prosody-modules,brahmi2/prosody-modules,either1/prosody-modules,mardraze/prosody-modules,softer/prosody-modules,obelisk21/prosody-modules,apung/prosody-modules,dhotson/prosody-modules,apung/prosody-modules,LanceJenkinZA/prosody-modules,vince06fr/prosody-modules,1st8/prosody-modules,NSAKEY/prosody-modules,amenophis1er/prosody-modules,joewalker/prosody-modules,crunchuser/prosody-modules,syntafin/prosody-modules,either1/prosody-modules,vince06fr/prosody-modules,jkprg/prosody-modules,vince06fr/prosody-modules,vfedoroff/prosody-modules,heysion/prosody-modules,stephen322/prosody-modules,crunchuser/prosody-modules,olax/prosody-modules,LanceJenkinZA/prosody-modules,drdownload/prosody-modules,stephen322/prosody-modules,Craige/prosody-modules,heysion/prosody-modules,cryptotoad/prosody-modules,1st8/prosody-modules,prosody-modules/import,vfedoroff/prosody-modules,joewalker/prosody-modules,cryptotoad/prosody-modules,brahmi2/prosody-modules,crunchuser/prosody-modules,joewalker/prosody-modules,NSAKEY/prosody-modules,obelisk21/prosody-modules,amenophis1er/prosody-modules,NSAKEY/prosody-modules,crunchuser/prosody-modules,BurmistrovJ/prosody-modules,either1/prosody-modules,softer/prosody-modules,apung/prosody-modules,either1/prosody-modules,iamliqiang/prosody-modules,either1/prosody-modules,syntafin/prosody-modules,amenophis1er/prosody-modules,guilhem/prosody-modules,asdofindia/prosody-modules,mmusial/prosody-modules,cryptotoad/prosody-modules,mmusial/prosody-modules,amenophis1er/prosody-modules,prosody-modules/import
|
2e38ebdd5ef132aea47856e19b30eff59f161e7a
|
mod_smacks/mod_smacks.lua
|
mod_smacks/mod_smacks.lua
|
local st = require "util.stanza";
local t_insert, t_remove = table.insert, table.remove;
local tonumber, tostring = tonumber, tostring;
local add_filter = require "util.filters".add_filter;
local xmlns_sm = "urn:xmpp:sm:2";
local sm_attr = { xmlns = xmlns_sm };
local max_unacked_stanzas = 0;
module:add_event_hook("stream-features",
function (session, features)
features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook("s2s-stream-features",
function (data)
data.features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook_stanza(xmlns_sm, "enable",
function (session, stanza)
module:log("debug", "Enabling stream management");
session.smacks = true;
session.handled_stanza_count = 0;
-- Overwrite process_stanza() and send()
local queue, queue_length = {}, 0;
session.outgoing_stanza_queue, session.outgoing_stanza_count = queue, queue_length;
local _send = session.send;
function session.send(stanza)
local attr = stanza.attr;
if attr and not attr.xmlns then -- Stanza in default stream namespace
queue_length = queue_length + 1;
session.outgoing_stanza_count = queue_length;
queue[queue_length] = st.reply(stanza);
end
local ok, err = _send(stanza);
if ok and queue_length > max_unacked_stanzas and not session.awaiting_ack then
session.awaiting_ack = true;
return _send(st.stanza("r", { xmlns = xmlns_sm }));
end
return ok, err;
end
session.handled_stanza_count = 0;
add_filter(session, "stanzas/in", function (stanza)
if not stanza.attr.xmlns then
session.handled_stanza_count = session.handled_stanza_count + 1;
session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count);
end
return stanza;
end);
if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/
_send(st.stanza("enabled", sm_attr));
return true;
end
end, 100);
module:hook_stanza(xmlns_sm, "r", function (origin, stanza)
if not origin.smacks then
module:log("debug", "Received ack request from non-smack-enabled session");
return;
end
module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count);
-- Reply with <a>
origin.send(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) }));
return true;
end);
module:hook_stanza(xmlns_sm, "a", function (origin, stanza)
if not origin.smacks then return; end
origin.awaiting_ack = nil;
-- Remove handled stanzas from outgoing_stanza_queue
local handled_stanza_count = tonumber(stanza.attr.h)+1;
for i=1,handled_stanza_count do
t_remove(origin.outgoing_stanza_queue, 1);
end
return true;
end);
--TODO: Optimise... incoming stanzas should be handled by a per-session
-- function that has a counter as an upvalue (no table indexing for increments,
-- and won't slow non-198 sessions). We can also then remove the .handled flag
-- on stanzas
function handle_unacked_stanzas(session)
local queue = session.outgoing_stanza_queue;
local error_attr = { type = "cancel" };
if #queue > 0 then
session.outgoing_stanza_queue = {};
for i=1,#queue do
local reply = queue[i];
if reply.attr.to ~= session.full_jid then
reply.attr.type = "error";
reply:tag("error", error_attr)
:tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"});
core_process_stanza(session, queue[i]);
end
end
end
end
local _destroy_session = sessionmanager.destroy_session;
function sessionmanager.destroy_session(session, err)
if session.smacks then
local queue = session.outgoing_stanza_queue;
if #queue > 0 then
module:log("warn", "Destroying session with %d unacked stanzas:", #queue);
for i=1,#queue do
module:log("warn", "::%s", tostring(queue[i]));
end
handle_unacked_stanzas(session);
end
end
return _destroy_session(session, err);
end
|
local st = require "util.stanza";
local t_insert, t_remove = table.insert, table.remove;
local math_min = math.min;
local tonumber, tostring = tonumber, tostring;
local add_filter = require "util.filters".add_filter;
local xmlns_sm = "urn:xmpp:sm:2";
local sm_attr = { xmlns = xmlns_sm };
local max_unacked_stanzas = 0;
module:add_event_hook("stream-features",
function (session, features)
features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook("s2s-stream-features",
function (data)
data.features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook_stanza(xmlns_sm, "enable",
function (session, stanza)
module:log("debug", "Enabling stream management");
session.smacks = true;
-- Overwrite process_stanza() and send()
local queue = {};
session.outgoing_stanza_queue = queue;
session.last_acknowledged_stanza = 0;
local _send = session.send;
function session.send(stanza)
local attr = stanza.attr;
if attr and not attr.xmlns then -- Stanza in default stream namespace
queue[#queue+1] = st.reply(stanza);
end
local ok, err = _send(stanza);
if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then
session.awaiting_ack = true;
return _send(st.stanza("r", { xmlns = xmlns_sm }));
end
return ok, err;
end
session.handled_stanza_count = 0;
add_filter(session, "stanzas/in", function (stanza)
if not stanza.attr.xmlns then
session.handled_stanza_count = session.handled_stanza_count + 1;
session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count);
end
return stanza;
end);
if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/
_send(st.stanza("enabled", sm_attr));
return true;
end
end, 100);
module:hook_stanza(xmlns_sm, "r", function (origin, stanza)
if not origin.smacks then
module:log("debug", "Received ack request from non-smack-enabled session");
return;
end
module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count);
-- Reply with <a>
origin.send(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) }));
return true;
end);
module:hook_stanza(xmlns_sm, "a", function (origin, stanza)
if not origin.smacks then return; end
origin.awaiting_ack = nil;
-- Remove handled stanzas from outgoing_stanza_queue
local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza;
local queue = origin.outgoing_stanza_queue;
if handled_stanza_count > #queue then
module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)",
handled_stanza_count, #queue);
for i=1,#queue do
module:log("debug", "Q item %d: %s", i, tostring(queue[i]));
end
end
for i=1,math_min(handled_stanza_count,#queue) do
t_remove(origin.outgoing_stanza_queue, 1);
end
origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count;
return true;
end);
--TODO: Optimise... incoming stanzas should be handled by a per-session
-- function that has a counter as an upvalue (no table indexing for increments,
-- and won't slow non-198 sessions). We can also then remove the .handled flag
-- on stanzas
function handle_unacked_stanzas(session)
local queue = session.outgoing_stanza_queue;
local error_attr = { type = "cancel" };
if #queue > 0 then
session.outgoing_stanza_queue = {};
for i=1,#queue do
local reply = queue[i];
if reply.attr.to ~= session.full_jid then
reply.attr.type = "error";
reply:tag("error", error_attr)
:tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"});
core_process_stanza(session, queue[i]);
end
end
end
end
local _destroy_session = sessionmanager.destroy_session;
function sessionmanager.destroy_session(session, err)
if session.smacks then
local queue = session.outgoing_stanza_queue;
if #queue > 0 then
module:log("warn", "Destroying session with %d unacked stanzas:", #queue);
for i=1,#queue do
module:log("warn", "::%s", tostring(queue[i]));
end
handle_unacked_stanzas(session);
end
end
return _destroy_session(session, err);
end
|
mod_smacks: Fix the logic for handling outgoing stanzas and ack requests
|
mod_smacks: Fix the logic for handling outgoing stanzas and ack requests
|
Lua
|
mit
|
dhotson/prosody-modules,crunchuser/prosody-modules,drdownload/prosody-modules,jkprg/prosody-modules,mmusial/prosody-modules,jkprg/prosody-modules,amenophis1er/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,olax/prosody-modules,mmusial/prosody-modules,1st8/prosody-modules,jkprg/prosody-modules,cryptotoad/prosody-modules,BurmistrovJ/prosody-modules,LanceJenkinZA/prosody-modules,crunchuser/prosody-modules,1st8/prosody-modules,NSAKEY/prosody-modules,jkprg/prosody-modules,apung/prosody-modules,mmusial/prosody-modules,dhotson/prosody-modules,drdownload/prosody-modules,brahmi2/prosody-modules,mardraze/prosody-modules,amenophis1er/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,syntafin/prosody-modules,softer/prosody-modules,guilhem/prosody-modules,crunchuser/prosody-modules,olax/prosody-modules,heysion/prosody-modules,crunchuser/prosody-modules,vfedoroff/prosody-modules,amenophis1er/prosody-modules,heysion/prosody-modules,dhotson/prosody-modules,NSAKEY/prosody-modules,apung/prosody-modules,amenophis1er/prosody-modules,asdofindia/prosody-modules,obelisk21/prosody-modules,syntafin/prosody-modules,Craige/prosody-modules,mardraze/prosody-modules,BurmistrovJ/prosody-modules,LanceJenkinZA/prosody-modules,either1/prosody-modules,cryptotoad/prosody-modules,either1/prosody-modules,either1/prosody-modules,iamliqiang/prosody-modules,syntafin/prosody-modules,either1/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,stephen322/prosody-modules,apung/prosody-modules,brahmi2/prosody-modules,NSAKEY/prosody-modules,softer/prosody-modules,drdownload/prosody-modules,joewalker/prosody-modules,stephen322/prosody-modules,syntafin/prosody-modules,dhotson/prosody-modules,asdofindia/prosody-modules,stephen322/prosody-modules,drdownload/prosody-modules,LanceJenkinZA/prosody-modules,olax/prosody-modules,brahmi2/prosody-modules,olax/prosody-modules,Craige/prosody-modules,asdofindia/prosody-modules,amenophis1er/prosody-modules,obelisk21/prosody-modules,brahmi2/prosody-modules,softer/prosody-modules,asdofindia/prosody-modules,NSAKEY/prosody-modules,guilhem/prosody-modules,either1/prosody-modules,guilhem/prosody-modules,1st8/prosody-modules,softer/prosody-modules,vince06fr/prosody-modules,prosody-modules/import,BurmistrovJ/prosody-modules,dhotson/prosody-modules,mmusial/prosody-modules,joewalker/prosody-modules,cryptotoad/prosody-modules,mardraze/prosody-modules,guilhem/prosody-modules,vince06fr/prosody-modules,heysion/prosody-modules,cryptotoad/prosody-modules,Craige/prosody-modules,Craige/prosody-modules,heysion/prosody-modules,jkprg/prosody-modules,vfedoroff/prosody-modules,vfedoroff/prosody-modules,mardraze/prosody-modules,1st8/prosody-modules,BurmistrovJ/prosody-modules,brahmi2/prosody-modules,stephen322/prosody-modules,joewalker/prosody-modules,NSAKEY/prosody-modules,joewalker/prosody-modules,LanceJenkinZA/prosody-modules,iamliqiang/prosody-modules,vfedoroff/prosody-modules,BurmistrovJ/prosody-modules,iamliqiang/prosody-modules,olax/prosody-modules,iamliqiang/prosody-modules,cryptotoad/prosody-modules,joewalker/prosody-modules,drdownload/prosody-modules,vince06fr/prosody-modules,iamliqiang/prosody-modules,heysion/prosody-modules,vince06fr/prosody-modules,vfedoroff/prosody-modules,mardraze/prosody-modules,1st8/prosody-modules,prosody-modules/import,obelisk21/prosody-modules,stephen322/prosody-modules,vince06fr/prosody-modules,prosody-modules/import,softer/prosody-modules,LanceJenkinZA/prosody-modules,mmusial/prosody-modules,syntafin/prosody-modules,prosody-modules/import,prosody-modules/import,asdofindia/prosody-modules,crunchuser/prosody-modules
|
b29796e6828c3ef7d8e93f8f977f114f42ab5c2f
|
modules/outfit/outfit.lua
|
modules/outfit/outfit.lua
|
Outfit = {}
-- private variables
local window = nil
local m_creature = nil
local m_outfit = nil
local m_outfits = nil
local m_currentOutfit = 1
local m_currentColor = nil
-- private functions
local function onAddonCheckChange(addon, value)
if addon:isChecked() then
m_outfit.addons = m_outfit.addons + value
else
m_outfit.addons = m_outfit.addons - value
end
m_creature:setOutfit(m_outfit)
end
local function update()
local nameWidget = window:getChildById('name')
nameWidget:setText(m_outfits[currentOutfit][2])
local availableAddons = m_outfits[currentOutfit][3]
local addon1 = window:getChildById('addon1')
local addon2 = window:getChildById('addon2')
local addon3 = window:getChildById('addon3')
addon1.onCheckChange = function() onAddonCheckChange(addon1, 1) end
addon2.onCheckChange = function() onAddonCheckChange(addon2, 2) end
addon3.onCheckChange = function() onAddonCheckChange(addon3, 4) end
addon1:setChecked(false)
addon2:setChecked(false)
addon3:setChecked(false)
addon1:setEnabled(false)
addon2:setEnabled(false)
addon3:setEnabled(false)
-- Maybe rework this someday
if availableAddons == 1 then
addon1:setEnabled(true)
elseif availableAddons == 2 then
addon2:setEnabled(true)
elseif availableAddons == 3 then
addon1:setEnabled(true)
addon2:setEnabled(true)
elseif availableAddons == 4 then
addon3:setEnabled(true)
elseif availableAddons == 5 then
addon1:setEnabled(true)
addon3:setEnabled(true)
elseif availableAddons == 6 then
addon2:setEnabled(true)
addon3:setEnabled(true)
elseif availableAddons == 7 then
addon1:setEnabled(true)
addon2:setEnabled(true)
addon3:setEnabled(true)
end
m_outfit.type = m_outfits[currentOutfit][1]
m_outfit.addons = 0
m_creature:setOutfit(m_outfit)
end
local function onColorCheckChange(color)
if color == m_currentColor then
color.onCheckChange = nil
color:setChecked(true)
color.onCheckChange = function() onColorCheckChange(color) end
else
m_currentColor.onCheckChange = nil
m_currentColor:setChecked(false)
local color2 = m_currentColor
m_currentColor.onCheckChange = function() onColorCheckChange(color2) end
m_currentColor = color
m_outfit.head = m_currentColor.colorId
m_creature:setOutfit(m_outfit)
end
end
-- public functions
function Outfit.test()
local button = UIButton.create()
UI.root:addChild(button)
button:setText('Set Outfit')
button:setStyle('Button')
button:moveTo({x = 0, y = 100})
button:setWidth('100')
button:setHeight('30')
button.onClick = function() Game.openOutfitWindow() end
end
function Outfit.create(creature, outfitList)
Outfit.destroy()
window = loadUI("/outfit/outfit.otui", UI.root)
window:lock()
m_outfit = creature:getOutfit()
local creatureWidget = window:getChildById('creature')
creatureWidget:setCreature(creature)
for i=0,18 do
for j=0,6 do
local color = UICheckBox.create()
window:addChild(color)
local outfitColor = getOufitColor(j*19 + i)
color.colorId = j*19 + i
color:setStyle('Color')
color:setBackgroundColor(outfitColor)
color:setMarginTop(j * 3 + j * 14)
color:setMarginLeft(10 + i * 3 + i * 14)
if j*19 + i == m_outfit.head then
m_currentColor = color
color:setChecked(true)
end
color.onCheckChange = function() onColorCheckChange(color) end
end
end
m_creature = creature
m_outfits = outfitList
currentOutfit = 1
update()
end
function Outfit.destroy()
if window ~= nil then
window:destroy()
window = nil
end
end
function Outfit.accept()
Game.setOutfit(m_outfit)
Outfit.destroy()
end
function Outfit.nextType()
currentOutfit = currentOutfit + 1
if currentOutfit > #m_outfits then
currentOutfit = 1
end
update()
end
function Outfit.previousType()
currentOutfit = currentOutfit - 1
if currentOutfit <= 0 then
currentOutfit = #m_outfits
end
update()
end
-- hooked events
connect(Game, { onOpenOutfitWindow = Outfit.create,
onLogout = Outfit.destroy })
connect(Game, { onLogin = Outfit.test })
|
Outfit = {}
-- private variables
local window = nil
local m_creature = nil
local m_outfit = nil
local m_outfits = nil
local m_currentOutfit = 1
local m_currentColor = nil
-- private functions
local function onAddonCheckChange(addon, value)
if addon:isChecked() then
m_outfit.addons = m_outfit.addons + value
else
m_outfit.addons = m_outfit.addons - value
end
m_creature:setOutfit(m_outfit)
end
local function update()
local nameWidget = window:getChildById('name')
nameWidget:setText(m_outfits[currentOutfit][2])
local availableAddons = m_outfits[currentOutfit][3]
local addon1 = window:getChildById('addon1')
local addon2 = window:getChildById('addon2')
local addon3 = window:getChildById('addon3')
addon1.onCheckChange = function() onAddonCheckChange(addon1, 1) end
addon2.onCheckChange = function() onAddonCheckChange(addon2, 2) end
addon3.onCheckChange = function() onAddonCheckChange(addon3, 4) end
addon1:setChecked(false)
addon2:setChecked(false)
addon3:setChecked(false)
addon1:setEnabled(false)
addon2:setEnabled(false)
addon3:setEnabled(false)
-- Maybe rework this someday
if availableAddons == 1 then
addon1:setEnabled(true)
elseif availableAddons == 2 then
addon2:setEnabled(true)
elseif availableAddons == 3 then
addon1:setEnabled(true)
addon2:setEnabled(true)
elseif availableAddons == 4 then
addon3:setEnabled(true)
elseif availableAddons == 5 then
addon1:setEnabled(true)
addon3:setEnabled(true)
elseif availableAddons == 6 then
addon2:setEnabled(true)
addon3:setEnabled(true)
elseif availableAddons == 7 then
addon1:setEnabled(true)
addon2:setEnabled(true)
addon3:setEnabled(true)
end
m_outfit.type = m_outfits[currentOutfit][1]
m_outfit.addons = 0
m_creature:setOutfit(m_outfit)
end
local function onColorCheckChange(color)
if color == m_currentColor then
color.onCheckChange = nil
color:setChecked(true)
color.onCheckChange = function() onColorCheckChange(color) end
else
m_currentColor.onCheckChange = nil
m_currentColor:setChecked(false)
local color2 = m_currentColor
m_currentColor.onCheckChange = function() onColorCheckChange(color2) end
m_currentColor = color
m_outfit.head = m_currentColor.colorId
m_creature:setOutfit(m_outfit)
end
end
-- public functions
function Outfit.test()
local button = UIButton.create()
UI.root:addChild(button)
button:setText('Set Outfit')
button:setStyle('Button')
button:moveTo({x = 0, y = 100})
button:setWidth('100')
button:setHeight('30')
button.onClick = function() Game.openOutfitWindow() end
end
function Outfit.create(creature, outfitList)
Outfit.destroy()
window = loadUI("/outfit/outfit.otui", UI.root)
window:lock()
m_outfit = creature:getOutfit()
local creatureWidget = window:getChildById('creature')
creatureWidget:setCreature(creature)
for i=0,18 do
for j=0,6 do
local color = UICheckBox.create()
window:addChild(color)
local outfitColor = getOufitColor(j*19 + i)
color.colorId = j*19 + i
color:setStyle('Color')
color:setBackgroundColor(outfitColor)
color:setMarginTop(j * 3 + j * 14)
color:setMarginLeft(10 + i * 3 + i * 14)
if j*19 + i == m_outfit.head then
m_currentColor = color
color:setChecked(true)
end
color.onCheckChange = function() onColorCheckChange(color) end
end
end
m_creature = creature
m_outfits = outfitList
currentOutfit = 1
for i=1,#outfitList do
if outfitList[i][1] == m_outfit.type then
currentOutfit = i
break
end
end
update()
end
function Outfit.destroy()
if window ~= nil then
window:destroy()
window = nil
end
end
function Outfit.accept()
Game.setOutfit(m_outfit)
Outfit.destroy()
end
function Outfit.nextType()
currentOutfit = currentOutfit + 1
if currentOutfit > #m_outfits then
currentOutfit = 1
end
update()
end
function Outfit.previousType()
currentOutfit = currentOutfit - 1
if currentOutfit <= 0 then
currentOutfit = #m_outfits
end
update()
end
-- hooked events
connect(Game, { onOpenOutfitWindow = Outfit.create,
onLogout = Outfit.destroy })
connect(Game, { onLogin = Outfit.test })
|
outfit fix
|
outfit fix
|
Lua
|
mit
|
gpedro/otclient,Cavitt/otclient_mapgen,Radseq/otclient,dreamsxin/otclient,gpedro/otclient,EvilHero90/otclient,kwketh/otclient,dreamsxin/otclient,gpedro/otclient,EvilHero90/otclient,Cavitt/otclient_mapgen,kwketh/otclient,Radseq/otclient,dreamsxin/otclient
|
5f2d2e3c356c379acdbfc8da7bf36384421aad79
|
packages/rotate.lua
|
packages/rotate.lua
|
local pdf = require("justenoughlibtexpdf")
local enter = function(self)
if not self.rotate then return end
local x = -math.rad(self.rotate)
-- Keep center point the same
pdf:gsave()
local cx = self:left()
local cy = -self:bottom()
pdf.setmatrix(1,0,0,1,cx + math.sin(x) * self:height(),cy)
pdf.setmatrix(math.cos(x), math.sin(x), -math.sin(x), math.cos(x), 0, 0)
pdf.setmatrix(1,0,0,1,-cx,-cy)
end
local leave = function(self)
if not self.rotate then return end
pdf:grestore()
end
if SILE.typesetter.frame then
enter(SILE.typesetter.frame)
table.insert(SILE.typesetter.frame.leaveHooks, leave)
end
table.insert(SILE.framePrototype.enterHooks, enter)
table.insert(SILE.framePrototype.leaveHooks, leave)
-- What is the width, depth and height of a rectangle width w and height h rotated by angle theta?
-- rect1 = Rectangle[{0, 0}, {w, h}]
-- {{xmin, xmax}, {ymin, ymax}} = Refine[RegionBounds[TransformedRegion[rect1,
-- RotationTransform[theta, {w/2,h/2}]]],
-- w > 0 && h > 0 && theta > 0 && theta < 2 Pi ]
-- PiecewiseExpand[xmax - xmin]
-- \[Piecewise] -w Cos[theta]-h Sin[theta] Sin[theta]<=0&&Cos[theta]<=0
-- w Cos[theta]-h Sin[theta] Sin[theta]<=0&&Cos[theta]>0
-- -w Cos[theta]+h Sin[theta] Sin[theta]>0&&Cos[theta]<=0
-- w Cos[theta]+h Sin[theta] True
local outputRotatedHbox = function (self, typesetter, line)
local origbox = self.value.orig
local x = self.value.theta
-- Find origin of untransformed hbox
local save = typesetter.frame.state.cursorX
typesetter.frame.state.cursorX = typesetter.frame.state.cursorX - (origbox.width.length-self.width)/2
local horigin = (typesetter.frame.state.cursorX + origbox.width.length / 2):tonumber()
local vorigin = -(typesetter.frame.state.cursorY + origbox.height / 2):tonumber()
pdf:gsave()
pdf.setmatrix(1, 0, 0, 1, horigin, vorigin)
pdf.setmatrix(math.cos(x), math.sin(x), -math.sin(x), math.cos(x), 0, 0)
pdf.setmatrix(1, 0, 0, 1, -horigin, -vorigin)
origbox:outputYourself(typesetter, line)
pdf:grestore()
typesetter.frame.state.cursorX = save
typesetter.frame:advanceWritingDirection(self.width)
end
SILE.registerCommand("rotate", function(options, content)
local angle = SU.required(options, "angle", "rotate command")
local theta = -math.rad(angle)
local origbox = SILE.call("hbox", {}, content)
SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] = nil
local h = origbox.height + origbox.depth
local w = origbox.width.length
local st = math.sin(theta)
local ct = math.cos(theta)
local height, width, depth
if st <= 0 and ct <= 0 then
width = -w * ct - h * st
height = 0.5*(h-h*ct-w*st)
depth = 0.5*(h+h*ct+w*st)
elseif st <=0 and ct > 0 then
width = w * ct - h * st
height = 0.5*(h+h*ct-w*st)
depth = 0.5*(h-h*ct+w*st)
elseif st > 0 and ct <= 0 then
width = -w * ct + h * st
height = 0.5*(h-h*ct+w*st)
depth = 0.5*(h+h*ct-w*st)
else
width = w * ct + h * st
height = 0.5*(h+h*ct+w*st)
depth = 0.5*(h-h*ct-w*st)
end
depth = -depth
if depth < 0 then depth = 0 end
SILE.typesetter:pushHbox({
value = { orig = origbox, theta = theta},
height = height,
width = width,
depth = depth,
outputYourself= outputRotatedHbox
})
end)
return { documentation = [[\begin{document}
The \code{rotate} package allows you to rotate things. You can rotate entire
frames, by adding the \code{rotate=<angle>} declaration to your frame declaration,
and you can rotate any content by issuing the command \code{\\rotate[angle=<angle>]\{...\}},
where \code{<angle>} is measured in degrees.
Content which is rotated is placed in a box and rotated. The height and width of
the rotated box is measured, and then put into the normal horizontal list for
typesetting. The effect of this is that space is reserved around the rotated content.
The best way to understand this is by example: here is some text rotated by
\rotate[angle=10]{ten}, \rotate[angle=20]{twenty} and \rotate[angle=40]{forty} degrees.
The previous line was produced by the following code:
\begin{verbatim}
\line
here is some text rotated by
\\rotate[angle=10]\{ten\}, \\rotate[angle=20]\{twenty\} and \\rotate[angle=40]\{forty\} degrees.
\line
\end{verbatim}
\end{document}]] }
|
local pdf = require("justenoughlibtexpdf")
local enter = function (self)
if not self.rotate then return end
local x = -math.rad(self.rotate)
-- Keep center point the same
pdf:gsave()
local cx = self:left():tonumber()
local cy = -self:bottom():tonumber()
pdf.setmatrix(1, 0, 0, 1, cx + math.sin(x) * self:height():tonumber(), cy)
pdf.setmatrix(math.cos(x), math.sin(x), -math.sin(x), math.cos(x), 0, 0)
pdf.setmatrix(1, 0, 0, 1, -cx, -cy)
end
local leave = function(self)
if not self.rotate then return end
pdf:grestore()
end
if SILE.typesetter.frame then
enter(SILE.typesetter.frame)
table.insert(SILE.typesetter.frame.leaveHooks, leave)
end
table.insert(SILE.framePrototype.enterHooks, enter)
table.insert(SILE.framePrototype.leaveHooks, leave)
-- What is the width, depth and height of a rectangle width w and height h rotated by angle theta?
-- rect1 = Rectangle[{0, 0}, {w, h}]
-- {{xmin, xmax}, {ymin, ymax}} = Refine[RegionBounds[TransformedRegion[rect1,
-- RotationTransform[theta, {w/2,h/2}]]],
-- w > 0 && h > 0 && theta > 0 && theta < 2 Pi ]
-- PiecewiseExpand[xmax - xmin]
-- \[Piecewise] -w Cos[theta]-h Sin[theta] Sin[theta]<=0&&Cos[theta]<=0
-- w Cos[theta]-h Sin[theta] Sin[theta]<=0&&Cos[theta]>0
-- -w Cos[theta]+h Sin[theta] Sin[theta]>0&&Cos[theta]<=0
-- w Cos[theta]+h Sin[theta] True
local outputRotatedHbox = function (self, typesetter, line)
local origbox = self.value.orig
local x = self.value.theta
-- Find origin of untransformed hbox
local save = typesetter.frame.state.cursorX
typesetter.frame.state.cursorX = typesetter.frame.state.cursorX - (origbox.width.length-self.width)/2
local horigin = (typesetter.frame.state.cursorX + origbox.width.length / 2):tonumber()
local vorigin = -(typesetter.frame.state.cursorY + origbox.height / 2):tonumber()
pdf:gsave()
pdf.setmatrix(1, 0, 0, 1, horigin, vorigin)
pdf.setmatrix(math.cos(x), math.sin(x), -math.sin(x), math.cos(x), 0, 0)
pdf.setmatrix(1, 0, 0, 1, -horigin, -vorigin)
origbox:outputYourself(typesetter, line)
pdf:grestore()
typesetter.frame.state.cursorX = save
typesetter.frame:advanceWritingDirection(self.width)
end
SILE.registerCommand("rotate", function(options, content)
local angle = SU.required(options, "angle", "rotate command")
local theta = -math.rad(angle)
local origbox = SILE.call("hbox", {}, content)
SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] = nil
local h = origbox.height + origbox.depth
local w = origbox.width.length
local st = math.sin(theta)
local ct = math.cos(theta)
local height, width, depth
if st <= 0 and ct <= 0 then
width = -w * ct - h * st
height = 0.5*(h-h*ct-w*st)
depth = 0.5*(h+h*ct+w*st)
elseif st <=0 and ct > 0 then
width = w * ct - h * st
height = 0.5*(h+h*ct-w*st)
depth = 0.5*(h-h*ct+w*st)
elseif st > 0 and ct <= 0 then
width = -w * ct + h * st
height = 0.5*(h-h*ct+w*st)
depth = 0.5*(h+h*ct-w*st)
else
width = w * ct + h * st
height = 0.5*(h+h*ct+w*st)
depth = 0.5*(h-h*ct-w*st)
end
depth = -depth
if depth < 0 then depth = 0 end
SILE.typesetter:pushHbox({
value = { orig = origbox, theta = theta},
height = height,
width = width,
depth = depth,
outputYourself= outputRotatedHbox
})
end)
return { documentation = [[\begin{document}
The \code{rotate} package allows you to rotate things. You can rotate entire
frames, by adding the \code{rotate=<angle>} declaration to your frame declaration,
and you can rotate any content by issuing the command \code{\\rotate[angle=<angle>]\{...\}},
where \code{<angle>} is measured in degrees.
Content which is rotated is placed in a box and rotated. The height and width of
the rotated box is measured, and then put into the normal horizontal list for
typesetting. The effect of this is that space is reserved around the rotated content.
The best way to understand this is by example: here is some text rotated by
\rotate[angle=10]{ten}, \rotate[angle=20]{twenty} and \rotate[angle=40]{forty} degrees.
The previous line was produced by the following code:
\begin{verbatim}
\line
here is some text rotated by
\\rotate[angle=10]\{ten\}, \\rotate[angle=20]\{twenty\} and \\rotate[angle=40]\{forty\} degrees.
\line
\end{verbatim}
\end{document}]] }
|
fix(packages): Cast measurements to numbers before use in PDF functions
|
fix(packages): Cast measurements to numbers before use in PDF functions
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
ddeb09c0f1027f93161087839ff8afc8ca0650ac
|
src/luacheck/utils.lua
|
src/luacheck/utils.lua
|
local utils = {}
local lfs = require "lfs"
-- Returns whether path points to a directory.
function utils.is_dir(path)
return lfs.attributes(path, "mode") == "directory"
end
-- Returns whether path points to a file.
function utils.is_file(path)
return lfs.attributes(path, "mode") == "file"
end
local dir_sep = package.config:sub(1,1)
-- Returns list of all files in directory matching pattern.
function utils.extract_files(dir_path, pattern)
local res = {}
local function scan(dir_path)
for path in lfs.dir(dir_path) do
if path ~= "." and path ~= ".." then
local full_path = dir_path .. dir_sep .. path
if utils.is_dir(full_path) then
scan(full_path)
elseif path:match(pattern) and utils.is_file(full_path) then
table.insert(res, full_path)
end
end
end
end
scan(dir_path)
table.sort(res)
return res
end
-- Returns all contents of file(path or file handler) or nil.
function utils.read_file(file)
local res
return pcall(function()
local handler = type(file) == "string" and io.open(file, "rb") or file
res = assert(handler:read("*a"))
handler:close()
end) and res or nil
end
-- Parses rockspec-like source, returns data or nil.
local function capture_env(src, env)
env = env or {}
local func
if _VERSION:find "5.2" then
func = load(src, nil, "t", env)
else
func = loadstring(src)
if func then
setfenv(func, env)
end
end
return func and pcall(func) and env
end
-- Loads config containing assignments to global variables from path.
-- Returns config table or nil and error message("I/O" or "syntax").
function utils.load_config(path, env)
local src = utils.read_file(path)
if not src then
return nil, "I/O"
end
local cfg = capture_env(src, env)
if not cfg then
return nil, "syntax"
end
return cfg
end
function utils.array_to_set(array)
local set = {}
for _, item in ipairs(array) do
set[item] = true
end
return set
end
function utils.concat_arrays(array)
local res = {}
for _, subarray in ipairs(array) do
for _, item in ipairs(subarray) do
table.insert(res, item)
end
end
return res
end
return utils
|
local utils = {}
local lfs = require "lfs"
-- Returns whether path points to a directory.
function utils.is_dir(path)
return lfs.attributes(path, "mode") == "directory"
end
-- Returns whether path points to a file.
function utils.is_file(path)
return lfs.attributes(path, "mode") == "file"
end
local dir_sep = package.config:sub(1,1)
-- Returns list of all files in directory matching pattern.
function utils.extract_files(dir_path, pattern)
local res = {}
local function scan(dir_path)
for path in lfs.dir(dir_path) do
if path ~= "." and path ~= ".." then
local full_path = dir_path .. dir_sep .. path
if utils.is_dir(full_path) then
scan(full_path)
elseif path:match(pattern) and utils.is_file(full_path) then
table.insert(res, full_path)
end
end
end
end
scan(dir_path)
table.sort(res)
return res
end
-- Returns all contents of file(path or file handler) or nil.
function utils.read_file(file)
local res
return pcall(function()
local handler = type(file) == "string" and io.open(file, "rb") or file
res = assert(handler:read("*a"))
handler:close()
end) and res or nil
end
-- Parses rockspec-like source, returns data or nil.
local function capture_env(src, env)
env = env or {}
local func
if _VERSION:find "5.1" then
func = loadstring(src)
if func then
setfenv(func, env)
end
else
func = load(src, nil, "t", env)
end
return func and pcall(func) and env
end
-- Loads config containing assignments to global variables from path.
-- Returns config table or nil and error message("I/O" or "syntax").
function utils.load_config(path, env)
local src = utils.read_file(path)
if not src then
return nil, "I/O"
end
local cfg = capture_env(src, env)
if not cfg then
return nil, "syntax"
end
return cfg
end
function utils.array_to_set(array)
local set = {}
for _, item in ipairs(array) do
set[item] = true
end
return set
end
function utils.concat_arrays(array)
local res = {}
for _, subarray in ipairs(array) do
for _, item in ipairs(subarray) do
table.insert(res, item)
end
end
return res
end
return utils
|
Fixed incompatibility with Lua 5.3
|
Fixed incompatibility with Lua 5.3
Now the only thing stopping luacheck running unpatched on 5.3 is lfs.
|
Lua
|
mit
|
mpeterv/luacheck,kidaa/luacheck,linuxmaniac/luacheck,mpeterv/luacheck,xpol/luacheck,xpol/luacheck,linuxmaniac/luacheck,adan830/luacheck,xpol/luacheck,mpeterv/luacheck,adan830/luacheck,tst2005/luacheck,tst2005/luacheck,kidaa/luacheck
|
f4eddbd772245842a4eab337a078c897efdfbde5
|
icesl-gallery/involute.lua
|
icesl-gallery/involute.lua
|
-- emit the inside of the involute of the circle of radius r for the first two quadrants
local r = 5
local h = 3
involute_of_circle = implicit_solid(v(-6*r,0,0), v(2*r,4*r,h), 0.25,
[[
uniform float r = 5;
float solid(vec3 p) {
float l = length(p.xy) - r;
if (l <= 0) {
return l;
}
float num = p.y + sqrt(p.x * p.x + p.y * p.y - r * r);
float denom = r + p.x;
float theta = 2 * atan(num, denom);
vec2 c = vec2(r * cos(theta), r * sin(theta));
float s = r * theta;
float sp = length(p.xy - c);
return sp - s;
}
]])
set_uniform_scalar(involute_of_circle, 'r', r)
emit(involute_of_circle,2)
emit(cylinder(r,h),1)
|
-- emit the inside of the involute of the circle of radius r for the first two quadrants
local r = 20
local h = 3
involute_of_circle = implicit_solid(v(-6*r,0,0), v(2*r,4*r,h), 0.1,
[[
uniform float r = 5;
float solid(vec3 p) {
float l = length(p.xy) - r;
float num = p.y + sqrt(p.x * p.x + p.y * p.y - r * r);
float denom = r + p.x;
float theta = 2 * atan(num, denom);
vec2 c = vec2(r * cos(theta), r * sin(theta));
float s = r * theta;
float sp = length(p.xy - c);
return min(l, sp - s);
}
]])
set_uniform_scalar(involute_of_circle, 'r', r)
emit(involute_of_circle,2)
emit(cylinder(r,h),1)
|
fix(gallery): Remove branch condition on involute
|
fix(gallery): Remove branch condition on involute
|
Lua
|
mit
|
loic-fejoz/loic-fejoz-fabmoments,loic-fejoz/loic-fejoz-fabmoments,loic-fejoz/loic-fejoz-fabmoments
|
4e0d0532a19eb3c477ef306ea518060929be1672
|
kong/cmd/init.lua
|
kong/cmd/init.lua
|
local pl_app = require "pl.lapp"
local log = require "kong.cmd.utils.log"
local options = [[
--v verbose
--vv debug
--trace with traceback
]]
local cmds_arr = {}
local cmds = {
start = true,
stop = true,
quit = true,
restart = true,
reload = true,
health = true,
check = true,
compile = true,
migrations = true,
cluster = true,
version = true,
roar = true
}
for k in pairs(cmds) do
cmds_arr[#cmds_arr+1] = k
end
table.sort(cmds_arr)
local help = string.format([[
Usage: kong COMMAND [OPTIONS]
The available commands are:
%s
Options:
%s
]], table.concat(cmds_arr, "\n "), options)
return function(args)
local cmd_name = table.remove(args, 1)
if not cmd_name then
pl_app(help)
pl_app.quit()
elseif not cmds[cmd_name] then
pl_app(help)
pl_app.quit("No such command: "..cmd_name)
end
local cmd = require("kong.cmd."..cmd_name)
local cmd_lapp = cmd.lapp
local cmd_exec = cmd.execute
if cmd_lapp then
cmd_lapp = cmd_lapp..options -- append universal options
args = pl_app(cmd_lapp)
end
-- check sub-commands
if cmd.sub_commands then
local sub_cmd = table.remove(args, 1)
if not sub_cmd then
pl_app.quit()
elseif not cmd.sub_commands[sub_cmd] then
pl_app.quit("No such command for "..cmd_name..": "..sub_cmd)
else
args.command = sub_cmd
end
end
-- verbose mode
if args.v then
log.set_lvl(log.levels.verbose)
elseif args.vv then
log.set_lvl(log.levels.debug)
args.trace = true
end
xpcall(function() cmd_exec(args) end, function(err)
if not args.trace then
err = err:match "^.-:.-:.(.*)$"
io.stderr:write("Error: "..err.."\n")
io.stderr:write("\n Run with --trace to see traceback\n")
else
local trace = debug.traceback(err, 2)
io.stderr:write("Error: \n")
io.stderr:write(trace.."\n")
end
pl_app.quit(nil, true)
end)
end
|
local pl_app = require "pl.lapp"
local log = require "kong.cmd.utils.log"
local options = [[
--v verbose
--vv debug
]]
local cmds_arr = {}
local cmds = {
start = true,
stop = true,
quit = true,
restart = true,
reload = true,
health = true,
check = true,
compile = true,
migrations = true,
cluster = true,
version = true,
roar = true
}
for k in pairs(cmds) do
cmds_arr[#cmds_arr+1] = k
end
table.sort(cmds_arr)
local help = string.format([[
Usage: kong COMMAND [OPTIONS]
The available commands are:
%s
Options:
%s
]], table.concat(cmds_arr, "\n "), options)
return function(args)
local cmd_name = table.remove(args, 1)
if not cmd_name then
pl_app(help)
pl_app.quit()
elseif not cmds[cmd_name] then
pl_app(help)
pl_app.quit("No such command: "..cmd_name)
end
local cmd = require("kong.cmd."..cmd_name)
local cmd_lapp = cmd.lapp
local cmd_exec = cmd.execute
if cmd_lapp then
cmd_lapp = cmd_lapp..options -- append universal options
args = pl_app(cmd_lapp)
end
-- check sub-commands
if cmd.sub_commands then
local sub_cmd = table.remove(args, 1)
if not sub_cmd then
pl_app.quit()
elseif not cmd.sub_commands[sub_cmd] then
pl_app.quit("No such command for "..cmd_name..": "..sub_cmd)
else
args.command = sub_cmd
end
end
-- verbose mode
if args.v then
log.set_lvl(log.levels.verbose)
elseif args.vv then
log.set_lvl(log.levels.debug)
end
xpcall(function() cmd_exec(args) end, function(err)
if not (args.v or args.vv) then
err = err:match "^.-:.-:.(.*)$"
io.stderr:write("Error: "..err.."\n")
io.stderr:write("\n Run with --v (verbose) or --vv (debug) for more details\n")
else
local trace = debug.traceback(err, 2)
io.stderr:write("Error: \n")
io.stderr:write(trace.."\n")
end
pl_app.quit(nil, true)
end)
end
|
fix(cli) drop the --trace option as it provides little information.
|
fix(cli) drop the --trace option as it provides little information.
The former `trace` info is automatically added to verbose and debug level logging.
|
Lua
|
apache-2.0
|
ccyphers/kong,li-wl/kong,akh00/kong,Vermeille/kong,jebenexer/kong,jerizm/kong,shiprabehera/kong,icyxp/kong,Mashape/kong,beauli/kong,salazar/kong,Kong/kong,Kong/kong,Kong/kong
|
1ca1b111d0c98376e72dfe660c479ed60b00d6d9
|
modules/admin-full/luasrc/model/cbi/admin_network/network.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/network.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
m = Map("network", translate("Interfaces"))
m:section(SimpleSection).template = "admin_network/iface_overview"
-- Show ATM bridge section if we have the capabilities
if fs.access("/usr/sbin/br2684ctl") then
atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"),
translate("ATM bridges expose encapsulated ethernet in AAL5 " ..
"connections as virtual Linux network interfaces which can " ..
"be used in conjunction with DHCP or PPP to dial into the " ..
"provider network."))
atm.addremove = true
atm.anonymous = true
atm.create = function(self, section)
local sid = TypedSection.create(self, section)
local max_unit = -1
m.uci:foreach("network", "atm-bridge",
function(s)
local u = tonumber(s.unit)
if u ~= nil and u > max_unit then
max_unit = u
end
end)
m.uci:set("network", sid, "unit", max_unit + 1)
m.uci:set("network", sid, "atmdev", 0)
m.uci:set("network", sid, "encaps", "llc")
m.uci:set("network", sid, "payload", "bridged")
m.uci:set("network", sid, "vci", 35)
m.uci:set("network", sid, "vpi", 8)
return sid
end
atm:tab("general", translate("General Setup"))
atm:tab("advanced", translate("Advanced Settings"))
vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)"))
vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)"))
encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode"))
encaps:value("llc", translate("LLC"))
encaps:value("vc", translate("VC-Mux"))
atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number"))
unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number"))
payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode"))
payload:value("bridged", translate("bridged"))
payload:value("routed", translate("routed"))
else
m.pageaction = false
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
m = Map("network", translate("Interfaces"))
m.pageaction = false
m:section(SimpleSection).template = "admin_network/iface_overview"
-- Show ATM bridge section if we have the capabilities
if fs.access("/usr/sbin/br2684ctl") then
atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"),
translate("ATM bridges expose encapsulated ethernet in AAL5 " ..
"connections as virtual Linux network interfaces which can " ..
"be used in conjunction with DHCP or PPP to dial into the " ..
"provider network."))
atm.addremove = true
atm.anonymous = true
atm.create = function(self, section)
local sid = TypedSection.create(self, section)
local max_unit = -1
m.uci:foreach("network", "atm-bridge",
function(s)
local u = tonumber(s.unit)
if u ~= nil and u > max_unit then
max_unit = u
end
end)
m.uci:set("network", sid, "unit", max_unit + 1)
m.uci:set("network", sid, "atmdev", 0)
m.uci:set("network", sid, "encaps", "llc")
m.uci:set("network", sid, "payload", "bridged")
m.uci:set("network", sid, "vci", 35)
m.uci:set("network", sid, "vpi", 8)
return sid
end
atm:tab("general", translate("General Setup"))
atm:tab("advanced", translate("Advanced Settings"))
vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)"))
vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)"))
encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode"))
encaps:value("llc", translate("LLC"))
encaps:value("vc", translate("VC-Mux"))
atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number"))
unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number"))
payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode"))
payload:value("bridged", translate("bridged"))
payload:value("routed", translate("routed"))
m.pageaction = true
end
local network = require "luci.model.network"
if network:has_ipv6() then
local s = m:section(NamedSection, "globals", "globals", translate("Global network options"))
local o = s:option(Value, "ula_prefix", translate("IPv6 ULA-Prefix"))
o.datatype = "ip6addr"
o.rmempty = true
m.pageaction = true
end
return m
|
Add support for changing ULA prefix
|
Add support for changing ULA prefix
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@9647 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
ThingMesh/openwrt-luci,gwlim/luci,phi-psi/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,ch3n2k/luci,ch3n2k/luci,ch3n2k/luci,Canaan-Creative/luci,Canaan-Creative/luci,phi-psi/luci,zwhfly/openwrt-luci,gwlim/luci,Canaan-Creative/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,phi-psi/luci,ThingMesh/openwrt-luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,8devices/carambola2-luci,phi-psi/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,Canaan-Creative/luci,phi-psi/luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,phi-psi/luci,Canaan-Creative/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,8devices/carambola2-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,vhpham80/luci,8devices/carambola2-luci,gwlim/luci,ch3n2k/luci,8devices/carambola2-luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,yeewang/openwrt-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,vhpham80/luci,yeewang/openwrt-luci,8devices/carambola2-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,Canaan-Creative/luci,eugenesan/openwrt-luci,ch3n2k/luci,gwlim/luci,gwlim/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci
|
6296bec45de0423cdfc5272b6543204a1d1566af
|
modules/tcp/tcp-connection.lua
|
modules/tcp/tcp-connection.lua
|
module("tcp-connection", package.seeall)
local function forge(self)
if not self.connection then
return nil
end
pkt = self.stream:pop()
if not pkt then
pkt = table.remove(self.connection.data.queue)
if pkt then
self.connection:stream(self.direction):seq(pkt)
end
end
if pkt then
self.connection:stream(not self.direction):ack(pkt)
end
if self.__drop then
self.connection:drop()
self.connection = nil
elseif self.__close then
self.connection:close()
self.connection = nil
end
return pkt
end
local function drop(self)
self.__drop = true
end
local function dissect(pkt)
local stream_dir, dropped
local newpkt = {}
newpkt.connection, newpkt.direction, dropped = pkt:getconnection()
newpkt.dissector = "tcp-connection"
newpkt.next_dissector = nil
newpkt.valid = function (self)
return not self.__close and not self.__drop
end
newpkt.drop = drop
newpkt.forge = forge
newpkt.__close = false
newpkt.__drop = false
if not newpkt.connection then
-- new connection
if pkt.flags.syn then
newpkt.tcp = pkt
newpkt.connection = pkt:newconnection()
newpkt.connection.data = {}
haka.rule_hook("tcp-connection-new", newpkt)
if not newpkt:valid() then
newpkt.connection:drop()
newpkt.connection = nil
pkt:drop()
return nil
end
newpkt.connection.data.next_dissector = newpkt.next_dissector
newpkt.connection.data.state = 0
newpkt.connection.data.queue = {}
newpkt.direction = true
else
if not dropped then
haka.log.error("tcp-connection", "no connection found")
end
pkt:drop()
return nil
end
end
newpkt.stream = newpkt.connection:stream(newpkt.direction)
if pkt.flags.syn then
newpkt.stream:init(pkt.seq+1)
return nil
elseif pkt.flags.rst then
newpkt.__close = true
table.insert(newpkt.connection.data.queue, pkt)
return newpkt
elseif newpkt.connection.data.state >= 2 then
if pkt.flags.ack then
newpkt.connection.data.state = newpkt.connection.data.state + 1
end
if newpkt.connection.data.state >= 3 then
newpkt.__close = true
end
table.insert(newpkt.connection.data.queue, pkt)
return newpkt
elseif pkt.flags.fin then
newpkt.connection.data.state = newpkt.connection.data.state+1
table.insert(newpkt.connection.data.queue, pkt)
return newpkt
else
newpkt.stream:push(pkt)
newpkt.next_dissector = newpkt.connection.data.next_dissector
return newpkt
end
end
haka.dissector {
name = "tcp-connection",
dissect = dissect
}
|
module("tcp-connection", package.seeall)
local function forge(self)
if not self.connection then
return nil
end
pkt = self.stream:pop()
if not pkt then
pkt = table.remove(self.connection.data.queue)
if pkt then
self.connection:stream(self.direction):seq(pkt)
end
end
if pkt then
self.connection:stream(not self.direction):ack(pkt)
end
if self.__drop then
self.connection:drop()
self.connection = nil
elseif self.__close then
self.connection:close()
self.connection = nil
end
return pkt
end
local function drop(self)
self.__drop = true
end
local function dissect(pkt)
local stream_dir, dropped
local newpkt = {}
newpkt.connection, newpkt.direction, dropped = pkt:getconnection()
newpkt.dissector = "tcp-connection"
newpkt.next_dissector = nil
newpkt.valid = function (self)
return not self.__close and not self.__drop
end
newpkt.drop = drop
newpkt.forge = forge
newpkt.__close = false
newpkt.__drop = false
if not newpkt.connection then
-- new connection
if pkt.flags.syn and not pkt.flags.ack then
newpkt.tcp = pkt
newpkt.connection = pkt:newconnection()
newpkt.connection.data = {}
haka.rule_hook("tcp-connection-new", newpkt)
if not newpkt:valid() then
newpkt.connection:drop()
newpkt.connection = nil
pkt:drop()
return nil
end
newpkt.connection.data.next_dissector = newpkt.next_dissector
newpkt.connection.data.state = 0
newpkt.connection.data.queue = {}
newpkt.direction = true
else
if not dropped then
haka.log.error("tcp-connection", "no connection found")
haka.log.debug("tcp-connection", "no connection found %s:%d -> %s:%d", pkt.ip.src,
pkt.srcport, pkt.ip.dst, pkt.dstport)
end
pkt:drop()
return nil
end
end
newpkt.stream = newpkt.connection:stream(newpkt.direction)
if pkt.flags.syn then
newpkt.stream:init(pkt.seq+1)
return nil
elseif pkt.flags.rst then
newpkt.__drop = true
table.insert(newpkt.connection.data.queue, pkt)
return newpkt
elseif newpkt.connection.data.state >= 2 then
if pkt.flags.ack then
newpkt.connection.data.state = newpkt.connection.data.state + 1
end
if newpkt.connection.data.state >= 3 then
newpkt.__close = true
end
table.insert(newpkt.connection.data.queue, pkt)
return newpkt
elseif pkt.flags.fin then
newpkt.connection.data.state = newpkt.connection.data.state+1
table.insert(newpkt.connection.data.queue, pkt)
return newpkt
else
newpkt.stream:push(pkt)
newpkt.next_dissector = newpkt.connection.data.next_dissector
return newpkt
end
end
haka.dissector {
name = "tcp-connection",
dissect = dissect
}
|
Fix tcp connection
|
Fix tcp connection
The connection first packet need to be a SYN only. Otherwise a repeated
SYN-ACK could be seen as a connection creation.
Also changed the behavior to drop the connection in case of a RST to
avoid "no connection found" log showing after it.
|
Lua
|
mpl-2.0
|
nabilbendafi/haka,lcheylus/haka,haka-security/haka,nabilbendafi/haka,LubyRuffy/haka,lcheylus/haka,Wingless-Archangel/haka,Wingless-Archangel/haka,LubyRuffy/haka,nabilbendafi/haka,haka-security/haka,lcheylus/haka,haka-security/haka
|
77b2e6d5eaea838d05eb8de3ed32fedc01933e8d
|
src/haka/lua/context.lua
|
src/haka/lua/context.lua
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
local LocalContext = class()
function LocalContext.method:__init()
self._connections = {}
self._dissector_connections = {}
end
function LocalContext.method:createnamespace(ref, data)
self[ref] = data
end
function LocalContext.method:namespace(ref)
return self[ref]
end
local Context = class()
function Context.method:__init()
self.connections = haka.events.StaticEventConnections:new()
end
function Context.method:signal(emitter, event, ...)
if not self.connections:signal(emitter, event, ...) then
return false
end
if self.context then
for _, connections in ipairs(self.context._connections) do
if not connections:signal(emitter, event, ...) then
return false
end
end
for _, connections in ipairs(self.context._dissector_connections) do
if not connections:signal(emitter, event, ...) then
return false
end
end
end
return true
end
function Context.method:newscope()
return LocalContext:new()
end
function Context.method:scope(context, func)
local old = self.context
self.context = context
local ret, msg = haka.pcall(func)
self.context = old
if not ret then error(msg) end
end
function Context.method:install_dissector(dissector)
if self.context then
local connections = dissector:connections()
if connections then
table.insert(self.context._dissector_connections, connections)
end
else
error("invalid context")
end
end
haka.context = Context:new()
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
local LocalContext = class()
function LocalContext.method:__init()
self._connections = {}
self._dissector_connections = {}
end
function LocalContext.method:createnamespace(ref, data)
self[ref] = data
end
function LocalContext.method:namespace(ref)
return self[ref]
end
local Context = class()
function Context.method:__init()
self.connections = haka.events.StaticEventConnections:new()
end
function Context.method:signal(emitter, event, ...)
if not self.connections:signal(emitter, event, ...) then
return false
end
if self.context then
for _, connections in ipairs(self.context._connections) do
if not connections:signal(emitter, event, ...) then
return false
end
end
for _, connections in ipairs(self.context._dissector_connections) do
if not connections:signal(emitter, event, ...) then
return false
end
end
end
return true
end
function Context.method:newscope()
return LocalContext:new()
end
function Context.method:scope(context, func)
local old = self.context
self.context = context
local success, msg = xpcall(func, debug.format_error)
self.context = old
if not success then error(msg) end
end
function Context.method:install_dissector(dissector)
if self.context then
local connections = dissector:connections()
if connections then
table.insert(self.context._dissector_connections, connections)
end
else
error("invalid context")
end
end
haka.context = Context:new()
|
Fix bad error report in Lua
|
Fix bad error report in Lua
Sometimes a (null) error was reported in the output.
|
Lua
|
mpl-2.0
|
Wingless-Archangel/haka,LubyRuffy/haka,LubyRuffy/haka,haka-security/haka,lcheylus/haka,Wingless-Archangel/haka,nabilbendafi/haka,haka-security/haka,haka-security/haka,lcheylus/haka,nabilbendafi/haka,nabilbendafi/haka,lcheylus/haka
|
71e27245fcffe7531270647d14e77bf68077f301
|
spec/03-plugins/syslog/log_spec.lua
|
spec/03-plugins/syslog/log_spec.lua
|
local utils = require "kong.tools.utils"
local cjson = require "cjson"
local helpers = require "spec.helpers"
local exec = require("pl.utils").executeex
describe("Syslog #ci", function()
local client, platform
setup(function()
helpers.dao:truncate_tables()
assert(helpers.prepare_prefix())
local api1 = assert(helpers.dao.apis:insert {
request_host = "logging.com",
upstream_url = "http://mockbin.com"
})
local api2 = assert(helpers.dao.apis:insert {
request_host = "logging2.com",
upstream_url = "http://mockbin.com"
})
local api3 = assert(helpers.dao.apis:insert {
request_host = "logging3.com",
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
api_id = api1.id,
name = "syslog",
config = {
log_level = "info",
successful_severity = "warning",
client_errors_severity = "warning",
server_errors_severity = "warning"
},
})
assert(helpers.dao.plugins:insert {
api_id = api2.id,
name = "syslog",
config = {
log_level = "err",
successful_severity = "warning",
client_errors_severity = "warning",
server_errors_severity = "warning"
},
})
assert(helpers.dao.plugins:insert {
api_id = api3.id,
name = "syslog",
config = {
log_level = "warning",
successful_severity = "warning",
client_errors_severity = "warning",
server_errors_severity = "warning"
},
})
local success, code, _
success, code, platform, _ = exec("/bin/uname")
if code ~= 0 then
success, code, platform, _ = exec("/usr/bin/uname")
end
assert(code == 0, "Failed to retrieve platform name")
assert(helpers.start_kong())
end)
teardown(function()
if client then client:close() end
helpers.stop_kong()
end)
before_each(function()
client = assert(helpers.http_client("127.0.0.1", helpers.test_conf.proxy_port))
end)
after_each(function()
if client then client:close() end
end)
local function do_test(host, expecting_same)
local uuid = utils.random_string()
-- Making the request
local response = assert( client:send {
method = "GET",
path = "/request",
headers = {
host = host,
sys_log_uuid = uuid,
},
})
assert.has.res_status(200, response)
if platform == "Darwin" then
local success, code, output, errout = exec("syslog -k Sender kong | tail -1")
assert.equal(0, code)
local message = {}
for w in string.gmatch(output,"{.*}") do
table.insert(message, w)
end
local log_message = cjson.decode(message[1])
if expecting_same then
assert.equal(uuid, log_message.request.headers.sys_log_uuid)
else
assert.not_equal(uuid, log_message.request.headers.sys_log_uuid)
end
else
if expecting_same then
local success, code, output, errout = exec("find /var/log -type f -mmin -5 2>/dev/null | xargs grep -l "..uuid)
assert.are.equal(0, code)
assert.is.True(#output > 0)
end
end
end
it("should log to syslog if log_level is lower", function()
do_test("logging.com", true)
end)
it("should not log to syslog if the log_level is higher", function()
do_test("logging2.com", false)
end)
it("should log to syslog if log_level is the same", function()
do_test("logging3.com", true)
end)
end)
|
local helpers = require "spec.helpers"
local utils = require "kong.tools.utils"
local cjson = require "cjson"
local pl_stringx = require "pl.stringx"
describe("Plugin: syslog", function()
local client, platform
setup(function()
helpers.dao:truncate_tables()
assert(helpers.prepare_prefix())
local api1 = assert(helpers.dao.apis:insert {
request_host = "logging.com",
upstream_url = "http://mockbin.com"
})
local api2 = assert(helpers.dao.apis:insert {
request_host = "logging2.com",
upstream_url = "http://mockbin.com"
})
local api3 = assert(helpers.dao.apis:insert {
request_host = "logging3.com",
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
api_id = api1.id,
name = "syslog",
config = {
log_level = "info",
successful_severity = "warning",
client_errors_severity = "warning",
server_errors_severity = "warning"
}
})
assert(helpers.dao.plugins:insert {
api_id = api2.id,
name = "syslog",
config = {
log_level = "err",
successful_severity = "warning",
client_errors_severity = "warning",
server_errors_severity = "warning"
}
})
assert(helpers.dao.plugins:insert {
api_id = api3.id,
name = "syslog",
config = {
log_level = "warning",
successful_severity = "warning",
client_errors_severity = "warning",
server_errors_severity = "warning"
}
})
local ok, _, stdout = helpers.execute("uname")
assert(ok, "failed to retrieve platform name")
assert(helpers.start_kong())
platform = pl_stringx.strip(stdout)
end)
teardown(function()
helpers.stop_kong()
end)
before_each(function()
client = assert(helpers.http_client("127.0.0.1", helpers.test_conf.proxy_port))
end)
after_each(function()
if client then client:close() end
end)
local function do_test(host, expecting_same)
local uuid = utils.random_string()
local response = assert(client:send {
method = "GET",
path = "/request",
headers = {
host = host,
sys_log_uuid = uuid,
}
})
assert.res_status(200, response)
if platform == "Darwin" then
local _, code, stdout = helpers.execute("syslog -k Sender kong | tail -1")
assert.equal(0, code)
local msg = string.match(stdout, "{.*}")
local json = cjson.decode(msg)
if expecting_same then
assert.equal(uuid, json.request.headers["sys-log-uuid"])
else
assert.not_equal(uuid, json.request.headers["sys-log-uuid"])
end
elseif expecting_same then
local _, code, stdout = helpers.execute("find /var/log -type f -mmin -5 2>/dev/null | xargs grep -l "..uuid)
assert.equal(0, code)
assert.True(#stdout > 0)
end
end
it("logs to syslog if log_level is lower", function()
do_test("logging.com", true)
end)
it("does not log to syslog if log_level is higher", function()
do_test("logging2.com", false)
end)
it("logs to syslog if log_level is the same", function()
do_test("logging3.com", true)
end)
end)
|
tests(syslog) fix linting and boilerplate
|
tests(syslog) fix linting and boilerplate
|
Lua
|
apache-2.0
|
salazar/kong,li-wl/kong,Kong/kong,beauli/kong,Kong/kong,akh00/kong,icyxp/kong,Vermeille/kong,shiprabehera/kong,jebenexer/kong,Kong/kong,Mashape/kong,ccyphers/kong,jerizm/kong
|
86e5d8283dba1b3701b4f122f788e81c1feea95e
|
examples/read_by_line.lua
|
examples/read_by_line.lua
|
-- read input stream line by line
local uv = require "lluv"
local ut = require "lluv.utils"
local host, port = "127.0.0.1", 5555
local buffer = ut.Buffer("\r\n")
local function read_data(cli, err, data)
if err then return cli:close() end
local line = buffer.next_line(data)
while line do
print(line)
line = buffer.next_line()
end
end
uv.tcp():connect(host, port, function(cli, err)
if err then return cli:close() end
cli:start_read(read_data)
end)
uv.run(debug.traceback)
|
-- read input stream line by line
local uv = require "lluv"
local ut = require "lluv.utils"
local host, port = "127.0.0.1", 5555
local buffer = ut.Buffer.new("\r\n")
local function read_data(cli, err, data)
if err then return cli:close() end
buffer:append(data)
while true do
local line = buffer:next_line()
if not line then break end
print(line)
end
end
uv.tcp():connect(host, port, function(cli, err)
if err then return cli:close() end
cli:start_read(read_data)
end)
uv.run(debug.traceback)
|
Fix. Read line example
|
Fix. Read line example
|
Lua
|
mit
|
moteus/lua-lluv,moteus/lua-lluv,moteus/lua-lluv,kidaa/lua-lluv,kidaa/lua-lluv
|
5511c29bdfbcb986c1efedc2ec133065760108ae
|
modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/iface_add.lua
|
modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/iface_add.lua
|
-- Copyright 2009-2010 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local nw = require "luci.model.network".init()
local fw = require "luci.model.firewall".init()
local utl = require "luci.util"
local uci = require "luci.model.uci".cursor()
m = SimpleForm("network", translate("Create Interface"))
m.redirect = luci.dispatcher.build_url("admin/network/network")
m.reset = false
newnet = m:field(Value, "_netname", translate("Name of the new interface"),
translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " ..
"<code>0-9</code> and <code>_</code>"
))
newnet:depends("_attach", "")
newnet.default = arg[1] and "net_" .. arg[1]:gsub("[^%w_]+", "_")
newnet.datatype = "uciname"
newproto = m:field(ListValue, "_netproto", translate("Protocol of the new interface"))
netbridge = m:field(Flag, "_bridge", translate("Create a bridge over multiple interfaces"))
sifname = m:field(Value, "_ifname", translate("Cover the following interface"))
sifname.widget = "radio"
sifname.template = "cbi/network_ifacelist"
sifname.nobridges = true
mifname = m:field(Value, "_ifnames", translate("Cover the following interfaces"))
mifname.widget = "checkbox"
mifname.template = "cbi/network_ifacelist"
mifname.nobridges = true
local _, p
for _, p in ipairs(nw:get_protocols()) do
if p:is_installed() then
newproto:value(p:proto(), p:get_i18n())
if not p:is_virtual() then netbridge:depends("_netproto", p:proto()) end
if not p:is_floating() then
sifname:depends({ _bridge = "", _netproto = p:proto()})
mifname:depends({ _bridge = "1", _netproto = p:proto()})
end
end
end
function newproto.validate(self, value, section)
local name = newnet:formvalue(section)
if not name or #name == 0 then
newnet:add_error(section, translate("No network name specified"))
elseif m:get(name) then
newnet:add_error(section, translate("The given network name is not unique"))
end
local proto = nw:get_protocol(value)
if proto and not proto:is_floating() then
local br = (netbridge:formvalue(section) == "1")
local ifn = br and mifname:formvalue(section) or sifname:formvalue(section)
for ifn in utl.imatch(ifn) do
return value
end
return nil, translate("The selected protocol needs a device assigned")
end
return value
end
function newproto.write(self, section, value)
local name = newnet:formvalue(section)
if name and #name > 0 then
local br = (netbridge:formvalue(section) == "1") and "bridge" or nil
local net = nw:add_network(name, { proto = value, type = br })
if net then
local ifn
for ifn in utl.imatch(
br and mifname:formvalue(section) or sifname:formvalue(section)
) do
net:add_interface(ifn)
end
nw:save("network")
nw:save("wireless")
end
luci.http.redirect(luci.dispatcher.build_url("admin/network/network", name))
end
end
return m
|
-- Copyright 2009-2010 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local nw = require "luci.model.network".init()
local fw = require "luci.model.firewall".init()
local utl = require "luci.util"
local uci = require "luci.model.uci".cursor()
m = SimpleForm("network", translate("Create Interface"))
m.redirect = luci.dispatcher.build_url("admin/network/network")
m.reset = false
newnet = m:field(Value, "_netname", translate("Name of the new interface"),
translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " ..
"<code>0-9</code> and <code>_</code>"
))
newnet:depends("_attach", "")
newnet.default = arg[1] and "net_" .. arg[1]:gsub("[^%w_]+", "_")
newnet.datatype = "and(uciname,maxlength(15))"
advice = m:field(DummyValue, "d1", translate("Note: interface name length"),
translate("Maximum length of the name is 15 characters including " ..
"the automatic protocol/bridge prefix (br-, 6in4-, pppoe- etc.)"
))
newproto = m:field(ListValue, "_netproto", translate("Protocol of the new interface"))
netbridge = m:field(Flag, "_bridge", translate("Create a bridge over multiple interfaces"))
sifname = m:field(Value, "_ifname", translate("Cover the following interface"))
sifname.widget = "radio"
sifname.template = "cbi/network_ifacelist"
sifname.nobridges = true
mifname = m:field(Value, "_ifnames", translate("Cover the following interfaces"))
mifname.widget = "checkbox"
mifname.template = "cbi/network_ifacelist"
mifname.nobridges = true
local _, p
for _, p in ipairs(nw:get_protocols()) do
if p:is_installed() then
newproto:value(p:proto(), p:get_i18n())
if not p:is_virtual() then netbridge:depends("_netproto", p:proto()) end
if not p:is_floating() then
sifname:depends({ _bridge = "", _netproto = p:proto()})
mifname:depends({ _bridge = "1", _netproto = p:proto()})
end
end
end
function newproto.validate(self, value, section)
local name = newnet:formvalue(section)
if not name or #name == 0 then
newnet:add_error(section, translate("No network name specified"))
elseif m:get(name) then
newnet:add_error(section, translate("The given network name is not unique"))
end
local proto = nw:get_protocol(value)
if proto and not proto:is_floating() then
local br = (netbridge:formvalue(section) == "1")
local ifn = br and mifname:formvalue(section) or sifname:formvalue(section)
for ifn in utl.imatch(ifn) do
return value
end
return nil, translate("The selected protocol needs a device assigned")
end
return value
end
function newproto.write(self, section, value)
local name = newnet:formvalue(section)
if name and #name > 0 then
local br = (netbridge:formvalue(section) == "1") and "bridge" or nil
local net = nw:add_network(name, { proto = value, type = br })
if net then
local ifn
for ifn in utl.imatch(
br and mifname:formvalue(section) or sifname:formvalue(section)
) do
net:add_interface(ifn)
end
nw:save("network")
nw:save("wireless")
end
luci.http.redirect(luci.dispatcher.build_url("admin/network/network", name))
end
end
return m
|
luci-mod-admin-full: limit interface name length to 15 chars
|
luci-mod-admin-full: limit interface name length to 15 chars
Limit the name of a new interface to 15 characters.
Add a note about the maximum length and the automatic protocol/bridge
prefixes (br-, 6in4-, pppoe- etc.).
Reference to:
https://dev.openwrt.org/ticket/20380
https://github.com/openwrt/luci/issues/507
There is a 15 character limit to the "real" interface name,
enforced both in the firewall and dnsmasq. The real interface name
includes the possible prefix "br-", "6in4-" etc. Example of an error:
interface name `br-lan_protected' must be shorter than IFNAMSIZ (15)
Signed-off-by: Hannu Nyman <ab53a3387de93e31696058c104e6f769cd83fd1b@iki.fi>
(cherry picked from commit b1217c88c3566c1bd726bce9203da591af564bcf)
|
Lua
|
apache-2.0
|
db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,RuiChen1113/luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,RuiChen1113/luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,RuiChen1113/luci,Sakura-Winkey/LuCI
|
38251718297142f966f28385a79a111b0c5b5009
|
share/lua/website/collegehumor.lua
|
share/lua/website/collegehumor.lua
|
-- libquvi-scripts
-- Copyright (C) 2012 Toni Gundogdu <legatvs@gmail.com>
-- Copyright (C) 2010-2011 Lionel Elie Mamane <lionel@mamane.lu>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
local CollegeHumor = {} -- Utility functions unique to this script
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
local domains= {"collegehumor%.com", "dorkly%.com"}
r.domain = table.concat(domains, "|")
r.formats = "default|best"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, domains,
{"/video[:/]%d+/?", "/embed/%d+"})
return r
end
-- Query formats.
function query_formats(self)
if CollegeHumor.redirect_if_embed(self) then
return self
end
local config = CollegeHumor.get_config(self)
local formats = CollegeHumor.iter_formats(config)
local t = {}
for k,v in pairs(formats) do
table.insert(t, CollegeHumor.to_s(v))
end
table.sort(t)
self.formats = table.concat(t, "|")
return self
end
-- Parse media URL.
function parse(self)
self.host_id = "collegehumor"
if CollegeHumor.redirect_if_embed(self) then
return self
end
local c = CollegeHumor.get_config(self)
self.title = c:match('<caption>(.-)<')
or error("no match: media title")
self.thumbnail_url = c:match('<thumbnail><!%[.-%[(.-)%]') or ''
local formats = CollegeHumor.iter_formats(c)
local U = require 'quvi/util'
local format = U.choose_format(self, formats,
CollegeHumor.choose_best,
CollegeHumor.choose_default,
CollegeHumor.to_s)
or error("unable to choose format")
self.url = {format.url or error("no match: media URL")}
return self
end
--
-- Utility functions
--
function CollegeHumor.redirect_if_embed(self) -- dorkly embeds YouTube videos
if self.page_url:match('/embed/%d+') then
local p = quvi.fetch(self.page_url)
local s = p:match('youtube.com/embed/([%w-_]+)')
if s then
-- Hand over to youtube.lua
self.redirect_url = 'http://youtube.com/watch?v=' .. s
return true
end
end
return false
end
function CollegeHumor.get_media_id(self)
local U = require 'quvi/url'
local domain = U.parse(self.page_url).host:gsub('^www%.', '', 1)
self.host_id = domain:match('^(.+)%.[^.]+$')
or error("no match: domain")
self.id = self.page_url:match('/video[/:](%d+)')
or error("no match: media ID")
return domain
end
function CollegeHumor.get_config(self)
local domain = CollegeHumor.get_media_id(self)
-- quvi normally checks the page URL for a redirection to another
-- URL. Disabling this check (QUVIOPT_NORESOLVE) breaks the support
-- which is why we do this manually here.
local r = quvi.resolve(self.page_url)
-- Make a note of the use of the quvi.resolve returned string.
local config_url =
string.format("http://www.%s/moogaloop/video%s%s",
domain, (#r > 0) and ':' or '/', self.id)
return quvi.fetch(config_url, {fetch_type='config'})
end
function CollegeHumor.iter_formats(config)
local sd_url = config:match('<file><!%[.-%[(.-)%]')
local hq_url = config:match('<hq><!%[.-%[(.-)%]')
local hq_avail = (hq_url and #hq_url > 0) and 1 or 0
local t = {}
local s = sd_url:match('%.(%w+)$')
table.insert(t, {quality='sd', url=sd_url, container=s})
if hq_avail == 1 and hq_url then
local s = hq_url:match('%.(%w+)$')
table.insert(t, {quality='hq', url=hq_url, container=s})
end
return t
end
function CollegeHumor.choose_best(formats) -- Assume last is best.
local r
for _,v in pairs(formats) do r = v end
return r
end
function CollegeHumor.choose_default(formats) -- Whatever is found first.
for _,v in pairs(formats) do return v end
end
function CollegeHumor.to_s(t)
return string.format('%s_%s', t.container, t.quality)
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2012 Toni Gundogdu <legatvs@gmail.com>
-- Copyright (C) 2010-2011 Lionel Elie Mamane <lionel@mamane.lu>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
local CollegeHumor = {} -- Utility functions unique to this script
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
local domains= {"collegehumor%.com", "dorkly%.com"}
r.domain = table.concat(domains, "|")
r.formats = "default|best"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, domains,
{"/video[:/]%d+/?", "/embed/%d+"})
return r
end
-- Query formats.
function query_formats(self)
if CollegeHumor.redirect_if_embed(self) then
return self
end
local config = CollegeHumor.get_config(self)
local formats = CollegeHumor.iter_formats(config)
local t = {}
for k,v in pairs(formats) do
table.insert(t, CollegeHumor.to_s(v))
end
table.sort(t)
self.formats = table.concat(t, "|")
return self
end
-- Parse media URL.
function parse(self)
self.host_id = "collegehumor"
if CollegeHumor.redirect_if_embed(self) then
return self
end
local c = CollegeHumor.get_config(self)
self.title = c:match('<caption>.-%[.-%[(.-)%]%]')
or error("no match: media title")
self.thumbnail_url = c:match('<thumbnail><!%[.-%[(.-)%]') or ''
local formats = CollegeHumor.iter_formats(c)
local U = require 'quvi/util'
local format = U.choose_format(self, formats,
CollegeHumor.choose_best,
CollegeHumor.choose_default,
CollegeHumor.to_s)
or error("unable to choose format")
self.url = {format.url or error("no match: media URL")}
return self
end
--
-- Utility functions
--
function CollegeHumor.redirect_if_embed(self) -- dorkly embeds YouTube videos
if self.page_url:match('/embed/%d+') then
local p = quvi.fetch(self.page_url)
local s = p:match('youtube.com/embed/([%w-_]+)')
if s then
-- Hand over to youtube.lua
self.redirect_url = 'http://youtube.com/watch?v=' .. s
return true
end
end
return false
end
function CollegeHumor.get_media_id(self)
local U = require 'quvi/url'
local domain = U.parse(self.page_url).host:gsub('^www%.', '', 1)
self.host_id = domain:match('^(.+)%.[^.]+$') or error("no match: domain")
self.id = self.page_url:match('/video[/:](%d+)')
or error("no match: media ID")
return domain
end
function CollegeHumor.get_config(self)
local domain = CollegeHumor.get_media_id(self)
-- quvi normally checks the page URL for a redirection to another
-- URL. Disabling this check (QUVIOPT_NORESOLVE) breaks the support
-- which is why we do this manually here.
local r = quvi.resolve(self.page_url)
-- Make a note of the use of the quvi.resolve returned string.
local u = string.format("http://www.%s/moogaloop/video%s%s",
domain, (#r > 0) and ':' or '/', self.id)
return quvi.fetch(u, {fetch_type='config'})
end
function CollegeHumor.iter_formats(config)
local sd_url = config:match('<file><!%[.-%[(.-)%]')
local hq_url = config:match('<hq><!%[.-%[(.-)%]')
local hq_avail = (hq_url and #hq_url > 0) and 1 or 0
local t = {}
local s = sd_url:match('%.(%w+)$')
table.insert(t, {quality='sd', url=sd_url, container=s})
if hq_avail == 1 and hq_url then
local s = hq_url:match('%.(%w+)$')
table.insert(t, {quality='hq', url=hq_url, container=s})
end
return t
end
function CollegeHumor.choose_best(formats) -- Assume last is best.
local r
for _,v in pairs(formats) do r = v end
return r
end
function CollegeHumor.choose_default(formats) -- Whatever is found first.
for _,v in pairs(formats) do return v end
end
function CollegeHumor.to_s(t)
return string.format('%s_%s', t.container, t.quality)
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
FIX: website/collegehumor.lua: title pattern
|
FIX: website/collegehumor.lua: title pattern
|
Lua
|
lgpl-2.1
|
hadess/libquvi-scripts-iplayer,alech/libquvi-scripts,legatvs/libquvi-scripts,hadess/libquvi-scripts-iplayer,DangerCove/libquvi-scripts,alech/libquvi-scripts,DangerCove/libquvi-scripts,legatvs/libquvi-scripts
|
f609905267f5a0c04159834614a21376809ca365
|
profiles/lib/profile_debugger.lua
|
profiles/lib/profile_debugger.lua
|
-- Enable calling our lua profile code directly from the lua command line,
-- which makes it easier to debug.
-- We simulate the normal C++ environment by defining the required globals and functions.
-- See debug_example.lua for an example of how to require and use this file.
-- for more convenient printing of tables
local pprint = require('lib/pprint')
-- globals that are normally set from C++
-- profiles code modifies this table
properties = {}
-- should match values defined in include/extractor/guidance/road_classification.hpp
road_priority_class = {
motorway = 0,
trunk = 2,
primary = 4,
secondary = 6,
tertiary = 8,
main_residential = 10,
side_residential = 11,
link_road = 14,
bike_path = 16,
foot_path = 18,
connectivity = 31,
}
-- should match values defined in include/extractor/travel_mode.hpp
mode = {
inaccessible = 0,
driving = 1,
cycling = 2,
walking = 3,
ferry = 4,
train = 5,
pushing_bike = 6,
}
-- Mock C++ helper functions which are called from LUA.
-- TODO
-- Debugging LUA code that uses these will not work correctly
-- unless we reimplement the methods in LUA.
function durationIsValid(str)
return true
end
function parseDuration(str)
return 1
end
function canonicalizeStringList(str)
return str
end
-- debug helper
local Debug = {}
-- helpers for sorting associative array
function Debug.get_keys_sorted_by_value(tbl, sortFunction)
local keys = {}
for key in pairs(tbl) do
table.insert(keys, key)
end
table.sort(keys, function(a, b)
return sortFunction(tbl[a], tbl[b])
end)
return keys
end
-- helper for printing sorted array
function Debug.print_sorted(sorted,associative)
for _, key in ipairs(sorted) do
print(associative[key], key)
end
end
function Debug.report_tag_fetches()
print("Tag fetches:")
sorted_counts = Debug.get_keys_sorted_by_value(Debug.tags.counts, function(a, b) return a > b end)
Debug.print_sorted(sorted_counts, Debug.tags.counts)
print(Debug.tags.total, 'total')
end
function Debug.load_profile(profile)
Debug.functions = require(profile)
Debug.profile = Debug.functions.setup()
end
function Debug.reset_tag_fetch_counts()
Debug.tags = {
total = 0,
counts = {}
}
end
function Debug.register_tag_fetch(k)
if Debug.tags.total then
Debug.tags.total = Debug.tags.total + 1
else
Debug['tags']['total'] = 1
end
if Debug['tags']['counts'][k] then
Debug['tags']['counts'][k] = Debug['tags']['counts'][k] + 1
else
Debug['tags']['counts'][k] = 1
end
end
function Debug.process_way(way,result)
-- setup result table
result.road_classification = {}
result.forward_speed = -1
result.backward_speed = -1
result.duration = 0
-- intercept tag function normally provided via C++
function way:get_value_by_key(k)
Debug.register_tag_fetch(k)
return self[k]
end
-- reset tag counts
Debug:reset_tag_fetch_counts()
-- call the way processsing function
Debug.functions.process_way(Debug.profile,way,result)
end
return Debug
|
-- Enable calling our lua profile code directly from the lua command line,
-- which makes it easier to debug.
-- We simulate the normal C++ environment by defining the required globals and functions.
-- See debug_example.lua for an example of how to require and use this file.
-- for more convenient printing of tables
local pprint = require('lib/pprint')
-- globals that are normally set from C++
-- should match values defined in include/extractor/guidance/road_classification.hpp
road_priority_class = {
motorway = 0,
trunk = 2,
primary = 4,
secondary = 6,
tertiary = 8,
main_residential = 10,
side_residential = 11,
link_road = 14,
bike_path = 16,
foot_path = 18,
connectivity = 31,
}
-- should match values defined in include/extractor/travel_mode.hpp
mode = {
inaccessible = 0,
driving = 1,
cycling = 2,
walking = 3,
ferry = 4,
train = 5,
pushing_bike = 6,
}
-- Mock C++ helper functions which are called from LUA.
-- TODO
-- Debugging LUA code that uses these will not work correctly
-- unless we reimplement the methods in LUA.
function durationIsValid(str)
return true
end
function parseDuration(str)
return 1
end
function canonicalizeStringList(str)
return str
end
-- debug helper
local Debug = {}
-- helpers for sorting associative array
function Debug.get_keys_sorted_by_value(tbl, sortFunction)
local keys = {}
for key in pairs(tbl) do
table.insert(keys, key)
end
table.sort(keys, function(a, b)
return sortFunction(tbl[a], tbl[b])
end)
return keys
end
-- helper for printing sorted array
function Debug.print_sorted(sorted,associative)
for _, key in ipairs(sorted) do
print(associative[key], key)
end
end
function Debug.report_tag_fetches()
print("Tag fetches:")
sorted_counts = Debug.get_keys_sorted_by_value(Debug.tags.counts, function(a, b) return a > b end)
Debug.print_sorted(sorted_counts, Debug.tags.counts)
print(Debug.tags.total, 'total')
end
function Debug.load_profile(profile)
Debug.functions = require(profile)
Debug.profile = Debug.functions.setup()
end
function Debug.reset_tag_fetch_counts()
Debug.tags = {
total = 0,
counts = {}
}
end
function Debug.register_tag_fetch(k)
if Debug.tags.total then
Debug.tags.total = Debug.tags.total + 1
else
Debug['tags']['total'] = 1
end
if Debug['tags']['counts'][k] then
Debug['tags']['counts'][k] = Debug['tags']['counts'][k] + 1
else
Debug['tags']['counts'][k] = 1
end
end
function Debug.process_way(way,result)
-- setup result table
result.road_classification = {}
result.forward_speed = -1
result.backward_speed = -1
result.duration = 0
result.forward_classes = {}
result.backward_classes = {}
-- intercept tag function normally provided via C++
function way:get_value_by_key(k)
Debug.register_tag_fetch(k)
return self[k]
end
-- reset tag counts
Debug:reset_tag_fetch_counts()
-- call the way processsing function
Debug.functions.process_way(Debug.profile,way,result)
end
return Debug
|
fix profile debugging related to way classes
|
fix profile debugging related to way classes
|
Lua
|
bsd-2-clause
|
Project-OSRM/osrm-backend,felixguendling/osrm-backend,oxidase/osrm-backend,deniskoronchik/osrm-backend,neilbu/osrm-backend,Project-OSRM/osrm-backend,bjtaylor1/osrm-backend,yuryleb/osrm-backend,KnockSoftware/osrm-backend,neilbu/osrm-backend,bjtaylor1/osrm-backend,felixguendling/osrm-backend,neilbu/osrm-backend,frodrigo/osrm-backend,frodrigo/osrm-backend,Project-OSRM/osrm-backend,oxidase/osrm-backend,deniskoronchik/osrm-backend,oxidase/osrm-backend,bjtaylor1/osrm-backend,yuryleb/osrm-backend,Project-OSRM/osrm-backend,KnockSoftware/osrm-backend,yuryleb/osrm-backend,deniskoronchik/osrm-backend,neilbu/osrm-backend,KnockSoftware/osrm-backend,frodrigo/osrm-backend,felixguendling/osrm-backend,frodrigo/osrm-backend,bjtaylor1/osrm-backend,KnockSoftware/osrm-backend,deniskoronchik/osrm-backend,oxidase/osrm-backend,yuryleb/osrm-backend
|
68b79bcc4c4ea6a1ed5ad8d1828719c03a2d52e4
|
kong/serf.lua
|
kong/serf.lua
|
-- from the previous services.serf module, simply decoupled from
-- the Serf agent supervision logic.
local pl_stringx = require "pl.stringx"
local pl_utils = require "pl.utils"
local pl_file = require "pl.file"
local cjson = require "cjson.safe"
local log = require "kong.cmd.utils.log"
local Serf = {}
Serf.__index = Serf
Serf.args_mt = {
__tostring = function(t)
local buf = {}
for k, v in pairs(t) do buf[#buf+1] = k.." '"..v.."'" end
return table.concat(buf, " ")
end
}
function Serf.new(kong_config, dao)
return setmetatable({
node_name = pl_file.read(kong_config.serf_node_id),
config = kong_config,
dao = dao
}, Serf)
end
-- WARN: BAD, this is **blocking** IO. Legacy code from previous Serf
-- implementation that needs to be upgraded.
function Serf:invoke_signal(signal, args, no_rpc)
args = args or {}
if type(args) == "table" then
setmetatable(args, Serf.args_mt)
end
local rpc = no_rpc and "" or "-rpc-addr="..self.config.cluster_listen_rpc
local cmd = string.format("%s %s %s %s", self.config.serf_path, signal, rpc, tostring(args))
local ok, code, stdout, stderr = pl_utils.executeex(cmd)
if not ok or code ~= 0 then
-- always print the first error line of serf
local err = stdout ~= "" and pl_stringx.splitlines(stdout)[1] or stderr
return nil, err
end
return stdout
end
function Serf:join_node(address)
return select(2, self:invoke_signal("join", address)) == nil
end
function Serf:leave()
local res, err = self:invoke_signal("leave")
if not res then return nil, err end
local _, err = self.dao.nodes:delete {name = self.node_name}
if err then return nil, tostring(err) end
return true
end
function Serf:force_leave(node_name)
local res, err = self:invoke_signal("force-leave", node_name)
if not res then return nil, err end
return true
end
function Serf:members()
local res, err = self:invoke_signal("members", {["-format"] = "json"})
if not res then return nil, err end
local json, err = cjson.decode(res)
if not json then return nil, err end
return json.members
end
function Serf:keygen()
return self:invoke_signal("keygen", nil, true)
end
function Serf:reachability()
return self:invoke_signal("reachability")
end
function Serf:cleanup()
-- Delete current node just in case it was there
-- (due to an inconsistency caused by a crash)
local _, err = self.dao.nodes:delete {name = self.node_name }
if err then return nil, tostring(err) end
return true
end
function Serf:autojoin()
local nodes, err = self.dao.nodes:find_all()
if err then return nil, tostring(err)
elseif #nodes == 0 then
log.verbose("no other nodes found in the cluster")
else
-- Sort by newest to oldest (although by TTL would be a better sort)
table.sort(nodes, function(a, b) return a.created_at > b.created_at end)
local joined
for _, v in ipairs(nodes) do
if self:join_node(v.cluster_listening_address) then
log.verbose("successfully joined cluster at %s", v.cluster_listening_address)
joined = true
break
else
log.warn("could not join cluster at %s, if the node does not exist "..
"anymore it will be purged automatically", v.cluster_listening_address)
end
end
if not joined then
log.warn("could not join the existing cluster")
end
end
return true
end
function Serf:add_node()
local members, err = self:members()
if not members then return nil, err end
local addr
for _, member in ipairs(members) do
if member.name == self.node_name then
addr = member.addr
break
end
end
if not addr then
return nil, "can't find current member address"
end
local _, err = self.dao.nodes:insert({
name = self.node_name,
cluster_listening_address = pl_stringx.strip(addr)
}, {ttl = self.config.cluster_ttl_on_failure})
if err then return nil, tostring(err) end
return true
end
function Serf:event(t_payload)
local payload, err = cjson.encode(t_payload)
if not payload then return nil, err end
if #payload > 512 then
-- Serf can't send a payload greater than 512 bytes
return nil, "encoded payload is "..#payload.." and exceeds the limit of 512 bytes!"
end
return self:invoke_signal("event -coalesce=false", " kong '"..payload.."'")
end
return Serf
|
-- from the previous services.serf module, simply decoupled from
-- the Serf agent supervision logic.
local pl_stringx = require "pl.stringx"
local pl_utils = require "pl.utils"
local pl_file = require "pl.file"
local cjson = require "cjson.safe"
local log = require "kong.cmd.utils.log"
local Serf = {}
Serf.__index = Serf
Serf.args_mt = {
__tostring = function(t)
local buf = {}
for k, v in pairs(t) do buf[#buf+1] = k.." '"..v.."'" end
return table.concat(buf, " ")
end
}
function Serf.new(kong_config, dao)
return setmetatable({
node_name = pl_file.read(kong_config.serf_node_id),
config = kong_config,
dao = dao
}, Serf)
end
-- WARN: BAD, this is **blocking** IO. Legacy code from previous Serf
-- implementation that needs to be upgraded.
function Serf:invoke_signal(signal, args, no_rpc)
args = args or {}
if type(args) == "table" then
setmetatable(args, Serf.args_mt)
end
local rpc = no_rpc and "" or "-rpc-addr="..self.config.cluster_listen_rpc
local cmd = string.format("%s %s %s %s", self.config.serf_path, signal, rpc, tostring(args))
local ok, code, stdout, stderr = pl_utils.executeex(cmd)
if not ok or code ~= 0 then
-- always print the first error line of serf
local err = stdout ~= "" and pl_stringx.splitlines(stdout)[1] or stderr
return nil, err
end
return stdout
end
function Serf:join_node(address)
return select(2, self:invoke_signal("join", address)) == nil
end
function Serf:leave()
-- See https://github.com/hashicorp/serf/issues/400
-- Currently sometimes this returns an error, once that Serf issue has been
-- fixed we can check again for any errors returned by the following command.
self:invoke_signal("leave")
local _, err = self.dao.nodes:delete {name = self.node_name}
if err then return nil, tostring(err) end
return true
end
function Serf:force_leave(node_name)
local res, err = self:invoke_signal("force-leave", node_name)
if not res then return nil, err end
return true
end
function Serf:members()
local res, err = self:invoke_signal("members", {["-format"] = "json"})
if not res then return nil, err end
local json, err = cjson.decode(res)
if not json then return nil, err end
return json.members
end
function Serf:keygen()
return self:invoke_signal("keygen", nil, true)
end
function Serf:reachability()
return self:invoke_signal("reachability")
end
function Serf:cleanup()
-- Delete current node just in case it was there
-- (due to an inconsistency caused by a crash)
local _, err = self.dao.nodes:delete {name = self.node_name }
if err then return nil, tostring(err) end
return true
end
function Serf:autojoin()
local nodes, err = self.dao.nodes:find_all()
if err then return nil, tostring(err)
elseif #nodes == 0 then
log.verbose("no other nodes found in the cluster")
else
-- Sort by newest to oldest (although by TTL would be a better sort)
table.sort(nodes, function(a, b) return a.created_at > b.created_at end)
local joined
for _, v in ipairs(nodes) do
if self:join_node(v.cluster_listening_address) then
log.verbose("successfully joined cluster at %s", v.cluster_listening_address)
joined = true
break
else
log.warn("could not join cluster at %s, if the node does not exist "..
"anymore it will be purged automatically", v.cluster_listening_address)
end
end
if not joined then
log.warn("could not join the existing cluster")
end
end
return true
end
function Serf:add_node()
local members, err = self:members()
if not members then return nil, err end
local addr
for _, member in ipairs(members) do
if member.name == self.node_name then
addr = member.addr
break
end
end
if not addr then
return nil, "can't find current member address"
end
local _, err = self.dao.nodes:insert({
name = self.node_name,
cluster_listening_address = pl_stringx.strip(addr)
}, {ttl = self.config.cluster_ttl_on_failure})
if err then return nil, tostring(err) end
return true
end
function Serf:event(t_payload)
local payload, err = cjson.encode(t_payload)
if not payload then return nil, err end
if #payload > 512 then
-- Serf can't send a payload greater than 512 bytes
return nil, "encoded payload is "..#payload.." and exceeds the limit of 512 bytes!"
end
return self:invoke_signal("event -coalesce=false", " kong '"..payload.."'")
end
return Serf
|
fix(serf) disable error checking because of Serf bug
|
fix(serf) disable error checking because of Serf bug
|
Lua
|
apache-2.0
|
Kong/kong,jerizm/kong,icyxp/kong,ccyphers/kong,li-wl/kong,salazar/kong,beauli/kong,shiprabehera/kong,Kong/kong,akh00/kong,Mashape/kong,jebenexer/kong,Vermeille/kong,Kong/kong
|
d291e1c3f5664d86054736912f671af1bc339235
|
libs/sgi-webuci/root/usr/lib/boa/luci.lua
|
libs/sgi-webuci/root/usr/lib/boa/luci.lua
|
module("luci-plugin", package.seeall)
function normalize(path)
local newpath
while newpath ~= path do
if (newpath) then
path = newpath
end
newpath = string.gsub(path, "/[^/]+/../", "/")
end
return newpath
end
function init(path)
-- NB: path points to ROOT/usr/lib/boa, change it to /usr/lib/lua
root = normalize(path .. '/../../../')
path = normalize(path .. '/../lua/')
package.cpath = path..'?.so;'..package.cpath
package.path = path..'?.lua;'..package.path
require("luci.dispatcher")
require("luci.sgi.webuci")
require("uci")
if (root ~= '/') then
-- Entering dummy mode
uci.set_savedir(root..'/tmp/.uci')
uci.set_confdir(root..'/etc/config')
luci.sys.hostname = function() return "" end
luci.sys.loadavg = function() return 0,0,0,0,0 end
luci.sys.reboot = function() return end
luci.sys.sysinfo = function() return "","","" end
luci.sys.syslog = function() return "" end
luci.sys.net.arptable = function() return {} end
luci.sys.net.devices = function() return {} end
luci.sys.net.routes = function() return {} end
luci.sys.wifi.getiwconfig = function() return {} end
luci.sys.wifi.iwscan = function() return {} end
luci.sys.user.checkpasswd = function() return true end
end
end
function prepare_req(uri)
luci.dispatcher.createindex()
env = {}
env.REQUEST_URI = uri
-- TODO: setting luci-plugin.reload = true allows this function to trigger a context reload
end
function handle_req(context)
env.SERVER_PROTOCOL = context.server_proto
env.REMOTE_ADDR = context.remote_addr
env.REQUEST_METHOD = context.request_method
env.PATH_INFO = context.uri
env.REMOTE_PORT = context.remote_port
env.SERVER_ADDR = context.server_addr
env.SCRIPT_NAME = env.REQUEST_URI:sub(1, #env.REQUEST_URI - #env.PATH_INFO)
luci.sgi.webuci.initenv(env, vars)
luci.dispatcher.httpdispatch()
end
|
module("luci-plugin", package.seeall)
function normalize(path)
local newpath
while newpath ~= path do
if (newpath) then
path = newpath
end
newpath = string.gsub(path, "/[^/]+/../", "/")
end
return newpath
end
function init(path)
-- NB: path points to ROOT/usr/lib/boa, change it to /usr/lib/lua
root = normalize(path .. '/../../../')
path = normalize(path .. '/../lua/')
package.cpath = path..'?.so;'..package.cpath
package.path = path..'?.lua;'..package.path
require("luci.dispatcher")
require("luci.sgi.webuci")
require("uci")
if (root ~= '/') then
-- Entering dummy mode
uci.set_savedir(root..'/tmp/.uci')
uci.set_confdir(root..'/etc/config')
luci.sys.hostname = function() return "" end
luci.sys.loadavg = function() return 0,0,0,0,0 end
luci.sys.reboot = function() return end
luci.sys.sysinfo = function() return "","","" end
luci.sys.syslog = function() return "" end
luci.sys.net.arptable = function() return {} end
luci.sys.net.devices = function() return {} end
luci.sys.net.routes = function() return {} end
luci.sys.wifi.getiwconfig = function() return {} end
luci.sys.wifi.iwscan = function() return {} end
luci.sys.user.checkpasswd = function() return true end
luci.http.basic_auth = function() return true end
end
end
function prepare_req(uri)
luci.dispatcher.createindex()
env = {}
env.REQUEST_URI = uri
-- TODO: setting luci-plugin.reload = true allows this function to trigger a context reload
end
function handle_req(context)
env.SERVER_PROTOCOL = context.server_proto
env.REMOTE_ADDR = context.remote_addr
env.REQUEST_METHOD = context.request_method
env.PATH_INFO = context.uri
env.REMOTE_PORT = context.remote_port
env.SERVER_ADDR = context.server_addr
env.SCRIPT_NAME = env.REQUEST_URI:sub(1, #env.REQUEST_URI - #env.PATH_INFO)
luci.sgi.webuci.initenv(env, vars)
luci.dispatcher.httpdispatch()
end
|
* Fixed host builds
|
* Fixed host builds
|
Lua
|
apache-2.0
|
tobiaswaldvogel/luci,jlopenwrtluci/luci,ollie27/openwrt_luci,shangjiyu/luci-with-extra,rogerpueyo/luci,oneru/luci,opentechinstitute/luci,slayerrensky/luci,palmettos/test,artynet/luci,maxrio/luci981213,Hostle/luci,zhaoxx063/luci,tcatm/luci,oneru/luci,slayerrensky/luci,fkooman/luci,Hostle/openwrt-luci-multi-user,MinFu/luci,981213/luci-1,cappiewu/luci,oneru/luci,tobiaswaldvogel/luci,Hostle/luci,ff94315/luci-1,shangjiyu/luci-with-extra,teslamint/luci,lcf258/openwrtcn,RuiChen1113/luci,remakeelectric/luci,aircross/OpenWrt-Firefly-LuCI,Hostle/openwrt-luci-multi-user,deepak78/new-luci,palmettos/test,dwmw2/luci,tobiaswaldvogel/luci,teslamint/luci,artynet/luci,teslamint/luci,keyidadi/luci,cshore/luci,RuiChen1113/luci,ReclaimYourPrivacy/cloak-luci,palmettos/test,david-xiao/luci,Wedmer/luci,thesabbir/luci,oneru/luci,dwmw2/luci,keyidadi/luci,palmettos/cnLuCI,LuttyYang/luci,nwf/openwrt-luci,hnyman/luci,tcatm/luci,Noltari/luci,florian-shellfire/luci,bittorf/luci,ff94315/luci-1,openwrt-es/openwrt-luci,ollie27/openwrt_luci,kuoruan/lede-luci,lcf258/openwrtcn,keyidadi/luci,openwrt/luci,obsy/luci,Sakura-Winkey/LuCI,bright-things/ionic-luci,jchuang1977/luci-1,981213/luci-1,schidler/ionic-luci,aa65535/luci,male-puppies/luci,cshore-firmware/openwrt-luci,keyidadi/luci,opentechinstitute/luci,jchuang1977/luci-1,bright-things/ionic-luci,aa65535/luci,Kyklas/luci-proto-hso,tcatm/luci,NeoRaider/luci,MinFu/luci,NeoRaider/luci,schidler/ionic-luci,opentechinstitute/luci,chris5560/openwrt-luci,Noltari/luci,rogerpueyo/luci,schidler/ionic-luci,jchuang1977/luci-1,aa65535/luci,lcf258/openwrtcn,lbthomsen/openwrt-luci,bittorf/luci,palmettos/cnLuCI,openwrt-es/openwrt-luci,kuoruan/luci,slayerrensky/luci,openwrt/luci,kuoruan/lede-luci,ollie27/openwrt_luci,deepak78/new-luci,mumuqz/luci,MinFu/luci,urueedi/luci,cshore/luci,remakeelectric/luci,palmettos/cnLuCI,jorgifumi/luci,aircross/OpenWrt-Firefly-LuCI,taiha/luci,david-xiao/luci,dwmw2/luci,sujeet14108/luci,dismantl/luci-0.12,palmettos/cnLuCI,lcf258/openwrtcn,chris5560/openwrt-luci,MinFu/luci,lbthomsen/openwrt-luci,joaofvieira/luci,jorgifumi/luci,obsy/luci,RuiChen1113/luci,LuttyYang/luci,fkooman/luci,aircross/OpenWrt-Firefly-LuCI,harveyhu2012/luci,Hostle/luci,marcel-sch/luci,harveyhu2012/luci,david-xiao/luci,981213/luci-1,ollie27/openwrt_luci,nmav/luci,artynet/luci,bittorf/luci,ff94315/luci-1,david-xiao/luci,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,tobiaswaldvogel/luci,opentechinstitute/luci,Wedmer/luci,RedSnake64/openwrt-luci-packages,MinFu/luci,nmav/luci,thesabbir/luci,Wedmer/luci,daofeng2015/luci,981213/luci-1,palmettos/test,tcatm/luci,cappiewu/luci,joaofvieira/luci,opentechinstitute/luci,ollie27/openwrt_luci,palmettos/test,RedSnake64/openwrt-luci-packages,oyido/luci,Kyklas/luci-proto-hso,rogerpueyo/luci,nmav/luci,forward619/luci,Wedmer/luci,rogerpueyo/luci,marcel-sch/luci,lbthomsen/openwrt-luci,jorgifumi/luci,shangjiyu/luci-with-extra,oyido/luci,daofeng2015/luci,teslamint/luci,forward619/luci,RedSnake64/openwrt-luci-packages,lcf258/openwrtcn,bittorf/luci,cshore-firmware/openwrt-luci,hnyman/luci,Hostle/openwrt-luci-multi-user,obsy/luci,daofeng2015/luci,cshore/luci,forward619/luci,openwrt-es/openwrt-luci,remakeelectric/luci,jorgifumi/luci,kuoruan/luci,db260179/openwrt-bpi-r1-luci,cshore/luci,Sakura-Winkey/LuCI,lbthomsen/openwrt-luci,forward619/luci,male-puppies/luci,Hostle/luci,ollie27/openwrt_luci,david-xiao/luci,teslamint/luci,dwmw2/luci,oyido/luci,deepak78/new-luci,deepak78/new-luci,chris5560/openwrt-luci,urueedi/luci,opentechinstitute/luci,hnyman/luci,LazyZhu/openwrt-luci-trunk-mod,maxrio/luci981213,chris5560/openwrt-luci,fkooman/luci,kuoruan/luci,nmav/luci,nmav/luci,ff94315/luci-1,lcf258/openwrtcn,palmettos/cnLuCI,remakeelectric/luci,LuttyYang/luci,oneru/luci,dismantl/luci-0.12,forward619/luci,981213/luci-1,openwrt/luci,harveyhu2012/luci,LazyZhu/openwrt-luci-trunk-mod,dismantl/luci-0.12,nwf/openwrt-luci,cshore-firmware/openwrt-luci,sujeet14108/luci,Kyklas/luci-proto-hso,Wedmer/luci,florian-shellfire/luci,LazyZhu/openwrt-luci-trunk-mod,cappiewu/luci,ollie27/openwrt_luci,dismantl/luci-0.12,Kyklas/luci-proto-hso,jorgifumi/luci,Hostle/luci,jchuang1977/luci-1,LazyZhu/openwrt-luci-trunk-mod,mumuqz/luci,LazyZhu/openwrt-luci-trunk-mod,rogerpueyo/luci,NeoRaider/luci,marcel-sch/luci,marcel-sch/luci,lcf258/openwrtcn,thess/OpenWrt-luci,LuttyYang/luci,nmav/luci,kuoruan/luci,openwrt/luci,db260179/openwrt-bpi-r1-luci,schidler/ionic-luci,mumuqz/luci,aa65535/luci,aa65535/luci,thess/OpenWrt-luci,maxrio/luci981213,kuoruan/luci,marcel-sch/luci,tobiaswaldvogel/luci,cappiewu/luci,florian-shellfire/luci,slayerrensky/luci,artynet/luci,LazyZhu/openwrt-luci-trunk-mod,artynet/luci,cshore-firmware/openwrt-luci,RuiChen1113/luci,male-puppies/luci,cappiewu/luci,tcatm/luci,bright-things/ionic-luci,cshore-firmware/openwrt-luci,wongsyrone/luci-1,MinFu/luci,lcf258/openwrtcn,openwrt-es/openwrt-luci,hnyman/luci,thesabbir/luci,mumuqz/luci,kuoruan/lede-luci,zhaoxx063/luci,shangjiyu/luci-with-extra,oyido/luci,MinFu/luci,RedSnake64/openwrt-luci-packages,teslamint/luci,palmettos/cnLuCI,deepak78/new-luci,ReclaimYourPrivacy/cloak-luci,urueedi/luci,male-puppies/luci,keyidadi/luci,kuoruan/lede-luci,Sakura-Winkey/LuCI,wongsyrone/luci-1,bittorf/luci,Sakura-Winkey/LuCI,nwf/openwrt-luci,daofeng2015/luci,dismantl/luci-0.12,obsy/luci,cappiewu/luci,thesabbir/luci,maxrio/luci981213,shangjiyu/luci-with-extra,florian-shellfire/luci,harveyhu2012/luci,slayerrensky/luci,aircross/OpenWrt-Firefly-LuCI,jorgifumi/luci,urueedi/luci,ff94315/luci-1,openwrt-es/openwrt-luci,keyidadi/luci,Hostle/luci,thesabbir/luci,RedSnake64/openwrt-luci-packages,wongsyrone/luci-1,jlopenwrtluci/luci,maxrio/luci981213,obsy/luci,bright-things/ionic-luci,taiha/luci,jlopenwrtluci/luci,ReclaimYourPrivacy/cloak-luci,Noltari/luci,harveyhu2012/luci,oyido/luci,Wedmer/luci,nmav/luci,male-puppies/luci,Noltari/luci,taiha/luci,zhaoxx063/luci,oneru/luci,NeoRaider/luci,openwrt/luci,thess/OpenWrt-luci,dismantl/luci-0.12,NeoRaider/luci,slayerrensky/luci,thess/OpenWrt-luci,Hostle/luci,ReclaimYourPrivacy/cloak-luci,keyidadi/luci,deepak78/new-luci,cshore/luci,kuoruan/lede-luci,981213/luci-1,ff94315/luci-1,forward619/luci,fkooman/luci,urueedi/luci,fkooman/luci,bright-things/ionic-luci,LuttyYang/luci,oyido/luci,urueedi/luci,ff94315/luci-1,Noltari/luci,joaofvieira/luci,Kyklas/luci-proto-hso,opentechinstitute/luci,oyido/luci,taiha/luci,cappiewu/luci,david-xiao/luci,aa65535/luci,db260179/openwrt-bpi-r1-luci,kuoruan/luci,schidler/ionic-luci,bright-things/ionic-luci,dwmw2/luci,obsy/luci,slayerrensky/luci,aircross/OpenWrt-Firefly-LuCI,rogerpueyo/luci,Kyklas/luci-proto-hso,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,palmettos/cnLuCI,artynet/luci,kuoruan/lede-luci,thesabbir/luci,jchuang1977/luci-1,daofeng2015/luci,RuiChen1113/luci,zhaoxx063/luci,remakeelectric/luci,oyido/luci,thess/OpenWrt-luci,david-xiao/luci,joaofvieira/luci,jorgifumi/luci,nwf/openwrt-luci,keyidadi/luci,Hostle/openwrt-luci-multi-user,chris5560/openwrt-luci,kuoruan/luci,sujeet14108/luci,chris5560/openwrt-luci,remakeelectric/luci,LuttyYang/luci,bittorf/luci,RuiChen1113/luci,joaofvieira/luci,dismantl/luci-0.12,openwrt/luci,bittorf/luci,jchuang1977/luci-1,ReclaimYourPrivacy/cloak-luci,zhaoxx063/luci,bright-things/ionic-luci,sujeet14108/luci,tcatm/luci,florian-shellfire/luci,daofeng2015/luci,artynet/luci,mumuqz/luci,marcel-sch/luci,wongsyrone/luci-1,lcf258/openwrtcn,forward619/luci,dwmw2/luci,forward619/luci,harveyhu2012/luci,palmettos/test,oneru/luci,thesabbir/luci,schidler/ionic-luci,openwrt/luci,db260179/openwrt-bpi-r1-luci,sujeet14108/luci,aircross/OpenWrt-Firefly-LuCI,LazyZhu/openwrt-luci-trunk-mod,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,NeoRaider/luci,chris5560/openwrt-luci,Hostle/openwrt-luci-multi-user,opentechinstitute/luci,david-xiao/luci,florian-shellfire/luci,aa65535/luci,ReclaimYourPrivacy/cloak-luci,palmettos/test,deepak78/new-luci,nwf/openwrt-luci,hnyman/luci,deepak78/new-luci,tobiaswaldvogel/luci,wongsyrone/luci-1,jchuang1977/luci-1,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,nwf/openwrt-luci,db260179/openwrt-bpi-r1-luci,hnyman/luci,Wedmer/luci,ollie27/openwrt_luci,schidler/ionic-luci,jlopenwrtluci/luci,shangjiyu/luci-with-extra,sujeet14108/luci,Sakura-Winkey/LuCI,male-puppies/luci,joaofvieira/luci,MinFu/luci,Hostle/openwrt-luci-multi-user,urueedi/luci,981213/luci-1,kuoruan/lede-luci,harveyhu2012/luci,fkooman/luci,dwmw2/luci,thesabbir/luci,NeoRaider/luci,taiha/luci,ff94315/luci-1,Hostle/openwrt-luci-multi-user,NeoRaider/luci,taiha/luci,zhaoxx063/luci,shangjiyu/luci-with-extra,Noltari/luci,obsy/luci,Noltari/luci,RedSnake64/openwrt-luci-packages,rogerpueyo/luci,maxrio/luci981213,tcatm/luci,openwrt-es/openwrt-luci,RuiChen1113/luci,palmettos/test,schidler/ionic-luci,bittorf/luci,mumuqz/luci,tcatm/luci,kuoruan/lede-luci,fkooman/luci,Hostle/luci,marcel-sch/luci,thess/OpenWrt-luci,jorgifumi/luci,ReclaimYourPrivacy/cloak-luci,florian-shellfire/luci,wongsyrone/luci-1,thess/OpenWrt-luci,mumuqz/luci,cappiewu/luci,maxrio/luci981213,palmettos/cnLuCI,taiha/luci,jlopenwrtluci/luci,jlopenwrtluci/luci,oneru/luci,florian-shellfire/luci,jchuang1977/luci-1,jlopenwrtluci/luci,remakeelectric/luci,sujeet14108/luci,daofeng2015/luci,cshore-firmware/openwrt-luci,sujeet14108/luci,nmav/luci,lbthomsen/openwrt-luci,joaofvieira/luci,Noltari/luci,Sakura-Winkey/LuCI,thess/OpenWrt-luci,remakeelectric/luci,openwrt-es/openwrt-luci,wongsyrone/luci-1,Sakura-Winkey/LuCI,hnyman/luci,marcel-sch/luci,cshore/luci,dwmw2/luci,taiha/luci,daofeng2015/luci,RuiChen1113/luci,wongsyrone/luci-1,zhaoxx063/luci,cshore/luci,nwf/openwrt-luci,kuoruan/luci,aircross/OpenWrt-Firefly-LuCI,Sakura-Winkey/LuCI,nwf/openwrt-luci,shangjiyu/luci-with-extra,lcf258/openwrtcn,ReclaimYourPrivacy/cloak-luci,aa65535/luci,openwrt/luci,hnyman/luci,male-puppies/luci,jlopenwrtluci/luci,slayerrensky/luci,maxrio/luci981213,RedSnake64/openwrt-luci-packages,Noltari/luci,chris5560/openwrt-luci,cshore-firmware/openwrt-luci,openwrt-es/openwrt-luci,LuttyYang/luci,bright-things/ionic-luci,teslamint/luci,mumuqz/luci,Kyklas/luci-proto-hso,artynet/luci,artynet/luci,cshore/luci,rogerpueyo/luci,fkooman/luci,nmav/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,Wedmer/luci,Hostle/openwrt-luci-multi-user,teslamint/luci,male-puppies/luci,LuttyYang/luci,zhaoxx063/luci,obsy/luci,joaofvieira/luci
|
8bcd11faa79bdbc6b23a18b9540cb39b5aec2ba6
|
scripts/OvalePriest.lua
|
scripts/OvalePriest.lua
|
local _, Ovale = ...
local OvaleScripts = Ovale.OvaleScripts
do
local name = "Ovale"
local desc = "[5.2] Ovale: Shadow"
local code = [[
Define(berserking 26297)
SpellInfo(berserking duration=10 cd=180 )
SpellAddBuff(berserking berserking=1)
Define(cascade 120785)
SpellInfo(cascade duration=0.1 )
Define(devouring_plague 2944)
SpellInfo(devouring_plague duration=6 tick=1 shadoworbs=1 haste=spell )
SpellAddTargetDebuff(devouring_plague devouring_plague=1)
Define(dispersion 47585)
SpellInfo(dispersion duration=6 cd=120 )
SpellAddBuff(dispersion dispersion=1)
Define(divine_insight_shadow 124430)
SpellInfo(divine_insight_shadow duration=12 )
SpellAddBuff(divine_insight_shadow divine_insight_shadow=1)
Define(divine_star 110744)
SpellInfo(divine_star cd=15 )
Define(halo 120517)
SpellInfo(halo duration=5.5 cd=40 )
Define(inner_fire 588)
SpellAddBuff(inner_fire inner_fire=1)
Define(inner_will 73413)
SpellAddBuff(inner_will inner_will=1)
Define(mind_blast 8092)
SpellInfo(mind_blast shadoworbs=-1 cd=8 test)
Define(mind_flay 15407)
SpellInfo(mind_flay duration=3 canStopChannelling=1 )
SpellAddTargetDebuff(mind_flay mind_flay=1)
Define(mind_flay_insanity 129197)
SpellInfo(mind_flay_insanity duration=3 tick=1 haste=spell canStopChannelling=1 )
SpellAddTargetDebuff(mind_flay_insanity mind_flay_insanity=1)
Define(mind_sear 48045)
SpellInfo(mind_sear duration=5 canStopChannelling=1 )
SpellAddBuff(mind_sear mind_sear=1)
Define(mind_spike 73510)
Define(mindbender 123040)
SpellInfo(mindbender duration=15 cd=60 )
Define(power_infusion 10060)
SpellInfo(power_infusion duration=20 cd=120 )
SpellAddBuff(power_infusion power_infusion=1)
Define(power_word_fortitude 21562)
SpellInfo(power_word_fortitude duration=3600 )
SpellAddBuff(power_word_fortitude power_word_fortitude=1)
Define(shadow_word_death 32379)
SpellInfo(shadow_word_death cd=8 )
Define(shadow_word_pain 589)
SpellInfo(shadow_word_pain duration=18 tick=3 haste=spell )
SpellAddTargetDebuff(shadow_word_pain shadow_word_pain=1)
Define(shadowfiend 34433)
SpellInfo(shadowfiend duration=12 cd=180 )
Define(shadowform 15473)
SpellAddBuff(shadowform shadowform=1)
Define(surge_of_darkness 87160)
SpellInfo(surge_of_darkness duration=10 )
SpellAddBuff(surge_of_darkness surge_of_darkness=1)
Define(vampiric_embrace 15286)
SpellInfo(vampiric_embrace duration=15 cd=180 )
SpellAddBuff(vampiric_embrace vampiric_embrace=1)
Define(vampiric_touch 34914)
SpellInfo(vampiric_touch duration=15 tick=3 haste=spell )
SpellAddTargetDebuff(vampiric_touch vampiric_touch=1)
Define(cascade_talent 16)
Define(divine_star_talent 17)
Define(halo_talent 18)
Define(mindbender_talent 8)
Define(power_infusion_talent 14)
AddCheckBox(showwait L(showwait) default)
AddIcon mastery=3 help=main
{
if not InCombat()
{
if not BuffPresent(stamina any=1) Spell(power_word_fortitude)
if BuffExpires(inner_fire) and BuffExpires(inner_will) Spell(inner_fire)
if BuffExpires(shadowform) Spell(shadowform)
}
if BuffExpires(shadowform) Spell(shadowform)
if TalentPoints(mindbender_talent) Spell(mindbender)
if ShadowOrbs() ==3 and {SpellCooldown(mind_blast) <1.5 or target.HealthPercent() <20 and SpellCooldown(shadow_word_death) <1.5 } Spell(devouring_plague)
if target.HealthPercent(less 20) Spell(shadow_word_death)
if SpellCooldown(mind_blast) Spell(mind_blast)
if target.TicksRemain(devouring_plague) ==1 Spell(mind_flay_insanity)
Spell(mind_flay_insanity)
if not target.DebuffPresent(shadow_word_pain) Spell(shadow_word_pain)
if target.DebuffRemains(vampiric_touch) <CastTime(vampiric_touch) Spell(vampiric_touch)
if BuffStacks(surge_of_darkness) ==2 Spell(mind_spike)
if target.TicksRemain(shadow_word_pain) <=1 Spell(shadow_word_pain)
if target.DebuffRemains(vampiric_touch) <CastTime(vampiric_touch) +TickTime(vampiric_touch) Spell(vampiric_touch)
if ShadowOrbs() ==3 and target.TicksRemain(devouring_plague) <=1 Spell(devouring_plague)
if TalentPoints(halo_talent) Spell(halo)
if TalentPoints(cascade_talent) Spell(cascade)
if target.HealthPercent() <20 and SpellCooldown(shadow_word_death) <0.5 if CheckBoxOn(showwait) Texture(Spell_nature_timestop)
if SpellCooldown(mind_blast) <0.5 if CheckBoxOn(showwait) Texture(Spell_nature_timestop)
if BuffStacks(surge_of_darkness) Spell(mind_spike)
Spell(mind_flay)
}
AddIcon mastery=3 help=offgcd
{
if TalentPoints(divine_star_talent) Spell(divine_star)
}
AddIcon mastery=3 help=moving
{
if target.HealthPercent(less 20) Spell(shadow_word_death)
if BuffStacks(divine_insight_shadow) and SpellCooldown(mind_blast) Spell(mind_blast)
Spell(shadow_word_pain)
}
AddIcon mastery=3 help=aoe
{
Spell(mind_sear)
}
AddIcon mastery=3 help=cd
{
{ Item(Trinket0Slot usable=1) Item(Trinket1Slot usable=1) }
if not TalentPoints(mindbender_talent) Spell(shadowfiend)
if TalentPoints(power_infusion_talent) Spell(power_infusion)
Spell(berserking)
if ShadowOrbs() ==3 and Health() <=40 Spell(vampiric_embrace)
Spell(dispersion)
}
]]
OvaleScripts:RegisterScript("PRIEST", name, desc, code)
end
|
local _, Ovale = ...
local OvaleScripts = Ovale.OvaleScripts
do
local name = "Ovale"
local desc = "[5.2] Ovale: Shadow"
local code = [[
Define(berserking 26297)
SpellInfo(berserking duration=10 cd=180 )
SpellAddBuff(berserking berserking=1)
Define(cascade 120785)
SpellInfo(cascade duration=0.1 )
Define(devouring_plague 2944)
SpellInfo(devouring_plague duration=6 tick=1 shadoworbs=1 haste=spell )
SpellAddTargetDebuff(devouring_plague devouring_plague=1)
Define(dispersion 47585)
SpellInfo(dispersion duration=6 cd=120 )
SpellAddBuff(dispersion dispersion=1)
Define(divine_insight_shadow 124430)
SpellInfo(divine_insight_shadow duration=12 )
SpellAddBuff(divine_insight_shadow divine_insight_shadow=1)
Define(divine_star 110744)
SpellInfo(divine_star cd=15 )
Define(halo 120517)
SpellInfo(halo duration=5.5 cd=40 )
Define(inner_fire 588)
SpellAddBuff(inner_fire inner_fire=1)
Define(inner_will 73413)
SpellAddBuff(inner_will inner_will=1)
Define(mind_blast 8092)
SpellInfo(mind_blast shadoworbs=-1 cd=8)
Define(mind_flay 15407)
SpellInfo(mind_flay duration=3 canStopChannelling=1 )
SpellAddTargetDebuff(mind_flay mind_flay=1)
Define(mind_flay_insanity 129197)
SpellInfo(mind_flay_insanity duration=3 tick=1 haste=spell canStopChannelling=1 )
SpellAddTargetDebuff(mind_flay_insanity mind_flay_insanity=1)
Define(mind_sear 48045)
SpellInfo(mind_sear duration=5 canStopChannelling=1 )
SpellAddBuff(mind_sear mind_sear=1)
Define(mind_spike 73510)
Define(mindbender 123040)
SpellInfo(mindbender duration=15 cd=60 )
Define(power_infusion 10060)
SpellInfo(power_infusion duration=20 cd=120 )
SpellAddBuff(power_infusion power_infusion=1)
Define(power_word_fortitude 21562)
SpellInfo(power_word_fortitude duration=3600 )
SpellAddBuff(power_word_fortitude power_word_fortitude=1)
Define(shadow_word_death 32379)
SpellInfo(shadow_word_death cd=8 )
Define(shadow_word_pain 589)
SpellInfo(shadow_word_pain duration=18 tick=3 haste=spell )
SpellAddTargetDebuff(shadow_word_pain shadow_word_pain=1)
Define(shadowfiend 34433)
SpellInfo(shadowfiend duration=12 cd=180 )
Define(shadowform 15473)
SpellAddBuff(shadowform shadowform=1)
Define(surge_of_darkness 87160)
SpellInfo(surge_of_darkness duration=10 )
SpellAddBuff(surge_of_darkness surge_of_darkness=1)
Define(vampiric_embrace 15286)
SpellInfo(vampiric_embrace duration=15 cd=180 )
SpellAddBuff(vampiric_embrace vampiric_embrace=1)
Define(vampiric_touch 34914)
SpellInfo(vampiric_touch duration=15 tick=3 haste=spell )
SpellAddTargetDebuff(vampiric_touch vampiric_touch=1)
Define(cascade_talent 16)
Define(divine_star_talent 17)
Define(halo_talent 18)
Define(mindbender_talent 8)
Define(power_infusion_talent 14)
AddCheckBox(showwait L(showwait) default)
AddIcon mastery=3 help=main
{
if not InCombat()
{
if not BuffPresent(stamina any=1) Spell(power_word_fortitude)
if BuffExpires(inner_fire) and BuffExpires(inner_will) Spell(inner_fire)
if BuffExpires(shadowform) Spell(shadowform)
}
if BuffExpires(shadowform) Spell(shadowform)
if TalentPoints(mindbender_talent) Spell(mindbender)
if ShadowOrbs() ==3 and {SpellCooldown(mind_blast) <1.5 or target.HealthPercent() <20 and SpellCooldown(shadow_word_death) <1.5 } Spell(devouring_plague)
if target.HealthPercent(less 20) Spell(shadow_word_death)
Spell(mind_blast)
if target.TicksRemain(devouring_plague) ==1 Spell(mind_flay_insanity)
Spell(mind_flay_insanity)
if not target.DebuffPresent(shadow_word_pain) Spell(shadow_word_pain)
if target.DebuffRemains(vampiric_touch) <CastTime(vampiric_touch) Spell(vampiric_touch)
if BuffStacks(surge_of_darkness) ==2 Spell(mind_spike)
if target.TicksRemain(shadow_word_pain) <=1 Spell(shadow_word_pain)
if target.DebuffRemains(vampiric_touch) <CastTime(vampiric_touch) +TickTime(vampiric_touch) Spell(vampiric_touch)
if ShadowOrbs() ==3 and target.TicksRemain(devouring_plague) <=1 Spell(devouring_plague)
if TalentPoints(halo_talent) Spell(halo)
if TalentPoints(cascade_talent) Spell(cascade)
if target.HealthPercent() <20 and SpellCooldown(shadow_word_death) <0.5 if CheckBoxOn(showwait) Texture(Spell_nature_timestop)
if SpellCooldown(mind_blast) <0.5 if CheckBoxOn(showwait) Texture(Spell_nature_timestop)
if BuffStacks(surge_of_darkness) Spell(mind_spike)
Spell(mind_flay)
}
AddIcon mastery=3 help=offgcd
{
if TalentPoints(divine_star_talent) Spell(divine_star)
}
AddIcon mastery=3 help=moving
{
if target.HealthPercent(less 20) Spell(shadow_word_death)
if BuffStacks(divine_insight_shadow) and SpellCooldown(mind_blast) Spell(mind_blast)
Spell(shadow_word_pain)
}
AddIcon mastery=3 help=aoe
{
Spell(mind_sear)
}
AddIcon mastery=3 help=cd
{
{ Item(Trinket0Slot usable=1) Item(Trinket1Slot usable=1) }
if not TalentPoints(mindbender_talent) Spell(shadowfiend)
if TalentPoints(power_infusion_talent) Spell(power_infusion)
Spell(berserking)
if ShadowOrbs() ==3 and Health() <=40 Spell(vampiric_embrace)
Spell(dispersion)
}
]]
OvaleScripts:RegisterScript("PRIEST", name, desc, code)
end
|
Fix error with using Mind Blast in default priest script.
|
Fix error with using Mind Blast in default priest script.
- Remove spurious "test" parameter to SpellInfo that shouldn't be there.
- If a condition that returns a number is used as a boolean, then boolean
evaluation rules dictate that non-zero is true and zero is false. Fix:
if SpellCooldown(mind_blast) Spell(mind_blast)
was probably intended to be:
if SpellCooldown(mind_blast) == 0 Spell(mind_blast)
which is simply just:
Spell(mind_blast)
git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@1133 d5049fe3-3747-40f7-a4b5-f36d6801af5f
|
Lua
|
mit
|
eXhausted/Ovale,ultijlam/ovale,eXhausted/Ovale,eXhausted/Ovale,ultijlam/ovale,Xeltor/ovale,ultijlam/ovale
|
5da324dcf821676f02735e4df5caa805ad6d2f9a
|
build/LLVM.lua
|
build/LLVM.lua
|
-- Setup the LLVM dependency directories
LLVMRootDir = depsdir .. "/llvm/"
local LLVMDirPerConfiguration = false
local LLVMRootDirDebug = ""
local LLVMRootDirRelease = ""
require "scripts/LLVM"
function SearchLLVM()
LLVMRootDirDebug = basedir .. "/scripts/" .. get_llvm_package_name(nil, "Debug")
LLVMRootDirRelease = basedir .. "/scripts/" .. get_llvm_package_name()
if os.isdir(LLVMRootDirDebug) or os.isdir(LLVMRootDirRelease) then
LLVMDirPerConfiguration = true
print("Using debug LLVM build: " .. LLVMRootDirDebug)
print("Using release LLVM build: " .. LLVMRootDirRelease)
elseif os.isdir(LLVMRootDir) then
print("Using LLVM build: " .. LLVMRootDir)
else
error("Error finding an LLVM build")
end
end
function get_llvm_build_dir()
return path.join(LLVMRootDir, "build")
end
function SetupLLVMIncludes()
local c = filter()
if LLVMDirPerConfiguration then
filter { "configurations:Debug" }
includedirs
{
path.join(LLVMRootDirDebug, "include"),
path.join(LLVMRootDirDebug, "tools/clang/include"),
path.join(LLVMRootDirDebug, "tools/clang/lib"),
path.join(LLVMRootDirDebug, "build/include"),
path.join(LLVMRootDirDebug, "build/tools/clang/include"),
}
filter { "configurations:Release" }
includedirs
{
path.join(LLVMRootDirRelease, "include"),
path.join(LLVMRootDirRelease, "tools/clang/include"),
path.join(LLVMRootDirRelease, "tools/clang/lib"),
path.join(LLVMRootDirRelease, "build/include"),
path.join(LLVMRootDirRelease, "build/tools/clang/include"),
}
else
local LLVMBuildDir = get_llvm_build_dir()
includedirs
{
path.join(LLVMRootDir, "include"),
path.join(LLVMRootDir, "tools/clang/include"),
path.join(LLVMRootDir, "tools/clang/lib"),
path.join(LLVMBuildDir, "include"),
path.join(LLVMBuildDir, "tools/clang/include"),
}
end
filter(c)
end
function CopyClangIncludes()
local clangBuiltinIncludeDir = path.join(LLVMRootDir, "lib")
if LLVMDirPerConfiguration then
local clangBuiltinDebug = path.join(LLVMRootDirDebug, "lib")
local clangBuiltinRelease = path.join(LLVMRootDirRelease, "lib")
if os.isdir(path.join(clangBuiltinDebug, "clang")) then
clangBuiltinIncludeDir = clangBuiltinDebug
end
if os.isdir(path.join(clangBuiltinRelease, "clang")) then
clangBuiltinIncludeDir = clangBuiltinRelease
end
end
if os.isdir(clangBuiltinIncludeDir) then
postbuildcommands { string.format("{COPY} %s %%{cfg.buildtarget.directory}", clangBuiltinIncludeDir) }
end
end
function SetupLLVMLibs()
local c = filter()
filter { "action:not vs*" }
defines { "__STDC_CONSTANT_MACROS", "__STDC_LIMIT_MACROS" }
filter { "system:macosx" }
links { "c++", "curses", "pthread", "z" }
filter { "action:vs*" }
links { "version" }
filter {}
if LLVMDirPerConfiguration then
filter { "configurations:Debug" }
libdirs { path.join(LLVMRootDirDebug, "build/lib") }
filter { "configurations:Release" }
libdirs { path.join(LLVMRootDirRelease, "build/lib") }
else
local LLVMBuildDir = get_llvm_build_dir()
libdirs { path.join(LLVMBuildDir, "lib") }
filter { "configurations:Debug", "action:vs*" }
libdirs { path.join(LLVMBuildDir, "Debug/lib") }
filter { "configurations:Release", "actoin:vs*" }
libdirs { path.join(LLVMBuildDir, "RelWithDebInfo/lib") }
end
filter {}
links
{
"clangFrontend",
"clangDriver",
"clangSerialization",
"clangCodeGen",
"clangParse",
"clangSema",
"clangAnalysis",
"clangEdit",
"clangAST",
"clangLex",
"clangBasic",
"clangIndex",
"LLVMLinker",
"LLVMipo",
"LLVMVectorize",
"LLVMBinaryFormat",
"LLVMBitWriter",
"LLVMIRReader",
"LLVMAsmParser",
"LLVMOption",
"LLVMInstrumentation",
"LLVMProfileData",
"LLVMX86AsmParser",
"LLVMX86Desc",
"LLVMObject",
"LLVMMCParser",
"LLVMBitReader",
"LLVMX86Info",
"LLVMX86AsmPrinter",
"LLVMX86Utils",
"LLVMCodeGen",
"LLVMScalarOpts",
"LLVMInstCombine",
"LLVMTransformUtils",
"LLVMAnalysis",
"LLVMTarget",
"LLVMMC",
"LLVMCoverage",
"LLVMCore",
"LLVMSupport",
}
filter(c)
end
|
-- Setup the LLVM dependency directories
LLVMRootDir = depsdir .. "/llvm/"
local LLVMDirPerConfiguration = false
local LLVMRootDirDebug = ""
local LLVMRootDirRelease = ""
require "scripts/LLVM"
function SearchLLVM()
LLVMRootDirDebug = basedir .. "/scripts/" .. get_llvm_package_name(nil, "Debug")
LLVMRootDirRelease = basedir .. "/scripts/" .. get_llvm_package_name()
if os.isdir(LLVMRootDirDebug) or os.isdir(LLVMRootDirRelease) then
LLVMDirPerConfiguration = true
print("Using debug LLVM build: " .. LLVMRootDirDebug)
print("Using release LLVM build: " .. LLVMRootDirRelease)
elseif os.isdir(LLVMRootDir) then
print("Using LLVM build: " .. LLVMRootDir)
else
error("Error finding an LLVM build")
end
end
function get_llvm_build_dir()
return path.join(LLVMRootDir, "build")
end
function SetupLLVMIncludes()
local c = filter()
if LLVMDirPerConfiguration then
filter { "configurations:Debug" }
includedirs
{
path.join(LLVMRootDirDebug, "include"),
path.join(LLVMRootDirDebug, "tools/clang/include"),
path.join(LLVMRootDirDebug, "tools/clang/lib"),
path.join(LLVMRootDirDebug, "build/include"),
path.join(LLVMRootDirDebug, "build/tools/clang/include"),
}
filter { "configurations:Release" }
includedirs
{
path.join(LLVMRootDirRelease, "include"),
path.join(LLVMRootDirRelease, "tools/clang/include"),
path.join(LLVMRootDirRelease, "tools/clang/lib"),
path.join(LLVMRootDirRelease, "build/include"),
path.join(LLVMRootDirRelease, "build/tools/clang/include"),
}
else
local LLVMBuildDir = get_llvm_build_dir()
includedirs
{
path.join(LLVMRootDir, "include"),
path.join(LLVMRootDir, "tools/clang/include"),
path.join(LLVMRootDir, "tools/clang/lib"),
path.join(LLVMBuildDir, "include"),
path.join(LLVMBuildDir, "tools/clang/include"),
}
end
filter(c)
end
function CopyClangIncludes()
local clangBuiltinIncludeDir = path.join(LLVMRootDir, "lib")
if LLVMDirPerConfiguration then
local clangBuiltinDebug = path.join(LLVMRootDirDebug, "lib")
local clangBuiltinRelease = path.join(LLVMRootDirRelease, "lib")
if os.isdir(path.join(clangBuiltinDebug, "clang")) then
clangBuiltinIncludeDir = clangBuiltinDebug
end
if os.isdir(path.join(clangBuiltinRelease, "clang")) then
clangBuiltinIncludeDir = clangBuiltinRelease
end
end
if os.isdir(clangBuiltinIncludeDir) then
postbuildcommands { string.format("{COPY} %s %%{cfg.buildtarget.directory}", clangBuiltinIncludeDir) }
end
end
function SetupLLVMLibs()
local c = filter()
filter { "action:not vs*" }
defines { "__STDC_CONSTANT_MACROS", "__STDC_LIMIT_MACROS" }
filter { "system:macosx" }
links { "c++", "curses", "pthread", "z" }
filter { "action:vs*" }
links { "version" }
filter {}
if LLVMDirPerConfiguration then
filter { "configurations:Debug" }
libdirs { path.join(LLVMRootDirDebug, "build/lib") }
filter { "configurations:Release" }
libdirs { path.join(LLVMRootDirRelease, "build/lib") }
else
local LLVMBuildDir = get_llvm_build_dir()
libdirs { path.join(LLVMBuildDir, "lib") }
filter { "configurations:Debug", "action:vs*" }
libdirs { path.join(LLVMBuildDir, "Debug/lib") }
filter { "configurations:Release", "actoin:vs*" }
libdirs { path.join(LLVMBuildDir, "RelWithDebInfo/lib") }
end
filter {}
links
{
"clangFrontend",
"clangDriver",
"clangSerialization",
"clangCodeGen",
"clangParse",
"clangSema",
"clangAnalysis",
"clangEdit",
"clangAST",
"clangLex",
"clangBasic",
"clangIndex",
"LLVMLinker",
"LLVMipo",
"LLVMVectorize",
"LLVMBitWriter",
"LLVMIRReader",
"LLVMAsmParser",
"LLVMOption",
"LLVMInstrumentation",
"LLVMProfileData",
"LLVMX86AsmParser",
"LLVMX86Desc",
"LLVMObject",
"LLVMMCParser",
"LLVMBitReader",
"LLVMX86Info",
"LLVMX86AsmPrinter",
"LLVMX86Utils",
"LLVMCodeGen",
"LLVMScalarOpts",
"LLVMInstCombine",
"LLVMTransformUtils",
"LLVMAnalysis",
"LLVMTarget",
"LLVMMC",
"LLVMCoverage",
"LLVMCore",
"LLVMSupport",
"LLVMBinaryFormat",
}
filter(c)
end
|
Link LLVM's BinaryFormat library last to fix Linux symbol linkage.
|
Link LLVM's BinaryFormat library last to fix Linux symbol linkage.
|
Lua
|
mit
|
mono/CppSharp,u255436/CppSharp,zillemarco/CppSharp,mono/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,mohtamohit/CppSharp,ktopouzi/CppSharp,ddobrev/CppSharp,mono/CppSharp,mohtamohit/CppSharp,ktopouzi/CppSharp,u255436/CppSharp,ktopouzi/CppSharp,ddobrev/CppSharp,mohtamohit/CppSharp,mono/CppSharp,mohtamohit/CppSharp,u255436/CppSharp,inordertotest/CppSharp,ddobrev/CppSharp,ktopouzi/CppSharp,zillemarco/CppSharp,ktopouzi/CppSharp,inordertotest/CppSharp,mono/CppSharp,inordertotest/CppSharp,inordertotest/CppSharp,mono/CppSharp,zillemarco/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,u255436/CppSharp,ddobrev/CppSharp,zillemarco/CppSharp,inordertotest/CppSharp
|
9f52c61807232da93a1ff899c51be723de14642c
|
lgi/override/Gio.lua
|
lgi/override/Gio.lua
|
------------------------------------------------------------------------------
--
-- lgi Gio override module.
--
-- Copyright (c) 2010, 2011, 2013 Pavel Holejsovsky
-- Licensed under the MIT license:
-- http://www.opensource.org/licenses/mit-license.php
--
------------------------------------------------------------------------------
local select, type, pairs, setmetatable, rawset, unpack =
select, type, pairs, setmetatable, rawset, unpack or table.unpack
local coroutine = require 'coroutine'
local lgi = require 'lgi'
local GLib = lgi.GLib
local GObject = lgi.GObject
local Gio = lgi.Gio
local component = require 'lgi.component'
local core = require 'lgi.core'
local gi = core.gi
-- Create completely new 'Async' pseudoclass, wrapping lgi-specific
-- async helpers.
local async_context = setmetatable({}, { __mode = 'k' })
Gio.Async = setmetatable(
{}, {
__index = function(self, key)
if key == 'io_priority' or key == 'cancellable' then
return (async_context[coroutine.running] or {})[key]
end
end,
__newindex = function(self, key, value)
if key == 'io_priority' or key == 'cancellable' then
(async_context[coroutine.running])[key] = value
else
rawset(self, key, value)
end
end,
})
-- Creates new context for new coroutine and stores it into async_context.
local function register_async(coro, cancellable, io_priority)
local current = async_context[coroutine.running()] or {}
async_context[coro] = {
io_priority = io_priority or current.io_priority or GLib.PRIORITY_DEFAULT,
cancellable = cancellable or current.cancellable,
}
end
function Gio.Async.start(func, cancellable, io_priority)
-- Create coroutine and store context for it.
local coro = coroutine.create(func)
register_async(coro, cancellable, io_priority)
-- Return coroutine starter.
return function(...)
return coroutine.resume(coro, ...)
end
end
function Gio.Async.call(func, cancellable, io_priority)
-- Create mainloop which will create modality.
local loop = GLib.MainLoop()
local results
-- Create coroutine around function wrapper which will invoke
-- target and then terminate the loop.
local coro = coroutine.create(function(...)
(function(...)
results = { n = select('#', ...), ... }
loop:quit()
end)(func(...))
end)
-- Register coroutine.
register_async(coro, cancellable, io_priority)
-- Return starter closure.
return function(...)
-- Spawn it inside idle handler, to avoid hang in case that
-- coroutine finishes during its first resuming.
local args = { n = select('#', ...), ... }
GLib.idle_add(
GLib.PRIORITY_DEFAULT, function()
coroutine.resume(coro, unpack(args, 1, args.n))
end)
-- Spin the loop.
loop:run()
-- Unpack results.
return unpack(results, 1, results.n)
end
end
-- Add 'async_' method handling. Dynamically generates wrapper around
-- xxx_async()/xxx_finish() sequence using currently running
-- coroutine.
local tag_int = gi.GObject.ParamSpecEnum.fields.default_value.typeinfo.tag
local inherited_element = GObject.Object._element
function GObject.Object:_element(object, name)
local element, category = inherited_element(self, object, name)
if element or not object then return element, category end
-- Check, whether we have async_xxx request.
local name_root = name:match('^async_(.+)$')
if name_root then
local async = inherited_element(self, object, name_root .. '_async')
local finish = inherited_element(self, object, name_root .. '_finish')
if async and finish then
element = { name = name_root, in_args = 0,
async = async, finish = finish, }
-- Go through arguments of async method and find indices of
-- io_priority, cancellable and callback args.
for _, param in ipairs(async.params) do
if param['in'] then
element.in_args = element.in_args + 1
if not param['out'] and param.typeinfo then
if param.name == 'io_priority' and
param.typeinfo.tag == tag_int then
element.io_priority = element.in_args
elseif param.name == 'cancellable' and
param.typeinfo.tag == 'interface' then
element.cancellable = element.in_args
end
end
end
end
-- Returns accumulated async call data.
return element, '_async'
end
end
end
function GObject.Object:_access_async(object, element, ...)
if select('#', ...) > 0 then
error(("%s: `%s' not writable"):format(
core.object.query(object, 'repo')._name, name))
end
-- Generate wrapper method calling _async/_finish pair automatically.
return function(...)
-- Check that we are running inside context.
local context = async_context[coroutine.running()]
if not context then
error(("%s.async_%s: called out of async context"):format(
self._name, element.name), 4)
end
-- Create input args, intersperse them with automatic ones.
local args, i, index = {}, 1, 1
for i = 1, element.in_args - 1 do
if i == element.io_priority then
args[i] = context.io_priority
elseif i == element.cancellable then
args[i] = context.cancellable
else
args[i] = select(index, ...)
index = index + 1
end
end
args[element.in_args] = coroutine.running()
element.async(unpack(args, 1, element.in_args))
return element.finish(coroutine.yield())
end
end
-- GOI < 1.30 did not map static factory method into interface
-- namespace. The prominent example of this fault was that
-- Gio.File.new_for_path() had to be accessed as
-- Gio.file_new_for_path(). Create a compatibility layer to mask this
-- flaw.
for _, name in pairs { 'path', 'uri', 'commandline_arg' } do
if not Gio.File['new_for_' .. name] then
Gio.File['new_for_' .. name] = Gio['file_new_for_' .. name]
end
end
-- Older versions of gio did not annotate input stream methods as
-- taking an array. Apply workaround.
-- https://github.com/pavouk/lgi/issues/59
for _, name in pairs { 'read', 'read_all', 'read_async' } do
local raw_read = Gio.InputStream[name]
if gi.Gio.InputStream.methods[name].args[1].typeinfo.tag ~= 'array' then
Gio.InputStream[name] = function(self, buffer, ...)
return raw_read(self, buffer, #buffer, ...)
end
if name == 'read_async' then
raw_finish = Gio.InputStream.read_finish
function Gio.InputStream.async_read(stream, buffer, prio, cancellable)
raw_read(stream, buffer, prio, cancellable, coroutine.running())
return raw_finish(coroutine.yield())
end
end
end
end
|
------------------------------------------------------------------------------
--
-- lgi Gio override module.
--
-- Copyright (c) 2010, 2011, 2013 Pavel Holejsovsky
-- Licensed under the MIT license:
-- http://www.opensource.org/licenses/mit-license.php
--
------------------------------------------------------------------------------
local select, type, pairs, setmetatable, rawset, unpack =
select, type, pairs, setmetatable, rawset, unpack or table.unpack
local coroutine = require 'coroutine'
local lgi = require 'lgi'
local GLib = lgi.GLib
local GObject = lgi.GObject
local Gio = lgi.Gio
local component = require 'lgi.component'
local core = require 'lgi.core'
local gi = core.gi
-- Create completely new 'Async' pseudoclass, wrapping lgi-specific
-- async helpers.
local async_context = setmetatable({}, { __mode = 'k' })
Gio.Async = setmetatable(
{}, {
__index = function(self, key)
if key == 'io_priority' or key == 'cancellable' then
return (async_context[coroutine.running] or {})[key]
end
end,
__newindex = function(self, key, value)
if key == 'io_priority' or key == 'cancellable' then
(async_context[coroutine.running])[key] = value
else
rawset(self, key, value)
end
end,
})
-- Creates new context for new coroutine and stores it into async_context.
local function register_async(coro, cancellable, io_priority)
local current = async_context[coroutine.running()] or {}
async_context[coro] = {
io_priority = io_priority or current.io_priority or GLib.PRIORITY_DEFAULT,
cancellable = cancellable or current.cancellable,
}
end
function Gio.Async.start(func, cancellable, io_priority)
-- Create coroutine and store context for it.
local coro = coroutine.create(func)
register_async(coro, cancellable, io_priority)
-- Return coroutine starter.
return function(...)
return coroutine.resume(coro, ...)
end
end
function Gio.Async.call(func, cancellable, io_priority)
-- Create mainloop which will create modality.
local loop = GLib.MainLoop()
local results
-- Create coroutine around function wrapper which will invoke
-- target and then terminate the loop.
local coro = coroutine.create(function(...)
(function(...)
results = { n = select('#', ...), ... }
loop:quit()
end)(func(...))
end)
-- Register coroutine.
register_async(coro, cancellable, io_priority)
-- Return starter closure.
return function(...)
-- Spawn it inside idle handler, to avoid hang in case that
-- coroutine finishes during its first resuming.
local args = { n = select('#', ...), ... }
GLib.idle_add(
GLib.PRIORITY_DEFAULT, function()
coroutine.resume(coro, unpack(args, 1, args.n))
end)
-- Spin the loop.
loop:run()
-- Unpack results.
return unpack(results, 1, results.n)
end
end
-- Add 'async_' method handling. Dynamically generates wrapper around
-- xxx_async()/xxx_finish() sequence using currently running
-- coroutine.
local tag_int = gi.GObject.ParamSpecEnum.fields.default_value.typeinfo.tag
local inherited_element = GObject.Object._element
function GObject.Object:_element(object, name)
local element, category = inherited_element(self, object, name)
if element or not object then return element, category end
-- Check, whether we have async_xxx request.
local name_root = name:match('^async_(.+)$')
if name_root then
local async = inherited_element(self, object, name_root .. '_async')
local finish = inherited_element(self, object, name_root .. '_finish')
if async and finish then
element = { name = name_root, in_args = 0,
async = async, finish = finish, }
-- Go through arguments of async method and find indices of
-- io_priority, cancellable and callback args.
for _, param in ipairs(async.params) do
if param['in'] then
element.in_args = element.in_args + 1
if not param['out'] and param.typeinfo then
if param.name == 'io_priority' and
param.typeinfo.tag == tag_int then
element.io_priority = element.in_args
elseif param.name == 'cancellable' and
param.typeinfo.tag == 'interface' then
element.cancellable = element.in_args
end
end
end
end
-- Returns accumulated async call data.
return element, '_async'
end
end
end
function GObject.Object:_access_async(object, element, ...)
if select('#', ...) > 0 then
error(("%s: `%s' not writable"):format(
core.object.query(object, 'repo')._name, name))
end
-- Generate wrapper method calling _async/_finish pair automatically.
return function(...)
-- Check that we are running inside context.
local context = async_context[coroutine.running()]
if not context then
error(("%s.async_%s: called out of async context"):format(
self._name, element.name), 4)
end
-- Create input args, intersperse them with automatic ones.
local args, i, index = {}, 1, 1
for i = 1, element.in_args - 1 do
if i == element.io_priority then
args[i] = context.io_priority
elseif i == element.cancellable then
args[i] = context.cancellable
else
args[i] = select(index, ...)
index = index + 1
end
end
args[element.in_args] = coroutine.running()
element.async(unpack(args, 1, element.in_args))
return element.finish(coroutine.yield())
end
end
-- GOI < 1.30 did not map static factory method into interface
-- namespace. The prominent example of this fault was that
-- Gio.File.new_for_path() had to be accessed as
-- Gio.file_new_for_path(). Create a compatibility layer to mask this
-- flaw.
for _, name in pairs { 'path', 'uri', 'commandline_arg' } do
if not Gio.File['new_for_' .. name] then
Gio.File['new_for_' .. name] = Gio['file_new_for_' .. name]
end
end
-- Older versions of gio did not annotate input stream methods as
-- taking an array. Apply workaround.
-- https://github.com/pavouk/lgi/issues/59
for _, name in pairs { 'read', 'read_all', 'read_async' } do
local raw_read = Gio.InputStream[name]
if gi.Gio.InputStream.methods[name].args[1].typeinfo.tag ~= 'array' then
Gio.InputStream[name] = function(self, buffer, ...)
return raw_read(self, buffer, #buffer, ...)
end
if name == 'read_async' then
raw_finish = Gio.InputStream.read_finish
function Gio.InputStream.async_read(stream, buffer)
raw_read(stream, buffer, Gio.Async.io_priority,
Gio.Async.cancellable, coroutine.running())
return raw_finish(coroutine.yield())
end
end
end
end
|
Fix for custom override of g_input_stream_async_read()
|
Fix for custom override of g_input_stream_async_read()
This manual override did not follow previous changes in Gio.Async
architecture.
|
Lua
|
mit
|
psychon/lgi,pavouk/lgi
|
6bff4b83a5c52eae0f13592744997a912d32b7d0
|
spec/unit/statics_spec.lua
|
spec/unit/statics_spec.lua
|
local spec_helper = require "spec.spec_helpers"
local constants = require "kong.constants"
local stringy = require "stringy"
local IO = require "kong.tools.io"
local fs = require "luarocks.fs"
describe("Static files", function()
describe("Constants", function()
it("version set in constants should match the one in the rockspec", function()
local rockspec_path
for _, filename in ipairs(fs.list_dir(".")) do
if stringy.endswith(filename, "rockspec") then
rockspec_path = filename
break
end
end
if not rockspec_path then
error("Can't find the rockspec file")
end
local file_content = IO.read_file(rockspec_path)
local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+")
local extracted_version = res:sub(2, res:len() - 1)
assert.are.same(constants.ROCK_VERSION, extracted_version)
local dash = string.find(extracted_version, "-")
assert.are.same(constants.VERSION, dash and extracted_version:sub(1, dash - 1) or extracted_version)
end)
it("accessing non-existing error code should throw an error", function()
assert.has_no_error(function() local _ = constants.DATABASE_ERROR_TYPES.DATABASE end)
assert.has_error(function() local _ = constants.DATABASE_ERROR_TYPES.ThIs_TyPe_DoEs_NoT_ExIsT end)
end)
end)
describe("Configuration", function()
it("should equal to this template to make sure no errors are pushed in the default config", function()
local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE)
assert.are.same([[
## Available plugins on this server
plugins_available:
- ssl
- jwt
- acl
- cors
- oauth2
- tcp-log
- udp-log
- file-log
- http-log
- key-auth
- hmac-auth
- basic-auth
- ip-restriction
- mashape-analytics
- request-transformer
- response-transformer
- request-size-limiting
- rate-limiting
- response-ratelimiting
## The Kong working directory
## (Make sure you have read and write permissions)
nginx_working_dir: /usr/local/kong/
## Port configuration
proxy_port: 8000
proxy_ssl_port: 8443
admin_api_port: 8001
## Secondary port configuration
dnsmasq_port: 8053
## Specify the DAO to use
database: cassandra
## Databases configuration
databases_available:
cassandra:
properties:
contact_points:
- "localhost:9042"
timeout: 1000
keyspace: kong
keepalive: 60000 # in milliseconds
# ssl: false
# ssl_verify: false
# ssl_certificate: "/path/to/cluster-ca-certificate.pem"
# user: cassandra
# password: cassandra
## Cassandra cache configuration
database_cache_expiration: 5 # in seconds
## SSL Settings
## (Uncomment the two properties below to set your own certificate)
# ssl_cert_path: /path/to/certificate.pem
# ssl_key_path: /path/to/certificate.key
## Sends anonymous error reports
send_anonymous_reports: true
## In-memory cache size (MB)
memory_cache_size: 128
## Nginx configuration
nginx: |
worker_processes auto;
error_log logs/error.log error;
daemon on;
worker_rlimit_nofile {{auto_worker_rlimit_nofile}};
env KONG_CONF;
events {
worker_connections {{auto_worker_connections}};
multi_accept on;
}
http {
resolver {{dns_resolver}} ipv6=off;
charset UTF-8;
access_log logs/access.log;
access_log off;
# Timeouts
keepalive_timeout 60s;
client_header_timeout 60s;
client_body_timeout 60s;
send_timeout 60s;
# Proxy Settings
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
proxy_ssl_server_name on;
# IP Address
real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;
real_ip_recursive on;
# Other Settings
client_max_body_size 0;
underscores_in_headers on;
reset_timedout_connection on;
tcp_nopush on;
################################################
# The following code is required to run Kong #
# Please be careful if you'd like to change it #
################################################
# Lua Settings
lua_package_path ';;';
lua_code_cache on;
lua_max_running_timers 4096;
lua_max_pending_timers 16384;
lua_shared_dict locks 100k;
lua_shared_dict cache {{memory_cache_size}}m;
lua_socket_log_errors off;
{{lua_ssl_trusted_certificate}}
init_by_lua '
kong = require "kong"
local status, err = pcall(kong.init)
if not status then
ngx.log(ngx.ERR, "Startup error: "..err)
os.exit(1)
end
';
init_worker_by_lua 'kong.exec_plugins_init_worker()';
server {
server_name _;
listen {{proxy_port}};
listen {{proxy_ssl_port}} ssl;
ssl_certificate_by_lua 'kong.exec_plugins_certificate()';
ssl_certificate {{ssl_cert}};
ssl_certificate_key {{ssl_key}};
location / {
default_type 'text/plain';
# These properties will be used later by proxy_pass
set $backend_host nil;
set $backend_url nil;
# Authenticate the user and load the API info
access_by_lua 'kong.exec_plugins_access()';
# Proxy the request
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $backend_host;
proxy_pass $backend_url;
proxy_pass_header Server;
# Add additional response headers
header_filter_by_lua 'kong.exec_plugins_header_filter()';
# Change the response body
body_filter_by_lua 'kong.exec_plugins_body_filter()';
# Log the request
log_by_lua 'kong.exec_plugins_log()';
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
error_page 500 /500.html;
location = /500.html {
internal;
content_by_lua '
local responses = require "kong.tools.responses"
responses.send_HTTP_INTERNAL_SERVER_ERROR("An unexpected error occurred")
';
}
}
server {
listen {{admin_api_port}};
location / {
default_type application/json;
content_by_lua '
ngx.header["Access-Control-Allow-Origin"] = "*"
if ngx.req.get_method() == "OPTIONS" then
ngx.header["Access-Control-Allow-Methods"] = "GET,HEAD,PUT,PATCH,POST,DELETE"
ngx.exit(204)
end
local lapis = require "lapis"
lapis.serve("kong.api.app")
';
}
location /nginx_status {
internal;
stub_status;
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
# Do not remove, additional configuration placeholder for some plugins
# {{additional_configuration}}
}
}
]], configuration)
end)
end)
end)
|
local spec_helper = require "spec.spec_helpers"
local constants = require "kong.constants"
local stringy = require "stringy"
local IO = require "kong.tools.io"
local fs = require "luarocks.fs"
describe("Static files", function()
describe("Constants", function()
it("version set in constants should match the one in the rockspec", function()
local rockspec_path
for _, filename in ipairs(fs.list_dir(".")) do
if stringy.endswith(filename, "rockspec") then
rockspec_path = filename
break
end
end
if not rockspec_path then
error("Can't find the rockspec file")
end
local file_content = IO.read_file(rockspec_path)
local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+")
local extracted_version = res:sub(2, res:len() - 1)
assert.are.same(constants.ROCK_VERSION, extracted_version)
local dash = string.find(extracted_version, "-")
assert.are.same(constants.VERSION, dash and extracted_version:sub(1, dash - 1) or extracted_version)
end)
it("accessing non-existing error code should throw an error", function()
assert.has_no_error(function() local _ = constants.DATABASE_ERROR_TYPES.DATABASE end)
assert.has_error(function() local _ = constants.DATABASE_ERROR_TYPES.ThIs_TyPe_DoEs_NoT_ExIsT end)
end)
end)
describe("Configuration", function()
it("should equal to this template to make sure no errors are pushed in the default config", function()
local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE)
assert.are.same([[
## Available plugins on this server
plugins_available:
- ssl
- jwt
- acl
- cors
- oauth2
- tcp-log
- udp-log
- file-log
- http-log
- key-auth
- hmac-auth
- basic-auth
- ip-restriction
- mashape-analytics
- request-transformer
- response-transformer
- request-size-limiting
- rate-limiting
- response-ratelimiting
## The Kong working directory
## (Make sure you have read and write permissions)
nginx_working_dir: /usr/local/kong/
## Port configuration
proxy_port: 8000
proxy_ssl_port: 8443
admin_api_port: 8001
## Secondary port configuration
dnsmasq_port: 8053
## Specify the DAO to use
database: cassandra
## Databases configuration
databases_available:
cassandra:
properties:
contact_points:
- "localhost:9042"
timeout: 1000
keyspace: kong
keepalive: 60000 # in milliseconds
# ssl: false
# ssl_verify: false
# ssl_certificate: "/path/to/cluster-ca-certificate.pem"
# user: cassandra
# password: cassandra
## Cassandra cache configuration
database_cache_expiration: 5 # in seconds
## SSL Settings
## (Uncomment the two properties below to set your own certificate)
# ssl_cert_path: /path/to/certificate.pem
# ssl_key_path: /path/to/certificate.key
## Sends anonymous error reports
send_anonymous_reports: true
## In-memory cache size (MB)
memory_cache_size: 128
## Nginx configuration
nginx: |
worker_processes auto;
error_log logs/error.log error;
daemon on;
worker_rlimit_nofile {{auto_worker_rlimit_nofile}};
env KONG_CONF;
events {
worker_connections {{auto_worker_connections}};
multi_accept on;
}
http {
resolver {{dns_resolver}} ipv6=off;
charset UTF-8;
access_log logs/access.log;
access_log off;
# Timeouts
keepalive_timeout 60s;
client_header_timeout 60s;
client_body_timeout 60s;
send_timeout 60s;
# Proxy Settings
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
proxy_ssl_server_name on;
# IP Address
real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;
real_ip_recursive on;
# Other Settings
client_max_body_size 0;
underscores_in_headers on;
reset_timedout_connection on;
tcp_nopush on;
################################################
# The following code is required to run Kong #
# Please be careful if you'd like to change it #
################################################
# Lua Settings
lua_package_path ';;';
lua_code_cache on;
lua_max_running_timers 4096;
lua_max_pending_timers 16384;
lua_shared_dict locks 100k;
lua_shared_dict cache {{memory_cache_size}}m;
lua_socket_log_errors off;
{{lua_ssl_trusted_certificate}}
init_by_lua '
kong = require "kong"
local status, err = pcall(kong.init)
if not status then
ngx.log(ngx.ERR, "Startup error: "..err)
os.exit(1)
end
';
init_worker_by_lua 'kong.exec_plugins_init_worker()';
server {
server_name _;
listen {{proxy_port}};
listen {{proxy_ssl_port}} ssl;
ssl_certificate_by_lua 'kong.exec_plugins_certificate()';
ssl_certificate {{ssl_cert}};
ssl_certificate_key {{ssl_key}};
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;# omit SSLv3 because of POODLE (CVE-2014-3566)
location / {
default_type 'text/plain';
# These properties will be used later by proxy_pass
set $backend_host nil;
set $backend_url nil;
# Authenticate the user and load the API info
access_by_lua 'kong.exec_plugins_access()';
# Proxy the request
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $backend_host;
proxy_pass $backend_url;
proxy_pass_header Server;
# Add additional response headers
header_filter_by_lua 'kong.exec_plugins_header_filter()';
# Change the response body
body_filter_by_lua 'kong.exec_plugins_body_filter()';
# Log the request
log_by_lua 'kong.exec_plugins_log()';
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
error_page 500 /500.html;
location = /500.html {
internal;
content_by_lua '
local responses = require "kong.tools.responses"
responses.send_HTTP_INTERNAL_SERVER_ERROR("An unexpected error occurred")
';
}
}
server {
listen {{admin_api_port}};
location / {
default_type application/json;
content_by_lua '
ngx.header["Access-Control-Allow-Origin"] = "*"
if ngx.req.get_method() == "OPTIONS" then
ngx.header["Access-Control-Allow-Methods"] = "GET,HEAD,PUT,PATCH,POST,DELETE"
ngx.exit(204)
end
local lapis = require "lapis"
lapis.serve("kong.api.app")
';
}
location /nginx_status {
internal;
stub_status;
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
# Do not remove, additional configuration placeholder for some plugins
# {{additional_configuration}}
}
}
]], configuration)
end)
end)
end)
|
fix(test) fix config test after #563
|
fix(test) fix config test after #563
|
Lua
|
apache-2.0
|
Mashape/kong,Kong/kong,shiprabehera/kong,jebenexer/kong,icyxp/kong,salazar/kong,akh00/kong,Vermeille/kong,beauli/kong,ccyphers/kong,xvaara/kong,li-wl/kong,smanolache/kong,Kong/kong,ajayk/kong,jerizm/kong,Kong/kong
|
2e7c83ada8313257e1d5b80f71eaf2a76af12cb6
|
OvaleActionBar.lua
|
OvaleActionBar.lua
|
--[[--------------------------------------------------------------------
Ovale Spell Priority
Copyright (C) 2012 Sidoine
Copyright (C) 2012, 2013 Johnny C. Lam
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License in the LICENSE
file accompanying this program.
--]]--------------------------------------------------------------------
-- Keep data about the player action bars (key bindings mostly)
local _, Ovale = ...
local OvaleActionBar = Ovale:NewModule("OvaleActionBar", "AceEvent-3.0")
Ovale.OvaleActionBar = OvaleActionBar
--<private-static-properties>
local tonumber = tonumber
local wipe = table.wipe
local API_GetActionInfo = GetActionInfo
local API_GetActionText = GetActionText
local API_GetBindingKey = GetBindingKey
--key: spell name / value: action icon id
local self_actionSpell = {}
local self_actionMacro = {}
local self_actionItem = {}
local self_keybind = {}
local OVALE_ACTIONBAR_DEBUG = "action_bar"
--</private-static-properties>
--<public-static-methods>
function OvaleActionBar:OnEnable()
self:RegisterEvent("ACTIONBAR_SLOT_CHANGED")
self:RegisterEvent("ACTIVE_TALENT_GROUP_CHANGED", "FillActionIndexes")
self:RegisterEvent("PLAYER_ENTERING_WORLD", "FillActionIndexes")
self:RegisterEvent("PLAYER_TALENT_UPDATE", "FillActionIndexes")
self:RegisterEvent("UPDATE_BINDINGS", "FillActionIndexes")
end
function OvaleActionBar:OnDisable()
self:UnregisterEvent("ACTIONBAR_SLOT_CHANGED")
self:UnregisterEvent("ACTIVE_TALENT_GROUP_CHANGED")
self:UnregisterEvent("PLAYER_ENTERING_WORLD")
self:UnregisterEvent("PLAYER_TALENT_UPDATE")
self:UnregisterEvent("UPDATE_BINDINGS")
end
function OvaleActionBar:ACTIONBAR_SLOT_CHANGED(event, slot, unknown)
if (slot == 0) then
self:FillActionIndexes(event)
elseif (slot) then
-- on reoit aussi si c'est une macro avec mouseover chaque fois que la souris passe sur une cible!
self:FillActionIndex(tonumber(slot))
Ovale:DebugPrintf(OVALE_ACTIONBAR_DEBUG, "Mapping button %s to spell/macro", slot)
end
end
function OvaleActionBar:FillActionIndexes(event)
Ovale:DebugPrintf(OVALE_ACTIONBAR_DEBUG, "Mapping buttons to spells/macros for %s", event)
wipe(self_actionSpell)
wipe(self_actionMacro)
wipe(self_actionItem)
wipe(self_keybind)
for i=1,120 do
self:FillActionIndex(i)
end
end
function OvaleActionBar:FillActionIndex(i)
self_keybind[i] = self:FindKeyBinding(i)
local actionText = API_GetActionText(i)
if actionText then
self_actionMacro[actionText] = i
else
local type, spellId = API_GetActionInfo(i);
if (type=="spell") then
self_actionSpell[spellId] = i
elseif (type =="item") then
self_actionItem[spellId] = i
end
end
end
function OvaleActionBar:FindKeyBinding(id)
-- ACTIONBUTTON1..12 => principale (1..12, 13..24, 73..108)
-- MULTIACTIONBAR1BUTTON1..12 => bas gauche (61..72)
-- MULTIACTIONBAR2BUTTON1..12 => bas droite (49..60)
-- MULTIACTIONBAR3BUTTON1..12 => haut droit (25..36)
-- MULTIACTIONBAR4BUTTON1..12 => haut gauche (37..48)
local name;
if (id<=24 or id>72) then
name = "ACTIONBUTTON"..(((id-1)%12)+1);
elseif (id<=36) then
name = "MULTIACTIONBAR3BUTTON"..(id-24);
elseif (id<=48) then
name = "MULTIACTIONBAR4BUTTON"..(id-36);
elseif (id<=60) then
name = "MULTIACTIONBAR2BUTTON"..(id-48);
else
name = "MULTIACTIONBAR1BUTTON"..(id-60);
end
local key = API_GetBindingKey(name);
--[[ if (not key) then
DEFAULT_CHAT_FRAME:AddMessage(id.."=>"..name.." introuvable")
else
DEFAULT_CHAT_FRAME:AddMessage(id.."=>"..name.."="..key)
end]]
return key;
end
-- Get the action id that match a spell id
function OvaleActionBar:GetForSpell(spellId)
return self_actionSpell[spellId]
end
-- Get the action id that match a macro id
function OvaleActionBar:GetForMacro(macroId)
return self_actionMacro[macroId]
end
-- Get the action id that match an item id
function OvaleActionBar:GetForItem(itemId)
return self_actionItem[itemId]
end
function OvaleActionBar:GetBinding(actionId)
return self_keybind[actionId]
end
--</public-static-methods>
|
--[[--------------------------------------------------------------------
Ovale Spell Priority
Copyright (C) 2012 Sidoine
Copyright (C) 2012, 2013 Johnny C. Lam
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License in the LICENSE
file accompanying this program.
--]]--------------------------------------------------------------------
-- Keep data about the player action bars (key bindings mostly)
local _, Ovale = ...
local OvaleActionBar = Ovale:NewModule("OvaleActionBar", "AceEvent-3.0")
Ovale.OvaleActionBar = OvaleActionBar
--<private-static-properties>
local tonumber = tonumber
local wipe = table.wipe
local API_GetActionInfo = GetActionInfo
local API_GetActionText = GetActionText
local API_GetBindingKey = GetBindingKey
-- Maps each action slot (1..120) to the current action: self_action[slot] = action
local self_action = {}
-- Maps each action slot (1..120) to its current keybind: self_keybind[slot] = keybind
local self_keybind = {}
-- Maps each spell/macro/item ID to its current action slot.
-- self_spell[spellId] = slot
local self_spell = {}
-- self_macro[macroName] = slot
local self_macro = {}
-- self_item[itemId] = slot
local self_item = {}
local OVALE_ACTIONBAR_DEBUG = "action_bar"
--</private-static-properties>
--<private-static-methods>
local function GetKeyBinding(slot)
--[[
ACTIONBUTTON1..12 => primary (1..12, 13..24, 73..108)
MULTIACTIONBAR1BUTTON1..12 => bottom left (61..72)
MULTIACTIONBAR2BUTTON1..12 => bottom right (49..60)
MULTIACTIONBAR3BUTTON1..12 => top right (25..36)
MULTIACTIONBAR4BUTTON1..12 => top left (37..48)
--]]
local name
if slot <= 24 or slot > 72 then
name = "ACTIONBUTTON" .. (((slot - 1)%12) + 1)
elseif slot <= 36 then
name = "MULTIACTIONBAR3BUTTON" .. (slot - 24)
elseif slot <= 48 then
name = "MULTIACTIONBAR4BUTTON" .. (slot - 36)
elseif slot <= 60 then
name = "MULTIACTIONBAR2BUTTON" .. (slot - 48)
else
name = "MULTIACTIONBAR1BUTTON" .. (slot - 60)
end
local key = name and API_GetBindingKey(name)
return key
end
local function UpdateActionSlot(slot)
-- Clear old slot and associated actions.
local action = self_action[slot]
if self_spell[action] == slot then
self_spell[action] = nil
elseif self_item[action] == slot then
self_item[action] = nil
elseif self_macro[action] == slot then
self_macro[action] = nil
end
self_action[slot] = nil
-- Map the current action in the slot.
local actionType, id, subType = API_GetActionInfo(slot)
if actionType == "spell" then
id = tonumber(id)
if id then
if self_spell[id] and slot < self_spell[id] then
self_spell[id] = slot
end
self_action[slot] = id
end
elseif actionType == "item" then
id = tonumber(id)
if id then
if self_item[id] and slot < self_item[id] then
self_item[id] = slot
end
self_action[slot] = id
end
elseif actionType == "macro" then
local actionText = API_GetActionText(slot)
if actionText then
if self_macro[actionText] and slot < self_macro[actionText] then
self_macro[actionText] = slot
end
self_action[slot] = actionText
end
end
Ovale:DebugPrintf(OVALE_ACTIONBAR_DEBUG, "Mapping button %s to %s", slot, self_action[slot])
-- Update the keybind for the slot.
self_keybind[slot] = GetKeyBinding(slot)
end
--</private-static-methods>
--<public-static-methods>
function OvaleActionBar:OnEnable()
self:RegisterEvent("ACTIONBAR_SLOT_CHANGED")
self:RegisterEvent("ACTIVE_TALENT_GROUP_CHANGED", "UpdateActionSlots")
self:RegisterEvent("PLAYER_ENTERING_WORLD", "UpdateActionSlots")
self:RegisterEvent("PLAYER_TALENT_UPDATE", "UpdateActionSlots")
self:RegisterEvent("UPDATE_BINDINGS")
end
function OvaleActionBar:OnDisable()
self:UnregisterEvent("ACTIONBAR_SLOT_CHANGED")
self:UnregisterEvent("ACTIVE_TALENT_GROUP_CHANGED")
self:UnregisterEvent("PLAYER_ENTERING_WORLD")
self:UnregisterEvent("PLAYER_TALENT_UPDATE")
self:UnregisterEvent("UPDATE_BINDINGS")
end
function OvaleActionBar:ACTIONBAR_SLOT_CHANGED(event, slot)
slot = tonumber(slot)
if slot == 0 then
self:UpdateActionSlots(event)
elseif slot then
UpdateActionSlot(slot)
end
end
function OvaleActionBar:UPDATE_BINDINGS(event)
Ovale:DebugPrintf(OVALE_ACTIONBAR_DEBUG, "%s: Updating key bindings.", event)
for slot = 1, 120 do
self_keybind[slot] = GetKeyBinding(slot)
end
end
function OvaleActionBar:UpdateActionSlots(event)
Ovale:DebugPrintf(OVALE_ACTIONBAR_DEBUG, "%s: Updating all action slot mappings.", event)
wipe(self_action)
wipe(self_item)
wipe(self_macro)
wipe(self_spell)
for slot = 1, 120 do
UpdateActionSlot(slot)
end
end
-- Get the action slot that matches a spell ID.
function OvaleActionBar:GetForSpell(spellId)
return self_spell[spellId]
end
-- Get the action slot that matches a macro name.
function OvaleActionBar:GetForMacro(macroName)
return self_macro[macroName]
end
-- Get the action slot that matches an item ID.
function OvaleActionBar:GetForItem(itemId)
return self_item[itemId]
end
-- Get the keybinding for an action slot.
function OvaleActionBar:GetBinding(slot)
return self_keybind[slot]
end
--</public-static-methods>
|
Fix ticket 208 - wrong key binding being displayed.
|
Fix ticket 208 - wrong key binding being displayed.
Manage an additional mapping from slot number to action, and clear the
mappings for a slot if an action is removed from that slot.
git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@1206 d5049fe3-3747-40f7-a4b5-f36d6801af5f
|
Lua
|
mit
|
ultijlam/ovale,eXhausted/Ovale,ultijlam/ovale,eXhausted/Ovale,ultijlam/ovale,eXhausted/Ovale,Xeltor/ovale
|
87a1b5e5d9d0c89a4011d5859155798cd782472c
|
regress/51-join-defunct-thread.lua
|
regress/51-join-defunct-thread.lua
|
#!/bin/sh
_=[[
. "${0%%/*}/regress.sh"
exec runlua -t -j- "$0" "$@"
]]
require"regress".export".*"
check(jit, "LuaJIT required")
check(errno.EOWNERDEAD, "EOWNERDEAD not defined")
local thr = assert(thread.start(function ()
local errno = require"cqueues.errno"
local ffi = require"ffi"
require"regress".export".*"
info"calling prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT)"
local PR_SET_SECCOMP = 22
local SECCOMP_MODE_STRICT = 1
ffi.cdef"int prctl(int, unsigned long, unsigned long, unsigned long, unsigned long)"
local ok, rv = pcall(function () return ffi.C.prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT, 0, 0, 0) end)
if not ok then
local rv = string.match(rv, "[^:]+:[^:]+$") or rv
info("prctl call failed: %s", rv)
elseif rv ~= 0 then
info("prctl call failed: %s", errno.strerror(ffi.errno()))
else
info"attempting to open /nonexistant"
io.open"/nonexistant" -- should cause us to be killed
info"prctl call failed: still able to open files"
end
info"calling pthread_exit"
ffi.cdef"void pthread_exit(void *);"
ffi.C.pthread_exit(nil)
info"pthread_exit call failed: thread still running"
end))
local ok, why, code = auxlib.fileresult(thr:join(5))
check(not ok, "thread unexpectedly joined (%s)", why or "no error")
check(code == errno.EOWNERDEAD or code == errno.ETIMEDOUT, "unexpected error: %s", why)
check(code == errno.EOWNERDEAD, "robust mutex strategy not supported on this system")
say"OK"
|
#!/bin/sh
_=[[
. "${0%%/*}/regress.sh"
exec runlua -t -j- "$0" "$@"
]]
require"regress".export".*"
check(jit, "LuaJIT required")
check(errno.EOWNERDEAD, "EOWNERDEAD not defined")
local thr, con = assert(thread.start(function (con)
local errno = require"cqueues.errno"
local ffi = require"ffi"
require"regress".export".*"
--
-- NOTE: On musl-libc the parent process deadlocks on flockfile as
-- apparently the thread dies when writing to stderr. Log to our
-- communications socket instead, which doesn't hold any locks.
--
local function info(...)
con:write(string.format(...), "\n")
con:flush()
end
info"calling prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT)"
local PR_SET_SECCOMP = 22
local SECCOMP_MODE_STRICT = 1
ffi.cdef"int prctl(int, unsigned long, unsigned long, unsigned long, unsigned long)"
local ok, rv = pcall(function () return ffi.C.prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT, 0, 0, 0) end)
if not ok then
local rv = string.match(rv, "[^:]+:[^:]+$") or rv
info("prctl call failed: %s", rv)
elseif rv ~= 0 then
info("prctl call failed: %s", errno.strerror(ffi.errno()))
else
info"attempting to open /nonexistant"
io.open"/nonexistant" -- should cause us to be killed
info"prctl call failed: still able to open files"
end
info"calling pthread_exit"
ffi.cdef"void pthread_exit(void *);"
ffi.C.pthread_exit(nil)
info"pthread_exit call failed: thread still running"
end))
local main = check(cqueues.new())
-- read thread's log lines from pcall because socket:read will throw an
-- error when the socket is closed asynchronously below.
check(main:wrap(pcall, function ()
for ln in con:lines() do
info("%s", ln)
end
end))
check(main:wrap(function ()
local ok, why, code = auxlib.fileresult(thr:join(5))
check(not ok, "thread unexpectedly joined (%s)", why or "no error")
check(code == errno.EOWNERDEAD or code == errno.ETIMEDOUT, "unexpected error: %s", why)
check(code == errno.EOWNERDEAD, "robust mutex strategy not supported on this system")
con:close()
end))
check(main:loop())
say"OK"
|
fix defunct thread regression test to avoid musl-libc flockfile deadlock which hangs the entire process
|
fix defunct thread regression test to avoid musl-libc flockfile deadlock which hangs the entire process
|
Lua
|
mit
|
bigcrush/cqueues,daurnimator/cqueues,daurnimator/cqueues,wahern/cqueues,bigcrush/cqueues,wahern/cqueues
|
7e0b49edd14b4822a26af7a66d041aa1ffa43b13
|
frontend/dump.lua
|
frontend/dump.lua
|
--[[
simple serialization function, won't do uservalues, functions, loops
]]
local insert = table.insert
local function _serialize(what, outt, indent, max_lv, history)
if not max_lv then
max_lv = math.huge
end
if indent > max_lv then
return
end
history = history or {}
for up, item in ipairs(history) do
if item == what then
insert(outt, "nil --[[ LOOP:\n")
insert(outt, string.rep("\t", indent - up))
insert(outt, "^------- ]]")
return
end
end
if type(what) == "table" then
local new_history = { what, unpack(history) }
local didrun = false
insert(outt, "{")
for k, v in pairs(what) do
if didrun then
insert(outt, ",")
end
insert(outt, "\n")
insert(outt, string.rep("\t", indent+1))
insert(outt, "[")
_serialize(k, outt, indent+1, max_lv, new_history)
insert(outt, "] = ")
_serialize(v, outt, indent+1, max_lv, new_history)
didrun = true
end
if didrun then
insert(outt, "\n")
insert(outt, string.rep("\t", indent))
end
insert(outt, "}")
elseif type(what) == "string" then
insert(outt, string.format("%q", what))
elseif type(what) == "number" or type(what) == "boolean" then
insert(outt, tostring(what))
elseif type(what) == "function" then
insert(outt, "nil --[[ FUNCTION ]]")
elseif type(what) == "nil" then
insert(outt, "nil")
end
end
--[[
Serializes whatever is in "data" to a string that is parseable by Lua
You can optionally specify a maximum recursion depth in "max_lv"
--]]
local function dump(data, max_lv)
local out = {}
_serialize(data, out, 0, max_lv)
return table.concat(out)
end
return dump
|
--[[
simple serialization function, won't do uservalues, functions, loops
]]
local insert = table.insert
local function _serialize(what, outt, indent, max_lv, history)
if not max_lv then
max_lv = math.huge
end
if indent > max_lv then
return
end
if type(what) == "table" then
history = history or {}
for up, item in ipairs(history) do
if item == what then
insert(outt, "nil --[[ LOOP:\n")
insert(outt, string.rep("\t", indent - up))
insert(outt, "^------- ]]")
return
end
end
local new_history = { what, unpack(history) }
local didrun = false
insert(outt, "{")
for k, v in pairs(what) do
if didrun then
insert(outt, ",")
end
insert(outt, "\n")
insert(outt, string.rep("\t", indent+1))
insert(outt, "[")
_serialize(k, outt, indent+1, max_lv, new_history)
insert(outt, "] = ")
_serialize(v, outt, indent+1, max_lv, new_history)
didrun = true
end
if didrun then
insert(outt, "\n")
insert(outt, string.rep("\t", indent))
end
insert(outt, "}")
elseif type(what) == "string" then
insert(outt, string.format("%q", what))
elseif type(what) == "number" or type(what) == "boolean" then
insert(outt, tostring(what))
elseif type(what) == "function" then
insert(outt, "nil --[[ FUNCTION ]]")
elseif type(what) == "nil" then
insert(outt, "nil")
end
end
--[[
Serializes whatever is in "data" to a string that is parseable by Lua
You can optionally specify a maximum recursion depth in "max_lv"
--]]
local function dump(data, max_lv)
local out = {}
_serialize(data, out, 0, max_lv)
return table.concat(out)
end
return dump
|
fix dump() recursion detection
|
fix dump() recursion detection
only detect recursions for table values.
|
Lua
|
agpl-3.0
|
ashhher3/koreader,chrox/koreader,ashang/koreader,NiLuJe/koreader,poire-z/koreader,chihyang/koreader,mihailim/koreader,NickSavage/koreader,noname007/koreader,koreader/koreader,poire-z/koreader,frankyifei/koreader,lgeek/koreader,koreader/koreader,Frenzie/koreader,Markismus/koreader,pazos/koreader,mwoz123/koreader,robert00s/koreader,NiLuJe/koreader,apletnev/koreader,Frenzie/koreader,houqp/koreader,Hzj-jie/koreader
|
34e98ccdc38866223dc7e66bfd50f1ee6b9fb98a
|
spec/unit/statics_spec.lua
|
spec/unit/statics_spec.lua
|
local spec_helper = require "spec.spec_helpers"
local constants = require "kong.constants"
local stringy = require "stringy"
local IO = require "kong.tools.io"
local fs = require "luarocks.fs"
describe("Static files", function()
describe("Constants", function()
it("version set in constants should match the one in the rockspec", function()
local rockspec_path
for _, filename in ipairs(fs.list_dir(".")) do
if stringy.endswith(filename, "rockspec") then
rockspec_path = filename
break
end
end
if not rockspec_path then
error("Can't find the rockspec file")
end
local file_content = IO.read_file(rockspec_path)
local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+")
local extracted_version = res:sub(2, res:len() - 1)
assert.are.same(constants.VERSION, extracted_version)
end)
end)
describe("Configuration", function()
it("should equal to this template to make sure no errors are pushed in the default config", function()
local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE)
assert.are.same([[
# Available plugins on this server
plugins_available:
- keyauth
- basicauth
- ratelimiting
- tcplog
- udplog
- filelog
- cors
- request_transformer
nginx_working_dir: /usr/local/kong/
proxy_port: 8000
admin_api_port: 8001
dnsmasq_port: 8053
# Specify the DAO to use
database: cassandra
# Databases configuration
databases_available:
cassandra:
properties:
hosts: "localhost"
port: 9042
timeout: 1000
keyspace: kong
keepalive: 60000 # in milliseconds
# Cassandra cache configuration
database_cache_expiration: 5 # in seconds
# Sends anonymous error reports
send_anonymous_reports: true
# Nginx configuration
nginx: |
worker_processes auto;
error_log logs/error.log info;
daemon on;
worker_rlimit_nofile {{auto_worker_rlimit_nofile}};
env KONG_CONF;
events {
worker_connections {{auto_worker_connections}};
multi_accept on;
}
http {
resolver {{dns_resolver}};
charset UTF-8;
access_log logs/access.log;
access_log on;
# Timeouts
keepalive_timeout 60s;
client_header_timeout 60s;
client_body_timeout 60s;
send_timeout 60s;
# Proxy Settings
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
proxy_ssl_server_name on;
# IP Address
real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;
real_ip_recursive on;
# Other Settings
client_max_body_size 128m;
underscores_in_headers on;
reset_timedout_connection on;
tcp_nopush on;
################################################
# The following code is required to run Kong #
# Please be careful if you'd like to change it #
################################################
# Lua Settings
lua_package_path ';;';
lua_code_cache on;
lua_max_running_timers 4096;
lua_max_pending_timers 16384;
lua_shared_dict cache 512m;
lua_socket_log_errors off;
init_by_lua '
kong = require "kong"
local status, err = pcall(kong.init)
if not status then
ngx.log(ngx.ERR, "Startup error: "..err)
os.exit(1)
end
';
server {
listen {{proxy_port}};
location / {
default_type 'text/plain';
# This property will be used later by proxy_pass
set $backend_url nil;
# Authenticate the user and load the API info
access_by_lua 'kong.exec_plugins_access()';
# Proxy the request
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass $backend_url;
proxy_pass_header Server;
# Add additional response headers
header_filter_by_lua 'kong.exec_plugins_header_filter()';
# Change the response body
body_filter_by_lua 'kong.exec_plugins_body_filter()';
# Log the request
log_by_lua 'kong.exec_plugins_log()';
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
error_page 500 /500.html;
location = /500.html {
internal;
content_by_lua '
local utils = require "kong.tools.utils"
utils.show_error(ngx.status, "Oops, an unexpected error occurred!")
';
}
}
server {
listen {{admin_api_port}};
location / {
default_type application/json;
content_by_lua 'require("lapis").serve("kong.api.app")';
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
# Do not remove, additional configuration placeholder for some plugins
# {{additional_configuration}}
}
}
]], configuration)
end)
end)
end)
|
local spec_helper = require "spec.spec_helpers"
local constants = require "kong.constants"
local stringy = require "stringy"
local IO = require "kong.tools.io"
local fs = require "luarocks.fs"
describe("Static files", function()
describe("Constants", function()
it("version set in constants should match the one in the rockspec", function()
local rockspec_path
for _, filename in ipairs(fs.list_dir(".")) do
if stringy.endswith(filename, "rockspec") then
rockspec_path = filename
break
end
end
if not rockspec_path then
error("Can't find the rockspec file")
end
local file_content = IO.read_file(rockspec_path)
local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+")
local extracted_version = res:sub(2, res:len() - 1)
assert.are.same(constants.VERSION, extracted_version)
end)
end)
describe("Configuration", function()
it("should equal to this template to make sure no errors are pushed in the default config", function()
local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE)
assert.are.same([[
# Available plugins on this server
plugins_available:
- keyauth
- basicauth
- ratelimiting
- tcplog
- udplog
- filelog
- cors
- request_transformer
nginx_working_dir: /usr/local/kong/
proxy_port: 8000
admin_api_port: 8001
dnsmasq_port: 8053
# Specify the DAO to use
database: cassandra
# Databases configuration
databases_available:
cassandra:
properties:
hosts: "localhost"
port: 9042
timeout: 1000
keyspace: kong
keepalive: 60000 # in milliseconds
# Cassandra cache configuration
database_cache_expiration: 5 # in seconds
# Sends anonymous error reports
send_anonymous_reports: true
# In-memory cache size (MB)
memory_cache_size: 128
# Nginx configuration
nginx: |
worker_processes auto;
error_log logs/error.log info;
daemon on;
worker_rlimit_nofile {{auto_worker_rlimit_nofile}};
env KONG_CONF;
events {
worker_connections {{auto_worker_connections}};
multi_accept on;
}
http {
resolver {{dns_resolver}};
charset UTF-8;
access_log logs/access.log;
access_log on;
# Timeouts
keepalive_timeout 60s;
client_header_timeout 60s;
client_body_timeout 60s;
send_timeout 60s;
# Proxy Settings
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
proxy_ssl_server_name on;
# IP Address
real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;
real_ip_recursive on;
# Other Settings
client_max_body_size 128m;
underscores_in_headers on;
reset_timedout_connection on;
tcp_nopush on;
################################################
# The following code is required to run Kong #
# Please be careful if you'd like to change it #
################################################
# Lua Settings
lua_package_path ';;';
lua_code_cache on;
lua_max_running_timers 4096;
lua_max_pending_timers 16384;
lua_shared_dict cache {{memory_cache_size}}m;
lua_socket_log_errors off;
init_by_lua '
kong = require "kong"
local status, err = pcall(kong.init)
if not status then
ngx.log(ngx.ERR, "Startup error: "..err)
os.exit(1)
end
';
server {
listen {{proxy_port}};
location / {
default_type 'text/plain';
# This property will be used later by proxy_pass
set $backend_url nil;
# Authenticate the user and load the API info
access_by_lua 'kong.exec_plugins_access()';
# Proxy the request
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass $backend_url;
proxy_pass_header Server;
# Add additional response headers
header_filter_by_lua 'kong.exec_plugins_header_filter()';
# Change the response body
body_filter_by_lua 'kong.exec_plugins_body_filter()';
# Log the request
log_by_lua 'kong.exec_plugins_log()';
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
error_page 500 /500.html;
location = /500.html {
internal;
content_by_lua '
local utils = require "kong.tools.utils"
utils.show_error(ngx.status, "Oops, an unexpected error occurred!")
';
}
}
server {
listen {{admin_api_port}};
location / {
default_type application/json;
content_by_lua 'require("lapis").serve("kong.api.app")';
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
# Do not remove, additional configuration placeholder for some plugins
# {{additional_configuration}}
}
}
]], configuration)
end)
end)
end)
|
Fixing configuration test
|
Fixing configuration test
|
Lua
|
apache-2.0
|
sbuettner/kong,AnsonSmith/kong,peterayeni/kong,paritoshmmmec/kong,vmercierfr/kong,bbalu/kong,wakermahmud/kong,puug/kong,ChristopherBiscardi/kong,skynet/kong,chourobin/kong,Skyscanner/kong
|
51a7f96877d8c5bf70217073ed8aa7ab6a196d20
|
modules/luci-base/luasrc/tools/status.lua
|
modules/luci-base/luasrc/tools/status.lua
|
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.tools.status", package.seeall)
local uci = require "luci.model.uci".cursor()
local function dhcp_leases_common(family)
local rv = { }
local nfs = require "nixio.fs"
local leasefile = "/tmp/dhcp.leases"
uci:foreach("dhcp", "dnsmasq",
function(s)
if s.leasefile and nfs.access(s.leasefile) then
leasefile = s.leasefile
return false
end
end)
local fd = io.open(leasefile, "r")
if fd then
while true do
local ln = fd:read("*l")
if not ln then
break
else
local ts, mac, ip, name, duid = ln:match("^(%d+) (%S+) (%S+) (%S+) (%S+)")
if ts and mac and ip and name and duid then
if family == 4 and not ip:match(":") then
rv[#rv+1] = {
expires = os.difftime(tonumber(ts) or 0, os.time()),
macaddr = mac,
ipaddr = ip,
hostname = (name ~= "*") and name
}
elseif family == 6 and ip:match(":") then
rv[#rv+1] = {
expires = os.difftime(tonumber(ts) or 0, os.time()),
ip6addr = ip,
duid = (duid ~= "*") and duid,
hostname = (name ~= "*") and name
}
end
end
end
end
fd:close()
end
local fd = io.open("/tmp/hosts/odhcpd", "r")
if fd then
while true do
local ln = fd:read("*l")
if not ln then
break
else
local iface, duid, iaid, name, ts, id, length, ip = ln:match("^# (%S+) (%S+) (%S+) (%S+) (%d+) (%S+) (%S+) (.*)")
if ip and iaid ~= "ipv4" and family == 6 then
rv[#rv+1] = {
expires = os.difftime(tonumber(ts) or 0, os.time()),
duid = duid,
ip6addr = ip,
hostname = (name ~= "-") and name
}
elseif ip and iaid == "ipv4" and family == 4 then
rv[#rv+1] = {
expires = os.difftime(tonumber(ts) or 0, os.time()),
macaddr = duid,
ipaddr = ip,
hostname = (name ~= "-") and name
}
end
end
end
fd:close()
end
return rv
end
function dhcp_leases()
return dhcp_leases_common(4)
end
function dhcp6_leases()
return dhcp_leases_common(6)
end
function wifi_networks()
local rv = { }
local ntm = require "luci.model.network".init()
local dev
for _, dev in ipairs(ntm:get_wifidevs()) do
local rd = {
up = dev:is_up(),
device = dev:name(),
name = dev:get_i18n(),
networks = { }
}
local net
for _, net in ipairs(dev:get_wifinets()) do
rd.networks[#rd.networks+1] = {
name = net:shortname(),
link = net:adminlink(),
up = net:is_up(),
mode = net:active_mode(),
ssid = net:active_ssid(),
bssid = net:active_bssid(),
encryption = net:active_encryption(),
frequency = net:frequency(),
channel = net:channel(),
signal = net:signal(),
quality = net:signal_percent(),
noise = net:noise(),
bitrate = net:bitrate(),
ifname = net:ifname(),
assoclist = net:assoclist(),
country = net:country(),
txpower = net:txpower(),
txpoweroff = net:txpower_offset(),
disabled = (dev:get("disabled") == "1" or
net:get("disabled") == "1")
}
end
rv[#rv+1] = rd
end
return rv
end
function wifi_network(id)
local ntm = require "luci.model.network".init()
local net = ntm:get_wifinet(id)
if net then
local dev = net:get_device()
if dev then
return {
id = id,
name = net:shortname(),
link = net:adminlink(),
up = net:is_up(),
mode = net:active_mode(),
ssid = net:active_ssid(),
bssid = net:active_bssid(),
encryption = net:active_encryption(),
frequency = net:frequency(),
channel = net:channel(),
signal = net:signal(),
quality = net:signal_percent(),
noise = net:noise(),
bitrate = net:bitrate(),
ifname = net:ifname(),
assoclist = net:assoclist(),
country = net:country(),
txpower = net:txpower(),
txpoweroff = net:txpower_offset(),
disabled = (dev:get("disabled") == "1" or
net:get("disabled") == "1"),
device = {
up = dev:is_up(),
device = dev:name(),
name = dev:get_i18n()
}
}
end
end
return { }
end
function switch_status(devs)
local dev
local switches = { }
for dev in devs:gmatch("[^%s,]+") do
local ports = { }
local swc = io.popen("swconfig dev %q show" % dev, "r")
if swc then
local l
repeat
l = swc:read("*l")
if l then
local port, up = l:match("port:(%d+) link:(%w+)")
if port then
local speed = l:match(" speed:(%d+)")
local duplex = l:match(" (%w+)-duplex")
local txflow = l:match(" (txflow)")
local rxflow = l:match(" (rxflow)")
local auto = l:match(" (auto)")
ports[#ports+1] = {
port = tonumber(port) or 0,
speed = tonumber(speed) or 0,
link = (up == "up"),
duplex = (duplex == "full"),
rxflow = (not not rxflow),
txflow = (not not txflow),
auto = (not not auto)
}
end
end
until not l
swc:close()
end
switches[dev] = ports
end
return switches
end
|
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.tools.status", package.seeall)
local uci = require "luci.model.uci".cursor()
local function dhcp_leases_common(family)
local rv = { }
local nfs = require "nixio.fs"
local leasefile = "/tmp/dhcp.leases"
uci:foreach("dhcp", "dnsmasq",
function(s)
if s.leasefile and nfs.access(s.leasefile) then
leasefile = s.leasefile
return false
end
end)
local fd = io.open(leasefile, "r")
if fd then
while true do
local ln = fd:read("*l")
if not ln then
break
else
local ts, mac, ip, name, duid = ln:match("^(%d+) (%S+) (%S+) (%S+) (%S+)")
if ts and mac and ip and name and duid then
if family == 4 and not ip:match(":") then
rv[#rv+1] = {
expires = os.difftime(tonumber(ts) or 0, os.time()),
macaddr = mac,
ipaddr = ip,
hostname = (name ~= "*") and name
}
elseif family == 6 and ip:match(":") then
rv[#rv+1] = {
expires = os.difftime(tonumber(ts) or 0, os.time()),
ip6addr = ip,
duid = (duid ~= "*") and duid,
hostname = (name ~= "*") and name
}
end
end
end
end
fd:close()
end
local lease6file = "/tmp/hosts/odhcpd"
uci:foreach("dhcp", "odhcpd",
function(t)
if t.leasefile and nfs.access(t.leasefile) then
lease6file = t.leasefile
return false
end
end)
local fd = io.open(lease6file, "r")
if fd then
while true do
local ln = fd:read("*l")
if not ln then
break
else
local iface, duid, iaid, name, ts, id, length, ip = ln:match("^# (%S+) (%S+) (%S+) (%S+) (%d+) (%S+) (%S+) (.*)")
if ip and iaid ~= "ipv4" and family == 6 then
rv[#rv+1] = {
expires = os.difftime(tonumber(ts) or 0, os.time()),
duid = duid,
ip6addr = ip,
hostname = (name ~= "-") and name
}
elseif ip and iaid == "ipv4" and family == 4 then
rv[#rv+1] = {
expires = os.difftime(tonumber(ts) or 0, os.time()),
macaddr = duid,
ipaddr = ip,
hostname = (name ~= "-") and name
}
end
end
end
fd:close()
end
return rv
end
function dhcp_leases()
return dhcp_leases_common(4)
end
function dhcp6_leases()
return dhcp_leases_common(6)
end
function wifi_networks()
local rv = { }
local ntm = require "luci.model.network".init()
local dev
for _, dev in ipairs(ntm:get_wifidevs()) do
local rd = {
up = dev:is_up(),
device = dev:name(),
name = dev:get_i18n(),
networks = { }
}
local net
for _, net in ipairs(dev:get_wifinets()) do
rd.networks[#rd.networks+1] = {
name = net:shortname(),
link = net:adminlink(),
up = net:is_up(),
mode = net:active_mode(),
ssid = net:active_ssid(),
bssid = net:active_bssid(),
encryption = net:active_encryption(),
frequency = net:frequency(),
channel = net:channel(),
signal = net:signal(),
quality = net:signal_percent(),
noise = net:noise(),
bitrate = net:bitrate(),
ifname = net:ifname(),
assoclist = net:assoclist(),
country = net:country(),
txpower = net:txpower(),
txpoweroff = net:txpower_offset(),
disabled = (dev:get("disabled") == "1" or
net:get("disabled") == "1")
}
end
rv[#rv+1] = rd
end
return rv
end
function wifi_network(id)
local ntm = require "luci.model.network".init()
local net = ntm:get_wifinet(id)
if net then
local dev = net:get_device()
if dev then
return {
id = id,
name = net:shortname(),
link = net:adminlink(),
up = net:is_up(),
mode = net:active_mode(),
ssid = net:active_ssid(),
bssid = net:active_bssid(),
encryption = net:active_encryption(),
frequency = net:frequency(),
channel = net:channel(),
signal = net:signal(),
quality = net:signal_percent(),
noise = net:noise(),
bitrate = net:bitrate(),
ifname = net:ifname(),
assoclist = net:assoclist(),
country = net:country(),
txpower = net:txpower(),
txpoweroff = net:txpower_offset(),
disabled = (dev:get("disabled") == "1" or
net:get("disabled") == "1"),
device = {
up = dev:is_up(),
device = dev:name(),
name = dev:get_i18n()
}
}
end
end
return { }
end
function switch_status(devs)
local dev
local switches = { }
for dev in devs:gmatch("[^%s,]+") do
local ports = { }
local swc = io.popen("swconfig dev %q show" % dev, "r")
if swc then
local l
repeat
l = swc:read("*l")
if l then
local port, up = l:match("port:(%d+) link:(%w+)")
if port then
local speed = l:match(" speed:(%d+)")
local duplex = l:match(" (%w+)-duplex")
local txflow = l:match(" (txflow)")
local rxflow = l:match(" (rxflow)")
local auto = l:match(" (auto)")
ports[#ports+1] = {
port = tonumber(port) or 0,
speed = tonumber(speed) or 0,
link = (up == "up"),
duplex = (duplex == "full"),
rxflow = (not not rxflow),
txflow = (not not txflow),
auto = (not not auto)
}
end
end
until not l
swc:close()
end
switches[dev] = ports
end
return switches
end
|
luci-base: read odhcpd leasefile location via uci
|
luci-base: read odhcpd leasefile location via uci
Check the location of the odhcpd leasefile from /etc/config/dhcp
via uci. Fallback to the default location.
This fixes #702
Signed-off-by: Hannu Nyman <ab53a3387de93e31696058c104e6f769cd83fd1b@iki.fi>
|
Lua
|
apache-2.0
|
LuttyYang/luci,bittorf/luci,bittorf/luci,shangjiyu/luci-with-extra,bittorf/luci,bittorf/luci,wongsyrone/luci-1,remakeelectric/luci,shangjiyu/luci-with-extra,shangjiyu/luci-with-extra,mumuqz/luci,artynet/luci,981213/luci-1,hnyman/luci,mumuqz/luci,kuoruan/luci,hnyman/luci,981213/luci-1,openwrt/luci,teslamint/luci,Noltari/luci,rogerpueyo/luci,kuoruan/lede-luci,kuoruan/lede-luci,Wedmer/luci,Noltari/luci,kuoruan/lede-luci,981213/luci-1,981213/luci-1,lbthomsen/openwrt-luci,shangjiyu/luci-with-extra,taiha/luci,tobiaswaldvogel/luci,LuttyYang/luci,oneru/luci,kuoruan/lede-luci,rogerpueyo/luci,oneru/luci,kuoruan/lede-luci,nmav/luci,bright-things/ionic-luci,chris5560/openwrt-luci,cshore/luci,oneru/luci,kuoruan/luci,bittorf/luci,bright-things/ionic-luci,shangjiyu/luci-with-extra,chris5560/openwrt-luci,openwrt-es/openwrt-luci,remakeelectric/luci,wongsyrone/luci-1,shangjiyu/luci-with-extra,oneru/luci,artynet/luci,daofeng2015/luci,remakeelectric/luci,Noltari/luci,bittorf/luci,tobiaswaldvogel/luci,ollie27/openwrt_luci,oneru/luci,lbthomsen/openwrt-luci,taiha/luci,cshore-firmware/openwrt-luci,LuttyYang/luci,nmav/luci,lbthomsen/openwrt-luci,daofeng2015/luci,daofeng2015/luci,aa65535/luci,lbthomsen/openwrt-luci,daofeng2015/luci,teslamint/luci,chris5560/openwrt-luci,mumuqz/luci,aa65535/luci,taiha/luci,hnyman/luci,kuoruan/lede-luci,teslamint/luci,daofeng2015/luci,bright-things/ionic-luci,remakeelectric/luci,bright-things/ionic-luci,ollie27/openwrt_luci,chris5560/openwrt-luci,ollie27/openwrt_luci,nmav/luci,cshore-firmware/openwrt-luci,taiha/luci,kuoruan/luci,nmav/luci,openwrt-es/openwrt-luci,mumuqz/luci,openwrt-es/openwrt-luci,ollie27/openwrt_luci,shangjiyu/luci-with-extra,cshore/luci,daofeng2015/luci,981213/luci-1,tobiaswaldvogel/luci,Noltari/luci,tobiaswaldvogel/luci,981213/luci-1,oneru/luci,ollie27/openwrt_luci,wongsyrone/luci-1,artynet/luci,cshore/luci,aa65535/luci,hnyman/luci,openwrt/luci,Noltari/luci,ollie27/openwrt_luci,Wedmer/luci,lbthomsen/openwrt-luci,mumuqz/luci,Noltari/luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,artynet/luci,nmav/luci,mumuqz/luci,bright-things/ionic-luci,cshore-firmware/openwrt-luci,ollie27/openwrt_luci,rogerpueyo/luci,kuoruan/luci,nmav/luci,remakeelectric/luci,openwrt-es/openwrt-luci,artynet/luci,openwrt/luci,artynet/luci,chris5560/openwrt-luci,cshore-firmware/openwrt-luci,chris5560/openwrt-luci,oneru/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,taiha/luci,nmav/luci,wongsyrone/luci-1,LuttyYang/luci,openwrt/luci,rogerpueyo/luci,bright-things/ionic-luci,Wedmer/luci,Noltari/luci,aa65535/luci,daofeng2015/luci,LuttyYang/luci,hnyman/luci,Wedmer/luci,rogerpueyo/luci,Wedmer/luci,aa65535/luci,cshore/luci,981213/luci-1,taiha/luci,chris5560/openwrt-luci,LuttyYang/luci,artynet/luci,artynet/luci,cshore-firmware/openwrt-luci,bright-things/ionic-luci,cshore/luci,lbthomsen/openwrt-luci,cshore-firmware/openwrt-luci,nmav/luci,cshore/luci,openwrt/luci,cshore-firmware/openwrt-luci,Noltari/luci,aa65535/luci,Wedmer/luci,openwrt-es/openwrt-luci,remakeelectric/luci,oneru/luci,kuoruan/luci,teslamint/luci,shangjiyu/luci-with-extra,tobiaswaldvogel/luci,rogerpueyo/luci,taiha/luci,Wedmer/luci,hnyman/luci,rogerpueyo/luci,Wedmer/luci,teslamint/luci,mumuqz/luci,wongsyrone/luci-1,ollie27/openwrt_luci,remakeelectric/luci,LuttyYang/luci,kuoruan/luci,hnyman/luci,kuoruan/luci,teslamint/luci,openwrt-es/openwrt-luci,mumuqz/luci,tobiaswaldvogel/luci,LuttyYang/luci,openwrt-es/openwrt-luci,artynet/luci,bittorf/luci,rogerpueyo/luci,hnyman/luci,remakeelectric/luci,kuoruan/lede-luci,chris5560/openwrt-luci,cshore-firmware/openwrt-luci,wongsyrone/luci-1,tobiaswaldvogel/luci,openwrt/luci,teslamint/luci,cshore/luci,Noltari/luci,bittorf/luci,openwrt/luci,lbthomsen/openwrt-luci,nmav/luci,wongsyrone/luci-1,aa65535/luci,wongsyrone/luci-1,cshore/luci,daofeng2015/luci,taiha/luci,bright-things/ionic-luci,openwrt/luci,aa65535/luci,teslamint/luci,kuoruan/luci
|
88e0b1760069b42cf006237d740e798657399f5e
|
modules/admin-full/luasrc/model/cbi/admin_services/dnsmasq.lua
|
modules/admin-full/luasrc/model/cbi/admin_services/dnsmasq.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("dhcp", "Dnsmasq")
s = m:section(TypedSection, "dnsmasq", translate("Settings"))
s.anonymous = true
s:option(Flag, "domainneeded")
s:option(Flag, "authoritative")
s:option(Flag, "boguspriv")
s:option(Flag, "filterwin2k")
s:option(Flag, "localise_queries")
s:option(Value, "local")
s:option(Value, "domain")
s:option(Flag, "expandhosts")
s:option(Flag, "nonegcache")
s:option(Flag, "readethers")
s:option(Value, "leasefile")
s:option(Value, "resolvfile")
s:option(Flag, "nohosts").optional = true
s:option(Flag, "strictorder").optional = true
s:option(Flag, "logqueries").optional = true
s:option(Flag, "noresolv").optional = true
s:option(Value, "dnsforwardmax").optional = true
s:option(Value, "port").optional = true
s:option(Value, "ednspacket_max").optional = true
s:option(Value, "dhcpleasemax").optional = true
s:option(Value, "addnhosts").optional = true
s:option(Value, "queryport").optional = true
s:option(Flag, "enable_tftp").optional = true
s:option(Value, "tftp_root").optional = true
s:option(Value, "dhcp_boot").optional = true
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("dhcp", "Dnsmasq",
translate("Dnsmasq is a combined <abbr title=\"Dynamic Host Configuration Protocol" ..
"\">DHCP</abbr>-Server and <abbr title=\"Domain Name System\">DNS</abbr>-" ..
"Forwarder for <abbr title=\"Network Address Translation\">NAT</abbr> " ..
"firewalls"))
s = m:section(TypedSection, "dnsmasq", translate("Settings"))
s.anonymous = true
s.addremove = false
s:option(Flag, "domainneeded",
translate("Domain required"),
translate("Don't forward <abbr title=\"Domain Name System\">DNS</abbr>-Requests without " ..
"<abbr title=\"Domain Name System\">DNS</abbr>-Name"))
s:option(Flag, "authoritative",
translate("Authoritative"),
translate("This is the only <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</" ..
"abbr> in the local network"))
s:option(Flag, "boguspriv",
translate("Filter private"),
translate("Don't forward reverse lookups for local networks"))
s:option(Flag, "filterwin2k",
translate("Filter useless"),
translate("filter useless <abbr title=\"Domain Name System\">DNS</abbr>-queries of " ..
"Windows-systems"))
s:option(Flag, "localise_queries",
translate("Localise queries"),
translate("localises the hostname depending on its subnet"))
s:option(Value, "local",
translate("Local Server"))
s:option(Value, "domain",
translate("Local Domain"))
s:option(Flag, "expandhosts",
translate("Expand Hosts"),
translate("adds domain names to hostentries in the resolv file"))
s:option(Flag, "nonegcache",
translate("don't cache unknown"),
translate("prevents caching of negative <abbr title=\"Domain Name System\">DNS</abbr>-" ..
"replies"))
s:option(Flag, "readethers",
translate("Use <code>/etc/ethers</code>"),
translate("Read <code>/etc/ethers</code> to configure the <abbr title=\"Dynamic Host " ..
"Configuration Protocol\">DHCP</abbr>-Server"))
s:option(Value, "leasefile",
translate("Leasefile"),
translate("file where given <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</" ..
"abbr>-leases will be stored"))
s:option(Value, "resolvfile",
translate("Resolvfile"),
translate("local <abbr title=\"Domain Name System\">DNS</abbr> file"))
s:option(Flag, "nohosts",
translate("Ignore <code>/etc/hosts</code>")).optional = true
s:option(Flag, "strictorder",
translate("Strict order"),
translate("<abbr title=\"Domain Name System\">DNS</abbr>-Server will be queried in the " ..
"order of the resolvfile")).optional = true
s:option(Flag, "logqueries",
translate("Log queries")).optional = true
s:option(Flag, "noresolv",
translate("Ignore resolve file")).optional = true
s:option(Value, "dnsforwardmax",
translate("concurrent queries")).optional = true
s:option(Value, "port",
translate("<abbr title=\"Domain Name System\">DNS</abbr>-Port")).optional = true
s:option(Value, "ednspacket_max",
translate("<abbr title=\"maximal\">max.</abbr> <abbr title=\"Extension Mechanisms for " ..
"Domain Name System\">EDNS0</abbr> paket size")).optional = true
s:option(Value, "dhcpleasemax",
translate("<abbr title=\"maximal\">max.</abbr> <abbr title=\"Dynamic Host Configuration " ..
"Protocol\">DHCP</abbr>-Leases")).optional = true
s:option(Value, "addnhosts",
translate("additional hostfile")).optional = true
s:option(Value, "queryport",
translate("query port")).optional = true
s:option(Flag, "enable_tftp",
translate("Enable TFTP-Server")).optional = true
s:option(Value, "tftp_root",
translate("TFTP-Server Root")).optional = true
s:option(Value, "dhcp_boot",
translate("Network Boot Image")).optional = true
return m
|
modules/admin-full: fix dnsmasq page
|
modules/admin-full: fix dnsmasq page
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5462 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
projectbismark/luci-bismark,vhpham80/luci,phi-psi/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,ch3n2k/luci,freifunk-gluon/luci,freifunk-gluon/luci,gwlim/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,dtaht/cerowrt-luci-3.3,phi-psi/luci,projectbismark/luci-bismark,jschmidlapp/luci,8devices/carambola2-luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,saraedum/luci-packages-old,freifunk-gluon/luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,jschmidlapp/luci,vhpham80/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,gwlim/luci,saraedum/luci-packages-old,vhpham80/luci,freifunk-gluon/luci,stephank/luci,ThingMesh/openwrt-luci,gwlim/luci,dtaht/cerowrt-luci-3.3,Flexibity/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,gwlim/luci,jschmidlapp/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,Canaan-Creative/luci,Flexibity/luci,Flexibity/luci,8devices/carambola2-luci,vhpham80/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,ch3n2k/luci,eugenesan/openwrt-luci,ch3n2k/luci,gwlim/luci,projectbismark/luci-bismark,8devices/carambola2-luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,freifunk-gluon/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,gwlim/luci,stephank/luci,projectbismark/luci-bismark,vhpham80/luci,phi-psi/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,ThingMesh/openwrt-luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,Flexibity/luci,phi-psi/luci,ch3n2k/luci,Canaan-Creative/luci,saraedum/luci-packages-old,phi-psi/luci,Flexibity/luci,phi-psi/luci,ThingMesh/openwrt-luci,stephank/luci,stephank/luci,zwhfly/openwrt-luci,jschmidlapp/luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,ch3n2k/luci,vhpham80/luci,freifunk-gluon/luci,Canaan-Creative/luci,yeewang/openwrt-luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,jschmidlapp/luci,Flexibity/luci,Canaan-Creative/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,stephank/luci,eugenesan/openwrt-luci,Flexibity/luci,Canaan-Creative/luci,jschmidlapp/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,Canaan-Creative/luci,stephank/luci,8devices/carambola2-luci,Canaan-Creative/luci,phi-psi/luci,ch3n2k/luci
|
281df50da5e782d6410a07056f44975c704e4350
|
frontend/cache.lua
|
frontend/cache.lua
|
--[[
A global LRU cache
]]--
require("MD5")
local lfs = require("libs/libkoreader-lfs")
local DEBUG = require("dbg")
local function calcFreeMem()
local meminfo = io.open("/proc/meminfo", "r")
local freemem = 0
if meminfo then
for line in meminfo:lines() do
local free, buffer, cached, n
free, n = line:gsub("^MemFree:%s-(%d+) kB", "%1")
if n ~= 0 then freemem = freemem + tonumber(free)*1024 end
buffer, n = line:gsub("^Buffers:%s-(%d+) kB", "%1")
if n ~= 0 then freemem = freemem + tonumber(buffer)*1024 end
cached, n = line:gsub("^Cached:%s-(%d+) kB", "%1")
if n ~= 0 then freemem = freemem + tonumber(cached)*1024 end
end
meminfo:close()
end
return freemem
end
local function calcCacheMemSize()
local min = DGLOBAL_CACHE_SIZE_MINIMUM
local max = DGLOBAL_CACHE_SIZE_MAXIMUM
local calc = calcFreeMem()*(DGLOBAL_CACHE_FREE_PROPORTION or 0)
return math.min(max, math.max(min, calc))
end
local cache_path = lfs.currentdir().."/cache/"
--[[
-- return a snapshot of disk cached items for subsequent check
--]]
function getDiskCache()
local cached = {}
for key_md5 in lfs.dir(cache_path) do
local file = cache_path..key_md5
if lfs.attributes(file, "mode") == "file" then
cached[key_md5] = file
end
end
return cached
end
local Cache = {
-- cache configuration:
max_memsize = calcCacheMemSize(),
-- cache state:
current_memsize = 0,
-- associative cache
cache = {},
-- this will hold the LRU order of the cache
cache_order = {},
-- disk Cache snapshot
cached = getDiskCache(),
}
function Cache:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function Cache:insert(key, object)
-- guarantee that we have enough memory in cache
if(object.size > self.max_memsize) then
-- we're not allowed to claim this much at all
error("too much memory claimed")
end
-- delete objects that least recently used
-- (they are at the end of the cache_order array)
while self.current_memsize + object.size > self.max_memsize do
local removed_key = table.remove(self.cache_order)
self.current_memsize = self.current_memsize - self.cache[removed_key].size
self.cache[removed_key]:onFree()
self.cache[removed_key] = nil
end
-- insert new object in front of the LRU order
table.insert(self.cache_order, 1, key)
self.cache[key] = object
self.current_memsize = self.current_memsize + object.size
end
--[[
-- check for cache item for key
-- if ItemClass is given, disk cache is also checked.
--]]
function Cache:check(key, ItemClass)
if self.cache[key] then
if self.cache_order[1] ~= key then
-- put key in front of the LRU list
for k, v in ipairs(self.cache_order) do
if v == key then
table.remove(self.cache_order, k)
end
end
table.insert(self.cache_order, 1, key)
end
return self.cache[key]
elseif ItemClass then
local cached = self.cached[md5(key)]
if cached then
local item = ItemClass:new{}
local ok, msg = pcall(item.load, item, cached)
if ok then
self:insert(key, item)
return item
else
DEBUG("discard cache", msg)
end
end
end
end
function Cache:willAccept(size)
-- we only allow single objects to fill 75% of the cache
if size*4 < self.max_memsize*3 then
return true
end
end
function Cache:serialize()
-- calculate disk cache size
local cached_size = 0
local sorted_caches = {}
for _,file in pairs(self.cached) do
table.insert(sorted_caches, {file=file, time=lfs.attributes(file, "access")})
cached_size = cached_size + (lfs.attributes(file, "size") or 0)
end
table.sort(sorted_caches, function(v1,v2) return v1.time > v2.time end)
-- serialize the most recently used cache
local cache_size = 0
for _, key in ipairs(self.cache_order) do
if self.cache[key].dump then
cache_size = self.cache[key]:dump(cache_path..md5(key)) or 0
if cache_size > 0 then break end
end
end
-- set disk cache the same limit as memory cache
while cached_size + cache_size - self.max_memsize > 0 do
-- discard the least recently used cache
local discarded = table.remove(sorted_caches)
cached_size = cached_size - lfs.attributes(discarded.file, "size")
os.remove(discarded.file)
end
-- disk cache may have changes so need to refresh disk cache snapshot
self.cached = getDiskCache()
end
-- blank the cache
function Cache:clear()
for k, _ in pairs(self.cache) do
self.cache[k]:onFree()
end
self.cache = {}
self.cache_order = {}
self.current_memsize = 0
end
return Cache
|
--[[
A global LRU cache
]]--
require("MD5")
local lfs = require("libs/libkoreader-lfs")
local DEBUG = require("dbg")
local function calcFreeMem()
local meminfo = io.open("/proc/meminfo", "r")
local freemem = 0
if meminfo then
for line in meminfo:lines() do
local free, buffer, cached, n
free, n = line:gsub("^MemFree:%s-(%d+) kB", "%1")
if n ~= 0 then freemem = freemem + tonumber(free)*1024 end
buffer, n = line:gsub("^Buffers:%s-(%d+) kB", "%1")
if n ~= 0 then freemem = freemem + tonumber(buffer)*1024 end
cached, n = line:gsub("^Cached:%s-(%d+) kB", "%1")
if n ~= 0 then freemem = freemem + tonumber(cached)*1024 end
end
meminfo:close()
end
return freemem
end
local function calcCacheMemSize()
local min = DGLOBAL_CACHE_SIZE_MINIMUM
local max = DGLOBAL_CACHE_SIZE_MAXIMUM
local calc = calcFreeMem()*(DGLOBAL_CACHE_FREE_PROPORTION or 0)
return math.min(max, math.max(min, calc))
end
local cache_path = lfs.currentdir().."/cache/"
--[[
-- return a snapshot of disk cached items for subsequent check
--]]
function getDiskCache()
local cached = {}
for key_md5 in lfs.dir(cache_path) do
local file = cache_path..key_md5
if lfs.attributes(file, "mode") == "file" then
cached[key_md5] = file
end
end
return cached
end
local Cache = {
-- cache configuration:
max_memsize = calcCacheMemSize(),
-- cache state:
current_memsize = 0,
-- associative cache
cache = {},
-- this will hold the LRU order of the cache
cache_order = {},
-- disk Cache snapshot
cached = getDiskCache(),
}
function Cache:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function Cache:insert(key, object)
-- guarantee that we have enough memory in cache
if(object.size > self.max_memsize) then
DEBUG("too much memory claimed for", key)
return
end
-- delete objects that least recently used
-- (they are at the end of the cache_order array)
while self.current_memsize + object.size > self.max_memsize do
local removed_key = table.remove(self.cache_order)
self.current_memsize = self.current_memsize - self.cache[removed_key].size
self.cache[removed_key]:onFree()
self.cache[removed_key] = nil
end
-- insert new object in front of the LRU order
table.insert(self.cache_order, 1, key)
self.cache[key] = object
self.current_memsize = self.current_memsize + object.size
end
--[[
-- check for cache item for key
-- if ItemClass is given, disk cache is also checked.
--]]
function Cache:check(key, ItemClass)
if self.cache[key] then
if self.cache_order[1] ~= key then
-- put key in front of the LRU list
for k, v in ipairs(self.cache_order) do
if v == key then
table.remove(self.cache_order, k)
end
end
table.insert(self.cache_order, 1, key)
end
return self.cache[key]
elseif ItemClass then
local cached = self.cached[md5(key)]
if cached then
local item = ItemClass:new{}
local ok, msg = pcall(item.load, item, cached)
if ok then
self:insert(key, item)
return item
else
DEBUG("discard cache", msg)
end
end
end
end
function Cache:willAccept(size)
-- we only allow single objects to fill 75% of the cache
if size*4 < self.max_memsize*3 then
return true
end
end
function Cache:serialize()
-- calculate disk cache size
local cached_size = 0
local sorted_caches = {}
for _,file in pairs(self.cached) do
table.insert(sorted_caches, {file=file, time=lfs.attributes(file, "access")})
cached_size = cached_size + (lfs.attributes(file, "size") or 0)
end
table.sort(sorted_caches, function(v1,v2) return v1.time > v2.time end)
-- serialize the most recently used cache
local cache_size = 0
for _, key in ipairs(self.cache_order) do
if self.cache[key].dump then
cache_size = self.cache[key]:dump(cache_path..md5(key)) or 0
if cache_size > 0 then break end
end
end
-- set disk cache the same limit as memory cache
while cached_size + cache_size - self.max_memsize > 0 do
-- discard the least recently used cache
local discarded = table.remove(sorted_caches)
cached_size = cached_size - lfs.attributes(discarded.file, "size")
os.remove(discarded.file)
end
-- disk cache may have changes so need to refresh disk cache snapshot
self.cached = getDiskCache()
end
-- blank the cache
function Cache:clear()
for k, _ in pairs(self.cache) do
self.cache[k]:onFree()
end
self.cache = {}
self.cache_order = {}
self.current_memsize = 0
end
return Cache
|
fix #1028
|
fix #1028
|
Lua
|
agpl-3.0
|
NickSavage/koreader,poire-z/koreader,ashhher3/koreader,mihailim/koreader,koreader/koreader,pazos/koreader,lgeek/koreader,apletnev/koreader,houqp/koreader,Frenzie/koreader,koreader/koreader,Frenzie/koreader,NiLuJe/koreader,Markismus/koreader,NiLuJe/koreader,frankyifei/koreader,poire-z/koreader,mwoz123/koreader,robert00s/koreader,chihyang/koreader,ashang/koreader,chrox/koreader,Hzj-jie/koreader,noname007/koreader
|
362ab0e1c675c8788a186ee25af2a6f7aaec248f
|
modules/game_healthbar/healthbar.lua
|
modules/game_healthbar/healthbar.lua
|
HealthBar = {}
-- constants
local Icons = {}
Icons[1] = { tooltip = tr('You are poisoned'), path = '/game_healthbar/icons/poisoned.png', id = 'condition_poisoned' }
Icons[2] = { tooltip = tr('You are burning'), path = '/game_healthbar/icons/burning.png', id = 'condition_burning' }
Icons[4] = { tooltip = tr('You are electrified'), path = '/game_healthbar/icons/electrified.png', id = 'condition_electrified' }
Icons[8] = { tooltip = tr('You are freezing'), path = '/game_healthbar/icons/drunk.png', id = 'condition_drunk' }
Icons[16] = { tooltip = tr('You are protected by a magic shield'), path = '/game_healthbar/icons/magic_shield.png', id = 'condition_magic_shield' }
Icons[32] = { tooltip = tr('You are paralysed'), path = '/game_healthbar/icons/slowed.png', id = 'condition_slowed' }
Icons[64] = { tooltip = tr('You are hasted'), path = '/game_healthbar/icons/haste.png', id = 'condition_haste' }
Icons[128] = { tooltip = tr('You may not logout during a fight'), path = '/game_healthbar/icons/logout_block.png', id = 'condition_logout_block' }
Icons[256] = { tooltip = tr('You are drowing'), path = '/game_healthbar/icons/drowning.png', id = 'condition_drowning' }
Icons[512] = { tooltip = tr('You are freezing'), path = '/game_healthbar/icons/freezing.png', id = 'condition_freezing' }
Icons[1024] = { tooltip = tr('You are dazzled'), path = '/game_healthbar/icons/dazzled.png', id = 'condition_dazzled' }
Icons[2048] = { tooltip = tr('You are cursed'), path = '/game_healthbar/icons/cursed.png', id = 'condition_cursed' }
Icons[4096] = { tooltip = tr('You are strengthened'), path = '/game_healthbar/icons/strengthened.png', id = 'condition_strengthened' }
Icons[8192] = { tooltip = tr('You may not logout or enter a protection zone'), path = '/game_healthbar/icons/protection_zone_block.png', id = 'condition_protection_zone_block' }
Icons[16384] = { tooltip = tr('You are within a protection zone'), path = '/game_healthbar/icons/protection_zone.png', id = 'condition_protection_zone' }
Icons[32768] = { tooltip = tr('You are bleeding'), path = '/game_healthbar/icons/bleeding.png', id = 'condition_bleeding' }
Icons[65536] = { tooltip = tr('You are hungry'), path = '/game_healthbar/icons/hungry.png', id = 'condition_hungry' }
-- private variables
local healthBarWindow
local healthBar
local manaBar
local healthLabel
local manaLabel
-- public functions
function HealthBar.init()
connect(LocalPlayer, { onHealthChange = HealthBar.onHealthChange,
onManaChange = HealthBar.onManaChange,
onStatesChange = HealthBar.onStatesChange })
connect(g_game, { onGameEnd = HealthBar.offline })
healthBarWindow = displayUI('healthbar.otui', GameInterface.getLeftPanel())
healthBarButton = TopMenu.addGameToggleButton('healthBarButton', tr('Health Bar'), 'healthbar.png', HealthBar.toggle)
healthBarButton:setOn(true)
healthBar = healthBarWindow:recursiveGetChildById('healthBar')
manaBar = healthBarWindow:recursiveGetChildById('manaBar')
healthLabel = healthBarWindow:recursiveGetChildById('healthLabel')
manaLabel = healthBarWindow:recursiveGetChildById('manaLabel')
if g_game.isOnline() then
local localPlayer = g_game.getLocalPlayer()
HealthBar.onHealthChange(localPlayer, localPlayer:getHealth(), localPlayer:getMaxHealth())
HealthBar.onManaChange(localPlayer, localPlayer:getMana(), localPlayer:getMaxMana())
end
end
function HealthBar.terminate()
disconnect(LocalPlayer, { onHealthChange = HealthBar.onHealthChange,
onManaChange = HealthBar.onManaChange,
onStatesChange = HealthBar.onStatesChange })
disconnect(g_game, { onGameEnd = HealthBar.offline })
healthBarWindow:destroy()
healthBarButton:destroy()
healthBarWindow = nil
healthBarButton = nil
healthBar = nil
manaBar = nil
healthLabel = nil
manaLabel = nil
HealthBar = nil
end
function HealthBar.toggle()
local visible = not healthBarWindow:isExplicitlyVisible()
healthBarWindow:setVisible(visible)
healthBarButton:setOn(visible)
end
function HealthBar.offline()
healthBarWindow:recursiveGetChildById('conditions_content'):destroyChildren()
end
-- hooked events
function HealthBar.onHealthChange(localPlayer, health, maxHealth)
healthLabel:setText(health .. ' / ' .. maxHealth)
healthBar:setPercent(health / maxHealth * 100)
end
function HealthBar.onManaChange(localPlayer, mana, maxMana)
manaLabel:setText(mana .. ' / ' .. maxMana)
local percent
if maxMana == 0 then
percent = 100
else
percent = (mana * 100)/maxMana
end
manaBar:setPercent(percent)
end
function HealthBar.onStatesChange(localPlayer, now, old)
local bitsChanged = bit32.bxor(now, old)
for i = 1, 32 do
local pow = math.pow(2, i-1)
if pow > bitsChanged then break end
local bitChanged = bit32.band(bitsChanged, pow)
if bitChanged ~= 0 then
HealthBar.toggleIcon(bitChanged)
end
end
end
function HealthBar.toggleIcon(bitChanged)
local content = healthBarWindow:recursiveGetChildById('conditions_content')
local icon = content:getChildById(Icons[bitChanged].id)
if icon then
icon:destroy()
else
icon = createWidget('ConditionWidget', content)
icon:setId(Icons[bitChanged].id)
icon:setImageSource(Icons[bitChanged].path)
icon:setTooltip(Icons[bitChanged].tooltip)
end
end
|
HealthBar = {}
-- constants
local Icons = {}
Icons[1] = { tooltip = tr('You are poisoned'), path = '/game_healthbar/icons/poisoned.png', id = 'condition_poisoned' }
Icons[2] = { tooltip = tr('You are burning'), path = '/game_healthbar/icons/burning.png', id = 'condition_burning' }
Icons[4] = { tooltip = tr('You are electrified'), path = '/game_healthbar/icons/electrified.png', id = 'condition_electrified' }
Icons[8] = { tooltip = tr('You are freezing'), path = '/game_healthbar/icons/drunk.png', id = 'condition_drunk' }
Icons[16] = { tooltip = tr('You are protected by a magic shield'), path = '/game_healthbar/icons/magic_shield.png', id = 'condition_magic_shield' }
Icons[32] = { tooltip = tr('You are paralysed'), path = '/game_healthbar/icons/slowed.png', id = 'condition_slowed' }
Icons[64] = { tooltip = tr('You are hasted'), path = '/game_healthbar/icons/haste.png', id = 'condition_haste' }
Icons[128] = { tooltip = tr('You may not logout during a fight'), path = '/game_healthbar/icons/logout_block.png', id = 'condition_logout_block' }
Icons[256] = { tooltip = tr('You are drowing'), path = '/game_healthbar/icons/drowning.png', id = 'condition_drowning' }
Icons[512] = { tooltip = tr('You are freezing'), path = '/game_healthbar/icons/freezing.png', id = 'condition_freezing' }
Icons[1024] = { tooltip = tr('You are dazzled'), path = '/game_healthbar/icons/dazzled.png', id = 'condition_dazzled' }
Icons[2048] = { tooltip = tr('You are cursed'), path = '/game_healthbar/icons/cursed.png', id = 'condition_cursed' }
Icons[4096] = { tooltip = tr('You are strengthened'), path = '/game_healthbar/icons/strengthened.png', id = 'condition_strengthened' }
Icons[8192] = { tooltip = tr('You may not logout or enter a protection zone'), path = '/game_healthbar/icons/protection_zone_block.png', id = 'condition_protection_zone_block' }
Icons[16384] = { tooltip = tr('You are within a protection zone'), path = '/game_healthbar/icons/protection_zone.png', id = 'condition_protection_zone' }
Icons[32768] = { tooltip = tr('You are bleeding'), path = '/game_healthbar/icons/bleeding.png', id = 'condition_bleeding' }
Icons[65536] = { tooltip = tr('You are hungry'), path = '/game_healthbar/icons/hungry.png', id = 'condition_hungry' }
-- private variables
local healthBarWindow
local healthBar
local manaBar
local healthLabel
local manaLabel
-- public functions
function HealthBar.init()
connect(LocalPlayer, { onHealthChange = HealthBar.onHealthChange,
onManaChange = HealthBar.onManaChange,
onStatesChange = HealthBar.onStatesChange })
connect(g_game, { onGameEnd = HealthBar.offline })
healthBarWindow = displayUI('healthbar.otui', GameInterface.getLeftPanel())
healthBarButton = TopMenu.addGameToggleButton('healthBarButton', tr('Health Bar'), 'healthbar.png', HealthBar.toggle)
healthBarButton:setOn(true)
healthBar = healthBarWindow:recursiveGetChildById('healthBar')
manaBar = healthBarWindow:recursiveGetChildById('manaBar')
healthLabel = healthBarWindow:recursiveGetChildById('healthLabel')
manaLabel = healthBarWindow:recursiveGetChildById('manaLabel')
if g_game.isOnline() then
local localPlayer = g_game.getLocalPlayer()
HealthBar.onHealthChange(localPlayer, localPlayer:getHealth(), localPlayer:getMaxHealth())
HealthBar.onManaChange(localPlayer, localPlayer:getMana(), localPlayer:getMaxMana())
HealthBar.onStatesChange(localPlayer, localPlayer:getStates(), 0)
end
end
function HealthBar.terminate()
disconnect(LocalPlayer, { onHealthChange = HealthBar.onHealthChange,
onManaChange = HealthBar.onManaChange,
onStatesChange = HealthBar.onStatesChange })
disconnect(g_game, { onGameEnd = HealthBar.offline })
healthBarWindow:destroy()
healthBarButton:destroy()
healthBarWindow = nil
healthBarButton = nil
healthBar = nil
manaBar = nil
healthLabel = nil
manaLabel = nil
HealthBar = nil
end
function HealthBar.toggle()
local visible = not healthBarWindow:isExplicitlyVisible()
healthBarWindow:setVisible(visible)
healthBarButton:setOn(visible)
end
function HealthBar.offline()
healthBarWindow:recursiveGetChildById('conditions_content'):destroyChildren()
end
-- hooked events
function HealthBar.onHealthChange(localPlayer, health, maxHealth)
healthLabel:setText(health .. ' / ' .. maxHealth)
healthBar:setPercent(health / maxHealth * 100)
end
function HealthBar.onManaChange(localPlayer, mana, maxMana)
manaLabel:setText(mana .. ' / ' .. maxMana)
local percent
if maxMana == 0 then
percent = 100
else
percent = (mana * 100)/maxMana
end
manaBar:setPercent(percent)
end
function HealthBar.onStatesChange(localPlayer, now, old)
if now == old then return end
local bitsChanged = bit32.bxor(now, old)
for i = 1, 32 do
local pow = math.pow(2, i-1)
if pow > bitsChanged then break end
local bitChanged = bit32.band(bitsChanged, pow)
if bitChanged ~= 0 then
HealthBar.toggleIcon(bitChanged)
end
end
end
function HealthBar.toggleIcon(bitChanged)
local content = healthBarWindow:recursiveGetChildById('conditions_content')
local icon = content:getChildById(Icons[bitChanged].id)
if icon then
icon:destroy()
else
icon = createWidget('ConditionWidget', content)
icon:setId(Icons[bitChanged].id)
icon:setImageSource(Icons[bitChanged].path)
icon:setTooltip(Icons[bitChanged].tooltip)
end
end
|
fix conditions on reload
|
fix conditions on reload
|
Lua
|
mit
|
dreamsxin/otclient,dreamsxin/otclient,dreamsxin/otclient,gpedro/otclient,Radseq/otclient,Cavitt/otclient_mapgen,gpedro/otclient,kwketh/otclient,EvilHero90/otclient,EvilHero90/otclient,Radseq/otclient,kwketh/otclient,gpedro/otclient,Cavitt/otclient_mapgen
|
eacdb3fce4c723c44c512b4c8bdd961defbbcd06
|
defaut/Guerrier.lua
|
defaut/Guerrier.lua
|
Ovale.defaut["WARRIOR"] =
[[
Define(THUNDERCLAP 6343)
Define(SHOCKWAVE 46968)
Define(DEMOSHOUT 1160)
Define(COMMANDSHOUT 469)
Define(BATTLESHOUT 2048)
Define(REVENGE 6572)
Define(SHIELDSLAM 23922)
Define(DEVASTATE 20243)
Define(VICTORY 34428)
Define(EXECUTE 5308)
Define(BLOODTHIRST 23881)
Define(WHIRLWIND 1680)
Define(SLAMBUFF 46916)
Define(SLAM 1464)
Define(MORTALSTRIKE 12294)
Define(SLAMTALENT 2233)
Define(CLEAVE 845)
Define(HEROICSTRIKE 78)
Define(SUNDER 7386)
Define(CONCUSSIONBLOW 12809)
Define(REND 772)
Define(OVERPOWER 7384)
Define(SHIELDBLOCK 2565)
Define(SHIELDWALL 871)
Define(LASTSTAND 12975)
Define(DEATHWISH 12292)
Define(RECKLESSNESS 1719)
Define(BLADESTORM 46924)
Define(DEMORALIZINGROAR 48560)
Define(CURSEOFWEAKNESS 50511)
AddCheckBox(multi L(AOE))
AddCheckBox(demo SpellName(DEMOSHOUT))
AddCheckBox(whirlwind SpellName(WHIRLWIND))
AddListItem(shout none L(None))
AddListItem(shout battle SpellName(BATTLESHOUT))
AddListItem(shout command SpellName(COMMANDSHOUT))
AddIcon
{
if List(shout command) and
BuffExpires(COMMANDSHOUT 3)
Spell(COMMANDSHOUT)
if List(shout battle) and BuffExpires(BATTLESHOUT 3)
Spell(BATTLESHOUT)
if TargetClassification(worldboss)
and CheckBoxOn(demo)
and TargetDebuffExpires(DEMOSHOUT 2)
and TargetDebuffExpires(DEMORALIZINGROAR 0)
and TargetDebuffExpires(CURSEOFWEAKNESS 0)
Spell(DEMOSHOUT)
if Stance(2) #Defense
{
if TargetClassification(worldboss)
and TargetDebuffExpires(THUNDERCLAP 2)
Spell(THUNDERCLAP)
if CheckBoxOn(multi)
{
Spell(THUNDERCLAP)
Spell(SHOCKWAVE)
}
Spell(REVENGE usable=1)
Spell(SHIELDSLAM)
Spell(BLOODTHIRST)
if Mana(more 10) Spell(DEVASTATE priority=2)
}
if Stance(3) #berserker
{
Spell(VICTORY usable=1)
if TargetLifePercent(less 20)
{
Spell(WHIRLWIND)
Spell(BLOODTHIRST)
if BuffPresent(SLAMBUFF) and Mana(more 29) Spell(SLAM)
Spell(EXECUTE)
}
if HasShield() Spell(SHIELDSLAM)
Spell(SHOCKWAVE)
Spell(CONCUSSIONBLOW)
if CheckBoxOn(whirlwind) Spell(WHIRLWIND)
Spell(BLOODTHIRST)
if BuffPresent(SLAMBUFF) Spell(SLAM)
Spell(MORTALSTRIKE)
Spell(DEVASTATE)
if TalentPoints(SLAMTALENT more 1)
Spell(SLAM)
}
if Stance(1) #combat
{
Spell(VICTORY usable=1)
Spell(OVERPOWER usable=1)
Spell(MORTALSTRIKE)
Spell(REND)
Spell(SHIELDSLAM usable=1)
Spell(SHOCKWAVE)
Spell(CONCUSSIONBLOW)
Spell(DEVASTATE)
if TalentPoints(SLAMTALENT more 1)
Spell(SLAM)
}
if TargetDebuffExpires(SUNDER 5 stacks=5)
Spell(SUNDER)
}
AddIcon
{
if Mana(more 66)
{
if CheckBoxOn(multi)
Spell(CLEAVE doNotRepeat=1)
if CheckBoxOff(multi)
Spell(HEROICSTRIKE doNotRepeat=1)
}
}
AddIcon
{
if Stance(2) #Defense
{
Spell(SHIELDBLOCK)
Spell(LASTSTAND)
Spell(SHIELDWALL)
}
if Stance(3) #berserker
{
Spell(DEATHWISH)
Spell(RECKLESSNESS)
}
if Stance(1) #combat
{
Spell(BLADESTORM)
}
}
]]
|
Ovale.defaut["WARRIOR"] =
[[
Define(THUNDERCLAP 6343)
Define(SHOCKWAVE 46968)
Define(DEMOSHOUT 1160)
Define(COMMANDSHOUT 469)
Define(BATTLESHOUT 2048)
Define(REVENGE 6572)
Define(SHIELDSLAM 23922)
Define(DEVASTATE 20243)
Define(VICTORY 34428)
Define(EXECUTE 5308)
Define(BLOODTHIRST 23881)
Define(WHIRLWIND 1680)
Define(SLAMBUFF 46916)
Define(SLAM 1464)
Define(MORTALSTRIKE 12294)
Define(SLAMTALENT 2233)
Define(CLEAVE 845)
Define(HEROICSTRIKE 78)
Define(SUNDER 7386)
Define(CONCUSSIONBLOW 12809)
Define(REND 772)
Define(OVERPOWER 7384)
Define(SHIELDBLOCK 2565)
Define(SHIELDWALL 871)
Define(LASTSTAND 12975)
Define(DEATHWISH 12292)
Define(RECKLESSNESS 1719)
Define(BLADESTORM 46924)
Define(SUDDENDEATH 52437)
Define(RETALIATION 20230)
Define(DEMORALIZINGROAR 48560)
Define(CURSEOFWEAKNESS 50511)
AddCheckBox(multi L(AOE))
AddCheckBox(demo SpellName(DEMOSHOUT))
AddCheckBox(whirlwind SpellName(WHIRLWIND))
AddListItem(shout none L(None))
AddListItem(shout battle SpellName(BATTLESHOUT))
AddListItem(shout command SpellName(COMMANDSHOUT))
AddIcon
{
if List(shout command) and
BuffExpires(COMMANDSHOUT 3)
Spell(COMMANDSHOUT)
if List(shout battle) and BuffExpires(BATTLESHOUT 3)
Spell(BATTLESHOUT)
if TargetClassification(worldboss)
and CheckBoxOn(demo)
and TargetDebuffExpires(DEMOSHOUT 2)
and TargetDebuffExpires(DEMORALIZINGROAR 0)
and TargetDebuffExpires(CURSEOFWEAKNESS 0)
Spell(DEMOSHOUT)
if Stance(2) #Defense
{
if TargetClassification(worldboss)
and TargetDebuffExpires(THUNDERCLAP 2)
Spell(THUNDERCLAP)
if CheckBoxOn(multi)
{
Spell(THUNDERCLAP)
Spell(SHOCKWAVE)
}
Spell(REVENGE usable=1)
Spell(SHIELDSLAM)
Spell(BLOODTHIRST)
if Mana(more 10) Spell(DEVASTATE priority=2)
}
if Stance(3) #berserker
{
Spell(VICTORY usable=1)
if TargetLifePercent(less 20)
{
Spell(WHIRLWIND)
Spell(BLOODTHIRST)
if BuffPresent(SLAMBUFF) and Mana(more 29) Spell(SLAM)
Spell(EXECUTE)
}
if HasShield() Spell(SHIELDSLAM)
Spell(SHOCKWAVE)
Spell(CONCUSSIONBLOW)
if CheckBoxOn(whirlwind) Spell(WHIRLWIND)
Spell(BLOODTHIRST)
if BuffPresent(SLAMBUFF) Spell(SLAM)
Spell(MORTALSTRIKE)
Spell(DEVASTATE)
if TalentPoints(SLAMTALENT more 1)
Spell(SLAM)
}
if Stance(1) #combat
{
Spell(VICTORY usable=1)
if TargetDebuffExpires(REND 0) Spell(REND)
if BuffPresent(SUDDENDEATH) or TargetLifePercent(less 20) Spell(EXECUTE)
Spell(MORTALSTRIKE)
Spell(OVERPOWER usable=1)
if TalentPoints(SLAMTALENT more 1)
Spell(SLAM priority=2)
#Some other specs stuff, just in case
Spell(BLOODTHIRST)
if HasShield() Spell(SHIELDSLAM)
Spell(SHOCKWAVE)
Spell(CONCUSSIONBLOW)
Spell(DEVASTATE)
}
if TargetDebuffExpires(SUNDER 5 stacks=5)
Spell(SUNDER)
}
AddIcon
{
if Mana(more 66)
{
if CheckBoxOn(multi)
Spell(CLEAVE doNotRepeat=1)
if CheckBoxOff(multi)
Spell(HEROICSTRIKE doNotRepeat=1)
}
}
AddIcon
{
if Stance(2) #Defense
{
Spell(SHIELDBLOCK)
Spell(LASTSTAND)
Spell(SHIELDWALL)
}
if Stance(3) #berserker
{
Spell(DEATHWISH)
Spell(RECKLESSNESS)
}
if Stance(1) #combat
{
Spell(BLADESTORM)
Spell(RETALIATION)
}
}
]]
|
- fixed arm warrior default script, which was VERY bad
|
- fixed arm warrior default script, which was VERY bad
git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@45 d5049fe3-3747-40f7-a4b5-f36d6801af5f
|
Lua
|
mit
|
ultijlam/ovale,eXhausted/Ovale,eXhausted/Ovale,ultijlam/ovale,ultijlam/ovale,eXhausted/Ovale,Xeltor/ovale
|
eb7ae363ce8e3de4c6ab7428edf3fe7f15a59396
|
share/lua/playlist/youtube.lua
|
share/lua/playlist/youtube.lua
|
--[[
$Id$
Copyright © 2007-2011 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Helper function to get a parameter's value in a URL
function get_url_param( url, name )
local _, _, res = string.find( url, "[&?]"..name.."=([^&]*)" )
return res
end
function get_arturl( path, video_id )
if string.match( vlc.path, "iurl=" ) then
return vlc.strings( get_url_param( vlc.path, "iurl" ) )
end
if not arturl then
return "http://img.youtube.com/vi/"..video_id.."/default.jpg"
end
end
-- Probe function.
function probe()
if vlc.access ~= "http" and vlc.access ~= "https" then
return false
end
youtube_site = string.match( string.sub( vlc.path, 1, 8 ), "youtube" )
if not youtube_site then
-- FIXME we should be using a builtin list of known youtube websites
-- like "fr.youtube.com", "uk.youtube.com" etc..
youtube_site = string.find( vlc.path, ".youtube.com" )
if youtube_site == nil then
return false
end
end
return ( string.match( vlc.path, "watch%?v=" ) -- the html page
or string.match( vlc.path, "watch_fullscreen%?video_id=" ) -- the fullscreen page
or string.match( vlc.path, "p.swf" ) -- the (old?) player url
or string.match( vlc.path, "jp.swf" ) -- the (new?) player url (as of 24/08/2007)
or string.match( vlc.path, "player2.swf" ) ) -- another player url
end
-- Parse function.
function parse()
if string.match( vlc.path, "watch%?v=" )
then -- This is the HTML page's URL
-- fmt is the format of the video
-- (cf. http://en.wikipedia.org/wiki/YouTube#Quality_and_codecs)
fmt = get_url_param( vlc.path, "fmt" )
while true do
-- Try to find the video's title
line = vlc.readline()
if not line then break end
if string.match( line, "<meta name=\"title\"" ) then
_,_,name = string.find( line, "content=\"(.-)\"" )
name = vlc.strings.resolve_xml_special_chars( name )
name = vlc.strings.resolve_xml_special_chars( name )
end
if string.match( line, "<meta name=\"description\"" ) then
-- Don't ask me why they double encode ...
_,_,description = string.find( line, "content=\"(.-)\"" )
description = vlc.strings.resolve_xml_special_chars( description )
description = vlc.strings.resolve_xml_special_chars( description )
end
if string.match( line, "subscribe_to_user=" ) then
_,_,artist = string.find( line, "subscribe_to_user=([^&]*)" )
end
-- JSON parameters, also formerly known as "swfConfig",
-- "SWF_ARGS", "swfArgs" ...
if string.match( line, "PLAYER_CONFIG" ) then
url_map = string.match( line, "\"url_encoded_fmt_stream_map\": \"(.-)\"" )
if url_map then
-- FIXME: do this properly
url_map = string.gsub( url_map, "\\u0026", "&" )
for url,itag in string.gmatch( url_map, "url=([^&,]+).-&itag=(%d+)" ) do
-- Apparently formats are listed in quality order,
-- so we can afford to simply take the first one
if not fmt or tonumber( itag ) == tonumber( fmt ) then
url = vlc.strings.decode_uri( url )
path = url
break
end
end
end
-- There is also another version of the parameters, encoded
-- differently, as an HTML attribute of an <object> or <embed>
-- tag; but we don't need it now
end
end
video_id = get_url_param( vlc.path, "v" )
arturl = get_arturl( vlc.path, video_id )
if not path then
vlc.msg.err( "Couldn't extract youtube video URL, please check for updates to this script" )
return { }
end
return { { path = path; name = name; description = description; artist = artist; arturl = arturl } }
else -- This is the flash player's URL
if string.match( vlc.path, "title=" ) then
name = vlc.strings.decode_uri(get_url_param( vlc.path, "title" ))
end
video_id = get_url_param( vlc.path, "video_id" )
arturl = get_arturl( vlc.path, video_id )
fmt = get_url_param( vlc.path, "fmt" )
if fmt then
format = "&fmt=" .. fmt
else
format = ""
end
if not string.match( vlc.path, "t=" ) then
-- This sucks, we're missing "t" which is now mandatory. Let's
-- try using another url
return { { path = "http://www.youtube.com/v/"..video_id; name = name; arturl = arturl } }
end
return { { path = "http://www.youtube.com/get_video.php?video_id="..video_id.."&t="..get_url_param( vlc.path, "t" )..format; name = name; arturl = arturl } }
end
end
|
--[[
$Id$
Copyright © 2007-2011 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Helper function to get a parameter's value in a URL
function get_url_param( url, name )
local _, _, res = string.find( url, "[&?]"..name.."=([^&]*)" )
return res
end
function get_arturl( path, video_id )
if string.match( vlc.path, "iurl=" ) then
return vlc.strings( get_url_param( vlc.path, "iurl" ) )
end
if not arturl then
return "http://img.youtube.com/vi/"..video_id.."/default.jpg"
end
end
-- Probe function.
function probe()
if vlc.access ~= "http" and vlc.access ~= "https" then
return false
end
youtube_site = string.match( string.sub( vlc.path, 1, 8 ), "youtube" )
if not youtube_site then
-- FIXME we should be using a builtin list of known youtube websites
-- like "fr.youtube.com", "uk.youtube.com" etc..
youtube_site = string.find( vlc.path, ".youtube.com" )
if youtube_site == nil then
return false
end
end
return ( string.match( vlc.path, "watch%?v=" ) -- the html page
or string.match( vlc.path, "watch_fullscreen%?video_id=" ) -- the fullscreen page
or string.match( vlc.path, "p.swf" ) -- the (old?) player url
or string.match( vlc.path, "jp.swf" ) -- the (new?) player url (as of 24/08/2007)
or string.match( vlc.path, "player2.swf" ) ) -- another player url
end
-- Parse function.
function parse()
if string.match( vlc.path, "watch%?v=" )
then -- This is the HTML page's URL
-- fmt is the format of the video
-- (cf. http://en.wikipedia.org/wiki/YouTube#Quality_and_codecs)
fmt = get_url_param( vlc.path, "fmt" )
while true do
-- Try to find the video's title
line = vlc.readline()
if not line then break end
if string.match( line, "<meta name=\"title\"" ) then
_,_,name = string.find( line, "content=\"(.-)\"" )
name = vlc.strings.resolve_xml_special_chars( name )
name = vlc.strings.resolve_xml_special_chars( name )
end
if string.match( line, "<meta name=\"description\"" ) then
-- Don't ask me why they double encode ...
_,_,description = string.find( line, "content=\"(.-)\"" )
description = vlc.strings.resolve_xml_special_chars( description )
description = vlc.strings.resolve_xml_special_chars( description )
end
if string.match( line, " rel=\"author\"" ) then
_,_,artist = string.find( line, "href=\"/user/([^\"]*)\"" )
end
-- JSON parameters, also formerly known as "swfConfig",
-- "SWF_ARGS", "swfArgs" ...
if string.match( line, "PLAYER_CONFIG" ) then
url_map = string.match( line, "\"url_encoded_fmt_stream_map\": \"(.-)\"" )
if url_map then
-- FIXME: do this properly
url_map = string.gsub( url_map, "\\u0026", "&" )
for url,itag in string.gmatch( url_map, "url=([^&,]+).-&itag=(%d+)" ) do
-- Apparently formats are listed in quality order,
-- so we can afford to simply take the first one
if not fmt or tonumber( itag ) == tonumber( fmt ) then
url = vlc.strings.decode_uri( url )
path = url
break
end
end
end
-- There is also another version of the parameters, encoded
-- differently, as an HTML attribute of an <object> or <embed>
-- tag; but we don't need it now
end
end
video_id = get_url_param( vlc.path, "v" )
arturl = get_arturl( vlc.path, video_id )
if not path then
vlc.msg.err( "Couldn't extract youtube video URL, please check for updates to this script" )
return { }
end
return { { path = path; name = name; description = description; artist = artist; arturl = arturl } }
else -- This is the flash player's URL
if string.match( vlc.path, "title=" ) then
name = vlc.strings.decode_uri(get_url_param( vlc.path, "title" ))
end
video_id = get_url_param( vlc.path, "video_id" )
arturl = get_arturl( vlc.path, video_id )
fmt = get_url_param( vlc.path, "fmt" )
if fmt then
format = "&fmt=" .. fmt
else
format = ""
end
if not string.match( vlc.path, "t=" ) then
-- This sucks, we're missing "t" which is now mandatory. Let's
-- try using another url
return { { path = "http://www.youtube.com/v/"..video_id; name = name; arturl = arturl } }
end
return { { path = "http://www.youtube.com/get_video.php?video_id="..video_id.."&t="..get_url_param( vlc.path, "t" )..format; name = name; arturl = arturl } }
end
end
|
youtube.lua: fix fetching of uploader's name
|
youtube.lua: fix fetching of uploader's name
|
Lua
|
lgpl-2.1
|
shyamalschandra/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,krichter722/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,krichter722/vlc,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,shyamalschandra/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.2,krichter722/vlc,jomanmuk/vlc-2.1,krichter722/vlc,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc,shyamalschandra/vlc,xkfz007/vlc
|
9da2b344ed926a98e92d4a6fa0e43322fd13614c
|
src/cosy/connexion/js.lua
|
src/cosy/connexion/js.lua
|
require "cosy.lang.cosy"
js.global.cosy = cosy
local observed = require "cosy.lang.view.observed"
observed [#observed + 1] = require "cosy.lang.view.update"
cosy = observed (cosy)
local sha1 = require "sha1"
local json = require "dkjson"
local seq = require "cosy.lang.iterators" . seq
local set = require "cosy.lang.iterators" . set
local map = require "cosy.lang.iterators" . map
local raw = require "cosy.lang.data" . raw
local tags = require "cosy.lang.tags"
local update = require "cosy.lang.view.update"
local type = require "cosy.util.type"
local WS = tags.WS
local RESOURCE = tags.RESOURCE
local UPDATES = tags.UPDATES
local function connect (parameters)
local token = parameters.token
local resource = parameters.resource
local editor = parameters.editor
local ws = js.global:websocket (editor)
local result = {
[RESOURCE] = resource,
[WS ] = ws,
[UPDATES ] = {},
}
ws.token = token
function ws:onopen ()
ws:request {
action = "set-resource",
token = token,
resource = resource,
}
end
function ws:onclose ()
result [WS] = nil
end
function ws:onmessage (event)
local message = event.data
print (message)
if not message then
return
end
local command = json.decode (message)
if command.action == "update" then
update.from_patch = true
for patch in seq (command.patches) do
print ("Applying patch " .. tostring (patch.data))
pcall (loadstring, patch.data)
end
update.from_patch = nil
else
-- do nothing
end
end
function ws:onerror ()
ws:close ()
end
function ws:request (command)
local str = json.encode (command)
command.request_id = sha1 (tostring (os.time()) .. "+" .. str)
command.token = ws.token
if ws.readyState == 1 then
ws:send (json.encode (command))
end
end
function ws:patch (str)
local command = {
action = "add-patch",
data = str,
}
local str = json.encode (command)
command.request_id = sha1 (tostring (os.time()) .. "+" .. str)
command.token = ws.token
if ws.readyState == 1 then
ws:send (json.encode (command))
end
end
cosy [resource] = result
return cosy [resource]
end
function window:count (x)
return #x
end
function window:id (x)
if type (x) == "table" then
local mt = getmetatable (x)
setmetatable (x, nil)
local result = tostring (x)
setmetatable (x, mt)
return result
else
return tostring (x)
end
end
function window:keys (x)
local result = {}
for key, _ in pairs (x) do
result [#result + 1] = key
end
return result
end
function window:elements (model)
local TYPE = tags.TYPE
local function set_of (e)
local result = {}
for _, x in map (e) do
if type (x) . table and x [TYPE] then
result [raw (x)] = true
elseif type (x) . table then
for y in seq (set_of (x)) do
result [y] = true
end
end
end
return result
end
local result = {}
for x in set (set_of (model)) do
result [#result + 1] = x
end
return result
end
function window:connect (editor, token, resource)
return connect {
editor = editor,
token = token,
resource = resource,
}
end
|
require "cosy.lang.cosy"
js.global.cosy = cosy
local observed = require "cosy.lang.view.observed"
observed [#observed + 1] = require "cosy.lang.view.update"
cosy = observed (cosy)
local sha1 = require "sha1"
local json = require "dkjson"
local seq = require "cosy.lang.iterators" . seq
local set = require "cosy.lang.iterators" . set
local map = require "cosy.lang.iterators" . map
local raw = require "cosy.lang.data" . raw
local tags = require "cosy.lang.tags"
local update = require "cosy.lang.view.update"
local type = require "cosy.util.type"
local WS = tags.WS
local RESOURCE = tags.RESOURCE
local UPDATES = tags.UPDATES
local function connect (parameters)
local token = parameters.token
local resource = parameters.resource
local editor = parameters.editor
local ws = js.global:websocket (editor)
local result = {
[RESOURCE] = resource,
[WS ] = ws,
[UPDATES ] = {},
}
ws.token = token
function ws:onopen ()
ws:request {
action = "set-resource",
token = token,
resource = resource,
}
end
function ws:onclose ()
result [WS] = nil
end
function ws:onmessage (event)
local message = event.data
print (message)
if not message then
return
end
local command = json.decode (message)
if command.action == "update" then
update.from_patch = true
for patch in seq (command.patches) do
print ("Applying patch " .. tostring (patch.data))
pcall (loadstring, patch.data)
end
update.from_patch = nil
else
-- do nothing
end
end
function ws:onerror ()
ws:close ()
end
function ws:request (command)
local str = json.encode (command)
command.request_id = sha1 (tostring (os.time()) .. "+" .. str)
command.token = ws.token
if ws.readyState == 1 then
ws:send (json.encode (command))
end
end
function ws:patch (str)
local command = {
action = "add-patch",
data = str,
}
local str = json.encode (command)
command.request_id = sha1 (tostring (os.time()) .. "+" .. str)
command.token = ws.token
if ws.readyState == 1 then
ws:send (json.encode (command))
end
end
cosy [resource] = result
return cosy [resource]
end
function window:count (x)
return #x
end
function window:id (x)
if type (x) == "table" then
local mt = getmetatable (x)
setmetatable (x, nil)
local result = tostring (x)
setmetatable (x, mt)
return result
else
return tostring (x)
end
end
function window:keys (x)
local result = {}
for key, _ in pairs (x) do
result [#result + 1] = key
end
return result
end
function window:elements (model)
local function set_of (e)
local result = {}
for k, x in map (e) do
if type (k) . tag and not k.persistent then
-- nothing
elseif type (x) . table then
if x.type then
result [raw (x)] = true
end
for y in set (set_of (x)) do
result [y] = true
end
end
end
return result
end
local result = {}
for x in set (set_of (model)) do
result [#result + 1] = x
end
return result
end
function window:connect (editor, token, resource)
return connect {
editor = editor,
token = token,
resource = resource,
}
end
|
Fix elements function.
|
Fix elements function.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.