repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
MalRD/darkstar | scripts/globals/items/salmon_croute.lua | 11 | 1471 | -----------------------------------------
-- ID: 4551
-- Item: salmon_croute
-- Food Effect: 30Min, All Races
-----------------------------------------
-- MP +3% (cap 130)
-- Dexterity 2
-- MND -2
-- Ranged Accuracy +6% (cap 15)
-- HP recovered while healing 2
-- MP recovered while healing 1
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,1800,4551)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.FOOD_MPP, 3)
target:addMod(dsp.mod.FOOD_MP_CAP, 130)
target:addMod(dsp.mod.DEX, 2)
target:addMod(dsp.mod.MND, -2)
target:addMod(dsp.mod.FOOD_RACCP, 6)
target:addMod(dsp.mod.FOOD_RACC_CAP, 15)
target:addMod(dsp.mod.HPHEAL, 2)
target:addMod(dsp.mod.MPHEAL, 1)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.FOOD_MPP, 3)
target:delMod(dsp.mod.FOOD_MP_CAP, 130)
target:delMod(dsp.mod.DEX, 2)
target:delMod(dsp.mod.MND, -2)
target:delMod(dsp.mod.FOOD_RACCP, 6)
target:delMod(dsp.mod.FOOD_RACC_CAP, 15)
target:delMod(dsp.mod.HPHEAL, 2)
target:delMod(dsp.mod.MPHEAL, 1)
end
| gpl-3.0 |
Lsty/ygopro-scripts | c5399521.lua | 3 | 3238 | --音響戦士マイクス
function c5399521.initial_effect(c)
--pendulum summon
aux.AddPendulumProcedure(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--scale
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_CHANGE_LSCALE)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_PZONE)
e2:SetCondition(c5399521.slcon)
e2:SetValue(4)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EFFECT_CHANGE_RSCALE)
c:RegisterEffect(e3)
--tohand
local e4=Effect.CreateEffect(c)
e4:SetCategory(CATEGORY_TOHAND)
e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e4:SetProperty(EFFECT_FLAG_CARD_TARGET)
e4:SetCode(EVENT_PHASE+PHASE_END)
e4:SetRange(LOCATION_PZONE)
e4:SetCountLimit(1)
e4:SetCondition(c5399521.thcon)
e4:SetTarget(c5399521.thtg)
e4:SetOperation(c5399521.thop)
c:RegisterEffect(e4)
--spsummon
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_FIELD)
e5:SetCode(EFFECT_SPSUMMON_PROC)
e5:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e5:SetRange(LOCATION_HAND)
e5:SetCondition(c5399521.spcon)
e5:SetOperation(c5399521.spop)
c:RegisterEffect(e5)
--extra summon
local e6=Effect.CreateEffect(c)
e6:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e6:SetCode(EVENT_SUMMON_SUCCESS)
e6:SetOperation(c5399521.sumop)
c:RegisterEffect(e6)
local e7=e6:Clone()
e7:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e7)
end
function c5399521.thcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function c5399521.thfilter(c)
return c:IsFaceup() and c:IsSetCard(0x1066) and c:IsAbleToHand()
end
function c5399521.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_REMOVED) and c5399521.thfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c5399521.thfilter,tp,LOCATION_REMOVED,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,c5399521.thfilter,tp,LOCATION_REMOVED,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function c5399521.thop(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,tc)
end
end
function c5399521.slcon(e)
local seq=e:GetHandler():GetSequence()
local tc=Duel.GetFieldCard(e:GetHandlerPlayer(),LOCATION_SZONE,13-seq)
return not tc or not tc:IsSetCard(0x1066)
end
function c5399521.spcon(e,c)
if c==nil then return true end
local tp=c:GetControler()
return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsCanRemoveCounter(tp,1,0,0x35,3,REASON_COST)
end
function c5399521.spop(e,tp,eg,ep,ev,re,r,rp,c)
Duel.RemoveCounter(tp,1,0,0x35,3,REASON_COST)
end
function c5399521.sumop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetFlagEffect(tp,5399521)~=0 then return end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetTargetRange(LOCATION_HAND+LOCATION_MZONE,0)
e1:SetCode(EFFECT_EXTRA_SUMMON_COUNT)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
Duel.RegisterFlagEffect(tp,5399521,RESET_PHASE+PHASE_END,0,1)
end
| gpl-2.0 |
cshore-firmware/openwrt-luci | modules/luci-base/luasrc/cbi.lua | 19 | 42590 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.cbi", package.seeall)
require("luci.template")
local util = require("luci.util")
require("luci.http")
--local event = require "luci.sys.event"
local fs = require("nixio.fs")
local uci = require("luci.model.uci")
local datatypes = require("luci.cbi.datatypes")
local dispatcher = require("luci.dispatcher")
local class = util.class
local instanceof = util.instanceof
FORM_NODATA = 0
FORM_PROCEED = 0
FORM_VALID = 1
FORM_DONE = 1
FORM_INVALID = -1
FORM_CHANGED = 2
FORM_SKIP = 4
AUTO = true
CREATE_PREFIX = "cbi.cts."
REMOVE_PREFIX = "cbi.rts."
RESORT_PREFIX = "cbi.sts."
FEXIST_PREFIX = "cbi.cbe."
-- Loads a CBI map from given file, creating an environment and returns it
function load(cbimap, ...)
local fs = require "nixio.fs"
local i18n = require "luci.i18n"
require("luci.config")
require("luci.util")
local upldir = "/etc/luci-uploads/"
local cbidir = luci.util.libpath() .. "/model/cbi/"
local func, err
if fs.access(cbidir..cbimap..".lua") then
func, err = loadfile(cbidir..cbimap..".lua")
elseif fs.access(cbimap) then
func, err = loadfile(cbimap)
else
func, err = nil, "Model '" .. cbimap .. "' not found!"
end
assert(func, err)
local env = {
translate=i18n.translate,
translatef=i18n.translatef,
arg={...}
}
setfenv(func, setmetatable(env, {__index =
function(tbl, key)
return rawget(tbl, key) or _M[key] or _G[key]
end}))
local maps = { func() }
local uploads = { }
local has_upload = false
for i, map in ipairs(maps) do
if not instanceof(map, Node) then
error("CBI map returns no valid map object!")
return nil
else
map:prepare()
if map.upload_fields then
has_upload = true
for _, field in ipairs(map.upload_fields) do
uploads[
field.config .. '.' ..
(field.section.sectiontype or '1') .. '.' ..
field.option
] = true
end
end
end
end
if has_upload then
local uci = luci.model.uci.cursor()
local prm = luci.http.context.request.message.params
local fd, cbid
luci.http.setfilehandler(
function( field, chunk, eof )
if not field then return end
if field.name and not cbid then
local c, s, o = field.name:gmatch(
"cbid%.([^%.]+)%.([^%.]+)%.([^%.]+)"
)()
if c and s and o then
local t = uci:get( c, s ) or s
if uploads[c.."."..t.."."..o] then
local path = upldir .. field.name
fd = io.open(path, "w")
if fd then
cbid = field.name
prm[cbid] = path
end
end
end
end
if field.name == cbid and fd then
fd:write(chunk)
end
if eof and fd then
fd:close()
fd = nil
cbid = nil
end
end
)
end
return maps
end
--
-- Compile a datatype specification into a parse tree for evaluation later on
--
local cdt_cache = { }
function compile_datatype(code)
local i
local pos = 0
local esc = false
local depth = 0
local stack = { }
for i = 1, #code+1 do
local byte = code:byte(i) or 44
if esc then
esc = false
elseif byte == 92 then
esc = true
elseif byte == 40 or byte == 44 then
if depth <= 0 then
if pos < i then
local label = code:sub(pos, i-1)
:gsub("\\(.)", "%1")
:gsub("^%s+", "")
:gsub("%s+$", "")
if #label > 0 and tonumber(label) then
stack[#stack+1] = tonumber(label)
elseif label:match("^'.*'$") or label:match('^".*"$') then
stack[#stack+1] = label:gsub("[\"'](.*)[\"']", "%1")
elseif type(datatypes[label]) == "function" then
stack[#stack+1] = datatypes[label]
stack[#stack+1] = { }
else
error("Datatype error, bad token %q" % label)
end
end
pos = i + 1
end
depth = depth + (byte == 40 and 1 or 0)
elseif byte == 41 then
depth = depth - 1
if depth <= 0 then
if type(stack[#stack-1]) ~= "function" then
error("Datatype error, argument list follows non-function")
end
stack[#stack] = compile_datatype(code:sub(pos, i-1))
pos = i + 1
end
end
end
return stack
end
function verify_datatype(dt, value)
if dt and #dt > 0 then
if not cdt_cache[dt] then
local c = compile_datatype(dt)
if c and type(c[1]) == "function" then
cdt_cache[dt] = c
else
error("Datatype error, not a function expression")
end
end
if cdt_cache[dt] then
return cdt_cache[dt][1](value, unpack(cdt_cache[dt][2]))
end
end
return true
end
-- Node pseudo abstract class
Node = class()
function Node.__init__(self, title, description)
self.children = {}
self.title = title or ""
self.description = description or ""
self.template = "cbi/node"
end
-- hook helper
function Node._run_hook(self, hook)
if type(self[hook]) == "function" then
return self[hook](self)
end
end
function Node._run_hooks(self, ...)
local f
local r = false
for _, f in ipairs(arg) do
if type(self[f]) == "function" then
self[f](self)
r = true
end
end
return r
end
-- Prepare nodes
function Node.prepare(self, ...)
for k, child in ipairs(self.children) do
child:prepare(...)
end
end
-- Append child nodes
function Node.append(self, obj)
table.insert(self.children, obj)
end
-- Parse this node and its children
function Node.parse(self, ...)
for k, child in ipairs(self.children) do
child:parse(...)
end
end
-- Render this node
function Node.render(self, scope)
scope = scope or {}
scope.self = self
luci.template.render(self.template, scope)
end
-- Render the children
function Node.render_children(self, ...)
local k, node
for k, node in ipairs(self.children) do
node.last_child = (k == #self.children)
node.index = k
node:render(...)
end
end
--[[
A simple template element
]]--
Template = class(Node)
function Template.__init__(self, template)
Node.__init__(self)
self.template = template
end
function Template.render(self)
luci.template.render(self.template, {self=self})
end
function Template.parse(self, readinput)
self.readinput = (readinput ~= false)
return Map.formvalue(self, "cbi.submit") and FORM_DONE or FORM_NODATA
end
--[[
Map - A map describing a configuration file
]]--
Map = class(Node)
function Map.__init__(self, config, ...)
Node.__init__(self, ...)
self.config = config
self.parsechain = {self.config}
self.template = "cbi/map"
self.apply_on_parse = nil
self.readinput = true
self.proceed = false
self.flow = {}
self.uci = uci.cursor()
self.save = true
self.changed = false
local path = "%s/%s" %{ self.uci:get_confdir(), self.config }
if fs.stat(path, "type") ~= "reg" then
fs.writefile(path, "")
end
local ok, err = self.uci:load(self.config)
if not ok then
local url = dispatcher.build_url(unpack(dispatcher.context.request))
local source = self:formvalue("cbi.source")
if type(source) == "string" then
fs.writefile(path, source:gsub("\r\n", "\n"))
ok, err = self.uci:load(self.config)
if ok then
luci.http.redirect(url)
end
end
self.save = false
end
if not ok then
self.template = "cbi/error"
self.error = err
self.source = fs.readfile(path) or ""
self.pageaction = false
end
end
function Map.formvalue(self, key)
return self.readinput and luci.http.formvalue(key) or nil
end
function Map.formvaluetable(self, key)
return self.readinput and luci.http.formvaluetable(key) or {}
end
function Map.get_scheme(self, sectiontype, option)
if not option then
return self.scheme and self.scheme.sections[sectiontype]
else
return self.scheme and self.scheme.variables[sectiontype]
and self.scheme.variables[sectiontype][option]
end
end
function Map.submitstate(self)
return self:formvalue("cbi.submit")
end
-- Chain foreign config
function Map.chain(self, config)
table.insert(self.parsechain, config)
end
function Map.state_handler(self, state)
return state
end
-- Use optimized UCI writing
function Map.parse(self, readinput, ...)
if self:formvalue("cbi.skip") then
self.state = FORM_SKIP
elseif not self.save then
self.state = FORM_INVALID
elseif not self:submitstate() then
self.state = FORM_NODATA
end
-- Back out early to prevent unauthorized changes on the subsequent parse
if self.state ~= nil then
return self:state_handler(self.state)
end
self.readinput = (readinput ~= false)
self:_run_hooks("on_parse")
Node.parse(self, ...)
if self.save then
self:_run_hooks("on_save", "on_before_save")
for i, config in ipairs(self.parsechain) do
self.uci:save(config)
end
self:_run_hooks("on_after_save")
if (not self.proceed and self.flow.autoapply) or luci.http.formvalue("cbi.apply") then
self:_run_hooks("on_before_commit")
for i, config in ipairs(self.parsechain) do
self.uci:commit(config)
-- Refresh data because commit changes section names
self.uci:load(config)
end
self:_run_hooks("on_commit", "on_after_commit", "on_before_apply")
if self.apply_on_parse then
self.uci:apply(self.parsechain)
self:_run_hooks("on_apply", "on_after_apply")
else
-- This is evaluated by the dispatcher and delegated to the
-- template which in turn fires XHR to perform the actual
-- apply actions.
self.apply_needed = true
end
-- Reparse sections
Node.parse(self, true)
end
for i, config in ipairs(self.parsechain) do
self.uci:unload(config)
end
if type(self.commit_handler) == "function" then
self:commit_handler(self:submitstate())
end
end
if not self.save then
self.state = FORM_INVALID
elseif self.proceed then
self.state = FORM_PROCEED
elseif self.changed then
self.state = FORM_CHANGED
else
self.state = FORM_VALID
end
return self:state_handler(self.state)
end
function Map.render(self, ...)
self:_run_hooks("on_init")
Node.render(self, ...)
end
-- Creates a child section
function Map.section(self, class, ...)
if instanceof(class, AbstractSection) then
local obj = class(self, ...)
self:append(obj)
return obj
else
error("class must be a descendent of AbstractSection")
end
end
-- UCI add
function Map.add(self, sectiontype)
return self.uci:add(self.config, sectiontype)
end
-- UCI set
function Map.set(self, section, option, value)
if type(value) ~= "table" or #value > 0 then
if option then
return self.uci:set(self.config, section, option, value)
else
return self.uci:set(self.config, section, value)
end
else
return Map.del(self, section, option)
end
end
-- UCI del
function Map.del(self, section, option)
if option then
return self.uci:delete(self.config, section, option)
else
return self.uci:delete(self.config, section)
end
end
-- UCI get
function Map.get(self, section, option)
if not section then
return self.uci:get_all(self.config)
elseif option then
return self.uci:get(self.config, section, option)
else
return self.uci:get_all(self.config, section)
end
end
--[[
Compound - Container
]]--
Compound = class(Node)
function Compound.__init__(self, ...)
Node.__init__(self)
self.template = "cbi/compound"
self.children = {...}
end
function Compound.populate_delegator(self, delegator)
for _, v in ipairs(self.children) do
v.delegator = delegator
end
end
function Compound.parse(self, ...)
local cstate, state = 0
for k, child in ipairs(self.children) do
cstate = child:parse(...)
state = (not state or cstate < state) and cstate or state
end
return state
end
--[[
Delegator - Node controller
]]--
Delegator = class(Node)
function Delegator.__init__(self, ...)
Node.__init__(self, ...)
self.nodes = {}
self.defaultpath = {}
self.pageaction = false
self.readinput = true
self.allow_reset = false
self.allow_cancel = false
self.allow_back = false
self.allow_finish = false
self.template = "cbi/delegator"
end
function Delegator.set(self, name, node)
assert(not self.nodes[name], "Duplicate entry")
self.nodes[name] = node
end
function Delegator.add(self, name, node)
node = self:set(name, node)
self.defaultpath[#self.defaultpath+1] = name
end
function Delegator.insert_after(self, name, after)
local n = #self.chain + 1
for k, v in ipairs(self.chain) do
if v == after then
n = k + 1
break
end
end
table.insert(self.chain, n, name)
end
function Delegator.set_route(self, ...)
local n, chain, route = 0, self.chain, {...}
for i = 1, #chain do
if chain[i] == self.current then
n = i
break
end
end
for i = 1, #route do
n = n + 1
chain[n] = route[i]
end
for i = n + 1, #chain do
chain[i] = nil
end
end
function Delegator.get(self, name)
local node = self.nodes[name]
if type(node) == "string" then
node = load(node, name)
end
if type(node) == "table" and getmetatable(node) == nil then
node = Compound(unpack(node))
end
return node
end
function Delegator.parse(self, ...)
if self.allow_cancel and Map.formvalue(self, "cbi.cancel") then
if self:_run_hooks("on_cancel") then
return FORM_DONE
end
end
if not Map.formvalue(self, "cbi.delg.current") then
self:_run_hooks("on_init")
end
local newcurrent
self.chain = self.chain or self:get_chain()
self.current = self.current or self:get_active()
self.active = self.active or self:get(self.current)
assert(self.active, "Invalid state")
local stat = FORM_DONE
if type(self.active) ~= "function" then
self.active:populate_delegator(self)
stat = self.active:parse()
else
self:active()
end
if stat > FORM_PROCEED then
if Map.formvalue(self, "cbi.delg.back") then
newcurrent = self:get_prev(self.current)
else
newcurrent = self:get_next(self.current)
end
elseif stat < FORM_PROCEED then
return stat
end
if not Map.formvalue(self, "cbi.submit") then
return FORM_NODATA
elseif stat > FORM_PROCEED
and (not newcurrent or not self:get(newcurrent)) then
return self:_run_hook("on_done") or FORM_DONE
else
self.current = newcurrent or self.current
self.active = self:get(self.current)
if type(self.active) ~= "function" then
self.active:populate_delegator(self)
local stat = self.active:parse(false)
if stat == FORM_SKIP then
return self:parse(...)
else
return FORM_PROCEED
end
else
return self:parse(...)
end
end
end
function Delegator.get_next(self, state)
for k, v in ipairs(self.chain) do
if v == state then
return self.chain[k+1]
end
end
end
function Delegator.get_prev(self, state)
for k, v in ipairs(self.chain) do
if v == state then
return self.chain[k-1]
end
end
end
function Delegator.get_chain(self)
local x = Map.formvalue(self, "cbi.delg.path") or self.defaultpath
return type(x) == "table" and x or {x}
end
function Delegator.get_active(self)
return Map.formvalue(self, "cbi.delg.current") or self.chain[1]
end
--[[
Page - A simple node
]]--
Page = class(Node)
Page.__init__ = Node.__init__
Page.parse = function() end
--[[
SimpleForm - A Simple non-UCI form
]]--
SimpleForm = class(Node)
function SimpleForm.__init__(self, config, title, description, data)
Node.__init__(self, title, description)
self.config = config
self.data = data or {}
self.template = "cbi/simpleform"
self.dorender = true
self.pageaction = false
self.readinput = true
end
SimpleForm.formvalue = Map.formvalue
SimpleForm.formvaluetable = Map.formvaluetable
function SimpleForm.parse(self, readinput, ...)
self.readinput = (readinput ~= false)
if self:formvalue("cbi.skip") then
return FORM_SKIP
end
if self:formvalue("cbi.cancel") and self:_run_hooks("on_cancel") then
return FORM_DONE
end
if self:submitstate() then
Node.parse(self, 1, ...)
end
local valid = true
for k, j in ipairs(self.children) do
for i, v in ipairs(j.children) do
valid = valid
and (not v.tag_missing or not v.tag_missing[1])
and (not v.tag_invalid or not v.tag_invalid[1])
and (not v.error)
end
end
local state =
not self:submitstate() and FORM_NODATA
or valid and FORM_VALID
or FORM_INVALID
self.dorender = not self.handle
if self.handle then
local nrender, nstate = self:handle(state, self.data)
self.dorender = self.dorender or (nrender ~= false)
state = nstate or state
end
return state
end
function SimpleForm.render(self, ...)
if self.dorender then
Node.render(self, ...)
end
end
function SimpleForm.submitstate(self)
return self:formvalue("cbi.submit")
end
function SimpleForm.section(self, class, ...)
if instanceof(class, AbstractSection) then
local obj = class(self, ...)
self:append(obj)
return obj
else
error("class must be a descendent of AbstractSection")
end
end
-- Creates a child field
function SimpleForm.field(self, class, ...)
local section
for k, v in ipairs(self.children) do
if instanceof(v, SimpleSection) then
section = v
break
end
end
if not section then
section = self:section(SimpleSection)
end
if instanceof(class, AbstractValue) then
local obj = class(self, section, ...)
obj.track_missing = true
section:append(obj)
return obj
else
error("class must be a descendent of AbstractValue")
end
end
function SimpleForm.set(self, section, option, value)
self.data[option] = value
end
function SimpleForm.del(self, section, option)
self.data[option] = nil
end
function SimpleForm.get(self, section, option)
return self.data[option]
end
function SimpleForm.get_scheme()
return nil
end
Form = class(SimpleForm)
function Form.__init__(self, ...)
SimpleForm.__init__(self, ...)
self.embedded = true
end
--[[
AbstractSection
]]--
AbstractSection = class(Node)
function AbstractSection.__init__(self, map, sectiontype, ...)
Node.__init__(self, ...)
self.sectiontype = sectiontype
self.map = map
self.config = map.config
self.optionals = {}
self.defaults = {}
self.fields = {}
self.tag_error = {}
self.tag_invalid = {}
self.tag_deperror = {}
self.changed = false
self.optional = true
self.addremove = false
self.dynamic = false
end
-- Define a tab for the section
function AbstractSection.tab(self, tab, title, desc)
self.tabs = self.tabs or { }
self.tab_names = self.tab_names or { }
self.tab_names[#self.tab_names+1] = tab
self.tabs[tab] = {
title = title,
description = desc,
childs = { }
}
end
-- Check whether the section has tabs
function AbstractSection.has_tabs(self)
return (self.tabs ~= nil) and (next(self.tabs) ~= nil)
end
-- Appends a new option
function AbstractSection.option(self, class, option, ...)
if instanceof(class, AbstractValue) then
local obj = class(self.map, self, option, ...)
self:append(obj)
self.fields[option] = obj
return obj
elseif class == true then
error("No valid class was given and autodetection failed.")
else
error("class must be a descendant of AbstractValue")
end
end
-- Appends a new tabbed option
function AbstractSection.taboption(self, tab, ...)
assert(tab and self.tabs and self.tabs[tab],
"Cannot assign option to not existing tab %q" % tostring(tab))
local l = self.tabs[tab].childs
local o = AbstractSection.option(self, ...)
if o then l[#l+1] = o end
return o
end
-- Render a single tab
function AbstractSection.render_tab(self, tab, ...)
assert(tab and self.tabs and self.tabs[tab],
"Cannot render not existing tab %q" % tostring(tab))
local k, node
for k, node in ipairs(self.tabs[tab].childs) do
node.last_child = (k == #self.tabs[tab].childs)
node.index = k
node:render(...)
end
end
-- Parse optional options
function AbstractSection.parse_optionals(self, section, noparse)
if not self.optional then
return
end
self.optionals[section] = {}
local field = nil
if not noparse then
field = self.map:formvalue("cbi.opt."..self.config.."."..section)
end
for k,v in ipairs(self.children) do
if v.optional and not v:cfgvalue(section) and not self:has_tabs() then
if field == v.option then
field = nil
self.map.proceed = true
else
table.insert(self.optionals[section], v)
end
end
end
if field and #field > 0 and self.dynamic then
self:add_dynamic(field)
end
end
-- Add a dynamic option
function AbstractSection.add_dynamic(self, field, optional)
local o = self:option(Value, field, field)
o.optional = optional
end
-- Parse all dynamic options
function AbstractSection.parse_dynamic(self, section)
if not self.dynamic then
return
end
local arr = luci.util.clone(self:cfgvalue(section))
local form = self.map:formvaluetable("cbid."..self.config.."."..section)
for k, v in pairs(form) do
arr[k] = v
end
for key,val in pairs(arr) do
local create = true
for i,c in ipairs(self.children) do
if c.option == key then
create = false
end
end
if create and key:sub(1, 1) ~= "." then
self.map.proceed = true
self:add_dynamic(key, true)
end
end
end
-- Returns the section's UCI table
function AbstractSection.cfgvalue(self, section)
return self.map:get(section)
end
-- Push events
function AbstractSection.push_events(self)
--luci.util.append(self.map.events, self.events)
self.map.changed = true
end
-- Removes the section
function AbstractSection.remove(self, section)
self.map.proceed = true
return self.map:del(section)
end
-- Creates the section
function AbstractSection.create(self, section)
local stat
if section then
stat = section:match("^[%w_]+$") and self.map:set(section, nil, self.sectiontype)
else
section = self.map:add(self.sectiontype)
stat = section
end
if stat then
for k,v in pairs(self.children) do
if v.default then
self.map:set(section, v.option, v.default)
end
end
for k,v in pairs(self.defaults) do
self.map:set(section, k, v)
end
end
self.map.proceed = true
return stat
end
SimpleSection = class(AbstractSection)
function SimpleSection.__init__(self, form, ...)
AbstractSection.__init__(self, form, nil, ...)
self.template = "cbi/nullsection"
end
Table = class(AbstractSection)
function Table.__init__(self, form, data, ...)
local datasource = {}
local tself = self
datasource.config = "table"
self.data = data or {}
datasource.formvalue = Map.formvalue
datasource.formvaluetable = Map.formvaluetable
datasource.readinput = true
function datasource.get(self, section, option)
return tself.data[section] and tself.data[section][option]
end
function datasource.submitstate(self)
return Map.formvalue(self, "cbi.submit")
end
function datasource.del(...)
return true
end
function datasource.get_scheme()
return nil
end
AbstractSection.__init__(self, datasource, "table", ...)
self.template = "cbi/tblsection"
self.rowcolors = true
self.anonymous = true
end
function Table.parse(self, readinput)
self.map.readinput = (readinput ~= false)
for i, k in ipairs(self:cfgsections()) do
if self.map:submitstate() then
Node.parse(self, k)
end
end
end
function Table.cfgsections(self)
local sections = {}
for i, v in luci.util.kspairs(self.data) do
table.insert(sections, i)
end
return sections
end
function Table.update(self, data)
self.data = data
end
--[[
NamedSection - A fixed configuration section defined by its name
]]--
NamedSection = class(AbstractSection)
function NamedSection.__init__(self, map, section, stype, ...)
AbstractSection.__init__(self, map, stype, ...)
-- Defaults
self.addremove = false
self.template = "cbi/nsection"
self.section = section
end
function NamedSection.prepare(self)
AbstractSection.prepare(self)
AbstractSection.parse_optionals(self, self.section, true)
end
function NamedSection.parse(self, novld)
local s = self.section
local active = self:cfgvalue(s)
if self.addremove then
local path = self.config.."."..s
if active then -- Remove the section
if self.map:formvalue("cbi.rns."..path) and self:remove(s) then
self:push_events()
return
end
else -- Create and apply default values
if self.map:formvalue("cbi.cns."..path) then
self:create(s)
return
end
end
end
if active then
AbstractSection.parse_dynamic(self, s)
if self.map:submitstate() then
Node.parse(self, s)
end
AbstractSection.parse_optionals(self, s)
if self.changed then
self:push_events()
end
end
end
--[[
TypedSection - A (set of) configuration section(s) defined by the type
addremove: Defines whether the user can add/remove sections of this type
anonymous: Allow creating anonymous sections
validate: a validation function returning nil if the section is invalid
]]--
TypedSection = class(AbstractSection)
function TypedSection.__init__(self, map, type, ...)
AbstractSection.__init__(self, map, type, ...)
self.template = "cbi/tsection"
self.deps = {}
self.anonymous = false
end
function TypedSection.prepare(self)
AbstractSection.prepare(self)
local i, s
for i, s in ipairs(self:cfgsections()) do
AbstractSection.parse_optionals(self, s, true)
end
end
-- Return all matching UCI sections for this TypedSection
function TypedSection.cfgsections(self)
local sections = {}
self.map.uci:foreach(self.map.config, self.sectiontype,
function (section)
if self:checkscope(section[".name"]) then
table.insert(sections, section[".name"])
end
end)
return sections
end
-- Limits scope to sections that have certain option => value pairs
function TypedSection.depends(self, option, value)
table.insert(self.deps, {option=option, value=value})
end
function TypedSection.parse(self, novld)
if self.addremove then
-- Remove
local crval = REMOVE_PREFIX .. self.config
local name = self.map:formvaluetable(crval)
for k,v in pairs(name) do
if k:sub(-2) == ".x" then
k = k:sub(1, #k - 2)
end
if self:cfgvalue(k) and self:checkscope(k) then
self:remove(k)
end
end
end
local co
for i, k in ipairs(self:cfgsections()) do
AbstractSection.parse_dynamic(self, k)
if self.map:submitstate() then
Node.parse(self, k, novld)
end
AbstractSection.parse_optionals(self, k)
end
if self.addremove then
-- Create
local created
local crval = CREATE_PREFIX .. self.config .. "." .. self.sectiontype
local origin, name = next(self.map:formvaluetable(crval))
if self.anonymous then
if name then
created = self:create(nil, origin)
end
else
if name then
-- Ignore if it already exists
if self:cfgvalue(name) then
name = nil;
end
name = self:checkscope(name)
if not name then
self.err_invalid = true
end
if name and #name > 0 then
created = self:create(name, origin) and name
if not created then
self.invalid_cts = true
end
end
end
end
if created then
AbstractSection.parse_optionals(self, created)
end
end
if self.sortable then
local stval = RESORT_PREFIX .. self.config .. "." .. self.sectiontype
local order = self.map:formvalue(stval)
if order and #order > 0 then
local sid
local num = 0
for sid in util.imatch(order) do
self.map.uci:reorder(self.config, sid, num)
num = num + 1
end
self.changed = (num > 0)
end
end
if created or self.changed then
self:push_events()
end
end
-- Verifies scope of sections
function TypedSection.checkscope(self, section)
-- Check if we are not excluded
if self.filter and not self:filter(section) then
return nil
end
-- Check if at least one dependency is met
if #self.deps > 0 and self:cfgvalue(section) then
local stat = false
for k, v in ipairs(self.deps) do
if self:cfgvalue(section)[v.option] == v.value then
stat = true
end
end
if not stat then
return nil
end
end
return self:validate(section)
end
-- Dummy validate function
function TypedSection.validate(self, section)
return section
end
--[[
AbstractValue - An abstract Value Type
null: Value can be empty
valid: A function returning the value if it is valid otherwise nil
depends: A table of option => value pairs of which one must be true
default: The default value
size: The size of the input fields
rmempty: Unset value if empty
optional: This value is optional (see AbstractSection.optionals)
]]--
AbstractValue = class(Node)
function AbstractValue.__init__(self, map, section, option, ...)
Node.__init__(self, ...)
self.section = section
self.option = option
self.map = map
self.config = map.config
self.tag_invalid = {}
self.tag_missing = {}
self.tag_reqerror = {}
self.tag_error = {}
self.deps = {}
--self.cast = "string"
self.track_missing = false
self.rmempty = true
self.default = nil
self.size = nil
self.optional = false
end
function AbstractValue.prepare(self)
self.cast = self.cast or "string"
end
-- Add a dependencie to another section field
function AbstractValue.depends(self, field, value)
local deps
if type(field) == "string" then
deps = {}
deps[field] = value
else
deps = field
end
table.insert(self.deps, deps)
end
-- Serialize dependencies
function AbstractValue.deplist2json(self, section, deplist)
local deps, i, d = { }
if type(self.deps) == "table" then
for i, d in ipairs(deplist or self.deps) do
local a, k, v = { }
for k, v in pairs(d) do
if k:find("!", 1, true) then
a[k] = v
elseif k:find(".", 1, true) then
a['cbid.%s' % k] = v
else
a['cbid.%s.%s.%s' %{ self.config, section, k }] = v
end
end
deps[#deps+1] = a
end
end
return util.serialize_json(deps)
end
-- Generates the unique CBID
function AbstractValue.cbid(self, section)
return "cbid."..self.map.config.."."..section.."."..self.option
end
-- Return whether this object should be created
function AbstractValue.formcreated(self, section)
local key = "cbi.opt."..self.config.."."..section
return (self.map:formvalue(key) == self.option)
end
-- Returns the formvalue for this object
function AbstractValue.formvalue(self, section)
return self.map:formvalue(self:cbid(section))
end
function AbstractValue.additional(self, value)
self.optional = value
end
function AbstractValue.mandatory(self, value)
self.rmempty = not value
end
function AbstractValue.add_error(self, section, type, msg)
self.error = self.error or { }
self.error[section] = msg or type
self.section.error = self.section.error or { }
self.section.error[section] = self.section.error[section] or { }
table.insert(self.section.error[section], msg or type)
if type == "invalid" then
self.tag_invalid[section] = true
elseif type == "missing" then
self.tag_missing[section] = true
end
self.tag_error[section] = true
self.map.save = false
end
function AbstractValue.parse(self, section, novld)
local fvalue = self:formvalue(section)
local cvalue = self:cfgvalue(section)
-- If favlue and cvalue are both tables and have the same content
-- make them identical
if type(fvalue) == "table" and type(cvalue) == "table" then
local equal = #fvalue == #cvalue
if equal then
for i=1, #fvalue do
if cvalue[i] ~= fvalue[i] then
equal = false
end
end
end
if equal then
fvalue = cvalue
end
end
if fvalue and #fvalue > 0 then -- If we have a form value, write it to UCI
local val_err
fvalue, val_err = self:validate(fvalue, section)
fvalue = self:transform(fvalue)
if not fvalue and not novld then
self:add_error(section, "invalid", val_err)
end
if fvalue and (self.forcewrite or not (fvalue == cvalue)) then
if self:write(section, fvalue) then
-- Push events
self.section.changed = true
--luci.util.append(self.map.events, self.events)
end
end
else -- Unset the UCI or error
if self.rmempty or self.optional then
if self:remove(section) then
-- Push events
self.section.changed = true
--luci.util.append(self.map.events, self.events)
end
elseif cvalue ~= fvalue and not novld then
-- trigger validator with nil value to get custom user error msg.
local _, val_err = self:validate(nil, section)
self:add_error(section, "missing", val_err)
end
end
end
-- Render if this value exists or if it is mandatory
function AbstractValue.render(self, s, scope)
if not self.optional or self.section:has_tabs() or self:cfgvalue(s) or self:formcreated(s) then
scope = scope or {}
scope.section = s
scope.cbid = self:cbid(s)
Node.render(self, scope)
end
end
-- Return the UCI value of this object
function AbstractValue.cfgvalue(self, section)
local value
if self.tag_error[section] then
value = self:formvalue(section)
else
value = self.map:get(section, self.option)
end
if not value then
return nil
elseif not self.cast or self.cast == type(value) then
return value
elseif self.cast == "string" then
if type(value) == "table" then
return value[1]
end
elseif self.cast == "table" then
return { value }
end
end
-- Validate the form value
function AbstractValue.validate(self, value)
if self.datatype and value then
if type(value) == "table" then
local v
for _, v in ipairs(value) do
if v and #v > 0 and not verify_datatype(self.datatype, v) then
return nil
end
end
else
if not verify_datatype(self.datatype, value) then
return nil
end
end
end
return value
end
AbstractValue.transform = AbstractValue.validate
-- Write to UCI
function AbstractValue.write(self, section, value)
return self.map:set(section, self.option, value)
end
-- Remove from UCI
function AbstractValue.remove(self, section)
return self.map:del(section, self.option)
end
--[[
Value - A one-line value
maxlength: The maximum length
]]--
Value = class(AbstractValue)
function Value.__init__(self, ...)
AbstractValue.__init__(self, ...)
self.template = "cbi/value"
self.keylist = {}
self.vallist = {}
self.readonly = nil
end
function Value.reset_values(self)
self.keylist = {}
self.vallist = {}
end
function Value.value(self, key, val)
val = val or key
table.insert(self.keylist, tostring(key))
table.insert(self.vallist, tostring(val))
end
function Value.parse(self, section, novld)
if self.readonly then return end
AbstractValue.parse(self, section, novld)
end
-- DummyValue - This does nothing except being there
DummyValue = class(AbstractValue)
function DummyValue.__init__(self, ...)
AbstractValue.__init__(self, ...)
self.template = "cbi/dvalue"
self.value = nil
end
function DummyValue.cfgvalue(self, section)
local value
if self.value then
if type(self.value) == "function" then
value = self:value(section)
else
value = self.value
end
else
value = AbstractValue.cfgvalue(self, section)
end
return value
end
function DummyValue.parse(self)
end
--[[
Flag - A flag being enabled or disabled
]]--
Flag = class(AbstractValue)
function Flag.__init__(self, ...)
AbstractValue.__init__(self, ...)
self.template = "cbi/fvalue"
self.enabled = "1"
self.disabled = "0"
self.default = self.disabled
end
-- A flag can only have two states: set or unset
function Flag.parse(self, section, novld)
local fexists = self.map:formvalue(
FEXIST_PREFIX .. self.config .. "." .. section .. "." .. self.option)
if fexists then
local fvalue = self:formvalue(section) and self.enabled or self.disabled
local cvalue = self:cfgvalue(section)
local val_err
fvalue, val_err = self:validate(fvalue, section)
if not fvalue then
if not novld then
self:add_error(section, "invalid", val_err)
end
return
end
if fvalue == self.default and (self.optional or self.rmempty) then
self:remove(section)
else
self:write(section, fvalue)
end
if (fvalue ~= cvalue) then self.section.changed = true end
else
self:remove(section)
self.section.changed = true
end
end
function Flag.cfgvalue(self, section)
return AbstractValue.cfgvalue(self, section) or self.default
end
function Flag.validate(self, value)
return value
end
--[[
ListValue - A one-line value predefined in a list
widget: The widget that will be used (select, radio)
]]--
ListValue = class(AbstractValue)
function ListValue.__init__(self, ...)
AbstractValue.__init__(self, ...)
self.template = "cbi/lvalue"
self.size = 1
self.widget = "select"
self:reset_values()
end
function ListValue.reset_values(self)
self.keylist = {}
self.vallist = {}
self.deplist = {}
end
function ListValue.value(self, key, val, ...)
if luci.util.contains(self.keylist, key) then
return
end
val = val or key
table.insert(self.keylist, tostring(key))
table.insert(self.vallist, tostring(val))
table.insert(self.deplist, {...})
end
function ListValue.validate(self, val)
if luci.util.contains(self.keylist, val) then
return val
else
return nil
end
end
--[[
MultiValue - Multiple delimited values
widget: The widget that will be used (select, checkbox)
delimiter: The delimiter that will separate the values (default: " ")
]]--
MultiValue = class(AbstractValue)
function MultiValue.__init__(self, ...)
AbstractValue.__init__(self, ...)
self.template = "cbi/mvalue"
self.widget = "checkbox"
self.delimiter = " "
self:reset_values()
end
function MultiValue.render(self, ...)
if self.widget == "select" and not self.size then
self.size = #self.vallist
end
AbstractValue.render(self, ...)
end
function MultiValue.reset_values(self)
self.keylist = {}
self.vallist = {}
self.deplist = {}
end
function MultiValue.value(self, key, val)
if luci.util.contains(self.keylist, key) then
return
end
val = val or key
table.insert(self.keylist, tostring(key))
table.insert(self.vallist, tostring(val))
end
function MultiValue.valuelist(self, section)
local val = self:cfgvalue(section)
if not(type(val) == "string") then
return {}
end
return luci.util.split(val, self.delimiter)
end
function MultiValue.validate(self, val)
val = (type(val) == "table") and val or {val}
local result
for i, value in ipairs(val) do
if luci.util.contains(self.keylist, value) then
result = result and (result .. self.delimiter .. value) or value
end
end
return result
end
StaticList = class(MultiValue)
function StaticList.__init__(self, ...)
MultiValue.__init__(self, ...)
self.cast = "table"
self.valuelist = self.cfgvalue
if not self.override_scheme
and self.map:get_scheme(self.section.sectiontype, self.option) then
local vs = self.map:get_scheme(self.section.sectiontype, self.option)
if self.value and vs.values and not self.override_values then
for k, v in pairs(vs.values) do
self:value(k, v)
end
end
end
end
function StaticList.validate(self, value)
value = (type(value) == "table") and value or {value}
local valid = {}
for i, v in ipairs(value) do
if luci.util.contains(self.keylist, v) then
table.insert(valid, v)
end
end
return valid
end
DynamicList = class(AbstractValue)
function DynamicList.__init__(self, ...)
AbstractValue.__init__(self, ...)
self.template = "cbi/dynlist"
self.cast = "table"
self:reset_values()
end
function DynamicList.reset_values(self)
self.keylist = {}
self.vallist = {}
end
function DynamicList.value(self, key, val)
val = val or key
table.insert(self.keylist, tostring(key))
table.insert(self.vallist, tostring(val))
end
function DynamicList.write(self, section, value)
local t = { }
if type(value) == "table" then
local x
for _, x in ipairs(value) do
if x and #x > 0 then
t[#t+1] = x
end
end
else
t = { value }
end
if self.cast == "string" then
value = table.concat(t, " ")
else
value = t
end
return AbstractValue.write(self, section, value)
end
function DynamicList.cfgvalue(self, section)
local value = AbstractValue.cfgvalue(self, section)
if type(value) == "string" then
local x
local t = { }
for x in value:gmatch("%S+") do
if #x > 0 then
t[#t+1] = x
end
end
value = t
end
return value
end
function DynamicList.formvalue(self, section)
local value = AbstractValue.formvalue(self, section)
if type(value) == "string" then
if self.cast == "string" then
local x
local t = { }
for x in value:gmatch("%S+") do
t[#t+1] = x
end
value = t
else
value = { value }
end
end
return value
end
--[[
TextValue - A multi-line value
rows: Rows
]]--
TextValue = class(AbstractValue)
function TextValue.__init__(self, ...)
AbstractValue.__init__(self, ...)
self.template = "cbi/tvalue"
end
--[[
Button
]]--
Button = class(AbstractValue)
function Button.__init__(self, ...)
AbstractValue.__init__(self, ...)
self.template = "cbi/button"
self.inputstyle = nil
self.rmempty = true
self.unsafeupload = false
end
FileUpload = class(AbstractValue)
function FileUpload.__init__(self, ...)
AbstractValue.__init__(self, ...)
self.template = "cbi/upload"
if not self.map.upload_fields then
self.map.upload_fields = { self }
else
self.map.upload_fields[#self.map.upload_fields+1] = self
end
end
function FileUpload.formcreated(self, section)
if self.unsafeupload then
return AbstractValue.formcreated(self, section) or
self.map:formvalue("cbi.rlf."..section.."."..self.option) or
self.map:formvalue("cbi.rlf."..section.."."..self.option..".x") or
self.map:formvalue("cbid."..self.map.config.."."..section.."."..self.option..".textbox")
else
return AbstractValue.formcreated(self, section) or
self.map:formvalue("cbid."..self.map.config.."."..section.."."..self.option..".textbox")
end
end
function FileUpload.cfgvalue(self, section)
local val = AbstractValue.cfgvalue(self, section)
if val and fs.access(val) then
return val
end
return nil
end
-- If we have a new value, use it
-- otherwise use old value
-- deletion should be managed by a separate button object
-- unless self.unsafeupload is set in which case if the user
-- choose to remove the old file we do so.
-- Also, allow to specify (via textbox) a file already on router
function FileUpload.formvalue(self, section)
local val = AbstractValue.formvalue(self, section)
if val then
if self.unsafeupload then
if not self.map:formvalue("cbi.rlf."..section.."."..self.option) and
not self.map:formvalue("cbi.rlf."..section.."."..self.option..".x")
then
return val
end
fs.unlink(val)
self.value = nil
return nil
elseif val ~= "" then
return val
end
end
val = luci.http.formvalue("cbid."..self.map.config.."."..section.."."..self.option..".textbox")
if val == "" then
val = nil
end
if not self.unsafeupload then
if not val then
val = self.map:formvalue("cbi.rlf."..section.."."..self.option)
end
end
return val
end
function FileUpload.remove(self, section)
if self.unsafeupload then
local val = AbstractValue.formvalue(self, section)
if val and fs.access(val) then fs.unlink(val) end
return AbstractValue.remove(self, section)
else
return nil
end
end
FileBrowser = class(AbstractValue)
function FileBrowser.__init__(self, ...)
AbstractValue.__init__(self, ...)
self.template = "cbi/browser"
end
| apache-2.0 |
Lsty/ygopro-scripts | c29088922.lua | 3 | 2120 | --フォーチュンレディ・ウォーテリー
function c29088922.initial_effect(c)
--atk,def
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EFFECT_SET_ATTACK)
e1:SetValue(c29088922.value)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_SET_DEFENCE)
c:RegisterEffect(e2)
--level up
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(29088922,0))
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e3:SetRange(LOCATION_MZONE)
e3:SetCountLimit(1)
e3:SetCode(EVENT_PHASE+PHASE_STANDBY)
e3:SetCondition(c29088922.lvcon)
e3:SetOperation(c29088922.lvop)
c:RegisterEffect(e3)
--draw
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(29088922,1))
e4:SetCategory(CATEGORY_DRAW)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e4:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e4:SetCode(EVENT_SPSUMMON_SUCCESS)
e4:SetTarget(c29088922.drtg)
e4:SetOperation(c29088922.drop)
c:RegisterEffect(e4)
end
function c29088922.value(e,c)
return c:GetLevel()*300
end
function c29088922.lvcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp and e:GetHandler():IsLevelAbove(1) and e:GetHandler():IsLevelBelow(11)
end
function c29088922.lvop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsFacedown() or not c:IsRelateToEffect(e) or c:IsLevelAbove(12) then return end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_LEVEL)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+0x1ff0000)
c:RegisterEffect(e1)
end
function c29088922.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0x31) and c:GetCode()~=29088922
end
function c29088922.drtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c29088922.cfilter,tp,LOCATION_MZONE,0,1,nil) end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(2)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,2)
end
function c29088922.drop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Draw(p,d,REASON_EFFECT)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c43241495.lua | 3 | 2143 | --EMトランポリンクス
function c43241495.initial_effect(c)
--pendulum summon
aux.AddPendulumProcedure(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--tohand
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(43241495,0))
e2:SetCategory(CATEGORY_TOHAND)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetRange(LOCATION_PZONE)
e2:SetCountLimit(1,43241495)
e2:SetCondition(c43241495.thcon)
e2:SetTarget(c43241495.thtg)
e2:SetOperation(c43241495.thop1)
c:RegisterEffect(e2)
--tohand
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(43241495,1))
e3:SetCategory(CATEGORY_TOHAND)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_SUMMON_SUCCESS)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetTarget(c43241495.thtg)
e3:SetOperation(c43241495.thop2)
c:RegisterEffect(e3)
end
function c43241495.cfilter(c,tp)
return c:IsControler(tp) and c:GetSummonType()==SUMMON_TYPE_PENDULUM
end
function c43241495.thcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c43241495.cfilter,1,nil,tp)
end
function c43241495.filter(c)
return (c:GetSequence()==6 or c:GetSequence()==7) and c:IsAbleToHand()
end
function c43241495.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_SZONE) and c43241495.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c43241495.filter,tp,LOCATION_SZONE,LOCATION_SZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND)
local g=Duel.SelectTarget(tp,c43241495.filter,tp,LOCATION_SZONE,LOCATION_SZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function c43241495.thop1(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
end
end
function c43241495.thop2(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
end
end
| gpl-2.0 |
tryroach/vlc | share/lua/extensions/VLSub.lua | 38 | 59549 | --[[
VLSub Extension for VLC media player 1.1 and 2.0
Copyright 2013 Guillaume Le Maout
Authors: Guillaume Le Maout
Contact:
http://addons.videolan.org/messages/?action=newmessage&username=exebetche
Bug report: http://addons.videolan.org/content/show.php/?content=148752
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.
--]]
--[[ Global var ]]--
-- You can set here your default language by replacing nil with
-- your language code (see below).Example:
-- language = "fre",
-- language = "ger",
-- language = "eng",
-- ...
local options = {
language = nil,
downloadBehaviour = 'save',
langExt = false,
removeTag = false,
showMediaInformation = true,
progressBarSize = 80,
intLang = 'eng',
translations_avail = {
eng = 'English',
cze = 'Czech',
dan = 'Danish',
dut = 'Nederlands',
fre = 'Français',
ell = 'Greek',
baq = 'Basque',
pob = 'Brazilian Portuguese',
por = 'Portuguese (Portugal)',
rum = 'Romanian',
slo = 'Slovak',
spa = 'Spanish',
swe = 'Swedish',
ukr = 'Ukrainian',
hun = 'Hungarian'
},
translation = {
int_all = 'All',
int_descr = 'Download subtitles from OpenSubtitles.org',
int_research = 'Research',
int_config = 'Config',
int_configuration = 'Configuration',
int_help = 'Help',
int_search_hash = 'Search by hash',
int_search_name = 'Search by name',
int_title = 'Title',
int_season = 'Season (series)',
int_episode = 'Episode (series)',
int_show_help = 'Show help',
int_show_conf = 'Show config',
int_dowload_sel = 'Download selection',
int_close = 'Close',
int_ok = 'Ok',
int_save = 'Save',
int_cancel = 'Cancel',
int_bool_true = 'Yes',
int_bool_false = 'No',
int_search_transl = 'Search translations',
int_searching_transl = 'Searching translations ...',
int_int_lang = 'Interface language',
int_default_lang = 'Subtitles language',
int_dowload_behav = 'What to do with subtitles',
int_dowload_save = 'Load and save',
int_dowload_load = 'Load only',
int_dowload_manual = 'Manual download',
int_display_code = 'Display language code in file name',
int_remove_tag = 'Remove tags',
int_vlsub_work_dir = 'VLSub working directory',
int_os_username = 'Username',
int_os_password = 'Password',
int_help_mess =[[
Download subtitles from
<a href='http://www.opensubtitles.org/'>
opensubtitles.org
</a> and display them while watching a video.<br>
<br>
<b><u>Usage:</u></b><br>
<br>
Start your video. If you use Vlsub witout playing a video
you will get a link to download the subtitles in your browser
but the subtitles won't be saved and loaded automatically.<br>
<br>
Choose the language for your subtitles and click on the
button corresponding to one of the two research methods
provided by VLSub:<br>
<br>
<b>Method 1: Search by hash</b><br>
It is recommended to try this method first, because it
performs a research based on the video file print, so you
can find subtitles synchronized with your video.<br>
<br>
<b>Method 2: Search by name</b><br>
If you have no luck with the first method, just check the
title is correct before clicking. If you search subtitles
for a series, you can also provide a season and episode
number.<br>
<br>
<b>Downloading Subtitles</b><br>
Select one subtitle in the list and click on 'Download'.<br>
It will be put in the same directory that your video, with
the same name (different extension)
so VLC will load them automatically the next time you'll
start the video.<br>
<br>
<b>/!\\ Beware :</b> Existing subtitles are overwritten
without asking confirmation, so put them elsewhere if
they're important.<br>
<br>
Find more VLC extensions at
<a href='http://addons.videolan.org'>addons.videolan.org</a>.
]],
int_no_support_mess = [[
<strong>VLSub is not working with Vlc 2.1.x on
any platform</strong>
because the lua "net" module needed to interact
with opensubtitles has been
removed in this release for the extensions.
<br>
<strong>Works with Vlc 2.2 on mac and linux.</strong>
<br>
<strong>On windows you have to install an older version
of Vlc (2.0.8 for example)</strong>
to use Vlsub:
<br>
<a target="_blank" rel="nofollow"
href="http://download.videolan.org/pub/videolan/vlc/2.0.8/">
http://download.videolan.org/pub/videolan/vlc/2.0.8/</a><br>
]],
action_login = 'Logging in',
action_logout = 'Logging out',
action_noop = 'Checking session',
action_search = 'Searching subtitles',
action_hash = 'Calculating movie hash',
mess_success = 'Success',
mess_error = 'Error',
mess_no_response = 'Server not responding',
mess_unauthorized = 'Request unauthorized',
mess_expired = 'Session expired, retrying',
mess_overloaded = 'Server overloaded, please retry later',
mess_no_input = 'Please use this method during playing',
mess_not_local = 'This method works with local file only (for now)',
mess_not_found = 'File not found',
mess_not_found2 = 'File not found (illegal character?)',
mess_no_selection = 'No subtitles selected',
mess_save_fail = 'Unable to save subtitles',
mess_click_link = 'Click here to open the file',
mess_complete = 'Research complete',
mess_no_res = 'No result',
mess_res = 'result(s)',
mess_loaded = 'Subtitles loaded',
mess_not_load = 'Unable to load subtitles',
mess_downloading = 'Downloading subtitle',
mess_dowload_link = 'Download link',
mess_err_conf_access ='Can\'t find a suitable path to save'..
'config, please set it manually',
mess_err_wrong_path ='the path contains illegal character, '..
'please correct it'
}
}
local languages = {
{'alb', 'Albanian'},
{'ara', 'Arabic'},
{'arm', 'Armenian'},
{'baq', 'Basque'},
{'ben', 'Bengali'},
{'bos', 'Bosnian'},
{'bre', 'Breton'},
{'bul', 'Bulgarian'},
{'bur', 'Burmese'},
{'cat', 'Catalan'},
{'chi', 'Chinese'},
{'hrv', 'Croatian'},
{'cze', 'Czech'},
{'dan', 'Danish'},
{'dut', 'Dutch'},
{'eng', 'English'},
{'epo', 'Esperanto'},
{'est', 'Estonian'},
{'fin', 'Finnish'},
{'fre', 'French'},
{'glg', 'Galician'},
{'geo', 'Georgian'},
{'ger', 'German'},
{'ell', 'Greek'},
{'heb', 'Hebrew'},
{'hin', 'Hindi'},
{'hun', 'Hungarian'},
{'ice', 'Icelandic'},
{'ind', 'Indonesian'},
{'ita', 'Italian'},
{'jpn', 'Japanese'},
{'kaz', 'Kazakh'},
{'khm', 'Khmer'},
{'kor', 'Korean'},
{'lav', 'Latvian'},
{'lit', 'Lithuanian'},
{'ltz', 'Luxembourgish'},
{'mac', 'Macedonian'},
{'may', 'Malay'},
{'mal', 'Malayalam'},
{'mon', 'Mongolian'},
{'nor', 'Norwegian'},
{'oci', 'Occitan'},
{'per', 'Persian'},
{'pol', 'Polish'},
{'por', 'Portuguese'},
{'pob', 'Brazilian Portuguese'},
{'rum', 'Romanian'},
{'rus', 'Russian'},
{'scc', 'Serbian'},
{'sin', 'Sinhalese'},
{'slo', 'Slovak'},
{'slv', 'Slovenian'},
{'spa', 'Spanish'},
{'swa', 'Swahili'},
{'swe', 'Swedish'},
{'syr', 'Syriac'},
{'tgl', 'Tagalog'},
{'tel', 'Telugu'},
{'tha', 'Thai'},
{'tur', 'Turkish'},
{'ukr', 'Ukrainian'},
{'urd', 'Urdu'},
{'vie', 'Vietnamese'}
}
-- Languages code conversion table: iso-639-1 to iso-639-3
-- See https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
local lang_os_to_iso = {
sq = "alb",
ar = "ara",
hy = "arm",
eu = "baq",
bn = "ben",
bs = "bos",
br = "bre",
bg = "bul",
my = "bur",
ca = "cat",
zh = "chi",
hr = "hrv",
cs = "cze",
da = "dan",
nl = "dut",
en = "eng",
eo = "epo",
et = "est",
fi = "fin",
fr = "fre",
gl = "glg",
ka = "geo",
de = "ger",
el = "ell",
he = "heb",
hi = "hin",
hu = "hun",
is = "ice",
id = "ind",
it = "ita",
ja = "jpn",
kk = "kaz",
km = "khm",
ko = "kor",
lv = "lav",
lt = "lit",
lb = "ltz",
mk = "mac",
ms = "may",
ml = "mal",
mn = "mon",
no = "nor",
oc = "oci",
fa = "per",
pl = "pol",
pt = "por",
po = "pob",
ro = "rum",
ru = "rus",
sr = "scc",
si = "sin",
sk = "slo",
sl = "slv",
es = "spa",
sw = "swa",
sv = "swe",
tl = "tgl",
te = "tel",
th = "tha",
tr = "tur",
uk = "ukr",
ur = "urd",
vi = "vie"
}
local dlg = nil
local input_table = {} -- General widget id reference
local select_conf = {} -- Drop down widget / option table association
--[[ VLC extension stuff ]]--
function descriptor()
return {
title = "VLsub 0.9.13",
version = "0.9.13",
author = "exebetche",
url = 'http://www.opensubtitles.org/',
shortdesc = "VLsub";
description = options.translation.int_descr,
capabilities = {"menu", "input-listener" }
}
end
function activate()
vlc.msg.dbg("[VLsub] Welcome")
if not check_config() then
vlc.msg.err("[VLsub] Unsupported VLC version")
return false
end
if vlc.input.item() then
openSub.getFileInfo()
openSub.getMovieInfo()
end
show_main()
end
function close()
vlc.deactivate()
end
function deactivate()
vlc.msg.dbg("[VLsub] Bye bye!")
if dlg then
dlg:hide()
end
if openSub.session.token and openSub.session.token ~= "" then
openSub.request("LogOut")
end
end
function menu()
return {
lang.int_research,
lang.int_config,
lang.int_help
}
end
function meta_changed()
return false
end
function input_changed()
collectgarbage()
set_interface_main()
collectgarbage()
end
--[[ Interface data ]]--
function interface_main()
dlg:add_label(lang["int_default_lang"]..':', 1, 1, 1, 1)
input_table['language'] = dlg:add_dropdown(2, 1, 2, 1)
dlg:add_button(lang["int_search_hash"],
searchHash, 4, 1, 1, 1)
dlg:add_label(lang["int_title"]..':', 1, 2, 1, 1)
input_table['title'] = dlg:add_text_input(
openSub.movie.title or "", 2, 2, 2, 1)
dlg:add_button(lang["int_search_name"],
searchIMBD, 4, 2, 1, 1)
dlg:add_label(lang["int_season"]..':', 1, 3, 1, 1)
input_table['seasonNumber'] = dlg:add_text_input(
openSub.movie.seasonNumber or "", 2, 3, 2, 1)
dlg:add_label(lang["int_episode"]..':', 1, 4, 1, 1)
input_table['episodeNumber'] = dlg:add_text_input(
openSub.movie.episodeNumber or "", 2, 4, 2, 1)
input_table['mainlist'] = dlg:add_list(1, 5, 4, 1)
input_table['message'] = nil
input_table['message'] = dlg:add_label(' ', 1, 6, 4, 1)
dlg:add_button(
lang["int_show_help"], show_help, 1, 7, 1, 1)
dlg:add_button(
' '..lang["int_show_conf"]..' ', show_conf, 2, 7, 1, 1)
dlg:add_button(
lang["int_dowload_sel"], download_subtitles, 3, 7, 1, 1)
dlg:add_button(
lang["int_close"], deactivate, 4, 7, 1, 1)
assoc_select_conf(
'language',
'language',
openSub.conf.languages,
2,
lang["int_all"])
display_subtitles()
end
function set_interface_main()
-- Update movie title and co. if video input change
if not type(input_table['title']) == 'userdata' then return false end
openSub.getFileInfo()
openSub.getMovieInfo()
input_table['title']:set_text(
openSub.movie.title or "")
input_table['episodeNumber']:set_text(
openSub.movie.episodeNumber or "")
input_table['seasonNumber']:set_text(
openSub.movie.seasonNumber or "")
end
function interface_config()
input_table['intLangLab'] = dlg:add_label(
lang["int_int_lang"]..':', 1, 1, 1, 1)
input_table['intLangBut'] = dlg:add_button(
lang["int_search_transl"],
get_available_translations, 2, 1, 1, 1)
input_table['intLang'] = dlg:add_dropdown(3, 1, 1, 1)
dlg:add_label(
lang["int_default_lang"]..':', 1, 2, 2, 1)
input_table['default_language'] = dlg:add_dropdown(3, 2, 1, 1)
dlg:add_label(
lang["int_dowload_behav"]..':', 1, 3, 2, 1)
input_table['downloadBehaviour'] = dlg:add_dropdown(3, 3, 1, 1)
dlg:add_label(
lang["int_display_code"]..':', 1, 4, 0, 1)
input_table['langExt'] = dlg:add_dropdown(3, 4, 1, 1)
dlg:add_label(
lang["int_remove_tag"]..':', 1, 5, 0, 1)
input_table['removeTag'] = dlg:add_dropdown(3, 5, 1, 1)
if openSub.conf.dirPath then
if openSub.conf.os == "win" then
dlg:add_label(
"<a href='file:///"..openSub.conf.dirPath.."'>"..
lang["int_vlsub_work_dir"].."</a>", 1, 6, 2, 1)
else
dlg:add_label(
"<a href='"..openSub.conf.dirPath.."'>"..
lang["int_vlsub_work_dir"].."</a>", 1, 6, 2, 1)
end
else
dlg :add_label(
lang["int_vlsub_work_dir"], 1, 6, 2, 1)
end
input_table['dir_path'] = dlg:add_text_input(
openSub.conf.dirPath, 2, 6, 2, 1)
dlg:add_label(
lang["int_os_username"]..':', 1, 7, 0, 1)
input_table['os_username'] = dlg:add_text_input(
type(openSub.option.os_username) == "string"
and openSub.option.os_username or "", 2, 7, 2, 1)
dlg:add_label(
lang["int_os_password"]..':', 1, 8, 0, 1)
input_table['os_password'] = dlg:add_text_input(
type(openSub.option.os_password) == "string"
and openSub.option.os_password or "", 2, 8, 2, 1)
input_table['message'] = nil
input_table['message'] = dlg:add_label(' ', 1, 9, 3, 1)
dlg:add_button(
lang["int_cancel"],
show_main, 2, 10, 1, 1)
dlg:add_button(
lang["int_save"],
apply_config, 3, 10, 1, 1)
input_table['langExt']:add_value(
lang["int_bool_"..tostring(openSub.option.langExt)], 1)
input_table['langExt']:add_value(
lang["int_bool_"..tostring(not openSub.option.langExt)], 2)
input_table['removeTag']:add_value(
lang["int_bool_"..tostring(openSub.option.removeTag)], 1)
input_table['removeTag']:add_value(
lang["int_bool_"..tostring(not openSub.option.removeTag)], 2)
assoc_select_conf(
'intLang',
'intLang',
openSub.conf.translations_avail,
2)
assoc_select_conf(
'default_language',
'language',
openSub.conf.languages,
2,
lang["int_all"])
assoc_select_conf(
'downloadBehaviour',
'downloadBehaviour',
openSub.conf.downloadBehaviours,
1)
end
function interface_help()
local help_html = lang["int_help_mess"]
input_table['help'] = dlg:add_html(
help_html, 1, 1, 4, 1)
dlg:add_label(
string.rep (" ", 100), 1, 2, 3, 1)
dlg:add_button(
lang["int_ok"], show_main, 4, 2, 1, 1)
end
function interface_no_support()
local no_support_html = lang["int_no_support_mess"]
input_table['no_support'] = dlg:add_html(
no_support_html, 1, 1, 4, 1)
dlg:add_label(
string.rep (" ", 100), 1, 2, 3, 1)
end
function trigger_menu(dlg_id)
if dlg_id == 1 then
close_dlg()
dlg = vlc.dialog(
openSub.conf.useragent)
interface_main()
elseif dlg_id == 2 then
close_dlg()
dlg = vlc.dialog(
openSub.conf.useragent..': '..lang["int_configuration"])
interface_config()
elseif dlg_id == 3 then
close_dlg()
dlg = vlc.dialog(
openSub.conf.useragent..': '..lang["int_help"])
interface_help()
end
collectgarbage() --~ !important
end
function show_main()
trigger_menu(1)
end
function show_conf()
trigger_menu(2)
end
function show_help()
trigger_menu(3)
end
function close_dlg()
vlc.msg.dbg("[VLSub] Closing dialog")
if dlg ~= nil then
--~ dlg:delete() -- Throw an error
dlg:hide()
end
dlg = nil
input_table = nil
input_table = {}
collectgarbage() --~ !important
end
--[[ Drop down / config association]]--
function assoc_select_conf(select_id, option, conf, ind, default)
-- Helper for i/o interaction between drop down and option list
select_conf[select_id] = {
cf = conf,
opt = option,
dflt = default,
ind = ind
}
set_default_option(select_id)
display_select(select_id)
end
function set_default_option(select_id)
-- Put the selected option of a list in first place of the associated table
local opt = select_conf[select_id].opt
local cfg = select_conf[select_id].cf
local ind = select_conf[select_id].ind
if openSub.option[opt] then
table.sort(cfg, function(a, b)
if a[1] == openSub.option[opt] then
return true
elseif b[1] == openSub.option[opt] then
return false
else
return a[ind] < b[ind]
end
end)
end
end
function display_select(select_id)
-- Display the drop down values with an optional default value at the top
local conf = select_conf[select_id].cf
local opt = select_conf[select_id].opt
local option = openSub.option[opt]
local default = select_conf[select_id].dflt
local default_isset = false
if not default then
default_isset = true
end
for k, l in ipairs(conf) do
if default_isset then
input_table[select_id]:add_value(l[2], k)
else
if option then
input_table[select_id]:add_value(l[2], k)
input_table[select_id]:add_value(default, 0)
else
input_table[select_id]:add_value(default, 0)
input_table[select_id]:add_value(l[2], k)
end
default_isset = true
end
end
end
--[[ Config & interface localization]]--
function check_config()
-- Make a copy of english translation to use it as default
-- in case some element aren't translated in other translations
eng_translation = {}
for k, v in pairs(openSub.option.translation) do
eng_translation[k] = v
end
-- Get available translation full name from code
trsl_names = {}
for i, lg in ipairs(languages) do
trsl_names[lg[1]] = lg[2]
end
if is_window_path(vlc.config.datadir()) then
openSub.conf.os = "win"
slash = "\\"
else
openSub.conf.os = "lin"
slash = "/"
end
local path_generic = {"lua", "extensions", "userdata", "vlsub"}
local dirPath = slash..table.concat(path_generic, slash)
local filePath = slash.."vlsub_conf.xml"
local config_saved = false
sub_dir = slash.."vlsub_subtitles"
-- Check if config file path is stored in vlc config
local other_dirs = {}
for path in
vlc.config.get("sub-autodetect-path"):gmatch("[^,]+") do
if path:match(".*"..sub_dir.."$") then
openSub.conf.dirPath = path:gsub(
"%s*(.*)"..sub_dir.."%s*$", "%1")
config_saved = true
end
table.insert(other_dirs, path)
end
-- if not stored in vlc config
-- try to find a suitable config file path
if openSub.conf.dirPath then
if not is_dir(openSub.conf.dirPath) and
(openSub.conf.os == "lin" or
is_win_safe(openSub.conf.dirPath)) then
mkdir_p(openSub.conf.dirPath)
end
else
local userdatadir = vlc.config.userdatadir()
local datadir = vlc.config.datadir()
-- check if the config already exist
if file_exist(userdatadir..dirPath..filePath) then
-- in vlc.config.userdatadir()
openSub.conf.dirPath = userdatadir..dirPath
config_saved = true
elseif file_exist(datadir..dirPath..filePath) then
-- in vlc.config.datadir()
openSub.conf.dirPath = datadir..dirPath
config_saved = true
else
-- if not found determine an accessible path
local extension_path = slash..path_generic[1]
..slash..path_generic[2]
-- use the same folder as the extension if accessible
if is_dir(userdatadir..extension_path)
and file_touch(userdatadir..dirPath..filePath) then
openSub.conf.dirPath = userdatadir..dirPath
elseif file_touch(datadir..dirPath..filePath) then
openSub.conf.dirPath = datadir..dirPath
end
-- try to create working dir in user folder
if not openSub.conf.dirPath
and is_dir(userdatadir) then
if not is_dir(userdatadir..dirPath) then
mkdir_p(userdatadir..dirPath)
end
if is_dir(userdatadir..dirPath) and
file_touch(userdatadir..dirPath..filePath) then
openSub.conf.dirPath = userdatadir..dirPath
end
end
-- try to create working dir in vlc folder
if not openSub.conf.dirPath and
is_dir(datadir) then
if not is_dir(datadir..dirPath) then
mkdir_p(datadir..dirPath)
end
if file_touch(datadir..dirPath..filePath) then
openSub.conf.dirPath = datadir..dirPath
end
end
end
end
if openSub.conf.dirPath then
vlc.msg.dbg("[VLSub] Working directory: " ..
(openSub.conf.dirPath or "not found"))
openSub.conf.filePath = openSub.conf.dirPath..filePath
openSub.conf.localePath = openSub.conf.dirPath..slash.."locale"
if config_saved
and file_exist(openSub.conf.filePath) then
vlc.msg.dbg(
"[VLSub] Loading config file: "..openSub.conf.filePath)
load_config()
else
vlc.msg.dbg("[VLSub] No config file")
getenv_lang()
config_saved = save_config()
if not config_saved then
vlc.msg.dbg("[VLSub] Unable to save config")
end
end
-- Check presence of a translation file
-- in "%vlsub_directory%/locale"
-- Add translation files to available translation list
local file_list = list_dir(openSub.conf.localePath)
local translations_avail = openSub.conf.translations_avail
if file_list then
for i, file_name in ipairs(file_list) do
local lg = string.gsub(
file_name,
"^(%w%w%w).xml$",
"%1")
if lg
and not openSub.option.translations_avail[lg] then
table.insert(translations_avail, {
lg,
trsl_names[lg]
})
end
end
end
-- Load selected translation from file
if openSub.option.intLang ~= "eng"
and not openSub.conf.translated
then
local transl_file_path = openSub.conf.localePath..
slash..openSub.option.intLang..".xml"
if file_exist(transl_file_path) then
vlc.msg.dbg(
"[VLSub] Loading translation from file: "..
transl_file_path)
load_transl(transl_file_path)
end
end
else
vlc.msg.dbg("[VLSub] Unable to find a suitable path"..
"to save config, please set it manually")
end
lang = nil
lang = options.translation -- just a short cut
if not vlc.net or not vlc.net.poll then
dlg = vlc.dialog(
openSub.conf.useragent..': '..lang["mess_error"])
interface_no_support()
dlg:show()
return false
end
SetDownloadBehaviours()
if not openSub.conf.dirPath then
setError(lang["mess_err_conf_access"])
end
-- Set table list of available translations from assoc. array
-- so it is sortable
for k, l in pairs(openSub.option.translations_avail) do
if k == openSub.option.int_research then
table.insert(openSub.conf.translations_avail, 1, {k, l})
else
table.insert(openSub.conf.translations_avail, {k, l})
end
end
collectgarbage()
return true
end
function load_config()
-- Overwrite default conf with loaded conf
local tmpFile = io.open(openSub.conf.filePath, "rb")
if not tmpFile then return false end
local resp = tmpFile:read("*all")
tmpFile:flush()
tmpFile:close()
local option = parse_xml(resp)
for key, value in pairs(option) do
if type(value) == "table" then
if key == "translation" then
openSub.conf.translated = true
for k, v in pairs(value) do
openSub.option.translation[k] = v
end
else
openSub.option[key] = value
end
else
if value == "true" then
openSub.option[key] = true
elseif value == "false" then
openSub.option[key] = false
else
openSub.option[key] = value
end
end
end
collectgarbage()
end
function load_transl(path)
-- Overwrite default conf with loaded conf
local tmpFile = assert(io.open(path, "rb"))
local resp = tmpFile:read("*all")
tmpFile:flush()
tmpFile:close()
openSub.option.translation = nil
openSub.option.translation = parse_xml(resp)
collectgarbage()
end
function apply_translation()
-- Overwrite default conf with loaded conf
for k, v in pairs(eng_translation) do
if not openSub.option.translation[k] then
openSub.option.translation[k] = eng_translation[k]
end
end
end
function getenv_lang()
-- Retrieve the user OS language
local os_lang = os.getenv("LANG")
if os_lang then -- unix, mac
os_lang = string.sub(os_lang, 0, 2)
if type(lang_os_to_iso[os_lang]) then
openSub.option.language = lang_os_to_iso[os_lang]
end
else -- Windows
local lang_w = string.match(
os.setlocale("", "collate"),
"^[^_]+")
for i, v in ipairs(openSub.conf.languages) do
if v[2] == lang_w then
openSub.option.language = v[1]
end
end
end
end
function apply_config()
-- Apply user config selection to local config
local lg_sel = input_table['intLang']:get_value()
local sel_val
local opt
local sel_cf
if lg_sel and lg_sel ~= 1
and openSub.conf.translations_avail[lg_sel] then
local lg = openSub.conf.translations_avail[lg_sel][1]
set_translation(lg)
SetDownloadBehaviours()
end
for select_id, v in pairs(select_conf) do
if input_table[select_id]
and select_conf[select_id] then
sel_val = input_table[select_id]:get_value()
sel_cf = select_conf[select_id]
opt = sel_cf.opt
if sel_val == 0 then
openSub.option[opt] = nil
else
openSub.option[opt] = sel_cf.cf[sel_val][1]
end
set_default_option(select_id)
end
end
openSub.option.os_username = input_table['os_username']:get_text()
openSub.option.os_password = input_table['os_password']:get_text()
if input_table["langExt"]:get_value() == 2 then
openSub.option.langExt = not openSub.option.langExt
end
if input_table["removeTag"]:get_value() == 2 then
openSub.option.removeTag = not openSub.option.removeTag
end
-- Set a custom working directory
local dir_path = input_table['dir_path']:get_text()
local dir_path_err = false
if trim(dir_path) == "" then dir_path = nil end
if dir_path ~= openSub.conf.dirPath then
if openSub.conf.os == "lin"
or is_win_safe(dir_path)
or not dir_path then
local other_dirs = {}
for path in
vlc.config.get(
"sub-autodetect-path"):gmatch("[^,]+"
) do
path = trim(path)
if path ~= (openSub.conf.dirPath or "")..sub_dir then
table.insert(other_dirs, path)
end
end
openSub.conf.dirPath = dir_path
if dir_path then
table.insert(other_dirs,
string.gsub(dir_path, "^(.-)[\\/]?$", "%1")..sub_dir)
if not is_dir(dir_path) then
mkdir_p(dir_path)
end
openSub.conf.filePath = openSub.conf.dirPath..
slash.."vlsub_conf.xml"
openSub.conf.localePath = openSub.conf.dirPath..
slash.."locale"
else
openSub.conf.filePath = nil
openSub.conf.localePath = nil
end
vlc.config.set(
"sub-autodetect-path",
table.concat(other_dirs, ", "))
else
dir_path_err = true
setError(lang["mess_err_wrong_path"]..
"<br><b>"..
string.gsub(
dir_path,
"[^%:%w%p%s§¤]+",
"<span style='color:#B23'>%1</span>"
)..
"</b>")
end
end
if openSub.conf.dirPath and
not dir_path_err then
local config_saved = save_config()
trigger_menu(1)
if not config_saved then
setError(lang["mess_err_conf_access"])
end
else
setError(lang["mess_err_conf_access"])
end
end
function save_config()
-- Dump local config into config file
if openSub.conf.dirPath
and openSub.conf.filePath then
vlc.msg.dbg(
"[VLSub] Saving config file: "..
openSub.conf.filePath)
if file_touch(openSub.conf.filePath) then
local tmpFile = assert(
io.open(openSub.conf.filePath, "wb"))
local resp = dump_xml(openSub.option)
tmpFile:write(resp)
tmpFile:flush()
tmpFile:close()
tmpFile = nil
else
return false
end
collectgarbage()
return true
else
vlc.msg.dbg("[VLSub] Unable fount a suitable path "..
"to save config, please set it manually")
setError(lang["mess_err_conf_access"])
return false
end
end
function SetDownloadBehaviours()
openSub.conf.downloadBehaviours = nil
openSub.conf.downloadBehaviours = {
{'save', lang["int_dowload_save"]},
{'manual', lang["int_dowload_manual"]}
}
end
function get_available_translations()
-- Get all available translation files from the internet
-- (drop previous direct download from github repo
-- causing error with github https CA certficate on OS X an XP)
-- https://github.com/exebetche/vlsub/tree/master/locale
local translations_url = "http://addons.videolan.org/CONTENT/"..
"content-files/148752-vlsub_translations.xml"
if input_table['intLangBut']:get_text() == lang["int_search_transl"]
then
openSub.actionLabel = lang["int_searching_transl"]
local translations_content, lol = get(translations_url)
local translations_avail = openSub.option.translations_avail
all_trsl = parse_xml(translations_content)
local lg, trsl
for lg, trsl in pairs(all_trsl) do
if lg ~= options.intLang[1]
and not translations_avail[lg] then
translations_avail[lg] = trsl_names[lg] or ""
table.insert(openSub.conf.translations_avail, {
lg,
trsl_names[lg]
})
input_table['intLang']:add_value(
trsl_names[lg],
#openSub.conf.translations_avail)
end
end
setMessage(success_tag(lang["mess_complete"]))
collectgarbage()
end
end
function set_translation(lg)
openSub.option.translation = nil
openSub.option.translation = {}
if lg == 'eng' then
for k, v in pairs(eng_translation) do
openSub.option.translation[k] = v
end
else
-- If translation file exists in /locale directory load it
if openSub.conf.localePath
and file_exist(openSub.conf.localePath..
slash..lg..".xml") then
local transl_file_path = openSub.conf.localePath..
slash..lg..".xml"
vlc.msg.dbg("[VLSub] Loading translation from file: "..
transl_file_path)
load_transl(transl_file_path)
apply_translation()
else
-- Load translation file from internet
if not all_trsl then
get_available_translations()
end
if not all_trsl or not all_trsl[lg] then
vlc.msg.dbg("[VLSub] Error, translation not found")
return false
end
openSub.option.translation = all_trsl[lg]
apply_translation()
all_trsl = nil
end
end
lang = nil
lang = openSub.option.translation
collectgarbage()
end
--[[ Core ]]--
openSub = {
itemStore = nil,
actionLabel = "",
conf = {
url = "http://api.opensubtitles.org/xml-rpc",
path = nil,
userAgentHTTP = "VLSub",
useragent = "VLSub 0.9",
translations_avail = {},
downloadBehaviours = nil,
languages = languages
},
option = options,
session = {
loginTime = 0,
token = ""
},
file = {
hasInput = false,
uri = nil,
ext = nil,
name = nil,
path = nil,
protocol = nil,
cleanName = nil,
dir = nil,
hash = nil,
bytesize = nil,
fps = nil,
timems = nil,
frames = nil
},
movie = {
title = "",
seasonNumber = "",
episodeNumber = "",
sublanguageid = ""
},
request = function(methodName)
local params = openSub.methods[methodName].params()
local reqTable = openSub.getMethodBase(methodName, params)
local request = "<?xml version='1.0'?>"..dump_xml(reqTable)
local host, path = parse_url(openSub.conf.url)
local header = {
"POST "..path.." HTTP/1.1",
"Host: "..host,
"User-Agent: "..openSub.conf.userAgentHTTP,
"Content-Type: text/xml",
"Content-Length: "..string.len(request),
"",
""
}
request = table.concat(header, "\r\n")..request
local response
local status, responseStr = http_req(host, 80, request)
if status == 200 then
response = parse_xmlrpc(responseStr)
if response then
if response.status == "200 OK" then
return openSub.methods[methodName]
.callback(response)
elseif response.status == "406 No session" then
openSub.request("LogIn")
elseif response then
setError("code '"..
response.status..
"' ("..status..")")
return false
end
else
setError("Server not responding")
return false
end
elseif status == 401 then
setError("Request unauthorized")
response = parse_xmlrpc(responseStr)
if openSub.session.token ~= response.token then
setMessage("Session expired, retrying")
openSub.session.token = response.token
openSub.request(methodName)
end
return false
elseif status == 503 then
setError("Server overloaded, please retry later")
return false
end
end,
getMethodBase = function(methodName, param)
if openSub.methods[methodName].methodName then
methodName = openSub.methods[methodName].methodName
end
local request = {
methodCall={
methodName=methodName,
params={ param=param }}}
return request
end,
methods = {
LogIn = {
params = function()
openSub.actionLabel = lang["action_login"]
return {
{ value={ string=openSub.option.os_username } },
{ value={ string=openSub.option.os_password } },
{ value={ string=openSub.movie.sublanguageid } },
{ value={ string=openSub.conf.useragent } }
}
end,
callback = function(resp)
openSub.session.token = resp.token
openSub.session.loginTime = os.time()
return true
end
},
LogOut = {
params = function()
openSub.actionLabel = lang["action_logout"]
return {
{ value={ string=openSub.session.token } }
}
end,
callback = function()
return true
end
},
NoOperation = {
params = function()
openSub.actionLabel = lang["action_noop"]
return {
{ value={ string=openSub.session.token } }
}
end,
callback = function(resp)
return true
end
},
SearchSubtitlesByHash = {
methodName = "SearchSubtitles",
params = function()
openSub.actionLabel = lang["action_search"]
setMessage(openSub.actionLabel..": "..
progressBarContent(0))
return {
{ value={ string=openSub.session.token } },
{ value={
array={
data={
value={
struct={
member={
{ name="sublanguageid", value={
string=openSub.movie.sublanguageid }
},
{ name="moviehash", value={
string=openSub.file.hash } },
{ name="moviebytesize", value={
double=openSub.file.bytesize } }
}}}}}}}
}
end,
callback = function(resp)
openSub.itemStore = resp.data
end
},
SearchSubtitles = {
methodName = "SearchSubtitles",
params = function()
openSub.actionLabel = lang["action_search"]
setMessage(openSub.actionLabel..": "..
progressBarContent(0))
local member = {
{ name="sublanguageid", value={
string=openSub.movie.sublanguageid } },
{ name="query", value={
string=openSub.movie.title } } }
if openSub.movie.seasonNumber ~= nil then
table.insert(member, { name="season", value={
string=openSub.movie.seasonNumber } })
end
if openSub.movie.episodeNumber ~= nil then
table.insert(member, { name="episode", value={
string=openSub.movie.episodeNumber } })
end
return {
{ value={ string=openSub.session.token } },
{ value={
array={
data={
value={
struct={
member=member
}}}}}}
}
end,
callback = function(resp)
openSub.itemStore = resp.data
end
}
},
getInputItem = function()
return vlc.item or vlc.input.item()
end,
getFileInfo = function()
-- Get video file path, name, extension from input uri
local item = openSub.getInputItem()
local file = openSub.file
if not item then
file.hasInput = false;
file.cleanName = nil;
file.protocol = nil;
file.path = nil;
file.ext = nil;
file.uri = nil;
else
vlc.msg.dbg("[VLSub] Video URI: "..item:uri())
local parsed_uri = vlc.net.url_parse(item:uri())
file.uri = item:uri()
file.protocol = parsed_uri["protocol"]
file.path = parsed_uri["path"]
-- Corrections
-- For windows
file.path = string.match(file.path, "^/(%a:/.+)$") or file.path
-- For file in archive
local archive_path, name_in_archive = string.match(
file.path, '^([^!]+)!/([^!/]*)$')
if archive_path and archive_path ~= "" then
file.path = string.gsub(
archive_path,
'\063',
'%%')
file.path = vlc.strings.decode_uri(file.path)
file.completeName = string.gsub(
name_in_archive,
'\063',
'%%')
file.completeName = vlc.strings.decode_uri(
file.completeName)
file.is_archive = true
else -- "classic" input
file.path = vlc.strings.decode_uri(file.path)
file.dir, file.completeName = string.match(
file.path,
'^(.+/)([^/]*)$')
local file_stat = vlc.net.stat(file.path)
if file_stat
then
file.stat = file_stat
end
file.is_archive = false
end
file.name, file.ext = string.match(
file.completeName,
'^([^/]-)%.?([^%.]*)$')
if file.ext == "part" then
file.name, file.ext = string.match(
file.name,
'^([^/]+)%.([^%.]+)$')
end
file.hasInput = true;
file.cleanName = string.gsub(
file.name,
"[%._]", " ")
vlc.msg.dbg("[VLSub] file info "..(dump_xml(file)))
end
collectgarbage()
end,
getMovieInfo = function()
-- Clean video file name and check for season/episode pattern in title
if not openSub.file.name then
openSub.movie.title = ""
openSub.movie.seasonNumber = ""
openSub.movie.episodeNumber = ""
return false
end
local showName, seasonNumber, episodeNumber = string.match(
openSub.file.cleanName,
"(.+)[sS](%d%d)[eE](%d%d).*")
if not showName then
showName, seasonNumber, episodeNumber = string.match(
openSub.file.cleanName,
"(.+)(%d)[xX](%d%d).*")
end
if showName then
openSub.movie.title = showName
openSub.movie.seasonNumber = seasonNumber
openSub.movie.episodeNumber = episodeNumber
else
openSub.movie.title = openSub.file.cleanName
openSub.movie.seasonNumber = ""
openSub.movie.episodeNumber = ""
end
collectgarbage()
end,
getMovieHash = function()
-- Calculate movie hash
openSub.actionLabel = lang["action_hash"]
setMessage(openSub.actionLabel..": "..
progressBarContent(0))
local item = openSub.getInputItem()
if not item then
setError(lang["mess_no_input"])
return false
end
openSub.getFileInfo()
if not openSub.file.path then
setError(lang["mess_not_found"])
return false
end
local data_start = ""
local data_end = ""
local size
local chunk_size = 65536
-- Get data for hash calculation
if openSub.file.is_archive then
vlc.msg.dbg("[VLSub] Read hash data from stream")
local file = vlc.stream(openSub.file.uri)
local dataTmp1 = ""
local dataTmp2 = ""
size = chunk_size
data_start = file:read(chunk_size)
while data_end do
size = size + string.len(data_end)
dataTmp1 = dataTmp2
dataTmp2 = data_end
data_end = file:read(chunk_size)
collectgarbage()
end
data_end = string.sub((dataTmp1..dataTmp2), -chunk_size)
elseif not file_exist(openSub.file.path)
and openSub.file.stat then
vlc.msg.dbg("[VLSub] Read hash data from stream")
local file = vlc.stream(openSub.file.uri)
if not file then
vlc.msg.dbg("[VLSub] No stream")
return false
end
size = openSub.file.stat.size
local decal = size%chunk_size
data_start = file:read(chunk_size)
-- "Seek" to the end
file:read(decal)
for i = 1, math.floor(((size-decal)/chunk_size))-2 do
file:read(chunk_size)
end
data_end = file:read(chunk_size)
file = nil
else
vlc.msg.dbg("[VLSub] Read hash data from file")
local file = io.open( openSub.file.path, "rb")
if not file then
vlc.msg.dbg("[VLSub] No stream")
return false
end
data_start = file:read(chunk_size)
size = file:seek("end", -chunk_size) + chunk_size
data_end = file:read(chunk_size)
file = nil
end
-- Hash calculation
local lo = size
local hi = 0
local o,a,b,c,d,e,f,g,h
local hash_data = data_start..data_end
local max_size = 4294967296
local overflow
for i = 1, #hash_data, 8 do
a,b,c,d,e,f,g,h = hash_data:byte(i,i+7)
lo = lo + a + b*256 + c*65536 + d*16777216
hi = hi + e + f*256 + g*65536 + h*16777216
if lo > max_size then
overflow = math.floor(lo/max_size)
lo = lo-(overflow*max_size)
hi = hi+overflow
end
if hi > max_size then
overflow = math.floor(hi/max_size)
hi = hi-(overflow*max_size)
end
end
openSub.file.bytesize = size
openSub.file.hash = string.format("%08x%08x", hi,lo)
vlc.msg.dbg("[VLSub] Video hash: "..openSub.file.hash)
vlc.msg.dbg("[VLSub] Video bytesize: "..size)
collectgarbage()
return true
end,
checkSession = function()
if openSub.session.token == "" then
openSub.request("LogIn")
else
openSub.request("NoOperation")
end
end
}
function searchHash()
local sel = input_table["language"]:get_value()
if sel == 0 then
openSub.movie.sublanguageid = 'all'
else
openSub.movie.sublanguageid = openSub.conf.languages[sel][1]
end
openSub.getMovieHash()
if openSub.file.hash then
openSub.checkSession()
openSub.request("SearchSubtitlesByHash")
display_subtitles()
end
end
function searchIMBD()
openSub.movie.title = trim(input_table["title"]:get_text())
openSub.movie.seasonNumber = tonumber(
input_table["seasonNumber"]:get_text())
openSub.movie.episodeNumber = tonumber(
input_table["episodeNumber"]:get_text())
local sel = input_table["language"]:get_value()
if sel == 0 then
openSub.movie.sublanguageid = 'all'
else
openSub.movie.sublanguageid = openSub.conf.languages[sel][1]
end
if openSub.movie.title ~= "" then
openSub.checkSession()
openSub.request("SearchSubtitles")
display_subtitles()
end
end
function display_subtitles()
local mainlist = input_table["mainlist"]
mainlist:clear()
if openSub.itemStore == "0" then
mainlist:add_value(lang["mess_no_res"], 1)
setMessage("<b>"..lang["mess_complete"]..":</b> "..
lang["mess_no_res"])
elseif openSub.itemStore then
for i, item in ipairs(openSub.itemStore) do
mainlist:add_value(
item.SubFileName..
" ["..item.SubLanguageID.."]"..
" ("..item.SubSumCD.." CD)", i)
end
setMessage("<b>"..lang["mess_complete"]..":</b> "..
#(openSub.itemStore).." "..lang["mess_res"])
end
end
function get_first_sel(list)
local selection = list:get_selection()
for index, name in pairs(selection) do
return index
end
return 0
end
function download_subtitles()
local index = get_first_sel(input_table["mainlist"])
if index == 0 then
setMessage(lang["mess_no_selection"])
return false
end
openSub.actionLabel = lang["mess_downloading"]
display_subtitles() -- reset selection
local item = openSub.itemStore[index]
if openSub.option.downloadBehaviour == 'manual'
or not openSub.file.hasInput then
local link = "<span style='color:#181'>"
link = link.."<b>"..lang["mess_dowload_link"]..":</b>"
link = link.."</span> "
link = link.."</span> <a href='"..
item.ZipDownloadLink.."'>"
link = link..item.MovieReleaseName.."</a>"
setMessage(link)
return false
end
local message = ""
local subfileName = openSub.file.name or ""
if openSub.option.langExt then
subfileName = subfileName.."."..item.SubLanguageID
end
subfileName = subfileName.."."..item.SubFormat
local tmp_dir
local file_target_access = true
if is_dir(openSub.file.dir) then
tmp_dir = openSub.file.dir
elseif openSub.conf.dirPath then
tmp_dir = openSub.conf.dirPath
message = "<br>"..error_tag(lang["mess_save_fail"].." "..
"<a href='"..vlc.strings.make_uri(openSub.conf.dirPath).."'>"..
lang["mess_click_link"].."</a>")
else
setError(lang["mess_save_fail"].." "..
"<a href='"..item.ZipDownloadLink.."'>"..
lang["mess_click_link"].."</a>")
return false
end
local tmpFileURI, tmpFileName = dump_zip(
item.ZipDownloadLink,
tmp_dir,
item.SubFileName)
vlc.msg.dbg("[VLsub] tmpFileName: "..tmpFileName)
-- Determine if the path to the video file is accessible for writing
local target = openSub.file.dir..subfileName
if not file_touch(target) then
if openSub.conf.dirPath then
target = openSub.conf.dirPath..slash..subfileName
message = "<br>"..
error_tag(lang["mess_save_fail"].." "..
"<a href='"..vlc.strings.make_uri(
openSub.conf.dirPath).."'>"..
lang["mess_click_link"].."</a>")
else
setError(lang["mess_save_fail"].." "..
"<a href='"..item.ZipDownloadLink.."'>"..
lang["mess_click_link"].."</a>")
return false
end
end
vlc.msg.dbg("[VLsub] Subtitles files: "..target)
-- Unzipped data into file target
local stream = vlc.stream(tmpFileURI)
local data = ""
local subfile = io.open(target, "wb")
while data do
subfile:write(data)
data = stream:read(65536)
end
subfile:flush()
subfile:close()
stream = nil
collectgarbage()
if not os.remove(tmpFileName) then
vlc.msg.err("[VLsub] Unable to remove temp: "..tmpFileName)
end
-- load subtitles
if add_sub(target) then
message = success_tag(lang["mess_loaded"]) .. message
else
message = error_tag(lang["mess_not_load"]) .. message
end
setMessage(message)
end
function dump_zip(url, dir, subfileName)
-- Dump zipped data in a temporary file
setMessage(openSub.actionLabel..": "..progressBarContent(0))
local resp = get(url)
if not resp then
setError(lang["mess_no_response"])
return false
end
local tmpFileName = dir..subfileName..".gz"
if not file_touch(tmpFileName) then
return false
end
local tmpFile = assert(io.open(tmpFileName, "wb"))
tmpFile:write(resp)
tmpFile:flush()
tmpFile:close()
tmpFile = nil
collectgarbage()
return "zip://"..make_uri(tmpFileName)
.."!/"..subfileName, tmpFileName
end
function add_sub(subPath)
if vlc.item or vlc.input.item() then
subPath = decode_uri(subPath)
vlc.msg.dbg("[VLsub] Adding subtitle :" .. subPath)
return vlc.input.add_subtitle(subPath)
end
return false
end
--[[ Interface helpers]]--
function progressBarContent(pct)
local accomplished = math.ceil(
openSub.option.progressBarSize*pct/100)
local left = openSub.option.progressBarSize - accomplished
local content = "<span style='background-color:#181;color:#181;'>"..
string.rep ("-", accomplished).."</span>"..
"<span style='background-color:#fff;color:#fff;'>"..
string.rep ("-", left)..
"</span>"
return content
end
function setMessage(str)
if input_table["message"] then
input_table["message"]:set_text(str)
dlg:update()
end
end
function setError(mess)
setMessage(error_tag(mess))
end
function success_tag(str)
return "<span style='color:#181'><b>"..
lang["mess_success"]..":</b></span> "..str..""
end
function error_tag(str)
return "<span style='color:#B23'><b>"..
lang["mess_error"]..":</b></span> "..str..""
end
--[[ Network utils]]--
function get(url)
local host, path = parse_url(url)
local header = {
"GET "..path.." HTTP/1.1",
"Host: "..host,
"User-Agent: "..openSub.conf.userAgentHTTP,
"",
""
}
local request = table.concat(header, "\r\n")
local response
local status, response = http_req(host, 80, request)
if status == 200 then
return response
else
return false, status, response
end
end
function http_req(host, port, request)
local fd = vlc.net.connect_tcp(host, port)
if not fd then return false end
local pollfds = {}
pollfds[fd] = vlc.net.POLLIN
vlc.net.send(fd, request)
vlc.net.poll(pollfds)
local chunk = vlc.net.recv(fd, 2048)
local response = ""
local headerStr, header, body
local contentLength, status
local pct = 0
while chunk do
response = response..chunk
if not header then
headerStr, body = response:match("(.-\r?\n)\r?\n(.*)")
if headerStr then
response = body
header = parse_header(headerStr)
contentLength = tonumber(header["Content-Length"])
status = tonumber(header["statuscode"])
end
end
if contentLength then
bodyLenght = #response
pct = bodyLenght / contentLength * 100
setMessage(openSub.actionLabel..": "..progressBarContent(pct))
if bodyLenght >= contentLength then
break
end
end
vlc.net.poll(pollfds)
chunk = vlc.net.recv(fd, 1024)
end
vlc.net.close(fd)
if status == 301
and header["Location"] then
local host, path = parse_url(trim(header["Location"]))
request = request
:gsub("^([^%s]+ )([^%s]+)", "%1"..path)
:gsub("(Host: )([^\n]*)", "%1"..host)
return http_req(host, port, request)
end
return status, response
end
function parse_header(data)
local header = {}
for name, s, val in string.gmatch(
data,
"([^%s:]+)(:?)%s([^\n]+)\r?\n")
do
if s == "" then
header['statuscode'] = tonumber(string.sub(val, 1 , 3))
else
header[name] = val
end
end
return header
end
function parse_url(url)
local url_parsed = vlc.net.url_parse(url)
return url_parsed["host"],
url_parsed["path"],
url_parsed["option"]
end
--[[ XML utils]]--
function parse_xml(data)
local tree = {}
local stack = {}
local tmp = {}
local level = 0
local op, tag, p, empty, val
table.insert(stack, tree)
local resolve_xml = vlc.strings.resolve_xml_special_chars
for op, tag, p, empty, val in string.gmatch(
data,
"[%s\r\n\t]*<(%/?)([%w:_]+)(.-)(%/?)>"..
"[%s\r\n\t]*([^<]*)[%s\r\n\t]*"
) do
if op=="/" then
if level>0 then
level = level - 1
table.remove(stack)
end
else
level = level + 1
if val == "" then
if type(stack[level][tag]) == "nil" then
stack[level][tag] = {}
table.insert(stack, stack[level][tag])
else
if type(stack[level][tag][1]) == "nil" then
tmp = nil
tmp = stack[level][tag]
stack[level][tag] = nil
stack[level][tag] = {}
table.insert(stack[level][tag], tmp)
end
tmp = nil
tmp = {}
table.insert(stack[level][tag], tmp)
table.insert(stack, tmp)
end
else
if type(stack[level][tag]) == "nil" then
stack[level][tag] = {}
end
stack[level][tag] = resolve_xml(val)
table.insert(stack, {})
end
if empty ~= "" then
stack[level][tag] = ""
level = level - 1
table.remove(stack)
end
end
end
collectgarbage()
return tree
end
function parse_xmlrpc(data)
local tree = {}
local stack = {}
local tmp = {}
local tmpTag = ""
local level = 0
local op, tag, p, empty, val
local resolve_xml = vlc.strings.resolve_xml_special_chars
table.insert(stack, tree)
for op, tag, p, empty, val in string.gmatch(
data,
"<(%/?)([%w:]+)(.-)(%/?)>[%s\r\n\t]*([^<]*)"
) do
if op=="/" then
if tag == "member" or tag == "array" then
if level>0 then
level = level - 1
table.remove(stack)
end
end
elseif tag == "name" then
level = level + 1
if val~= "" then tmpTag = resolve_xml(val) end
if type(stack[level][tmpTag]) == "nil" then
stack[level][tmpTag] = {}
table.insert(stack, stack[level][tmpTag])
else
tmp = nil
tmp = {}
table.insert(stack[level-1], tmp)
stack[level] = nil
stack[level] = tmp
table.insert(stack, tmp)
end
if empty ~= "" then
level = level - 1
stack[level][tmpTag] = ""
table.remove(stack)
end
elseif tag == "array" then
level = level + 1
tmp = nil
tmp = {}
table.insert(stack[level], tmp)
table.insert(stack, tmp)
elseif val ~= "" then
stack[level][tmpTag] = resolve_xml(val)
end
end
collectgarbage()
return tree
end
function dump_xml(data)
local level = 0
local stack = {}
local dump = ""
local convert_xml = vlc.strings.convert_xml_special_chars
local function parse(data, stack)
local data_index = {}
local k
local v
local i
local tb
for k,v in pairs(data) do
table.insert(data_index, {k, v})
table.sort(data_index, function(a, b)
return a[1] < b[1]
end)
end
for i,tb in pairs(data_index) do
k = tb[1]
v = tb[2]
if type(k)=="string" then
dump = dump.."\r\n"..string.rep(
" ",
level)..
"<"..k..">"
table.insert(stack, k)
level = level + 1
elseif type(k)=="number" and k ~= 1 then
dump = dump.."\r\n"..string.rep(
" ",
level-1)..
"<"..stack[level]..">"
end
if type(v)=="table" then
parse(v, stack)
elseif type(v)=="string" then
dump = dump..(convert_xml(v) or v)
elseif type(v)=="number" then
dump = dump..v
else
dump = dump..tostring(v)
end
if type(k)=="string" then
if type(v)=="table" then
dump = dump.."\r\n"..string.rep(
" ",
level-1)..
"</"..k..">"
else
dump = dump.."</"..k..">"
end
table.remove(stack)
level = level - 1
elseif type(k)=="number" and k ~= #data then
if type(v)=="table" then
dump = dump.."\r\n"..string.rep(
" ",
level-1)..
"</"..stack[level]..">"
else
dump = dump.."</"..stack[level]..">"
end
end
end
end
parse(data, stack)
collectgarbage()
return dump
end
--[[ Misc utils]]--
function make_uri(str)
str = str:gsub("\\", "/")
local windowdrive = string.match(str, "^(%a:).+$")
local encode_uri = vlc.strings.encode_uri_component
local encodedPath = ""
for w in string.gmatch(str, "/([^/]+)") do
encodedPath = encodedPath.."/"..encode_uri(w)
end
if windowdrive then
return "file:///"..windowdrive..encodedPath
else
return "file://"..encodedPath
end
end
function file_touch(name) -- test write ability
if not name or trim(name) == ""
then return false end
local f=io.open(name ,"w")
if f~=nil then
io.close(f)
return true
else
return false
end
end
function file_exist(name) -- test readability
if not name or trim(name) == ""
then return false end
local f=io.open(name ,"r")
if f~=nil then
io.close(f)
return true
else
return false
end
end
function is_dir(path)
if not path or trim(path) == ""
then return false end
-- Remove slash at the end or it won't work on Windows
path = string.gsub(path, "^(.-)[\\/]?$", "%1")
local f, _, code = io.open(path, "rb")
if f then
_, _, code = f:read("*a")
f:close()
if code == 21 then
return true
end
elseif code == 13 then
return true
end
return false
end
function list_dir(path)
if not path or trim(path) == ""
then return false end
local dir_list_cmd
local list = {}
if not is_dir(path) then return false end
if openSub.conf.os == "win" then
dir_list_cmd = io.popen('dir /b "'..path..'"')
elseif openSub.conf.os == "lin" then
dir_list_cmd = io.popen('ls -1 "'..path..'"')
end
if dir_list_cmd then
for filename in dir_list_cmd:lines() do
if string.match(filename, "^[^%s]+.+$") then
table.insert(list, filename)
end
end
return list
else
return false
end
end
function mkdir_p(path)
if not path or trim(path) == ""
then return false end
if openSub.conf.os == "win" then
os.execute('mkdir "' .. path..'"')
elseif openSub.conf.os == "lin" then
os.execute("mkdir -p '" .. path.."'")
end
end
function decode_uri(str)
vlc.msg.err(slash)
return str:gsub("/", slash)
end
function is_window_path(path)
return string.match(path, "^(%a:.+)$")
end
function is_win_safe(path)
if not path or trim(path) == ""
or not is_window_path(path)
then return false end
return string.match(path, "^%a?%:?[\\%w%p%s§¤]+$")
end
function trim(str)
if not str then return "" end
return string.gsub(str, "^[\r\n%s]*(.-)[\r\n%s]*$", "%1")
end
function remove_tag(str)
return string.gsub(str, "{[^}]+}", "")
end
| gpl-2.0 |
CommandPost/CommandPost-App | extensions/httpserver/cgilua_compatibility_functions.lua | 6 | 40556 | --- === hs.httpserver.hsminweb.cgilua ===
---
--- Provides support functions in the `cgilua` module for Hammerspoon Minimal Web Server Lua templates.
---
--- This file contains functions which attempt to mimic as closely as possible the functions available to lua template files in the CGILua module provided by the Kepler Project at http://keplerproject.github.io/cgilua/index.html
---
--- The goal of this file is to provide most of the same functionality that CGILua does for template files. Any differences in the results or errors are most likely due to this code and you should direct all error reports or code change suggestions to the Hammerspoon GitHub repository.
---
--- **Do not include this file directly in your Lua templates.** This library is provided automatically in the `cgilua` table (module) in Lua template web server files. This submodule will only work from within that environment and should not be used in any other code.
-- Per the CGILua license at http://keplerproject.github.io/cgilua/license.html, portions of this file may be covered under the following license:
--
-- Copyright © 2003 Kepler Project.
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--
local cgilua = {}
--- hs.httpserver.hsminweb.cgilua.print(...) -> nil
--- Function
--- Appends the given arguments to the response body.
---
--- Parameters:
--- * ... - a list of comma separated arguments to add to the response body
---
--- Returns:
--- * None
---
--- Notes:
--- * Available within a lua template file as `cgilua.print`
--- * This function works like the lua builtin `print` command in that it converts all its arguments to strings, separates them with tabs (`\t`), and ends the line with a newline (`\n`) before appending them to the current response body.
cgilua.print = function(_parent, ...)
local args = { ... }
for i = 1, select("#",...) do
args[i] = tostring(args[i])
end
_parent.response.body = _parent.response.body .. table.concat(args, "\t") .. "\n"
end
--- hs.httpserver.hsminweb.cgilua.put(...) -> nil
--- Function
--- Appends the given arguments to the response body.
---
--- Parameters:
--- * ... - a list of comma separated arguments to add to the response body
---
--- Returns:
--- * None
---
--- Notes:
--- * Available within a lua template file as `cgilua.put`
--- * This function works by flattening tables and converting all values except for `nil` and `false` to their string representation and then appending them in order to the response body. Unlike `cgilua.print`, it does not separate values with a tab character or terminate the line with a newline character.
cgilua.put = function(_parent, ...)
for _, s in ipairs{ ... } do
if type(s) == "table" then
cgilua.put(_parent, table.unpack(s))
elseif s then
_parent.response.body = _parent.response.body .. tostring(s)
end
end
end
--- hs.httpserver.hsminweb.cgilua.errorlog(msg) -> nil
--- Function
--- Sends the message to the `hs.httpserver.hsminweb` log, tagged as an error.
---
--- Parameters:
--- * msg - the message to send to the module's error log
---
--- Returns:
--- * None
---
--- Notes:
--- * Available within a lua template file as `cgilua.errorlog`
--- * By default, messages logged with this method will appear in the Hammerspoon console and are available in the `hs.logger` history.
cgilua.errorlog = function(_parent, string) _parent.log.e(string) end
--- hs.httpserver.hsminweb.cgilua.tmp_path
--- Variable
--- The directory used by `cgilua.tmpfile`
---
--- This variable contains the location where temporary files should be created. Defaults to the user's temporary directory as returned by `hs.fs.temporaryDirectory`.
cgilua.tmp_path = require"hs.fs".temporaryDirectory():match("^(.*)/")
--- hs.httpserver.hsminweb.cgilua.tmpname() -> string
--- Function
--- Returns a temporary file name used by `cgilua.tmpfile`.
---
--- Parameters:
--- * None
---
--- Returns:
--- * a temporary filename, without the path.
---
--- Notes:
--- * This function uses `hs.host.globallyUniqueString` to generate a unique file name.
cgilua.tmpname = function()
return "lua_" .. require"hs.host".globallyUniqueString()
end
--- hs.httpserver.hsminweb.cgilua.tmpfile([dir], [namefunction]) -> file[, err]
--- Function
--- Returns the file handle to a temporary file for writing, or nil and an error message if the file could not be created for any reason.
---
--- Parameters:
--- * dir - the system directory where the temporary file should be created. Defaults to `cgilua.tmp_path`.
--- * namefunction - an optional function used to generate unique file names for use as temporary files. Defaults to `cgilua.tmpname`.
---
--- Returns:
--- * the created file's handle and the filename or nil and an error message if the file could not be created.
---
--- Notes:
--- * The file is automatically deleted when the HTTP request has been completed, so if you need for the data to persist, make sure to `io.flush` or `io.close` the file handle yourself and copy the file to a more permanent location.
cgilua.tmpfile = function(_parent, dir, namefunction)
dir = dir or cgilua.tmp_path
namefunction = namefunction or cgilua.tmpname
local tempname = namefunction()
local filename = dir.."/"..tempname
local file, err = io.open(filename, "w+b")
if file then
table.insert(_parent._tmpfiles, {name = filename, file = file})
err = filename
end
return file, err
end
--- hs.httpserver.hsminweb.cgilua.servervariable(varname) -> string
--- Function
--- Returns a string with the value of the CGI environment variable correspoding to varname.
---
--- Parameters:
--- * varname - the name of the CGI variable to get the value of.
---
--- Returns:
--- * the value of the CGI variable as a string, or nil if no such variable exists.
---
--- Notes:
--- * CGI Variables include server defined values commonly shared with CGI scripts and the HTTP request headers from the web request. The server variables include the following (note that depending upon the request and type of resource the URL refers to, not all values may exist for every request):
--- * "AUTH_TYPE" - If the server supports user authentication, and the script is protected, this is the protocol-specific authentication method used to validate the user.
--- * "CONTENT_LENGTH" - The length of the content itself as given by the client.
--- * "CONTENT_TYPE" - For queries which have attached information, such as HTTP POST and PUT, this is the content type of the data.
--- * "DOCUMENT_ROOT" - the real directory on the server that corresponds to a DOCUMENT_URI of "/". This is the first directory which contains files or sub-directories which are served by the web server.
--- * "DOCUMENT_URI" - the path portion of the HTTP URL requested
--- * "GATEWAY_INTERFACE" - The revision of the CGI specification to which this server complies. Format: CGI/revision
--- * "PATH_INFO" - The extra path information, as given by the client. In other words, scripts can be accessed by their virtual pathname, followed by extra information at the end of this path. The extra information is sent as PATH_INFO. This information should be decoded by the server if it comes from a URL before it is passed to the CGI script.
--- * "PATH_TRANSLATED" - The server provides a translated version of PATH_INFO, which takes the path and does any virtual-to-physical mapping to it.
--- * "QUERY_STRING" - The information which follows the "?" in the URL which referenced this script. This is the query information. It should not be decoded in any fashion. This variable should always be set when there is query information, regardless of command line decoding.
--- * "REMOTE_ADDR" - The IP address of the remote host making the request.
--- * "REMOTE_HOST" - The hostname making the request. If the server does not have this information, it should set REMOTE_ADDR and leave this unset.
--- * "REMOTE_IDENT" - If the HTTP server supports RFC 931 identification, then this variable will be set to the remote user name retrieved from the server. Usage of this variable should be limited to logging only.
--- * "REMOTE_USER" - If the server supports user authentication, and the script is protected, this is the username they have authenticated as.
--- * "REQUEST_METHOD" - The method with which the request was made. For HTTP, this is "GET", "HEAD", "POST", etc.
--- * "REQUEST_TIME" - the time the server received the request represented as the number of seconds since 00:00:00 UTC on 1 January 1970. Usable with `os.date` to provide the date and time in whatever format you require.
--- * "REQUEST_URI" - the DOCUMENT_URI with any query string present in the request appended. Usually this corresponds to the URL without the scheme or host information.
--- * "SCRIPT_FILENAME" - the actual path to the script being executed.
--- * "SCRIPT_NAME" - A virtual path to the script being executed, used for self-referencing URLs.
--- * "SERVER_NAME" - The server's hostname, DNS alias, or IP address as it would appear in self-referencing URLs.
--- * "SERVER_PORT" - The port number to which the request was sent.
--- * "SERVER_PROTOCOL" - The name and revision of the information protcol this request came in with. Format: protocol/revision
--- * "SERVER_SOFTWARE" - The name and version of the web server software answering the request (and running the gateway). Format: name/version
---
--- * The HTTP Request header names are prefixed with "HTTP_", converted to all uppercase, and have all hyphens converted into underscores. Common headers (converted to their CGI format) might include, but are not limited to:
--- * HTTP_ACCEPT, HTTP_ACCEPT_ENCODING, HTTP_ACCEPT_LANGUAGE, HTTP_CACHE_CONTROL, HTTP_CONNECTION, HTTP_DNT, HTTP_HOST, HTTP_USER_AGENT
--- * This server also defines the following (which are replicated in the CGI variables above, so those should be used for portability):
--- * HTTP_X_REMOTE_ADDR, HTTP_X_REMOTE_PORT, HTTP_X_SERVER_ADDR, HTTP_X_SERVER_PORT
--- * A list of common request headers and their definitions can be found at https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
cgilua.servervariable = function(_parent, varname)
return _parent.CGIVariables[varname]
end
--- hs.httpserver.hsminweb.cgilua.splitonlast(path) -> directory, file
--- Function
--- Returns two strings with the "directory path" and "file" parts of the given path string splitted on the last separator ("/" or "\").
---
--- Parameters:
--- * path - the path to split
---
--- Returns:
--- * the directory path, the file
---
--- Notes:
--- * This function used to be called cgilua.splitpath and still can be accessed by this name for compatibility reasons. cgilua.splitpath may be deprecated in future versions.
cgilua.splitonlast = function(_, path) return path:match("^(.-)([^:/\\]*)$") end
cgilua.splitpath = cgilua.splitonlast -- compatibility with previous versions
--- hs.httpserver.hsminweb.cgilua.splitfirst(path) -> path component, path remainder
--- Function
--- Returns two strings with the "first directory" and the "remaining paht" of the given path string splitted on the first separator ("/" or "\").
---
--- Parameters:
--- * path - the path to split
---
--- Returns:
--- * the first directory component, the remainder of the path
cgilua.splitonfirst = function(_, path) return path:match("^/([^:/\\]*)(.*)") end
--- hs.httpserver.hsminweb.cgilua.script_path
--- Variable
--- The system path of the running script. Equivalent to the CGI environment variable SCRIPT_FILENAME.
---
--- Notes:
--- * CGILua supports being invoked through a URL that amounts to set of chained paths and script names; this is not necessary for this module, so these variables may differ somewhat from a true CGILua installation; the intent of the variable has been maintained as closely as I can determine at present. If this changes, so will this documentation.
--- hs.httpserver.hsminweb.cgilua.script_file
--- Variable
--- The file name of the running script. Obtained from cgilua.script_path.
---
--- Notes:
--- * CGILua supports being invoked through a URL that amounts to set of chained paths and script names; this is not necessary for this module, so these variables may differ somewhat from a true CGILua installation; the intent of the variable has been maintained as closely as I can determine at present. If this changes, so will this documentation.
--- hs.httpserver.hsminweb.cgilua.script_pdir
--- Variable
--- The directory of the running script. Obtained from cgilua.script_path.
---
--- Notes:
--- * CGILua supports being invoked through a URL that amounts to set of chained paths and script names; this is not necessary for this module, so these variables may differ somewhat from a true CGILua installation; the intent of the variable has been maintained as closely as I can determine at present. If this changes, so will this documentation.
--- hs.httpserver.hsminweb.cgilua.script_vpath
--- Variable
--- Equivalent to the CGI environment variable PATH_INFO or "/", if no PATH_INFO is set.
---
--- Notes:
--- * CGILua supports being invoked through a URL that amounts to set of chained paths and script names; this is not necessary for this module, so these variables may differ somewhat from a true CGILua installation; the intent of the variable has been maintained as closely as I can determine at present. If this changes, so will this documentation.
--- hs.httpserver.hsminweb.cgilua.script_vdir
--- Variable
--- If PATH_INFO represents a directory (i.e. ends with "/"), then this is equal to `cgilua.script_vpath`. Otherwise, this contains the directory portion of `cgilua.script_vpath`.
---
--- Notes:
--- * CGILua supports being invoked through a URL that amounts to set of chained paths and script names; this is not necessary for this module, so these variables may differ somewhat from a true CGILua installation; the intent of the variable has been maintained as closely as I can determine at present. If this changes, so will this documentation.
--- hs.httpserver.hsminweb.cgilua.urlpath
--- Variable
--- The name of the script as requested in the URL. Equivalent to the CGI environment variable SCRIPT_NAME.
---
--- Notes:
--- * CGILua supports being invoked through a URL that amounts to set of chained paths and script names; this is not necessary for this module, so these variables may differ somewhat from a true CGILua installation; the intent of the variable has been maintained as closely as I can determine at present. If this changes, so will this documentation.
--- hs.httpserver.hsminweb.cgilua.doscript(filename) -> results
--- Function
--- Executes a lua file (given by filepath).
---
--- Parameters:
--- * filepath - the file to interpret as Lua code
---
--- Returns:
--- * the values returned by the execution, or nil followed by an error message if the file does not exists.
---
--- Notes:
--- * If the file does not exist, an Internal Server error is returned to the client and an error is logged to the Hammerspoon console.
--- * During the processing of a web request, the local directory is temporarily changed to match the local directory of the path of the file being served, as determined by the URL of the request. This is usually different than the Hammerspoon default directory which corresponds to the directory which contains the `init.lua` file for Hammerspoon.
cgilua.doscript = function(_parent, filename)
local f, err = loadfile(filename, "bt", _parent.__luaInternal_cgiluaENV)
if not f then
error(string.format("Cannot execute '%s'. Exiting.\n%s", filename, err), 3)
else
local results = { xpcall(f, _parent.__luaInternal_cgiluaENV.cgilua._errorhandler) }
local ok = table.remove(results, 1)
if ok then
if #results == 0 then results = { true } end
return table.unpack(results)
else
error(table.unpack(results), 3)
end
end
end
--- hs.httpserver.hsminweb.cgilua.doif(filename) -> results
--- Function
--- Executes a lua file (given by filepath) if it exists.
---
--- Parameters:
--- * filepath - the file to interpret as Lua code
---
--- Returns:
--- * the values returned by the execution, or nil followed by an error message if the file does not exists.
---
--- Notes:
--- * This function only interprets the file if it exists; if the file does not exist, it returns an error to the calling code (not the web client)
--- * During the processing of a web request, the local directory is temporarily changed to match the local directory of the path of the file being served, as determined by the URL of the request. This is usually different than the Hammerspoon default directory which corresponds to the directory which contains the `init.lua` file for Hammerspoon.
cgilua.doif = function(_parent, filename)
if not filename then return end -- no file
local f, err = io.open(filename)
if not f then return nil, err end -- no file (or unreadable file)
f:close()
return cgilua.doscript(_parent, filename)
end
--- hs.httpserver.hsminweb.cgilua.contentheader(maintype, subtype) -> none
--- Function
--- Sets the HTTP response type for the content being generated to maintype/subtype.
---
--- Parameters:
--- * maintype - the primary content type (e.g. "text")
--- * subtype - the sub-type for the content (e.g. "plain")
---
--- Returns:
--- * None
---
--- Notes:
--- * This sets the `Content-Type` header field for the HTTP response being generated. This will override any previous setting, including the default of "text/html".
cgilua.contentheader = function(_parent, mainType, subType)
_parent.response.headers["Content-Type"] = tostring(mainType) .. "/" .. tostring(subType)
end
--- hs.httpserver.hsminweb.cgilua.htmlheader() -> none
--- Function
--- Sets the HTTP response type to "text/html"
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
---
--- Notes:
--- * This sets the `Content-Type` header field for the HTTP response being generated to "text/html". This is the default value, so generally you should not need to call this function unless you have previously changed it with the [cgilua.contentheader](#contentheader) function.
cgilua.htmlheader = function(_parent)
_parent.response.headers["Content-Type"] = "text/html"
end
--- hs.httpserver.hsminweb.cgilua.header(key, value) -> none
--- Function
--- Sets the HTTP response header `key` to `value`
---
--- Parameters:
--- * key - the HTTP response header to set a value to. This should be a string.
--- * value - the value for the header. This should be a string or a value representable as a string.
---
--- Returns:
--- * None
---
--- Notes:
--- * You should not use this function to set the value for the "Content-Type" key; instead use [cgilua.contentheader](#contentheader) or [cgilua.htmlheader](#htmlheader).
cgilua.header = function(_parent, key, value)
_parent.response.headers[key] = value
end
--- hs.httpserver.hsminweb.cgilua.redirect(url, [args]) -> none
--- Function
--- Sends the headers to force a redirection to the given URL adding the parameters in table args to the new URL.
---
--- Parameters:
--- * url - the URL the client should be redirected to
--- * args - an optional table which should have key-value pairs that will be encoded to form a valid query at the end of the URL (see [cgilua.urlcode.encodetable](#encodetable).
---
--- Returns:
--- * None
---
--- Notes:
--- * This function should generally be followed by a `return` in your lua template page as no additional processing or output should occur when a request is to be redirected.
cgilua.redirect = function(_parent, url, args)
if not url:find("^https?:") then
if url:find("^/") then
url = _parent.CGIVariables.REQUEST_SCHEME .. "://" .. _parent.CGIVariables.HTTP_HOST .. url
else
url = _parent.CGIVariables.REQUEST_SCHEME .. "://" .. _parent.CGIVariables.HTTP_HOST .. "/" .. table.concat(_parent.request.headers._.pathParts.pathComponents, "/", 2, #_parent.request.headers._.pathParts.pathComponents - 1) .. url
end
end
local params = ""
if args then
params = "?" .. cgilua.urlcode.encodetable(_parent, args)
end
_parent.response.code = 307
_parent.response.headers["Location"] = url .. params
end
--- hs.httpserver.hsminweb.cgilua.mkabsoluteurl(uri) -> string
--- Function
--- Returns an absolute URL for the given URI by prepending the path with the scheme, hostname, and port of this web server.
---
--- Parameters:
--- * URI - A path to a resource served by this web server. A "/" will be prepended to the path if it is not present.
---
--- Returns:
--- * An absolute URL for the given path of the form "scheme://hostname:port/path" where `scheme` will be either "http" or "https", and the hostname and port will match that of this web server.
---
--- Notes:
--- * If you wish to append query items to the path or expand a relative path into it's full path, see [cgilua.mkurlpath](#mkurlpath).
cgilua.mkabsoluteurl = function(_parent, path)
if path:sub(1,1) ~= '/' then
path = '/'..path
end
return string.format("%s://%s:%s%s",
_parent.CGIVariables.REQUEST_SCHEME,
_parent.CGIVariables.SERVER_NAME,
_parent.CGIVariables.SERVER_PORT,
path)
end
--- hs.httpserver.hsminweb.cgilua.mkurlpath(uri, [args]) -> string
--- Function
--- Creates a full document URI from a partial URI, including query arguments if present.
---
--- Parameters:
--- * uri - the full or partial URI (path and file component of a URL) of the document
--- * args - an optional table which should have key-value pairs that will be encoded to form a valid query at the end of the URI (see [cgilua.urlcode.encodetable](#encodetable).
---
--- Returns:
--- * A full URI including any query arguments, if present.
---
--- Notes:
--- * This function is intended to be used in conjunction with [cgilua.mkabsoluteurl](#mkabsoluteurl) to generate a full URL. If the `uri` provided does not begin with a "/", then the current directory path is prepended to the uri and any query arguments are appended.
--- * e.g. `cgilua.mkabsoluteurl(cgiurl.mkurlpath("file.lp", { key = value, ... }))` will return a full URL specifying the file `file.lp` in the current directory with the specified key-value pairs as query arguments.
cgilua.mkurlpath = function(_parent, script, args)
local params = ""
if args then
params = "?" .. cgilua.urlcode.encodetable(_parent, args)
end
local urldir = _parent.__luaInternal_cgiluaENV.cgilua.urlpath:match("^(.-)[^:/\\]*$")
if script:sub(1,1) == '/' then
return script .. params
else
return urldir .. script .. params
end
end
--- === hs.httpserver.hsminweb.cgilua.urlcode ===
---
--- Support functions for the CGILua compatibility module for encoding and decoding URL components in accordance with RFC 3986.
cgilua.urlcode = {}
--- hs.httpserver.hsminweb.cgilua.urlcode.escape(string) -> string
--- Function
--- URL encodes the provided string, making it safe as a component within a URL.
---
--- Parameters:
--- * string - the string to encode
---
--- Returns:
--- * a string with non-alphanumeric characters percent encoded and spaces converted into "+" as per RFC 3986.
---
--- Notes:
--- * this function assumes that the provided string is a single component and URL encodes *all* non-alphanumeric characters. Do not use this function to generate a URL query string -- use [cgilua.urlcode.encodetable](#encodetable).
cgilua.urlcode.escape = function(_, str)
return (str:gsub("\n", "\r\n"):gsub("([^0-9a-zA-Z ])", function(_) return string.format("%%%02X", string.byte(_)) end):gsub(" ", "+"))
end
--- hs.httpserver.hsminweb.cgilua.urlcode.unescape(string) -> string
--- Function
--- Removes any URL encoding in the provided string.
---
--- Parameters:
--- * string - the string to decode
---
--- Returns:
--- * a string with all "+" characters converted to spaces and all percent encoded sequences converted to their ascii equivalents.
cgilua.urlcode.unescape = function(_, str)
return (str:gsub("+", " "):gsub("%%(%x%x)", function(_) return string.char(tonumber(_, 16)) end):gsub("\r\n", "\n"))
end
--- hs.httpserver.hsminweb.cgilua.urlcode.encodetable(table) -> string
--- Function
--- Encodes the table of key-value pairs as a query string suitable for inclusion in a URL.
---
--- Parameters:
--- * table - a table of key-value pairs to be converted into a query string
---
--- Returns:
--- * a query string as specified in RFC 3986.
---
--- Notes:
--- * the string will be of the form: "key1=value1&key2=value2..." where all of the keys and values are properly escaped using [cgilua.urlcode.escape](#escape). If you are crafting a URL by hand, the result of this function should be appended to the end of the URL after a "?" character to specify where the query string begins.
cgilua.urlcode.encodetable = function(_parent, args)
if args == nil or next(args) == nil then return "" end
local results = {}
for k, v in pairs(args) do
if type(v) ~= "table" then v = { v } end
for _, v2 in ipairs(v) do
table.insert(results, cgilua.urlcode.escape(_parent, tostring(k)) .. "=" .. cgilua.urlcode.escape(_parent, tostring(v2)))
end
end
return table.concat(results, "&")
end
--- hs.httpserver.hsminweb.cgilua.urlcode.insertfield(table, key, value) -> none
--- Function
--- Inserts the specified key and value into the table of key-value pairs.
---
--- Parameters:
--- * table - the table of arguments being built
--- * key - the key name
--- * value - the value to assign to the key specified
---
--- Returns:
--- * None
---
--- Notes:
--- * If the key already exists in the table, its value is converted to a table (if it isn't already) and the new value is added to the end of the array of values for the key.
--- * This function is used internally by [cgilua.urlcode.parsequery](#parsequery) or can be used to prepare a table of key-value pairs for [cgilua.urlcode.encodetable](#encodetable).
cgilua.urlcode.insertfield = function(_, args, name, value)
if not args[name] then
args[name] = value
else
local t = type(args[name])
if t ~= "table" then
args[name] = {
args[name],
value,
}
else
table.insert(args[name], value)
end
end
end
--- hs.httpserver.hsminweb.cgilua.urlcode.parsequery(query, table) -> none
--- Function
--- Parse the query string and store the key-value pairs in the provided table.
---
--- Parameters:
--- * query - a URL encoded query string, either from a URL or from the body of a POST request encoded in the "x-www-form-urlencoded" format.
--- * table - the table to add the key-value pairs to
---
--- Returns:
--- * None
---
--- Notes:
--- * The specification allows for the same key to be assigned multiple values in an encoded string, but does not specify the behavior; by convention, web servers assign these multiple values to the same key in an array (table). This function follows that convention. This is most commonly used by forms which allow selecting multiple options via check boxes or in a selection list.
--- * This function uses [cgilua.urlcode.insertfield](#insertfield) to build the key-value table.
cgilua.urlcode.parsequery = function(_parent, query, args)
if type(query) == "string" then
query:gsub("([^&=]+)=([^&=]*)&?",
function(key, val)
cgilua.urlcode.insertfield(_parent, args, cgilua.urlcode.unescape(_parent, key), cgilua.urlcode.unescape(_parent, val))
end)
end
end
local out = function(s, i, f)
if type(s) ~= "string" then s = tostring(s) end
s = s:sub(i, f or -1)
if s == "" then return s end
-- we could use `%q' here, but this way we have better control
s = s:gsub("([\\\n\'])", "\\%1")
-- substitute '\r' by '\'+'r' and let `loadstring' reconstruct it
s = s:gsub("\r", "\\r")
return string.format(" %s('%s'); ", "cgilua.put", s)
end
--- === hs.httpserver.hsminweb.cgilua.lp ===
---
--- Support functions for the CGILua compatibility module for including and translating Lua template pages into Lua code for execution within the Hammerspoon environment to provide dynamic content for http requests.
---
--- The most commonly used function is likely to be [cgilua.lp.include](#include), which allows including a template driven file during rendering so that common code can be reused more easily. While passing in your own environment table for upvalues is possible, this is not recommended for general use because the default environment passed to each included file ensures that all server variables and the CGILua compatibility functions are available with the same names, and any new non-local (i.e. "global") variable defined are shared with the calling environment and not shared with the Hammerspoon global environment.
---
--- If your template file requires the ability to create variables in the Hammerspoon global environment, access the global environment directly through `_G`.
---
--- Note that the above considerations only apply to creating new "global" variables. Any currently defined global variables (for example, the `hs` table where Hammerspoon module functions are stored) are available within the template file as long as no local or CGILua environment variable shares the same name (e.g. `_G["hs"]` and `hs` refer to the same table.
---
--- See the documentation for the [cgilua.lp.include](#include) for more information.
cgilua.lp = {}
--- hs.httpserver.hsminweb.cgilua.lp.translate(source) -> luaCode
--- Function
--- Converts the specified Lua template source into Lua code executable within the Hammerspoon environment.
---
--- Parameters:
--- * source - a string containing the contents of a Lua/HTML template to be converted into true Lua code
---
--- Returns:
--- * The lua code corresponding to the provided source which can be fed into the `load` lua builtin to generate a Lua function.
---
--- Notes:
--- * This function is used internally by [cgilua.lp.include](#include), and probably won't be useful unless you want to translate a dynamically generated template -- which has security implications, depending upon what inputs you use to generate this template, because the resulting Lua code will execute within your Hammerspoon environment. Be very careful about your inputs if you choose to ignore this warning.
--- * To ensure that the translated code has access to the `cgilua` support functions, pass `_ENV` as the environment argument to the `load` lua builtin; otherwise any output generated by the resulting function will be sent to the Hammerspoon console and not included in the HTTP response sent back to the client.
cgilua.lp.translate = function(_, source)
-- in an effort to attempt to maintain compatibility with CGILua, we should expect/allow the same things in a source file...
source = source:gsub("^#![^\n]+\n", "")
-- compatibility with earlier versions...
-- translates $| lua-var |$
source = source:gsub("$|(.-)|%$", "<?lua = %1 ?>")
-- translates <!--$$ lua-code $$-->
source = source:gsub("<!%-%-$$(.-)$$%-%->", "<?lua %1 ?>")
-- translates <% lua-code %>
source = source:gsub("<%%(.-)%%>", "<?lua %1 ?>")
local res = {}
local start = 1 -- start of untranslated part in `s'
while true do
local ip, fp, target, exp, code = source:find("<%?(%w*)[ \t]*(=?)(.-)%?>", start)
if not ip then break end
table.insert(res, out(source, start, ip-1))
if target ~= "" and target ~= "lua" then
-- not for Lua; pass whole instruction to the output
table.insert(res, out(source, ip, fp))
else
if exp == "=" then -- expression?
table.insert(res, string.format(" %s(%s);", "cgilua.put", code))
else -- command
table.insert(res, string.format(" %s ", code))
end
end
start = fp + 1
end
table.insert(res, out(source, start))
return table.concat(res)
end
--- hs.httpserver.hsminweb.cgilua.lp.compile(source, name, [env]) -> function
--- Function
--- Converts the specified Lua template source into a Lua function.
---
--- Parameters:
--- * source - a string containing the contents of a Lua/HTML template to be converted into a function
--- * name - a label used in an error message if execution of the returned function results in a run-time error
--- * env - an optional table specifying the environment to be used by the lua builtin function `load` when converting the source into a function. By default, the function will inherit its caller's environment.
---
--- Returns:
--- * A lua function which should take no arguments.
---
--- Notes:
--- * The source provided is first compared to a stored cache of previously translated templates and will re-use an existing translation if the template has been seen before. If the source is unique, [cgilua.lp.translate](#translate) is called on the template source.
--- * This function is used internally by [cgilua.lp.include](#include), and probably won't be useful unless you want to translate a dynamically generated template -- which has security implications, depending upon what inputs you use to generate this template, because the resulting Lua code will execute within your Hammerspoon environment. Be very careful about your inputs if you choose to ignore this warning.
cgilua.lp.compile = function(_parent, string, chunkname, env)
local s = _parent.__luaCached_translations[string]
if not s then
s = cgilua.lp.translate(_parent, string)
_parent.__luaCached_translations[string] = s
end
local f, err = load(s, chunkname, "bt", env or _parent.__luaInternal_cgiluaENV)
if not f then error(err, 3) end
return f
end
--- hs.httpserver.hsminweb.cgilua.lp.include(file, [env]) -> none
--- Function
--- Includes the template specified by the `file` parameter.
---
--- Parameters:
--- * file - a string containing the file system path to the template to include.
--- * env - an optional table specifying the environment to be used by the included template. By default, the template will inherit its caller's environment.
---
--- Returns:
--- * None
---
--- Notes:
--- * This function is called by the web server to process the template specified by the requested URL. Subsequent invocations of this function can be used to include common or re-used code from other template files and will be included in-line where the `cgilua.lp.include` function is invoked in the originating template.
--- * During the processing of a web request, the local directory is temporarily changed to match the local directory of the path of the file being served, as determined by the URL of the request. This is usually different than the Hammerspoon default directory which corresponds to the directory which contains the `init.lua` file for Hammerspoon.
---
--- * The default template environment provides the following:
--- * the `__index` metamethod points to the `_G` environment variable in the Hammerspoon Lua instance; this means that any global variable in the Hammerspoon environment is available to the lua code in a template file.
--- * the `__newindex` metamethod points to a function which creates new "global" variables in the template files environment; this means that if a template includes another template file, and that second template file creates a "global" variable, that new variable will be available in the environment of the calling template, but will not be shared with the Hammerspoon global variable space; "global" variables created in this manner will be released when the HTTP request is completed.
---
--- * `print` is overridden so that its output is streamed into the response body to be returned when the web request completes. It follows the traditional pattern of the `print` builtin function: multiple arguments are separated by a tab character, the output is terminated with a new-line character, non-string arguments are converted to strings via the `tostring` builtin function.
--- * `write` is defined as an alternative to `print` and differs in the following ways from the `print` function described above: no intermediate tabs or newline are included in the output streamed to the response body.
--- * `cgilua` is defined as a table containing all of the functions included in this support sub-module.
--- * `hsminweb` is defined as a table which contains the following tables which may be of use:
--- * CGIVariables - a table containing key-value pairs of the same data available through the [cgilua.servervariable](#servervariable) function.
--- * id - a string, generated via `hs.host.globallyUniqueString`, unique to this specific HTTP request.
--- * log - a table/object representing the `hs.httpserver.hsminweb` instance of `hs.logger`. This can be used to log messages to the Hammerspoon console as described in the documentation for `hs.logger`.
--- * request - a table containing data representing the details of the HTTP request as it was made by the web client to the server. The following keys are commonly found:
--- * headers - a table containing key-value pairs representing the headers included in the HTTP request; unlike the values available through [cgilua.servervariable](#servervariable) or found in `CGIVariables`, these are available in their raw form.
--- * this table also contains a table with the key "_". This table contains functions and data used internally, and is described more fully in a supporting document (TBD). It is targeted primarily at custom error functions designed for use with `hs.httpserver.hsminweb` and should not generally be necessary for Lua template files.
--- * method - the method of the HTTP request, most commonly "GET" or "POST"
--- * path - the path portion of the requested URL.
--- * response - a table containing data representing the response being formed for the response to the HTTP request. This is generally handled for you by the `cgilua` support functions, but for special cases, you can modify it directly; this should contain only the following keys:
--- * body - a string containing the response body. As the lua template outputs content, this string is appended to.
--- * code - an integer representing the currently expected response code for the HTTP request.
--- * headers - a table containing key-value pairs of the currently defined response headers
--- * _tmpfiles - used internally to track temporary files used in the completion of this HTTP request; do not modify directly.
cgilua.lp.include = function(_parent, filename, env)
-- read the whole contents of the file
local fh = assert(io.open(filename))
local src = fh:read("a")
fh:close()
if src:sub(1,3) == "\xEF\xBB\xBF" then src = src:sub(4) end
-- translates the file into a function
local prog = cgilua.lp.compile(_parent, src, '@'..filename, env or _parent.__luaInternal_cgiluaENV)
prog()
end
return cgilua
| mit |
ara8586/9900 | plugins/filter.lua | 1 | 2517 | local function addword(msg, name)
local hash = 'chat:'..msg.to.id..':badword'
redis:hset(hash, name, 'newword')
return "کلمه جدید به فیلتر کلمات اضافه شد\n>"..name
end
local function get_variables_hash(msg)
return 'chat:'..msg.to.id..':badword'
end
local function list_variablesbad(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = 'لیست کلمات غیرمجاز :\n\n'
for i=1, #names do
text = text..'> '..names[i]..'\n'
end
return text
else
return
end
end
function clear_commandbad(msg, var_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:del(hash, var_name)
return 'پاک شدند'
end
local function list_variables2(msg, value)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
if string.match(value, names[i]) and not is_momod(msg) then
if msg.to.type == 'channel' then
delete_msg(msg.id,ok_cb,false)
else
kick_user(msg.from.id, msg.to.id)
end
return
end
--text = text..names[i]..'\n'
end
end
end
local function get_valuebad(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
function clear_commandsbad(msg, cmd_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:hdel(hash, cmd_name)
return ''..cmd_name..' پاک شد'
end
local function run(msg, matches)
if matches[2] == 'filter' then
if not is_momod(msg) then
return 'only for moderators'
end
local name = string.sub(matches[3], 1, 50)
local text = addword(msg, name)
return text
end
if matches[2] == 'filterlist' then
return list_variablesbad(msg)
elseif matches[2] == 'clean' then
if not is_momod(msg) then return '_|_' end
local asd = '1'
return clear_commandbad(msg, asd)
elseif matches[2] == 'unfilter' or matches[2] == 'rw' then
if not is_momod(msg) then return '_|_' end
return clear_commandsbad(msg, matches[3])
else
local name = user_print_name(msg.from)
return list_variables2(msg, matches[1])
end
end
return {
patterns = {
"^([!/#])(rw) (.*)$",
"^([!/#])(filter) (.*)$",
"^([!/#])(unfilter) (.*)$",
"^([!/#])(filterlist)$",
"^([!#/])(clean) filterlist$",
"^(.+)$",
},
run = run
}
-- by @mr_ahmadix
-- sp @suport_arabot
| agpl-3.0 |
MalRD/darkstar | scripts/globals/items/homura.lua | 12 | 1066 | -----------------------------------------
-- ID: 16973
-- Item: Homura
-- Additional Effect: Fire Damage
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/magic")
require("scripts/globals/msg")
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 5
if (math.random(0,99) >= chance) then
return 0,0,0
else
local dmg = math.random(4,19)
local params = {}
params.bonusmab = 0
params.includemab = false
dmg = addBonusesAbility(player, dsp.magic.ele.FIRE, target, dmg, params)
dmg = dmg * applyResistanceAddEffect(player,target,dsp.magic.ele.FIRE,0)
dmg = adjustForTarget(target,dmg,dsp.magic.ele.FIRE)
dmg = finalMagicNonSpellAdjustments(player,target,dsp.magic.ele.FIRE,dmg)
local message = dsp.msg.basic.ADD_EFFECT_DMG
if (dmg < 0) then
message = dsp.msg.basic.ADD_EFFECT_HEAL
end
return dsp.subEffect.FIRE_DAMAGE,message,dmg
end
end | gpl-3.0 |
robertbrook/Penlight | examples/symbols.lua | 9 | 6518 | require 'pl'
utils.import 'pl.func'
local ops = require 'pl.operator'
local List = require 'pl.List'
local append,concat = table.insert,table.concat
local compare,find_if,compare_no_order,imap,reduce,count_map = tablex.compare,tablex.find_if,tablex.compare_no_order,tablex.imap,tablex.reduce,tablex.count_map
local unpack = utils.unpack
function bindval (self,val)
rawset(self,'value',val)
end
local optable = ops.optable
function sexpr (e)
if isPE(e) then
if e.op ~= 'X' then
local args = tablex.imap(sexpr,e)
return '('..e.op..' '..table.concat(args,' ')..')'
else
return e.repr
end
else
return tostring(e)
end
end
psexpr = compose(print,sexpr)
function equals (e1,e2)
local p1,p2 = isPE(e1),isPE(e2)
if p1 ~= p2 then return false end -- different kinds of animals!
if p1 and p2 then -- both PEs
-- operators must be the same
if e1.op ~= e2.op then return false end
-- PHs are equal if their representations are equal
if e1.op == 'X' then return e1.repr == e2.repr
-- commutative operators
elseif e1.op == '+' or e1.op == '*' then
return compare_no_order(e1,e2,equals)
else
-- arguments must be the same
return compare(e1,e2,equals)
end
else -- fall back on simple equality for non PEs
return e1 == e2
end
end
-- run down an unbalanced operator chain (like a+b+c) and return the arguments {a,b,c}
function tcollect (op,e,ls)
if isPE(e) and e.op == op then
for i = 1,#e do
tcollect(op,e[i],ls)
end
else
ls:append(e)
return
end
end
function rcollect (e)
local res = List()
tcollect(e.op,e,res)
return res
end
-- balance ensures that +/* chains are collected together, operates in-place.
-- thus (+(+ a b) c) or (+ a (+ b c)) becomes (+ a b c), order immaterial
function balance (e)
if isPE(e) and e.op ~= 'X' then
local op,args = e.op
if op == '+' or op == '*' then
args = rcollect(e)
else
args = imap(balance,e)
end
for i = 1,#args do
e[i] = args[i]
end
end
return e
end
-- fold constants in an expression
function fold (e)
if isPE(e) then
if e.op == 'X' then
-- there could be _bound values_!
local val = rawget(e,'value')
return val and val or e
else
local op = e.op
local addmul = op == '*' or op == '+'
-- first fold all arguments
local args = imap(fold,e)
if not addmul and not find_if(args,isPE) then
-- no placeholders in these args, we can fold the expression.
local opfn = optable[op]
if opfn then
return opfn(unpack(args))
else
return '?'
end
elseif addmul then
-- enforce a few rules for + and *
-- split the args into two classes, PE args and non-PE args.
local classes = List.partition(args,isPE)
local pe,npe = classes[true],classes[false]
if npe then -- there's at least one non PE argument
-- so fold them
if #npe == 1 then npe = npe[1]
else npe = npe:reduce(optable[op])
end
-- if the result is a constant, return it
if not pe then return npe end
-- either (* 1 x) => x or (* 1 x y ...) => (* x y ...)
if op == '*' then
if npe == 0 then return 0
elseif npe == 1 then -- identity
if #pe == 1 then return pe[1] else npe = nil end
end
else -- special cases for +
if npe == 0 then -- identity
if #pe == 1 then return pe[1] else npe = nil end
end
end
end
-- build up the final arguments
local res = {}
if npe then append(res,npe) end
for val,count in pairs(count_map(pe,equals)) do
if count > 1 then
if op == '*' then val = val ^ count
else val = val * count
end
end
append(res,val)
end
if #res == 1 then return res[1] end
return PE{op=op,unpack(res)}
elseif op == '^' then
if args[2] == 1 then return args[1] end -- identity
if args[2] == 0 then return 1 end
end
return PE{op=op,unpack(args)}
end
else
return e
end
end
function expand (e)
if isPE(e) and e.op == '*' and isPE(e[2]) and e[2].op == '+' then
local a,b = e[1],e[2]
return expand(b[1]*a) + expand(b[2]*a)
else
return e
end
end
function isnumber (x)
return type(x) == 'number'
end
-- does this PE contain a reference to x?
function references (e,x)
if isPE(e) then
if e.op == 'X' then return x.repr == e.repr
else
return find_if(e,references,x)
end
else
return false
end
end
local function muli (args)
return PE{op='*',unpack(args)}
end
local function addi (args)
return PE{op='+',unpack(args)}
end
function diff (e,x)
if isPE(e) and references(e,x) then
local op = e.op
if op == 'X' then
return 1
else
local a,b = e[1],e[2]
if op == '+' then -- differentiation is linear
local args = imap(diff,e,x)
return balance(addi(args))
elseif op == '*' then -- product rule
local res,d,ee = {}
for i = 1,#e do
d = fold(diff(e[i],x))
if d ~= 0 then
ee = {unpack(e)}
ee[i] = d
append(res,balance(muli(ee)))
end
end
if #res > 1 then return addi(res)
else return res[1] end
elseif op == '^' and isnumber(b) then -- power rule
return b*x^(b-1)
end
end
else
return 0
end
end
| mit |
MalRD/darkstar | scripts/globals/items/m&p_cracker.lua | 11 | 1071 | -----------------------------------------
-- ID: 5640
-- Item: M&P Cracker
-- Food Effect: 3Min, All Races
-----------------------------------------
-- Vitality 5
-- Mind -5
-- Defense % 25
-- Attack Cap 154
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,180,5640)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.VIT, 5)
target:addMod(dsp.mod.MND, -5)
target:addMod(dsp.mod.FOOD_DEFP, 25)
target:addMod(dsp.mod.FOOD_DEF_CAP, 154)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.VIT, 5)
target:delMod(dsp.mod.MND, -5)
target:delMod(dsp.mod.FOOD_DEFP, 25)
target:delMod(dsp.mod.FOOD_DEF_CAP, 154)
end
| gpl-3.0 |
MalRD/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Lageegee.lua | 11 | 2411 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Lageegee
-- Type: Assault Mission Giver
-- !pos 120.808 0.161 -30.435
-----------------------------------
local ID = require("scripts/zones/Aht_Urhgan_Whitegate/IDs")
require("scripts/globals/besieged")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
require("scripts/globals/npc_util")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local rank = dsp.besieged.getMercenaryRank(player)
local haveimperialIDtag
local assaultPoints = player:getAssaultPoint(PERIQIA_ASSAULT_POINT)
if player:hasKeyItem(dsp.ki.IMPERIAL_ARMY_ID_TAG) then
haveimperialIDtag = 1
else
haveimperialIDtag = 0
end
--[[ if (rank > 0) then
player:startEvent(276,rank,haveimperialIDtag,assaultPoints,player:getCurrentAssault())
else]]
player:startEvent(282) -- no rank
--end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if csid == 276 then
local selectiontype = bit.band(option, 0xF)
if selectiontype == 1 then
-- taken assault mission
player:addAssault(bit.rshift(option,4))
player:delKeyItem(dsp.ki.IMPERIAL_ARMY_ID_TAG)
npcUtil.giveKeyItem(player, dsp.ki.PERIQIA_ASSAULT_ORDERS)
elseif (selectiontype == 2) then
-- purchased an item
local item = bit.rshift(option,14)
local items =
{
[1] = {itemid = 15973, price = 3000},
[2] = {itemid = 15778, price = 5000},
[3] = {itemid = 15524, price = 8000},
[4] = {itemid = 15887, price = 10000},
[5] = {itemid = 15493, price = 10000},
[6] = {itemid = 18025, price = 15000},
[7] = {itemid = 18435, price = 15000},
[8] = {itemid = 18686, price = 15000},
[9] = {itemid = 16062, price = 20000},
[10] = {itemid = 15695, price = 20000},
[11] = {itemid = 14527, price = 20000},
}
local choice = items[item]
if choice and npcUtil.giveItem(player, choice.itemid) then
player:delCurrency("PERIQIA_ASSAULT_POINT", choice.price)
end
end
end
end
| gpl-3.0 |
MalRD/darkstar | scripts/globals/mobskills/glittering_ruby.lua | 12 | 1193 | ---------------------------------------------
-- Glittering Ruby
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/msg")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
--randomly give str/dex/vit/agi/int/mnd/chr (+12)
local effect = math.random()
local effectid = dsp.effect.STR_BOOST
if (effect<=0.14) then --STR
effectid = dsp.effect.STR_BOOST
elseif (effect<=0.28) then --DEX
effectid = dsp.effect.DEX_BOOST
elseif (effect<=0.42) then --VIT
effectid = dsp.effect.VIT_BOOST
elseif (effect<=0.56) then --AGI
effectid = dsp.effect.AGI_BOOST
elseif (effect<=0.7) then --INT
effectid = dsp.effect.INT_BOOST
elseif (effect<=0.84) then --MND
effectid = dsp.effect.MND_BOOST
else --CHR
effectid = dsp.effect.CHR_BOOST
end
target:addStatusEffect(effectid,math.random(12,14),0,90)
skill:setMsg(dsp.msg.basic.SKILL_GAIN_EFFECT)
return effectid
end
| gpl-3.0 |
Lsty/ygopro-scripts | c84136000.lua | 3 | 2000 | --復活の墓穴
function c84136000.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_BATTLE_DESTROYED)
e1:SetCondition(c84136000.condition)
e1:SetTarget(c84136000.target)
e1:SetOperation(c84136000.activate)
c:RegisterEffect(e1)
end
function c84136000.cfilter(c,tp)
return c:IsLocation(LOCATION_GRAVE) and c:GetPreviousControler()==tp and c:IsReason(REASON_BATTLE)
end
function c84136000.condition(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c84136000.cfilter,1,nil,tp)
end
function c84136000.spfilter(c,e,tp)
return c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c84136000.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return false end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.GetLocationCount(1-tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c84136000.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp)
and Duel.IsExistingTarget(c84136000.spfilter,1-tp,LOCATION_GRAVE,0,1,nil,e,1-tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g1=Duel.SelectTarget(tp,c84136000.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.Hint(HINT_SELECTMSG,1-tp,HINTMSG_SPSUMMON)
local g2=Duel.SelectTarget(1-tp,c84136000.spfilter,1-tp,LOCATION_GRAVE,0,1,1,nil,e,1-tp)
g1:Merge(g2)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g1,2,PLAYER_ALL,g1:GetFirst():GetOwner())
end
function c84136000.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
local tc=g:GetFirst()
while tc do
if tc:IsRelateToEffect(e) and Duel.SpecialSummonStep(tc,0,tc:GetControler(),tc:GetControler(),false,false,POS_FACEUP_DEFENCE) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_CHANGE_POSITION)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1,true)
end
tc=g:GetNext()
end
Duel.SpecialSummonComplete()
end
| gpl-2.0 |
Lsty/ygopro-scripts | c27178262.lua | 5 | 1668 | --六武衆の理
function c27178262.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c27178262.cost)
e1:SetTarget(c27178262.target)
e1:SetOperation(c27178262.activate)
c:RegisterEffect(e1)
end
function c27178262.costfilter(c)
return c:IsFaceup() and c:IsSetCard(0x3d) and c:IsAbleToGraveAsCost()
end
function c27178262.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c27178262.costfilter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c27178262.costfilter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.SendtoGrave(g,REASON_COST)
end
function c27178262.filter(c,e,tp)
return c:IsSetCard(0x3d) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c27178262.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and c27178262.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1
and Duel.IsExistingTarget(c27178262.filter,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c27178262.filter,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c27178262.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c90885155.lua | 3 | 4551 | --クリフォート・シェル
function c90885155.initial_effect(c)
--pendulum summon
aux.AddPendulumProcedure(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--splimit
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CANNOT_DISABLE)
e2:SetRange(LOCATION_PZONE)
e2:SetTargetRange(1,0)
e2:SetCondition(aux.nfbdncon)
e2:SetTarget(c90885155.splimit)
c:RegisterEffect(e2)
--atk down
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetRange(LOCATION_PZONE)
e3:SetCode(EFFECT_UPDATE_ATTACK)
e3:SetTargetRange(0,LOCATION_MZONE)
e3:SetValue(-300)
c:RegisterEffect(e3)
--summon with no tribute
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(90885155,0))
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e4:SetCode(EFFECT_SUMMON_PROC)
e4:SetCondition(c90885155.ntcon)
c:RegisterEffect(e4)
--change level
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_SINGLE)
e5:SetCode(EFFECT_SUMMON_COST)
e5:SetOperation(c90885155.lvop)
c:RegisterEffect(e5)
local e6=Effect.CreateEffect(c)
e6:SetType(EFFECT_TYPE_SINGLE)
e6:SetCode(EFFECT_SPSUMMON_COST)
e6:SetOperation(c90885155.lvop2)
c:RegisterEffect(e6)
--immune
local e7=Effect.CreateEffect(c)
e7:SetType(EFFECT_TYPE_SINGLE)
e7:SetCode(EFFECT_IMMUNE_EFFECT)
e7:SetProperty(EFFECT_FLAG_SINGLE_RANGE+EFFECT_FLAG_UNCOPYABLE)
e7:SetRange(LOCATION_MZONE)
e7:SetCondition(c90885155.immcon)
e7:SetValue(aux.qlifilter)
c:RegisterEffect(e7)
--effect
local e8=Effect.CreateEffect(c)
e8:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e8:SetCode(EVENT_SUMMON_SUCCESS)
e8:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e8:SetCondition(c90885155.effcon)
e8:SetOperation(c90885155.effop)
c:RegisterEffect(e8)
--tribute check
local e9=Effect.CreateEffect(c)
e9:SetType(EFFECT_TYPE_SINGLE)
e9:SetCode(EFFECT_MATERIAL_CHECK)
e9:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e9:SetValue(c90885155.valcheck)
e9:SetLabelObject(e8)
c:RegisterEffect(e9)
end
function c90885155.splimit(e,c)
return not c:IsSetCard(0xaa)
end
function c90885155.ntcon(e,c,minc)
if c==nil then return true end
return minc==0 and c:GetLevel()>4 and Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0
end
function c90885155.lvcon(e)
return e:GetHandler():GetMaterialCount()==0
end
function c90885155.lvop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c90885155.lvcon)
e1:SetValue(4)
e1:SetReset(RESET_EVENT+0xff0000)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_SET_BASE_ATTACK)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetCondition(c90885155.lvcon)
e2:SetValue(1800)
e2:SetReset(RESET_EVENT+0xff0000)
c:RegisterEffect(e2)
end
function c90885155.lvop2(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(4)
e1:SetReset(RESET_EVENT+0xff0000)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_SET_BASE_ATTACK)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetValue(1800)
e2:SetReset(RESET_EVENT+0xff0000)
c:RegisterEffect(e2)
end
function c90885155.immcon(e)
return bit.band(e:GetHandler():GetSummonType(),SUMMON_TYPE_NORMAL)==SUMMON_TYPE_NORMAL
end
function c90885155.effcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_ADVANCE and e:GetLabel()==1
end
function c90885155.effop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_EXTRA_ATTACK)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+0x1fc0000)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_PIERCE)
e2:SetReset(RESET_EVENT+0x1fc0000)
c:RegisterEffect(e2)
end
function c90885155.valcheck(e,c)
local g=c:GetMaterial()
if g:IsExists(Card.IsSetCard,1,nil,0xaa) then
e:GetLabelObject():SetLabel(1)
else
e:GetLabelObject():SetLabel(0)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/globals/items/steamed_catfish.lua | 11 | 1524 | -----------------------------------------
-- ID: 4557
-- Item: steamed_catfish
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Health 30
-- Magic % 1 (cap 110)
-- Dex 3
-- Intelligence 1
-- Mind -3
-- Earth Res 10
-- Ranged Accuracy +6% (cap 15)
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,10800,4557)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.HP, 30)
target:addMod(dsp.mod.FOOD_MPP, 1)
target:addMod(dsp.mod.FOOD_MP_CAP, 110)
target:addMod(dsp.mod.DEX, 3)
target:addMod(dsp.mod.INT, 1)
target:addMod(dsp.mod.MND, -3)
target:addMod(dsp.mod.EARTHRES, 10)
target:addMod(dsp.mod.FOOD_RACCP, 6)
target:addMod(dsp.mod.FOOD_RACC_CAP, 15)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.HP, 30)
target:delMod(dsp.mod.FOOD_MPP, 1)
target:delMod(dsp.mod.FOOD_MP_CAP, 110)
target:delMod(dsp.mod.DEX, 3)
target:delMod(dsp.mod.INT, 1)
target:delMod(dsp.mod.MND, -3)
target:delMod(dsp.mod.EARTHRES, 10)
target:delMod(dsp.mod.FOOD_RACCP, 6)
target:delMod(dsp.mod.FOOD_RACC_CAP, 15)
end
| gpl-3.0 |
MalRD/darkstar | scripts/globals/abilities/pets/heat_capacitor.lua | 12 | 1082 | ---------------------------------------------
-- Heat Capacitor
---------------------------------------------
require("scripts/globals/automatonweaponskills")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/msg")
---------------------------------------------
function onMobSkillCheck(target, automaton, skill)
return 0
end
function onPetAbility(target, automaton, skill, master, action)
automaton:addRecast(dsp.recast.ABILITY, skill:getID(), 90)
local maneuvers = master:countEffect(dsp.effect.FIRE_MANEUVER)
skill:setMsg(dsp.msg.basic.TP_INCREASE)
for i = 1, maneuvers do
master:delStatusEffectSilent(dsp.effect.FIRE_MANEUVER)
end
if automaton:getLocalVar("heat_capacitor") >= 3 then -- Heat Capacitor & Heat Capacitor II
target:addTP(1000 * maneuvers)
elseif automaton:getLocalVar("heat_capacitor") >= 2 then -- Heat Capacitor II
target:addTP(600 * maneuvers)
else -- Heat Capacitor
target:addTP(400 * maneuvers)
end
return target:getTP()
end
| gpl-3.0 |
ashkanpj/yagoopfire | plugins/channels.lua | 300 | 1680 | -- Checks if bot was disabled on specific chat
local function is_channel_disabled( receiver )
if not _config.disabled_channels then
return false
end
if _config.disabled_channels[receiver] == nil then
return false
end
return _config.disabled_channels[receiver]
end
local function enable_channel(receiver)
if not _config.disabled_channels then
_config.disabled_channels = {}
end
if _config.disabled_channels[receiver] == nil then
return 'Channel isn\'t disabled'
end
_config.disabled_channels[receiver] = false
save_config()
return "Channel re-enabled"
end
local function disable_channel( receiver )
if not _config.disabled_channels then
_config.disabled_channels = {}
end
_config.disabled_channels[receiver] = true
save_config()
return "Channel disabled"
end
local function pre_process(msg)
local receiver = get_receiver(msg)
-- If sender is sudo then re-enable the channel
if is_sudo(msg) then
if msg.text == "!channel enable" then
enable_channel(receiver)
end
end
if is_channel_disabled(receiver) then
msg.text = ""
end
return msg
end
local function run(msg, matches)
local receiver = get_receiver(msg)
-- Enable a channel
if matches[1] == 'enable' then
return enable_channel(receiver)
end
-- Disable a channel
if matches[1] == 'disable' then
return disable_channel(receiver)
end
end
return {
description = "Plugin to manage channels. Enable or disable channel.",
usage = {
"!channel enable: enable current channel",
"!channel disable: disable current channel" },
patterns = {
"^!channel? (enable)",
"^!channel? (disable)" },
run = run,
privileged = true,
pre_process = pre_process
} | gpl-2.0 |
MalRD/darkstar | scripts/globals/items/beef_stewpot.lua | 11 | 1475 | -----------------------------------------
-- ID: 5547
-- Item: Beef Stewpot
-- Food Effect: 3 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- HP +10% Cap 50
-- MP +10
-- HP Recoverd while healing 5
-- MP Recovered while healing 1
-- Attack +18% Cap 40
-- Evasion +5
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,10800,5547)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.FOOD_HPP, 10)
target:addMod(dsp.mod.FOOD_HP_CAP, 50)
target:addMod(dsp.mod.MP, 10)
target:addMod(dsp.mod.HPHEAL, 5)
target:addMod(dsp.mod.MPHEAL, 1)
target:addMod(dsp.mod.FOOD_ATTP, 18)
target:addMod(dsp.mod.FOOD_ATT_CAP, 40)
target:addMod(dsp.mod.EVA, 5)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.FOOD_HPP, 10)
target:delMod(dsp.mod.FOOD_HP_CAP, 50)
target:delMod(dsp.mod.MP, 10)
target:delMod(dsp.mod.HPHEAL, 5)
target:delMod(dsp.mod.MPHEAL, 1)
target:delMod(dsp.mod.FOOD_ATTP, 18)
target:delMod(dsp.mod.FOOD_ATT_CAP, 40)
target:delMod(dsp.mod.EVA, 5)
end
| gpl-3.0 |
LuaDist2/tethys | tethys2/plugins/user_manager/UnixAlias.lua | 2 | 1524 | module(..., package.seeall)
local oo = require "loop.simple"
local Plugin = require 'tethys2.plugins.user_manager.Plugin'
require'config'
require'io'
new = oo.class({}, Plugin.class)
UnixAlias = new
class = new
function UnixAlias:getUser(account, host)
local hosts = config.settings.user_manager.unixalias.hosts
if not hosts[host] then return nil end
local aliases = {}
for line in io.lines(config.settings.user_manager.unixalias.alias_file) do
if not line:find("^#") and line:len() > 0 then
local i, j, alias, dest = line:find("^([^:]+)%s*:%s*(.+)%s*$")
if i then
aliases[alias] = dest
end
end
end
while aliases[account] do
if not aliases[account] then break end
account = aliases[account]
end
for line in io.lines(config.settings.user_manager.unixalias.users_file) do
if not line:find("^#") and line:len() > 0 then
local i, j, user, uid, gid, home = line:find("^([^:]*):[^:]*:(%d*):(%d*):[^:]*:([^:]*):[^:]*$")
if i and user == account then
return {
account=user,
host=host,
type='account',
param={
path = ("%s/#PATHEXT#"):format(home),
uid = tonumber(uid),
gid = tonumber(gid),
}
}
end
end
end
return nil
end
function UnixAlias:getRelayHost(host)
-- Do we know this host?
return config.settings.user_manager.unixalias.hosts[host]
end
function UnixAlias:authUser(account, host, pass)
-- This module cant handle login
return false
end
function UnixAlias:init(server)
oo.superclass(UnixAlias).init(self, server)
end
| gpl-3.0 |
shahabsaf1/My-system | plugins/linkpv.lua | 46 | 31163 | do
local function check_member(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted.')
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
if success == -1 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' then
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'rem' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 then
return automodadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local receiver = 'user#id'..msg.action.user.id
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return false
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id)
send_large_msg(receiver, rules)
end
if matches[1] == 'chat_del_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and matches[2] then
if not is_owner(msg) then
return "Only owner can promote"
end
local member = string.gsub(matches[2], "@", "")
local mod_cmd = 'promote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'demote' and matches[2] then
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username then
return "You can't demote yourself"
end
local member = string.gsub(matches[2], "@", "")
local mod_cmd = 'demote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
if matches[1] == 'newlink' then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'linkpv' then
if not is_momod(msg) then
return "For moderators only!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
send_large_msg('user#id'..msg.from.id, "Group link:\n"..group_link)
end
if matches[1] == 'setowner' then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "Group owner is ["..group_owner..']'
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'help' then
if not is_momod(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
end
return {
patterns = {
"^[!/](linkpv)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
--Iwas Lazy So I Just Removed Patterns And Didn't Del Junk Items
--https://github.com/ThisIsArman
--Telegram.me/ThisIsArman
| gpl-2.0 |
Lsty/ygopro-scripts | c596051.lua | 3 | 1279 | --毒蛇の牙
function c596051.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DEFCHANGE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(TIMING_DAMAGE_STEP)
e1:SetCondition(c596051.condition)
e1:SetTarget(c596051.target)
e1:SetOperation(c596051.activate)
c:RegisterEffect(e1)
end
function c596051.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentPhase()~=PHASE_DAMAGE or not Duel.IsDamageCalculated()
end
function c596051.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsFaceup() end
if chk==0 then return Duel.IsExistingTarget(Card.IsFaceup,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,Card.IsFaceup,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
end
function c596051.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_DEFENCE)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END)
e1:SetValue(-500)
tc:RegisterEffect(e1)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c43661068.lua | 3 | 1560 | --星に願いを
function c43661068.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c43661068.target)
e1:SetOperation(c43661068.activate)
c:RegisterEffect(e1)
end
function c43661068.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c43661068.tfilter(chkc,tp) end
if chk==0 then return Duel.IsExistingTarget(c43661068.tfilter,tp,LOCATION_MZONE,0,1,nil,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c43661068.tfilter,tp,LOCATION_MZONE,0,1,1,nil,tp)
end
function c43661068.filter(c,atk,def)
return c:IsFaceup() and c:GetLevel()>0 and (c:GetAttack()==atk or c:GetDefence()==def)
end
function c43661068.tfilter(c,tp)
return c:IsFaceup() and c:GetLevel()>0
and Duel.IsExistingMatchingCard(c43661068.filter,tp,LOCATION_MZONE,0,1,c,c:GetAttack(),c:GetDefence())
end
function c43661068.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) then
local g=Duel.GetMatchingGroup(c43661068.filter,tp,LOCATION_MZONE,0,tc,tc:GetAttack(),tc:GetDefence())
local lv=tc:GetLevel()
local lc=g:GetFirst()
while lc do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL_FINAL)
e1:SetValue(lv)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
lc:RegisterEffect(e1)
lc=g:GetNext()
end
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/globals/icanheararainbow.lua | 9 | 8093 | -- Functions below used in quest: I Can Hear a Rainbow
require( "scripts/globals/status");
require( "scripts/globals/quests");
require( "scripts/globals/weather");
colorsAvailable = { 102, 103, 104, 105, 106, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 123, 124, 125}; -- Zone IDs
-- Data below from http://wiki.ffxiclopedia.org/wiki/I_Can_Hear_a_Rainbow - Feb. 02, 2013
colorsAvailable[100] = { false, true, false, false, false, false, false}; -- West Ronfaure
colorsAvailable[101] = { false, true, false, false, false, false, false}; -- East Ronfaure
colorsAvailable[102] = { false, false, false, true, true, false, false}; -- La Theine Plateau
colorsAvailable[103] = { true, false, true, false, false, false, false}; -- Valkurm Dunes
colorsAvailable[104] = { false, false, false, false, true, false, true }; -- Jugner Forest
colorsAvailable[105] = { false, false, true, false, false, true, false}; -- Batallia Downs
colorsAvailable[106] = { false, true, false, false, false, false, false}; -- North Gustaberg
colorsAvailable[107] = { false, true, false, false, false, false, false}; -- South Gustaberg
colorsAvailable[108] = { false, false, true, false, false, false, true }; -- Konschtat Highlands
colorsAvailable[109] = { false, false, false, false, true, false, true }; -- Pashhow Marshlands
colorsAvailable[110] = { true, false, false, false, true, false, false}; -- Rolanberry Fields
colorsAvailable[111] = { false, false, false, false, false, true, false}; -- Beaucedine Glacier
colorsAvailable[112] = { false, false, false, false, false, true, false}; -- Xarcabard
colorsAvailable[113] = { true, false, false, true, false, false, false}; -- Cape Teriggan
colorsAvailable[114] = { true, true, true, false, false, false, false}; -- Eastern Altepa Desert
colorsAvailable[115] = { false, true, false, false, false, false, false}; -- West Sarutabaruta
colorsAvailable[116] = { false, true, false, false, false, false, false}; -- East Sarutabaruta
colorsAvailable[117] = { false, false, true, true, false, false, false}; -- Tahrongi Canyon
colorsAvailable[118] = { false, true, false, true, true, false, false}; -- Buburimu Peninsula
colorsAvailable[119] = { true, false, true, false, false, false, false}; -- Meriphataud Mountains
colorsAvailable[120] = { false, false, true, false, false, false, true }; -- Sauromugue Champaign
colorsAvailable[121] = { false, false, false, false, true, false, true }; -- The Sanctuary of Zi'Tah
colorsAvailable[123] = { true, false, false, false, true, false, false}; -- Yuhtunga Jungle
colorsAvailable[124] = { true, true, false, false, true, false, false}; -- Yhoator Jungle
colorsAvailable[125] = { true, false, true, false, false, false, false}; -- Western Altepa Desert
-- The Event IDs to trigger the light cutscene for the following 3 zones is currently unknown.
-- They are included only because they are listed at http://wiki.ffxiclopedia.org/wiki/I_Can_Hear_a_Rainbow
-- colorsAvailable[128] = { false, false, false, true, false, false, false}; -- Valley of Sorrows
-- colorsAvailable[136] = { false, false, false, false, false, true, false}; -- Beaucedine Glacier (S)
-- colorsAvailable[205] = { true, false, false, false, false, false, false}; -- Ifrit's Cauldron
-----------------------------------
-- triggerLightCutscene
-----------------------------------
function triggerLightCutscene( player)
local cutsceneTriggered = false;
local RED = 1;
local ORANGE = 2;
local YELLOW = 3;
local GREEN = 4;
local BLUE = 5;
local INDIGO = 6;
local VIOLET = 7;
local zone = player:getZoneID();
local weather = player:getWeather();
if (player:hasItem( 1125, 0)) then -- Player has Carbuncle's Ruby?
if (player:getQuestStatus(WINDURST, dsp.quest.id.windurst.I_CAN_HEAR_A_RAINBOW) == QUEST_ACCEPTED) then
if (player:getMaskBit(player:getCharVar("I_CAN_HEAR_A_RAINBOW"),0) == false and (weather == dsp.weather.HOT_SPELL or weather == dsp.weather.HEAT_WAVE)) then
if (colorsAvailable[zone][RED]) then
cutsceneTriggered = true;
player:setMaskBit(player:getCharVar("I_CAN_HEAR_A_RAINBOW"),"I_CAN_HEAR_A_RAINBOW",0,true);
player:setCharVar( "I_CAN_HEAR_A_RAINBOW_Weather", weather);
end
elseif (player:getMaskBit(player:getCharVar("I_CAN_HEAR_A_RAINBOW"),1) == false and (weather == dsp.weather.NONE or weather == dsp.weather.SUNSHINE)) then
if (colorsAvailable[zone][ORANGE]) then
cutsceneTriggered = true;
player:setMaskBit(player:getCharVar("I_CAN_HEAR_A_RAINBOW"),"I_CAN_HEAR_A_RAINBOW",1,true);
player:setCharVar( "I_CAN_HEAR_A_RAINBOW_Weather", weather);
end
elseif (player:getMaskBit(player:getCharVar("I_CAN_HEAR_A_RAINBOW"),2) == false and (weather == dsp.weather.DUST_STORM or weather == dsp.weather.SAND_STORM)) then
if (colorsAvailable[zone][YELLOW]) then
cutsceneTriggered = true;
player:setMaskBit(player:getCharVar("I_CAN_HEAR_A_RAINBOW"),"I_CAN_HEAR_A_RAINBOW",2,true);
player:setCharVar( "I_CAN_HEAR_A_RAINBOW_Weather", weather);
end
elseif (player:getMaskBit(player:getCharVar("I_CAN_HEAR_A_RAINBOW"),3) == false and (weather == dsp.weather.WIND or weather == dsp.weather.GALES)) then
if (colorsAvailable[zone][GREEN]) then
cutsceneTriggered = true;
player:setMaskBit(player:getCharVar("I_CAN_HEAR_A_RAINBOW"),"I_CAN_HEAR_A_RAINBOW",3,true);
player:setCharVar( "I_CAN_HEAR_A_RAINBOW_Weather", weather);
end
elseif (player:getMaskBit(player:getCharVar("I_CAN_HEAR_A_RAINBOW"),4) == false and (weather == dsp.weather.RAIN or weather == dsp.weather.SQUALL)) then
if (colorsAvailable[zone][BLUE]) then
cutsceneTriggered = true;
player:setMaskBit(player:getCharVar("I_CAN_HEAR_A_RAINBOW"),"I_CAN_HEAR_A_RAINBOW",4,true);
player:setCharVar( "I_CAN_HEAR_A_RAINBOW_Weather", weather);
end
elseif (player:getMaskBit(player:getCharVar("I_CAN_HEAR_A_RAINBOW"),5) == false and (weather == dsp.weather.SNOW or weather == dsp.weather.BLIZZARDS)) then
if (colorsAvailable[zone][INDIGO]) then
cutsceneTriggered = true;
player:setMaskBit(player:getCharVar("I_CAN_HEAR_A_RAINBOW"),"I_CAN_HEAR_A_RAINBOW",5,true);
player:setCharVar( "I_CAN_HEAR_A_RAINBOW_Weather", weather);
end
elseif (player:getMaskBit(player:getCharVar("I_CAN_HEAR_A_RAINBOW"),6) == false and (weather == dsp.weather.THUNDER or weather == dsp.weather.THUNDERSTORMS)) then
if (colorsAvailable[zone][VIOLET]) then
cutsceneTriggered = true;
player:setMaskBit(player:getCharVar("I_CAN_HEAR_A_RAINBOW"),"I_CAN_HEAR_A_RAINBOW",6,true);
player:setCharVar( "I_CAN_HEAR_A_RAINBOW_Weather", weather);
end
end
end
end
return cutsceneTriggered;
end;
-----------------------------------
-- lightCutsceneUpdate
-----------------------------------
function lightCutsceneUpdate( player)
local weather = player:getCharVar( "I_CAN_HEAR_A_RAINBOW_Weather");
if (weather == dsp.weather.SUNSHINE) then -- In some zones the light cutscene does not handle dsp.weather.SUNSHINE properly
weather = dsp.weather.NONE;
end
if (player:getCharVar("I_CAN_HEAR_A_RAINBOW") < 127) then
player:updateEvent( 0, 0, weather);
else
player:updateEvent( 0, 0, weather, 6);
end
end;
-----------------------------------
-- lightCutsceneFinish
-----------------------------------
function lightCutsceneFinish( player)
player:setCharVar("I_CAN_HEAR_A_RAINBOW_Weather", 0);
end; | gpl-3.0 |
MalRD/darkstar | scripts/zones/Metalworks/npcs/Pius.lua | 9 | 1517 | -----------------------------------
-- Area: Metalworks
-- NPC: Pius
-- Involved In Mission: Journey Abroad
-- !pos 99 -21 -12 237
-----------------------------------
require("scripts/globals/missions");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
Mission = player:getCurrentMission(player:getNation());
MissionStatus = player:getCharVar("MissionStatus");
if (Mission == dsp.mission.id.sandoria.JOURNEY_TO_BASTOK and MissionStatus == 3 or
Mission == dsp.mission.id.sandoria.JOURNEY_TO_BASTOK2 and MissionStatus == 8) then
player:startEvent(355);
elseif (Mission == dsp.mission.id.windurst.THE_THREE_KINGDOMS_BASTOK and MissionStatus == 3 or
Mission == dsp.mission.id.windurst.THE_THREE_KINGDOMS_BASTOK2 and MissionStatus == 8) then
player:startEvent(355,1);
elseif (Mission == dsp.mission.id.sandoria.JOURNEY_TO_BASTOK or
Mission == dsp.mission.id.sandoria.JOURNEY_TO_BASTOK2 or
Mission == dsp.mission.id.windurst.THE_THREE_KINGDOMS_BASTOK2 and MissionStatus < 11) then
player:startEvent(356);
else
player:startEvent(350);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 355) then
if (player:getCharVar("MissionStatus") == 3) then
player:setCharVar("MissionStatus",4);
else
player:setCharVar("MissionStatus",9);
end
end
end; | gpl-3.0 |
Lsty/ygopro-scripts | c94119480.lua | 3 | 1387 | --終焉の守護者アドレウス
function c94119480.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,nil,5,2)
c:EnableReviveLimit()
--destroy
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY)
e1:SetDescription(aux.Stringid(94119480,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c94119480.cost)
e1:SetTarget(c94119480.target)
e1:SetOperation(c94119480.operation)
c:RegisterEffect(e1)
end
function c94119480.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c94119480.filter(c)
return c:IsFaceup() and c:IsDestructable()
end
function c94119480.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and chkc:IsControler(1-tp) and c94119480.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c94119480.filter,tp,0,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c94119480.filter,tp,0,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c94119480.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Southern_San_dOria/npcs/Leuveret.lua | 9 | 1046 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Leuveret
-- General Info NPC
-------------------------------------
local ID = require("scripts/zones/Southern_San_dOria/IDs");
require("scripts/globals/quests");
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getCharVar("tradeLeuveret") == 0) then
player:messageSpecial(ID.text.LEUVERET_DIALOG);
player:addCharVar("FFR", -1)
player:setCharVar("tradeLeuveret",1);
player:messageSpecial(ID.text.FLYER_ACCEPTED);
player:tradeComplete();
elseif (player:getCharVar("tradeLeuveret") == 1) then
player:messageSpecial(ID.text.FLYER_ALREADY);
end
end
end;
function onTrigger(player,npc)
player:startEvent(621);
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
Mijyuoon/starfall | lua/starfall/libs_sh/hook.lua | 1 | 8076 | -------------------------------------------------------------------------------
-- Hook library
-------------------------------------------------------------------------------
--- Deals with hooks
-- @shared
local hook_library, _ = SF.Libraries.Register("hook")
local registered_instances = {}
--- Sets a hook function
function hook_library.add(hookname, name, func)
SF.CheckType(hookname,"string")
SF.CheckType(name,"string")
if func then SF.CheckType(func,"function") else return end
local inst = SF.instance
local hooks = inst.hooks[hookname:lower()]
if not hooks then
hooks = {}
inst.hooks[hookname:lower()] = hooks
end
hooks[name] = func
registered_instances[inst] = true
end
--- Run a hook
-- @shared
-- @param hookname The hook name
-- @param ... arguments
function hook_library.run(hookname, ...)
SF.CheckType(hookname,"string")
local instance = SF.instance
local lower = hookname:lower()
SF.instance = nil -- Pretend we're not running an instance
local ret = {instance:runScriptHookForResult(lower, ... )}
SF.instance = instance -- Set it back
local ok = table.remove(ret, 1)
if not ok then
instance:Error("Hook '" .. lower .. "' errored with " .. ret[1], ret[2])
return
end
return unpack(ret)
end
--- Remove a hook
-- @shared
-- @param hookname The hook name
-- @param name The unique name for this hook
function hook_library.remove(hookname, name)
SF.CheckType(hookname,"string")
SF.CheckType(name,"string")
local instance = SF.instance
local lower = hookname:lower()
if instance.hooks[lower] then
instance.hooks[lower][name] = nil
if not next(instance.hooks[lower]) then
instance.hooks[lower] = nil
end
end
if not next(instance.hooks) then
registered_instances[instance] = nil
end
end
SF.Libraries.AddHook("deinitialize",function(instance)
registered_instances[instance] = nil
end)
SF.Libraries.AddHook("cleanup",function(instance,name,func,err)
if name == "_runFunction" and err == true then
registered_instances[instance] = nil
instance.hooks = {}
end
end)
local wrapArguments = SF.Sanitize
local function run(hookname, customfunc, ...)
for instance,_ in pairs(registered_instances) do
local ret = {instance:runScriptHookForResult(hookname, ...)}
local ok = table.remove(ret, 1)
if not ok then
instance:Error("Hook '" .. hookname .. "' errored with " .. ret[1], ret[2])
elseif customfunc then
local a,b,c,d,e,f,g,h = customfunc(instance, ret, ...)
if a ~= nil then return a,b,c,d,e,f,g,h end
end
end
end
local hooks = {}
--- Add a GMod hook so that SF gets access to it
-- @shared
-- @param hookname The hook name. In-SF hookname will be lowercased
-- @param customfunc Optional custom function
function SF.hookAdd(hookname, customfunc)
hooks[#hooks+1] = hookname
local lower = hookname:lower()
hook.Add(hookname, "SF_" .. hookname, function(...)
return run(lower, customfunc, wrapArguments(...))
end)
end
local add = SF.hookAdd
if SERVER then
-- Server hooks
local function filter_chat(inst, args, ply)
if inst.player ~= ply then return end
if args then return args[1] end
end
add("GravGunOnPickedUp")
add("GravGunOnDropped")
add("OnPhysgunFreeze")
add("OnPhysgunReload")
add("PlayerDeath")
add("PlayerDisconnected")
add("PlayerInitialSpawn")
add("PlayerSpawn")
add("PlayerLeaveVehicle")
add("PlayerSay", filter_chat)
add("PlayerSpray")
add("PlayerUse")
add("PlayerSwitchFlashlight")
else
-- Client hooks
-- todo
end
-- Shared hooks
-- Player hooks
add("PlayerHurt")
add("PlayerNoClip")
add("KeyPress")
add("KeyRelease")
add("GravGunPunt")
add("PhysgunPickup")
add("PhysgunDrop")
-- Entity hooks
add("OnEntityCreated")
add("EntityRemoved")
-- Other
add("EndEntityDriving")
add("StartEntityDriving")
--- Called when an entity is being picked up by a gravity gun
-- @name GravGunOnPickedUp
-- @class hook
-- @server
-- @param ply Player picking up an object
-- @param ent Entity being picked up
--- Called when an entity is being dropped by a gravity gun
-- @name GravGunOnDropped
-- @class hook
-- @server
-- @param ply Player dropping the object
-- @param ent Entity being dropped
--- Called when an entity is being frozen
-- @name OnPhysgunFreeze
-- @class hook
-- @server
-- @param physgun Entity of the physgun
-- @param physobj PhysObj of the entity
-- @param ent Entity being frozen
-- @param ply Player freezing the entity
--- Called when a player reloads his physgun
-- @name OnPhysgunReload
-- @class hook
-- @server
-- @param physgun Entity of the physgun
-- @param ply Player reloading the physgun
--- Called when a player dies
-- @name PlayerDeath
-- @class hook
-- @server
-- @param ply Player who died
-- @param inflictor Entity used to kill the player
-- @param attacker Entity that killed the player
--- Called when a player disconnects
-- @name PlayerDisconnected
-- @class hook
-- @server
-- @param ply Player that disconnected
--- Called when a player spawns for the first time
-- @name PlayerInitialSpawn
-- @param player Player who spawned
-- @server
--- Called when a player spawns
-- @name PlayerSpawn
-- @class hook
-- @server
-- @param player Player who spawned
--- Called when a players leaves a vehicle
-- @name PlayerLeaveVehicle
-- @class hook
-- @server
-- @param ply Player who left a vehicle
-- @param vehicle Vehicle that was left
--- Called when a player sends a chat message
-- @name PlayerSay
-- @class hook
-- @server
-- @param ply Player that sent the message
-- @param text Content of the message
-- @param teamChat True if team chat
-- @return New text. "" to stop from displaying. Nil to keep original.
--- Called when a players sprays his logo
-- @name PlayerSpray
-- @class hook
-- @server
-- @param ply Player that sprayed
--- Called when a player holds their use key and looks at an entity.
-- Will continuously run.
-- @name PlayerUse
-- @server
-- @class hook
-- @param ply Player using the entity
-- @param ent Entity being used
--- Called when a players turns their flashlight on or off
-- @name PlayerSwitchFlashlight
-- @class hook
-- @server
-- @param ply Player switching flashlight
-- @param state New flashlight state. True if on.
--- Called when a player gets hurt
-- @name PlayerHurt
-- @class hook
-- @shared
-- @param ply Player being hurt
-- @param attacker Entity causing damage to the player
-- @param newHealth New health of the player
-- @param damageTaken Amount of damage the player has taken
--- Called when a player toggles noclip
-- @name PlayerNoClip
-- @class hook
-- @shared
-- @param ply Player toggling noclip
-- @param newState New noclip state. True if on.
--- Called when a player presses a key
-- @name KeyPress
-- @class hook
-- @shared
-- @param ply Player pressing the key
-- @param key The key being pressed
--- Called when a player releases a key
-- @name KeyRelease
-- @class hook
-- @shared
-- @param ply Player releasing the key
-- @param key The key being released
--- Called when a player punts with the gravity gun
-- @name GravGunPunt
-- @class hook
-- @shared
-- @param ply Player punting the gravgun
-- @param ent Entity being punted
--- Called when an entity gets picked up by a physgun
-- @name PhysgunPickup
-- @class hook
-- @shared
-- @param ply Player picking up the entity
-- @param ent Entity being picked up
--- Called when an entity being held by a physgun gets dropped
-- @name PhysgunDrop
-- @class hook
-- @shared
-- @param ply Player droppig the entity
-- @param ent Entity being dropped
--- Called when an entity gets created
-- @name OnEntityCreated
-- @class hook
-- @shared
-- @param ent New entity
--- Called when an entity is removed
-- @name EntityRemoved
-- @class hook
-- @shared
-- @param ent Entity being removed
--- Called when a player stops driving an entity
-- @name EndEntityDriving
-- @class hook
-- @shared
-- @param ent Entity that had been driven
-- @param ply Player that drove the entity
--- Called when a player starts driving an entity
-- @name StartEntityDriving
-- @class hook
-- @shared
-- @param ent Entity being driven
-- @param Player that is driving the entity
| bsd-3-clause |
ThingMesh/openwrt-luci | modules/niu/luasrc/model/cbi/niu/system/general1.lua | 49 | 1145 | --[[
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$
]]--
local fs = require "nixio.fs"
local i18n = require "luci.i18n"
local util = require "luci.util"
local config = require "luci.config"
m = Map("luci", "Device Settings")
c = m:section(NamedSection, "main", "core", translate("Local Settings"))
hn = c:option(Value, "_uniquename", translate("Unique Devicename"))
function hn:cfgvalue(self)
return require "nixio.fs".readfile("/proc/sys/kernel/hostname")
end
l = c:option(ListValue, "lang", translate("System Language"))
l:value("auto")
local i18ndir = i18n.i18ndir .. "default."
for k, v in util.kspairs(config.languages) do
local file = i18ndir .. k:gsub("_", "-")
if k:sub(1, 1) ~= "." and fs.access(file .. ".lmo") then
l:value(k, v)
end
end
pw1 = c:option(Value, "_pw1", translate("Administrator Password"))
pw1.password = true
pw1.default = "**********"
return m
| apache-2.0 |
Lsty/ygopro-scripts | c18895832.lua | 9 | 1176 | --システム・ダウン
function c18895832.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_REMOVE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c18895832.cost)
e1:SetTarget(c18895832.target)
e1:SetOperation(c18895832.activate)
c:RegisterEffect(e1)
end
function c18895832.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,1000) end
Duel.PayLPCost(tp,1000)
end
function c18895832.filter(c)
return c:IsFaceup() and c:IsRace(RACE_MACHINE)
end
function c18895832.tfilter(c)
return not c:IsAbleToRemove()
end
function c18895832.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
local g=Duel.GetMatchingGroup(c18895832.filter,tp,0,LOCATION_MZONE+LOCATION_GRAVE,nil)
return g:GetCount()>0 and not g:IsExists(c18895832.tfilter,1,nil)
end
local g=Duel.GetMatchingGroup(c18895832.filter,tp,0,LOCATION_MZONE+LOCATION_GRAVE,nil)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,g:GetCount(),0,0)
end
function c18895832.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c18895832.filter,tp,0,LOCATION_MZONE+LOCATION_GRAVE,nil)
Duel.Remove(g,POS_FACEUP,REASON_EFFECT)
end
| gpl-2.0 |
Mijyuoon/starfall | lua/starfall/permissions/core.lua | 5 | 5523 | ---------------------------------------------------------------------
-- SF Permissions management
---------------------------------------------------------------------
-- TODO: Client version
--- Permission format
-- @name Permission
-- @class table
-- @field name The name of the permission
-- @field desc The description of the permission.
-- @field level The abusability of the permission. 0 = low (print to console),
-- 1 = normal (modify entities), 2 = high (run arbitrary lua)
-- @field value Boolean. True to allow, false to deny
SF.Permissions = {}
local P = SF.Permissions
P.__index = P
P.privileges = {}
if SERVER then
util.AddNetworkString( "starfall_permissions_privileges" )
else
P.serverPrivileges = {}
end
do
local lockmeta = {
__newindex = function ( table, key, value )
error( "attempting to assign to a read-only table", 2 )
end,
__metatable = "constant"
}
local result_vals = {
DENY = setmetatable( {}, lockmeta ),
ALLOW = setmetatable( {}, lockmeta ),
NEUTRAL = setmetatable( {}, lockmeta )
}
P.Result = setmetatable( {}, {
__index = result_vals,
__newindex = lockmeta.__newindex,
__metatable = "enum"
} )
end
local DENY = P.Result.DENY
local ALLOW = P.Result.ALLOW
local NEUTRAL = P.Result.NEUTRAL
local providers = {}
local have_owner = false
--- Adds a provider implementation to the set used by this library.
-- Providers must implement the {@link SF.Permissions.Provider} interface.
-- @param provider the provider to be registered
function P.registerProvider ( provider )
if type( provider ) ~= "table"
or type( provider.supportsOwner ) ~= "function"
or type( provider.isOwner ) ~= "function"
or type( provider.check ) ~= "function" then
error( "given object does not implement the provider interface", 2 )
end
providers[ provider ] = provider
if provider:supportsOwner() then
have_owner = true
end
end
--- Checks whether a player may perform an action.
-- @param principal the player performing the action to be authorized
-- @param target the object on which the action is being performed
-- @param key a string identifying the action being performed
-- @return boolean whether the action is permitted
function P.check ( principal, target, key )
if not P.privileges[ key ] then print( "WARNING: Starfall privilege " .. key .. " was not registered!" ) end
-- server owners can do whatever they want
if have_owner then
-- this can't be merged into the check loop below because that
for _, provider in pairs( providers ) do
if provider:isOwner( principal ) then return true end
end
elseif principal:IsSuperAdmin() then
return true
end
local allow = false
for _, provider in pairs( providers ) do
local result = provider:check( principal, target, key )
if DENY == result then
-- a single deny overrides any allows, just deny it now
return false
elseif ALLOW == result then
-- an allow can be overridden by a deny, so remember and keep going
allow = true
end
-- otherwise, this provider has no opinion, just go on to the next one
end
return allow
end
--- Registers a privilege
-- @param id unique identifier of the privilege being registered
-- @param name Human readable name of the privilege
-- @param description a short description of the privilege
function P.registerPrivilege ( id, name, description )
P.privileges[ id ] = { name = name, description = description }
-- The second check is not really necessary, but since it will resolve to false most of the time, we can save some time
if SERVER and #player.GetAll() > 0 then
net.Start( "starfall_permissions_privileges" )
net.WriteInt( #P.privileges, 16 )
for k, v in pairs( P.privileges ) do
net.WriteString( k )
net.WriteString( v.name )
net.WriteString( v.description )
end
net.Broadcast()
end
end
-- Find and include all provider files.
do
local function IncludeClientFile ( file )
if SERVER then
AddCSLuaFile( file )
else
include( file )
end
end
if SERVER then
include( "starfall/permissions/provider.lua" )
end
IncludeClientFile( "starfall/permissions/provider.lua" )
if SERVER then
local files = file.Find( "starfall/permissions/providers_sv/*.lua", "LUA" )
for _, file in pairs( files ) do
include( "starfall/permissions/providers_sv/" .. file )
end
end
local sh_files = file.Find( "starfall/permissions/providers_sh/*.lua", "LUA" )
for _, file in pairs( sh_files ) do
if SERVER then
AddCSLuaFile( "starfall/permissions/providers_sh/" .. file )
end
include( "starfall/permissions/providers_sh/" .. file )
end
local cl_files = file.Find( "starfall/permissions/providers_cl/*.lua", "LUA" )
for _, file in pairs( cl_files ) do
IncludeClientFile( "starfall/permissions/providers_cl/" .. file )
end
end
-- Send serverside privileges to client
if SERVER then
local function sendPrivileges ( ply )
net.Start( "starfall_permissions_privileges" )
net.WriteInt( #P.privileges, 16 )
for k, v in pairs( P.privileges ) do
net.WriteString( k )
net.WriteString( v.name )
net.WriteString( v.description )
end
if ply then
net.Send( ply )
else
net.Broadcast()
end
end
sendPrivileges()
hook.Add( "PlayerInitialSpawn", "starfall_permissions", sendPrivileges )
else
net.Receive( "starfall_permissions_privileges", function ()
local len = net.ReadInt( 16 )
for i = 1, len do
P.serverPrivileges[ net.ReadString() ] = { name = net.ReadString(), description = net.ReadString() }
end
end )
end
| bsd-3-clause |
MalRD/darkstar | scripts/zones/Port_Bastok/npcs/Alib-Mufalib.lua | 9 | 3948 | -----------------------------------
-- Area: Port Bastok
-- NPC: Alib-Mufalib
-- Type: Warp NPC
-- !pos 116.080 7.372 -31.820 236
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/globals/teleports");
require("scripts/globals/keyitems");
local ID = require("scripts/zones/Port_Bastok/IDs");
--[[
Bitmask Designations:
Port Bastok (East to West)
00001 (J-5) Kaede (northernmost house)
00002 (F-5) Patient Wheel (north of Warehouse 2)
00004 (F-6) Paujean (bottom floor of Warehouse 2)
00008 (E-6) Hilda (Steaming Sheep Restaurant, walks on the top floor and occasionally down. However, she can still be talked to when on second floor. Unable to get if you have Cid's Secret flagged.)
00010 (F-8) Tilian (end of a pier west of Air Travel Agency)
Metalworks (all found on top floor)
00020 (G-8) Raibaht (Cid's lab)
00040 (G-8) Invincible Shield (outside Cid's Lab)
00080 (G-7) Manilam (on top of Cermet Refinery)
00100 (I-8) Kaela (between Consulate of Windurst & Consulate of Bastok)
00200 (K-7) Ayame (Inside north Cannonry)
Bastok Markets (East to West)
00400 (K-10) Harmodios (Harmodios's Music Shop)
00800 (J-10) Arawn (west of music store)
01000 (I-9) Horatius (Inside Trader's Home)
02000 (E-10) Ken (outside Mjoll's General Goods)
04000 (E-11) Pavel (West Gate to South Gustaberg)
Bastok Mines (Clockwise, starting at Ore Street, upper floor to lower floor)
08000 (H-5) Griselda (upper floor, Bat's Lair Inn)
10000 (I-6) Goraow (upper floor, in stairwell of Ore Street)
20000 (I-7) Echo Hawk (lower floor, Ore Street)
40000 (H-6) Deidogg (lower floor, Ore Street)
80000 (H-9) Vaghron (southwest of South Auction House)
]]--
function onTrade(player,npc,trade)
if (trade:getGil() == 300 and trade:getItemCount() == 1 and player:getQuestStatus(BASTOK,dsp.quest.id.bastok.LURE_OF_THE_WILDCAT) == QUEST_COMPLETED and player:getCurrentMission(TOAU) > dsp.mission.id.toau.IMMORTAL_SENTRIES) then
-- Needs a check for at least traded an invitation card to Naja Salaheem
player:startEvent(379);
end
end;
function onTrigger(player,npc)
local LureBastok = player:getQuestStatus(BASTOK,dsp.quest.id.bastok.LURE_OF_THE_WILDCAT);
local WildcatBastok = player:getCharVar("WildcatBastok");
if (LureBastok ~= 2 and ENABLE_TOAU == 1) then
if (LureBastok == 0) then
player:startEvent(357);
else
if (WildcatBastok == 0) then
player:startEvent(358);
elseif (player:isMaskFull(WildcatBastok,20) == true) then
player:startEvent(360);
else
player:startEvent(359);
end
end
elseif (player:getCurrentMission(TOAU) >= dsp.mission.id.toau.PRESIDENT_SALAHEEM) then
player:startEvent(378);
else
player:startEvent(361);
end
end;
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if (csid == 357) then
player:addQuest(BASTOK,dsp.quest.id.bastok.LURE_OF_THE_WILDCAT);
player:setCharVar("WildcatBastok",0);
player:addKeyItem(dsp.ki.BLUE_SENTINEL_BADGE);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.BLUE_SENTINEL_BADGE);
elseif (csid == 360) then
player:completeQuest(BASTOK,dsp.quest.id.bastok.LURE_OF_THE_WILDCAT);
player:addFame(BASTOK,150);
player:setCharVar("WildcatBastok",0);
player:delKeyItem(dsp.ki.BLUE_SENTINEL_BADGE);
player:addKeyItem(dsp.ki.BLUE_INVITATION_CARD);
player:messageSpecial(ID.text.KEYITEM_LOST,dsp.ki.BLUE_SENTINEL_BADGE);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.BLUE_INVITATION_CARD);
elseif (csid == 379) then
player:tradeComplete();
dsp.teleport.to(player, dsp.teleport.id.WHITEGATE);
end
end;
| gpl-3.0 |
Lsty/ygopro-scripts | c22790789.lua | 3 | 3151 | --巨大戦艦 クリスタル・コア
function c22790789.initial_effect(c)
--summon success
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(22790789,0))
e1:SetCategory(CATEGORY_COUNTER)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetTarget(c22790789.addct)
e1:SetOperation(c22790789.addc)
c:RegisterEffect(e1)
--battle indestructable
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e2:SetValue(1)
c:RegisterEffect(e2)
--remove counter
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(22790789,1))
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e3:SetCode(EVENT_DAMAGE_STEP_END)
e3:SetCondition(c22790789.rctcon)
e3:SetOperation(c22790789.rctop)
c:RegisterEffect(e3)
--destroy
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(22790789,2))
e4:SetCategory(CATEGORY_DESTROY)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e4:SetCode(EVENT_DAMAGE_STEP_END)
e4:SetCondition(c22790789.descon)
e4:SetTarget(c22790789.destg)
e4:SetOperation(c22790789.desop)
c:RegisterEffect(e4)
--pos
local e5=Effect.CreateEffect(c)
e5:SetDescription(aux.Stringid(22790789,3))
e5:SetCategory(CATEGORY_POSITION)
e5:SetProperty(EFFECT_FLAG_CARD_TARGET)
e5:SetType(EFFECT_TYPE_IGNITION)
e5:SetRange(LOCATION_MZONE)
e5:SetCountLimit(1)
e5:SetTarget(c22790789.postg)
e5:SetOperation(c22790789.posop)
c:RegisterEffect(e5)
end
function c22790789.addct(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_COUNTER,nil,3,0,0x1f)
end
function c22790789.addc(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsRelateToEffect(e) then
e:GetHandler():AddCounter(0x1f,3)
end
end
function c22790789.rctcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetCounter(0x1f)~=0
end
function c22790789.rctop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsFaceup() and c:IsRelateToEffect(e) then
c:RemoveCounter(tp,0x1f,1,REASON_EFFECT)
end
end
function c22790789.descon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetCounter(0x1f)==0
end
function c22790789.destg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,e:GetHandler(),1,0,0)
end
function c22790789.desop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsFaceup() and c:IsRelateToEffect(e) then
Duel.Destroy(c,REASON_EFFECT)
end
end
function c22790789.postg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and chkc:IsPosition(POS_FACEUP_ATTACK) end
if chk==0 then return Duel.IsExistingTarget(Card.IsPosition,tp,0,LOCATION_MZONE,1,nil,POS_FACEUP_ATTACK) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_POSCHANGE)
local g=Duel.SelectTarget(tp,Card.IsPosition,tp,0,LOCATION_MZONE,1,1,nil,POS_FACEUP_ATTACK)
Duel.SetOperationInfo(0,CATEGORY_POSITION,g,1,0,0)
end
function c22790789.posop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsPosition(POS_FACEUP_ATTACK) and tc:IsRelateToEffect(e) then
Duel.ChangePosition(tc,POS_FACEUP_DEFENCE)
end
end
| gpl-2.0 |
ntop/nProbe | custom_fields/Sonicwall/sonicwall_app_id.lua | 1 | 145599 | --
-- (C) 2013-18 - ntop.org
--
local sonicwall = {}
-- ################################################################################
local type_map = {
["1"] = "TIME_STAMP",
["2"] = "FLOW_IDENTIFIER",
["3"] = "INITIATOR_GW_MAC",
["4"] = "RESPONDER_GW_MAC",
["5"] = "INITIATOR_IP_ADDR",
["6"] = "RESPONDER_IP_ADDR",
["7"] = "INITIATOR_GW_IP_ADDR",
["8"] = "RESPONDER_GW_IP_ADDR",
["9"] = "INITIATOR_IFACE",
["10"] = "RESPONDER_IFACE",
["11"] = "INITIATOR_PORT",
["12"] = "RESPONDER_PORT",
["13"] = "INIT_TO_RESP_PKTS",
["14"] = "INIT_TO_RESP_OCTETS",
["15"] = "RESP_TO_INIT_PKTS",
["16"] = "RESP_TO_INIT_OCTETS",
["17"] = "FLOW_START_TIME",
["18"] = "FLOW_END_TIME",
["19"] = "INTERNAL_FLAGS",
["20"] = "PROTOCOL_TYPE",
["22"] = "FLOW_TO_APPLICATION_ID",
["23"] = "FLOW_TO_USER_ID",
["25"] = "FLOW_TO_IPS_ID",
["26"] = "FLOW_TO_VIRUS_ID",
["27"] = "FLOW_TO_SPYWARE_ID",
["28"] = "TEMPLATE_IDENTIFIER",
["29"] = "TABLE_NAME",
["30"] = "COLUMN_IDENTIFIER",
["31"] = "COLUMN_NAME",
["32"] = "COLUMN_TYPE",
["33"] = "COLUMN_STANDARD_IPFIX_ID",
["34"] = "SONIC_USER_INDEX",
["35"] = "SONIC_USER_NAME",
["36"] = "SONIC_USER_ID",
["38"] = "USER_AUTH_TYPE",
["39"] = "APP_INDEX",
["40"] = "APP_ID",
["41"] = "APP_NAME",
["42"] = "APP_CAT_ID",
["43"] = "APP_CAT_NAME",
["44"] = "APP_SIG_ID",
["45"] = "GAV_INDEX",
["46"] = "GAV_NAME",
["47"] = "GAV_SIG_ID",
["48"] = "IPS_INDEX",
["49"] = "IPS_NAME",
["50"] = "IPS_CAT_ID",
["51"] = "IPS_CAT_NAME",
["52"] = "IPS_SIG_ID",
["53"] = "ASPY_INDEX",
["54"] = "ASPY_NAME",
["55"] = "ASPY_PROD_ID",
["56"] = "ASPY_PROD_NAME",
["57"] = "ASPY_SIG_ID",
["59"] = "URL_NAME",
["60"] = "URL_IP",
["62"] = "RATING_INDEX",
["63"] = "RATING_NAME",
["64"] = "REGION_ID",
["65"] = "COUNTRY_ID",
["66"] = "COUNTRY_NAME",
["67"] = "REGION_NAME",
["68"] = "LOCATION_IP",
["69"] = "LOCATION_REGION_ID",
["70"] = "LOCATION_DOMAIN_NAME",
["101"] = "IF_STAT_IFACE",
["102"] = "IF_STAT_IN_PKTS_RATE",
["103"] = "IF_STAT_OUT_PKTS_RATE",
["104"] = "IF_STAT_IN_OCTETS_RATE",
["105"] = "IF_STAT_OUT_OCTETS_RATE",
["106"] = "IF_STAT_IN_PKT_SIZE",
["107"] = "IF_STAT_OUT_PKT_SIZE",
["108"] = "IF_STAT_CONN_RATE",
["111"] = "FLOW_INIT_OCTETS_RATE",
["112"] = "FLOW_RESP_OCTETS_RATE",
["113"] = "FLOW_INIT_PKT_RATE",
["114"] = "FLOW_RESP_PKT_RATE",
["115"] = "FLOW_INIT_PKT_SIZE",
["116"] = "FLOW_RESP_PKT_SIZE",
["117"] = "IF_STAT_IF_NAME",
["118"] = "IF_STAT_IF_TYPE",
["119"] = "IF_STAT_IF_SPEED",
["120"] = "IF_STAT_IF_STATE",
["121"] = "IF_STAT_IF_MTU",
["122"] = "IF_STAT_IF_MODE",
["123"] = "URL_FLOW_ID",
["124"] = "URL_TIME_ID",
["126"] = "CORE_STAT_CORE_ID",
["127"] = "CORE_STAT_CORE_UTIL",
["128"] = "VOIP_FLOW_ID",
["130"] = "VOIP_INIT_CALL_ID",
["131"] = "VOIP_RESP_CALL_ID",
["132"] = "MEDIA_TYPE",
["133"] = "MEDIA_PROTOCOL",
["134"] = "SERVICE_NAME",
["135"] = "SERVICE_IP_TYPE",
["136"] = "SERVICE_PORT_BEGIN",
["137"] = "SERVICE_PORT_END",
["138"] = "SPAM_SESS_ID",
["139"] = "SPAM_FLOW_ID",
["140"] = "SPAM_TIME_ID",
["141"] = "SPAM_SPAMMER",
["142"] = "SPAM_TYPE",
["143"] = "SPAM_TO_E_MAIL",
["144"] = "SPAM_FROM_E_MAIL",
["145"] = "MEM_TOTAL_RAM",
["146"] = "MEM_AVAIL_RAM",
["147"] = "MEM_USED_RAM",
["148"] = "MEM_DB_RAM",
["149"] = "MEM_FLOW_COUNT",
["150"] = "MEM_PER_FLOW",
["151"] = "DEV_IFACE_ID",
["152"] = "DEV_IP_ADDR",
["153"] = "DEV_MAC_ADDR",
["154"] = "DEV_NAME",
["155"] = "VPN_IN_SPI_ID",
["156"] = "VPN_OUT_SPI_ID",
["157"] = "VPN_TUNNEL_NAME",
["158"] = "VPN_LOCAL_GW",
["159"] = "VPN_REMOTE_GW",
["160"] = "VPN_TUNNEL_IFACE_ID",
["161"] = "VPN_POLICY_TYPE",
["162"] = "VPN_PROTOCOL_TYPE",
["163"] = "VPN_ENCRYPTION_TYPE",
["164"] = "VPN_AUTHENTICATION_TYPE",
["165"] = "VPN_START_TIME",
["166"] = "VPN_END_TIME",
["167"] = "INIT_VPN_SPI_OUT",
["168"] = "RESP_VPN_SPI_OUT",
["169"] = "INIT_TO_RESP_DELTA_PKTS",
["170"] = "INIT_TO_RESP_DELTA_OCTETS",
["171"] = "RESP_TO_INIT_DELTA_PKTS",
["172"] = "RESP_TO_INIT_DELTA_OCTETS",
["173"] = "FLOW_BLOCK_REASON",
["174"] = "IF_STAT_MAC_ADDRESS",
["175"] = "IF_STAT_IP_ADDRESS",
["176"] = "IF_STAT_SECURITY_TYPE",
["177"] = "IF_STAT_ZONE_NAME",
["178"] = "USER_IP_ADDR",
["179"] = "URL_RATING_VAL1",
["180"] = "URL_RATING_VAL2",
["181"] = "URL_RATING_VAL3",
["182"] = "URL_RATING_VAL4",
["183"] = "APP_BWM_ATTR",
["184"] = "VOIP_INIT2RESP_LOST_PKTS",
["185"] = "VOIP_RESP2INIT_LOST_PKTS",
["186"] = "VOIP_INIT2RESP_AVG_LATENCY",
["187"] = "VOIP_INIT2RESP_MAX_LATENCY",
["188"] = "VOIP_RESP2INIT_AVG_LATENCY",
["189"] = "VOIP_RESP2INIT_MAX_LATENCY",
["190"] = "APP_CONTENT_TYPE",
["191"] = "SNWL_OPTION",
["192"] = "APP_RISK_ATTR",
["193"] = "APP_TECH_ATTR",
["194"] = "APP_ATTR_BIT_MASK",
["195"] = "TOP_APPS_SIGID",
["196"] = "TOP_APPS_APPNAME",
["197"] = "TOP_APPS_RATE",
}
local type_value_map = {
["22"] = { -- EField = 22, Field bytes = 4, EntId = 8741, type = unsigned int-32bits, name=flow to application id
["1"] = "Skype",
["3"] = "Winny",
["4"] = "eMule",
["5"] = "Encrypted Key Exchange",
["6"] = "Non-SSL traffic over SSL port",
["7"] = "Encrypted Key Exchange",
["58"] = "Flash Video (FLV)",
["59"] = "Flash Video (FLV)",
["63"] = "BitTorrent Protocol",
["66"] = "BitTorrent Protocol",
["69"] = "Tlen",
["70"] = "Tlen",
["74"] = "Microsoft MSN Messenger",
["76"] = "Microsoft MSN Messenger",
["77"] = "Hotspot Shield VPN",
["78"] = "Flash Video (FLV)",
["79"] = "Xunlei Thunder",
["84"] = "QQDownload",
["87"] = "ICQ",
["89"] = "QQDownload",
["94"] = "Microsoft MSN Messenger",
["95"] = "IRC",
["100"] = "IRC",
["101"] = "IRC",
["102"] = "AIM",
["103"] = "AIM",
["104"] = "AIM",
["107"] = "NomaDesk",
["108"] = "NomaDesk",
["110"] = "NomaDesk",
["112"] = "NewsStand",
["113"] = "Netlog",
["118"] = "QQDownload",
["119"] = "The Motley Fool",
["120"] = "Morningstar",
["121"] = "AIM/ICQ",
["123"] = "Microsoft Silverlight",
["127"] = "QQDownload",
["128"] = "PPStream",
["129"] = "PPStream",
["130"] = "PPStream",
["133"] = "Telnet",
["135"] = "GOGOBOX",
["136"] = "Morningstar",
["137"] = "Morningstar",
["138"] = "Oracle",
["139"] = "Kerberos v5",
["140"] = "TeamViewer",
["141"] = "AIM",
["143"] = "AIM",
["144"] = "Shutterfly",
["145"] = "Mop BBS",
["147"] = "Mixi",
["148"] = "Shockwave Flash (SWF)",
["150"] = "Freegate",
["152"] = "LogMeIn Hamachi",
["153"] = "LogMeIn Hamachi",
["154"] = "LogMeIn Hamachi",
["158"] = "TeamViewer",
["159"] = "TeamViewer",
["160"] = "Telnet",
["163"] = "Google Earth",
["164"] = "Windows Media",
["165"] = "JAP",
["166"] = "JAP",
["167"] = "Folding@Home",
["168"] = "Folding@Home",
["169"] = "HTTP-Tunnel",
["170"] = "MegaUpload",
["171"] = "MegaUpload",
["172"] = "Xunlei Thunder",
["173"] = "Microsoft MSN Messenger",
["175"] = "Windows Media",
["177"] = "Windows Media Player",
["178"] = "IDrive",
["179"] = "IDrive",
["181"] = "PPStream",
["182"] = "PPLive (PPTV)",
["183"] = "PPLive (PPTV)",
["184"] = "VNC (Remote Frame Buffer)",
["186"] = "Subversion",
["187"] = "Subversion",
["188"] = "Subversion",
["189"] = "MediaFire",
["191"] = "Xunlei Thunder",
["192"] = "Xunlei Thunder",
["193"] = "Xunlei Thunder",
["194"] = "Xunlei Thunder",
["195"] = "Xunlei Thunder",
["196"] = "Xunlei Thunder",
["197"] = "IBM DB2",
["198"] = "Oracle",
["201"] = "FileMaker Server",
["205"] = "Xunlei Thunder",
["206"] = "Microsoft SQL Server",
["207"] = "MediaFire",
["210"] = "GNUTella",
["211"] = "LimeWire",
["215"] = "Hulu",
["216"] = "Trend Micro",
["217"] = "Trend Micro",
["219"] = "Shockwave Flash (SWF)",
["220"] = "Microsoft Windows Updates",
["223"] = "Microsoft Windows Updates",
["224"] = "TeamViewer",
["233"] = "NinjaCloak",
["234"] = "NinjaCloak",
["240"] = "BeInSync",
["244"] = "SopCast",
["246"] = "TVU Networks",
["247"] = "Bing Maps",
["249"] = "CrossLoop",
["250"] = "CrossLoop",
["251"] = "CrossLoop",
["252"] = "FastViewer",
["254"] = "UUSee",
["255"] = "RAdmin",
["256"] = "Shutterfly",
["257"] = "SmugMug",
["258"] = "SIP",
["262"] = "Veetle",
["263"] = "Perforce",
["264"] = "SIP",
["265"] = "SIP",
["266"] = "SIP",
["267"] = "Perforce",
["268"] = "SmugMug",
["269"] = "MyHeritage",
["270"] = "MyHeritage",
["271"] = "NetMeeting",
["283"] = "IBM Informix",
["284"] = "Lulu",
["287"] = "TeamSpeak",
["288"] = "Lulu",
["289"] = "Sybase Anywhere",
["295"] = "Yoics",
["297"] = "Ventrilo",
["298"] = "Topix",
["299"] = "Apple Updates",
["300"] = "Apple Updates",
["305"] = "Bing Maps",
["306"] = "Bing Maps",
["311"] = "Kaixin001",
["313"] = "VSee",
["315"] = "WebSense",
["317"] = "Acresso",
["322"] = "SOAP",
["324"] = "Topix",
["326"] = "DistCC",
["327"] = "Oracle Java",
["328"] = "Jiayuan",
["329"] = "Jiayuan",
["330"] = "Jianghai Zhengquan",
["332"] = "Jira",
["336"] = "TeamSpeak",
["338"] = "Tokbox",
["339"] = "Tokbox",
["340"] = "Xunlei Thunder",
["341"] = "Xunlei Thunder",
["342"] = "RPC Portmapper",
["343"] = "RPC Portmapper",
["349"] = "Spotify",
["350"] = "Spotify",
["351"] = "Spotify",
["353"] = "AIM",
["355"] = "AIM",
["359"] = "AIM",
["360"] = "AIM",
["366"] = "Microsoft MSN Messenger",
["378"] = "Camfrog",
["383"] = "Camfrog",
["389"] = "Camfrog",
["390"] = "Camfrog",
["392"] = "Camfrog",
["393"] = "Imeem",
["395"] = "Camfrog",
["404"] = "Tonghuashun",
["405"] = "AIM",
["406"] = "Autobahn",
["410"] = "SIP",
["412"] = "SIP",
["413"] = "Ventrilo",
["414"] = "Vimeo",
["416"] = "Vimeo",
["417"] = "VSee",
["418"] = "PCAnywhere",
["419"] = "VSee",
["420"] = "SIP",
["421"] = "SIP",
["424"] = "Comcast",
["425"] = "Cox",
["426"] = "Microsoft",
["427"] = "Hushmail",
["431"] = "Trillian",
["435"] = "Microsoft Remote Desktop",
["436"] = "Microsoft Remote Desktop",
["439"] = "Yahoo!",
["440"] = "Yahoo! Messenger",
["441"] = "SOAP",
["442"] = "CBS Radio Player",
["446"] = "SSH Protocol",
["447"] = "Hi5",
["448"] = "Hi5",
["449"] = "Zimbra",
["450"] = "Blog Flux",
["451"] = "Zimbra",
["452"] = "Blog Flux",
["455"] = "Horde",
["456"] = "Quicktime",
["457"] = "Windows Media",
["458"] = "Windows Media",
["459"] = "SHOUTcast",
["460"] = "Icecast",
["461"] = "Upcoming",
["462"] = "IlohaMail",
["466"] = "Hexungudao",
["467"] = "Habbo",
["469"] = "Mail.com",
["470"] = "Mail.ru",
["471"] = "Gabbly",
["472"] = "Gabbly",
["473"] = "Gabbly",
["474"] = "Friendster",
["475"] = "SMB",
["476"] = "SMB",
["477"] = "Microsoft RPC End Point Mapper",
["481"] = "FriendFeed",
["484"] = "Twig",
["486"] = "SquirrelMail",
["491"] = "Mobilatory",
["494"] = "PPLive (PPTV)",
["496"] = "RoundCube",
["497"] = "PodOmatic",
["498"] = "QQ Mail",
["499"] = "Optimum Webmail",
["500"] = "OpenWebMail",
["501"] = "OpenWebMail",
["504"] = "Noteworthy Webmail",
["506"] = "MGCP",
["507"] = "PodOmatic",
["508"] = "X11",
["509"] = "X11",
["510"] = "Telnet",
["511"] = "Telnet",
["512"] = "X Font Server",
["513"] = "X Font Server",
["514"] = "Rlogin",
["515"] = "Rlogin",
["516"] = "Vedivi Wallcooler",
["517"] = "RSH",
["518"] = "RSH",
["520"] = "PCAnywhere",
["522"] = "Sensepost ReDuh",
["525"] = "GBridge",
["527"] = "GBridge",
["529"] = "Google Calendar",
["533"] = "CUPS",
["536"] = "IPSec PGPNet",
["537"] = "ShowMyPC",
["539"] = "ShowMyPC",
["541"] = "ShowMyPC",
["545"] = "Flixster",
["546"] = "Feedreader",
["547"] = "FeedBlitz",
["548"] = "FC2 Blog",
["549"] = "eSnips",
["550"] = "eBay",
["551"] = "EatLime",
["554"] = "FeedBlitz",
["555"] = "Meeting Maker",
["556"] = "Geni",
["564"] = "37signals Basecamp",
["565"] = "37signals Basecamp",
["566"] = "Zoho",
["567"] = "Carbonite Online Backup",
["568"] = "Apple iCloud",
["569"] = "IBackup",
["570"] = "IBackup",
["571"] = "Mozy Online Backup",
["572"] = "Internet Printing Protocol",
["573"] = "Internet Printing Protocol",
["574"] = "MP3",
["575"] = "Shockwave Flash (SWF)",
["578"] = "Microsoft Active Directory",
["581"] = "Microsoft Distributed Transaction Coord",
["582"] = "Microsoft File Replication",
["583"] = "Microsoft File Replication",
["584"] = "Microsoft File Replication",
["585"] = "Microsoft IIS",
["594"] = "MPEG",
["595"] = "Microsoft Messenger",
["596"] = "Microsoft Messenger",
["597"] = "Microsoft Message Queue",
["598"] = "Microsoft Message Queue",
["599"] = "Microsoft Message Queue",
["600"] = "Microsoft Message Queue",
["601"] = "Microsoft Message Queue",
["602"] = "Microsoft Netlogon",
["603"] = "Microsoft Task Scheduler",
["604"] = "Microsoft Task Scheduler",
["605"] = "Microsoft Task Scheduler",
["606"] = "Microsoft DNS",
["607"] = "Microsoft WINS",
["608"] = "Microsoft WINS",
["609"] = "Microsoft Exchange",
["610"] = "Microsoft Exchange",
["612"] = "Microsoft Exchange",
["613"] = "Microsoft Exchange",
["615"] = "Microsoft Exchange",
["616"] = "Microsoft Exchange",
["617"] = "Microsoft Exchange",
["618"] = "Microsoft Exchange",
["620"] = "Microsoft Exchange",
["621"] = "Microsoft Exchange",
["622"] = "Microsoft Exchange",
["625"] = "Microsoft Exchange",
["626"] = "Microsoft Exchange",
["627"] = "Microsoft Exchange",
["628"] = "QuakeLive",
["629"] = "Eachnet",
["630"] = "Eachnet",
["632"] = "CVSup",
["633"] = "163.com Webmail",
["634"] = "Trend Micro",
["635"] = "163.com Webmail",
["638"] = "Geni",
["639"] = "Gnolia",
["640"] = "NetFlow v9",
["641"] = "NetFlow v9",
["642"] = "Gaia Online",
["643"] = "Gaia Online",
["644"] = "Microsoft SQL Server",
["645"] = "Clarizen",
["654"] = "Nagios",
["655"] = "Nagios",
["656"] = "Nagios",
["657"] = "Nagios",
["658"] = "Kerberos v5",
["661"] = "Kerberos v5",
["663"] = "Kerberos v5",
["666"] = "LDAP v3",
["667"] = "LDAP v3",
["668"] = "LDAP v3",
["669"] = "LDAP v3",
["670"] = "Radius",
["671"] = "Radius",
["672"] = "TACACS Plus",
["673"] = "TACACS Plus",
["674"] = "TACACS Plus",
["675"] = "TACACS Plus",
["676"] = "Spotify",
["677"] = "Spotify",
["678"] = "Spotify",
["680"] = "Blackboard",
["682"] = "Blackboard",
["685"] = "RSS",
["686"] = "RSS",
["688"] = "Atom Syndication",
["690"] = "BitTorrent Protocol",
["691"] = "Kuwo",
["698"] = "Dealio Toolbar",
["699"] = "eBay API",
["700"] = "Finger",
["701"] = "Finger",
["704"] = "Google Analytics",
["705"] = "Google Toolbar",
["706"] = "Google Toolbar",
["707"] = "Google Safe Browsing",
["708"] = "Google Safe Browsing",
["711"] = "MSN Toolbar",
["712"] = "MSN Toolbar",
["713"] = "NNTP",
["715"] = "NNTP",
["718"] = "UPnP",
["723"] = "Microsoft Silverlight",
["724"] = "Microsoft Silverlight",
["726"] = "Whois",
["731"] = "CDDB",
["734"] = "Nico Nico Douga",
["735"] = "Ooyala",
["736"] = "Salesforce",
["738"] = "SugarCRM",
["739"] = "SugarCRM",
["740"] = "Bebo Mail",
["742"] = "Bebo Mail",
["743"] = "Yandex.ru Webmail",
["744"] = "Yandex.ru Webmail",
["745"] = "37signals Campfire",
["746"] = "37signals",
["747"] = "Adobe Acrobat",
["748"] = "SNMP",
["749"] = "SNMP",
["750"] = "SNMP",
["751"] = "Elluminate",
["752"] = "Elluminate",
["753"] = "eRoom.net",
["754"] = "GoToMeeting",
["755"] = "Premiere Global Services",
["757"] = "Vyew",
["759"] = "Vyew",
["760"] = "Yugma",
["761"] = "WebEx WebOffice",
["762"] = "Metacafe",
["763"] = "Metacafe",
["765"] = "BitComet",
["766"] = "BitComet",
["772"] = "WebCrawler",
["773"] = "Modbus",
["774"] = "Modbus",
["782"] = "Ubuntu APT",
["783"] = "Xdebug",
["784"] = "Xdebug",
["785"] = "BitDefender",
["788"] = "BitDefender",
["789"] = "AVG",
["790"] = "Rising Antivirus",
["791"] = "Rising Antivirus",
["792"] = "Avira",
["793"] = "Firefox",
["794"] = "Firefox",
["795"] = "Tortoise SVN",
["796"] = "RealNetworks",
["800"] = "VMware",
["801"] = "Opera",
["802"] = "Google Software",
["803"] = "JPDA",
["804"] = "JPDA",
["805"] = "Microsoft Visual Studio",
["806"] = "Microsoft Visual Studio",
["807"] = "Debian APT",
["808"] = "Yum",
["814"] = "ZYpp",
["815"] = "VirusTotal",
["816"] = "VirusTotal",
["817"] = "RSYNC",
["819"] = "RSYNC",
["820"] = "SOS Online Backup",
["821"] = "BOINC",
["822"] = "TD Ameritrade",
["823"] = "Thinkorswim",
["826"] = "Sina",
["829"] = "ALTools",
["830"] = "ALTools",
["831"] = "ESET",
["832"] = "Sophos",
["835"] = "Sina",
["836"] = "Sina",
["839"] = "Microsoft SQL Server",
["844"] = "Charles Schwab",
["845"] = "Scottrade",
["852"] = "RapidShare",
["857"] = "Blizzard Entertainment",
["858"] = "Blizzard Entertainment",
["861"] = "eBuddy",
["862"] = "Baidu Hi",
["869"] = "Serv-U FTP Server",
["870"] = "Serv-U FTP Server",
["872"] = "Pure-FTPd FTP Server",
["873"] = "Pure-FTPd FTP Server",
["874"] = "QQGame",
["875"] = "STUN",
["876"] = "QQMusic",
["878"] = "QQMusic",
["879"] = "QQMusic",
["880"] = "PCast",
["883"] = "WS_FTP Server",
["884"] = "WS_FTP Server",
["885"] = "QQLive",
["893"] = "PokerStars",
["894"] = "PokerStars",
["895"] = "Bwin Interactive",
["899"] = "EuroPoker",
["900"] = "PartyGaming",
["901"] = "PartyGaming",
["902"] = "Zynga Texas Holdem",
["904"] = "Baidu",
["906"] = "QQGame",
["908"] = "Chikka Messenger",
["909"] = "Chikka Messenger",
["912"] = "Daum",
["916"] = "AOL",
["917"] = "ILoveIM",
["919"] = "IMVU",
["920"] = "Instan-t",
["922"] = "Instan-t",
["926"] = "Google Talk",
["928"] = "Google Chat",
["930"] = "Lava Lava",
["931"] = "Lava Lava",
["932"] = "Lava Lava",
["933"] = "Dianji DNA",
["940"] = "NateOn",
["941"] = "NateOn",
["945"] = "NetEase PoPo",
["947"] = "PalTalk",
["948"] = "PalTalk",
["949"] = "PalTalk Express",
["955"] = "Spotify",
["956"] = "Spotify",
["957"] = "Namipan",
["961"] = "BitSpirit",
["963"] = "Xfire",
["965"] = "Xfire",
["966"] = "Twitter",
["967"] = "Twitter",
["969"] = "Newegg",
["970"] = "Newegg",
["971"] = "LiveJournal",
["972"] = "LiveJournal",
["973"] = "Awareness Technologies",
["974"] = "Sonar Central",
["975"] = "WebWatcher",
["976"] = "LinkedIn",
["977"] = "LinkedIn",
["980"] = "ZhanZuo",
["982"] = "Yahoo!",
["983"] = "Yahoo!",
["984"] = "YaCy",
["985"] = "Xobni",
["989"] = "Yahoo! Groups",
["990"] = "Yahoo! Games",
["992"] = "Yahoo! Finance",
["993"] = "Yahoo! Finance",
["994"] = "Xinhuanet Forum",
["995"] = "XING",
["996"] = "Xilu Forums",
["997"] = "Xici",
["1016"] = "VoipBuster",
["1018"] = "Kontiki",
["1019"] = "Kontiki",
["1020"] = "QQDownload",
["1021"] = "Google Crawler",
["1026"] = "Doodle",
["1028"] = "Doodle",
["1031"] = "Docstoc",
["1034"] = "BitTorrent Protocol",
["1035"] = "Dict.cn",
["1036"] = "eMule",
["1037"] = "Dict.cn",
["1039"] = "eMule",
["1042"] = "DepositFiles",
["1047"] = "RTSP",
["1050"] = "RTSP",
["1052"] = "VoipBuster",
["1055"] = "DepositFiles",
["1058"] = "163.com FlashMail",
["1063"] = "Coremail",
["1066"] = "TOM Online",
["1070"] = "Sohu",
["1076"] = "Eastday",
["1077"] = "Sina",
["1078"] = "Sina",
["1086"] = "163.com Alumni",
["1087"] = "163.com BBS",
["1089"] = "18900.com",
["1090"] = "18900.com",
["1093"] = "JD.com",
["1094"] = "JD.com",
["1097"] = "4Shared",
["1098"] = "51.com Games",
["1101"] = "51.com BBS",
["1102"] = "51.com",
["1107"] = "5460.net",
["1108"] = "55BBS",
["1110"] = "55BBS",
["1115"] = "800Buy",
["1118"] = "Alibaba.com",
["1119"] = "Alibaba.cn",
["1120"] = "Amazon.cn",
["1122"] = "Apple Store",
["1124"] = "Baidu Tieba",
["1127"] = "Cat898 Club",
["1128"] = "ChinaRen Club",
["1129"] = "ChinaRen Class",
["1131"] = "ChinaRen Class",
["1133"] = "Gracenote",
["1136"] = "Freedb",
["1137"] = "Classmates",
["1138"] = "Jive Software",
["1139"] = "Citrix",
["1141"] = "Citrix",
["1151"] = "Cyworld",
["1155"] = "D1",
["1156"] = "D1",
["1157"] = "DangDang",
["1159"] = "DangDang",
["1162"] = "BitTorrent Protocol",
["1166"] = "Second Life",
["1171"] = "Dazhihui",
["1173"] = "Dazhihui",
["1176"] = "RemotelyAnywhere",
["1177"] = "RemotelyAnywhere",
["1180"] = "RemotelyAnywhere",
["1182"] = "RemotelyAnywhere",
["1183"] = "RemotelyAnywhere",
["1191"] = "Microsoft Media Server (MMS)",
["1193"] = "MagicJack",
["1197"] = "360Safe",
["1198"] = "CVS",
["1199"] = "360Safe",
["1200"] = "360Safe",
["1201"] = "360Safe",
["1202"] = "360Safe",
["1203"] = "360Safe",
["1204"] = "360Safe",
["1205"] = "Kingsoft DuBa",
["1206"] = "MySQL Server",
["1207"] = "Kingsoft DuBa",
["1208"] = "MySQL Server",
["1211"] = "Adobe",
["1212"] = "Google Picasa",
["1214"] = "Google Picasa",
["1215"] = "PostgreSQL Server",
["1217"] = "Google Picasa",
["1219"] = "Google Picasa",
["1220"] = "ALYac",
["1221"] = "PostgreSQL Server",
["1222"] = "ALTools",
["1224"] = "Symantec Live Update",
["1225"] = "Symantec Live Update",
["1234"] = "Symantec Live Update",
["1235"] = "Totorosa JJAM",
["1236"] = "ToTo Browser",
["1238"] = "TVU Networks",
["1241"] = "Soulseek",
["1242"] = "Odeo",
["1243"] = "SinaTV",
["1244"] = "SinaTV",
["1246"] = "iDisk",
["1257"] = "Odeo",
["1264"] = "LimeWire",
["1277"] = "Dealio Toolbar",
["1279"] = "WidgiToolbar",
["1281"] = "SearchSettings Toolbar",
["1282"] = "eMule",
["1302"] = "RaySource",
["1304"] = "RaySource",
["1306"] = "RaySource",
["1311"] = "Cisco WebEx",
["1312"] = "QQLive",
["1314"] = "QQLive",
["1315"] = "QQLive",
["1321"] = "QQDownload",
["1324"] = "QQDownload",
["1329"] = "Poco",
["1330"] = "Poco",
["1339"] = "Nullsoft Winamp",
["1342"] = "Experience Project",
["1372"] = "Slingbox",
["1373"] = "Experience Project",
["1378"] = "KKBox",
["1384"] = "KKBox",
["1387"] = "MeteorNetTV",
["1396"] = "DontStayIn",
["1400"] = "GNUTella",
["1402"] = "GNUTella",
["1404"] = "GNUTella",
["1409"] = "Veetle",
["1412"] = "VeohTV",
["1413"] = "VeohTV",
["1414"] = "GNUnet",
["1416"] = "YouTube",
["1431"] = "FastTV",
["1434"] = "UUSee",
["1437"] = "Blinkx",
["1447"] = "Blinkx",
["1449"] = "DontStayIn",
["1453"] = "Anon.me",
["1454"] = "Anon.me",
["1479"] = "LogMeIn",
["1480"] = "HideMyAss",
["1482"] = "HideMyAss",
["1484"] = "WPAD",
["1486"] = "Club Xcar",
["1487"] = "UUSee",
["1488"] = "UUSee",
["1491"] = "UUSee",
["1492"] = "Wikipedia",
["1493"] = "Wikispaces",
["1494"] = "Wikidot",
["1501"] = "UUSee",
["1502"] = "UUSee",
["1503"] = "UUSee",
["1504"] = "UUSee",
["1506"] = "UUSee",
["1507"] = "UUSee",
["1508"] = "VOC BBS",
["1509"] = "Viadeo",
["1511"] = "Tongdaxin",
["1518"] = "TikiWiki",
["1519"] = "Tiexue BBS",
["1520"] = "Tianya BBS",
["1522"] = "Tianya BBS",
["1523"] = "Aliwangwang",
["1526"] = "Aliwangwang",
["1531"] = "Aliwangwang",
["1534"] = "Aliwangwang",
["1536"] = "Microsoft",
["1537"] = "Supei",
["1539"] = "Compass.cn",
["1544"] = "Soribada",
["1548"] = "Club Sohu",
["1551"] = "MediaZone",
["1558"] = "Download Master",
["1559"] = "Speedbit",
["1561"] = "Help.com",
["1562"] = "Unblocked.org",
["1563"] = "Unblocked.org",
["1565"] = "Speedbit",
["1568"] = "Help.com",
["1570"] = "Speedbit",
["1571"] = "Speedbit",
["1572"] = "DownloadStudio",
["1574"] = "FlashGet",
["1576"] = "Free Download Manager",
["1577"] = "GetRight",
["1578"] = "Xunlei Thunder",
["1579"] = "Avoidr",
["1580"] = "InetURL",
["1581"] = "Internet Download Accelerator",
["1584"] = "Go!Zilla",
["1585"] = "Avoidr",
["1587"] = "KProxy",
["1588"] = "KProxy",
["1589"] = "vsFTPd FTP Server",
["1590"] = "vsFTPd FTP Server",
["1591"] = "KProxy",
["1592"] = "Gaia Community",
["1594"] = "JDownloader",
["1597"] = "Megaproxy",
["1602"] = "MLDonkey",
["1603"] = "Shareaza",
["1604"] = "Shareaza",
["1605"] = "Shareaza",
["1606"] = "Gaia Community",
["1608"] = "LibraryThing",
["1609"] = "LibraryThing",
["1611"] = "Shareaza",
["1612"] = "wxDownload Fast",
["1613"] = "Wget",
["1617"] = "SiteScope",
["1618"] = "cURL",
["1619"] = "Lftp",
["1620"] = "Gadu-Gadu",
["1621"] = "Surrogafier",
["1622"] = "Gadu-Gadu",
["1626"] = "Axel",
["1628"] = "ConnectFusion",
["1630"] = "Skyrock",
["1631"] = "Skyrock",
["1632"] = "Sina BBS",
["1634"] = "SendSpace",
["1635"] = "Vtunnel",
["1636"] = "Vtunnel",
["1637"] = "YouPorn",
["1639"] = "SendSpace",
["1640"] = "YouPorn",
["1641"] = "Youku",
["1642"] = "Youku",
["1643"] = "Yahoo! Video",
["1645"] = "SendSpace",
["1646"] = "SendSpace",
["1647"] = "Scour",
["1648"] = "Scour",
["1649"] = "MyLife",
["1650"] = "Windows Media Guide",
["1651"] = "Rednet BBS",
["1652"] = "CarDomain",
["1653"] = "Windows Media Guide",
["1654"] = "Ragnarok Online",
["1655"] = "Ragnarok Online",
["1656"] = "Webshots",
["1657"] = "Raging Bull",
["1658"] = "Webshots",
["1659"] = "Veoh",
["1660"] = "Veoh",
["1666"] = "CarDomain",
["1671"] = "Sirius XM",
["1672"] = "Sirius XM",
["1673"] = "UStream",
["1674"] = "Qianlong BBS",
["1677"] = "Pioneer StarTech",
["1678"] = "Tudou",
["1679"] = "Netflix",
["1680"] = "QQ Jiaoyou",
["1684"] = "Sohu TV",
["1688"] = "SinaTV",
["1689"] = "RuTube",
["1690"] = "Revver",
["1693"] = "Revver",
["1694"] = "9rules",
["1695"] = "9rules",
["1696"] = "Pcpop BBS",
["1697"] = "Ze Frank",
["1699"] = "PBworks",
["1700"] = "Qvod",
["1701"] = "Paipai",
["1702"] = "Qvod",
["1708"] = "GNUTella",
["1710"] = "Qvod",
["1713"] = "Qvod",
["1716"] = "Fastrack",
["1717"] = "BitTorrent Protocol",
["1718"] = "BitTorrent Protocol",
["1719"] = "People BBS",
["1720"] = "Yahoo! Messenger",
["1723"] = "People BBS",
["1729"] = "AIM",
["1732"] = "Photobucket",
["1734"] = "Orkut",
["1735"] = "Box",
["1736"] = "Dropbox",
["1749"] = "Pandora Radio",
["1751"] = "Pandora Radio",
["1756"] = "eMule",
["1758"] = "Filetopia",
["1759"] = "WinMX",
["1760"] = "MP2P",
["1761"] = "MP2P",
["1762"] = "Ze Frank",
["1763"] = "Ares",
["1765"] = "Shockwave Flash (SWF)",
["1766"] = "National Public Radio (NPR)",
["1767"] = "Livestream",
["1768"] = "Shockwave Flash (SWF)",
["1771"] = "Kademlia",
["1775"] = "SOCKS 5",
["1776"] = "SOCKS 4",
["1777"] = "eMule",
["1780"] = "QQ",
["1781"] = "QQ",
["1782"] = "QQ Mail",
["1786"] = "GoToMyPC",
["1787"] = "GoToMyPC",
["1788"] = "GoToMyPC",
["1789"] = "Bolt.com",
["1790"] = "Live365",
["1791"] = "6cn",
["1794"] = "ABC Streaming Media",
["1796"] = "Adobe Media Player",
["1799"] = "Blinkx",
["1800"] = "Audiogalaxy Rhapsody",
["1804"] = "CCTV Box",
["1806"] = "Bolt.com",
["1808"] = "aNobii",
["1809"] = "aNobii",
["1811"] = "Dailymotion",
["1812"] = "Deezer",
["1814"] = "EveryZing",
["1815"] = "Flickr",
["1816"] = "Gizmoz",
["1817"] = "Gougou",
["1818"] = "Gougou",
["1819"] = "Funshion",
["1838"] = "Funshion",
["1839"] = "Funshion",
["1840"] = "GOM Player",
["1841"] = "GOM Player",
["1842"] = "aSmallWorld",
["1850"] = "GMX",
["1851"] = "GMX",
["1852"] = "Apple iTunes",
["1854"] = "Musicmatch",
["1857"] = "aSmallWorld",
["1859"] = "Bing",
["1860"] = "Bing",
["1861"] = "Bing",
["1862"] = "Bing",
["1864"] = "Google Desktop",
["1865"] = "Google Docs",
["1866"] = "Google Finance",
["1869"] = "Google Groups",
["1871"] = "Google Sites",
["1872"] = "Google Search",
["1874"] = "Blogger.com",
["1876"] = "Ask.com Search",
["1879"] = "VoipStunt",
["1881"] = "VoipStunt",
["1883"] = "VoipStunt",
["1884"] = "VoipStunt",
["1885"] = "TelTel",
["1886"] = "Stickam",
["1887"] = "Stickam",
["1893"] = "IAX2",
["1895"] = "H.245 Call Control",
["1896"] = "Yahoo! Toolbar",
["1898"] = "StumbleUpon",
["1899"] = "StumbleUpon",
["1900"] = "Icecast",
["1901"] = "Windows Media",
["1902"] = "StumbleUpon",
["1903"] = "Nullsoft Winamp",
["1904"] = "RealMedia",
["1905"] = "XMMS",
["1906"] = "McAfee SiteAdvisor",
["1907"] = "eBay API",
["1908"] = "Alexa",
["1909"] = "Alexa",
["1910"] = "AOL Toolbar",
["1911"] = "AOL Toolbar",
["1912"] = "Microsoft Media Server (MMS)",
["1913"] = "AOL Toolbar",
["1915"] = "Windows Media",
["1917"] = "AOL Toolbar",
["1921"] = "eMule",
["1922"] = "eMule",
["1925"] = "TakingITGlobal",
["1926"] = "Syslog",
["1927"] = "Yourfilehost",
["1929"] = "Yourfilehost",
["1930"] = "YouSendIt",
["1932"] = "YouSendIt",
["1933"] = "Barafranca (Omerta)",
["1934"] = "Barafranca (Omerta)",
["1949"] = "Chosenspace",
["1950"] = "Microsoft MSN Messenger",
["1951"] = "Windows Live Messenger File Transfer",
["1952"] = "Windows Live Messenger File Transfer",
["1953"] = "Microsoft MSN Messenger",
["1955"] = "Chosenspace",
["1958"] = "Criminal Nations",
["1960"] = "AIM",
["1963"] = "AIM",
["1967"] = "Bigpoint Games",
["1968"] = "Bigpoint Games",
["1970"] = "DarkOrbit",
["1972"] = "TakingITGlobal",
["1975"] = "BearShare",
["1976"] = "Rappelz",
["1977"] = "GPotato",
["1985"] = "Blokus Online",
["1986"] = "GameABC",
["1988"] = "BNB",
["1990"] = "Mac OS X",
["1994"] = "BitTorrent Protocol",
["1996"] = "Evony",
["1997"] = "Kazaa",
["1998"] = "Evony",
["2000"] = "Hotspot Shield VPN",
["2001"] = "Hotspot Shield VPN",
["2008"] = "Xunlei Thunder",
["2012"] = "Hopster",
["2026"] = "OpenVPN",
["2033"] = "OpenVPN",
["2038"] = "ChinaGames",
["2041"] = "Dark Age Of Camelot",
["2043"] = "Dark Age Of Camelot",
["2044"] = "Doof",
["2047"] = "Haofang",
["2049"] = "Skype",
["2052"] = "Skype",
["2054"] = "Skype",
["2055"] = "Hobowars",
["2056"] = "Hobowars",
["2058"] = "Blogs.com",
["2066"] = "Big Brother",
["2068"] = "Executable",
["2070"] = "Kaillera",
["2071"] = "Kaillera",
["2072"] = "Kaillera",
["2073"] = "Kaillera",
["2082"] = "Blogs.com",
["2085"] = "QQMusic",
["2090"] = "Ourgame GLWorld",
["2091"] = "JinWuTuan",
["2093"] = "MoYu",
["2094"] = "MoYu",
["2097"] = "MoYu",
["2101"] = "eMule",
["2106"] = "Bebo",
["2107"] = "Frappr!",
["2110"] = "Faceparty",
["2111"] = "Frappr!",
["2112"] = "QQMusic",
["2114"] = "MiGente",
["2115"] = "Oodle",
["2117"] = "Oodle",
["2126"] = "Hyves",
["2128"] = "Hyves",
["2129"] = "Direct Connect",
["2130"] = "Direct Connect",
["2132"] = "MSN Games",
["2133"] = "Tiancity Popkart",
["2134"] = "163.com Popogame",
["2135"] = "QQGame",
["2136"] = "QQGame",
["2137"] = "RuneScape",
["2138"] = "RuneScape",
["2139"] = "Samurai Of Legend",
["2140"] = "Samurai Of Legend",
["2141"] = "iWiW",
["2146"] = "CDC Games",
["2148"] = "Second Life",
["2149"] = "Second Life",
["2150"] = "Second Life (Teen)",
["2152"] = "Sina Game",
["2154"] = "Changyou",
["2155"] = "CDC Games",
["2158"] = "Changyou Tian Long Ba Bu",
["2159"] = "iWiW",
["2161"] = "QQMusic",
["2165"] = "Changyou Tian Long Ba Bu",
["2166"] = "Tibia Game",
["2170"] = "Tibia Game",
["2171"] = "Tycoon Online",
["2172"] = "Tycoon Online",
["2173"] = "VSA",
["2174"] = "VSA",
["2178"] = "VSA",
["2179"] = "VSA",
["2180"] = "VSA",
["2182"] = "GamersFirst",
["2183"] = "Blizzard Entertainment",
["2184"] = "Kaillera",
["2185"] = "Perfect World (Wanmei)",
["2186"] = "Searchles",
["2188"] = "Perfect World (Wanmei)",
["2189"] = "Perfect World (Wanmei)",
["2193"] = "Searchles",
["2196"] = "MOG",
["2199"] = "The Wrestling Game",
["2200"] = "MOG",
["2202"] = "The Wrestling Game",
["2203"] = "163.com XYQ",
["2204"] = "YHGame",
["2206"] = "QQMusic",
["2213"] = "QQMusic",
["2214"] = "Advogato",
["2217"] = "Advogato",
["2219"] = "BlogMarks",
["2222"] = "BlogMarks",
["2223"] = "QQMusic",
["2225"] = "Woophy",
["2226"] = "Google Analytics",
["2227"] = "Woophy",
["2228"] = "Atlas DMT",
["2232"] = "Sohu SOQ",
["2236"] = "WAYN",
["2237"] = "Quantcast",
["2238"] = "WAYN",
["2240"] = "VOX",
["2243"] = "VOX",
["2244"] = "Atlas DMT",
["2256"] = "Apple iChat",
["2260"] = "Zhuxian",
["2261"] = "Sina UC",
["2263"] = "Sina Weibo",
["2266"] = "Piczo",
["2272"] = "Rediff BOL",
["2273"] = "Phanfare",
["2274"] = "Xunlei Thunder",
["2276"] = "Rediff BOL",
["2277"] = "Phanfare",
["2278"] = "Xunlei Thunder",
["2279"] = "StudiVZ",
["2285"] = "APCUPSd",
["2286"] = "Tribe.net",
["2288"] = "Tribe.net",
["2289"] = "Xunlei Thunder",
["2291"] = "Your Freedom",
["2293"] = "Laplink Everywhere",
["2294"] = "Travellersrpoint",
["2296"] = "Travellersrpoint",
["2297"] = "Your Freedom",
["2298"] = "Your Freedom",
["2301"] = "DRDA",
["2302"] = "Fastmule",
["2303"] = "CouchSurfing",
["2305"] = "CouchSurfing",
["2307"] = "TravBuddy",
["2308"] = "Kuwo",
["2310"] = "TravBuddy",
["2311"] = "Mafia Wars",
["2312"] = "Kuwo",
["2313"] = "Kuwo",
["2314"] = "Bomgar",
["2315"] = "Bomgar",
["2316"] = "Student.com",
["2317"] = "PPTP",
["2318"] = "Student.com",
["2319"] = "GDS DB",
["2321"] = "SCCP",
["2323"] = "SCCP",
["2327"] = "SCCP",
["2328"] = "Friends Reunited",
["2330"] = "JuRen (Huge Man)",
["2333"] = "Zelune Proxy",
["2336"] = "Glype",
["2339"] = "Friends Reunited",
["2348"] = "Shelfari",
["2350"] = "CGIProxy",
["2352"] = "SoftEther PacketiX",
["2353"] = "SoftEther PacketiX",
["2354"] = "SoftEther PacketiX",
["2356"] = "CoralCDN",
["2357"] = "CoralCDN",
["2358"] = "Shockwave Flash (SWF)",
["2361"] = "Shelfari",
["2362"] = "VMware Server",
["2363"] = "IBM Tivoli Storage Manager",
["2364"] = "Teen.com",
["2365"] = "CA ARCserve Backup",
["2368"] = "Teen.com",
["2370"] = "MySpace",
["2382"] = "Guotai Junan",
["2384"] = "Cafe World",
["2385"] = "HP StorageWorks Storage Mirroring",
["2386"] = "OkCupid",
["2388"] = "SurfingToday Proxy",
["2389"] = "OkCupid",
["2390"] = "HP StorageWorks Storage Mirroring",
["2391"] = "HP StorageWorks Storage Mirroring",
["2392"] = "SurfingToday Proxy",
["2393"] = "Odnoklassniki",
["2395"] = "Odnoklassniki",
["2396"] = "Java RMI",
["2397"] = "Nexopia",
["2398"] = "optionsXpress",
["2399"] = "Qianlong",
["2400"] = "Rstatd",
["2401"] = "AddictingGames",
["2402"] = "Nexopia",
["2403"] = "NTR Connect",
["2407"] = "Fenxijia",
["2410"] = "Symantec Antivirus",
["2414"] = "File Dropper",
["2415"] = "File Dropper",
["2417"] = "Google Web Accelerator",
["2422"] = "PDBOX",
["2423"] = "PDBOX",
["2425"] = "PDBOX",
["2426"] = "AddictingGames",
["2428"] = "RayFile",
["2434"] = "JibJab",
["2436"] = "Jubii",
["2437"] = "Jubii Email",
["2440"] = "JumpTV",
["2441"] = "JumpTV Latino",
["2442"] = "Justin.tv",
["2443"] = "Ku6.com",
["2449"] = "Ku6.com",
["2453"] = "Last.fm",
["2455"] = "SageTV",
["2459"] = "Zynga Poker",
["2460"] = "SageTV",
["2461"] = "SageTV",
["2462"] = "ISAKMP",
["2463"] = "ISAKMP",
["2464"] = "BGP",
["2465"] = "BOOTP",
["2466"] = "CMP",
["2468"] = "Hotspot Shield VPN",
["2469"] = "Hotspot Shield VPN",
["2470"] = "4Shared",
["2471"] = "2Shared",
["2472"] = "iSCSI",
["2479"] = "LDP",
["2480"] = "LDP",
["2484"] = "NFS",
["2491"] = "NDMP",
["2492"] = "NDMP",
["2493"] = "OpenVPN",
["2498"] = "OpenVPN",
["2502"] = "RIP",
["2503"] = "Vipuls Razor",
["2504"] = "Rwho",
["2505"] = "Quake III Arena",
["2506"] = "Quake III Arena",
["2507"] = "SonicWall Unblock Proxy",
["2509"] = "RPCAP",
["2510"] = "NAT-PMP",
["2511"] = "NAT-PMP",
["2513"] = "UPnP",
["2515"] = "Microsoft CryptoAPI",
["2532"] = "Freegate",
["2543"] = "Last.fm",
["2544"] = "Microsoft WINS",
["2547"] = "SonicWall Unblock Proxy",
["2549"] = "Game Sites 200",
["2550"] = "Game Sites 200",
["2560"] = "FortiClient",
["2564"] = "YY",
["2565"] = "Miniclip",
["2572"] = "GOGOBOX",
["2573"] = "Digsby",
["2574"] = "Digsby",
["2576"] = "Digsby",
["2577"] = "Digsby",
["2578"] = "Digsby",
["2579"] = "Digsby",
["2581"] = "Baofeng",
["2582"] = "Break",
["2583"] = "EarthCam",
["2584"] = "EarthCam",
["2585"] = "Facebook Apps",
["2589"] = "Break",
["2590"] = "Five.tv",
["2591"] = "GOM TV",
["2592"] = "GOM TV",
["2593"] = "Graboid Video",
["2596"] = "Graboid Video",
["2597"] = "ITV Video Playback",
["2598"] = "Pogo",
["2600"] = "Tagoo",
["2601"] = "Tagoo",
["2608"] = "Willing Webcam",
["2610"] = "FONA",
["2611"] = "FONA",
["2612"] = "Livedoor",
["2613"] = "Livedoor",
["2614"] = "ESET",
["2618"] = "Infoseek",
["2619"] = "Game Zone",
["2621"] = "Goo Mail",
["2622"] = "Yahoo! Search",
["2625"] = "HowardForums",
["2628"] = "HowardForums",
["2633"] = "Techinline Remote Desktop",
["2635"] = "SpyAgent",
["2640"] = "eBLVD",
["2644"] = "QQ",
["2645"] = "Baofeng",
["2646"] = "Baofeng",
["2647"] = "PIPI Player",
["2648"] = "PIPI Player",
["2659"] = "Hotspot Shield VPN",
["2662"] = "MvBoxPlayer",
["2668"] = "MvBoxPlayer",
["2675"] = "Xunlei XLGame",
["2677"] = "Xunlei XLGame",
["2678"] = "Xunlei XLGame",
["2687"] = "FlashGet",
["2688"] = "Sina",
["2691"] = "Baidu Hi",
["2692"] = "CCTV",
["2708"] = "Sina UC",
["2709"] = "Hupu.com",
["2710"] = "Alicall",
["2711"] = "Alicall",
["2716"] = "Google Mail (Gmail)",
["2717"] = "Yahoo! Mail",
["2720"] = "Yahoo! Mail",
["2729"] = "Kazaa",
["2733"] = "Kugou Music Disk",
["2735"] = "Microsoft Remote Desktop",
["2742"] = "Microsoft Remote Desktop",
["2743"] = "BBC iPlayer",
["2745"] = "Smashing Games",
["2746"] = "Smashing Games",
["2747"] = "Free Online Games",
["2748"] = "Flickr",
["2752"] = "SpywareBlaster",
["2754"] = "Torrent Episode Downloader (ted)",
["2756"] = "Free Online Games",
["2765"] = "Sogou Musicbox",
["2776"] = "Coremail",
["2777"] = "163.com FlashMail",
["2778"] = "RSS Xpress",
["2780"] = "163.com FlashMail",
["2782"] = "SharpReader",
["2786"] = "Xunlei Thunder",
["2787"] = "Frontier Compute Engine",
["2789"] = "Xunlei Thunder",
["2790"] = "Xunlei XLGame",
["2794"] = "Slingbox",
["2795"] = "No-IP DUC",
["2797"] = "Azureus",
["2798"] = "Gambling Sites",
["2799"] = "Juice Receiver",
["2800"] = "Skype",
["2802"] = "Slingbox",
["2803"] = "Slingbox",
["2805"] = "Slingbox",
["2808"] = "BitTorrent Protocol",
["2812"] = "DynDNS Updater",
["2817"] = "StupidCensorship",
["2818"] = "StupidCensorship",
["2819"] = "Glype",
["2820"] = "NewFastWorkingProxies",
["2821"] = "Facebook",
["2822"] = "Facebook Inc",
["2823"] = "Tagged.com",
["2824"] = "Tagged.com",
["2825"] = "Ning",
["2826"] = "Ning",
["2827"] = "43Things",
["2828"] = "BlackPlanet",
["2829"] = "Broadcaster.com",
["2830"] = "Broadcaster.com",
["2831"] = "Care2",
["2832"] = "Care2",
["2833"] = "Espin",
["2835"] = "Woot",
["2836"] = "Woot",
["2837"] = "RedFlagDeals",
["2838"] = "Kaboodle",
["2841"] = "ThisNext",
["2842"] = "Stylehive",
["2844"] = "ShopStyle",
["2845"] = "Badoo",
["2846"] = "TortoiseCVS",
["2850"] = "Cisco WebEx",
["2851"] = "Cherry Red Casino",
["2852"] = "Rushmore Online",
["2853"] = "Players Only",
["2854"] = "Casino Bodog",
["2855"] = "Casino Bodog",
["2856"] = "Casino Tropez",
["2857"] = "Sports Book",
["2858"] = "Sports Book",
["2861"] = "1UP",
["2862"] = "Games Top 100",
["2865"] = "Games Top 100",
["2866"] = "Boxee",
["2867"] = "Skype",
["2871"] = "Xmarks",
["2874"] = "Xmarks",
["2875"] = "Xunlei Thunder",
["2877"] = "Synergy",
["2878"] = "Skype",
["2881"] = "Nickelodeon Jr Arcade",
["2882"] = "BigFish Games",
["2886"] = "BigFish Games",
["2887"] = "Candystand",
["2888"] = "Candystand",
["2889"] = "Games.com",
["2890"] = "Games.com",
["2891"] = "Neopets",
["2892"] = "FreshDownload",
["2895"] = "Neopets",
["2896"] = "CFNetwork",
["2898"] = "Vembu StoreGrid",
["2902"] = "OnlineGamesNet",
["2903"] = "OnlineGamesNet",
["2905"] = "Vembu StoreGrid",
["2908"] = "Morpheus",
["2910"] = "Morpheus",
["2912"] = "Played Online",
["2913"] = "DriveHQ",
["2915"] = "Played Online",
["2916"] = "DriveHQ",
["2918"] = "PopCap Games",
["2919"] = "PopCap Games",
["2925"] = "WildTangent ORB",
["2926"] = "Viewpoint Toolbar",
["2927"] = "Viewpoint Toolbar",
["2928"] = "Motorola Timbuktu Pro",
["2929"] = "Motorola Timbuktu Pro",
["2930"] = "GameSpy",
["2931"] = "GameSpy",
["2932"] = "GameSpy",
["2933"] = "GameSpy",
["2934"] = "GameSpy",
["2935"] = "GameSpy",
["2936"] = "GameSpy",
["2937"] = "GameSpy",
["2938"] = "Xbox",
["2939"] = "Xbox",
["2940"] = "Xbox",
["2941"] = "Xbox",
["2947"] = "Twister MP3",
["2951"] = "Twister MP3",
["2952"] = "MyOtherDrive",
["2953"] = "Microsoft MSN Messenger",
["2954"] = "Microsoft MSN Messenger",
["2955"] = "SHOUTcast",
["2957"] = "BearShare",
["2958"] = "BearShare",
["2959"] = "Zilla Mp3 Finder",
["2960"] = "Microsoft OneDrive",
["2961"] = "Microsoft OneDrive",
["2962"] = "Microsoft OneDrive",
["2963"] = "WeatherBug",
["2964"] = "WeatherBug",
["2965"] = "WeatherBug",
["2966"] = "WeatherBug",
["2967"] = "WeatherBug",
["2968"] = "Dr. Backup",
["2971"] = "WeatherBug",
["2976"] = "Elephant Drive",
["2978"] = "MapQuest",
["2979"] = "MapQuest",
["2983"] = "Executable",
["2985"] = "Executable",
["2986"] = "Executable",
["2989"] = "Executable",
["2990"] = "Executable",
["2991"] = "Image",
["2992"] = "Image",
["2993"] = "Image",
["2994"] = "Image",
["2995"] = "Image",
["2996"] = "Image",
["2999"] = "Image",
["3000"] = "Image",
["3001"] = "Executable",
["3003"] = "Executable",
["3004"] = "Executable",
["3005"] = "Hotspot Shield VPN",
["3006"] = "Executable",
["3007"] = "Executable",
["3008"] = "Executable",
["3010"] = "QQ",
["3024"] = "QQ",
["3027"] = "Netflix",
["3028"] = "SMS Free Sender",
["3029"] = "OfficeSMS",
["3030"] = "mGinger",
["3031"] = "Redux",
["3032"] = "Convivea",
["3034"] = "Convivea",
["3039"] = "Netflix",
["3042"] = "Document",
["3043"] = "Document",
["3046"] = "Document",
["3047"] = "Document",
["3048"] = "Document",
["3049"] = "Document",
["3050"] = "1337x",
["3052"] = "Archive",
["3053"] = "1337x",
["3055"] = "Archive",
["3056"] = "Archive",
["3057"] = "Archive",
["3058"] = "Archive",
["3059"] = "Archive",
["3060"] = "Archive",
["3061"] = "Netflix",
["3062"] = "Archive",
["3063"] = "Archive",
["3064"] = "Archive",
["3070"] = "QQ",
["3072"] = "QQ",
["3075"] = "Google",
["3076"] = "Archive",
["3077"] = "Archive",
["3080"] = "Archive",
["3081"] = "Archive",
["3086"] = "Archive",
["3087"] = "Archive",
["3088"] = "Archive",
["3091"] = "iPROConference",
["3093"] = "Webroot",
["3094"] = "Webroot",
["3096"] = "XMPP (Jabber) Protocol",
["3097"] = "XMPP (Jabber) Protocol",
["3100"] = "Netflix",
["3106"] = "Steganos",
["3107"] = "Steganos",
["3108"] = "Guardster",
["3116"] = "BitTorrent Protocol",
["3118"] = "Netflix",
["3127"] = "Netflix",
["3129"] = "ISL Light",
["3131"] = "VeryCD",
["3134"] = "VeryCD",
["3137"] = "Xunlei Thunder",
["3138"] = "DameWare Mini Remote Control",
["3140"] = "eMule",
["3145"] = "eMule",
["3148"] = "NetViewer",
["3149"] = "NetViewer",
["3150"] = "NetViewer",
["3152"] = "AOL Radio",
["3154"] = "Tor",
["3155"] = "Tor",
["3156"] = "Tor",
["3158"] = "eMule",
["3159"] = "eMule",
["3161"] = "eMule",
["3165"] = "eMule",
["3171"] = "eMule",
["3189"] = "eMule",
["3191"] = "eMule",
["3192"] = "Xunlei Thunder",
["3194"] = "Xunlei Thunder",
["3195"] = "Xunlei Thunder",
["3198"] = "Xunlei Thunder",
["3199"] = "Xunlei Thunder",
["3200"] = "Xunlei Thunder",
["3206"] = "Xunlei Thunder",
["3213"] = "Metacafe",
["3219"] = "Active WebCam",
["3220"] = "Scramby",
["3221"] = "Scramby",
["3224"] = "Raketu",
["3225"] = "Raketu",
["3231"] = "Executable",
["3233"] = "Executable",
["3234"] = "Executable",
["3237"] = "Executable",
["3238"] = "Executable",
["3239"] = "eMule",
["3241"] = "eMule",
["3243"] = "eMule",
["3244"] = "eMule",
["3250"] = "Document",
["3251"] = "Document",
["3252"] = "Document",
["3253"] = "Windows Media Player",
["3255"] = "Archive",
["3256"] = "Archive",
["3257"] = "Archive",
["3259"] = "Archive",
["3260"] = "Archive",
["3261"] = "Archive",
["3262"] = "Archive",
["3263"] = "Archive",
["3264"] = "Toonel.net",
["3265"] = "Microsoft OneDrive",
["3266"] = "Tonido",
["3267"] = "Windows Live Messenger File Transfer",
["3269"] = "XML",
["3270"] = "Microsoft OneDrive",
["3271"] = "XML",
["3272"] = "XML",
["3273"] = "Box",
["3274"] = "Box",
["3275"] = "Tonido",
["3277"] = "Tonido",
["3279"] = "Tonido",
["3281"] = "ZumoDrive",
["3282"] = "Ares",
["3283"] = "Ares",
["3284"] = "XML",
["3285"] = "Livedrive",
["3289"] = "DBank",
["3291"] = "21CN Webmail",
["3295"] = "Tianya Webmail",
["3296"] = "Lenovo Data",
["3297"] = "Syncplicity",
["3303"] = "Windows Live Messenger File Transfer",
["3307"] = "JWChat",
["3313"] = "Zoho Chat",
["3314"] = "CitrixWire",
["3315"] = "SpiderOak",
["3317"] = "FrostWire",
["3318"] = "FrostWire",
["3319"] = "Crux P2P",
["3321"] = "BT Chat",
["3324"] = "WordPress",
["3325"] = "BT Chat",
["3328"] = "BTMon",
["3329"] = "BTMon",
["3330"] = "BitTorrent.am",
["3331"] = "magicVORTEX",
["3333"] = "BitTorrent.am",
["3340"] = "Magic MP3 Tagger",
["3345"] = "Full DLs",
["3348"] = "Full DLs",
["3349"] = "H33t",
["3350"] = "H33t",
["3351"] = "ISO Hunt",
["3352"] = "ISO Hunt",
["3354"] = "Indy Torrents",
["3356"] = "Shufflr",
["3359"] = "Mikogo",
["3360"] = "GoToMyPC",
["3361"] = "GoToMyPC",
["3362"] = "GoToMyPC",
["3365"] = "QQ",
["3369"] = "Mininova",
["3370"] = "Mininova",
["3371"] = "New Torrents",
["3372"] = "New Torrents",
["3373"] = "RAR Bg",
["3374"] = "RAR Bg",
["3375"] = "The Pirate Bay",
["3376"] = "The Pirate Bay",
["3377"] = "Torrent Box",
["3378"] = "Torrent Box",
["3380"] = "Ares",
["3381"] = "AOL Radio",
["3382"] = "Torrent Portal",
["3383"] = "Torrent Portal",
["3385"] = "Ares",
["3386"] = "Torrent Reactor",
["3387"] = "Torrent Reactor",
["3388"] = "Ammyy Admin",
["3389"] = "LogMeIn",
["3390"] = "Torrent Zap",
["3391"] = "Ammyy Admin",
["3392"] = "LogMeIn Hamachi",
["3393"] = "Torrent Zap",
["3396"] = "Accordiva",
["3397"] = "Ammyy Admin",
["3409"] = "Viack VIA3",
["3410"] = "Windows Live Messenger File Transfer",
["3411"] = "Windows Live Messenger File Transfer",
["3414"] = "Microsoft SharePoint",
["3418"] = "Microsoft OneDrive",
["3430"] = "LogMeIn",
["3439"] = "Google Mail (Gmail)",
["3440"] = "Google Mail (Gmail)",
["3441"] = "Google Mail (Gmail)",
["3442"] = "Google Talk",
["3443"] = "Apple iMessage",
["3446"] = "NCAA March Madness",
["3449"] = "Moodstream",
["3450"] = "X-Lite",
["3451"] = "3CX Phone System",
["3452"] = "ZoIPer Communicator",
["3453"] = "NCAA March Madness",
["3456"] = "NCAA March Madness",
["3458"] = "NCAA March Madness",
["3460"] = "Buzz Softphone",
["3463"] = "IAX2",
["3465"] = "Sanguo Sha",
["3470"] = "Pangolin",
["3473"] = "SugarSync",
["3476"] = "Vphonet",
["3477"] = "Baidu Wenku",
["3478"] = "DocIn",
["3482"] = "MediaRing Talk",
["3483"] = "MediaRing Talk",
["3484"] = "Acronis Snap Deploy",
["3486"] = "TeamTalk",
["3487"] = "Brekeke",
["3488"] = "CC File Transfer",
["3489"] = "Live365",
["3490"] = "CC File Transfer",
["3498"] = "iCall",
["3499"] = "BeamYourScreen",
["3502"] = "BeamYourScreen",
["3504"] = "iCall",
["3506"] = "Yak Communications",
["3507"] = "Delephone",
["3508"] = "Delephone",
["3509"] = "BeamYourScreen",
["3516"] = "TiViPhone",
["3517"] = "Buzzfon",
["3519"] = "Gadu-Gadu",
["3525"] = "SJphone",
["3526"] = "Apple Spotlight Suggestions",
["3530"] = "Reunion.com",
["3535"] = "Techinline",
["3536"] = "Jango",
["3537"] = "VLC Media Player",
["3538"] = "wwiTV",
["3539"] = "wwiTV",
["3543"] = "Grooveshark",
["3544"] = "MizuPhone",
["3546"] = "Anyplace Control",
["3548"] = "Skype",
["3549"] = "Windows Media Player",
["3550"] = "SnapStream BeyondTV",
["3551"] = "Anyplace Control",
["3553"] = "SnapStream BeyondTV",
["3554"] = "SnapStream BeyondTV",
["3557"] = "Anyplace Control",
["3560"] = "Telnet",
["3561"] = "Weblin",
["3562"] = "Club Cooee",
["3563"] = "Club Cooee",
["3566"] = "tChat",
["3570"] = "Telnet",
["3572"] = "AliveChat",
["3577"] = "Action Allstars",
["3578"] = "Google Mail (Gmail)",
["3579"] = "All Girl Arcade",
["3583"] = "Nefsis",
["3584"] = "Tor",
["3586"] = "Deepnet Explorer",
["3588"] = "Torrent Reactor",
["3589"] = "Torrent Reactor",
["3590"] = "Torrent Spy",
["3593"] = "Torrent Spy",
["3594"] = "Brainshark",
["3595"] = "BitLord",
["3598"] = "Input Director",
["3602"] = "PeerFolders",
["3603"] = "BitTornado",
["3604"] = "WWW File Share Pro",
["3612"] = "Aimini",
["3613"] = "Saba Enterprise (SaaS)",
["3614"] = "Input Director",
["3617"] = "XML",
["3618"] = "XMPP (Jabber) Protocol",
["3619"] = "Scopia Desktop",
["3622"] = "BadBlue",
["3624"] = "Be Bratz",
["3627"] = "SoonR Desktop Agent",
["3629"] = "XML",
["3630"] = "XML",
["3631"] = "Beanie Babies Online",
["3632"] = "AOL Radio",
["3633"] = "SoonR Desktop Agent",
["3634"] = "AOL Radio",
["3635"] = "BadBlue",
["3636"] = "SoonR Desktop Agent",
["3639"] = "Windows Media Player",
["3644"] = "Skype",
["3647"] = "Bella Sara Online",
["3648"] = "HTTP Proxy",
["3650"] = "BoomBang Online",
["3651"] = "CackleBerries Online",
["3654"] = "Winamp Remote",
["3659"] = "Build-A-Bearville Online",
["3660"] = "MP3",
["3665"] = "BitDefender",
["3669"] = "Biennesoft",
["3670"] = "iSendr",
["3672"] = "ABC (Yet Another Bittorrent Client)",
["3679"] = "00unblock",
["3683"] = "CCleaner",
["3684"] = "AccuConference",
["3687"] = "Apple iMessage",
["3689"] = "Python urllib",
["3693"] = "Dr.Web Anti-Virus",
["3694"] = "Dr.Web Anti-Virus",
["3702"] = "Panda Security",
["3703"] = "Avast! Antivirus",
["3712"] = "Microsoft Windows Updates",
["3713"] = "Microsoft Windows Updates",
["3715"] = "Microsoft Windows Genuine Advantage",
["3716"] = "Microsoft Dr.Watson",
["3717"] = "Microsoft Dr.Watson",
["3721"] = "BeamYourScreen",
["3722"] = "Ubuntu APT",
["3726"] = "IObit Security 360",
["3727"] = "IObit Security 360",
["3728"] = "PC Tools Smart Update",
["3729"] = "Microsoft MSN Messenger",
["3731"] = "PC Tools ThreatFire",
["3732"] = "PC Tools ThreatFire",
["3733"] = "PC Tools ThreatFire",
["3737"] = "Clam AntiVirus (ClamAV)",
["3740"] = "Web Conferencing Central",
["3742"] = "iLinc",
["3746"] = "QQ",
["3753"] = "ReadyTalk",
["3754"] = "QQ",
["3758"] = "ReadyTalk",
["3759"] = "ReadyTalk",
["3760"] = "VoiceText",
["3761"] = "VoiceText",
["3763"] = "Chart Beat",
["3764"] = "Twiddla",
["3767"] = "Chart Beat",
["3770"] = "Twiddla",
["3789"] = "QQ",
["3794"] = "Facebook",
["3796"] = "UVC",
["3797"] = "Facebook",
["3798"] = "Adobe Acrobat Connect",
["3801"] = "Facebook",
["3802"] = "Facebook",
["3810"] = "AT Conference",
["3811"] = "AT Conference",
["3812"] = "MegaMeeting",
["3813"] = "MegaMeeting",
["3814"] = "MegaMeeting",
["3815"] = "UVC",
["3819"] = "GatherPlace",
["3820"] = "GatherPlace",
["3821"] = "InstantPresenter",
["3822"] = "LiveLOOK",
["3823"] = "LiveLOOK",
["3824"] = "Glance",
["3825"] = "Critical Force Critical Ops",
["3827"] = "Glance",
["3831"] = "QQ",
["3833"] = "Glance",
["3834"] = "InterCall",
["3835"] = "QQ",
["3838"] = "Voddler",
["3841"] = "InterCall",
["3843"] = "InstantService",
["3845"] = "VoipWise",
["3846"] = "VoipWise",
["3847"] = "VoipWise",
["3848"] = "VoipWise",
["3852"] = "Express Talk",
["3853"] = "KoalaDC",
["3854"] = "Jaxtr",
["3855"] = "Jaxtr",
["3856"] = "Plaxo",
["3857"] = "Plaxo",
["3858"] = "Plaxo",
["3859"] = "Delicious",
["3860"] = "Delicious",
["3861"] = "Delicious",
["3862"] = "Fotolog",
["3866"] = "Voddler",
["3874"] = "Omegle",
["3879"] = "Xanga",
["3881"] = "Windows Media Player",
["3882"] = "Xanga",
["3883"] = "Digg",
["3884"] = "Digg",
["3885"] = "Crackle",
["3886"] = "Crackle",
["3891"] = "Slide",
["3899"] = "Slide",
["3904"] = "FeedBurner",
["3906"] = "Icecast",
["3907"] = "Buzznet",
["3908"] = "Buzznet",
["3909"] = "Squidoo",
["3912"] = "Squidoo",
["3918"] = "Fotki",
["3935"] = "Fotki",
["3942"] = "QQ",
["3945"] = "Reddit",
["3946"] = "Reddit",
["3947"] = "Netvibes",
["3950"] = "QQ",
["3952"] = "Netvibes",
["3953"] = "myYearbook",
["3961"] = "myYearbook",
["3962"] = "Meetup",
["3963"] = "Yahoo! Apps",
["3965"] = "Meetup",
["3966"] = "Fotolia",
["3967"] = "Fotolia",
["3968"] = "Yahoo! Apps",
["3969"] = "Farmville",
["3970"] = "Sony Online Entertainment",
["3971"] = "Sony Online Entertainment",
["3972"] = "Electronic Arts",
["3973"] = "Nexon Games",
["3975"] = "Nexon Games",
["3979"] = "Nexon Games",
["3980"] = "Apple iMessage",
["3982"] = "Apple FaceTime",
["3983"] = "Twitter",
["3986"] = "FooPets",
["3989"] = "DoubleClick",
["3990"] = "ScoreCard Research",
["3991"] = "Google Mail (Gmail)",
["3994"] = "FunnelBrain",
["3995"] = "urFooz",
["3996"] = "MuchGames",
["3997"] = "SocialSplash",
["4000"] = "Pulse News",
["4042"] = "Apple FaceTime",
["4054"] = "Twitter",
["4056"] = "YouTube",
["4058"] = "XML",
["4236"] = "Image",
["4239"] = "Image",
["4243"] = "Image",
["4245"] = "Image",
["4254"] = "Image",
["4261"] = "Image",
["4265"] = "Image",
["4267"] = "Image",
["4273"] = "Image",
["4277"] = "Image",
["4282"] = "Image",
["4284"] = "Image",
["4289"] = "Image",
["4294"] = "Image",
["4295"] = "Image",
["4301"] = "Image",
["4306"] = "Archive",
["4395"] = "DNS Protocol",
["4398"] = "DNS Protocol",
["4399"] = "DNS Protocol",
["4410"] = "IMAP",
["4413"] = "POP",
["4448"] = "Nimbuzz",
["4476"] = "H.225 Call Signaling",
["4477"] = "H.225 Call Signaling",
["4481"] = "H.245 Call Control",
["4489"] = "T.120",
["4495"] = "RTCP",
["4687"] = "IDM",
["4826"] = "Chess.com",
["5018"] = "BitCoin Mining Protocol",
["5020"] = "BitCoin Mining Protocol",
["5140"] = "LogMeIn Hamachi",
["5147"] = "HTTP Protocol",
["5148"] = "HTTP Protocol",
["5149"] = "SMTP",
["5151"] = "SMTP",
["5153"] = "SSL",
["5159"] = "SSL",
["5174"] = "IMAP",
["5180"] = "POP",
["5181"] = "SMB",
["5183"] = "DNS Protocol",
["5193"] = "ICMP",
["5195"] = "ICMP",
["5198"] = "ICMP",
["5202"] = "ICMP",
["5227"] = "War Rock",
["5228"] = "Knight Online",
["5229"] = "Wolfenstein Enemy Territory",
["5230"] = "Steam Software",
["5231"] = "Steam Software",
["5233"] = "Blizzard Entertainment",
["5297"] = "Spore",
["5368"] = "Happy Pets",
["5386"] = "Google Analytics",
["5388"] = "Google Analytics",
["5391"] = "Mint.com",
["5393"] = "Picnik",
["5401"] = "Picnik",
["5402"] = "TinyChat",
["5403"] = "AllRecipes",
["5406"] = "Boing Boing",
["5420"] = "CocktailDB",
["5421"] = "Epicurious",
["5425"] = "FunnyOrDie",
["5427"] = "FunnyOrDie",
["5429"] = "FunnyOrDie",
["5430"] = "Instructables",
["5433"] = "The Onion",
["5453"] = "Craigslist",
["5455"] = "Howcast",
["5457"] = "iFixIt",
["5458"] = "iFixIt",
["5460"] = "IMDb",
["5463"] = "Indeed.com",
["5464"] = "Kayak.com",
["5465"] = "metacritic",
["5469"] = "Snopes.com",
["5472"] = "Snopes.com",
["5473"] = "TED",
["5478"] = "Wikipedia",
["5480"] = "New York Times Online",
["5481"] = "New York Times Online",
["5485"] = "Sports Illustrated Online",
["5486"] = "Amazon.com",
["5487"] = "Consumerist",
["5490"] = "Etsy",
["5496"] = "Restaurant.com",
["5499"] = "Tumblr.com",
["5501"] = "Ars Technica",
["5502"] = "FileHippo.com",
["5505"] = "gdgt",
["5517"] = "Apple FaceTime",
["5524"] = "Manolito",
["5525"] = "Manolito",
["5531"] = "AOL Toolbar",
["5532"] = "ApacheBenchmark",
["5533"] = "AutoIt",
["5534"] = "Boitho",
["5535"] = "Youngzsoft CCProxy",
["5539"] = "CentralOps.net",
["5565"] = "Single Click Connect",
["5576"] = "Google Talk",
["5578"] = "XMPP (Jabber) Protocol",
["5579"] = "Google",
["5581"] = "AOL Webmail",
["5583"] = "AIM",
["5584"] = "AOL",
["5585"] = "AIM",
["5586"] = "Microsoft MSN Messenger",
["5596"] = "ScoreCard Research",
["5599"] = "Yahoo!",
["5600"] = "360Safe",
["5601"] = "Yahoo!",
["5602"] = "Google",
["5604"] = "Facebook",
["5606"] = "FeedBurner",
["5607"] = "Google Desktop",
["5608"] = "Google Docs",
["5609"] = "Google Groups",
["5610"] = "Google Sites",
["5612"] = "Symantec Live Update",
["5613"] = "Symantec Live Update",
["5614"] = "Bing",
["5618"] = "Microsoft Dr.Watson",
["5621"] = "Upcoming",
["5623"] = "Yahoo! Finance",
["5624"] = "Yahoo! Finance",
["5625"] = "Yahoo! Video",
["5626"] = "Yahoo! Search",
["5627"] = "Orkut",
["5628"] = "MySpace",
["5631"] = "Chatroulette",
["5633"] = "4Shared",
["5634"] = "NCAA March Madness",
["5635"] = "51.com Music",
["5636"] = "BigUpload.com",
["5637"] = "Tagged.com",
["5638"] = "Kaixin001",
["5644"] = "WeatherBug",
["5645"] = "WeatherBug",
["5647"] = "WeatherBug",
["5648"] = "WeatherBug",
["5649"] = "LinkedIn",
["5650"] = "Google Analytics",
["5651"] = "Google Mail (Gmail)",
["5653"] = "BitDefender",
["5654"] = "Yahoo! Toolbar",
["5655"] = "Google",
["5660"] = "Dropbox",
["5666"] = "Microsoft MSN Messenger",
["5670"] = "Microsoft Outlook.com (Hotmail)",
["5684"] = "The Weather Channel",
["5693"] = "POP",
["5697"] = "YumSugar",
["5698"] = "PerezHilton",
["5699"] = "TMZ",
["5700"] = "The Superficial",
["5701"] = "The Superficial",
["5702"] = "WhatWouldTylerDurdenDo",
["5703"] = "IDontLikeYouInThatWay",
["5704"] = "Dlisted",
["5705"] = "Dlisted",
["5706"] = "Salesforce",
["5715"] = "Last.fm",
["5716"] = "Apple iWeb",
["5718"] = "Apple iCloud",
["5720"] = "AppleTV",
["5721"] = "Apple Front Row",
["5722"] = "Apple iPhoto",
["5727"] = "YouTube",
["5738"] = "Transmission",
["5741"] = "Cisco WebEx",
["5742"] = "Cisco WebEx",
["5743"] = "Evernote",
["5744"] = "Evernote",
["5745"] = "eMule",
["5746"] = "Facebook",
["5750"] = "eBay",
["5754"] = "eBay",
["5756"] = "NetNewsWire",
["5757"] = "NewsFire",
["5758"] = "Google Mail (Gmail)",
["5759"] = "Adium",
["5760"] = "Skype",
["5766"] = "Miro",
["5775"] = "PhotoBook",
["5778"] = "MediaNet",
["5779"] = "BearShare",
["5783"] = "Pandora Radio",
["5784"] = "The Hype Machine",
["5785"] = "The Hype Machine",
["5786"] = "Deezer",
["5787"] = "iLike",
["5789"] = "Musicovery",
["5790"] = "Musicovery",
["5791"] = "OurStage",
["5792"] = "OurStage",
["5794"] = "Slacker",
["5796"] = "Zune",
["5797"] = "Zune",
["5798"] = "Zune",
["5799"] = "8tracks",
["5801"] = "IAX2",
["5802"] = "IAX2",
["5808"] = "eBay",
["5809"] = "Twitter",
["5812"] = "Yahoo!",
["5814"] = "AOL",
["5815"] = "ScoreCard Research",
["5816"] = "AOL",
["5817"] = "AOL",
["5818"] = "AOL Webmail",
["5819"] = "AOL Webmail",
["5820"] = "AOL Webmail",
["5821"] = "AOL",
["5824"] = "Trillian",
["5825"] = "Trillian",
["5826"] = "Trillian",
["5841"] = "AOL Webmail",
["5842"] = "AOL",
["5856"] = "AOL",
["5868"] = "Facebook",
["5874"] = "Google Analytics",
["5901"] = "Wells Fargo Bank",
["5902"] = "Chase Bank",
["5907"] = "Blippy.com",
["5909"] = "Fark.com",
["5912"] = "Farmville",
["5913"] = "Cafe World",
["5921"] = "Zynga Poker",
["5930"] = "Teredo",
["5938"] = "Zynga Poker",
["5939"] = "Mesmo Games",
["5940"] = "Facebook Apps",
["5942"] = "Slashdot.org",
["5946"] = "Playfish",
["5947"] = "MindJolt",
["5948"] = "PopCap Games",
["5960"] = "Arcor",
["5964"] = "Freenet.de",
["5966"] = "Lavabit",
["5967"] = "t-online.de",
["5968"] = "web.de",
["5972"] = "SAP",
["5973"] = "Microsoft MSN Messenger",
["5979"] = "Safari Browser",
["5981"] = "Apple iTunes",
["5982"] = "YouTube",
["5984"] = "Wall Street Journal",
["5985"] = "ABC Player",
["5986"] = "National Public Radio (NPR)",
["5987"] = "Zillow",
["5988"] = "Dropbox",
["5989"] = "FT",
["5990"] = "Tonghuashun",
["5991"] = "Epicurious",
["5992"] = "Craigsphone",
["5993"] = "Fandango",
["5994"] = "Groupon",
["5995"] = "Free Books",
["5996"] = "iPDF",
["5997"] = "Wired Magazine",
["5998"] = "Apple iTunes",
["6002"] = "Google",
["6003"] = "Apple PubSub",
["6004"] = "Google Talk Gadget",
["6005"] = "Google Reader",
["6007"] = "Xfinity",
["6011"] = "Google",
["6012"] = "H.248 Protocol",
["6013"] = "H.248 Protocol",
["6014"] = "H.248 Protocol",
["6015"] = "Google",
["6016"] = "GMX",
["6017"] = "ICCP",
["6018"] = "ICCP",
["6019"] = "ICCP",
["6021"] = "Facebook",
["6029"] = "ICCP",
["6030"] = "Safari Browser",
["6034"] = "ICCP",
["6035"] = "DNP3",
["6036"] = "DNP3",
["6037"] = "DNP3",
["6038"] = "DNP3",
["6039"] = "DNP3",
["6040"] = "DNP3",
["6042"] = "AXIS Camera",
["6044"] = "AXIS Camera",
["6045"] = "Windows Media",
["6046"] = "Linksys Webcam",
["6047"] = "Totorosa JJAM",
["6066"] = "GoToMeeting",
["6067"] = "GoToMeeting",
["6068"] = "Unica",
["6069"] = "GoToMeeting",
["6089"] = "Dropbox",
["6110"] = "Database File",
["6114"] = "QQ File Transfer",
["6115"] = "Fetion",
["6116"] = "Fetion",
["6117"] = "Fetion",
["6122"] = "WGCI.com",
["6123"] = "WGCI.com",
["6124"] = "AOL",
["6141"] = "Lotus Notes",
["6149"] = "Google Talk",
["6157"] = "Facebook",
["6158"] = "Facebook",
["6159"] = "Microsoft Yammer",
["6167"] = "Blizzard Entertainment",
["6168"] = "Blizzard Entertainment",
["6186"] = "Blizzard Entertainment",
["6197"] = "Citrix",
["6198"] = "Citrix",
["6199"] = "Citrix",
["6213"] = "TeamViewer",
["6214"] = "TeamViewer",
["6215"] = "TeamViewer",
["6216"] = "TeamViewer",
["6217"] = "TeamViewer",
["6222"] = "Google Plus",
["6225"] = "SlideRocket",
["6231"] = "Shockwave Flash (SWF)",
["6232"] = "Shockwave Flash (SWF)",
["6233"] = "Shockwave Flash (SWF)",
["6234"] = "Shockwave Flash (SWF)",
["6235"] = "Shockwave Flash (SWF)",
["6236"] = "Shockwave Flash (SWF)",
["6237"] = "Google Talk Gadget",
["6239"] = "Google Plus",
["6244"] = "RenRen",
["6245"] = "RenRen",
["6247"] = "Facebook",
["6255"] = "Yahoo! Mail",
["6258"] = "Cybozu",
["6259"] = "Cybozu",
["6260"] = "Cybozu",
["6261"] = "DoubleClick",
["6262"] = "BlueLithium",
["6263"] = "TurboTax",
["6264"] = "TurboTax",
["6265"] = "TurboTax",
["6266"] = "BayNote",
["6267"] = "H&R Block",
["6268"] = "Accuen",
["6270"] = "eTax.com",
["6271"] = "TaxAct",
["6274"] = "AIM",
["6275"] = "AIM",
["6277"] = "DarkOrbit",
["6284"] = "Perforce",
["6285"] = "Sanguo Sha",
["6303"] = "QuakeLive",
["6321"] = "OnlineGamblingSites",
["6328"] = "Nexon Games",
["6332"] = "ANts",
["6334"] = "Nexon Games",
["6339"] = "Nexon Games",
["6341"] = "Nexon Games",
["6358"] = "Nexon Games",
["6359"] = "NCAA March Madness",
["6360"] = "NCAA March Madness",
["6361"] = "Nexon Games",
["6362"] = "Nexon Games",
["6363"] = "Facebook",
["6364"] = "163.com Webmail",
["6365"] = "163.com Webmail",
["6383"] = "Sharebox",
["6384"] = "Sharebox",
["6385"] = "Sharebox",
["6386"] = "Sharebox",
["6387"] = "Sharebox",
["6388"] = "Sharebox",
["6389"] = "Sharebox",
["6390"] = "Sharebox",
["6397"] = "Micro Focus GroupWise",
["6398"] = "Micro Focus GroupWise",
["6401"] = "Sharebox",
["6403"] = "Micro Focus GroupWise",
["6405"] = "Novell Client",
["6407"] = "Novell Client",
["6410"] = "Novell Messenger",
["6411"] = "Novell Messenger",
["6413"] = "Sirius XM",
["6414"] = "Canada Revenue Agency",
["6415"] = "H&R Block",
["6416"] = "HMRC.GOV.UK",
["6417"] = "Australian Tax Office",
["6419"] = "Korea National Tax Service",
["6420"] = "Japan National Tax Agency",
["6425"] = "IMO IM",
["6426"] = "Microsoft Outlook.com (Hotmail)",
["6427"] = "OpenSSL Client",
["6431"] = "Wells Fargo Bank",
["6439"] = "OpenOffice",
["6441"] = "Opera",
["6445"] = "RemoteView",
["6446"] = "RemoteView",
["6447"] = "RemoteView",
["6448"] = "RemoteView",
["6449"] = "RemoteView",
["6450"] = "Blinkx.com",
["6452"] = "HotBar",
["6453"] = "ScanQuery",
["6454"] = "Google",
["6455"] = "QDown",
["6456"] = "QDown",
["6457"] = "QDown",
["6461"] = "Afreeca",
["6462"] = "Afreeca",
["6463"] = "Afreeca",
["6465"] = "Afreeca",
["6466"] = "Afreeca",
["6467"] = "Afreeca",
["6470"] = "SoftEther PacketiX",
["6474"] = "SoftEther PacketiX",
["6477"] = "eBuddy",
["6478"] = "eBuddy",
["6479"] = "eBuddy",
["6488"] = "Hangame",
["6489"] = "Hangame",
["6503"] = "Raptr",
["6504"] = "Raptr",
["6507"] = "Raptr",
["6509"] = "Korea.com",
["6510"] = "MPEG",
["6511"] = "Shockwave Flash (SWF)",
["6512"] = "Mgoon.com",
["6513"] = "RealClick",
["6514"] = "Pandora.tv",
["6521"] = "Nate.com",
["6533"] = "Facebook",
["6536"] = "2ch",
["6537"] = "RTP",
["6539"] = "360Safe",
["6540"] = "360Safe",
["6541"] = "DHCP Protocol",
["6542"] = "NTLMSSP",
["6543"] = "DCERPC",
["6544"] = "DCERPC",
["6545"] = "HTTP Protocol",
["6546"] = "HTTP Protocol",
["6547"] = "AFS",
["6549"] = "RTP",
["6550"] = "FTP",
["6551"] = "AFDM",
["6552"] = "LDAP v3",
["6553"] = "ADSelfService",
["6554"] = "ADSelfService",
["6558"] = "ADNStream",
["6560"] = "Adobe Acrobat Connect",
["6561"] = "RTP",
["6562"] = "Adobe Marketing",
["6564"] = "Adobe",
["6566"] = "Adobe Connect",
["6570"] = "Akamai NetSession Interface",
["6572"] = "Akamai NetSession Interface",
["6573"] = "Akamai NetSession Interface",
["6574"] = "Akamai NetSession Interface",
["6575"] = "Alisoft",
["6578"] = "Jackpot Capital",
["6579"] = "Jackpot Capital",
["6580"] = "RTP",
["6581"] = "RTP",
["6582"] = "Jackpot Capital",
["6583"] = "Microsoft BITS",
["6589"] = "RTP",
["6590"] = "RTP",
["6593"] = "RTP",
["6596"] = "HTTP Protocol",
["6597"] = "HTTP Protocol",
["6598"] = "RTP",
["6601"] = "Hulu",
["6602"] = "RTP",
["6603"] = "Netflix",
["6604"] = "RTP",
["6608"] = "RTP",
["6617"] = "RTP",
["6618"] = "Ultrasurf",
["6624"] = "Amazon.com",
["6625"] = "Amazon Web Services",
["6626"] = "Amazon Web Services",
["6627"] = "SoftEther PacketiX",
["6628"] = "SoftEther PacketiX",
["6643"] = "RTP",
["6644"] = "RTP",
["6659"] = "Facebook",
["6661"] = "RTP",
["6663"] = "RTP",
["6665"] = "RTP",
["6666"] = "RTP",
["6668"] = "Facebook",
["6672"] = "Facebook",
["6673"] = "Facebook",
["6674"] = "Facebook",
["6675"] = "Facebook",
["6676"] = "Facebook",
["6679"] = "Facebook",
["6689"] = "Facebook",
["6692"] = "AIM",
["6696"] = "RTP",
["6702"] = "filesend.to",
["6706"] = "Chess.com",
["6732"] = "RTP",
["6733"] = "RTP",
["6740"] = "Google Chat",
["6745"] = "Bypass",
["6746"] = "Bypassthat",
["6747"] = "MouseMatrix.com",
["6754"] = "Google Mail (Gmail)",
["6755"] = "filesend.to",
["6766"] = "2ch",
["6767"] = "Yahoo! Japan",
["6768"] = "Yahoo! Japan",
["6769"] = "Yahoo! Japan",
["6773"] = "2ch",
["6783"] = "Blizzard Entertainment",
["6787"] = "Google Mail (Gmail)",
["6805"] = "Web Conferencing Central",
["6806"] = "SoftEther PacketiX",
["6807"] = "SoftEther PacketiX",
["6810"] = "SoftEther PacketiX",
["6812"] = "SoftEther PacketiX",
["6813"] = "SoftEther PacketiX",
["6817"] = "DNS Protocol",
["6818"] = "DNS Protocol",
["6819"] = "DNS Protocol",
["6820"] = "DNS Protocol",
["6821"] = "DNS Protocol",
["6822"] = "DNS Protocol",
["6823"] = "Digsby",
["6824"] = "Digsby",
["6825"] = "Digsby",
["6826"] = "eMule",
["6827"] = "eMule",
["6828"] = "eMule",
["6842"] = "DNS Protocol",
["6846"] = "Ultrasurf",
["6860"] = "Habbo",
["6862"] = "Meetup",
["6863"] = "MyLife",
["6864"] = "Flixster",
["6866"] = "Skyrock",
["6870"] = "Opera Mini",
["6871"] = "Opera Mini",
["6872"] = "HTTP Protocol",
["6874"] = "Tycoon Online",
["6876"] = "Steam Software",
["6877"] = "Steam Software",
["6878"] = "Steam Software",
["6880"] = "Steam Software",
["6882"] = "Intertops Casino",
["6883"] = "Intertops Casino",
["6884"] = "Intertops Casino",
["6886"] = "Omniture",
["6887"] = "Spore",
["6888"] = "Spore",
["6889"] = "Spore",
["6892"] = "JonDo Proxy",
["6893"] = "Bigpoint Games",
["6894"] = "DarkOrbit",
["6896"] = "Baidu",
["6897"] = "Baidu",
["6908"] = "OCSP",
["6911"] = "httptunnel",
["6913"] = "httptunnel",
["6915"] = "Hopster",
["6917"] = "HTTP-Tunnel",
["6918"] = "HTTP-Tunnel",
["6920"] = "HTTP-Tunnel",
["6921"] = "Facebook",
["6938"] = "SNMP",
["6939"] = "SNMP",
["6940"] = "SNMP",
["6941"] = "Schoology",
["6942"] = "eBay Classifieds",
["6943"] = "Cheap Tickets",
["6944"] = "Chickipedia",
["6945"] = "Mademan",
["6946"] = "Douban",
["6947"] = "Douban",
["6948"] = "Cheap Tickets",
["6949"] = "Drupal",
["6950"] = "Elluminate",
["6951"] = "Blackboard",
["6952"] = "37signals Campfire",
["6957"] = "Tongdaxin",
["6958"] = "Tongdaxin",
["6959"] = "Apple Security",
["6960"] = "Apple Location Service",
["6962"] = "Apple iTunes",
["6963"] = "Apple iTunes",
["6964"] = "Apple Push Notifications",
["6965"] = "Apple Filing Protocol",
["6966"] = "Apple Filing Protocol",
["6967"] = "Apple Updates",
["6968"] = "Apple Bonjour",
["6969"] = "Apple Bonjour",
["6980"] = "Apple iTunes",
["6982"] = "Dongfangcaifutong",
["6983"] = "Dongfangcaifutong",
["6985"] = "Facebook",
["6986"] = "Facebook",
["6987"] = "Facebook",
["6988"] = "Gree.jp",
["6989"] = "Baidu Hi",
["6990"] = "Baidu Hi",
["6992"] = "IBackup",
["6995"] = "56.com",
["6997"] = "Yahoo! Mail",
["7000"] = "Android Dalvik",
["7001"] = "Flurry",
["7002"] = "Citrix",
["7003"] = "Citrix",
["7004"] = "Citrix",
["7008"] = "GoToMyPC",
["7009"] = "Citrix",
["7011"] = "Safari Browser",
["7023"] = "IMR Worldwide",
["7036"] = "Farmville",
["7049"] = "Apple Security",
["7050"] = "Apple Updates",
["7054"] = "Spotify",
["7055"] = "Spotify",
["7056"] = "Avocent",
["7057"] = "Avocent",
["7058"] = "Desknets",
["7063"] = "Taobao",
["7064"] = "Taobao",
["7065"] = "Taobao",
["7067"] = "DeskShare",
["7071"] = "LogMeIn",
["7075"] = "ISL Light",
["7076"] = "Jump Desktop",
["7077"] = "Jump Desktop",
["7078"] = "Jump Desktop",
["7079"] = "Jump Desktop",
["7080"] = "Jump Desktop",
["7082"] = "Jump Desktop",
["7083"] = "Google Talk",
["7094"] = "MyGreenPC",
["7095"] = "MySpace",
["7096"] = "MySpace",
["7100"] = "Tongdaxin",
["7101"] = "Apple iMessage",
["7102"] = "Apple iMessage",
["7105"] = "Google Mail (Gmail)",
["7135"] = "pcvisit Remote",
["7139"] = "NetOp Remote Control",
["7140"] = "NetOp Remote Control",
["7141"] = "NetOp Remote Control",
["7142"] = "NetOp Remote Control",
["7143"] = "NetOp Remote Control",
["7144"] = "NetOp Remote Control",
["7145"] = "NetOp Remote Control",
["7149"] = "pcvisit Remote",
["7150"] = "pcvisit Remote",
["7152"] = "Apple Siri",
["7153"] = "Apple Siri",
["7160"] = "Apple iMessage",
["7166"] = "NTRglobal",
["7167"] = "PhoneMyPC",
["7168"] = "RDM Plus",
["7169"] = "RDM Plus",
["7170"] = "Splashtop Remote Desktop",
["7171"] = "Splashtop Remote Desktop",
["7182"] = "Google Crawler",
["7185"] = "TweetDeck",
["7187"] = "TweetDeck",
["7188"] = "TweetDeck",
["7189"] = "TweetDeck",
["7191"] = "Armagetron",
["7194"] = "Armagetron",
["7195"] = "Electronic Arts",
["7196"] = "Electronic Arts",
["7197"] = "Battlefield",
["7200"] = "Java RMI",
["7201"] = "Battlefield",
["7204"] = "Aliwangwang",
["7212"] = "Cafe World",
["7213"] = "Farmville",
["7215"] = "Executable",
["7216"] = "Executable",
["7217"] = "Executable",
["7218"] = "Mob Wars",
["7219"] = "Zynga Poker",
["7223"] = "Ask.fm",
["7244"] = "Executable",
["7246"] = "Executable",
["7247"] = "Executable",
["7248"] = "Executable",
["7249"] = "Executable",
["7250"] = "Executable",
["7251"] = "Document",
["7252"] = "Document",
["7253"] = "Archive",
["7254"] = "Audio Video Stream",
["7257"] = "Ask.fm",
["7259"] = "Facebook",
["7271"] = "QQ Mail",
["7281"] = "Lockbox",
["7283"] = "Lockbox",
["7284"] = "ShareFile",
["7285"] = "ShareFile",
["7286"] = "Shockwave Flash (SWF)",
["7289"] = "Flash Video (FLV)",
["7290"] = "Baofeng",
["7291"] = "Baofeng",
["7294"] = "Baofeng",
["7300"] = "HTTP Proxy",
["7304"] = "The Weather Channel",
["7322"] = "Foursquare",
["7324"] = "PCAnywhere",
["7325"] = "PCAnywhere",
["7328"] = "PCAnywhere",
["7331"] = "HonghuiNSD",
["7333"] = "Feigechuanshu",
["7340"] = "ooVoo",
["7341"] = "115Udown",
["7342"] = "115Udown",
["7344"] = "Tor",
["7346"] = "Vuze",
["7347"] = "Vuze",
["7348"] = "Azureus",
["7350"] = "BitTorrent Protocol",
["7355"] = "DBank",
["7362"] = "Google Voice",
["7364"] = "Google Chat",
["7373"] = "M1905 Dianyingwang",
["7374"] = "M1905 Dianyingwang",
["7375"] = "M1905 Dianyingwang",
["7426"] = "BitTorrent Protocol",
["7432"] = "Azureus",
["7434"] = "BitTorrent Protocol",
["7437"] = "Azureus",
["7438"] = "Azureus",
["7441"] = "BitTorrent Protocol",
["7442"] = "Google",
["7443"] = "XMPP (Jabber) Protocol",
["7446"] = "Facebook",
["7447"] = "Facebook",
["7448"] = "Facebook",
["7450"] = "TeamViewer",
["7451"] = "TeamViewer",
["7452"] = "TeamViewer",
["7458"] = "BitTorrent Protocol",
["7459"] = "BitTorrent Protocol",
["7460"] = "BitTorrent Protocol",
["7461"] = "BitTorrent Protocol",
["7465"] = "Ultrasurf",
["7518"] = "Microsoft SQL Server",
["7519"] = "Microsoft SQL Server",
["7521"] = "Microsoft Exchange",
["7527"] = "NCAA March Madness",
["7537"] = "NCAA March Madness",
["7538"] = "NCAA March Madness",
["7617"] = "Ocarina",
["7618"] = "Ocarina",
["7619"] = "Microsoft OneDrive",
["7620"] = "Facebook",
["7624"] = "Google Mail (Gmail)",
["7628"] = "Nimbuzz",
["7650"] = "Skype",
["7651"] = "Skype",
["7652"] = "RapidShare",
["7653"] = "RapidShare",
["7654"] = "RapidShare",
["7668"] = "YouTube",
["7681"] = "League of Legends",
["7682"] = "League of Legends",
["7683"] = "League of Legends",
["7684"] = "League of Legends",
["7691"] = "Daum",
["7692"] = "Daum",
["7702"] = "Yoono Desktop",
["7704"] = "Yoono Desktop",
["7713"] = "Instagram",
["7714"] = "Instagram",
["7715"] = "Instagram",
["7716"] = "Instagram",
["7720"] = "CloudFile",
["7733"] = "ShareFile",
["7734"] = "ShareFile",
["7735"] = "ShareFile",
["7737"] = "Google Drive",
["7738"] = "Google Drive",
["7739"] = "Apple Core Media",
["7751"] = "Dictionary.com",
["7753"] = "Dictionary.com",
["7758"] = "CricBuzz",
["7759"] = "CricBuzz",
["7767"] = "Yahoo! Messenger",
["7768"] = "K-Meleon Browser",
["7777"] = "Opera Mini",
["7778"] = "Opera Mini",
["7779"] = "eBuddy",
["7780"] = "YouTube",
["7781"] = "PacketVideo",
["7784"] = "Jackpot Capital",
["7785"] = "Hulu",
["7786"] = "Hulu",
["7787"] = "Hulu",
["7788"] = "StrongVPN",
["7789"] = "StrongVPN",
["7790"] = "StrongVPN",
["7791"] = "StrongVPN",
["7792"] = "StrongVPN",
["7793"] = "StrongVPN",
["7794"] = "Witopia VPN",
["7795"] = "Witopia VPN",
["7796"] = "Witopia VPN",
["7797"] = "IMO IM",
["7798"] = "IMO IM",
["7799"] = "Pinterest",
["7800"] = "Pinterest",
["7801"] = "Pinterest",
["7802"] = "Quora",
["7803"] = "Quora",
["7804"] = "Uber",
["7805"] = "Uber",
["7806"] = "Uber",
["7807"] = "TaskRabbit",
["7808"] = "TaskRabbit",
["7809"] = "TaskRabbit",
["7810"] = "Airbnb",
["7811"] = "Airbnb",
["7812"] = "Airbnb",
["7814"] = "Skillshare",
["7815"] = "Skillshare",
["7816"] = "Getaround",
["7817"] = "Getaround",
["7818"] = "Airtime",
["7819"] = "Airtime",
["7820"] = "Path",
["7821"] = "Path",
["7822"] = "Path",
["7823"] = "Square",
["7824"] = "Square",
["7825"] = "Square",
["7826"] = "Square",
["7827"] = "Pinwheel",
["7828"] = "Pinwheel",
["7829"] = "Pinwheel",
["7836"] = "QQ File Transfer",
["7837"] = "IMO IM",
["7838"] = "IMO IM",
["7840"] = "WhatsApp Messenger",
["7841"] = "WhatsApp Messenger",
["7846"] = "Psiphon",
["7853"] = "ISAKMP",
["7857"] = "Mail.com",
["7858"] = "Mail.com",
["7859"] = "Mail.com",
["7860"] = "Mail.com",
["7861"] = "TVB",
["7862"] = "TVB",
["7863"] = "EdgeSuite",
["7864"] = "Serving-Sys",
["7865"] = "Acuity Platform",
["7866"] = "Ad Server Plus",
["7867"] = "Adsonar",
["7868"] = "CPX Interactive",
["7869"] = "SayMedia",
["7870"] = "Casale Media",
["7871"] = "Betr Ad",
["7872"] = "Double Verify",
["7873"] = "Optimizely",
["7874"] = "Optimax Media Delivery",
["7875"] = "Atwola",
["7876"] = "Admailtiser",
["7877"] = "Criteo",
["7878"] = "CMP Advisors",
["7879"] = "United Internet Media",
["7880"] = "eXelate Media",
["7881"] = "Adsrvr",
["7882"] = "Casale Media",
["7883"] = "Site Scout",
["7884"] = "RealMedia",
["7885"] = "Google Analytics",
["7887"] = "AOL Advertising",
["7888"] = "eyeReturn Marketing",
["7889"] = "Ministerial5",
["7890"] = "Super Sonic Ads",
["7891"] = "AppNexus",
["7892"] = "MediaMath",
["7893"] = "Media Innovation Group",
["7894"] = "Eq Ads",
["7895"] = "BlueKai Research",
["7896"] = "BlueKai Research",
["7898"] = "AppNexus",
["7899"] = "Ministerial5",
["7900"] = "DoubleClick",
["7901"] = "AdTech",
["7902"] = "PointRoll",
["7903"] = "ABMR",
["7904"] = "Chango Marketing",
["7905"] = "ADGRX",
["7906"] = "Adnetik",
["7907"] = "Aggregrate Knowledge",
["7908"] = "Accuen Media",
["7909"] = "Turn Advertising",
["7910"] = "Adsafe Media",
["7911"] = "Media6Degrees",
["7912"] = "ooVoo",
["7913"] = "ooVoo",
["7914"] = "ooVoo",
["7926"] = "SSL",
["7927"] = "SSL",
["7929"] = "ExpatShield",
["7930"] = "ExpatShield",
["7936"] = "TextPlus",
["7937"] = "TextPlus",
["7939"] = "ExpatShield",
["7940"] = "ExpatShield",
["7948"] = "Mozy Online Backup",
["7949"] = "Mozy Online Backup",
["7950"] = "Mozy Online Backup",
["7951"] = "Mozy Online Backup",
["7992"] = "Xunlei Thunder",
["7999"] = "Xunlei Thunder",
["8055"] = "Yahoo! Mail",
["8061"] = "The Weather Channel",
["8062"] = "The Weather Channel",
["8063"] = "Google Translate",
["8090"] = "Zinio",
["8091"] = "Zinio",
["8092"] = "Viber",
["8093"] = "Viber",
["8094"] = "Shazam",
["8104"] = "NateOn",
["8105"] = "NateOn",
["8137"] = "Blizzard Entertainment",
["8138"] = "Blizzard Entertainment",
["8168"] = "Banjo",
["8178"] = "Banjo",
["8179"] = "Banjo",
["8190"] = "Zynga With Friends",
["8191"] = "Zynga With Friends",
["8192"] = "Zynga With Friends",
["8193"] = "Words With Friends",
["8196"] = "Voxer",
["8197"] = "Voxer",
["8199"] = "Voxer",
["8254"] = "IMDb",
["8255"] = "IMDb",
["8337"] = "SocialCam",
["8338"] = "SocialCam",
["8339"] = "Google Analytics",
["8343"] = "Olympic Games",
["8344"] = "Olympic Games",
["8350"] = "Craigslist",
["8360"] = "LinkedIn",
["8363"] = "SoundHound",
["8364"] = "SoundHound",
["8366"] = "SoundHound",
["8394"] = "Olympic Games",
["8395"] = "Olympic Games",
["8408"] = "Olympic Games",
["8410"] = "Olympic Games",
["8411"] = "CNTV",
["8412"] = "CNTV",
["8413"] = "War Commander",
["8415"] = "Olympic Games",
["8438"] = "Ammyy Admin",
["8445"] = "Audio Video Stream",
["8449"] = "TuneIn Radio",
["8450"] = "TuneIn Radio",
["8451"] = "TuneIn Radio",
["8452"] = "TuneIn Radio",
["8453"] = "TuneIn Radio",
["8454"] = "TuneIn Radio",
["8455"] = "TuneIn Radio",
["8456"] = "TuneIn Radio",
["8458"] = "Amazon.com",
["8459"] = "Amazon.com",
["8460"] = "Amazon.com",
["8462"] = "Tango",
["8463"] = "Tango",
["8464"] = "Tango",
["8465"] = "Tango",
["8466"] = "Tango",
["8468"] = "Tango",
["8469"] = "Tango",
["8471"] = "FTP",
["8480"] = "Apple iCloud",
["8481"] = "Apple iCloud",
["8494"] = "Google Maps",
["8495"] = "Google Maps",
["8496"] = "eBay",
["8505"] = "Facebook",
["8506"] = "Apple Mac.com",
["8507"] = "Apple Mac.com",
["8510"] = "WebDAV",
["8511"] = "WebDAV",
["8512"] = "WebDAV",
["8513"] = "WebDAV",
["8514"] = "WebDAV",
["8515"] = "WebDAV",
["8516"] = "WebDAV",
["8528"] = "NateOn",
["8540"] = "NateOn",
["8541"] = "NateOn",
["8544"] = "NateOn",
["8557"] = "Database File",
["8559"] = "Archive",
["8560"] = "Audio Video Stream",
["8561"] = "Document",
["8562"] = "Archive",
["8563"] = "Archive",
["8564"] = "Archive",
["8566"] = "Archive",
["8567"] = "Audio Video Stream",
["8570"] = "Image",
["8571"] = "Archive",
["8572"] = "Document",
["8573"] = "Image",
["8574"] = "Image",
["8575"] = "Image",
["8576"] = "Image",
["8579"] = "Dell Kace",
["8580"] = "Dell Kace",
["8583"] = "Dell Kace",
["8584"] = "LINE",
["8585"] = "LINE",
["8586"] = "LINE",
["8587"] = "The Pirate Bay",
["8592"] = "Minecraft",
["8593"] = "Minecraft",
["8596"] = "FTP",
["8597"] = "SMTP",
["8598"] = "SMTP",
["8599"] = "Google Play",
["8600"] = "Google Play",
["8601"] = "Google Play",
["8602"] = "Google Play",
["8603"] = "LinkedIn",
["8606"] = "IMAP",
["8608"] = "Box",
["8609"] = "Box",
["8610"] = "Box",
["8611"] = "Box",
["8617"] = "Tor",
["8652"] = "TextMe",
["8658"] = "CCTV",
["8676"] = "Qvod",
["8681"] = "Image",
["8682"] = "Image",
["8684"] = "Facebook",
["8685"] = "Facebook",
["8687"] = "DropSend",
["8688"] = "DropSend",
["8689"] = "DropSend",
["8690"] = "DropSend",
["8691"] = "YouTube",
["8692"] = "YouTube",
["8693"] = "LINE",
["8694"] = "LINE",
["8695"] = "LINE",
["8701"] = "TheBestKeylogger.com",
["8711"] = "New York Times Online",
["8741"] = "Spotflux",
["8742"] = "Spotflux",
["8756"] = "Spotflux",
["8759"] = "Spotflux",
["9009"] = "QQ",
["9165"] = "QQ File Transfer",
["9175"] = "QQ File Transfer",
["9192"] = "WhatsApp Messenger",
["9193"] = "QQ",
["9203"] = "Xunlei Thunder",
["9217"] = "QQGame",
["9223"] = "Electronic Arts",
["9224"] = "Electronic Arts",
["9225"] = "Electronic Arts",
["9226"] = "Electronic Arts",
["9227"] = "Electronic Arts",
["9228"] = "Electronic Arts",
["9234"] = "Xunlei Thunder",
["9235"] = "Xunlei Thunder",
["9247"] = "Dell SonicWALL CDP",
["9248"] = "Dell SonicWALL CDP",
["9249"] = "Dell SonicWALL CDP",
["9255"] = "YouTube",
["9256"] = "YouTube",
["9257"] = "YouTube",
["9260"] = "Scotty Transporter",
["9262"] = "Sina Weibo",
["9263"] = "Tencent Weibo",
["9264"] = "Tencent Weibo",
["9265"] = "Tianya Weibo",
["9266"] = "Tianya Weibo",
["9267"] = "Sohu Weibo",
["9268"] = "Sohu Weibo",
["9270"] = "GAppProxy",
["9271"] = "GAppProxy",
["9274"] = "PPStream",
["9275"] = "PPStream",
["9276"] = "PPStream",
["9277"] = "PPStream",
["9278"] = "PPStream",
["9279"] = "GAppProxy",
["9280"] = "Win2Day.be",
["9281"] = "Win2Day.be",
["9282"] = "Win2Day.be",
["9283"] = "Xunlei Thunder",
["9286"] = "Google Plus",
["9288"] = "163.com Webmail",
["9290"] = "Facebook",
["9327"] = "Executable",
["9335"] = "Apple Inc",
["9336"] = "Apple Maps",
["9338"] = "Dell SonicWALL Endpoint Security",
["9343"] = "Single Click Connect",
["9344"] = "Single Click Connect",
["9369"] = "Zook",
["9370"] = "Zook",
["9375"] = "Google Talk",
["9376"] = "Google Talk",
["9377"] = "Google Talk",
["9378"] = "Google Talk",
["9379"] = "Google",
["9380"] = "Google Mail (Gmail)",
["9383"] = "Google Docs",
["9384"] = "Google Docs",
["9388"] = "Document",
["9389"] = "Document",
["9390"] = "Document",
["9391"] = "Document",
["9392"] = "Document",
["9394"] = "Document",
["9395"] = "Executable",
["9397"] = "Executable",
["9398"] = "Executable",
["9400"] = "SMB",
["9401"] = "SMB2",
["9402"] = "SMB2",
["9405"] = "Executable",
["9406"] = "Executable",
["9407"] = "Executable",
["9408"] = "Executable",
["9409"] = "Document",
["9410"] = "Document",
["9411"] = "Document",
["9412"] = "Document",
["9413"] = "Document",
["9414"] = "Document",
["9415"] = "Document",
["9416"] = "Document",
["9417"] = "Document",
["9418"] = "Document",
["9421"] = "Document",
["9422"] = "Document",
["9423"] = "Document",
["9424"] = "Document",
["9425"] = "Document",
["9426"] = "Document",
["9427"] = "Document",
["9428"] = "Document",
["9429"] = "Document",
["9430"] = "Document",
["9432"] = "Document",
["9433"] = "Document",
["9434"] = "Document",
["9435"] = "Document",
["9439"] = "Document",
["9440"] = "Document",
["9443"] = "Document",
["9455"] = "Zook",
["9459"] = "Alicall",
["9460"] = "Alicall",
["9461"] = "Alicall",
["9462"] = "Alicall",
["9463"] = "McAfee",
["9464"] = "McAfee",
["9475"] = "Puffin Browser",
["9476"] = "Microsoft MSN Messenger",
["9477"] = "Microsoft MSN Messenger",
["9478"] = "Private Internet Access VPN",
["9479"] = "Haofang",
["9480"] = "Puffin Browser",
["9481"] = "Pandora Radio",
["9482"] = "Pandora Radio",
["9483"] = "Pandora Radio",
["9484"] = "Private Internet Access VPN",
["9485"] = "Private Internet Access VPN",
["9516"] = "Tongchengdapai",
["9518"] = "Tongchengdapai",
["9521"] = "Qvod",
["9522"] = "Qvod",
["9530"] = "Qvod",
["9534"] = "Liushuitongcheng",
["9535"] = "Liushuitongcheng",
["9536"] = "Liushuitongcheng",
["9537"] = "Qvod",
["9539"] = "Qvod",
["9553"] = "Tuenti Social Messenger",
["9554"] = "Tuenti Social Messenger",
["9565"] = "GO SMS",
["9566"] = "GO SMS",
["9567"] = "GO SMS",
["9568"] = "GO SMS",
["9572"] = "Baidu Yun",
["9573"] = "Baidu Yun",
["9577"] = "Sanguolaile",
["9578"] = "Sanguolaile",
["9624"] = "OpenVPN",
["9625"] = "OpenVPN",
["9628"] = "OpenVPN",
["9672"] = "Facebook",
["9678"] = "PC-over-IP Remote Desktop",
["9681"] = "PC-over-IP Remote Desktop",
["9685"] = "HTTP Proxy",
["9686"] = "Ivacy VPN",
["9687"] = "SnapChat",
["9689"] = "SnapChat",
["9690"] = "SnapChat",
["9691"] = "IMAP",
["9692"] = "IMAP",
["9693"] = "SquirrelMail",
["9710"] = "Chrome Remote Desktop",
["9713"] = "Chrome Remote Desktop",
["9714"] = "Chrome Remote Desktop",
["9719"] = "Chrome Remote Desktop",
["9720"] = "Chrome Remote Desktop",
["9721"] = "Chrome Remote Desktop",
["9727"] = "RTP",
["9772"] = "Giganews",
["9773"] = "Giganews",
["9808"] = "Google Drive",
["9809"] = "Google Drive",
["9812"] = "FTP",
["9813"] = "H.323 Protocols",
["9814"] = "SIP",
["9823"] = "Facebook",
["9862"] = "Sophos",
["9863"] = "Vine",
["9864"] = "Vine",
["9865"] = "Vine",
["9868"] = "KProxy",
["9878"] = "SMTP",
["9880"] = "IMAP",
["9882"] = "IMAP",
["9883"] = "POP",
["9910"] = "Apple FaceTime",
["10000"] = "VMware",
["10001"] = "VMware",
["10002"] = "GameDay Central",
["10003"] = "Yahoo!",
["10004"] = "Yahoo! Mail",
["10064"] = "Executable",
["10065"] = "Executable",
["10066"] = "TeamViewer",
["10067"] = "OpenDoor",
["10072"] = "Mail.ru",
["10073"] = "Join Me",
["10074"] = "Join Me",
["10076"] = "Kaspersky AV",
["10077"] = "Kaspersky AV",
["10078"] = "Microsoft OneDrive",
["10079"] = "Kakao Talk",
["10080"] = "iHeartRadio",
["10081"] = "iHeartRadio",
["10082"] = "iHeartRadio",
["10083"] = "iHeartRadio",
["10084"] = "iHeartRadio",
["10085"] = "iHeartRadio",
["10086"] = "iHeartRadio",
["10087"] = "iHeartRadio",
["10088"] = "iHeartRadio",
["10090"] = "Microsoft Skype for Business",
["10091"] = "Microsoft Skype for Business",
["10092"] = "Bitvise SSH (Tunnelier)",
["10093"] = "Bitvise SSH (Tunnelier)",
["10094"] = "Kaspersky AV",
["10095"] = "Secretbook",
["10096"] = "SSH Protocol",
["10097"] = "SSH Protocol",
["10098"] = "FriendVox",
["10099"] = "100Bao",
["10100"] = "AbelCam",
["10101"] = "AbelCam",
["10104"] = "ADrive",
["10105"] = "ADrive",
["10106"] = "appleJuice",
["10107"] = "appleJuice",
["10110"] = "Archive",
["10111"] = "Archive",
["10112"] = "Gladinet",
["10113"] = "Gladinet",
["10114"] = "Glide",
["10115"] = "WeTransfer",
["10116"] = "Kakao Talk",
["10117"] = "Kakao Talk",
["10118"] = "Kik Messenger",
["10119"] = "Kik Messenger",
["10120"] = "Kik Messenger",
["10121"] = "Candy Crush Saga",
["10122"] = "Candy Crush Saga",
["10123"] = "NFL (National Football League)",
["10124"] = "NFL (National Football League)",
["10125"] = "NFL (National Football League)",
["10126"] = "Samsung SmartTV",
["10127"] = "Samsung SmartTV",
["10128"] = "Samsung SmartTV",
["10129"] = "Amazon Prime Video",
["10130"] = "Hulu",
["10131"] = "Burp Proxy",
["10132"] = "Apple iTunes Radio",
["10133"] = "TextMe",
["10134"] = "Apple iTunes Radio",
["10135"] = "Apple iTunes Radio",
["10136"] = "Box",
["10137"] = "iQiyi",
["10138"] = "iQiyi",
["10139"] = "iQiyi",
["10140"] = "iQiyi",
["10141"] = "LeTV.com",
["10142"] = "LeTV.com",
["10143"] = "LeTV.com",
["10144"] = "LeTV.com",
["10145"] = "WeChat",
["10146"] = "WeChat",
["10147"] = "PPLive (PPTV)",
["10148"] = "Onavo VPN",
["10149"] = "Onavo VPN",
["10150"] = "Tumblr.com",
["10151"] = "Tumblr.com",
["10152"] = "ZenMate SSLVPN Proxy",
["10154"] = "MyPeople Messenger",
["10155"] = "MyPeople Messenger",
["10156"] = "MyPeople Messenger",
["10157"] = "Kakao Talk",
["10161"] = "IBVPN",
["10162"] = "IBVPN",
["10163"] = "IBVPN",
["10164"] = "IBVPN",
["10165"] = "IBVPN",
["10166"] = "Dash VPN",
["10167"] = "Dash VPN",
["10168"] = "IBVPN",
["10177"] = "SnapChat",
["10178"] = "AppSpot",
["10179"] = "AppSpot",
["10180"] = "Audio Video Stream",
["10181"] = "Audio Video Stream",
["10198"] = "Secret.ly",
["10199"] = "Secret.ly",
["10201"] = "LinkedIn",
["10207"] = "QQ",
["10208"] = "QQ",
["10209"] = "Apple Daily News",
["10210"] = "Apple Daily News",
["10211"] = "Apple Daily News",
["10212"] = "QQ",
["10213"] = "QQ",
["10214"] = "QQ",
["10215"] = "QQ",
["10227"] = "Yik Yak",
["10228"] = "Yik Yak",
["10230"] = "WebSocket",
["10231"] = "Talking Angela",
["10232"] = "Talking Angela",
["10233"] = "Google Mail (Gmail)",
["10234"] = "Google Mail (Gmail)",
["10235"] = "Google Chrome Data Compression Proxy",
["10236"] = "Google Chrome Data Compression Proxy",
["10243"] = "GetPrivate VPN",
["10244"] = "GetPrivate VPN",
["10245"] = "BeamYourScreen",
["10248"] = "Wattpad",
["10249"] = "Zoom.us",
["10253"] = "YouTube",
["10257"] = "SurfEasy",
["10261"] = "Octoshape",
["10266"] = "Octoshape",
["10267"] = "Octoshape",
["10268"] = "Octoshape",
["10269"] = "Microsoft Internet Explorer",
["10270"] = "Microsoft Internet Explorer",
["10271"] = "Microsoft Internet Explorer",
["10272"] = "Microsoft Internet Explorer",
["10273"] = "Microsoft Internet Explorer",
["10274"] = "Microsoft Internet Explorer",
["10275"] = "Microsoft Internet Explorer",
["10281"] = "Blackberry AppWorld",
["10282"] = "Blackberry AppWorld",
["10283"] = "Blackberry AppWorld",
["10284"] = "HTTP User-Agent",
["10285"] = "HTTP User-Agent",
["10286"] = "HTTP User-Agent",
["10287"] = "HTTP User-Agent",
["10288"] = "HTTP User-Agent",
["10289"] = "HTTP User-Agent",
["10290"] = "HTTP User-Agent",
["10291"] = "HTTP User-Agent",
["10292"] = "HTTP User-Agent",
["10293"] = "HTTP User-Agent",
["10294"] = "HTTP User-Agent",
["10295"] = "HTTP User-Agent",
["10297"] = "HTTP User-Agent",
["10298"] = "HTTP User-Agent",
["10299"] = "HTTP User-Agent",
["10300"] = "HTTP User-Agent",
["10310"] = "Supercell Games",
["10311"] = "Executable",
["10312"] = "Executable",
["10313"] = "Microsoft App Store",
["10314"] = "Microsoft App Store",
["10315"] = "Zoho",
["10316"] = "HP JetDirect Protocol",
["10317"] = "IMVU",
["10318"] = "Tor",
["10323"] = "Hotspot Shield VPN",
["10325"] = "Hotspot Shield VPN",
["10326"] = "Hotspot Shield VPN",
["10330"] = "Psiphon",
["10363"] = "Amazon Cloud Drive",
["10364"] = "Amazon Cloud Drive",
["10366"] = "Microsoft App Store",
["10367"] = "Yahoo! UK EuroSport",
["10374"] = "Supercell Games",
["10376"] = "Supercell Games",
["10377"] = "Supercell Games",
["10378"] = "Supercell Games",
["10379"] = "Supercell Games",
["10380"] = "Xunlei Thunder",
["10381"] = "Xunlei Thunder",
["10382"] = "Dovecot rfc822_parse_domain Out of B...",
["10383"] = "VPN Express",
["10384"] = "ExpressVPN",
["10388"] = "TVB",
["10398"] = "Google Drive",
["10400"] = "Microsoft Outlook Web Access",
["10403"] = "Google Drive",
["10406"] = "Evernote",
["10407"] = "Kakao Talk",
["10408"] = "Kakao Talk",
["10409"] = "Kakao Talk",
["10410"] = "Kakao Talk",
["10411"] = "Kakao Talk",
["10412"] = "Evernote",
["10418"] = "Evernote",
["10419"] = "Evernote",
["10430"] = "TunnelBear VPN",
["10431"] = "TunnelBear VPN",
["10443"] = "Tor",
["10454"] = "Xunlei Thunder",
["10464"] = "Ddooo Download",
["10473"] = "Ddooo Download",
["10481"] = "LINE",
["10482"] = "Xunlei Thunder",
["10484"] = "BIOS Agent Plus",
["10485"] = "CCleaner",
["10486"] = "CCleaner",
["10487"] = "YouTube Downloader",
["10490"] = "Google Talk",
["10491"] = "WeChat",
["10492"] = "WeChat",
["10495"] = "WeChat",
["10500"] = "TunnelBear VPN",
["10501"] = "Ngrok",
["10502"] = "Ngrok",
["10503"] = "NTRglobal",
["10507"] = "YouTube",
["10508"] = "YouTube",
["10512"] = "Facebook",
["10515"] = "Psiphon",
["10517"] = "Psiphon",
["10518"] = "Tinder",
["10519"] = "Tinder",
["10520"] = "Google API",
["10521"] = "Google API",
["10522"] = "NTRglobal",
["10524"] = "PD-Proxy",
["10527"] = "GNU Debugger",
["10535"] = "Puffin Browser",
["10536"] = "Facebook",
["10537"] = "Facebook",
["10538"] = "Amazon CloudFront",
["10539"] = "PD-Proxy",
["10553"] = "OpenDoor",
["10555"] = "vShare",
["10557"] = "Ultrasurf",
["10558"] = "QQGame",
["10563"] = "Microsoft Office 365",
["10564"] = "Microsoft Office 365",
["10565"] = "Microsoft Office 365",
["10566"] = "Microsoft Office 365",
["10568"] = "Yik Yak",
["10569"] = "Microsoft Office 365",
["10570"] = "Microsoft Office 365",
["10571"] = "Microsoft Office 365",
["10572"] = "Microsoft Office 365",
["10573"] = "Microsoft Office 365",
["10574"] = "Yik Yak",
["10575"] = "Yik Yak",
["10585"] = "QQGame",
["10592"] = "Yahoo!",
["10604"] = "Browsec",
["10609"] = "Bingbot Crawler",
["10614"] = "Yik Yak",
["10615"] = "Whisper",
["10616"] = "Whisper",
["10617"] = "Whisper",
["10618"] = "Whisper",
["10625"] = "Yahoo! Messenger",
["10627"] = "Yahoo! Messenger",
["10630"] = "Dropbox",
["10631"] = "Dropbox",
["10632"] = "Flash VPN",
["10633"] = "Flash VPN",
["10634"] = "Flash VPN",
["10637"] = "Spotify",
["10638"] = "Spotify",
["10639"] = "VPN In Touch",
["10640"] = "VPN In Touch",
["10641"] = "VPN In Touch",
["10642"] = "Hola Free VPN",
["10643"] = "Hola Free VPN",
["10644"] = "Hideman VPN",
["10645"] = "Hideman VPN",
["10646"] = "Hideman VPN",
["10647"] = "VPN One Click",
["10649"] = "VPN One Click",
["10651"] = "JonDo Proxy",
["10652"] = "JonDo Proxy",
["10656"] = "Ahrefs",
["10657"] = "Ahrefs",
["10660"] = "SEMrush",
["10661"] = "SEMrush",
["10662"] = "SEMrush",
["10663"] = "VPN proXPN",
["10664"] = "VPN proXPN",
["10665"] = "VPN proXPN",
["10669"] = "Browsec",
["10670"] = "Backblaze",
["10671"] = "After School",
["10675"] = "Microsoft OneDrive",
["10678"] = "YouTube",
["10679"] = "Wickr",
["10680"] = "Wickr",
["10681"] = "Faceless VPN",
["10682"] = "Faceless VPN",
["10683"] = "GoBrowse VPN",
["10684"] = "GoBrowse VPN",
["10685"] = "GoBrowse VPN",
["10688"] = "GreenVPN",
["10689"] = "GreenVPN",
["10690"] = "PureVPN",
["10691"] = "PureVPN",
["10692"] = "PureVPN",
["10693"] = "Astrill VPN",
["10694"] = "Astrill VPN",
["10697"] = "Younited",
["10698"] = "Younited",
["10699"] = "Younited",
["10700"] = "Psiphon",
["10704"] = "HMA VPN",
["10705"] = "HMA VPN",
["10710"] = "ITV Video Playback",
["10711"] = "ITV Video Playback",
["10712"] = "VPN Unlimited",
["10713"] = "VPN Unlimited",
["10714"] = "VPN Unlimited",
["10715"] = "OverPlay VPN",
["10716"] = "OverPlay VPN",
["10721"] = "Akamai CDN",
["10722"] = "Akamai CDN",
["10723"] = "CloudFlare CDN",
["10725"] = "WeChat",
["10738"] = "WeChat",
["10742"] = "Secret.ly",
["10749"] = "MubasherTrade",
["10750"] = "MubasherTrade",
["10759"] = "DotVPN",
["10760"] = "DotVPN",
["10761"] = "SSTP VPN",
["10763"] = "SSTP VPN",
["10764"] = "SSTP VPN",
["10765"] = "SSTP VPN",
["10767"] = "Soulseek",
["10768"] = "Soulseek",
["10773"] = "Soulseek",
["10774"] = "Soulseek",
["10780"] = "Dotloop",
["10782"] = "AliveChat",
["10796"] = "HBO",
["10797"] = "HBO",
["10798"] = "HBO",
["10799"] = "HBO",
["10815"] = "Executable",
["10817"] = "I2P",
["10820"] = "I2P",
["10821"] = "I2P",
["10822"] = "Fastly CDN",
["10834"] = "Meerkat",
["10835"] = "Meerkat",
["10836"] = "ClashofClans Game",
["10839"] = "Supercell Games",
["10840"] = "ClashofClans Game",
["10841"] = "ClashofClans Game",
["10852"] = "Xunlei Thunder",
["10871"] = "Chrome Remote Desktop",
["10872"] = "CommVault",
["10873"] = "CommVault",
["10874"] = "CommVault",
["10875"] = "Google QUIC",
["10876"] = "Google QUIC",
["10879"] = "VPN Defender",
["10880"] = "VPN Defender",
["10881"] = "VPN Defender",
["10882"] = "VPN Defender",
["10912"] = "BitTorrent Protocol",
["10913"] = "UC Browser",
["10914"] = "UC Browser",
["10915"] = "UC Browser",
["10916"] = "TunnelBear VPN",
["10921"] = "UC Browser",
["10922"] = "UC Browser",
["10938"] = "Google Play",
["10939"] = "Google Play",
["10942"] = "League of Legends",
["10943"] = "League of Legends",
["10976"] = "Google Hangouts",
["10989"] = "Google Pay",
["10990"] = "Google Hangouts",
["10991"] = "Dropbox",
["10992"] = "iHeartRadio",
["10998"] = "Ultrasurf",
["10999"] = "Ultrasurf",
["11043"] = "Microsoft Outlook.com (Hotmail)",
["11046"] = "Microsoft OneDrive",
["11051"] = "Facebook",
["11052"] = "SSL",
["11114"] = "GomVPN",
["11115"] = "GomVPN",
["11128"] = "DotVPN",
["11149"] = "Hotspot Shield VPN",
["11152"] = "Psiphon",
["11155"] = "skyZIP Proxy",
["11183"] = "Crashplan",
["11212"] = "Twitter",
["11213"] = "Twitter",
["11217"] = "Facebook",
["11226"] = "Psiphon",
["11241"] = "WeChat",
["11270"] = "Photon Browser",
["11271"] = "Photon Browser",
["11272"] = "Photon Browser",
["11273"] = "Photon Browser",
["11274"] = "HTTP User-Agent",
["11275"] = "WeChat",
["11280"] = "Malwarebytes",
["11281"] = "Malwarebytes",
["11294"] = "WordPress",
["11296"] = "VK",
["11298"] = "Tmall",
["11305"] = "After School",
["11306"] = "Wish App",
["11307"] = "Wish App",
["11308"] = "Wish App",
["11311"] = "Shockwave Flash (SWF)",
["11312"] = "Audio Video Stream",
["11313"] = "NetEase PoPo",
["11332"] = "The Proxy Bay",
["11334"] = "Open Whisper Systems Signal",
["11335"] = "Open Whisper Systems Signal",
["11336"] = "Open Whisper Systems Signal",
["11337"] = "Sunrise Calendar",
["11338"] = "Sunrise Calendar",
["11340"] = "Feedly",
["11341"] = "Telegram Messenger",
["11342"] = "Telegram Messenger",
["11343"] = "WhatsApp Messenger",
["11344"] = "VPN In Touch",
["11345"] = "Macroplant DocHub",
["11348"] = "360 Yunpan",
["11349"] = "360 Yunpan",
["11350"] = "360 Yunpan",
["11351"] = "360 Yunpan",
["11352"] = "360 Yunpan",
["11353"] = "QQ Weiyun",
["11354"] = "QQ Weiyun",
["11355"] = "QQ Weiyun",
["11357"] = "Thinfinity Remote Desktop Server",
["11359"] = "Hide.me VPN",
["11360"] = "Hide.me VPN",
["11361"] = "NordVPN",
["11362"] = "NordVPN",
["11364"] = "Apple Push Notifications",
["11365"] = "WeChat",
["11366"] = "WeChat",
["11367"] = "NordVPN",
["11368"] = "NordVPN",
["11369"] = "DocuSign",
["11374"] = "Tumblr.com",
["11403"] = "Flipboard",
["11404"] = "Flipboard",
["11406"] = "Facebook",
["11407"] = "Facebook",
["11408"] = "Facebook",
["11412"] = "LastPass",
["11416"] = "Facebook",
["11419"] = "Apple Updates",
["11420"] = "Baidu Pan",
["11421"] = "Baidu Yun",
["11429"] = "Hiworks",
["11430"] = "Hiworks",
["11433"] = "Daoki",
["11434"] = "Daoki",
["11437"] = "Baidu Yun",
["11438"] = "Baidu Yun",
["11440"] = "Baidu Pan",
["11441"] = "Baidu Pan",
["11442"] = "Psiphon",
["11460"] = "BetternetVPN",
["11461"] = "BetternetVPN",
["11462"] = "BetternetVPN",
["11472"] = "BetternetVPN",
["11473"] = "Steam Software",
["11474"] = "Steam Software",
["11482"] = "Ark VPN",
["11484"] = "Cloud VPN",
["11486"] = "Cloud VPN",
["11510"] = "SuperVPN",
["11520"] = "OpenVPN",
["11521"] = "WorldofTanks",
["11522"] = "WorldofTanks",
["11526"] = "Boom Beach",
["11527"] = "Private Tunnel VPN",
["11529"] = "WhatsApp Messenger",
["11530"] = "8BallPool",
["11531"] = "8BallPool",
["11534"] = "EvilApples",
["11535"] = "EvilApples",
["11537"] = "Blendoku",
["11538"] = "Blendoku",
["11542"] = "Dirtybit",
["11545"] = "Noodlecake",
["11561"] = "YouTube Downloader",
["11571"] = "Epic Browser Proxy",
["11572"] = "Epic Browser Proxy",
["11574"] = "QQ",
["11577"] = "QQ",
["11580"] = "QQ",
["11600"] = "Supercell Games",
["11601"] = "Supercell Games",
["11602"] = "FreeMyBrowser",
["11603"] = "SecureVPN",
["11604"] = "SecureVPN",
["11605"] = "SecureVPN",
["11612"] = "Tactile Wars",
["11614"] = "Zoom.us",
["11616"] = "Zoom.us",
["11618"] = "Fields of Battle",
["11620"] = "PacMan",
["11623"] = "Asphalt8",
["11624"] = "Asphalt8",
["11625"] = "Twitch",
["11639"] = "Dococab",
["11643"] = "YouTube",
["11644"] = "YouTube",
["11646"] = "YouTube",
["11649"] = "JustProxy VPN",
["11657"] = "Google News",
["11666"] = "YouTube Downloader",
["11672"] = "Google Drive",
["11674"] = "BitTorrent Protocol",
["11675"] = "Microsoft Office 365",
["11676"] = "BitTorrent Protocol",
["11677"] = "BitTorrent Protocol",
["11678"] = "BitTorrent Protocol",
["11679"] = "BitTorrent Protocol",
["11680"] = "Salesforce",
["11681"] = "Salesforce",
["11687"] = "YouTube Downloader",
["11688"] = "YouTube Downloader",
["11689"] = "Dococab",
["11691"] = "YouTube Downloader",
["11693"] = "Microsoft Outlook.com (Hotmail)",
["11694"] = "Microsoft Outlook.com (Hotmail)",
["11695"] = "Microsoft Outlook.com (Hotmail)",
["11696"] = "Microsoft Outlook.com (Hotmail)",
["11697"] = "Microsoft Outlook.com (Hotmail)",
["11700"] = "iHeartRadio",
["11701"] = "iHeartRadio",
["11702"] = "iHeartRadio",
["11703"] = "HTTP Proxy",
["11710"] = "Connectify",
["11715"] = "Connectify",
["11730"] = "Pokemon Go",
["11731"] = "Pokemon Go",
["11732"] = "Pokemon Go",
["11733"] = "Pokemon Go",
["11738"] = "AddThis.com",
["11743"] = "Reddit",
["11744"] = " AlienBlue",
["11750"] = " Jumpshare",
["11751"] = " Jumpshare",
["11758"] = "Agar.io",
["11762"] = "Zoosk",
["11763"] = "Zoosk",
["11765"] = "IFTTT",
["11772"] = "Microsoft Windows Updates",
["11803"] = "Mega.nz",
["11807"] = "Mega.nz",
["11808"] = "Mega.nz",
["11809"] = "Mega.nz",
["11819"] = "Google Chrome",
["11820"] = "GroupMe",
["11821"] = "GroupMe",
["11826"] = "Hawkeye VPN",
["11827"] = "Hawkeye VPN",
["11828"] = "Hawkeye VPN",
["11829"] = "Opera Free VPN",
["11830"] = "Opera Free VPN",
["11831"] = "Opera Free VPN",
["11832"] = "Opera Free VPN",
["11833"] = "Golden Key VPN",
["11862"] = "ZeroVPN",
["11872"] = "Facebook",
["11873"] = "Facebook",
["11912"] = "Google Drive",
["11913"] = "ISAKMP",
["11918"] = "VPN Master",
["11924"] = "VPN Master",
["11928"] = "Neat Scanner",
["11930"] = "Neat Scanner",
["11976"] = "ZeroVPN",
["11977"] = "ZeroVPN",
["11978"] = "ZeroVPN",
["11984"] = "ZeroVPN",
["11986"] = "ZeroVPN",
["11989"] = "VPN Master",
["11990"] = "GlobusVPN",
["11991"] = "GlobusVPN",
["11993"] = "Turbo VPN",
["11994"] = "Invisible Net VPN",
["11995"] = "Invisible Net VPN",
["11996"] = "HotVPN",
["11997"] = "FreeVPN",
["12000"] = "Walmart",
["12501"] = "Walmart",
["12503"] = "Cross Web Server",
["12550"] = "Yelp",
["12551"] = "Yelp",
["12552"] = "Yelp",
["12553"] = "Lyft",
["12554"] = "Lyft",
["12572"] = "Ultrahook",
["12596"] = "WhatsApp Messenger",
["12604"] = "Psiphon",
["12636"] = "AnyDesk Remote Desktop",
["12640"] = "BitTorrent Protocol",
["12645"] = "SetupVPN",
["12659"] = "Foxtel",
["12661"] = "Foxtel",
["12680"] = "ConnectWise Control ScreenConnect",
["12681"] = "ConnectWise Control ScreenConnect",
["12684"] = "Apple iCloud",
["12686"] = "SoundCloud",
["12687"] = "SoundCloud",
["12695"] = "Confide Messenger",
["12734"] = "STUN",
["12736"] = "Mastodon",
["12746"] = "LeapFILE",
["12747"] = "LeapFILE",
["12748"] = "Tmall",
["12750"] = "Suning.com",
["12752"] = "Hupu.com",
["12753"] = "Mixi",
["12754"] = "Twinavi.jp",
["12755"] = "Ameba Pigg",
["12756"] = "Ameba Pigg",
["12757"] = "Rakuten Ichiba",
["12758"] = "Amazon.co.jp",
["12759"] = "Amazon.co.jp",
["12760"] = "GMarket.co.kr",
["12761"] = "11st.co.kr",
["12762"] = "11st.co.kr",
["12763"] = "GS Shop",
["12764"] = "GS Shop",
["12819"] = "BetternetVPN",
["12824"] = "SnapChat",
["12825"] = "SnapChat",
["12871"] = "Aspera FASP Protocol",
["12872"] = "Aspera FASP Protocol",
["12874"] = "Aspera FASP Protocol",
["12875"] = "LINE",
["12876"] = "LINE",
["12894"] = "Signiant",
["12922"] = "FTP",
["12923"] = "FTP",
["12926"] = "Sarahah",
["12927"] = "Sarahah",
["12931"] = "Hexatech VPN",
["12932"] = "Hexatech VPN",
["12933"] = "Hexatech VPN",
["12939"] = "Archive",
["12940"] = "Archive",
["12956"] = "Incognito VPN",
["12957"] = "Incognito VPN",
["12986"] = "HTTP Protocol",
["12989"] = "HTTP Protocol",
["12990"] = "HTTP Protocol",
["12991"] = "HTTP Protocol",
["12996"] = "Gracenote",
["12997"] = "Plex TV",
["12998"] = "WhatsApp Messenger",
["12999"] = "WhatsApp Messenger",
["13000"] = "Yahoo! Messenger",
["13021"] = "QQ",
["13026"] = "QQ",
["13027"] = "QQ",
["13038"] = "QQ",
["13039"] = "Dingding",
["13040"] = "Dingding",
["13042"] = "Dingding",
["13053"] = "QQ",
["13054"] = "Discord",
["13055"] = "Discord",
["13077"] = "WhatsApp Messenger",
["13078"] = "WhatsApp Messenger",
["13079"] = "WhatsApp Messenger",
["13081"] = "WhatsApp Messenger",
["13082"] = "WhatsApp Messenger",
["13083"] = "WhatsApp Messenger",
["13086"] = "Telegram Messenger",
["13087"] = "QQ",
["13098"] = "MinerGate",
["13099"] = "SuperVPN",
["13100"] = "SuperVPN",
["13129"] = "SuperVPN",
["13130"] = "SuperVPN",
["13131"] = "SuperVPN",
["13132"] = "SuperVPN",
["13144"] = "BACnet Protocol",
["13146"] = "SnapChat",
["13150"] = "CODESYS",
["13153"] = "WeChat",
["13167"] = "SuperVPN",
["13168"] = "SuperVPN",
["13181"] = "ShareFile",
["13183"] = "Coinhive Monero Miner",
["13184"] = "Coinhive Monero Miner",
["13185"] = "Coinhive Monero Miner",
["13186"] = "RingOver",
["13195"] = "Hoxx VPN",
["13197"] = "Wikipedia",
["13198"] = "Executable",
["13208"] = "CODESYS",
["13209"] = "CODESYS",
["13210"] = "CODESYS",
["13211"] = "CODESYS",
["13212"] = "CODESYS",
["13215"] = "Microsoft Windows Updates",
["13216"] = "Microsoft Windows Updates",
["13217"] = "Amazon Prime Video",
["13218"] = "Amazon Prime Video",
["13219"] = "Amazon Prime Video",
["13220"] = "Amazon Prime Video",
["13241"] = "DNP3",
["13242"] = "EtherNet/IP",
["13243"] = "EtherNet/IP",
["13244"] = "EtherNet/IP",
["13247"] = "Browsec",
["13249"] = "ISAKMP",
["13252"] = "SAIA ETHER S-BUS",
["13253"] = "ETHERSIO",
["13255"] = "OMRON-FINS",
["13256"] = "OMRON-FINS",
["13259"] = "Hexatech VPN",
["13264"] = "iWASEL VPN",
["13265"] = "iWASEL VPN",
["13267"] = "RingOver",
["13268"] = "RingOver",
["13269"] = "RingOver",
["13278"] = "Google Mail (Gmail)",
["13285"] = "EpicGames",
["13288"] = "QQ",
["13289"] = "QQ",
["13290"] = "QQ",
["13291"] = "QQ",
["13296"] = "HART-IP",
["13297"] = "HART-IP",
["13298"] = "HART-IP",
["13299"] = "WebSocket",
["13300"] = "WebSocket",
["13302"] = "IEC 61850",
["13303"] = "PC_WORX",
["13304"] = "ISO-TSAP",
["13305"] = "ISO-TSAP",
["13306"] = "ISO-TSAP",
["13307"] = "S7comm",
["13308"] = "S7comm",
["13337"] = "Cisco Meeting Server",
["13380"] = "Houseparty (LOA)",
["13381"] = "Houseparty (LOA)",
["13404"] = "PP VPN",
["13405"] = "PP VPN",
["13438"] = "Executable",
["13439"] = "Executable",
["13440"] = "Wikipedia",
["13441"] = "YouTube",
["13445"] = "Alpemix VNC",
["13446"] = "Alpemix VNC",
["13447"] = "Alpemix VNC",
["13450"] = "Alpemix VNC",
["13451"] = "Alpemix VNC",
["13467"] = "ADP",
["13468"] = "American Bar Association Journal",
["13469"] = "American Bar Association",
["13470"] = "American Express Inc",
["13471"] = "American Express Inc",
["13472"] = "AutoNews",
["13473"] = "BBC",
["13475"] = "BerkeleyEdu",
["13476"] = "Bank of America",
["13477"] = "Bank of America",
["13478"] = "Box",
["13479"] = "Business Insider",
["13480"] = "BusinessWire",
["13481"] = "CNBC",
["13482"] = "CNBC",
["13483"] = "CNBC",
["13484"] = "CNBC",
["13485"] = "CNN News",
["13486"] = "Chase Bank",
["13488"] = "Concur Solutions",
["13489"] = "Construction Dive",
["13490"] = "Dailymotion",
["13491"] = "Dailymotion",
["13492"] = "Dailymotion",
["13493"] = "DocuSign",
["13494"] = "DocuSign",
["13495"] = "eBay",
["13496"] = "eBay",
["13497"] = "eBay",
["13498"] = "eBay",
["13499"] = "EducationNews",
["13500"] = "IMDb",
["13501"] = "Investopedia",
["13502"] = "Instagram",
["13503"] = "Light Reading",
["13504"] = "Light Reading",
["13505"] = "Dow Jones Co",
["13506"] = "Dow Jones Co",
["13507"] = "Marketwatch",
["13509"] = "Wall Street Journal",
["13510"] = "Wall Street Journal",
["13511"] = "News Corp",
["13512"] = "News Corp",
["13515"] = "MayoClinic",
["13516"] = "Medical News",
["13517"] = "Morningstar",
["13518"] = "Morningstar",
["13519"] = "NOAA",
["13520"] = "National Geographic",
["13521"] = "National Geographic",
["13522"] = "ServiceNow",
["13524"] = "Netflix",
["13525"] = "Netflix",
["13526"] = "Netflix",
["13527"] = "Network World",
["13528"] = "Microsoft Office 365",
["13530"] = "Microsoft Office 365",
["13531"] = "Microsoft SharePoint",
["13532"] = "Microsoft SharePoint",
["13533"] = "Microsoft",
["13534"] = "Microsoft",
["13535"] = "Reddit",
["13536"] = "OneLogin",
["13537"] = "Slack",
["13538"] = "Slack",
["13539"] = "Yelp",
["13540"] = "Yelp",
["13541"] = "Wikipedia",
["13542"] = "Trello",
["13543"] = "Tumblr.com",
["13544"] = "NOAA",
["13545"] = "WebMD",
["13546"] = "UCLA",
["13547"] = "WhatsApp Messenger",
["13548"] = "Vimeo",
["13549"] = "Vimeo",
["13550"] = "Google",
["13551"] = "Taobao",
["13552"] = "Tmall",
["13553"] = "Amazon.com",
["13554"] = "Twitter",
["13555"] = "Sohu",
["13556"] = "JD.com",
["13557"] = "VK",
["13558"] = "Sina Weibo",
["13559"] = "360 Yunpan",
["13560"] = "Google",
["13561"] = "Google",
["13562"] = "Google",
["13563"] = "Google",
["13567"] = "BBC iPlayer",
["13568"] = "BBC iPlayer",
["13569"] = "BBC",
["13570"] = "BBC",
["13571"] = "XING",
["13572"] = "XING",
["13573"] = "XING",
["13577"] = "BBC iPlayer",
["13580"] = "Amazon Prime Music",
["13581"] = "Amazon Prime Music",
["13582"] = "EpicGames",
["13583"] = "EpicGames Fortnite",
["13584"] = "EpicGames Fortnite",
["13585"] = "EpicGames",
["13589"] = "Google Mail (Gmail)",
["13590"] = "Google Mail (Gmail)",
["13607"] = "Twitch",
["13608"] = "Twitch",
["13609"] = "Twitch",
["13610"] = "Twitch",
["13611"] = "Twitch",
["13612"] = "Twitch",
["13620"] = "Microsoft Store",
["13621"] = "Microsoft Store",
["13622"] = "Microsoft Store",
["13627"] = "X-VPN",
["13629"] = "X-VPN",
["13645"] = "Coinhive Monero Miner",
["13646"] = "Coinhive Monero Miner",
["13647"] = "Coinhive Monero Miner",
["13853"] = "Microsoft Edge",
["13855"] = "Microsoft Office 365",
["13856"] = "Microsoft Skype for Business",
["13857"] = "Microsoft Office 365",
["13859"] = "Microsoft Skype for Business",
["13860"] = "Microsoft Skype for Business",
["13861"] = "Microsoft Skype for Business",
["13862"] = "Microsoft Skype for Business",
["13863"] = "Microsoft Skype for Business",
["13864"] = "Microsoft Skype for Business",
["13865"] = "Microsoft Skype for Business",
["13866"] = "Microsoft Office 365",
["13867"] = "Microsoft Office 365",
["13868"] = "Microsoft Office 365",
["13869"] = "Microsoft Office 365",
["13870"] = "Microsoft Skype for Business",
["13871"] = "Microsoft Skype for Business",
["13872"] = "Microsoft Skype for Business",
["13873"] = "STUN",
["13893"] = "SIP",
["13894"] = "Ring Central",
["13895"] = "Ring Central",
["13896"] = "Ring Central",
["13897"] = "Ring Central",
["13901"] = "Google Meet",
["13902"] = "Google Meet",
["13903"] = "Microsoft Teams",
["13904"] = "Microsoft Teams",
["13905"] = "ServiceNow",
["13906"] = "Microsoft OneNote",
["13907"] = "Microsoft OneNote",
["13908"] = "Microsoft Outlook.com (Hotmail)",
["13909"] = "Microsoft Yammer",
["13920"] = "Google Translate",
["13921"] = "Google Calendar",
["13922"] = "Google Photos",
["13923"] = "ExpressVPN",
["13927"] = "STUN",
["13928"] = "STUN",
["13942"] = "RTP",
["13953"] = "Microsoft Skype for Business",
["13969"] = "SIP",
["13970"] = "SIP",
["13971"] = "SIP",
["13972"] = "SIP",
["13987"] = "X-VPN",
["13988"] = "X-VPN",
["13989"] = "X-VPN",
["13990"] = "X-VPN",
["13991"] = "X-VPN",
["13992"] = "Hola Free VPN",
["14007"] = "YogaVPN",
["14008"] = "YogaVPN",
["49152"] = "Firewall management",
["49153"] = "General Broadcast",
["49154"] = "General Multicast",
["49155"] = "General Unicast",
["49156"] = "General Subnet broadcast",
["49157"] = "General PPTP control",
["49158"] = "General PPTP data",
["49159"] = "General RAS control",
["49160"] = "General RAS data",
["49161"] = "General Oracle data",
["49162"] = "General Oracle data",
["49163"] = "General RT stream",
["49164"] = "General SIP stream",
["49165"] = "General NETBIOS",
["49166"] = "General IKE",
["49167"] = "General EMAIL",
["49168"] = "General DHCP",
["49169"] = "General DNS",
["49170"] = "General FTP control",
["49171"] = "General FTP data",
["49172"] = "General GOPHER",
["49173"] = "General H323 control",
["49174"] = "General H323 media",
["49175"] = "General HTTP",
["49176"] = "General HTTP MGMT",
["49177"] = "General HTTPS",
["49178"] = "General HTTPS MGMT",
["49179"] = "General LDAP",
["49180"] = "General MSN",
["49181"] = "General MSN media",
["49182"] = "General NETBIOS",
["49183"] = "General NNTP",
["49184"] = "General NTP",
["49185"] = "General POP3",
["49186"] = "General RADIUS",
["49187"] = "General RIP",
["49188"] = "General RTSP control",
["49189"] = "General RTSP media",
["49190"] = "General SIP control",
["49191"] = "General SIP media",
["49192"] = "General SMTP",
["49193"] = "General SNMP",
["49194"] = "General SNMP Trap",
["49195"] = "General SSH",
["49196"] = "General SYSLOG",
["49197"] = "General Telnet",
["49198"] = "General Tftp",
["49199"] = "General Tftp data",
["49200"] = "General URL",
["49201"] = "General TCP",
["49202"] = "General UDP",
["49203"] = "General ICMP",
["49204"] = "General IGMP",
["49205"] = "General GRE",
["49206"] = "General IPSEC ESP",
["49207"] = "General IPSEC AH",
["49208"] = "General OSPF",
["49209"] = "General PIM SM",
["49210"] = "General EIGRP",
["49211"] = "General IPCOMP",
["49212"] = "General 6to4",
["49213"] = "General IPinIP",
["49214"] = "General ETHERinIP",
["49215"] = "General VRRP",
["49216"] = "General L2TP",
["49217"] = "General RSVP",
["49218"] = "General FiberChannel",
["49219"] = "General MPLSinIP",
["49220"] = "General LLMNR",
["49221"] = "Service HTTP",
["49222"] = "Service HTTP Management",
["49223"] = "Service HTTPS",
["49224"] = "Service HTTPS Management",
["49225"] = "Service HTTPS Redirect",
["49226"] = "Service RADIUS Accounting",
["49227"] = "Service SSO 3rd-Party API",
["49228"] = "Service IDENT",
["49229"] = "Service IMAP3",
["49230"] = "Service IMAP4",
["49231"] = "Service ISAKMP",
["49232"] = "Service LDAP",
["49233"] = "Service LDAP (UDP)",
["49234"] = "Service LDAPS",
["49235"] = "Service LPR (Unix Printer)",
["49236"] = "Service Megaco H.248 TCP",
["49237"] = "Service Megaco Text H.248 UDP",
["49238"] = "Service Megaco Binary H.248 UDP",
["49239"] = "Service MS SQL",
["49240"] = "Service NNTP (News)",
["49241"] = "Service NTP",
["49242"] = "Service POP3 (Retrieve E-Mail)",
["49243"] = "Service Terminal Services TCP",
["49244"] = "Service Terminal Services UDP",
["49245"] = "Service PPTP",
["49246"] = "Service SMTP (Send E-Mail)",
["49247"] = "Service SNMP",
["49248"] = "Service SQL*Net",
["49249"] = "Service SSH",
["49250"] = "Service Telnet",
["49251"] = "Service TFTP",
["49252"] = "Service Citrix TCP",
["49253"] = "Service Citrix TCP (Session Reliability)",
["49254"] = "Service Citrix UDP",
["49255"] = "Service IRC (Chat) 194",
["49256"] = "Service IRC (Chat) 6666-6670",
["49257"] = "Service IRC (Chat) 7000",
["49258"] = "Service DNS (Name Service) TCP",
["49259"] = "Service DNS (Name Service) UDP",
["49260"] = "Service Enhanced TV",
["49261"] = "Service ESP (IPSec)",
["49262"] = "Service FTP",
["49263"] = "Service FTP Data",
["49264"] = "Service FTP Control",
["49265"] = "Service Gopher",
["49266"] = "Service IKE (Key Exchange)",
["49267"] = "Service IKE (Traversal)",
["49268"] = "Service Lotus Notes",
["49269"] = "Service Echo Reply",
["49270"] = "Service Destination Unreachable",
["49271"] = "Service Source Quench",
["49272"] = "Service Redirect",
["49273"] = "Service Echo",
["49274"] = "Service Router Advertisement",
["49275"] = "Service Router Solicitation",
["49276"] = "Service Time Exceeded",
["49277"] = "Service Ping 0",
["49278"] = "Service Ping 8",
["49279"] = "Service Kerberos TCP",
["49280"] = "Service Kerberos UDP",
["49281"] = "Service NetBios NS TCP",
["49282"] = "Service NetBios NS UDP",
["49283"] = "Service NetBios DGM TCP",
["49284"] = "Service NetBios DGM UDP",
["49285"] = "Service NetBios SSN TCP",
["49286"] = "Service NetBios SSN UDP",
["49287"] = "Service SMB",
["49288"] = "Service NFS TCP",
["49289"] = "Service NFS UDP",
["49290"] = "Service Syslog TCP",
["49291"] = "Service Syslog UDP",
["49292"] = "Service SIP UDP",
["49293"] = "Service SIP TCP",
["49294"] = "Service H323 Call Signaling",
["49295"] = "Service H323 Gatekeeper Discovery",
["49296"] = "Service H323 Gatekeeper RAS",
["49297"] = "Service MGCP TCP",
["49298"] = "Service MGCP UDP",
["49299"] = "Service Skinny",
["49300"] = "Service T120 (Whiteboard+A43)",
["49301"] = "Service PC Anywhere TCP",
["49302"] = "Service PC Anywhere UDP",
["49303"] = "Service Timbuktu TCP 407",
["49304"] = "Service Timbuktu UDP 407",
["49305"] = "Service Timbuktu TCP 1417-1420",
["49306"] = "Service Timbuktu UDP 1419",
["49307"] = "Service RTSP TCP",
["49308"] = "Service RTSP UDP",
["49309"] = "Service PNA",
["49310"] = "Service MMS TCP",
["49311"] = "Service MMS UDP",
["49312"] = "Service MSN TCP",
["49313"] = "Service MSN UDP",
["49314"] = "Service Squid",
["49315"] = "Service Yahoo Messenger TCP",
["49316"] = "Service Yahoo Messenger UDP",
["49317"] = "Service VNC 5500",
["49318"] = "Service VNC 5800",
["49319"] = "Service VNC 5900",
["49320"] = "Service Remotely Anywhere",
["49321"] = "Service Remotely Possible",
["49322"] = "Service Quake",
["49323"] = "Service cu-seeme",
["49324"] = "Service Edonkey TCP",
["49325"] = "Service Edonkey UDP",
["49326"] = "Service WinMX TCP 6699",
["49327"] = "Service WinMX TCP 7729-7735",
["49328"] = "Service WinMX UDP 6257",
["49329"] = "Service Kazaa / FastTrack",
["49330"] = "Service iMesh",
["49331"] = "Service Direct Connect",
["49332"] = "Service BearShare",
["49333"] = "Service ZebTelnet",
["49334"] = "Service Membership Query",
["49335"] = "Service V2 Membership Report",
["49336"] = "Service Leave Group",
["49337"] = "Service V3 Membership Report",
["49338"] = "Service GMS HTTPS",
["49339"] = "Service Radius",
["49340"] = "Service GSCTrace",
["49341"] = "Service SSH Management",
["49342"] = "Service NT Domain Login Port 1025",
["49343"] = "Service DCE EndPoint",
["49344"] = "Service External Guest Authentication",
["49345"] = "Service ShoreTel Call Control",
["49346"] = "Service ShoreTel RTP",
["49347"] = "Service ShoreTel IP Phone Control 2427",
["49348"] = "Service ShoreTel IP Phone Control 2727",
["49349"] = "Service Tivo TCP Beacon",
["49350"] = "Service Tivo UDP Beacon",
["49351"] = "Service Tivo TCP Data",
["49352"] = "Service Tivo TCP Desktop (8101/8102)",
["49353"] = "Service Tivo TCP Desktop (8200)",
["49354"] = "Service IPcomp",
["49355"] = "Service Apple Bonjour",
["49356"] = "Service SMTP (Anti-Spam Inbound Port)",
["49357"] = "Service SSLVPN",
["49358"] = "Service SonicpointN Layer3 Management",
["49359"] = "Service SonicWALL Console Proxy",
["49360"] = "Service BGP",
["49361"] = "Service 6over4",
["49362"] = "Service Host Name Server TCP",
["49363"] = "Service Host Name Server UDP",
["49364"] = "Service NetBios TCP",
["49365"] = "Service NetBios UDP",
["49366"] = "Service RPC Services",
["49367"] = "Service RPC Services (IANA)",
["49368"] = "Service DRP",
["49369"] = "Service NetFlow / IPFIX",
["49370"] = "Service Rip",
["49371"] = "Service Destination Unreachable (IPv6)",
["49372"] = "Service Packet Too Big",
["49373"] = "Service Time Exceeded (IPv6)",
["49374"] = "Service Parameter Problem",
["49375"] = "Service Echo (IPv6)",
["49376"] = "Service Echo Reply (IPv6)",
["49377"] = "Service Router Solicitation (IPv6)",
["49378"] = "Service Router Advertisement (IPv6)",
["49379"] = "Service Neighbor Solicitation",
["49380"] = "Service Neighbor Advertisement",
["49381"] = "Service Redirect (IPv6)",
["49382"] = "Service Ping6 128",
["49383"] = "Service Ping6 129",
["49384"] = "Service GRE",
["49385"] = "Service Comm Dst Host Admin Prohibited",
["49386"] = "Service Dst Network Unreachable",
["49387"] = "Service Dst Host Unreachable",
["49388"] = "Service Communication Admin Prohibited",
["49389"] = "Service Redr Datagram for the Host",
["49390"] = "Service Redr Datagram for Service and Network",
["49391"] = "Service Redr Datagram for Service and Host",
["49392"] = "Service Fragment Reassembly Time Exceeded",
["49393"] = "Service Parameter Problem(IPv4)",
["49394"] = "Service Missing a Required Option",
["49395"] = "Service Bad Length",
["49396"] = "Service Timestamp",
["49397"] = "Service Timestamp Reply",
["49398"] = "Service Information Request",
["49399"] = "Service Information Reply",
["49400"] = "Service Address Mask Request",
["49401"] = "Service Address Mask Reply",
["49402"] = "Service Traceroute",
["49403"] = "Service Datagram Conversion Error",
["49404"] = "Service Mobile Host Redirect",
["49405"] = "Service Mobile Registration Request",
["49406"] = "Service Mobile Registration Reply",
["49407"] = "Service Commu Dstination Admin Prohibited",
["49408"] = "Service Beyond Scope of Source Address",
["49409"] = "Service Address Unreachable",
["49410"] = "Service Port Unreachable (IPv6)",
["49411"] = "Service Src Address Failed Ingress Egress",
["49412"] = "Service Reject Route to Destination",
["49413"] = "Service Error in Source Routing Header",
["49414"] = "Service Frgm Reassembly Time Exceeded (IPv6)",
["49415"] = "Service Unrecg Next Header Type Encount",
["49416"] = "Service Unrecg IPv6 Operation Encount",
["49417"] = "Service Multicast Listener Query (IPv6)",
["49418"] = "Service Multicast Listener Report (IPv6)",
["49419"] = "Service Multicast Listener Done (IPv6)",
["49420"] = "Service Router Renumbering (IPv6)",
["49421"] = "Service Router Renumbering Result (IPv6)",
["49422"] = "Service Sequence Number Reset (IPv6)",
["49423"] = "Service ICMP Node Information Query (IPv6)",
["49424"] = "Service contain empty name (IPv6)",
["49425"] = "Service contain IPv4 address (IPv6)",
["49426"] = "Service ICMP Node Information Response (IPv6)",
["49427"] = "Service Responder refuses (IPv6)",
["49428"] = "Service Qtype of the Query is unknown (IPv6)",
["49429"] = "Service Inverse Neighbor Discovery Solicitation Message (IPv6)",
["49430"] = "Service Inverse Neighbor Discovery Advertisement Message (IPv6)",
["49431"] = "Service Version 2 Multicast Listener Report (IPv6)",
["49432"] = "Service Home Agent Address Discovery Request Message (IPv6)",
["49433"] = "Service Home Agent Address Discovery Reply Message (IPv6)",
["49434"] = "Service Mobile Prefix Solicitation (IPv6)",
["49435"] = "Service Mobile Prefix Advertisement (IPv6)",
["49436"] = "Service Certification Path Solicitation Message (IPv6)",
["49437"] = "Service Certification Path Advertisement Msg (IPv6)",
["49438"] = "Service ICMP messages utilized (IPv6)",
["49439"] = "Service Multicast Router Advertisement (IPv6)",
["49440"] = "Service Multicast Router Solicitation (IPv6)",
["49441"] = "Service Multicast Router Termination (IPv6)",
["49442"] = "Service FMIPv6 Messages (IPv6)",
["49443"] = "Service RPL Control Message (IPv6)",
["49444"] = "Service Alternative Address for Host",
}
}
-- ################################################################################
function sonicwall.map_field_value(ifid, field_type, value)
if type_value_map[field_type] and type_value_map[field_type][value] then
value = type_value_map[field_type][value]
end
if type_map[field_type] then
field_type = type_map[field_type]
end
return field_type, value
end
-- ################################################################################
return sonicwall
| gpl-2.0 |
Frenzie/koreader | frontend/ui/elements/screen_eink_opt_menu_table.lua | 8 | 1220 | local Device = require("device")
local _ = require("gettext")
local Screen = Device.screen
local eink_settings_table = {
text = _("E-ink settings"),
sub_item_table = {
{
text = _("Use smaller panning rate"),
checked_func = function() return Screen.low_pan_rate end,
callback = function()
Screen.low_pan_rate = not Screen.low_pan_rate
G_reader_settings:saveSetting("low_pan_rate", Screen.low_pan_rate)
end,
},
require("ui/elements/flash_ui"),
require("ui/elements/flash_keyboard"),
{
text = _("Avoid mandatory black flashes in UI"),
checked_func = function() return G_reader_settings:isTrue("avoid_flashing_ui") end,
callback = function()
G_reader_settings:flipNilOrFalse("avoid_flashing_ui")
end,
},
},
}
if Device:hasEinkScreen() then
table.insert(eink_settings_table.sub_item_table, 1, require("ui/elements/refresh_menu_table"))
if (Screen.wf_level_max or 0) > 0 then
table.insert(eink_settings_table.sub_item_table, require("ui/elements/waveform_level"))
end
end
return eink_settings_table
| agpl-3.0 |
Mike325/.vim | lua/utils/windows.lua | 1 | 8008 | local nvim = require 'neovim'
local set_autocmd = require('neovim.autocmds').set_autocmd
local M = {}
local function autowipe(win, buffer)
vim.validate { window = { win, 'number' }, buffer = { buffer, 'number' } }
set_autocmd {
event = { 'WinClosed' },
pattern = win,
cmd = ('lua if vim.api.nvim_buf_is_valid(%s) then vim.api.nvim_buf_delete(%s, {force=true}) end'):format(
buffer,
buffer
),
group = 'AutoCloseWindow',
once = true,
nested = true,
}
end
local function close_on_move(win, buffer)
vim.validate { window = { win, 'number' } }
set_autocmd {
event = { 'CursorMoved' },
pattern = ('<buffer=%s>'):format(buffer or vim.api.nvim_get_current_buf()),
cmd = ('lua if vim.api.nvim_win_is_valid(%s) then vim.api.nvim_win_close(%s, true) end'):format(
win,
win
),
group = 'AutoCloseWindow',
once = true,
nested = true,
}
end
local function close_on_leave(win, buffer)
vim.validate { window = { win, 'number' } }
if win then
set_autocmd {
event = { 'WinLeave' },
pattern = win,
cmd = ('lua if vim.api.nvim_win_is_valid(%s) then vim.api.nvim_win_close(%s, true) end'):format(
win,
win
),
group = 'AutoCloseWindow',
once = true,
nested = true,
}
end
if buffer then
set_autocmd {
event = { 'BufLeave' },
pattern = ('<buffer=%s>'):format(buffer),
cmd = ('lua if vim.api.nvim_win_is_valid(%s) then vim.api.nvim_win_close(%s, true) end'):format(
win,
win
),
group = 'AutoCloseWindow',
once = true,
nested = true,
}
end
end
function M.big_center(buffer)
assert(
not buffer or (type(buffer) == type(0) and buffer >= 0),
debug.traceback('Invalid buffer: ' .. vim.inspect(buffer))
)
local columns = vim.opt.columns:get()
local lines = vim.opt.lines:get()
local height_percentage = 10 / 100
local width_percentage = 5 / 100
if not buffer then
-- create a new, scratch buffer, for fzf
buffer = vim.api.nvim_create_buf(false, true)
vim.api.nvim_buf_set_option(buffer, 'buftype', 'nofile')
end
-- if the editor is big enough
if columns > 100 or lines > 35 then
-- fzf's window height is 3/4 of the max height, but not more than 70
local win_height = math.min(math.ceil(lines * 3 / 4), 70)
local win_width = (columns < 100) and math.ceil(columns - 8) or math.ceil(columns * 0.9)
-- create a new floating window, centered in the editor
local win = vim.api.nvim_open_win(buffer, true, {
style = 'minimal',
border = 'rounded',
relative = 'editor',
row = math.ceil(lines * height_percentage),
col = math.ceil(columns * width_percentage),
width = win_width,
height = win_height,
noautocmd = true,
focusable = true,
zindex = 10,
})
return win
else
error(debug.traceback 'Current neovim window is too small')
end
end
function M.progress(buffer)
assert(
not buffer or (type(buffer) == type(0) and buffer >= 0),
debug.traceback('Invalid buffer: ' .. vim.inspect(buffer))
)
local columns = vim.opt.columns:get()
local lines = vim.opt.lines:get()
local scratch = false
if not buffer then
buffer = vim.api.nvim_create_buf(false, true)
scratch = true
end
if not vim.t.progress_win then
vim.t.progress_win = vim.api.nvim_open_win(buffer, false, {
style = 'minimal',
border = 'rounded',
relative = 'win',
anchor = 'SW',
row = lines - 5,
col = 2,
-- bufpos = {lines/2, 15},
height = 15,
width = columns - 5,
noautocmd = true,
focusable = true,
zindex = 1, -- very low priority
})
set_autocmd {
event = 'WinClosed',
pattern = vim.t.progress_win,
cmd = 'unlet t:progress_win',
group = 'JobProgress',
once = true,
}
if scratch then
autowipe(vim.t.progress_win, buffer)
end
else
nvim.win.set_buf(vim.t.progress_win, buffer)
end
return vim.t.progress_win
end
function M.cursor_window(buffer, auto_size)
assert(
not buffer or (type(buffer) == type(0) and buffer >= 0),
debug.traceback('Invalid buffer: ' .. vim.inspect(buffer))
)
-- local columns = vim.opt.columns:get()
-- local lines = vim.opt.lines:get()
-- local current_win = vim.api.nvim_get_current_win()
-- local current_buf = vim.api.nvim_buf_get_name(vim.api.nvim_get_current_buf())
local scratch = false
local win_width = 80
local win_height = math.ceil(win_width / 5)
if not buffer then
buffer = vim.api.nvim_create_buf(false, true)
scratch = true
elseif auto_size then
local lines = vim.api.nvim_buf_get_lines(buffer, 0, -1, false)
local width = 0
for _, line in ipairs(lines) do
if #line > width then
width = #line
end
end
win_width = width <= 150 and width or 150
win_height = #lines <= 15 and #lines or 15
end
local win = vim.api.nvim_open_win(buffer, false, {
style = 'minimal',
border = 'rounded',
relative = 'cursor',
anchor = 'SW',
col = 0,
row = -2,
height = win_height,
width = win_width,
-- noautocmd = true,
focusable = true,
zindex = 10,
})
close_on_move(win)
close_on_leave(win, buffer)
if scratch then
autowipe(win, buffer)
end
return win
end
function M.input(opts, on_confirm)
vim.validate {
opts = { opts, 'table' },
on_confirm = { on_confirm, 'function' },
}
-- local columns = vim.opt.columns:get()
-- local lines = vim.opt.lines:get()
-- local current_win = vim.api.nvim_get_current_win()
-- local current_buf = vim.api.nvim_buf_get_name(vim.api.nvim_get_current_buf())
local buffer = vim.api.nvim_create_buf(false, true)
local win_width = 30
local win_height = 1
local win = vim.api.nvim_open_win(buffer, true, {
style = 'minimal',
border = 'rounded',
relative = 'cursor',
anchor = 'SW',
col = 0,
row = -1,
height = win_height,
width = win_width,
-- noautocmd = true,
focusable = true,
zindex = 10,
})
autowipe(win, buffer)
close_on_leave(win, buffer)
set_autocmd {
event = { 'BufWipeout', 'BufUnload', 'BufLeave', 'BufWinLeave' },
pattern = ('<buffer=%s>'):format(buffer),
cmd = 'stopinsert',
group = 'AutoCloseWindow',
once = true,
nested = true,
}
vim.keymap.set({ 'i', 'n' }, '<ESC>', function()
if vim.api.nvim_win_is_valid(win) then
vim.api.nvim_win_close(win, true)
end
if on_confirm then
on_confirm()
end
end, { silent = true, buffer = buffer, nowait = true })
vim.keymap.set({ 'i', 'n' }, '<CR>', function()
local result
if vim.api.nvim_win_is_valid(win) then
vim.api.nvim_win_close(win, true)
end
if vim.api.nvim_buf_is_valid(win) then
result = vim.api.nvim_buf_get_lines(buffer, 0, -1, false)[1]
end
if on_confirm then
on_confirm(result)
end
end, { silent = true, buffer = buffer, nowait = true })
nvim.ex.startinsert()
return win
end
return M
| mit |
sonoro1234/cimgui | generator/output/impl_definitions.lua | 1 | 34701 | local defs = {}
defs["ImGui_ImplGlfw_CharCallback"] = {}
defs["ImGui_ImplGlfw_CharCallback"][1] = {}
defs["ImGui_ImplGlfw_CharCallback"][1]["args"] = "(GLFWwindow* window,unsigned int c)"
defs["ImGui_ImplGlfw_CharCallback"][1]["argsT"] = {}
defs["ImGui_ImplGlfw_CharCallback"][1]["argsT"][1] = {}
defs["ImGui_ImplGlfw_CharCallback"][1]["argsT"][1]["name"] = "window"
defs["ImGui_ImplGlfw_CharCallback"][1]["argsT"][1]["type"] = "GLFWwindow*"
defs["ImGui_ImplGlfw_CharCallback"][1]["argsT"][2] = {}
defs["ImGui_ImplGlfw_CharCallback"][1]["argsT"][2]["name"] = "c"
defs["ImGui_ImplGlfw_CharCallback"][1]["argsT"][2]["type"] = "unsigned int"
defs["ImGui_ImplGlfw_CharCallback"][1]["argsoriginal"] = "(GLFWwindow* window,unsigned int c)"
defs["ImGui_ImplGlfw_CharCallback"][1]["call_args"] = "(window,c)"
defs["ImGui_ImplGlfw_CharCallback"][1]["cimguiname"] = "ImGui_ImplGlfw_CharCallback"
defs["ImGui_ImplGlfw_CharCallback"][1]["defaults"] = {}
defs["ImGui_ImplGlfw_CharCallback"][1]["funcname"] = "ImGui_ImplGlfw_CharCallback"
defs["ImGui_ImplGlfw_CharCallback"][1]["ov_cimguiname"] = "ImGui_ImplGlfw_CharCallback"
defs["ImGui_ImplGlfw_CharCallback"][1]["ret"] = "void"
defs["ImGui_ImplGlfw_CharCallback"][1]["signature"] = "(GLFWwindow*,unsigned int)"
defs["ImGui_ImplGlfw_CharCallback"][1]["stname"] = ""
defs["ImGui_ImplGlfw_CharCallback"]["(GLFWwindow*,unsigned int)"] = defs["ImGui_ImplGlfw_CharCallback"][1]
defs["ImGui_ImplGlfw_InitForOpenGL"] = {}
defs["ImGui_ImplGlfw_InitForOpenGL"][1] = {}
defs["ImGui_ImplGlfw_InitForOpenGL"][1]["args"] = "(GLFWwindow* window,bool install_callbacks)"
defs["ImGui_ImplGlfw_InitForOpenGL"][1]["argsT"] = {}
defs["ImGui_ImplGlfw_InitForOpenGL"][1]["argsT"][1] = {}
defs["ImGui_ImplGlfw_InitForOpenGL"][1]["argsT"][1]["name"] = "window"
defs["ImGui_ImplGlfw_InitForOpenGL"][1]["argsT"][1]["type"] = "GLFWwindow*"
defs["ImGui_ImplGlfw_InitForOpenGL"][1]["argsT"][2] = {}
defs["ImGui_ImplGlfw_InitForOpenGL"][1]["argsT"][2]["name"] = "install_callbacks"
defs["ImGui_ImplGlfw_InitForOpenGL"][1]["argsT"][2]["type"] = "bool"
defs["ImGui_ImplGlfw_InitForOpenGL"][1]["argsoriginal"] = "(GLFWwindow* window,bool install_callbacks)"
defs["ImGui_ImplGlfw_InitForOpenGL"][1]["call_args"] = "(window,install_callbacks)"
defs["ImGui_ImplGlfw_InitForOpenGL"][1]["cimguiname"] = "ImGui_ImplGlfw_InitForOpenGL"
defs["ImGui_ImplGlfw_InitForOpenGL"][1]["defaults"] = {}
defs["ImGui_ImplGlfw_InitForOpenGL"][1]["funcname"] = "ImGui_ImplGlfw_InitForOpenGL"
defs["ImGui_ImplGlfw_InitForOpenGL"][1]["ov_cimguiname"] = "ImGui_ImplGlfw_InitForOpenGL"
defs["ImGui_ImplGlfw_InitForOpenGL"][1]["ret"] = "bool"
defs["ImGui_ImplGlfw_InitForOpenGL"][1]["signature"] = "(GLFWwindow*,bool)"
defs["ImGui_ImplGlfw_InitForOpenGL"][1]["stname"] = ""
defs["ImGui_ImplGlfw_InitForOpenGL"]["(GLFWwindow*,bool)"] = defs["ImGui_ImplGlfw_InitForOpenGL"][1]
defs["ImGui_ImplGlfw_InitForVulkan"] = {}
defs["ImGui_ImplGlfw_InitForVulkan"][1] = {}
defs["ImGui_ImplGlfw_InitForVulkan"][1]["args"] = "(GLFWwindow* window,bool install_callbacks)"
defs["ImGui_ImplGlfw_InitForVulkan"][1]["argsT"] = {}
defs["ImGui_ImplGlfw_InitForVulkan"][1]["argsT"][1] = {}
defs["ImGui_ImplGlfw_InitForVulkan"][1]["argsT"][1]["name"] = "window"
defs["ImGui_ImplGlfw_InitForVulkan"][1]["argsT"][1]["type"] = "GLFWwindow*"
defs["ImGui_ImplGlfw_InitForVulkan"][1]["argsT"][2] = {}
defs["ImGui_ImplGlfw_InitForVulkan"][1]["argsT"][2]["name"] = "install_callbacks"
defs["ImGui_ImplGlfw_InitForVulkan"][1]["argsT"][2]["type"] = "bool"
defs["ImGui_ImplGlfw_InitForVulkan"][1]["argsoriginal"] = "(GLFWwindow* window,bool install_callbacks)"
defs["ImGui_ImplGlfw_InitForVulkan"][1]["call_args"] = "(window,install_callbacks)"
defs["ImGui_ImplGlfw_InitForVulkan"][1]["cimguiname"] = "ImGui_ImplGlfw_InitForVulkan"
defs["ImGui_ImplGlfw_InitForVulkan"][1]["defaults"] = {}
defs["ImGui_ImplGlfw_InitForVulkan"][1]["funcname"] = "ImGui_ImplGlfw_InitForVulkan"
defs["ImGui_ImplGlfw_InitForVulkan"][1]["ov_cimguiname"] = "ImGui_ImplGlfw_InitForVulkan"
defs["ImGui_ImplGlfw_InitForVulkan"][1]["ret"] = "bool"
defs["ImGui_ImplGlfw_InitForVulkan"][1]["signature"] = "(GLFWwindow*,bool)"
defs["ImGui_ImplGlfw_InitForVulkan"][1]["stname"] = ""
defs["ImGui_ImplGlfw_InitForVulkan"]["(GLFWwindow*,bool)"] = defs["ImGui_ImplGlfw_InitForVulkan"][1]
defs["ImGui_ImplGlfw_KeyCallback"] = {}
defs["ImGui_ImplGlfw_KeyCallback"][1] = {}
defs["ImGui_ImplGlfw_KeyCallback"][1]["args"] = "(GLFWwindow* window,int key,int scancode,int action,int mods)"
defs["ImGui_ImplGlfw_KeyCallback"][1]["argsT"] = {}
defs["ImGui_ImplGlfw_KeyCallback"][1]["argsT"][1] = {}
defs["ImGui_ImplGlfw_KeyCallback"][1]["argsT"][1]["name"] = "window"
defs["ImGui_ImplGlfw_KeyCallback"][1]["argsT"][1]["type"] = "GLFWwindow*"
defs["ImGui_ImplGlfw_KeyCallback"][1]["argsT"][2] = {}
defs["ImGui_ImplGlfw_KeyCallback"][1]["argsT"][2]["name"] = "key"
defs["ImGui_ImplGlfw_KeyCallback"][1]["argsT"][2]["type"] = "int"
defs["ImGui_ImplGlfw_KeyCallback"][1]["argsT"][3] = {}
defs["ImGui_ImplGlfw_KeyCallback"][1]["argsT"][3]["name"] = "scancode"
defs["ImGui_ImplGlfw_KeyCallback"][1]["argsT"][3]["type"] = "int"
defs["ImGui_ImplGlfw_KeyCallback"][1]["argsT"][4] = {}
defs["ImGui_ImplGlfw_KeyCallback"][1]["argsT"][4]["name"] = "action"
defs["ImGui_ImplGlfw_KeyCallback"][1]["argsT"][4]["type"] = "int"
defs["ImGui_ImplGlfw_KeyCallback"][1]["argsT"][5] = {}
defs["ImGui_ImplGlfw_KeyCallback"][1]["argsT"][5]["name"] = "mods"
defs["ImGui_ImplGlfw_KeyCallback"][1]["argsT"][5]["type"] = "int"
defs["ImGui_ImplGlfw_KeyCallback"][1]["argsoriginal"] = "(GLFWwindow* window,int key,int scancode,int action,int mods)"
defs["ImGui_ImplGlfw_KeyCallback"][1]["call_args"] = "(window,key,scancode,action,mods)"
defs["ImGui_ImplGlfw_KeyCallback"][1]["cimguiname"] = "ImGui_ImplGlfw_KeyCallback"
defs["ImGui_ImplGlfw_KeyCallback"][1]["defaults"] = {}
defs["ImGui_ImplGlfw_KeyCallback"][1]["funcname"] = "ImGui_ImplGlfw_KeyCallback"
defs["ImGui_ImplGlfw_KeyCallback"][1]["ov_cimguiname"] = "ImGui_ImplGlfw_KeyCallback"
defs["ImGui_ImplGlfw_KeyCallback"][1]["ret"] = "void"
defs["ImGui_ImplGlfw_KeyCallback"][1]["signature"] = "(GLFWwindow*,int,int,int,int)"
defs["ImGui_ImplGlfw_KeyCallback"][1]["stname"] = ""
defs["ImGui_ImplGlfw_KeyCallback"]["(GLFWwindow*,int,int,int,int)"] = defs["ImGui_ImplGlfw_KeyCallback"][1]
defs["ImGui_ImplGlfw_MouseButtonCallback"] = {}
defs["ImGui_ImplGlfw_MouseButtonCallback"][1] = {}
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["args"] = "(GLFWwindow* window,int button,int action,int mods)"
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["argsT"] = {}
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["argsT"][1] = {}
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["argsT"][1]["name"] = "window"
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["argsT"][1]["type"] = "GLFWwindow*"
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["argsT"][2] = {}
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["argsT"][2]["name"] = "button"
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["argsT"][2]["type"] = "int"
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["argsT"][3] = {}
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["argsT"][3]["name"] = "action"
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["argsT"][3]["type"] = "int"
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["argsT"][4] = {}
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["argsT"][4]["name"] = "mods"
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["argsT"][4]["type"] = "int"
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["argsoriginal"] = "(GLFWwindow* window,int button,int action,int mods)"
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["call_args"] = "(window,button,action,mods)"
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["cimguiname"] = "ImGui_ImplGlfw_MouseButtonCallback"
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["defaults"] = {}
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["funcname"] = "ImGui_ImplGlfw_MouseButtonCallback"
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["ov_cimguiname"] = "ImGui_ImplGlfw_MouseButtonCallback"
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["ret"] = "void"
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["signature"] = "(GLFWwindow*,int,int,int)"
defs["ImGui_ImplGlfw_MouseButtonCallback"][1]["stname"] = ""
defs["ImGui_ImplGlfw_MouseButtonCallback"]["(GLFWwindow*,int,int,int)"] = defs["ImGui_ImplGlfw_MouseButtonCallback"][1]
defs["ImGui_ImplGlfw_NewFrame"] = {}
defs["ImGui_ImplGlfw_NewFrame"][1] = {}
defs["ImGui_ImplGlfw_NewFrame"][1]["args"] = "()"
defs["ImGui_ImplGlfw_NewFrame"][1]["argsT"] = {}
defs["ImGui_ImplGlfw_NewFrame"][1]["argsoriginal"] = "()"
defs["ImGui_ImplGlfw_NewFrame"][1]["call_args"] = "()"
defs["ImGui_ImplGlfw_NewFrame"][1]["cimguiname"] = "ImGui_ImplGlfw_NewFrame"
defs["ImGui_ImplGlfw_NewFrame"][1]["defaults"] = {}
defs["ImGui_ImplGlfw_NewFrame"][1]["funcname"] = "ImGui_ImplGlfw_NewFrame"
defs["ImGui_ImplGlfw_NewFrame"][1]["ov_cimguiname"] = "ImGui_ImplGlfw_NewFrame"
defs["ImGui_ImplGlfw_NewFrame"][1]["ret"] = "void"
defs["ImGui_ImplGlfw_NewFrame"][1]["signature"] = "()"
defs["ImGui_ImplGlfw_NewFrame"][1]["stname"] = ""
defs["ImGui_ImplGlfw_NewFrame"]["()"] = defs["ImGui_ImplGlfw_NewFrame"][1]
defs["ImGui_ImplGlfw_ScrollCallback"] = {}
defs["ImGui_ImplGlfw_ScrollCallback"][1] = {}
defs["ImGui_ImplGlfw_ScrollCallback"][1]["args"] = "(GLFWwindow* window,double xoffset,double yoffset)"
defs["ImGui_ImplGlfw_ScrollCallback"][1]["argsT"] = {}
defs["ImGui_ImplGlfw_ScrollCallback"][1]["argsT"][1] = {}
defs["ImGui_ImplGlfw_ScrollCallback"][1]["argsT"][1]["name"] = "window"
defs["ImGui_ImplGlfw_ScrollCallback"][1]["argsT"][1]["type"] = "GLFWwindow*"
defs["ImGui_ImplGlfw_ScrollCallback"][1]["argsT"][2] = {}
defs["ImGui_ImplGlfw_ScrollCallback"][1]["argsT"][2]["name"] = "xoffset"
defs["ImGui_ImplGlfw_ScrollCallback"][1]["argsT"][2]["type"] = "double"
defs["ImGui_ImplGlfw_ScrollCallback"][1]["argsT"][3] = {}
defs["ImGui_ImplGlfw_ScrollCallback"][1]["argsT"][3]["name"] = "yoffset"
defs["ImGui_ImplGlfw_ScrollCallback"][1]["argsT"][3]["type"] = "double"
defs["ImGui_ImplGlfw_ScrollCallback"][1]["argsoriginal"] = "(GLFWwindow* window,double xoffset,double yoffset)"
defs["ImGui_ImplGlfw_ScrollCallback"][1]["call_args"] = "(window,xoffset,yoffset)"
defs["ImGui_ImplGlfw_ScrollCallback"][1]["cimguiname"] = "ImGui_ImplGlfw_ScrollCallback"
defs["ImGui_ImplGlfw_ScrollCallback"][1]["defaults"] = {}
defs["ImGui_ImplGlfw_ScrollCallback"][1]["funcname"] = "ImGui_ImplGlfw_ScrollCallback"
defs["ImGui_ImplGlfw_ScrollCallback"][1]["ov_cimguiname"] = "ImGui_ImplGlfw_ScrollCallback"
defs["ImGui_ImplGlfw_ScrollCallback"][1]["ret"] = "void"
defs["ImGui_ImplGlfw_ScrollCallback"][1]["signature"] = "(GLFWwindow*,double,double)"
defs["ImGui_ImplGlfw_ScrollCallback"][1]["stname"] = ""
defs["ImGui_ImplGlfw_ScrollCallback"]["(GLFWwindow*,double,double)"] = defs["ImGui_ImplGlfw_ScrollCallback"][1]
defs["ImGui_ImplGlfw_Shutdown"] = {}
defs["ImGui_ImplGlfw_Shutdown"][1] = {}
defs["ImGui_ImplGlfw_Shutdown"][1]["args"] = "()"
defs["ImGui_ImplGlfw_Shutdown"][1]["argsT"] = {}
defs["ImGui_ImplGlfw_Shutdown"][1]["argsoriginal"] = "()"
defs["ImGui_ImplGlfw_Shutdown"][1]["call_args"] = "()"
defs["ImGui_ImplGlfw_Shutdown"][1]["cimguiname"] = "ImGui_ImplGlfw_Shutdown"
defs["ImGui_ImplGlfw_Shutdown"][1]["defaults"] = {}
defs["ImGui_ImplGlfw_Shutdown"][1]["funcname"] = "ImGui_ImplGlfw_Shutdown"
defs["ImGui_ImplGlfw_Shutdown"][1]["ov_cimguiname"] = "ImGui_ImplGlfw_Shutdown"
defs["ImGui_ImplGlfw_Shutdown"][1]["ret"] = "void"
defs["ImGui_ImplGlfw_Shutdown"][1]["signature"] = "()"
defs["ImGui_ImplGlfw_Shutdown"][1]["stname"] = ""
defs["ImGui_ImplGlfw_Shutdown"]["()"] = defs["ImGui_ImplGlfw_Shutdown"][1]
defs["ImGui_ImplOpenGL2_CreateDeviceObjects"] = {}
defs["ImGui_ImplOpenGL2_CreateDeviceObjects"][1] = {}
defs["ImGui_ImplOpenGL2_CreateDeviceObjects"][1]["args"] = "()"
defs["ImGui_ImplOpenGL2_CreateDeviceObjects"][1]["argsT"] = {}
defs["ImGui_ImplOpenGL2_CreateDeviceObjects"][1]["argsoriginal"] = "()"
defs["ImGui_ImplOpenGL2_CreateDeviceObjects"][1]["call_args"] = "()"
defs["ImGui_ImplOpenGL2_CreateDeviceObjects"][1]["cimguiname"] = "ImGui_ImplOpenGL2_CreateDeviceObjects"
defs["ImGui_ImplOpenGL2_CreateDeviceObjects"][1]["defaults"] = {}
defs["ImGui_ImplOpenGL2_CreateDeviceObjects"][1]["funcname"] = "ImGui_ImplOpenGL2_CreateDeviceObjects"
defs["ImGui_ImplOpenGL2_CreateDeviceObjects"][1]["ov_cimguiname"] = "ImGui_ImplOpenGL2_CreateDeviceObjects"
defs["ImGui_ImplOpenGL2_CreateDeviceObjects"][1]["ret"] = "bool"
defs["ImGui_ImplOpenGL2_CreateDeviceObjects"][1]["signature"] = "()"
defs["ImGui_ImplOpenGL2_CreateDeviceObjects"][1]["stname"] = ""
defs["ImGui_ImplOpenGL2_CreateDeviceObjects"]["()"] = defs["ImGui_ImplOpenGL2_CreateDeviceObjects"][1]
defs["ImGui_ImplOpenGL2_CreateFontsTexture"] = {}
defs["ImGui_ImplOpenGL2_CreateFontsTexture"][1] = {}
defs["ImGui_ImplOpenGL2_CreateFontsTexture"][1]["args"] = "()"
defs["ImGui_ImplOpenGL2_CreateFontsTexture"][1]["argsT"] = {}
defs["ImGui_ImplOpenGL2_CreateFontsTexture"][1]["argsoriginal"] = "()"
defs["ImGui_ImplOpenGL2_CreateFontsTexture"][1]["call_args"] = "()"
defs["ImGui_ImplOpenGL2_CreateFontsTexture"][1]["cimguiname"] = "ImGui_ImplOpenGL2_CreateFontsTexture"
defs["ImGui_ImplOpenGL2_CreateFontsTexture"][1]["defaults"] = {}
defs["ImGui_ImplOpenGL2_CreateFontsTexture"][1]["funcname"] = "ImGui_ImplOpenGL2_CreateFontsTexture"
defs["ImGui_ImplOpenGL2_CreateFontsTexture"][1]["ov_cimguiname"] = "ImGui_ImplOpenGL2_CreateFontsTexture"
defs["ImGui_ImplOpenGL2_CreateFontsTexture"][1]["ret"] = "bool"
defs["ImGui_ImplOpenGL2_CreateFontsTexture"][1]["signature"] = "()"
defs["ImGui_ImplOpenGL2_CreateFontsTexture"][1]["stname"] = ""
defs["ImGui_ImplOpenGL2_CreateFontsTexture"]["()"] = defs["ImGui_ImplOpenGL2_CreateFontsTexture"][1]
defs["ImGui_ImplOpenGL2_DestroyDeviceObjects"] = {}
defs["ImGui_ImplOpenGL2_DestroyDeviceObjects"][1] = {}
defs["ImGui_ImplOpenGL2_DestroyDeviceObjects"][1]["args"] = "()"
defs["ImGui_ImplOpenGL2_DestroyDeviceObjects"][1]["argsT"] = {}
defs["ImGui_ImplOpenGL2_DestroyDeviceObjects"][1]["argsoriginal"] = "()"
defs["ImGui_ImplOpenGL2_DestroyDeviceObjects"][1]["call_args"] = "()"
defs["ImGui_ImplOpenGL2_DestroyDeviceObjects"][1]["cimguiname"] = "ImGui_ImplOpenGL2_DestroyDeviceObjects"
defs["ImGui_ImplOpenGL2_DestroyDeviceObjects"][1]["defaults"] = {}
defs["ImGui_ImplOpenGL2_DestroyDeviceObjects"][1]["funcname"] = "ImGui_ImplOpenGL2_DestroyDeviceObjects"
defs["ImGui_ImplOpenGL2_DestroyDeviceObjects"][1]["ov_cimguiname"] = "ImGui_ImplOpenGL2_DestroyDeviceObjects"
defs["ImGui_ImplOpenGL2_DestroyDeviceObjects"][1]["ret"] = "void"
defs["ImGui_ImplOpenGL2_DestroyDeviceObjects"][1]["signature"] = "()"
defs["ImGui_ImplOpenGL2_DestroyDeviceObjects"][1]["stname"] = ""
defs["ImGui_ImplOpenGL2_DestroyDeviceObjects"]["()"] = defs["ImGui_ImplOpenGL2_DestroyDeviceObjects"][1]
defs["ImGui_ImplOpenGL2_DestroyFontsTexture"] = {}
defs["ImGui_ImplOpenGL2_DestroyFontsTexture"][1] = {}
defs["ImGui_ImplOpenGL2_DestroyFontsTexture"][1]["args"] = "()"
defs["ImGui_ImplOpenGL2_DestroyFontsTexture"][1]["argsT"] = {}
defs["ImGui_ImplOpenGL2_DestroyFontsTexture"][1]["argsoriginal"] = "()"
defs["ImGui_ImplOpenGL2_DestroyFontsTexture"][1]["call_args"] = "()"
defs["ImGui_ImplOpenGL2_DestroyFontsTexture"][1]["cimguiname"] = "ImGui_ImplOpenGL2_DestroyFontsTexture"
defs["ImGui_ImplOpenGL2_DestroyFontsTexture"][1]["defaults"] = {}
defs["ImGui_ImplOpenGL2_DestroyFontsTexture"][1]["funcname"] = "ImGui_ImplOpenGL2_DestroyFontsTexture"
defs["ImGui_ImplOpenGL2_DestroyFontsTexture"][1]["ov_cimguiname"] = "ImGui_ImplOpenGL2_DestroyFontsTexture"
defs["ImGui_ImplOpenGL2_DestroyFontsTexture"][1]["ret"] = "void"
defs["ImGui_ImplOpenGL2_DestroyFontsTexture"][1]["signature"] = "()"
defs["ImGui_ImplOpenGL2_DestroyFontsTexture"][1]["stname"] = ""
defs["ImGui_ImplOpenGL2_DestroyFontsTexture"]["()"] = defs["ImGui_ImplOpenGL2_DestroyFontsTexture"][1]
defs["ImGui_ImplOpenGL2_Init"] = {}
defs["ImGui_ImplOpenGL2_Init"][1] = {}
defs["ImGui_ImplOpenGL2_Init"][1]["args"] = "()"
defs["ImGui_ImplOpenGL2_Init"][1]["argsT"] = {}
defs["ImGui_ImplOpenGL2_Init"][1]["argsoriginal"] = "()"
defs["ImGui_ImplOpenGL2_Init"][1]["call_args"] = "()"
defs["ImGui_ImplOpenGL2_Init"][1]["cimguiname"] = "ImGui_ImplOpenGL2_Init"
defs["ImGui_ImplOpenGL2_Init"][1]["defaults"] = {}
defs["ImGui_ImplOpenGL2_Init"][1]["funcname"] = "ImGui_ImplOpenGL2_Init"
defs["ImGui_ImplOpenGL2_Init"][1]["ov_cimguiname"] = "ImGui_ImplOpenGL2_Init"
defs["ImGui_ImplOpenGL2_Init"][1]["ret"] = "bool"
defs["ImGui_ImplOpenGL2_Init"][1]["signature"] = "()"
defs["ImGui_ImplOpenGL2_Init"][1]["stname"] = ""
defs["ImGui_ImplOpenGL2_Init"]["()"] = defs["ImGui_ImplOpenGL2_Init"][1]
defs["ImGui_ImplOpenGL2_NewFrame"] = {}
defs["ImGui_ImplOpenGL2_NewFrame"][1] = {}
defs["ImGui_ImplOpenGL2_NewFrame"][1]["args"] = "()"
defs["ImGui_ImplOpenGL2_NewFrame"][1]["argsT"] = {}
defs["ImGui_ImplOpenGL2_NewFrame"][1]["argsoriginal"] = "()"
defs["ImGui_ImplOpenGL2_NewFrame"][1]["call_args"] = "()"
defs["ImGui_ImplOpenGL2_NewFrame"][1]["cimguiname"] = "ImGui_ImplOpenGL2_NewFrame"
defs["ImGui_ImplOpenGL2_NewFrame"][1]["defaults"] = {}
defs["ImGui_ImplOpenGL2_NewFrame"][1]["funcname"] = "ImGui_ImplOpenGL2_NewFrame"
defs["ImGui_ImplOpenGL2_NewFrame"][1]["ov_cimguiname"] = "ImGui_ImplOpenGL2_NewFrame"
defs["ImGui_ImplOpenGL2_NewFrame"][1]["ret"] = "void"
defs["ImGui_ImplOpenGL2_NewFrame"][1]["signature"] = "()"
defs["ImGui_ImplOpenGL2_NewFrame"][1]["stname"] = ""
defs["ImGui_ImplOpenGL2_NewFrame"]["()"] = defs["ImGui_ImplOpenGL2_NewFrame"][1]
defs["ImGui_ImplOpenGL2_RenderDrawData"] = {}
defs["ImGui_ImplOpenGL2_RenderDrawData"][1] = {}
defs["ImGui_ImplOpenGL2_RenderDrawData"][1]["args"] = "(ImDrawData* draw_data)"
defs["ImGui_ImplOpenGL2_RenderDrawData"][1]["argsT"] = {}
defs["ImGui_ImplOpenGL2_RenderDrawData"][1]["argsT"][1] = {}
defs["ImGui_ImplOpenGL2_RenderDrawData"][1]["argsT"][1]["name"] = "draw_data"
defs["ImGui_ImplOpenGL2_RenderDrawData"][1]["argsT"][1]["type"] = "ImDrawData*"
defs["ImGui_ImplOpenGL2_RenderDrawData"][1]["argsoriginal"] = "(ImDrawData* draw_data)"
defs["ImGui_ImplOpenGL2_RenderDrawData"][1]["call_args"] = "(draw_data)"
defs["ImGui_ImplOpenGL2_RenderDrawData"][1]["cimguiname"] = "ImGui_ImplOpenGL2_RenderDrawData"
defs["ImGui_ImplOpenGL2_RenderDrawData"][1]["defaults"] = {}
defs["ImGui_ImplOpenGL2_RenderDrawData"][1]["funcname"] = "ImGui_ImplOpenGL2_RenderDrawData"
defs["ImGui_ImplOpenGL2_RenderDrawData"][1]["ov_cimguiname"] = "ImGui_ImplOpenGL2_RenderDrawData"
defs["ImGui_ImplOpenGL2_RenderDrawData"][1]["ret"] = "void"
defs["ImGui_ImplOpenGL2_RenderDrawData"][1]["signature"] = "(ImDrawData*)"
defs["ImGui_ImplOpenGL2_RenderDrawData"][1]["stname"] = ""
defs["ImGui_ImplOpenGL2_RenderDrawData"]["(ImDrawData*)"] = defs["ImGui_ImplOpenGL2_RenderDrawData"][1]
defs["ImGui_ImplOpenGL2_Shutdown"] = {}
defs["ImGui_ImplOpenGL2_Shutdown"][1] = {}
defs["ImGui_ImplOpenGL2_Shutdown"][1]["args"] = "()"
defs["ImGui_ImplOpenGL2_Shutdown"][1]["argsT"] = {}
defs["ImGui_ImplOpenGL2_Shutdown"][1]["argsoriginal"] = "()"
defs["ImGui_ImplOpenGL2_Shutdown"][1]["call_args"] = "()"
defs["ImGui_ImplOpenGL2_Shutdown"][1]["cimguiname"] = "ImGui_ImplOpenGL2_Shutdown"
defs["ImGui_ImplOpenGL2_Shutdown"][1]["defaults"] = {}
defs["ImGui_ImplOpenGL2_Shutdown"][1]["funcname"] = "ImGui_ImplOpenGL2_Shutdown"
defs["ImGui_ImplOpenGL2_Shutdown"][1]["ov_cimguiname"] = "ImGui_ImplOpenGL2_Shutdown"
defs["ImGui_ImplOpenGL2_Shutdown"][1]["ret"] = "void"
defs["ImGui_ImplOpenGL2_Shutdown"][1]["signature"] = "()"
defs["ImGui_ImplOpenGL2_Shutdown"][1]["stname"] = ""
defs["ImGui_ImplOpenGL2_Shutdown"]["()"] = defs["ImGui_ImplOpenGL2_Shutdown"][1]
defs["ImGui_ImplOpenGL3_CreateDeviceObjects"] = {}
defs["ImGui_ImplOpenGL3_CreateDeviceObjects"][1] = {}
defs["ImGui_ImplOpenGL3_CreateDeviceObjects"][1]["args"] = "()"
defs["ImGui_ImplOpenGL3_CreateDeviceObjects"][1]["argsT"] = {}
defs["ImGui_ImplOpenGL3_CreateDeviceObjects"][1]["argsoriginal"] = "()"
defs["ImGui_ImplOpenGL3_CreateDeviceObjects"][1]["call_args"] = "()"
defs["ImGui_ImplOpenGL3_CreateDeviceObjects"][1]["cimguiname"] = "ImGui_ImplOpenGL3_CreateDeviceObjects"
defs["ImGui_ImplOpenGL3_CreateDeviceObjects"][1]["defaults"] = {}
defs["ImGui_ImplOpenGL3_CreateDeviceObjects"][1]["funcname"] = "ImGui_ImplOpenGL3_CreateDeviceObjects"
defs["ImGui_ImplOpenGL3_CreateDeviceObjects"][1]["ov_cimguiname"] = "ImGui_ImplOpenGL3_CreateDeviceObjects"
defs["ImGui_ImplOpenGL3_CreateDeviceObjects"][1]["ret"] = "bool"
defs["ImGui_ImplOpenGL3_CreateDeviceObjects"][1]["signature"] = "()"
defs["ImGui_ImplOpenGL3_CreateDeviceObjects"][1]["stname"] = ""
defs["ImGui_ImplOpenGL3_CreateDeviceObjects"]["()"] = defs["ImGui_ImplOpenGL3_CreateDeviceObjects"][1]
defs["ImGui_ImplOpenGL3_CreateFontsTexture"] = {}
defs["ImGui_ImplOpenGL3_CreateFontsTexture"][1] = {}
defs["ImGui_ImplOpenGL3_CreateFontsTexture"][1]["args"] = "()"
defs["ImGui_ImplOpenGL3_CreateFontsTexture"][1]["argsT"] = {}
defs["ImGui_ImplOpenGL3_CreateFontsTexture"][1]["argsoriginal"] = "()"
defs["ImGui_ImplOpenGL3_CreateFontsTexture"][1]["call_args"] = "()"
defs["ImGui_ImplOpenGL3_CreateFontsTexture"][1]["cimguiname"] = "ImGui_ImplOpenGL3_CreateFontsTexture"
defs["ImGui_ImplOpenGL3_CreateFontsTexture"][1]["defaults"] = {}
defs["ImGui_ImplOpenGL3_CreateFontsTexture"][1]["funcname"] = "ImGui_ImplOpenGL3_CreateFontsTexture"
defs["ImGui_ImplOpenGL3_CreateFontsTexture"][1]["ov_cimguiname"] = "ImGui_ImplOpenGL3_CreateFontsTexture"
defs["ImGui_ImplOpenGL3_CreateFontsTexture"][1]["ret"] = "bool"
defs["ImGui_ImplOpenGL3_CreateFontsTexture"][1]["signature"] = "()"
defs["ImGui_ImplOpenGL3_CreateFontsTexture"][1]["stname"] = ""
defs["ImGui_ImplOpenGL3_CreateFontsTexture"]["()"] = defs["ImGui_ImplOpenGL3_CreateFontsTexture"][1]
defs["ImGui_ImplOpenGL3_DestroyDeviceObjects"] = {}
defs["ImGui_ImplOpenGL3_DestroyDeviceObjects"][1] = {}
defs["ImGui_ImplOpenGL3_DestroyDeviceObjects"][1]["args"] = "()"
defs["ImGui_ImplOpenGL3_DestroyDeviceObjects"][1]["argsT"] = {}
defs["ImGui_ImplOpenGL3_DestroyDeviceObjects"][1]["argsoriginal"] = "()"
defs["ImGui_ImplOpenGL3_DestroyDeviceObjects"][1]["call_args"] = "()"
defs["ImGui_ImplOpenGL3_DestroyDeviceObjects"][1]["cimguiname"] = "ImGui_ImplOpenGL3_DestroyDeviceObjects"
defs["ImGui_ImplOpenGL3_DestroyDeviceObjects"][1]["defaults"] = {}
defs["ImGui_ImplOpenGL3_DestroyDeviceObjects"][1]["funcname"] = "ImGui_ImplOpenGL3_DestroyDeviceObjects"
defs["ImGui_ImplOpenGL3_DestroyDeviceObjects"][1]["ov_cimguiname"] = "ImGui_ImplOpenGL3_DestroyDeviceObjects"
defs["ImGui_ImplOpenGL3_DestroyDeviceObjects"][1]["ret"] = "void"
defs["ImGui_ImplOpenGL3_DestroyDeviceObjects"][1]["signature"] = "()"
defs["ImGui_ImplOpenGL3_DestroyDeviceObjects"][1]["stname"] = ""
defs["ImGui_ImplOpenGL3_DestroyDeviceObjects"]["()"] = defs["ImGui_ImplOpenGL3_DestroyDeviceObjects"][1]
defs["ImGui_ImplOpenGL3_DestroyFontsTexture"] = {}
defs["ImGui_ImplOpenGL3_DestroyFontsTexture"][1] = {}
defs["ImGui_ImplOpenGL3_DestroyFontsTexture"][1]["args"] = "()"
defs["ImGui_ImplOpenGL3_DestroyFontsTexture"][1]["argsT"] = {}
defs["ImGui_ImplOpenGL3_DestroyFontsTexture"][1]["argsoriginal"] = "()"
defs["ImGui_ImplOpenGL3_DestroyFontsTexture"][1]["call_args"] = "()"
defs["ImGui_ImplOpenGL3_DestroyFontsTexture"][1]["cimguiname"] = "ImGui_ImplOpenGL3_DestroyFontsTexture"
defs["ImGui_ImplOpenGL3_DestroyFontsTexture"][1]["defaults"] = {}
defs["ImGui_ImplOpenGL3_DestroyFontsTexture"][1]["funcname"] = "ImGui_ImplOpenGL3_DestroyFontsTexture"
defs["ImGui_ImplOpenGL3_DestroyFontsTexture"][1]["ov_cimguiname"] = "ImGui_ImplOpenGL3_DestroyFontsTexture"
defs["ImGui_ImplOpenGL3_DestroyFontsTexture"][1]["ret"] = "void"
defs["ImGui_ImplOpenGL3_DestroyFontsTexture"][1]["signature"] = "()"
defs["ImGui_ImplOpenGL3_DestroyFontsTexture"][1]["stname"] = ""
defs["ImGui_ImplOpenGL3_DestroyFontsTexture"]["()"] = defs["ImGui_ImplOpenGL3_DestroyFontsTexture"][1]
defs["ImGui_ImplOpenGL3_Init"] = {}
defs["ImGui_ImplOpenGL3_Init"][1] = {}
defs["ImGui_ImplOpenGL3_Init"][1]["args"] = "(const char* glsl_version)"
defs["ImGui_ImplOpenGL3_Init"][1]["argsT"] = {}
defs["ImGui_ImplOpenGL3_Init"][1]["argsT"][1] = {}
defs["ImGui_ImplOpenGL3_Init"][1]["argsT"][1]["name"] = "glsl_version"
defs["ImGui_ImplOpenGL3_Init"][1]["argsT"][1]["type"] = "const char*"
defs["ImGui_ImplOpenGL3_Init"][1]["argsoriginal"] = "(const char* glsl_version=NULL)"
defs["ImGui_ImplOpenGL3_Init"][1]["call_args"] = "(glsl_version)"
defs["ImGui_ImplOpenGL3_Init"][1]["cimguiname"] = "ImGui_ImplOpenGL3_Init"
defs["ImGui_ImplOpenGL3_Init"][1]["defaults"] = {}
defs["ImGui_ImplOpenGL3_Init"][1]["defaults"]["glsl_version"] = "NULL"
defs["ImGui_ImplOpenGL3_Init"][1]["funcname"] = "ImGui_ImplOpenGL3_Init"
defs["ImGui_ImplOpenGL3_Init"][1]["ov_cimguiname"] = "ImGui_ImplOpenGL3_Init"
defs["ImGui_ImplOpenGL3_Init"][1]["ret"] = "bool"
defs["ImGui_ImplOpenGL3_Init"][1]["signature"] = "(const char*)"
defs["ImGui_ImplOpenGL3_Init"][1]["stname"] = ""
defs["ImGui_ImplOpenGL3_Init"]["(const char*)"] = defs["ImGui_ImplOpenGL3_Init"][1]
defs["ImGui_ImplOpenGL3_NewFrame"] = {}
defs["ImGui_ImplOpenGL3_NewFrame"][1] = {}
defs["ImGui_ImplOpenGL3_NewFrame"][1]["args"] = "()"
defs["ImGui_ImplOpenGL3_NewFrame"][1]["argsT"] = {}
defs["ImGui_ImplOpenGL3_NewFrame"][1]["argsoriginal"] = "()"
defs["ImGui_ImplOpenGL3_NewFrame"][1]["call_args"] = "()"
defs["ImGui_ImplOpenGL3_NewFrame"][1]["cimguiname"] = "ImGui_ImplOpenGL3_NewFrame"
defs["ImGui_ImplOpenGL3_NewFrame"][1]["defaults"] = {}
defs["ImGui_ImplOpenGL3_NewFrame"][1]["funcname"] = "ImGui_ImplOpenGL3_NewFrame"
defs["ImGui_ImplOpenGL3_NewFrame"][1]["ov_cimguiname"] = "ImGui_ImplOpenGL3_NewFrame"
defs["ImGui_ImplOpenGL3_NewFrame"][1]["ret"] = "void"
defs["ImGui_ImplOpenGL3_NewFrame"][1]["signature"] = "()"
defs["ImGui_ImplOpenGL3_NewFrame"][1]["stname"] = ""
defs["ImGui_ImplOpenGL3_NewFrame"]["()"] = defs["ImGui_ImplOpenGL3_NewFrame"][1]
defs["ImGui_ImplOpenGL3_RenderDrawData"] = {}
defs["ImGui_ImplOpenGL3_RenderDrawData"][1] = {}
defs["ImGui_ImplOpenGL3_RenderDrawData"][1]["args"] = "(ImDrawData* draw_data)"
defs["ImGui_ImplOpenGL3_RenderDrawData"][1]["argsT"] = {}
defs["ImGui_ImplOpenGL3_RenderDrawData"][1]["argsT"][1] = {}
defs["ImGui_ImplOpenGL3_RenderDrawData"][1]["argsT"][1]["name"] = "draw_data"
defs["ImGui_ImplOpenGL3_RenderDrawData"][1]["argsT"][1]["type"] = "ImDrawData*"
defs["ImGui_ImplOpenGL3_RenderDrawData"][1]["argsoriginal"] = "(ImDrawData* draw_data)"
defs["ImGui_ImplOpenGL3_RenderDrawData"][1]["call_args"] = "(draw_data)"
defs["ImGui_ImplOpenGL3_RenderDrawData"][1]["cimguiname"] = "ImGui_ImplOpenGL3_RenderDrawData"
defs["ImGui_ImplOpenGL3_RenderDrawData"][1]["defaults"] = {}
defs["ImGui_ImplOpenGL3_RenderDrawData"][1]["funcname"] = "ImGui_ImplOpenGL3_RenderDrawData"
defs["ImGui_ImplOpenGL3_RenderDrawData"][1]["ov_cimguiname"] = "ImGui_ImplOpenGL3_RenderDrawData"
defs["ImGui_ImplOpenGL3_RenderDrawData"][1]["ret"] = "void"
defs["ImGui_ImplOpenGL3_RenderDrawData"][1]["signature"] = "(ImDrawData*)"
defs["ImGui_ImplOpenGL3_RenderDrawData"][1]["stname"] = ""
defs["ImGui_ImplOpenGL3_RenderDrawData"]["(ImDrawData*)"] = defs["ImGui_ImplOpenGL3_RenderDrawData"][1]
defs["ImGui_ImplOpenGL3_Shutdown"] = {}
defs["ImGui_ImplOpenGL3_Shutdown"][1] = {}
defs["ImGui_ImplOpenGL3_Shutdown"][1]["args"] = "()"
defs["ImGui_ImplOpenGL3_Shutdown"][1]["argsT"] = {}
defs["ImGui_ImplOpenGL3_Shutdown"][1]["argsoriginal"] = "()"
defs["ImGui_ImplOpenGL3_Shutdown"][1]["call_args"] = "()"
defs["ImGui_ImplOpenGL3_Shutdown"][1]["cimguiname"] = "ImGui_ImplOpenGL3_Shutdown"
defs["ImGui_ImplOpenGL3_Shutdown"][1]["defaults"] = {}
defs["ImGui_ImplOpenGL3_Shutdown"][1]["funcname"] = "ImGui_ImplOpenGL3_Shutdown"
defs["ImGui_ImplOpenGL3_Shutdown"][1]["ov_cimguiname"] = "ImGui_ImplOpenGL3_Shutdown"
defs["ImGui_ImplOpenGL3_Shutdown"][1]["ret"] = "void"
defs["ImGui_ImplOpenGL3_Shutdown"][1]["signature"] = "()"
defs["ImGui_ImplOpenGL3_Shutdown"][1]["stname"] = ""
defs["ImGui_ImplOpenGL3_Shutdown"]["()"] = defs["ImGui_ImplOpenGL3_Shutdown"][1]
defs["ImGui_ImplSDL2_InitForD3D"] = {}
defs["ImGui_ImplSDL2_InitForD3D"][1] = {}
defs["ImGui_ImplSDL2_InitForD3D"][1]["args"] = "(SDL_Window* window)"
defs["ImGui_ImplSDL2_InitForD3D"][1]["argsT"] = {}
defs["ImGui_ImplSDL2_InitForD3D"][1]["argsT"][1] = {}
defs["ImGui_ImplSDL2_InitForD3D"][1]["argsT"][1]["name"] = "window"
defs["ImGui_ImplSDL2_InitForD3D"][1]["argsT"][1]["type"] = "SDL_Window*"
defs["ImGui_ImplSDL2_InitForD3D"][1]["argsoriginal"] = "(SDL_Window* window)"
defs["ImGui_ImplSDL2_InitForD3D"][1]["call_args"] = "(window)"
defs["ImGui_ImplSDL2_InitForD3D"][1]["cimguiname"] = "ImGui_ImplSDL2_InitForD3D"
defs["ImGui_ImplSDL2_InitForD3D"][1]["defaults"] = {}
defs["ImGui_ImplSDL2_InitForD3D"][1]["funcname"] = "ImGui_ImplSDL2_InitForD3D"
defs["ImGui_ImplSDL2_InitForD3D"][1]["ov_cimguiname"] = "ImGui_ImplSDL2_InitForD3D"
defs["ImGui_ImplSDL2_InitForD3D"][1]["ret"] = "bool"
defs["ImGui_ImplSDL2_InitForD3D"][1]["signature"] = "(SDL_Window*)"
defs["ImGui_ImplSDL2_InitForD3D"][1]["stname"] = ""
defs["ImGui_ImplSDL2_InitForD3D"]["(SDL_Window*)"] = defs["ImGui_ImplSDL2_InitForD3D"][1]
defs["ImGui_ImplSDL2_InitForOpenGL"] = {}
defs["ImGui_ImplSDL2_InitForOpenGL"][1] = {}
defs["ImGui_ImplSDL2_InitForOpenGL"][1]["args"] = "(SDL_Window* window,void* sdl_gl_context)"
defs["ImGui_ImplSDL2_InitForOpenGL"][1]["argsT"] = {}
defs["ImGui_ImplSDL2_InitForOpenGL"][1]["argsT"][1] = {}
defs["ImGui_ImplSDL2_InitForOpenGL"][1]["argsT"][1]["name"] = "window"
defs["ImGui_ImplSDL2_InitForOpenGL"][1]["argsT"][1]["type"] = "SDL_Window*"
defs["ImGui_ImplSDL2_InitForOpenGL"][1]["argsT"][2] = {}
defs["ImGui_ImplSDL2_InitForOpenGL"][1]["argsT"][2]["name"] = "sdl_gl_context"
defs["ImGui_ImplSDL2_InitForOpenGL"][1]["argsT"][2]["type"] = "void*"
defs["ImGui_ImplSDL2_InitForOpenGL"][1]["argsoriginal"] = "(SDL_Window* window,void* sdl_gl_context)"
defs["ImGui_ImplSDL2_InitForOpenGL"][1]["call_args"] = "(window,sdl_gl_context)"
defs["ImGui_ImplSDL2_InitForOpenGL"][1]["cimguiname"] = "ImGui_ImplSDL2_InitForOpenGL"
defs["ImGui_ImplSDL2_InitForOpenGL"][1]["defaults"] = {}
defs["ImGui_ImplSDL2_InitForOpenGL"][1]["funcname"] = "ImGui_ImplSDL2_InitForOpenGL"
defs["ImGui_ImplSDL2_InitForOpenGL"][1]["ov_cimguiname"] = "ImGui_ImplSDL2_InitForOpenGL"
defs["ImGui_ImplSDL2_InitForOpenGL"][1]["ret"] = "bool"
defs["ImGui_ImplSDL2_InitForOpenGL"][1]["signature"] = "(SDL_Window*,void*)"
defs["ImGui_ImplSDL2_InitForOpenGL"][1]["stname"] = ""
defs["ImGui_ImplSDL2_InitForOpenGL"]["(SDL_Window*,void*)"] = defs["ImGui_ImplSDL2_InitForOpenGL"][1]
defs["ImGui_ImplSDL2_InitForVulkan"] = {}
defs["ImGui_ImplSDL2_InitForVulkan"][1] = {}
defs["ImGui_ImplSDL2_InitForVulkan"][1]["args"] = "(SDL_Window* window)"
defs["ImGui_ImplSDL2_InitForVulkan"][1]["argsT"] = {}
defs["ImGui_ImplSDL2_InitForVulkan"][1]["argsT"][1] = {}
defs["ImGui_ImplSDL2_InitForVulkan"][1]["argsT"][1]["name"] = "window"
defs["ImGui_ImplSDL2_InitForVulkan"][1]["argsT"][1]["type"] = "SDL_Window*"
defs["ImGui_ImplSDL2_InitForVulkan"][1]["argsoriginal"] = "(SDL_Window* window)"
defs["ImGui_ImplSDL2_InitForVulkan"][1]["call_args"] = "(window)"
defs["ImGui_ImplSDL2_InitForVulkan"][1]["cimguiname"] = "ImGui_ImplSDL2_InitForVulkan"
defs["ImGui_ImplSDL2_InitForVulkan"][1]["defaults"] = {}
defs["ImGui_ImplSDL2_InitForVulkan"][1]["funcname"] = "ImGui_ImplSDL2_InitForVulkan"
defs["ImGui_ImplSDL2_InitForVulkan"][1]["ov_cimguiname"] = "ImGui_ImplSDL2_InitForVulkan"
defs["ImGui_ImplSDL2_InitForVulkan"][1]["ret"] = "bool"
defs["ImGui_ImplSDL2_InitForVulkan"][1]["signature"] = "(SDL_Window*)"
defs["ImGui_ImplSDL2_InitForVulkan"][1]["stname"] = ""
defs["ImGui_ImplSDL2_InitForVulkan"]["(SDL_Window*)"] = defs["ImGui_ImplSDL2_InitForVulkan"][1]
defs["ImGui_ImplSDL2_NewFrame"] = {}
defs["ImGui_ImplSDL2_NewFrame"][1] = {}
defs["ImGui_ImplSDL2_NewFrame"][1]["args"] = "(SDL_Window* window)"
defs["ImGui_ImplSDL2_NewFrame"][1]["argsT"] = {}
defs["ImGui_ImplSDL2_NewFrame"][1]["argsT"][1] = {}
defs["ImGui_ImplSDL2_NewFrame"][1]["argsT"][1]["name"] = "window"
defs["ImGui_ImplSDL2_NewFrame"][1]["argsT"][1]["type"] = "SDL_Window*"
defs["ImGui_ImplSDL2_NewFrame"][1]["argsoriginal"] = "(SDL_Window* window)"
defs["ImGui_ImplSDL2_NewFrame"][1]["call_args"] = "(window)"
defs["ImGui_ImplSDL2_NewFrame"][1]["cimguiname"] = "ImGui_ImplSDL2_NewFrame"
defs["ImGui_ImplSDL2_NewFrame"][1]["defaults"] = {}
defs["ImGui_ImplSDL2_NewFrame"][1]["funcname"] = "ImGui_ImplSDL2_NewFrame"
defs["ImGui_ImplSDL2_NewFrame"][1]["ov_cimguiname"] = "ImGui_ImplSDL2_NewFrame"
defs["ImGui_ImplSDL2_NewFrame"][1]["ret"] = "void"
defs["ImGui_ImplSDL2_NewFrame"][1]["signature"] = "(SDL_Window*)"
defs["ImGui_ImplSDL2_NewFrame"][1]["stname"] = ""
defs["ImGui_ImplSDL2_NewFrame"]["(SDL_Window*)"] = defs["ImGui_ImplSDL2_NewFrame"][1]
defs["ImGui_ImplSDL2_ProcessEvent"] = {}
defs["ImGui_ImplSDL2_ProcessEvent"][1] = {}
defs["ImGui_ImplSDL2_ProcessEvent"][1]["args"] = "(const SDL_Event* event)"
defs["ImGui_ImplSDL2_ProcessEvent"][1]["argsT"] = {}
defs["ImGui_ImplSDL2_ProcessEvent"][1]["argsT"][1] = {}
defs["ImGui_ImplSDL2_ProcessEvent"][1]["argsT"][1]["name"] = "event"
defs["ImGui_ImplSDL2_ProcessEvent"][1]["argsT"][1]["type"] = "const SDL_Event*"
defs["ImGui_ImplSDL2_ProcessEvent"][1]["argsoriginal"] = "(const SDL_Event* event)"
defs["ImGui_ImplSDL2_ProcessEvent"][1]["call_args"] = "(event)"
defs["ImGui_ImplSDL2_ProcessEvent"][1]["cimguiname"] = "ImGui_ImplSDL2_ProcessEvent"
defs["ImGui_ImplSDL2_ProcessEvent"][1]["defaults"] = {}
defs["ImGui_ImplSDL2_ProcessEvent"][1]["funcname"] = "ImGui_ImplSDL2_ProcessEvent"
defs["ImGui_ImplSDL2_ProcessEvent"][1]["ov_cimguiname"] = "ImGui_ImplSDL2_ProcessEvent"
defs["ImGui_ImplSDL2_ProcessEvent"][1]["ret"] = "bool"
defs["ImGui_ImplSDL2_ProcessEvent"][1]["signature"] = "(const SDL_Event*)"
defs["ImGui_ImplSDL2_ProcessEvent"][1]["stname"] = ""
defs["ImGui_ImplSDL2_ProcessEvent"]["(const SDL_Event*)"] = defs["ImGui_ImplSDL2_ProcessEvent"][1]
defs["ImGui_ImplSDL2_Shutdown"] = {}
defs["ImGui_ImplSDL2_Shutdown"][1] = {}
defs["ImGui_ImplSDL2_Shutdown"][1]["args"] = "()"
defs["ImGui_ImplSDL2_Shutdown"][1]["argsT"] = {}
defs["ImGui_ImplSDL2_Shutdown"][1]["argsoriginal"] = "()"
defs["ImGui_ImplSDL2_Shutdown"][1]["call_args"] = "()"
defs["ImGui_ImplSDL2_Shutdown"][1]["cimguiname"] = "ImGui_ImplSDL2_Shutdown"
defs["ImGui_ImplSDL2_Shutdown"][1]["defaults"] = {}
defs["ImGui_ImplSDL2_Shutdown"][1]["funcname"] = "ImGui_ImplSDL2_Shutdown"
defs["ImGui_ImplSDL2_Shutdown"][1]["ov_cimguiname"] = "ImGui_ImplSDL2_Shutdown"
defs["ImGui_ImplSDL2_Shutdown"][1]["ret"] = "void"
defs["ImGui_ImplSDL2_Shutdown"][1]["signature"] = "()"
defs["ImGui_ImplSDL2_Shutdown"][1]["stname"] = ""
defs["ImGui_ImplSDL2_Shutdown"]["()"] = defs["ImGui_ImplSDL2_Shutdown"][1]
return defs | mit |
Lsty/ygopro-scripts | c53208660.lua | 3 | 2438 | --ペンデュラム・コール
function c53208660.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SEARCH+CATEGORY_TOHAND)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,53208660+EFFECT_COUNT_CODE_OATH)
e1:SetCondition(c53208660.condition)
e1:SetCost(c53208660.cost)
e1:SetTarget(c53208660.target)
e1:SetOperation(c53208660.activate)
c:RegisterEffect(e1)
Duel.AddCustomActivityCounter(53208660,ACTIVITY_CHAIN,c53208660.chainfilter)
end
function c53208660.chainfilter(re,tp,cid)
local rc=re:GetHandler()
local loc,seq=Duel.GetChainInfo(cid,CHAININFO_TRIGGERING_LOCATION,CHAININFO_TRIGGERING_SEQUENCE)
return not (re:IsActiveType(TYPE_SPELL) and not re:IsHasType(EFFECT_TYPE_ACTIVATE)
and loc==LOCATION_SZONE and (seq==6 or seq==7) and rc:IsSetCard(0x98))
end
function c53208660.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCustomActivityCount(53208660,tp,ACTIVITY_CHAIN)==0
end
function c53208660.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsDiscardable,tp,LOCATION_HAND,0,1,e:GetHandler()) end
Duel.DiscardHand(tp,Card.IsDiscardable,1,1,REASON_COST+REASON_DISCARD)
end
function c53208660.thfilter(c)
return c:IsSetCard(0x98) and c:IsType(TYPE_PENDULUM) and c:IsAbleToHand()
end
function c53208660.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
local g=Duel.GetMatchingGroup(c53208660.thfilter,tp,LOCATION_DECK,0,nil)
return g:GetClassCount(Card.GetCode)>=2
end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,2,tp,LOCATION_DECK)
end
function c53208660.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c53208660.thfilter,tp,LOCATION_DECK,0,nil)
if g:GetClassCount(Card.GetCode)>=2 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g1=g:Select(tp,1,1,nil)
g:Remove(Card.IsCode,nil,g1:GetFirst():GetCode())
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g2=g:Select(tp,1,1,nil)
g1:Merge(g2)
Duel.SendtoHand(g1,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g1)
end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e1:SetTargetRange(LOCATION_SZONE,0)
e1:SetTarget(c53208660.indtg)
e1:SetValue(1)
e1:SetReset(RESET_PHASE+PHASE_END+RESET_OPPO_TURN)
Duel.RegisterEffect(e1,tp)
end
function c53208660.indtg(e,c)
return (c:GetSequence()==6 or c:GetSequence()==7) and c:IsSetCard(0x98)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c58477767.lua | 7 | 1442 | --女王の選択
function c58477767.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_BATTLE_DESTROYED)
e1:SetCondition(c58477767.condition)
e1:SetTarget(c58477767.target)
e1:SetOperation(c58477767.operation)
c:RegisterEffect(e1)
end
function c58477767.check(c1,c2,tp)
return c1:IsLocation(LOCATION_GRAVE) and c1:IsReason(REASON_BATTLE) and c1:GetPreviousControler()~=tp and c2:IsSetCard(0x4)
end
function c58477767.condition(e,tp,eg,ep,ev,re,r,rp)
local dc=eg:GetFirst()
local bc=dc:GetBattleTarget()
return c58477767.check(dc,bc,tp) or c58477767.check(bc,dc,tp)
end
function c58477767.spfilter(c,e,tp)
return c:IsLevelBelow(4) and c:IsSetCard(0x4) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c58477767.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c58477767.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c58477767.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c58477767.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c88671720.lua | 3 | 1672 | --ブラック・ボンバー
function c88671720.initial_effect(c)
--summon success
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(88671720,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(c88671720.sumtg)
e1:SetOperation(c88671720.sumop)
c:RegisterEffect(e1)
end
function c88671720.filter(c,e,tp)
return c:GetLevel()==4 and c:IsRace(RACE_MACHINE) and c:IsAttribute(ATTRIBUTE_DARK)
and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c88671720.sumtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c88671720.filter(chkc,e,tp) end
if chk==0 then return Duel.IsExistingTarget(c88671720.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c88671720.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c88671720.sumop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP_DEFENCE) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e2)
end
Duel.SpecialSummonComplete()
end
| gpl-2.0 |
Death15/Test | plugins/GpCOntrol.lua | 1 | 17075 | -- data saved to data/moderation.json
do
local function export_chat_link_cb(extra, success, result)
local msg = extra.msg
local data = extra.data
if success == 0 then
return send_large_msg(get_receiver(msg), 'Cannot generate invite link for this group.\nMake sure you are an admin or a sudoer.')
end
data[tostring(msg.to.id)]['link'] = result
save_data(_config.moderation.data, data)
return send_large_msg(get_receiver(msg),'Newest generated invite link for '..msg.to.title..' is:\n'..result)
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (get_receiver(msg), file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(get_receiver(msg), 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(get_receiver(msg), 'Failed, please try again!', ok_cb, false)
end
end
local function get_description(msg, data)
local about = data[tostring(msg.to.id)]['description']
if not about then
return 'No description available.'
end
return string.gsub(msg.to.print_name, '_', ' ')..':\n\n'..about
end
-- media handler. needed by group_photo_lock
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '['..msg.media.type..']'
end
return msg
end
function run(msg, matches)
if is_chat_msg(msg) then
local data = load_data(_config.moderation.data)
-- create a group
if matches[1] == 'mkgroup' and matches[2] and is_mod(msg.from.id, msg.to.id) then
create_group_chat (msg.from.print_name, matches[2], ok_cb, false)
return 'Group '..string.gsub(matches[2], '_', ' ')..' has been created.'
-- add a group to be moderated
elseif matches[1] == 'modadd' and is_admin(msg.from.id, msg.to.id) then
if data[tostring(msg.to.id)] then
return 'Group is already added.'
end
-- create data array in moderation.json
data[tostring(msg.to.id)] = {
moderators ={},
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_bots = 'no',
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
anti_flood = 'ban',
welcome = 'group',
sticker = 'ok',
}
}
save_data(_config.moderation.data, data)
return 'Group has been added.'
-- remove group from moderation
elseif matches[1] == 'modrem' and is_admin(msg.from.id, msg.to.id) then
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return 'Group has been removed'
end
if msg.media and is_chat_msg(msg) and is_mod(msg.from.id, msg.to.id) then
if msg.media.type == 'photo' and data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then
load_photo(msg.id, set_group_photo, msg)
end
end
end
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'setabout' and matches[2] and is_mod(msg.from.id, msg.to.id) then
data[tostring(msg.to.id)]['description'] = matches[2]
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..matches[2]
elseif matches[1] == 'about' then
return get_description(msg, data)
elseif matches[1] == 'setrules' and is_mod(msg.from.id, msg.to.id) then
data[tostring(msg.to.id)]['rules'] = matches[2]
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..matches[2]
elseif matches[1] == 'rules' then
if not data[tostring(msg.to.id)]['rules'] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)]['rules']
local rules = string.gsub(msg.to.print_name, '_', ' ')..' rules:\n\n'..rules
return rules
-- group link {get|set}
elseif matches[1] == 'link' then
if matches[2] == 'get' then
if data[tostring(msg.to.id)]['link'] then
local about = get_description(msg, data)
local link = data[tostring(msg.to.id)]['link']
return about..'\n\n'..link
else
return 'Invite link does not exist.\nTry !link set to generate.'
end
elseif matches[2] == 'set' and is_mod(msg.from.id, msg.to.id) then
msgr = export_chat_link(get_receiver(msg), export_chat_link_cb, {data=data, msg=msg})
end
elseif matches[1] == 'gp' then
-- lock {bot|name|member|photo|sticker}
if matches[2] == '+' then
if matches[3] == 'b' and is_mod(msg.from.id, msg.to.id) then
if settings.lock_bots == 'yes' then
return 'Group is already locked from bots.'
else
settings.lock_bots = 'yes'
save_data(_config.moderation.data, data)
return 'Group is locked from bots.'
end
elseif matches[3] == 'n' and is_mod(msg.from.id, msg.to.id) then
if settings.lock_name == 'yes' then
return 'Group name is already locked'
else
settings.lock_name = 'yes'
save_data(_config.moderation.data, data)
settings.set_name = string.gsub(msg.to.print_name, '_', ' ')
save_data(_config.moderation.data, data)
return 'Group name has been locked'
end
elseif matches[3] == 'm' and is_mod(msg.from.id, msg.to.id) then
if settings.lock_member == 'yes' then
return 'Group members are already locked'
else
settings.lock_member = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
elseif matches[3] == 'p' and is_mod(msg.from.id, msg.to.id) then
if settings.lock_photo == 'yes' then
return 'Group photo is already locked'
else
settings.set_photo = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
-- unlock {bot|name|member|photo|sticker}
elseif matches[2] == '-' then
if matches[3] == 'b' and is_mod(msg.from.id, msg.to.id) then
if settings.lock_bots == 'no' then
return 'Bots are allowed to enter group.'
else
settings.lock_bots = 'no'
save_data(_config.moderation.data, data)
return 'Group is open for bots.'
end
elseif matches[3] == 'n' and is_mod(msg.from.id, msg.to.id) then
if settings.lock_name == 'no' then
return 'Group name is already unlocked'
else
settings.lock_name = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
elseif matches[3] == 'm' and is_mod(msg.from.id, msg.to.id) then
if settings.lock_member == 'no' then
return 'Group members are not locked'
else
settings.lock_member = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
elseif matches[3] == 'p' and is_mod(msg.from.id, msg.to.id) then
if settings.lock_photo == 'no' then
return 'Group photo is not locked'
else
settings.lock_photo = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
-- view group settings
elseif matches[2] == 'settings' and is_mod(msg.from.id, msg.to.id) then
if settings.lock_bots == 'yes' then
lock_bots_state = '✔️'
elseif settings.lock_bots == 'no' then
lock_bots_state = '➖'
end
if settings.lock_name == 'yes' then
lock_name_state = '✔️'
elseif settings.lock_name == 'no' then
lock_name_state = '➖'
end
if settings.lock_photo == 'yes' then
lock_photo_state = '✔️'
elseif settings.lock_photo == 'no' then
lock_photo_state = '➖'
end
if settings.lock_member == 'yes' then
lock_member_state = '✔️'
elseif settings.lock_member == 'no' then
lock_member_state = '➖'
end
if settings.anti_flood ~= 'no' then
antispam_state = '✔️'
elseif settings.anti_flood == 'no' then
antispam_state = '➖'
end
if settings.welcome ~= 'no' then
greeting_state = '🔒'
elseif settings.welcome == 'no' then
greeting_state = '➖'
end
if settings.sticker ~= 'no' then
sticker_state = '🔒'
elseif settings.sticker == 'no' then
sticker_state = '➖'
end
local text = 'Group settings:\n'
..'\n'..lock_bots_state..' group from bot : '..settings.lock_bots
..'\n'..lock_name_state..' group name : '..settings.lock_name
..'\n'..lock_photo_state..' group photo : '..settings.lock_photo
..'\n'..lock_member_state..' group member : '..settings.lock_member
..'\n'..antispam_state..' Spam and Flood Policy : '..settings.anti_flood
..'\n'..sticker_state..' Sticker policy : '..settings.sticker
..'\n'..greeting_state..' Welcome message : '..settings.welcome
return text
end
elseif matches[1] == 'stickers' then
if matches[2] == 'enable' then
if settings.sticker ~= 'warn' then
settings.sticker = 'warn'
save_data(_config.moderation.data, data)
end
return 'Offender Will Warned!.\n'
elseif matches[2] == 'k' then
if settings.sticker ~= 'k' then
settings.sticker = 'k'
save_data(_config.moderation.data, data)
end
return 'Sender will be kicked!'
elseif matches[2] == 'disable' then
if settings.sticker == 'no' then
return 'Sticker restriction is not enabled.'
else
settings.sticker = 'no'
save_data(_config.moderation.data, data)
return 'Sticker restriction has been disabled.'
end
end
-- if group name is renamed
elseif matches[1] == 'chat_rename' then
if not msg.service then
return 'Are you trying to troll me?'
end
if settings.lock_name == 'yes' then
if settings.set_name ~= tostring(msg.to.print_name) then
rename_chat(get_receiver(msg), settings.set_name, ok_cb, false)
end
elseif settings.lock_name == 'no' then
return nil
end
-- set group name
elseif matches[1] == 'setname' and is_mod(msg.from.id, msg.to.id) then
settings.set_name = string.gsub(matches[2], '_', ' ')
save_data(_config.moderation.data, data)
rename_chat(get_receiver(msg), settings.set_name, ok_cb, false)
-- set group photo
elseif matches[1] == 'setphoto' and is_mod(msg.from.id, msg.to.id) then
settings.set_photo = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
-- if a user is added to group
elseif matches[1] == 'chat_add_user' then
if not msg.service then
return 'Are you trying to troll me?'
end
local user = 'user#id'..msg.action.user.id
if settings.lock_member == 'yes' then
chat_del_user(get_receiver(msg), user, ok_cb, true)
-- no APIs bot are allowed to enter chat group, except invited by mods.
elseif settings.lock_bots == 'yes' and msg.action.user.flags == 4352 and not is_mod(msg.from.id, msg.to.id) then
chat_del_user(get_receiver(msg), user, ok_cb, true)
elseif settings.lock_bots == 'no' or settings.lock_member == 'no' then
return nil
end
-- if sticker is sent
elseif msg.media and msg.media.caption == 'sticker.webp' and not is_sudo(msg.from.id) then
local user_id = msg.from.id
local chat_id = msg.to.id
local sticker_hash = 'mer_sticker:'..chat_id..':'..user_id
local is_sticker_offender = redis:get(sticker_hash)
if settings.sticker == 'warn' then
if is_sticker_offender then
chat_del_user(get_receiver(msg), 'user#id'..user_id, ok_cb, true)
redis:del(sticker_hash)
return 'You have been warned to not sending sticker into this group!'
elseif not is_sticker_offender then
redis:set(sticker_hash, true)
return 'DO NOT send sticker into this group!\nThis is a WARNING, next time you will be kicked!'
end
elseif settings.sticker == 'kick' then
chat_del_user(get_receiver(msg), 'user#id'..user_id, ok_cb, true)
return 'DO NOT send sticker into this group!'
elseif settings.sticker == 'ok' then
return nil
end
-- if group photo is deleted
elseif matches[1] == 'chat_delete_photo' then
if not msg.service then
return 'Are you trying to troll me?'
end
if settings.lock_photo == 'yes' then
chat_set_photo (get_receiver(msg), settings.set_photo, ok_cb, false)
elseif settings.lock_photo == 'no' then
return nil
end
-- if group photo is changed
elseif matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return 'Are you trying to troll me?'
end
if settings.lock_photo == 'yes' then
chat_set_photo (get_receiver(msg), settings.set_photo, ok_cb, false)
elseif settings.lock_photo == 'no' then
return nil
end
end
end
else
print '>>> This is not a chat group.'
end
end
return {
description = 'Plugin to manage group chat.',
usage = {
admin = {
'!mkgroup <group_name> : Make/create a new group.',
'!addgroup : Add group to moderation list.',
'!remgroup : Remove group from moderation list.'
},
moderator = {
'!group <lock|unlock> bot : {Dis}allow APIs bots.',
'!group <lock|unlock> member : Lock/unlock group member.',
'!group <lock|unlock> name : Lock/unlock group name.',
'!group <lock|unlock> photo : Lock/unlock group photo.',
'!group settings : Show group settings.',
'!link <set> : Generate/revoke invite link.',
'!setabout <description> : Set group description.',
'!setname <new_name> : Set group name.',
'!setphoto : Set group photo.',
'!setrules <rules> : Set group rules.',
'!sticker warn : Sticker restriction, sender will be warned for the first violation.',
'!sticker kick : Sticker restriction, sender will be kick.',
'!sticker ok : Disable sticker restriction.'
},
user = {
'!about : Read group description',
'!rules : Read group rules',
'!link <get> : Print invite link'
},
},
patterns = {
'^(about)$',
'^(modadd)$',
'%[(audio)%]',
'%[(document)%]',
'^(gp) (+) (.*)$',
'^(gp) (?)$',
'^(gp) (-) (.*)$',
'^(link) (.*)$',
'^(mkgroup) (.*)$',
'%[(photo)%]',
'^(modrem)$',
'^(rules)$',
'^(setabout) (.*)$',
'^(setname) (.*)$',
'^(setphoto)$',
'^(setrules) (.*)$',
'^(stickers) (.*)$',
'^!!tgservice (.+)$',
'%[(video)%]'
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
Lsty/ygopro-scripts | c1498130.lua | 7 | 1091 | --六武衆の影武者
function c1498130.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(1498130,0))
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_CHAINING)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c1498130.tgcon)
e1:SetOperation(c1498130.tgop)
c:RegisterEffect(e1)
end
function c1498130.tgcon(e,tp,eg,ep,ev,re,r,rp)
if not re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then return false end
local g=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS)
if not g or g:GetCount()~=1 then return false end
local tc=g:GetFirst()
local c=e:GetHandler()
if tc==c or tc:GetControler()~=tp or tc:IsFacedown() or not tc:IsLocation(LOCATION_MZONE) or not tc:IsSetCard(0x3d) then return false end
local tf=re:GetTarget()
local res,ceg,cep,cev,cre,cr,crp=Duel.CheckEvent(re:GetCode(),true)
return tf(re,rp,ceg,cep,cev,cre,cr,crp,0,c)
end
function c1498130.tgop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and c:IsFaceup() then
local g=Group.CreateGroup()
g:AddCard(c)
Duel.ChangeTargetCard(ev,g)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/globals/spells/cryohelix.lua | 12 | 2046 | --------------------------------------
-- Spell: Cryohelix
-- Deals ice damage that gradually reduces
-- a target's HP. Damage dealt is greatly affected by the weather.
--------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/magic")
--------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
-- get helix acc/att merits
local merit = caster:getMerit(dsp.merit.HELIX_MAGIC_ACC_ATT)
-- calculate raw damage
local params = {}
params.dmg = 35
params.multiplier = 1
params.skillType = dsp.skill.ELEMENTAL_MAGIC
params.attribute = dsp.mod.INT
params.hasMultipleTargetReduction = false
local dmg = calculateMagicDamage(caster, target, spell, params)
dmg = dmg + caster:getMod(dsp.mod.HELIX_EFFECT)
-- get resist multiplier (1x if no resist)
local params = {}
params.diff = caster:getStat(dsp.mod.INT)-target:getStat(dsp.mod.INT)
params.attribute = dsp.mod.INT
params.skillType = dsp.skill.ELEMENTAL_MAGIC
-- bonus accuracy from merit
params.bonus = merit*3
local resist = applyResistance(caster, target, spell, params)
-- get the resisted damage
dmg = dmg*resist
-- add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = addBonuses(caster,spell,target,dmg,params)
-- add in target adjustment
dmg = adjustForTarget(target,dmg,spell:getElement())
-- helix MAB merits are actually a percentage increase
dmg = dmg * ((100 + merit*2)/100)
local dot = dmg
-- add in final adjustments
dmg = finalMagicAdjustments(caster,target,spell,dmg)
-- calculate Damage over time
dot = target:magicDmgTaken(dot)
local duration = getHelixDuration(caster) + caster:getMod(dsp.mod.HELIX_DURATION)
duration = duration * (resist/2)
if (dot > 0) then
target:addStatusEffect(dsp.effect.HELIX,dot,3,duration)
end
return dmg
end | gpl-3.0 |
cleytonk/globalfull | data/spells/scripts/party/protect.lua | 15 | 1808 | local combat = createCombatObject()
local area = createCombatArea(AREA_CROSS5X5)
setCombatArea(combat, area)
setCombatParam(combat, COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_GREEN)
setCombatParam(combat, COMBAT_PARAM_AGGRESSIVE, 0)
local condition = createConditionObject(CONDITION_ATTRIBUTES)
setConditionParam(condition, CONDITION_PARAM_SUBID, 2)
setConditionParam(condition, CONDITION_PARAM_BUFF_SPELL, 1)
setConditionParam(condition, CONDITION_PARAM_TICKS, 2 * 60 * 1000)
setConditionParam(condition, CONDITION_PARAM_SKILL_SHIELD, 2)
local baseMana = 90
function onCastSpell(cid, var)
local pos = getCreaturePosition(cid)
local membersList = getPartyMembers(cid)
if(membersList == nil or type(membersList) ~= 'table' or #membersList <= 1) then
doPlayerSendCancel(cid, "No party members in range.")
doSendMagicEffect(pos, CONST_ME_POFF)
return LUA_ERROR
end
local affectedList = {}
for _, pid in ipairs(membersList) do
if(getDistanceBetween(getCreaturePosition(pid), pos) <= 36) then
table.insert(affectedList, pid)
end
end
local tmp = #affectedList
if(tmp <= 1) then
doPlayerSendCancel(cid, "No party members in range.")
doSendMagicEffect(pos, CONST_ME_POFF)
return LUA_ERROR
end
local mana = math.ceil((0.9 ^ (tmp - 1) * baseMana) * tmp)
if(getPlayerMana(cid) < mana) then
doPlayerSendDefaultCancel(cid, RETURNVALUE_NOTENOUGHMANA)
doSendMagicEffect(pos, CONST_ME_POFF)
return LUA_ERROR
end
if(doCombat(cid, combat, var) ~= LUA_NO_ERROR) then
doPlayerSendDefaultCancel(cid, RETURNVALUE_NOTPOSSIBLE)
doSendMagicEffect(pos, CONST_ME_POFF)
return LUA_ERROR
end
doPlayerAddMana(cid, -(mana - baseMana), FALSE)
doPlayerAddManaSpent(cid, (mana - baseMana))
for _, pid in ipairs(affectedList) do
doAddCondition(pid, condition)
end
return LUA_NO_ERROR
end
| gpl-2.0 |
MalRD/darkstar | scripts/globals/spells/bio_iii.lua | 11 | 2691 | -----------------------------------------
-- Spell: Bio III
-- Deals dark damage that weakens an enemy's attacks and gradually reduces its HP.
-- caster:getMerit() returns a value which is equal to the number of merit points TIMES the value of each point
-- Bio III value per point is '30' This is a constant set in the table 'merits'
-----------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/magic")
require("scripts/globals/utils")
require("scripts/globals/msg")
--------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
local basedmg = caster:getSkillLevel(dsp.skill.DARK_MAGIC) / 4
local params = {}
params.dmg = basedmg
params.multiplier = 3
params.skillType = dsp.skill.DARK_MAGIC
params.attribute = dsp.mod.INT
params.hasMultipleTargetReduction = false
params.diff = caster:getStat(dsp.mod.INT)-target:getStat(dsp.mod.INT)
params.attribute = dsp.mod.INT
params.skillType = dsp.skill.DARK_MAGIC
params.bonus = 1.0
-- Calculate raw damage
local dmg = calculateMagicDamage(caster, target, spell, params)
-- Softcaps at 62, should always do at least 1
dmg = utils.clamp(dmg, 1, 62)
-- Get resist multiplier (1x if no resist)
local resist = applyResistance(caster, target, spell, params)
-- Get the resisted damage
dmg = dmg * resist
-- Add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = addBonuses(caster, spell, target, dmg)
-- Add in target adjustment
dmg = adjustForTarget(target, dmg, spell:getElement())
-- Add in final adjustments including the actual damage dealt
local final = finalMagicAdjustments(caster, target, spell, dmg)
-- Calculate duration
local duration = caster:getMerit(dsp.merit.BIO_III)
-- If caster has the spell but no merits in it, they are either a mob or we assume they are GM or otherwise gifted with max duration
if duration == 0 then
duration = 150
end
-- Check for Dia
local dia = target:getStatusEffect(dsp.effect.DIA)
-- Calculate DoT effect (rough, though fairly accurate)
local dotdmg = 4 + math.floor(caster:getSkillLevel(dsp.skill.DARK_MAGIC) / 60)
-- Do it!
target:addStatusEffect(dsp.effect.BIO, dotdmg, 3, duration, 0, 20, 3)
spell:setMsg(dsp.msg.basic.MAGIC_DMG)
-- Try to kill same tier Dia (default behavior)
if DIA_OVERWRITE == 1 and dia ~= nil then
if dia:getPower() <= 3 then
target:delStatusEffect(dsp.effect.DIA)
end
end
return final
end
| gpl-3.0 |
MalRD/darkstar | scripts/globals/spells/cure_ii.lua | 5 | 5091 | -----------------------------------------
-- Spell: Cure II
-- Restores target's HP.
-- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html
-----------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/magic")
require("scripts/globals/msg")
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
local divisor = 0
local constant = 0
local basepower = 0
local power = 0
local basecure = 0
local final = 0
local minCure = 60
if (USE_OLD_CURE_FORMULA == true) then
power = getCurePowerOld(caster)
divisor = 1
constant = 20
if (power > 170) then
divisor = 35.6666
constant = 87.62
elseif (power > 110) then
divisor = 2
constant = 47.5
end
else
power = getCurePower(caster)
if (power < 70) then
divisor = 1
constant = 60
basepower = 40
elseif (power < 125) then
divisor = 5.5
constant = 90
basepower = 70
elseif (power < 200) then
divisor = 7.5
constant = 100
basepower = 125
elseif (power < 400) then
divisor = 10
constant = 110
basepower = 200
elseif (power < 700) then
divisor = 20
constant = 130
basepower = 400
else
divisor = 999999
constant = 145
basepower = 0
end
end
if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == dsp.objType.PC or target:getObjType() == dsp.objType.MOB)) then
if (USE_OLD_CURE_FORMULA == true) then
basecure = getBaseCureOld(power,divisor,constant)
else
basecure = getBaseCure(power,divisor,constant,basepower)
end
final = getCureFinal(caster,spell,basecure,minCure,false)
if (caster:hasStatusEffect(dsp.effect.AFFLATUS_SOLACE) and target:hasStatusEffect(dsp.effect.STONESKIN) == false) then
local solaceStoneskin = 0
local equippedBody = caster:getEquipID(dsp.slot.BODY)
if (equippedBody == 11186) then
solaceStoneskin = math.floor(final * 0.30)
elseif (equippedBody == 11086) then
solaceStoneskin = math.floor(final * 0.35)
else
solaceStoneskin = math.floor(final * 0.25)
end
target:addStatusEffect(dsp.effect.STONESKIN,solaceStoneskin,0,25,0,0,1)
end
final = final + (final * (target:getMod(dsp.mod.CURE_POTENCY_RCVD)/100))
--Applying server mods....
final = final * CURE_POWER
local diff = (target:getMaxHP() - target:getHP())
if (final > diff) then
final = diff
end
target:addHP(final)
target:wakeUp()
caster:updateEnmityFromCure(target,final)
else
if (target:isUndead()) then
spell:setMsg(dsp.msg.basic.MAGIC_DMG)
local params = {}
params.dmg = minCure
params.multiplier = 1
params.skillType = dsp.skill.HEALING_MAGIC
params.attribute = dsp.mod.MND
params.hasMultipleTargetReduction = false
local dmg = calculateMagicDamage(caster, target, spell, params)*0.5
local params = {}
params.diff = caster:getStat(dsp.mod.MND)-target:getStat(dsp.mod.MND)
params.attribute = dsp.mod.MND
params.skillType = dsp.skill.HEALING_MAGIC
params.bonus = 1.0
local resist = applyResistance(caster, target, spell, params)
dmg = dmg*resist
dmg = addBonuses(caster,spell,target,dmg)
dmg = adjustForTarget(target,dmg,spell:getElement())
dmg = finalMagicAdjustments(caster,target,spell,dmg)
final = dmg
target:takeDamage(final, caster, dsp.attackType.MAGICAL, dsp.damageType.LIGHT)
target:updateEnmityFromDamage(caster,final)
elseif (caster:getObjType() == dsp.objType.PC) then
spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT)
else
-- e.g. monsters healing themselves.
if (USE_OLD_CURE_FORMULA == true) then
basecure = getBaseCureOld(power,divisor,constant)
else
basecure = getBaseCure(power,divisor,constant,basepower)
end
final = getCureFinal(caster,spell,basecure,minCure,false)
local diff = (target:getMaxHP() - target:getHP())
if (final > diff) then
final = diff
end
target:addHP(final)
end
end
local mpBonusPercent = (final*caster:getMod(dsp.mod.CURE2MP_PERCENT))/100
if (mpBonusPercent > 0) then
caster:addMP(mpBonusPercent)
end
return final
end
| gpl-3.0 |
Lsty/ygopro-scripts | c65830223.lua | 5 | 1199 | --棺桶売り
function c65830223.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--damage
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(65830223,0))
e2:SetCategory(CATEGORY_DAMAGE)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_TO_GRAVE)
e2:SetRange(LOCATION_SZONE)
e2:SetCondition(c65830223.condition)
e2:SetTarget(c65830223.target)
e2:SetOperation(c65830223.operation)
c:RegisterEffect(e2)
end
function c65830223.filter(c,tp)
return c:IsType(TYPE_MONSTER) and c:GetControler()==1-tp
end
function c65830223.condition(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c65830223.filter,1,nil,tp)
end
function c65830223.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsRelateToEffect(e) end
Duel.SetTargetPlayer(1-tp)
Duel.SetTargetParam(300)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,0,0,1-tp,300)
end
function c65830223.operation(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Damage(p,d,REASON_EFFECT)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c83135907.lua | 3 | 2674 | --スクラップ・ゴブリン
function c83135907.initial_effect(c)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EVENT_BE_BATTLE_TARGET)
e1:SetOperation(c83135907.regop)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(83135907,0))
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EVENT_PHASE+PHASE_BATTLE)
e2:SetCountLimit(1)
e2:SetTarget(c83135907.destg)
e2:SetOperation(c83135907.desop)
c:RegisterEffect(e2)
--search
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(83135907,1))
e3:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_TO_GRAVE)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY)
e3:SetCondition(c83135907.thcon)
e3:SetTarget(c83135907.thtg)
e3:SetOperation(c83135907.thop)
c:RegisterEffect(e3)
--indes
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e4:SetValue(1)
c:RegisterEffect(e4)
end
function c83135907.regop(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsDefencePos() and e:GetHandler():IsFaceup() then
e:GetHandler():RegisterFlagEffect(83135907,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_BATTLE,0,1)
end
end
function c83135907.destg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():GetFlagEffect(83135907)~=0 end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,e:GetHandler(),1,0,0)
end
function c83135907.desop(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsRelateToEffect(e) then
Duel.Destroy(e:GetHandler(),REASON_EFFECT)
end
end
function c83135907.thcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return bit.band(c:GetReason(),0x41)==0x41 and re and re:GetOwner():IsSetCard(0x24)
end
function c83135907.filter(c)
return c:IsSetCard(0x24) and c:IsType(TYPE_MONSTER) and c:GetCode()~=83135907 and c:IsAbleToHand()
end
function c83135907.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c83135907.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c83135907.filter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,c83135907.filter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function c83135907.thop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,tc)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c57470761.lua | 3 | 4350 | --タイラント・ウィング
function c57470761.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(TIMING_DAMAGE_STEP)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCondition(c57470761.condition)
e1:SetTarget(c57470761.target)
e1:SetOperation(c57470761.activate)
c:RegisterEffect(e1)
end
function c57470761.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentPhase()~=PHASE_DAMAGE or not Duel.IsDamageCalculated()
end
function c57470761.filter(c)
return c:IsFaceup() and c:IsRace(RACE_DRAGON)
end
function c57470761.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c57470761.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c57470761.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c57470761.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
end
function c57470761.activate(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsLocation(LOCATION_SZONE) then return end
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then
Duel.Equip(tp,c,tc)
c:CancelToGrave()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_EQUIP_LIMIT)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetValue(c57470761.eqlimit)
e1:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_EQUIP)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetValue(400)
e2:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EFFECT_UPDATE_DEFENCE)
c:RegisterEffect(e3)
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_EQUIP)
e4:SetCode(EFFECT_EXTRA_ATTACK)
e4:SetValue(1)
e4:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e4)
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_EQUIP)
e5:SetCode(EFFECT_CANNOT_DIRECT_ATTACK)
e5:SetCondition(c57470761.dircon)
e5:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e5)
local e6=e5:Clone()
e6:SetCode(EFFECT_CANNOT_ATTACK)
e6:SetCondition(c57470761.atkcon)
c:RegisterEffect(e6)
local e7=Effect.CreateEffect(c)
e7:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e7:SetCode(EVENT_BATTLE_START)
e7:SetRange(LOCATION_SZONE)
e7:SetOperation(c57470761.regop)
e7:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e7)
local e8=Effect.CreateEffect(c)
e8:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e8:SetCode(EVENT_EQUIP)
e8:SetRange(LOCATION_SZONE)
e8:SetOperation(c57470761.resetop)
e8:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e8)
local e9=Effect.CreateEffect(c)
e9:SetCategory(CATEGORY_DESTROY)
e9:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e9:SetCode(EVENT_PHASE+PHASE_END)
e9:SetRange(LOCATION_SZONE)
e9:SetCountLimit(1)
e9:SetCondition(c57470761.descon)
e9:SetTarget(c57470761.destg)
e9:SetOperation(c57470761.desop)
e9:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e9)
end
end
function c57470761.eqlimit(e,c)
return c:IsRace(RACE_DRAGON)
end
function c57470761.dircon(e)
return e:GetHandler():GetEquipTarget():GetAttackAnnouncedCount()>0
end
function c57470761.atkcon(e)
return e:GetHandler():GetEquipTarget():IsDirectAttacked()
end
function c57470761.regop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local ec=c:GetEquipTarget()
if not ec:IsRelateToBattle() then return end
local bc=ec:GetBattleTarget()
if bc and bc:IsControler(1-tp) then
c:RegisterFlagEffect(57470761,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1)
end
end
function c57470761.resetop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if eg:IsContains(c) then
c:ResetFlagEffect(57470761)
end
end
function c57470761.descon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetFlagEffect(57470761)~=0
end
function c57470761.destg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,e:GetHandler(),1,0,0)
end
function c57470761.desop(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsRelateToEffect(e) then
Duel.Destroy(e:GetHandler(),REASON_EFFECT)
end
end
| gpl-2.0 |
t4im/homedecor_modpack | homedecor/furniture_recipes.lua | 14 | 5117 |
minetest.register_craft({
output = "homedecor:table", "homedecor:chair 2",
recipe = {
{ "group:wood","group:wood", "group:wood" },
{ "group:stick", "", "group:stick" },
},
})
minetest.register_craft({
type = "shapeless",
output = "homedecor:table_mahogany",
recipe = {
"homedecor:table",
"dye:brown",
},
})
minetest.register_craft({
type = "shapeless",
output = "homedecor:table_mahogany",
recipe = {
"homedecor:table",
"unifieddyes:dark_orange",
},
})
minetest.register_craft({
type = "shapeless",
output = "homedecor:table_white",
recipe = {
"homedecor:table",
"dye:white",
},
})
minetest.register_craft({
type = "fuel",
recipe = "homedecor:table",
burntime = 30,
})
minetest.register_craft({
type = "fuel",
recipe = "homedecor:table_mahogany",
burntime = 30,
})
minetest.register_craft({
type = "fuel",
recipe = "homedecor:table_white",
burntime = 30,
})
minetest.register_craft({
output = "homedecor:chair 2",
recipe = {
{ "group:stick",""},
{ "group:wood","group:wood" },
{ "group:stick","group:stick" },
},
})
minetest.register_craft({
type = "fuel",
recipe = "homedecor:chair",
burntime = 15,
})
local chaircolors = { "black", "red", "pink", "violet", "blue", "dark_green" }
for _, color in ipairs(chaircolors) do
minetest.register_craft({
type = "shapeless",
output = "homedecor:chair_"..color,
recipe = {
"homedecor:chair",
"wool:white",
"dye:"..color
},
})
minetest.register_craft({
type = "shapeless",
output = "homedecor:chair_"..color,
recipe = {
"homedecor:chair",
"wool:"..color
},
})
minetest.register_craft({
type = "fuel",
recipe = "homedecor:chair_"..color,
burntime = 15,
})
end
minetest.register_craft({
type = "fuel",
recipe = "homedecor:armchair",
burntime = 30,
})
minetest.register_craft({
output = "homedecor:table_lamp_white_off",
recipe = {
{"default:paper","default:torch" ,"default:paper"},
{"","group:stick",""},
{"","stairs:slab_wood",""},
},
})
minetest.register_craft({
output = "homedecor:table_lamp_white_off",
recipe = {
{"default:paper","default:torch" ,"default:paper"},
{"","group:stick",""},
{"","moreblocks:slab_wood",""},
},
})
minetest.register_craft({
output = "homedecor:standing_lamp_white_off",
recipe = {
{"homedecor:table_lamp_white_off"},
{"group:stick"},
{"group:stick"},
},
})
minetest.register_craft({
type = "fuel",
recipe = "homedecor:table_lamp_white_off",
burntime = 10,
})
local lamp_colors = { "blue", "green", "pink", "red", "violet" }
for _, color in ipairs(lamp_colors) do
minetest.register_craft({
output = "homedecor:table_lamp_"..color.."_off",
recipe = {
{"wool:"..color,"default:torch" ,"wool:"..color},
{"","group:stick",""},
{"","stairs:slab_wood",""},
},
})
minetest.register_craft({
output = "homedecor:table_lamp_"..color.."_off",
recipe = {
{"wool:"..color,"default:torch" ,"wool:"..color},
{"","group:stick",""},
{"","moreblocks:slab_wood",""},
},
})
minetest.register_craft({
type = "shapeless",
output = "homedecor:table_lamp_"..color.."_off",
recipe = {
"dye:"..color,
"homedecor:table_lamp_off",
},
})
minetest.register_craft({
type = "fuel",
recipe = "homedecor:table_lamp_"..color.."_off",
burntime = 10,
})
minetest.register_craft({
output = "homedecor:standing_lamp_"..color.."_off",
recipe = {
{"homedecor:table_lamp_"..color.."_off"},
{"group:stick"},
{"group:stick"},
},
})
minetest.register_craft({
type = "shapeless",
output = "homedecor:standing_lamp_"..color.."_off",
recipe = {
"homedecor:standing_lamp_off",
"dye:"..color
},
})
end
minetest.register_craft({
output = "homedecor:toilet",
recipe = {
{"","","bucket:bucket_water"},
{ "group:marble","group:marble", "group:marble" },
{ "", "bucket:bucket_empty", "" },
},
})
minetest.register_craft({
output = "homedecor:sink",
recipe = {
{ "group:marble","bucket:bucket_empty", "group:marble" },
},
})
minetest.register_craft({
output = "homedecor:taps",
recipe = {
{ "default:steel_ingot","bucket:bucket_water", "default:steel_ingot" },
},
})
minetest.register_craft({
output = "homedecor:taps_brass",
recipe = {
{ "technic:brass_ingot","bucket:bucket_water", "technic:brass_ingot" },
},
})
minetest.register_craft({
output = "homedecor:shower_tray",
recipe = {
{ "group:marble","bucket:bucket_water", "group:marble" },
},
})
minetest.register_craft({
output = "homedecor:shower_head",
recipe = {
{"default:steel_ingot", "bucket:bucket_water"},
},
})
minetest.register_craft({
output = "homedecor:bars 6",
recipe = {
{ "default:steel_ingot","default:steel_ingot","default:steel_ingot" },
{ "homedecor:pole_wrought_iron","homedecor:pole_wrought_iron","homedecor:pole_wrought_iron" },
},
})
minetest.register_craft({
output = "homedecor:L_binding_bars 3",
recipe = {
{ "homedecor:bars","" },
{ "homedecor:bars","homedecor:bars" },
},
})
minetest.register_craft({
output = "homedecor:torch_wall 10",
recipe = {
{ "default:coal_lump" },
{ "default:steel_ingot" },
},
})
| lgpl-3.0 |
Lsty/ygopro-scripts | c41386308.lua | 7 | 1814 | --マスマティシャン
function c41386308.initial_effect(c)
--send to grave
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(41386308,0))
e1:SetCategory(CATEGORY_TOGRAVE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetTarget(c41386308.target)
e1:SetOperation(c41386308.operation)
c:RegisterEffect(e1)
--draw
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(41386308,1))
e2:SetCategory(CATEGORY_DRAW)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e2:SetCode(EVENT_BATTLE_DESTROYED)
e2:SetCondition(c41386308.drcon)
e2:SetTarget(c41386308.drtg)
e2:SetOperation(c41386308.drop)
c:RegisterEffect(e2)
end
function c41386308.tgfilter(c)
return c:IsLevelBelow(4) and c:IsAbleToGrave()
end
function c41386308.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c41386308.tgfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK)
end
function c41386308.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c41386308.tgfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoGrave(g,REASON_EFFECT)
end
end
function c41386308.drcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsLocation(LOCATION_GRAVE) and c:IsReason(REASON_BATTLE)
end
function c41386308.drtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(1)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c41386308.drop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Draw(p,d,REASON_EFFECT)
end | gpl-2.0 |
Lsty/ygopro-scripts | c10489311.lua | 5 | 1082 | --ヒーロー・メダル
function c10489311.initial_effect(c)
--draw
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(10489311,0))
e1:SetCategory(CATEGORY_TODECK+CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c10489311.drcon)
e1:SetTarget(c10489311.drtg)
e1:SetOperation(c10489311.drop)
c:RegisterEffect(e1)
end
function c10489311.drcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return bit.band(r,0x41)==0x41 and rp~=tp and c:GetPreviousControler()==tp
and c:IsPreviousLocation(LOCATION_ONFIELD) and c:IsPreviousPosition(POS_FACEDOWN)
end
function c10489311.drtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_TODECK,e:GetHandler(),1,0,0)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c10489311.drop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and Duel.SendtoDeck(c,nil,2,REASON_EFFECT)~=0 and c:IsLocation(LOCATION_DECK) then
Duel.ShuffleDeck(tp)
Duel.Draw(tp,1,REASON_EFFECT)
end
end
| gpl-2.0 |
Distrotech/vlc | share/lua/sd/katsomo.lua | 110 | 1336 | --[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Ilkka Ollakka <ileoo 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.
--]]
function descriptor()
return { title="Katsomo.fi"}
end
function find( haystack, needle )
local _,_,r = string.find( haystack, needle )
return r
end
function main()
vlc.sd.add_item( {title="Uutiset ja fakta", path="http://www.katsomo.fi/?treeId=1"} )
vlc.sd.add_item( {title="Urheilu", path="http://www.katsomo.fi/?treeId=2000021"} )
vlc.sd.add_item( {title="Viihde ja sarjat", path="http://www.katsomo.fi/?treeId=3"} )
vlc.sd.add_item( {title="Lifestyle", path="http://www.katsomo.fi/?treeId=8"} )
end
| gpl-2.0 |
Mijyuoon/starfall | lua/moonscript/lulpeg.lua | 1 | 79641 | -- LuLPeg, a pure Lua port of LPeg, Roberto Ierusalimschy's
-- Parsing Expression Grammars library.
--
-- Copyright (C) Pierre-Yves Gerardy.
-- Released under the Romantic WTF Public License (cf. the LICENSE
-- file or the end of this file, whichever is present).
--
-- See http://www.inf.puc-rio.br/~roberto/lpeg/ for the original.
--
-- The re.lua module and the test suite (tests/lpeg.*.*.tests.lua)
-- are part of the original LPeg distribution.
local _ENV, loaded, packages, release
= _ENV or _G, {}, {}, true
local deflibs = {
string = string,
math = math,
table = table,
debug = debug,
}
local function require(...)
local lib = ...
-- is it a private file?
if loaded[lib] then
return loaded[lib]
elseif packages[lib] then
loaded[lib] = packages[lib](lib)
return loaded[lib]
elseif deflibs[lib] then
return deflibs[lib]
else
return false
end
end
--=============================================================================
do local _ENV = _ENV
packages['analizer'] = function (...)
local u = require"util"
local nop, weakkey = u.nop, u.weakkey
local hasVcache, hasCmtcache , lengthcache
= weakkey{}, weakkey{}, weakkey{}
return {
hasV = nop,
hasCmt = nop,
length = nop,
hasCapture = nop
}
end
end
--=============================================================================
do local _ENV = _ENV
packages['compiler'] = function (...)
local assert, error, pairs, rawset, select, setmetatable, tostring, type
= assert, error, pairs, rawset, select, setmetatable, tostring, type
local s, t, u = require"string", require"table", require"util"
local _ENV = u.noglobals() ----------------------------------------------------
local s_byte, s_sub, t_concat, t_insert, t_remove, t_unpack
= s.byte, s.sub, t.concat, t.insert, t.remove, u.unpack
local load, map, map_all, t_pack
= u.load, u.map, u.map_all, u.pack
local expose = u.expose
return function(Builder, LL)
local evaluate, LL_ispattern = LL.evaluate, LL.ispattern
local charset = Builder.charset
local compilers = {}
local
function compile(pt, ccache)
if not LL_ispattern(pt) then
error("pattern expected")
end
local typ = pt.pkind
if typ == "grammar" then
ccache = {}
elseif typ == "ref" or typ == "choice" or typ == "sequence" then
if not ccache[pt] then
ccache[pt] = compilers[typ](pt, ccache)
end
return ccache[pt]
end
if not pt.compiled then
pt.compiled = compilers[pt.pkind](pt, ccache)
end
return pt.compiled
end
LL.compile = compile
local
function clear_captures(ary, ci)
for i = ci, #ary do ary[i] = nil end
end
local LL_compile, LL_evaluate, LL_P
= LL.compile, LL.evaluate, LL.P
local function computeidex(i, len)
if i == 0 or i == 1 or i == nil then return 1
elseif type(i) ~= "number" then error"number or nil expected for the stating index"
elseif i > 0 then return i > len and len + 1 or i
else return len + i < 0 and 1 or len + i + 1
end
end
local function newcaps()
return {
kind = {},
bounds = {},
openclose = {},
aux = -- [[DBG]] dbgcaps
{}
}
end
local
function _match(dbg, pt, sbj, si, ...)
if dbg then -------------
print("@!!! Match !!!@", pt)
end ---------------------
pt = LL_P(pt)
assert(type(sbj) == "string", "string expected for the match subject")
si = computeidex(si, #sbj)
if dbg then -------------
print(("-"):rep(30))
print(pt.pkind)
LL.pprint(pt)
end ---------------------
local matcher = compile(pt, {})
local caps = newcaps()
local matcher_state = {grammars = {}, args = {n = select('#',...),...}, tags = {}}
local success, final_si, ci = matcher(sbj, si, caps, 1, matcher_state)
if dbg then -------------
print("!!! Done Matching !!! success: ", success,
"final position", final_si, "final cap index", ci,
"#caps", #caps.openclose)
end----------------------
if success then
clear_captures(caps.kind, ci)
clear_captures(caps.aux, ci)
if dbg then -------------
print("trimmed cap index = ", #caps + 1)
LL.cprint(caps, sbj, 1)
end ---------------------
local values, _, vi = LL_evaluate(caps, sbj, 1, 1)
if dbg then -------------
print("#values", vi)
expose(values)
end ---------------------
if vi == 0
then return final_si
else return t_unpack(values, 1, vi) end
else
if dbg then print("Failed") end
return nil
end
end
function LL.match(...)
return _match(false, ...)
end
function LL.dmatch(...)
return _match(true, ...)
end
for _, v in pairs{
"C", "Cf", "Cg", "Cs", "Ct", "Clb",
"div_string", "div_table", "div_number", "div_function"
} do
compilers[v] = load(([=[
local compile, expose, type, LL = ...
return function (pt, ccache)
local matcher, this_aux = compile(pt.pattern, ccache), pt.aux
return function (sbj, si, caps, ci, state)
local ref_ci = ci
local kind, bounds, openclose, aux
= caps.kind, caps.bounds, caps.openclose, caps.aux
kind [ci] = "XXXX"
bounds [ci] = si
openclose [ci] = 0
caps.aux [ci] = (this_aux or false)
local success
success, si, ci
= matcher(sbj, si, caps, ci + 1, state)
if success then
if ci == ref_ci + 1 then
caps.openclose[ref_ci] = si
else
kind [ci] = "XXXX"
bounds [ci] = si
openclose [ci] = ref_ci - ci
aux [ci] = this_aux or false
ci = ci + 1
end
else
ci = ci - 1
end
return success, si, ci
end
end]=]):gsub("XXXX", v), v.." compiler")(compile, expose, type, LL)
end
compilers["Carg"] = function (pt, ccache)
local n = pt.aux
return function (sbj, si, caps, ci, state)
if state.args.n < n then error("reference to absent argument #"..n) end
caps.kind [ci] = "value"
caps.bounds [ci] = si
if state.args[n] == nil then
caps.openclose [ci] = 1/0
caps.aux [ci] = 1/0
else
caps.openclose [ci] = si
caps.aux [ci] = state.args[n]
end
return true, si, ci + 1
end
end
for _, v in pairs{
"Cb", "Cc", "Cp"
} do
compilers[v] = load(([=[
return function (pt, ccache)
local this_aux = pt.aux
return function (sbj, si, caps, ci, state)
caps.kind [ci] = "XXXX"
caps.bounds [ci] = si
caps.openclose [ci] = si
caps.aux [ci] = this_aux or false
return true, si, ci + 1
end
end]=]):gsub("XXXX", v), v.." compiler")(expose)
end
compilers["/zero"] = function (pt, ccache)
local matcher = compile(pt.pattern, ccache)
return function (sbj, si, caps, ci, state)
local success, nsi = matcher(sbj, si, caps, ci, state)
clear_captures(caps.aux, ci)
return success, nsi, ci
end
end
local function pack_Cmt_caps(i,...) return i, t_pack(...) end
compilers["Cmt"] = function (pt, ccache)
local matcher, func = compile(pt.pattern, ccache), pt.aux
return function (sbj, si, caps, ci, state)
local success, Cmt_si, Cmt_ci = matcher(sbj, si, caps, ci, state)
if not success then
clear_captures(caps.aux, ci)
return false, si, ci
end
local final_si, values
if Cmt_ci == ci then
final_si, values = pack_Cmt_caps(
func(sbj, Cmt_si, s_sub(sbj, si, Cmt_si - 1))
)
else
clear_captures(caps.aux, Cmt_ci)
clear_captures(caps.kind, Cmt_ci)
local cps, _, nn = evaluate(caps, sbj, ci)
final_si, values = pack_Cmt_caps(
func(sbj, Cmt_si, t_unpack(cps, 1, nn))
)
end
if not final_si then
return false, si, ci
end
if final_si == true then final_si = Cmt_si end
if type(final_si) == "number"
and si <= final_si
and final_si <= #sbj + 1
then
local kind, bounds, openclose, aux
= caps.kind, caps.bounds, caps.openclose, caps.aux
for i = 1, values.n do
kind [ci] = "value"
bounds [ci] = si
if values[i] == nil then
caps.openclose [ci] = 1/0
caps.aux [ci] = 1/0
else
caps.openclose [ci] = final_si
caps.aux [ci] = values[i]
end
ci = ci + 1
end
elseif type(final_si) == "number" then
error"Index out of bounds returned by match-time capture."
else
error("Match time capture must return a number, a boolean or nil"
.." as first argument, or nothing at all.")
end
return true, final_si, ci
end
end
compilers["string"] = function (pt, ccache)
local S = pt.aux
local N = #S
return function(sbj, si, caps, ci, state)
local in_1 = si - 1
for i = 1, N do
local c
c = s_byte(sbj,in_1 + i)
if c ~= S[i] then
return false, si, ci
end
end
return true, si + N, ci
end
end
compilers["char"] = function (pt, ccache)
return load(([=[
local s_byte, s_char = ...
return function(sbj, si, caps, ci, state)
local c, nsi = s_byte(sbj, si), si + 1
if c ~= __C0__ then
return false, si, ci
end
return true, nsi, ci
end]=]):gsub("__C0__", tostring(pt.aux)))(s_byte, ("").char)
end
local
function truecompiled (sbj, si, caps, ci, state)
return true, si, ci
end
compilers["true"] = function (pt)
return truecompiled
end
local
function falsecompiled (sbj, si, caps, ci, state)
return false, si, ci
end
compilers["false"] = function (pt)
return falsecompiled
end
local
function eoscompiled (sbj, si, caps, ci, state)
return si > #sbj, si, ci
end
compilers["eos"] = function (pt)
return eoscompiled
end
local
function onecompiled (sbj, si, caps, ci, state)
local char, _ = s_byte(sbj, si), si + 1
if char
then return true, si + 1, ci
else return false, si, ci end
end
compilers["one"] = function (pt)
return onecompiled
end
compilers["any"] = function (pt)
local N = pt.aux
if N == 1 then
return onecompiled
else
N = pt.aux - 1
return function (sbj, si, caps, ci, state)
local n = si + N
if n <= #sbj then
return true, n + 1, ci
else
return false, si, ci
end
end
end
end
do
local function checkpatterns(g)
for k,v in pairs(g.aux) do
if not LL_ispattern(v) then
error(("rule 'A' is not a pattern"):gsub("A", tostring(k)))
end
end
end
compilers["grammar"] = function (pt, ccache)
checkpatterns(pt)
local gram = map_all(pt.aux, compile, ccache)
local start = gram[1]
return function (sbj, si, caps, ci, state)
t_insert(state.grammars, gram)
local success, nsi, ci = start(sbj, si, caps, ci, state)
t_remove(state.grammars)
return success, nsi, ci
end
end
end
local dummy_acc = {kind={}, bounds={}, openclose={}, aux={}}
compilers["behind"] = function (pt, ccache)
local matcher, N = compile(pt.pattern, ccache), pt.aux
return function (sbj, si, caps, ci, state)
if si <= N then return false, si, ci end
local success = matcher(sbj, si - N, dummy_acc, ci, state)
dummy_acc.aux = {}
return success, si, ci
end
end
compilers["range"] = function (pt)
local ranges = pt.aux
return function (sbj, si, caps, ci, state)
local char, nsi = s_byte(sbj, si), si + 1
for i = 1, #ranges do
local r = ranges[i]
if char and r[char]
then return true, nsi, ci end
end
return false, si, ci
end
end
compilers["set"] = function (pt)
local s = pt.aux
return function (sbj, si, caps, ci, state)
local char, nsi = s_byte(sbj, si), si + 1
if s[char]
then return true, nsi, ci
else return false, si, ci end
end
end
compilers["range"] = compilers.set
compilers["ref"] = function (pt, ccache)
local name = pt.aux
local ref
return function (sbj, si, caps, ci, state)
if not ref then
if #state.grammars == 0 then
error(("rule 'XXXX' used outside a grammar"):gsub("XXXX", tostring(name)))
elseif not state.grammars[#state.grammars][name] then
error(("rule 'XXXX' undefined in given grammar"):gsub("XXXX", tostring(name)))
end
ref = state.grammars[#state.grammars][name]
end
local success, nsi, nci = ref(sbj, si, caps, ci, state)
return success, nsi, nci
end
end
local choice_tpl = [=[
success, si, ci = XXXX(sbj, si, caps, ci, state)
if success then
return true, si, ci
else
end]=]
compilers["choice"] = function (pt, ccache)
local choices, n = map(pt.aux, compile, ccache), #pt.aux
local names, chunks = {}, {}
for i = 1, n do
local m = "ch"..i
names[#names + 1] = m
chunks[ #names ] = choice_tpl:gsub("XXXX", m)
end
names[#names + 1] = "clear_captures"
choices[ #names ] = clear_captures
local compiled = t_concat{
"local ", t_concat(names, ", "), [=[ = ...
return function (sbj, si, caps, ci, state)
local aux, success = caps.aux, false
]=],
t_concat(chunks,"\n"),[=[--
return false, si, ci
end]=]
}
return load(compiled, "Choice")(t_unpack(choices))
end
local sequence_tpl = [=[
success, si, ci = XXXX(sbj, si, caps, ci, state)
if not success then
return false, ref_si, ref_ci
end]=]
compilers["sequence"] = function (pt, ccache)
local sequence, n = map(pt.aux, compile, ccache), #pt.aux
local names, chunks = {}, {}
for i = 1, n do
local m = "seq"..i
names[#names + 1] = m
chunks[ #names ] = sequence_tpl:gsub("XXXX", m)
end
names[#names + 1] = "clear_captures"
sequence[ #names ] = clear_captures
local compiled = t_concat{
"local ", t_concat(names, ", "), [=[ = ...
return function (sbj, si, caps, ci, state)
local ref_si, ref_ci, success = si, ci
]=],
t_concat(chunks,"\n"),[=[
return true, si, ci
end]=]
}
return load(compiled, "Sequence")(t_unpack(sequence))
end
compilers["at most"] = function (pt, ccache)
local matcher, n = compile(pt.pattern, ccache), pt.aux
n = -n
return function (sbj, si, caps, ci, state)
local success = true
for i = 1, n do
success, si, ci = matcher(sbj, si, caps, ci, state)
if not success then
break
end
end
return true, si, ci
end
end
compilers["at least"] = function (pt, ccache)
local matcher, n = compile(pt.pattern, ccache), pt.aux
if n == 0 then
return function (sbj, si, caps, ci, state)
local last_si, last_ci
while true do
local success
last_si, last_ci = si, ci
success, si, ci = matcher(sbj, si, caps, ci, state)
if not success then
si, ci = last_si, last_ci
break
end
end
return true, si, ci
end
elseif n == 1 then
return function (sbj, si, caps, ci, state)
local last_si, last_ci
local success = true
success, si, ci = matcher(sbj, si, caps, ci, state)
if not success then
return false, si, ci
end
while true do
local success
last_si, last_ci = si, ci
success, si, ci = matcher(sbj, si, caps, ci, state)
if not success then
si, ci = last_si, last_ci
break
end
end
return true, si, ci
end
else
return function (sbj, si, caps, ci, state)
local last_si, last_ci
local success = true
for _ = 1, n do
success, si, ci = matcher(sbj, si, caps, ci, state)
if not success then
return false, si, ci
end
end
while true do
local success
last_si, last_ci = si, ci
success, si, ci = matcher(sbj, si, caps, ci, state)
if not success then
si, ci = last_si, last_ci
break
end
end
return true, si, ci
end
end
end
compilers["unm"] = function (pt, ccache)
if pt.pkind == "any" and pt.aux == 1 then
return eoscompiled
end
local matcher = compile(pt.pattern, ccache)
return function (sbj, si, caps, ci, state)
local success, _, _ = matcher(sbj, si, caps, ci, state)
return not success, si, ci
end
end
compilers["lookahead"] = function (pt, ccache)
local matcher = compile(pt.pattern, ccache)
return function (sbj, si, caps, ci, state)
local success, _, _ = matcher(sbj, si, caps, ci, state)
return success, si, ci
end
end
end
end
end
--=============================================================================
do local _ENV = _ENV
packages['datastructures'] = function (...)
local getmetatable, pairs, setmetatable, type
= getmetatable, pairs, setmetatable, type
local m, t , u = require"math", require"table", require"util"
local compat = require"compat"
local ffi if compat.luajit then
ffi = require"ffi"
end
local _ENV = u.noglobals() ----------------------------------------------------
local extend, load, u_max
= u.extend, u.load, u.max
local m_max, t_concat, t_insert, t_sort
= m.max, t.concat, t.insert, t.sort
local structfor = {}
local byteset_new, isboolset, isbyteset
local byteset_mt = {}
local
function byteset_constructor (upper)
local set = setmetatable(load(t_concat{
"return{ [0]=false",
(", false"):rep(upper),
" }"
})(),
byteset_mt)
return set
end
if compat.jit then
local struct, boolset_constructor = {v={}}
function byteset_mt.__index(s,i)
if i == nil or i > s.upper then return nil end
return s.v[i]
end
function byteset_mt.__len(s)
return s.upper
end
function byteset_mt.__newindex(s,i,v)
s.v[i] = v
end
boolset_constructor = ffi.metatype('struct { int upper; bool v[?]; }', byteset_mt)
function byteset_new (t)
if type(t) == "number" then
local res = boolset_constructor(t+1)
res.upper = t
return res
end
local upper = u_max(t)
struct.upper = upper
if upper > 255 then error"bool_set overflow" end
local set = boolset_constructor(upper+1)
set.upper = upper
for i = 1, #t do set[t[i]] = true end
return set
end
function isboolset(s) return type(s)=="cdata" and ffi.istype(s, boolset_constructor) end
isbyteset = isboolset
else
function byteset_new (t)
if type(t) == "number" then return byteset_constructor(t) end
local set = byteset_constructor(u_max(t))
for i = 1, #t do set[t[i]] = true end
return set
end
function isboolset(s) return false end
function isbyteset (s)
return getmetatable(s) == byteset_mt
end
end
local
function byterange_new (low, high)
high = ( low <= high ) and high or -1
local set = byteset_new(high)
for i = low, high do
set[i] = true
end
return set
end
local tmpa, tmpb ={}, {}
local
function set_if_not_yet (s, dest)
if type(s) == "number" then
dest[s] = true
return dest
else
return s
end
end
local
function clean_ab (a,b)
tmpa[a] = nil
tmpb[b] = nil
end
local
function byteset_union (a ,b)
local upper = m_max(
type(a) == "number" and a or #a,
type(b) == "number" and b or #b
)
local A, B
= set_if_not_yet(a, tmpa)
, set_if_not_yet(b, tmpb)
local res = byteset_new(upper)
for i = 0, upper do
res[i] = A[i] or B[i] or false
end
clean_ab(a,b)
return res
end
local
function byteset_difference (a, b)
local res = {}
for i = 0, 255 do
res[i] = a[i] and not b[i]
end
return res
end
local
function byteset_tostring (s)
local list = {}
for i = 0, 255 do
list[#list+1] = (s[i] == true) and i or nil
end
return t_concat(list,", ")
end
structfor.binary = {
set ={
new = byteset_new,
union = byteset_union,
difference = byteset_difference,
tostring = byteset_tostring
},
Range = byterange_new,
isboolset = isboolset,
isbyteset = isbyteset,
isset = isbyteset
}
local set_mt = {}
local
function set_new (t)
local set = setmetatable({}, set_mt)
for i = 1, #t do set[t[i]] = true end
return set
end
local -- helper for the union code.
function add_elements(a, res)
for k in pairs(a) do res[k] = true end
return res
end
local
function set_union (a, b)
a, b = (type(a) == "number") and set_new{a} or a
, (type(b) == "number") and set_new{b} or b
local res = set_new{}
add_elements(a, res)
add_elements(b, res)
return res
end
local
function set_difference(a, b)
local list = {}
a, b = (type(a) == "number") and set_new{a} or a
, (type(b) == "number") and set_new{b} or b
for el in pairs(a) do
if a[el] and not b[el] then
list[#list+1] = el
end
end
return set_new(list)
end
local
function set_tostring (s)
local list = {}
for el in pairs(s) do
t_insert(list,el)
end
t_sort(list)
return t_concat(list, ",")
end
local
function isset (s)
return (getmetatable(s) == set_mt)
end
local
function range_new (start, finish)
local list = {}
for i = start, finish do
list[#list + 1] = i
end
return set_new(list)
end
structfor.other = {
set = {
new = set_new,
union = set_union,
tostring = set_tostring,
difference = set_difference,
},
Range = range_new,
isboolset = isboolset,
isbyteset = isbyteset,
isset = isset,
isrange = function(a) return false end
}
return function(Builder, LL)
local cs = (Builder.options or {}).charset or "binary"
if type(cs) == "string" then
cs = (cs == "binary") and "binary" or "other"
else
cs = cs.binary and "binary" or "other"
end
return extend(Builder, structfor[cs])
end
end
end
--=============================================================================
do local _ENV = _ENV
packages['charsets'] = function (...)
local s, t, u = require"string", require"table", require"util"
local _ENV = u.noglobals() ----------------------------------------------------
local copy = u.copy
local s_char, s_sub, s_byte, t_concat, t_insert
= s.char, s.sub, s.byte, t.concat, t.insert
local
function utf8_offset (byte)
if byte < 128 then return 0, byte
elseif byte < 192 then
error("Byte values between 0x80 to 0xBF cannot start a multibyte sequence")
elseif byte < 224 then return 1, byte - 192
elseif byte < 240 then return 2, byte - 224
elseif byte < 248 then return 3, byte - 240
elseif byte < 252 then return 4, byte - 248
elseif byte < 254 then return 5, byte - 252
else
error("Byte values between 0xFE and OxFF cannot start a multibyte sequence")
end
end
local
function utf8_validate (subject, start, finish)
start = start or 1
finish = finish or #subject
local offset, char
= 0
for i = start,finish do
local b = s_byte(subject,i)
if offset == 0 then
char = i
success, offset = pcall(utf8_offset, b)
if not success then return false, char - 1 end
else
if not (127 < b and b < 192) then
return false, char - 1
end
offset = offset -1
end
end
if offset ~= 0 then return nil, char - 1 end -- Incomplete input.
return true, finish
end
local
function utf8_next_int (subject, i)
i = i and i+1 or 1
if i > #subject then return end
local c = s_byte(subject, i)
local offset, val = utf8_offset(c)
for i = i+1, i+offset do
c = s_byte(subject, i)
val = val * 64 + (c-128)
end
return i + offset, i, val
end
local
function utf8_next_char (subject, i)
i = i and i+1 or 1
if i > #subject then return end
local offset = utf8_offset(s_byte(subject,i))
return i + offset, i, s_sub(subject, i, i + offset)
end
local
function utf8_split_int (subject)
local chars = {}
for _, _, c in utf8_next_int, subject do
t_insert(chars,c)
end
return chars
end
local
function utf8_split_char (subject)
local chars = {}
for _, _, c in utf8_next_char, subject do
t_insert(chars,c)
end
return chars
end
local
function utf8_get_int(subject, i)
if i > #subject then return end
local c = s_byte(subject, i)
local offset, val = utf8_offset(c)
for i = i+1, i+offset do
c = s_byte(subject, i)
val = val * 64 + ( c - 128 )
end
return val, i + offset + 1
end
local
function split_generator (get)
if not get then return end
return function(subject)
local res = {}
local o, i = true
while o do
o,i = get(subject, i)
res[#res] = o
end
return res
end
end
local
function merge_generator (char)
if not char then return end
return function(ary)
local res = {}
for i = 1, #ary do
t_insert(res,char(ary[i]))
end
return t_concat(res)
end
end
local
function utf8_get_int2 (subject, i)
local byte, b5, b4, b3, b2, b1 = s_byte(subject, i)
if byte < 128 then return byte, i + 1
elseif byte < 192 then
error("Byte values between 0x80 to 0xBF cannot start a multibyte sequence")
elseif byte < 224 then
return (byte - 192)*64 + s_byte(subject, i+1), i+2
elseif byte < 240 then
b2, b1 = s_byte(subject, i+1, i+2)
return (byte-224)*4096 + b2%64*64 + b1%64, i+3
elseif byte < 248 then
b3, b2, b1 = s_byte(subject, i+1, i+2, 1+3)
return (byte-240)*262144 + b3%64*4096 + b2%64*64 + b1%64, i+4
elseif byte < 252 then
b4, b3, b2, b1 = s_byte(subject, i+1, i+2, 1+3, i+4)
return (byte-248)*16777216 + b4%64*262144 + b3%64*4096 + b2%64*64 + b1%64, i+5
elseif byte < 254 then
b5, b4, b3, b2, b1 = s_byte(subject, i+1, i+2, 1+3, i+4, i+5)
return (byte-252)*1073741824 + b5%64*16777216 + b4%64*262144 + b3%64*4096 + b2%64*64 + b1%64, i+6
else
error("Byte values between 0xFE and OxFF cannot start a multibyte sequence")
end
end
local
function utf8_get_char(subject, i)
if i > #subject then return end
local offset = utf8_offset(s_byte(subject,i))
return s_sub(subject, i, i + offset), i + offset + 1
end
local
function utf8_char(c)
if c < 128 then
return s_char(c)
elseif c < 2048 then
return s_char(192 + c/64, 128 + c%64)
elseif c < 55296 or 57343 < c and c < 65536 then
return s_char(224 + c/4096, 128 + c/64%64, 128 + c%64)
elseif c < 2097152 then
return s_char(240 + c/262144, 128 + c/4096%64, 128 + c/64%64, 128 + c%64)
elseif c < 67108864 then
return s_char(248 + c/16777216, 128 + c/262144%64, 128 + c/4096%64, 128 + c/64%64, 128 + c%64)
elseif c < 2147483648 then
return s_char( 252 + c/1073741824,
128 + c/16777216%64, 128 + c/262144%64, 128 + c/4096%64, 128 + c/64%64, 128 + c%64)
end
error("Bad Unicode code point: "..c..".")
end
local
function binary_validate (subject, start, finish)
start = start or 1
finish = finish or #subject
return true, finish
end
local
function binary_next_int (subject, i)
i = i and i+1 or 1
if i >= #subject then return end
return i, i, s_sub(subject, i, i)
end
local
function binary_next_char (subject, i)
i = i and i+1 or 1
if i > #subject then return end
return i, i, s_byte(subject,i)
end
local
function binary_split_int (subject)
local chars = {}
for i = 1, #subject do
t_insert(chars, s_byte(subject,i))
end
return chars
end
local
function binary_split_char (subject)
local chars = {}
for i = 1, #subject do
t_insert(chars, s_sub(subject,i,i))
end
return chars
end
local
function binary_get_int(subject, i)
return s_byte(subject, i), i + 1
end
local
function binary_get_char(subject, i)
return s_sub(subject, i, i), i + 1
end
local charsets = {
binary = {
name = "binary",
binary = true,
validate = binary_validate,
split_char = binary_split_char,
split_int = binary_split_int,
next_char = binary_next_char,
next_int = binary_next_int,
get_char = binary_get_char,
get_int = binary_get_int,
tochar = s_char
},
["UTF-8"] = {
name = "UTF-8",
validate = utf8_validate,
split_char = utf8_split_char,
split_int = utf8_split_int,
next_char = utf8_next_char,
next_int = utf8_next_int,
get_char = utf8_get_char,
get_int = utf8_get_int
}
}
return function (Builder)
local cs = Builder.options.charset or "binary"
if charsets[cs] then
Builder.charset = copy(charsets[cs])
Builder.binary_split_int = binary_split_int
else
error("NYI: custom charsets")
end
end
end
end
--=============================================================================
do local _ENV = _ENV
packages['evaluator'] = function (...)
local select, tonumber, tostring, type
= select, tonumber, tostring, type
local s, t, u = require"string", require"table", require"util"
local s_sub, t_concat
= s.sub, t.concat
local t_unpack
= u.unpack
local _ENV = u.noglobals() ----------------------------------------------------
return function(Builder, LL) -- Decorator wrapper
local eval = {}
local
function insert (caps, sbj, vals, ci, vi)
local openclose, kind = caps.openclose, caps.kind
while kind[ci] and openclose[ci] >= 0 do
ci, vi = eval[kind[ci]](caps, sbj, vals, ci, vi)
end
return ci, vi
end
function eval.C (caps, sbj, vals, ci, vi)
if caps.openclose[ci] > 0 then
vals[vi] = s_sub(sbj, caps.bounds[ci], caps.openclose[ci] - 1)
return ci + 1, vi + 1
end
vals[vi] = false -- pad it for now
local cj, vj = insert(caps, sbj, vals, ci + 1, vi + 1)
vals[vi] = s_sub(sbj, caps.bounds[ci], caps.bounds[cj] - 1)
return cj + 1, vj
end
local
function lookback (caps, label, ci)
local aux, openclose, kind= caps.aux, caps.openclose, caps.kind
repeat
ci = ci - 1
local auxv, oc = aux[ci], openclose[ci]
if oc < 0 then ci = ci + oc end
if oc ~= 0 and kind[ci] == "Clb" and label == auxv then
return ci
end
until ci == 1
label = type(label) == "string" and "'"..label.."'" or tostring(label)
error("back reference "..label.." not found")
end
function eval.Cb (caps, sbj, vals, ci, vi)
local Cb_ci = lookback(caps, caps.aux[ci], ci)
Cb_ci, vi = eval.Cg(caps, sbj, vals, Cb_ci, vi)
return ci + 1, vi
end
function eval.Cc (caps, sbj, vals, ci, vi)
local these_values = caps.aux[ci]
for i = 1, these_values.n do
vi, vals[vi] = vi + 1, these_values[i]
end
return ci + 1, vi
end
eval["Cf"] = function() error("NYI: Cf") end
function eval.Cf (caps, sbj, vals, ci, vi)
if caps.openclose[ci] > 0 then
error"No First Value"
end
local func, Cf_vals, Cf_vi = caps.aux[ci], {}
ci = ci + 1
ci, Cf_vi = eval[caps.kind[ci]](caps, sbj, Cf_vals, ci, 1)
if Cf_vi == 1 then
error"No first value"
end
local result = Cf_vals[1]
while caps.kind[ci] and caps.openclose[ci] >= 0 do
ci, Cf_vi = eval[caps.kind[ci]](caps, sbj, Cf_vals, ci, 1)
result = func(result, t_unpack(Cf_vals, 1, Cf_vi - 1))
end
vals[vi] = result
return ci +1, vi + 1
end
function eval.Cg (caps, sbj, vals, ci, vi)
if caps.openclose[ci] > 0 then
vals[vi] = s_sub(sbj, caps.bounds[ci], caps.openclose[ci] - 1)
return ci + 1, vi + 1
end
local cj, vj = insert(caps, sbj, vals, ci + 1, vi)
if vj == vi then
vals[vj] = s_sub(sbj, caps.bounds[ci], caps.bounds[cj] - 1)
vj = vj + 1
end
return cj + 1, vj
end
function eval.Clb (caps, sbj, vals, ci, vi)
local oc = caps.openclose
if oc[ci] > 0 then
return ci + 1, vi
end
local depth = 0
repeat
if oc[ci] == 0 then depth = depth + 1
elseif oc[ci] < 0 then depth = depth - 1
end
ci = ci + 1
until depth == 0
return ci, vi
end
function eval.Cp (caps, sbj, vals, ci, vi)
vals[vi] = caps.bounds[ci]
return ci + 1, vi + 1
end
function eval.Ct (caps, sbj, vals, ci, vi)
local aux, openclose, kind = caps. aux, caps.openclose, caps.kind
local tbl_vals = {}
vals[vi] = tbl_vals
if openclose[ci] > 0 then
return ci + 1, vi + 1
end
local tbl_vi, Clb_vals = 1, {}
ci = ci + 1
while kind[ci] and openclose[ci] >= 0 do
if kind[ci] == "Clb" then
local label, Clb_vi = aux[ci], 1
ci, Clb_vi = eval.Cg(caps, sbj, Clb_vals, ci, 1)
if Clb_vi ~= 1 then tbl_vals[label] = Clb_vals[1] end
else
ci, tbl_vi = eval[kind[ci]](caps, sbj, tbl_vals, ci, tbl_vi)
end
end
return ci + 1, vi + 1
end
local inf = 1/0
function eval.value (caps, sbj, vals, ci, vi)
local val
if caps.aux[ci] ~= inf or caps.openclose[ci] ~= inf
then val = caps.aux[ci]
end
vals[vi] = val
return ci + 1, vi + 1
end
function eval.Cs (caps, sbj, vals, ci, vi)
if caps.openclose[ci] > 0 then
vals[vi] = s_sub(sbj, caps.bounds[ci], caps.openclose[ci] - 1)
else
local bounds, kind, openclose = caps.bounds, caps.kind, caps.openclose
local start, buffer, Cs_vals, bi, Cs_vi = bounds[ci], {}, {}, 1, 1
local last
ci = ci + 1
while openclose[ci] >= 0 do
last = bounds[ci]
buffer[bi] = s_sub(sbj, start, last - 1)
bi = bi + 1
ci, Cs_vi = eval[kind[ci]](caps, sbj, Cs_vals, ci, 1)
if Cs_vi > 1 then
buffer[bi] = Cs_vals[1]
bi = bi + 1
start = openclose[ci-1] > 0 and openclose[ci-1] or bounds[ci-1]
else
start = last
end
end
buffer[bi] = s_sub(sbj, start, bounds[ci] - 1)
vals[vi] = t_concat(buffer)
end
return ci + 1, vi + 1
end
local
function insert_divfunc_results(acc, val_i, ...)
local n = select('#', ...)
for i = 1, n do
val_i, acc[val_i] = val_i + 1, select(i, ...)
end
return val_i
end
function eval.div_function (caps, sbj, vals, ci, vi)
local func = caps.aux[ci]
local params, divF_vi
if caps.openclose[ci] > 0 then
params, divF_vi = {s_sub(sbj, caps.bounds[ci], caps.openclose[ci] - 1)}, 2
else
params = {}
ci, divF_vi = insert(caps, sbj, params, ci + 1, 1)
end
ci = ci + 1 -- skip the closed or closing node.
vi = insert_divfunc_results(vals, vi, func(t_unpack(params, 1, divF_vi - 1)))
return ci, vi
end
function eval.div_number (caps, sbj, vals, ci, vi)
local this_aux = caps.aux[ci]
local divN_vals, divN_vi
if caps.openclose[ci] > 0 then
divN_vals, divN_vi = {s_sub(sbj, caps.bounds[ci], caps.openclose[ci] - 1)}, 2
else
divN_vals = {}
ci, divN_vi = insert(caps, sbj, divN_vals, ci + 1, 1)
end
ci = ci + 1 -- skip the closed or closing node.
if this_aux >= divN_vi then error("no capture '"..this_aux.."' in /number capture.") end
vals[vi] = divN_vals[this_aux]
return ci, vi + 1
end
local function div_str_cap_refs (caps, ci)
local opcl = caps.openclose
local refs = {open=caps.bounds[ci]}
if opcl[ci] > 0 then
refs.close = opcl[ci]
return ci + 1, refs, 0
end
local first_ci = ci
local depth = 1
ci = ci + 1
repeat
local oc = opcl[ci]
if depth == 1 and oc >= 0 then refs[#refs+1] = ci end
if oc == 0 then
depth = depth + 1
elseif oc < 0 then
depth = depth - 1
end
ci = ci + 1
until depth == 0
refs.close = caps.bounds[ci - 1]
return ci, refs, #refs
end
function eval.div_string (caps, sbj, vals, ci, vi)
local n, refs
local cached
local cached, divS_vals = {}, {}
local the_string = caps.aux[ci]
ci, refs, n = div_str_cap_refs(caps, ci)
vals[vi] = the_string:gsub("%%([%d%%])", function (d)
if d == "%" then return "%" end
d = tonumber(d)
if not cached[d] then
if d > n then
error("no capture at index "..d.." in /string capture.")
end
if d == 0 then
cached[d] = s_sub(sbj, refs.open, refs.close - 1)
else
local _, vi = eval[caps.kind[refs[d]]](caps, sbj, divS_vals, refs[d], 1)
if vi == 1 then error("no values in capture at index"..d.." in /string capture.") end
cached[d] = divS_vals[1]
end
end
return cached[d]
end)
return ci, vi + 1
end
function eval.div_table (caps, sbj, vals, ci, vi)
local this_aux = caps.aux[ci]
local key
if caps.openclose[ci] > 0 then
key = s_sub(sbj, caps.bounds[ci], caps.openclose[ci] - 1)
else
local divT_vals, _ = {}
ci, _ = insert(caps, sbj, divT_vals, ci + 1, 1)
key = divT_vals[1]
end
ci = ci + 1
if this_aux[key] then
vals[vi] = this_aux[key]
return ci, vi + 1
else
return ci, vi
end
end
function LL.evaluate (caps, sbj, ci)
local vals = {}
local _, vi = insert(caps, sbj, vals, ci, 1)
return vals, 1, vi - 1
end
end -- Decorator wrapper
end
end
--=============================================================================
do local _ENV = _ENV
packages['printers'] = function (...)
return function(Builder, LL)
local ipairs, pairs, print, tostring, type
= ipairs, pairs, print, tostring, type
local s, t, u = require"string", require"table", require"util"
local S_tostring = Builder.set.tostring
local _ENV = u.noglobals() ----------------------------------------------------
local s_char, s_sub, t_concat
= s.char, s.sub, t.concat
local expose, load, map
= u.expose, u.load, u.map
local escape_index = {
["\f"] = "\\f",
["\n"] = "\\n",
["\r"] = "\\r",
["\t"] = "\\t",
["\v"] = "\\v",
["\127"] = "\\ESC"
}
for i = 0, 8 do escape_index[s_char(i)] = "\\"..i end
for i = 14, 31 do escape_index[s_char(i)] = "\\"..i end
local
function escape( str )
return str:gsub("%c", escape_index)
end
local
function set_repr (set)
return s_char(load("return "..S_tostring(set))())
end
local printers = {}
local
function LL_pprint (pt, offset, prefix)
return printers[pt.pkind](pt, offset, prefix)
end
function LL.pprint (pt0)
local pt = LL.P(pt0)
print"\nPrint pattern"
LL_pprint(pt, "", "")
print"--- /pprint\n"
return pt0
end
for k, v in pairs{
string = [[ "P( \""..escape(pt.as_is).."\" )" ]],
char = [[ "P( \""..escape(to_char(pt.aux)).."\" )"]],
["true"] = [[ "P( true )" ]],
["false"] = [[ "P( false )" ]],
eos = [[ "~EOS~" ]],
one = [[ "P( one )" ]],
any = [[ "P( "..pt.aux.." )" ]],
set = [[ "S( "..'"'..escape(set_repr(pt.aux))..'"'.." )" ]],
["function"] = [[ "P( "..pt.aux.." )" ]],
ref = [[
"V( ",
(type(pt.aux) == "string" and "\""..pt.aux.."\"")
or tostring(pt.aux)
, " )"
]],
range = [[
"R( ",
escape(t_concat(map(
pt.as_is,
function(e) return '"'..e..'"' end)
, ", "))
," )"
]]
} do
printers[k] = load(([==[
local k, map, t_concat, to_char, escape, set_repr = ...
return function (pt, offset, prefix)
print(t_concat{offset,prefix,XXXX})
end
]==]):gsub("XXXX", v), k.." printer")(k, map, t_concat, s_char, escape, set_repr)
end
for k, v in pairs{
["behind"] = [[ LL_pprint(pt.pattern, offset, "B ") ]],
["at least"] = [[ LL_pprint(pt.pattern, offset, pt.aux.." ^ ") ]],
["at most"] = [[ LL_pprint(pt.pattern, offset, pt.aux.." ^ ") ]],
unm = [[LL_pprint(pt.pattern, offset, "- ")]],
lookahead = [[LL_pprint(pt.pattern, offset, "# ")]],
choice = [[
print(offset..prefix.."+")
map(pt.aux, LL_pprint, offset.." :", "")
]],
sequence = [=[
if u.all(pt.aux, function(p) return p.pkind == "char" end) then
local acc = {}
for i = 1, #(pt.aux) do
acc[i] = pt.aux[i].aux
end
print(offset..prefix..'"'..s.char(u.unpack(acc))..'"')
else
local xformed = u.fold(pt.aux, function(acc, p)
local n = #acc
if n == 0 then
acc[1] = p
elseif p.pkind == "char" and acc[n].pkind == "char"
then acc[n] = {buffer = true, acc[n].aux, p.aux}
elseif p.pkind == "char" and acc[n].buffer then
acc[n][#acc[n]+1] = p.aux
elseif acc[n].buffer and p.pkind ~= "char" then
acc[n].pkind = "string"
acc[n].as_is = s.char(u.unpack(acc[n]))
else
acc[n+1] = p
end
return acc
end, {})
if xformed[#xformed].buffer then
xformed[#xformed].pkind = "string"
xformed[#xformed].as_is = s.char(u.unpack(xformed[#xformed]))
end
print(offset..prefix.."*")
map(xformed, LL_pprint, offset.." |", "")
end
]=],
grammar = [[
print(offset..prefix.."Grammar")
for k, pt in pairs(pt.aux) do
local prefix = ( type(k)~="string"
and tostring(k)
or "\""..k.."\"" )
LL_pprint(pt, offset.." ", prefix .. " = ")
end
]]
} do
printers[k] = load(([[
local map, LL_pprint, pkind, s, u = ...
return function (pt, offset, prefix)
XXXX
end
]]):gsub("XXXX", v), k.." printer")(map, LL_pprint, type, s, u)
end
for _, cap in pairs{"C", "Cs", "Ct"} do
printers[cap] = function (pt, offset, prefix)
print(offset..prefix..cap)
LL_pprint(pt.pattern, offset.." ", "")
end
end
for _, cap in pairs{"Cg", "Clb", "Cf", "Cmt", "div_number", "/zero", "div_function", "div_table"} do
printers[cap] = function (pt, offset, prefix)
print(offset..prefix..cap.." "..tostring(pt.aux or ""))
LL_pprint(pt.pattern, offset.." ", "")
end
end
printers["div_string"] = function (pt, offset, prefix)
print(offset..prefix..'/string "'..tostring(pt.aux or "")..'"')
LL_pprint(pt.pattern, offset.." ", "")
end
for _, cap in pairs{"Carg", "Cp"} do
printers[cap] = function (pt, offset, prefix)
print(offset..prefix..cap.."( "..tostring(pt.aux).." )")
end
end
printers["Cb"] = function (pt, offset, prefix)
print(offset..prefix.."Cb( \""..pt.aux.."\" )")
end
printers["Cc"] = function (pt, offset, prefix)
print(offset..prefix.."Cc(" ..t_concat(map(pt.aux, tostring),", ").." )")
end
local cprinters = {}
local padding = " "
local function padnum(n)
n = tostring(n)
n = n .."."..((" "):rep(4 - #n))
return n
end
local function _cprint(caps, ci, indent, sbj, n)
local openclose, kind = caps.openclose, caps.kind
indent = indent or 0
while kind[ci] and openclose[ci] >= 0 do
if caps.openclose[ci] > 0 then
print(t_concat({
padnum(n),
padding:rep(indent),
caps.kind[ci],
": start = ", tostring(caps.bounds[ci]),
" finish = ", tostring(caps.openclose[ci]),
caps.aux[ci] and " aux = " or "",
caps.aux[ci] and (
type(caps.aux[ci]) == "string"
and '"'..tostring(caps.aux[ci])..'"'
or tostring(caps.aux[ci])
) or "",
" \t", s_sub(sbj, caps.bounds[ci], caps.openclose[ci] - 1)
}))
if type(caps.aux[ci]) == "table" then expose(caps.aux[ci]) end
else
local kind = caps.kind[ci]
local start = caps.bounds[ci]
print(t_concat({
padnum(n),
padding:rep(indent), kind,
": start = ", start,
caps.aux[ci] and " aux = " or "",
caps.aux[ci] and (
type(caps.aux[ci]) == "string"
and '"'..tostring(caps.aux[ci])..'"'
or tostring(caps.aux[ci])
) or ""
}))
ci, n = _cprint(caps, ci + 1, indent + 1, sbj, n + 1)
print(t_concat({
padnum(n),
padding:rep(indent),
"/", kind,
" finish = ", tostring(caps.bounds[ci]),
" \t", s_sub(sbj, start, (caps.bounds[ci] or 1) - 1)
}))
end
n = n + 1
ci = ci + 1
end
return ci, n
end
function LL.cprint (caps, ci, sbj)
ci = ci or 1
print"\nCapture Printer:\n================"
_cprint(caps, ci, 0, sbj, 1)
print"================\n/Cprinter\n"
end
return { pprint = LL.pprint,cprint = LL.cprint }
end -- module wrapper ---------------------------------------------------------
end
end
--=============================================================================
do local _ENV = _ENV
packages['compat'] = function (...)
local debug = require"debug"
local jit = require"jit"
local compat = {
debug = debug,
lua51 = (_VERSION == "Lua 5.1") and not jit,
lua52 = _VERSION == "Lua 5.2",
luajit = jit and true or false,
jit = jit and jit.status(),
lua52_len = not #setmetatable({},{__len = function()end}),
proxies = pcall(function()
local prox = newproxy(true)
local prox2 = newproxy(prox)
assert (type(getmetatable(prox)) == "table"
and (getmetatable(prox)) == (getmetatable(prox2)))
end)
}
if compat.lua52 then
compat._goto = true
else
compat._goto = CompileString("::R::", "!") and true or false
end
return compat
end
end
--=============================================================================
do local _ENV = _ENV
packages['factorizer'] = function (...)
local ipairs, pairs, print, setmetatable
= ipairs, pairs, print, setmetatable
local u = require"util"
local id, setify, arrayify
= u.id, u.setify, u.arrayify
local V_hasCmt = u.nop
local _ENV = u.noglobals() ----------------------------------------------------
local
function process_booleans(lst, opts)
local acc, id, brk = {}, opts.id, opts.brk
for i = 1,#lst do
local p = lst[i]
if p ~= id then
acc[#acc + 1] = p
end
if p == brk then
break
end
end
return acc
end
local unary = setify{
"C", "Cf", "Cg", "Cs", "Ct", "/zero",
"Clb", "Cmt", "div_string", "div_number",
"div_table", "div_function", "at least", "at most"
}
local unifiable = setify{"char", "set", "range"}
local
function mergeseqhead (p1, p2)
local n, len = 0, m_min(#p1, p2)
while n <= len do
if pi[n + 1] == p2[n + 1] then n = n + 1
else break end
end
end
return function (Builder, LL) --------------------------------------------------
if Builder.options.factorize == false then
print"No factorization"
return {
choice = arrayify,
sequence = arrayify,
lookahead = id,
unm = id
}
end
local -- flattens a choice/sequence (a * b) * (c * d) => a * b * c * d
function flatten(typ, ary)
local acc = {}
for _, p in ipairs(ary) do
if p.pkind == typ then
for _, q in ipairs(p.aux) do
acc[#acc+1] = q
end
else
acc[#acc+1] = p
end
end
return acc
end
local constructors, LL_P = Builder.constructors, LL.P
local truept, falsept
= constructors.constant.truept
, constructors.constant.falsept
local --Range, Set,
S_union
= --Builder.Range, Builder.set.new,
Builder.set.union
local mergeable = setify{"char", "set"}
local type2cons = {
["/zero"] = "__div",
["div_number"] = "__div",
["div_string"] = "__div",
["div_table"] = "__div",
["div_function"] = "__div",
["at least"] = "__exp",
["at most"] = "__exp",
["Clb"] = "Cg",
}
local
function choice (a,b, ...)
local dest
if b ~= nil then
dest = flatten("choice", {a,b,...})
else
dest = flatten("choice", a)
end
dest = process_booleans(dest, { id = falsept, brk = truept })
local changed
local src
repeat
src, dest, changed = dest, {dest[1]}, false
for i = 2,#src do
local p1, p2 = dest[#dest], src[i]
local type1, type2 = p1.pkind, p2.pkind
if mergeable[type1] and mergeable[type2] then
dest[#dest] = constructors.aux("set", S_union(p1.aux, p2.aux))
changed = true
elseif mergeable[type1] and type2 == "any" and p2.aux == 1
or mergeable[type2] and type1 == "any" and p1.aux == 1 then
dest[#dest] = type1 == "any" and p1 or p2
changed = true
elseif type1 == type2 then
if unary[type1] and ( p1.aux == p2.aux ) then
dest[#dest] = LL[type2cons[type1] or type1](p1.pattern + p2.pattern, p1.aux)
changed = true
elseif p1 == p2 then
changed = true
else
dest[#dest + 1] = p2
end
else
dest[#dest + 1] = p2
end -- if identical and without Cmt, fold them into one.
end
until not changed
return dest
end
local
function lookahead (pt)
return pt
end
local
function append (acc, p1, p2)
acc[#acc + 1] = p2
end
local
function seq_any_any (acc, p1, p2)
acc[#acc] = LL_P(p1.aux + p2.aux)
end
local seq_optimize = {
any = {
any = seq_any_any,
one = seq_any_any
},
one = {
any = seq_any_any,
one = seq_any_any
},
unm = {
unm = append -- seq_unm_unm
}
}
local metaappend_mt = {
__index = function()return append end
}
for _, v in pairs(seq_optimize) do
setmetatable(v, metaappend_mt)
end
local metaappend = setmetatable({}, metaappend_mt)
setmetatable(seq_optimize, {
__index = function() return metaappend end
})
local
function sequence(a, b, ...)
local seq1
if b ~=nil then
seq1 = flatten("sequence", {a, b, ...})
else
seq1 = flatten("sequence", a)
end
seq1 = process_booleans(seq1, { id = truept, brk = falsept })
local seq2 = {}
seq2[1] = seq1[1]
for i = 2,#seq1 do
local p1, p2 = seq2[#seq2], seq1[i]
seq_optimize[p1.pkind][p2.pkind](seq2, p1, p2)
end
return seq2
end
local
function unm (pt)
if pt == truept then return falsept
elseif pt == falsept then return truept
elseif pt.pkind == "unm" then return #pt.pattern
elseif pt.pkind == "lookahead" then return -pt.pattern
end
end
return {
choice = choice,
lookahead = lookahead,
sequence = sequence,
unm = unm
}
end
end
end
--=============================================================================
do local _ENV = _ENV
packages['match'] = function (...)
end
end
--=============================================================================
do local _ENV = _ENV
packages['util'] = function (...)
local getmetatable, setmetatable, load, loadstring, next
, pairs, pcall, print, rawget, rawset, select, tostring
, type, unpack
= getmetatable, setmetatable, load, CompileString, next
, pairs, pcall, print, rawget, rawset, select, tostring
, type, unpack
local m, s, t = require"math", require"string", require"table"
local m_max, s_match, s_gsub, t_concat, t_insert
= m.max, s.match, s.gsub, t.concat, t.insert
local compat = require"compat"
local
function nop () end
local noglobals, getglobal, setglobal if pcall and not compat.lua52 and not release then
local function errR (_,i)
error("illegal global read: " .. tostring(i), 2)
end
local function errW (_,i, v)
error("illegal global write: " .. tostring(i)..": "..tostring(v), 2)
end
local env = setmetatable({}, { __index=errR, __newindex=errW })
noglobals = function()
pcall(setfenv, 3, env)
end
function getglobal(k) rawget(env, k) end
function setglobal(k, v) rawset(env, k, v) end
else
noglobals = nop
end
local _ENV = noglobals() ------------------------------------------------------
local util = {
nop = nop,
noglobals = noglobals,
getglobal = getglobal,
setglobal = setglobal
}
util.unpack = t.unpack or unpack
util.pack = t.pack or function(...) return { n = select('#', ...), ... } end
if compat.lua51 then
local old_load = load
function util.load (ld, source, mode, env)
local fun
if type (ld) == 'string' then
fun = loadstring(ld, "LuLPeg")
else
fun = old_load (ld, source)
end
if env then
setfenv (fun, env)
end
return fun
end
else
util.load = load
end
if compat.luajit and compat.jit then
function util.max (ary)
local max = 0
for i = 1, #ary do
max = m_max(max,ary[i])
end
return max
end
elseif compat.luajit then
local t_unpack = util.unpack
function util.max (ary)
local len = #ary
if len <=30 or len > 10240 then
local max = 0
for i = 1, #ary do
local j = ary[i]
if j > max then max = j end
end
return max
else
return m_max(t_unpack(ary))
end
end
else
local t_unpack = util.unpack
local safe_len = 1000
function util.max(array)
local len = #array
if len == 0 then return -1 end -- FIXME: shouldn't this be `return -1`?
local off = 1
local off_end = safe_len
local max = array[1] -- seed max.
repeat
if off_end > len then off_end = len end
local seg_max = m_max(t_unpack(array, off, off_end))
if seg_max > max then
max = seg_max
end
off = off + safe_len
off_end = off_end + safe_len
until off >= len
return max
end
end
local
function setmode(t,mode)
local mt = getmetatable(t) or {}
if mt.__mode then
error("The mode has already been set on table "..tostring(t)..".")
end
mt.__mode = mode
return setmetatable(t, mt)
end
util.setmode = setmode
function util.weakboth (t)
return setmode(t,"kv")
end
function util.weakkey (t)
return setmode(t,"k")
end
function util.weakval (t)
return setmode(t,"v")
end
function util.strip_mt (t)
return setmetatable(t, nil)
end
local getuniqueid
do
local N, index = 0, {}
function getuniqueid(v)
if not index[v] then
N = N + 1
index[v] = N
end
return index[v]
end
end
util.getuniqueid = getuniqueid
do
local counter = 0
function util.gensym ()
counter = counter + 1
return "___SYM_"..counter
end
end
function util.passprint (...) print(...) return ... end
local val_to_str_, key_to_str, table_tostring, cdata_to_str, t_cache
local multiplier = 2
local
function val_to_string (v, indent)
indent = indent or 0
t_cache = {} -- upvalue.
local acc = {}
val_to_str_(v, acc, indent, indent)
local res = t_concat(acc, "")
return res
end
util.val_to_str = val_to_string
function val_to_str_ ( v, acc, indent, str_indent )
str_indent = str_indent or 1
if "string" == type( v ) then
v = s_gsub( v, "\n", "\n" .. (" "):rep( indent * multiplier + str_indent ) )
if s_match( s_gsub( v,"[^'\"]",""), '^"+$' ) then
acc[#acc+1] = t_concat{ "'", "", v, "'" }
else
acc[#acc+1] = t_concat{'"', s_gsub(v,'"', '\\"' ), '"' }
end
elseif "cdata" == type( v ) then
cdata_to_str( v, acc, indent )
elseif "table" == type(v) then
if t_cache[v] then
acc[#acc+1] = t_cache[v]
else
t_cache[v] = tostring( v )
table_tostring( v, acc, indent )
end
else
acc[#acc+1] = tostring( v )
end
end
function key_to_str ( k, acc, indent )
if "string" == type( k ) and s_match( k, "^[_%a][_%a%d]*$" ) then
acc[#acc+1] = s_gsub( k, "\n", (" "):rep( indent * multiplier + 1 ) .. "\n" )
else
acc[#acc+1] = "[ "
val_to_str_( k, acc, indent )
acc[#acc+1] = " ]"
end
end
function cdata_to_str(v, acc, indent)
acc[#acc+1] = ( " " ):rep( indent * multiplier )
acc[#acc+1] = "["
print(#acc)
for i = 0, #v do
if i % 16 == 0 and i ~= 0 then
acc[#acc+1] = "\n"
acc[#acc+1] = (" "):rep(indent * multiplier + 2)
end
acc[#acc+1] = v[i] and 1 or 0
acc[#acc+1] = i ~= #v and ", " or ""
end
print(#acc, acc[1], acc[2])
acc[#acc+1] = "]"
end
function table_tostring ( tbl, acc, indent )
acc[#acc+1] = t_cache[tbl]
acc[#acc+1] = "{\n"
for k, v in pairs( tbl ) do
local str_indent = 1
acc[#acc+1] = (" "):rep((indent + 1) * multiplier)
key_to_str( k, acc, indent + 1)
if acc[#acc] == " ]"
and acc[#acc - 2] == "[ "
then str_indent = 8 + #acc[#acc - 1]
end
acc[#acc+1] = " = "
val_to_str_( v, acc, indent + 1, str_indent)
acc[#acc+1] = "\n"
end
acc[#acc+1] = ( " " ):rep( indent * multiplier )
acc[#acc+1] = "}"
end
function util.expose(v) print(val_to_string(v)) return v end
function util.map (ary, func, ...)
if type(ary) == "function" then ary, func = func, ary end
local res = {}
for i = 1,#ary do
res[i] = func(ary[i], ...)
end
return res
end
function util.selfmap (ary, func, ...)
if type(ary) == "function" then ary, func = func, ary end
for i = 1,#ary do
ary[i] = func(ary[i], ...)
end
return ary
end
local
function map_all (tbl, func, ...)
if type(tbl) == "function" then tbl, func = func, tbl end
local res = {}
for k, v in next, tbl do
res[k]=func(v, ...)
end
return res
end
util.map_all = map_all
local
function fold (ary, func, acc)
local i0 = 1
if not acc then
acc = ary[1]
i0 = 2
end
for i = i0, #ary do
acc = func(acc,ary[i])
end
return acc
end
util.fold = fold
local
function map_fold(ary, mfunc, ffunc, acc)
local i0 = 1
if not acc then
acc = mfunc(ary[1])
i0 = 2
end
for i = i0, #ary do
acc = ffunc(acc,mfunc(ary[i]))
end
return acc
end
util.map_fold = map_fold
function util.zip(a1, a2)
local res, len = {}, m_max(#a1,#a2)
for i = 1,len do
res[i] = {a1[i], a2[i]}
end
return res
end
function util.zip_all(t1, t2)
local res = {}
for k,v in pairs(t1) do
res[k] = {v, t2[k]}
end
for k,v in pairs(t2) do
if res[k] == nil then
res[k] = {t1[k], v}
end
end
return res
end
function util.filter(ary,func)
local res = {}
for i = 1,#ary do
if func(ary[i]) then
t_insert(res, ary[i])
end
end
end
local
function id (...) return ... end
util.id = id
local function AND (a,b) return a and b end
local function OR (a,b) return a or b end
function util.copy (tbl) return map_all(tbl, id) end
function util.all (ary, mfunc)
if mfunc then
return map_fold(ary, mfunc, AND)
else
return fold(ary, AND)
end
end
function util.any (ary, mfunc)
if mfunc then
return map_fold(ary, mfunc, OR)
else
return fold(ary, OR)
end
end
function util.get(field)
return function(tbl) return tbl[field] end
end
function util.lt(ref)
return function(val) return val < ref end
end
function util.compose(f,g)
return function(...) return f(g(...)) end
end
function util.extend (destination, ...)
for i = 1, select('#', ...) do
for k,v in pairs((select(i, ...))) do
destination[k] = v
end
end
return destination
end
function util.setify (t)
local set = {}
for i = 1, #t do
set[t[i]]=true
end
return set
end
function util.arrayify (...) return {...} end
local
function _checkstrhelper(s)
return s..""
end
function util.checkstring(s, func)
local success, str = pcall(_checkstrhelper, s)
if not success then
if func == nil then func = "?" end
error("bad argument to '"
..tostring(func)
.."' (string expected, got "
..type(s)
..")",
2)
end
return str
end
return util
end
end
--=============================================================================
do local _ENV = _ENV
packages['API'] = function (...)
local assert, error, ipairs, pairs, pcall, print
, require, select, tonumber, type
= assert, error, ipairs, pairs, pcall, print
, require, select, tonumber, type
local t, u = require"table", require"util"
local _ENV = u.noglobals() ---------------------------------------------------
local t_concat = t.concat
local checkstring, copy, fold, load, map, setify, t_pack, t_unpack
= u.checkstring, u.copy, u.fold, u.load, u.map, u.setify, u.pack, u.unpack
local
function charset_error(index, charset)
error("Character at position ".. index + 1
.." is not a valid "..charset.." one.",
2)
end
return function(Builder, LL) -- module wrapper -------------------------------
local cs = Builder.charset
local constructors, LL_ispattern
= Builder.constructors, LL.ispattern
local truept, falsept, Cppt
= constructors.constant.truept
, constructors.constant.falsept
, constructors.constant.Cppt
local split_int, validate
= cs.split_int, cs.validate
local Range, Set, S_union, S_tostring
= Builder.Range, Builder.set.new
, Builder.set.union, Builder.set.tostring
local factorize_choice, factorize_lookahead, factorize_sequence, factorize_unm
local
function makechar(c)
return constructors.aux("char", c)
end
local
function LL_P (...)
local v, n = (...), select('#', ...)
if n == 0 then error"bad argument #1 to 'P' (value expected)" end
local typ = type(v)
if LL_ispattern(v) then
return v
elseif typ == "function" then
return
LL.Cmt("", v)
elseif typ == "string" then
local success, index = validate(v)
if not success then
charset_error(index, cs.name)
end
if v == "" then return truept end
return
Builder.sequence(map(makechar, split_int(v)))
elseif typ == "table" then
local g = copy(v)
if g[1] == nil then error("grammar has no initial rule") end
if not LL_ispattern(g[1]) then g[1] = LL.V(g[1]) end
return
constructors.none("grammar", g)
elseif typ == "boolean" then
return v and truept or falsept
elseif typ == "number" then
if v == 0 then
return truept
elseif v > 0 then
return
constructors.aux("any", v)
else
return
- constructors.aux("any", -v)
end
else
error("bad argument #1 to 'P' (lpeg-pattern expected, got "..typ..")")
end
end
LL.P = LL_P
local
function LL_S (set)
if set == "" then
return
falsept
else
local success
set = checkstring(set, "S")
return
constructors.aux("set", Set(split_int(set)), set)
end
end
LL.S = LL_S
local
function LL_R (...)
if select('#', ...) == 0 then
return LL_P(false)
else
local range = Range(1,0)--Set("")
for _, r in ipairs{...} do
r = checkstring(r, "R")
assert(#r == 2, "bad argument #1 to 'R' (range must have two characters)")
range = S_union ( range, Range(t_unpack(split_int(r))) )
end
return
constructors.aux("set", range)
end
end
LL.R = LL_R
local
function LL_V (name)
assert(name ~= nil)
return
constructors.aux("ref", name)
end
LL.V = LL_V
do
local one = setify{"set", "range", "one", "char"}
local zero = setify{"true", "false", "lookahead", "unm"}
local forbidden = setify{
"Carg", "Cb", "C", "Cf",
"Cg", "Cs", "Ct", "/zero",
"Clb", "Cmt", "Cc", "Cp",
"div_string", "div_number", "div_table", "div_function",
"at least", "at most", "behind"
}
local function fixedlen(pt, gram, cycle)
local typ = pt.pkind
if forbidden[typ] then return false
elseif one[typ] then return 1
elseif zero[typ] then return 0
elseif typ == "string" then return #pt.as_is
elseif typ == "any" then return pt.aux
elseif typ == "choice" then
return fold(map(pt.aux,fixedlen), function(a,b) return (a == b) and a end )
elseif typ == "sequence" then
return fold(map(pt.aux, fixedlen), function(a,b) return a and b and a + b end)
elseif typ == "grammar" then
if pt.aux[1].pkind == "ref" then
return fixedlen(pt.aux[pt.aux[1].aux], pt.aux, {})
else
return fixedlen(pt.aux[1], pt.aux, {})
end
elseif typ == "ref" then
if cycle[pt] then return false end
cycle[pt] = true
return fixedlen(gram[pt.aux], gram, cycle)
else
print(typ,"is not handled by fixedlen()")
end
end
function LL.B (pt)
pt = LL_P(pt)
local len = fixedlen(pt)
assert(len, "A 'behind' pattern takes a fixed length pattern as argument.")
if len >= 260 then error("Subpattern too long in 'behind' pattern constructor.") end
return
constructors.both("behind", pt, len)
end
end
local
function choice (a, b, ...)
if b ~= nil then
a, b = LL_P(a), LL_P(b)
end
local ch = factorize_choice(a, b, ...)
if #ch == 0 then
return falsept
elseif #ch == 1 then
return ch[1]
else
return
constructors.aux("choice", ch)
end
end
function LL.__add (a,b)
return
choice(LL_P(a), LL_P(b))
end
local
function sequence (a, b, ...)
local seq = factorize_sequence(a, b, ...)
if #seq == 0 then
return truept
elseif #seq == 1 then
return seq[1]
end
return
constructors.aux("sequence", seq)
end
Builder.sequence = sequence
function LL.__mul (a, b)
return
sequence(LL_P(a), LL_P(b))
end
local
function LL_lookahead (pt)
if pt == truept
or pt == falsept
or pt.pkind == "unm"
or pt.pkind == "lookahead"
then
return pt
end
return
constructors.subpt("lookahead", pt)
end
LL.__len = LL_lookahead
LL.L = LL_lookahead
local
function LL_unm(pt)
return
factorize_unm(pt)
or constructors.subpt("unm", pt)
end
LL.__unm = LL_unm
local
function LL_sub (a, b)
a, b = LL_P(a), LL_P(b)
return LL_unm(b) * a
end
LL.__sub = LL_sub
local
function LL_repeat (pt, n)
local success
success, n = pcall(tonumber, n)
assert(success and type(n) == "number",
"Invalid type encountered at right side of '^'.")
return constructors.both(( n < 0 and "at most" or "at least" ), pt, n)
end
LL.__pow = LL_repeat
for _, cap in pairs{"C", "Cs", "Ct"} do
LL[cap] = function(pt)
pt = LL_P(pt)
return
constructors.subpt(cap, pt)
end
end
LL["Cb"] = function(aux)
return
constructors.aux("Cb", aux)
end
LL["Carg"] = function(aux)
assert(type(aux)=="number", "Number expected as parameter to Carg capture.")
assert( 0 < aux and aux <= 200, "Argument out of bounds in Carg capture.")
return
constructors.aux("Carg", aux)
end
local
function LL_Cp ()
return Cppt
end
LL.Cp = LL_Cp
local
function LL_Cc (...)
return
constructors.none("Cc", t_pack(...))
end
LL.Cc = LL_Cc
for _, cap in pairs{"Cf", "Cmt"} do
local msg = "Function expected in "..cap.." capture"
LL[cap] = function(pt, aux)
assert(type(aux) == "function", msg)
pt = LL_P(pt)
return
constructors.both(cap, pt, aux)
end
end
local
function LL_Cg (pt, tag)
pt = LL_P(pt)
if tag ~= nil then
return
constructors.both("Clb", pt, tag)
else
return
constructors.subpt("Cg", pt)
end
end
LL.Cg = LL_Cg
local valid_slash_type = setify{"string", "number", "table", "function"}
local
function LL_slash (pt, aux)
if LL_ispattern(aux) then
error"The right side of a '/' capture cannot be a pattern."
elseif not valid_slash_type[type(aux)] then
error("The right side of a '/' capture must be of type "
.."string, number, table or function.")
end
local name
if aux == 0 then
name = "/zero"
else
name = "div_"..type(aux)
end
return
constructors.both(name, pt, aux)
end
LL.__div = LL_slash
if Builder.proxymt then
for k, v in pairs(LL) do
if k:match"^__" then
Builder.proxymt[k] = v
end
end
else
LL.__index = LL
end
local factorizer
= Builder.factorizer(Builder, LL)
factorize_choice, factorize_lookahead, factorize_sequence, factorize_unm =
factorizer.choice, factorizer.lookahead, factorizer.sequence, factorizer.unm
end -- module wrapper --------------------------------------------------------
end
end
--=============================================================================
do local _ENV = _ENV
packages['constructors'] = function (...)
local getmetatable, ipairs, newproxy, print, setmetatable
= getmetatable, ipairs, newproxy, print, setmetatable
local t, u, compat
= require"table", require"util", require"compat"
local t_concat = t.concat
local copy, getuniqueid, id, map
, weakkey, weakval
= u.copy, u.getuniqueid, u.id, u.map
, u.weakkey, u.weakval
local _ENV = u.noglobals() ----------------------------------------------------
local patternwith = {
constant = {
"Cp", "true", "false"
},
aux = {
"string", "any",
"char", "range", "set",
"ref", "sequence", "choice",
"Carg", "Cb"
},
subpt = {
"unm", "lookahead", "C", "Cf",
"Cg", "Cs", "Ct", "/zero"
},
both = {
"behind", "at least", "at most", "Clb", "Cmt",
"div_string", "div_number", "div_table", "div_function"
},
none = "grammar", "Cc"
}
return function(Builder, LL) --- module wrapper.
local S_tostring = Builder.set.tostring
local newpattern, pattmt
if compat.proxies and not compat.lua52_len then
local proxycache = weakkey{}
local __index_LL = {__index = LL}
local baseproxy = newproxy(true)
pattmt = getmetatable(baseproxy)
pattmt.MetaName = "lpeg-pattern"
Builder.proxymt = pattmt
function pattmt:__index(k)
return proxycache[self][k]
end
function pattmt:__newindex(k, v)
proxycache[self][k] = v
end
function LL.getdirect(p) return proxycache[p] end
function newpattern(cons)
local pt = newproxy(baseproxy)
setmetatable(cons, __index_LL)
proxycache[pt]=cons
return pt
end
else
if LL.warnings and not compat.lua52_len then
print("Warning: The `__len` metatethod won't work with patterns, "
.."use `LL.L(pattern)` for lookaheads.")
end
pattmt = LL
function LL.getdirect (p) return p end
function newpattern(pt)
return setmetatable(pt,LL)
end
end
Builder.newpattern = newpattern
local
function LL_ispattern(pt) return getmetatable(pt) == pattmt end
LL.ispattern = LL_ispattern
function LL.type(pt)
if LL_ispattern(pt) then
return "pattern"
else
return nil
end
end
local ptcache, meta
local
function resetcache()
ptcache, meta = {}, weakkey{}
for _, p in ipairs(patternwith.aux) do
ptcache[p] = weakval{}
end
for _, p in ipairs(patternwith.subpt) do
ptcache[p] = weakval{}
end
for _, p in ipairs(patternwith.both) do
ptcache[p] = {}
end
return ptcache
end
LL.resetptcache = resetcache
resetcache()
local constructors = {}
Builder.constructors = constructors
constructors["constant"] = {
truept = newpattern{ pkind = "true" },
falsept = newpattern{ pkind = "false" },
Cppt = newpattern{ pkind = "Cp" }
}
local getauxkey = {
string = function(aux, as_is) return as_is end,
table = copy,
set = function(aux, as_is)
return S_tostring(aux)
end,
range = function(aux, as_is)
return t_concat(as_is, "|")
end,
sequence = function(aux, as_is)
return t_concat(map(getuniqueid, aux),"|")
end
}
getauxkey.choice = getauxkey.sequence
constructors["aux"] = function(typ, aux, as_is)
local cache = ptcache[typ]
local key = (getauxkey[typ] or id)(aux, as_is)
if not cache[key] then
cache[key] = newpattern{
pkind = typ,
aux = aux,
as_is = as_is
}
end
return cache[key]
end
constructors["none"] = function(typ, aux)
return newpattern{
pkind = typ,
aux = aux
}
end
constructors["subpt"] = function(typ, pt)
local cache = ptcache[typ]
if not cache[pt] then
cache[pt] = newpattern{
pkind = typ,
pattern = pt
}
end
return cache[pt]
end
constructors["both"] = function(typ, pt, aux)
local cache = ptcache[typ][aux]
if not cache then
ptcache[typ][aux] = weakval{}
cache = ptcache[typ][aux]
end
if not cache[pt] then
cache[pt] = newpattern{
pkind = typ,
pattern = pt,
aux = aux,
cache = cache -- needed to keep the cache as long as the pattern exists.
}
end
return cache[pt]
end
end -- module wrapper
end
end
--=============================================================================
do
packages['init'] = function (...)
local getmetatable, setmetatable, pcall
= getmetatable, setmetatable, pcall
local u = require"util"
local copy, map, nop, t_unpack
= u.copy, u.map, u.nop, u.unpack
local API, charsets, compiler, constructors
, datastructures, evaluator, factorizer
, locale, printers
= t_unpack(map(require,
{ "API", "charsets", "compiler", "constructors"
, "datastructures", "evaluator", "factorizer"
, "locale", "printers" }))
local VERSION = "0.12"
local LuVERSION = "0.1.0"
local function register(self, env)
if env then
env.lpeg, env.re = self, self.re
end
return self
end
local
function LuLPeg(options)
options = options and copy(options) or {}
local Builder, LL
= { options = options, factorizer = factorizer }
, { new = LuLPeg
, version = function () return VERSION end
, luversion = function () return LuVERSION end
, setmaxstack = nop --Just a stub, for compatibility.
}
LL.util = u
LL.register = register
;-- Decorate the LuLPeg object.
charsets(Builder, LL)
datastructures(Builder, LL)
printers(Builder, LL)
constructors(Builder, LL)
API(Builder, LL)
evaluator(Builder, LL)
;(options.compiler or compiler)(Builder, LL)
locale(Builder, LL)
return LL
end -- LuLPeg
local LL = LuLPeg()
return LL
end
end
--=============================================================================
do
packages['locale'] = function (...)
local extend = require("util").extend
return function(Builder, LL) -- Module wrapper {-------------------------------
local R, S = LL.R, LL.S
local locale = {}
locale["cntrl"] = R"\0\31" + "\127"
locale["digit"] = R"09"
locale["lower"] = R"az"
locale["print"] = R" ~" -- 0x20 to 0xee
locale["space"] = S" \f\n\r\t\v" -- \f == form feed (for a printer), \v == vtab
locale["upper"] = R"AZ"
locale["alpha"] = locale["lower"] + locale["upper"]
locale["alnum"] = locale["alpha"] + locale["digit"]
locale["graph"] = locale["print"] - locale["space"]
locale["punct"] = locale["graph"] - locale["alnum"]
locale["xdigit"] = locale["digit"] + R"af" + R"AF"
function LL.locale (t)
return extend(t or {}, locale)
end
end -- Module wrapper --------------------------------------------------------}
end
end
--=============================================================================
do local _ENV = _ENV
packages['optimizer'] = function (...)
-- Nothing for now.
end
end
return require"init"
| bsd-3-clause |
Lsty/ygopro-scripts | c39122311.lua | 3 | 2907 | --竜魂の幻泉
function c39122311.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMING_END_PHASE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(c39122311.target)
e1:SetOperation(c39122311.operation)
c:RegisterEffect(e1)
--destroy
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e2:SetCode(EVENT_LEAVE_FIELD_P)
e2:SetOperation(c39122311.checkop)
c:RegisterEffect(e2)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_SINGLE)
e3:SetCode(EVENT_LEAVE_FIELD)
e3:SetOperation(c39122311.desop)
e3:SetLabelObject(e2)
c:RegisterEffect(e3)
--destroy2
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD)
e4:SetRange(LOCATION_SZONE)
e4:SetCode(EVENT_LEAVE_FIELD)
e4:SetCondition(c39122311.descon2)
e4:SetOperation(c39122311.desop2)
c:RegisterEffect(e4)
end
function c39122311.filter(c,e,tp)
return c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c39122311.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c39122311.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c39122311.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c39122311.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c39122311.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e)
and Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP_DEFENCE) then
c:SetCardTarget(tc)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_RACE)
e1:SetProperty(EFFECT_FLAG_OWNER_RELATE)
e1:SetReset(RESET_EVENT+0x1fe0000)
e1:SetValue(RACE_WYRM)
e1:SetCondition(c39122311.rcon)
tc:RegisterEffect(e1)
Duel.SpecialSummonComplete()
end
end
function c39122311.rcon(e)
return e:GetOwner():IsHasCardTarget(e:GetHandler())
end
function c39122311.checkop(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsDisabled() then
e:SetLabel(1)
else e:SetLabel(0) end
end
function c39122311.desop(e,tp,eg,ep,ev,re,r,rp)
if e:GetLabelObject():GetLabel()~=0 then return end
local tc=e:GetHandler():GetFirstCardTarget()
if tc and tc:IsLocation(LOCATION_MZONE) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
function c39122311.descon2(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetHandler():GetFirstCardTarget()
return tc and eg:IsContains(tc)
end
function c39122311.desop2(e,tp,eg,ep,ev,re,r,rp)
Duel.Destroy(e:GetHandler(),REASON_EFFECT)
end
| gpl-2.0 |
t4im/homedecor_modpack | homedecor/furniture.lua | 2 | 4095 | local S = homedecor.gettext
local table_colors = {
{ "", homedecor.plain_wood },
{ "_mahogany", homedecor.mahogany_wood },
{ "_white", homedecor.white_wood }
}
for i in ipairs(table_colors) do
local desc = S("Table ("..i..")")
if i == 1 then
desc = S("Table")
end
homedecor.register("table"..table_colors[i][1], {
description = desc,
tiles = { table_colors[i][2] },
node_box = {
type = "fixed",
fixed = {
{ -0.4, -0.5, -0.4, -0.3, 0.4, -0.3 },
{ 0.3, -0.5, -0.4, 0.4, 0.4, -0.3 },
{ -0.4, -0.5, 0.3, -0.3, 0.4, 0.4 },
{ 0.3, -0.5, 0.3, 0.4, 0.4, 0.4 },
{ -0.5, 0.4, -0.5, 0.5, 0.5, 0.5 },
{ -0.4, -0.2, -0.3, -0.3, -0.1, 0.3 },
{ 0.3, -0.2, -0.4, 0.4, -0.1, 0.3 },
{ -0.3, -0.2, -0.4, 0.4, -0.1, -0.3 },
{ -0.3, -0.2, 0.3, 0.3, -0.1, 0.4 },
},
},
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=2},
sounds = default.node_sound_wood_defaults(),
})
end
local chaircolors = {
{ "", "plain" },
{ "black", "Black" },
{ "red", "Red" },
{ "pink", "Pink" },
{ "violet", "Violet" },
{ "blue", "Blue" },
{ "dark_green", "Dark Green" },
}
local kc_cbox = {
type = "fixed",
fixed = { -0.3125, -0.5, -0.3125, 0.3125, 0.5, 0.3125 },
}
local ac_cbox = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, 0, 0.5 },
{-0.5, -0.5, 0.4, 0.5, 0.5, 0.5 }
}
}
for i in ipairs(chaircolors) do
local color = "_"..chaircolors[i][1]
local color2 = chaircolors[i][1]
local name = S(chaircolors[i][2])
local chairtiles = {
homedecor.plain_wood,
"wool"..color..".png",
}
if chaircolors[i][1] == "" then
color = ""
chairtiles = {
homedecor.plain_wood,
homedecor.plain_wood
}
end
homedecor.register("chair"..color, {
description = S("Kitchen chair (%s)"):format(name),
mesh = "homedecor_kitchen_chair.obj",
tiles = chairtiles,
selection_box = kc_cbox,
collision_box = kc_cbox,
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=2},
sounds = default.node_sound_wood_defaults(),
on_rightclick = function(pos, node, clicker, itemstack, pointed_thing)
pos.y = pos.y+0 -- where do I put my ass ?
homedecor.sit(pos, node, clicker)
return itemstack
end
})
if color ~= "" then
homedecor.register("armchair"..color, {
description = S("Armchair (%s)"):format(name),
mesh = "forniture_armchair.obj",
tiles = {
"wool"..color..".png",
"wool_dark_grey.png",
"default_wood.png"
},
groups = {snappy=3},
sounds = default.node_sound_wood_defaults(),
node_box = ac_cbox
})
minetest.register_craft({
output = "homedecor:armchair"..color.." 2",
recipe = {
{ "wool:"..color2,""},
{ "group:wood","group:wood" },
{ "wool:"..color2,"wool:"..color2 },
},
})
end
end
local ob_cbox = {
type = "fixed",
fixed = { -0.5, -0.5, 0, 0.5, 0.5, 0.5 }
}
minetest.register_node(":homedecor:openframe_bookshelf", {
description = "Bookshelf (open-frame)",
drawtype = "mesh",
mesh = "homedecor_openframe_bookshelf.obj",
tiles = {
"homedecor_openframe_bookshelf_books.png",
"default_wood.png"
},
groups = {choppy=3,oddly_breakable_by_hand=2,flammable=3},
sounds = default.node_sound_wood_defaults(),
paramtype = "light",
paramtype2 = "facedir",
selection_box = ob_cbox,
collision_box = ob_cbox,
})
homedecor.register("wall_shelf", {
description = "Wall Shelf",
tiles = {
"homedecor_wood_table_large_edges.png",
},
groups = { snappy = 3 },
sounds = default.node_sound_wood_defaults(),
node_box = {
type = "fixed",
fixed = {
{-0.5, 0.4, 0.47, 0.5, 0.47, 0.5},
{-0.5, 0.47, -0.1875, 0.5, 0.5, 0.5}
}
}
})
-- Aliases for 3dforniture mod.
minetest.register_alias("3dforniture:table", "homedecor:table")
minetest.register_alias("3dforniture:chair", "homedecor:chair")
minetest.register_alias("3dforniture:armchair", "homedecor:armchair_black")
minetest.register_alias("homedecor:armchair", "homedecor:armchair_black")
minetest.register_alias('table', 'homedecor:table')
minetest.register_alias('chair', 'homedecor:chair')
minetest.register_alias('armchair', 'homedecor:armchair')
| lgpl-3.0 |
Lsty/ygopro-scripts | c63257623.lua | 3 | 2459 | --森羅の実張り ピース
function c63257623.initial_effect(c)
--deck check
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(63257623,0))
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetTarget(c63257623.target)
e1:SetOperation(c63257623.operation)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e2)
--special summon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(63257623,1))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY)
e3:SetCode(EVENT_TO_GRAVE)
e3:SetCountLimit(1,63257623)
e3:SetCondition(c63257623.spcon)
e3:SetTarget(c63257623.sptg)
e3:SetOperation(c63257623.spop)
c:RegisterEffect(e3)
end
function c63257623.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDiscardDeck(tp,1) end
end
function c63257623.operation(e,tp,eg,ep,ev,re,r,rp)
if not Duel.IsPlayerCanDiscardDeck(tp,1) then return end
Duel.ConfirmDecktop(tp,1)
local g=Duel.GetDecktopGroup(tp,1)
local tc=g:GetFirst()
if tc:IsRace(RACE_PLANT) then
Duel.DisableShuffleCheck()
Duel.SendtoGrave(g,REASON_EFFECT+REASON_REVEAL)
else
Duel.MoveSequence(tc,1)
end
end
function c63257623.spcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsPreviousLocation(LOCATION_DECK) and
(c:IsReason(REASON_REVEAL) or c:GetPreviousPosition()==POS_FACEUP_DEFENCE or Duel.IsPlayerAffectedByEffect(tp,EFFECT_REVERSE_DECK))
end
function c63257623.filter(c,e,tp)
return c:IsLevelBelow(4) and c:IsRace(RACE_PLANT) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c63257623.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c63257623.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c63257623.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c63257623.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c63257623.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c65277087.lua | 9 | 1325 | --ガスタ・ガルド
function c65277087.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(65277087,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c65277087.condition)
e1:SetTarget(c65277087.target)
e1:SetOperation(c65277087.operation)
c:RegisterEffect(e1)
end
function c65277087.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD)
end
function c65277087.filter(c,e,tp)
return c:IsLevelBelow(2) and c:IsSetCard(0x10) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c65277087.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c65277087.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c65277087.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c65277087.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
jadarve/lluvia | lluvia/nodes/lluvia/imgproc/ImagePyramid_r8ui.lua | 1 | 3510 | local builder = ll.class(ll.ContainerNodeBuilder)
builder.name = 'lluvia/imgproc/ImagePyramid_r8ui'
builder.doc = [[
Creates an image pyramid from an input gray scale image.
For `levels >= 2`, the pyramid is generated by concatenating a series of
ImageDownsampleX_r8ui and ImageDownsampleY_r8ui nodes.
Parameters
----------
levels : int. Defaults to 1.
The number of levels to create. If the value is 1, the in_gray input is bound
as out_gray in the output, without any memory copy.
Inputs
------
in_gray : ImageView.
r8ui image.
Outputs
-------
out_gray_0 : ImageView.
r8ui image. The base level of the pyramid. This corresponds to in_gray.
Other levels are named `out_gray_1`, to `out_gray_{levels - 1}`
out_gray : ImageView
r8ui image. The output at the top level of the pyramid. This is equivalent
to `out_gray_{levels - 1}`
]]
function builder.newDescriptor()
local desc = ll.ContainerNodeDescriptor.new()
desc.builderName = builder.name
local in_gray = ll.PortDescriptor.new(0, 'in_gray', ll.PortDirection.In, ll.PortType.ImageView)
in_gray:checkImageChannelCountIs(ll.ChannelCount.C1)
in_gray:checkImageChannelTypeIs(ll.ChannelType.Uint8)
desc:addPort(in_gray)
-- parameter with default value
desc:setParameter('levels', 1)
return desc
end
function builder.onNodeInit(node)
local levels = node.descriptor:getParameter('levels')
ll.logd(builder.name, 'onNodeInit: levels:', levels)
-- in_gray should have been bound before calling init()
local in_gray = node:getPort('in_gray')
node:bind(string.format('out_gray_0', i), in_gray)
if levels < 1 then
error(builder.name .. ': levels must be greater or equal 1, got: ' .. levels)
end
-- Pass through the input to the output
if levels == 1 then
node:bind('out_gray_0', in_gray)
node:bind('out_gray', in_gray)
end
for i = 1, levels -1 do
ll.logd(builder.name, 'onNodeInit: level:', i)
local downX = ll.createComputeNode('lluvia/imgproc/ImageDownsampleX_r8ui')
local downY = ll.createComputeNode('lluvia/imgproc/ImageDownsampleY_r8ui')
downX:bind('in_gray', in_gray)
downX:init()
downY:bind('in_gray', downX:getPort('out_gray'))
downY:init()
in_gray = downY:getPort('out_gray')
-- bind the output
if i == levels -1 then
node:bind('out_gray', downY:getPort('out_gray'))
end
ll.logd(builder.name, 'onNodeInit: level:', i, 'binding node')
node:bindNode(string.format('ImageDownsampleX_r8ui_%d', i), downX)
node:bindNode(string.format('ImageDownsampleY_r8ui_%d', i), downY)
-- outputs of each level
node:bind(string.format('out_gray_%d', i), downY:getPort('out_gray'))
end
end
function builder.onNodeRecord(node, cmdBuffer)
ll.logd(node.descriptor.builderName, 'onNodeRecord')
local levels = node.descriptor:getParameter('levels')
for i = 1, levels -1 do
ll.logd(node.descriptor.builderName, 'onNodeRecord: level:', i)
local downX = node:getNode(string.format('ImageDownsampleX_r8ui_%d', i))
local downY = node:getNode(string.format('ImageDownsampleY_r8ui_%d', i))
downX:record(cmdBuffer)
cmdBuffer:memoryBarrier()
downY:record(cmdBuffer)
cmdBuffer:memoryBarrier()
end
ll.logd(node.descriptor.builderName, 'onNodeRecord: finish')
end
ll.registerNodeBuilder(builder)
| apache-2.0 |
Lsty/ygopro-scripts | c55321970.lua | 3 | 1658 | --突風の扇
function c55321970.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(c55321970.target)
e1:SetOperation(c55321970.operation)
c:RegisterEffect(e1)
--atk up
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_EQUIP)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetValue(400)
c:RegisterEffect(e2)
--def down
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_EQUIP)
e3:SetCode(EFFECT_UPDATE_DEFENCE)
e3:SetValue(-200)
c:RegisterEffect(e3)
--equip limit
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetCode(EFFECT_EQUIP_LIMIT)
e4:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e4:SetValue(c55321970.eqlimit)
c:RegisterEffect(e4)
end
function c55321970.eqlimit(e,c)
return c:IsAttribute(ATTRIBUTE_WIND)
end
function c55321970.filter(c)
return c:IsFaceup() and c:IsAttribute(ATTRIBUTE_WIND)
end
function c55321970.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c55321970.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c55321970.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c55321970.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
end
function c55321970.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if e:GetHandler():IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then
Duel.Equip(tp,e:GetHandler(),tc)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Yuhtunga_Jungle/mobs/Overgrown_Rose.lua | 9 | 1040 | -----------------------------------
-- Area: Yuhtunga Jungle
-- Mob: Overgrown Rose
-----------------------------------
local ID = require("scripts/zones/Yuhtunga_Jungle/IDs")
function onMobSpawn(mob)
if mob:getID() == ID.mob.ROSE_GARDEN_PH then
mob:setLocalVar("timeToGrow", os.time() + math.random(36000,37800)) -- 10:00:00 to 10:30:00
end
end
function onMobDisengage(mob)
if mob:getID() == ID.mob.ROSE_GARDEN_PH then
mob:setLocalVar("timeToGrow", os.time() + math.random(36000,37800)) -- 10:00:00 to 10:30:00
end
end
function onMobRoam(mob)
-- Rose Garden PH has been left alone for 10.25 hours
if mob:getID() == ID.mob.ROSE_GARDEN_PH and os.time() > mob:getLocalVar("timeToGrow") then
DisallowRespawn(ID.mob.ROSE_GARDEN_PH, true)
DespawnMob(ID.mob.ROSE_GARDEN_PH)
DisallowRespawn(ID.mob.ROSE_GARDEN, false)
pos = mob:getPos()
SpawnMob(ID.mob.ROSE_GARDEN):setPos(pos.x, pos.y, pos.z, pos.rot)
end
end
function onMobDeath(mob, player, isKiller)
end
| gpl-3.0 |
moody2020/TH3_BOSS | plugins/newgroup.lua | 13 | 36380 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY MOHAMMED HISHAM ▀▄ ▄▀
▀▄ ▄▀ BY MOHAMMEDHISHAM (@TH3BOSS) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY MOHAMMED HISHAM ▀▄ ▄▀
▀▄ ▄▀ create : صنع مجموعه ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
—]]
-- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin1(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'المجموعة 👥 [ '..string.gsub(group_name, '_', ' ')..' ] تم ☑️ صناعتها بنجاح 😚👋🏿'
end
end
local function create_realm(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin1(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.peer_id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.peer_id, result.peer_id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.peer_id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.peer_id, result.peer_id)
end
end
local function get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
if msg.to.type == 'chat' and not is_realm(msg) then
data[tostring(msg.to.id)]['group_type'] = 'Group'
save_data(_config.moderation.data, data)
elseif msg.to.type == 'channel' then
data[tostring(msg.to.id)]['group_type'] = 'SuperGroup'
save_data(_config.moderation.data, data)
end
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.peer_id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
local channel = 'channel#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
send_large_msg(channel, user..'\n'..name)
return user
end
local function set_description(msg, data, target, about)
if not is_admin1(msg) then
return "For admins only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_arabic(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic/Persian is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic/Persian has been unlocked'
end
end
local function lock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'yes' then
return 'RTL char. in names is already locked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'yes'
save_data(_config.moderation.data, data)
return 'RTL char. in names has been locked'
end
end
local function unlock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'no' then
return 'RTL char. in names is already unlocked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'no'
save_data(_config.moderation.data, data)
return 'RTL char. in names has been unlocked'
end
end
local function lock_group_links(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'yes' then
return 'Link posting is already locked'
else
data[tostring(target)]['settings']['lock_link'] = 'yes'
save_data(_config.moderation.data, data)
return 'Link posting has been locked'
end
end
local function unlock_group_links(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'no' then
return 'Link posting is not locked'
else
data[tostring(target)]['settings']['lock_link'] = 'no'
save_data(_config.moderation.data, data)
return 'Link posting has been unlocked'
end
end
local function lock_group_spam(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'yes' then
return 'SuperGroup spam is already locked'
else
data[tostring(target)]['settings']['lock_spam'] = 'yes'
save_data(_config.moderation.data, data)
return 'SuperGroup spam has been locked'
end
end
local function unlock_group_spam(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'no' then
return 'SuperGroup spam is not locked'
else
data[tostring(target)]['settings']['lock_spam'] = 'no'
save_data(_config.moderation.data, data)
return 'SuperGroup spam has been unlocked'
end
end
local function lock_group_rtl(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'yes' then
return 'RTL char. in names is already locked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'yes'
save_data(_config.moderation.data, data)
return 'RTL char. in names has been locked'
end
end
local function unlock_group_rtl(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'no' then
return 'RTL char. in names is already unlocked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'no'
save_data(_config.moderation.data, data)
return 'RTL char. in names has been unlocked'
end
end
local function lock_group_sticker(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'yes' then
return 'Sticker posting is already locked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'yes'
save_data(_config.moderation.data, data)
return 'Sticker posting has been locked'
end
end
local function unlock_group_sticker(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'no' then
return 'Sticker posting is already unlocked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'no'
save_data(_config.moderation.data, data)
return 'Sticker posting has been unlocked'
end
end
local function set_public_membermod(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_public_lock = data[tostring(target)]['settings']['public']
if group_public_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'SuperGroup is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_admin1(msg) then
return "For admins only!"
end
local group_public_lock = data[tostring(target)]['settings']['public']
if group_public_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'SuperGroup is now: not public'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin1(msg) then
return "For admins only!"
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['public'] then
data[tostring(target)]['settings']['public'] = 'no'
end
end
local settings = data[tostring(target)]['settings']
local text = "Group settings for "..target..":\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nPublic: "..settings.public
end
-- show SuperGroup settings
local function show_super_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin1(msg) then
return "For admins only!"
end
if data[tostring(msg.to.id)]['settings'] then
if not data[tostring(msg.to.id)]['settings']['public'] then
data[tostring(msg.to.id)]['settings']['public'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_rtl'] then
data[tostring(target)]['settings']['lock_rtl'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_member'] then
data[tostring(target)]['settings']['lock_member'] = 'no'
end
end
local settings = data[tostring(target)]['settings']
local text = "SuperGroup settings for "..target..":\nLock links : "..settings.lock_link.."\nLock flood: "..settings.flood.."\nLock spam: "..settings.lock_spam.."\nLock Arabic: "..settings.lock_arabic.."\nLock Member: "..settings.lock_member.."\nLock RTL: "..settings.lock_rtl.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public.."\nStrict settings: "..settings.strict
return text
end
local function returnids(cb_extra, success, result)
local i = 1
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.peer_id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' (ID: '..result.peer_id..'):\n\n'
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text ..i..' - '.. string.gsub(v.print_name,"_"," ") .. " [" .. v.peer_id .. "] \n\n"
i = i + 1
end
end
local file = io.open("./groups/lists/"..result.peer_id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function cb_user_info(cb_extra, success, result)
local receiver = cb_extra.receiver
if result.first_name then
first_name = result.first_name:gsub("_", " ")
else
first_name = "None"
end
if result.last_name then
last_name = result.last_name:gsub("_", " ")
else
last_name = "None"
end
if result.username then
username = "@"..result.username
else
username = "@[none]"
end
text = "User Info:\n\nID: "..result.peer_id.."\nFirst: "..first_name.."\nLast: "..last_name.."\nUsername: "..username
send_large_msg(receiver, text)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List of global admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function groups_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
if data[tostring(v)] then
if data[tostring(v)]['settings'] then
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
end
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, '@'..member_username..' is already an admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
send_large_msg(receiver, "@"..member_username..' is not an admin.')
return
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Admin @'..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.peer_id
if mod_cmd == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function res_user_support(cb_extra, success, result)
local receiver = cb_extra.receiver
local get_cmd = cb_extra.get_cmd
local support_id = result.peer_id
if get_cmd == 'addsupport' then
support_add(support_id)
send_large_msg(receiver, "User ["..support_id.."] has been added to the support team")
elseif get_cmd == 'removesupport' then
support_remove(support_id)
send_large_msg(receiver, "User ["..support_id.."] has been removed from the support team")
end
end
local function set_log_group(target, data)
if not is_admin1(msg) then
return
end
local log_group = data[tostring(target)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(target)]['log_group'] = 'yes'
save_data(_config.moderation.data, data)
return 'Log group has been set'
end
end
local function unset_log_group(msg)
if not is_admin1(msg) then
return
end
local log_group = data[tostring(target)]['log_group']
if log_group == 'no' then
return 'Log group is not set'
else
data[tostring(target)]['log_group'] = 'no'
save_data(_config.moderation.data, data)
return 'log group has been disabled'
end
end
local function help()
local help_text = tostring(_config.help_text_realm)
return help_text
end
function run(msg, matches)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
local receiver = get_receiver(msg)
savelog(msg.to.id, "log file created by owner/support/admin")
send_document(receiver,"./groups/logs/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and msg.to.type == 'chat' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
local file = io.open("./groups/lists/"..msg.to.id.."memberlist.txt", "r")
text = file:read("*a")
send_large_msg(receiver,text)
file:close()
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
send_document("chat#id"..msg.to.id,"./groups/lists/"..msg.to.id.."memberlist.txt", ok_cb, false)
end
if matches[1] == 'whois' and is_momod(msg) then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
user_info(user_id, cb_user_info, {receiver = receiver})
end
if not is_sudo(msg) then
if is_realm(msg) and is_admin1(msg) then
print("Admin detected")
else
return
end
end
if matches[1] == 'صنع مجموعه' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
--[[ Experimental
if matches[1] == 'createsuper' and matches[2] then
if not is_sudo(msg) or is_admin1(msg) and is_realm(msg) then
return "You cant create groups!"
end
group_name = matches[2]
group_type = 'super_group'
return create_group(msg)
end]]
if matches[1] == 'createrealm' and matches[2] then
if not is_sudo(msg) then
return "Sudo users only !"
end
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[1] == 'setabout' and matches[2] == 'group' and is_realm(msg) then
local target = matches[3]
local about = matches[4]
return set_description(msg, data, target, about)
end
if matches[1] == 'setabout' and matches[2] == 'sgroup'and is_realm(msg) then
local channel = 'channel#id'..matches[3]
local about_text = matches[4]
local data_cat = 'description'
local target = matches[3]
channel_set_about(channel, about_text, ok_cb, false)
data[tostring(target)][data_cat] = about_text
save_data(_config.moderation.data, data)
return "Description has been set for ["..matches[2]..']'
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
if matches[2] == 'arabic' then
return lock_group_arabic(msg, data, target)
end
if matches[3] == 'links' then
return lock_group_links(msg, data, target)
end
if matches[3] == 'spam' then
return lock_group_spam(msg, data, target)
end
if matches[3] == 'rtl' then
return unlock_group_rtl(msg, data, target)
end
if matches[3] == 'sticker' then
return lock_group_sticker(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
if matches[3] == 'arabic' then
return unlock_group_arabic(msg, data, target)
end
if matches[3] == 'links' then
return unlock_group_links(msg, data, target)
end
if matches[3] == 'spam' then
return unlock_group_spam(msg, data, target)
end
if matches[3] == 'rtl' then
return unlock_group_rtl(msg, data, target)
end
if matches[3] == 'sticker' then
return unlock_group_sticker(msg, data, target)
end
end
if matches[1] == 'settings' and matches[2] == 'group' and data[tostring(matches[3])]['settings'] then
local target = matches[3]
text = show_group_settingsmod(msg, target)
return text.."\nID: "..target.."\n"
end
if matches[1] == 'settings' and matches[2] == 'sgroup' and data[tostring(matches[3])]['settings'] then
local target = matches[3]
text = show_supergroup_settingsmod(msg, target)
return text.."\nID: "..target.."\n"
end
if matches[1] == 'setname' and is_realm(msg) then
local settings = data[tostring(matches[2])]['settings']
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin1(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local chat_to_rename = 'chat#id'..matches[2]
local channel_to_rename = 'channel#id'..matches[2]
rename_chat(to_rename, group_name_set, ok_cb, false)
rename_channel(channel_to_rename, group_name_set, ok_cb, false)
savelog(matches[3], "Group { "..group_name_set.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'help' and is_realm(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
--[[if matches[1] == 'set' then
if matches[2] == 'loggroup' and is_sudo(msg) then
local target = msg.to.peer_id
savelog(msg.to.peer_id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(target, data)
end
end
if matches[1] == 'rem' then
if matches[2] == 'loggroup' and is_sudo(msg) then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return unset_log_group(target, data)
end
end]]
if matches[1] == 'kill' and matches[2] == 'chat' and matches[3] then
if not is_admin1(msg) then
return
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' and matches[3] then
if not is_admin1(msg) then
return
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'rem' and matches[2] then
-- Group configuration removal
data[tostring(matches[2])] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(matches[2])] = nil
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Chat '..matches[2]..' removed')
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if not is_admin1(msg) and is_realm(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if not is_sudo(msg) then-- Sudo only
return
end
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if not is_sudo(msg) then-- Sudo only
return
end
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'support' and matches[2] then
if string.match(matches[2], '^%d+$') then
local support_id = matches[2]
print("User "..support_id.." has been added to the support team")
support_add(support_id)
return "User ["..support_id.."] has been added to the support team"
else
local member = string.gsub(matches[2], "@", "")
local receiver = get_receiver(msg)
local get_cmd = "addsupport"
resolve_username(member, res_user_support, {get_cmd = get_cmd, receiver = receiver})
end
end
if matches[1] == '-support' then
if string.match(matches[2], '^%d+$') then
local support_id = matches[2]
print("User "..support_id.." has been removed from the support team")
support_remove(support_id)
return "User ["..support_id.."] has been removed from the support team"
else
local member = string.gsub(matches[2], "@", "")
local receiver = get_receiver(msg)
local get_cmd = "removesupport"
resolve_username(member, res_user_support, {get_cmd = get_cmd, receiver = receiver})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' then
if matches[2] == 'admins' then
return admin_list(msg)
end
-- if matches[2] == 'support' and not matches[2] then
-- return support_list()
-- end
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' or msg.to.type == 'channel' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
send_document("channel#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' or msg.to.type == 'channel' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
send_document("channel#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
end
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return resolve_username(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^(صنع مجموعه) (.*)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
Lsty/ygopro-scripts | c16674846.lua | 3 | 1272 | --スピリット・フォース
function c16674846.initial_effect(c)
--no damage
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_PRE_DAMAGE_CALCULATE)
e1:SetCondition(c16674846.condition)
e1:SetOperation(c16674846.operation)
c:RegisterEffect(e1)
end
function c16674846.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()~=tp and Duel.GetBattleDamage(tp)>0
end
function c16674846.filter(c)
return c:IsDefenceBelow(1500) and c:IsType(TYPE_TUNER) and c:IsRace(RACE_WARRIOR)
and c:IsAbleToHand() and not c:IsHasEffect(EFFECT_NECRO_VALLEY)
end
function c16674846.operation(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PRE_BATTLE_DAMAGE)
e1:SetOperation(c16674846.damop)
e1:SetReset(RESET_PHASE+PHASE_DAMAGE)
Duel.RegisterEffect(e1,tp)
local g=Duel.GetMatchingGroup(c16674846.filter,tp,LOCATION_GRAVE,0,nil)
if g:GetCount()~=0 and Duel.SelectYesNo(tp,aux.Stringid(16674846,0)) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local sg=g:Select(tp,1,1,nil)
Duel.SendtoHand(sg,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,sg)
end
end
function c16674846.damop(e,tp,eg,ep,ev,re,r,rp)
Duel.ChangeBattleDamage(tp,0)
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Port_Windurst/npcs/Taniko-Maniko.lua | 12 | 1158 | -----------------------------------
-- Area: Port Windurst
-- NPC: Taniko-Maniko
-- Standard Merchant NPC
-----------------------------------
local ID = require("scripts/zones/Port_Windurst/IDs")
require("scripts/globals/shop")
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local stock =
{
16649, 5864, 2, -- Bone Pick
16405, 104, 3, -- Cat Baghnakhs
16385, 129, 3, -- Cesti
16391, 1521, 3, -- Brass Knuckles
16407, 1521, 3, -- Brass Baghnakhs
16642, 4198, 3, -- Bone Axe
16768, 309, 3, -- Bronze Zaghnal
16769, 2542, 3, -- Brass Zaghnal
16832, 97, 3, -- Harpoon
16448, 143, 3, -- Bronze Dagger
16449, 837, 3, -- Brass Dagger
16450, 1827, 3, -- Dagger
16512, 3215, 3, -- Bilbo
16530, 618, 3, -- Xiphos
16565, 1674, 3, -- Spatha
}
player:showText(npc, ID.text.TANIKOMANIKO_SHOP_DIALOG)
dsp.shop.nation(player, stock, dsp.nation.WINDURST)
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
| gpl-3.0 |
Lsty/ygopro-scripts | c88089103.lua | 7 | 1105 | --四次元の墓
function c88089103.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TODECK)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c88089103.target)
e1:SetOperation(c88089103.activate)
c:RegisterEffect(e1)
end
function c88089103.filter(c)
return c:IsSetCard(0x41) and c:IsAbleToDeck()
end
function c88089103.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c88089103.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c88089103.filter,tp,LOCATION_GRAVE,0,2,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectTarget(tp,c88089103.filter,tp,LOCATION_GRAVE,0,2,2,nil)
Duel.SetOperationInfo(0,CATEGORY_TODECK,g,2,0,0)
end
function c88089103.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
local sg=g:Filter(Card.IsRelateToEffect,nil,e)
if sg:GetCount()>0 then
Duel.SendtoDeck(sg,nil,2,REASON_EFFECT)
Duel.ConfirmCards(1-tp,sg)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c77901552.lua | 3 | 2487 | --聖刻龍-トフェニドラゴン
function c77901552.initial_effect(c)
--spsummon from hand
local e1=Effect.CreateEffect(c)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetRange(LOCATION_HAND)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetCondition(c77901552.hspcon)
e1:SetOperation(c77901552.hspop)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(77901552,0))
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetCode(EVENT_RELEASE)
e2:SetTarget(c77901552.sptg)
e2:SetOperation(c77901552.spop)
c:RegisterEffect(e2)
end
function c77901552.hspcon(e,c)
if c==nil then return true end
local tp=c:GetControler()
return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.GetFieldGroupCount(tp,LOCATION_MZONE,0)==0
and Duel.GetFieldGroupCount(tp,0,LOCATION_MZONE)~=0
end
function c77901552.hspop(e,tp,eg,ep,ev,re,r,rp,c)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EFFECT_CANNOT_ATTACK)
e1:SetReset(RESET_EVENT+0xfe0000+RESET_PHASE+PHASE_END)
c:RegisterEffect(e1)
end
function c77901552.spfilter(c,e,tp)
return c:IsType(TYPE_NORMAL) and c:IsRace(RACE_DRAGON) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
and not c:IsHasEffect(EFFECT_NECRO_VALLEY)
end
function c77901552.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,0x13)
end
function c77901552.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c77901552.spfilter,tp,0x13,0,1,1,nil,e,tp)
local tc=g:GetFirst()
if tc and Duel.SpecialSummonStep(g:GetFirst(),0,tp,tp,false,false,POS_FACEUP) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SET_ATTACK)
e1:SetValue(0)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_SET_DEFENCE)
tc:RegisterEffect(e2)
Duel.SpecialSummonComplete()
elseif Duel.IsPlayerCanSpecialSummon(tp) then
local cg1=Duel.GetFieldGroup(tp,LOCATION_HAND,0)
local cg2=Duel.GetFieldGroup(tp,LOCATION_DECK,0)
Duel.ConfirmCards(1-tp,cg1)
Duel.ConfirmCards(1-tp,cg2)
Duel.ConfirmCards(tp,cg2)
Duel.ShuffleHand(tp)
Duel.ShuffleDeck(tp)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Famad.lua | 11 | 2414 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Famad
-- Type: Assault Mission Giver
-- !pos 134.098 0.161 -43.759 50
-----------------------------------
local ID = require("scripts/zones/Aht_Urhgan_Whitegate/IDs")
require("scripts/globals/besieged")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
require("scripts/globals/npc_util")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local rank = dsp.besieged.getMercenaryRank(player)
local haveimperialIDtag
local assaultPoints = player:getAssaultPoint(LEBROS_ASSAULT_POINT)
if (player:hasKeyItem(dsp.ki.IMPERIAL_ARMY_ID_TAG)) then
haveimperialIDtag = 1
else
haveimperialIDtag = 0
end
--[[ if (rank > 0) then
player:startEvent(275,rank,haveimperialIDtag,assaultPoints,player:getCurrentAssault())
else]]
player:startEvent(281) -- no rank
--end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if (csid == 275) then
local selectiontype = bit.band(option, 0xF)
if (selectiontype == 1) then
-- taken assault mission
player:addAssault(bit.rshift(option,4))
player:delKeyItem(dsp.ki.IMPERIAL_ARMY_ID_TAG)
npcUtil.giveKeyItem(player, dsp.ki.LEBROS_ASSAULT_ORDERS)
elseif (selectiontype == 2) then
-- purchased an item
local item = bit.rshift(option,14)
local items =
{
[1] = {itemid = 15972, price = 3000},
[2] = {itemid = 15777, price = 5000},
[3] = {itemid = 15523, price = 8000},
[4] = {itemid = 15886, price = 10000},
[5] = {itemid = 15492, price = 10000},
[6] = {itemid = 18583, price = 15000},
[7] = {itemid = 18383, price = 15000},
[8] = {itemid = 18417, price = 15000},
[9] = {itemid = 14525, price = 20000},
[10] = {itemid = 14940, price = 20000},
[11] = {itemid = 15690, price = 20000},
}
local choice = items[item]
if choice and npcUtil.giveItem(player, choice.itemid) then
player:delCurrency("LEBROS_ASSAULT_POINT", choice.price)
end
end
end
end
| gpl-3.0 |
Frenzie/koreader | frontend/dispatcher.lua | 1 | 47202 | --[[--
This module is responsible for dispatching events.
To add a new action an entry must be added to `settingsList` & `dispatcher_menu_order`
This can also be done at runtime via @{registerAction}().
`settingsList` contains the list of dispatchable settings.
Each setting contains:
* category: one of:
* none: a direct event call
* arg: a event that expects a gesture object or an argument
* absolutenumber: event that sets a number
* incrementalnumber: event that increments a number & accepts a gesture object
* string: event with a list of arguments to chose from
* configurable: like string but instead of an event it updates the configurable (used by kopt)
* event: what to call.
* title: for use in ui.
* section: under which menu to display (currently: general, device, screen, filemanager, reader, rolling, paging)
and optionally
* min/max: for number
* step: for number
* default
* args: allowed values for string.
* toggle: display name for args
* separator: put a separator after in the menu list
* configurable: can be parsed from cre/kopt and used to set `document.configurable`. Should not be set manually
--]]--
local CreOptions = require("ui/data/creoptions")
local KoptOptions = require("ui/data/koptoptions")
local Device = require("device")
local Event = require("ui/event")
local Notification = require("ui/widget/notification")
local ReaderZooming = require("apps/reader/modules/readerzooming")
local UIManager = require("ui/uimanager")
local util = require("util")
local _ = require("gettext")
local C_ = _.pgettext
local N_ = _.ngettext
local T = require("ffi/util").template
local Dispatcher = {
initialized = false,
}
-- See above for description.
local settingsList = {
-- Screen & Lights
show_frontlight_dialog = {category="none", event="ShowFlDialog", title=_("Show frontlight dialog"), screen=true, condition=Device:hasFrontlight()},
toggle_frontlight = {category="none", event="ToggleFrontlight", title=_("Toggle frontlight"), screen=true, condition=Device:hasFrontlight()},
set_frontlight = {category="absolutenumber", event="SetFlIntensity", min=0, max=Device:getPowerDevice().fl_max, title=_("Set frontlight brightness to %1"), screen=true, condition=Device:hasFrontlight()},
increase_frontlight = {category="incrementalnumber", event="IncreaseFlIntensity", min=1, max=Device:getPowerDevice().fl_max, title=_("Increase frontlight brightness by %1"), screen=true, condition=Device:hasFrontlight()},
decrease_frontlight = {category="incrementalnumber", event="DecreaseFlIntensity", min=1, max=Device:getPowerDevice().fl_max, title=_("Decrease frontlight brightness by %1"), screen=true, condition=Device:hasFrontlight()},
set_frontlight_warmth = {category="absolutenumber", event="SetFlWarmth", min=0, max=100, title=_("Set frontlight warmth to %1"), screen=true, condition=Device:hasNaturalLight()},
increase_frontlight_warmth = {category="incrementalnumber", event="IncreaseFlWarmth", min=1, max=Device:getPowerDevice().fl_warmth_max, title=_("Increase frontlight warmth by %1"), screen=true, condition=Device:hasNaturalLight()},
decrease_frontlight_warmth = {category="incrementalnumber", event="DecreaseFlWarmth", min=1, max=Device:getPowerDevice().fl_warmth_max, title=_("Decrease frontlight warmth by %1"), screen=true, condition=Device:hasNaturalLight(), separator=true},
full_refresh = {category="none", event="FullRefresh", title=_("Full screen refresh"), screen=true},
night_mode = {category="none", event="ToggleNightMode", title=_("Toggle night mode"), screen=true},
set_night_mode = {category="string", event="SetNightMode", title=_("Set night mode"), screen=true, args={true, false}, toggle={_("On"), _("Off")}, separator=true},
set_refresh_rate = {category="absolutenumber", event="SetBothRefreshRates", min=-1, max=200, title=_("Flash every %1 pages (always)"), screen=true, condition=Device:hasEinkScreen()},
set_day_refresh_rate = {category="absolutenumber", event="SetDayRefreshRate", min=-1, max=200, title=_("Flash every %1 pages (not in night mode)"), screen=true, condition=Device:hasEinkScreen()},
set_night_refresh_rate = {category="absolutenumber", event="SetNightRefreshRate", min=-1, max=200, title=_("Flash every %1 pages (in night mode)"), screen=true, condition=Device:hasEinkScreen()},
set_flash_on_chapter_boundaries = {category="string", event="SetFlashOnChapterBoundaries", title=_("Always flash on chapter boundaries"), screen=true, condition=Device:hasEinkScreen(), args={true, false}, toggle={_("On"), _("Off")}},
toggle_flash_on_chapter_boundaries = {category="none", event="ToggleFlashOnChapterBoundaries", title=_("Toggle flashing on chapter boundaries"), screen=true, condition=Device:hasEinkScreen()},
set_no_flash_on_second_chapter_page = {category="string", event="SetNoFlashOnSecondChapterPage", title=_("Never flash on chapter's 2nd page"), screen=true, condition=Device:hasEinkScreen(), args={true, false}, toggle={_("On"), _("Off")}},
toggle_no_flash_on_second_chapter_page = {category="none", event="ToggleNoFlashOnSecondChapterPage", title=_("Toggle flashing on chapter's 2nd page"), screen=true, condition=Device:hasEinkScreen(), separator=true},
-- Device settings
toggle_gsensor = {category="none", event="ToggleGSensor", title=_("Toggle accelerometer"), device=true, condition=Device:canToggleGSensor()},
wifi_on = {category="none", event="InfoWifiOn", title=_("Turn on Wi-Fi"), device=true, condition=Device:hasWifiToggle()},
wifi_off = {category="none", event="InfoWifiOff", title=_("Turn off Wi-Fi"), device=true, condition=Device:hasWifiToggle()},
toggle_wifi = {category="none", event="ToggleWifi", title=_("Toggle Wi-Fi"), device=true, condition=Device:hasWifiToggle()},
toggle_fullscreen = {category="none", event="ToggleFullscreen", title=_("Toggle Fullscreen"), device=true, condition=not Device:isAlwaysFullscreen()},
show_network_info = {category="none", event="ShowNetworkInfo", title=_("Show network info"), device=true, separator=true},
exit_screensaver = {category="none", event="ExitScreensaver", title=_("Exit screensaver"), device=true},
restart = {category="none", event="Restart", title=_("Restart KOReader"), device=true, condition=Device:canRestart()},
suspend = {category="none", event="RequestSuspend", title=_("Suspend"), device=true},
reboot = {category="none", event="RequestReboot", title=_("Reboot the device"), device=true, condition=Device:canReboot()},
poweroff = {category="none", event="RequestPowerOff", title=_("Power off"), device=true, condition=Device:canPowerOff(), separator=true},
exit = {category="none", event="Exit", title=_("Exit KOReader"), device=true},
toggle_hold_corners = {category="none", event="IgnoreHoldCorners", title=_("Toggle hold corners"), device=true, separator=true},
toggle_rotation = {category="none", event="SwapRotation", title=_("Toggle orientation"), device=true},
invert_rotation = {category="none", event="InvertRotation", title=_("Invert rotation"), device=true},
iterate_rotation = {category="none", event="IterateRotation", title=_("Rotate by 90° CW"), device=true},
iterate_rotation_ccw = {category="none", event="IterateRotation", arg=true, title=_("Rotate by 90° CCW"), device=true, separator=true},
-- General
reading_progress = {category="none", event="ShowReaderProgress", title=_("Reading progress"), general=true},
history = {category="none", event="ShowHist", title=_("History"), general=true},
open_previous_document = {category="none", event="OpenLastDoc", title=_("Open previous document"), general=true},
filemanager = {category="none", event="Home", title=_("File browser"), general=true, separator=true},
dictionary_lookup = {category="none", event="ShowDictionaryLookup", title=_("Dictionary lookup"), general=true},
wikipedia_lookup = {category="none", event="ShowWikipediaLookup", title=_("Wikipedia lookup"), general=true},
fulltext_search = {category="none", event="ShowFulltextSearchInput", title=_("Fulltext search"), general=true},
file_search = {category="none", event="ShowFileSearch", title=_("File search"), general=true, separator=true},
show_menu = {category="none", event="ShowMenu", title=_("Show menu"), general=true},
favorites = {category="none", event="ShowColl", arg="favorites", title=_("Favorites"), general=true},
screenshot = {category="none", event="Screenshot", title=_("Screenshot"), general=true, separator=true},
-- filemanager settings
folder_up = {category="none", event="FolderUp", title=_("Folder up"), filemanager=true},
show_plus_menu = {category="none", event="ShowPlusMenu", title=_("Show plus menu"), filemanager=true},
toggle_select_mode = {category="none", event="ToggleSelectMode", title=_("Toggle select mode"), filemanager=true},
refresh_content = {category="none", event="RefreshContent", title=_("Refresh content"), filemanager=true},
folder_shortcuts = {category="none", event="ShowFolderShortcutsDialog", title=_("Folder shortcuts"), filemanager=true, separator=true},
-- reader settings
toggle_status_bar = {category="none", event="TapFooter", title=_("Toggle status bar"), reader=true, separator=true},
prev_chapter = {category="none", event="GotoPrevChapter", title=_("Previous chapter"), reader=true},
next_chapter = {category="none", event="GotoNextChapter", title=_("Next chapter"), reader=true},
first_page = {category="none", event="GoToBeginning", title=_("First page"), reader=true},
last_page = {category="none", event="GoToEnd", title=_("Last page"), reader=true},
prev_bookmark = {category="none", event="GotoPreviousBookmarkFromPage", title=_("Previous bookmark"), reader=true},
next_bookmark = {category="none", event="GotoNextBookmarkFromPage", title=_("Next bookmark"), reader=true},
go_to = {category="none", event="ShowGotoDialog", title=_("Go to page"), filemanager=true, reader=true},
skim = {category="none", event="ShowSkimtoDialog", title=_("Skim document"), reader=true},
back = {category="none", event="Back", title=_("Back"), reader=true},
previous_location = {category="none", event="GoBackLink", arg=true, title=_("Back to previous location"), reader=true},
latest_bookmark = {category="none", event="GoToLatestBookmark", title=_("Go to latest bookmark"), reader=true},
follow_nearest_link = {category="arg", event="GoToPageLink", arg={pos={x=0,y=0}}, title=_("Follow nearest link"), reader=true},
follow_nearest_internal_link = {category="arg", event="GoToInternalPageLink", arg={pos={x=0,y=0}}, title=_("Follow nearest internal link"), reader=true},
clear_location_history = {category="none", event="ClearLocationStack", arg=true, title=_("Clear location history"), reader=true, separator=true},
toc = {category="none", event="ShowToc", title=_("Table of contents"), reader=true},
book_map = {category="none", event="ShowBookMap", title=_("Book map"), reader=true, condition=Device:isTouchDevice()},
page_browser = {category="none", event="ShowPageBrowser", title=_("Page browser"), reader=true, condition=Device:isTouchDevice()},
bookmarks = {category="none", event="ShowBookmark", title=_("Bookmarks"), reader=true},
bookmark_search = {category="none", event="SearchBookmark", title=_("Bookmark search"), reader=true},
book_status = {category="none", event="ShowBookStatus", title=_("Book status"), reader=true},
book_info = {category="none", event="ShowBookInfo", title=_("Book information"), reader=true},
book_description = {category="none", event="ShowBookDescription", title=_("Book description"), reader=true},
book_cover = {category="none", event="ShowBookCover", title=_("Book cover"), reader=true, separator=true},
show_config_menu = {category="none", event="ShowConfigMenu", title=_("Show bottom menu"), reader=true},
toggle_bookmark = {category="none", event="ToggleBookmark", title=_("Toggle bookmark"), reader=true},
toggle_page_change_animation = {category="none", event="TogglePageChangeAnimation", title=_("Toggle page turn animations"), reader=true, condition=Device:canDoSwipeAnimation()},
toggle_inverse_reading_order = {category="none", event="ToggleReadingOrder", title=_("Toggle page turn direction"), reader=true, separator=true},
swap_page_turn_buttons = {category="none", event="SwapPageTurnButtons", title=_("Invert page turn buttons"), reader=true, condition=Device:hasKeys(), separator=true},
cycle_highlight_action = {category="none", event="CycleHighlightAction", title=_("Cycle highlight action"), reader=true},
cycle_highlight_style = {category="none", event="CycleHighlightStyle", title=_("Cycle highlight style"), reader=true},
page_jmp = {category="absolutenumber", event="GotoViewRel", min=-100, max=100, title=_("Go %1 pages"), reader=true},
panel_zoom_toggle = {category="none", event="TogglePanelZoomSetting", title=_("Toggle panel zoom"), paging=true, separator=true},
-- rolling reader settings
set_font = {category="string", event="SetFont", title=_("Set font"), rolling=true, args_func=require("fontlist").getFontArgFunc,},
increase_font = {category="incrementalnumber", event="IncreaseFontSize", min=0.5, max=255, step=0.5, title=_("Increase font size by %1"), rolling=true},
decrease_font = {category="incrementalnumber", event="DecreaseFontSize", min=0.5, max=255, step=0.5, title=_("Decrease font size by %1"), rolling=true},
-- paging reader settings
toggle_page_flipping = {category="none", event="TogglePageFlipping", title=_("Toggle page flipping"), paging=true},
toggle_reflow = {category="none", event="ToggleReflow", title=_("Toggle reflow"), paging=true},
zoom = {category="string", event="SetZoomMode", title=_("Zoom mode"), args=ReaderZooming.available_zoom_modes, toggle=ReaderZooming.available_zoom_modes, paging=true},
zoom_factor_change = {category="none", event="ZoomFactorChange", title=_("Change zoom factor"), paging=true, separator=true},
-- parsed from CreOptions
-- the rest of the table elements are built from their counterparts in CreOptions
rotation_mode = {category="string", device=true},
visible_pages = {category="string", rolling=true, separator=true},
h_page_margins = {category="string", rolling=true},
sync_t_b_page_margins = {category="string", rolling=true},
t_page_margin = {category="absolutenumber", rolling=true},
b_page_margin = {category="absolutenumber", rolling=true, separator=true},
view_mode = {category="string", rolling=true},
block_rendering_mode = {category="string", rolling=true},
render_dpi = {category="string", rolling=true},
line_spacing = {category="absolutenumber", rolling=true, separator=true},
font_size = {category="absolutenumber", title=_("Set font size to %1"), rolling=true, step=0.5},
font_base_weight = {category="string", rolling=true},
font_gamma = {category="string", rolling=true},
font_hinting = {category="string", rolling=true},
font_kerning = {category="string", rolling=true, separator=true},
status_line = {category="string", rolling=true},
embedded_css = {category="string", rolling=true},
embedded_fonts = {category="string", rolling=true},
smooth_scaling = {category="string", rolling=true},
nightmode_images = {category="string", rolling=true},
-- parsed from KoptOptions
kopt_trim_page = {category="string", paging=true},
kopt_page_margin = {category="string", paging=true},
kopt_zoom_overlap_h = {category="absolutenumber", paging=true},
kopt_zoom_overlap_v = {category="absolutenumber", paging=true},
kopt_zoom_mode_type = {category="string", paging=true},
kopt_zoom_range_number = {category="string", paging=true},
kopt_zoom_factor = {category="string", paging=true},
kopt_zoom_mode_genus = {category="string", paging=true},
kopt_zoom_direction = {category="string", paging=true},
kopt_page_scroll = {category="string", paging=true},
kopt_page_gap_height = {category="string", paging=true},
kopt_full_screen = {category="string", paging=true},
kopt_line_spacing = {category="configurable", paging=true},
kopt_justification = {category="configurable", paging=true},
kopt_font_size = {category="string", paging=true, title=_("Font Size")},
kopt_font_fine_tune = {category="string", paging=true},
kopt_word_spacing = {category="configurable", paging=true},
kopt_text_wrap = {category="string", paging=true},
kopt_contrast = {category="absolutenumber", paging=true},
kopt_page_opt = {category="configurable", paging=true},
kopt_hw_dithering = {category="configurable", paging=true, condition=Device:hasEinkScreen() and Device:canHWDither()},
kopt_sw_dithering = {category="configurable", paging=true, condition=Device:hasEinkScreen() and not Device:canHWDither() and Device.screen.fb_bpp == 8},
kopt_quality = {category="configurable", paging=true},
kopt_doc_language = {category="string", paging=true},
kopt_forced_ocr = {category="configurable", paging=true},
kopt_writing_direction = {category="configurable", paging=true},
kopt_defect_size = {category="string", paging=true, condition=false},
kopt_auto_straighten = {category="absolutenumber", paging=true},
kopt_detect_indent = {category="configurable", paging=true, condition=false},
kopt_max_columns = {category="configurable", paging=true},
settings = nil, -- reserved for per instance dispatcher settings
}
-- array for item order in menu
local dispatcher_menu_order = {
-- device
"reading_progress",
"open_previous_document",
"history",
"favorites",
"filemanager",
"dictionary_lookup",
"wikipedia_lookup",
"fulltext_search",
"file_search",
"show_menu",
"screenshot",
"exit_screensaver",
"suspend",
"exit",
"restart",
"reboot",
"poweroff",
"toggle_hold_corners",
"toggle_gsensor",
"rotation_mode",
"toggle_rotation",
"invert_rotation",
"iterate_rotation",
"iterate_rotation_ccw",
"wifi_on",
"wifi_off",
"toggle_wifi",
"toggle_fullscreen",
"show_network_info",
"show_frontlight_dialog",
"toggle_frontlight",
"set_frontlight",
"increase_frontlight",
"decrease_frontlight",
"set_frontlight_warmth",
"increase_frontlight_warmth",
"decrease_frontlight_warmth",
"night_mode",
"set_night_mode",
"full_refresh",
"set_refresh_rate",
"set_day_refresh_rate",
"set_night_refresh_rate",
"set_flash_on_chapter_boundaries",
"toggle_flash_on_chapter_boundaries",
"set_no_flash_on_second_chapter_page",
"toggle_no_flash_on_second_chapter_page",
-- filemanager
"folder_up",
"show_plus_menu",
"toggle_select_mode",
"refresh_content",
"folder_shortcuts",
-- reader
"show_config_menu",
"toggle_status_bar",
"prev_chapter",
"next_chapter",
"first_page",
"last_page",
"page_jmp",
"go_to",
"skim",
"prev_bookmark",
"next_bookmark",
"latest_bookmark",
"back",
"previous_location",
"follow_nearest_link",
"follow_nearest_internal_link",
"clear_location_history",
"toc",
"book_map",
"page_browser",
"bookmarks",
"bookmark_search",
"book_status",
"book_info",
"book_description",
"book_cover",
"set_font",
"increase_font",
"decrease_font",
"font_size",
"font_gamma",
"font_base_weight",
"font_hinting",
"font_kerning",
"toggle_bookmark",
"toggle_page_change_animation",
"toggle_page_flipping",
"toggle_reflow",
"toggle_inverse_reading_order",
"swap_page_turn_buttons",
"zoom",
"zoom_factor_change",
"cycle_highlight_action",
"cycle_highlight_style",
"panel_zoom_toggle",
"visible_pages",
"h_page_margins",
"sync_t_b_page_margins",
"t_page_margin",
"b_page_margin",
"view_mode",
"block_rendering_mode",
"render_dpi",
"line_spacing",
"status_line",
"embedded_css",
"embedded_fonts",
"smooth_scaling",
"nightmode_images",
"kopt_trim_page",
"kopt_page_margin",
"kopt_zoom_overlap_h",
"kopt_zoom_overlap_v",
"kopt_zoom_mode_type",
--"kopt_zoom_range_number", -- can't figure out how this name text func works
"kopt_zoom_factor",
"kopt_zoom_mode_genus",
"kopt_zoom_direction",
"kopt_page_scroll",
"kopt_page_gap_height",
"kopt_full_screen",
"kopt_line_spacing",
"kopt_justification",
"kopt_font_size",
"kopt_font_fine_tune",
"kopt_word_spacing",
"kopt_text_wrap",
"kopt_contrast",
"kopt_page_opt",
"kopt_hw_dithering",
"kopt_sw_dithering",
"kopt_quality",
"kopt_doc_language",
"kopt_forced_ocr",
"kopt_writing_direction",
"kopt_defect_size",
"kopt_auto_straighten",
"kopt_detect_indent",
"kopt_max_columns",
}
--[[--
add settings from CreOptions / KoptOptions
--]]--
function Dispatcher:init()
if Dispatcher.initialized then return end
local parseoptions = function(base, i, prefix)
for y=1, #base[i].options do
local option = base[i].options[y]
local name = prefix and prefix .. option.name or option.name
if settingsList[name] ~= nil then
if option.name ~= nil and option.values ~= nil then
settingsList[name].configurable = {name = option.name, values = option.values}
end
if settingsList[name].event == nil then
settingsList[name].event = option.event
end
if settingsList[name].title == nil then
settingsList[name].title = option.name_text
end
if settingsList[name].category == "string" or settingsList[name].category == "configurable" then
if settingsList[name].toggle == nil then
settingsList[name].toggle = option.toggle or option.labels
if settingsList[name].toggle == nil then
settingsList[name].toggle = {}
for z=1,#option.values do
if type(option.values[z]) == "table" then
settingsList[name].toggle[z] = option.values[z][1]
else
settingsList[name].toggle[z] = option.values[z]
end
end
end
end
if settingsList[name].args == nil then
settingsList[name].args = option.args or option.values
end
elseif settingsList[name].category == "absolutenumber" then
if settingsList[name].min == nil then
settingsList[name].min = option.args and option.args[1] or option.values[1]
end
if settingsList[name].max == nil then
settingsList[name].max = option.args and option.args[#option.args] or option.values[#option.values]
end
if settingsList[name].default == nil then
settingsList[name].default = option.default_value
end
end
end
end
end
for i=1,#CreOptions do
parseoptions(CreOptions, i)
end
for i=1,#KoptOptions do
parseoptions(KoptOptions, i, "kopt_")
end
UIManager:broadcastEvent(Event:new("DispatcherRegisterActions"))
Dispatcher.initialized = true
end
--[[--
Adds settings at runtime.
@usage
function Hello:onDispatcherRegisterActions()
Dispatcher:registerAction("helloworld_action", {category="none", event="HelloWorld", title=_("Hello World"), general=true})
end
function Hello:init()
self:onDispatcherRegisterActions()
end
@param name the key to use in the table
@param value a table per settingsList above
--]]--
function Dispatcher:registerAction(name, value)
if settingsList[name] == nil then
settingsList[name] = value
table.insert(dispatcher_menu_order, name)
end
return true
end
--[[--
Removes settings at runtime.
@param name the key to use in the table
--]]--
function Dispatcher:removeAction(name)
local k = util.arrayContains(dispatcher_menu_order, name)
if k then
table.remove(dispatcher_menu_order, k)
settingsList[name] = nil
end
return true
end
local function iter_func(settings)
if settings and settings.settings and settings.settings.order then
return ipairs(settings.settings.order)
else
return pairs(settings)
end
end
-- Returns the number of items present in the settings table
function Dispatcher:_itemsCount(settings)
if settings then
local count = util.tableSize(settings)
if count > 0 and settings.settings ~= nil then
count = count - 1
end
return count
end
end
-- Returns a display name for the item.
function Dispatcher:getNameFromItem(item, settings)
if settingsList[item] == nil then
return _("Unknown item")
end
local amount
if settings ~= nil and settings[item] ~= nil then
amount = settings[item]
end
if amount == nil
or (amount == 0 and settingsList[item].category == "incrementalnumber")
then
amount = C_("Number placeholder", "#")
end
return T(settingsList[item].title, amount)
end
-- Add the item to the end of the execution order.
-- If item or the order is nil all items will be added.
function Dispatcher:_addToOrder(location, settings, item)
if location[settings] then
if not location[settings].settings then location[settings].settings = {} end
if not location[settings].settings.order or item == nil then
location[settings].settings.order = {}
for k in pairs(location[settings]) do
if settingsList[k] ~= nil then
table.insert(location[settings].settings.order, k)
end
end
else
if not util.arrayContains(location[settings].settings.order, item) then
table.insert(location[settings].settings.order, item)
end
end
end
end
-- Remove the item from the execution order.
-- If item is nil all items will be removed.
-- If the resulting order is empty it will be nilled
function Dispatcher:_removeFromOrder(location, settings, item)
if location[settings] and location[settings].settings then
if location[settings].settings.order then
if item then
local k = util.arrayContains(location[settings].settings.order, item)
if k then table.remove(location[settings].settings.order, k) end
else
location[settings].settings.order = {}
end
if next(location[settings].settings.order) == nil then
location[settings].settings.order = nil
if next(location[settings].settings) == nil then
location[settings].settings = nil
end
end
end
end
end
-- Get a textual representation of the enabled actions to display in a menu item.
function Dispatcher:menuTextFunc(settings)
local action_name = _("Pass through")
if settings then
local count = Dispatcher:_itemsCount(settings)
if count == 0 then return _("Nothing") end
if count == 1 then
local item = next(settings)
if item == "settings" then item = next(settings, item) end
action_name = Dispatcher:getNameFromItem(item, settings)
else
action_name = T(N_("", "%1 actions", count), count)
end
end
return action_name
end
-- Get a list of all enabled actions to display in a menu.
function Dispatcher:getDisplayList(settings)
local item_table = {}
if not settings then return item_table end
for item, v in iter_func(settings) do
if type(item) == "number" then item = v end
if settingsList[item] ~= nil and (settingsList[item].condition == nil or settingsList[item].condition == true) then
table.insert(item_table, {text = Dispatcher:getNameFromItem(item, settings), key = item})
end
end
return item_table
end
-- Display a SortWidget to sort the enable actions execution order.
function Dispatcher:_sortActions(caller, location, settings, touchmenu_instance)
local display_list = Dispatcher:getDisplayList(location[settings])
local SortWidget = require("ui/widget/sortwidget")
local sort_widget
sort_widget = SortWidget:new{
title = _("Sort"),
item_table = display_list,
callback = function()
if location[settings] and next(location[settings]) ~= nil then
if not location[settings].settings then
location[settings].settings = {}
end
location[settings].settings.order = {}
for i, v in ipairs(sort_widget.item_table) do
location[settings].settings.order[i] = v.key
end
end
if touchmenu_instance then touchmenu_instance:updateItems() end
caller.updated = true
end
}
UIManager:show(sort_widget)
end
function Dispatcher:_addItem(caller, menu, location, settings, section)
for _, k in ipairs(dispatcher_menu_order) do
if settingsList[k][section] == true and
(settingsList[k].condition == nil or settingsList[k].condition)
then
if settingsList[k].category == "none" or settingsList[k].category == "arg" then
table.insert(menu, {
text = settingsList[k].title,
checked_func = function()
return location[settings] ~= nil and location[settings][k] ~= nil
end,
callback = function(touchmenu_instance)
if location[settings] == nil then
location[settings] = {}
end
if location[settings][k] then
location[settings][k] = nil
Dispatcher:_removeFromOrder(location, settings, k)
else
location[settings][k] = true
Dispatcher:_addToOrder(location, settings, k)
end
caller.updated = true
if touchmenu_instance then touchmenu_instance:updateItems() end
end,
separator = settingsList[k].separator,
})
elseif settingsList[k].category == "absolutenumber" then
table.insert(menu, {
text_func = function()
return Dispatcher:getNameFromItem(k, location[settings])
end,
checked_func = function()
return location[settings] ~= nil and location[settings][k] ~= nil
end,
callback = function(touchmenu_instance)
local SpinWidget = require("ui/widget/spinwidget")
local precision
if settingsList[k].step and math.floor(settingsList[k].step) ~= settingsList[k].step then
precision = "%0.1f"
end
local items = SpinWidget:new{
value = location[settings] ~= nil and location[settings][k] or settingsList[k].default or 0,
value_min = settingsList[k].min,
value_step = settingsList[k].step or 1,
precision = precision,
value_hold_step = 5,
value_max = settingsList[k].max,
default_value = settingsList[k].default,
title_text = Dispatcher:getNameFromItem(k, location[settings]),
ok_always_enabled = true,
callback = function(spin)
if location[settings] == nil then
location[settings] = {}
end
location[settings][k] = spin.value
Dispatcher:_addToOrder(location, settings, k)
caller.updated = true
if touchmenu_instance then
touchmenu_instance:updateItems()
end
end
}
UIManager:show(items)
end,
hold_callback = function(touchmenu_instance)
if location[settings] ~= nil and location[settings][k] ~= nil then
location[settings][k] = nil
Dispatcher:_removeFromOrder(location, settings, k)
caller.updated = true
end
if touchmenu_instance then touchmenu_instance:updateItems() end
end,
separator = settingsList[k].separator,
})
elseif settingsList[k].category == "incrementalnumber" then
table.insert(menu, {
text_func = function()
return Dispatcher:getNameFromItem(k, location[settings])
end,
checked_func = function()
return location[settings] ~= nil and location[settings][k] ~= nil
end,
callback = function(touchmenu_instance)
local _ = require("gettext")
local precision
if settingsList[k].step and math.floor(settingsList[k].step) ~= settingsList[k].step then
precision = "%0.1f"
end
local SpinWidget = require("ui/widget/spinwidget")
local items = SpinWidget:new{
value = location[settings] ~= nil and location[settings][k] or 0,
value_min = settingsList[k].min,
value_step = settingsList[k].step or 1,
precision = precision,
value_hold_step = 5,
value_max = settingsList[k].max,
default_value = 0,
title_text = Dispatcher:getNameFromItem(k, location[settings]),
info_text = _([[If called by a gesture the amount of the gesture will be used]]),
ok_always_enabled = true,
callback = function(spin)
if location[settings] == nil then
location[settings] = {}
end
location[settings][k] = spin.value
Dispatcher:_addToOrder(location, settings, k)
caller.updated = true
if touchmenu_instance then
touchmenu_instance:updateItems()
end
end
}
UIManager:show(items)
end,
hold_callback = function(touchmenu_instance)
if location[settings] ~= nil and location[settings][k] ~= nil then
location[settings][k] = nil
Dispatcher:_removeFromOrder(location, settings, k)
caller.updated = true
end
if touchmenu_instance then
touchmenu_instance:updateItems()
end
end,
separator = settingsList[k].separator,
})
elseif settingsList[k].category == "string" or settingsList[k].category == "configurable" then
local sub_item_table = {}
if settingsList[k].args_func then
settingsList[k].args, settingsList[k].toggle = settingsList[k].args_func()
end
for i=1,#settingsList[k].args do
table.insert(sub_item_table, {
text = tostring(settingsList[k].toggle[i]),
checked_func = function()
return location[settings] ~= nil
and location[settings][k] ~= nil
and location[settings][k] == settingsList[k].args[i]
end,
callback = function()
if location[settings] == nil then
location[settings] = {}
end
location[settings][k] = settingsList[k].args[i]
Dispatcher:_addToOrder(location, settings, k)
caller.updated = true
end,
})
end
table.insert(menu, {
text_func = function()
return Dispatcher:getNameFromItem(k, location[settings])
end,
checked_func = function()
return location[settings] ~= nil and location[settings][k] ~= nil
end,
sub_item_table = sub_item_table,
keep_menu_open = true,
hold_callback = function(touchmenu_instance)
if location[settings] ~= nil and location[settings][k] ~= nil then
location[settings][k] = nil
Dispatcher:_removeFromOrder(location, settings, k)
caller.updated = true
end
if touchmenu_instance then
touchmenu_instance:updateItems()
end
end,
separator = settingsList[k].separator,
menu_item_id = k,
})
end
end
end
end
--[[--
Add a submenu to edit which items are dispatched
arguments are:
1) the caller so dispatcher can set the updated flag
2) the table representing the submenu (can be empty)
3) the object (table) in which the settings table is found
4) the name of the settings table
example usage:
Dispatcher:addSubMenu(self, sub_items, self.data, "profile1")
--]]--
function Dispatcher:addSubMenu(caller, menu, location, settings)
Dispatcher:init()
table.insert(menu, {
text = _("Nothing"),
separator = true,
checked_func = function()
return location[settings] ~= nil and Dispatcher:_itemsCount(location[settings]) == 0
end,
callback = function(touchmenu_instance)
local name = location[settings] and location[settings].settings and location[settings].settings.name
location[settings] = {}
if name then
location[settings].settings = { name = name }
end
caller.updated = true
if touchmenu_instance then touchmenu_instance:updateItems() end
end,
})
local section_list = {
{"general", _("General")},
{"device", _("Device")},
{"screen", _("Screen and lights")},
{"filemanager", _("File browser")},
{"reader", _("Reader")},
{"rolling", _("Reflowable documents (epub, fb2, txt…)")},
{"paging", _("Fixed layout documents (pdf, djvu, pics…)")},
}
for _, section in ipairs(section_list) do
local submenu = {}
Dispatcher:_addItem(caller, submenu, location, settings, section[1])
table.insert(menu, {
text = section[2],
checked_func = function()
if location[settings] ~= nil then
for k, _ in pairs(location[settings]) do
if settingsList[k] ~= nil and settingsList[k][section[1]] == true and
(settingsList[k].condition == nil or settingsList[k].condition)
then return true end
end
end
end,
hold_callback = function(touchmenu_instance)
if location[settings] ~= nil then
for k, _ in pairs(location[settings]) do
if settingsList[k] ~= nil and settingsList[k][section[1]] == true then
location[settings][k] = nil
Dispatcher:_removeFromOrder(location, settings, k)
caller.updated = true
end
end
if touchmenu_instance then touchmenu_instance:updateItems() end
end
end,
sub_item_table = submenu,
})
end
menu[#menu].separator = true
table.insert(menu, {
text = _("Show as QuickMenu"),
checked_func = function()
return location[settings] ~= nil
and location[settings].settings ~= nil
and location[settings].settings.show_as_quickmenu
end,
callback = function()
if location[settings] then
if location[settings].settings then
if location[settings].settings.show_as_quickmenu then
location[settings].settings.show_as_quickmenu = nil
if next(location[settings].settings) == nil then
location[settings].settings = nil
end
else
location[settings].settings.show_as_quickmenu = true
end
else
location[settings].settings = {["show_as_quickmenu"] = true}
end
caller.updated = true
end
end,
})
table.insert(menu, {
text = _("Sort"),
checked_func = function()
return location[settings] ~= nil
and location[settings].settings ~= nil
and location[settings].settings.order ~= nil
end,
callback = function(touchmenu_instance)
Dispatcher:_sortActions(caller, location, settings, touchmenu_instance)
end,
hold_callback = function(touchmenu_instance)
if location[settings]
and location[settings].settings
and location[settings].settings.order then
Dispatcher:_removeFromOrder(location, settings)
caller.updated = true
if touchmenu_instance then touchmenu_instance:updateItems() end
end
end,
})
end
function Dispatcher:_showAsMenu(settings)
local display_list = Dispatcher:getDisplayList(settings)
local quickmenu
local buttons = {}
for _, v in ipairs(display_list) do
table.insert(buttons, {{
text = v.text,
align = "left",
font_face = "smallinfofont",
font_size = 22,
font_bold = false,
callback = function()
UIManager:close(quickmenu)
Dispatcher:execute({[v.key] = settings[v.key]})
end,
}})
end
local ButtonDialogTitle = require("ui/widget/buttondialogtitle")
quickmenu = ButtonDialogTitle:new{
title = settings.settings.name or "Quick Menu",
title_align = "center",
width_factor = 0.8,
use_info_style = false,
buttons = buttons,
}
UIManager:show(quickmenu)
end
--[[--
Calls the events in a settings list
arguments are:
1) a reference to the uimanager
2) the settings table
3) optionally a `gestures`object
--]]--
function Dispatcher:execute(settings, gesture)
if settings.settings ~= nil and settings.settings.show_as_quickmenu == true then
return Dispatcher:_showAsMenu(settings)
end
local has_many = Dispatcher:_itemsCount(settings) > 1
if has_many then
UIManager:broadcastEvent(Event:new("BatchedUpdate"))
end
for k, v in iter_func(settings) do
if type(k) == "number" then
k = v
v = settings[k]
end
if settingsList[k] ~= nil and (settingsList[k].condition == nil or settingsList[k].condition == true) then
Notification:setNotifySource(Notification.SOURCE_DISPATCHER)
if settingsList[k].configurable then
local value = v
if type(v) ~= "number" then
for i, r in ipairs(settingsList[k].args) do
if v == r then value = settingsList[k].configurable.values[i] break end
end
end
UIManager:sendEvent(Event:new("ConfigChange", settingsList[k].configurable.name, value))
end
if settingsList[k].category == "none" then
if settingsList[k].arg ~= nil then
UIManager:sendEvent(Event:new(settingsList[k].event, settingsList[k].arg))
else
UIManager:sendEvent(Event:new(settingsList[k].event))
end
end
if settingsList[k].category == "absolutenumber"
or settingsList[k].category == "string"
then
UIManager:sendEvent(Event:new(settingsList[k].event, v))
end
-- the event can accept a gesture object or an argument
if settingsList[k].category == "arg" then
local arg = gesture or settingsList[k].arg
UIManager:sendEvent(Event:new(settingsList[k].event, arg))
end
-- the event can accept a gesture object or a number
if settingsList[k].category == "incrementalnumber" then
local arg = v ~= 0 and v or gesture or 0
UIManager:sendEvent(Event:new(settingsList[k].event, arg))
end
end
Notification:resetNotifySource()
end
if has_many then
UIManager:broadcastEvent(Event:new("BatchedUpdateDone"))
end
end
return Dispatcher
| agpl-3.0 |
MalRD/darkstar | scripts/globals/abilities/pets/zantetsuken.lua | 11 | 1540 | ---------------------------------------------
-- Zantetsuken
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/magic")
require("scripts/globals/msg")
---------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0
end
function onPetAbility(target, pet, skill, master)
local power = master:getMP() / master:getMaxMP()
master:setMP(0)
if (target:isNM()) then
local dmg = 0.1 * target:getHP() + 0.1 * target:getHP() * power
if (dmg > 9999) then
dmg = 9999
end
dmg = MobMagicalMove(pet,target,skill,dmg,dsp.magic.ele.DARK,1,TP_NO_EFFECT,0)
dmg = mobAddBonuses(pet, nil, target, dmg.dmg, dsp.magic.ele.DARK)
dmg = AvatarFinalAdjustments(dmg,pet,skill,target,dsp.attackType.MAGICAL,dsp.damageType.DARK,1)
target:takeDamage(damage, pet, dsp.attackType.MAGICAL, dsp.damageType.DARK)
target:updateEnmityFromDamage(pet,dmg)
return dmg
else
local chance = (100 * power) / skill:getTotalTargets()
if math.random(0,99) < chance and target:getAnimation() ~= 33 then
skill:setMsg(dsp.msg.basic.SKILL_ENFEEB_IS)
target:takeDamage(target:getHP(), pet, dsp.attackType.MAGICAL, dsp.damageType.DARK)
return dsp.effect.KO
else
skill:setMsg(dsp.msg.basic.EVADES)
return 0
end
end
end
| gpl-3.0 |
MalRD/darkstar | scripts/zones/Temenos/mobs/Light_Elemental.lua | 9 | 1313 | -----------------------------------
-- Area: Temenos E T
-- Mob: Light Elemental
-----------------------------------
require("scripts/globals/limbus");
-----------------------------------
function onMobEngaged(mob,target)
local mobID = mob:getID();
if (mobID==16929031) then
GetMobByID(16929032):updateEnmity(target);
GetMobByID(16929030):updateEnmity(target);
elseif (mobID==16929032) then
GetMobByID(16929031):updateEnmity(target);
GetMobByID(16929030):updateEnmity(target);
end
end;
function onMobDeath(mob, player, isKiller)
local mobID = mob:getID();
switch (mobID): caseof {
[16929031] = function (x)
if (IsMobDead(16929030)==true and IsMobDead(16929032)==true ) then
GetNPCByID(16928768+77):setPos(0.5,-6,-459);
GetNPCByID(16928768+77):setStatus(dsp.status.NORMAL);
GetNPCByID(16928768+472):setStatus(dsp.status.NORMAL);
end
end ,
[16929032] = function (x)
if (IsMobDead(16929030)==true and IsMobDead(16929031)==true ) then
GetNPCByID(16928768+77):setPos(0.5,-6,-459);
GetNPCByID(16928768+77):setStatus(dsp.status.NORMAL);
GetNPCByID(16928768+472):setStatus(dsp.status.NORMAL);
end
end ,
}
end; | gpl-3.0 |
Lsty/ygopro-scripts | c26268488.lua | 3 | 3972 | --聖珖神竜 スターダスト・シフル
function c26268488.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,aux.FilterBoolFunction(Card.IsType,TYPE_SYNCHRO),aux.NonTuner(Card.IsType,TYPE_SYNCHRO),2)
c:EnableReviveLimit()
--cannot special summon
local e1=Effect.CreateEffect(c)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
e1:SetValue(aux.synlimit)
c:RegisterEffect(e1)
--indes
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EFFECT_DESTROY_REPLACE)
e2:SetRange(LOCATION_MZONE)
e2:SetTarget(c26268488.reptg)
e2:SetValue(c26268488.repval)
c:RegisterEffect(e2)
local g=Group.CreateGroup()
g:KeepAlive()
e2:SetLabelObject(g)
--disable
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(26268488,0))
e3:SetCategory(CATEGORY_DESTROY+CATEGORY_DISABLE)
e3:SetType(EFFECT_TYPE_QUICK_O)
e3:SetCode(EVENT_CHAINING)
e3:SetRange(LOCATION_MZONE)
e3:SetCountLimit(1)
e3:SetCondition(c26268488.discon)
e3:SetTarget(c26268488.distg)
e3:SetOperation(c26268488.disop)
c:RegisterEffect(e3)
--spsummon
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(26268488,1))
e4:SetCategory(CATEGORY_SPECIAL_SUMMON)
e4:SetType(EFFECT_TYPE_IGNITION)
e4:SetRange(LOCATION_GRAVE)
e4:SetProperty(EFFECT_FLAG_CARD_TARGET)
e4:SetCost(c26268488.spcost)
e4:SetTarget(c26268488.sptg)
e4:SetOperation(c26268488.spop)
c:RegisterEffect(e4)
end
function c26268488.repfilter(c,tp)
return c:IsControler(tp) and c:IsOnField() and c:IsReason(REASON_BATTLE+REASON_EFFECT) and c:GetFlagEffect(26268488)==0
end
function c26268488.reptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return eg:IsExists(c26268488.repfilter,1,nil,tp) end
local g=eg:Filter(c26268488.repfilter,nil,tp)
local tc=g:GetFirst()
while tc do
tc:RegisterFlagEffect(26268488,RESET_EVENT+0x1fc0000+RESET_PHASE+RESET_END,EFFECT_FLAG_CLIENT_HINT,1,0,aux.Stringid(26268488,2))
tc=g:GetNext()
end
e:GetLabelObject():Clear()
e:GetLabelObject():Merge(g)
return true
end
function c26268488.repval(e,c)
local g=e:GetLabelObject()
return g:IsContains(c)
end
function c26268488.discon(e,tp,eg,ep,ev,re,r,rp)
return not e:GetHandler():IsStatus(STATUS_BATTLE_DESTROYED) and rp~=tp and re:IsActiveType(TYPE_MONSTER) and Duel.IsChainDisablable(ev)
end
function c26268488.distg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DISABLE,eg,1,0,0)
local g=Duel.GetMatchingGroup(Card.IsDestructable,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c26268488.disop(e,tp,eg,ep,ev,re,r,rp)
Duel.NegateEffect(ev)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectMatchingCard(tp,Card.IsDestructable,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
if g:GetCount()>0 then
Duel.Destroy(g,REASON_EFFECT)
end
end
function c26268488.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST)
end
function c26268488.spfilter(c,e,tp)
return c:IsSetCard(0xa3) and c:IsLevelBelow(8) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c26268488.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c26268488.spfilter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c26268488.spfilter,tp,LOCATION_GRAVE,0,1,e:GetHandler(),e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c26268488.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c26268488.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
gallenmu/MoonGen | interface/options/dataLimit.lua | 4 | 1770 | local units = require "units"
local option = {}
option.description = "Stop sending this flow after a certain amount of data. As"
.. " flows should only be cut short at a whole number of packets sent, every"
.. " value passed will be rounded up to the nearest whole number of packets."
.. "\n\nEach thread will keep its own packet counter, so the actual amount of"
.. " packets sent is the setting of this option multiplied by the nummer of"
.. " tx queues requested."
option.configHelp = "Passing a number instead of a string will interpret the value as megabit."
option.usage = { { "<number><sizeUnit>", "Default use case." } }
local function _parse_limit(lstring, psize)
local num, unit = string.match(lstring, "^(%d+%.?%d*)(%a+)$")
if not num then
return nil, "Invalid format. Should be '<number><unit>'."
end
num, unit = tonumber(num), string.lower(unit)
if unit == "" then
unit = units.size.m --default is mbit
elseif string.find(unit, "bit$") then
unit = units.size[string.sub(unit, 1, -4)]
elseif string.find(unit, "b$") then
unit = units.size[string.sub(unit, 1, -2)] * 8
elseif string.find(unit, "p$") then
unit = units.size[string.sub(unit, 1, -2)] * psize * 8
else
return nil, unit.sizeError
end
return num, unit
end
function option.parse(self, limit, error)
if not limit then return end
local psize = self:packetSize(true)
local t = type(limit)
local num, unit
if t == "number" then
num, unit = limit, units.size.m
elseif t == "string" then
num, unit = _parse_limit(limit, psize)
error:assert(num, unit)
else
error("Invalid argument. String or number expected, got %s.", t)
end
-- round up to mimic behaviour of timeLimit
if num then
return math.ceil(num * unit / (psize * 8))
end
end
return option
| mit |
raiguard/ModernGadgets | Skins/ModernGadgets/@Resources/Scripts/LoadSkin.lua | 2 | 6059 | --[[
----------------------------------------------------------------------------------------------------
LOADSKIN.LUA
raiguard
v4.0.0
----------------------------------------------------------------------------------------------------
Release Notes:
v4.0.0 - 2019-05-12
- Added support for an unlimited number of asset variants
- Replaced GetIcon() with GetAsset()
- Fixed that calling the script through inline LUA from a MeterStyle line would
crash Rainmeter
v3.0.1 - 2018-10-28
- Changed default toggle values back to the #toggleOn# and #toggleOff# variables
- Fixed script crashing if called through inline LUA
v3.0.0 - 2018-10-28
- Redesigned script to simplify the required inputs
- Improved documentation
v2.0.0 - 2018-6-22
- Updated to use the new ConfigActive plugin rather than WebParser
v1.3.0 - 2018-6-21
- The script now gets the input from a WebParser measure, rather than directly parsing
Rainmeter.ini (for Rainmeter 4.2+ compatibility)
v1.2.0 - 2017-12-27
- Added ability to specifically load or unload skins, rather than always toggling them
v1.1.0 - 2017-12-7
- Consolidated LoadConfig() into LoadSkin()
v1.0.0 - 2017-10-2
- Initial release
----------------------------------------------------------------------------------------------------
This script loads / unlaods the specified skin or config, and sets parameters for toggle
buttons related to those skins.
INSTRUCTIONS FOR USE:
Copy this file and paste it into your own suite. First, you will need to create a
ConfigActive plugin measure:
[MeasureConfigActive]
Measure=Plugin
Plugin=ConfigActive
That's all you need to add to this measure, the script will handle the rest. Speaking of
the script, that is the next measure you need to create:
[MeasureLoadSkinScript]
Measure=Script
ScriptFile=#@#Scripts\LoadSkin.lua
Assets={ check_icon = { 'check-on', 'check-off' } }
ToggleGroup=ToggleButtons
MeasureName=MeasureConfigActive
The 'Assets' parameter is a raw LUA table defining what assets to use for the skin buttons.
The format of the assets table goes { groupname = { 'OnAsset', 'OffAsset' } }. You can
add as many groups as you want to the parent table. If you do not specify this option, the
table will default to having a 'state' group with the strings 'On' and 'Off' as their
respective states.
The 'ToggleGroup' parameter specifies the group that the toggle button meters belong to.
If you do not include this option, it will default to 'SkinToggles'.
Last but not least, the 'MeasureName' option is simply the name of the ConfigActive
measure that you created before. If unspecified, it will default to 'MeasureConfigActive'.
A toggle button meter should look something like this:
[MeterToggleSystem]
Meter=Image
ImageName=#@#Images\[&MeasureLoadSkinScript:GetAsset('check_icon', 'illustro\\System')].png
X=5
Y=5
W=31
H=20
LeftMouseUpAction=[!CommandMeasure MeasureLoadSkinScript "ToggleSkin('illustro\\System')"]
DynamicVariables=1
Group=SkinToggles
The toggle buttons get their parameters via inline LUA, which requires that
'DynamicVariables=1' must be set on all the buttons. The buttons must also belong to the
group specified in the script measure.
Obviously, if you are using strings as your buttons, the inline LUA will be contained in
the 'Text' option, rather than 'ImageName'.
----------------------------------------------------------------------------------------------------
]]--
function Initialize()
assets = loadstring('return ' .. SELF:GetOption('Assets', '{ state = { \'On\', \'Off\' } }'))()
toggleOn = SELF:GetOption('ToggleOn', SKIN:GetVariable('toggleOn'))
toggleOff = SELF:GetOption('ToggleOff', SKIN:GetVariable('toggleOff'))
radioOn = SELF:GetOption('RadioOn', toggleOn)
radioOff = SELF:GetOption('RadioOff', toggleOff)
toggleGroup = SELF:GetOption('ToggleGroup', 'SkinToggles')
caMeasureName = SELF:GetOption('MeasureName', 'MeasureConfigActive')
end
function Update() end
-- toggles or sets the specified skin or config
function ToggleSkin(configName, iniName, toState)
--[[
PLEASE NOTE THAT THE DOUBLE BACKSLASHES ARE ALWAYS REQUIRED BECAUSE OF LUA SHENANIGANS
configName: the name of the config you wish to toggle (e.g. 'illustro\\Disk')
iniName (optional): the name of the skin INI you wish to toggle (e.g. '1 Disk.ini')
toState (optional): the state you wish to set the skin to (1 for active, -1 for inactive)
]]--
local configState, activeIni = GetConfigState(configName)
local toState = toState or iniName and (iniName == activeIni and -1 or 1) or configState * -1
if toState == 1 then
if iniName == nil then
SKIN:Bang('!ActivateConfig', configName)
elseif iniName ~= activeIni then
SKIN:Bang('!ActivateConfig', configName, iniName)
end
elseif configState == 1 then
SKIN:Bang('!DeactivateConfig', configName)
end
SKIN:Bang('!UpdateMeterGroup', toggleGroup)
SKIN:Bang('!Redraw')
return ''
end
-- returns the requested asset based on the config's active status
function GetAsset(type, configName, iniName)
--[[
PLEASE NOTE THAT THE DOUBLE BACKSLASHES ARE ALWAYS REQUIRED BECAUSE OF LUA SHENANIGANS
type: the asset type to retrieve from the assets table (e.g. 'check_icon')
configName: the name of the relevant config (e.g. 'illustro\\Disk')
iniName (optional): the name of the relevant INI file (e.g. '1 Disk.ini')
]]--
local configState, activeIni = GetConfigState(configName)
return (configState and assets[type]) and (configState == 1 and (iniName and (activeIni == iniName and assets[type][1] or assets[type][2]) or assets[type][1]) or assets[type][2]) or SKIN:Bang('!Log', 'Variable reference or icon type are invalid!', 'Error')
end
-- retrieves config state and active INI
function GetConfigState(configName)
local isActive = SKIN:ReplaceVariables('[&' .. caMeasureName .. ':IsActive(' .. configName .. ')]')
local activeIni = SKIN:ReplaceVariables('[&' .. caMeasureName .. ':ConfigVariantName(' .. configName .. ')]')
return tonumber(isActive), activeIni
end | mit |
Lsty/ygopro-scripts | c46656406.lua | 3 | 1138 | --呪言の鏡
function c46656406.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY+CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetTarget(c46656406.target)
e1:SetOperation(c46656406.activate)
c:RegisterEffect(e1)
end
function c46656406.filter(c,tp)
return c:GetSummonPlayer()~=tp and c:IsPreviousLocation(LOCATION_DECK) and c:IsDestructable()
end
function c46656406.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return eg:IsExists(c46656406.filter,1,nil,tp) and Duel.IsPlayerCanDraw(tp,1) end
local g=eg:Filter(c46656406.filter,nil,tp)
Duel.SetTargetCard(eg)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c46656406.filter2(c,e,tp)
return c:IsRelateToEffect(e) and c:GetSummonPlayer()~=tp and c:IsPreviousLocation(LOCATION_DECK) and c:IsDestructable()
end
function c46656406.activate(e,tp,eg,ep,ev,re,r,rp)
local g=eg:Filter(c46656406.filter2,nil,e,tp)
if Duel.Destroy(g,REASON_EFFECT)~=0 then
Duel.BreakEffect()
Duel.Draw(tp,1,REASON_EFFECT)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Western_Adoulin/npcs/Nylene.lua | 9 | 1282 | -----------------------------------
-- Area: Western Adoulin
-- NPC: Nylene
-- Type: Standard NPC and Quest NPC
-- Involved with Quest: 'A Certain Substitute Patrolman'
-- !pos 12 0 -82 256
-----------------------------------
require("scripts/globals/missions");
require("scripts/globals/quests");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local ACSP = player:getQuestStatus(ADOULIN, dsp.quest.id.adoulin.A_CERTAIN_SUBSTITUTE_PATROLMAN);
local SOA_Mission = player:getCurrentMission(SOA);
if (SOA_Mission >= dsp.mission.id.soa.LIFE_ON_THE_FRONTIER) then
if ((ACSP == QUEST_ACCEPTED) and (player:getCharVar("ACSP_NPCs_Visited") == 7)) then
-- Progresses Quest: 'A Certain Substitute Patrolman'
player:startEvent(2559);
else
-- Standard dialogue
player:startEvent(562);
end
else
-- Dialogue prior to joining colonization effort
player:startEvent(533);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 2559) then
-- Progresses Quest: 'A Certain Substitute Patrolman'
player:setCharVar("ACSP_NPCs_Visited", 8);
end
end;
| gpl-3.0 |
maxrio/luci981213 | applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/interface.lua | 39 | 2614 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.statistics.rrdtool.definitions.interface", package.seeall)
function rrdargs( graph, plugin, plugin_instance )
--
-- traffic diagram
--
local traffic = {
-- draw this diagram for each plugin instance
per_instance = true,
title = "%H: Transfer on %pi",
vlabel = "Bytes/s",
-- diagram data description
data = {
-- defined sources for data types, if ommitted assume a single DS named "value" (optional)
sources = {
if_octets = { "tx", "rx" }
},
-- special options for single data lines
options = {
if_octets__tx = {
total = true, -- report total amount of bytes
color = "00ff00", -- tx is green
title = "Bytes (TX)"
},
if_octets__rx = {
flip = true, -- flip rx line
total = true, -- report total amount of bytes
color = "0000ff", -- rx is blue
title = "Bytes (RX)"
}
}
}
}
--
-- packet diagram
--
local packets = {
-- draw this diagram for each plugin instance
per_instance = true,
title = "%H: Packets on %pi",
vlabel = "Packets/s",
-- diagram data description
data = {
-- data type order
types = { "if_packets", "if_errors" },
-- defined sources for data types
sources = {
if_packets = { "tx", "rx" },
if_errors = { "tx", "rx" }
},
-- special options for single data lines
options = {
-- processed packets (tx DS)
if_packets__tx = {
weight = 1,
overlay = true, -- don't summarize
total = true, -- report total amount of bytes
color = "00ff00", -- processed tx is green
title = "Processed (TX)"
},
-- processed packets (rx DS)
if_packets__rx = {
weight = 2,
overlay = true, -- don't summarize
flip = true, -- flip rx line
total = true, -- report total amount of bytes
color = "0000ff", -- processed rx is blue
title = "Processed (RX)"
},
-- packet errors (tx DS)
if_errors__tx = {
weight = 0,
overlay = true, -- don't summarize
total = true, -- report total amount of packets
color = "ff5500", -- tx errors are orange
title = "Errors (TX)"
},
-- packet errors (rx DS)
if_errors__rx = {
weight = 3,
overlay = true, -- don't summarize
flip = true, -- flip rx line
total = true, -- report total amount of packets
color = "ff0000", -- rx errors are red
title = "Errors (RX)"
}
}
}
}
return { traffic, packets }
end
| apache-2.0 |
MalRD/darkstar | scripts/globals/mobskills/primal_drill.lua | 11 | 1068 | ---------------------------------------------
-- Primal Drill
--
-- Description: Drills into nearby targets with appendages. Additional effect: Bind
-- Type: Physical
-- Utsusemi/Blink absorb: 2-3 shadows
-- Range: Unknown radial
-- Notes:
---------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local numhits = math.random(2,3)
local accmod = 1
local dmgmod = .8
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.PIERCING,info.hitslanded)
local typeEffect = dsp.effect.BIND
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 45)
target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.PIERCING)
return dmg
end
| gpl-3.0 |
Lsty/ygopro-scripts | c65496056.lua | 3 | 1453 | --コダロス
function c65496056.initial_effect(c)
--send to grave
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(65496056,0))
e1:SetCategory(CATEGORY_TOGRAVE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c65496056.cost)
e1:SetTarget(c65496056.target)
e1:SetOperation(c65496056.operation)
c:RegisterEffect(e1)
end
function c65496056.cfilter(c)
return c:IsFaceup() and c:IsCode(22702055) and c:IsAbleToGraveAsCost()
end
function c65496056.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c65496056.cfilter,tp,LOCATION_SZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c65496056.cfilter,tp,LOCATION_SZONE,0,1,1,nil)
Duel.SendtoGrave(g,REASON_COST)
end
function c65496056.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(1-tp) and chkc:IsOnField() and chkc:IsAbleToGrave() end
if chk==0 then return Duel.IsExistingTarget(Card.IsAbleToGrave,tp,0,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectTarget(tp,Card.IsAbleToGrave,tp,0,LOCATION_ONFIELD,1,2,nil)
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,g,g:GetCount(),0,0)
end
function c65496056.operation(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e)
Duel.SendtoGrave(g,REASON_EFFECT)
end
| gpl-2.0 |
mikhail-angelov/vlc | share/lua/intf/telnet.lua | 116 | 1876 | --[==========================================================================[
telnet.lua: wrapper for legacy telnet configuration
--[==========================================================================[
Copyright (C) 2011 the VideoLAN team
$Id$
Authors: Pierre Ynard
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.
--]==========================================================================]
if config.hosts == nil and config.host == nil then
config.host = "telnet://localhost:4212"
else
if config.hosts == nil then
config.hosts = { config.host }
end
for i,host in pairs(config.hosts) do
if host ~= "*console" then
local proto = string.match(host, "^%s*(.-)://")
if proto == nil or proto ~= "telnet" then
local newhost
if proto == nil then
newhost = "telnet://"..host
else
newhost = string.gsub(host, "^%s*.-://", "telnet://")
end
--vlc.msg.warn("Replacing host `"..host.."' with `"..newhost.."'")
config.hosts[i] = newhost
end
end
end
end
--[[ Launch vlm ]]
vlm = vlc.vlm()
dofile(wrapped_file)
| gpl-2.0 |
Aaa1r/DRAGON | plugins/supergroup.lua | 1 | 125744 | --[[
_ BY:@Aaa1R
__| |_ __ __ _ __ _ ___ _ __
/ _` | '__/ _` |/ _` |/ _ \| '_ \
| (_| | | | (_| | (_| | (_) | | | |
\__,_|_| \__,_|\__, |\___/|_| |_|
|___/
--]]
local function check_member_super(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
if success == 0 then
send_large_msg(receiver, "لــــلادمــنــيــه فــــقــط 🌀")
end
for k,v in pairs(result) do
local member_id = v.peer_id
if member_id ~= our_id then
-- SuperGroup configuration
data[tostring(msg.to.id)] = {
group_type = 'SuperGroup',
long_id = msg.to.peer_id,
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.title, '_', ' '),
lock_arabic = 'no',
lock_link = "no",
flood = 'yes',
lock_spam = 'yes',
lock_sticker = 'no',
member = 'no',
public = 'no',
lock_rtl = 'no',
lock_contacts = 'no',
strict = 'no'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
local text = 'تــــــم🆕تــــــفــعــيــل📢 الـــمــجــمــوعــه☑️تــــــاج👑مــــــخــــي🐲'
return reply_msg(msg.id, text, ok_cb, false)
end
end
end
--Check Members #rem supergroup
local function check_member_superrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local text = 'تــــــم🆕تـــــعـــطــيـــل⚠️ الـــمــجــمــوعــه☑️تــــــاج👑مــــــخــــي🐲'
return reply_msg(msg.id, text, ok_cb, false)
end
end
end
--Function to Add supergroup
local function superadd(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
channel_get_users(receiver, check_member_super,{receiver = receiver, data = data, msg = msg})
end
--Function to remove supergroup
local function superrem(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
channel_get_users(receiver, check_member_superrem,{receiver = receiver, data = data, msg = msg})
end
--Get and output admins and bots in supergroup
local function callback(cb_extra, success, result)
local i = 1
local chat_name = string.gsub(cb_extra.msg.to.print_name, "_", " ")
local member_type = cb_extra.member_type
local text = member_type.." for "..chat_name..":\n"
for k,v in pairsByKeys(result) do
if not v.first_name then
name = " "
else
vname = v.first_name:gsub("", "")
name = vname:gsub("_", " ")
end
text = text.."\n"..i.." - "..name.."["..v.peer_id.."]"
i = i + 1
end
send_large_msg(cb_extra.receiver, text)
end
--Get and output info about supergroup
local function callback_info(cb_extra, success, result)
local title ="مــعــلــــومــات📋عــن🔍 الــــمــــجــــمــــوعــة : ["..result.title.."]\n\n"
local admin_num = "💯عــــدد الادمــــنــــيــــة : "..result.admins_count.."\n"
local user_num = "💯عــــدد الاعــــــضــــاء : "..result.participants_count.."\n"
local kicked_num = "💯الاعــــــضــــاء الاكــــثــــر تــــفــاعــلا : "..result.kicked_count.."\n"
local channel_id = "💯ايــــديــ🆔الــــــمــجــــمــــوعــة : "..result.peer_id.."\n"
if result.username then
channel_username = " : @"..result.username
else
channel_username = ""
end
local text = title..admin_num..user_num..kicked_num..channel_id..channel_username
send_large_msg(cb_extra.receiver, text)
end
--Get and output members of supergroup
local function callback_who(cb_extra, success, result)
local text = "اعــــضــــاء الــــمــجــمــوعــة 🎯"..cb_extra.receiver
local i = 1
for k,v in pairsByKeys(result) do
if not v.print_name then
name = " "
else
vname = v.print_name:gsub("", "")
name = vname:gsub("_", " ")
end
if v.username then
username = " @"..v.username
else
username = ""
end
text = text.."\n"..i.." - "..name.." "..username.." [ "..v.peer_id.." ]\n"
--text = text.."\n"..username
i = i + 1
end
local file = io.open("./groups/lists/supergroups/"..cb_extra.receiver..".txt", "w")
file:write(text)
file:flush()
file:close()
send_document(cb_extra.receiver,"./groups/lists/supergroups/"..cb_extra.receiver..".txt", ok_cb, false)
post_msg(cb_extra.receiver, text, ok_cb, false)
end
--Get and output list of kicked users for supergroup
local function callback_kicked(cb_extra, success, result)
--vardump(result)
local text = "قائــــمــــه ايــــديــات🆔 الاعــــــضــــاء"..cb_extra.receiver.."\n\n"
local i = 1
for k,v in pairsByKeys(result) do
if not v.print_name then
name = " "
else
vname = v.print_name:gsub("", "")
name = vname:gsub("_", " ")
end
if v.username then
name = name.." @"..v.username
end
text = text.."\n"..i.." - "..name.." [ "..v.peer_id.." ]\n"
i = i + 1
end
local file = io.open("./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", "w")
file:write(text)
file:flush()
file:close()
send_document(cb_extra.receiver,"./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", ok_cb, false)
--send_large_msg(cb_extra.receiver, text)
end
--Begin supergroup locks
local function lock_group_links(msg, data, target)
if not is_momod(msg) then
return
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'yes' then
return 'الــــروابــــط🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_link'] = 'yes'
save_data(_config.moderation.data, data)
return 'تــــم✔️قــــفــــل🔒الــــروابــــط♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function unlock_group_links(msg, data, target)
if not is_momod(msg) then
return
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'no' then
return 'الــــروابــــط🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_link'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــم✔️فــــتــــح🔓الــــروابــــط♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function lock_group_spam(msg, data, target)
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "لــــلادمــنــيــه فــــقــط #لــــتــــلــح🐸🚬"
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'yes' then
return 'الــــــــكــــلايــــش🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_spam'] = 'yes'
save_data(_config.moderation.data, data)
return 'تــــم✔️قــــفــــل🔒الــــــــكــــلايــــش♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function unlock_group_spam(msg, data, target)
if not is_momod(msg) then
return
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'no' then
return 'الــــــــكــــلايــــش🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_spam'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــم✔️فــــتــــح🔓الــــــــكــــلايــــش♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function lock_group_flood(msg, data, target)
if not is_momod(msg) then
return
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'الــــــتكــــــرار🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'تــــم✔️قــــفــــل🔒الــــــتكــــــرار♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function unlock_group_flood(msg, data, target)
if not is_momod(msg) then
return
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'الــــتــكــرار بلــفــعــل✔️ مــفــــتــــوحــة🔓اهــــنــــا👾♨️\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــم✔️فــــتــــح🔓الــــــتكــــــرار♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'لــــــغــــة📝الــــعــــربــيــة📚🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'تــــم✔️قــــفــــل🔒لــــــغــــة📝الــــعــــربــيــة📚♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'لــــــغــــة📝الــــعــــربــيــة📚🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــم✔️فــــتــــح🔓لــــــغــــة📝الــــعــــربــيــة📚♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'الاضــــافــــه🚹🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'تــــم✔️قــــفــــل🔒الاضــــافــــه🚹♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'الاضــــافــــه🚹🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــم✔️فــــتــــح🔓الاضــــافــــه🚹♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function lock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'yes' then
return 'اضــــافــة جــــمــــاعــيــة🌚❤️🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_rtl'] = 'yes'
save_data(_config.moderation.data, data)
return 'تــــم✔️قــــفــــل🔒اضــــافــة جــــمــــاعــيــة🌚❤️♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function unlock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'no' then
return 'اضـــــافــة جــــمــــاعــيــة❤️🌚بلــــفــعــل✔️ مــفــــتــــوحــة🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_rtl'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــم ✔️فــــتــــح 🔓اضـــــافــة جــــمــــاعــيــة❤️🌚🏴\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function lock_group_sticker(msg, data, target)
if not is_momod(msg) then
return
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'yes' then
return 'الــــمــلصــقــات🔞🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_sticker'] = 'yes'
save_data(_config.moderation.data, data)
return 'تــــم✔️قــــفــــل🔒الــــمــلصــقــات🔞♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function unlock_group_sticker(msg, data, target)
if not is_momod(msg) then
return
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'no' then
return 'الــــمــلصــقــات🔞🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_sticker'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــم✔️فــــتــــح🔓الــــمــلصــقــات🔞♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function lock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'yes' then
return 'جــــهــات الاتــــصــال🌞⚡️🔊 بلــــفعــل✔️مــــقــفوله🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_contacts'] = 'yes'
save_data(_config.moderation.data, data)
return 'تــــم✔️قــــفــــل🔒جــــهــات الاتــــصــال🌞⚡️♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function unlock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'no' then
return 'جــــهــات الاتــــصــال🌞⚡️🔊 بلــــفعــل✔️مــــفــتوحه🔒هــــنــا👾\nبواسطه 🎈 ➖ (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_contacts'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــم✔️فــــتــــح🔓جــــهــات الاتــــصــال🌞⚡️♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function enable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_strict_lock = data[tostring(target)]['settings']['strict']
if group_strict_lock == 'yes' then
return 'طــــرد😌👞🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['strict'] = 'yes'
save_data(_config.moderation.data, data)
return 'تــــم✔️قــــفــــل🔒طــــرد😌👞♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function disable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_strict_lock = data[tostring(target)]['settings']['strict']
if group_strict_lock == 'no' then
return 'طــــرد😌👞🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['strict'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــم✔️فــــتــــح🔓طــــرد😌👞♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function lock_group_username(msg, data, target)
if not is_momod(msg) then
return
end
local group_username_lock = data[tostring(target)]['settings']['username']
if group_username_lock == 'yes' then
return 'الـــمـعــــرفــات🛐🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['username'] = 'yes'
save_data(_config.moderation.data, data)
return 'تــــم✔️قــــفــــل🔒الـــمـعــــرفــات🛐♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function unlock_group_username(msg, data, target)
if not is_momod(msg) then
return
end
local group_username_lock = data[tostring(target)]['settings']['username']
if group_username_lock == 'no' then
return 'الـــمـعــــرفــات🛐🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['username'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــم✔️فــــتــــح🔓الـــمـعــــرفــات🛐♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function lock_group_emoji(msg, data, target)
if not is_momod(msg) then
return
end
local group_emoji_lock = data[tostring(target)]['settings']['emoji']
if group_emoji_lock == 'yes' then
return 'الــســمايــلات⁉️🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['emoji'] = 'yes'
save_data(_config.moderation.data, data)
return 'تــــم✔️قــــفــــل🔒الــســمايــلات⁉️♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function unlock_group_emoji(msg, data, target)
if not is_momod(msg) then
return
end
local group_emoji_lock = data[tostring(target)]['settings']['emoji']
if group_emoji_lock == 'no' then
return 'الــســمايــلات⁉️🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['emoji'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــم✔️فــــتــــح🔓الــســمايــلات⁉️♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function lock_group_tag(msg, data, target)
if not is_momod(msg) then
return
end
local group_tag_lock = data[tostring(target)]['settings']['tag']
if group_tag_lock == 'yes' then
return 'تــــاك 😍🖖🏻🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['tag'] = 'yes'
save_data(_config.moderation.data, data)
return 'تــــم✔️قــــفــــل🔒تــــاك 😍🖖🏻♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function unlock_group_tag(msg, data, target)
if not is_momod(msg) then
return
end
local group_tag_lock = data[tostring(target)]['settings']['tag']
if group_tag_lock == 'no' then
return 'تــــاك 😍🖖🏻🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['tag'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــم✔️فــــتــــح🔓تــــاك 😍🖖🏻♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function lock_group_fwd(msg, data, target)
if not is_momod(msg) then
return
end
local group_fwd_lock = data[tostring(target)]['settings']['fwd']
if group_fwd_lock == 'yes' then
return 'بــلــــفــــعــــل✅تــــم🔘قــــــفــــل☑️🔒اعــــاده⏩الــــتــــوجــيــة⚠️💯\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['fwd'] = 'yes'
save_data(_config.moderation.data, data)
return 'تــــمـ✅تــــفـــعــيــل قــــفـــلـ☑️🔒الــــتـــوجــــيـــه💯🔰مـــــع الــــتحــذيــر⚠️\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function unlock_group_fwd(msg, data, target)
if not is_momod(msg) then
return
end
local group_fwd_lock = data[tostring(target)]['settings']['fwd']
if group_fwd_lock == 'no' then
return 'بــلــــفــــعــــل✅تــــم🔘فــــتــــح☑️🔓اعــــاده⏩الــــتــــوجــيــة🌀💯\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['fwd'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــمـ✅تــــفـــعــيــل فــــــتـــــحـ☑️🔓الــــتـــوجــــيـــه💯🔰و الــــتحــذيــر\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function lock_group_cmd(msg, data, target)
if not is_momod(msg) then
return
end
local group_cmd_lock = data[tostring(target)]['settings']['cmd']
if group_cmd_lock == 'yes' then
return 'الــــشــرحة❗️🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['cmd'] = 'yes'
save_data(_config.moderation.data, data)
return 'تــــم✔️قــــفــــل🔒الــــشــرحة❗️ ♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function unlock_group_cmd(msg, data, target)
if not is_momod(msg) then
return
end
local group_cmd_lock = data[tostring(target)]['settings']['cmd']
if group_cmd_lock == 'no' then
return 'الــــشــرحة❗️🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n' else
data[tostring(target)]['settings']['cmd'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــم✔️فــــتــــح🔓الــــشــرحة❗️ ♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function lock_group_unsupported(msg, data, target)
if not is_momod(msg) then
return
end
local group_unsupported_lock = data[tostring(target)]['settings']['unsupported']
if group_unsupported_lock == 'yes' then
return 'الانــــلاين❗️🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['unsupported'] = 'yes'
save_data(_config.moderation.data, data)
return 'تــــم✔️قــــفــــل🔒الانــــلايــــن🍹🌜 ♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function unlock_group_unsupported(msg, data, target)
if not is_momod(msg) then
return
end
local group_unsupported_lock = data[tostring(target)]['settings']['unsupported']
if group_unsupported_lock == 'no' then
return 'الانــــلايــــن🍹🌜🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['unsupported'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــم✔️فــــتــــح🔓الانــــلايــــن🍹🌜\nبواسطه 🐉 👁🗨 @'..msg.from.username..'\n'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'الــــبــــوتــــات🆎 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'تــــم✔️قــــفــــل🔒الــــبــــوتــــات🆎\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'الــــبــــوتــــات🆎 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــم✔️فــــتــــح🔓الـــــبــــوتــــات🆎\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function lock_group_join(msg, data, target)
if not is_momod(msg) then
return
end
local group_join_lock = data[tostring(target)]['settings']['join']
if group_join_lock == 'yes' then
return 'دخــــل🚶بلــرابــــط🌝✨💫🔊 بلــــفعــل✔️مــــقــفــول🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_join'] = 'yes'
save_data(_config.moderation.data, data)
return 'تــــم✔️قــــفــــل🔒دخــــل🚶بلــرابــــط🌝✨💫 ♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function unlock_group_join(msg, data, target)
if not is_momod(msg) then
return
end
local group_join_lock = data[tostring(target)]['settings']['lock_join']
if group_join_lock == 'no' then
return 'دخــــل🚶بلــرابــــط🌝✨💫🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_join'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــم✔️فــــتــــح🔓دخــــل🚶بلــرابــــط🌝✨💫 ♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function lock_group_tgservice(msg, data, target)
if not is_momod(msg) then
return
end
local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice']
if group_tgservice_lock == 'yes' then
return 'الاشــــعــارت🔔🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_tgservice'] = 'yes'
save_data(_config.moderation.data, data)
return 'تــــم✔️قــــفــــل🔒الاشــــعــارت🔔 ♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
local function unlock_group_tgservice(msg, data, target)
if not is_momod(msg) then
return
end
local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice']
if group_tgservice_lock == 'no' then
return 'الاشــــعــارت🔔🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
data[tostring(target)]['settings']['lock_tgservice'] = 'no'
save_data(_config.moderation.data, data)
return 'تــــم✔️فــــتــــح🔓الاشــــعــارت🔔 ♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
--End supergroup locks
--'Set supergroup rules' function
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'تــــــمــ☑️وضــــع الــــقــــوانــــيــن🙃عــــزيــــزي انَـَY̷ ̜̩O̷ ̜̩U̷ ̜̩ـَتَ 🤗'
end
--'Get supergroup rules' function
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'لــــمــ❌يــــتــم وضــــع الــــقــــوانــــيــن⁉️🚫مــــع احــــتــرمــي🙂 لــك'
end
local rules = data[tostring(msg.to.id)][data_cat]
local group_name = data[tostring(msg.to.id)]['settings']['set_name']
local rules = group_name..' قــــوانــــيــن⁉️🚫 الــــمــــجــــمــــوعــة🌐 \n\n'..rules:gsub("/n", " ")
return rules
end
--Set supergroup to public or not public function
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "لــــلادمــنــيــه فــــقــط 🌀"
end
local group_public_lock = data[tostring(target)]['settings']['public']
local long_id = data[tostring(target)]['long_id']
if not long_id then
data[tostring(target)]['long_id'] = msg.to.peer_id
save_data(_config.moderation.data, data)
end
if group_public_lock == 'yes' then
return 'الــــمــجــمــوعــة بلــــفــعــل💯عــامــة\nبواسطه 🐉 👁🗨 @'..msg.from.username..'\n'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'الــــمــــجــــمــــوعــة اصــبــحــت عــامــة💯\nبواسطه 🐉 👁🗨 @'..msg.from.username..'\n'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_public_lock = data[tostring(target)]['settings']['public']
local long_id = data[tostring(target)]['long_id']
if not long_id then
data[tostring(target)]['long_id'] = msg.to.peer_id
save_data(_config.moderation.data, data)
end
if group_public_lock == 'no' then
return 'الــــمــجــمــوعــة بلــــفــعــل لــيســت💯عــامــة\nبواسطه 🐉 👁🗨 @'..msg.from.username..'\n'
else
data[tostring(target)]['settings']['public'] = 'no'
data[tostring(target)]['long_id'] = msg.to.long_id
save_data(_config.moderation.data, data)
return 'الــــمــــجــــمــــوعــة لــيســت عــامــة💯\nبواسطه 🐉 👁🗨 @'..msg.from.username..'\n'
end
end
--Show supergroup settings; function
function show_supergroup_settingsmod(msg, target)
if not is_momod(msg) then
return
end
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(target)]['settings']['lock_bots'] then
bots_protection = data[tostring(target)]['settings']['lock_bots']
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['public'] then
data[tostring(target)]['settings']['public'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_rtl'] then
data[tostring(target)]['settings']['lock_rtl'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_tgservice'] then
data[tostring(target)]['settings']['lock_tgservice'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['tag'] then
data[tostring(target)]['settings']['tag'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['emoji'] then
data[tostring(target)]['settings']['emoji'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['english'] then
data[tostring(target)]['settings']['english'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['fwd'] then
data[tostring(target)]['settings']['fwd'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['reply'] then
data[tostring(target)]['settings']['reply'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['join'] then
data[tostring(target)]['settings']['join'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['fosh'] then
data[tostring(target)]['settings']['fosh'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['username'] then
data[tostring(target)]['settings']['username'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['media'] then
data[tostring(target)]['settings']['media'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['leave'] then
data[tostring(target)]['settings']['leave'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_member'] then
data[tostring(target)]['settings']['lock_member'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['all'] then
data[tostring(target)]['settings']['all'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['operator'] then
data[tostring(target)]['settings']['operator'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['etehad'] then
data[tostring(target)]['settings']['etehad'] = 'no'
end
end
local gp_type = data[tostring(msg.to.id)]['group_type']
local settings = data[tostring(target)]['settings']
local text = "🔺----------------------🔺\nاعدادات المجموعه :-\n💠- اسم المجموعه : "..msg.to.title.."\n🔺----------------------🔺\n💠- الروابط : "..settings.lock_link.."\n💠- جهات الاتصال : "..settings.lock_contacts.."\n💠- التكرار : "..settings.flood.."\n💠- عدد التكرار : "..NUM_MSG_MAX.."\n💠- الاسبام : "..settings.lock_spam.."\n💠- العربيه : "..settings.lock_arabic.."\n💠- الانكليزيه : "..settings.english.."\n💠- الاضافه : "..settings.lock_member.."\n \n💠- الرتل : "..settings.lock_rtl.."\n💠- اشعارات الدخول : "..settings.lock_tgservice.."\n💠- الملصقات : "..settings.lock_sticker.."\n💠- التاك : "..settings.tag.."\n💠- الاسمايلات : "..settings.emoji.."\n💠- البوتات : "..bots_protection.."\n💠- اعاده توجيه : "..settings.fwd.."\n💠- الدخول : "..settings.join.."\n💠- المعرف : "..settings.username.."\n🔺----------------------🔺\n @lTSHAKEl_CH"
return text
end
local function promote_admin(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
local member_tag_username = string.gsub(member_username, '@', '(at)')
if not data[group] then
return
end
if data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_username..' هــــو بلــفــعــل ضــــمــن ادمــنــيــة☹️🖕🏿ضمن الادمنيه')
end
data[group]['moderators'][tostring(user_id)] = member_tag_username
save_data(_config.moderation.data, data)
end
local function demote_admin(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
if not data[group] then
return
end
if not data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_tag_username..'هــــو بلــفــعــل ضــــمــن الاعــضــاء☹️🖕🏿بالفعل ضمن الاعضاء')
end
data[group]['moderators'][tostring(user_id)] = nil
save_data(_config.moderation.data, data)
end
local function promote2(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
local member_tag_username = string.gsub(member_username, '@', '(at)')
if not data[group] then
return send_large_msg(receiver, 'الــــمـــجــــمـــوعــة لـــيــســت فـــعــالــة😸✌🏿')
end
if data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_username..'هــــو بلــفــعــل ضــــمــن ادمــنــيــة☹️🖕🏿')
end
data[group]['moderators'][tostring(user_id)] = member_tag_username
save_data(_config.moderation.data, data)
send_large_msg(receiver, member_username..'تــــــم🙀رفــــعــك😮ادمــــن😻🙊يــعــني حــــلــو مــالــ الــمــديــر😍الــك ونــــه😝🎤')
end
local function demote2(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
if not data[group] then
return ' الــــمـــجــــمـــوعــة لـــيــســت فـــعــالــة😸✌🏿 '
end
if not data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_username.. 'بلــفــعــل تــــمــ🌞🍾تــــنــزيــله☀️🌜 مـــِْن ادمــنــة😿')
end
data[group]['moderators'][tostring(user_id)] = nil
save_data(_config.moderation.data, data)
send_large_msg(receiver, member_username.. 'تــــمــ🌞🍾تــــنــزيــلك☀️🌜 مـــِْن ادمــنــة😿لانك مــكــنســه😹🌚')
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return 'الــــمـــجــــمـــوعــة لـــيــســت فـــعــالــة😸✌🏿'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then
return 'لا يوجد ادمنيه 🎈 '
end
local i = 1
local message = '\n🎈 قائمه الادمنيه ️ ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
-- Start by reply actions
function get_message_callback(extra, success, result)
local get_cmd = extra.get_cmd
local msg = extra.msg
local data = load_data(_config.moderation.data)
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
if get_cmd == "ايدي" and not result.action then
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for: ["..result.from.peer_id.."]")
id1 = send_large_msg(channel, result.from.peer_id)
elseif get_cmd == 'ايدي' and result.action then
local action = result.action.type
if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then
if result.action.user then
user_id = result.action.user.peer_id
else
user_id = result.peer_id
end
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id by service msg for: ["..user_id.."]")
id1 = send_large_msg(channel, user_id)
end
elseif get_cmd == "idfrom" then
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for msg fwd from: ["..result.fwd_from.peer_id.."]")
id2 = send_large_msg(channel, result.fwd_from.peer_id)
elseif get_cmd == 'channel_block' and not result.action then
local member_id = result.from.peer_id
local channel_id = result.to.peer_id
if member_id == msg.from.id then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then
return send_large_msg("channel#id"..channel_id, "لا تــســتــطــيــع طــرد ادمـن او الــمديــر😼👊🏿")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "لا تــســتــطــيــع طــــرد الاداري😼👊🏿")
end
--savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply")
kick_user(member_id, channel_id)
elseif get_cmd == 'channel_block' and result.action and result.action.type == 'chat_add_user' then
local user_id = result.action.user.peer_id
local channel_id = result.to.peer_id
if member_id == msg.from.id then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then
return send_large_msg("channel#id"..channel_id, "لا تــســتــطــيــع طــرد ادمـن او الــمديــر😼👊🏿")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "لا تــســتــطــيــع طــــرد الاداري😼👊🏿")
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply to sev. msg.")
kick_user(user_id, channel_id)
elseif get_cmd == "مسح" then
delete_msg(result.id, ok_cb, false)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted a message by reply")
elseif get_cmd == "رفع اداري" then
local user_id = result.from.peer_id
local channel_id = "channel#id"..result.to.peer_id
channel_set_admin(channel_id, "user#id"..user_id, ok_cb, false)
if result.from.username then
text = " @"..result.from.username.." تــــــم🙀رفــــعــك😮اداريــ😎يــعــني ضــلــع الــمــديــر😍الــك ونــــه😝🎤 "
else
text = " [ "..user_id.." ] تــــــم🙀رفــــعــك😮اداريــ😎يــعــني ضــلــع الــمــديــر😍الــك ونــــه😝🎤 "
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..user_id.."] as admin by reply")
send_large_msg(channel_id, text)
elseif get_cmd == "تنزيل اداري" then
local user_id = result.from.peer_id
local channel_id = "channel#id"..result.to.peer_id
if is_admin2(result.from.peer_id) then
return send_large_msg(channel_id, " لا تــســتــطــيــع طــــرد الاداري😼👊🏿")
end
channel_demote(channel_id, "user#id"..user_id, ok_cb, false)
if result.from.username then
text = " @"..result.from.username.. " تــــمــ☑️تــــنــــزيــلــك مــــن الادارة😿 "
else
text = " [ "..user_id.." ] تــــمــ☑️تــــنــــزيــلــك مــــن الادارة😿"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted: ["..user_id.."] from admin by reply")
send_large_msg(channel_id, text)
elseif get_cmd == "رفع المدير" then
local group_owner = data[tostring(result.to.peer_id)]['set_owner']
if group_owner then
local channel_id = 'channel#id'..result.to.peer_id
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(channel_id, user, ok_cb, false)
end
local user_id = "user#id"..result.from.peer_id
channel_set_admin(channel_id, user_id, ok_cb, false)
data[tostring(result.to.peer_id)]['set_owner'] = tostring(result.from.peer_id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..result.from.peer_id.."] as owner by reply")
if result.from.username then
text = " @"..result.from.username.." تــــــم🙀رفــــعــك😮مــــديــر😎خــالــي😍الــك ونــــه😝🎤 "
else
text = " @"..result.from.username.." تــــــم🙀رفــــعــك😮مــــديــر😎خــالــي😍الــك ونــــه😝🎤 "
end
send_large_msg(channel_id, text)
end
elseif get_cmd == "رفع ادمن" then
local receiver = result.to.peer_id
local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '')
local member_name = full_name:gsub("", "")
local member_username = member_name:gsub("_", " ")
if result.from.username then
member_username = '@'.. result.from.username
end
local member_id = result.from.peer_id
if result.to.peer_type == 'channel' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted mod: @"..member_username.."["..result.from.peer_id.."] by reply")
promote2("channel#id"..result.to.peer_id, member_username, member_id)
--channel_set_mod(channel_id, user, ok_cb, false)
end
elseif get_cmd == "تنزيل ادمن" then
local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '')
local member_name = full_name:gsub("", "")
local member_username = member_name:gsub("_", " ")
if result.from.username then
member_username = '@'.. result.from.username
end
local member_id = result.from.peer_id
--local user = "user#id"..result.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] تنزيل ادمن: @"..member_username.."["..result.from.peer_id.."] by reply")
demote2("channel#id"..result.to.peer_id, member_username, member_id)
--channel_demote(channel_id, user, ok_cb, false)
elseif get_cmd == 'mute_user' then
if result.service then
local action = result.action.type
if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then
if result.action.user then
user_id = result.action.user.peer_id
end
end
if action == 'chat_add_user_link' then
if result.from then
user_id = result.from.peer_id
end
end
else
user_id = result.from.peer_id
end
local receiver = extra.receiver
local chat_id = msg.to.id
print(user_id)
print(chat_id)
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] تــــــاج👑مــــــخي🐲انــــشــــال😽😻كــــــــتــــم👻مــــــنــك💋 ")
elseif is_momod(msg) then
mute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] تــــــم😎كــــــتــــمــــك😶مــــن وره ســــولــــفــك🤗يــــاخــرا💩")
end
end
end
-- End by reply actions
--By ID actions
local function cb_user_info(extra, success, result)
local receiver = extra.receiver
local user_id = result.peer_id
local get_cmd = extra.get_cmd
local data = load_data(_config.moderation.data)
--[[if get_cmd == "setadmin" then
local user_id = "user#id"..result.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been set as an admin"
else
text = "[ "..result.peer_id.." ] has been set as an admin"
end
send_large_msg(receiver, text)]]
if get_cmd == "تنزيل اداري" then
if is_admin2(result.peer_id) then
return send_large_msg(receiver, "لا تــســتــطــيــع تــنــزيــل الاداري😼👊🏿")
end
local user_id = "user#id"..result.peer_id
channel_demote(receiver, user_id, ok_cb, false)
if result.username then
text = " @"..result.username.." تــــمــ☑️تــــنــــزيــلــك مــــن الادارة😿 "
send_large_msg(receiver, text)
else
text = " [ "..result.peer_id.." ] تــــمــ☑️تــــنــــزيــلــك مــــن الادارة😿 "
send_large_msg(receiver, text)
end
elseif get_cmd == "رفع ادمن" then
if result.username then
member_username = "@"..result.username
else
member_username = string.gsub(result.print_name, '_', ' ')
end
promote2(receiver, member_username, user_id)
elseif get_cmd == "تنزيل ادمن" then
if result.username then
member_username = "@"..result.username
else
member_username = string.gsub(result.print_name, '_', ' ')
end
demote2(receiver, member_username, user_id)
end
end
-- Begin resolve username actions
local function callbackres(extra, success, result)
local member_id = result.peer_id
local member_username = "@"..result.username
local get_cmd = extra.get_cmd
if get_cmd == "الايدي" then
local user = result.peer_id
local name = string.gsub(result.print_name, "_", " ")
local channel = 'channel#id'..extra.channelid
send_large_msg(channel, user..'\n'..name)
return user
elseif get_cmd == "ايدي" then
local user = result.peer_id
local channel = 'channel#id'..extra.channelid
send_large_msg(channel, user)
return user
elseif get_cmd == "invite" then
local receiver = extra.channel
local user_id = "user#id"..result.peer_id
channel_invite(receiver, user_id, ok_cb, false)
--[[elseif get_cmd == "channel_block" then
local user_id = result.peer_id
local channel_id = extra.channelid
local sender = extra.sender
if member_id == sender then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(sender) then
return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "You can't kick other admins")
end
kick_user(user_id, channel_id)
elseif get_cmd == "setadmin" then
local user_id = "user#id"..result.peer_id
local channel_id = extra.channel
channel_set_admin(channel_id, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been set as an admin"
send_large_msg(channel_id, text)
else
text = "@"..result.peer_id.." has been set as an admin"
send_large_msg(channel_id, text)
end
elseif get_cmd == "setowner" then
local receiver = extra.channel
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = extra.from_id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
local user = "user#id"..group_owner
if not is_admin2(group_owner) and not is_support(group_owner) then
channel_demote(receiver, user, ok_cb, false)
end
local user_id = "user#id"..result.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
data[tostring(channel)]['set_owner'] = tostring(result.peer_id)
save_data(_config.moderation.data, data)
savelog(channel, name_log.." ["..from_id.."] set ["..result.peer_id.."] as owner by username")
if result.username then
text = member_username.." [ "..result.peer_id.." ] added as owner"
else
text = "[ "..result.peer_id.." ] added as owner"
end
send_large_msg(receiver, text)
end]]
elseif get_cmd == "رفع ادمن" then
local receiver = extra.channel
local user_id = result.peer_id
--local user = "user#id"..result.peer_id
promote2(receiver, member_username, user_id)
--channel_set_mod(receiver, user, ok_cb, false)
elseif get_cmd == "تنزيل ادمن" then
local receiver = extra.channel
local user_id = result.peer_id
local user = "user#id"..result.peer_id
demote2(receiver, member_username, user_id)
elseif get_cmd == "تنزيل اداري" then
local user_id = "user#id"..result.peer_id
local channel_id = extra.channel
if is_admin2(result.peer_id) then
return send_large_msg(channel_id, " لا تــســتــطــيــع تــنــزيــل الاداري😼👊🏿 ")
end
channel_demote(channel_id, user_id, ok_cb, false)
if result.username then
text = " @"..result.username.." تــــمــ☑️تــــنــــزيــلــك مــــن الادارة😿 "
send_large_msg(channel_id, text)
else
text = " @"..result.peer_id.." تــــمــ☑️تــــنــــزيــلــك مــــن الادارة😿 "
send_large_msg(channel_id, text)
end
local receiver = extra.channel
local user_id = result.peer_id
demote_admin(receiver, member_username, user_id)
elseif get_cmd == 'mute_user' then
local user_id = result.peer_id
local receiver = extra.receiver
local chat_id = string.gsub(receiver, 'channel#id', '')
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] تــــــاج👑مــــــخي🐲انــــشــــال😽😻كــــــــتــــم👻مــــــنــك💋")
elseif is_momod(extra.msg) then
mute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] تــــــم😎كــــــتــــمــــك😶مــــن وره ســــولــــفــك🤗يــــاخــرا💩")
end
end
end
--End resolve username actions
--Begin non-channel_invite username actions
local function in_channel_cb(cb_extra, success, result)
local get_cmd = cb_extra.get_cmd
local receiver = cb_extra.receiver
local msg = cb_extra.msg
local data = load_data(_config.moderation.data)
local print_name = user_print_name(cb_extra.msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
local member = cb_extra.username
local memberid = cb_extra.user_id
if member then
text = 'لايوجد عضو @'..member..' في هذه المجموعه.'
else
text = 'لايوجد عضو ['..memberid..'] في هذه المجموعه.'
end
if get_cmd == "channel_block" then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local user_id = v.peer_id
local channel_id = cb_extra.msg.to.id
local sender = cb_extra.msg.from.id
if user_id == sender then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(user_id, channel_id) and not is_admin2(sender) then
return send_large_msg("channel#id"..channel_id, "لا تــســتــطــيــع طــــرد الاداري😼👊🏿")
end
if is_admin2(user_id) then
return send_large_msg("channel#id"..channel_id, "لا تــســتــطــيــع طــرد ادمـن او الــمديــر😼👊🏿")
end
if v.username then
text = ""
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..v.username.." ["..v.peer_id.."]")
else
text = ""
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..v.peer_id.."]")
end
kick_user(user_id, channel_id)
return
end
end
elseif get_cmd == "رفع اداري" then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local user_id = "user#id"..v.peer_id
local channel_id = "channel#id"..cb_extra.msg.to.id
channel_set_admin(channel_id, user_id, ok_cb, false)
if v.username then
text = " @"..v.username.." ["..v.peer_id.."] تــــــم🙀رفــــعــك😮اداريــ😎يــعــني ضــلــع الــمــديــر😍الــك ونــــه😝🎤 "
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..v.username.." ["..v.peer_id.."]")
else
text = " ["..v.peer_id.."] تــــــم🙀رفــــعــك😮اداريــ😎يــعــني ضــلــع الــمــديــر😍الــك ونــــه😝🎤 "
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin "..v.peer_id)
end
if v.username then
member_username = "@"..v.username
else
member_username = string.gsub(v.print_name, '_', ' ')
end
local receiver = channel_id
local user_id = v.peer_id
promote_admin(receiver, member_username, user_id)
end
send_large_msg(channel_id, text)
return
end
elseif get_cmd == 'رفع المدير' then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = cb_extra.msg.from.id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(receiver, user, ok_cb, false)
end
local user_id = "user#id"..v.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
data[tostring(channel)]['set_owner'] = tostring(v.peer_id)
save_data(_config.moderation.data, data)
savelog(channel, name_log.."["..from_id.."] set ["..v.peer_id.."] as owner by username")
if result.username then
text = member_username.." @"..v.username.." تــــــم🙀رفــــعــك😮مــــديــر😎خــالــي😍الــك ونــــه😝🎤 "
else
text = " @"..v.username.." تــــــم🙀رفــــعــك😮مــــديــر😎خــالــي😍الــك ونــــه😝🎤 "
end
end
elseif memberid and vusername ~= member and vpeer_id ~= memberid then
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = cb_extra.msg.from.id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(receiver, user, ok_cb, false)
end
data[tostring(channel)]['set_owner'] = tostring(memberid)
save_data(_config.moderation.data, data)
savelog(channel, name_log.."["..from_id.."] set ["..memberid.."] as owner by username")
text = " ["..memberid.."] تــــــم🙀رفــــعــك😮مــــديــر😎خــالــي😍الــك ونــــه😝🎤 "
end
end
end
end
send_large_msg(receiver, text)
end
--End non-channel_invite username actions
--'Set supergroup photo' function
local function set_supergroup_photo(msg, success, result)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return
end
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/channel_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
channel_set_photo(receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'تــــمــ✅حــــفــــظ الــــصــــورة🎠', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
--Run function
local function run(msg, matches)
if msg.to.type == 'chat' then
if matches[1] == 'ترقيه سوبر' then
if not is_admin1(msg) then
return
end
local receiver = get_receiver(msg)
chat_upgrade(receiver, ok_cb, false)
end
elseif msg.to.type == 'channel'then
if matches[1] == 'ترقيه سوبر' then
if not is_admin1(msg) then
return
end
return "الــــمــــجــــمــــوعــة🚀خــــارقــة بلــفــعــل😻🙈"
end
end
if msg.to.type == 'channel' then
local support_id = msg.from.id
local receiver = get_receiver(msg)
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
local data = load_data(_config.moderation.data)
if matches[1] == 'تفعيل' and not matches[2] then
if not is_admin1(msg) and not is_support(support_id) then
return
end
if is_super_group(msg) then
return reply_msg(msg.id, 'الــــمــــجــــمــــوعــة💯 بلــفــعــل☢مــــفــعــلة😻🙈 ', ok_cb, false)
end
print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") added")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added SuperGroup")
superadd(msg)
set_mutes(msg.to.id)
channel_set_admin(receiver, 'user#id'..msg.from.id, ok_cb, false)
end
if matches[1] == 'تعطيل' and is_admin1(msg) and not matches[2] then if not is_super_group(msg) then
return reply_msg(msg.id, 'الــــمــــجــــمــــوعــة⚠️ بلــفــعــل☢مــــعــــطــلــة❌🚫 ', ok_cb, false)
end
print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed")
superrem(msg)
rem_mutes(msg.to.id)
end
if not data[tostring(msg.to.id)] then
return
end
if matches[1] == "معلومات المجموعه" then
if not is_owner(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup info")
channel_info(receiver, callback_info, {receiver = receiver, msg = msg})
end
if matches[1] == "الاداريين" then
if not is_owner(msg) and not is_support(msg.from.id) then
return
end
member_type = 'قــــامــة الادريــــن🔱🔆'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup Admins list")
admins = channel_get_admins(receiver,callback, {receiver = receiver, msg = msg, member_type = member_type})
end
if matches[1] == "مدير المجموعه" then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return " لا يــــوجــــد مــــديــــر🙀فــي الــــمــــجــــمــــوعــة😿"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "الــــمــديــر الــــمــــجــــمــــوعــة عــــزيــــزيــ😻🌸 ["..group_owner..']'
end
if matches[1] == "الادمنيه" then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
-- channel_get_admins(receiver,callback, {receiver = receiver})
end
if matches[1] == "كشف بوت" and is_momod(msg) then
member_type = 'تــــمــ✅كــــشــف♻️الــــبــــوتــات🅱فــــي الــــمــــجــــمــــوعــة😼🖕🏿'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup bots list")
channel_get_bots(receiver, callback, {receiver = receiver, msg = msg, member_type = member_type})
end
if matches[1] == "ايدي الاعضاء" and not matches[2] and is_momod(msg) then
local user_id = msg.from.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup users list")
channel_get_users(receiver, callback_who, {receiver = receiver})
end
if matches[1] == "kicked" and is_momod(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested Kicked users list")
channel_get_kicked(receiver, callback_kicked, {receiver = receiver})
end
if matches[1] == 'مسح' and is_momod(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'مسح',
msg = msg
}
delete_msg(msg.id, ok_cb, false)
get_message(msg.reply_id, get_message_callback, cbreply_extra)
end
end
if matches[1] == 'بلوك' and is_momod(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'channel_block',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'بلوك' and string.match(matches[2], '^%d+$') then
--[[local user_id = matches[2]
local channel_id = msg.to.id
if is_momod2(user_id, channel_id) and not is_admin2(user_id) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: [ user#id"..user_id.." ]")
kick_user(user_id, channel_id)]]
local get_cmd = 'channel_block'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif msg.text:match("@[%a%d]") then
--[[local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'channel_block',
sender = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..username)
resolve_username(username, callbackres, cbres_extra)]]
local get_cmd = 'channel_block'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'ايدي' then
if type(msg.reply_id) ~= "nil" and is_momod(msg) and not matches[2] then
local cbreply_extra = {
get_cmd = 'ايدي',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif type(msg.reply_id) ~= "nil" and matches[2] == "from" and is_momod(msg) then
local cbreply_extra = {
get_cmd = 'idfrom',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif msg.text:match("@[%a%d]") then
local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'ايدي'
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested ID for: @"..username)
resolve_username(username, callbackres, cbres_extra)
else
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup ID")
return "ايــــديــ🆔الــــمــــجــــمــــوعــة💢"..string.gsub(msg.to.print_name, "_", " ")..": "..msg.to.id
end
end
if matches[1] == 'دعبلني' then
if msg.to.type == 'channel' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] left via kickme")
channel_kick("channel#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if matches[1] == 'تغير الرابط' and is_momod(msg)then
local function callback_link (extra , success, result)
local receiver = get_receiver(msg)
if success == 0 then
send_large_msg(receiver, 'لا يمكنك تغيير الرابط \nالمجموعه ليست من صنع البوت')
data[tostring(msg.to.id)]['settings']['set_link'] = nil
save_data(_config.moderation.data, data)
else
send_large_msg(receiver, "تــــمــ☑️حــــفــــظ الــــرابــــط🔴⚫️")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to create a new SuperGroup link")
export_channel_link(receiver, callback_link, false)
end
if matches[1] == 'ضع رابط' and is_owner(msg) then
data[tostring(msg.to.id)]['settings']['set_link'] = 'waiting'
save_data(_config.moderation.data, data)
return 'قــــمــ🔃بــــرســال الــــرابــــط📣'
end
if msg.text then
if msg.text:match("^(https://telegram.me/joinchat/%S+)$") and data[tostring(msg.to.id)]['settings']['set_link'] == 'waiting' and is_owner(msg) then
data[tostring(msg.to.id)]['settings']['set_link'] = msg.text
save_data(_config.moderation.data, data)
return "تــــمــ☑️حــــفــــظ الــــرابــــط🔴⚫️"
end
end
if matches[1] == 'الرابط' then
if not is_momod(msg) then
return
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "يرجى ارسال [تغير الرابط] لانشاء رابط المجموعه"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "رابــــــط🔴⚫️الــــمــــجــــمــــوعــة💢 :\n"..group_link
end
if matches[1] == "invite" and is_sudo(msg) then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = "invite"
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] invited @"..username)
resolve_username(username, callbackres, cbres_extra)
end
if matches[1] == 'الايدي' and is_owner(msg) then
local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'الايدي'
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] resolved username: @"..username)
resolve_username(username, callbackres, cbres_extra)
end
--[[if matches[1] == 'kick' and is_momod(msg) then
local receiver = channel..matches[3]
local user = "user#id"..matches[2]
chaannel_kick(receiver, user, ok_cb, false)
end]]
if matches[1] == 'رفع اداري' then
if not is_support(msg.from.id) and not is_owner(msg) then
return
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'رفع اداري',
msg = msg
}
setadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'رفع اداري' and string.match(matches[2], '^%d+$') then
--[[] local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'setadmin'
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})]]
local get_cmd = 'رفع اداري'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif matches[1] == 'رفع اداري' and not string.match(matches[2], '^%d+$') then
--[[local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'setadmin'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..username)
resolve_username(username, callbackres, cbres_extra)]]
local get_cmd = 'رفع اداري'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'تنزيل اداري' then
if not is_support(msg.from.id) and not is_owner(msg) then
return
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'تنزيل اداري',
msg = msg
}
demoteadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'تنزيل اداري' and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'تنزيل اداري'
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif matches[1] == 'تنزيل اداري' and not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'تنزيل اداري'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted admin @"..username)
resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == 'رفع المدير' and is_owner(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'رفع المدير',
msg = msg
}
setowner = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'رفع المدير' and string.match(matches[2], '^%d+$') then
--[[ local group_owner = data[tostring(msg.to.id)]['set_owner']
if group_owner then
local receiver = get_receiver(msg)
local user_id = "user#id"..group_owner
if not is_admin2(group_owner) and not is_support(group_owner) then
channel_demote(receiver, user_id, ok_cb, false)
end
local user = "user#id"..matches[2]
channel_set_admin(receiver, user, ok_cb, false)
data[tostring(msg.to.id)]['set_owner'] = tostring(matches[2])
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = "[ "..matches[2].." ] added as owner"
return text
end]]
local get_cmd = 'رفع المدير'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif matches[1] == 'رفع المدير' and not string.match(matches[2], '^%d+$') then
local get_cmd = 'رفع المدير'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'رفع ادمن' then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "لــــدامــنــيــة🅰فــــقــط"
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'رفع ادمن',
msg = msg
}
promote = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'رفع ادمن' and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'رفع ادمن'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted user#id"..matches[2])
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif matches[1] == 'رفع ادمن' and not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'رفع ادمن',
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @"..username)
return resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == 'mp' and is_sudo(msg) then
channel = get_receiver(msg)
user_id = 'user#id'..matches[2]
channel_set_mod(channel, user_id, ok_cb, false)
return "ok"
end
if matches[1] == 'md' and is_sudo(msg) then
channel = get_receiver(msg)
user_id = 'user#id'..matches[2]
channel_demote(channel, user_id, ok_cb, false)
return "ok"
end
if matches[1] == 'تنزيل ادمن' then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "لــــدامــنــيــة🅰فــــقــط"
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'تنزيل ادمن',
msg = msg
}
demote = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'تنزيل ادمن' and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'تنزيل ادمن'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted user#id"..matches[2])
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'تنزيل ادمن'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @"..username)
return resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == "ضع اسم" and is_momod(msg) then
local receiver = get_receiver(msg)
local set_name = string.gsub(matches[2], '_', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..matches[2])
rename_channel(receiver, set_name, ok_cb, false)
end
if msg.service and msg.action.type == 'chat_rename' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..msg.to.title)
data[tostring(msg.to.id)]['settings']['set_name'] = msg.to.title
save_data(_config.moderation.data, data)
end
if matches[1] == "ضع وصف" and is_momod(msg) then
local receiver = get_receiver(msg)
local about_text = matches[2]
local data_cat = 'description'
local target = msg.to.id
data[tostring(target)][data_cat] = about_text
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup description to: "..about_text)
channel_set_about(receiver, about_text, ok_cb, false)
return "تــــمــ✔️تــــعــيــن وصــف الــــمــجــمــوعــه🐉\n\n"
end
if matches[1] == "ضع معرف" and is_admin1(msg) then
local function ok_username_cb (extra, success, result)
local receiver = extra.receiver
if success == 1 then
send_large_msg(receiver, "تــــمــ✔️حــــــفــــظ ➰الــــمــــعــــرف⤴️\n\n")
elseif success == 0 then
send_large_msg(receiver, "فــــشــل❌⁉️حــــــفــــظ‼️الــــمــــعــــرف⛔️\nUsername may already be taken.\n\nNote: Username can use a-z, 0-9 and underscores.\nMinimum length is 5 characters.")
end
end
local username = string.gsub(matches[2], '@', '')
channel_set_username(receiver, username, ok_username_cb, {receiver=receiver})
end
if matches[1] == 'ضع قوانين' and is_momod(msg) then
rules = matches[2]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[2].."]")
return set_rulesmod(msg, data, target)
end
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_momod(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set new SuperGroup photo")
load_photo(msg.id, set_supergroup_photo, msg)
return
end
end
if matches[1] == 'ضع صوره' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] started setting new SuperGroup photo")
return 'قــــم بــارســال♻️صــــورة🎠 الان😼👋'
end
if matches[1] == 'مسح' then
if not is_momod(msg) then
return
end
if not is_momod(msg) then
return 'فــــقــــط😎✋لــلــمــديــر😎🖖🏻'
end
if matches[2] == 'الادمنيه' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then
return "عــــذران لايــــوجد ❌⁉️ادمــــنــيــة⚠️‼️"
end
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
return 'تــــــمــ☑️مــــســح قــــامــة✅الادمــــنــيــة♻️💯'
end
if matches[2] == 'القوانين' then
local data_cat = 'rules'
if data[tostring(msg.to.id)][data_cat] == nil then
return "عــــذران لايــــوجد ❌⁉️قــــوانــيــن فــي🙁الــــمــــجــــمــــوعــة🌐لــــيــتــم🆕مــســح🗑"
end
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
return 'تــــــمــ☑️مــــســح 🗑قــــوانــــيــن♻️💯الــــمــــجــــمــــوعــة🌐'
end
if matches[2] == 'الوصف' then
local receiver = get_receiver(msg)
local about_text = ''
local data_cat = 'description'
if data[tostring(msg.to.id)][data_cat] == nil then
return 'عــــذران لايــــوجد ❌⁉️وصــــف فــي🙁الــــمــــجــــمــــوعــة🌐لــــيــتــم🆕مــســح🗑'
end
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
channel_set_about(receiver, about_text, ok_cb, false)
return "تــــمــ☑️مــســح🗑وصــــف📋"
end
if matches[2] == 'المكتومين' then
chat_id = msg.to.id
local hash = 'mute_user:'..chat_id
redis:del(hash)
return "تــــمــ☑️مــســح🗑قــائــمــة📋 الــــمــكــتــومــيــن🤗"
end
if matches[2] == 'المعرف' and is_admin1(msg) then
local function ok_username_cb (extra, success, result)
local receiver = extra.receiver
if success == 1 then
send_large_msg(receiver, "مـــســح🗑حــــــفــــظ ➰الــــمــــعــــرف⤴️")
elseif success == 0 then
send_large_msg(receiver, "فــــشـــل⚠️ مـــســح🗑الــــمــــعــــرف⤴️")
end
end
local username = ""
channel_set_username(receiver, username, ok_username_cb, {receiver=receiver})
end
end
if matches[1] == 'قفل' and is_momod(msg) then
local target = msg.to.id
if matches[2] == 'الروابط' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ")
return lock_group_links(msg, data, target)
end
if matches[2] == 'الكلايش' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked spam ")
return lock_group_spam(msg, data, target)
end
if matches[2] == 'التكرار' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_flood(msg, data, target)
end
if matches[2] == 'العربيه' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'الاضافه' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2]:lower() == 'الاضافه الجماعيه' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked rtl chars. in names")
return lock_group_rtl(msg, data, target)
end
if matches[2] == 'الملصقات' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker posting")
return lock_group_sticker(msg, data, target)
end
if matches[2] == 'جهات الاتصال' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked contact posting")
return lock_group_contacts(msg, data, target)
end
if matches[2] == 'الطرد' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked enabled strict settings")
return enable_strict_rules(msg, data, target)
end
if matches[2] == 'المعرف' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked username")
return lock_group_username(msg, data, target)
end
if matches[2] == 'السمايل' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked emoji")
return lock_group_emoji(msg, data, target)
end
if matches[2] == 'التاك' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked tag ")
return lock_group_tag(msg, data, target)
end
if matches[2] == 'اعاده توجيه' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked fwd")
return lock_group_fwd(msg, data, target)
end
if matches[2] == 'الشارحه' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked cmd")
return lock_group_cmd(msg, data, target)
end
if matches[2] == 'الانلاين' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked unsupported")
return lock_group_unsupported(msg, data, target)
end
if matches[2] == 'البوتات' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'الدخول بالرابط' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked join ")
return lock_group_join(msg, data, target)
end
if matches[2] == 'الاشعارات' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked Tgservice Actions")
return lock_group_tgservice(msg, data, target)
end
end
if matches[1] == 'فتح' and is_momod(msg) then
local target = msg.to.id
if matches[2] == 'الروابط' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting")
return unlock_group_links(msg, data, target)
end
if matches[2] == 'الكلايش' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked spam")
return unlock_group_spam(msg, data, target)
end
if matches[2] == 'التكرار' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood")
return unlock_group_flood(msg, data, target)
end
if matches[2] == 'العربيه' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked Arabic")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'الاضافه' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2]:lower() == 'الاضافه الجماعيه' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked RTL chars. in names")
return unlock_group_rtl(msg, data, target)
end
if matches[2] == 'الملصقات' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker posting")
return unlock_group_sticker(msg, data, target)
end
if matches[2] == 'جهات الاتصال' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked contact posting")
return unlock_group_contacts(msg, data, target)
end
if matches[2] == 'الطرد' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled strict settings")
return disable_strict_rules(msg, data, target)
end
if matches[2] == 'المعرف' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled username")
return unlock_group_username(msg, data, target)
end
if matches[2] == 'السمايل' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled emoji")
return unlock_group_emoji(msg, data, target)
end
if matches[2] == 'التاك' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tag")
return unlock_group_tag(msg, data, target)
end
if matches[2] == 'اعاده توجيه' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked fwd")
return unlock_group_fwd(msg, data, target)
end
if matches[2] == 'الشارحه' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked cmd")
return unlock_group_cmd(msg, data, target)
end
if matches[2] == 'الانلاين' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked unsupported")
return unlock_group_unsupported(msg, data, target)
end
if matches[2] == 'البوتات' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'الدخول بالرابط' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked join")
return unlock_group_join(msg, data, target)
end
if matches[2] == 'الاشعارات' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tgservice actions")
return unlock_group_tgservice(msg, data, target)
end
end
if matches[1] == 'ضع تكرار' then
if not is_momod(msg) then
return
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "ضــع⬅️تــــكــــرار م̷ـــِْن 5⃣الــــﯽ 0⃣2⃣"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'تــــمــ☑️تــــعــيــيــن 🔃الــتــكــرار🔄لـلــعــدد↙️↘️ : '..matches[2]
end
if matches[1] == 'المراقبه' and is_momod(msg) then
local target = msg.to.id
if matches[2] == 'نعم' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'لا' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: not public")
return unset_public_membermod(msg, data, target)
end
end
if matches[1] == 'قفل' and is_owner(msg) then
local chat_id = msg.to.id
if matches[2] == 'الصوت' then
local msg_type = 'Audio'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return 'تــــم✔️قــــفــــل🔒الــــــصــــوت🎤🎧♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
return 'الــــــصــــوت🎤🎧🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
if matches[2] == 'الصور' then
local msg_type = 'Photo'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return 'تــــم✔️قــــفــــل🔒الــــــصــــور🎠♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
return 'الــــــصــــور🎠🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
if matches[2] == 'الفيديو' then
local msg_type = 'Video'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return 'تــــم✔️قــــفــــل🔒الــــــفــيــديــــو🎥♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
return 'الــــــفــيــديــــو🎥🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
if matches[2] == 'الصور المتحركه' then
local msg_type = 'Gifs'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return 'تــــم✔️قــــفــــل🔒الــــــصــــور🎠 الــــــمتــــحــــركــــﮥ🚼♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
return 'الــــــصــــور🎠 الــــــمتــــحــــركــــﮥ🚼🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
if matches[2] == 'الفايلات' then
local msg_type = 'Documents'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return 'تــــم✔️قــــفــــل🔒الــــفــايــلات🗂♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
return 'الــــفــايــلات🗂🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
if matches[2] == 'الدردشه' then
local msg_type = 'Text'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return 'تــــم✔️قــــفــــل🔒الــــدردشــــة🛃♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
return 'الــــدردشــــة🛃🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
if matches[2] == 'المجموعه' then
local msg_type = 'All'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return 'تــــم✔️قــــفــــل🔒الــــــمــــجــــمــــوعــة🔆💯♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
return 'الــــــمــــجــــمــــوعــة🔆💯🔊 بلــــفعــل✔️مــــقــفوله🔒هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
end
if matches[1] == 'فتح' and is_momod(msg) then
local chat_id = msg.to.id
if matches[2] == 'الصوت' then
local msg_type = 'Audio'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return 'تــــم✔️فــــتــــح🔓الــــــصــــوت🎤🎧♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
return 'الــــــصــــوت🎤🎧🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
if matches[2] == 'الصور' then
local msg_type = 'Photo'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return 'تــــم✔️فــــتــــح🔓الــــــصــــور🎠♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
return 'الــــــصــــور🎠🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
if matches[2] == 'الفيديو' then
local msg_type = 'Video'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return 'تــــم✔️فــــتــــح🔓الــــــفــيــديــــو🎥♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
return 'الــــــفــيــديــــو🎥🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
if matches[2] == 'الصور المتحركه' then
local msg_type = 'Gifs'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return 'تــــم✔️فــــتــــح🔓الــــــصــــور🎠 الــــــمتــــحــــركــــﮥ🚼♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
return 'الــــــصــــور🎠 الــــــمتــــحــــركــــﮥ🚼🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
if matches[2] == 'الفايلات' then
local msg_type = 'Documents'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return 'تــــم✔️فــــتــــح🔓الــــفــايــلات🗂♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
return 'الــــفــايــلات🗂🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
if matches[2] == 'الدردشه' then
local msg_type = 'Text'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute message")
unmute(chat_id, msg_type)
return 'تــــم✔️فــــتــــح🔓الــــدردشــــة🛃♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
return 'الــــدردشــــة🛃🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
if matches[2] == 'المجموعه' then
local msg_type = 'All'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return 'تــــم✔️فــــتــــح🔓الــــــمــــجــــمــــوعــة🔆💯♨️🚫\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
else
return 'الــــــمــــجــــمــــوعــة🔆💯🔊 بلــــفعــل✔️مــــفــتوحه🔓هــــنــا👾\nبواسطه 🐉 👁🗨 (@'..(msg.from.username or 'لا يوجد')..')\n'
end
end
end
if matches[1] == "كتم" and is_momod(msg) then
local chat_id = msg.to.id
local hash = "mute_user"..chat_id
local user_id = ""
if type(msg.reply_id) ~= "nil" then
local receiver = get_receiver(msg)
local get_cmd = "mute_user"
muteuser = get_message(msg.reply_id, get_message_callback, {receiver = receiver, get_cmd = get_cmd, msg = msg})
elseif matches[1] == "كتم" and string.match(matches[2], '^%d+$') then
local user_id = matches[2]
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed ["..user_id.."] from the muted users list")
return "["..user_id.."] تــــــاج👑مــــــخي🐲انــــشــــال😽😻كــــــــتــــم👻مــــــنــك💋"
elseif is_momod(msg) then
mute_user(chat_id, user_id)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."] to the muted users list")
return "["..user_id.."] تــــــم😎كــــــتــــمــــك😶مــــن وره ســــولــــفــك🤗يــــاخــرا💩"
end
elseif matches[1] == "كتم" and not string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local get_cmd = "mute_user"
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
resolve_username(username, callbackres, {receiver = receiver, get_cmd = get_cmd, msg=msg})
end
end
if matches[1] == "اعدادات الوسائط" and is_momod(msg) then
local chat_id = msg.to.id
if not has_mutes(chat_id) then
set_mutes(chat_id)
return mutes_list(chat_id)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist")
return mutes_list(chat_id)
end
if matches[1] == "المكتومين" and is_momod(msg) then
local chat_id = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup mutelist")
return muted_user_list(chat_id)
end
if matches[1] == 'الاعدادات' and is_momod(msg) then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup settings ")
return show_supergroup_settingsmod(msg, target)
end
if matches[1] == 'القوانين' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'help' and not is_owner(msg) then
text = "Message /superhelp to @Teleseed in private for SuperGroup help"
reply_msg(msg.id, text, ok_cb, false)
elseif matches[1] == 'help' and is_owner(msg) then
local name_log = user_print_name(msg.from)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /superhelp")
return super_help()
end
if matches[1] == 'peer_id' and is_admin1(msg)then
text = msg.to.peer_id
reply_msg(msg.id, text, ok_cb, false)
post_large_msg(receiver, text)
end
if matches[1] == 'msg.to.id' and is_admin1(msg) then
text = msg.to.id
reply_msg(msg.id, text, ok_cb, false)
post_large_msg(receiver, text)
end
--Admin Join Service Message
if msg.service then
local action = msg.action.type
if action == 'chat_add_user_link' then
if is_owner2(msg.from.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.from.id
savelog(msg.to.id, name_log.." Admin ["..msg.from.id.."] joined the SuperGroup via link")
channel_set_admin(receiver, user, ok_cb, false)
end
if is_support(msg.from.id) and not is_owner2(msg.from.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.from.id
savelog(msg.to.id, name_log.." Support member ["..msg.from.id.."] joined the SuperGroup")
channel_set_mod(receiver, user, ok_cb, false)
end
end
if action == 'chat_add_user' then
if is_owner2(msg.action.user.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.action.user.id
savelog(msg.to.id, name_log.." Admin ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]")
channel_set_admin(receiver, user, ok_cb, false)
end
if is_support(msg.action.user.id) and not is_owner2(msg.action.user.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.action.user.id
savelog(msg.to.id, name_log.." Support member ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]")
channel_set_mod(receiver, user, ok_cb, false)
end
end
end
if matches[1] == 'msg.to.peer_id' then
post_large_msg(receiver, msg.to.peer_id)
end
end
end
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '['..msg.media.type..']'
end
return msg
end
return {
patterns = {
"^(تفعيل)$",
"^(تعطيل)$",
"^([Mm]ove) (.*)$",
"^(معلومات المجموعه)$",
"^(الاداريين)$",
"^(مدير المجموعه)$",
"^(الادمنيه)$",
"^(كشف بوت)$",
"^(ايدي الاعضاء)$",
"^([Kk]icked)$",
"^(بلوك) (.*)",
"^(بلوك)",
"^(ترقيه سوبر)$",
"^(ايدي)$",
"^(ايدي) (.*)$",
"^(مغادره)$",
"^[#!/]([Kk]ick) (.*)$",
"^(تغير الرابط)$",
"^(ضع رابط)$",
"^(الرابط)$",
"^(الايدي) (.*)$",
"^(رفع اداري) (.*)$",
"^(رفع اداري)",
"^(تنزيل اداري) (.*)$",
"^(تنزيل اداري)",
"^(رفع المدير) (.*)$",
"^(رفع المدير)$",
"^(رفع ادمن) (.*)$",
"^(رفع ادمن)",
"^(تنزيل ادمن) (.*)$",
"^(تنزيل ادمن)",
"^(ضع اسم) (.*)$",
"^(ضع وصف) (.*)$",
"^(ضع قوانين) (.*)$",
"^(ضع صوره)$",
"^(ضع معرف) (.*)$",
"^(مسح)$",
"^(قفل) (.*)$",
"^(فتح) (.*)$",
"^(قفل) ([^%s]+)$",
"^(فتح) ([^%s]+)$",
"^(كتم)$",
"^(كتم) (.*)$",
"^(المراقبه) (.*)$",
"^(الاعدادات)$",
"^(القوانين)$",
"^(ضع تكرار) (%d+)$",
"^(مسح) (.*)$",
"^[#!/]([Hh]elpp)$",
"^(اعدادات الوسائط)$",
"^(المكتومين)$",
"^[#!/](تفعيل)$",
"^[#!/](تعطيل)$",
"^[#!/]([Mm]ove) (.*)$",
"^[#!/](معلومات المجموعه)$",
"^[#!/](الاداريين)$",
"^[#!/](مدير المجموعه)$",
"^[#!/](الادمنيه)$",
"^[#!/](كشف بوت)$",
"^[#!/](ايدي الاعضاء)$",
"^[#!/]([Kk]icked)$",
"^[#!/](بلوك) (.*)",
"^[#!/](بلوك)",
"^[#!/](ترقيه سوبر)$",
"^[#!/](ايدي)$",
"^[#!/](ايدي) (.*)$",
"^[#!/](مغادره)$",
"^[#!/]([Kk]ick) (.*)$",
"^[#!/](تغير الرابط)$",
"^[#!/](ضع رابط)$",
"^[#!/](الرابط)$",
"^[#!/](الايدي) (.*)$",
"^[#!/](رفع اداري) (.*)$",
"^[#!/](رفع اداري)",
"^[#!/](تنزيل اداري) (.*)$",
"^[#!/](تنزيل اداري)",
"^[#!/](رفع المدير) (.*)$",
"^[#!/](رفع المدير)$",
"^[#!/](رفع ادمن) (.*)$",
"^[#!/](رفع ادمن)",
"^[#!/](تنزيل ادمن) (.*)$",
"^[#!/](تنزيل ادمن)",
"^[#!/](ضع اسم) (.*)$",
"^[#!/](ضع وصف) (.*)$",
"^[#!/](ضع قوانين) (.*)$",
"^[#!/](ضع صوره)$",
"^[#!/](ضع معرف) (.*)$",
"^[#!/](مسح)$",
"^[#!/](قفل) (.*)$",
"^[#!/](فتح) (.*)$",
"^[#!/](قفل) ([^%s]+)$",
"^[#!/](فتح) ([^%s]+)$",
"^[#!/](كتم)$",
"^[#!/](كتم) (.*)$",
"^[#!/](المراقبه) (.*)$",
"^[#!/](الاعدادات)$",
"^[#!/](القوانين)$",
"^[#!/](ضع تكرار) (%d+)$",
"^[#!/](مسح) (.*)$",
"^[#!/]([Hh]elpp)$",
"^[#!/](اعدادات الوسائط)$",
"^[#!/](المكتومين)$",
"[#!/](mp) (.*)",
"[#!/](md) (.*)",
"^(https://telegram.me/joinchat/%S+)$",
"msg.to.peer_id",
"%[(document)%]",
"%[(photo)%]",
"%[(video)%]",
"%[(audio)%]",
"%[(contact)%]",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
}
--[[
_ BY:@Aaa1R
__| |_ __ __ _ __ _ ___ _ __
/ _` | '__/ _` |/ _` |/ _ \| '_ \
| (_| | | | (_| | (_| | (_) | | | |
\__,_|_| \__,_|\__, |\___/|_| |_|
|___/
--]]
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Promyvion-Holla/Zone.lua | 9 | 2301 | -----------------------------------
--
-- Zone: Promyvion-Holla (16)
--
-----------------------------------
local ID = require("scripts/zones/Promyvion-Holla/IDs")
require("scripts/globals/promyvion")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
require("scripts/globals/settings")
require("scripts/globals/status")
-----------------------------------
function onInitialize(zone)
dsp.promyvion.initZone(zone)
end
function onZoneIn(player, prevZone)
local cs = -1
if player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0 then
player:setPos(92.033, 0, 80.380, 255) -- To Floor 1 {R}
end
if player:getCurrentMission(COP) == dsp.mission.id.cop.BELOW_THE_ARKS and player:getCharVar("PromathiaStatus") == 2 then
player:completeMission(COP, dsp.mission.id.cop.BELOW_THE_ARKS)
player:addMission(COP, dsp.mission.id.cop.THE_MOTHERCRYSTALS) -- start mission 1.3
player:setCharVar("PromathiaStatus", 0)
elseif player:getCurrentMission(COP) == dsp.mission.id.cop.THE_MOTHERCRYSTALS then
if player:hasKeyItem(dsp.ki.LIGHT_OF_DEM) and player:hasKeyItem(dsp.ki.LIGHT_OF_MEA) then
if player:getCharVar("cslastpromy") == 1 then
player:setCharVar("cslastpromy", 0)
cs = 52
end
elseif player:hasKeyItem(dsp.ki.LIGHT_OF_DEM) or player:hasKeyItem(dsp.ki.LIGHT_OF_MEA) then
if player:getCharVar("cs2ndpromy") == 1 then
player:setCharVar("cs2ndpromy", 0)
cs = 51
end
end
end
if player:getCharVar("FirstPromyvionHolla") == 1 then
cs = 50
end
return cs
end
function afterZoneIn(player)
if ENABLE_COP_ZONE_CAP == 1 then
player:addStatusEffect(dsp.effect.LEVEL_RESTRICTION, 30, 0, 0)
end
end
function onRegionEnter(player, region)
dsp.promyvion.onRegionEnter(player, region)
end
function onRegionLeave(player, region)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 46 and option == 1 then
player:setPos(-225.682, -6.459, 280.002, 128, 14) -- To Hall of Transference {R}
elseif csid == 50 then
player:setCharVar("FirstPromyvionHolla", 0)
end
end | gpl-3.0 |
gallenmu/MoonGen | libmoon/lua/log.lua | 6 | 4193 | ---------------------------------
--- @file log.lua
--- @brief Logging module.
--- @todo Docu
---------------------------------
require "utils"
local log = {}
------------------------------------------------------
---- Log Levels
------------------------------------------------------
-- terminates by calling error()
log.FATAL = 4
-- most likely terminates
log.ERROR = 3
-- something unexpected but not critical
log.WARN = 2
-- information for user
log.INFO = 1
-- debugging
log.DEBUG = 0
----------------------------------------------------
---- stdout Logging
----------------------------------------------------
-- current log level
log.level = log.INFO
--- Set the log level
--- @param level Set log level to level. Default: INFO
function log:setLevel(level)
local prevLevel = self.level
self.level = self[level] or self.INFO
if not prevLevel == self.level then
self:info("Changed log level to %s.", self[level] and level or "INFO")
end
end
----------------------------------------------------
---- File Logging
----------------------------------------------------
-- en- or disable file logging
log.fileEnabled = false
--- Enable logging to file
function log:fileEnable()
self.fileEnabled = true
self:info("Enabled logging to '" .. log.file .. "'")
end
--- Disable logging to file
function log:fileDisable()
self.fileEnabled = false
self:info("Disabled logging to " .. log.file .. "'")
end
-- current file log level
log.fileLevel = log.DEBUG
--- Set the file log level.
--- @param level Set file log level to level. Default: DEBUG
function log:setFileLevel(level)
self.fileLevel = self.level or self.DEBUG
end
--- path to log file
log.file = nil
log.locations = {
"log/",
"../log/",
}
do
local function fileExists(f)
local file = io.open(f, "r")
if file then
file:close()
end
return not not file
end
-- find log/ path
for _, f in ipairs(log.locations) do
if fileExists(f) then
log.file = f .. "debug.log"
end
end
if not log.file then
log.file = "debug.log"
-- print("Unable to locate log directory. Logging to debug.log in working directory.")
end
-- print("Logging to " .. log.file)
end
--- Write a message to the log file specified in log.file
--- @param str Log message.
function log:writeToLog(str)
local f = assert(io.open(self.file, "a"))
f:write(getTimeMicros() .. " " .. str .. "\n")
f:close()
end
---------------------------------------------------
---- Logging Functions
---------------------------------------------------
--- Log a message, level FATAL.
--- This message is written with error(), hence, terminates the application.
--- FATAL log messages to stdout cannot be disabled.
--- @param str Log message
--- @param args Formatting parameters
function log:fatal(str, ...)
str = str:format(...)
if self.fileEnabled then
self:writeToLog("[FATAL] " .. str)
end
error(red(str), 2)
end
--- Log a message, level ERROR.
--- @param str Log message
--- @param args Formatting parameters
function log:error(str, ...)
str = "[ERROR] " .. str:format(...)
if self.ERROR >= self.level then
print(bred("%s", str))
end
if self.fileEnabled and self.ERROR >= self.fileLevel then
self:writeToLog(str)
end
end
--- Log a message, level WARN.
--- @param str Log message
--- @param args Formatting parameters
function log:warn(str, ...)
str = "[WARN] " .. str:format(...)
if self.WARN >= self.level then
print(yellow("%s", str))
end
if self.fileEnabled and self.WARN >= self.fileLevel then
self:writeToLog(str)
end
end
--- Log a message, level INFO.
--- @param str Log message
--- @param args Formatting parameters
function log:info(str, ...)
str = "[INFO] " .. str:format(...)
if self.INFO >= self.level then
print(white("%s", str))
end
if self.fileEnabled and self.INFO >= self.fileLevel then
self:writeToLog(str)
end
end
--- Log a message, level DEBUG.
--- @param str Log message
--- @param args Formatting parameters
function log:debug(str, ...)
str = "[DEBUG] " .. str:format(...)
if self.DEBUG >= self.level then
print(green("%s", str))
end
if self.fileEnabled and self.DEBUG >= self.fileLevel then
self:writeToLog(str)
end
end
return log
| mit |
ashkanpj/yagoopfire | plugins/isX.lua | 605 | 2031 | local https = require "ssl.https"
local ltn12 = require "ltn12"
local function request(imageUrl)
-- Edit data/mashape.lua with your Mashape API key
-- http://docs.mashape.com/api-keys
local mashape = load_from_file('data/mashape.lua', {
api_key = ''
})
local api_key = mashape.api_key
if api_key:isempty() then
return nil, 'Configure your Mashape API Key'
end
local api = "https://sphirelabs-advanced-porn-nudity-and-adult-content-detection.p.mashape.com/v1/get/index.php?"
local parameters = "&url="..(URL.escape(imageUrl) or "")
local url = api..parameters
local respbody = {}
local headers = {
["X-Mashape-Key"] = api_key,
["Accept"] = "Accept: application/json"
}
print(url)
local body, code, headers, status = https.request{
url = url,
method = "GET",
headers = headers,
sink = ltn12.sink.table(respbody),
protocol = "tlsv1"
}
if code ~= 200 then return "", code end
local body = table.concat(respbody)
return body, code
end
local function parseData(data)
local jsonBody = json:decode(data)
local response = ""
print(data)
if jsonBody["Error Occured"] ~= nil then
response = response .. jsonBody["Error Occured"]
elseif jsonBody["Is Porn"] == nil or jsonBody["Reason"] == nil then
response = response .. "I don't know if that has adult content or not."
else
if jsonBody["Is Porn"] == "True" then
response = response .. "Beware!\n"
end
response = response .. jsonBody["Reason"]
end
return jsonBody["Is Porn"], response
end
local function run(msg, matches)
local data, code = request(matches[1])
if code ~= 200 then return "There was an error. "..code end
local isPorn, result = parseData(data)
return result
end
return {
description = "Does this photo contain adult content?",
usage = {
"!isx [url]",
"!isporn [url]"
},
patterns = {
"^!is[x|X] (.*)$",
"^!is[p|P]orn (.*)$"
},
run = run
} | gpl-2.0 |
Attractive1/Attractive-Robot | plugins/feedback.lua | 35 | 1028 | do
function run(msg, matches)
local fuse = '#DearAdmin , we have recive a new feedback just now : #newfeedback \n\nID : ' .. msg.from.id .. '\n\nName : ' .. msg.from.print_name ..'\n\nusername : @' .. msg.from.username ..'\n\nFeedBack :\n\n\n' .. matches[1]
local fuses = '!printf user#id' .. msg.from.id
local text = matches[1]
bannedidone = string.find(msg.from.id, '123')
bannedidtwo =string.find(msg.from.id, '465')
bannedidthree =string.find(msg.from.id, '678')
print(msg.to.id)
if bannedidone or bannedidtwo or bannedidthree then --for banned people
return 'You are banned to send a feedback'
else
local sends0 = send_msg('chat#36515907', fuse, ok_cb, false)
return 'ارسال شد :)'
end
end
return {
description = "Feedback",
usage = "ارسال نظر : send maseage to admins with bot",
patterns = {
"^ارسال نظر (.*)$"
},
run = run
}
end
--add your realm id to line 22 chat#
| gpl-2.0 |
rigeirani/teshep | plugins/ingroup.lua | 3 | 38187 | do
local function check_member(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
lock_bots = 'no',
lock_arabic = 'no',
flood = 'yes'
},
realm_field = 'no'
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Ora sei il proprietario del gruppo.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
lock_bots = 'no',
lock_arabic = 'no',
flood = 'yes'
},
realm_field = 'no'
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Gruppo indicizzato, ora sei il suo proprietario')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Gruppo rimosso dall\'indice')
end
end
end
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local settings = data[tostring(target)]['settings']
local text = "Impostazioni gruppo:\nBlocco nome: "..settings.lock_name.."\nBlocco foto: "..settings.lock_photo.."\nBlocco membri: "..settings.lock_member.."\nSensitività flood: "..NUM_MSG_MAX.."\nScudo bot: "..bots_protection
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Descrizione del gruppo impostata:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'Nessuna descrizione disponibile.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'Descrizione '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Caratteri arabi già bloccati'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Caratteri arabi bloccati'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Caratteri arabi già sbloccati'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Caratteri arabi sbloccati'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Protezione dai bot (API) già abilitata'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Protezione dai bot (API) abilitata'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Protezione dai bot (API) già disabilitata'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Protezione dai bot (API) disabilitata'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Nome già bloccato'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Nome bloccato'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Nome già sbloccato'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Nome sbloccato'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Solo il proprietario può modificare questa impostazione"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Flood già bloccato'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Flood bloccato'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Solo il proprietario può modificare questa impostazione"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Flood già sbloccato'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Flood sbloccato'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Membri già bloccati'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Membri bloccati'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Membri già sbloccati'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Membri sbloccati'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Foto già sbloccata'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Foto sbloccata'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Regole impostate:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "Non sei un amministratore"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
return 'Il gruppo è già aggiunto.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "Non sei amministratore"
end
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Il gruppo non era aggiunto.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
local function realmadd(msg)
local data = load_data(_config.moderation.data)
local target = msg.to.id
local realm_field = data[tostring(target)]['realm_field']
if realm_field == 'yes' then
return 'Questo gruppo è già un Realm'
else
data[tostring(target)]['realm_field'] = 'yes'
save_data(_config.moderation.data, data)
return 'Questo gruppo ora è un Realm'
end
end
local function realmrem(msg)
local data = load_data(_config.moderation.data)
local target = msg.to.id
local realm_field = data[tostring(target)]['realm_field']
if realm_field == 'no' then
return 'Questo gruppo non è un Realm'
else
data[tostring(target)]['realm_field'] = 'no'
save_data(_config.moderation.data, data)
return 'Questo gruppo ora non è più un Realm'
end
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'Nessuna regola disponibile.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Regole:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File scaricato in:', result)
os.rename(result, file)
print('File spostato in:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Foto salvata!', ok_cb, false)
else
print('Errore nel download: '..msg.id)
send_large_msg(receiver, 'Errore, per favore prova di nuovo!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Il gruppo non è aggiunto.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' è già moderatore.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' è stato promosso moderatore.')
end
local function promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Il gruppo non è aggiunto.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' non è un moderatore.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' ora non è più moderatore.')
end
local function demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setowner_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha impostato ["..msg.from.id.."] come proprietario")
local text = msg.from.print_name:gsub("_", " ").." è il proprietario"
return send_large_msg(receiver, text)
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'Nessun @'..member..' in questo gruppo.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = '@'..member
member_id = v.id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Il gruppo non è aggiunto.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'Nessun moderatore in questo gruppo.'
end
local i = 1
local message = '\nLista dei moderatori di ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
if success == -1 then
return send_large_msg(receiver, '*Errore: nessun link creato* \nNon sono il creatore del gruppo. Solo il creatore può generare un link.')
end
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function kicknouser(cb_extra, success, result)
local chat = "chat#id"..cb_extra.chat
local user
for k,v in pairs(result.members) do
if not v.username then
user = 'user#id'..v.id
chat_del_user(chat, user, ok_cb, true)
end
end
end
--QUESTE TRE FUNZIONI (SOTTO) SERVONO A KICKARE GLI UTENTI INATTIVI
local function user_msgs(user_id, chat_id)
local user_info
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat = "chat#id"..cb_extra.chat_id
local chat_id = cb_extra.chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'agg' then
print("Gruppo "..msg.to.print_name.."("..msg.to.id..") aggiunto")
return modadd(msg)
end
if matches[1] == 'rim' then
print("Gruppo "..msg.to.print_name.."("..msg.to.id..") rimosso")
return modrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 then
return automodadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local receiver = 'user#id'..msg.action.user.id
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return false
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Benvenuto in "' .. string.gsub(msg.to.print_name, '_', ' ') ..'", ecco le regole del gruppo:\n'..rules
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha rimosso "..msg.action.user.id)
send_large_msg(receiver, rules)
end
if matches[1] == 'chat_del_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha provato a rimuovere la foto ma ha fallito ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha provato a cambiare la foto ma ha fallito ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha provato a cambiare il nome ma ha fallito ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'nome' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Gruppo { "..msg.to.print_name.." } nome cambiato in [ "..new_name.." ] da "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'foto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Per favore inviami la nuova foto del gruppo ora'
end
if matches[1] == 'promuovi' and not matches[2] then
if not is_owner(msg) then
return "Solo il proprietario può promuovere nuovi moderatori"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promuovi' and matches[2] then
if not is_owner(msg) then
return "Solo il proprietario può promuovere nuovi moderatori"
end
local member = string.gsub(matches[2], "@", "")
local mod_cmd = 'promote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha promosso @".. member)
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'degrada' and not matches[2] then
if not is_owner(msg) then
return "Solo il proprietario può degradare un moderatore"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'degrada' and matches[2] then
if not is_owner(msg) then
return "Solo il proprietario può degradare un moderatore"
end
if string.gsub(matches[2], "@", "") == msg.from.username then
return "Non puoi rinunciare alla carica di moderatore da solo"
end
local member = string.gsub(matches[2], "@", "")
local mod_cmd = 'demote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha degradato @".. member)
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'listamod' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha richiesto la lista dei moderatori")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha richiesto la descrizione")
return get_description(msg, data)
end
if matches[1] == 'regole' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha richiesto le regole")
return get_rules(msg, data)
end
if matches[1] == 'setta' then
if matches[2] == 'regole' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha cambiato le regole in ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha cambiato la descrizione in ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'blocca' then
local target = msg.to.id
if matches[2] == 'nome' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha bloccato il nome ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'membri' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha bloccato i membri ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha bloccato il flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha bloccato i caratteri arabi ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bot' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha bloccato i bot ")
return lock_group_bots(msg, data, target)
end
end
if matches[1] == 'sblocca' then
local target = msg.to.id
if matches[2] == 'nome' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha sbloccato il nome ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'membri' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha sbloccato i membri ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'foto' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha sbloccato la foto ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha sbloccato il flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha sbloccato la lingua araba ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bot' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha sbloccato i bot ")
return unlock_group_bots(msg, data, target)
end
end
if matches[1] == 'info' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha richiesto le impostazioni ")
return show_group_settingsmod(msg, data, target)
end
if matches[1] == 'nuovolink' then
if not is_momod(msg) then
return "Solo per moderatori!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Errore: link non creato* \nNon sono il creatore di questo gruppo, solo il creatore può generare il link.')
end
send_large_msg(receiver, "Nuovo link creato")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha revocato il link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'link' then
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Crea un nuovo link usando /nuovolink prima!"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha richiesto il link ["..group_link.."]")
return "Link del gruppo:\n"..group_link
end
if matches[1] == 'setboss' and matches[2] then
if not is_owner(msg) then
return "Solo per il proprietario!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha impostato ["..matches[2].."] come proprietario")
local text = matches[2].." impostato come proprietario"
return text
end
if matches[1] == 'setboss' and not matches[2] then
if not is_owner(msg) then
return "Solo per il proprietario!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
end
if matches[1] == 'boss' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "Nessun proprietario. Chiedi ad un amministratore del bot di impostare il proprietario di questo gruppo"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "Il proprietario è ["..group_owner..']'
end
if matches[1] == 'setgrboss' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "Solo per amministratori!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." impostato come proprietario"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "Solo per moderatori!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Il valore deve rientrare nel range [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha impostato il flood a ["..matches[2].."]")
return 'Flood impostato a '..matches[2]
end
if matches[1] == 'spazza' then
if not is_owner(msg) then
return "Solo il proprietario può cancellare"
end
if matches[2] == 'membri' then
if not is_owner(msg) then
return "Solo il proprietario può eliminare tutti i membri"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'mod' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'Nessun moderatore in questo gruppo.'
end
--local message = '\nLista dei moderatori di ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha rimosso i moderatori")
return 'Moderatori rimossi'
end
if matches[2] == 'regole' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha rimosso le regole")
return 'Regole rimosse'
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha rimosso la descrizione")
return 'Descrizione rimossa'
end
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha usato /res "..username)
return res_user(username, callbackres, cbres_extra)
end
if matches[1] == 'aggrealm' and is_admin(msg) then
print("Gruppo "..msg.to.print_name.."("..msg.to.id..") aggiunto ai realm")
return realmadd(msg)
end
if matches[1] == 'rimrealm' and is_admin(msg) then
print("Gruppo "..msg.to.print_name.."("..msg.to.id..") rimosso dai realm")
return realmrem(msg)
end
if matches[1] == 'isrealm' then
if is_realmM(msg) then
return 'Questo gruppo è un Realm'
else
return 'Questo gruppo non è un Realm'
end
end
if matches[1] == 'kickanouser' then
if not is_owner(msg) then
return "Solo il proprietario può usare questo comando!"
end
chat_info(receiver, kicknouser, {chat = msg.to.id})
end
if matches[1] == 'kickainattivi' then
if not is_momod(msg) then
return 'Solo un moderatore può rimuovere gli utenti inattivi'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^/(agg)$",
"^/(rim)$",
"^/(regole)$",
"^/(about)$",
"^/(nome) (.*)$",
"^/(foto)$",
"^/(promuovi) (.*)$",
"^/(promuovi)",
"^/(spazza) (.*)$",
"^/(degrada) (.*)$",
"^/(degrada)",
"^/(setta) ([^%s]+) (.*)$",
"^/(blocca) (.*)$",
"^/(setboss) (%d+)$",
"^/(setboss)",
"^/(boss)$",
"^/(res) (.*)$",
"^/(setgrboss) (%d+) (%d+)$",-- (group id) (owner id)
"^/(sblocca) (.*)$",
"^/(setflood) (%d+)$",
"^/(info)$",
"^/(listamod)$",
"^/(nuovolink)$",
"^/(link)$",
"^/(aggrealm)$",
"^/(rimrealm)$",
"^/(isrealm)$",
"^/(kickanouser)$",
"^/(kickainattivi)$",
"^/(kickainattivi) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
mneudert/luxy | src/luxy.lua | 1 | 1942 | -- public module table
local luxy = {}
--- Stores the configuration for the module.
--
-- This call replaces any existing configuration.
--
-- Available configuration keys:
-- - "default_upstream"
--
-- @param config configuration table
luxy.configure = function(config)
local luxy_conf = ngx.shared.luxy_conf
if not config then
luxy_conf:flush_all()
luxy_conf:flush_expired()
return
end
-- remove keys not used anymore
for _, key in next, luxy_conf:get_keys() do
if not config[key] then
luxy_conf:delete(key)
end
end
-- fill config with new values
for key, val in pairs(config) do
luxy_conf:set(key, val)
end
luxy_conf:set('configured', true)
end
--- Returns the upstream for the current request.
--
-- @return string
luxy.get_upstream = function()
local luxy_conf = ngx.shared.luxy_conf
local luxy_proxy = ngx.shared.luxy_proxy
local default = luxy_conf:get('default_upstream')
local mappings = luxy_proxy:get_keys()
if not mappings then
return default
end
for _, key in next, mappings do
if ngx.var.uri == key then
return luxy_proxy:get(key)
end
end
return default
end
--- Returns if the module is configured.
--
-- @return boolean
luxy.is_configured = function()
return true == ngx.shared.luxy_conf:get('configured')
end
--- Sets a new upstream mapping.
--
-- This call replaces any existing mappings.
--
-- @param mapping upstream mapping table
luxy.set_mappings = function(mappings)
local luxy_proxy = ngx.shared.luxy_proxy
if not mappings then
luxy_proxy:flush_all()
luxy_proxy:flush_expired()
return
end
-- remove keys not used anymore
for _, key in next, luxy_proxy:get_keys() do
if not mappings[key] then
luxy_proxy:delete(key)
end
end
-- fill mapping with new values
for key, val in pairs(mappings) do
luxy_proxy:set(key, val)
end
end
-- export module
return luxy
| bsd-2-clause |
Frenzie/koreader | frontend/userpatch.lua | 4 | 4575 | --[[--
Allows applying developer patches while running KOReader.
The contents in `koreader/patches/` are applied on calling `userpatch.applyPatches(priority)`.
--]]--
local isAndroid, android = pcall(require, "android")
local userpatch = {
-- priorities for user patches,
early_once = "0", -- to be started early on startup (once after an update)
early = "1", -- to be started early on startup (always, but after an `early_once`)
late = "2", -- to be started after UIManager is ready (always)
-- 3-7 are reserved for later use
before_exit = "8", -- to be started a bit before exit before settings are saved (always)
on_exit = "9", -- to be started right before exit (always)
-- the patch function itself
applyPatches = function(priority) end, -- to be overwritten, if the device allows it.
}
if isAndroid and android.prop.flavor == "fdroid" then
return userpatch -- allows to use applyPatches as a no-op on F-Droid flavor
end
local lfs = require("libs/libkoreader-lfs")
local logger = require("logger")
local DataStorage = require("datastorage")
-- the directory KOReader is installed in (and runs from)
local package_dir = lfs.currentdir()
-- the directory where KOReader stores user data
local data_dir = DataStorage:getDataDir()
--- Run lua patches
-- Execution order order is alphanum-sort for humans version 4: `1-patch.lua` is executed before `10-patch.lua`
-- (see http://notebook.kulchenko.com/algorithms/alphanumeric-natural-sorting-for-humans-in-lua)
-- string directory ... to scan through (flat no recursion)
-- string priority ... only files starting with `priority` followed by digits and a '-' will be processed.
-- return true if a patch was executed
local function runUserPatchTasks(dir, priority)
if lfs.attributes(dir, "mode") ~= "directory" then
return
end
local patches = {}
for entry in lfs.dir(dir) do
local mode = lfs.attributes(dir .. "/" .. entry, "mode")
if entry and mode == "file" and entry:match("^" .. priority .. "%d*%-") then
table.insert(patches, entry)
end
end
if #patches == 0 then
return -- nothing to do
end
local function addLeadingZeroes(d)
local dec, n = string.match(d, "(%.?)0*(.+)")
return #dec > 0 and ("%.12f"):format(d) or ("%s%03d%s"):format(dec, #n, n)
end
local function sorting(a, b)
return tostring(a):gsub("%.?%d+", addLeadingZeroes)..("%3d"):format(#b)
< tostring(b):gsub("%.?%d+", addLeadingZeroes)..("%3d"):format(#a)
end
table.sort(patches, sorting)
for i, entry in ipairs(patches) do
local fullpath = dir .. "/" .. entry
if lfs.attributes(fullpath, "mode") == "file" then
if fullpath:match("%.lua$") then -- execute patch-files first
logger.info("Applying patch:", fullpath)
local ok, err = pcall(dofile, fullpath)
if not ok then
logger.warn("Patching failed:", err)
-- Only show InfoMessage, when UIManager is working
if priority >= userpatch.late and priority < userpatch.before_exit then
-- Only developers (advanced users) will use this mechanism.
-- A warning on a patch failure after an OTA update will simplify troubleshooting.
local UIManager = require("ui/uimanager")
local InfoMessage = require("ui/widget/infomessage")
UIManager:show(InfoMessage:new{text = "Error applying patch:\n" .. fullpath}) -- no translate
end
end
end
end
end
return true
end
--- This function applies lua patches from `/koreader/patches`
---- @string priority ... one of the defined priorities in the userpatch hashtable
function userpatch.applyPatches(priority)
local patch_dir = data_dir .. "/patches"
local update_once_marker = package_dir .. "/update_once.marker"
local update_once_pending = lfs.attributes(update_once_marker, "mode") == "file"
if priority >= userpatch.early or update_once_pending then
local executed_something = runUserPatchTasks(patch_dir, priority)
if executed_something and update_once_pending then
-- Only delete update once marker if `early_once` updates have been applied.
os.remove(update_once_marker) -- Prevent another execution on a further starts.
end
end
end
return userpatch
| agpl-3.0 |
MalRD/darkstar | scripts/zones/Cloister_of_Flames/bcnms/trial_by_fire.lua | 9 | 1506 | -----------------------------------
-- Area: Cloister of Flames
-- BCNM: Trial by Fire
-----------------------------------
local ID = require("scripts/zones/Cloister_of_Flames/IDs")
require("scripts/globals/battlefield")
require("scripts/globals/keyitems")
require("scripts/globals/quests")
require("scripts/globals/titles")
-----------------------------------
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
local arg8 = (player:hasCompletedQuest(OUTLANDS, dsp.quest.id.outlands.TRIAL_BY_FIRE)) and 1 or 0
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), arg8)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 32001 then
player:delKeyItem(dsp.ki.TUNING_FORK_OF_FIRE)
player:addKeyItem(dsp.ki.WHISPER_OF_FLAMES)
player:addTitle(dsp.title.HEIR_OF_THE_GREAT_FIRE)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.WHISPER_OF_FLAMES)
end
end
| gpl-3.0 |
Lsty/ygopro-scripts | c45045866.lua | 3 | 1090 | --オーシャンズ・オーパー
function c45045866.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_PIERCE)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(45045866,0))
e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_BATTLE_DESTROYED)
e2:SetTarget(c45045866.target)
e2:SetOperation(c45045866.operation)
c:RegisterEffect(e2)
end
function c45045866.filter(c)
local code=c:GetCode()
return (code==81434470 or code==18828179) and c:IsAbleToHand()
end
function c45045866.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c45045866.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c45045866.filter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
mdsandell/DatePicker | datePickerWheel.lua | 1 | 5423 | --[[
The MIT License (MIT)
Copyright (c) 2015 Mark Sandell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]
local widget = require("widget")
-- Create tables to hold data for months, days, and years.
local dayCount = {
31, -- January
28, -- February
31, -- March
30, -- April
31, -- May
30, -- June
31, -- July
31, -- August
30, -- September
31, -- October
30, -- November
31, -- December
}
-- Figure out the local month names.
local months = {}
local now = {year=2015, month=1, day=1, isdst=false}
for i=1, 12 do
now.month = i
months[i] = os.date("%B", os.time(now))
end
-- Add the last 100 years.
local years = {}
local currYear = tonumber(os.date("%Y")) + 1
for i = 100, 1, -1 do
years[i] = currYear - i
end
local function isLeapYear(year)
--[[
:Parameters:
year : int
Year
:Returns:
If the given year is a leap year
:Rtype:
boolean
]]
if 0 == year % 4 then
if 0 == year % 100 then
if 0 == year % 400 then
return true
else
return false
end
else
return true
end
else
return false
end
end
local function daysInMonth(month, year)
--[[
:Parameters:
month : int
Number of month
year : int
Year, used to calculate leap years
:Returns
Number of days in the given month for the given year
:Rtype:
int
]]
if year and month == 2 and isLeapYear(year) then
return 29
end
return dayCount[month]
end
local function daysTable(month, year)
--[[
:Parameters:
month : int
Number of month
year : int
Year, used to calculate leap years
:Returns:
A table of day numbers based on the given month and year. (e.g. {1,2,3,...,31})
]]
local t = {}
for i=1, daysInMonth(month, year) do
t[#t+1] = i
end
return t
end
local function newWheel(year, month, day)
--[[
Does not support years in the future. Only goes back 100 years.
These should be easy to adjust if needed.
:Parameters:
year : int
Selected year
month :int
Selected month (1-12)
day : int
Selected day
]]
local columnData = {
{ -- Months
align = "right",
width = 140,
startIndex = month,
labels = months
},
{ -- Days
align = "center",
width = 60,
startIndex = day,
labels = daysTable(month, year)
},
{ -- Years
align = "center",
width = 80,
startIndex = currYear - year,
labels = years
}
}
return widget.newPickerWheel{columns = columnData}
end
function widget.newDatePickerWheel(year, month, day)
year = year or tonumber(os.date("%Y"))
month = month or tonumber(os.date("%m"))
day = day or tonumber(os.date("%d"))
local w = display.newGroup()
w.wheel = newWheel(year, month, day)
w:insert(w.wheel)
function w:getValues()
return self.wheel:getValues()
end
-- NOTE: If day or year column are still scrolling when month column changes, those will
-- snap back to their original selection.
function w:monitor()
-- Get selections from the picker wheel.
local values = self:getValues()
-- CORONA BUG: Sometimes the values can be nil.
-- This happens when one of the tables stopped scrolling but hasn't "snapped" to a selected index.
if not values[1] or not values[2] or not values[3] then return end
local month = values[1].index
local year = tonumber(values[3].value)
local maxDays = daysInMonth(month, year)
-- If the selected month has changed and the month has a different number of days than
-- before, or the selected month is February and the year changes to/from a leap year,
-- then redraw the picker wheel.
if (month ~= self.selectedMonth and maxDays ~= daysInMonth(self.selectedMonth, year)) or
(month == 2 and year ~= self.selectedYear and isLeapYear(year) ~= isLeapYear(self.selectedYear)) then
-- Make sure we no longer have a day selected greater than the number of days in
-- the current month.
local day = math.min(values[2].index, maxDays)
-- Remove the old wheel.
self.wheel:removeSelf()
-- Create the new wheel.
self.wheel = newWheel(year, month, day)
self:insert(self.wheel)
-- Save the current selection so we can tell if it changes.
self.selectedMonth = month
self.selectedYear = year
end
end
function w:finalize(event)
timer.cancel(self.timer)
self.timer = nil
self.wheel:removeSelf()
self.wheel = nil
end
w:addEventListener("finalize")
-- Monitor for changes roughly 30 times per second.
w.timer = timer.performWithDelay(33, function() w:monitor() end, -1)
return w
end | mit |
MalRD/darkstar | scripts/globals/mobskills/fuscous_ooze.lua | 11 | 1139 | ---------------------------------------------------
-- Fuscous Ooze
-- Family: Slugs
-- Description: A dusky slime inflicts encumberance and weight.
-- Type: Magical
-- Utsusemi/Blink absorb: Ignores shadows
-- Range: Cone
-- Notes:
---------------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
-- TODO: Encumberance seems to do nothing?
local typeEffect = dsp.effect.WEIGHT
local duration = 45
MobStatusEffectMove(mob, target, typeEffect, 50, 0, duration)
local dmgmod = 1
local baseDamage = mob:getWeaponDmg()*3.7
local info = MobMagicalMove(mob,target,skill,baseDamage,dsp.magic.ele.WATER,dmgmod,TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.WATER,MOBPARAM_IGNORE_SHADOWS)
target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.WATER)
return dmg
end | gpl-3.0 |
MalRD/darkstar | scripts/globals/spells/mages_ballad_iii.lua | 12 | 1163 | -----------------------------------------
-- Spell: Mage's Ballad III
-- Gradually restores target's MP.
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
local power = 3
local iBoost = caster:getMod(dsp.mod.BALLAD_EFFECT) + caster:getMod(dsp.mod.ALL_SONGS_EFFECT)
power = power + iBoost
if (caster:hasStatusEffect(dsp.effect.SOUL_VOICE)) then
power = power * 2
elseif (caster:hasStatusEffect(dsp.effect.MARCATO)) then
power = power * 1.5
end
caster:delStatusEffect(dsp.effect.MARCATO)
local duration = 120
duration = duration * ((iBoost * 0.1) + (caster:getMod(dsp.mod.SONG_DURATION_BONUS)/100) + 1)
if (caster:hasStatusEffect(dsp.effect.TROUBADOUR)) then
duration = duration * 2
end
if not (target:addBardSong(caster,dsp.effect.BALLAD,power,0,duration,caster:getID(), 0, 3)) then
spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT)
end
return dsp.effect.BALLAD
end
| gpl-3.0 |
MalRD/darkstar | scripts/zones/East_Ronfaure_[S]/npcs/qm3.lua | 11 | 1130 | -----------------------------------
-- Area: East Ronfaure [S]
-- NPC: qm3 "???"
-- Involved in Quests: Steamed Rams
-- !pos 312.821 -30.495 -67.15
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/campaign");
local ID = require("scripts/zones/East_Ronfaure_[S]/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if (player:getQuestStatus(CRYSTAL_WAR,dsp.quest.id.crystalWar.STEAMED_RAMS) == QUEST_ACCEPTED) then
if (player:hasKeyItem(dsp.ki.CHARRED_PROPELLER)) then
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY);
else
player:startEvent(1);
end
else
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
-- print("CSID:",csid);
-- print("RESULT:",option);
if (csid == 1) then
player:addKeyItem(dsp.ki.CHARRED_PROPELLER);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.CHARRED_PROPELLER);
end
end; | gpl-3.0 |
Lsty/ygopro-scripts | c61639289.lua | 3 | 1904 | --イグナイト・イーグル
function c61639289.initial_effect(c)
--pendulum summon
aux.AddPendulumProcedure(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--tohand
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_DESTROY+CATEGORY_TOHAND+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_PZONE)
e2:SetCondition(c61639289.thcon)
e2:SetTarget(c61639289.thtg)
e2:SetOperation(c61639289.thop)
c:RegisterEffect(e2)
end
function c61639289.thcon(e,tp,eg,ep,ev,re,r,rp)
local seq=e:GetHandler():GetSequence()
local pc=Duel.GetFieldCard(tp,LOCATION_SZONE,13-seq)
return pc and pc:IsSetCard(0xc8)
end
function c61639289.filter(c)
return c:IsRace(RACE_WARRIOR) and c:IsAttribute(ATTRIBUTE_FIRE) and c:IsAbleToHand()
end
function c61639289.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
local pc=Duel.GetFieldCard(tp,LOCATION_SZONE,13-c:GetSequence())
if chk==0 then return c:IsDestructable() and pc:IsDestructable()
and Duel.IsExistingMatchingCard(c61639289.filter,tp,LOCATION_DECK+LOCATION_GRAVE,0,1,nil) end
local g=Group.FromCards(c,pc)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,2,0,0)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK+LOCATION_GRAVE)
end
function c61639289.thop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
local pc=Duel.GetFieldCard(tp,LOCATION_SZONE,13-c:GetSequence())
if not pc then return end
local dg=Group.FromCards(c,pc)
if Duel.Destroy(dg,REASON_EFFECT)~=2 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c61639289.filter,tp,LOCATION_DECK+LOCATION_GRAVE,0,1,1,nil)
if g:GetCount()>0 and not g:GetFirst():IsHasEffect(EFFECT_NECRO_VALLEY) then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
Nuthen/ludum-dare-39 | entities/sprite.lua | 1 | 4798 | -- Rotate point (px, py) about (cx, cy) by rotation (radians)
local function rotatePoint(rot, px, py, cx, cy)
local x = math.cos(rot) * (px - cx) - math.sin(rot) * (py - cy) + cx
local y = math.sin(rot) * (px - cx) + math.cos(rot) * (py - cy) + cy
return x, y
end
local Sprite = Class("Sprite")
Sprite.static.DEFAULT_CORNER_MODE = "topleft"
function Sprite:initialize(image, params)
if type(image) == "string" then
self.image = love.graphics.newImage(image)
if DEBUG and Sentinel then
Sentinel:watch(image, function(image)
self.image = love.graphics.newImage(image)
end)
end
else
self.image = image
end
self.position = Vector(0, 0)
self.color = {255, 255, 255, 255}
self.opacity = 1
self.visible = true
self.rotation = 0
self.scale = Vector(1, 1)
self.offset = Vector(0, 0)
self.originOffset = Vector(0, 0)
-- Unsupported by most functions
self.shear = Vector(0, 0)
self.cornerMode = Sprite.DEFAULT_CORNER_MODE
local params = params or {}
for k, v in pairs(params) do
self[k] = v
end
self.width, self.height = self:calculateSize()
self:moveOriginToCorner(self.cornerMode)
end
function Sprite:update()
self.width, self.height = self:calculateSize()
end
function Sprite:draw()
self:update()
if self.cornerMode then
self:moveOriginToCorner(self.cornerMode)
end
local x, y = self.position:unpack()
x = x + self.offset.x
y = y + self.offset.y
x = math.floor(x + 0.5)
y = math.floor(y + 0.5)
if self.visible then
local r, g, b, a = self.color[1], self.color[2], self.color[3], self.color[4]
a = a or 255
a = a * self.opacity
love.graphics.setColor(r, g, b, a)
love.graphics.draw(self.image, x, y, self.rotation, self.scale.x, self.scale.y, self.originOffset.x, self.originOffset.y, self.shear.x, self.shear.y)
end
end
function Sprite:calculateSize()
local width = self.image:getWidth() * math.abs(self.scale.x)
local height = self.image:getHeight() * math.abs(self.scale.y)
return width, height
end
-- Corner mode relates to how the sprite is positioned relative to the origin
-- For example, sprites can be drawn relative to the bottom-right of an image rather
-- than the top-left
function Sprite:moveOriginToCorner(cornerMode)
self.cornerMode = cornerMode
if cornerMode == "topleft" then
self.originOffset.x = 0
self.originOffset.y = 0
elseif cornerMode == "topright" then
self.originOffset.x = self.width
self.originOffset.y = 0
elseif cornerMode == "bottomleft" then
self.originOffset.x = 0
self.originOffset.y = self.height
elseif cornerMode == "bottomright" then
self.originOffset.x = self.width
self.originOffset.y = self.height
elseif cornerMode == "center" then
self.originOffset.x = self.width/2
self.originOffset.y = self.height/2
elseif cornerMode == "centerleft" then
self.originOffset.x = 0
self.originOffset.y = self.height/2
elseif cornerMode == "centerright" then
self.originOffset.x = self.width
self.originOffset.y = self.height/2
elseif cornerMode == "topcenter" then
self.originOffset.x = self.width/2
self.originOffset.y = 0
elseif cornerMode == "bottomcenter" then
self.originOffset.x = self.width/2
self.originOffset.y = self.height
end
-- Account for changes in scale
self.originOffset.x = self.originOffset.x / self.scale.x
self.originOffset.y = self.originOffset.y / self.scale.y
end
function Sprite:getRelativePosition(x, y, prescaled)
if not prescaled then
x = x * self.scale.x
y = y * self.scale.y
end
x = x + self.position.x + self.offset.x
y = y + self.position.y + self.offset.y
x, y = rotatePoint(self.rotation, x, y, self.position.x + self.offset.x, self.position.y + self.offset.y)
x = math.floor(x + 0.5)
y = math.floor(y + 0.5)
return x, y
end
-- Returns the true top left position, no matter the origin offset
function Sprite:getTopLeftPosition()
return self:getRelativePosition(-self.originOffset.x, -self.originOffset.y)
end
function Sprite:getRectangle()
local points = {
0, 0,
self.width, 0,
self.width, self.height,
0, self.height,
0, 0
}
for i=1, #points, 2 do
local x = points[i]
local y = points[i+1]
x = x - self.originOffset.x * self.scale.x
y = y - self.originOffset.y * self.scale.y
points[i], points[i+1] = self:getRelativePosition(x, y, true)
end
return points
end
return Sprite
| mit |
Lsty/ygopro-scripts | c49702428.lua | 3 | 1092 | --黒・魔・導・爆・裂・破
function c49702428.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCondition(c49702428.condition)
e1:SetTarget(c49702428.target)
e1:SetOperation(c49702428.activate)
c:RegisterEffect(e1)
end
function c49702428.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0x10a2)
end
function c49702428.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c49702428.cfilter,tp,LOCATION_MZONE,0,1,nil)
end
function c49702428.filter(c)
return c:IsFaceup() and c:IsDestructable()
end
function c49702428.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c49702428.filter,tp,0,LOCATION_MZONE,1,nil) end
local g=Duel.GetMatchingGroup(c49702428.filter,tp,0,LOCATION_MZONE,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c49702428.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c49702428.filter,tp,0,LOCATION_MZONE,nil)
Duel.Destroy(g,REASON_EFFECT)
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Temenos/mobs/Orichalcum_Quadav.lua | 9 | 1222 | -----------------------------------
-- Area: Temenos
-- Mob: Orichalcum Quadav
-----------------------------------
require("scripts/globals/limbus");
-----------------------------------
function onMobEngaged(mob,target)
if (IsMobDead(16929017)==true and IsMobDead(16929018)==true and IsMobDead(16929019)==true and
IsMobDead(16929020)==true and IsMobDead(16929021)==true and IsMobDead(16929022)==true
) then
mob:setMod(dsp.mod.SLASHRES,1400);
mob:setMod(dsp.mod.PIERCERES,1400);
mob:setMod(dsp.mod.IMPACTRES,1400);
mob:setMod(dsp.mod.HTHRES,1400);
else
mob:setMod(dsp.mod.SLASHRES,300);
mob:setMod(dsp.mod.PIERCERES,300);
mob:setMod(dsp.mod.IMPACTRES,300);
mob:setMod(dsp.mod.HTHRES,300);
end
GetMobByID(16929005):updateEnmity(target);
GetMobByID(16929007):updateEnmity(target);
end;
function onMobDeath(mob, player, isKiller)
if (IsMobDead(16929005)==true and IsMobDead(16929006)==true and IsMobDead(16929007)==true) then
GetNPCByID(16928768+78):setPos(-280,-161,-440);
GetNPCByID(16928768+78):setStatus(dsp.status.NORMAL);
GetNPCByID(16928768+473):setStatus(dsp.status.NORMAL);
end
end; | gpl-3.0 |
Lsty/ygopro-scripts | c70138455.lua | 3 | 1589 | --ミスター・ボンバー
function c70138455.initial_effect(c)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(70138455,0))
e1:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_FIELD)
e1:SetCategory(CATEGORY_DESTROY)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c70138455.condition)
e1:SetCost(c70138455.cost)
e1:SetTarget(c70138455.target)
e1:SetOperation(c70138455.operation)
c:RegisterEffect(e1)
end
function c70138455.condition(e,tp,eg,ep,ev,re,r,rp)
return tp==Duel.GetTurnPlayer()
end
function c70138455.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsReleasable() end
Duel.Release(e:GetHandler(),REASON_COST)
end
function c70138455.filter(c)
return c:IsFaceup() and c:IsDestructable() and c:IsAttackBelow(1000)
end
function c70138455.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c70138455.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c70138455.filter,tp,LOCATION_MZONE,LOCATION_MZONE,2,e:GetHandler()) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c70138455.filter,tp,LOCATION_MZONE,LOCATION_MZONE,2,2,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,2,0,0)
end
function c70138455.desfilter(c,e)
return c:IsRelateToEffect(e) and c:IsFaceup() and c:IsDestructable() and c:IsAttackBelow(1000)
end
function c70138455.operation(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
local sg=g:Filter(c70138455.desfilter,nil,e)
Duel.Destroy(sg,REASON_EFFECT)
end
| gpl-2.0 |
tarulas/luadch | scripts/etc_usercommands.lua | 2 | 2504 | --[[
etc_usercommands.lua by blastbeat
v0.03: by blastbeat
- added some dynamic ucmd testing...
- usage: user.write( ucmd.format( ... ) )
v0.02: by pulsar
- export scriptsettings to "/cfg/cfg.tbl"
v0.01: by blastbeat
- this script exports a module to reg usercommands
]]--
--// settings begin //--
local scriptname = "etc_usercommands"
local scriptversion = "0.03"
--// settings end //--
local cfg_get = cfg.get
local utf_match = utf.match
local hub_escapeto = hub.escapeto
local hub_debug = hub.debug
local table_insert = table.insert
local table_concat = table.concat
local toplevelmenu = cfg_get( "etc_usercommands_toplevelmenu" )
local commands = { }
local level = { }
local sep = [[/]] -- accordings the UCMD specs
local format = function( menu, command, params, flags, llevel )
table_insert( menu, 1, toplevelmenu )
local menu = hub_escapeto( table_concat( menu, sep ) ) -- create ucmd name with submenus
local ucmd = "ICMD " .. menu
--hub.debug( ucmd )
ucmd = ucmd .. " TTBMSG\\s%[mySID]\\s+"
ucmd = ucmd .. hub_escapeto( hub_escapeto( command .. " " .. table_concat( params, " " ) ) .. "\n" )
ucmd = ucmd .. " " .. table_concat( flags, " " ) .. "\n"
return ucmd
end
local add = function( menu, command, params, flags, llevel ) -- quick and dirty...
local ucmd = format( menu, command, params, flags, llevel )
assert( not level[ ucmd ] ) -- names are unique
level[ ucmd ] = llevel
commands[ #commands + 1 ] = ucmd
end
hub.setlistener( "onLogin", { },
function( user )
local userlevel = user:level( )
for i, ucmd in ipairs( commands ) do
if level[ ucmd ] <= userlevel then
user.write( ucmd )
end
end
return nil
end
)
--[[ test
hub.setlistener( "onBroadcast", { },
function( user, adccmd, txt )
local cmd, menu = utf_match( txt, "^[+!#](%a+) ?(.*)" )
if cmd == "ucmdtest" then
user:reply( "[ucmd test!] " .. txt, hub.getbot( ) )
local ucmd = format( { menu }, "", { }, { "CT1" } )
user.write( ucmd )
return PROCESSED
end
return nil
end
)
]]
hub_debug( "** Loaded " .. scriptname .. " ".. scriptversion .. " **" )
--// public //--
return {
format = format,
add = add,
} | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.